code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php /** * FeedGator - Aggregate RSS newsfeed content into a Joomla! database * @version 3.0a1 * @package FeedGator * @author Matt Faulds * @email mattfaulds@gmail.com * @copyright (C) 2010 Matthew Faulds - All rights reserved * @license GNU/GPL: http://www.gnu.org/copyleft/gpl.html * **/ /// Check to ensure this file is within the rest of the framework defined('_JEXEC') or die('Restricted access'); jimport('joomla.form.formfield'); jimport('joomla.form.helper'); JFormHelper::loadFieldClass('list'); /** * Renders a select list of content_type/sects/cats * * @package Joomla.Framework * @subpackage Parameter * @since 1.5 */ class JFormFieldFGContent extends JFormFieldList { protected $type = 'FGContent'; public function getInput() { $user = JFactory::getUser(); $db = JFactory::getDBO(); $feedModel = FGFactory::getFeedModel(); $pluginModel = FGFactory::getPluginModel(); $task = JFactory::getApplication()->input->get('task','','WORD'); $cid = JFactory::getApplication()->input->get('cid',array(),'ARRAY'); $cid = (empty($cid) ? 0 : (int)$cid[0]); //node attributes var -> dyna $type = $this->element['var']; if (!$this->class) { $this->class = "inputbox"; } $fgParams = $feedModel->getParams(); if(!$this->value) $this->value = $fgParams->getValue('default_type'); $plugins = $pluginModel->loadInstalledPlugins(); $options = array(); // needs fail safe to make sure a default is loaded or the whole thing breaks! // if($cid != -2) { // $options[] = JHTML::_('select.option', '', JText::_('Use Default'), 'id', 'title'); // } else { $options[] = JHTML::_('select.option', -1, $type ? '- '.JText::_('FG_CHOOSE_CONTENT').' -' : '- '.JText::_('FG_DEFAULT_CONTENT').' -', 'id', 'title'); // } foreach($plugins as $plugin) { if($plugin->published) { $options[] = JHTML::_('select.option', $plugin->extension, $plugin->name, 'id', 'title'); } } $type ? $javascript = ' onchange="changeDynaList( \'paramssectionid\', contentsections, document.adminForm.paramscontent_type.options[document.adminForm.paramscontent_type.selectedIndex].value, 0, 0); changeDynaList( \'paramscatid\', sectioncategories, document.adminForm.paramssectionid.options[document.adminForm.paramssectionid.selectedIndex].value, 0, 0);"' : $javascript = ''; //return JHTML::_('select.genericlist', $options, ''.$control_name.'['.$name.']', $attributes, 'value', 'text', $value, $control_name.$name); //return JHTML::_('select.genericlist', $options, ''.$control_name.'['.$name.']'.$multipleArray, $attributes, $key, $val, $value, $control_name.$name); return JHTML::_('select.genericlist', $options, $this->name, 'class="'.$this->class.'"'.$javascript, 'id', 'title', $this->value, $this->name); } }
proizprojetos/olhemaisumavez
administrator/components/com_feedgator/models/fields/fgcontent.php
PHP
gpl-2.0
2,775
<?php /** * Base class for simple profiling. * * 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 Profiler */ /** * Simple profiler base class. * @todo document methods (?) * @ingroup Profiler */ class ProfilerSimple extends Profiler { var $mMinimumTime = 0; var $errorEntry; public function getZeroEntry() { return array( 'cpu' => 0.0, 'cpu_sq' => 0.0, 'real' => 0.0, 'real_sq' => 0.0, 'count' => 0 ); } public function getErrorEntry() { $entry = $this->getZeroEntry(); $entry['count'] = 1; return $entry; } public function updateEntry( $name, $elapsedCpu, $elapsedReal ) { $entry =& $this->mCollated[$name]; if ( !is_array( $entry ) ) { $entry = $this->getZeroEntry(); $this->mCollated[$name] =& $entry; } $entry['cpu'] += $elapsedCpu; $entry['cpu_sq'] += $elapsedCpu * $elapsedCpu; $entry['real'] += $elapsedReal; $entry['real_sq'] += $elapsedReal * $elapsedReal; $entry['count']++; } public function isPersistent() { /* Implement in output subclasses */ return false; } protected function addInitialStack() { $this->errorEntry = $this->getErrorEntry(); $initialTime = $this->getInitialTime(); $initialCpu = $this->getInitialTime( 'cpu' ); if ( $initialTime !== null && $initialCpu !== null ) { $this->mWorkStack[] = array( '-total', 0, $initialTime, $initialCpu ); $this->mWorkStack[] = array( '-setup', 1, $initialTime, $initialCpu ); $this->profileOut( '-setup' ); } else { $this->profileIn( '-total' ); } } function setMinimum( $min ) { $this->mMinimumTime = $min; } function profileIn( $functionname ) { global $wgDebugFunctionEntry; if ( $wgDebugFunctionEntry ) { $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) . 'Entering ' . $functionname . "\n" ); } $this->mWorkStack[] = array( $functionname, count( $this->mWorkStack ), $this->getTime(), $this->getTime( 'cpu' ) ); } function profileOut( $functionname ) { global $wgDebugFunctionEntry; if ( $wgDebugFunctionEntry ) { $this->debug( str_repeat( ' ', count( $this->mWorkStack ) - 1 ) . 'Exiting ' . $functionname . "\n" ); } list( $ofname, /* $ocount */, $ortime, $octime ) = array_pop( $this->mWorkStack ); if ( !$ofname ) { $this->debug( "Profiling error: $functionname\n" ); } else { if ( $functionname == 'close' ) { $message = "Profile section ended by close(): {$ofname}"; $functionname = $ofname; $this->debug( "$message\n" ); $this->mCollated[$message] = $this->errorEntry; } elseif ( $ofname != $functionname ) { $message = "Profiling error: in({$ofname}), out($functionname)"; $this->debug( "$message\n" ); $this->mCollated[$message] = $this->errorEntry; } $elapsedcpu = $this->getTime( 'cpu' ) - $octime; $elapsedreal = $this->getTime() - $ortime; $this->updateEntry( $functionname, $elapsedcpu, $elapsedreal ); $this->updateTrxProfiling( $functionname, $elapsedreal ); } } public function getFunctionReport() { /* Implement in output subclasses */ return ''; } public function logData() { /* Implement in subclasses */ } }
legoktm/wikihow-src
includes/profiler/ProfilerSimple.php
PHP
gpl-2.0
3,861
<?php namespace LeagueWrap\Api; use LeagueWrap\Dto\StaticData\Champion as staticChampion; use LeagueWrap\Dto\StaticData\ChampionList; use LeagueWrap\Dto\StaticData\Item as staticItem; use LeagueWrap\Dto\StaticData\ItemList; use LeagueWrap\Dto\StaticData\Mastery as staticMastery; use LeagueWrap\Dto\StaticData\MasteryList; use LeagueWrap\Dto\StaticData\Rune as staticRune; use LeagueWrap\Dto\StaticData\RuneList; use LeagueWrap\Dto\StaticData\SummonerSpell as staticSummonerSpell; use LeagueWrap\Dto\StaticData\SummonerSpellList; use LeagueWrap\Dto\StaticData\Realm as staticRealm; class Staticdata extends AbstractApi { /** * The locale you want the response in. By default it is not * passed (null). * * @var string */ protected $locale = null; /** * The version of League of Legends that we want data from. By default * it is not passed (null). * * @var string */ protected $DDversion = null; /** * Valid version for this api call. * * @var array */ protected $versions = [ 'v1.2', ]; /** * A list of all permitted regions for the Staticdata api call. * * @var array */ protected $permittedRegions = [ 'br', 'eune', 'euw', 'kr', 'lan', 'las', 'na', 'oce', 'ru', 'tr', ]; /** * A list of all calls that require to get the data by Id * @var array */ protected $dataById = ['champion', 'summoner-spell']; /** * The amount of time we intend to remember the response for. * * @var int */ protected $defaultRemember = 86400; /** * Sets the locale the data should be returned in. Null returns * the default local for that region. * * @param string $locale * @chainable */ public function setLocale($locale) { $this->locale = $locale; return $this; } /** * Sets the DDversion to be used in the query. Null will return * the most recent version. * * @param string $DDversion * @chainable */ public function setDDversion($DDversion = null) { $this->DDversion = $DDversion; return $this; } /** * Gets all static champion data with the given $data option. * * @param mixed #data * @retrn ChampionList */ public function getChampions($data = null) { return $this->getChampion(null, $data); } /** * Gets the static champion data of all champions if $championId is null. * If $championI is set it will attempt to get info for that champion only. * * @param int $championId * @param mixed $data * @return ChampionList|Champion */ public function getChampion($championId, $data = null) { $params = $this->setUpParams('champion', $championId, $data, 'champData', 'champData'); $array = $this->makeRequest('champion', $championId, $params); if ($this->appendId($championId)) { return new staticChampion($array); } else { return new ChampionList($array); } } /** * Gets static data on all items. * * @param mixed $data * @return ItemList */ public function getItems($data = null) { return $this->getItem(null, $data); } /** * Gets the static item data of all items if $itemId is null. * If $itemId is set it will attempt to get info for that item only. * * @param int $itemId * @param mixed $data * @return ItemList|Item */ public function getItem($itemId, $data = null) { $params = $this->setUpParams('item', $itemId, $data, 'itemListData', 'itemData'); $array = $this->makeRequest('item', $itemId, $params); if ($this->appendId($itemId)) { return new staticItem($array); } else { return new ItemList($array); } } /** * Gets static data on all masteries. * * @param mixed $data * @return MasteryList */ public function getMasteries($data = null) { return $this->getMastery(null, $data); } /** * Gets the mastery data of all masteries if $masteryId is null. * If $masteryId is a set it will attempt to get info for that mastery only. * * @param int $masteryId * @param mixed $data * @return MasteryList|Mastery */ public function getMastery($masteryId, $data = null) { $params = $this->setUpParams('mastery', $masteryId, $data, 'masteryListData', 'masteryData'); $array = $this->makeRequest('mastery', $masteryId, $params); if ($this->appendId($masteryId)) { return new staticMastery($array); } else { return new MasteryList($array); } } /** * Gets static data on all runes. * * @param mixed $data * @return RuneList */ public function getRunes($data = null) { return $this->getRune('all', $data); } /** * Gets the rune data of all runes if $runeId is null. * If $runeId is set it will attempt to get info for that rune only. * * $param int $runeId * @param mixed $data * @return RuneList|Rune */ public function getRune($runeId, $data = null) { $params = $this->setUpParams('rune', $runeId, $data, 'runeListData', 'runeData'); $array = $this->makeRequest('rune', $runeId, $params); if ($this->appendId($runeId)) { return new staticRune($array); } else { return new RuneList($array); } } /** * Gets static data on all summoner spells. * * @param mixed $data * @return SummonerSpellList */ public function getSummonerSpells($data = null) { return $this->getSummonerSpell('all', $data); } /** * Gets the summoner spell data of all spells if $summonerSpellId is null * If $summonerSpellId is set it will attept to get info for that spell only. * * @param int $summonerSpellId * @param mixed $data * @return SummonerSpell|SummonerSpellList */ public function getSummonerSpell($summonerSpellId, $data = null) { $params = $this->setUpParams('summoner-spell', $summonerSpellId, $data, 'spellData', 'spellData'); $array = $this->makeRequest('summoner-spell', $summonerSpellId, $params); if ($this->appendId($summonerSpellId)) { return new staticSummonerSpell($array); } else { return new SummonerSpellList($array); } } /** * Get the realm information for the current region. * * @return Realm */ public function getRealm() { $params = $this->setUpParams(); $array = $this->makeRequest('realm', null, $params); return new staticRealm($array); } /** * Get the version information for the current region. * * @return Array */ public function version() { $params = $this->setUpParams(); return $this->makeRequest('versions', null, $params); } /** * Make the request given the proper information. * * @param string $path * @param mixed $requestId * @param array $params * @return array */ protected function makeRequest($path, $requestId, array $params) { if ($this->appendId($requestId)) { $path .= "/$requestId"; } return $this->request($path, $params, true); } /** * Set up the boiler plate for the param array for any * static data call. * * @param string $name of api call * @param mixed $requestId * @param mixed $data * @param string $listData * @param string $itemData * @return array */ protected function setUpParams($name='', $requestId = null, $data = null, $listData = '', $itemData = '') { $params = []; if ( ! is_null($this->locale)) { $params['locale'] = $this->locale; } if ( ! is_null($this->DDversion)) { $params['version'] = $this->DDversion; } if(! $this->appendId($requestId) && $this->dataById($name)) { $params['dataById'] = 'true'; } if ( ! is_null($data)) { if ($this->appendId($requestId)) { if(is_array($data) && !empty($data)) { $data = implode(",", $data); } $params[$itemData] = $data; } else { if(is_array($data) && !empty($data)) { $data = implode(",", $data); } $params[$listData] = $data; } } return $params; } /** * Check if we should append the id to the end of the * url or not. * * @param mixed $requestId * @return bool */ protected function appendId($requestId) { if ( ! is_null($requestId) && $requestId != 'all') { return true; } return false; } /** * Check if we need the data by Id * * @param $name string * @return bool */ protected function dataById($name) { return in_array($name, $this->dataById); } }
epoch365/rito-api-challenge
vendor/paquettg/leaguewrap/src/LeagueWrap/Api/Staticdata.php
PHP
gpl-2.0
8,303
/* * Microtuner.cpp - manage tuning and scale information of an instrument * * Copyright (c) 2020 Martin Pavelek <he29.HS/at/gmail.com> * * This file is part of LMMS - https://lmms.io * * 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 (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #include "Microtuner.h" #include <vector> #include <cmath> #include "ConfigManager.h" #include "Engine.h" #include "Keymap.h" #include "Scale.h" #include "Song.h" Microtuner::Microtuner() : Model(nullptr, tr("Microtuner")), m_enabledModel(false, this, tr("Microtuner on / off")), m_scaleModel(this, tr("Selected scale")), m_keymapModel(this, tr("Selected keyboard mapping")), m_keyRangeImportModel(true) { for (unsigned int i = 0; i < MaxScaleCount; i++) { m_scaleModel.addItem(QString::number(i) + ": " + Engine::getSong()->getScale(i)->getDescription()); } for (unsigned int i = 0; i < MaxKeymapCount; i++) { m_keymapModel.addItem(QString::number(i) + ": " + Engine::getSong()->getKeymap(i)->getDescription()); } connect(Engine::getSong(), SIGNAL(scaleListChanged(int)), this, SLOT(updateScaleList(int))); connect(Engine::getSong(), SIGNAL(keymapListChanged(int)), this, SLOT(updateKeymapList(int))); } /** \brief Return frequency for a given MIDI key, using the active mapping and scale. * \param key A MIDI key number ranging from 0 to 127. * \return Frequency in Hz; 0 if key is out of range or not mapped. */ float Microtuner::keyToFreq(int key, int userBaseNote) const { if (key < 0 || key >= NumKeys) {return 0;} Song *song = Engine::getSong(); if (!song) {return 0;} // Get keymap and scale selected at this moment std::shared_ptr<const Keymap> keymap = song->getKeymap(m_keymapModel.value()); std::shared_ptr<const Scale> scale = song->getScale(m_scaleModel.value()); const std::vector<Interval> &intervals = scale->getIntervals(); // Convert MIDI key to scale degree + octave offset. // The octaves are primarily driven by the keymap wraparound: octave count is increased or decreased if the key // goes over or under keymap range. In case the keymap refers to a degree that does not exist in the scale, it is // assumed the keymap is non-repeating or just really big, so the octaves are also driven by the scale wraparound. const int keymapDegree = keymap->getDegree(key); // which interval should be used according to the keymap if (keymapDegree == -1) {return 0;} // key is not mapped, abort const int keymapOctave = keymap->getOctave(key); // how many times did the keymap repeat const int octaveDegree = intervals.size() - 1; // index of the interval with octave ratio if (octaveDegree == 0) { // octave interval is 1/1, i.e. constant base frequency return keymap->getBaseFreq(); // → return the baseFreq directly } const int scaleOctave = keymapDegree / octaveDegree; // which interval should be used according to the scale and keymap together const int degree_rem = keymapDegree % octaveDegree; const int scaleDegree = degree_rem >= 0 ? degree_rem : degree_rem + octaveDegree; // get true modulo // Compute base note (the "A4 reference") degree and octave const int baseNote = m_keyRangeImportModel.value() ? keymap->getBaseKey() : userBaseNote; const int baseKeymapDegree = keymap->getDegree(baseNote); if (baseKeymapDegree == -1) {return 0;} // base key is not mapped, umm... const int baseKeymapOctave = keymap->getOctave(baseNote); const int baseScaleOctave = baseKeymapDegree / octaveDegree; const int baseDegree_rem = baseKeymapDegree % octaveDegree; const int baseScaleDegree = baseDegree_rem >= 0 ? baseDegree_rem : baseDegree_rem + octaveDegree; // Compute frequency of the middle note and return the final frequency const double octaveRatio = intervals[octaveDegree].getRatio(); const float middleFreq = (keymap->getBaseFreq() / pow(octaveRatio, (baseScaleOctave + baseKeymapOctave))) / intervals[baseScaleDegree].getRatio(); return middleFreq * intervals[scaleDegree].getRatio() * pow(octaveRatio, keymapOctave + scaleOctave); } /** * \brief Update scale name displayed in the microtuner scale list. * \param index Index of the scale to update; update all scales if -1 or out of range. */ void Microtuner::updateScaleList(int index) { if (index >= 0 && index < MaxScaleCount) { m_scaleModel.replaceItem(index, QString::number(index) + ": " + Engine::getSong()->getScale(index)->getDescription()); } else { for (int i = 0; i < MaxScaleCount; i++) { m_scaleModel.replaceItem(i, QString::number(i) + ": " + Engine::getSong()->getScale(i)->getDescription()); } } } /** * \brief Update keymap name displayed in the microtuner scale list. * \param index Index of the keymap to update; update all keymaps if -1 or out of range. */ void Microtuner::updateKeymapList(int index) { if (index >= 0 && index < MaxKeymapCount) { m_keymapModel.replaceItem(index, QString::number(index) + ": " + Engine::getSong()->getKeymap(index)->getDescription()); } else { for (int i = 0; i < MaxKeymapCount; i++) { m_keymapModel.replaceItem(i, QString::number(i) + ": " + Engine::getSong()->getKeymap(i)->getDescription()); } } } void Microtuner::saveSettings(QDomDocument &document, QDomElement &element) { m_enabledModel.saveSettings(document, element, "enabled"); m_scaleModel.saveSettings(document, element, "scale"); m_keymapModel.saveSettings(document, element, "keymap"); m_keyRangeImportModel.saveSettings(document, element, "range_import"); } void Microtuner::loadSettings(const QDomElement &element) { m_enabledModel.loadSettings(element, "enabled"); m_scaleModel.loadSettings(element, "scale"); m_keymapModel.loadSettings(element, "keymap"); m_keyRangeImportModel.loadSettings(element, "range_import"); }
zonkmachine/lmms
src/core/Microtuner.cpp
C++
gpl-2.0
6,427
<?php defined('WYSIJA') or die('Restricted access'); class WYSIJA_control_front_subscribers extends WYSIJA_control_front{ var $model="user"; var $view="widget_nl"; function WYSIJA_control_front_subscribers(){ parent::WYSIJA_control_front(); if(isset($_REQUEST['message_success'])){ $this->messages['insert'][true]=$_REQUEST['message_success']; }else{ $this->messages['insert'][true]=__("User has been inserted.",WYSIJA); } $this->messages['insert'][false]=__("User has not been inserted.",WYSIJA); $this->messages['update'][true]=__("User has been updated.",WYSIJA); $this->messages['update'][false]=__("User has not been updated.",WYSIJA); } function save(){ $config=&WYSIJA::get('config','model'); if(!$config->getValue("allow_no_js")){ $this->notice(__("Subscription without JavaScript is disabled.",WYSIJA)); return false; } if(isset($_REQUEST['wysija']['user_list']['list_id'])){ $_REQUEST['wysija']['user_list']['list_ids']=$_REQUEST['wysija']['user_list']['list_id']; unset($_REQUEST['wysija']['user_list']['list_id']); }elseif(isset($_REQUEST['wysija']['user_list']['list_ids'])){ $_REQUEST['wysija']['user_list']['list_ids']=explode(',',$_REQUEST['wysija']['user_list']['list_ids']); } $data=$_REQUEST['wysija']; unset($_REQUEST['wysija']); foreach($_REQUEST as $key => $val){ if(!isset($data[$key])) $data[$key]=$val; } $helperUser=&WYSIJA::get('user','helper'); if(!$helperUser->checkData($data))return false; $helperUser->addSubscriber($data); return true; } function wysija_outter() { if(isset($_REQUEST['encodedForm'])){ $encodedForm=json_decode(base64_decode(urldecode($_REQUEST['encodedForm']))); } else{ if(isset($_REQUEST['fullWysijaForm'])){ $encodedForm=json_decode(base64_decode(urldecode($_REQUEST['fullWysijaForm']))); }else{ if(isset($_REQUEST['widgetnumber'])){ $widgets=get_option('widget_wysija'); if(isset($widgets[$_REQUEST['widgetnumber']])){ $encodedForm=$widgets[$_REQUEST['widgetnumber']]; } }else{ $encodedForm=$_REQUEST['formArray']; $encodedForm=stripslashes_deep($encodedForm); } } } $widgetdata=array(); if($encodedForm){ foreach($encodedForm as $key =>$val) { $widgetdata[$key]=$val; if(is_object($val)){ $valu=array(); foreach($val as $keyin =>$valin){ $valu[$keyin]=$valin; if(is_object($valin)){ $inin=array(); foreach($valin as $kin => $vin){ $inin[$kin]=$vin; } $valu[$keyin]=$inin; } } $widgetdata[$key]=$valu; } } }else{ if(current_user_can('switch_themes')) echo '<b>'.str_replace(array('[link]','[/link]'),array('<a target="_blank" href="'. admin_url('widgets.php').'">','</a>'),__('It seems your widget has been deleted from the WordPress\' [link]widgets area[/link].',WYSIJA)).'</b>'; exit; } if(isset($_REQUEST['widgetnumber'])) $intrand=$_REQUEST['widgetnumber']; else $intrand=rand(5, 1500); $widgetdata['widget_id']='wysija-nl-iframe-'.$intrand; $widgetNL=new WYSIJA_NL_Widget(1); $widgetNL->iFrame=true; $subscriptionForm= $widgetNL->widget($widgetdata,$widgetdata); echo $subscriptionForm; exit; } }
marcosposada/emily
wp-content/plugins/wysija-newsletters/controllers/front/subscribers.php
PHP
gpl-2.0
4,037
/* * Copyright (C) 2012 The Android Open Source Project * * 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. */ package com.motorola.studio.android.monkey.options; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.osgi.util.NLS; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.motorola.studio.android.AndroidPlugin; import com.motorola.studio.android.common.log.StudioLogger; import com.motorola.studio.android.i18n.AndroidNLS; /** * This class provides methods to manage monkey options */ public class MonkeyOptionsMgt implements IMonkeyOptionsConstants { /** * List of all monkey options groups (the monkey options themselves will * be accessed through the use of a method in the group object that returns * the monkey options in that group) */ private static List<MonkeyOptionsGroup> monkeyOptionsGroupsList = null; /** * List of all monkey options, indexed by their names, for fast access */ private static Map<String, MonkeyOption> monkeyOptionsMap = new HashMap<String, MonkeyOption>(); /* * Load the monkey options / groups list */ static { load(); } /** * Get the monkey options groups list * * @return monkey options groups list */ public static List<MonkeyOptionsGroup> getMonkeyOptionsGroupsList() { return monkeyOptionsGroupsList; } /** * Read all groups and monkey options available for editing from a XML * and stores the information in the correspondent beans */ public static void load() { try { // Clear monkey options groups list monkeyOptionsGroupsList = new ArrayList<MonkeyOptionsGroup>(); // Define XML path InputStream xmlStream = AndroidPlugin.getDefault().getBundle().getEntry(MONKEY_OPTIONS_XML_PATH) .openStream(); // Load XML DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(xmlStream); /* * Iterate through Monkey Groups */ Element rootNode = document.getDocumentElement(); NodeList monkeyOptionsGroups = rootNode.getElementsByTagName(GROUP_TAG); for (int i = 0; i < monkeyOptionsGroups.getLength(); i++) { /* * Create group */ Element group = (Element) monkeyOptionsGroups.item(i); String strKey = group.getAttributeNode(GROUP_TAG_ID).getNodeValue(); strKey = Platform.getResourceString(AndroidPlugin.getDefault().getBundle(), strKey.trim()); MonkeyOptionsGroup monkeyOptionsGroup = new MonkeyOptionsGroup(strKey); monkeyOptionsGroup.setTitle(monkeyOptionsGroup.getId()); /* * Iterate through Monkey Options in this group */ NodeList monkeyOptions = group.getElementsByTagName(MONKEY_OPT_TAG); monkeyOptionsGroup.setMonkeyOptions(new ArrayList<MonkeyOption>()); // clear monkey options for (int j = 0; j < monkeyOptions.getLength(); j++) { /* * Create monkey option */ Element option = (Element) monkeyOptions.item(j); MonkeyOption monkeyOption = new MonkeyOption(option.getAttributeNode(MONKEY_OPT_TAG_NAME) .getNodeValue(), getMonkeyOptionType(option.getAttributeNode( MONKEY_OPT_TAG_TYPE).getNodeValue())); // name and type strKey = option.getAttributeNode(MONKEY_OPT_TAG_FRIENDLY_NAME).getNodeValue(); strKey = Platform.getResourceString(AndroidPlugin.getDefault().getBundle(), strKey.trim()); monkeyOption.setUserFriendlyName(strKey); // friendly name strKey = option.getElementsByTagName(MONKEY_OPT_TAG_DESCRIPTION).item(0) .getTextContent(); strKey = Platform.getResourceString(AndroidPlugin.getDefault().getBundle(), strKey.trim()); monkeyOption.setDescription(strKey); // description if (option.getAttributeNode(MONKEY_OPT_TAG_TYPE_DETAILS) != null) { monkeyOption.setTypeDetails(option.getAttributeNode( MONKEY_OPT_TAG_TYPE_DETAILS).getNodeValue()); // type details } // Iterate through monkey option pre-defined values, if any NodeList preDefinedValuesContainer = option.getElementsByTagName(PREDEFINED_VALUES_TAG); monkeyOption.setPreDefinedValues(new ArrayList<String>()); // clear pre-defined values if (preDefinedValuesContainer.getLength() > 0) { NodeList preDefinedValues = ((Element) preDefinedValuesContainer.item(0)) .getElementsByTagName(PREDEFINED_VALUE_TAG); for (int k = 0; k < preDefinedValues.getLength(); k++) { // Add pre-defined values to the option Element preDefinedValue = (Element) preDefinedValues.item(k); monkeyOption.getPreDefinedValues() .add(preDefinedValue.getTextContent()); } } /* * Add monkey options to the group */ monkeyOptionsGroup.getMonkeyOptions().add(monkeyOption); monkeyOptionsMap.put(monkeyOption.getName(), monkeyOption); } /* * Add groups to the groups list */ monkeyOptionsGroupsList.add(monkeyOptionsGroup); } } catch (Exception e) { StudioLogger.error("Failed to load monkey options"); } } /** * Validate the values assigned for the monkey options marked as checked (the ones that are * being used), according to its type and type details. * * @return Status object with the result of the validation */ public static Status validate() { Status status = (Status) Status.OK_STATUS; String msg = null; /* * Iterate through Monkey Groups */ for (MonkeyOptionsGroup group : getMonkeyOptionsGroupsList()) { /* * Iterate through monkey options in this group */ for (MonkeyOption monkeyOption : group.getMonkeyOptions()) { /* * Check if the Monkey Option is checked */ if (monkeyOption.isChecked() && (status.isOK())) { String name = monkeyOption.getName(); // monkey option name String ufname = monkeyOption.getUserFriendlyName(); // user-friendly monkey option name String value = monkeyOption.getValue(); // monkey option value String typeDetails = monkeyOption.getTypeDetails(); // monkey option type detail /* * General validation: no quotes in values */ if ((!monkeyOption.getName().equals(OTHERS_OTHER)) && (value.indexOf("\"") >= 0)) { msg = NLS.bind(AndroidNLS.ERR_PropertiesMainComposite_Monkey_NoQuotes, ufname); } else { /* * Call the appropriate validation method */ switch (monkeyOption.getType()) { case TYPE_TEXT: msg = validateTextField(name, ufname, value, typeDetails); break; case TYPE_NUMBER: msg = validadeNumberField(name, ufname, value, typeDetails); break; case TYPE_PATH: msg = validadePathField(name, ufname, value, typeDetails); break; } } /* * If some validation has failed, return with an error message */ if (msg != null) { status = new Status(Status.ERROR, AndroidPlugin.PLUGIN_ID, msg); break; } } } } return status; } /** * Validate the monkey option value for an monkey option of "text" type * * @param name the monkey option name * @param ufname the user-friendly monkey option name * @param value the current assigned value for the monkey option * @param typeDetails any special requirements that the assigned value must be match * @return null if the value assigned for the monkey option is a valid one or an error message otherwise */ private static String validateTextField(String name, String ufName, String value, String typeDetails) { String msg = null; // Check if the value is blank if ((value == null) || (value.equals(""))) { msg = NLS.bind(AndroidNLS.ERR_PropertiesMainComposite_Monkey_TextBlank, ufName); } return msg; } /** * Validate the monkey option value for an monkey option of "number" type * * @param name the monkey option name * @param ufname the user-friendly monkey option name * @param value the current assigned value for the monkey option * @param typeDetails any special requirements that the assigned value must be match * @return null if the value assigned for the monkey option is a valid one or an error message otherwise */ private static String validadeNumberField(String name, String ufName, String value, String typeDetails) { String msg = null; // Check if the value is blank if ((value == null) || (value.equals(""))) { msg = NLS.bind(AndroidNLS.ERR_PropertiesMainComposite_Monkey_NumberRequired, ufName); } else { try { /* * Check if it's an Integer. * If it's not, an exception will be thrown */ int intValue = Integer.parseInt(value); /* * Check if it's positive */ if (intValue < 0) { msg = NLS.bind( AndroidNLS.ERR_PropertiesMainComposite_Monkey_NumberMustBePositiveInteger, ufName); } else { /* * Check if the value is in the correct range */ if (typeDetails != null) { String[] valueRange = typeDetails.split(";"); if ((intValue < Integer.parseInt(valueRange[0])) || (intValue > Integer.parseInt(valueRange[1]))) { // the value is not in the correct range msg = NLS.bind( AndroidNLS.ERR_PropertiesMainComposite_Monkey_NumberIntRange, new String[] { ufName, valueRange[0], valueRange[1] }); } } } } catch (NumberFormatException ex) { // it's not a number msg = NLS.bind(AndroidNLS.ERR_PropertiesMainComposite_Monkey_NumberMustBeInteger, ufName); } } return msg; } /** * Validate the monkey option value for an monkey option of "path" type * * @param name the monkey option name * @param ufname the user-friendly monkey option name * @param value the current assigned value for the monkey option * @param typeDetails any special requirements that the assigned value must be match * @return null if the value assigned for the monkey option is a valid one or an error message otherwise */ private static String validadePathField(String name, String ufName, String value, String typeDetails) { String msg = null; if ((value == null) || (value.equals(""))) { msg = NLS.bind(AndroidNLS.ERR_PropertiesMainComposite_Monkey_PathRequired, ufName); } else { File file = new File(value); /* * Validate folder */ if (typeDetails.equals(TYPE_PATH_DIR)) { /* * Check if the path exists */ if (!file.exists()) { // the folder doesn't exist msg = NLS.bind(AndroidNLS.ERR_PropertiesMainComposite_Monkey_PathDirNotExist, ufName); } else { if (file.isFile()) { // it's not a folder msg = NLS.bind( AndroidNLS.ERR_PropertiesMainComposite_Monkey_PathMustBeDir, ufName); } } } /* * Validate file */ else { if (!file.exists()) { // the file doesn't exist msg = NLS.bind( AndroidNLS.ERR_PropertiesMainComposite_Monkey_PathFileNotExist, ufName); } else { // it's not a file if (file.isDirectory()) { msg = NLS.bind( AndroidNLS.ERR_PropertiesMainComposite_Monkey_PathMustBeFile, ufName); } // it doesn't have the correct extension else { if (!typeDetails.equals("." + (new Path(value)).getFileExtension())) { msg = NLS.bind( AndroidNLS.ERR_PropertiesMainComposite_Monkey_PathIncorrectFileType, new String[] { ufName, typeDetails }); } } } } } return msg; } /** * Generates the list of parameters that shall to be sent to adb shell * * @return the list of parameters that shall to be sent to the adb shell */ public static String getParamList() { String paramList = ""; /* * Iterate through Monkey Groups */ for (MonkeyOptionsGroup group : getMonkeyOptionsGroupsList()) { /* * Iterate through Monkey Options in this group */ int monkeyOptionType; for (MonkeyOption monkeyOption : group.getMonkeyOptions()) { monkeyOptionType = monkeyOption.getType(); if (monkeyOption.isChecked()) // check if the monkey option is being used { if (monkeyOptionType == TYPE_NONE) { paramList += ((paramList.equals("")) ? "" : " ") + monkeyOption.getName(); } else { if ((monkeyOption.getName().equals(OTHERS_OTHER))) { paramList += ((paramList.equals("")) ? "" : " ") + monkeyOption.getValue(); } else { if ((monkeyOption.getName().equals(CATEGORY_OPTION))) { String[] values = monkeyOption.getValue().split(" "); for (int i = 0; i < values.length; i++) { if (values[i].trim().length() > 0) { paramList += ((paramList.equals("")) ? "" : " ") + monkeyOption.getName() + " " + values[i]; } } } else { String value = monkeyOption.getValue(); if (!value.equals("")) { if (Platform.getOS().equals(Platform.OS_WIN32)) { if (value.contains(" ")) { value = "\"" + value + "\""; } } else { if (value.contains("\\")) { value = value.replace("\\", "\\\\"); } if (value.contains(" ")) { value = value.replace(" ", "\\ "); } } paramList += ((paramList.equals("")) ? "" : " ") + monkeyOption.getName() + (value.trim().length() > 0 ? " " + value : ""); } } } } } } } return paramList; } /** * Load values from a Properties object * * @param properties properties object containing the values that must be loaded into de model */ private static void loadValues(Properties properties) { /* * Iterate through Monkey Groups */ for (MonkeyOptionsGroup group : getMonkeyOptionsGroupsList()) { /* * Iterate through monkey options in this group */ String soValue = ""; for (MonkeyOption monkeyOption : group.getMonkeyOptions()) { soValue = properties.getProperty(monkeyOption.getName()); if (soValue != null) { monkeyOption.setChecked(true); monkeyOption.setValue(soValue); } else { monkeyOption.setChecked(false); monkeyOption.setValue(""); } monkeyOption.updateUI(); } } } /** * Create a properties object with the information contained in a command line * * @param commandLine the command line used to start the emulator * @return properties object with the information contained in a command line */ public static Properties parseCommandLine(String commandLine) { Properties properties = new Properties(); if (!commandLine.equals("")) { /* * Iterate through Monkey Groups */ for (MonkeyOptionsGroup group : getMonkeyOptionsGroupsList()) { /* * Iterate through monkey options in this group */ String soName, soValue = ""; int soType, shift = 0; for (MonkeyOption monkeyOption : group.getMonkeyOptions()) { soName = monkeyOption.getName(); soType = monkeyOption.getType(); if (commandLine.startsWith(soName)) { if (soType == TYPE_NONE) { soValue = new Boolean(true).toString(); shift = soName.length() + 1; } else { if ((monkeyOption.getName().equals(CATEGORY_OPTION))) { String soValueCat = ""; while (commandLine.startsWith(CATEGORY_OPTION)) { commandLine = commandLine.substring(soName.length() + 1, commandLine.length()); ParameterBean param = getNextParameterValue(commandLine); soValue = param.getValue(); shift = param.getLastPosition() + 1; soValueCat = (soValueCat.equals("") ? soValueCat : soValueCat + " ") + soValue; if (shift < (commandLine.length() - 1)) { commandLine = commandLine.substring(shift, commandLine.length()); } else { commandLine = ""; } } shift = 0; soValue = soValueCat; } else { commandLine = commandLine.substring(soName.length() + 1, commandLine.length()); ParameterBean param = getNextParameterValue(commandLine); soValue = param.getValue(); shift = param.getLastPosition() + 1; } } properties.put(monkeyOption.getName(), soValue); if (shift < (commandLine.length() - 1)) { commandLine = commandLine.substring(shift, commandLine.length()); } else { commandLine = ""; } } } } if (!commandLine.equals("")) { properties.put(OTHERS_OTHER, commandLine); } } return properties; } /** * Load values from a command line * * @param commandLine the command line used to start the emulator */ public static void loadFromCommandLine(String commandLine) { loadValues(parseCommandLine(commandLine)); } /** * Convert the type of the monkey option from a string * to a number * * @param type string that represents the type * @return number that represents the type */ private static int getMonkeyOptionType(String type) { return (TYPE_MAP.get(type)).intValue(); } /** * Parses the next parameter value on a command line * * @param commandLine the command line * * @return a bean containing the parameter value and the last position looked at * the command line */ private static ParameterBean getNextParameterValue(String commandLine) { boolean isWin32 = Platform.getOS().equals(Platform.OS_WIN32); boolean escaped = false; boolean quoted = false; char c; String value = ""; int i; for (i = 0; i < commandLine.length(); i++) { c = commandLine.charAt(i); if (escaped) { value += c; escaped = false; } else if ((c == '\\') && !isWin32) { escaped = true; } else if ((c == '"') && isWin32) { if (value.length() == 0) { quoted = true; } else if (quoted) { break; } else { value += c; } } else if ((c == ' ') && (!quoted)) { break; } else { value += c; } } return new ParameterBean(value, ((quoted) ? i + 1 : i)); } /** * Bean used to identify a parameter value when parsing the * monkey options */ private static class ParameterBean { private final String value; private final int lastPosition; /** * Constructor * * @param value The parameter value * @param lastPosition The last position looked at the command line before stopping * the parse operation */ public ParameterBean(String value, int lastPosition) { this.value = value; this.lastPosition = lastPosition; } /** * Retrieves the parameter value * * @return the parameter value */ public String getValue() { return value; } /** * Retrieves the last position looked at the command line before stopping * the parse operation * * @return the last position looked at the command line before stopping * the parse operation */ public int getLastPosition() { return lastPosition; } } }
rex-xxx/mt6572_x201
tools/motodev/src/plugins/android/src/com/motorola/studio/android/monkey/options/MonkeyOptionsMgt.java
Java
gpl-2.0
30,495
<?php /** * FEDEX Service codes in array format */ return array( 'FIRST_OVERNIGHT' => 'FedEx First Overnight', 'PRIORITY_OVERNIGHT' => 'FedEx Priority Overnight', 'STANDARD_OVERNIGHT' => 'FedEx Standard Overnight', 'FEDEX_2_DAY_AM' => 'FedEx 2Day A.M', 'FEDEX_2_DAY' => 'FedEx 2Day', 'FEDEX_EXPRESS_SAVER' => 'FedEx Express Saver', 'GROUND_HOME_DELIVERY' => 'FedEx Ground Home Delivery', 'FEDEX_GROUND' => 'FedEx Ground', 'INTERNATIONAL_ECONOMY' => 'FedEx International Economy', 'INTERNATIONAL_FIRST' => 'FedEx International First', 'INTERNATIONAL_PRIORITY' => 'FedEx International Priority', 'EUROPE_FIRST_INTERNTIONAL_PRIORITY' => 'FedEx Europe First International Priority', 'FEDEX_1_DAY_FREIGHT' => 'FedEx 1 Day Freight', 'FEDEX_2_DAY_FREIGHT' => 'FedEx 2 Day Freight', 'FEDEX_3_DAY_FREIGHT' => 'FedEx 3 Day Freight', 'INTERNATIONAL_ECONOMY_FREIGHT' => 'FedEx Economy Freight', 'INTERNATIONAL_PRIORITY_FREIGHT' => 'FedEx Priority Freight', 'FEDEX_FREIGHT' => 'Fedex Freight', 'FEDEX_NATIONAL_FREIGHT' => 'FedEx National Freight', 'INTERNATIONAL_GROUND' => 'FedEx International Ground', 'SMART_POST' => 'FedEx Smart Post', 'FEDEX_FIRST_FREIGHT' => 'FedEx First Freight', 'FEDEX_FREIGHT_ECONOMY' => 'FedEx Freight Economy', 'FEDEX_FREIGHT_PRIORITY' => 'FedEx Freight Priority', );
acscoleen/acsdevelopment
wp-content/plugins/woocommerce-shipping-fedex/includes/data/data-service-codes.php
PHP
gpl-2.0
1,659
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2011 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC) * * 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: Marco Miozzo <marco.miozzo@cttc.es>, * Nicola Baldo <nbaldo@cttc.es> * Dizhi Zhou <dizhi.zhou@gmail.com> */ #include <iostream> #include <sstream> #include <string> #include <ns3/object.h> #include <ns3/spectrum-interference.h> #include <ns3/spectrum-error-model.h> #include <ns3/log.h> #include <ns3/test.h> #include <ns3/simulator.h> #include <ns3/packet.h> #include <ns3/ptr.h> #include "ns3/radio-bearer-stats-calculator.h" #include <ns3/constant-position-mobility-model.h> #include <ns3/ff-mac-scheduler.h> #include "lte-test-fdmt-ff-mac-scheduler.h" #include <ns3/eps-bearer.h> #include <ns3/node-container.h> #include <ns3/mobility-helper.h> #include <ns3/net-device-container.h> #include <ns3/lte-ue-net-device.h> #include <ns3/lte-enb-net-device.h> #include <ns3/lte-ue-rrc.h> #include <ns3/lte-helper.h> #include "ns3/string.h" #include "ns3/double.h" #include <ns3/lte-enb-phy.h> #include <ns3/lte-ue-phy.h> #include <ns3/boolean.h> #include <ns3/enum.h> using namespace ns3; NS_LOG_COMPONENT_DEFINE ("LenaTestFdMtFfMacScheduler"); LenaTestFdMtFfMacSchedulerSuite::LenaTestFdMtFfMacSchedulerSuite () : TestSuite ("lte-fdmt-ff-mac-scheduler", SYSTEM) { NS_LOG_INFO ("creating LenaTestFdMtFfMacSchedulerSuite"); bool errorModel = false; //Test Case : AMC works in FDMT //Note: here the MCS is calculated by the narrowband CQI // DOWNLINK - DISTANCE 0 -> MCS 28 -> Itbs 26 (from table 7.1.7.2.1-1 of 36.213) // 1 user -> 24 PRB at Itbs 26 -> 2196 -> 2196000 bytes/sec for one UE; 0 bytes/sec for other UEs // 3 users -> 2196000 among 3 users -> 2196000 bytes/sec for one UE; 0 bytes/sec for other UEs // 6 users -> 2196000 among 6 users -> 2196000 bytes/sec for one UE; 0 bytes/sec for other UEs // 12 users -> 2196000 among 12 users -> 2196000 bytes/sec for one UE; 0 bytes/sec for other UEs // UPLINK- DISTANCE 0 -> MCS 28 -> Itbs 26 (from table 7.1.7.2.1-1 of 36.213) // 1 user -> 25 PRB at Itbs 26 -> 2292 -> 2292000 bytes/sec // 3 users -> 8 PRB at Itbs 26 -> 749 -> 749000 bytes/sec // 6 users -> 4 PRB at Itbs 26 -> 373 -> 373000 bytes/sec // after the patch enforcing min 3 PRBs per UE: // 12 users -> 3 PRB at Itbs 26 -> 277 bytes * 8/12 UE/TTI -> 184670 bytes/sec AddTestCase (new LenaFdMtFfMacSchedulerTestCase (1,0,2196000,2292000, errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (3,0,2196000,749000,errorModel), TestCase::QUICK); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (6,0,2196000,373000, errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (12,0,2196000,184670, errorModel), TestCase::EXTENSIVE); // DOWNLINK - DISTANCE 4800 -> MCS 22 -> Itbs 20 (from table 7.1.7.2.1-1 of 36.213) // 1 user -> 24 PRB at Itbs 20 -> 1383 -> 1383000 byte/secfor one UE; 0 bytes/sec for other UEs // 3 users -> 1383000 among 3 users -> 1383000 bytes/sec for one UE; 0 bytes/sec for other UEs // 6 users -> 1383000 among 6 users -> 1383000 bytes/sec for one UE; 0 bytes/sec for other UEs // 12 users -> 1383000 among 12 users -> 1383000 bytes/sec for one UE; 0 bytes/sec for other UEs // UPLINK - DISTANCE 4800 -> MCS 14 -> Itbs 13 (from table 7.1.7.2.1-1 of 36.213) // 1 user -> 25 PRB at Itbs 13 -> 807 -> 807000 bytes/sec // 3 users -> 8 PRB at Itbs 13 -> 253 -> 253000 bytes/sec // 6 users -> 4 PRB at Itbs 13 -> 125 -> 125000 bytes/sec // after the patch enforcing min 3 PRBs per UE: // 12 users -> 3 PRB at Itbs 13 -> 93 bytes * 8/12 UE/TTI -> 62000 bytes/sec AddTestCase (new LenaFdMtFfMacSchedulerTestCase (1,4800,1383000,807000,errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (3,4800,1383000,253000,errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (6,4800,1383000,125000,errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (12,4800,1383000,62000,errorModel), TestCase::EXTENSIVE); // DOWNLINK - DISTANCE 6000 -> MCS 20 -> Itbs 18 (from table 7.1.7.2.1-1 of 36.213) // 1 user -> 24 PRB at Itbs 18 -> 1191 -> 1191000 byte/sec for one UE; 0 bytes/sec for other UEs // 3 users -> 1191000 among 3 users -> 1191000 bytes/sec for one UE; 0 bytes/sec for other UEs // 6 users -> 1191000 among 6 users -> 1191000 bytes/sec for one UE; 0 bytes/sec for other UEs // 12 users ->1191000 among 12 users -> 1191000 bytes/sec for one UE; 0 bytes/sec for other UEs // UPLINK - DISTANCE 6000 -> MCS 12 -> Itbs 11 (from table 7.1.7.2.1-1 of 36.213) // 1 user -> 25 PRB at Itbs 11 -> 621 -> 621000 bytes/sec // 3 users -> 8 PRB at Itbs 11 -> 201 -> 201000 bytes/sec // 6 users -> 4 PRB at Itbs 11 -> 97 -> 97000 bytes/sec // after the patch enforcing min 3 PRBs per UE: // 12 users -> 3 PRB at Itbs 11 -> 73 bytes * 8/12 UE/TTI -> 48667 bytes/sec AddTestCase (new LenaFdMtFfMacSchedulerTestCase (1,6000,1191000,621000, errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (3,6000,1191000,201000, errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (6,6000,1191000,97000, errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (12,6000,1191000,48667, errorModel), TestCase::EXTENSIVE); // DOWNLINK - DISTANCE 10000 -> MCS 14 -> Itbs 13 (from table 7.1.7.2.1-1 of 36.213) // 1 user -> 24 PRB at Itbs 13 -> 775 -> 775000 byte/sec for one UE; 0 bytes/sec for other UEs // 3 users -> 775000 among 3 users -> 775000 bytes/sec for one UE; 0 bytes/sec for other UEs // 6 users -> 775000 among 6 users -> 775000 bytes/sec for one UE; 0 bytes/sec for other UEs // 12 users -> 775000 among 12 users -> 775000 bytes/sec for one UE; 0 bytes/sec for other UEs // UPLINK - DISTANCE 10000 -> MCS 8 -> Itbs 8 (from table 7.1.7.2.1-1 of 36.213) // 1 user -> 24 PRB at Itbs 8 -> 437 -> 437000 bytes/sec // 3 users -> 8 PRB at Itbs 8 -> 137 -> 137000 bytes/sec // 6 users -> 4 PRB at Itbs 8 -> 67 -> 67000 bytes/sec // after the patch enforcing min 3 PRBs per UE: // 12 users -> 3 PRB at Itbs 8 -> 49 bytes * 8/12 UE/TTI -> 32667 bytes/sec AddTestCase (new LenaFdMtFfMacSchedulerTestCase (1,10000,775000,437000,errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (3,10000,775000,137000,errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (6,10000,775000,67000,errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (12,10000,775000,32667,errorModel), TestCase::EXTENSIVE); // DONWLINK - DISTANCE 20000 -> MCS 8 -> Itbs 8 (from table 7.1.7.2.1-1 of 36.213) // 1 user -> 24 PRB at Itbs 8 -> 421 -> 421000 bytes/sec for one UE; 0 bytes/sec for other UEs // 3 users -> 421000 among 3 users -> 421000 bytes/sec for one UE; 0 bytes/sec for other UEs // 6 users -> 421000 among 6 users -> 421000 bytes/sec for one UE; 0 bytes/sec for other UEs // 12 users -> 421000 among 12 users -> 421000 bytes/sec for one UE; 0 bytes/sec for other UEs // UPLINK - DISTANCE 20000 -> MCS 2 -> Itbs 2 (from table 7.1.7.2.1-1 of 36.213) // 1 user -> 25 PRB at Itbs 2 -> 233 -> 137000 bytes/sec // 3 users -> 8 PRB at Itbs 2 -> 69 -> 41000 bytes/sec // 6 users -> 4 PRB at Itbs 2 -> 32 -> 22000 bytes/sec // after the patch enforcing min 3 PRBs per UE: // 12 users -> 3 PRB at Itbs 2 -> 26 bytes * 8/12 UE/TTI -> 12000 bytes/sec AddTestCase (new LenaFdMtFfMacSchedulerTestCase (1,20000,421000,137000,errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (3,20000,421000,41000,errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (6,20000,421000,22000,errorModel), TestCase::EXTENSIVE); AddTestCase (new LenaFdMtFfMacSchedulerTestCase (12,20000,421000,12000,errorModel), TestCase::EXTENSIVE); // DOWNLINK - DISTANCE 100000 -> CQI == 0 -> out of range -> 0 bytes/sec // UPLINK - DISTANCE 100000 -> CQI == 0 -> out of range -> 0 bytes/sec AddTestCase (new LenaFdMtFfMacSchedulerTestCase (1,100000,0,0,errorModel), TestCase::QUICK); } static LenaTestFdMtFfMacSchedulerSuite lenaTestFdMtFfMacSchedulerSuite; // --------------- T E S T - C A S E ------------------------------ std::string LenaFdMtFfMacSchedulerTestCase::BuildNameString (uint16_t nUser, double dist) { std::ostringstream oss; oss << nUser << " UEs, distance " << dist << " m"; return oss.str (); } LenaFdMtFfMacSchedulerTestCase::LenaFdMtFfMacSchedulerTestCase (uint16_t nUser, double dist, double thrRefDl, double thrRefUl, bool errorModelEnabled) : TestCase (BuildNameString (nUser, dist)), m_nUser (nUser), m_dist (dist), m_thrRefDl (thrRefDl), m_thrRefUl (thrRefUl), m_errorModelEnabled (errorModelEnabled) { } LenaFdMtFfMacSchedulerTestCase::~LenaFdMtFfMacSchedulerTestCase () { } void LenaFdMtFfMacSchedulerTestCase::DoRun (void) { NS_LOG_FUNCTION (this << m_nUser << m_dist); if (!m_errorModelEnabled) { Config::SetDefault ("ns3::LteSpectrumPhy::CtrlErrorModelEnabled", BooleanValue (false)); Config::SetDefault ("ns3::LteSpectrumPhy::DataErrorModelEnabled", BooleanValue (false)); } Config::SetDefault ("ns3::LteHelper::UseIdealRrc", BooleanValue (true)); /** * Initialize Simulation Scenario: 1 eNB and m_nUser UEs */ Ptr<LteHelper> lteHelper = CreateObject<LteHelper> (); lteHelper->SetAttribute ("PathlossModel", StringValue ("ns3::FriisSpectrumPropagationLossModel")); // Create Nodes: eNodeB and UE NodeContainer enbNodes; NodeContainer ueNodes; enbNodes.Create (1); ueNodes.Create (m_nUser); // Install Mobility Model MobilityHelper mobility; mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel"); mobility.Install (enbNodes); mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel"); mobility.Install (ueNodes); // Create Devices and install them in the Nodes (eNB and UE) NetDeviceContainer enbDevs; NetDeviceContainer ueDevs; lteHelper->SetSchedulerType ("ns3::FdMtFfMacScheduler"); lteHelper->SetSchedulerAttribute ("UlCqiFilter", EnumValue (FfMacScheduler::SRS_UL_CQI)); enbDevs = lteHelper->InstallEnbDevice (enbNodes); ueDevs = lteHelper->InstallUeDevice (ueNodes); // Attach a UE to a eNB lteHelper->Attach (ueDevs, enbDevs.Get (0)); // Activate an EPS bearer enum EpsBearer::Qci q = EpsBearer::GBR_CONV_VOICE; EpsBearer bearer (q); lteHelper->ActivateDataRadioBearer (ueDevs, bearer); Ptr<LteEnbNetDevice> lteEnbDev = enbDevs.Get (0)->GetObject<LteEnbNetDevice> (); Ptr<LteEnbPhy> enbPhy = lteEnbDev->GetPhy (); enbPhy->SetAttribute ("TxPower", DoubleValue (30.0)); enbPhy->SetAttribute ("NoiseFigure", DoubleValue (5.0)); // Set UEs' position and power for (int i = 0; i < m_nUser; i++) { Ptr<ConstantPositionMobilityModel> mm = ueNodes.Get (i)->GetObject<ConstantPositionMobilityModel> (); mm->SetPosition (Vector (m_dist, 0.0, 0.0)); Ptr<LteUeNetDevice> lteUeDev = ueDevs.Get (i)->GetObject<LteUeNetDevice> (); Ptr<LteUePhy> uePhy = lteUeDev->GetPhy (); uePhy->SetAttribute ("TxPower", DoubleValue (23.0)); uePhy->SetAttribute ("NoiseFigure", DoubleValue (9.0)); } double statsStartTime = 0.300; // need to allow for RRC connection establishment + SRS double statsDuration = 0.6; double tolerance = 0.1; Simulator::Stop (Seconds (statsStartTime + statsDuration - 0.000001)); lteHelper->EnableMacTraces (); lteHelper->EnableRlcTraces (); Ptr<RadioBearerStatsCalculator> rlcStats = lteHelper->GetRlcStats (); rlcStats->SetAttribute ("StartTime", TimeValue (Seconds (statsStartTime))); rlcStats->SetAttribute ("EpochDuration", TimeValue (Seconds (statsDuration))); Simulator::Run (); /** * Check that the downlink assignation is done in a "frequency domain maximum throughput" manner */ NS_LOG_INFO ("DL - Test with " << m_nUser << " user(s) at distance " << m_dist); std::vector <uint64_t> dlDataRxed; for (int i = 0; i < m_nUser; i++) { // get the imsi uint64_t imsi = ueDevs.Get (i)->GetObject<LteUeNetDevice> ()->GetImsi (); uint8_t lcId = 3; dlDataRxed.push_back (rlcStats->GetDlRxData (imsi, lcId)); NS_LOG_INFO ("\tUser " << i << " imsi " << imsi << " bytes rxed " << (double)dlDataRxed.at (i) << " thr " << (double)dlDataRxed.at (i) / statsDuration << " ref " << m_thrRefDl); } /** * Check that the assignation is done in a "frequency domain maximum throughput" manner among users * with maximum SINRs: without fading, current FD MT always assign all resources to one UE */ uint8_t found = 0; for (int i = 0; i < m_nUser; i++) { double throughput = (double)dlDataRxed.at (i) / statsDuration; if (throughput != 0 && found == 0) { NS_TEST_ASSERT_MSG_EQ_TOL (throughput, m_thrRefDl, m_thrRefDl * tolerance, " Unfair Throughput!"); found = 1; } else if (throughput != 0 && found == 1) { NS_TEST_ASSERT_MSG_EQ_TOL (0, m_thrRefDl, m_thrRefDl * tolerance, " Unfair Throughput!"); } else NS_TEST_ASSERT_MSG_EQ_TOL (throughput, 0, 0, " Unfair Throughput!"); } /** * Check that the uplink assignation is done in a "proportional fair" manner */ NS_LOG_INFO ("UL - Test with " << m_nUser << " user(s) at distance " << m_dist); std::vector <uint64_t> ulDataRxed; for (int i = 0; i < m_nUser; i++) { // get the imsi uint64_t imsi = ueDevs.Get (i)->GetObject<LteUeNetDevice> ()->GetImsi (); // get the lcId uint8_t lcId = 3; ulDataRxed.push_back (rlcStats->GetUlRxData (imsi, lcId)); NS_LOG_INFO ("\tUser " << i << " imsi " << imsi << " bytes rxed " << (double)ulDataRxed.at (i) << " thr " << (double)ulDataRxed.at (i) / statsDuration << " ref " << m_thrRefUl); } /** * Check that the assignation is done in a "proportional fair" manner among users * with equal SINRs: the bandwidth should be distributed according to the * ratio of the estimated throughput per TTI of each user; therefore equally * partitioning the whole bandwidth achievable from a single users in a TTI */ for (int i = 0; i < m_nUser; i++) { NS_TEST_ASSERT_MSG_EQ_TOL ((double)ulDataRxed.at (i) / statsDuration, m_thrRefUl, m_thrRefUl * tolerance, " Unfair Throughput!"); } Simulator::Destroy (); }
tomhenderson/ns-3-dev-git
src/lte/test/lte-test-fdmt-ff-mac-scheduler.cc
C++
gpl-2.0
15,227
<?php namespace at\externet\eps_bank_transfer; class TransferMsgDetails { /** @var string Jene URL, an die der eps SO den vitality-check und die eps Zahlungs-bestätigungsnachricht (= confirma-tion) sendet. */ public $ConfirmationUrl; /** @var string Jene URL, um für den Käufer einen durchgängigen Ablauf zu garantieren und einen Rücksprungpunkt in den Webshop des Händlers anzubieten. */ public $TransactionOkUrl; /** @var string Wurde die Transaktion nicht erfolg-reich durchgeführt, so erhält der Käufer, nach Rückmeldung des Sys-tems, einen Redirect auf diese URL */ public $TransactionNokUrl; /** @var string Jenes Fenster, in welches der Redirect auf die Ok URL erfolgen soll. */ public $TargetWindowOk; /** @var string Jenes Fenster, in welches der Redirect auf die Nok URL erfolgen soll. */ public $TargetWindowNok; /** * * @param type $ConfirmationUrl * @param type $TransactionOkUrl * @param type $TransactionNokUrl */ public function __construct($ConfirmationUrl, $TransactionOkUrl, $TransactionNokUrl) { $this->ConfirmationUrl = $ConfirmationUrl; $this->TransactionOkUrl = $TransactionOkUrl; $this->TransactionNokUrl = $TransactionNokUrl; } } ?>
hakito/PHP-Stuzza-EPS-BankTransfer
src/TransferMsgDetails.php
PHP
gpl-2.0
1,282
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * 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 SimplePie Team 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 HOLDERS * AND 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. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Manages all item-related data * * Used by {@see SimplePie::get_item()} and {@see SimplePie::get_items()} * * This class can be overloaded with {@see SimplePie::set_item_class()} * * @package SimplePie * @subpackage API */ class SimplePie_Item { /** * Parent feed * * @access private * @var SimplePie */ var $feed; /** * Raw data * * @access private * @var array */ var $data = array(); /** * Registry object * * @see set_registry * @var SimplePie_Registry */ protected $registry; /** * Create a new item object * * This is usually used by {@see SimplePie::get_items} and * {@see SimplePie::get_item}. Avoid creating this manually. * * @param SimplePie $feed Parent feed * @param array $data Raw data */ public function __construct( $feed, $data ) { $this->feed = $feed; $this->data = $data; } /** * Set the registry handler * * This is usually used by {@see SimplePie_Registry::create} * * @since 1.3 * * @param SimplePie_Registry $registry */ public function set_registry( SimplePie_Registry $registry ) { $this->registry = $registry; } /** * Get a string representation of the item * * @return string */ public function __toString() { return md5( serialize( $this->data ) ); } /** * Remove items that link back to this before destroying this object */ public function __destruct() { if ( ( version_compare( PHP_VERSION, '5.3', '<' ) || ! gc_enabled() ) && ! ini_get( 'zend.ze1_compatibility_mode' ) ) { unset( $this->feed ); } } /** * Get data for an item-level element * * This method allows you to get access to ANY element/attribute that is a * sub-element of the item/entry tag. * * See {@see SimplePie::get_feed_tags()} for a description of the return value * * @since 1.0 * @see http://simplepie.org/wiki/faq/supported_xml_namespaces * * @param string $namespace The URL of the XML namespace of the elements you're trying to access * @param string $tag Tag name * * @return array */ public function get_item_tags( $namespace, $tag ) { if ( isset( $this->data['child'][$namespace][$tag] ) ) { return $this->data['child'][$namespace][$tag]; } else { return null; } } /** * Get the base URL value from the parent feed * * Uses `<xml:base>` * * @param array $element * * @return string */ public function get_base( $element = array() ) { return $this->feed->get_base( $element ); } /** * Sanitize feed data * * @access private * @see SimplePie::sanitize() * * @param string $data Data to sanitize * @param int $type One of the SIMPLEPIE_CONSTRUCT_* constants * @param string $base Base URL to resolve URLs against * * @return string Sanitized data */ public function sanitize( $data, $type, $base = '' ) { return $this->feed->sanitize( $data, $type, $base ); } /** * Get the parent feed * * Note: this may not work as you think for multifeeds! * * @link http://simplepie.org/faq/typical_multifeed_gotchas#missing_data_from_feed * @since 1.0 * @return SimplePie */ public function get_feed() { return $this->feed; } /** * Get the unique identifier for the item * * This is usually used when writing code to check for new items in a feed. * * Uses `<atom:id>`, `<guid>`, `<dc:identifier>` or the `about` attribute * for RDF. If none of these are supplied (or `$hash` is true), creates an * MD5 hash based on the permalink and title. If either of those are not * supplied, creates a hash based on the full feed data. * * @since Beta 2 * * @param boolean $hash Should we force using a hash instead of the supplied ID? * * @return string */ public function get_id( $hash = false ) { if ( ! $hash ) { if ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'id' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_03, 'id' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_20, 'guid' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_11, 'identifier' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_10, 'identifier' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( isset( $this->data['attribs'][SIMPLEPIE_NAMESPACE_RDF]['about'] ) ) { return $this->sanitize( $this->data['attribs'][SIMPLEPIE_NAMESPACE_RDF]['about'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( ( $return = $this->get_permalink() ) !== null ) { return $return; } elseif ( ( $return = $this->get_title() ) !== null ) { return $return; } } if ( $this->get_permalink() !== null || $this->get_title() !== null ) { return md5( $this->get_permalink() . $this->get_title() ); } else { return md5( serialize( $this->data ) ); } } /** * Get the title of the item * * Uses `<atom:title>`, `<title>` or `<dc:title>` * * @since Beta 2 (previously called `get_item_title` since 0.8) * @return string|null */ public function get_title() { if ( ! isset( $this->data['title'] ) ) { if ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'title' ) ) { $this->data['title'] = $this->sanitize( $return[0]['data'], $this->registry->call( 'Misc', 'atom_10_construct_type', array( $return[0]['attribs'] ) ), $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_03, 'title' ) ) { $this->data['title'] = $this->sanitize( $return[0]['data'], $this->registry->call( 'Misc', 'atom_03_construct_type', array( $return[0]['attribs'] ) ), $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_10, 'title' ) ) { $this->data['title'] = $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_090, 'title' ) ) { $this->data['title'] = $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_20, 'title' ) ) { $this->data['title'] = $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_11, 'title' ) ) { $this->data['title'] = $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_10, 'title' ) ) { $this->data['title'] = $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $this->data['title'] = null; } } return $this->data['title']; } /** * Get the content for the item * * Prefers summaries over full content , but will return full content if a * summary does not exist. * * To prefer full content instead, use {@see get_content} * * Uses `<atom:summary>`, `<description>`, `<dc:description>` or * `<itunes:subtitle>` * * @since 0.8 * * @param boolean $description_only Should we avoid falling back to the content? * * @return string|null */ public function get_description( $description_only = false ) { if ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'summary' ) ) { return $this->sanitize( $return[0]['data'], $this->registry->call( 'Misc', 'atom_10_construct_type', array( $return[0]['attribs'] ) ), $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_03, 'summary' ) ) { return $this->sanitize( $return[0]['data'], $this->registry->call( 'Misc', 'atom_03_construct_type', array( $return[0]['attribs'] ) ), $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_10, 'description' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_20, 'description' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_11, 'description' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_10, 'description' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ITUNES, 'summary' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ITUNES, 'subtitle' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_090, 'description' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML ); } elseif ( ! $description_only ) { return $this->get_content( true ); } else { return null; } } /** * Get the content for the item * * Prefers full content over summaries, but will return a summary if full * content does not exist. * * To prefer summaries instead, use {@see get_description} * * Uses `<atom:content>` or `<content:encoded>` (RSS 1.0 Content Module) * * @since 1.0 * * @param boolean $content_only Should we avoid falling back to the description? * * @return string|null */ public function get_content( $content_only = false ) { if ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'content' ) ) { return $this->sanitize( $return[0]['data'], $this->registry->call( 'Misc', 'atom_10_content_construct_type', array( $return[0]['attribs'] ) ), $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_03, 'content' ) ) { return $this->sanitize( $return[0]['data'], $this->registry->call( 'Misc', 'atom_03_construct_type', array( $return[0]['attribs'] ) ), $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_10_MODULES_CONTENT, 'encoded' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base( $return[0] ) ); } elseif ( ! $content_only ) { return $this->get_description( true ); } else { return null; } } /** * Get a category for the item * * @since Beta 3 (previously called `get_categories()` since Beta 2) * * @param int $key The category that you want to return. Remember that arrays begin with 0, not 1 * * @return SimplePie_Category|null */ public function get_category( $key = 0 ) { $categories = $this->get_categories(); if ( isset( $categories[$key] ) ) { return $categories[$key]; } else { return null; } } /** * Get all categories for the item * * Uses `<atom:category>`, `<category>` or `<dc:subject>` * * @since Beta 3 * @return array|null List of {@see SimplePie_Category} objects */ public function get_categories() { $categories = array(); foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'category' ) as $category ) { $term = null; $scheme = null; $label = null; if ( isset( $category['attribs']['']['term'] ) ) { $term = $this->sanitize( $category['attribs']['']['term'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $category['attribs']['']['scheme'] ) ) { $scheme = $this->sanitize( $category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $category['attribs']['']['label'] ) ) { $label = $this->sanitize( $category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT ); } $categories[] = $this->registry->create( 'Category', array( $term, $scheme, $label ) ); } foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_20, 'category' ) as $category ) { // This is really the label, but keep this as the term also for BC. // Label will also work on retrieving because that falls back to term. $term = $this->sanitize( $category['data'], SIMPLEPIE_CONSTRUCT_TEXT ); if ( isset( $category['attribs']['']['domain'] ) ) { $scheme = $this->sanitize( $category['attribs']['']['domain'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $scheme = null; } $categories[] = $this->registry->create( 'Category', array( $term, $scheme, null ) ); } foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_11, 'subject' ) as $category ) { $categories[] = $this->registry->create( 'Category', array( $this->sanitize( $category['data'], SIMPLEPIE_CONSTRUCT_TEXT ), null, null ) ); } foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_10, 'subject' ) as $category ) { $categories[] = $this->registry->create( 'Category', array( $this->sanitize( $category['data'], SIMPLEPIE_CONSTRUCT_TEXT ), null, null ) ); } if ( ! empty( $categories ) ) { return array_unique( $categories ); } else { return null; } } /** * Get an author for the item * * @since Beta 2 * * @param int $key The author that you want to return. Remember that arrays begin with 0, not 1 * * @return SimplePie_Author|null */ public function get_author( $key = 0 ) { $authors = $this->get_authors(); if ( isset( $authors[$key] ) ) { return $authors[$key]; } else { return null; } } /** * Get a contributor for the item * * @since 1.1 * * @param int $key The contrbutor that you want to return. Remember that arrays begin with 0, not 1 * * @return SimplePie_Author|null */ public function get_contributor( $key = 0 ) { $contributors = $this->get_contributors(); if ( isset( $contributors[$key] ) ) { return $contributors[$key]; } else { return null; } } /** * Get all contributors for the item * * Uses `<atom:contributor>` * * @since 1.1 * @return array|null List of {@see SimplePie_Author} objects */ public function get_contributors() { $contributors = array(); foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'contributor' ) as $contributor ) { $name = null; $uri = null; $email = null; if ( isset( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'] ) ) { $name = $this->sanitize( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'] ) ) { $uri = $this->sanitize( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0] ) ); } if ( isset( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'] ) ) { $email = $this->sanitize( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( $name !== null || $email !== null || $uri !== null ) { $contributors[] = $this->registry->create( 'Author', array( $name, $uri, $email ) ); } } foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_03, 'contributor' ) as $contributor ) { $name = null; $url = null; $email = null; if ( isset( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'] ) ) { $name = $this->sanitize( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'] ) ) { $url = $this->sanitize( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0] ) ); } if ( isset( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'] ) ) { $email = $this->sanitize( $contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( $name !== null || $email !== null || $url !== null ) { $contributors[] = $this->registry->create( 'Author', array( $name, $url, $email ) ); } } if ( ! empty( $contributors ) ) { return array_unique( $contributors ); } else { return null; } } /** * Get all authors for the item * * Uses `<atom:author>`, `<author>`, `<dc:creator>` or `<itunes:author>` * * @since Beta 2 * @return array|null List of {@see SimplePie_Author} objects */ public function get_authors() { $authors = array(); foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author' ) as $author ) { $name = null; $uri = null; $email = null; if ( isset( $author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'] ) ) { $name = $this->sanitize( $author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'] ) ) { $uri = $this->sanitize( $author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0] ) ); } if ( isset( $author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'] ) ) { $email = $this->sanitize( $author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( $name !== null || $email !== null || $uri !== null ) { $authors[] = $this->registry->create( 'Author', array( $name, $uri, $email ) ); } } if ( $author = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_03, 'author' ) ) { $name = null; $url = null; $email = null; if ( isset( $author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'] ) ) { $name = $this->sanitize( $author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'] ) ) { $url = $this->sanitize( $author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0] ) ); } if ( isset( $author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'] ) ) { $email = $this->sanitize( $author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( $name !== null || $email !== null || $url !== null ) { $authors[] = $this->registry->create( 'Author', array( $name, $url, $email ) ); } } if ( $author = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_20, 'author' ) ) { $authors[] = $this->registry->create( 'Author', array( null, null, $this->sanitize( $author[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ) ) ); } foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_11, 'creator' ) as $author ) { $authors[] = $this->registry->create( 'Author', array( $this->sanitize( $author['data'], SIMPLEPIE_CONSTRUCT_TEXT ), null, null ) ); } foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_10, 'creator' ) as $author ) { $authors[] = $this->registry->create( 'Author', array( $this->sanitize( $author['data'], SIMPLEPIE_CONSTRUCT_TEXT ), null, null ) ); } foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_ITUNES, 'author' ) as $author ) { $authors[] = $this->registry->create( 'Author', array( $this->sanitize( $author['data'], SIMPLEPIE_CONSTRUCT_TEXT ), null, null ) ); } if ( ! empty( $authors ) ) { return array_unique( $authors ); } elseif ( ( $source = $this->get_source() ) && ( $authors = $source->get_authors() ) ) { return $authors; } elseif ( $authors = $this->feed->get_authors() ) { return $authors; } else { return null; } } /** * Get the copyright info for the item * * Uses `<atom:rights>` or `<dc:rights>` * * @since 1.1 * @return string */ public function get_copyright() { if ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'rights' ) ) { return $this->sanitize( $return[0]['data'], $this->registry->call( 'Misc', 'atom_10_construct_type', array( $return[0]['attribs'] ) ), $this->get_base( $return[0] ) ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_11, 'rights' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_10, 'rights' ) ) { return $this->sanitize( $return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { return null; } } /** * Get the posting date/time for the item * * Uses `<atom:published>`, `<atom:updated>`, `<atom:issued>`, * `<atom:modified>`, `<pubDate>` or `<dc:date>` * * Note: obeys PHP's timezone setting. To get a UTC date/time, use * {@see get_gmdate} * * @since Beta 2 (previously called `get_item_date` since 0.8) * * @param string $date_format Supports any PHP date format from {@see http://php.net/date} (empty for the raw data) * * @return int|string|null */ public function get_date( $date_format = 'j F Y, g:i a' ) { if ( ! isset( $this->data['date'] ) ) { if ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'published' ) ) { $this->data['date']['raw'] = $return[0]['data']; } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'updated' ) ) { $this->data['date']['raw'] = $return[0]['data']; } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_03, 'issued' ) ) { $this->data['date']['raw'] = $return[0]['data']; } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_03, 'created' ) ) { $this->data['date']['raw'] = $return[0]['data']; } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_03, 'modified' ) ) { $this->data['date']['raw'] = $return[0]['data']; } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_20, 'pubDate' ) ) { $this->data['date']['raw'] = $return[0]['data']; } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_11, 'date' ) ) { $this->data['date']['raw'] = $return[0]['data']; } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_DC_10, 'date' ) ) { $this->data['date']['raw'] = $return[0]['data']; } if ( ! empty( $this->data['date']['raw'] ) ) { $parser = $this->registry->call( 'Parse_Date', 'get' ); $this->data['date']['parsed'] = $parser->parse( $this->data['date']['raw'] ); } else { $this->data['date'] = null; } } if ( $this->data['date'] ) { $date_format = (string) $date_format; switch ( $date_format ) { case '': return $this->sanitize( $this->data['date']['raw'], SIMPLEPIE_CONSTRUCT_TEXT ); case 'U': return $this->data['date']['parsed']; default: return date( $date_format, $this->data['date']['parsed'] ); } } else { return null; } } /** * Get the update date/time for the item * * Uses `<atom:updated>` * * Note: obeys PHP's timezone setting. To get a UTC date/time, use * {@see get_gmdate} * * @param string $date_format Supports any PHP date format from {@see http://php.net/date} (empty for the raw data) * * @return int|string|null */ public function get_updated_date( $date_format = 'j F Y, g:i a' ) { if ( ! isset( $this->data['updated'] ) ) { if ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'updated' ) ) { $this->data['updated']['raw'] = $return[0]['data']; } if ( ! empty( $this->data['updated']['raw'] ) ) { $parser = $this->registry->call( 'Parse_Date', 'get' ); $this->data['updated']['parsed'] = $parser->parse( $this->data['date']['raw'] ); } else { $this->data['updated'] = null; } } if ( $this->data['updated'] ) { $date_format = (string) $date_format; switch ( $date_format ) { case '': return $this->sanitize( $this->data['updated']['raw'], SIMPLEPIE_CONSTRUCT_TEXT ); case 'U': return $this->data['updated']['parsed']; default: return date( $date_format, $this->data['updated']['parsed'] ); } } else { return null; } } /** * Get the localized posting date/time for the item * * Returns the date formatted in the localized language. To display in * languages other than the server's default, you need to change the locale * with {@link http://php.net/setlocale setlocale()}. The available * localizations depend on which ones are installed on your web server. * * @since 1.0 * * @param string $date_format Supports any PHP date format from {@see http://php.net/strftime} (empty for the raw data) * * @return int|string|null */ public function get_local_date( $date_format = '%c' ) { if ( ! $date_format ) { return $this->sanitize( $this->get_date( '' ), SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( ( $date = $this->get_date( 'U' ) ) !== null && $date !== false ) { return strftime( $date_format, $date ); } else { return null; } } /** * Get the posting date/time for the item (UTC time) * * @see get_date * * @param string $date_format Supports any PHP date format from {@see http://php.net/date} * * @return int|string|null */ public function get_gmdate( $date_format = 'j F Y, g:i a' ) { $date = $this->get_date( 'U' ); if ( $date === null ) { return null; } return gmdate( $date_format, $date ); } /** * Get the update date/time for the item (UTC time) * * @see get_updated_date * * @param string $date_format Supports any PHP date format from {@see http://php.net/date} * * @return int|string|null */ public function get_updated_gmdate( $date_format = 'j F Y, g:i a' ) { $date = $this->get_updated_date( 'U' ); if ( $date === null ) { return null; } return gmdate( $date_format, $date ); } /** * Get the permalink for the item * * Returns the first link available with a relationship of "alternate". * Identical to {@see get_link()} with key 0 * * @see get_link * @since 0.8 * @return string|null Permalink URL */ public function get_permalink() { $link = $this->get_link(); $enclosure = $this->get_enclosure( 0 ); if ( $link !== null ) { return $link; } elseif ( $enclosure !== null ) { return $enclosure->get_link(); } else { return null; } } /** * Get a single link for the item * * @since Beta 3 * * @param int $key The link that you want to return. Remember that arrays begin with 0, not 1 * @param string $rel The relationship of the link to return * * @return string|null Link URL */ public function get_link( $key = 0, $rel = 'alternate' ) { $links = $this->get_links( $rel ); if ( $links[$key] !== null ) { return $links[$key]; } else { return null; } } /** * Get all links for the item * * Uses `<atom:link>`, `<link>` or `<guid>` * * @since Beta 2 * * @param string $rel The relationship of links to return * * @return array|null Links found for the item (strings) */ public function get_links( $rel = 'alternate' ) { if ( ! isset( $this->data['links'] ) ) { $this->data['links'] = array(); foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'link' ) as $link ) { if ( isset( $link['attribs']['']['href'] ) ) { $link_rel = ( isset( $link['attribs']['']['rel'] ) ) ? $link['attribs']['']['rel'] : 'alternate'; $this->data['links'][$link_rel][] = $this->sanitize( $link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $link ) ); } } foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_03, 'link' ) as $link ) { if ( isset( $link['attribs']['']['href'] ) ) { $link_rel = ( isset( $link['attribs']['']['rel'] ) ) ? $link['attribs']['']['rel'] : 'alternate'; $this->data['links'][$link_rel][] = $this->sanitize( $link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $link ) ); } } if ( $links = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_10, 'link' ) ) { $this->data['links']['alternate'][] = $this->sanitize( $links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $links[0] ) ); } if ( $links = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_090, 'link' ) ) { $this->data['links']['alternate'][] = $this->sanitize( $links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $links[0] ) ); } if ( $links = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_20, 'link' ) ) { $this->data['links']['alternate'][] = $this->sanitize( $links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $links[0] ) ); } if ( $links = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_20, 'guid' ) ) { if ( ! isset( $links[0]['attribs']['']['isPermaLink'] ) || strtolower( trim( $links[0]['attribs']['']['isPermaLink'] ) ) === 'true' ) { $this->data['links']['alternate'][] = $this->sanitize( $links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $links[0] ) ); } } $keys = array_keys( $this->data['links'] ); foreach ( $keys as $key ) { if ( $this->registry->call( 'Misc', 'is_isegment_nz_nc', array( $key ) ) ) { if ( isset( $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] ) ) { $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge( $this->data['links'][$key], $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] ); $this->data['links'][$key] =& $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]; } else { $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] =& $this->data['links'][$key]; } } elseif ( substr( $key, 0, 41 ) === SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY ) { $this->data['links'][substr( $key, 41 )] =& $this->data['links'][$key]; } $this->data['links'][$key] = array_unique( $this->data['links'][$key] ); } } if ( isset( $this->data['links'][$rel] ) ) { return $this->data['links'][$rel]; } else { return null; } } /** * Get an enclosure from the item * * Supports the <enclosure> RSS tag, as well as Media RSS and iTunes RSS. * * @since Beta 2 * @todo Add ability to prefer one type of content over another (in a media group). * * @param int $key The enclosure that you want to return. Remember that arrays begin with 0, not 1 * * @return SimplePie_Enclosure|null */ public function get_enclosure( $key = 0, $prefer = null ) { $enclosures = $this->get_enclosures(); if ( isset( $enclosures[$key] ) ) { return $enclosures[$key]; } else { return null; } } /** * Get all available enclosures (podcasts, etc.) * * Supports the <enclosure> RSS tag, as well as Media RSS and iTunes RSS. * * At this point, we're pretty much assuming that all enclosures for an item * are the same content. Anything else is too complicated to * properly support. * * @since Beta 2 * @todo Add support for end-user defined sorting of enclosures by type/handler (so we can prefer the faster-loading FLV over MP4). * @todo If an element exists at a level, but it's value is empty, we should fall back to the value from the parent (if it exists). * @return array|null List of SimplePie_Enclosure items */ public function get_enclosures() { if ( ! isset( $this->data['enclosures'] ) ) { $this->data['enclosures'] = array(); // Elements $captions_parent = null; $categories_parent = null; $copyrights_parent = null; $credits_parent = null; $description_parent = null; $duration_parent = null; $hashes_parent = null; $keywords_parent = null; $player_parent = null; $ratings_parent = null; $restrictions_parent = null; $thumbnails_parent = null; $title_parent = null; // Let's do the channel and item-level ones first, and just re-use them if we need to. $parent = $this->get_feed(); // CAPTIONS if ( $captions = $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'text' ) ) { foreach ( $captions as $caption ) { $caption_type = null; $caption_lang = null; $caption_startTime = null; $caption_endTime = null; $caption_text = null; if ( isset( $caption['attribs']['']['type'] ) ) { $caption_type = $this->sanitize( $caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['lang'] ) ) { $caption_lang = $this->sanitize( $caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['start'] ) ) { $caption_startTime = $this->sanitize( $caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['end'] ) ) { $caption_endTime = $this->sanitize( $caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['data'] ) ) { $caption_text = $this->sanitize( $caption['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $captions_parent[] = $this->registry->create( 'Caption', array( $caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text ) ); } } elseif ( $captions = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'text' ) ) { foreach ( $captions as $caption ) { $caption_type = null; $caption_lang = null; $caption_startTime = null; $caption_endTime = null; $caption_text = null; if ( isset( $caption['attribs']['']['type'] ) ) { $caption_type = $this->sanitize( $caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['lang'] ) ) { $caption_lang = $this->sanitize( $caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['start'] ) ) { $caption_startTime = $this->sanitize( $caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['end'] ) ) { $caption_endTime = $this->sanitize( $caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['data'] ) ) { $caption_text = $this->sanitize( $caption['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $captions_parent[] = $this->registry->create( 'Caption', array( $caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text ) ); } } if ( is_array( $captions_parent ) ) { $captions_parent = array_values( array_unique( $captions_parent ) ); } // CATEGORIES foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'category' ) as $category ) { $term = null; $scheme = null; $label = null; if ( isset( $category['data'] ) ) { $term = $this->sanitize( $category['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $category['attribs']['']['scheme'] ) ) { $scheme = $this->sanitize( $category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $scheme = 'http://search.yahoo.com/mrss/category_schema'; } if ( isset( $category['attribs']['']['label'] ) ) { $label = $this->sanitize( $category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT ); } $categories_parent[] = $this->registry->create( 'Category', array( $term, $scheme, $label ) ); } foreach ( (array) $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'category' ) as $category ) { $term = null; $scheme = null; $label = null; if ( isset( $category['data'] ) ) { $term = $this->sanitize( $category['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $category['attribs']['']['scheme'] ) ) { $scheme = $this->sanitize( $category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $scheme = 'http://search.yahoo.com/mrss/category_schema'; } if ( isset( $category['attribs']['']['label'] ) ) { $label = $this->sanitize( $category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT ); } $categories_parent[] = $this->registry->create( 'Category', array( $term, $scheme, $label ) ); } foreach ( (array) $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_ITUNES, 'category' ) as $category ) { $term = null; $scheme = 'http://www.itunes.com/dtds/podcast-1.0.dtd'; $label = null; if ( isset( $category['attribs']['']['text'] ) ) { $label = $this->sanitize( $category['attribs']['']['text'], SIMPLEPIE_CONSTRUCT_TEXT ); } $categories_parent[] = $this->registry->create( 'Category', array( $term, $scheme, $label ) ); if ( isset( $category['child'][SIMPLEPIE_NAMESPACE_ITUNES]['category'] ) ) { foreach ( (array) $category['child'][SIMPLEPIE_NAMESPACE_ITUNES]['category'] as $subcategory ) { if ( isset( $subcategory['attribs']['']['text'] ) ) { $label = $this->sanitize( $subcategory['attribs']['']['text'], SIMPLEPIE_CONSTRUCT_TEXT ); } $categories_parent[] = $this->registry->create( 'Category', array( $term, $scheme, $label ) ); } } } if ( is_array( $categories_parent ) ) { $categories_parent = array_values( array_unique( $categories_parent ) ); } // COPYRIGHT if ( $copyright = $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'copyright' ) ) { $copyright_url = null; $copyright_label = null; if ( isset( $copyright[0]['attribs']['']['url'] ) ) { $copyright_url = $this->sanitize( $copyright[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $copyright[0]['data'] ) ) { $copyright_label = $this->sanitize( $copyright[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $copyrights_parent = $this->registry->create( 'Copyright', array( $copyright_url, $copyright_label ) ); } elseif ( $copyright = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'copyright' ) ) { $copyright_url = null; $copyright_label = null; if ( isset( $copyright[0]['attribs']['']['url'] ) ) { $copyright_url = $this->sanitize( $copyright[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $copyright[0]['data'] ) ) { $copyright_label = $this->sanitize( $copyright[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $copyrights_parent = $this->registry->create( 'Copyright', array( $copyright_url, $copyright_label ) ); } // CREDITS if ( $credits = $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'credit' ) ) { foreach ( $credits as $credit ) { $credit_role = null; $credit_scheme = null; $credit_name = null; if ( isset( $credit['attribs']['']['role'] ) ) { $credit_role = $this->sanitize( $credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $credit['attribs']['']['scheme'] ) ) { $credit_scheme = $this->sanitize( $credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $credit_scheme = 'urn:ebu'; } if ( isset( $credit['data'] ) ) { $credit_name = $this->sanitize( $credit['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $credits_parent[] = $this->registry->create( 'Credit', array( $credit_role, $credit_scheme, $credit_name ) ); } } elseif ( $credits = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'credit' ) ) { foreach ( $credits as $credit ) { $credit_role = null; $credit_scheme = null; $credit_name = null; if ( isset( $credit['attribs']['']['role'] ) ) { $credit_role = $this->sanitize( $credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $credit['attribs']['']['scheme'] ) ) { $credit_scheme = $this->sanitize( $credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $credit_scheme = 'urn:ebu'; } if ( isset( $credit['data'] ) ) { $credit_name = $this->sanitize( $credit['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $credits_parent[] = $this->registry->create( 'Credit', array( $credit_role, $credit_scheme, $credit_name ) ); } } if ( is_array( $credits_parent ) ) { $credits_parent = array_values( array_unique( $credits_parent ) ); } // DESCRIPTION if ( $description_parent = $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'description' ) ) { if ( isset( $description_parent[0]['data'] ) ) { $description_parent = $this->sanitize( $description_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } } elseif ( $description_parent = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'description' ) ) { if ( isset( $description_parent[0]['data'] ) ) { $description_parent = $this->sanitize( $description_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } } // DURATION if ( $duration_parent = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ITUNES, 'duration' ) ) { $seconds = null; $minutes = null; $hours = null; if ( isset( $duration_parent[0]['data'] ) ) { $temp = explode( ':', $this->sanitize( $duration_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ) ); if ( sizeof( $temp ) > 0 ) { $seconds = (int) array_pop( $temp ); } if ( sizeof( $temp ) > 0 ) { $minutes = (int) array_pop( $temp ); $seconds += $minutes * 60; } if ( sizeof( $temp ) > 0 ) { $hours = (int) array_pop( $temp ); $seconds += $hours * 3600; } unset( $temp ); $duration_parent = $seconds; } } // HASHES if ( $hashes_iterator = $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'hash' ) ) { foreach ( $hashes_iterator as $hash ) { $value = null; $algo = null; if ( isset( $hash['data'] ) ) { $value = $this->sanitize( $hash['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $hash['attribs']['']['algo'] ) ) { $algo = $this->sanitize( $hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $algo = 'md5'; } $hashes_parent[] = $algo . ':' . $value; } } elseif ( $hashes_iterator = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'hash' ) ) { foreach ( $hashes_iterator as $hash ) { $value = null; $algo = null; if ( isset( $hash['data'] ) ) { $value = $this->sanitize( $hash['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $hash['attribs']['']['algo'] ) ) { $algo = $this->sanitize( $hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $algo = 'md5'; } $hashes_parent[] = $algo . ':' . $value; } } if ( is_array( $hashes_parent ) ) { $hashes_parent = array_values( array_unique( $hashes_parent ) ); } // KEYWORDS if ( $keywords = $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'keywords' ) ) { if ( isset( $keywords[0]['data'] ) ) { $temp = explode( ',', $this->sanitize( $keywords[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ) ); foreach ( $temp as $word ) { $keywords_parent[] = trim( $word ); } } unset( $temp ); } elseif ( $keywords = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ITUNES, 'keywords' ) ) { if ( isset( $keywords[0]['data'] ) ) { $temp = explode( ',', $this->sanitize( $keywords[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ) ); foreach ( $temp as $word ) { $keywords_parent[] = trim( $word ); } } unset( $temp ); } elseif ( $keywords = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'keywords' ) ) { if ( isset( $keywords[0]['data'] ) ) { $temp = explode( ',', $this->sanitize( $keywords[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ) ); foreach ( $temp as $word ) { $keywords_parent[] = trim( $word ); } } unset( $temp ); } elseif ( $keywords = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_ITUNES, 'keywords' ) ) { if ( isset( $keywords[0]['data'] ) ) { $temp = explode( ',', $this->sanitize( $keywords[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ) ); foreach ( $temp as $word ) { $keywords_parent[] = trim( $word ); } } unset( $temp ); } if ( is_array( $keywords_parent ) ) { $keywords_parent = array_values( array_unique( $keywords_parent ) ); } // PLAYER if ( $player_parent = $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'player' ) ) { if ( isset( $player_parent[0]['attribs']['']['url'] ) ) { $player_parent = $this->sanitize( $player_parent[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI ); } } elseif ( $player_parent = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'player' ) ) { if ( isset( $player_parent[0]['attribs']['']['url'] ) ) { $player_parent = $this->sanitize( $player_parent[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI ); } } // RATINGS if ( $ratings = $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'rating' ) ) { foreach ( $ratings as $rating ) { $rating_scheme = null; $rating_value = null; if ( isset( $rating['attribs']['']['scheme'] ) ) { $rating_scheme = $this->sanitize( $rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $rating_scheme = 'urn:simple'; } if ( isset( $rating['data'] ) ) { $rating_value = $this->sanitize( $rating['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $ratings_parent[] = $this->registry->create( 'Rating', array( $rating_scheme, $rating_value ) ); } } elseif ( $ratings = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ITUNES, 'explicit' ) ) { foreach ( $ratings as $rating ) { $rating_scheme = 'urn:itunes'; $rating_value = null; if ( isset( $rating['data'] ) ) { $rating_value = $this->sanitize( $rating['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $ratings_parent[] = $this->registry->create( 'Rating', array( $rating_scheme, $rating_value ) ); } } elseif ( $ratings = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'rating' ) ) { foreach ( $ratings as $rating ) { $rating_scheme = null; $rating_value = null; if ( isset( $rating['attribs']['']['scheme'] ) ) { $rating_scheme = $this->sanitize( $rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $rating_scheme = 'urn:simple'; } if ( isset( $rating['data'] ) ) { $rating_value = $this->sanitize( $rating['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $ratings_parent[] = $this->registry->create( 'Rating', array( $rating_scheme, $rating_value ) ); } } elseif ( $ratings = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_ITUNES, 'explicit' ) ) { foreach ( $ratings as $rating ) { $rating_scheme = 'urn:itunes'; $rating_value = null; if ( isset( $rating['data'] ) ) { $rating_value = $this->sanitize( $rating['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $ratings_parent[] = $this->registry->create( 'Rating', array( $rating_scheme, $rating_value ) ); } } if ( is_array( $ratings_parent ) ) { $ratings_parent = array_values( array_unique( $ratings_parent ) ); } // RESTRICTIONS if ( $restrictions = $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'restriction' ) ) { foreach ( $restrictions as $restriction ) { $restriction_relationship = null; $restriction_type = null; $restriction_value = null; if ( isset( $restriction['attribs']['']['relationship'] ) ) { $restriction_relationship = $this->sanitize( $restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $restriction['attribs']['']['type'] ) ) { $restriction_type = $this->sanitize( $restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $restriction['data'] ) ) { $restriction_value = $this->sanitize( $restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $restrictions_parent[] = $this->registry->create( 'Restriction', array( $restriction_relationship, $restriction_type, $restriction_value ) ); } } elseif ( $restrictions = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ITUNES, 'block' ) ) { foreach ( $restrictions as $restriction ) { $restriction_relationship = 'allow'; $restriction_type = null; $restriction_value = 'itunes'; if ( isset( $restriction['data'] ) && strtolower( $restriction['data'] ) === 'yes' ) { $restriction_relationship = 'deny'; } $restrictions_parent[] = $this->registry->create( 'Restriction', array( $restriction_relationship, $restriction_type, $restriction_value ) ); } } elseif ( $restrictions = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'restriction' ) ) { foreach ( $restrictions as $restriction ) { $restriction_relationship = null; $restriction_type = null; $restriction_value = null; if ( isset( $restriction['attribs']['']['relationship'] ) ) { $restriction_relationship = $this->sanitize( $restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $restriction['attribs']['']['type'] ) ) { $restriction_type = $this->sanitize( $restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $restriction['data'] ) ) { $restriction_value = $this->sanitize( $restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $restrictions_parent[] = $this->registry->create( 'Restriction', array( $restriction_relationship, $restriction_type, $restriction_value ) ); } } elseif ( $restrictions = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_ITUNES, 'block' ) ) { foreach ( $restrictions as $restriction ) { $restriction_relationship = 'allow'; $restriction_type = null; $restriction_value = 'itunes'; if ( isset( $restriction['data'] ) && strtolower( $restriction['data'] ) === 'yes' ) { $restriction_relationship = 'deny'; } $restrictions_parent[] = $this->registry->create( 'Restriction', array( $restriction_relationship, $restriction_type, $restriction_value ) ); } } if ( is_array( $restrictions_parent ) ) { $restrictions_parent = array_values( array_unique( $restrictions_parent ) ); } else { $restrictions_parent = array( new SimplePie_Restriction( 'allow', null, 'default' ) ); } // THUMBNAILS if ( $thumbnails = $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'thumbnail' ) ) { foreach ( $thumbnails as $thumbnail ) { if ( isset( $thumbnail['attribs']['']['url'] ) ) { $thumbnails_parent[] = $this->sanitize( $thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI ); } } } elseif ( $thumbnails = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'thumbnail' ) ) { foreach ( $thumbnails as $thumbnail ) { if ( isset( $thumbnail['attribs']['']['url'] ) ) { $thumbnails_parent[] = $this->sanitize( $thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI ); } } } // TITLES if ( $title_parent = $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'title' ) ) { if ( isset( $title_parent[0]['data'] ) ) { $title_parent = $this->sanitize( $title_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } } elseif ( $title_parent = $parent->get_channel_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'title' ) ) { if ( isset( $title_parent[0]['data'] ) ) { $title_parent = $this->sanitize( $title_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } } // Clear the memory unset( $parent ); // Attributes $bitrate = null; $channels = null; $duration = null; $expression = null; $framerate = null; $height = null; $javascript = null; $lang = null; $length = null; $medium = null; $samplingrate = null; $type = null; $url = null; $width = null; // Elements $captions = null; $categories = null; $copyrights = null; $credits = null; $description = null; $hashes = null; $keywords = null; $player = null; $ratings = null; $restrictions = null; $thumbnails = null; $title = null; // If we have media:group tags, loop through them. foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_MEDIARSS, 'group' ) as $group ) { if ( isset( $group['child'] ) && isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content'] ) ) { // If we have media:content tags, loop through them. foreach ( (array) $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content'] as $content ) { if ( isset( $content['attribs']['']['url'] ) ) { // Attributes $bitrate = null; $channels = null; $duration = null; $expression = null; $framerate = null; $height = null; $javascript = null; $lang = null; $length = null; $medium = null; $samplingrate = null; $type = null; $url = null; $width = null; // Elements $captions = null; $categories = null; $copyrights = null; $credits = null; $description = null; $hashes = null; $keywords = null; $player = null; $ratings = null; $restrictions = null; $thumbnails = null; $title = null; // Start checking the attributes of media:content if ( isset( $content['attribs']['']['bitrate'] ) ) { $bitrate = $this->sanitize( $content['attribs']['']['bitrate'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['channels'] ) ) { $channels = $this->sanitize( $content['attribs']['']['channels'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['duration'] ) ) { $duration = $this->sanitize( $content['attribs']['']['duration'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $duration = $duration_parent; } if ( isset( $content['attribs']['']['expression'] ) ) { $expression = $this->sanitize( $content['attribs']['']['expression'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['framerate'] ) ) { $framerate = $this->sanitize( $content['attribs']['']['framerate'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['height'] ) ) { $height = $this->sanitize( $content['attribs']['']['height'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['lang'] ) ) { $lang = $this->sanitize( $content['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['fileSize'] ) ) { $length = ceil( $content['attribs']['']['fileSize'] ); } if ( isset( $content['attribs']['']['medium'] ) ) { $medium = $this->sanitize( $content['attribs']['']['medium'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['samplingrate'] ) ) { $samplingrate = $this->sanitize( $content['attribs']['']['samplingrate'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['type'] ) ) { $type = $this->sanitize( $content['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['width'] ) ) { $width = $this->sanitize( $content['attribs']['']['width'], SIMPLEPIE_CONSTRUCT_TEXT ); } $url = $this->sanitize( $content['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI ); // Checking the other optional media: elements. Priority: media:content, media:group, item, channel // CAPTIONS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'] ) ) { foreach ( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'] as $caption ) { $caption_type = null; $caption_lang = null; $caption_startTime = null; $caption_endTime = null; $caption_text = null; if ( isset( $caption['attribs']['']['type'] ) ) { $caption_type = $this->sanitize( $caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['lang'] ) ) { $caption_lang = $this->sanitize( $caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['start'] ) ) { $caption_startTime = $this->sanitize( $caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['end'] ) ) { $caption_endTime = $this->sanitize( $caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['data'] ) ) { $caption_text = $this->sanitize( $caption['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $captions[] = $this->registry->create( 'Caption', array( $caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text ) ); } if ( is_array( $captions ) ) { $captions = array_values( array_unique( $captions ) ); } } elseif ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'] ) ) { foreach ( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'] as $caption ) { $caption_type = null; $caption_lang = null; $caption_startTime = null; $caption_endTime = null; $caption_text = null; if ( isset( $caption['attribs']['']['type'] ) ) { $caption_type = $this->sanitize( $caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['lang'] ) ) { $caption_lang = $this->sanitize( $caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['start'] ) ) { $caption_startTime = $this->sanitize( $caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['end'] ) ) { $caption_endTime = $this->sanitize( $caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['data'] ) ) { $caption_text = $this->sanitize( $caption['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $captions[] = $this->registry->create( 'Caption', array( $caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text ) ); } if ( is_array( $captions ) ) { $captions = array_values( array_unique( $captions ) ); } } else { $captions = $captions_parent; } // CATEGORIES if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'] ) ) { foreach ( (array) $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'] as $category ) { $term = null; $scheme = null; $label = null; if ( isset( $category['data'] ) ) { $term = $this->sanitize( $category['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $category['attribs']['']['scheme'] ) ) { $scheme = $this->sanitize( $category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $scheme = 'http://search.yahoo.com/mrss/category_schema'; } if ( isset( $category['attribs']['']['label'] ) ) { $label = $this->sanitize( $category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT ); } $categories[] = $this->registry->create( 'Category', array( $term, $scheme, $label ) ); } } if ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'] ) ) { foreach ( (array) $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'] as $category ) { $term = null; $scheme = null; $label = null; if ( isset( $category['data'] ) ) { $term = $this->sanitize( $category['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $category['attribs']['']['scheme'] ) ) { $scheme = $this->sanitize( $category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $scheme = 'http://search.yahoo.com/mrss/category_schema'; } if ( isset( $category['attribs']['']['label'] ) ) { $label = $this->sanitize( $category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT ); } $categories[] = $this->registry->create( 'Category', array( $term, $scheme, $label ) ); } } if ( is_array( $categories ) && is_array( $categories_parent ) ) { $categories = array_values( array_unique( array_merge( $categories, $categories_parent ) ) ); } elseif ( is_array( $categories ) ) { $categories = array_values( array_unique( $categories ) ); } elseif ( is_array( $categories_parent ) ) { $categories = array_values( array_unique( $categories_parent ) ); } // COPYRIGHTS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'] ) ) { $copyright_url = null; $copyright_label = null; if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'] ) ) { $copyright_url = $this->sanitize( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'] ) ) { $copyright_label = $this->sanitize( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $copyrights = $this->registry->create( 'Copyright', array( $copyright_url, $copyright_label ) ); } elseif ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'] ) ) { $copyright_url = null; $copyright_label = null; if ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'] ) ) { $copyright_url = $this->sanitize( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'] ) ) { $copyright_label = $this->sanitize( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $copyrights = $this->registry->create( 'Copyright', array( $copyright_url, $copyright_label ) ); } else { $copyrights = $copyrights_parent; } // CREDITS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'] ) ) { foreach ( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'] as $credit ) { $credit_role = null; $credit_scheme = null; $credit_name = null; if ( isset( $credit['attribs']['']['role'] ) ) { $credit_role = $this->sanitize( $credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $credit['attribs']['']['scheme'] ) ) { $credit_scheme = $this->sanitize( $credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $credit_scheme = 'urn:ebu'; } if ( isset( $credit['data'] ) ) { $credit_name = $this->sanitize( $credit['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $credits[] = $this->registry->create( 'Credit', array( $credit_role, $credit_scheme, $credit_name ) ); } if ( is_array( $credits ) ) { $credits = array_values( array_unique( $credits ) ); } } elseif ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'] ) ) { foreach ( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'] as $credit ) { $credit_role = null; $credit_scheme = null; $credit_name = null; if ( isset( $credit['attribs']['']['role'] ) ) { $credit_role = $this->sanitize( $credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $credit['attribs']['']['scheme'] ) ) { $credit_scheme = $this->sanitize( $credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $credit_scheme = 'urn:ebu'; } if ( isset( $credit['data'] ) ) { $credit_name = $this->sanitize( $credit['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $credits[] = $this->registry->create( 'Credit', array( $credit_role, $credit_scheme, $credit_name ) ); } if ( is_array( $credits ) ) { $credits = array_values( array_unique( $credits ) ); } } else { $credits = $credits_parent; } // DESCRIPTION if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'] ) ) { $description = $this->sanitize( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'] ) ) { $description = $this->sanitize( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $description = $description_parent; } // HASHES if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'] ) ) { foreach ( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'] as $hash ) { $value = null; $algo = null; if ( isset( $hash['data'] ) ) { $value = $this->sanitize( $hash['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $hash['attribs']['']['algo'] ) ) { $algo = $this->sanitize( $hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $algo = 'md5'; } $hashes[] = $algo . ':' . $value; } if ( is_array( $hashes ) ) { $hashes = array_values( array_unique( $hashes ) ); } } elseif ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'] ) ) { foreach ( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'] as $hash ) { $value = null; $algo = null; if ( isset( $hash['data'] ) ) { $value = $this->sanitize( $hash['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $hash['attribs']['']['algo'] ) ) { $algo = $this->sanitize( $hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $algo = 'md5'; } $hashes[] = $algo . ':' . $value; } if ( is_array( $hashes ) ) { $hashes = array_values( array_unique( $hashes ) ); } } else { $hashes = $hashes_parent; } // KEYWORDS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'] ) ) { if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'] ) ) { $temp = explode( ',', $this->sanitize( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ) ); foreach ( $temp as $word ) { $keywords[] = trim( $word ); } unset( $temp ); } if ( is_array( $keywords ) ) { $keywords = array_values( array_unique( $keywords ) ); } } elseif ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'] ) ) { if ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'] ) ) { $temp = explode( ',', $this->sanitize( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ) ); foreach ( $temp as $word ) { $keywords[] = trim( $word ); } unset( $temp ); } if ( is_array( $keywords ) ) { $keywords = array_values( array_unique( $keywords ) ); } } else { $keywords = $keywords_parent; } // PLAYER if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'] ) ) { $player = $this->sanitize( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI ); } elseif ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'] ) ) { $player = $this->sanitize( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI ); } else { $player = $player_parent; } // RATINGS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'] ) ) { foreach ( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'] as $rating ) { $rating_scheme = null; $rating_value = null; if ( isset( $rating['attribs']['']['scheme'] ) ) { $rating_scheme = $this->sanitize( $rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $rating_scheme = 'urn:simple'; } if ( isset( $rating['data'] ) ) { $rating_value = $this->sanitize( $rating['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $ratings[] = $this->registry->create( 'Rating', array( $rating_scheme, $rating_value ) ); } if ( is_array( $ratings ) ) { $ratings = array_values( array_unique( $ratings ) ); } } elseif ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'] ) ) { foreach ( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'] as $rating ) { $rating_scheme = null; $rating_value = null; if ( isset( $rating['attribs']['']['scheme'] ) ) { $rating_scheme = $this->sanitize( $rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $rating_scheme = 'urn:simple'; } if ( isset( $rating['data'] ) ) { $rating_value = $this->sanitize( $rating['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $ratings[] = $this->registry->create( 'Rating', array( $rating_scheme, $rating_value ) ); } if ( is_array( $ratings ) ) { $ratings = array_values( array_unique( $ratings ) ); } } else { $ratings = $ratings_parent; } // RESTRICTIONS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'] ) ) { foreach ( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'] as $restriction ) { $restriction_relationship = null; $restriction_type = null; $restriction_value = null; if ( isset( $restriction['attribs']['']['relationship'] ) ) { $restriction_relationship = $this->sanitize( $restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $restriction['attribs']['']['type'] ) ) { $restriction_type = $this->sanitize( $restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $restriction['data'] ) ) { $restriction_value = $this->sanitize( $restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $restrictions[] = $this->registry->create( 'Restriction', array( $restriction_relationship, $restriction_type, $restriction_value ) ); } if ( is_array( $restrictions ) ) { $restrictions = array_values( array_unique( $restrictions ) ); } } elseif ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'] ) ) { foreach ( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'] as $restriction ) { $restriction_relationship = null; $restriction_type = null; $restriction_value = null; if ( isset( $restriction['attribs']['']['relationship'] ) ) { $restriction_relationship = $this->sanitize( $restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $restriction['attribs']['']['type'] ) ) { $restriction_type = $this->sanitize( $restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $restriction['data'] ) ) { $restriction_value = $this->sanitize( $restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $restrictions[] = $this->registry->create( 'Restriction', array( $restriction_relationship, $restriction_type, $restriction_value ) ); } if ( is_array( $restrictions ) ) { $restrictions = array_values( array_unique( $restrictions ) ); } } else { $restrictions = $restrictions_parent; } // THUMBNAILS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'] ) ) { foreach ( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'] as $thumbnail ) { $thumbnails[] = $this->sanitize( $thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI ); } if ( is_array( $thumbnails ) ) { $thumbnails = array_values( array_unique( $thumbnails ) ); } } elseif ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'] ) ) { foreach ( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'] as $thumbnail ) { $thumbnails[] = $this->sanitize( $thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI ); } if ( is_array( $thumbnails ) ) { $thumbnails = array_values( array_unique( $thumbnails ) ); } } else { $thumbnails = $thumbnails_parent; } // TITLES if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'] ) ) { $title = $this->sanitize( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } elseif ( isset( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'] ) ) { $title = $this->sanitize( $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $title = $title_parent; } $this->data['enclosures'][] = $this->registry->create( 'Enclosure', array( $url, $type, $length, null, $bitrate, $captions, $categories, $channels, $copyrights, $credits, $description, $duration, $expression, $framerate, $hashes, $height, $keywords, $lang, $medium, $player, $ratings, $restrictions, $samplingrate, $thumbnails, $title, $width ) ); } } } } // If we have standalone media:content tags, loop through them. if ( isset( $this->data['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content'] ) ) { foreach ( (array) $this->data['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content'] as $content ) { if ( isset( $content['attribs']['']['url'] ) || isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'] ) ) { // Attributes $bitrate = null; $channels = null; $duration = null; $expression = null; $framerate = null; $height = null; $javascript = null; $lang = null; $length = null; $medium = null; $samplingrate = null; $type = null; $url = null; $width = null; // Elements $captions = null; $categories = null; $copyrights = null; $credits = null; $description = null; $hashes = null; $keywords = null; $player = null; $ratings = null; $restrictions = null; $thumbnails = null; $title = null; // Start checking the attributes of media:content if ( isset( $content['attribs']['']['bitrate'] ) ) { $bitrate = $this->sanitize( $content['attribs']['']['bitrate'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['channels'] ) ) { $channels = $this->sanitize( $content['attribs']['']['channels'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['duration'] ) ) { $duration = $this->sanitize( $content['attribs']['']['duration'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $duration = $duration_parent; } if ( isset( $content['attribs']['']['expression'] ) ) { $expression = $this->sanitize( $content['attribs']['']['expression'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['framerate'] ) ) { $framerate = $this->sanitize( $content['attribs']['']['framerate'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['height'] ) ) { $height = $this->sanitize( $content['attribs']['']['height'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['lang'] ) ) { $lang = $this->sanitize( $content['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['fileSize'] ) ) { $length = ceil( $content['attribs']['']['fileSize'] ); } if ( isset( $content['attribs']['']['medium'] ) ) { $medium = $this->sanitize( $content['attribs']['']['medium'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['samplingrate'] ) ) { $samplingrate = $this->sanitize( $content['attribs']['']['samplingrate'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['type'] ) ) { $type = $this->sanitize( $content['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['width'] ) ) { $width = $this->sanitize( $content['attribs']['']['width'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['attribs']['']['url'] ) ) { $url = $this->sanitize( $content['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI ); } // Checking the other optional media: elements. Priority: media:content, media:group, item, channel // CAPTIONS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'] ) ) { foreach ( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'] as $caption ) { $caption_type = null; $caption_lang = null; $caption_startTime = null; $caption_endTime = null; $caption_text = null; if ( isset( $caption['attribs']['']['type'] ) ) { $caption_type = $this->sanitize( $caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['lang'] ) ) { $caption_lang = $this->sanitize( $caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['start'] ) ) { $caption_startTime = $this->sanitize( $caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['attribs']['']['end'] ) ) { $caption_endTime = $this->sanitize( $caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $caption['data'] ) ) { $caption_text = $this->sanitize( $caption['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $captions[] = $this->registry->create( 'Caption', array( $caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text ) ); } if ( is_array( $captions ) ) { $captions = array_values( array_unique( $captions ) ); } } else { $captions = $captions_parent; } // CATEGORIES if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'] ) ) { foreach ( (array) $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'] as $category ) { $term = null; $scheme = null; $label = null; if ( isset( $category['data'] ) ) { $term = $this->sanitize( $category['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $category['attribs']['']['scheme'] ) ) { $scheme = $this->sanitize( $category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $scheme = 'http://search.yahoo.com/mrss/category_schema'; } if ( isset( $category['attribs']['']['label'] ) ) { $label = $this->sanitize( $category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT ); } $categories[] = $this->registry->create( 'Category', array( $term, $scheme, $label ) ); } } if ( is_array( $categories ) && is_array( $categories_parent ) ) { $categories = array_values( array_unique( array_merge( $categories, $categories_parent ) ) ); } elseif ( is_array( $categories ) ) { $categories = array_values( array_unique( $categories ) ); } elseif ( is_array( $categories_parent ) ) { $categories = array_values( array_unique( $categories_parent ) ); } else { $categories = null; } // COPYRIGHTS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'] ) ) { $copyright_url = null; $copyright_label = null; if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'] ) ) { $copyright_url = $this->sanitize( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'] ) ) { $copyright_label = $this->sanitize( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $copyrights = $this->registry->create( 'Copyright', array( $copyright_url, $copyright_label ) ); } else { $copyrights = $copyrights_parent; } // CREDITS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'] ) ) { foreach ( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'] as $credit ) { $credit_role = null; $credit_scheme = null; $credit_name = null; if ( isset( $credit['attribs']['']['role'] ) ) { $credit_role = $this->sanitize( $credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $credit['attribs']['']['scheme'] ) ) { $credit_scheme = $this->sanitize( $credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $credit_scheme = 'urn:ebu'; } if ( isset( $credit['data'] ) ) { $credit_name = $this->sanitize( $credit['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $credits[] = $this->registry->create( 'Credit', array( $credit_role, $credit_scheme, $credit_name ) ); } if ( is_array( $credits ) ) { $credits = array_values( array_unique( $credits ) ); } } else { $credits = $credits_parent; } // DESCRIPTION if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'] ) ) { $description = $this->sanitize( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $description = $description_parent; } // HASHES if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'] ) ) { foreach ( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'] as $hash ) { $value = null; $algo = null; if ( isset( $hash['data'] ) ) { $value = $this->sanitize( $hash['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $hash['attribs']['']['algo'] ) ) { $algo = $this->sanitize( $hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $algo = 'md5'; } $hashes[] = $algo . ':' . $value; } if ( is_array( $hashes ) ) { $hashes = array_values( array_unique( $hashes ) ); } } else { $hashes = $hashes_parent; } // KEYWORDS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'] ) ) { if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'] ) ) { $temp = explode( ',', $this->sanitize( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ) ); foreach ( $temp as $word ) { $keywords[] = trim( $word ); } unset( $temp ); } if ( is_array( $keywords ) ) { $keywords = array_values( array_unique( $keywords ) ); } } else { $keywords = $keywords_parent; } // PLAYER if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'] ) ) { $player = $this->sanitize( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI ); } else { $player = $player_parent; } // RATINGS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'] ) ) { foreach ( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'] as $rating ) { $rating_scheme = null; $rating_value = null; if ( isset( $rating['attribs']['']['scheme'] ) ) { $rating_scheme = $this->sanitize( $rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $rating_scheme = 'urn:simple'; } if ( isset( $rating['data'] ) ) { $rating_value = $this->sanitize( $rating['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $ratings[] = $this->registry->create( 'Rating', array( $rating_scheme, $rating_value ) ); } if ( is_array( $ratings ) ) { $ratings = array_values( array_unique( $ratings ) ); } } else { $ratings = $ratings_parent; } // RESTRICTIONS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'] ) ) { foreach ( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'] as $restriction ) { $restriction_relationship = null; $restriction_type = null; $restriction_value = null; if ( isset( $restriction['attribs']['']['relationship'] ) ) { $restriction_relationship = $this->sanitize( $restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $restriction['attribs']['']['type'] ) ) { $restriction_type = $this->sanitize( $restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $restriction['data'] ) ) { $restriction_value = $this->sanitize( $restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } $restrictions[] = $this->registry->create( 'Restriction', array( $restriction_relationship, $restriction_type, $restriction_value ) ); } if ( is_array( $restrictions ) ) { $restrictions = array_values( array_unique( $restrictions ) ); } } else { $restrictions = $restrictions_parent; } // THUMBNAILS if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'] ) ) { foreach ( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'] as $thumbnail ) { $thumbnails[] = $this->sanitize( $thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI ); } if ( is_array( $thumbnails ) ) { $thumbnails = array_values( array_unique( $thumbnails ) ); } } else { $thumbnails = $thumbnails_parent; } // TITLES if ( isset( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'] ) ) { $title = $this->sanitize( $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT ); } else { $title = $title_parent; } $this->data['enclosures'][] = $this->registry->create( 'Enclosure', array( $url, $type, $length, null, $bitrate, $captions, $categories, $channels, $copyrights, $credits, $description, $duration, $expression, $framerate, $hashes, $height, $keywords, $lang, $medium, $player, $ratings, $restrictions, $samplingrate, $thumbnails, $title, $width ) ); } } } foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'link' ) as $link ) { if ( isset( $link['attribs']['']['href'] ) && ! empty( $link['attribs']['']['rel'] ) && $link['attribs']['']['rel'] === 'enclosure' ) { // Attributes $bitrate = null; $channels = null; $duration = null; $expression = null; $framerate = null; $height = null; $javascript = null; $lang = null; $length = null; $medium = null; $samplingrate = null; $type = null; $url = null; $width = null; $url = $this->sanitize( $link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $link ) ); if ( isset( $link['attribs']['']['type'] ) ) { $type = $this->sanitize( $link['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $link['attribs']['']['length'] ) ) { $length = ceil( $link['attribs']['']['length'] ); } // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor $this->data['enclosures'][] = $this->registry->create( 'Enclosure', array( $url, $type, $length, null, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width ) ); } } foreach ( (array) $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_03, 'link' ) as $link ) { if ( isset( $link['attribs']['']['href'] ) && ! empty( $link['attribs']['']['rel'] ) && $link['attribs']['']['rel'] === 'enclosure' ) { // Attributes $bitrate = null; $channels = null; $duration = null; $expression = null; $framerate = null; $height = null; $javascript = null; $lang = null; $length = null; $medium = null; $samplingrate = null; $type = null; $url = null; $width = null; $url = $this->sanitize( $link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $link ) ); if ( isset( $link['attribs']['']['type'] ) ) { $type = $this->sanitize( $link['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $link['attribs']['']['length'] ) ) { $length = ceil( $link['attribs']['']['length'] ); } // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor $this->data['enclosures'][] = $this->registry->create( 'Enclosure', array( $url, $type, $length, null, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width ) ); } } if ( $enclosure = $this->get_item_tags( SIMPLEPIE_NAMESPACE_RSS_20, 'enclosure' ) ) { if ( isset( $enclosure[0]['attribs']['']['url'] ) ) { // Attributes $bitrate = null; $channels = null; $duration = null; $expression = null; $framerate = null; $height = null; $javascript = null; $lang = null; $length = null; $medium = null; $samplingrate = null; $type = null; $url = null; $width = null; $url = $this->sanitize( $enclosure[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base( $enclosure[0] ) ); if ( isset( $enclosure[0]['attribs']['']['type'] ) ) { $type = $this->sanitize( $enclosure[0]['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT ); } if ( isset( $enclosure[0]['attribs']['']['length'] ) ) { $length = ceil( $enclosure[0]['attribs']['']['length'] ); } // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor $this->data['enclosures'][] = $this->registry->create( 'Enclosure', array( $url, $type, $length, null, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width ) ); } } if ( sizeof( $this->data['enclosures'] ) === 0 && ( $url || $type || $length || $bitrate || $captions_parent || $categories_parent || $channels || $copyrights_parent || $credits_parent || $description_parent || $duration_parent || $expression || $framerate || $hashes_parent || $height || $keywords_parent || $lang || $medium || $player_parent || $ratings_parent || $restrictions_parent || $samplingrate || $thumbnails_parent || $title_parent || $width ) ) { // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor $this->data['enclosures'][] = $this->registry->create( 'Enclosure', array( $url, $type, $length, null, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width ) ); } $this->data['enclosures'] = array_values( array_unique( $this->data['enclosures'] ) ); } if ( ! empty( $this->data['enclosures'] ) ) { return $this->data['enclosures']; } else { return null; } } /** * Get the latitude coordinates for the item * * Compatible with the W3C WGS84 Basic Geo and GeoRSS specifications * * Uses `<geo:lat>` or `<georss:point>` * * @since 1.0 * @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo * @link http://www.georss.org/ GeoRSS * @return string|null */ public function get_latitude() { if ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lat' ) ) { return (float) $return[0]['data']; } elseif ( ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_GEORSS, 'point' ) ) && preg_match( '/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim( $return[0]['data'] ), $match ) ) { return (float) $match[1]; } else { return null; } } /** * Get the longitude coordinates for the item * * Compatible with the W3C WGS84 Basic Geo and GeoRSS specifications * * Uses `<geo:long>`, `<geo:lon>` or `<georss:point>` * * @since 1.0 * @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo * @link http://www.georss.org/ GeoRSS * @return string|null */ public function get_longitude() { if ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'long' ) ) { return (float) $return[0]['data']; } elseif ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lon' ) ) { return (float) $return[0]['data']; } elseif ( ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_GEORSS, 'point' ) ) && preg_match( '/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim( $return[0]['data'] ), $match ) ) { return (float) $match[2]; } else { return null; } } /** * Get the `<atom:source>` for the item * * @since 1.1 * @return SimplePie_Source|null */ public function get_source() { if ( $return = $this->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'source' ) ) { return $this->registry->create( 'Source', array( $this, $return[0] ) ); } else { return null; } } }
AhmedSayedAhmed/MM_Portal
wp-content/plugins/wp-pipes/plugins/engines/rssreader/helpers/library/SimplePie/Item.php
PHP
gpl-2.0
99,035
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build aix darwin dragonfly freebsd linux nacl netbsd openbsd solaris windows package net import ( "context" "runtime" "syscall" ) func probeIPv4Stack() bool { s, err := socketFunc(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP) switch err { case syscall.EAFNOSUPPORT, syscall.EPROTONOSUPPORT: return false case nil: closeFunc(s) } return true } // Should we try to use the IPv4 socket interface if we're // only dealing with IPv4 sockets? As long as the host system // understands IPv6, it's okay to pass IPv4 addresses to the IPv6 // interface. That simplifies our code and is most general. // Unfortunately, we need to run on kernels built without IPv6 // support too. So probe the kernel to figure it out. // // probeIPv6Stack probes both basic IPv6 capability and IPv6 IPv4- // mapping capability which is controlled by IPV6_V6ONLY socket // option and/or kernel state "net.inet6.ip6.v6only". // It returns two boolean values. If the first boolean value is // true, kernel supports basic IPv6 functionality. If the second // boolean value is true, kernel supports IPv6 IPv4-mapping. func probeIPv6Stack() (supportsIPv6, supportsIPv4map bool) { var probes = []struct { laddr TCPAddr value int }{ // IPv6 communication capability {laddr: TCPAddr{IP: ParseIP("::1")}, value: 1}, // IPv4-mapped IPv6 address communication capability {laddr: TCPAddr{IP: IPv4(127, 0, 0, 1)}, value: 0}, } var supps [2]bool switch runtime.GOOS { case "dragonfly", "openbsd": // Some released versions of DragonFly BSD pretend to // accept IPV6_V6ONLY=0 successfully, but the state // still stays IPV6_V6ONLY=1. Eventually DragonFly BSD // stops pretending, but the transition period would // cause unpredictable behavior and we need to avoid // it. // // OpenBSD also doesn't support IPV6_V6ONLY=0 but it // never pretends to accept IPV6_V6OLY=0. It always // returns an error and we don't need to probe the // capability. probes = probes[:1] } for i := range probes { s, err := socketFunc(syscall.AF_INET6, syscall.SOCK_STREAM, syscall.IPPROTO_TCP) if err != nil { continue } defer closeFunc(s) syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, probes[i].value) sa, err := probes[i].laddr.sockaddr(syscall.AF_INET6) if err != nil { continue } if err := syscall.Bind(s, sa); err != nil { continue } supps[i] = true } return supps[0], supps[1] } // favoriteAddrFamily returns the appropriate address family to // the given net, laddr, raddr and mode. At first it figures // address family out from the net. If mode indicates "listen" // and laddr is a wildcard, it assumes that the user wants to // make a passive connection with a wildcard address family, both // AF_INET and AF_INET6, and a wildcard address like following: // // 1. A wild-wild listen, "tcp" + "" // If the platform supports both IPv6 and IPv6 IPv4-mapping // capabilities, or does not support IPv4, we assume that // the user wants to listen on both IPv4 and IPv6 wildcard // addresses over an AF_INET6 socket with IPV6_V6ONLY=0. // Otherwise we prefer an IPv4 wildcard address listen over // an AF_INET socket. // // 2. A wild-ipv4wild listen, "tcp" + "0.0.0.0" // Same as 1. // // 3. A wild-ipv6wild listen, "tcp" + "[::]" // Almost same as 1 but we prefer an IPv6 wildcard address // listen over an AF_INET6 socket with IPV6_V6ONLY=0 when // the platform supports IPv6 capability but not IPv6 IPv4- // mapping capability. // // 4. A ipv4-ipv4wild listen, "tcp4" + "" or "0.0.0.0" // We use an IPv4 (AF_INET) wildcard address listen. // // 5. A ipv6-ipv6wild listen, "tcp6" + "" or "[::]" // We use an IPv6 (AF_INET6, IPV6_V6ONLY=1) wildcard address // listen. // // Otherwise guess: if the addresses are IPv4 then returns AF_INET, // or else returns AF_INET6. It also returns a boolean value what // designates IPV6_V6ONLY option. // // Note that OpenBSD allows neither "net.inet6.ip6.v6only=1" change // nor IPPROTO_IPV6 level IPV6_V6ONLY socket option setting. func favoriteAddrFamily(net string, laddr, raddr sockaddr, mode string) (family int, ipv6only bool) { switch net[len(net)-1] { case '4': return syscall.AF_INET, false case '6': return syscall.AF_INET6, true } if mode == "listen" && (laddr == nil || laddr.isWildcard()) { if supportsIPv4map || !supportsIPv4 { return syscall.AF_INET6, false } if laddr == nil { return syscall.AF_INET, false } return laddr.family(), false } if (laddr == nil || laddr.family() == syscall.AF_INET) && (raddr == nil || raddr.family() == syscall.AF_INET) { return syscall.AF_INET, false } return syscall.AF_INET6, false } // Internet sockets (TCP, UDP, IP) func internetSocket(ctx context.Context, net string, laddr, raddr sockaddr, sotype, proto int, mode string) (fd *netFD, err error) { if (runtime.GOOS == "windows" || runtime.GOOS == "openbsd" || runtime.GOOS == "nacl") && mode == "dial" && raddr.isWildcard() { raddr = raddr.toLocal(net) } family, ipv6only := favoriteAddrFamily(net, laddr, raddr, mode) return socket(ctx, net, family, sotype, proto, ipv6only, laddr, raddr) } func ipToSockaddr(family int, ip IP, port int, zone string) (syscall.Sockaddr, error) { switch family { case syscall.AF_INET: if len(ip) == 0 { ip = IPv4zero } ip4 := ip.To4() if ip4 == nil { return nil, &AddrError{Err: "non-IPv4 address", Addr: ip.String()} } sa := &syscall.SockaddrInet4{Port: port} copy(sa.Addr[:], ip4) return sa, nil case syscall.AF_INET6: // In general, an IP wildcard address, which is either // "0.0.0.0" or "::", means the entire IP addressing // space. For some historical reason, it is used to // specify "any available address" on some operations // of IP node. // // When the IP node supports IPv4-mapped IPv6 address, // we allow an listener to listen to the wildcard // address of both IP addressing spaces by specifying // IPv6 wildcard address. if len(ip) == 0 || ip.Equal(IPv4zero) { ip = IPv6zero } // We accept any IPv6 address including IPv4-mapped // IPv6 address. ip6 := ip.To16() if ip6 == nil { return nil, &AddrError{Err: "non-IPv6 address", Addr: ip.String()} } sa := &syscall.SockaddrInet6{Port: port, ZoneId: uint32(zoneToInt(zone))} copy(sa.Addr[:], ip6) return sa, nil } return nil, &AddrError{Err: "invalid address family", Addr: ip.String()} }
itsimbal/gcc.cet
libgo/go/net/ipsock_posix.go
GO
gpl-2.0
6,580
// -*- Mode: C++; -*- // Package : omniORB // cs-UCS-4.cc Created on: 26/10/2000 // Author : Duncan Grisby (dpg1) // // Copyright (C) 2000 AT&T Laboratories Cambridge // // This file is part of the omniORB library // // The omniORB 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; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA // // // Description: // Native code set for Unicode / ISO 10646 UCS-4 #include <omniORB4/CORBA.h> #include <omniORB4/linkHacks.h> #include <codeSetUtil.h> OMNI_NAMESPACE_BEGIN(omni) #if (SIZEOF_WCHAR == 4) class NCS_W_UCS_4 : public omniCodeSet::NCS_W { public: virtual void marshalWChar(cdrStream& stream, omniCodeSet::TCS_W* tcs, _CORBA_WChar c); virtual void marshalWString(cdrStream& stream, omniCodeSet::TCS_W* tcs, _CORBA_ULong bound, _CORBA_ULong len, const _CORBA_WChar* s); virtual _CORBA_WChar unmarshalWChar(cdrStream& stream, omniCodeSet::TCS_W* tcs); virtual _CORBA_ULong unmarshalWString(cdrStream& stream, omniCodeSet::TCS_W* tcs, _CORBA_ULong bound, _CORBA_WChar*& s); NCS_W_UCS_4() : omniCodeSet::NCS_W(omniCodeSet::ID_UCS_4, "UCS-4", omniCodeSet::CS_Other) { } virtual ~NCS_W_UCS_4() {} }; class TCS_W_UCS_4 : public omniCodeSet::TCS_W { public: virtual void marshalWChar (cdrStream& stream, omniCodeSet::UniChar uc); virtual void marshalWString(cdrStream& stream, _CORBA_ULong bound, _CORBA_ULong len, const omniCodeSet::UniChar* us); virtual omniCodeSet::UniChar unmarshalWChar(cdrStream& stream); virtual _CORBA_ULong unmarshalWString(cdrStream& stream, _CORBA_ULong bound, omniCodeSet::UniChar*& us); // Fast marshalling functions. Return false if no fast case is // possible and Unicode functions should be used. virtual _CORBA_Boolean fastMarshalWChar (cdrStream& stream, omniCodeSet::NCS_W* ncs, _CORBA_WChar c); virtual _CORBA_Boolean fastMarshalWString (cdrStream& stream, omniCodeSet::NCS_W* ncs, _CORBA_ULong bound, _CORBA_ULong len, const _CORBA_WChar* s); virtual _CORBA_Boolean fastUnmarshalWChar (cdrStream& stream, omniCodeSet::NCS_W* ncs, _CORBA_WChar& c); virtual _CORBA_Boolean fastUnmarshalWString(cdrStream& stream, omniCodeSet::NCS_W* ncs, _CORBA_ULong bound, _CORBA_ULong& length, _CORBA_WChar*& s); TCS_W_UCS_4() : omniCodeSet::TCS_W(omniCodeSet::ID_UCS_4, "UCS-4", omniCodeSet::CS_Other, omniCodeSetUtil::GIOP12) { } virtual ~TCS_W_UCS_4() {} }; void NCS_W_UCS_4::marshalWChar(cdrStream& stream, omniCodeSet::TCS_W* tcs, _CORBA_WChar wc) { OMNIORB_CHECK_TCS_W_FOR_MARSHAL(tcs, stream); if (tcs->fastMarshalWChar(stream, this, wc)) return; if (wc > 0xffff) OMNIORB_THROW(BAD_PARAM, BAD_PARAM_WCharOutOfRange, (CORBA::CompletionStatus)stream.completion()); tcs->marshalWChar(stream, wc); } void NCS_W_UCS_4::marshalWString(cdrStream& stream, omniCodeSet::TCS_W* tcs, _CORBA_ULong bound, _CORBA_ULong len, const _CORBA_WChar* ws) { OMNIORB_CHECK_TCS_W_FOR_MARSHAL(tcs, stream); if (tcs->fastMarshalWString(stream, this, bound, len, ws)) return; if (bound && len > bound) OMNIORB_THROW(MARSHAL, MARSHAL_WStringIsTooLong, (CORBA::CompletionStatus)stream.completion()); omniCodeSetUtil::BufferU ub(len+1); _CORBA_WChar wc; for (_CORBA_ULong i=0; i<=len; i++) { wc = ws[i]; if (wc <= 0xffff) { ub.insert(wc); } else if (wc <= 0x10ffff) { // Surrogate pair wc -= 0x10000; ub.insert((wc >> 10) + 0xd800); ub.insert((wc & 0x3ff) + 0xdc00); } else OMNIORB_THROW(DATA_CONVERSION, DATA_CONVERSION_CannotMapChar, (CORBA::CompletionStatus)stream.completion()); } tcs->marshalWString(stream, bound, len, ub.extract()); } _CORBA_WChar NCS_W_UCS_4::unmarshalWChar(cdrStream& stream, omniCodeSet::TCS_W* tcs) { OMNIORB_CHECK_TCS_W_FOR_UNMARSHAL(tcs, stream); _CORBA_WChar wc; if (tcs->fastUnmarshalWChar(stream, this, wc)) return wc; return tcs->unmarshalWChar(stream); } _CORBA_ULong NCS_W_UCS_4::unmarshalWString(cdrStream& stream, omniCodeSet::TCS_W* tcs, _CORBA_ULong bound, _CORBA_WChar*& ws) { OMNIORB_CHECK_TCS_W_FOR_UNMARSHAL(tcs, stream); _CORBA_ULong len; if (tcs->fastUnmarshalWString(stream, this, bound, len, ws)) return len; omniCodeSet::UniChar* us; len = tcs->unmarshalWString(stream, bound, us); OMNIORB_ASSERT(us); omniCodeSetUtil::HolderU uh(us); omniCodeSetUtil::BufferW wb(len); omniCodeSet::UniChar uc; _CORBA_WChar wc; for (_CORBA_ULong i=0; i<=len; i++) { uc = us[i]; if (uc < 0xd800) { wb.insert(uc); } else if (uc < 0xdc00) { // Surrogate pair wc = (uc - 0xd800) << 10; if (++i == len) { // No second half to surrogate pair OMNIORB_THROW(DATA_CONVERSION, DATA_CONVERSION_BadInput, (CORBA::CompletionStatus)stream.completion()); } uc = us[i]; if (uc < 0xdc00 || uc > 0xdfff) { // Value is not a valid second half to a surrogate pair OMNIORB_THROW(DATA_CONVERSION, DATA_CONVERSION_BadInput, (CORBA::CompletionStatus)stream.completion()); } wc = wc + uc - 0xdc00 + 0x10000; wb.insert(wc); } else if (uc < 0xe000) { // Second half of surrogate pair not allowed on its own OMNIORB_THROW(DATA_CONVERSION, DATA_CONVERSION_BadInput, (CORBA::CompletionStatus)stream.completion()); } else { wb.insert(uc); } } OMNIORB_ASSERT(uc == 0); // Last char must be zero ws = wb.extract(); return wb.length() - 1; } // // Transmission code set // void TCS_W_UCS_4::marshalWChar(cdrStream& stream, omniCodeSet::UniChar uc) { // In GIOP 1.2, wchar is encoded as an octet containing a length, // followed by that number of octets representing the wchar. The // CORBA 2.3 spec is silent on endianness issues, and whether there // should be any padding. The 2.4 spec says that if TCS-W is UTF-16, // the wchar is marshalled big-endian, unless there is a Unicode // byte order mark telling us otherwise. That doesn't help us here, // since we're not transmitting UTF-16. We assume here that there is // no padding, and we use the stream's endianness. stream.declareArrayLength(omni::ALIGN_1, 5); stream.marshalOctet(4); _CORBA_ULong tc = uc; _CORBA_Octet* p = (_CORBA_Octet*)&tc; _CORBA_Octet o; if (0xd800 <= uc && uc <= 0xe000 ) { // Part of a surrogate pair -- can't be sent OMNIORB_THROW(DATA_CONVERSION, DATA_CONVERSION_BadInput, (CORBA::CompletionStatus)stream.completion()); } if (stream.marshal_byte_swap()) { o = p[3]; stream.marshalOctet(o); o = p[2]; stream.marshalOctet(o); o = p[1]; stream.marshalOctet(o); o = p[0]; stream.marshalOctet(o); } else { o = p[0]; stream.marshalOctet(o); o = p[1]; stream.marshalOctet(o); o = p[2]; stream.marshalOctet(o); o = p[3]; stream.marshalOctet(o); } } void TCS_W_UCS_4::marshalWString(cdrStream& stream, _CORBA_ULong bound, _CORBA_ULong len, const omniCodeSet::UniChar* us) { // Just to be different, wstring is marshalled without a terminating // null. Length is in octets. _CORBA_ULong mlen = len * 4; stream.declareArrayLength(omni::ALIGN_4, mlen + 4); mlen >>= stream; _CORBA_ULong tc; omniCodeSet::UniChar uc; for (_CORBA_ULong i=0; i < len; i++) { uc = us[i]; if (uc < 0xd800) { tc = uc; } else if (uc < 0xdc00) { // Surrogate pair tc = (uc - 0xd800) << 10; if (++i == len) { // No second half to surrogate pair OMNIORB_THROW(DATA_CONVERSION, DATA_CONVERSION_BadInput, (CORBA::CompletionStatus)stream.completion()); } uc = us[i]; if (uc < 0xdc00 || uc > 0xdfff) { // Value is not a valid second half to a surrogate pair OMNIORB_THROW(DATA_CONVERSION, DATA_CONVERSION_BadInput, (CORBA::CompletionStatus)stream.completion()); } tc = tc + uc - 0xdc00 + 0x10000; } else if (uc < 0xe000) { // Second half of surrogate pair not allowed on its own OMNIORB_THROW(DATA_CONVERSION, DATA_CONVERSION_BadInput, (CORBA::CompletionStatus)stream.completion()); tc = 0; // To shut paranoid compilers up } else { tc = uc; } tc >>= stream; } } omniCodeSet::UniChar TCS_W_UCS_4::unmarshalWChar(cdrStream& stream) { omniCodeSet::UniChar uc; _CORBA_Octet len = stream.unmarshalOctet(); _CORBA_Octet o; switch (len) { case 0: uc = 0; // Evil but it might happen, I suppose break; case 1: o = stream.unmarshalOctet(); uc = o; break; case 2: { _CORBA_Octet* p = (_CORBA_Octet*)&uc; if (stream.unmarshal_byte_swap()) { o = stream.unmarshalOctet(); p[1] = o; o = stream.unmarshalOctet(); p[0] = o; } else { o = stream.unmarshalOctet(); p[0] = o; o = stream.unmarshalOctet(); p[1] = o; } } break; case 4: { _CORBA_ULong tc; _CORBA_Octet* p = (_CORBA_Octet*)&tc; if (stream.unmarshal_byte_swap()) { o = stream.unmarshalOctet(); p[3] = o; o = stream.unmarshalOctet(); p[2] = o; o = stream.unmarshalOctet(); p[1] = o; o = stream.unmarshalOctet(); p[0] = o; } else { o = stream.unmarshalOctet(); p[0] = o; o = stream.unmarshalOctet(); p[1] = o; o = stream.unmarshalOctet(); p[2] = o; o = stream.unmarshalOctet(); p[3] = o; } if (tc > 0xffff) OMNIORB_THROW(DATA_CONVERSION, DATA_CONVERSION_CannotMapChar, (CORBA::CompletionStatus)stream.completion()); uc = tc; } break; default: OMNIORB_THROW(MARSHAL, MARSHAL_InvalidWCharSize, (CORBA::CompletionStatus)stream.completion()); } return uc; } _CORBA_ULong TCS_W_UCS_4::unmarshalWString(cdrStream& stream, _CORBA_ULong bound, omniCodeSet::UniChar*& us) { _CORBA_ULong mlen; mlen <<= stream; if (mlen % 4) OMNIORB_THROW(MARSHAL, MARSHAL_InvalidWCharSize, (CORBA::CompletionStatus)stream.completion()); _CORBA_ULong len = mlen / 4; // Note no terminating null in marshalled form if (bound && len > bound) OMNIORB_THROW(MARSHAL, MARSHAL_WStringIsTooLong, (CORBA::CompletionStatus)stream.completion()); if (!stream.checkInputOverrun(1, mlen)) OMNIORB_THROW(MARSHAL, MARSHAL_PassEndOfMessage, (CORBA::CompletionStatus)stream.completion()); omniCodeSetUtil::BufferU ub(len + 1); _CORBA_ULong tc; _CORBA_ULong i; for (i=0; i < len; i++) { tc <<= stream; if (tc <= 0xffff) { ub.insert(tc); } else if (tc <= 0x10ffff) { // Surrogate pair tc -= 0x10000; ub.insert((tc >> 10) + 0xd800); ub.insert((tc & 0x3ff) + 0xdc00); } else OMNIORB_THROW(DATA_CONVERSION, DATA_CONVERSION_CannotMapChar, (CORBA::CompletionStatus)stream.completion()); } ub.insert(0); // Null terminator us = ub.extract(); return ub.length() - 1; } _CORBA_Boolean TCS_W_UCS_4::fastMarshalWChar(cdrStream& stream, omniCodeSet::NCS_W* ncs, _CORBA_WChar wc) { if (ncs->id() == id()) { // Null transformation stream.declareArrayLength(omni::ALIGN_1, 5); stream.marshalOctet(4); _CORBA_Octet* p = (_CORBA_Octet*)&wc; _CORBA_Octet o; if (stream.marshal_byte_swap()) { o = p[3]; stream.marshalOctet(o); o = p[2]; stream.marshalOctet(o); o = p[1]; stream.marshalOctet(o); o = p[0]; stream.marshalOctet(o); } else { o = p[0]; stream.marshalOctet(o); o = p[1]; stream.marshalOctet(o); o = p[2]; stream.marshalOctet(o); o = p[3]; stream.marshalOctet(o); } return 1; } return 0; } _CORBA_Boolean TCS_W_UCS_4::fastMarshalWString(cdrStream& stream, omniCodeSet::NCS_W* ncs, _CORBA_ULong bound, _CORBA_ULong len, const _CORBA_WChar* ws) { if (ncs->id() == id()) { // Null transformation if (bound && len > bound) OMNIORB_THROW(MARSHAL, MARSHAL_WStringIsTooLong, (CORBA::CompletionStatus)stream.completion()); _CORBA_ULong mlen = len * 4; mlen >>= stream; if (stream.marshal_byte_swap()) { stream.declareArrayLength(omni::ALIGN_4, mlen); _CORBA_ULong tc; for (_CORBA_ULong i=0; i<len; i++) { tc = ws[i]; tc >>= stream; } } else { stream.put_octet_array((const _CORBA_Char*)ws, mlen, omni::ALIGN_4); } return 1; } return 0; } _CORBA_Boolean TCS_W_UCS_4::fastUnmarshalWChar(cdrStream& stream, omniCodeSet::NCS_W* ncs, _CORBA_WChar& wc) { if (ncs->id() == id()) { // Null transformation _CORBA_Octet len = stream.unmarshalOctet(); _CORBA_Octet o; switch (len) { case 0: wc = 0; // Evil but it might happen, I suppose break; case 1: o = stream.unmarshalOctet(); wc = o; break; case 2: { _CORBA_UShort tc; _CORBA_Octet* p = (_CORBA_Octet*)&tc; if (stream.unmarshal_byte_swap()) { o = stream.unmarshalOctet(); p[1] = o; o = stream.unmarshalOctet(); p[0] = o; } else { o = stream.unmarshalOctet(); p[0] = o; o = stream.unmarshalOctet(); p[1] = o; } wc = tc; } break; case 4: { _CORBA_Octet* p = (_CORBA_Octet*)&wc; if (stream.unmarshal_byte_swap()) { o = stream.unmarshalOctet(); p[3] = o; o = stream.unmarshalOctet(); p[2] = o; o = stream.unmarshalOctet(); p[1] = o; o = stream.unmarshalOctet(); p[0] = o; } else { o = stream.unmarshalOctet(); p[0] = o; o = stream.unmarshalOctet(); p[1] = o; o = stream.unmarshalOctet(); p[2] = o; o = stream.unmarshalOctet(); p[3] = o; } } break; default: OMNIORB_THROW(MARSHAL, MARSHAL_InvalidWCharSize, (CORBA::CompletionStatus)stream.completion()); } return 1; } return 0; } _CORBA_Boolean TCS_W_UCS_4::fastUnmarshalWString(cdrStream& stream, omniCodeSet::NCS_W* ncs, _CORBA_ULong bound, _CORBA_ULong& len, _CORBA_WChar*& ws) { if (ncs->id() == id()) { // Null transformation _CORBA_ULong mlen; mlen <<= stream; if (mlen % 4) OMNIORB_THROW(MARSHAL, MARSHAL_InvalidWCharSize, (CORBA::CompletionStatus)stream.completion()); len = mlen / 4; // Note no terminating null in marshalled form if (bound && len > bound) OMNIORB_THROW(MARSHAL, MARSHAL_WStringIsTooLong, (CORBA::CompletionStatus)stream.completion()); if (!stream.checkInputOverrun(1, mlen)) OMNIORB_THROW(MARSHAL, MARSHAL_PassEndOfMessage, (CORBA::CompletionStatus)stream.completion()); ws = omniCodeSetUtil::allocW(len + 1); omniCodeSetUtil::HolderW wh(ws); stream.unmarshalArrayULong((_CORBA_ULong*)ws, len); ws[len] = 0; // Null terminator wh.drop(); return 1; } return 0; } // // Initialiser // static NCS_W_UCS_4 _NCS_W_UCS_4; static TCS_W_UCS_4 _TCS_W_UCS_4; class CS_UCS_4_init { public: CS_UCS_4_init() { omniCodeSet::registerNCS_W(&_NCS_W_UCS_4); omniCodeSet::registerTCS_W(&_TCS_W_UCS_4); } }; static CS_UCS_4_init _CS_UCS_4_init; #endif // (SIZEOF_WCHAR == 4) OMNI_NAMESPACE_END(omni) OMNI_EXPORT_LINK_FORCE_SYMBOL(CS_UCS_4);
yeewang/omniORB
src/lib/omniORB/codesets/cs-UCS-4.cc
C++
gpl-2.0
16,387
// ********************************************************************** // // Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** package test.Ice.hold; import test.Ice.hold.Test._HoldDisp; public final class HoldI extends _HoldDisp { private static void test(boolean b) { if(!b) { throw new RuntimeException(); } } HoldI(java.util.Timer timer, Ice.ObjectAdapter adapter) { _timer = timer; _adapter = adapter; _last = 0; } @Override public void putOnHold(int milliSeconds, Ice.Current current) { if(milliSeconds < 0) { _adapter.hold(); } else if(milliSeconds == 0) { _adapter.hold(); _adapter.activate(); } else { _timer.schedule(new java.util.TimerTask() { @Override public void run() { try { putOnHold(0, null); } catch(Ice.ObjectAdapterDeactivatedException ex) { } } }, milliSeconds); } } @Override public void waitForHold(final Ice.Current current) { _timer.schedule(new java.util.TimerTask() { @Override public void run() { try { current.adapter.waitForHold(); current.adapter.activate(); } catch(Ice.ObjectAdapterDeactivatedException ex) { // // This shouldn't occur. The test ensures all the // waitForHold timers are // finished before shutting down the communicator. // test(false); } } }, 0); } @Override public int set(int value, int delay, Ice.Current current) { try { Thread.sleep(delay); } catch(java.lang.InterruptedException ex) { } synchronized(this) { int tmp = _last; _last = value; return tmp; } } @Override synchronized public void setOneway(int value, int expected, Ice.Current current) { test(_last == expected); _last = value; } @Override public void shutdown(Ice.Current current) { _adapter.hold(); _adapter.getCommunicator().shutdown(); } final private java.util.Timer _timer; final private Ice.ObjectAdapter _adapter; int _last = 0; }
elijah513/ice
java/test/src/main/java/test/Ice/hold/HoldI.java
Java
gpl-2.0
3,018
/* * Copyright 2013 Dolphin Emulator Project * Licensed under GPLv2+ * Refer to the license.txt file included. */ package org.dolphinemu.dolphinemu.overlay; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.Display; import android.view.MotionEvent; import android.view.SurfaceView; import android.view.View; import android.view.View.OnTouchListener; import android.widget.Toast; import org.dolphinemu.dolphinemu.NativeLibrary; import org.dolphinemu.dolphinemu.NativeLibrary.ButtonState; import org.dolphinemu.dolphinemu.NativeLibrary.ButtonType; import org.dolphinemu.dolphinemu.R; import org.dolphinemu.dolphinemu.features.settings.model.BooleanSetting; import org.dolphinemu.dolphinemu.features.settings.model.IntSetting; import org.dolphinemu.dolphinemu.features.settings.model.Settings; import org.dolphinemu.dolphinemu.features.settings.utils.SettingsFile; import org.dolphinemu.dolphinemu.utils.IniFile; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; /** * Draws the interactive input overlay on top of the * {@link SurfaceView} that is rendering emulation. */ public final class InputOverlay extends SurfaceView implements OnTouchListener { public static final int OVERLAY_GAMECUBE = 0; public static final int OVERLAY_WIIMOTE = 1; public static final int OVERLAY_WIIMOTE_SIDEWAYS = 2; public static final int OVERLAY_WIIMOTE_NUNCHUK = 3; public static final int OVERLAY_WIIMOTE_CLASSIC = 4; public static final int OVERLAY_NONE = 5; private static final int DISABLED_GAMECUBE_CONTROLLER = 0; private static final int EMULATED_GAMECUBE_CONTROLLER = 6; private static final int GAMECUBE_ADAPTER = 12; private final Set<InputOverlayDrawableButton> overlayButtons = new HashSet<>(); private final Set<InputOverlayDrawableDpad> overlayDpads = new HashSet<>(); private final Set<InputOverlayDrawableJoystick> overlayJoysticks = new HashSet<>(); private InputOverlayPointer overlayPointer = null; private Rect mSurfacePosition = null; private boolean mIsFirstRun = true; private boolean mIsInEditMode = false; private InputOverlayDrawableButton mButtonBeingConfigured; private InputOverlayDrawableDpad mDpadBeingConfigured; private InputOverlayDrawableJoystick mJoystickBeingConfigured; private final SharedPreferences mPreferences; // Buttons that have special positions in Wiimote only private static final ArrayList<Integer> WIIMOTE_H_BUTTONS = new ArrayList<>(); static { WIIMOTE_H_BUTTONS.add(ButtonType.WIIMOTE_BUTTON_A); WIIMOTE_H_BUTTONS.add(ButtonType.WIIMOTE_BUTTON_B); WIIMOTE_H_BUTTONS.add(ButtonType.WIIMOTE_BUTTON_1); WIIMOTE_H_BUTTONS.add(ButtonType.WIIMOTE_BUTTON_2); } private static final ArrayList<Integer> WIIMOTE_O_BUTTONS = new ArrayList<>(); static { WIIMOTE_O_BUTTONS.add(ButtonType.WIIMOTE_UP); } /** * Resizes a {@link Bitmap} by a given scale factor * * @param context The current {@link Context} * @param bitmap The {@link Bitmap} to scale. * @param scale The scale factor for the bitmap. * @return The scaled {@link Bitmap} */ public static Bitmap resizeBitmap(Context context, Bitmap bitmap, float scale) { // Determine the button size based on the smaller screen dimension. // This makes sure the buttons are the same size in both portrait and landscape. DisplayMetrics dm = context.getResources().getDisplayMetrics(); int minDimension = Math.min(dm.widthPixels, dm.heightPixels); return Bitmap.createScaledBitmap(bitmap, (int) (minDimension * scale), (int) (minDimension * scale), true); } /** * Constructor * * @param context The current {@link Context}. * @param attrs {@link AttributeSet} for parsing XML attributes. */ public InputOverlay(Context context, AttributeSet attrs) { super(context, attrs); mPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); if (!mPreferences.getBoolean("OverlayInitV3", false)) defaultOverlay(); // Load the controls if we can. If not, EmulationActivity has to do it later. if (NativeLibrary.IsGameMetadataValid()) refreshControls(); // Set the on touch listener. setOnTouchListener(this); // Force draw setWillNotDraw(false); // Request focus for the overlay so it has priority on presses. requestFocus(); } public void setSurfacePosition(Rect rect) { mSurfacePosition = rect; initTouchPointer(); } public void initTouchPointer() { // Check if we have all the data we need yet boolean aspectRatioAvailable = NativeLibrary.IsRunningAndStarted(); if (!aspectRatioAvailable || mSurfacePosition == null) return; // Check if there's any point in running the pointer code if (!NativeLibrary.IsEmulatingWii()) return; int doubleTapButton = IntSetting.MAIN_DOUBLE_TAP_BUTTON.getIntGlobal(); if (mPreferences.getInt("wiiController", OVERLAY_WIIMOTE_NUNCHUK) != InputOverlay.OVERLAY_WIIMOTE_CLASSIC && doubleTapButton == InputOverlayPointer.DOUBLE_TAP_CLASSIC_A) { doubleTapButton = InputOverlayPointer.DOUBLE_TAP_A; } overlayPointer = new InputOverlayPointer(mSurfacePosition, doubleTapButton); } @Override public void draw(Canvas canvas) { super.draw(canvas); for (InputOverlayDrawableButton button : overlayButtons) { button.draw(canvas); } for (InputOverlayDrawableDpad dpad : overlayDpads) { dpad.draw(canvas); } for (InputOverlayDrawableJoystick joystick : overlayJoysticks) { joystick.draw(canvas); } } @Override public boolean onTouch(View v, MotionEvent event) { if (isInEditMode()) { return onTouchWhileEditing(event); } int pointerIndex = event.getActionIndex(); // Tracks if any button/joystick is pressed down boolean pressed = false; for (InputOverlayDrawableButton button : overlayButtons) { // Determine the button state to apply based on the MotionEvent action flag. switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: // If a pointer enters the bounds of a button, press that button. if (button.getBounds() .contains((int) event.getX(pointerIndex), (int) event.getY(pointerIndex))) { button.setPressedState(true); button.setTrackId(event.getPointerId(pointerIndex)); pressed = true; NativeLibrary.onGamePadEvent(NativeLibrary.TouchScreenDevice, button.getId(), ButtonState.PRESSED); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: // If a pointer ends, release the button it was pressing. if (button.getTrackId() == event.getPointerId(pointerIndex)) { button.setPressedState(false); NativeLibrary.onGamePadEvent(NativeLibrary.TouchScreenDevice, button.getId(), ButtonState.RELEASED); button.setTrackId(-1); } break; } } for (InputOverlayDrawableDpad dpad : overlayDpads) { // Determine the button state to apply based on the MotionEvent action flag. switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: // If a pointer enters the bounds of a button, press that button. if (dpad.getBounds() .contains((int) event.getX(pointerIndex), (int) event.getY(pointerIndex))) { dpad.setTrackId(event.getPointerId(pointerIndex)); pressed = true; } case MotionEvent.ACTION_MOVE: if (dpad.getTrackId() == event.getPointerId(pointerIndex)) { // Up, Down, Left, Right boolean[] dpadPressed = {false, false, false, false}; if (dpad.getBounds().top + (dpad.getHeight() / 3) > (int) event.getY(pointerIndex)) dpadPressed[0] = true; if (dpad.getBounds().bottom - (dpad.getHeight() / 3) < (int) event.getY(pointerIndex)) dpadPressed[1] = true; if (dpad.getBounds().left + (dpad.getWidth() / 3) > (int) event.getX(pointerIndex)) dpadPressed[2] = true; if (dpad.getBounds().right - (dpad.getWidth() / 3) < (int) event.getX(pointerIndex)) dpadPressed[3] = true; // Release the buttons first, then press for (int i = 0; i < dpadPressed.length; i++) { if (!dpadPressed[i]) { NativeLibrary.onGamePadEvent(NativeLibrary.TouchScreenDevice, dpad.getId(i), ButtonState.RELEASED); } } // Press buttons for (int i = 0; i < dpadPressed.length; i++) { if (dpadPressed[i]) { NativeLibrary.onGamePadEvent(NativeLibrary.TouchScreenDevice, dpad.getId(i), ButtonState.PRESSED); } } setDpadState(dpad, dpadPressed[0], dpadPressed[1], dpadPressed[2], dpadPressed[3]); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: // If a pointer ends, release the buttons. if (dpad.getTrackId() == event.getPointerId(pointerIndex)) { for (int i = 0; i < 4; i++) { dpad.setState(InputOverlayDrawableDpad.STATE_DEFAULT); NativeLibrary.onGamePadEvent(NativeLibrary.TouchScreenDevice, dpad.getId(i), ButtonState.RELEASED); } dpad.setTrackId(-1); } break; } } for (InputOverlayDrawableJoystick joystick : overlayJoysticks) { if (joystick.TrackEvent(event)) { if (joystick.getTrackId() != -1) pressed = true; } int[] axisIDs = joystick.getAxisIDs(); float[] axises = joystick.getAxisValues(); for (int i = 0; i < 4; i++) { NativeLibrary.onGamePadMoveEvent(NativeLibrary.TouchScreenDevice, axisIDs[i], axises[i]); } } // No button/joystick pressed, safe to move pointer if (!pressed && overlayPointer != null) { overlayPointer.onTouch(event); float[] axes = overlayPointer.getAxisValues(); for (int i = 0; i < 4; i++) { NativeLibrary .onGamePadMoveEvent(NativeLibrary.TouchScreenDevice, ButtonType.WIIMOTE_IR_UP + i, axes[i]); } } invalidate(); return true; } public boolean onTouchWhileEditing(MotionEvent event) { int pointerIndex = event.getActionIndex(); int fingerPositionX = (int) event.getX(pointerIndex); int fingerPositionY = (int) event.getY(pointerIndex); final SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); int controller = sPrefs.getInt("wiiController", 3); String orientation = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? "-Portrait" : ""; // Maybe combine Button and Joystick as subclasses of the same parent? // Or maybe create an interface like IMoveableHUDControl? for (InputOverlayDrawableButton button : overlayButtons) { // Determine the button state to apply based on the MotionEvent action flag. switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: // If no button is being moved now, remember the currently touched button to move. if (mButtonBeingConfigured == null && button.getBounds().contains(fingerPositionX, fingerPositionY)) { mButtonBeingConfigured = button; mButtonBeingConfigured.onConfigureTouch(event); } break; case MotionEvent.ACTION_MOVE: if (mButtonBeingConfigured != null) { mButtonBeingConfigured.onConfigureTouch(event); invalidate(); return true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: if (mButtonBeingConfigured == button) { // Persist button position by saving new place. saveControlPosition(mButtonBeingConfigured.getId(), mButtonBeingConfigured.getBounds().left, mButtonBeingConfigured.getBounds().top, controller, orientation); mButtonBeingConfigured = null; } break; } } for (InputOverlayDrawableDpad dpad : overlayDpads) { // Determine the button state to apply based on the MotionEvent action flag. switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: // If no button is being moved now, remember the currently touched button to move. if (mButtonBeingConfigured == null && dpad.getBounds().contains(fingerPositionX, fingerPositionY)) { mDpadBeingConfigured = dpad; mDpadBeingConfigured.onConfigureTouch(event); } break; case MotionEvent.ACTION_MOVE: if (mDpadBeingConfigured != null) { mDpadBeingConfigured.onConfigureTouch(event); invalidate(); return true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: if (mDpadBeingConfigured == dpad) { // Persist button position by saving new place. saveControlPosition(mDpadBeingConfigured.getId(0), mDpadBeingConfigured.getBounds().left, mDpadBeingConfigured.getBounds().top, controller, orientation); mDpadBeingConfigured = null; } break; } } for (InputOverlayDrawableJoystick joystick : overlayJoysticks) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: if (mJoystickBeingConfigured == null && joystick.getBounds().contains(fingerPositionX, fingerPositionY)) { mJoystickBeingConfigured = joystick; mJoystickBeingConfigured.onConfigureTouch(event); } break; case MotionEvent.ACTION_MOVE: if (mJoystickBeingConfigured != null) { mJoystickBeingConfigured.onConfigureTouch(event); invalidate(); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: if (mJoystickBeingConfigured != null) { saveControlPosition(mJoystickBeingConfigured.getId(), mJoystickBeingConfigured.getBounds().left, mJoystickBeingConfigured.getBounds().top, controller, orientation); mJoystickBeingConfigured = null; } break; } } return true; } private void setDpadState(InputOverlayDrawableDpad dpad, boolean up, boolean down, boolean left, boolean right) { if (up) { if (left) dpad.setState(InputOverlayDrawableDpad.STATE_PRESSED_UP_LEFT); else if (right) dpad.setState(InputOverlayDrawableDpad.STATE_PRESSED_UP_RIGHT); else dpad.setState(InputOverlayDrawableDpad.STATE_PRESSED_UP); } else if (down) { if (left) dpad.setState(InputOverlayDrawableDpad.STATE_PRESSED_DOWN_LEFT); else if (right) dpad.setState(InputOverlayDrawableDpad.STATE_PRESSED_DOWN_RIGHT); else dpad.setState(InputOverlayDrawableDpad.STATE_PRESSED_DOWN); } else if (left) { dpad.setState(InputOverlayDrawableDpad.STATE_PRESSED_LEFT); } else if (right) { dpad.setState(InputOverlayDrawableDpad.STATE_PRESSED_RIGHT); } } private void addGameCubeOverlayControls(String orientation) { if (BooleanSetting.MAIN_BUTTON_TOGGLE_GC_0.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.gcpad_a, R.drawable.gcpad_a_pressed, ButtonType.BUTTON_A, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_GC_1.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.gcpad_b, R.drawable.gcpad_b_pressed, ButtonType.BUTTON_B, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_GC_2.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.gcpad_x, R.drawable.gcpad_x_pressed, ButtonType.BUTTON_X, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_GC_3.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.gcpad_y, R.drawable.gcpad_y_pressed, ButtonType.BUTTON_Y, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_GC_4.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.gcpad_z, R.drawable.gcpad_z_pressed, ButtonType.BUTTON_Z, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_GC_5.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.gcpad_start, R.drawable.gcpad_start_pressed, ButtonType.BUTTON_START, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_GC_6.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.gcpad_l, R.drawable.gcpad_l_pressed, ButtonType.TRIGGER_L, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_GC_7.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.gcpad_r, R.drawable.gcpad_r_pressed, ButtonType.TRIGGER_R, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_GC_8.getBooleanGlobal()) { overlayDpads.add(initializeOverlayDpad(getContext(), R.drawable.gcwii_dpad, R.drawable.gcwii_dpad_pressed_one_direction, R.drawable.gcwii_dpad_pressed_two_directions, ButtonType.BUTTON_UP, ButtonType.BUTTON_DOWN, ButtonType.BUTTON_LEFT, ButtonType.BUTTON_RIGHT, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_GC_9.getBooleanGlobal()) { overlayJoysticks.add(initializeOverlayJoystick(getContext(), R.drawable.gcwii_joystick_range, R.drawable.gcwii_joystick, R.drawable.gcwii_joystick_pressed, ButtonType.STICK_MAIN, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_GC_10.getBooleanGlobal()) { overlayJoysticks.add(initializeOverlayJoystick(getContext(), R.drawable.gcwii_joystick_range, R.drawable.gcpad_c, R.drawable.gcpad_c_pressed, ButtonType.STICK_C, orientation)); } } private void addWiimoteOverlayControls(String orientation) { if (BooleanSetting.MAIN_BUTTON_TOGGLE_WII_0.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.wiimote_a, R.drawable.wiimote_a_pressed, ButtonType.WIIMOTE_BUTTON_A, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_WII_1.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.wiimote_b, R.drawable.wiimote_b_pressed, ButtonType.WIIMOTE_BUTTON_B, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_WII_2.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.wiimote_one, R.drawable.wiimote_one_pressed, ButtonType.WIIMOTE_BUTTON_1, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_WII_3.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.wiimote_two, R.drawable.wiimote_two_pressed, ButtonType.WIIMOTE_BUTTON_2, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_WII_4.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.wiimote_plus, R.drawable.wiimote_plus_pressed, ButtonType.WIIMOTE_BUTTON_PLUS, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_WII_5.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.wiimote_minus, R.drawable.wiimote_minus_pressed, ButtonType.WIIMOTE_BUTTON_MINUS, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_WII_6.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.wiimote_home, R.drawable.wiimote_home_pressed, ButtonType.WIIMOTE_BUTTON_HOME, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_WII_7.getBooleanGlobal()) { overlayDpads.add(initializeOverlayDpad(getContext(), R.drawable.gcwii_dpad, R.drawable.gcwii_dpad_pressed_one_direction, R.drawable.gcwii_dpad_pressed_two_directions, ButtonType.WIIMOTE_UP, ButtonType.WIIMOTE_DOWN, ButtonType.WIIMOTE_LEFT, ButtonType.WIIMOTE_RIGHT, orientation)); } } private void addNunchukOverlayControls(String orientation) { if (BooleanSetting.MAIN_BUTTON_TOGGLE_WII_8.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.nunchuk_c, R.drawable.nunchuk_c_pressed, ButtonType.NUNCHUK_BUTTON_C, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_WII_9.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.nunchuk_z, R.drawable.nunchuk_z_pressed, ButtonType.NUNCHUK_BUTTON_Z, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_WII_10.getBooleanGlobal()) { overlayJoysticks.add(initializeOverlayJoystick(getContext(), R.drawable.gcwii_joystick_range, R.drawable.gcwii_joystick, R.drawable.gcwii_joystick_pressed, ButtonType.NUNCHUK_STICK, orientation)); } } private void addClassicOverlayControls(String orientation) { if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_0.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.classic_a, R.drawable.classic_a_pressed, ButtonType.CLASSIC_BUTTON_A, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_1.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.classic_b, R.drawable.classic_b_pressed, ButtonType.CLASSIC_BUTTON_B, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_2.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.classic_x, R.drawable.classic_x_pressed, ButtonType.CLASSIC_BUTTON_X, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_3.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.classic_y, R.drawable.classic_y_pressed, ButtonType.CLASSIC_BUTTON_Y, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_4.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.wiimote_plus, R.drawable.wiimote_plus_pressed, ButtonType.CLASSIC_BUTTON_PLUS, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_5.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.wiimote_minus, R.drawable.wiimote_minus_pressed, ButtonType.CLASSIC_BUTTON_MINUS, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_6.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.wiimote_home, R.drawable.wiimote_home_pressed, ButtonType.CLASSIC_BUTTON_HOME, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_7.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.classic_l, R.drawable.classic_l_pressed, ButtonType.CLASSIC_TRIGGER_L, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_8.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.classic_r, R.drawable.classic_r_pressed, ButtonType.CLASSIC_TRIGGER_R, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_9.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.classic_zl, R.drawable.classic_zl_pressed, ButtonType.CLASSIC_BUTTON_ZL, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_10.getBooleanGlobal()) { overlayButtons.add(initializeOverlayButton(getContext(), R.drawable.classic_zr, R.drawable.classic_zr_pressed, ButtonType.CLASSIC_BUTTON_ZR, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_11.getBooleanGlobal()) { overlayDpads.add(initializeOverlayDpad(getContext(), R.drawable.gcwii_dpad, R.drawable.gcwii_dpad_pressed_one_direction, R.drawable.gcwii_dpad_pressed_two_directions, ButtonType.CLASSIC_DPAD_UP, ButtonType.CLASSIC_DPAD_DOWN, ButtonType.CLASSIC_DPAD_LEFT, ButtonType.CLASSIC_DPAD_RIGHT, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_12.getBooleanGlobal()) { overlayJoysticks.add(initializeOverlayJoystick(getContext(), R.drawable.gcwii_joystick_range, R.drawable.gcwii_joystick, R.drawable.gcwii_joystick_pressed, ButtonType.CLASSIC_STICK_LEFT, orientation)); } if (BooleanSetting.MAIN_BUTTON_TOGGLE_CLASSIC_13.getBooleanGlobal()) { overlayJoysticks.add(initializeOverlayJoystick(getContext(), R.drawable.gcwii_joystick_range, R.drawable.gcwii_joystick, R.drawable.gcwii_joystick_pressed, ButtonType.CLASSIC_STICK_RIGHT, orientation)); } } public void refreshControls() { // Remove all the overlay buttons from the HashSet. overlayButtons.removeAll(overlayButtons); overlayDpads.removeAll(overlayDpads); overlayJoysticks.removeAll(overlayJoysticks); String orientation = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? "-Portrait" : ""; if (BooleanSetting.MAIN_SHOW_INPUT_OVERLAY.getBooleanGlobal()) { // Add all the enabled overlay items back to the HashSet. if (!NativeLibrary.IsEmulatingWii()) { IniFile dolphinIni = new IniFile(SettingsFile.getSettingsFile(Settings.FILE_DOLPHIN)); switch (dolphinIni.getInt(Settings.SECTION_INI_CORE, SettingsFile.KEY_GCPAD_PLAYER_1, EMULATED_GAMECUBE_CONTROLLER)) { case DISABLED_GAMECUBE_CONTROLLER: if (mIsFirstRun) { Toast.makeText(getContext(), R.string.disabled_gc_overlay_notice, Toast.LENGTH_SHORT) .show(); } break; case EMULATED_GAMECUBE_CONTROLLER: addGameCubeOverlayControls(orientation); break; case GAMECUBE_ADAPTER: break; } } else { switch (mPreferences.getInt("wiiController", 3)) { case OVERLAY_GAMECUBE: addGameCubeOverlayControls(orientation); break; case OVERLAY_WIIMOTE: case OVERLAY_WIIMOTE_SIDEWAYS: addWiimoteOverlayControls(orientation); break; case OVERLAY_WIIMOTE_NUNCHUK: addWiimoteOverlayControls(orientation); addNunchukOverlayControls(orientation); break; case OVERLAY_WIIMOTE_CLASSIC: addClassicOverlayControls(orientation); break; case OVERLAY_NONE: break; } } } mIsFirstRun = false; invalidate(); } public void resetButtonPlacement() { boolean isLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; // Values for these come from R.array.controllersEntries if (!NativeLibrary.IsEmulatingWii() || mPreferences.getInt("wiiController", 3) == 0) { if (isLandscape) gcDefaultOverlay(); else gcPortraitDefaultOverlay(); } else if (mPreferences.getInt("wiiController", 3) == 4) { if (isLandscape) wiiClassicDefaultOverlay(); else wiiClassicPortraitDefaultOverlay(); } else { if (isLandscape) { wiiDefaultOverlay(); wiiOnlyDefaultOverlay(); } else { wiiPortraitDefaultOverlay(); wiiOnlyPortraitDefaultOverlay(); } } refreshControls(); } private void saveControlPosition(int sharedPrefsId, int x, int y, int controller, String orientation) { final SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); SharedPreferences.Editor sPrefsEditor = sPrefs.edit(); sPrefsEditor.putFloat(getXKey(sharedPrefsId, controller, orientation), x); sPrefsEditor.putFloat(getYKey(sharedPrefsId, controller, orientation), y); sPrefsEditor.apply(); } private static String getKey(int sharedPrefsId, int controller, String orientation, String suffix) { if (controller == 2 && WIIMOTE_H_BUTTONS.contains(sharedPrefsId)) { return sharedPrefsId + "_H" + orientation + suffix; } else if (controller == 1 && WIIMOTE_O_BUTTONS.contains(sharedPrefsId)) { return sharedPrefsId + "_O" + orientation + suffix; } else { return sharedPrefsId + orientation + suffix; } } private static String getXKey(int sharedPrefsId, int controller, String orientation) { return getKey(sharedPrefsId, controller, orientation, "-X"); } private static String getYKey(int sharedPrefsId, int controller, String orientation) { return getKey(sharedPrefsId, controller, orientation, "-Y"); } /** * Initializes an InputOverlayDrawableButton, given by resId, with all of the * parameters set for it to be properly shown on the InputOverlay. * <p> * This works due to the way the X and Y coordinates are stored within * the {@link SharedPreferences}. * <p> * In the input overlay configuration menu, * once a touch event begins and then ends (ie. Organizing the buttons to one's own liking for the overlay). * the X and Y coordinates of the button at the END of its touch event * (when you remove your finger/stylus from the touchscreen) are then stored * within a SharedPreferences instance so that those values can be retrieved here. * <p> * This has a few benefits over the conventional way of storing the values * (ie. within the Dolphin ini file). * <ul> * <li>No native calls</li> * <li>Keeps Android-only values inside the Android environment</li> * </ul> * <p> * Technically no modifications should need to be performed on the returned * InputOverlayDrawableButton. Simply add it to the HashSet of overlay items and wait * for Android to call the onDraw method. * * @param context The current {@link Context}. * @param defaultResId The resource ID of the {@link Drawable} to get the {@link Bitmap} of (Default State). * @param pressedResId The resource ID of the {@link Drawable} to get the {@link Bitmap} of (Pressed State). * @param buttonId Identifier for determining what type of button the initialized InputOverlayDrawableButton represents. * @return An {@link InputOverlayDrawableButton} with the correct drawing bounds set. */ private static InputOverlayDrawableButton initializeOverlayButton(Context context, int defaultResId, int pressedResId, int buttonId, String orientation) { // Resources handle for fetching the initial Drawable resource. final Resources res = context.getResources(); // SharedPreference to retrieve the X and Y coordinates for the InputOverlayDrawableButton. final SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(context); int controller = sPrefs.getInt("wiiController", 3); // Decide scale based on button ID and user preference float scale; switch (buttonId) { case ButtonType.BUTTON_A: case ButtonType.WIIMOTE_BUTTON_B: case ButtonType.NUNCHUK_BUTTON_Z: scale = 0.2f; break; case ButtonType.BUTTON_X: case ButtonType.BUTTON_Y: scale = 0.175f; break; case ButtonType.BUTTON_Z: case ButtonType.TRIGGER_L: case ButtonType.TRIGGER_R: scale = 0.225f; break; case ButtonType.BUTTON_START: scale = 0.075f; break; case ButtonType.WIIMOTE_BUTTON_1: case ButtonType.WIIMOTE_BUTTON_2: if (controller == 2) scale = 0.14f; else scale = 0.0875f; break; case ButtonType.WIIMOTE_BUTTON_PLUS: case ButtonType.WIIMOTE_BUTTON_MINUS: case ButtonType.WIIMOTE_BUTTON_HOME: case ButtonType.CLASSIC_BUTTON_PLUS: case ButtonType.CLASSIC_BUTTON_MINUS: case ButtonType.CLASSIC_BUTTON_HOME: scale = 0.0625f; break; case ButtonType.CLASSIC_TRIGGER_L: case ButtonType.CLASSIC_TRIGGER_R: case ButtonType.CLASSIC_BUTTON_ZL: case ButtonType.CLASSIC_BUTTON_ZR: scale = 0.25f; break; default: scale = 0.125f; break; } scale *= (IntSetting.MAIN_CONTROL_SCALE.getIntGlobal() + 50); scale /= 100; // Initialize the InputOverlayDrawableButton. final Bitmap defaultStateBitmap = resizeBitmap(context, BitmapFactory.decodeResource(res, defaultResId), scale); final Bitmap pressedStateBitmap = resizeBitmap(context, BitmapFactory.decodeResource(res, pressedResId), scale); final InputOverlayDrawableButton overlayDrawable = new InputOverlayDrawableButton(res, defaultStateBitmap, pressedStateBitmap, buttonId); // The X and Y coordinates of the InputOverlayDrawableButton on the InputOverlay. // These were set in the input overlay configuration menu. int drawableX = (int) sPrefs.getFloat(getXKey(buttonId, controller, orientation), 0f); int drawableY = (int) sPrefs.getFloat(getYKey(buttonId, controller, orientation), 0f); int width = overlayDrawable.getWidth(); int height = overlayDrawable.getHeight(); // Now set the bounds for the InputOverlayDrawableButton. // This will dictate where on the screen (and the what the size) the InputOverlayDrawableButton will be. overlayDrawable.setBounds(drawableX, drawableY, drawableX + width, drawableY + height); // Need to set the image's position overlayDrawable.setPosition(drawableX, drawableY); return overlayDrawable; } /** * Initializes an {@link InputOverlayDrawableDpad} * * @param context The current {@link Context}. * @param defaultResId The {@link Bitmap} resource ID of the default sate. * @param pressedOneDirectionResId The {@link Bitmap} resource ID of the pressed sate in one direction. * @param pressedTwoDirectionsResId The {@link Bitmap} resource ID of the pressed sate in two directions. * @param buttonUp Identifier for the up button. * @param buttonDown Identifier for the down button. * @param buttonLeft Identifier for the left button. * @param buttonRight Identifier for the right button. * @return the initialized {@link InputOverlayDrawableDpad} */ private static InputOverlayDrawableDpad initializeOverlayDpad(Context context, int defaultResId, int pressedOneDirectionResId, int pressedTwoDirectionsResId, int buttonUp, int buttonDown, int buttonLeft, int buttonRight, String orientation) { // Resources handle for fetching the initial Drawable resource. final Resources res = context.getResources(); // SharedPreference to retrieve the X and Y coordinates for the InputOverlayDrawableDpad. final SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(context); int controller = sPrefs.getInt("wiiController", 3); // Decide scale based on button ID and user preference float scale; switch (buttonUp) { case ButtonType.BUTTON_UP: scale = 0.2375f; break; case ButtonType.CLASSIC_DPAD_UP: scale = 0.275f; break; default: if (controller == 2 || controller == 1) scale = 0.275f; else scale = 0.2125f; break; } scale *= (IntSetting.MAIN_CONTROL_SCALE.getIntGlobal() + 50); scale /= 100; // Initialize the InputOverlayDrawableDpad. final Bitmap defaultStateBitmap = resizeBitmap(context, BitmapFactory.decodeResource(res, defaultResId), scale); final Bitmap pressedOneDirectionStateBitmap = resizeBitmap(context, BitmapFactory.decodeResource(res, pressedOneDirectionResId), scale); final Bitmap pressedTwoDirectionsStateBitmap = resizeBitmap(context, BitmapFactory.decodeResource(res, pressedTwoDirectionsResId), scale); final InputOverlayDrawableDpad overlayDrawable = new InputOverlayDrawableDpad(res, defaultStateBitmap, pressedOneDirectionStateBitmap, pressedTwoDirectionsStateBitmap, buttonUp, buttonDown, buttonLeft, buttonRight); // The X and Y coordinates of the InputOverlayDrawableDpad on the InputOverlay. // These were set in the input overlay configuration menu. int drawableX = (int) sPrefs.getFloat(getXKey(buttonUp, controller, orientation), 0f); int drawableY = (int) sPrefs.getFloat(getYKey(buttonUp, controller, orientation), 0f); int width = overlayDrawable.getWidth(); int height = overlayDrawable.getHeight(); // Now set the bounds for the InputOverlayDrawableDpad. // This will dictate where on the screen (and the what the size) the InputOverlayDrawableDpad will be. overlayDrawable.setBounds(drawableX, drawableY, drawableX + width, drawableY + height); // Need to set the image's position overlayDrawable.setPosition(drawableX, drawableY); return overlayDrawable; } /** * Initializes an {@link InputOverlayDrawableJoystick} * * @param context The current {@link Context} * @param resOuter Resource ID for the outer image of the joystick (the static image that shows the circular bounds). * @param defaultResInner Resource ID for the default inner image of the joystick (the one you actually move around). * @param pressedResInner Resource ID for the pressed inner image of the joystick. * @param joystick Identifier for which joystick this is. * @return the initialized {@link InputOverlayDrawableJoystick}. */ private static InputOverlayDrawableJoystick initializeOverlayJoystick(Context context, int resOuter, int defaultResInner, int pressedResInner, int joystick, String orientation) { // Resources handle for fetching the initial Drawable resource. final Resources res = context.getResources(); // SharedPreference to retrieve the X and Y coordinates for the InputOverlayDrawableJoystick. final SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(context); int controller = sPrefs.getInt("wiiController", 3); // Decide scale based on user preference float scale = 0.275f; scale *= (IntSetting.MAIN_CONTROL_SCALE.getIntGlobal() + 50); scale /= 100; // Initialize the InputOverlayDrawableJoystick. final Bitmap bitmapOuter = resizeBitmap(context, BitmapFactory.decodeResource(res, resOuter), scale); final Bitmap bitmapInnerDefault = BitmapFactory.decodeResource(res, defaultResInner); final Bitmap bitmapInnerPressed = BitmapFactory.decodeResource(res, pressedResInner); // The X and Y coordinates of the InputOverlayDrawableButton on the InputOverlay. // These were set in the input overlay configuration menu. int drawableX = (int) sPrefs.getFloat(getXKey(joystick, controller, orientation), 0f); int drawableY = (int) sPrefs.getFloat(getYKey(joystick, controller, orientation), 0f); // Decide inner scale based on joystick ID float innerScale; if (joystick == ButtonType.STICK_C) { innerScale = 1.833f; } else { innerScale = 1.375f; } // Now set the bounds for the InputOverlayDrawableJoystick. // This will dictate where on the screen (and the what the size) the InputOverlayDrawableJoystick will be. int outerSize = bitmapOuter.getWidth(); Rect outerRect = new Rect(drawableX, drawableY, drawableX + outerSize, drawableY + outerSize); Rect innerRect = new Rect(0, 0, (int) (outerSize / innerScale), (int) (outerSize / innerScale)); // Send the drawableId to the joystick so it can be referenced when saving control position. final InputOverlayDrawableJoystick overlayDrawable = new InputOverlayDrawableJoystick(res, bitmapOuter, bitmapInnerDefault, bitmapInnerPressed, outerRect, innerRect, joystick); // Need to set the image's position overlayDrawable.setPosition(drawableX, drawableY); return overlayDrawable; } public void setIsInEditMode(boolean isInEditMode) { mIsInEditMode = isInEditMode; } public boolean isInEditMode() { return mIsInEditMode; } private void defaultOverlay() { if (!mPreferences.getBoolean("OverlayInitV2", false)) { // It's possible that a user has created their overlay before this was added // Only change the overlay if the 'A' button is not in the upper corner. // GameCube if (mPreferences.getFloat(ButtonType.BUTTON_A + "-X", 0f) == 0f) { gcDefaultOverlay(); } if (mPreferences.getFloat(ButtonType.BUTTON_A + "-Portrait" + "-X", 0f) == 0f) { gcPortraitDefaultOverlay(); } // Wii if (mPreferences.getFloat(ButtonType.WIIMOTE_BUTTON_A + "-X", 0f) == 0f) { wiiDefaultOverlay(); } if (mPreferences.getFloat(ButtonType.WIIMOTE_BUTTON_A + "-Portrait" + "-X", 0f) == 0f) { wiiPortraitDefaultOverlay(); } // Wii Classic if (mPreferences.getFloat(ButtonType.CLASSIC_BUTTON_A + "-X", 0f) == 0f) { wiiClassicDefaultOverlay(); } if (mPreferences.getFloat(ButtonType.CLASSIC_BUTTON_A + "-Portrait" + "-X", 0f) == 0f) { wiiClassicPortraitDefaultOverlay(); } } if (!mPreferences.getBoolean("OverlayInitV3", false)) { wiiOnlyDefaultOverlay(); wiiOnlyPortraitDefaultOverlay(); } SharedPreferences.Editor sPrefsEditor = mPreferences.edit(); sPrefsEditor.putBoolean("OverlayInitV2", true); sPrefsEditor.putBoolean("OverlayInitV3", true); sPrefsEditor.apply(); } private void gcDefaultOverlay() { SharedPreferences.Editor sPrefsEditor = mPreferences.edit(); // Get screen size Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay(); DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics); float maxX = outMetrics.heightPixels; float maxY = outMetrics.widthPixels; // Height and width changes depending on orientation. Use the larger value for height. if (maxY > maxX) { float tmp = maxX; maxX = maxY; maxY = tmp; } Resources res = getResources(); // Each value is a percent from max X/Y stored as an int. Have to bring that value down // to a decimal before multiplying by MAX X/Y. sPrefsEditor.putFloat(ButtonType.BUTTON_A + "-X", (((float) res.getInteger(R.integer.BUTTON_A_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_A + "-Y", (((float) res.getInteger(R.integer.BUTTON_A_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.BUTTON_B + "-X", (((float) res.getInteger(R.integer.BUTTON_B_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_B + "-Y", (((float) res.getInteger(R.integer.BUTTON_B_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.BUTTON_X + "-X", (((float) res.getInteger(R.integer.BUTTON_X_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_X + "-Y", (((float) res.getInteger(R.integer.BUTTON_X_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.BUTTON_Y + "-X", (((float) res.getInteger(R.integer.BUTTON_Y_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_Y + "-Y", (((float) res.getInteger(R.integer.BUTTON_Y_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.BUTTON_Z + "-X", (((float) res.getInteger(R.integer.BUTTON_Z_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_Z + "-Y", (((float) res.getInteger(R.integer.BUTTON_Z_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.BUTTON_UP + "-X", (((float) res.getInteger(R.integer.BUTTON_UP_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_UP + "-Y", (((float) res.getInteger(R.integer.BUTTON_UP_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.TRIGGER_L + "-X", (((float) res.getInteger(R.integer.TRIGGER_L_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.TRIGGER_L + "-Y", (((float) res.getInteger(R.integer.TRIGGER_L_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.TRIGGER_R + "-X", (((float) res.getInteger(R.integer.TRIGGER_R_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.TRIGGER_R + "-Y", (((float) res.getInteger(R.integer.TRIGGER_R_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.BUTTON_START + "-X", (((float) res.getInteger(R.integer.BUTTON_START_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_START + "-Y", (((float) res.getInteger(R.integer.BUTTON_START_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.STICK_C + "-X", (((float) res.getInteger(R.integer.STICK_C_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.STICK_C + "-Y", (((float) res.getInteger(R.integer.STICK_C_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.STICK_MAIN + "-X", (((float) res.getInteger(R.integer.STICK_MAIN_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.STICK_MAIN + "-Y", (((float) res.getInteger(R.integer.STICK_MAIN_Y) / 1000) * maxY)); // We want to commit right away, otherwise the overlay could load before this is saved. sPrefsEditor.commit(); } private void gcPortraitDefaultOverlay() { SharedPreferences.Editor sPrefsEditor = mPreferences.edit(); // Get screen size Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay(); DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics); float maxX = outMetrics.heightPixels; float maxY = outMetrics.widthPixels; // Height and width changes depending on orientation. Use the larger value for height. if (maxY < maxX) { float tmp = maxX; maxX = maxY; maxY = tmp; } Resources res = getResources(); String portrait = "-Portrait"; // Each value is a percent from max X/Y stored as an int. Have to bring that value down // to a decimal before multiplying by MAX X/Y. sPrefsEditor.putFloat(ButtonType.BUTTON_A + portrait + "-X", (((float) res.getInteger(R.integer.BUTTON_A_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_A + portrait + "-Y", (((float) res.getInteger(R.integer.BUTTON_A_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.BUTTON_B + portrait + "-X", (((float) res.getInteger(R.integer.BUTTON_B_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_B + portrait + "-Y", (((float) res.getInteger(R.integer.BUTTON_B_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.BUTTON_X + portrait + "-X", (((float) res.getInteger(R.integer.BUTTON_X_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_X + portrait + "-Y", (((float) res.getInteger(R.integer.BUTTON_X_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.BUTTON_Y + portrait + "-X", (((float) res.getInteger(R.integer.BUTTON_Y_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_Y + portrait + "-Y", (((float) res.getInteger(R.integer.BUTTON_Y_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.BUTTON_Z + portrait + "-X", (((float) res.getInteger(R.integer.BUTTON_Z_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_Z + portrait + "-Y", (((float) res.getInteger(R.integer.BUTTON_Z_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.BUTTON_UP + portrait + "-X", (((float) res.getInteger(R.integer.BUTTON_UP_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_UP + portrait + "-Y", (((float) res.getInteger(R.integer.BUTTON_UP_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.TRIGGER_L + portrait + "-X", (((float) res.getInteger(R.integer.TRIGGER_L_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.TRIGGER_L + portrait + "-Y", (((float) res.getInteger(R.integer.TRIGGER_L_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.TRIGGER_R + portrait + "-X", (((float) res.getInteger(R.integer.TRIGGER_R_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.TRIGGER_R + portrait + "-Y", (((float) res.getInteger(R.integer.TRIGGER_R_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.BUTTON_START + portrait + "-X", (((float) res.getInteger(R.integer.BUTTON_START_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.BUTTON_START + portrait + "-Y", (((float) res.getInteger(R.integer.BUTTON_START_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.STICK_C + portrait + "-X", (((float) res.getInteger(R.integer.STICK_C_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.STICK_C + portrait + "-Y", (((float) res.getInteger(R.integer.STICK_C_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.STICK_MAIN + portrait + "-X", (((float) res.getInteger(R.integer.STICK_MAIN_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.STICK_MAIN + portrait + "-Y", (((float) res.getInteger(R.integer.STICK_MAIN_PORTRAIT_Y) / 1000) * maxY)); // We want to commit right away, otherwise the overlay could load before this is saved. sPrefsEditor.commit(); } private void wiiDefaultOverlay() { SharedPreferences.Editor sPrefsEditor = mPreferences.edit(); // Get screen size Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay(); DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics); float maxX = outMetrics.heightPixels; float maxY = outMetrics.widthPixels; // Height and width changes depending on orientation. Use the larger value for maxX. if (maxY > maxX) { float tmp = maxX; maxX = maxY; maxY = tmp; } Resources res = getResources(); // Each value is a percent from max X/Y stored as an int. Have to bring that value down // to a decimal before multiplying by MAX X/Y. sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_A + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_A_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_A + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_A_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_B + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_B_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_B + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_B_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_1 + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_1_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_1 + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_1_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_2 + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_2_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_2 + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_2_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.NUNCHUK_BUTTON_Z + "-X", (((float) res.getInteger(R.integer.NUNCHUK_BUTTON_Z_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.NUNCHUK_BUTTON_Z + "-Y", (((float) res.getInteger(R.integer.NUNCHUK_BUTTON_Z_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.NUNCHUK_BUTTON_C + "-X", (((float) res.getInteger(R.integer.NUNCHUK_BUTTON_C_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.NUNCHUK_BUTTON_C + "-Y", (((float) res.getInteger(R.integer.NUNCHUK_BUTTON_C_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_MINUS + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_MINUS_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_MINUS + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_MINUS_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_PLUS + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_PLUS_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_PLUS + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_PLUS_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_UP + "-X", (((float) res.getInteger(R.integer.WIIMOTE_UP_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_UP + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_UP_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_HOME + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_HOME_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_HOME + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_HOME_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.NUNCHUK_STICK + "-X", (((float) res.getInteger(R.integer.NUNCHUK_STICK_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.NUNCHUK_STICK + "-Y", (((float) res.getInteger(R.integer.NUNCHUK_STICK_Y) / 1000) * maxY)); // We want to commit right away, otherwise the overlay could load before this is saved. sPrefsEditor.commit(); } private void wiiOnlyDefaultOverlay() { SharedPreferences.Editor sPrefsEditor = mPreferences.edit(); // Get screen size Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay(); DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics); float maxX = outMetrics.heightPixels; float maxY = outMetrics.widthPixels; // Height and width changes depending on orientation. Use the larger value for maxX. if (maxY > maxX) { float tmp = maxX; maxX = maxY; maxY = tmp; } Resources res = getResources(); // Each value is a percent from max X/Y stored as an int. Have to bring that value down // to a decimal before multiplying by MAX X/Y. sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_A + "_H-X", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_A_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_A + "_H-Y", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_A_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_B + "_H-X", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_B_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_B + "_H-Y", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_B_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_1 + "_H-X", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_1_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_1 + "_H-Y", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_1_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_2 + "_H-X", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_2_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_2 + "_H-Y", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_2_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_UP + "_O-X", (((float) res.getInteger(R.integer.WIIMOTE_O_UP_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_UP + "_O-Y", (((float) res.getInteger(R.integer.WIIMOTE_O_UP_Y) / 1000) * maxY)); // Horizontal dpad sPrefsEditor.putFloat(ButtonType.WIIMOTE_RIGHT + "-X", (((float) res.getInteger(R.integer.WIIMOTE_RIGHT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_RIGHT + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_RIGHT_Y) / 1000) * maxY)); // We want to commit right away, otherwise the overlay could load before this is saved. sPrefsEditor.commit(); } private void wiiPortraitDefaultOverlay() { SharedPreferences.Editor sPrefsEditor = mPreferences.edit(); // Get screen size Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay(); DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics); float maxX = outMetrics.heightPixels; float maxY = outMetrics.widthPixels; // Height and width changes depending on orientation. Use the larger value for maxX. if (maxY < maxX) { float tmp = maxX; maxX = maxY; maxY = tmp; } Resources res = getResources(); String portrait = "-Portrait"; // Each value is a percent from max X/Y stored as an int. Have to bring that value down // to a decimal before multiplying by MAX X/Y. sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_A + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_A_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_A + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_A_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_B + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_B_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_B + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_B_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_1 + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_1_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_1 + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_1_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_2 + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_2_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_2 + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_2_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.NUNCHUK_BUTTON_Z + portrait + "-X", (((float) res.getInteger(R.integer.NUNCHUK_BUTTON_Z_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.NUNCHUK_BUTTON_Z + portrait + "-Y", (((float) res.getInteger(R.integer.NUNCHUK_BUTTON_Z_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.NUNCHUK_BUTTON_C + portrait + "-X", (((float) res.getInteger(R.integer.NUNCHUK_BUTTON_C_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.NUNCHUK_BUTTON_C + portrait + "-Y", (((float) res.getInteger(R.integer.NUNCHUK_BUTTON_C_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_MINUS + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_MINUS_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_MINUS + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_MINUS_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_PLUS + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_PLUS_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_PLUS + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_PLUS_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_UP + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_UP_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_UP + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_UP_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_HOME + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_HOME_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_HOME + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_BUTTON_HOME_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.NUNCHUK_STICK + portrait + "-X", (((float) res.getInteger(R.integer.NUNCHUK_STICK_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.NUNCHUK_STICK + portrait + "-Y", (((float) res.getInteger(R.integer.NUNCHUK_STICK_PORTRAIT_Y) / 1000) * maxY)); // Horizontal dpad sPrefsEditor.putFloat(ButtonType.WIIMOTE_RIGHT + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_RIGHT_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_RIGHT + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_RIGHT_PORTRAIT_Y) / 1000) * maxY)); // We want to commit right away, otherwise the overlay could load before this is saved. sPrefsEditor.commit(); } private void wiiOnlyPortraitDefaultOverlay() { SharedPreferences.Editor sPrefsEditor = mPreferences.edit(); // Get screen size Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay(); DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics); float maxX = outMetrics.heightPixels; float maxY = outMetrics.widthPixels; // Height and width changes depending on orientation. Use the larger value for maxX. if (maxY < maxX) { float tmp = maxX; maxX = maxY; maxY = tmp; } Resources res = getResources(); String portrait = "-Portrait"; // Each value is a percent from max X/Y stored as an int. Have to bring that value down // to a decimal before multiplying by MAX X/Y. sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_A + "_H" + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_A_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_A + "_H" + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_A_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_B + "_H" + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_B_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_B + "_H" + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_B_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_1 + "_H" + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_1_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_1 + "_H" + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_1_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_2 + "_H" + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_2_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_BUTTON_2 + "_H" + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_H_BUTTON_2_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_UP + "_O" + portrait + "-X", (((float) res.getInteger(R.integer.WIIMOTE_O_UP_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.WIIMOTE_UP + "_O" + portrait + "-Y", (((float) res.getInteger(R.integer.WIIMOTE_O_UP_PORTRAIT_Y) / 1000) * maxY)); // We want to commit right away, otherwise the overlay could load before this is saved. sPrefsEditor.commit(); } private void wiiClassicDefaultOverlay() { SharedPreferences.Editor sPrefsEditor = mPreferences.edit(); // Get screen size Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay(); DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics); float maxX = outMetrics.heightPixels; float maxY = outMetrics.widthPixels; // Height and width changes depending on orientation. Use the larger value for maxX. if (maxY > maxX) { float tmp = maxX; maxX = maxY; maxY = tmp; } Resources res = getResources(); // Each value is a percent from max X/Y stored as an int. Have to bring that value down // to a decimal before multiplying by MAX X/Y. sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_A + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_A_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_A + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_A_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_B + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_B_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_B + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_B_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_X + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_X_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_X + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_X_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_Y + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_Y_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_Y + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_Y_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_MINUS + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_MINUS_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_MINUS + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_MINUS_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_PLUS + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_PLUS_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_PLUS + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_PLUS_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_HOME + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_HOME_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_HOME + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_HOME_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_ZL + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_ZL_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_ZL + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_ZL_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_ZR + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_ZR_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_ZR + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_ZR_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_DPAD_UP + "-X", (((float) res.getInteger(R.integer.CLASSIC_DPAD_UP_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_DPAD_UP + "-Y", (((float) res.getInteger(R.integer.CLASSIC_DPAD_UP_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_STICK_LEFT + "-X", (((float) res.getInteger(R.integer.CLASSIC_STICK_LEFT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_STICK_LEFT + "-Y", (((float) res.getInteger(R.integer.CLASSIC_STICK_LEFT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_STICK_RIGHT + "-X", (((float) res.getInteger(R.integer.CLASSIC_STICK_RIGHT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_STICK_RIGHT + "-Y", (((float) res.getInteger(R.integer.CLASSIC_STICK_RIGHT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_TRIGGER_L + "-X", (((float) res.getInteger(R.integer.CLASSIC_TRIGGER_L_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_TRIGGER_L + "-Y", (((float) res.getInteger(R.integer.CLASSIC_TRIGGER_L_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_TRIGGER_R + "-X", (((float) res.getInteger(R.integer.CLASSIC_TRIGGER_R_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_TRIGGER_R + "-Y", (((float) res.getInteger(R.integer.CLASSIC_TRIGGER_R_Y) / 1000) * maxY)); // We want to commit right away, otherwise the overlay could load before this is saved. sPrefsEditor.commit(); } private void wiiClassicPortraitDefaultOverlay() { SharedPreferences.Editor sPrefsEditor = mPreferences.edit(); // Get screen size Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay(); DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics); float maxX = outMetrics.heightPixels; float maxY = outMetrics.widthPixels; // Height and width changes depending on orientation. Use the larger value for maxX. if (maxY < maxX) { float tmp = maxX; maxX = maxY; maxY = tmp; } Resources res = getResources(); String portrait = "-Portrait"; // Each value is a percent from max X/Y stored as an int. Have to bring that value down // to a decimal before multiplying by MAX X/Y. sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_A + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_A_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_A + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_A_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_B + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_B_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_B + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_B_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_X + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_X_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_X + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_X_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_Y + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_Y_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_Y + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_Y_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_MINUS + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_MINUS_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_MINUS + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_MINUS_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_PLUS + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_PLUS_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_PLUS + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_PLUS_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_HOME + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_HOME_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_HOME + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_HOME_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_ZL + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_ZL_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_ZL + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_ZL_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_ZR + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_ZR_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_BUTTON_ZR + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_BUTTON_ZR_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_DPAD_UP + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_DPAD_UP_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_DPAD_UP + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_DPAD_UP_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_STICK_LEFT + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_STICK_LEFT_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_STICK_LEFT + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_STICK_LEFT_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_STICK_RIGHT + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_STICK_RIGHT_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_STICK_RIGHT + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_STICK_RIGHT_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_TRIGGER_L + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_TRIGGER_L_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_TRIGGER_L + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_TRIGGER_L_PORTRAIT_Y) / 1000) * maxY)); sPrefsEditor.putFloat(ButtonType.CLASSIC_TRIGGER_R + portrait + "-X", (((float) res.getInteger(R.integer.CLASSIC_TRIGGER_R_PORTRAIT_X) / 1000) * maxX)); sPrefsEditor.putFloat(ButtonType.CLASSIC_TRIGGER_R + portrait + "-Y", (((float) res.getInteger(R.integer.CLASSIC_TRIGGER_R_PORTRAIT_Y) / 1000) * maxY)); // We want to commit right away, otherwise the overlay could load before this is saved. sPrefsEditor.commit(); } }
TwitchPlaysPokemon/dolphinWatch
Source/Android/app/src/main/java/org/dolphinemu/dolphinemu/overlay/InputOverlay.java
Java
gpl-2.0
77,511
<?php /******************************************************************************* Copyright 2013 Whole Foods Co-op This file is part of IT CORE. IT CORE 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. IT CORE 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 in the file license.txt along with IT CORE; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *********************************************************************************/ class NoReceiptPreParse extends PreParser { var $remainder; function check($str){ if (substr($str,-2) == 'NR'){ $this->remainder = substr($str,0,strlen($str)-2); return True; } elseif (substr($str,0,2) == "NR"){ $this->remainder = substr($str,2); return True; } return False; } function parse($str){ global $CORE_LOCAL; $CORE_LOCAL->set('receiptToggle', 0); return $this->remainder; } function doc(){ return "<table cellspacing=0 cellpadding=3 border=1> <tr> <th>Input</th><th>Result</th> </tr> <tr> <td><i>tender command</i>NR<i>item</i></td> <td>Apply tender with receipt disabled</td> </tr> <tr> <td>NR<i>tender command</i></td> <td>Same as above</td> </tr> </table>"; } } ?>
joelbrock/ELFCO_CORE
pos/is4c-nf/parser-class-lib/preparse/NoReceiptPreParse.php
PHP
gpl-2.0
1,799
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program; if not, write to the Free Software // // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetradapp.model; import edu.cmu.tetrad.data.DataModel; import edu.cmu.tetrad.data.DataModelList; import edu.cmu.tetrad.data.DataSet; import edu.cmu.tetrad.graph.*; import edu.cmu.tetrad.search.*; import edu.cmu.tetrad.util.TetradSerializableUtils; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; /** * Extends AbstractAlgorithmRunner to produce a wrapper for the GES algorithm. * * @author Ricardo Silva */ public class LfsRunner extends AbstractAlgorithmRunner implements GraphSource, PropertyChangeListener { static final long serialVersionUID = 23L; private transient List<PropertyChangeListener> listeners; private Graph pattern; // ============================CONSTRUCTORS============================// // public LingamPatternRunner(DataWrapper dataWrapper, PcSearchParams // params) { // super(dataWrapper, params); // } public LfsRunner(GraphWrapper graphWrapper, DataWrapper dataWrapper, PcSearchParams params) { super(dataWrapper, params, null); this.pattern = graphWrapper.getGraph(); } public LfsRunner(GraphWrapper graphWrapper, DataWrapper dataWrapper, PcSearchParams params, KnowledgeBoxModel knowledgeBoxModel) { super(dataWrapper, params, knowledgeBoxModel); this.pattern = graphWrapper.getGraph(); } /** * Constucts a wrapper for the given EdgeListGraph. */ public LfsRunner(GraphSource graphWrapper, PcSearchParams params, KnowledgeBoxModel knowledgeBoxModel) { super(graphWrapper.getGraph(), params, knowledgeBoxModel); } /** * Constucts a wrapper for the given EdgeListGraph. */ public LfsRunner(GraphSource graphWrapper, PcSearchParams params) { super(graphWrapper.getGraph(), params, null); } public LfsRunner(PcRunner wrapper, DataWrapper dataWrapper, PcSearchParams params, KnowledgeBoxModel knowledgeBoxModel) { super(dataWrapper, params, knowledgeBoxModel); this.pattern = wrapper.getGraph(); } public LfsRunner(PcRunner wrapper, DataWrapper dataWrapper, PcSearchParams params) { super(dataWrapper, params, null); this.pattern = wrapper.getGraph(); } public LfsRunner(CpcRunner wrapper, DataWrapper dataWrapper, PcSearchParams params, KnowledgeBoxModel knowledgeBoxModel) { super(dataWrapper, params, knowledgeBoxModel); this.pattern = wrapper.getGraph(); } public LfsRunner(CpcRunner wrapper, DataWrapper dataWrapper, PcSearchParams params) { super(dataWrapper, params, null); this.pattern = wrapper.getGraph(); } public LfsRunner(JpcRunner wrapper, DataWrapper dataWrapper, PcSearchParams params, KnowledgeBoxModel knowledgeBoxModel) { super(dataWrapper, params, knowledgeBoxModel); this.pattern = wrapper.getGraph(); } public LfsRunner(JpcRunner wrapper, DataWrapper dataWrapper, PcSearchParams params) { super(dataWrapper, params, null); this.pattern = wrapper.getGraph(); } public LfsRunner(JcpcRunner wrapper, DataWrapper dataWrapper, PcSearchParams params, KnowledgeBoxModel knowledgeBoxModel) { super(dataWrapper, params, knowledgeBoxModel); this.pattern = wrapper.getGraph(); } public LfsRunner(JcpcRunner wrapper, DataWrapper dataWrapper, PcSearchParams params) { super(dataWrapper, params, null); this.pattern = wrapper.getGraph(); } public LfsRunner(FciRunner wrapper, DataWrapper dataWrapper, PcSearchParams params) { super(dataWrapper, params, null); this.pattern = wrapper.getGraph(); } public LfsRunner(CcdRunner wrapper, DataWrapper dataWrapper, BasicSearchParams params) { super(dataWrapper, params, null); this.pattern = wrapper.getGraph(); } public LfsRunner(IGesRunner wrapper, DataWrapper dataWrapper, PcSearchParams params, KnowledgeBoxModel knowledgeBoxModel) { super(dataWrapper, params, knowledgeBoxModel); this.pattern = wrapper.getGraph(); } public LfsRunner(IGesRunner wrapper, DataWrapper dataWrapper, PcSearchParams params) { super(dataWrapper, params, null); this.pattern = wrapper.getGraph(); } /** * Generates a simple exemplar of this class to test serialization. * * @see edu.cmu.TestSerialization * @see TetradSerializableUtils */ public static LingamStructureRunner serializableInstance() { return new LingamStructureRunner(DataWrapper.serializableInstance(), PcSearchParams.serializableInstance(), KnowledgeBoxModel .serializableInstance()); } // ============================PUBLIC METHODS==========================// /** * Executes the algorithm, producing (at least) a result workbench. Must be implemented in the extending class. */ public void execute() { DataModel source = getDataModel(); Graph graph = null; if (source instanceof DataModelList) { // graph = lingamPatternEdgeVote((DataModelList) source, pattern); graph = multiLingamPattern((DataModelList) source, pattern); } else { DataModelList list = new DataModelList(); list.add(source); graph = multiLingamPattern(list, pattern); } setResultGraph(graph); if (getSourceGraph() != null) { GraphUtils.arrangeBySourceGraph(graph, getSourceGraph()); } else if (getParams().getKnowledge().isDefaultToKnowledgeLayout()) { SearchGraphUtils.arrangeByKnowledgeTiers(graph, getParams().getKnowledge()); } else { GraphUtils.circleLayout(graph, 200, 200, 150); } // for (int i = 0; i < result.getDags().size(); i++) { // System.out.println("\n\nModel # " + (i + 1) + " # votes = " + // result.getCounts().get(i)); // System.out.println(result.getDags().get(i)); // } } private Graph lingamPatternEdgeVote(DataModelList dataSets, Graph pattern) { List<Graph> lingamPatternGraphs = new ArrayList<Graph>(); // Images plus lingam orientation on multiple subjects. for (DataModel dataModel : dataSets) { DataSet dataSet = (DataSet) dataModel; LingamPattern lingamPattern = new LingamPattern(pattern, dataSet); lingamPattern.setAlpha(getParams().getIndTestParams().getAlpha()); Graph _graph = lingamPattern.search(); System.out.println(_graph); lingamPatternGraphs.add(_graph); } Graph lingamizedGraph = new EdgeListGraph(pattern.getNodes()); for (Edge edge : pattern.getEdges()) { int numRight = 0, numLeft = 0; for (Graph graph : lingamPatternGraphs) { if (graph.containsEdge(Edges.directedEdge(edge.getNode1(), edge.getNode2()))) { numRight++; } else if (graph.containsEdge(Edges.directedEdge(edge.getNode2(), edge.getNode1()))) { numLeft++; } } int margin = 0; if (numRight > numLeft + margin) { lingamizedGraph.addDirectedEdge(edge.getNode1(), edge.getNode2()); } else if (numLeft > numRight + margin) { lingamizedGraph.addDirectedEdge(edge.getNode2(), edge.getNode1()); } else { lingamizedGraph.addUndirectedEdge(edge.getNode1(), edge.getNode2()); } } System.out.println("lingamized graph = " + lingamizedGraph); return lingamizedGraph; } private Graph multiLingamPattern(DataModelList dataSets, Graph pattern) { final PcSearchParams params = (PcSearchParams) getParams(); List<DataSet> _dataSets = new ArrayList<DataSet>(); for (DataModel dataModel : dataSets) { _dataSets.add((DataSet) dataModel); } Lofs lofs = new Lofs(pattern, _dataSets); lofs.setAlpha(getParams().getIndTestParams().getAlpha()); lofs.setR1Done(params.isR1Done()); lofs.setR2Done(params.isR2Done()); lofs.setStrongR2(!params.isOrientStrongerDirection()); lofs.setMeekDone(params.isMeekDone()); Graph graph = lofs.orient(); return graph; } public Graph getGraph() { return getResultGraph(); } /** * @return the names of the triple classifications. Coordinates with getTriplesList. */ public List<String> getTriplesClassificationTypes() { List<String> names = new ArrayList<String>(); names.add("Colliders"); names.add("Noncolliders"); return names; } /** * @return the list of triples corresponding to <code>getTripleClassificationNames</code> for the given node. */ public List<List<Triple>> getTriplesLists(Node node) { List<List<Triple>> triplesList = new ArrayList<List<Triple>>(); Graph graph = getGraph(); triplesList.add(GraphUtils.getCollidersFromGraph(node, graph)); triplesList.add(GraphUtils.getNoncollidersFromGraph(node, graph)); return triplesList; } public boolean supportsKnowledge() { return true; } public ImpliedOrientation getMeekRules() { MeekRules rules = new MeekRules(); rules.setKnowledge(getParams().getKnowledge()); return rules; } public void propertyChange(PropertyChangeEvent evt) { firePropertyChange(evt); } private void firePropertyChange(PropertyChangeEvent evt) { for (PropertyChangeListener l : getListeners()) { l.propertyChange(evt); } } private List<PropertyChangeListener> getListeners() { if (listeners == null) { listeners = new ArrayList<PropertyChangeListener>(); } return listeners; } public void addPropertyChangeListener(PropertyChangeListener l) { if (!getListeners().contains(l)) getListeners().add(l); } public IndependenceTest getIndependenceTest() { Object dataModel = getDataModel(); if (dataModel == null) { dataModel = getSourceGraph(); } IndTestType testType = (getParams()).getIndTestType(); return new IndTestChooser().getTest(dataModel, getParams(), testType); } }
jdramsey/tetrad
tetrad-gui/src/main/java/edu/cmu/tetradapp/model/LfsRunner.java
Java
gpl-2.0
12,606
<?php echo getTitleArea(Lang::t('_COURSESTATS', 'menu_course')); ?> <div class="std_block"> <div class="quick_search_form"> <div> <div class="simple_search_box" id="usermanagement_simple_filter_options" style="display: block;"> <?php echo '<label for="">'.Lang::t('_FILTER', 'standard').'</label>' .Form::getInputDropdown( 'dropdown', 'filter_selection', 'filter_selection', array( 0 => Lang::t('_ALL', 'standard'), 1 => Lang::t('_USER_STATUS_SUBS', 'standard'), 2 => Lang::t('_USER_STATUS_BEGIN', 'standard'), 3 => Lang::t('_USER_STATUS_END', 'standard') ), (int)$filter_selection, '' ); echo '&nbsp;&nbsp;'; //some space between status filter and text filter echo Form::getInputTextfield("search_t", "filter_text", "filter_text", $filter_text, '', 255, '' ); echo Form::getButton("filter_set", "filter_set", Lang::t('_SEARCH', 'standard'), "search_b"); echo Form::getButton("filter_reset", "filter_reset", Lang::t('_RESET', 'standard'), "reset_b"); ?> </div> <a id="advanced_search" class="advanced_search" href="javascript:;"><?php echo Lang::t("_ADVANCED_SEARCH", 'standard'); ?></a> <div id="advanced_search_options" class="advanced_search_options" style="display: <?php echo $is_active_advanced_filter ? 'block' : 'none'; ?>"> <?php //filter inputs $orgchart_after = '<br />'.Form::getInputCheckbox('filter_descendants', 'filter_descendants', 1, $filter_descendants ? true : false, "") .'&nbsp;<label for="filter_descendants">'.Lang::t('_ORG_CHART_INHERIT', 'organization_chart').'</label>'; echo Form::getDropdown(Lang::t('_DIRECTORY_MEMBERTYPETREE', 'admin_directory'), 'filter_orgchart', 'filter_orgchart', $orgchart_list, (int)$filter_orgchart, $orgchart_after); echo Form::getDropdown(Lang::t('_GROUPS', 'standard'), 'filter_groups', 'filter_groups', $groups_list, (int)$filter_groups); //buttons echo Form::openButtonSpace(); echo Form::getButton('set_advanced_filter', false, Lang::t('_SEARCH', 'standard')); echo Form::getButton('reset_advanced_filter', false, Lang::t('_UNDO', 'standard')); echo Form::closeButtonSpace(); ?> </div> </div> </div> <?php $columns = array( array('key' => 'userid', 'label' => Lang::t('_USERNAME', 'standard'), 'sortable' => true, 'formatter' => 'CourseStats.useridFormatter', 'className' => 'min-cell'), array('key' => 'fullname', 'label' => Lang::t('_NAME', 'standard'), 'sortable' => true, 'formatter' => 'CourseStats.fullnameFormatter', 'className' => 'min-cell'), array('key' => 'level', 'label' => Lang::t('_LEVEL', 'standard'), 'sortable' => true, 'className' => 'min-cell'), array('key' => 'status', 'label' => Lang::t('_STATUS', 'standard'), 'sortable' => true, 'className' => 'min-cell', 'editor' => 'CourseStats.statusEditor') ); foreach ($lo_list as $lo) { $icon = '('.$lo->type.')';//'<img alt="'.$lo->type.'" title="'.$lo->type.'" src="'.getPathImage().'lobject/'.$lo->type.'.gif" />'; $link = ''; switch ($lo->type) { case "poll": $link = '<a title="" href="index.php?r=coursestats/show_object&id_lo='.(int)$lo->id.'">'.$lo->title.'</a>'; break; default: $link = $lo->title; } $columns[] = array('key' => 'lo_'.$lo->id, 'label' => $link.'<br />'.$icon, 'sortable' => false, 'formatter' => 'CourseStats.LOFormatter', 'className' => 'min-cell'); } $columns[] = array('key' => 'completed', 'label' => Lang::t('_COMPLETED', 'course'), 'sortable' => false, 'formatter' => 'CourseStats.completedFormatter', 'className' => 'min-cell'); $fields = array('id', 'userid', 'firstname', 'lastname', 'level', 'status', 'status_id', 'completed'); foreach ($lo_list as $lo) { $fields[] = 'lo_'.$lo->id; } $rel_actions = '<a href="index.php?r=coursestats/export_csv" class="ico-wt-sprite subs_csv" title="'.Lang::t('_EXPORT_CSV', 'report').'">' .'<span>'.Lang::t('_EXPORT_CSV', 'report').'</span></a>'; $params = array( 'id' => 'coursestats_table', 'ajaxUrl' => 'ajax.server.php?r=coursestats/gettabledata', 'sort' => 'userid', 'columns' => $columns, 'fields' => $fields, 'generateRequest' => 'CourseStats.requestBuilder', 'rel_actions' => $rel_actions, 'events' => array( 'initEvent' => 'CourseStats.initEvent' ), 'scroll_x' => "100%" ); $this->widget('table', $params); ?> </div> <script type="text/javascript"> CourseStats.init({ langs: { _LO_NOT_STARTED: "<?php echo Lang::t('_NOT_STARTED', 'standard'); ?>", _COMPLETED: "<?php echo Lang::t('_COMPLETED', 'standard'); ?>", _PERCENTAGE: "<?php echo Lang::t('_PERCENTAGE', 'standard'); ?>" }, idCourse: <?php echo (int)$id_course; ?>, filterText: "<?php echo $filter_text; ?>", filterSelection: <?php echo (int)$filter_selection; ?>, filterOrgChart: <?php echo (int)$filter_orgchart; ?>, filterGroups: <?php echo (int)$filter_groups; ?>, filterDescendants: <?php echo $filter_descendants ? 'true' : 'false'; ?>, countLOs: <?php echo count($lo_list); ?>, footerData: [<?php echo $lo_totals_js; ?>], statusList: <?php echo $status_list; ?> }); </script>
formalms/formalms
html/appLms/views/coursestats/show.php
PHP
gpl-2.0
5,072
<?php defined('_JEXEC') or die('Restricted access'); ?> <?php $form = @$this->form; ?> <?php $row = @$this->row; JFilterOutput::objectHTMLSafe( $row ); ?> <form action="<?php echo JRoute::_( @$form['action'] ) ?>" method="post" class="adminform" name="adminForm" > <fieldset> <legend><?php echo JText::_('Form'); ?></legend> <table class="admintable"> <tr> <td width="100" align="right" class="key"> <label for="currency_name"> <?php echo JText::_( 'Title' ); ?>: </label> </td> <td> <input type="text" name="currency_name" id="currency_name" size="48" maxlength="250" value="<?php echo @$row->currency_name; ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <label for="currency_code"> <?php echo JText::_( 'Currency Code' ); ?>: </label> </td> <td> <input type="text" name="currency_code" id="currency_code" size="10" maxlength="250" value="<?php echo @$row->currency_code; ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <label for="symbol_left"> <?php echo JText::_( 'Left Symbol' ); ?>: </label> </td> <td> <input type="text" name="symbol_left" id="symbol_left" size="10" maxlength="250" value="<?php echo @$row->symbol_left; ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <label for="symbol_right"> <?php echo JText::_( 'Right Symbol' ); ?>: </label> </td> <td> <input type="text" name="symbol_right" id="symbol_right" size="10" maxlength="250" value="<?php echo @$row->symbol_right; ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <label for="currency_decimals"> <?php echo JText::_( 'Decimals' ); ?>: </label> </td> <td> <input type="text" name="currency_decimals" id="currency_decimals" size="10" maxlength="250" value="<?php echo @$row->currency_decimals; ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <label for="decimal_separator"> <?php echo JText::_( 'Decimal Separator' ); ?>: </label> </td> <td> <input type="text" name="decimal_separator" id="decimal_separator" size="10" maxlength="250" value="<?php echo @$row->decimal_separator; ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <label for="thousands_separator"> <?php echo JText::_( 'Thousands Separator' ); ?>: </label> </td> <td> <input type="text" name="thousands_separator" id="thousands_separator" size="10" maxlength="250" value="<?php echo @$row->thousands_separator; ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <label for="exchange_rate"> <?php echo JText::_( 'Exchange Rate' ); ?>: </label> </td> <td> <?php if( TiendaConfig::getInstance()->get('currency_exchange_autoupdate', '1') ): ?> <div class="note"> <?php echo JText::_('WARNING AUTOEXCHANGE ENABLED'); ?> </div> <?php endif;?> <input type="text" name="exchange_rate" id="exchange_rate" size="10" maxlength="250" value="<?php echo @$row->exchange_rate; ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <label for="currency_enabled"> <?php echo JText::_( 'Enabled' ); ?>: </label> </td> <td> <?php echo JHTML::_('select.booleanlist', 'currency_enabled', '', @$row->currency_enabled ) ?> </td> </tr> </table> <input type="hidden" name="id" value="<?php echo @$row->currency_id?>" /> <input type="hidden" name="task" value="" /> </fieldset> </form>
zuverza/se
tmp/install_4f46ab24b6733/admin/views/currencies/tmpl/form.php
PHP
gpl-2.0
4,300
/* * Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * 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 "ScriptMgr.h" #include "ScriptedCreature.h" enum Texts { SAY_AGGRO = 0, SAY_EARTHQUAKE = 1, SAY_OVERRUN = 2, SAY_SLAY = 3, SAY_DEATH = 4 }; enum Spells { SPELL_EARTHQUAKE = 153616, SPELL_SUNDER_ARMOR = 153726, SPELL_CHAIN_LIGHTNING = 153764, SPELL_OVERRUN = 154221, SPELL_ENRAGE = 157173, SPELL_MARK_DEATH = 153234, SPELL_AURA_DEATH = 153616 }; enum Events { EVENT_ENRAGE = 1, EVENT_ARMOR = 2, EVENT_CHAIN = 3, EVENT_QUAKE = 4, EVENT_OVERRUN = 5 }; class boss_taran_zhu : public CreatureScript { public: boss_taran_zhu() : CreatureScript("boss_taran_zhu") { } struct boss_taran_zhuAI : public ScriptedAI { boss_taran_zhuAI(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { _inEnrage = false; } void Reset() override { _events.Reset(); _events.ScheduleEvent(EVENT_ENRAGE, 0); _events.ScheduleEvent(EVENT_ARMOR, urand(5000, 13000)); _events.ScheduleEvent(EVENT_CHAIN, urand(10000, 30000)); _events.ScheduleEvent(EVENT_QUAKE, urand(25000, 35000)); _events.ScheduleEvent(EVENT_OVERRUN, urand(30000, 45000)); Initialize(); } void KilledUnit(Unit* victim) override { victim->CastSpell(victim, SPELL_MARK_DEATH, 0); if (urand(0, 4)) return; Talk(SAY_SLAY); } void JustDied(Unit* /*killer*/) override { Talk(SAY_DEATH); } void EnterCombat(Unit* /*who*/) override { Talk(SAY_AGGRO); } void MoveInLineOfSight(Unit* who) override { if (who && who->GetTypeId() == TYPEID_PLAYER && me->IsValidAttackTarget(who)) if (who->HasAura(SPELL_MARK_DEATH)) who->CastSpell(who, SPELL_AURA_DEATH, 1); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_ENRAGE: if (!HealthAbovePct(20)) { DoCast(me, SPELL_ENRAGE); _events.ScheduleEvent(EVENT_ENRAGE, 6000); _inEnrage = true; } break; case EVENT_OVERRUN: Talk(SAY_OVERRUN); DoCastVictim(SPELL_OVERRUN); _events.ScheduleEvent(EVENT_OVERRUN, urand(25000, 40000)); break; case EVENT_QUAKE: if (urand(0, 1)) return; Talk(SAY_EARTHQUAKE); //remove enrage before casting earthquake because enrage + earthquake = 16000dmg over 8sec and all dead if (_inEnrage) me->RemoveAurasDueToSpell(SPELL_ENRAGE); DoCast(me, SPELL_EARTHQUAKE); _events.ScheduleEvent(EVENT_QUAKE, urand(30000, 55000)); break; case EVENT_CHAIN: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true)) DoCast(target, SPELL_CHAIN_LIGHTNING); _events.ScheduleEvent(EVENT_CHAIN, urand(7000, 27000)); break; case EVENT_ARMOR: DoCastVictim(SPELL_SUNDER_ARMOR); _events.ScheduleEvent(EVENT_ARMOR, urand(10000, 25000)); break; default: break; } } DoMeleeAttackIfReady(); } private: EventMap _events; bool _inEnrage; }; CreatureAI* GetAI(Creature* creature) const override { return new boss_taran_zhuAI(creature); } }; void AddSC_boss_taran_zhu() { new boss_taran_zhu(); }
ahuraa/DeathCore_6.x.x
src/server/scripts/Pandaria/ShadoPanMonastery/boss_taran_zhu.cpp
C++
gpl-2.0
5,742
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @author pb * @license For full copyright and license information view LICENSE file distributed with this source code. * @version 2014.11.1 * @package ezfind * * @todo: see if we need to make this an abstract class to accomodate CouchDB, MongoDB, so API is not frozen * also, perhaps better use dependency injection instead for class attribute specific * handlers to facilitate custom overrides * * ezfSolrStorage is a helper class to store serialized versions of attribute content * meta-data from eZ Publish objects is inserted in its stored form already */ class ezfSolrStorage { /** * */ const STORAGE_ATTR_FIELD_PREFIX = 'as_'; const STORAGE_ATTR_FIELD_SUFFIX = '_bst'; const CONTENT_METHOD_TOSTRING = 'to_string'; const CONTENT_METHOD_CUSTOM_HANDLER = 'custom_handler'; const STORAGE_VERSION_FORMAT = '1'; /* var $handler; */ function __construct( ) { } /** * @param eZContentObjectAttribute $contentObjectAttribute the attribute to serialize * @return array for further processing */ public static function getAttributeData ( eZContentObjectAttribute $contentObjectAttribute ) { $dataTypeIdentifier = $contentObjectAttribute->attribute( 'data_type_string' ); $contentClassAttribute = eZContentClassAttribute::fetch( $contentObjectAttribute->attribute( 'contentclassattribute_id' ) ); $attributeHandler = $dataTypeIdentifier . 'SolrStorage'; // prefill the array with generic metadata first $target = array ( 'data_type_identifier' => $dataTypeIdentifier, 'version_format' => self::STORAGE_VERSION_FORMAT, 'attribute_identifier' => $contentClassAttribute->attribute( 'identifier' ), 'has_content' => $contentObjectAttribute->hasContent(), ); if ( class_exists( $attributeHandler ) ) { $attributeContent = call_user_func( array( $attributeHandler, 'getAttributeContent' ), $contentObjectAttribute, $contentClassAttribute ); return array_merge( $target, $attributeContent, array( 'content_method' => self::CONTENT_METHOD_CUSTOM_HANDLER ) ); } else { $target = array_merge( $target, array( 'content_method' => self::CONTENT_METHOD_TOSTRING, 'content' => $contentObjectAttribute->toString(), 'has_rendered_content' => false, 'rendered' => null )); return $target; } } public static function serializeData ( $attributeData ) { return base64_encode( json_encode( $attributeData ) ); } /** * * @param string $jsonString * @return mixed */ public static function unserializeData ( $storageString ) { // primitive for now, it does not return the content in a general usable form yet // could insert code to use fromString methods returning an array for the content part return json_decode( base64_decode( $storageString ) , true ); } /** * * @param string $fieldNameBase * @return string Solr field name */ public static function getSolrStorageFieldName( $fieldNameBase ) { return self::STORAGE_ATTR_FIELD_PREFIX . $fieldNameBase . self::STORAGE_ATTR_FIELD_SUFFIX; } } ?>
wnsonsa/destin-foot
ezpublish_legacy/extension/ezfind/classes/ezfsolrstorage.php
PHP
gpl-2.0
3,494
<?php /** * @package Redcore * @subpackage Database * * @copyright Copyright (C) 2008 - 2015 redCOMPONENT.com. All rights reserved. * @license GNU General Public License version 2 or later, see LICENSE. */ defined('JPATH_REDCORE') or die; /** * Sql Translation class enables table and fields replacement methods * * @package Redcore * @subpackage Database * @since 1.0 */ class RDatabaseSqlparserSqltranslation extends RTranslationHelper { /** * Checks if tables inside query have translatable tables and fields and fetch appropriate * value from translations table * * @param string $sql SQL query * @param string $prefix Table prefix * @param string $language Language tag you want to fetch translation from * @param array $translationTables List of translation tables * * @return mixed Parsed query with added table joins and fields if found */ public static function parseSelectQuery($sql = '', $prefix = '', $language = 'en-GB', $translationTables = array()) { if (empty($translationTables)) { // We do not have any translation table to check return null; } try { $db = JFactory::getDbo(); $sqlParser = new RDatabaseSqlparserSqlparser($sql); $parsedSql = $sqlParser->parsed; if (!empty($parsedSql)) { $foundTables = array(); $originalTables = array(); $parsedSqlColumns = null; $subQueryFound = false; $parsedSql = self::parseTableReplacements($parsedSql, $translationTables, $foundTables, $originalTables, $language, $subQueryFound); if (empty($foundTables) && !$subQueryFound) { // We did not find any table to translate return null; } // Prepare field replacement $columns = array(); $columnFound = false; $parsedSqlColumns = $parsedSql; // Prepare column replacements foreach ($foundTables as $foundTable) { // Get all columns from that table $tableColumns = (array) $translationTables[$foundTable['originalTableName']]->columns; $originalTableColumns = RTranslationTable::getTableColumns($foundTable['originalTableName']); if (!empty($tableColumns)) { $selectAllOriginalColumn = $foundTable['alias']['originalName'] . '.*'; $columnAll = array(); $columnAll['table'] = $foundTable; $columnAll['columnName'] = $selectAllOriginalColumn; $columnAll['base_expr'] = self::addBaseColumns($originalTableColumns, $tableColumns, $foundTable['alias']['originalName']); foreach ($tableColumns as $tableColumn) { $column = array(); $column['base_expr'] = '' . 'COALESCE(' . $foundTable['alias']['name'] . '.' . $tableColumn . ',' . $foundTable['alias']['originalName'] . '.' . $tableColumn . ')'; $column['alias'] = $db->qn($tableColumn); $column['table'] = $foundTable; $column['columnName'] = $tableColumn; $columns[] = $column; if (!empty($columnAll['base_expr'])) { $columnAll['base_expr'] .= ','; } $columnAll['base_expr'] .= $column['base_expr'] . ' AS ' . $db->qn($tableColumn); } $columns[] = $columnAll; } } if (!empty($foundTables)) { $parsedSqlColumns = self::parseColumnReplacements($parsedSqlColumns, $columns, $translationTables, $columnFound); } // We are only returning parsed SQL if we found at least one column in translation table if ($columnFound || $subQueryFound) { $sqlCreator = new RDatabaseSqlparserSqlcreator($parsedSqlColumns); return $sqlCreator->created; } } } catch (Exception $e) { return null; } return null; } /** * Checks if this query is qualified for translation and parses query * * @param string $sql SQL query * @param string $prefix Table prefix * * @return mixed Parsed query with added table joins and fields if found */ public static function buildTranslationQuery($sql = '', $prefix = '') { $db = JFactory::getDbo(); $selectedLanguage = !empty($db->forceLanguageTranslation) ? $db->forceLanguageTranslation : JFactory::getLanguage()->getTag(); if (!empty($db->parseTablesBefore)) { foreach ($db->parseTablesBefore as $tableGroup) { $sql = self::parseSelectQuery($sql, $prefix, $tableGroup->language, $tableGroup->translationTables); } } /** * Basic check for translations, translation will not be inserted if: * If we do not have SELECT anywhere in query * If current language is site default language * If we are in administration */ if (empty($sql) || JFactory::getApplication()->isAdmin() || !stristr(mb_strtolower($sql), 'select') || RTranslationHelper::getSiteLanguage() == $selectedLanguage) { if (empty($db->parseTablesBefore) && empty($db->parseTablesAfter)) { return null; } } $translationTables = RTranslationHelper::getInstalledTranslationTables(); $translationTables = RTranslationHelper::removeFromEditForm($translationTables); $sql = self::parseSelectQuery($sql, $prefix, $selectedLanguage, $translationTables); if (!empty($db->parseTablesAfter)) { foreach ($db->parseTablesAfter as $tableGroup) { $sql = self::parseSelectQuery($sql, $prefix, $tableGroup->language, $tableGroup->translationTables); } } return $sql; } /** * Recursive method which go through every array and joins table if we have found the match * * @param array $parsedSqlColumns Parsed SQL in array format * @param array $columns Found replacement tables * @param array $translationTables List of translation tables * @param bool &$columnFound Found at least one column from original table * @param bool $addAlias Should we add alias after column name * * @return array Parsed query with added table joins if found */ public static function parseColumnReplacements($parsedSqlColumns, $columns, $translationTables, &$columnFound, $addAlias = true) { if (!empty($parsedSqlColumns) && is_array($parsedSqlColumns)) { $db = JFactory::getDbo(); // Replace all Tables and keys foreach ($parsedSqlColumns as $groupColumnsKey => $parsedColumnGroup) { if (!empty($parsedColumnGroup)) { $filteredGroup = array(); foreach ($parsedColumnGroup as $tagKey => $tagColumnsValue) { $column = null; if (!empty($tagColumnsValue['expr_type']) && $tagColumnsValue['expr_type'] == 'colref') { $column = self::getNameIfIncluded($tagColumnsValue['base_expr'], '', $columns, false, $groupColumnsKey); if (!empty($column)) { $primaryKey = ''; if (!empty($translationTables[$column['table']['originalTableName']]->primaryKeys)) { foreach ($translationTables[$column['table']['originalTableName']]->primaryKeys as $primaryKeyValue) { $primaryKey = self::getNameIfIncluded( $primaryKeyValue, $column['table']['alias']['originalName'], array($tagColumnsValue['base_expr']), false, $groupColumnsKey ); if (empty($primaryKey)) { break; } } } // This is primary key so if only this is used in query then we do not need to parse it if (empty($primaryKey)) { $columnFound = true; } if (in_array($groupColumnsKey, array('FROM'))) { if (empty($primaryKey) && $groupColumnsKey != 'FROM') { $tagColumnsValue['base_expr'] = self::breakColumnAndReplace($tagColumnsValue['base_expr'], $column['table']['alias']['name']); } else { $tagColumnsValue['base_expr'] = self::breakColumnAndReplace($tagColumnsValue['base_expr'], $column['table']['alias']['originalName']); } } else { if (in_array($groupColumnsKey, array('ORDER', 'WHERE', 'GROUP')) && !empty($primaryKey)) { $tagColumnsValue['base_expr'] = self::breakColumnAndReplace($tagColumnsValue['base_expr'], $column['table']['alias']['originalName']); } else { $tagColumnsValue['base_expr'] = $column['base_expr']; if ($addAlias && !empty($column['alias']) && !in_array($groupColumnsKey, array('ORDER', 'WHERE', 'GROUP'))) { $alias = $column['alias']; if (!empty($tagColumnsValue['alias']['name'])) { $alias = $tagColumnsValue['alias']['name']; } $alias = $db->qn(self::cleanEscaping($alias)); $tagColumnsValue['alias'] = array( 'as' => true, 'name' => $alias, 'base_expr' => 'as ' . $alias ); } } } } } elseif (!empty($tagColumnsValue['sub_tree'])) { if (!empty($tagColumnsValue['expr_type']) && $tagColumnsValue['expr_type'] == 'subquery') { // SubQuery is already parsed so we do not need to parse columns again } elseif (!empty($tagColumnsValue['expr_type']) && in_array($tagColumnsValue['expr_type'], array('expression'))) { foreach ($tagColumnsValue['sub_tree'] as $subKey => $subTree) { if (!empty($tagColumnsValue['sub_tree'][$subKey]['sub_tree'])) { $tagColumnsValue['sub_tree'][$subKey]['sub_tree'] = self::parseColumnReplacements( array($groupColumnsKey => $tagColumnsValue['sub_tree'][$subKey]['sub_tree']), $columns, $translationTables, $columnFound, false ); $tagColumnsValue['sub_tree'][$subKey]['sub_tree'] = $tagColumnsValue['sub_tree'][$subKey]['sub_tree'][$groupColumnsKey]; } } } elseif (is_array($tagColumnsValue['sub_tree'])) { // We will not replace some aggregate functions columns if (!in_array($tagColumnsValue['expr_type'], array('aggregate_function')) && strtolower($tagColumnsValue['base_expr']) != 'count') { $keys = array_keys($tagColumnsValue['sub_tree']); if (!is_numeric($keys[0])) { $tagColumnsValue['sub_tree'] = self::parseColumnReplacements( $tagColumnsValue['sub_tree'], $columns, $translationTables, $columnFound, false ); } else { $tagColumnsValue['sub_tree'] = self::parseColumnReplacements( array($groupColumnsKey => $tagColumnsValue['sub_tree']), $columns, $translationTables, $columnFound, false ); $tagColumnsValue['sub_tree'] = $tagColumnsValue['sub_tree'][$groupColumnsKey]; } } } } elseif (!empty($tagColumnsValue['ref_clause'])) { if (is_array($tagColumnsValue['ref_clause'])) { $keys = array_keys($tagColumnsValue['ref_clause']); if (!is_numeric($keys[0])) { $tagColumnsValue['ref_clause'] = self::parseColumnReplacements( $tagColumnsValue['ref_clause'], $columns, $translationTables, $columnFound, false ); } else { $tagColumnsValue['ref_clause'] = self::parseColumnReplacements( array($groupColumnsKey => $tagColumnsValue['ref_clause']), $columns, $translationTables, $columnFound, false ); $tagColumnsValue['ref_clause'] = $tagColumnsValue['ref_clause'][$groupColumnsKey]; } } } if (!is_numeric($tagKey)) { $filteredGroup[$tagKey] = $tagColumnsValue; } else { $filteredGroup[] = $tagColumnsValue; } } $parsedSqlColumns[$groupColumnsKey] = $filteredGroup; } } } return $parsedSqlColumns; } /** * Recursive method which go through every array and joins table if we have found the match * * @param array $parsedSql Parsed SQL in array format * @param array $translationTables List of translation tables * @param array &$foundTables Found replacement tables * @param array &$originalTables Found original tables used for creating unique alias * @param string $language Language tag you want to fetch translation from * @param string &$subQueryFound If sub query is found then we must parse end sql * * @return array Parsed query with added table joins if found */ public static function parseTableReplacements($parsedSql, $translationTables, &$foundTables, &$originalTables, $language, &$subQueryFound) { if (!empty($parsedSql) && is_array($parsedSql)) { // Replace all Tables and keys foreach ($parsedSql as $groupKey => $parsedGroup) { if (!empty($parsedGroup)) { $filteredGroup = array(); $filteredGroupEndPosition = array(); foreach ($parsedGroup as $tagKey => $tagValue) { $tableName = null; $newTagValue = null; if (!empty($tagValue['expr_type']) && $tagValue['expr_type'] == 'table' && !empty($tagValue['table'])) { $tableName = self::getNameIfIncluded( $tagValue['table'], !empty($tagValue['alias']['name']) ? $tagValue['alias']['name'] : '', $translationTables, true, $groupKey ); if (!empty($tableName)) { $newTagValue = $tagValue; $newTagValue['originalTableName'] = $tableName; $newTagValue['table'] = RTranslationTable::getTranslationsTableName($tableName, ''); $newTagValue['join_type'] = 'LEFT'; $newTagValue['ref_type'] = 'ON'; $alias = self::getUniqueAlias($tableName, $originalTables); if (!empty($newTagValue['alias']['name'])) { $alias = $newTagValue['alias']['name']; } $tagValue['alias'] = array( 'as' => true, 'name' => $alias, 'base_expr' => '' ); $newTagValue['alias'] = array( 'as' => true, 'name' => self::getUniqueAlias($newTagValue['table'], $foundTables), 'originalName' => $alias, 'base_expr' => '' ); $refClause = self::createParserJoinOperand( $newTagValue['alias']['name'], '=', $newTagValue['alias']['originalName'], $translationTables[$tableName], $language ); $newTagValue['ref_clause'] = $refClause; $foundTables[$newTagValue['alias']['name']] = $newTagValue; $originalTables[$newTagValue['alias']['originalName']] = 1; } } // There is an issue in sql parser for UNION and UNION ALL, this is a solution for it elseif (!empty($tagValue['union_tree']) && is_array($tagValue['union_tree']) && in_array('UNION', $tagValue['union_tree'])) { $subQueryFound = true; $unionTree = array(); foreach ($tagValue['union_tree'] as $union) { $union = trim($union); if (!empty($union) && strtoupper($union) != 'UNION') { $parsedSubQuery = self::buildTranslationQuery(self::removeParenthesisFromStart($union)); $unionTree[] = !empty($parsedSubQuery) ? '(' . $parsedSubQuery . ')' : $union; } } $tagValue['base_expr'] = '(' . implode(' UNION ', $unionTree) . ')'; $tagValue['expr_type'] = 'const'; if (!empty($tagValue['sub_tree'])) { unset($tagValue['sub_tree']); } if (!empty($tagValue['join_type'])) { unset($tagValue['join_type']); } } // Other types of expressions elseif (!empty($tagValue['sub_tree'])) { if (!empty($tagValue['expr_type']) && $tagValue['expr_type'] == 'subquery') { $parsedSubQuery = self::buildTranslationQuery($tagValue['base_expr']); if (!empty($parsedSubQuery)) { $sqlParser = new RDatabaseSqlparserSqlparser($parsedSubQuery); $tagValue['sub_tree'] = $sqlParser->parsed; $tagValue['base_expr'] = $parsedSubQuery; $subQueryFound = true; } } elseif (!empty($tagValue['expr_type']) && in_array($tagValue['expr_type'], array('expression'))) { foreach ($tagValue['sub_tree'] as $subKey => $subTree) { if (!empty($tagValue['sub_tree'][$subKey]['sub_tree'])) { $tagValue['sub_tree'][$subKey]['sub_tree'] = self::parseTableReplacements( $tagValue['sub_tree'][$subKey]['sub_tree'], $translationTables, $foundTables, $originalTables, $language, $subQueryFound ); } } } else { $tagValue['sub_tree'] = self::parseTableReplacements( $tagValue['sub_tree'], $translationTables, $foundTables, $originalTables, $language, $subQueryFound ); } } if (!is_numeric($tagKey)) { $filteredGroup[$tagKey] = $tagValue; } else { $filteredGroup[] = $tagValue; } if (!empty($newTagValue)) { if (!empty($translationTables[$tableName]->tableJoinEndPosition)) { $filteredGroupEndPosition[] = $newTagValue; } else { $filteredGroup[] = $newTagValue; } } } foreach ($filteredGroupEndPosition as $table) { $filteredGroup[] = $table; } $parsedSql[$groupKey] = $filteredGroup; } } } return $parsedSql; } /** * Creates unique Alias name not used in existing query * * @param string $originalTableName Original table name which we use for creating alias * @param array $foundTables Currently used tables in the query * @param int $counter Auto increasing number if we already have alias with the same name * * @return string Parsed query with added table joins and fields if found */ public static function getUniqueAlias($originalTableName, $foundTables = array(), $counter = 0) { $string = str_replace('#__', '', $originalTableName); $string .= '_' . substr(RFilesystemFile::getUniqueName($counter), 0, 4); if (!empty($foundTables[$string])) { $counter++; return self::getUniqueAlias($originalTableName, $foundTables, $counter); } return $string; } /** * Breaks column name and replaces alias with the new one * * @param string $column Column Name with or without prefix * @param string $replaceWith Alias name to replace current one * * @return string Parsed query with added table joins and fields if found */ public static function breakColumnAndReplace($column, $replaceWith) { $column = explode('.', $column); if (!empty($column)) { if (count($column) == 1) { $column[1] = $column[0]; } if (empty($replaceWith)) { return $column[1]; } $column[0] = $replaceWith; } return implode('.', $column); } /** * Creates array in sql Parser format, this function adds language filter as well * * @param string $newTable Table alias of new table * @param string $operator Operator of joining tables * @param string $oldTable Alias of original table * @param object $tableObject Alias of original table * @param string $language Language tag you want to fetch translation from * * @return string Parsed query with added table joins and fields if found */ public static function createParserJoinOperand($newTable, $operator, $oldTable, $tableObject, $language) { $db = JFactory::getDbo(); $refClause = array(); if (!empty($tableObject->primaryKeys)) { foreach ($tableObject->primaryKeys as $primaryKey) { $refClause[] = self::createParserElement('colref', $db->qn($newTable) . '.' . $primaryKey); $refClause[] = self::createParserElement('operator', $operator); $refClause[] = self::createParserElement('colref', $db->qn(self::cleanEscaping($oldTable)) . '.' . $primaryKey); $refClause[] = self::createParserElement('operator', 'AND'); } } $refClause[] = self::createParserElement('colref', $db->qn($newTable) . '.rctranslations_language'); $refClause[] = self::createParserElement('operator', '='); $refClause[] = self::createParserElement('colref', $db->q($language)); $refClause[] = self::createParserElement('operator', 'AND'); $refClause[] = self::createParserElement('colref', $db->qn($newTable) . '.rctranslations_state'); $refClause[] = self::createParserElement('operator', '='); $refClause[] = self::createParserElement('colref', $db->q('1')); if (!empty($tableObject->tableJoinParams)) { foreach ($tableObject->tableJoinParams as $join) { $leftSide = $join['left']; $rightSide = $join['right']; // Add alias if needed to the left side if (!empty($join['aliasLeft'])) { $leftSide = ($join['aliasLeft'] == 'original' ? $db->qn(self::cleanEscaping($oldTable)) : $db->qn($newTable)) . '.' . $leftSide; } // Add alias if needed to the right side if (!empty($join['aliasRight'])) { $rightSide = ($join['aliasRight'] == 'original' ? $db->qn(self::cleanEscaping($oldTable)) : $db->qn($newTable)) . '.' . $rightSide; } $refClause[] = self::createParserElement('operator', $join['expressionOperator']); $refClause[] = self::createParserElement('colref', $leftSide); $refClause[] = self::createParserElement('operator', $join['operator']); $refClause[] = self::createParserElement('colref', $rightSide); } } return $refClause; } /** * Create Table Join Parameter * * @param string $left Table alias of new table * @param string $operator Operator of joining tables * @param string $right Alias of original table * @param object $aliasLeft Alias of original table * @param string $aliasRight Language tag you want to fetch translation from * @param string $expressionOperator Language tag you want to fetch translation from * * @return array table join param */ public static function createTableJoinParam($left, $operator = '=', $right = '', $aliasLeft = null, $aliasRight = null, $expressionOperator = 'AND') { return array( 'left' => $left, 'operator' => $operator, 'right' => $right, 'aliasLeft' => $aliasLeft, 'aliasRight' => $aliasRight, 'expressionOperator' => $expressionOperator, ); } /** * Create Table Join Parameter * * @param array $originalTableColumns Table alias of new table * @param array $tableColumns Operator of joining tables * @param string $alias Original table alias * * @return array table join param */ public static function addBaseColumns($originalTableColumns, $tableColumns, $alias) { $columns = array(); foreach ($originalTableColumns as $key => $value) { if (!in_array($key, $tableColumns)) { $columns[] = $alias . '.' . $key; } } return implode(',', $columns); } /** * Creates array in sql Parser format, this function adds language filter as well * * @param string $exprType Expression type * @param string $baseExpr Base expression * @param bool $subTree Sub Tree * * @return array Parser Element in array format */ public static function createParserElement($exprType, $baseExpr, $subTree = false) { $element = array( 'expr_type' => $exprType, 'base_expr' => $baseExpr, 'sub_tree' => $subTree ); return $element; } /** * Check for different types of field usage in field list and returns name with alias if present * * @param string $field Field name this can be with or without quotes * @param string $tableAlias Table alias | optional * @param array $fieldList List of fields to check against * @param bool $isTable If we are checking against table string * @param string $groupName Group name * * @return mixed Returns List item if Field name is included in field list */ public static function getNameIfIncluded($field, $tableAlias = '', $fieldList = array(), $isTable = false, $groupName = 'SELECT') { // No fields to search for if (empty($fieldList) || empty($field) || self::skipTranslationColumn($groupName, $field)) { return ''; } $field = self::cleanEscaping($field); $fieldParts = explode('.', $field); $alias = ''; if (count($fieldParts) > 1) { $alias = $fieldParts[0]; $field = $fieldParts[1]; } // Check for field inclusion with various cases foreach ($fieldList as $fieldFromListQuotes => $fieldFromList) { if ($isTable) { switch (self::cleanEscaping($fieldFromListQuotes)) { case $field: if (!empty($fieldFromList->tableAliasesToParse) && !empty($tableAlias) && !in_array(self::cleanEscaping($tableAlias), $fieldFromList->tableAliasesToParse)) { continue; } return $fieldFromListQuotes; } } elseif ($tableAlias == '') { switch (self::cleanEscaping($fieldFromList['columnName'])) { case $field: case self::cleanEscaping($fieldFromList['table']['alias']['originalName'] . '.' . $field): // If this is different table we do not check columns if (!empty($alias) && $alias != self::cleanEscaping($fieldFromList['table']['alias']['originalName'])) { continue; } return $fieldFromList; } } else { switch (self::cleanEscaping($fieldFromList)) { case $field: case self::cleanEscaping($tableAlias . '.' . $field): return $fieldFromList; } } } return ''; } /** * Check for database escape and remove it * * @param string $sql Sql to check against * * @return string Returns true if Field name is included in field list */ public static function cleanEscaping($sql) { return str_replace('`', '', trim($sql)); } /** * Check for enclosing brackets and remove it * * @param string $sql Sql to check against * * @return string Returns sql query without enclosing brackets */ public static function removeParenthesisFromStart($sql) { $parenthesisRemoved = 0; $trim = trim($sql); if ($trim !== "" && $trim[0] === "(") { // Remove only one parenthesis pair now! $parenthesisRemoved++; $trim[0] = " "; $trim = trim($trim); } $parenthesis = $parenthesisRemoved; $i = 0; $string = 0; while ($i < strlen($trim)) { if ($trim[$i] === "\\") { // An escape character, the next character is irrelevant $i += 2; continue; } if ($trim[$i] === "'" || $trim[$i] === '"') { $string++; } if (($string % 2 === 0) && ($trim[$i] === "(")) { $parenthesis++; } if (($string % 2 === 0) && ($trim[$i] === ")")) { if ($parenthesis == $parenthesisRemoved) { $trim[$i] = " "; $parenthesisRemoved--; } $parenthesis--; } $i++; } return trim($trim); } /** * Check for database escape and remove it * * @param string $groupName Group name * @param string $field Field name this can be with or without quotes * * @return bool Returns true if Field name is included in field list */ public static function skipTranslationColumn($groupName, $field) { $db = JFactory::getDbo(); if (!empty($db->skipColumns)) { foreach ($db->skipColumns as $skipGroupName => $skipColumns) { if (!empty($skipColumns)) { foreach ($skipColumns as $column) { if ($groupName == $skipGroupName && self::cleanEscaping($field) == $column) { return true; } } } } } return false; } }
tharunaredweb/redCORE
libraries/redcore/database/sqlparser/sqltranslation.php
PHP
gpl-2.0
28,041
<?php /** * Hooks for TemplateInfo extension * * @file * @ingroup Extensions */ class TemplateInfoHooks { /* Functions */ // Initialization public static function register( &$parser ) { // Register the hook with the parser $parser->setHook( 'templateinfo', array( 'TemplateInfoHooks', 'render' ) ); // add the CSS global $wgOut, $wgScriptPath; $wgOut->addStyle($wgScriptPath . '/extensions/TemplateInfo/TemplateInfo.css'); // Continue return true; } // Render the displayed XML, if any public static function render( $input, $args, $parser, $frame ) { // if this call is contained in a transcluded page or template, // or if the input is empty, display nothing if ( !$frame->title->equals( $parser->getTitle() ) || $input == '' ) return; // TODO: Do processing here, like parse to an array $error_msg = null; // recreate the top-level <templateinfo> tag, with whatever // attributes it contained, because that was actually a tag- // function call, as opposed to a real XML tag $input = Xml::tags('templateinfo', $args, $input); // if 'type=' was specified, and it wasn't set to one of the // allowed values (currently just 'auto'), don't validate - // just display the XML if (array_key_exists('type', $args) && $args['type'] != 'auto') { // Store XML in the page_props table - the Javascript // can figure out on its own whether or not to handle it $parser->getOutput()->setProperty( 'templateinfo', $input ); // TODO - a hook should be called here, to allow other // XML handlers to parse and display this $text = Html::element('p', null, "The (unhandled) XML definition for this template is:") . "\n"; $text .= Html::element('pre', null, $input); return $text; } if ( $xml_object = TemplateInfo::validateXML( $input, $error_msg ) ) { // Store XML in the page_props table $parser->getOutput()->setProperty( 'templateinfo', $input ); $text = TemplateInfo::parseTemplateInfo($xml_object); } else { // Store error message in the page_props table $parser->getOutput()->setProperty( 'templateinfo', $error_msg ); $text = Html::element('p', null, "The (incorrect) XML definition for this template is:") . "\n"; $text .= Html::element('pre', null, $input); } // return output return $text; } }
SuriyaaKudoIsc/wikia-app-test
extensions/TemplateInfo/TemplateInfo.hooks.php
PHP
gpl-2.0
2,319
<?php /** * HUBzero CMS * * Copyright 2005-2011 Purdue University. All rights reserved. * * This file is part of: The HUBzero(R) Platform for Scientific Collaboration * * The HUBzero(R) Platform for Scientific Collaboration (HUBzero) 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 3 of the License, or (at your option) any * later version. * * HUBzero 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 program. If not, see <http://www.gnu.org/licenses/>. * * HUBzero is a registered trademark of Purdue University. * * @package hubzero-cms * @author Shawn Rice <zooley@purdue.edu> * @copyright Copyright 2005-2011 Purdue University. All rights reserved. * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPLv3 */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); /** * Resources helper class for HTML */ class ResourcesHtml { /** * Display a message and go back tot he previous page * * @param string $msg Message * @return string Javascript */ public function alert($msg) { return "<script type=\"text/javascript\"> alert('" . $msg . "'); window.history.go(-1); </script>\n"; } /** * Display a key for various resource statuses * * @return void */ public function statusKey() { ?> <p><?php echo JText::_('Published status: (click icon above to toggle state)'); ?></p> <ul class="key"> <li class="draftinternal"><span>draft (internal)</span> = <?php echo JText::_('Draft (internal production)'); ?></li> <li class="draftexternal"><span>draft (external)</span> = <?php echo JText::_('Draft (user created)'); ?></li> <li class="submitted"><span>new</span> = <?php echo JText::_('New, awaiting approval'); ?></li> <li class="pending"><span>pending</span> = <?php echo JText::_('Published, but is Coming'); ?></li> <li class="published"><span>current</span> = <?php echo JText::_('Published and is Current'); ?></li> <li class="expired"><span>finished</span> = <?php echo JText::_('Published, but has Finished'); ?></li> <li class="unpublished"><span>unpublished</span> = <?php echo JText::_('Unpublished'); ?></li> <li class="deleted"><span>deleted</span> = <?php echo JText::_('Delete/Removed'); ?></li> </ul> <?php } /** * Format an ID by prepending 0 * * @param integer $someid ID to format * @return integer */ public function niceidformat($someid) { while (strlen($someid) < 5) { $someid = 0 . "$someid"; } return $someid; } /** * Build the path to resource files from the creation date * * @param string $date Resource creation date * @param integer $id Resource ID * @param string $base Base path to prepend * @return string */ public function build_path($date, $id, $base='') { if ($date && preg_match("/([0-9]{4})-([0-9]{2})-([0-9]{2})[ ]([0-9]{2}):([0-9]{2}):([0-9]{2})/", $date, $regs)) { $date = mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); } if ($date) { $dir_year = date('Y', $date); $dir_month = date('m', $date); } else { $dir_year = date('Y'); $dir_month = date('m'); } $dir_id = ResourcesHtml::niceidformat($id); $path = $base . DS . $dir_year . DS . $dir_month . DS . $dir_id; //return $base . DS . $dir_id; return $path; } /** * Short description for 'writeRating' * * Long description (if any) ... * * @param string $rating Parameter description (if any) ... * @return string Return description (if any) ... */ public function writeRating($rating) { switch ($rating) { case 0.5: $class = ' half'; break; case 1: $class = ' one'; break; case 1.5: $class = ' onehalf'; break; case 2: $class = ' two'; break; case 2.5: $class = ' twohalf'; break; case 3: $class = ' three'; break; case 3.5: $class = ' threehalf'; break; case 4: $class = ' four'; break; case 4.5: $class = ' fourhalf'; break; case 5: $class = ' five'; break; case 0: default: $class = ' none'; break; } return '<p class="avgrating'.$class.'"><span>Rating: '.$rating.' out of 5 stars</span></p>'; } /** * Generate a select access list * * @param array $as Access levels * @param string $value Value to select * @return string HTML */ public function selectAccess($as, $value) { $as = explode(',',$as); $html = '<select name="access">' . "\n"; for ($i=0, $n=count($as); $i < $n; $i++) { $html .= "\t" . '<option value="' . $i . '"'; if ($value == $i) { $html .= ' selected="selected"'; } $html .= '>' . trim($as[$i]) . '</option>' . "\n"; } $html .= '</select>' . "\n"; return $html; } /** * Generate a select list for groups * * @param array $groups Groups to populate list * @param string $value Value to select * @return string HTML */ public function selectGroup($groups, $value) { $html = '<select name="group_owner"'; if (!$groups) { $html .= ' disabled="disabled"'; } $html .= ' style="max-width: 15em;">' . "\n"; $html .= ' <option value="">' . JText::_('Select group ...') . '</option>' . "\n"; if ($groups) { foreach ($groups as $group) { $html .= ' <option value="' . $group->cn . '"'; if ($value == $group->cn) { $html .= ' selected="selected"'; } $html .= '>' . stripslashes($group->description) . '</option>' . "\n"; } } $html .= '</select>' . "\n"; return $html; } /** * Generate a section select list * * @param string $name Name of the field * @param array $array Values to populate list * @param integer $value Value to select * @param string $class Class name of field * @param string $id ID of field * @return string HTML */ public function selectSection($name, $array, $value, $class='', $id) { $html = '<select name="' . $name . '" id="' . $name . '" onchange="return listItemTask(\'cb' . $id . '\',\'regroup\')"'; $html .= ($class) ? ' class="' . $class . '">' . "\n" : '>' . "\n"; $html .= ' <option value="0"'; $html .= ($id == $value || $value == 0) ? ' selected="selected"' : ''; $html .= '>' . JText::_('[ none ]') . '</option>' . "\n"; foreach ($array as $anode) { $selected = ($anode->id == $value || $anode->type == $value) ? ' selected="selected"' : ''; $html .= ' <option value="' . $anode->id . '"' . $selected . '>' . $anode->type . '</option>' . "\n"; } $html .= '</select>' . "\n"; return $html; } /** * Generate a type select list * * @param array $arr Values to populate list * @param string $name Name of the field * @param mixed $value Value to select * @param string $shownone Show a 'none' option? * @param string $class Class name of field * @param string $js Scripts to add to field * @param string $skip ITems to skip * @return string HTML */ public function selectType($arr, $name, $value='', $shownone='', $class='', $js='', $skip='') { $html = '<select name="' . $name . '" id="' . $name . '"' . $js; $html .= ($class) ? ' class="' . $class . '">' . "\n" : '>' . "\n"; if ($shownone != '') { $html .= "\t" . '<option value=""'; $html .= ($value == 0 || $value == '') ? ' selected="selected"' : ''; $html .= '>' . $shownone . '</option>' . "\n"; } if ($skip) { $skips = explode(',', $skip); } else { $skips = array(); } foreach ($arr as $anode) { if (!in_array($anode->id, $skips)) { $selected = ($value && ($anode->id == $value || $anode->type == $value)) ? ' selected="selected"' : ''; $html .= "\t" . '<option value="' . $anode->id . '"' . $selected . '>' . stripslashes($anode->type) . '</option>' . "\n"; } } $html .= '</select>' . "\n"; return $html; } /** * Convert a date to a path * * @param string $date Date to convert (0000-00-00 00:00:00) * @return string */ public function dateToPath($date) { if ($date && preg_match("/([0-9]{4})-([0-9]{2})-([0-9]{2})[ ]([0-9]{2}):([0-9]{2}):([0-9]{2})/", $date, $regs)) { $date = mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); } $dir_year = date('Y', $date); $dir_month = date('m', $date); return $dir_year . DS . $dir_month; } }
CI-Water-DASYCIM/CIWaterHubZeroPortalDev
administrator/components/com_resources/helpers/html.php
PHP
gpl-2.0
8,895
<?php /** * Provides CreativeCommons metadata * * Copyright 2004, Evan Prodromou <evan@wikitravel.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * @author Evan Prodromou <evan@wikitravel.org> * @file */ class CreativeCommonsRdf extends RdfMetaData { public function show(){ if( $this->setup() ){ global $wgRightsUrl; $url = $this->reallyFullUrl(); $this->prologue(); $this->subPrologue('Work', $url); $this->basics(); if( $wgRightsUrl ){ $url = htmlspecialchars( $wgRightsUrl ); print "\t\t<cc:license rdf:resource=\"$url\" />\n"; } $this->subEpilogue('Work'); if( $wgRightsUrl ){ $terms = $this->getTerms( $wgRightsUrl ); if( $terms ){ $this->subPrologue( 'License', $wgRightsUrl ); $this->license( $terms ); $this->subEpilogue( 'License' ); } } } $this->epilogue(); } protected function prologue() { echo <<<PROLOGUE <?xml version='1.0' encoding="UTF-8" ?> <rdf:RDF xmlns:cc="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> PROLOGUE; } protected function subPrologue( $type, $url ){ $url = htmlspecialchars( $url ); echo "\t<cc:{$type} rdf:about=\"{$url}\">\n"; } protected function subEpilogue($type) { echo "\t</cc:{$type}>\n"; } protected function license($terms) { foreach( $terms as $term ){ switch( $term ) { case 're': $this->term('permits', 'Reproduction'); break; case 'di': $this->term('permits', 'Distribution'); break; case 'de': $this->term('permits', 'DerivativeWorks'); break; case 'nc': $this->term('prohibits', 'CommercialUse'); break; case 'no': $this->term('requires', 'Notice'); break; case 'by': $this->term('requires', 'Attribution'); break; case 'sa': $this->term('requires', 'ShareAlike'); break; case 'sc': $this->term('requires', 'SourceCode'); break; } } } protected function term( $term, $name ){ print "\t\t<cc:{$term} rdf:resource=\"http://web.resource.org/cc/{$name}\" />\n"; } protected function epilogue() { echo "</rdf:RDF>\n"; } }
SuriyaaKudoIsc/wikia-app-test
extensions/CreativeCommonsRdf/CreativeCommonsRdf_body.php
PHP
gpl-2.0
2,838
<?php /** * @file * Contains Drupal\system\Tests\Installer\InstallerTranslationVersionUnitTest. */ namespace Drupal\system\Tests\Installer; use Drupal\simpletest\DrupalUnitTestBase; /** * Tests translation release version fallback. */ class InstallerTranslationVersionUnitTest extends DrupalUnitTestBase { public static function getInfo() { return array( 'name' => 'Installer translation version fallback', 'description' => 'Tests the translation version fallback used during site installation to determine available translation files.', 'group' => 'Installer', ); } protected function setUp() { parent::setUp(); require_once DRUPAL_ROOT . '/core/includes/install.core.inc'; } /** * Asserts version fallback results of install_get_localization_release(). * * @param $version * Version string for which to determine version fallbacks. * @param $fallback * Array of fallback versions ordered for most to least significant. * @param string $message * (optional) A message to display with the assertion. * @param string $group * (optional) The group this message is in. * * @return bool * TRUE if the assertion succeeded, FALSE otherwise. */ protected function assertVersionFallback($version, $fallback, $message = '', $group = 'Other') { $equal = TRUE; $results = install_get_localization_release($version); // Check the calculated results with the required results. // The $results is an array of arrays, each containing: // 'version': A release version (e.g. 8.0) // 'core' : The matching core version (e.g. 8.x) if (count($fallback) == count($results)) { foreach($results as $key => $result) { $equal &= $result['version'] == $fallback[$key]; list($major_release) = explode('.', $fallback[$key]); $equal &= $result['core'] == $major_release . '.x'; } } else { $equal = FALSE; } $message = $message ? $message : t('Version fallback for @version.', array('@version' => $version)); return $this->assert((bool) $equal, $message, $group); } /** * Tests version fallback of install_get_localization_release(). */ public function testVersionFallback() { $version = '8.0'; $fallback = array('8.0', '8.0-rc1', '7.0'); $this->assertVersionFallback($version, $fallback); $version = '8.1'; $fallback = array('8.1', '8.0', '7.0'); $this->assertVersionFallback($version, $fallback); $version = '8.12'; $fallback = array('8.12', '8.11', '7.0'); $this->assertVersionFallback($version, $fallback); $version = '8.0-dev'; $fallback = array('8.0-rc1', '8.0-beta1', '8.0-alpha12', '7.0'); $this->assertVersionFallback($version, $fallback); $version = '8.9-dev'; $fallback = array('8.8', '7.0'); $this->assertVersionFallback($version, $fallback); $version = '8.0-alpha3'; $fallback = array('8.0-alpha3', '8.0-alpha2', '7.0'); $this->assertVersionFallback($version, $fallback); $version = '8.0-alpha1'; $fallback = array('8.0-alpha1', '7.0'); $this->assertVersionFallback($version, $fallback); $version = '8.0-beta2'; $fallback = array('8.0-beta2', '8.0-beta1', '7.0'); $this->assertVersionFallback($version, $fallback); $version = '8.0-beta1'; $fallback = array('8.0-beta1', '8.0-alpha2', '7.0'); $this->assertVersionFallback($version, $fallback); $version = '8.0-rc8'; $fallback = array('8.0-rc8', '8.0-rc7', '7.0'); $this->assertVersionFallback($version, $fallback); $version = '8.0-rc1'; $fallback = array('8.0-rc1', '8.0-beta1', '7.0'); $this->assertVersionFallback($version, $fallback); $version = '8.0-foo2'; $fallback = array('7.0'); $this->assertVersionFallback($version, $fallback); $version = '99.2'; $fallback = array('99.2', '99.1', '98.0'); $this->assertVersionFallback($version, $fallback); } }
drupaals/demo.com
d8/core/modules/system/src/Tests/Installer/InstallerTranslationVersionUnitTest.php
PHP
gpl-2.0
3,976
# Miro - an RSS based video player application # Copyright (C) 2010, 2011 # Participatory Culture Foundation # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the OpenSSL # library. # # You must obey the GNU General Public License in all respects for all of # the code used other than OpenSSL. If you modify file(s) with this # exception, you may extend this exception to your version of the file(s), # but you are not obligated to do so. If you do not wish to do so, delete # this exception statement from your version. If you delete this exception # statement from all source files in the program, then also delete it here. from watchhistory import main WATCHER = None def load(context): """Loads the watchhistory module. """ global WATCHER WATCHER = main.WatchHistory() def unload(): pass
debugger06/MiroX
tv/extensions/watchhistory/__init__.py
Python
gpl-2.0
1,599
<?php namespace Elgg\Helpers\Di; use Elgg\Traits\Di\ServiceFacade; /** * @see Elgg\Di\ServiceFacadeTest */ class ServiceFacadeTestService { use ServiceFacade; public static function name() { return 'foo'; } public function greet($name) { return "Hi, $name"; } }
mrclay/Elgg-leaf
engine/tests/classes/Elgg/Helpers/Di/ServiceFacadeTestService.php
PHP
gpl-2.0
282
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package com.aionemu.gameserver.model.broker.filter; import com.aionemu.gameserver.dataholders.DataManager; import com.aionemu.gameserver.model.templates.item.ItemTemplate; import com.aionemu.gameserver.model.templates.item.actions.CraftLearnAction; import com.aionemu.gameserver.model.templates.item.actions.ItemActions; import com.aionemu.gameserver.model.templates.recipe.RecipeTemplate; import org.apache.commons.lang.ArrayUtils; /** * @author xTz */ public class BrokerRecipeFilter extends BrokerFilter { private int craftSkillId; private int[] masks; /** * @param masks */ public BrokerRecipeFilter(int craftSkillId, int... masks) { this.craftSkillId = craftSkillId; this.masks = masks; } @Override public boolean accept(ItemTemplate template) { ItemActions actions = template.getActions(); if (actions != null) { CraftLearnAction craftAction = actions.getCraftLearnAction(); if (craftAction != null) { int id = craftAction.getRecipeId(); RecipeTemplate recipeTemplate = DataManager.RECIPE_DATA.getRecipeTemplateById(id); if (recipeTemplate != null && recipeTemplate.getSkillid() == craftSkillId) { return ArrayUtils.contains(masks, template.getTemplateId() / 100000); } } } return false; } }
GiGatR00n/Aion-Core-v4.7.5
AC-Game/src/com/aionemu/gameserver/model/broker/filter/BrokerRecipeFilter.java
Java
gpl-2.0
2,691
/*************************************************************************** * * * copyright : (C) 2012 Barth Netterfield * * netterfield@astro.utoronto.ca * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "circledimensionstab.h" #include "plotitem.h" #include <QDebug> namespace Kst { CircleDimensionsTab::CircleDimensionsTab(ViewItem* viewItem, QWidget *parent) : DialogTab(parent), _viewItem(viewItem) { setupUi(this); connect(_lockPosToData, SIGNAL(clicked(bool)), this, SLOT(fillDimensions(bool))); } void CircleDimensionsTab::fillDimensions(bool lock_pos_to_data) { if (lock_pos_to_data) { _x->setRange(-1E308, 1E308); _y->setRange(-1E308, 1E308); _radius->setRange(0,1E308); _x->setValue(_viewItem->dataRelativeRect().center().x()); _y->setValue(_viewItem->dataRelativeRect().center().y()); _radius->setValue(0.5*_viewItem->dataRelativeRect().width()); } else { _x->setRange(0, 1); _y->setRange(0, 1); _radius->setRange(0,1); _x->setValue(_viewItem->relativeCenter().x()); _y->setValue(_viewItem->relativeCenter().y()); _radius->setValue(0.5*_viewItem->relativeWidth()); } } void CircleDimensionsTab::setupDimensions() { fillDimensions(_viewItem->dataPosLockable() && _viewItem->lockPosToData()); _lockPosToData->setChecked(_viewItem->lockPosToData()); if (_viewItem->dataPosLockable()) { _lockPosToData->show(); } else { _lockPosToData->hide(); } } void CircleDimensionsTab::modified() { emit tabModified(); } void CircleDimensionsTab::clearTabValues() { _radius->clear(); _lockPosToData->setCheckState(Qt::PartiallyChecked); } void CircleDimensionsTab::enableSingleEditOptions(bool enabled) { _x->setEnabled(enabled); _y->setEnabled(enabled); } bool CircleDimensionsTab::radiusDirty() const { return (!_radius->text().isEmpty()); } bool CircleDimensionsTab::lockPosToDataDirty() const { return _lockPosToData->checkState() != Qt::PartiallyChecked; } }
RossWilliamson/kst_old
src/libkstapp/circledimensionstab.cpp
C++
gpl-2.0
2,625
<?php get_header(); ?> <?php get_template_part('templates/page', 'header'); ?> <?php global $pinnacle; if(isset($pinnacle['portfolio_style_default'])) { $pstyleclass = $pinnacle['portfolio_style_default']; } else { $pstyleclass = 'padded_style'; } if(isset($pinnacle['portfolio_ratio_default'])) { $pimgratio = $pinnacle['portfolio_ratio_default']; } else { $pimgratio = "square"; } if(isset($pinnacle['portfolio_hover_style_default'])) { $phoverstyleclass = $pinnacle['portfolio_hover_style_default']; } else { $phoverstyleclass = 'p_lightstyle'; } if(!empty($pinnacle['portfolio_tax_column'])) { $portfolio_column = $pinnacle['portfolio_tax_column']; } else { $portfolio_column = 4; } if ($portfolio_column == '2') { $itemsize = 'tcol-md-6 tcol-sm-6 tcol-xs-12 tcol-ss-12'; $slidewidth = 600; } else if ($portfolio_column == '3'){ $itemsize = 'tcol-md-4 tcol-sm-4 tcol-xs-6 tcol-ss-12'; $slidewidth = 400; } else if ($portfolio_column == '6'){ $itemsize = 'tcol-md-2 tcol-sm-3 tcol-xs-4 tcol-ss-6'; $slidewidth = 300; } else if ($portfolio_column == '5'){ $itemsize = 'tcol-md-25 tcol-sm-3 tcol-xs-4 tcol-ss-6'; $slidewidth = 300; } else { $itemsize = 'tcol-md-3 tcol-sm-4 tcol-xs-6 tcol-ss-12'; $slidewidth = 300; } if($pimgratio == 'portrait') { $temppimgheight = $slidewidth * 1.35; $slideheight = floor($temppimgheight); } else if($pimgratio == 'landscape') { $temppimgheight = $slidewidth / 1.35; $slideheight = floor($temppimgheight); } else if($pimgratio == 'widelandscape') { $temppimgheight = $slidewidth / 2; $slideheight = floor($temppimgheight); } else { $slideheight = $slidewidth; } $showexcerpt = false; $plb = false; $portfolio_item_types = true; ?> <div id="content" class="container"> <div class="row"> <div class="main <?php echo esc_attr( pinnacle_main_class() ); ?>" role="main"> <?php echo category_description(); ?> <?php if (!have_posts()) : ?> <div class="alert"> <?php _e('Sorry, no results were found.', 'virtue'); ?> </div> <?php get_search_form(); ?> <?php endif; ?> <div id="portfoliowrapper" class="rowtight <?php echo esc_attr($pstyleclass);?> <?php echo esc_attr($phoverstyleclass);?>"> <?php global $wp_query; $cat_obj = $wp_query->get_queried_object(); $termslug = $cat_obj->slug; query_posts(array( 'paged' => $paged, 'posts_per_page' => '12', 'orderby' => 'menu_order', 'order' => 'ASC', 'post_type' => 'portfolio', 'portfolio-type' => $termslug ) ); while (have_posts()) : the_post(); ?> <div class="<?php echo esc_attr($itemsize);?> p-item"> <div class="portfolio-item grid_item postclass kad-light-gallery kad_portfolio_fade_in"> <?php if (has_post_thumbnail( $post->ID ) ) { $image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); $thumbnailURL = $image_url[0]; $image = aq_resize($thumbnailURL, $slidewidth, $slideheight, true); if(empty($image)) {$image = $thumbnailURL;} ?> <div class="portfolio-imagepadding"> <div class="portfolio-hoverclass"> <a href="<?php the_permalink() ?>" class=""> <img src="<?php echo esc_url($image); ?>" alt="<?php the_title(); ?>" class="kad-lightboxhover"> <div class="portfolio-hoverover"></div> <div class="portfolio-table"> <div class="portfolio-cell"> <?php if($pstyleclass == "padded_style" ) { ?> <a href="<?php the_permalink() ?>" class="kad-btn kad-btn-primary"><?php echo __('View details', 'pinnacle');?></a> <?php if($plb) {?> <a href="<?php echo esc_url($thumbnailURL); ?>" class="kad-btn kad-btn-primary plightbox-btn" title="<?php the_title();?>" data-rel="lightbox"><i class="kt-icon-search4"></i></a> <?php } ?> <?php } elseif($pstyleclass == "flat-no-margin" || $pstyleclass == "flat-w-margin" ) { ?> <h5><?php the_title();?></h5> <?php if($portfolio_item_types == true) { $terms = get_the_terms( $post->ID, 'portfolio-type' ); if ($terms) {?> <p class="cportfoliotag"><?php $output = array(); foreach($terms as $term){ $output[] = $term->name;} echo implode(', ', $output); ?></p> <?php } } if($showexcerpt) {?> <p class="p_excerpt"><?php echo pinnacle_excerpt(16); ?></p> <?php } ?> <?php if($plb) {?> <a href="<?php echo esc_url($thumbnailURL); ?>" class="kad-btn kad-btn-primary plightbox-btn" title="<?php the_title();?>" data-rel="lightbox"><i class="kt-icon-search4"></i></a> <?php } } ?> </div> </div> </a> </div> </div> <?php $image = null; $thumbnailURL = null; } if($pstyleclass == "padded_style" ) { ?> <a href="<?php the_permalink() ?>" class="portfoliolink"> <div class="piteminfo"> <h5><?php the_title();?></h5> <?php if($portfolio_item_types == true) { $terms = get_the_terms( $post->ID, 'portfolio-type' ); if ($terms) {?> <p class="cportfoliotag"><?php $output = array(); foreach($terms as $term){ $output[] = $term->name;} echo implode(', ', $output); ?></p> <?php } } if($showexcerpt == true) {?> <p><?php echo pinnacle_excerpt(16); ?></p> <?php } ?> </div> </a> <?php } ?> </div> </div> <?php endwhile; ?> </div> <!--portfoliowrapper--> <?php if ($wp_query->max_num_pages > 1) : if(function_exists('pinnacle_wp_pagination')) { pinnacle_wp_pagination(); } else { ?> <nav id="post-nav" class="pager"> <div class="previous"><?php next_posts_link(__('&larr; Older posts', 'virtue')); ?></div> <div class="next"><?php previous_posts_link(__('Newer posts &rarr;', 'virtue')); ?></div> </nav> <?php } endif; $wp_query = null; wp_reset_query(); ?> </div><!-- /.main --> <?php get_sidebar(); ?> </div><!-- /.row--> </div><!-- /.content --> </div><!-- /.wrap --> <?php get_footer(); ?>
luismedina25148/aslan
wp-content/themes/pinnacle/taxonomy-portfolio-type.php
PHP
gpl-2.0
8,324
#include <cstdlib> #include "nibblevector.h" #include "../misc/utils.h" namespace CSA { NibbleVector::NibbleVector(std::ifstream& file) : BitVector(file) { } NibbleVector::NibbleVector(FILE* file) : BitVector(file) { } NibbleVector::NibbleVector(Encoder& encoder, usint universe_size) : BitVector(encoder, universe_size) { } NibbleVector::~NibbleVector() { } //-------------------------------------------------------------------------- usint NibbleVector::reportSize() const { usint bytes = sizeof(*this); bytes += BitVector::reportSize(); return bytes; } //-------------------------------------------------------------------------- NibbleVector::Iterator::Iterator(const NibbleVector& par) : BitVector::Iterator(par), use_rle(false) { } NibbleVector::Iterator::~Iterator() { } // FIXME gap encoding for all operations usint NibbleVector::Iterator::rank(usint value, bool at_least) { const NibbleVector& par = (const NibbleVector&)(this->parent); if(value >= par.size) { return par.items; } this->valueLoop(value); usint idx = this->sample.first + this->cur + 1; if(!at_least && this->val > value) { idx--; } if(at_least && this->val < value) { this->getSample(this->block + 1); idx = this->sample.first + this->cur + 1; } return idx; } usint NibbleVector::Iterator::select(usint index) { const NibbleVector& par = (const NibbleVector&)(this->parent); if(index >= par.items) { return par.size; } this->getSample(this->sampleForIndex(index)); usint lim = index - this->sample.first; while(this->cur < lim) { this->val += this->buffer.readNibbleCode(); usint temp = this->buffer.readNibbleCode(); this->val += temp - 1; this->cur += temp; } if(this->cur > lim) { this->run = this->cur - lim; this->cur -= this->run; this->val -= this->run; } return this->val; } usint NibbleVector::Iterator::selectNext() { if(this->cur >= this->block_items) { this->getSample(this->block + 1); return this->val; } this->cur++; if(this->run > 0) { this->val++; this->run--; } else { this->val += this->buffer.readNibbleCode(); this->run = this->buffer.readNibbleCode() - 1; } return this->val; } pair_type NibbleVector::Iterator::valueBefore(usint value) { const NibbleVector& par = (const NibbleVector&)(this->parent); if(value >= par.size) { return pair_type(par.size, par.items); } this->getSample(this->sampleForValue(value)); if(this->val > value) { return pair_type(par.size, par.items); } this->run = 0; while(this->cur < this->block_items && this->val < value) { usint temp = this->buffer.readNibbleCode(value - this->val); if(temp == 0) { break; } this->val += temp; temp = this->buffer.readNibbleCode(); this->cur += temp; this->val += temp - 1; } if(this->val > value) { this->run = this->val - value; this->val = value; this->cur -= this->run; } return pair_type(this->val, this->sample.first + this->cur); } pair_type NibbleVector::Iterator::valueAfter(usint value) { const NibbleVector& par = (const NibbleVector&)(this->parent); if(value >= par.size) { return pair_type(par.size, par.items); } this->valueLoop(value); if(this->val < value) { this->getSample(this->block + 1); } return pair_type(this->val, this->sample.first + this->cur); } pair_type NibbleVector::Iterator::nextValue() { if(this->cur >= this->block_items) { this->getSample(this->block + 1); return pair_type(this->val, this->sample.first); } this->cur++; if(this->run > 0) { this->val++; this->run--; } else { this->val += this->buffer.readNibbleCode(); this->run = this->buffer.readNibbleCode() - 1; } return pair_type(this->val, this->sample.first + this->cur); } pair_type NibbleVector::Iterator::selectRun(usint index, usint max_length) { usint value = this->select(index); usint len = std::min(max_length, this->run); this->run -= len; this->cur += len; this->val += len; return pair_type(value, len); } pair_type NibbleVector::Iterator::selectNextRun(usint max_length) { usint value = this->selectNext(); usint len = std::min(max_length, this->run); this->run -= len; this->cur += len; this->val += len; return pair_type(value, len); } bool NibbleVector::Iterator::isSet(usint value) { const NibbleVector& par = (const NibbleVector&)(this->parent); if(value >= par.size) { return false; } this->valueLoop(value); return (this->val == value); } usint NibbleVector::Iterator::countRuns() { const NibbleVector& par = (const NibbleVector&)(this->parent); if(par.items == 0) { return 0; } usint runs = 1; pair_type res = this->selectRun(0, par.items); usint last = res.first + res.second; while(last < par.size) { res = this->selectNextRun(par.items); if(res.first < par.size && res.first > last + 1) { runs++; } last = res.first + res.second; } return runs; } // FIXME for gap encoding void NibbleVector::Iterator::valueLoop(usint value) { this->getSample(this->sampleForValue(value)); if(this->val >= value) { return; } while(this->cur < this->block_items) { this->val += this->buffer.readNibbleCode(); this->cur++; this->run = this->buffer.readNibbleCode() - 1; if(this->val >= value) { break; } this->cur += this->run; this->val += this->run; if(this->val >= value) { this->run = this->val - value; this->val = value; this->cur -= this->run; break; } this->run = 0; } } //-------------------------------------------------------------------------- NibbleEncoder::NibbleEncoder(usint block_bytes, usint superblock_size) : VectorEncoder(block_bytes, superblock_size), run(EMPTY_PAIR) { } NibbleEncoder::~NibbleEncoder() { } void NibbleEncoder::setBit(usint value) { this->setRun(value, 1); } // FIXME for gap encoding void NibbleEncoder::setRun(usint start, usint len) { if(this->items == 0) { this->setFirstBit(start); if(len > 1) { this->nibbleEncode(1, len - 1); } return; } if(start < this->size || len == 0) { return; } // Write as much into the buffer as possible. usint diff = start + 1 - this->size; usint free_bits = this->buffer->bitsLeft(); usint code_bits = this->buffer->nibbleCodeLength(diff); if(free_bits >= code_bits + 4) // At least a part of the run fits into the block. { free_bits -= code_bits; usint run_bits = this->buffer->nibbleCodeLength(len); if(run_bits <= free_bits) { this->nibbleEncode(diff, len); return; } // Encode as much as possible and let the rest spill. usint llen = (usint)1 << (3 * (free_bits / 4)); this->nibbleEncode(diff, llen); len -= llen; // A new sample will be added. this->size++; this->items++; } else { this->size = start + 1; this->items++; } // Didn't fit into the block. A new sample & block required. this->addNewBlock(); if(len > 1) { this->nibbleEncode(1, len - 1); } } void NibbleEncoder::addBit(usint value) { this->addRun(value, 1); } void NibbleEncoder::addRun(usint start, usint len) { if(this->run.second == 0) { this->run = pair_type(start, len); } else if(start == this->run.first + this->run.second) { this->run.second += len; } else { this->setRun(this->run.first, this->run.second); this->run = pair_type(start, len); } } void NibbleEncoder::flush() { this->setRun(this->run.first, this->run.second); this->run.second = 0; } } // namespace CSA
alexandrutomescu/complete-contigs
src/rlcsa/bits/nibblevector.cpp
C++
gpl-2.0
7,631
/* Simple DirectMedia Layer Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "SDL.h" #if !SDL_VERSION_ATLEAST(2, 0, 0) #include "sdl/keyboard.hpp" #define SDLK_SCANCODE_MASK (1<<30) #define SDL_SCANCODE_TO_KEYCODE(X) (X | SDLK_SCANCODE_MASK) static const int SDL_default_keymap[SDL_NUM_SCANCODES] = { 0, 0, 0, 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', SDLK_RETURN, SDLK_ESCAPE, SDLK_BACKSPACE, SDLK_TAB, SDLK_SPACE, '-', '=', '[', ']', '\\', '#', ';', '\'', '`', ',', '.', '/', SDLK_CAPSLOCK, SDLK_F1, SDLK_F2, SDLK_F3, SDLK_F4, SDLK_F5, SDLK_F6, SDLK_F7, SDLK_F8, SDLK_F9, SDLK_F10, SDLK_F11, SDLK_F12, SDLK_PRINT, SDLK_SCROLLOCK, SDLK_PAUSE, SDLK_INSERT, SDLK_HOME, SDLK_PAGEUP, SDLK_DELETE, SDLK_END, SDLK_PAGEDOWN, SDLK_RIGHT, SDLK_LEFT, SDLK_DOWN, SDLK_UP, 0, SDLK_KP_DIVIDE, SDLK_KP_MULTIPLY, SDLK_KP_MINUS, SDLK_KP_PLUS, SDLK_KP_ENTER, SDLK_KP1, SDLK_KP2, SDLK_KP3, SDLK_KP4, SDLK_KP5, SDLK_KP6, SDLK_KP7, SDLK_KP8, SDLK_KP9, SDLK_KP0, SDLK_KP_PERIOD, 0, 0, SDLK_POWER, SDLK_KP_EQUALS, SDLK_F13, SDLK_F14, SDLK_F15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, SDLK_HELP, SDLK_MENU, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, SDLK_SYSREQ, 0, SDLK_CLEAR, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, SDLK_LCTRL, SDLK_LSHIFT, SDLK_LALT, SDLK_LMETA, SDLK_RCTRL, SDLK_RSHIFT, SDLK_RALT, SDLK_RMETA, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, SDLK_MODE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; static const char *SDL_scancode_names[SDL_NUM_SCANCODES] = { NULL, NULL, NULL, NULL, "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "Return", "Escape", "Backspace", "Tab", "Space", "-", "=", "[", "]", "\\", "#", ";", "'", "`", ",", ".", "/", "CapsLock", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "PrintScreen", "ScrollLock", "Pause", "Insert", "Home", "PageUp", "Delete", "End", "PageDown", "Right", "Left", "Down", "Up", "Numlock", "Keypad /", "Keypad *", "Keypad -", "Keypad +", "Keypad Enter", "Keypad 1", "Keypad 2", "Keypad 3", "Keypad 4", "Keypad 5", "Keypad 6", "Keypad 7", "Keypad 8", "Keypad 9", "Keypad 0", "Keypad .", NULL, "Application", "Power", "Keypad =", "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24", "Execute", "Help", "Menu", "Select", "Stop", "Again", "Undo", "Cut", "Copy", "Paste", "Find", "Mute", "VolumeUp", "VolumeDown", NULL, NULL, NULL, "Keypad ,", "Keypad = (AS400)", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "AltErase", "SysReq", "Cancel", "Clear", "Prior", "Return", "Separator", "Out", "Oper", "Clear / Again", "CrSel", "ExSel", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "Keypad 00", "Keypad 000", "ThousandsSeparator", "DecimalSeparator", "CurrencyUnit", "CurrencySubUnit", "Keypad (", "Keypad )", "Keypad {", "Keypad }", "Keypad Tab", "Keypad Backspace", "Keypad A", "Keypad B", "Keypad C", "Keypad D", "Keypad E", "Keypad F", "Keypad XOR", "Keypad ^", "Keypad %", "Keypad <", "Keypad >", "Keypad &", "Keypad &&", "Keypad |", "Keypad ||", "Keypad :", "Keypad #", "Keypad Space", "Keypad @", "Keypad !", "Keypad MemStore", "Keypad MemRecall", "Keypad MemClear", "Keypad MemAdd", "Keypad MemSubtract", "Keypad MemMultiply", "Keypad MemDivide", "Keypad +/-", "Keypad Clear", "Keypad ClearEntry", "Keypad Binary", "Keypad Octal", "Keypad Decimal", "Keypad Hexadecimal", NULL, NULL, "Left Ctrl", "Left Shift", "Left Alt", "Left GUI", "Right Ctrl", "Right Shift", "Right Alt", "Right GUI", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "ModeSwitch", "AudioNext", "AudioPrev", "AudioStop", "AudioPlay", "AudioMute", "MediaSelect", "WWW", "Mail", "Calculator", "Computer", "AC Search", "AC Home", "AC Back", "AC Forward", "AC Stop", "AC Refresh", "AC Bookmarks", "BrightnessDown", "BrightnessUp", "DisplaySwitch", "KBDIllumToggle", "KBDIllumDown", "KBDIllumUp", "Eject", "Sleep", }; /** * \brief Get the key code corresponding to the given scancode according * to the current keyboard layout. * * See ::SDL_Keycode for details. * * \sa SDL_GetKeyName() */ SDLKey SDL_GetKeyFromScancode(SDL_Scancode scancode); /** * \brief Get the scancode corresponding to the given key code according to the * current keyboard layout. * * See ::SDL_Scancode for details. * * \sa SDL_GetScancodeName() */ SDL_Scancode SDL_GetScancodeFromKey(SDLKey key); /** * \brief Get a human-readable name for a scancode. * * \return A pointer to the name for the scancode. * If the scancode doesn't have a name, this function returns * an empty string (""). * * \sa SDL_Scancode */ const char * SDL_GetScancodeName(SDL_Scancode scancode); /** * \brief Get a scancode from a human-readable name * * \return scancode, or SDL_SCANCODE_UNKNOWN if the name wasn't recognized * * \sa SDL_Scancode */ SDL_Scancode SDL_GetScancodeFromName(const char *name); SDLKey SDL_GetKeyFromScancode(SDL_Scancode scancode) { if (scancode < SDL_SCANCODE_UNKNOWN || scancode >= SDL_NUM_SCANCODES) { return SDLK_UNKNOWN; } return static_cast<SDLKey>(SDL_default_keymap[scancode]); } SDL_Scancode SDL_GetScancodeFromKey(SDLKey key) { for (int scancode = SDL_SCANCODE_UNKNOWN; scancode < SDL_NUM_SCANCODES; ++scancode) { if (SDL_default_keymap[scancode] == key) { return static_cast<SDL_Scancode>(scancode); } } return SDL_SCANCODE_UNKNOWN; } const char * SDL_GetScancodeName(SDL_Scancode scancode) { const char *name; if (scancode < SDL_SCANCODE_UNKNOWN || scancode >= SDL_NUM_SCANCODES) { return ""; } name = SDL_scancode_names[scancode]; if (name) return name; else return ""; } SDL_Scancode SDL_GetScancodeFromName(const char *name) { unsigned int i; if (!name || !*name) { return SDL_SCANCODE_UNKNOWN; } for (i = 0; i < SDL_arraysize(SDL_scancode_names); ++i) { if (!SDL_scancode_names[i]) { continue; } if (SDL_strcasecmp(name, SDL_scancode_names[i]) == 0) { return static_cast<SDL_Scancode>(i); } } return SDL_SCANCODE_UNKNOWN; } SDLKey SDL_GetKeyFromName(const char *name) { int key; /* Check input */ if (name == NULL) return SDLK_UNKNOWN; /* If it's a single UTF-8 character, then that's the keycode itself */ key = *reinterpret_cast<const unsigned char *>(name); if (key >= 0xF0) { if (SDL_strlen(name) == 4) { int i = 0; key = static_cast<Uint16>((name[i]&0x07) << 18); key |= static_cast<Uint16>((name[++i]&0x3F) << 12); key |= static_cast<Uint16>((name[++i]&0x3F) << 6); key |= static_cast<Uint16>((name[++i]&0x3F)); return static_cast<SDLKey>(key); } return SDLK_UNKNOWN; } else if (key >= 0xE0) { if (SDL_strlen(name) == 3) { int i = 0; key = static_cast<Uint16>((name[i]&0x0F) << 12); key |= static_cast<Uint16>((name[++i]&0x3F) << 6); key |= static_cast<Uint16>((name[++i]&0x3F)); return static_cast<SDLKey>(key); } return SDLK_UNKNOWN; } else if (key >= 0xC0) { if (SDL_strlen(name) == 2) { int i = 0; key = static_cast<Uint16>((name[i]&0x1F) << 6); key |= static_cast<Uint16>((name[++i]&0x3F)); return static_cast<SDLKey>(key); } return SDLK_UNKNOWN; } else { if (SDL_strlen(name) == 1) { if (key >= 'A' && key <= 'Z') { key += 32; } return static_cast<SDLKey>(key); } /* Get the scancode for this name, and the associated keycode */ return static_cast<SDLKey>(SDL_default_keymap[SDL_GetScancodeFromName(name)]); } } #endif /* vi: set ts=4 sw=4 expandtab: */
t-zuehlsdorff/wesnoth
src/sdl/keyboard.cpp
C++
gpl-2.0
11,240
<?php /** * This is the model class for table "order_product". * * The followings are the available columns in table 'order_product': * @property integer $order_product_id * @property integer $order_id * @property integer $product_id * @property string $name * @property string $model * @property integer $quantity * @property string $price * @property string $total * @property string $tax * @property integer $reward */ class OrderProduct extends CActiveRecord { /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return OrderProduct the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'order_product'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('order_id, product_id, name, model, quantity, reward', 'required'), array('order_id, product_id, quantity, reward', 'numerical', 'integerOnly' => true), array('name', 'length', 'max' => 255), array('model', 'length', 'max' => 64), array('price, total, tax', 'length', 'max' => 15), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('order_product_id, order_id, product_id, name, model, quantity, price, total, tax, reward', 'safe', 'on' => 'search'), ); } /** * @return array relational rules. */ public function relations() { return array( ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'order_product_id' => 'Order Product', 'order_id' => 'Order', 'product_id' => 'Product', 'name' => 'Name', 'model' => 'Model', 'quantity' => 'Quantity', 'price' => 'Price', 'total' => 'Total', 'tax' => 'Tax', 'reward' => 'Reward', ); } }
lvduit/DYiiShop
protected/models/OrderProduct.php
PHP
gpl-2.0
2,426
/* * Copyright (C) 2012 The Android Open Source Project * * 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. */ package android.drm.cts; import android.util.Log; import android.test.AndroidTestCase; import android.drm.DrmInfoStatus; import android.drm.DrmInfoRequest; import android.drm.ProcessedData; public class DrmInfoStatusTest extends AndroidTestCase { private static final String TAG = "CtsDrmInfoStatusTest"; private static final ProcessedData DEFAULT_DATA = null; private static final String DEFAULT_MIME = "video/"; private static final int DEFAULT_TYPE = DrmInfoRequest.TYPE_REGISTRATION_INFO; public static void testInvalidStatusCodes() throws Exception { checkInvalidStatusCode(DrmInfoStatus.STATUS_ERROR + 1); checkInvalidStatusCode(DrmInfoStatus.STATUS_OK - 1); } public static void testValidStatusCodes() throws Exception { checkValidStatusCode(DrmInfoStatus.STATUS_ERROR); checkValidStatusCode(DrmInfoStatus.STATUS_OK); } private static void checkInvalidStatusCode(int statusCode) throws Exception { try { DrmInfoStatus info = new DrmInfoStatus( statusCode, DEFAULT_TYPE, DEFAULT_DATA, DEFAULT_MIME); info = null; fail("Status code " + statusCode + " was accepted for DrmInfoStatus"); } catch(IllegalArgumentException e) { // Expected, and thus intentionally ignored. } } private static void checkValidStatusCode(int statusCode) throws Exception { DrmInfoStatus info = new DrmInfoStatus( statusCode, DEFAULT_TYPE, DEFAULT_DATA, DEFAULT_MIME); info = null; } }
rex-xxx/mt6572_x201
cts/tests/tests/drm/src/android/drm/cts/DrmInfoStatusTest.java
Java
gpl-2.0
2,208
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.features.topology.api; public interface HistoryManager { public void applyHistory(String userId, String fragmentId, GraphContainer container); public String getHistoryForUser(String userId); public String create(String userId, GraphContainer container); void onBind(HistoryOperation operation); void onUnbind(HistoryOperation operation); }
RangerRick/opennms
features/topology-map/org.opennms.features.topology.api/src/main/java/org/opennms/features/topology/api/HistoryManager.java
Java
gpl-2.0
1,562
/* * Copyright (c) 2008, 2014, Oracle and/or its affiliates. * All rights reserved. Use is subject to license terms. * * This file is available and licensed under the following license: * * 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 Oracle Corporation 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 * OWNER 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. */ package ensemble.samples.layout.flowpane; import javafx.application.Application; import javafx.geometry.Orientation; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.FlowPane; import javafx.stage.Stage; /** * A simple example of a FlowPane layout. * * @sampleName FlowPane * @preview preview.png * @see javafx.scene.layout.FlowPane * @related /Graphics 2d/Images/Image Creation * @embedded */ public class FlowPaneApp extends Application { private static final Image ICON_48 = new Image(FlowPaneApp.class.getResourceAsStream("/ensemble/samples/shared-resources/icon-48x48.png")); private static final Image ICON_68 = new Image(FlowPaneApp.class.getResourceAsStream("/ensemble/samples/shared-resources/icon-68x68.png")); private static final Image ICON_88 = new Image(FlowPaneApp.class.getResourceAsStream("/ensemble/samples/shared-resources/icon-88x88.png")); private static int ITEMS = 3; public Parent createContent() { FlowPane flowPane = new FlowPane(Orientation.HORIZONTAL, 4, 2); flowPane.setPrefWrapLength(240); //preferred wraplength ImageView[] imageViews48 = new ImageView[ITEMS]; ImageView[] imageViews68 = new ImageView[ITEMS]; ImageView[] imageViews88 = new ImageView[ITEMS]; for (int i = 0; i < ITEMS; i++) { imageViews48[i] = new ImageView(ICON_48); imageViews68[i] = new ImageView(ICON_68); imageViews88[i] = new ImageView(ICON_88); flowPane.getChildren().addAll(imageViews48[i], imageViews68[i], imageViews88[i]); } return flowPane; } @Override public void start(Stage primaryStage) throws Exception { primaryStage.setScene(new Scene(createContent())); primaryStage.show(); } /** * Java main for when running without JavaFX launcher * @param args command line arguments */ public static void main(String[] args) { launch(args); } }
loveyoupeng/rt
apps/samples/Ensemble8/src/samples/java/ensemble/samples/layout/flowpane/FlowPaneApp.java
Java
gpl-2.0
3,772
class AddRadiologyToPatients < ActiveRecord::Migration def self.up add_column :patients, :radiology, :boolean, :default => false end def self.down remove_column :patients, :radiology end end
mission-of-mercy/minnesota
db/migrate/20110409202513_add_radiology_to_patients.rb
Ruby
gpl-2.0
208
(function ($, document, window) { function reloadList(page) { ApiClient.getScheduledTasks({ isHidden: false }).done(function (tasks) { populateList(page, tasks); Dashboard.hideLoadingMsg(); }); } function populateList(page, tasks) { tasks = tasks.sort(function (a, b) { a = a.Category + " " + a.Name; b = b.Category + " " + b.Name; if (a == b) { return 0; } if (a < b) { return -1; } return 1; }); var html = ""; html += '<ul data-role="listview" data-inset="true" data-auto-enhanced="false" data-split-icon="Play">'; var currentCategory; for (var i = 0, length = tasks.length; i < length; i++) { var task = tasks[i]; if (task.Category != currentCategory) { currentCategory = task.Category; html += "<li data-role='list-divider'>" + currentCategory + "</li>"; } html += "<li title='" + task.Description + "'>"; html += "<a href='scheduledtask.html?id=" + task.Id + "'>"; html += "<h3>" + task.Name + "</h3>"; html += "<p id='" + task.Id + "'>" + getTaskProgressHtml(task) + "</p>"; if (task.State == "Idle") { html += "<a id='btnTask" + task.Id + "' class='btnStartTask' href='#' data-taskid='" + task.Id + "' data-icon='play'>" + Globalize.translate('ButtonStart') + "</a>"; } else if (task.State == "Running") { html += "<a id='btnTask" + task.Id + "' class='btnStopTask' href='#' data-taskid='" + task.Id + "' data-icon='stop'>" + Globalize.translate('ButtonStop') + "</a>"; } else { html += "<a id='btnTask" + task.Id + "' class='btnStartTask' href='#' data-taskid='" + task.Id + "' data-icon='play' style='display:none;'>" + Globalize.translate('ButtonStart') + "</a>"; } html += "</a>"; html += "</li>"; } html += "</ul>"; $('#divScheduledTasks', page).html(html).trigger('create'); } function getTaskProgressHtml(task) { var html = ''; if (task.State == "Idle") { if (task.LastExecutionResult) { html += Globalize.translate('LabelScheduledTaskLastRan').replace("{0}", humane_date(task.LastExecutionResult.EndTimeUtc)) .replace("{1}", humane_elapsed(task.LastExecutionResult.StartTimeUtc, task.LastExecutionResult.EndTimeUtc)); if (task.LastExecutionResult.Status == "Failed") { html += " <span style='color:#FF0000;'>" + Globalize.translate('LabelFailed') + "</span>"; } else if (task.LastExecutionResult.Status == "Cancelled") { html += " <span style='color:#0026FF;'>" + Globalize.translate('LabelCancelled') + "</span>"; } else if (task.LastExecutionResult.Status == "Aborted") { html += " <span style='color:#FF0000;'>" + Globalize.translate('LabelAbortedByServerShutdown') + "</span>"; } } } else if (task.State == "Running") { var progress = (task.CurrentProgressPercentage || 0).toFixed(1); html += '<progress max="100" value="' + progress + '" title="' + progress + '%">'; html += '' + progress + '%'; html += '</progress>'; html += "<span style='color:#009F00;margin-left:5px;'>" + progress + "%</span>"; } else { html += "<span style='color:#FF0000;'>" + Globalize.translate('LabelStopping') + "</span>"; } return html; } function onWebSocketMessage(e, msg) { if (msg.MessageType == "ScheduledTasksInfo") { var tasks = msg.Data; var page = $.mobile.activePage; updateTasks(page, tasks); } } function updateTasks(page, tasks) { for (var i = 0, length = tasks.length; i < length; i++) { var task = tasks[i]; $('#' + task.Id, page).html(getTaskProgressHtml(task)); var btnTask = $('#btnTask' + task.Id, page); updateTaskButton(btnTask, task.State); } } function updateTaskButton(btnTask, state) { var elem; if (state == "Idle") { elem = btnTask.addClass('btnStartTask').removeClass('btnStopTask').show().data("icon", "play").attr("title", Globalize.translate('ButtonStart')); elem.removeClass('ui-icon-stop').addClass('ui-icon-play'); } else if (state == "Running") { elem = btnTask.addClass('btnStopTask').removeClass('btnStartTask').show().data("icon", "stop").attr("title", Globalize.translate('ButtonStop')); elem.removeClass('ui-icon-play').addClass('ui-icon-stop'); } else { elem = btnTask.addClass('btnStartTask').removeClass('btnStopTask').hide().data("icon", "play").attr("title", Globalize.translate('ButtonStart')); elem.removeClass('ui-icon-stop').addClass('ui-icon-play'); } } function onWebSocketConnectionOpen() { startInterval(); reloadList($.mobile.activePage); } function startInterval() { if (ApiClient.isWebSocketOpen()) { ApiClient.sendWebSocketMessage("ScheduledTasksInfoStart", "1000,1000"); } } function stopInterval() { if (ApiClient.isWebSocketOpen()) { ApiClient.sendWebSocketMessage("ScheduledTasksInfoStop"); } } $(document).on('pageshow', "#scheduledTasksPage", function () { var page = this; Dashboard.showLoadingMsg(); startInterval(); reloadList(page); $(ApiClient).on("websocketmessage", onWebSocketMessage).on("websocketopen", onWebSocketConnectionOpen); $('#divScheduledTasks', page).on('click', '.btnStartTask', function () { var button = this; var id = button.getAttribute('data-taskid'); ApiClient.startScheduledTask(id).done(function () { updateTaskButton($(button), "Running"); reloadList(page); }); }).on('click', '.btnStopTask', function () { var button = this; var id = button.getAttribute('data-taskid'); ApiClient.stopScheduledTask(id).done(function () { updateTaskButton($(button), ""); reloadList(page); }); }); }).on('pagehide', "#scheduledTasksPage", function () { var page = this; $(ApiClient).off("websocketmessage", onWebSocketMessage).off("websocketopen", onWebSocketConnectionOpen); stopInterval(); $('#divScheduledTasks', page).off('click', '.btnStartTask').off('click', '.btnStopTask'); }); })(jQuery, document, window);
hamstercat/Emby
MediaBrowser.WebDashboard/dashboard-ui/scripts/scheduledtaskspage.js
JavaScript
gpl-2.0
7,041
# Copyright (C) 2003-2006 Kouichirou Eto, All rights reserved. # This is free software with ABSOLUTELY NO WARRANTY. # You can redistribute it and/or modify it under the terms of the GNU GPL 2. $LOAD_PATH.unshift '..' unless $LOAD_PATH.include? '..' require 'qwik/test-module-ml' if $0 == __FILE__ require 'qwik/server-memory' require 'qwik/farm' require 'qwik/group-site' require 'qwik/group' require 'qwik/password' $test = true end class TestSubmitUuencode < Test::Unit::TestCase include TestModuleML def test_all qml = QuickML::Group.new(@ml_config, 'test@example.com') qml.setup_test_config base64 = 'begin 666 1x1a.png MB5!.1PT*&@H````-24A$4@````$````!"`(```"0=U/>````#$E$051XVF/X 8__\_``7^`OXS$I44`````$E%3D2N0F"" ` end ' mail = post_mail(qml) { "Date: Mon, 3 Feb 2001 12:34:56 +0900 From: bob@example.net To: test@example.com Subject: UuencodeImage Content-Type: multipart/mixed; boundary=\"------------Boundary_iGrnGAlmY.rxNIm\" --------------Boundary_iGrnGAlmY.rxNIm Content-Type: text/plain; charset=ISO-2022-JP Content-Transfer-Encoding: 7bit This is a test. --------------Boundary_iGrnGAlmY.rxNIm Content-Type: application/octet-stream; name=\"1x1a.png\" Content-Transfer-Encoding: x-uuencode Content-Disposition: attachment; filename=\"1x1a.png\" #{base64} " } mail1 = QuickML::Mail.new mail1.read(mail.parts[1]) ok_eq('application/octet-stream', mail1.content_type) ok_eq("attachment; filename=\"1x1a.png\"", mail1['Content-Disposition']) ok_eq('1x1a.png', mail1.filename) ok_eq('x-uuencode', mail1['Content-Transfer-Encoding']) ok_eq("\211PNG\r\n\032\n\000\000\000\rIHDR\000\000\000\001\000\000\000\001\010\002\000\000\000\220wS\336\000\000\000\fIDATx\332c\370\377\377?\000\005\376\002\3763\022\225\024\000\000\000\000IEND\256B`\202", mail1.decoded_body) page = @site['UuencodeImage'] ok_eq('UuencodeImage', page.get_title) ok_eq('* UuencodeImage {{mail(bob@example.net,0) This is a test. {{file(1x1a.png)}} }} ', page.load) end end
snoozer05/qwikdoc
vendor/qwik/test-submit-uuencode.rb
Ruby
gpl-2.0
2,037
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * ExpressionEngine - by EllisLab * * @package ExpressionEngine * @author EllisLab Dev Team * @copyright Copyright (c) 2003 - 2014, EllisLab, Inc. * @license http://ellislab.com/expressionengine/user-guide/license.html * @link http://ellislab.com * @since Version 2.5 * @filesource */ // ------------------------------------------------------------------------ /** * ExpressionEngine Core Javascript Loader Class * * @package ExpressionEngine * @subpackage Core * @category Assets * @author EllisLab Dev Team * @link http://ellislab.com */ class Javascript_loader { /** * Constructor */ public function __construct() { $dir = ($this->config->item('use_compressed_js') == 'n') ? 'src' : 'compressed'; define('PATH_JAVASCRIPT', PATH_THEMES.'javascript/'.$dir.'/'); } // -------------------------------------------------------------------- /** * Javascript Combo Loader * * Combo load multiple javascript files to reduce HTTP requests * BASE.AMP.'C=javascript&M=combo&ui=ui,packages&file=another&plugin=plugins&package=third,party,packages' * * @access public * @return string */ public function combo_load() { $this->output->enable_profiler(FALSE); $contents = ''; $types = array( 'ui' => PATH_JAVASCRIPT.'jquery/ui/jquery.ui.', 'plugin' => PATH_JAVASCRIPT.'jquery/plugins/', 'file' => PATH_JAVASCRIPT, 'package' => PATH_THIRD, 'fp_module' => PATH_MOD ); $mock_name = ''; foreach($types as $type => $path) { $mock_name .= $this->input->get_post($type); $files = explode(',', $this->input->get_post($type)); foreach($files as $file) { if ($type == 'package' OR $type == 'fp_module') { $file = $file.'/javascript/'.$file; } elseif ($type == 'file') { $parts = explode('/', $file); $file = array(); foreach ($parts as $part) { if ($part != '..') { $file[] = $this->security->sanitize_filename($part); } } $file = implode('/', $file); } else { $file = $this->security->sanitize_filename($file); } $file = $path.$file.'.js'; if (file_exists($file)) { $contents .= file_get_contents($file)."\n\n"; } } } $modified = $this->input->get_post('v'); $this->set_headers($mock_name, $modified); $this->output->set_header('Content-Length: '.strlen($contents)); $this->output->set_output($contents); } // -------------------------------------------------------------------- /** * Set Headers * * @access private * @param string * @return string */ function set_headers($file, $mtime = FALSE) { $this->output->out_type = 'cp_asset'; $this->output->set_header("Content-Type: text/javascript"); if ($this->config->item('send_headers') != 'y') { // All we need is content type - we're done return; } $max_age = 5184000; $modified = ($mtime !== FALSE) ? $mtime : @filemtime($file); $modified_since = $this->input->server('HTTP_IF_MODIFIED_SINCE'); // Remove anything after the semicolon if ($pos = strrpos($modified_since, ';') !== FALSE) { $modified_since = substr($modified_since, 0, $pos); } // If the file is in the client cache, we'll // send a 304 and be done with it. if ($modified_since && (strtotime($modified_since) == $modified)) { $this->output->set_status_header(304); exit; } // Send a custom ETag to maintain a useful cache in // load-balanced environments $this->output->set_header("ETag: ".md5($modified.$file)); // All times GMT $modified = gmdate('D, d M Y H:i:s', $modified).' GMT'; $expires = gmdate('D, d M Y H:i:s', time() + $max_age).' GMT'; $this->output->set_status_header(200); $this->output->set_header("Cache-Control: max-age={$max_age}, must-revalidate"); $this->output->set_header('Vary: Accept-Encoding'); $this->output->set_header('Last-Modified: '.$modified); $this->output->set_header('Expires: '.$expires); } // -------------------------------------------------------------------- /** * Avoid get_instance() */ public function __get($key) { $EE =& get_instance(); return $EE->$key; } } /* End of file */ /* Location: */
runrobrun/ee-xc-site
xcrunner/expressionengine/libraries/Javascript_loader.php
PHP
gpl-2.0
4,300
/*---------------------------------------------------------------------------*\ ========= | \\ / 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 Class faLaplacianScheme Description Abstract base class for laplacian schemes. SourceFiles faLaplacianScheme.C faLaplacianSchemes.C \*---------------------------------------------------------------------------*/ #ifndef faLaplacianScheme_H #define faLaplacianScheme_H #include "tmp.H" #include "areaFieldsFwd.H" #include "edgeFieldsFwd.H" #include "linearEdgeInterpolation.H" #include "correctedLnGrad.H" #include "typeInfo.H" #include "runTimeSelectionTables.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { template<class Type> class faMatrix; class faMesh; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace fa { /*---------------------------------------------------------------------------*\ Class laplacianScheme Declaration \*---------------------------------------------------------------------------*/ template<class Type> class laplacianScheme : public refCount { protected: // Protected data const faMesh& mesh_; tmp<edgeInterpolationScheme<scalar> > tinterpGammaScheme_; tmp<lnGradScheme<Type> > tlnGradScheme_; // Private Member Functions //- Disallow copy construct laplacianScheme(const laplacianScheme&); //- Disallow default bitwise assignment void operator=(const laplacianScheme&); public: // Declare run-time constructor selection tables declareRunTimeSelectionTable ( tmp, laplacianScheme, Istream, (const faMesh& mesh, Istream& schemeData), (mesh, schemeData) ); // Constructors //- Construct from mesh laplacianScheme(const faMesh& mesh) : mesh_(mesh), tinterpGammaScheme_(new linearEdgeInterpolation<scalar>(mesh)), tlnGradScheme_(new correctedLnGrad<Type>(mesh)) {} //- Construct from mesh and Istream laplacianScheme(const faMesh& mesh, Istream& is) : mesh_(mesh), tinterpGammaScheme_(NULL), tlnGradScheme_(NULL) { if (is.eof()) { tinterpGammaScheme_ = tmp<edgeInterpolationScheme<scalar> > ( new linearEdgeInterpolation<scalar>(mesh) ); tlnGradScheme_ = tmp<lnGradScheme<Type> > ( new correctedLnGrad<Type>(mesh) ); } else { tinterpGammaScheme_ = tmp<edgeInterpolationScheme<scalar> > ( edgeInterpolationScheme<scalar>::New(mesh, is) ); tlnGradScheme_ = tmp<lnGradScheme<Type> > ( lnGradScheme<Type>::New(mesh, is) ); } } // Selectors //- Return a pointer to a new laplacianScheme created on freestore static tmp<laplacianScheme<Type> > New ( const faMesh& mesh, Istream& schemeData ); // Destructor virtual ~laplacianScheme(); // Member Functions //- Return mesh reference const faMesh& mesh() const { return mesh_; } virtual tmp<faMatrix<Type> > famLaplacian ( const edgeScalarField&, GeometricField<Type, faPatchField, areaMesh>& ) = 0; virtual tmp<faMatrix<Type> > famLaplacian ( const areaScalarField&, GeometricField<Type, faPatchField, areaMesh>& ); virtual tmp<GeometricField<Type, faPatchField, areaMesh> > facLaplacian ( const GeometricField<Type, faPatchField, areaMesh>& ) = 0; virtual tmp<GeometricField<Type, faPatchField, areaMesh> > facLaplacian ( const edgeScalarField&, const GeometricField<Type, faPatchField, areaMesh>& ) = 0; virtual tmp<GeometricField<Type, faPatchField, areaMesh> > facLaplacian ( const areaScalarField&, const GeometricField<Type, faPatchField, areaMesh>& ); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace fa // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Add the patch constructor functions to the hash tables #define makeFaLaplacianTypeScheme(SS, Type) \ \ defineNamedTemplateTypeNameAndDebug(SS<Type>, 0); \ \ laplacianScheme<Type>::addIstreamConstructorToTable<SS<Type> > \ add##SS##Type##IstreamConstructorToTable_; #define makeFaLaplacianScheme(SS) \ \ makeFaLaplacianTypeScheme(SS, scalar) \ makeFaLaplacianTypeScheme(SS, vector) \ makeFaLaplacianTypeScheme(SS, tensor) // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository # include "faLaplacianScheme.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
CFDEMproject/OpenFOAM-1.6-ext
src/finiteArea/finiteArea/laplacianSchemes/faLaplacianScheme/faLaplacianScheme.H
C++
gpl-2.0
6,918
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInit22c89fc07eb52a6ca68a4337a7f96853::getLoader();
aakb/os2web
sites/all/libraries/mailchimp/vendor/autoload.php
PHP
gpl-2.0
183
<?php /** * @Project NUKEVIET 4.x * @Author VINADES.,JSC (contact@vinades.vn) * @Copyright (C) 2014 VINADES.,JSC. All rights reserved * @License GNU/GPL version 2 or any later version * @Createdate 12/30/2009 1:31 */ if( ! defined( 'NV_MAINFILE' ) ) die( 'Stop!!!' ); if( ! nv_admin_checkip() ) { nv_info_die( $global_config['site_description'], $lang_global['site_info'], sprintf( $lang_global['admin_ipincorrect'], NV_CLIENT_IP ) . '<meta http-equiv="Refresh" content="5;URL=' . $global_config['site_url'] . '" />' ); } if( ! nv_admin_checkfirewall() ) { // remove non US-ASCII to respect RFC2616 $server_message = preg_replace( '/[^\x20-\x7e]/i', '', $lang_global['firewallsystem'] ); if( empty( $server_message ) ) { $server_message = 'Administrators Section'; } header( 'WWW-Authenticate: Basic realm="' . $server_message . '"' ); header( NV_HEADERSTATUS . ' 401 Unauthorized' ); if( php_sapi_name() !== 'cgi-fcgi' ) { header( 'status: 401 Unauthorized' ); } nv_info_die( $global_config['site_description'], $lang_global['site_info'], $lang_global['firewallincorrect'] . '<meta http-equiv="Refresh" content="5;URL=' . $global_config['site_url'] . '" />' ); } $error = ''; $login = ''; $checkss = md5( $global_config['sitekey'] . $client_info['session_id'] ); $array_gfx_chk = array( 1, 5, 6, 7 ); if( in_array( $global_config['gfx_chk'], $array_gfx_chk ) ) { $global_config['gfx_chk'] = 1; } else { $global_config['gfx_chk'] = 0; } $admin_login_redirect = $nv_Request->get_string( 'admin_login_redirect', 'session', '' ); if( $nv_Request->isset_request( 'nv_login,nv_password', 'post' ) AND $nv_Request->get_title( 'checkss', 'post' ) == $checkss) { $nv_username = $nv_Request->get_title( 'nv_login', 'post', '', 1 ); $nv_password = $nv_Request->get_title( 'nv_password', 'post', '' ); if( $global_config['gfx_chk'] == 1 ) { $nv_seccode = $nv_Request->get_title( 'nv_seccode', 'post', '' ); } if( empty( $nv_username ) ) { $error = $lang_global['username_empty']; } elseif( empty( $nv_password ) ) { $error = $lang_global['password_empty']; } elseif( $global_config['gfx_chk'] == 1 and ! nv_capcha_txt( $nv_seccode ) ) { $error = $lang_global['securitycodeincorrect']; } else { if( defined( 'NV_IS_USER_FORUM' ) ) { define( 'NV_IS_MOD_USER', true ); require_once NV_ROOTDIR . '/' . DIR_FORUM . '/nukeviet/login.php'; if( empty( $nv_username ) ) $nv_username = $nv_Request->get_title( 'nv_login', 'post', '', 1 ); if( empty( $nv_password ) ) $nv_password = $nv_Request->get_title( 'nv_password', 'post', '' ); } $userid = 0; $row = $db->query( "SELECT userid, username, password FROM " . $db_config['dbsystem'] . "." . NV_USERS_GLOBALTABLE . " WHERE md5username ='" . nv_md5safe( $nv_username ) . "'" )->fetch(); if( empty( $row ) ) { nv_insert_logs( NV_LANG_DATA, 'login', '[' . $nv_username . '] ' . $lang_global['loginsubmit'] . ' ' . $lang_global['fail'], ' Client IP:' . NV_CLIENT_IP, 0 ); } else { if( $row['username'] == $nv_username and $crypt->validate( $nv_password, $row['password'] ) ) { $userid = $row['userid']; } } $error = $lang_global['loginincorrect']; if( $userid > 0 ) { $row = $db->query( 'SELECT t1.admin_id as admin_id, t1.lev as admin_lev, t1.last_agent as admin_last_agent, t1.last_ip as admin_last_ip, t1.last_login as admin_last_login, t2.password as admin_pass FROM ' . NV_AUTHORS_GLOBALTABLE . ' t1 INNER JOIN ' . $db_config['dbsystem'] . '.' . NV_USERS_GLOBALTABLE . ' t2 ON t1.admin_id = t2.userid WHERE t1.admin_id = ' . $userid . ' AND t1.lev!=0 AND t1.is_suspend=0 AND t2.active=1' )->fetch(); if( ! empty( $row ) ) { $admin_lev = intval( $row['admin_lev'] ); if( ! defined( 'ADMIN_LOGIN_MODE' ) ) define( 'ADMIN_LOGIN_MODE', 3 ); if( ADMIN_LOGIN_MODE == 2 and ! in_array( $admin_lev, array( 1, 2 ) ) ) { $error = $lang_global['admin_access_denied2']; } elseif( ADMIN_LOGIN_MODE == 1 and $admin_lev != 1 ) { $error = $lang_global['admin_access_denied1']; } else { nv_insert_logs( NV_LANG_DATA, 'login', '[' . $nv_username . '] ' . $lang_global['loginsubmit'], ' Client IP:' . NV_CLIENT_IP, 0 ); $admin_id = intval( $row['admin_id'] ); $checknum = nv_genpass( 10 ); $checknum = $crypt->hash( $checknum ); $array_admin = array( 'admin_id' => $admin_id, 'checknum' => $checknum, 'current_agent' => NV_USER_AGENT, 'last_agent' => $row['admin_last_agent'], 'current_ip' => NV_CLIENT_IP, 'last_ip' => $row['admin_last_ip'], 'current_login' => NV_CURRENTTIME, 'last_login' => intval( $row['admin_last_login'] ) ); $admin_serialize = serialize( $array_admin ); $sth = $db->prepare( 'UPDATE ' . NV_AUTHORS_GLOBALTABLE . ' SET check_num = :check_num, last_login = ' . NV_CURRENTTIME . ', last_ip = :last_ip, last_agent = :last_agent WHERE admin_id=' . $admin_id ); $sth->bindValue( ':check_num', $checknum, PDO::PARAM_STR ); $sth->bindValue( ':last_ip', NV_CLIENT_IP, PDO::PARAM_STR ); $sth->bindValue( ':last_agent', NV_USER_AGENT, PDO::PARAM_STR ); $sth->execute(); $nv_Request->set_Session( 'admin', $admin_serialize ); $nv_Request->set_Session( 'online', '1|' . NV_CURRENTTIME . '|' . NV_CURRENTTIME . '|0' ); define( 'NV_IS_ADMIN', true ); $redirect = NV_BASE_SITEURL . NV_ADMINDIR; if( ! empty( $admin_login_redirect ) ) { $redirect = $admin_login_redirect; $nv_Request->unset_request( 'admin_login_redirect', 'session' ); } $error = ''; nv_info_die( $global_config['site_description'], $lang_global['site_info'], $lang_global['admin_loginsuccessfully'] . " \n <meta http-equiv=\"refresh\" content=\"3;URL=" . $redirect . "\" />" ); die(); } } else { nv_insert_logs( NV_LANG_DATA, 'login', '[ ' . $nv_username . ' ] ' . $lang_global['loginsubmit'] . ' ' . $lang_global['fail'], ' Client IP:' . NV_CLIENT_IP, 0 ); } } } } else { if( empty( $admin_login_redirect ) ) { $nv_Request->set_Session( 'admin_login_redirect', $nv_Request->request_uri ); } $nv_username = ''; } if( file_exists( NV_ROOTDIR . '/language/' . NV_LANG_INTERFACE . '/admin_global.php' ) ) { require_once NV_ROOTDIR . '/language/' . NV_LANG_INTERFACE . '/admin_global.php'; } elseif( file_exists( NV_ROOTDIR . '/language/en/admin_global.php' ) ) { require_once NV_ROOTDIR . '/language/en/admin_global.php'; } $info = ( ! empty( $error ) ) ? '<div class="error">' . $error . '</div>' : '<div class="normal">' . $lang_global['logininfo'] . '</div>'; $size = @getimagesize( NV_ROOTDIR . '/' . $global_config['site_logo'] ); $dir_template = ''; if( file_exists( NV_ROOTDIR . '/themes/' . $global_config['admin_theme'] . '/system/login.tpl' ) ) { $dir_template = NV_ROOTDIR . "/themes/" . $global_config['admin_theme'] . "/system"; } else { $dir_template = NV_ROOTDIR . "/themes/admin_default/system"; $global_config['admin_theme'] = "admin_default"; } $xtpl = new XTemplate( "login.tpl", $dir_template ); $xtpl->assign( 'CHARSET', $global_config['site_charset'] ); $xtpl->assign( 'SITE_NAME', $global_config['site_name'] ); $xtpl->assign( 'PAGE_TITLE', $lang_global['admin_page'] ); $xtpl->assign( 'ADMIN_THEME', $global_config['admin_theme'] ); $xtpl->assign( 'SITELANG', NV_LANG_INTERFACE ); $xtpl->assign( 'NV_BASE_SITEURL', NV_BASE_SITEURL ); $xtpl->assign( 'NV_BASE_ADMINURL', NV_BASE_ADMINURL ); $xtpl->assign( 'CHECK_SC', ( $global_config['gfx_chk'] == 1 ) ? 1 : 0 ); $xtpl->assign( 'LOGIN_TITLE', $lang_global['adminlogin'] ); $xtpl->assign( 'LOGIN_INFO', $info ); $xtpl->assign( 'N_LOGIN', $lang_global['username'] ); $xtpl->assign( 'N_PASSWORD', $lang_global['password'] ); $xtpl->assign( 'SITEURL', $global_config['site_url'] ); $xtpl->assign( 'N_SUBMIT', $lang_global['loginsubmit'] ); $xtpl->assign( 'NV_COOKIE_PREFIX', $global_config['cookie_prefix'] ); $xtpl->assign( 'CHECKSS', $checkss ); $xtpl->assign( 'NV_TITLEBAR_DEFIS', NV_TITLEBAR_DEFIS ); $xtpl->assign( 'LOGIN_ERROR_SECURITY', addslashes( sprintf( $lang_global['login_error_security'], NV_GFX_NUM ) ) ); $xtpl->assign( 'V_LOGIN', $nv_username ); $xtpl->assign( 'LANGINTERFACE', $lang_global['langinterface'] ); if( isset( $size[1] ) ) { if( $size[0] > 490 ) { $size[1] = ceil( 490 * $size[1] / $size[0] ); $size[0] = 490; } $xtpl->assign( 'LOGO', NV_BASE_SITEURL . $global_config['site_logo'] ); $xtpl->assign( 'WIDTH', $size[0] ); $xtpl->assign( 'HEIGHT', $size[1] ); if( isset( $size['mime'] ) AND $size['mime'] == 'application/x-shockwave-flash' ) { $xtpl->parse( 'main.swf' ); } else { $xtpl->parse( 'main.image' ); } } $xtpl->assign( 'LANGLOSTPASS', $lang_global['lostpass'] ); $xtpl->assign( 'LINKLOSTPASS', NV_BASE_SITEURL . 'index.php?' . NV_LANG_VARIABLE . '=' . $global_config['site_lang'] . '&amp;' . NV_NAME_VARIABLE . '=users&amp;' . NV_OP_VARIABLE . '=lostpass' ); if( $global_config['gfx_chk'] == 1 ) { $xtpl->assign( 'CAPTCHA_REFRESH', $lang_global['captcharefresh'] ); $xtpl->assign( 'CAPTCHA_REFR_SRC', NV_BASE_SITEURL . 'images/refresh.png' ); $xtpl->assign( 'N_CAPTCHA', $lang_global['securitycode'] ); $xtpl->assign( 'GFX_NUM', NV_GFX_NUM ); $xtpl->assign( 'GFX_WIDTH', NV_GFX_WIDTH ); $xtpl->assign( 'GFX_HEIGHT', NV_GFX_HEIGHT ); $xtpl->parse( 'main.captcha' ); } if( $global_config['lang_multi'] == 1 ) { foreach( $global_config['allow_adminlangs'] as $lang_i ) { if( file_exists( NV_ROOTDIR . '/language/' . $lang_i . '/global.php' ) and file_exists( NV_ROOTDIR . '/language/' . $lang_i . '/admin_global.php' ) ) { $xtpl->assign( 'LANGOP', NV_BASE_ADMINURL . 'index.php?langinterface=' . $lang_i ); $xtpl->assign( 'LANGTITLE', $lang_global['langinterface'] ); $xtpl->assign( 'SELECTED', ( $lang_i == NV_LANG_INTERFACE ) ? "selected='selected'" : "" ); $xtpl->assign( 'LANGVALUE', $language_array[$lang_i]['name'] ); $xtpl->parse( 'main.lang_multi.option' ); } } $xtpl->parse( 'main.lang_multi' ); } $xtpl->parse( 'main' ); $global_config['mudim_active'] = 0; include NV_ROOTDIR . '/includes/header.php'; $xtpl->out( 'main' ); include NV_ROOTDIR . '/includes/footer.php'; ?>
webvangvn/nukeviet41
includes/core/admin_login.php
PHP
gpl-2.0
10,213
package org.apache.commons.math.transform; public class FastFourierTransformer implements java.io.Serializable { static final long serialVersionUID = 5138259215438106000L; private static final java.lang.String NOT_POWER_OF_TWO_MESSAGE = "{0} is not a power of 2, consider padding for fix"; private static final java.lang.String DIMENSION_MISMATCH_MESSAGE = "some dimensions don't match: {0} != {1}"; private static final java.lang.String MISSING_ROOTS_OF_UNITY_MESSAGE = "roots of unity have not been computed yet"; private static final java.lang.String OUT_OF_RANGE_ROOT_INDEX_MESSAGE = "out of range root of unity index {0} (must be in [{1};{2}])"; private org.apache.commons.math.transform.FastFourierTransformer.RootsOfUnity roots = new org.apache.commons.math.transform.FastFourierTransformer.RootsOfUnity(); public FastFourierTransformer() { super(); } public org.apache.commons.math.complex.Complex[] transform(double[] f) throws java.lang.IllegalArgumentException { return fft(f, false); } public org.apache.commons.math.complex.Complex[] transform(org.apache.commons.math.analysis.UnivariateRealFunction f, double min, double max, int n) throws java.lang.IllegalArgumentException, org.apache.commons.math.FunctionEvaluationException { double[] data = org.apache.commons.math.transform.FastFourierTransformer.sample(f, min, max, n); return fft(data, false); } public org.apache.commons.math.complex.Complex[] transform(org.apache.commons.math.complex.Complex[] f) throws java.lang.IllegalArgumentException { roots.computeOmega(f.length); return fft(f); } public org.apache.commons.math.complex.Complex[] transform2(double[] f) throws java.lang.IllegalArgumentException { double scaling_coefficient = 1.0 / (java.lang.Math.sqrt(f.length)); return org.apache.commons.math.transform.FastFourierTransformer.scaleArray(fft(f, false), scaling_coefficient); } public org.apache.commons.math.complex.Complex[] transform2(org.apache.commons.math.analysis.UnivariateRealFunction f, double min, double max, int n) throws java.lang.IllegalArgumentException, org.apache.commons.math.FunctionEvaluationException { double[] data = org.apache.commons.math.transform.FastFourierTransformer.sample(f, min, max, n); double scaling_coefficient = 1.0 / (java.lang.Math.sqrt(n)); return org.apache.commons.math.transform.FastFourierTransformer.scaleArray(fft(data, false), scaling_coefficient); } public org.apache.commons.math.complex.Complex[] transform2(org.apache.commons.math.complex.Complex[] f) throws java.lang.IllegalArgumentException { roots.computeOmega(f.length); double scaling_coefficient = 1.0 / (java.lang.Math.sqrt(f.length)); return org.apache.commons.math.transform.FastFourierTransformer.scaleArray(fft(f), scaling_coefficient); } public org.apache.commons.math.complex.Complex[] inversetransform(double[] f) throws java.lang.IllegalArgumentException { double scaling_coefficient = 1.0 / (f.length); return org.apache.commons.math.transform.FastFourierTransformer.scaleArray(fft(f, true), scaling_coefficient); } public org.apache.commons.math.complex.Complex[] inversetransform(org.apache.commons.math.analysis.UnivariateRealFunction f, double min, double max, int n) throws java.lang.IllegalArgumentException, org.apache.commons.math.FunctionEvaluationException { double[] data = org.apache.commons.math.transform.FastFourierTransformer.sample(f, min, max, n); double scaling_coefficient = 1.0 / n; return org.apache.commons.math.transform.FastFourierTransformer.scaleArray(fft(data, true), scaling_coefficient); } public org.apache.commons.math.complex.Complex[] inversetransform(org.apache.commons.math.complex.Complex[] f) throws java.lang.IllegalArgumentException { roots.computeOmega(-(f.length)); double scaling_coefficient = 1.0 / (f.length); return org.apache.commons.math.transform.FastFourierTransformer.scaleArray(fft(f), scaling_coefficient); } public org.apache.commons.math.complex.Complex[] inversetransform2(double[] f) throws java.lang.IllegalArgumentException { double scaling_coefficient = 1.0 / (java.lang.Math.sqrt(f.length)); return org.apache.commons.math.transform.FastFourierTransformer.scaleArray(fft(f, true), scaling_coefficient); } public org.apache.commons.math.complex.Complex[] inversetransform2(org.apache.commons.math.analysis.UnivariateRealFunction f, double min, double max, int n) throws java.lang.IllegalArgumentException, org.apache.commons.math.FunctionEvaluationException { double[] data = org.apache.commons.math.transform.FastFourierTransformer.sample(f, min, max, n); double scaling_coefficient = 1.0 / (java.lang.Math.sqrt(n)); return org.apache.commons.math.transform.FastFourierTransformer.scaleArray(fft(data, true), scaling_coefficient); } public org.apache.commons.math.complex.Complex[] inversetransform2(org.apache.commons.math.complex.Complex[] f) throws java.lang.IllegalArgumentException { roots.computeOmega(-(f.length)); double scaling_coefficient = 1.0 / (java.lang.Math.sqrt(f.length)); return org.apache.commons.math.transform.FastFourierTransformer.scaleArray(fft(f), scaling_coefficient); } protected org.apache.commons.math.complex.Complex[] fft(double[] f, boolean isInverse) throws java.lang.IllegalArgumentException { org.apache.commons.math.transform.FastFourierTransformer.verifyDataSet(f); org.apache.commons.math.complex.Complex[] F = new org.apache.commons.math.complex.Complex[f.length]; if ((f.length) == 1) { F[0] = new org.apache.commons.math.complex.Complex(f[0] , 0.0); return F; } int N = (f.length) >> 1; org.apache.commons.math.complex.Complex[] c = new org.apache.commons.math.complex.Complex[N]; for (int i = 0 ; i < N ; i++) { c[i] = new org.apache.commons.math.complex.Complex(f[(2 * i)] , f[((2 * i) + 1)]); } roots.computeOmega((isInverse ? -N : N)); org.apache.commons.math.complex.Complex[] z = fft(c); roots.computeOmega((isInverse ? (-2) * N : 2 * N)); F[0] = new org.apache.commons.math.complex.Complex((2 * ((z[0].getReal()) + (z[0].getImaginary()))) , 0.0); F[N] = new org.apache.commons.math.complex.Complex((2 * ((z[0].getReal()) - (z[0].getImaginary()))) , 0.0); for (int i = 1 ; i < N ; i++) { org.apache.commons.math.complex.Complex A = z[(N - i)].conjugate(); org.apache.commons.math.complex.Complex B = z[i].add(A); org.apache.commons.math.complex.Complex C = z[i].subtract(A); org.apache.commons.math.complex.Complex D = new org.apache.commons.math.complex.Complex(-(roots.getOmegaImaginary(i)) , roots.getOmegaReal(i)); F[i] = B.subtract(C.multiply(D)); F[((2 * N) - i)] = F[i].conjugate(); } return org.apache.commons.math.transform.FastFourierTransformer.scaleArray(F, 0.5); } protected org.apache.commons.math.complex.Complex[] fft(org.apache.commons.math.complex.Complex[] data) throws java.lang.IllegalArgumentException { final int n = data.length; final org.apache.commons.math.complex.Complex[] f = new org.apache.commons.math.complex.Complex[n]; org.apache.commons.math.transform.FastFourierTransformer.verifyDataSet(data); if (n == 1) { f[0] = data[0]; return f; } if (n == 2) { f[0] = data[0].add(data[1]); f[1] = data[0].subtract(data[1]); return f; } int ii = 0; for (int i = 0 ; i < n ; i++) { f[i] = data[ii]; int k = n >> 1; while ((ii >= k) && (k > 0)) { ii -= k; k >>= 1; } ii += k; } for (int i = 0 ; i < n ; i += 4) { final org.apache.commons.math.complex.Complex a = f[i].add(f[(i + 1)]); final org.apache.commons.math.complex.Complex b = f[(i + 2)].add(f[(i + 3)]); final org.apache.commons.math.complex.Complex c = f[i].subtract(f[(i + 1)]); final org.apache.commons.math.complex.Complex d = f[(i + 2)].subtract(f[(i + 3)]); final org.apache.commons.math.complex.Complex e1 = c.add(d.multiply(org.apache.commons.math.complex.Complex.I)); final org.apache.commons.math.complex.Complex e2 = c.subtract(d.multiply(org.apache.commons.math.complex.Complex.I)); f[i] = a.add(b); f[(i + 2)] = a.subtract(b); f[(i + 1)] = roots.isForward() ? e2 : e1; f[(i + 3)] = roots.isForward() ? e1 : e2; } for (int i = 4 ; i < n ; i <<= 1) { final int m = n / (i << 1); for (int j = 0 ; j < n ; j += i << 1) { for (int k = 0 ; k < i ; k++) { final int k_times_m = k * m; final double omega_k_times_m_real = roots.getOmegaReal(k_times_m); final double omega_k_times_m_imaginary = roots.getOmegaImaginary(k_times_m); final org.apache.commons.math.complex.Complex z = new org.apache.commons.math.complex.Complex((((f[((i + j) + k)].getReal()) * omega_k_times_m_real) - ((f[((i + j) + k)].getImaginary()) * omega_k_times_m_imaginary)) , (((f[((i + j) + k)].getReal()) * omega_k_times_m_imaginary) + ((f[((i + j) + k)].getImaginary()) * omega_k_times_m_real))); f[((i + j) + k)] = f[(j + k)].subtract(z); f[(j + k)] = f[(j + k)].add(z); } } } return f; } public static double[] sample(org.apache.commons.math.analysis.UnivariateRealFunction f, double min, double max, int n) throws java.lang.IllegalArgumentException, org.apache.commons.math.FunctionEvaluationException { if (n <= 0) { throw org.apache.commons.math.MathRuntimeException.createIllegalArgumentException("number of sample is not positive: {0}", n); } org.apache.commons.math.transform.FastFourierTransformer.verifyInterval(min, max); double[] s = new double[n]; double h = (max - min) / n; for (int i = 0 ; i < n ; i++) { s[i] = f.value((min + (i * h))); } return s; } public static double[] scaleArray(double[] f, double d) { for (int i = 0 ; i < (f.length) ; i++) { f[i] *= d; } return f; } public static org.apache.commons.math.complex.Complex[] scaleArray(org.apache.commons.math.complex.Complex[] f, double d) { for (int i = 0 ; i < (f.length) ; i++) { f[i] = new org.apache.commons.math.complex.Complex((d * (f[i].getReal())) , (d * (f[i].getImaginary()))); } return f; } public static boolean isPowerOf2(long n) { return (n > 0) && ((n & (n - 1)) == 0); } public static void verifyDataSet(double[] d) throws java.lang.IllegalArgumentException { if (!(org.apache.commons.math.transform.FastFourierTransformer.isPowerOf2(d.length))) { throw org.apache.commons.math.MathRuntimeException.createIllegalArgumentException(NOT_POWER_OF_TWO_MESSAGE, d.length); } } public static void verifyDataSet(java.lang.Object[] o) throws java.lang.IllegalArgumentException { if (!(org.apache.commons.math.transform.FastFourierTransformer.isPowerOf2(o.length))) { throw org.apache.commons.math.MathRuntimeException.createIllegalArgumentException(NOT_POWER_OF_TWO_MESSAGE, o.length); } } public static void verifyInterval(double lower, double upper) throws java.lang.IllegalArgumentException { if (lower >= upper) { throw org.apache.commons.math.MathRuntimeException.createIllegalArgumentException("endpoints do not specify an interval: [{0}, {1}]", lower, upper); } } public java.lang.Object mdfft(java.lang.Object mdca, boolean forward) throws java.lang.IllegalArgumentException { org.apache.commons.math.transform.FastFourierTransformer.MultiDimensionalComplexMatrix mdcm = ((org.apache.commons.math.transform.FastFourierTransformer.MultiDimensionalComplexMatrix)(new org.apache.commons.math.transform.FastFourierTransformer.MultiDimensionalComplexMatrix(mdca).clone())); int[] dimensionSize = mdcm.getDimensionSizes(); for (int i = 0 ; i < (dimensionSize.length) ; i++) { mdfft(mdcm, forward, i, new int[0]); } return mdcm.getArray(); } private void mdfft(org.apache.commons.math.transform.FastFourierTransformer.MultiDimensionalComplexMatrix mdcm, boolean forward, int d, int[] subVector) throws java.lang.IllegalArgumentException { int[] dimensionSize = mdcm.getDimensionSizes(); if ((subVector.length) == (dimensionSize.length)) { org.apache.commons.math.complex.Complex[] temp = new org.apache.commons.math.complex.Complex[dimensionSize[d]]; for (int i = 0 ; i < (dimensionSize[d]) ; i++) { subVector[d] = i; temp[i] = mdcm.get(subVector); } if (forward) temp = transform2(temp); else temp = inversetransform2(temp); for (int i = 0 ; i < (dimensionSize[d]) ; i++) { subVector[d] = i; mdcm.set(temp[i], subVector); } } else { int[] vector = new int[(subVector.length) + 1]; java.lang.System.arraycopy(subVector, 0, vector, 0, subVector.length); if ((subVector.length) == d) { vector[d] = 0; mdfft(mdcm, forward, d, vector); } else { for (int i = 0 ; i < (dimensionSize[subVector.length]) ; i++) { vector[subVector.length] = i; mdfft(mdcm, forward, d, vector); } } } return ; } private static class MultiDimensionalComplexMatrix implements java.lang.Cloneable { protected int[] dimensionSize; protected java.lang.Object multiDimensionalComplexArray; public MultiDimensionalComplexMatrix(java.lang.Object multiDimensionalComplexArray) { this.multiDimensionalComplexArray = multiDimensionalComplexArray; int numOfDimensions = 0; for (java.lang.Object lastDimension = multiDimensionalComplexArray ; lastDimension instanceof java.lang.Object[] ; ) { final java.lang.Object[] array = ((java.lang.Object[])(lastDimension)); numOfDimensions++; lastDimension = array[0]; } dimensionSize = new int[numOfDimensions]; numOfDimensions = 0; for (java.lang.Object lastDimension = multiDimensionalComplexArray ; lastDimension instanceof java.lang.Object[] ; ) { final java.lang.Object[] array = ((java.lang.Object[])(lastDimension)); dimensionSize[numOfDimensions++] = array.length; lastDimension = array[0]; } } public org.apache.commons.math.complex.Complex get(int... vector) throws java.lang.IllegalArgumentException { if (vector == null) { if ((dimensionSize.length) > 0) { throw org.apache.commons.math.MathRuntimeException.createIllegalArgumentException(org.apache.commons.math.transform.FastFourierTransformer.DIMENSION_MISMATCH_MESSAGE, 0, dimensionSize.length); } return null; } if ((vector.length) != (dimensionSize.length)) { throw org.apache.commons.math.MathRuntimeException.createIllegalArgumentException(org.apache.commons.math.transform.FastFourierTransformer.DIMENSION_MISMATCH_MESSAGE, vector.length, dimensionSize.length); } java.lang.Object lastDimension = multiDimensionalComplexArray; for (int i = 0 ; i < (dimensionSize.length) ; i++) { lastDimension = ((java.lang.Object[])(lastDimension))[vector[i]]; } return ((org.apache.commons.math.complex.Complex)(lastDimension)); } public org.apache.commons.math.complex.Complex set(org.apache.commons.math.complex.Complex magnitude, int... vector) throws java.lang.IllegalArgumentException { if (vector == null) { if ((dimensionSize.length) > 0) { throw org.apache.commons.math.MathRuntimeException.createIllegalArgumentException(org.apache.commons.math.transform.FastFourierTransformer.DIMENSION_MISMATCH_MESSAGE, 0, dimensionSize.length); } return null; } if ((vector.length) != (dimensionSize.length)) { throw org.apache.commons.math.MathRuntimeException.createIllegalArgumentException(org.apache.commons.math.transform.FastFourierTransformer.DIMENSION_MISMATCH_MESSAGE, vector.length, dimensionSize.length); } java.lang.Object[] lastDimension = ((java.lang.Object[])(multiDimensionalComplexArray)); for (int i = 0 ; i < ((dimensionSize.length) - 1) ; i++) { lastDimension = ((java.lang.Object[])(lastDimension[vector[i]])); } org.apache.commons.math.complex.Complex lastValue = ((org.apache.commons.math.complex.Complex)(lastDimension[vector[((dimensionSize.length) - 1)]])); lastDimension[vector[((dimensionSize.length) - 1)]] = magnitude; return lastValue; } public int[] getDimensionSizes() { return dimensionSize.clone(); } public java.lang.Object getArray() { return multiDimensionalComplexArray; } @java.lang.Override public java.lang.Object clone() { org.apache.commons.math.transform.FastFourierTransformer.MultiDimensionalComplexMatrix mdcm = new org.apache.commons.math.transform.FastFourierTransformer.MultiDimensionalComplexMatrix(java.lang.reflect.Array.newInstance(org.apache.commons.math.complex.Complex.class, dimensionSize)); clone(mdcm); return mdcm; } private void clone(org.apache.commons.math.transform.FastFourierTransformer.MultiDimensionalComplexMatrix mdcm) { int[] vector = new int[dimensionSize.length]; int size = 1; for (int i = 0 ; i < (dimensionSize.length) ; i++) { size *= dimensionSize[i]; } int[][] vectorList = new int[size][dimensionSize.length]; for (int[] nextVector : vectorList) { java.lang.System.arraycopy(vector, 0, nextVector, 0, dimensionSize.length); for (int i = 0 ; i < (dimensionSize.length) ; i++) { (vector[i])++; if ((vector[i]) < (dimensionSize[i])) { break; } else { vector[i] = 0; } } } for (int[] nextVector : vectorList) { mdcm.set(get(nextVector), nextVector); } } } private static class RootsOfUnity implements java.io.Serializable { private static final long serialVersionUID = 6404784357747329667L; private int omegaCount; private double[] omegaReal; private double[] omegaImaginaryForward; private double[] omegaImaginaryInverse; private boolean isForward; public RootsOfUnity() { omegaCount = 0; omegaReal = null; omegaImaginaryForward = null; omegaImaginaryInverse = null; isForward = true; } public synchronized boolean isForward() throws java.lang.IllegalStateException { if ((omegaCount) == 0) { throw org.apache.commons.math.MathRuntimeException.createIllegalStateException(org.apache.commons.math.transform.FastFourierTransformer.MISSING_ROOTS_OF_UNITY_MESSAGE); } return isForward; } public synchronized void computeOmega(int n) throws java.lang.IllegalArgumentException { if (n == 0) { throw org.apache.commons.math.MathRuntimeException.createIllegalArgumentException("cannot compute 0-th root of unity, indefinite result"); } isForward = n > 0; final int absN = java.lang.Math.abs(n); if (absN == (omegaCount)) { return ; } final double t = (2.0 * (java.lang.Math.PI)) / absN; final double cosT = java.lang.Math.cos(t); final double sinT = java.lang.Math.sin(t); omegaReal = new double[absN]; omegaImaginaryForward = new double[absN]; omegaImaginaryInverse = new double[absN]; omegaReal[0] = 1.0; omegaImaginaryForward[0] = 0.0; omegaImaginaryInverse[0] = 0.0; for (int i = 1 ; i < absN ; i++) { omegaReal[i] = ((omegaReal[(i - 1)]) * cosT) + ((omegaImaginaryForward[(i - 1)]) * sinT); omegaImaginaryForward[i] = ((omegaImaginaryForward[(i - 1)]) * cosT) - ((omegaReal[(i - 1)]) * sinT); omegaImaginaryInverse[i] = -(omegaImaginaryForward[i]); } omegaCount = absN; } public synchronized double getOmegaReal(int k) throws java.lang.IllegalArgumentException, java.lang.IllegalStateException { if ((omegaCount) == 0) { throw org.apache.commons.math.MathRuntimeException.createIllegalStateException(org.apache.commons.math.transform.FastFourierTransformer.MISSING_ROOTS_OF_UNITY_MESSAGE); } if ((k < 0) || (k >= (omegaCount))) { throw org.apache.commons.math.MathRuntimeException.createIllegalArgumentException(org.apache.commons.math.transform.FastFourierTransformer.OUT_OF_RANGE_ROOT_INDEX_MESSAGE, k, 0, ((omegaCount) - 1)); } return omegaReal[k]; } public synchronized double getOmegaImaginary(int k) throws java.lang.IllegalArgumentException, java.lang.IllegalStateException { if ((omegaCount) == 0) { throw org.apache.commons.math.MathRuntimeException.createIllegalStateException(org.apache.commons.math.transform.FastFourierTransformer.MISSING_ROOTS_OF_UNITY_MESSAGE); } if ((k < 0) || (k >= (omegaCount))) { throw org.apache.commons.math.MathRuntimeException.createIllegalArgumentException(org.apache.commons.math.transform.FastFourierTransformer.OUT_OF_RANGE_ROOT_INDEX_MESSAGE, k, 0, ((omegaCount) - 1)); } return isForward ? omegaImaginaryForward[k] : omegaImaginaryInverse[k]; } } }
SpoonLabs/astor
examples/evo_suite_test/math_70_spooned/src/default/org/apache/commons/math/transform/FastFourierTransformer.java
Java
gpl-2.0
20,313
export { EncounterArmor } from './encounter_armor.js'; export { EncounterCoins } from './encounter_coins.js'; export { EncounterItem } from './encounter_item.js'; export { EncounterMagicItem } from './encounter_magic_item.js'; export { EncounterWeapon } from './encounter_weapon.js'; export { EnvironmentSection } from './environment_section.js'; export { Environment } from './environment.js'; export { MapsAndImagesSection } from './maps_and_images_section.js'; export { MonsterAbilityScore } from './monster_ability_score.js'; export { MonsterSection } from './monster_section.js'; export { Monster } from './monster.js'; export { NotesSection } from './notes_section.js'; export { NPCSection } from './npc_section.js'; export { NPC } from './npc.js'; export { PlayerTextSection } from './player_text_section.js'; export { PlayerText } from './player_text.js'; export { PointOfInterestSection } from './point_of_interest_section.js'; export { PointOfInterest } from './point_of_interest.js'; export { TreasureSection } from './treasure_section.js';
charactersheet/charactersheet
src/charactersheet/models/dm/encounter_sections/index.js
JavaScript
gpl-2.0
1,069
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.epl.enummethod.dot; import com.espertech.esper.client.EventBean; import com.espertech.esper.client.EventPropertyGetter; import com.espertech.esper.client.EventType; import com.espertech.esper.epl.expression.ExprEvaluatorContext; import com.espertech.esper.epl.expression.ExprEvaluatorEnumeration; import com.espertech.esper.epl.expression.ExprValidationException; import com.espertech.esper.event.EventAdapterService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Collection; public class PropertyExprEvaluatorScalarCollection implements ExprEvaluatorEnumeration { private static final Log log = LogFactory.getLog(PropertyExprEvaluatorScalarCollection.class); private final String propertyName; private final int streamId; private final EventPropertyGetter getter; private final Class componentType; public PropertyExprEvaluatorScalarCollection(String propertyName, int streamId, EventPropertyGetter getter, Class componentType) { this.propertyName = propertyName; this.streamId = streamId; this.getter = getter; this.componentType = componentType; } public Collection<EventBean> evaluateGetROCollectionEvents(EventBean[] eventsPerStream, boolean isNewData, ExprEvaluatorContext context) { return null; } public Collection evaluateGetROCollectionScalar(EventBean[] eventsPerStream, boolean isNewData, ExprEvaluatorContext context) { EventBean eventInQuestion = eventsPerStream[streamId]; Object result = getter.get(eventInQuestion); if (result == null) { return null; } if (!(result instanceof Collection)) { log.warn("Expected collection-type input from property '" + propertyName + "' but received " + result.getClass()); return null; } return (Collection) getter.get(eventInQuestion); } public EventType getEventTypeCollection(EventAdapterService eventAdapterService) { return null; } public Class getComponentTypeCollection() throws ExprValidationException { return componentType; } public EventType getEventTypeSingle(EventAdapterService eventAdapterService, String statementId) throws ExprValidationException { return null; } public EventBean evaluateGetEventBean(EventBean[] eventsPerStream, boolean isNewData, ExprEvaluatorContext context) { return null; } }
mobile-event-processing/Asper
source/src/com/espertech/esper/epl/enummethod/dot/PropertyExprEvaluatorScalarCollection.java
Java
gpl-2.0
3,297
<?php namespace EBT\ExtensionBuilder\Configuration; /*************************************************************** * Copyright notice * * (c) 2010 Nico de Haen * All rights reserved * * * This script is part of the TYPO3 project. The TYPO3 project 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. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * * This script 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. * * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ use TYPO3\CMS\Backend\Utility\BackendUtility; use TYPO3\CMS\Core\Http\AjaxRequestHandler; use TYPO3\CMS\Core\Utility\ExtensionManagementUtility; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface; /** * Load settings from yaml file and from TYPO3_CONF_VARS extConf */ class ConfigurationManager extends \TYPO3\CMS\Extbase\Configuration\ConfigurationManager { /** * @var string */ const SETTINGS_DIR = 'Configuration/ExtensionBuilder/'; /** * @var string */ const EXTENSION_BUILDER_SETTINGS_FILE = 'ExtensionBuilder.json'; /** * @var array */ private $inputData = array(); /** * Wrapper for file_get_contents('php://input') * * @return void */ public function parseRequest() { $jsonString = file_get_contents('php://input'); $this->inputData = json_decode($jsonString, TRUE); } /** * @return mixed */ public function getParamsFromRequest() { $params = $this->inputData['params']; return $params; } /** * Reads the configuration from this->inputData and returns it as array. * * @throws \Exception * @return array */ public function getConfigurationFromModeler() { if (empty($this->inputData)) { throw new \Exception('No inputData!'); } $extensionConfigurationJson = json_decode($this->inputData['params']['working'], TRUE); $extensionConfigurationJson = $this->reArrangeRelations($extensionConfigurationJson); $extensionConfigurationJson['modules'] = $this->checkForAbsoluteClassNames($extensionConfigurationJson['modules']); return $extensionConfigurationJson; } /** * @return mixed */ public function getSubActionFromRequest() { $subAction = $this->inputData['method']; return $subAction; } /** * Set settings from various sources: * * - Settings configured in module.extension_builder typoscript * - Module settings configured in the extension manager * * @param array $typoscript (optional) */ public function getSettings($typoscript = NULL) { if ($typoscript == NULL) { $typoscript = $this->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT); } $settings = $typoscript['module.']['extension_builder.']['settings.']; if (empty($settings['codeTemplateRootPath'])) { $settings['codeTemplateRootPath'] = 'EXT:extension_builder/Resources/Private/CodeTemplates/Extbase/'; } $settings['codeTemplateRootPath'] = self::substituteExtensionPath($settings['codeTemplateRootPath']); $settings['extConf'] = $this->getExtensionBuilderSettings(); return $settings; } /** * Get the extension_builder configuration (ext_template_conf). * * @return array */ public function getExtensionBuilderSettings() { $settings = array(); if (!empty($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['extension_builder'])) { $settings = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['extension_builder']); } return $settings; } /** * @param string $extensionKey * @return array settings */ public function getExtensionSettings($extensionKey) { $settings = array(); $settingsFile = $this->getSettingsFile($extensionKey); if (file_exists($settingsFile)) { $yamlParser = new \EBT\ExtensionBuilder\Utility\SpycYAMLParser(); $settings = $yamlParser->YAMLLoadString(file_get_contents($settingsFile)); } else { GeneralUtility::devlog('No settings found: ' . $settingsFile, 'extension_builder', 2); } return $settings; } /** * Reads the stored configuration (i.e. the extension model etc.). * * @param string $extensionKey * @return array|NULL */ public function getExtensionBuilderConfiguration($extensionKey) { $result = NULL; $jsonFile = PATH_typo3conf . 'ext/' . $extensionKey . '/' . self::EXTENSION_BUILDER_SETTINGS_FILE; if (file_exists($jsonFile)) { $extensionConfigurationJson = json_decode(file_get_contents($jsonFile), TRUE); $extensionConfigurationJson = $this->fixExtensionBuilderJSON($extensionConfigurationJson); $extensionConfigurationJson['properties']['originalExtensionKey'] = $extensionKey; if (floatval($extensionConfigurationJson['log']['extension_builder_version']) >= 2.5) { $result = $extensionConfigurationJson; } } return $result; } /** * This is mainly copied from DataMapFactory. * * @param string $className * @return array with configuration values */ public function getExtbaseClassConfiguration($className) { $classConfiguration = array(); if (strpos($className, '\\') === 0) { $className = substr($className, 1); } $frameworkConfiguration = $this->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK); $classSettings = $frameworkConfiguration['persistence']['classes'][$className]; if ($classSettings !== NULL) { if (isset($classSettings['subclasses']) && is_array($classSettings['subclasses'])) { $classConfiguration['subclasses'] = $classSettings['subclasses']; } if (isset($classSettings['mapping']['recordType']) && strlen($classSettings['mapping']['recordType']) > 0) { $classConfiguration['recordType'] = $classSettings['mapping']['recordType']; } if (isset($classSettings['mapping']['tableName']) && strlen($classSettings['mapping']['tableName']) > 0) { $classConfiguration['tableName'] = $classSettings['mapping']['tableName']; } $classHierachy = array_merge(array($className), class_parents($className)); $columnMapping = array(); foreach ($classHierachy as $currentClassName) { if (in_array( $currentClassName, array( 'TYPO3\\CMS\\Extbase\\DomainObject\\AbstractEntity', 'TYPO3\\CMS\\Extbase\\DomainObject\\AbstractValueObject' ) )) { break; } $currentClassSettings = $frameworkConfiguration['persistence']['classes'][$currentClassName]; if ($currentClassSettings !== NULL) { if (isset($currentClassSettings['mapping']['columns']) && is_array($currentClassSettings['mapping']['columns'])) { GeneralUtility::array_merge_recursive_overrule( $columnMapping, $currentClassSettings['mapping']['columns'], 0, // FALSE means: do not include empty values form 2nd array FALSE ); } } } } return $classConfiguration; } /** * Get the file name and path of the settings file. * * @param string $extensionKey * @return string path */ public function getSettingsFile($extensionKey) { $extensionDir = PATH_typo3conf . 'ext/' . $extensionKey . '/'; return $extensionDir . self::SETTINGS_DIR . 'settings.yaml'; } /** * @param \EBT\ExtensionBuilder\Domain\Model\Extension $extension * @param string $codeTemplateRootPath * @return void */ public function createInitialSettingsFile($extension, $codeTemplateRootPath) { GeneralUtility::mkdir_deep($extension->getExtensionDir(), self::SETTINGS_DIR); $settings = file_get_contents($codeTemplateRootPath . 'Configuration/ExtensionBuilder/settings.yamlt'); $settings = str_replace('{extension.extensionKey}', $extension->getExtensionKey(), $settings); $settings = str_replace('{f:format.date(format:\'Y-m-d\\TH:i:s\\Z\',date:\'now\')}', date('Y-m-d\TH:i:s\Z'), $settings); GeneralUtility::writeFile( $extension->getExtensionDir() . self::SETTINGS_DIR . 'settings.yaml', $settings ); } /** * Replace the EXT:extkey prefix with the appropriate path. * * @param string $encodedTemplateRootPath * @return string */ static public function substituteExtensionPath($encodedTemplateRootPath) { $result = ''; if (GeneralUtility::isFirstPartOfStr($encodedTemplateRootPath, 'EXT:')) { list($extKey, $script) = explode('/', substr($encodedTemplateRootPath, 4), 2); if ($extKey && ExtensionManagementUtility::isLoaded($extKey)) { $result = ExtensionManagementUtility::extPath($extKey) . $script; } } elseif (GeneralUtility::isAbsPath($encodedTemplateRootPath)) { $result = $encodedTemplateRootPath; } else { $result = PATH_site . $encodedTemplateRootPath; } return $result; } /** * Performs various fixes/workarounds for wireit limitations. * * @param array $extensionConfigurationJson * @return array the modified configuration */ public function fixExtensionBuilderJSON($extensionConfigurationJson) { $extensionConfigurationJson['modules'] = $this->resetOutboundedPositions($extensionConfigurationJson['modules']); $extensionConfigurationJson['modules'] = $this->mapAdvancedMode($extensionConfigurationJson['modules']); $extensionConfigurationJson = $this->reArrangeRelations($extensionConfigurationJson); return $extensionConfigurationJson; } /** * Copy values from simple mode fieldset to advanced fieldset. * * Enables compatibility with JSON from older versions of the extension builder. * * @param array $jsonConfig * @param boolean $prepareForModeler * * @return array modified json */ protected function mapAdvancedMode($jsonConfig, $prepareForModeler = TRUE) { $fieldsToMap = array( 'relationType', 'propertyIsExcludeField', 'propertyIsExcludeField', 'lazyLoading', 'relationDescription', 'foreignRelationClass' ); foreach ($jsonConfig as &$module) { for ($i = 0; $i < count($module['value']['relationGroup']['relations']); $i++) { if ($prepareForModeler) { if (empty($module['value']['relationGroup']['relations'][$i]['advancedSettings'])) { $module['value']['relationGroup']['relations'][$i]['advancedSettings'] = array(); foreach ($fieldsToMap as $fieldToMap) { $module['value']['relationGroup']['relations'][$i]['advancedSettings'][$fieldToMap] = $module['value']['relationGroup']['relations'][$i][$fieldToMap]; } $module['value']['relationGroup']['relations'][$i]['advancedSettings']['propertyIsExcludeField'] = $module['value']['relationGroup']['relations'][$i]['propertyIsExcludeField']; $module['value']['relationGroup']['relations'][$i]['advancedSettings']['lazyLoading'] = $module['value']['relationGroup']['relations'][$i]['lazyLoading']; $module['value']['relationGroup']['relations'][$i]['advancedSettings']['relationDescription'] = $module['value']['relationGroup']['relations'][$i]['relationDescription']; $module['value']['relationGroup']['relations'][$i]['advancedSettings']['foreignRelationClass'] = $module['value']['relationGroup']['relations'][$i]['foreignRelationClass']; } } elseif (isset($module['value']['relationGroup']['relations'][$i]['advancedSettings'])) { foreach ($fieldsToMap as $fieldToMap) { $module['value']['relationGroup']['relations'][$i][$fieldToMap] = $module['value']['relationGroup']['relations'][$i]['advancedSettings'][$fieldToMap]; } unset($module['value']['relationGroup']['relations'][$i]['advancedSettings']); } } } return $jsonConfig; } /** * Prefixes class names with a backslash to ensure that always fully qualified * class names are used. * * @param $moduleConfig * @return mixed */ protected function checkForAbsoluteClassNames($moduleConfig) { foreach ($moduleConfig as &$module) { if (!empty($module['value']['objectsettings']['parentClass']) && strpos($module['value']['objectsettings']['parentClass'], '\\') !== 0) { // namespaced classes always need a full qualified class name $module['value']['objectsettings']['parentClass'] = '\\' . $module['value']['objectsettings']['parentClass']; } } return $moduleConfig; } /** * Check if the confirm was send with input data. * * @param string $identifier * @return boolean */ public function isConfirmed($identifier) { if (isset($this->inputData['params'][$identifier]) && $this->inputData['params'][$identifier] == 1 ) { return TRUE; } return FALSE; } /** * Just a temporary workaround until the new UI is available. * * @param array $jsonConfig * @return array */ protected function resetOutboundedPositions($jsonConfig) { foreach ($jsonConfig as &$module) { if ($module['config']['position'][0] < 0) { $module['config']['position'][0] = 10; } if ($module['config']['position'][1] < 0) { $module['config']['position'][1] = 10; } } return $jsonConfig; } /** * This is a workaround for the bad design in WireIt. All wire terminals are * only identified by a simple index, that does not reflect deleting of models * and relations. * * @param array $jsonConfig * @return array */ protected function reArrangeRelations($jsonConfig) { foreach ($jsonConfig['wires'] as &$wire) { // format: relation_1 $parts = explode('_', $wire['src']['terminal']); $supposedRelationIndex = $parts[1]; $uid = $wire['src']['uid']; $wire['src'] = self::findModuleIndexByRelationUid( $wire['src']['uid'], $jsonConfig['modules'], $wire['src']['moduleId'], $supposedRelationIndex ); $wire['src']['uid'] = $uid; $uid = $wire['tgt']['uid']; $wire['tgt'] = self::findModuleIndexByRelationUid( $wire['tgt']['uid'], $jsonConfig['modules'], $wire['tgt']['moduleId'] ); $wire['tgt']['uid'] = $uid; } return $jsonConfig; } /** * @param int $uid * @param array $modules * @param int $supposedModuleIndex * @param int $supposedRelationIndex * @return array */ protected function findModuleIndexByRelationUid($uid, $modules, $supposedModuleIndex, $supposedRelationIndex = NULL) { $result = array( 'moduleId' => $supposedModuleIndex ); if ($supposedRelationIndex == NULL) { $result['terminal'] = 'SOURCES'; if ($modules[$supposedModuleIndex]['value']['objectsettings']['uid'] == $uid) { // everything as expected return $result; } else { $moduleCounter = 0; foreach ($modules as $module) { if ($module['value']['objectsettings']['uid'] == $uid) { $result['moduleId'] = $moduleCounter; return $result; } } } } elseif ($modules[$supposedModuleIndex]['value']['relationGroup']['relations'][$supposedRelationIndex]['uid'] == $uid) { $result['terminal'] = 'relationWire_' . $supposedRelationIndex; // everything as expected return $result; } else { $moduleCounter = 0; foreach ($modules as $module) { $relationCounter = 0; foreach ($module['value']['relationGroup']['relations'] as $relation) { if ($relation['uid'] == $uid) { $result['moduleId'] = $moduleCounter; $result['terminal'] = 'relationWire_' . $relationCounter; return $result; } $relationCounter++; } $moduleCounter++; } } return $result; } public function getParentClassForValueObject($extensionKey) { $settings = self::getExtensionSettings($extensionKey); if (isset($settings['classBuilder']['Model']['AbstractValueObject']['parentClass'])) { $parentClass = $settings['classBuilder']['Model']['AbstractValueObject']['parentClass']; } else { $parentClass = '\\TYPO3\\CMS\\Extbase\\DomainObject\\AbstractValueObject'; } return $parentClass; } public function getParentClassForEntityObject($extensionKey) { $settings = self::getExtensionSettings($extensionKey); if (isset($settings['classBuilder']['Model']['AbstractEntity']['parentClass'])) { $parentClass = $settings['classBuilder']['Model']['AbstractEntity']['parentClass']; } else { $parentClass = '\\TYPO3\\CMS\\Extbase\\DomainObject\\AbstractEntity'; } return $parentClass; } /** * Ajax callback that reads the smd file and modiefies the target URL to include * the module token. * * @param array $parameters (unused) * @param \TYPO3\CMS\Core\Http\AjaxRequestHandler $ajaxRequestHandler * @return void */ public function getWiringEditorSmd(array $parameters, AjaxRequestHandler $ajaxRequestHandler) { $smdJsonString = file_get_contents( ExtensionManagementUtility::extPath('extension_builder') . 'Resources/Public/jsDomainModeling/phpBackend/WiringEditor.smd' ); $smdJson = json_decode($smdJsonString); $parameters = array( 'tx_extensionbuilder_tools_extensionbuilderextensionbuilder' => array( 'controller' => 'BuilderModule', 'action' => 'dispatchRpc', ) ); $smdJson->target = BackendUtility::getModuleUrl('tools_ExtensionBuilderExtensionbuilder', $parameters); $smdJsonString = json_encode($smdJson); $ajaxRequestHandler->setContent(array($smdJsonString)); } }
mouadben/typo6
typo3conf/ext/extension_builder/Classes/Configuration/ConfigurationManager.php
PHP
gpl-2.0
17,359
<?php /** * The template part for displaying a message that posts cannot be found. * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package Konmi */ ?> <section class="no-results not-found"> <header class="page-header"> <h1 class="page-title"><?php _e( 'Nothing Found', 'konmi' ); ?></h1> </header><!-- .page-header --> <div class="page-content"> <?php if ( is_home() && current_user_can( 'publish_posts' ) ) : ?> <p><?php printf( __( 'Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'konmi' ), esc_url( admin_url( 'post-new.php' ) ) ); ?></p> <?php elseif ( is_search() ) : ?> <p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'konmi' ); ?></p> <?php get_search_form(); ?> <?php else : ?> <p><?php _e( 'It seems we can&rsquo;t find what you&rsquo;re looking for. Perhaps searching can help.', 'konmi' ); ?></p> <?php get_search_form(); ?> <?php endif; ?> </div><!-- .page-content --> </section><!-- .no-results -->
quixoticduck/liz-website
wp-content/themes/konmi/content-none.php
PHP
gpl-2.0
1,061
<?php if (!defined('APPLICATION')) exit(); $Definition['Addon-Type'] = 'Addon-Type'; $Definition['Download-URL'] = 'Download-URL'; $Definition['Install'] = 'Install'; $Definition['Locale.Usage'] = 'Copy the URL of the Addon you want to install and paste it into the textfield below. Browse <a href="http://vanillaforums.org/addons">Vanilla Addon Page</a> to find URLs. You can also use the big IFRAME.'; $Definition['Plugin Addon'] = 'Plugin Addon)'; $Definition['Theme Addon'] = 'Theme Addon'; // $Definition['Locale Addon'] = 'Locale Addon'; $Definition['Application Addon'] = 'Application Addon'; $Definition['Error while unzipping.'] = 'Error while unzipping.'; $Definition['Addon has been successfully installed.'] = 'Addon has been successfully installed.'; $Definition['Addon already exists.'] = 'Addon already exists.'; $Definition['Addon has to be an ZIP file.'] = 'Addon has to be an ZIP file.';
ru4/arabbnota
plugins/AddonManager/locale/en-CA.php
PHP
gpl-2.0
908
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2011, 2012 CERN. # # Invenio 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. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """JSON utilities.""" import re import sys if sys.hexversion < 0x2060000: try: import simplejson as json CFG_JSON_AVAILABLE = True except ImportError: # Okay, no Ajax app will be possible, but continue anyway, # since this package is only recommended, not mandatory. CFG_JSON_AVAILABLE = False json = None else: import json CFG_JSON_AVAILABLE = True def json_unicode_to_utf8(data): """Change all strings in a JSON structure to UTF-8.""" if type(data) == unicode: return data.encode('utf-8') elif type(data) == dict: newdict = {} for key in data: newdict[json_unicode_to_utf8(key)] = json_unicode_to_utf8(data[key]) return newdict elif type(data) == list: return [json_unicode_to_utf8(elem) for elem in data] else: return data def json_decode_file(filename): """ Parses a textfile using json to build a python object representation """ seq = open(filename).read() ## The JSON standard has no comments syntax. We have to remove them ## before feeding python's JSON parser seq = json_remove_comments(seq) ## Parse all the unicode stuff to utf-8 return json_unicode_to_utf8(json.loads(seq)) def json_remove_comments(text): """ Removes C style comments from the given string. Will keep newline characters intact. This way parsing errors from json will point to the right line. This is primarily used to make comments in JSON files possible. The JSON standard has no comments syntax, but we want to use JSON for our profiles and configuration files. The comments need to be removed first, before the text can be feed to the JSON parser of python. @param text: JSON string that should be cleaned @type text: string @return: Cleaned JSON @rtype: string """ def replacer(match): s = match.group(0) if s.startswith('/'): return "" else: return s pattern = re.compile( r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"', re.DOTALL | re.MULTILINE ) return re.sub(pattern, replacer, text) def wash_for_js(text): """ DEPRECATED: use htmlutils.escape_javascript_string() instead, and take note that returned value is no longer enclosed into quotes. """ from invenio.htmlutils import escape_javascript_string if isinstance(text, basestring): return '"%s"' % escape_javascript_string(text, escape_for_html=False, escape_CDATA=False, escape_script_tag_with_quote=None) else: return text
CERNDocumentServer/invenio
modules/miscutil/lib/jsonutils.py
Python
gpl-2.0
3,590
<?php /** * Lexicon English lexicon topic * * @language en * @package modx * @subpackage lexicon */ $_lang['duplicate'] = 'مكرر'; $_lang['entry'] = 'مدخل'; $_lang['entry_create'] = 'إنشاء مدخل'; $_lang['entry_err_ae'] = 'المدخل موجود مسبقاً!'; $_lang['entry_err_nf'] = 'المدخل غير موجود.'; $_lang['entry_err_ns'] = 'لم يتم تحديد المدخل.'; $_lang['entry_err_save'] = 'حدث خطأ أثناء محاولة حفظ مدخل المعجم.'; $_lang['entry_revert'] = 'تراجع عن مدخل المعجم'; $_lang['language'] = 'اللغة'; $_lang['languages'] = 'اللغات'; $_lang['last_modified'] = 'آخر تعديل في'; $_lang['lexicon'] = 'معجم'; $_lang['lexicon_export'] = 'تصدير الموضوع'; $_lang['lexicon_export_desc'] = 'هنا يمكنك تحديد موضوع من المعجم لتصديره إلى ملف.'; $_lang['lexicon_topics'] = 'مواضيع المعجم'; $_lang['lexicon_topics_desc'] = 'هنا يمكنك ادارة مواضيع المعجم.'; $_lang['lexicon_import'] = 'استيراد موضوع'; $_lang['lexicon_import_desc'] = 'تستطيع استيراد ملف لتحميله إلى معجم مواضيع محدد من أجل فضاء الأسماء. الملف الخاص بك يجب أن يرد مصفوفة ترابطية من السلاسل الخطية $_lang، مشابة لملفات core/lexicon. اذا كان الموضوع ضمن فضاء الأسماء موجود مسبقاً، سوف يتم الكتابة فوقه.'; $_lang['lexicon_import_err_ns'] = 'موضوع ملف المعجم لم يتم تحديده.'; $_lang['lexicon_import_err_upload'] = 'حدث خطأ أثناء محاولة رفع ملف موضوع معجم جديد. يرجى فحص صلاحيات مخدم الوب فيما يخص رفع ملف الى مجلد tmp . وقم أيضا بالتأكد من أن الملف الذي تحاول رفعه هو ملف صالح.'; $_lang['lexicon_management'] = 'أدارة المعجم'; $_lang['lexicon_management_desc'] = 'هنا يمكنك تجاوز اي مدخل معجم عبر فضاءات الاسماء ومايقابلها من مواضيع, قم بالضغط نقرتين على قيمة المدخل لتجاوزها. لإضافة مدخل جديد للقاموس او الموضوع فقط قم بإنشاء ملف للموضوع في فضاء الأسماء الخاص له في المجلد المقابل.'; $_lang['lexicon_rlfb_msg'] = 'تم بنجاح اعادة توليد [[+num]] سلسلة نصية.'; $_lang['reload_from_base'] = 'تراجع عن جميع الإدخالات الأساسية'; $_lang['reload_success'] = 'تم بنجاح اعادة تحميل [[+total]] سلسلة نصية.'; $_lang['search_by_key'] = 'البحث عن طريق المفتاح:'; $_lang['topic'] = 'الموضوع';
sergeiforward/gl
core_gl_xVCs4l0eEu/lexicon/ar/lexicon.inc.php
PHP
gpl-2.0
2,865
/* * Copyright (C) 2006, 2007, 2008 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 COMPUTER, 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 COMPUTER, 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 "ScrollView.h" #include "AXObjectCache.h" #include "GraphicsContext.h" #include "GraphicsLayer.h" #include "HostWindow.h" #include "PlatformMouseEvent.h" #include "PlatformWheelEvent.h" #include "ScrollAnimator.h" #include "Scrollbar.h" #include "ScrollbarTheme.h" #include <wtf/StdLibExtras.h> using namespace std; namespace WebCore { ScrollView::ScrollView() : m_horizontalScrollbarMode(ScrollbarAuto) , m_verticalScrollbarMode(ScrollbarAuto) , m_horizontalScrollbarLock(false) , m_verticalScrollbarLock(false) , m_prohibitsScrolling(false) , m_canBlitOnScroll(true) , m_scrollbarsAvoidingResizer(0) , m_scrollbarsSuppressed(false) , m_inUpdateScrollbars(false) , m_updateScrollbarsPass(0) , m_drawPanScrollIcon(false) , m_useFixedLayout(false) , m_paintsEntireContents(false) , m_clipsRepaints(true) , m_delegatesScrolling(false) , m_containsScrollableAreaWithOverlayScrollbars(false) { platformInit(); } ScrollView::~ScrollView() { platformDestroy(); } void ScrollView::addChild(PassRefPtr<Widget> prpChild) { Widget* child = prpChild.get(); ASSERT(child != this && !child->parent()); child->setParent(this); m_children.add(prpChild); if (child->platformWidget()) platformAddChild(child); } void ScrollView::removeChild(Widget* child) { ASSERT(child->parent() == this); child->setParent(0); m_children.remove(child); if (child->platformWidget()) platformRemoveChild(child); } void ScrollView::setHasHorizontalScrollbar(bool hasBar) { if (hasBar && avoidScrollbarCreation()) return; if (hasBar && !m_horizontalScrollbar) { m_horizontalScrollbar = createScrollbar(HorizontalScrollbar); addChild(m_horizontalScrollbar.get()); didAddHorizontalScrollbar(m_horizontalScrollbar.get()); m_horizontalScrollbar->styleChanged(); } else if (!hasBar && m_horizontalScrollbar) { willRemoveHorizontalScrollbar(m_horizontalScrollbar.get()); removeChild(m_horizontalScrollbar.get()); m_horizontalScrollbar = 0; } if (AXObjectCache::accessibilityEnabled() && axObjectCache()) axObjectCache()->handleScrollbarUpdate(this); } void ScrollView::setHasVerticalScrollbar(bool hasBar) { if (hasBar && avoidScrollbarCreation()) return; if (hasBar && !m_verticalScrollbar) { m_verticalScrollbar = createScrollbar(VerticalScrollbar); addChild(m_verticalScrollbar.get()); didAddVerticalScrollbar(m_verticalScrollbar.get()); m_verticalScrollbar->styleChanged(); } else if (!hasBar && m_verticalScrollbar) { willRemoveVerticalScrollbar(m_verticalScrollbar.get()); removeChild(m_verticalScrollbar.get()); m_verticalScrollbar = 0; } if (AXObjectCache::accessibilityEnabled() && axObjectCache()) axObjectCache()->handleScrollbarUpdate(this); } #if !USE(NATIVE_GTK_MAIN_FRAME_SCROLLBAR) PassRefPtr<Scrollbar> ScrollView::createScrollbar(ScrollbarOrientation orientation) { return Scrollbar::createNativeScrollbar(this, orientation, RegularScrollbar); } void ScrollView::setScrollbarModes(ScrollbarMode horizontalMode, ScrollbarMode verticalMode, bool horizontalLock, bool verticalLock) { bool needsUpdate = false; if (horizontalMode != horizontalScrollbarMode() && !m_horizontalScrollbarLock) { m_horizontalScrollbarMode = horizontalMode; needsUpdate = true; } if (verticalMode != verticalScrollbarMode() && !m_verticalScrollbarLock) { m_verticalScrollbarMode = verticalMode; needsUpdate = true; } if (horizontalLock) setHorizontalScrollbarLock(); if (verticalLock) setVerticalScrollbarLock(); if (!needsUpdate) return; if (platformWidget()) platformSetScrollbarModes(); else updateScrollbars(scrollOffset()); } #endif void ScrollView::scrollbarModes(ScrollbarMode& horizontalMode, ScrollbarMode& verticalMode) const { if (platformWidget()) { platformScrollbarModes(horizontalMode, verticalMode); return; } horizontalMode = m_horizontalScrollbarMode; verticalMode = m_verticalScrollbarMode; } void ScrollView::setCanHaveScrollbars(bool canScroll) { ScrollbarMode newHorizontalMode; ScrollbarMode newVerticalMode; scrollbarModes(newHorizontalMode, newVerticalMode); if (canScroll && newVerticalMode == ScrollbarAlwaysOff) newVerticalMode = ScrollbarAuto; else if (!canScroll) newVerticalMode = ScrollbarAlwaysOff; if (canScroll && newHorizontalMode == ScrollbarAlwaysOff) newHorizontalMode = ScrollbarAuto; else if (!canScroll) newHorizontalMode = ScrollbarAlwaysOff; setScrollbarModes(newHorizontalMode, newVerticalMode); } void ScrollView::setCanBlitOnScroll(bool b) { if (platformWidget()) { platformSetCanBlitOnScroll(b); return; } m_canBlitOnScroll = b; } bool ScrollView::canBlitOnScroll() const { if (platformWidget()) return platformCanBlitOnScroll(); return m_canBlitOnScroll; } void ScrollView::setPaintsEntireContents(bool paintsEntireContents) { m_paintsEntireContents = paintsEntireContents; } void ScrollView::setClipsRepaints(bool clipsRepaints) { m_clipsRepaints = clipsRepaints; } void ScrollView::setDelegatesScrolling(bool delegatesScrolling) { m_delegatesScrolling = delegatesScrolling; } #if !USE(NATIVE_GTK_MAIN_FRAME_SCROLLBAR) IntRect ScrollView::visibleContentRect(bool includeScrollbars) const { if (platformWidget()) return platformVisibleContentRect(includeScrollbars); if (paintsEntireContents()) return IntRect(IntPoint(0, 0), contentsSize()); int verticalScrollbarWidth = verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar() && !includeScrollbars ? verticalScrollbar()->width() : 0; int horizontalScrollbarHeight = horizontalScrollbar() && !horizontalScrollbar()->isOverlayScrollbar() && !includeScrollbars ? horizontalScrollbar()->height() : 0; return IntRect(IntPoint(m_scrollOffset.width(), m_scrollOffset.height()), IntSize(max(0, m_boundsSize.width() - verticalScrollbarWidth), max(0, m_boundsSize.height() - horizontalScrollbarHeight))); } #endif int ScrollView::layoutWidth() const { return m_fixedLayoutSize.isEmpty() || !m_useFixedLayout ? visibleWidth() : m_fixedLayoutSize.width(); } int ScrollView::layoutHeight() const { return m_fixedLayoutSize.isEmpty() || !m_useFixedLayout ? visibleHeight() : m_fixedLayoutSize.height(); } IntSize ScrollView::fixedLayoutSize() const { return m_fixedLayoutSize; } void ScrollView::setFixedLayoutSize(const IntSize& newSize) { if (fixedLayoutSize() == newSize) return; m_fixedLayoutSize = newSize; updateScrollbars(scrollOffset()); } bool ScrollView::useFixedLayout() const { return m_useFixedLayout; } void ScrollView::setUseFixedLayout(bool enable) { if (useFixedLayout() == enable) return; m_useFixedLayout = enable; updateScrollbars(scrollOffset()); } IntSize ScrollView::contentsSize() const { if (platformWidget()) return platformContentsSize(); return m_contentsSize; } void ScrollView::setContentsSize(const IntSize& newSize) { if (contentsSize() == newSize) return; m_contentsSize = newSize; if (platformWidget()) platformSetContentsSize(); else updateScrollbars(scrollOffset()); } #if PLATFORM(ANDROID) int ScrollView::actualWidth() const { if (platformWidget()) return platformActualWidth(); return width(); } int ScrollView::actualHeight() const { if (platformWidget()) return platformActualHeight(); return height(); } int ScrollView::actualScrollX() const { if (platformWidget()) return platformActualScrollX(); return scrollX(); } int ScrollView::actualScrollY() const { if (platformWidget()) return platformActualScrollY(); return scrollY(); } #endif IntPoint ScrollView::maximumScrollPosition() const { IntPoint maximumOffset(contentsWidth() - visibleWidth() - m_scrollOrigin.x(), contentsHeight() - visibleHeight() - m_scrollOrigin.y()); maximumOffset.clampNegativeToZero(); return maximumOffset; } IntPoint ScrollView::minimumScrollPosition() const { return IntPoint(-m_scrollOrigin.x(), -m_scrollOrigin.y()); } IntPoint ScrollView::adjustScrollPositionWithinRange(const IntPoint& scrollPoint) const { IntPoint newScrollPosition = scrollPoint.shrunkTo(maximumScrollPosition()); newScrollPosition = newScrollPosition.expandedTo(minimumScrollPosition()); return newScrollPosition; } int ScrollView::scrollSize(ScrollbarOrientation orientation) const { Scrollbar* scrollbar = ((orientation == HorizontalScrollbar) ? m_horizontalScrollbar : m_verticalScrollbar).get(); return scrollbar ? (scrollbar->totalSize() - scrollbar->visibleSize()) : 0; } void ScrollView::didCompleteRubberBand(const IntSize&) const { } void ScrollView::notifyPageThatContentAreaWillPaint() const { } void ScrollView::setScrollOffset(const IntPoint& offset) { int horizontalOffset = offset.x(); int verticalOffset = offset.y(); if (constrainsScrollingToContentEdge()) { horizontalOffset = max(min(horizontalOffset, contentsWidth() - visibleWidth()), 0); verticalOffset = max(min(verticalOffset, contentsHeight() - visibleHeight()), 0); } IntSize newOffset = m_scrollOffset; newOffset.setWidth(horizontalOffset - m_scrollOrigin.x()); newOffset.setHeight(verticalOffset - m_scrollOrigin.y()); scrollTo(newOffset); } void ScrollView::scrollTo(const IntSize& newOffset) { IntSize scrollDelta = newOffset - m_scrollOffset; if (scrollDelta == IntSize()) return; m_scrollOffset = newOffset; if (scrollbarsSuppressed()) return; repaintFixedElementsAfterScrolling(); scrollContents(scrollDelta); } int ScrollView::scrollPosition(Scrollbar* scrollbar) const { if (scrollbar->orientation() == HorizontalScrollbar) return scrollPosition().x() + m_scrollOrigin.x(); if (scrollbar->orientation() == VerticalScrollbar) return scrollPosition().y() + m_scrollOrigin.y(); return 0; } void ScrollView::setScrollPosition(const IntPoint& scrollPoint) { if (prohibitsScrolling()) return; if (platformWidget()) { platformSetScrollPosition(scrollPoint); return; } #if ENABLE(TILED_BACKING_STORE) if (delegatesScrolling()) { hostWindow()->delegatedScrollRequested(scrollPoint); if (!m_actualVisibleContentRect.isEmpty()) m_actualVisibleContentRect.setLocation(scrollPoint); return; } #endif IntPoint newScrollPosition = adjustScrollPositionWithinRange(scrollPoint); if (newScrollPosition == scrollPosition()) return; updateScrollbars(IntSize(newScrollPosition.x(), newScrollPosition.y())); } bool ScrollView::scroll(ScrollDirection direction, ScrollGranularity granularity) { if (platformWidget()) return platformScroll(direction, granularity); return ScrollableArea::scroll(direction, granularity); } bool ScrollView::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity) { return scroll(logicalToPhysical(direction, isVerticalDocument(), isFlippedDocument()), granularity); } IntSize ScrollView::overhangAmount() const { IntSize stretch; int physicalScrollY = scrollPosition().y() + m_scrollOrigin.y(); if (physicalScrollY < 0) stretch.setHeight(physicalScrollY); else if (physicalScrollY > contentsHeight() - visibleContentRect().height()) stretch.setHeight(physicalScrollY - (contentsHeight() - visibleContentRect().height())); int physicalScrollX = scrollPosition().x() + m_scrollOrigin.x(); if (physicalScrollX < 0) stretch.setWidth(physicalScrollX); else if (physicalScrollX > contentsWidth() - visibleContentRect().width()) stretch.setWidth(physicalScrollX - (contentsWidth() - visibleContentRect().width())); return stretch; } void ScrollView::windowResizerRectChanged() { if (platformWidget()) return; updateScrollbars(scrollOffset()); } static const unsigned cMaxUpdateScrollbarsPass = 2; void ScrollView::updateScrollbars(const IntSize& desiredOffset) { if (m_inUpdateScrollbars || prohibitsScrolling() || delegatesScrolling() || platformWidget()) return; // If we came in here with the view already needing a layout, then go ahead and do that // first. (This will be the common case, e.g., when the page changes due to window resizing for example). // This layout will not re-enter updateScrollbars and does not count towards our max layout pass total. if (!m_scrollbarsSuppressed) { m_inUpdateScrollbars = true; visibleContentsResized(); m_inUpdateScrollbars = false; } bool hasHorizontalScrollbar = m_horizontalScrollbar; bool hasVerticalScrollbar = m_verticalScrollbar; bool newHasHorizontalScrollbar = hasHorizontalScrollbar; bool newHasVerticalScrollbar = hasVerticalScrollbar; ScrollbarMode hScroll = m_horizontalScrollbarMode; ScrollbarMode vScroll = m_verticalScrollbarMode; if (hScroll != ScrollbarAuto) newHasHorizontalScrollbar = (hScroll == ScrollbarAlwaysOn); if (vScroll != ScrollbarAuto) newHasVerticalScrollbar = (vScroll == ScrollbarAlwaysOn); if (m_scrollbarsSuppressed || (hScroll != ScrollbarAuto && vScroll != ScrollbarAuto)) { if (hasHorizontalScrollbar != newHasHorizontalScrollbar) setHasHorizontalScrollbar(newHasHorizontalScrollbar); if (hasVerticalScrollbar != newHasVerticalScrollbar) setHasVerticalScrollbar(newHasVerticalScrollbar); } else { bool sendContentResizedNotification = false; IntSize docSize = contentsSize(); IntSize frameSize = m_boundsSize; if (hScroll == ScrollbarAuto) { newHasHorizontalScrollbar = docSize.width() > visibleWidth(); if (newHasHorizontalScrollbar && !m_updateScrollbarsPass && docSize.width() <= frameSize.width() && docSize.height() <= frameSize.height()) newHasHorizontalScrollbar = false; } if (vScroll == ScrollbarAuto) { newHasVerticalScrollbar = docSize.height() > visibleHeight(); if (newHasVerticalScrollbar && !m_updateScrollbarsPass && docSize.width() <= frameSize.width() && docSize.height() <= frameSize.height()) newHasVerticalScrollbar = false; } // If we ever turn one scrollbar off, always turn the other one off too. Never ever // try to both gain/lose a scrollbar in the same pass. if (!newHasHorizontalScrollbar && hasHorizontalScrollbar && vScroll != ScrollbarAlwaysOn) newHasVerticalScrollbar = false; if (!newHasVerticalScrollbar && hasVerticalScrollbar && hScroll != ScrollbarAlwaysOn) newHasHorizontalScrollbar = false; if (hasHorizontalScrollbar != newHasHorizontalScrollbar) { if (m_scrollOrigin.y() && !newHasHorizontalScrollbar) m_scrollOrigin.setY(m_scrollOrigin.y() - m_horizontalScrollbar->height()); setHasHorizontalScrollbar(newHasHorizontalScrollbar); sendContentResizedNotification = true; } if (hasVerticalScrollbar != newHasVerticalScrollbar) { if (m_scrollOrigin.x() && !newHasVerticalScrollbar) m_scrollOrigin.setX(m_scrollOrigin.x() - m_verticalScrollbar->width()); setHasVerticalScrollbar(newHasVerticalScrollbar); sendContentResizedNotification = true; } if (sendContentResizedNotification && m_updateScrollbarsPass < cMaxUpdateScrollbarsPass) { m_updateScrollbarsPass++; contentsResized(); visibleContentsResized(); IntSize newDocSize = contentsSize(); if (newDocSize == docSize) { // The layout with the new scroll state had no impact on // the document's overall size, so updateScrollbars didn't get called. // Recur manually. updateScrollbars(desiredOffset); } m_updateScrollbarsPass--; } } // Set up the range (and page step/line step), but only do this if we're not in a nested call (to avoid // doing it multiple times). if (m_updateScrollbarsPass) return; m_inUpdateScrollbars = true; IntPoint scrollPoint = adjustScrollPositionWithinRange(IntPoint(desiredOffset)); IntSize scroll(scrollPoint.x(), scrollPoint.y()); if (m_horizontalScrollbar) { int clientWidth = visibleWidth(); m_horizontalScrollbar->setEnabled(contentsWidth() > clientWidth); int pageStep = max(max<int>(clientWidth * Scrollbar::minFractionToStepWhenPaging(), clientWidth - Scrollbar::maxOverlapBetweenPages()), 1); IntRect oldRect(m_horizontalScrollbar->frameRect()); IntRect hBarRect = IntRect(0, m_boundsSize.height() - m_horizontalScrollbar->height(), m_boundsSize.width() - (m_verticalScrollbar ? m_verticalScrollbar->width() : 0), m_horizontalScrollbar->height()); m_horizontalScrollbar->setFrameRect(hBarRect); if (!m_scrollbarsSuppressed && oldRect != m_horizontalScrollbar->frameRect()) m_horizontalScrollbar->invalidate(); if (m_scrollbarsSuppressed) m_horizontalScrollbar->setSuppressInvalidation(true); m_horizontalScrollbar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep); m_horizontalScrollbar->setProportion(clientWidth, contentsWidth()); if (m_scrollbarsSuppressed) m_horizontalScrollbar->setSuppressInvalidation(false); } if (m_verticalScrollbar) { int clientHeight = visibleHeight(); m_verticalScrollbar->setEnabled(contentsHeight() > clientHeight); int pageStep = max(max<int>(clientHeight * Scrollbar::minFractionToStepWhenPaging(), clientHeight - Scrollbar::maxOverlapBetweenPages()), 1); IntRect oldRect(m_verticalScrollbar->frameRect()); IntRect vBarRect = IntRect(m_boundsSize.width() - m_verticalScrollbar->width(), 0, m_verticalScrollbar->width(), m_boundsSize.height() - (m_horizontalScrollbar ? m_horizontalScrollbar->height() : 0)); m_verticalScrollbar->setFrameRect(vBarRect); if (!m_scrollbarsSuppressed && oldRect != m_verticalScrollbar->frameRect()) m_verticalScrollbar->invalidate(); if (m_scrollbarsSuppressed) m_verticalScrollbar->setSuppressInvalidation(true); m_verticalScrollbar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep); m_verticalScrollbar->setProportion(clientHeight, contentsHeight()); if (m_scrollbarsSuppressed) m_verticalScrollbar->setSuppressInvalidation(false); } if (hasHorizontalScrollbar != (m_horizontalScrollbar != 0) || hasVerticalScrollbar != (m_verticalScrollbar != 0)) { frameRectsChanged(); updateScrollCorner(); } ScrollableArea::scrollToOffsetWithoutAnimation(FloatPoint(scroll.width() + m_scrollOrigin.x(), scroll.height() + m_scrollOrigin.y())); // Make sure the scrollbar offsets are up to date. if (m_horizontalScrollbar) m_horizontalScrollbar->offsetDidChange(); if (m_verticalScrollbar) m_verticalScrollbar->offsetDidChange(); m_inUpdateScrollbars = false; } const int panIconSizeLength = 16; void ScrollView::scrollContents(const IntSize& scrollDelta) { if (!hostWindow()) return; // Since scrolling is double buffered, we will be blitting the scroll view's intersection // with the clip rect every time to keep it smooth. IntRect clipRect = windowClipRect(); IntRect scrollViewRect = convertToContainingWindow(IntRect(0, 0, visibleWidth(), visibleHeight())); if (hasOverlayScrollbars()) { int verticalScrollbarWidth = verticalScrollbar() ? verticalScrollbar()->width() : 0; int horizontalScrollbarHeight = horizontalScrollbar() ? horizontalScrollbar()->height() : 0; scrollViewRect.setWidth(scrollViewRect.width() - verticalScrollbarWidth); scrollViewRect.setHeight(scrollViewRect.height() - horizontalScrollbarHeight); } IntRect updateRect = clipRect; updateRect.intersect(scrollViewRect); // Invalidate the window (not the backing store). hostWindow()->invalidateWindow(updateRect, false /*immediate*/); if (m_drawPanScrollIcon) { // FIXME: the pan icon is broken when accelerated compositing is on, since it will draw under the compositing layers. // https://bugs.webkit.org/show_bug.cgi?id=47837 int panIconDirtySquareSizeLength = 2 * (panIconSizeLength + max(abs(scrollDelta.width()), abs(scrollDelta.height()))); // We only want to repaint what's necessary IntPoint panIconDirtySquareLocation = IntPoint(m_panScrollIconPoint.x() - (panIconDirtySquareSizeLength / 2), m_panScrollIconPoint.y() - (panIconDirtySquareSizeLength / 2)); IntRect panScrollIconDirtyRect = IntRect(panIconDirtySquareLocation , IntSize(panIconDirtySquareSizeLength, panIconDirtySquareSizeLength)); panScrollIconDirtyRect.intersect(clipRect); hostWindow()->invalidateContentsAndWindow(panScrollIconDirtyRect, false /*immediate*/); } if (canBlitOnScroll()) { // The main frame can just blit the WebView window // FIXME: Find a way to scroll subframes with this faster path if (!scrollContentsFastPath(-scrollDelta, scrollViewRect, clipRect)) scrollContentsSlowPath(updateRect); } else { // We need to go ahead and repaint the entire backing store. Do it now before moving the // windowed plugins. scrollContentsSlowPath(updateRect); } // Invalidate the overhang areas if they are visible. IntRect horizontalOverhangRect; IntRect verticalOverhangRect; calculateOverhangAreasForPainting(horizontalOverhangRect, verticalOverhangRect); if (!horizontalOverhangRect.isEmpty()) hostWindow()->invalidateContentsAndWindow(horizontalOverhangRect, false /*immediate*/); if (!verticalOverhangRect.isEmpty()) hostWindow()->invalidateContentsAndWindow(verticalOverhangRect, false /*immediate*/); // This call will move children with native widgets (plugins) and invalidate them as well. frameRectsChanged(); // Now blit the backingstore into the window which should be very fast. hostWindow()->invalidateWindow(IntRect(), true); } bool ScrollView::scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect) { hostWindow()->scroll(scrollDelta, rectToScroll, clipRect); return true; } void ScrollView::scrollContentsSlowPath(const IntRect& updateRect) { hostWindow()->invalidateContentsForSlowScroll(updateRect, false); } IntPoint ScrollView::windowToContents(const IntPoint& windowPoint) const { IntPoint viewPoint = convertFromContainingWindow(windowPoint); return viewPoint + scrollOffset(); } IntPoint ScrollView::contentsToWindow(const IntPoint& contentsPoint) const { IntPoint viewPoint = contentsPoint - scrollOffset(); return convertToContainingWindow(viewPoint); } IntRect ScrollView::windowToContents(const IntRect& windowRect) const { IntRect viewRect = convertFromContainingWindow(windowRect); viewRect.move(scrollOffset()); return viewRect; } IntRect ScrollView::contentsToWindow(const IntRect& contentsRect) const { IntRect viewRect = contentsRect; viewRect.move(-scrollOffset()); return convertToContainingWindow(viewRect); } IntRect ScrollView::contentsToScreen(const IntRect& rect) const { if (platformWidget()) return platformContentsToScreen(rect); if (!hostWindow()) return IntRect(); return hostWindow()->windowToScreen(contentsToWindow(rect)); } IntPoint ScrollView::screenToContents(const IntPoint& point) const { if (platformWidget()) return platformScreenToContents(point); if (!hostWindow()) return IntPoint(); return windowToContents(hostWindow()->screenToWindow(point)); } bool ScrollView::containsScrollbarsAvoidingResizer() const { return !m_scrollbarsAvoidingResizer; } void ScrollView::adjustScrollbarsAvoidingResizerCount(int overlapDelta) { int oldCount = m_scrollbarsAvoidingResizer; m_scrollbarsAvoidingResizer += overlapDelta; if (parent()) parent()->adjustScrollbarsAvoidingResizerCount(overlapDelta); else if (!scrollbarsSuppressed()) { // If we went from n to 0 or from 0 to n and we're the outermost view, // we need to invalidate the windowResizerRect(), since it will now need to paint // differently. if ((oldCount > 0 && m_scrollbarsAvoidingResizer == 0) || (oldCount == 0 && m_scrollbarsAvoidingResizer > 0)) invalidateRect(windowResizerRect()); } } void ScrollView::setParent(ScrollView* parentView) { if (parentView == parent()) return; if (m_scrollbarsAvoidingResizer && parent()) parent()->adjustScrollbarsAvoidingResizerCount(-m_scrollbarsAvoidingResizer); Widget::setParent(parentView); if (m_scrollbarsAvoidingResizer && parent()) parent()->adjustScrollbarsAvoidingResizerCount(m_scrollbarsAvoidingResizer); } void ScrollView::setScrollbarsSuppressed(bool suppressed, bool repaintOnUnsuppress) { if (suppressed == m_scrollbarsSuppressed) return; m_scrollbarsSuppressed = suppressed; if (platformWidget()) platformSetScrollbarsSuppressed(repaintOnUnsuppress); else if (repaintOnUnsuppress && !suppressed) { if (m_horizontalScrollbar) m_horizontalScrollbar->invalidate(); if (m_verticalScrollbar) m_verticalScrollbar->invalidate(); // Invalidate the scroll corner too on unsuppress. invalidateRect(scrollCornerRect()); } } Scrollbar* ScrollView::scrollbarAtPoint(const IntPoint& windowPoint) { if (platformWidget()) return 0; IntPoint viewPoint = convertFromContainingWindow(windowPoint); if (m_horizontalScrollbar && m_horizontalScrollbar->frameRect().contains(viewPoint)) return m_horizontalScrollbar.get(); if (m_verticalScrollbar && m_verticalScrollbar->frameRect().contains(viewPoint)) return m_verticalScrollbar.get(); return 0; } void ScrollView::wheelEvent(PlatformWheelEvent& e) { // We don't allow mouse wheeling to happen in a ScrollView that has had its scrollbars explicitly disabled. #if PLATFORM(WX) if (!canHaveScrollbars()) { #else if (!canHaveScrollbars() || platformWidget()) { #endif return; } ScrollableArea::handleWheelEvent(e); } #if ENABLE(GESTURE_EVENTS) void ScrollView::gestureEvent(const PlatformGestureEvent& gestureEvent) { if (platformWidget()) return; ScrollableArea::handleGestureEvent(gestureEvent); } #endif void ScrollView::setFrameRect(const IntRect& newRect) { IntRect oldRect = frameRect(); if (newRect == oldRect) return; Widget::setFrameRect(newRect); } void ScrollView::setBoundsSize(const IntSize& newSize) { if (newSize == m_boundsSize) return; Widget::setBoundsSize(newSize); m_boundsSize = newSize; if (platformWidget()) return; updateScrollbars(m_scrollOffset); if (!m_useFixedLayout) contentsResized(); frameRectsChanged(); } void ScrollView::setInitialBoundsSize(const IntSize& newSize) { ASSERT(m_boundsSize.isZero()); m_boundsSize = newSize; } void ScrollView::frameRectsChanged() { if (platformWidget()) return; HashSet<RefPtr<Widget> >::const_iterator end = m_children.end(); for (HashSet<RefPtr<Widget> >::const_iterator current = m_children.begin(); current != end; ++current) (*current)->frameRectsChanged(); positionScrollbarLayers(); } #if USE(ACCELERATED_COMPOSITING) static void positionScrollbarLayer(GraphicsLayer* graphicsLayer, Scrollbar* scrollbar) { if (!graphicsLayer || !scrollbar) return; graphicsLayer->setDrawsContent(true); IntRect scrollbarRect = scrollbar->frameRect(); graphicsLayer->setPosition(scrollbarRect.location()); if (scrollbarRect.size() != graphicsLayer->size()) graphicsLayer->setNeedsDisplay(); graphicsLayer->setSize(scrollbarRect.size()); } static void positionScrollCornerLayer(GraphicsLayer* graphicsLayer, const IntRect& cornerRect) { if (!graphicsLayer) return; graphicsLayer->setDrawsContent(!cornerRect.isEmpty()); graphicsLayer->setPosition(cornerRect.location()); if (cornerRect.size() != graphicsLayer->size()) graphicsLayer->setNeedsDisplay(); graphicsLayer->setSize(cornerRect.size()); } #endif void ScrollView::positionScrollbarLayers() { #if USE(ACCELERATED_COMPOSITING) positionScrollbarLayer(layerForHorizontalScrollbar(), horizontalScrollbar()); positionScrollbarLayer(layerForVerticalScrollbar(), verticalScrollbar()); positionScrollCornerLayer(layerForScrollCorner(), scrollCornerRect()); #endif } void ScrollView::repaintContentRectangle(const IntRect& rect, bool now) { IntRect paintRect = rect; if (clipsRepaints() && !paintsEntireContents()) paintRect.intersect(visibleContentRect()); #ifdef ANDROID_CAPTURE_OFFSCREEN_PAINTS if (rect != paintRect) platformOffscreenContentRectangle(visibleContentRect(), rect); #endif if (paintRect.isEmpty()) return; if (platformWidget()) { platformRepaintContentRectangle(paintRect, now); return; } if (hostWindow()) hostWindow()->invalidateContentsAndWindow(contentsToWindow(paintRect), now /*immediate*/); } IntRect ScrollView::scrollCornerRect() const { IntRect cornerRect; if (hasOverlayScrollbars()) return cornerRect; if (m_horizontalScrollbar && m_boundsSize.width() - m_horizontalScrollbar->width() > 0) { cornerRect.unite(IntRect(m_horizontalScrollbar->width(), m_boundsSize.height() - m_horizontalScrollbar->height(), m_boundsSize.width() - m_horizontalScrollbar->width(), m_horizontalScrollbar->height())); } if (m_verticalScrollbar && m_boundsSize.height() - m_verticalScrollbar->height() > 0) { cornerRect.unite(IntRect(m_boundsSize.width() - m_verticalScrollbar->width(), m_verticalScrollbar->height(), m_verticalScrollbar->width(), m_boundsSize.height() - m_verticalScrollbar->height())); } return cornerRect; } bool ScrollView::isScrollCornerVisible() const { return !scrollCornerRect().isEmpty(); } void ScrollView::updateScrollCorner() { } void ScrollView::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect) { ScrollbarTheme::nativeTheme()->paintScrollCorner(this, context, cornerRect); } void ScrollView::invalidateScrollCornerRect(const IntRect& rect) { invalidateRect(rect); } void ScrollView::paintScrollbars(GraphicsContext* context, const IntRect& rect) { if (m_horizontalScrollbar #if USE(ACCELERATED_COMPOSITING) && !layerForHorizontalScrollbar() #endif ) m_horizontalScrollbar->paint(context, rect); if (m_verticalScrollbar #if USE(ACCELERATED_COMPOSITING) && !layerForVerticalScrollbar() #endif ) m_verticalScrollbar->paint(context, rect); #if USE(ACCELERATED_COMPOSITING) if (layerForScrollCorner()) return; #endif paintScrollCorner(context, scrollCornerRect()); } void ScrollView::paintPanScrollIcon(GraphicsContext* context) { static Image* panScrollIcon = Image::loadPlatformResource("panIcon").releaseRef(); context->drawImage(panScrollIcon, ColorSpaceDeviceRGB, m_panScrollIconPoint); } void ScrollView::paint(GraphicsContext* context, const IntRect& rect) { if (platformWidget()) { Widget::paint(context, rect); return; } if (context->paintingDisabled() && !context->updatingControlTints()) return; notifyPageThatContentAreaWillPaint(); // If we encounter any overlay scrollbars as we paint, this will be set to true. m_containsScrollableAreaWithOverlayScrollbars = false; IntRect documentDirtyRect = rect; documentDirtyRect.intersect(frameRect()); context->save(); context->translate(x(), y()); documentDirtyRect.move(-x(), -y()); if (!paintsEntireContents()) { context->translate(-scrollX(), -scrollY()); documentDirtyRect.move(scrollX(), scrollY()); context->clip(visibleContentRect()); } paintContents(context, documentDirtyRect); context->restore(); IntRect horizontalOverhangRect; IntRect verticalOverhangRect; calculateOverhangAreasForPainting(horizontalOverhangRect, verticalOverhangRect); if (rect.intersects(horizontalOverhangRect) || rect.intersects(verticalOverhangRect)) paintOverhangAreas(context, horizontalOverhangRect, verticalOverhangRect, rect); // Now paint the scrollbars. if (!m_scrollbarsSuppressed && (m_horizontalScrollbar || m_verticalScrollbar)) { context->save(); IntRect scrollViewDirtyRect = rect; scrollViewDirtyRect.intersect(frameRect()); context->translate(x(), y()); scrollViewDirtyRect.move(-x(), -y()); paintScrollbars(context, scrollViewDirtyRect); context->restore(); } // Paint the panScroll Icon if (m_drawPanScrollIcon) paintPanScrollIcon(context); } void ScrollView::calculateOverhangAreasForPainting(IntRect& horizontalOverhangRect, IntRect& verticalOverhangRect) { int verticalScrollbarWidth = (verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar()) ? verticalScrollbar()->width() : 0; int horizontalScrollbarHeight = (horizontalScrollbar() && !horizontalScrollbar()->isOverlayScrollbar()) ? horizontalScrollbar()->height() : 0; int physicalScrollY = scrollPosition().y() + m_scrollOrigin.y(); if (physicalScrollY < 0) { horizontalOverhangRect = frameRect(); horizontalOverhangRect.setHeight(-physicalScrollY); } else if (physicalScrollY > contentsHeight() - visibleContentRect().height()) { int height = physicalScrollY - (contentsHeight() - visibleContentRect().height()); horizontalOverhangRect = frameRect(); horizontalOverhangRect.setY(frameRect().maxY() - height - horizontalScrollbarHeight); horizontalOverhangRect.setHeight(height); } int physicalScrollX = scrollPosition().x() + m_scrollOrigin.x(); if (physicalScrollX < 0) { verticalOverhangRect.setWidth(-physicalScrollX); verticalOverhangRect.setHeight(frameRect().height() - horizontalOverhangRect.height()); verticalOverhangRect.setX(frameRect().x()); if (horizontalOverhangRect.y() == frameRect().y()) verticalOverhangRect.setY(frameRect().y() + horizontalOverhangRect.height()); else verticalOverhangRect.setY(frameRect().y()); } else if (physicalScrollX > contentsWidth() - visibleContentRect().width()) { int width = physicalScrollX - (contentsWidth() - visibleContentRect().width()); verticalOverhangRect.setWidth(width); verticalOverhangRect.setHeight(frameRect().height() - horizontalOverhangRect.height()); verticalOverhangRect.setX(frameRect().maxX() - width - verticalScrollbarWidth); if (horizontalOverhangRect.y() == frameRect().y()) verticalOverhangRect.setY(frameRect().y() + horizontalOverhangRect.height()); else verticalOverhangRect.setY(frameRect().y()); } } void ScrollView::paintOverhangAreas(GraphicsContext* context, const IntRect& horizontalOverhangRect, const IntRect& verticalOverhangRect, const IntRect&) { // FIXME: This should be checking the dirty rect. context->setFillColor(Color::white, ColorSpaceDeviceRGB); if (!horizontalOverhangRect.isEmpty()) context->fillRect(horizontalOverhangRect); context->setFillColor(Color::white, ColorSpaceDeviceRGB); if (!verticalOverhangRect.isEmpty()) context->fillRect(verticalOverhangRect); } bool ScrollView::isPointInScrollbarCorner(const IntPoint& windowPoint) { if (!scrollbarCornerPresent()) return false; IntPoint viewPoint = convertFromContainingWindow(windowPoint); if (m_horizontalScrollbar) { int horizontalScrollbarYMin = m_horizontalScrollbar->frameRect().y(); int horizontalScrollbarYMax = m_horizontalScrollbar->frameRect().y() + m_horizontalScrollbar->frameRect().height(); int horizontalScrollbarXMin = m_horizontalScrollbar->frameRect().x() + m_horizontalScrollbar->frameRect().width(); return viewPoint.y() > horizontalScrollbarYMin && viewPoint.y() < horizontalScrollbarYMax && viewPoint.x() > horizontalScrollbarXMin; } int verticalScrollbarXMin = m_verticalScrollbar->frameRect().x(); int verticalScrollbarXMax = m_verticalScrollbar->frameRect().x() + m_verticalScrollbar->frameRect().width(); int verticalScrollbarYMin = m_verticalScrollbar->frameRect().y() + m_verticalScrollbar->frameRect().height(); return viewPoint.x() > verticalScrollbarXMin && viewPoint.x() < verticalScrollbarXMax && viewPoint.y() > verticalScrollbarYMin; } bool ScrollView::scrollbarCornerPresent() const { return (m_horizontalScrollbar && m_boundsSize.width() - m_horizontalScrollbar->width() > 0) || (m_verticalScrollbar && m_boundsSize.height() - m_verticalScrollbar->height() > 0); } IntRect ScrollView::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& localRect) const { // Scrollbars won't be transformed within us IntRect newRect = localRect; newRect.move(scrollbar->x(), scrollbar->y()); return newRect; } IntRect ScrollView::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& parentRect) const { IntRect newRect = parentRect; // Scrollbars won't be transformed within us newRect.move(-scrollbar->x(), -scrollbar->y()); return newRect; } // FIXME: test these on windows IntPoint ScrollView::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& localPoint) const { // Scrollbars won't be transformed within us IntPoint newPoint = localPoint; newPoint.move(scrollbar->x(), scrollbar->y()); return newPoint; } IntPoint ScrollView::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& parentPoint) const { IntPoint newPoint = parentPoint; // Scrollbars won't be transformed within us newPoint.move(-scrollbar->x(), -scrollbar->y()); return newPoint; } void ScrollView::setParentVisible(bool visible) { if (isParentVisible() == visible) return; Widget::setParentVisible(visible); if (!isSelfVisible()) return; HashSet<RefPtr<Widget> >::iterator end = m_children.end(); for (HashSet<RefPtr<Widget> >::iterator it = m_children.begin(); it != end; ++it) (*it)->setParentVisible(visible); } void ScrollView::show() { if (!isSelfVisible()) { setSelfVisible(true); if (isParentVisible()) { HashSet<RefPtr<Widget> >::iterator end = m_children.end(); for (HashSet<RefPtr<Widget> >::iterator it = m_children.begin(); it != end; ++it) (*it)->setParentVisible(true); } } Widget::show(); } void ScrollView::hide() { if (isSelfVisible()) { if (isParentVisible()) { HashSet<RefPtr<Widget> >::iterator end = m_children.end(); for (HashSet<RefPtr<Widget> >::iterator it = m_children.begin(); it != end; ++it) (*it)->setParentVisible(false); } setSelfVisible(false); } Widget::hide(); } bool ScrollView::isOffscreen() const { if (platformWidget()) return platformIsOffscreen(); if (!isVisible()) return true; // FIXME: Add a HostWindow::isOffscreen method here. Since only Mac implements this method // currently, we can add the method when the other platforms decide to implement this concept. return false; } void ScrollView::addPanScrollIcon(const IntPoint& iconPosition) { if (!hostWindow()) return; m_drawPanScrollIcon = true; m_panScrollIconPoint = IntPoint(iconPosition.x() - panIconSizeLength / 2 , iconPosition.y() - panIconSizeLength / 2) ; hostWindow()->invalidateContentsAndWindow(IntRect(m_panScrollIconPoint, IntSize(panIconSizeLength, panIconSizeLength)), true /*immediate*/); } void ScrollView::removePanScrollIcon() { if (!hostWindow()) return; m_drawPanScrollIcon = false; hostWindow()->invalidateContentsAndWindow(IntRect(m_panScrollIconPoint, IntSize(panIconSizeLength, panIconSizeLength)), true /*immediate*/); } void ScrollView::setScrollOrigin(const IntPoint& origin, bool updatePositionAtAll, bool updatePositionSynchronously) { if (m_scrollOrigin == origin) return; m_scrollOrigin = origin; if (platformWidget()) { platformSetScrollOrigin(origin, updatePositionAtAll, updatePositionSynchronously); return; } // Update if the scroll origin changes, since our position will be different if the content size did not change. if (updatePositionAtAll && updatePositionSynchronously) updateScrollbars(scrollOffset()); } #if !PLATFORM(WX) && !USE(NATIVE_GTK_MAIN_FRAME_SCROLLBAR) && !PLATFORM(EFL) void ScrollView::platformInit() { } void ScrollView::platformDestroy() { } #endif #if !PLATFORM(WX) && !PLATFORM(QT) && !PLATFORM(MAC) void ScrollView::platformAddChild(Widget*) { } void ScrollView::platformRemoveChild(Widget*) { } #endif #if !PLATFORM(MAC) void ScrollView::platformSetScrollbarsSuppressed(bool) { } void ScrollView::platformSetScrollOrigin(const IntPoint&, bool updatePositionAtAll, bool updatePositionSynchronously) { } #endif #if !PLATFORM(MAC) && !PLATFORM(WX) #if !PLATFORM(ANDROID) void ScrollView::platformSetScrollbarModes() { } void ScrollView::platformScrollbarModes(ScrollbarMode& horizontal, ScrollbarMode& vertical) const { horizontal = ScrollbarAuto; vertical = ScrollbarAuto; } #endif void ScrollView::platformSetCanBlitOnScroll(bool) { } bool ScrollView::platformCanBlitOnScroll() const { return false; } #if !PLATFORM(ANDROID) IntRect ScrollView::platformVisibleContentRect(bool) const { return IntRect(); } #endif #if !PLATFORM(ANDROID) IntSize ScrollView::platformContentsSize() const { return IntSize(); } #endif void ScrollView::platformSetContentsSize() { } IntRect ScrollView::platformContentsToScreen(const IntRect& rect) const { return rect; } IntPoint ScrollView::platformScreenToContents(const IntPoint& point) const { return point; } #if !PLATFORM(ANDROID) void ScrollView::platformSetScrollPosition(const IntPoint&) { } #endif bool ScrollView::platformScroll(ScrollDirection, ScrollGranularity) { return true; } #if !PLATFORM(ANDROID) void ScrollView::platformRepaintContentRectangle(const IntRect&, bool /*now*/) { } #ifdef ANDROID_CAPTURE_OFFSCREEN_PAINTS void ScrollView::platformOffscreenContentRectangle(const IntRect& ) { } #endif bool ScrollView::platformIsOffscreen() const { return false; } #endif #endif }
xdajog/samsung_sources_i927
external/webkit/Source/WebCore/platform/ScrollView.cpp
C++
gpl-2.0
45,619
/* Copyright (C) 2003 - 2016 by David White <dave@whitevine.net> Part of the Battle for Wesnoth Project http://www.wesnoth.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. See the COPYING file for more details. */ /** * @file * Networking */ #include "global.hpp" #include "gettext.hpp" #include "log.hpp" #include "network_worker.hpp" #include "serialization/string_utils.hpp" #include "thread.hpp" #include "util.hpp" #include "config.hpp" #include "filesystem.hpp" #include <cerrno> #include <queue> #include <iomanip> #include <set> #include <cstring> #include <stdexcept> #include <sstream> #include <boost/exception/get_error_info.hpp> #include <boost/exception/info.hpp> #include <signal.h> #if defined(_WIN32) || defined(__WIN32__) || defined (WIN32) #undef INADDR_ANY #undef INADDR_BROADCAST #undef INADDR_NONE #include <windows.h> #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> // for TCP_NODELAY #include <fcntl.h> #define SOCKET int #endif static lg::log_domain log_network("network"); #define DBG_NW LOG_STREAM(debug, log_network) #define LOG_NW LOG_STREAM(info, log_network) #define WRN_NW LOG_STREAM(warn, log_network) #define ERR_NW LOG_STREAM(err, log_network) // Only warnings and not errors to avoid DoS by log flooding namespace { // We store the details of a connection in a map that must be looked up by its handle. // This allows a connection to be disconnected and then recovered, // but the handle remains the same, so it's all seamless to the user. struct connection_details { connection_details(TCPsocket sock, const std::string& host, int port) : sock(sock), host(host), port(port), remote_handle(0), connected_at(SDL_GetTicks()) {} TCPsocket sock; std::string host; int port; // The remote handle is the handle assigned to this connection by the remote host. // Is 0 before a handle has been assigned. int remote_handle; int connected_at; }; typedef std::map<network::connection,connection_details> connection_map; connection_map connections; network::connection connection_id = 1; /** Stores the time of the last server ping we received. */ time_t last_ping, last_ping_check = 0; } // end anon namespace static int create_connection(TCPsocket sock, const std::string& host, int port) { connections.insert(std::pair<network::connection,connection_details>(connection_id,connection_details(sock,host,port))); return connection_id++; } static connection_details& get_connection_details(network::connection handle) { const connection_map::iterator i = connections.find(handle); if(i == connections.end()) { throw network::error(_("invalid network handle")); } return i->second; } static TCPsocket get_socket(network::connection handle) { return get_connection_details(handle).sock; } static void remove_connection(network::connection handle) { connections.erase(handle); } static bool is_pending_remote_handle(network::connection handle) { const connection_details& details = get_connection_details(handle); return details.host != "" && details.remote_handle == 0; } static void set_remote_handle(network::connection handle, int remote_handle) { get_connection_details(handle).remote_handle = remote_handle; } static void check_error() { const TCPsocket sock = network_worker_pool::detect_error(); if(sock) { for(connection_map::const_iterator i = connections.begin(); i != connections.end(); ++i) { if(i->second.sock == sock) { throw network::error(_("Client disconnected"),i->first); } } } } /** * Check whether too much time since the last server ping has passed and we * timed out. If the last check is too long ago reset the last_ping to 'now'. * This happens when we "freeze" the client one way or another or we just * didn't try to receive data. */ static void check_timeout() { if (network::nconnections() == 0) { LOG_NW << "No network connections but last_ping is: " << last_ping; last_ping = 0; return; } const time_t& now = time(nullptr); DBG_NW << "Last ping: '" << last_ping << "' Current time: '" << now << "' Time since last ping: " << now - last_ping << "s\n"; // Reset last_ping if we didn't check for the last 10s. if (last_ping_check + 10 <= now) last_ping = now; // This static cast is required on some build systems. // (Reported in #wesnoth-dev 2012/11/24 21:10:21, log time.) if ( last_ping + static_cast<time_t>(network::ping_interval + network::ping_timeout) <= now ) { time_t timeout = now - last_ping; ERR_NW << "No server ping since " << timeout << " seconds. Connection timed out.\n"; utils::string_map symbols; symbols["timeout"] = std::to_string(timeout); throw network::error("No server ping since " + std::to_string(timeout) + " second. " "Connection timed out."); } last_ping_check = now; } namespace { SDLNet_SocketSet socket_set = 0; std::set<network::connection> waiting_sockets; typedef std::vector<network::connection> sockets_list; sockets_list sockets; struct partial_buffer { partial_buffer() : buf(), upto(0) { } std::vector<char> buf; size_t upto; }; TCPsocket server_socket; std::deque<network::connection> disconnection_queue; std::set<network::connection> bad_sockets; network_worker_pool::manager* worker_pool_man = nullptr; } // end anon namespace namespace network { /** * Amount of seconds after the last server ping when we assume to have timed out. * When set to '0' ping timeout isn't checked. * Gets set in preferences::manager according to the preferences file. */ unsigned int ping_timeout = 0; connection_stats::connection_stats(int sent, int received, int connected_at) : bytes_sent(sent), bytes_received(received), time_connected(SDL_GetTicks() - connected_at) {} connection_stats get_connection_stats(connection connection_num) { connection_details& details = get_connection_details(connection_num); return connection_stats(get_send_stats(connection_num).total,get_receive_stats(connection_num).total,details.connected_at); } error::error(const std::string& msg, connection sock) : game::error(msg), socket(sock) { if(socket) { bad_sockets.insert(socket); } } void error::disconnect() { if(socket) network::disconnect(socket); } pending_statistics get_pending_stats() { return network_worker_pool::get_pending_stats(); } manager::manager(size_t min_threads, size_t max_threads) : free_(true) { DBG_NW << "NETWORK MANAGER CALLED!\n"; // If the network is already being managed if(socket_set) { free_ = false; return; } if(SDLNet_Init() == -1) { ERR_NW << "could not initialize SDLNet; throwing error..." << std::endl; throw error(SDL_GetError()); } socket_set = SDLNet_AllocSocketSet(512); worker_pool_man = new network_worker_pool::manager(min_threads, max_threads); } manager::~manager() { if(free_) { disconnect(); delete worker_pool_man; worker_pool_man = nullptr; SDLNet_FreeSocketSet(socket_set); socket_set = 0; waiting_sockets.clear(); SDLNet_Quit(); } } void set_raw_data_only() { network_worker_pool::set_raw_data_only(); } // --- Proxy methods void enable_connection_through_proxy() { throw std::runtime_error("Proxy not available while using SDL_net. Use ANA instead."); } void set_proxy_address ( const std::string& ) { throw std::runtime_error("Proxy not available while using SDL_net. Use ANA instead."); } void set_proxy_port ( const std::string& ) { throw std::runtime_error("Proxy not available while using SDL_net. Use ANA instead."); } void set_proxy_user ( const std::string& ) { throw std::runtime_error("Proxy not available while using SDL_net. Use ANA instead."); } void set_proxy_password( const std::string& ) { throw std::runtime_error("Proxy not available while using SDL_net. Use ANA instead."); } // --- End Proxy methods server_manager::server_manager(int port, CREATE_SERVER create_server) : free_(false), connection_(0) { if(create_server != NO_SERVER && !server_socket) { try { connection_ = connect("",port); server_socket = get_socket(connection_); } catch(network::error&) { if(create_server == MUST_CREATE_SERVER) { throw; } else { return; } } DBG_NW << "server socket initialized: " << server_socket << "\n"; free_ = true; } } server_manager::~server_manager() { stop(); } void server_manager::stop() { if(free_) { SDLNet_TCP_Close(server_socket); remove_connection(connection_); server_socket = 0; free_ = false; } } bool server_manager::is_running() const { return server_socket != nullptr; } size_t nconnections() { return sockets.size(); } bool is_server() { return server_socket != 0; } namespace { class connect_operation : public threading::async_operation { public: connect_operation(const std::string& host, int port) : host_(host), port_(port), error_(), connect_(0) {} void check_error(); void run(); network::connection result() const { return connect_; } private: std::string host_; int port_; std::string error_; network::connection connect_; }; void connect_operation::check_error() { if(!error_.empty()) { throw error(error_); } } namespace { struct _TCPsocket { int ready; SOCKET channel; IPaddress remoteAddress; IPaddress localAddress; int sflag; }; } // end namespace void connect_operation::run() { char* const hostname = host_.empty() ? nullptr : const_cast<char*>(host_.c_str()); IPaddress ip; if(SDLNet_ResolveHost(&ip,hostname,port_) == -1) { error_ = N_("Could not connect to host."); return; } TCPsocket sock = SDLNet_TCP_Open(&ip); if(!sock) { error_ = hostname == nullptr ? "Could not bind to port" : N_("Could not connect to host."); return; } _TCPsocket* raw_sock = reinterpret_cast<_TCPsocket*>(sock); #ifdef TCP_NODELAY //set TCP_NODELAY to 0 because SDL_Net turns it off, causing packet //flooding! { int no = 0; setsockopt(raw_sock->channel, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&no), sizeof(no)); } #endif // Use non blocking IO #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) { unsigned long mode = 1; ioctlsocket (raw_sock->channel, FIONBIO, &mode); } #else int flags; flags = fcntl(raw_sock->channel, F_GETFL, 0); #if defined(O_NONBLOCK) flags |= O_NONBLOCK; #elif defined(O_NDELAY) flags |= O_NDELAY; #elif defined(FNDELAY) flags |= FNDELAY; #endif if (fcntl(raw_sock->channel, F_SETFL, flags) == -1) { error_ = "Could not make socket non-blocking: " + std::string(strerror(errno)); SDLNet_TCP_Close(sock); return; } #endif // If this is a server socket if(hostname == nullptr) { const threading::lock l(get_mutex()); connect_ = create_connection(sock,"",port_); return; } // Send data telling the remote host that this is a new connection union { char data[4] ALIGN_4; Uint32 num; } buf; SDLNet_Write32(0, &buf); const int nbytes = SDLNet_TCP_Send(sock,&buf,4); if(nbytes != 4) { SDLNet_TCP_Close(sock); error_ = "Could not send initial handshake"; return; } // No blocking operations from here on const threading::lock l(get_mutex()); DBG_NW << "sent handshake...\n"; if(is_aborted()) { DBG_NW << "connect operation aborted by calling thread\n"; SDLNet_TCP_Close(sock); return; } // Allocate this connection a connection handle connect_ = create_connection(sock,host_,port_); const int res = SDLNet_TCP_AddSocket(socket_set,sock); if(res == -1) { SDLNet_TCP_Close(sock); error_ = "Could not add socket to socket set"; return; } waiting_sockets.insert(connect_); sockets.push_back(connect_); while(!notify_finished()) {}; } } // end namespace connection connect(const std::string& host, int port) { connect_operation op(host,port); op.run(); op.check_error(); return op.result(); } connection connect(const std::string& host, int port, threading::waiter& waiter) { const threading::async_operation_ptr op(new connect_operation(host,port)); const connect_operation::RESULT res = op->execute(op, waiter); if(res == connect_operation::ABORTED) { return 0; } static_cast<connect_operation*>(op.get())->check_error(); return static_cast<connect_operation*>(op.get())->result(); } namespace { connection accept_connection_pending(std::vector<TCPsocket>& pending_sockets, SDLNet_SocketSet& pending_socket_set) { DBG_NW << "pending socket activity...\n"; std::vector<TCPsocket>::iterator i = pending_sockets.begin(); while (i != pending_sockets.end() && !SDLNet_SocketReady(*i)) ++i; if (i == pending_sockets.end()) return 0; // Receive the 4 bytes telling us if they're a new connection // or trying to recover a connection union { char data[4] ALIGN_4; Uint32 num; } buf; const TCPsocket psock = *i; SDLNet_TCP_DelSocket(pending_socket_set,psock); pending_sockets.erase(i); DBG_NW << "receiving data from pending socket...\n"; const int len = SDLNet_TCP_Recv(psock,&buf,4); if(len != 4) { WRN_NW << "pending socket disconnected" << std::endl; SDLNet_TCP_Close(psock); return 0; } const int handle = SDLNet_Read32(&buf); DBG_NW << "received handshake from client: '" << handle << "'\n"; const int res = SDLNet_TCP_AddSocket(socket_set,psock); if(res == -1) { ERR_NW << "SDLNet_GetError(): " << SDLNet_GetError() << std::endl; SDLNet_TCP_Close(psock); throw network::error(_("Could not add socket to socket set")); } const connection connect = create_connection(psock,"",0); // Send back their connection number SDLNet_Write32(connect, &buf); const int nbytes = SDLNet_TCP_Send(psock,&buf,4); if(nbytes != 4) { SDLNet_TCP_DelSocket(socket_set,psock); SDLNet_TCP_Close(psock); remove_connection(connect); throw network::error(_("Could not send initial handshake")); } waiting_sockets.insert(connect); sockets.push_back(connect); return connect; } } //anon namespace connection accept_connection() { if(!server_socket) { return 0; } // A connection isn't considered 'accepted' until it has sent its initial handshake. // The initial handshake is a 4 byte value, which is 0 for a new connection, // or the handle of the connection if it's trying to recover a lost connection. /** * A list of all the sockets which have connected, * but haven't had their initial handshake received. */ static std::vector<TCPsocket> pending_sockets; static SDLNet_SocketSet pending_socket_set = 0; const TCPsocket sock = SDLNet_TCP_Accept(server_socket); if(sock) { #if !defined(_WIN32) && !defined(__WIN32__) && !defined (WIN32) _TCPsocket* raw_sock = reinterpret_cast<_TCPsocket*>(sock); int fd_flags = fcntl(raw_sock->channel, F_GETFD, 0); fd_flags |= FD_CLOEXEC; if (fcntl(raw_sock->channel, F_SETFD, fd_flags) == -1) { WRN_NW << "could not make socket " << sock << " close-on-exec: " << strerror(errno); } else { DBG_NW << "made socket " << sock << " close-on-exec\n"; } #endif DBG_NW << "received connection. Pending handshake...\n"; if(pending_socket_set == 0) { pending_socket_set = SDLNet_AllocSocketSet(32); } if(pending_socket_set != 0) { int res = SDLNet_TCP_AddSocket(pending_socket_set,sock); if (res != -1) { pending_sockets.push_back(sock); } else { ERR_NW << "Pending socket set is full! Disconnecting " << sock << " connection" << std::endl; ERR_NW << "SDLNet_GetError(): " << SDLNet_GetError() << std::endl; SDLNet_TCP_Close(sock); } } else { ERR_NW << "Error in SDLNet_AllocSocketSet" << std::endl; } } if(pending_socket_set == 0) { return 0; } const int set_res = SDLNet_CheckSockets(pending_socket_set,0); if(set_res <= 0) { return 0; } return accept_connection_pending(pending_sockets, pending_socket_set); } bool disconnect(connection s) { if(s == 0) { while(sockets.empty() == false) { assert(sockets.back() != 0); while(disconnect(sockets.back()) == false) { SDL_Delay(1); } } return true; } if (!is_server()) last_ping = 0; const connection_map::iterator info = connections.find(s); if(info != connections.end()) { if (info->second.sock == server_socket) { return true; } if (!network_worker_pool::close_socket(info->second.sock)) { return false; } } bad_sockets.erase(s); std::deque<network::connection>::iterator dqi = std::find(disconnection_queue.begin(),disconnection_queue.end(),s); if(dqi != disconnection_queue.end()) { disconnection_queue.erase(dqi); } const sockets_list::iterator i = std::find(sockets.begin(),sockets.end(),s); if(i != sockets.end()) { sockets.erase(i); const TCPsocket sock = get_socket(s); waiting_sockets.erase(s); SDLNet_TCP_DelSocket(socket_set,sock); SDLNet_TCP_Close(sock); remove_connection(s); } else { if(sockets.size() == 1) { DBG_NW << "valid socket: " << static_cast<int>(*sockets.begin()) << "\n"; } } return true; } void queue_disconnect(network::connection sock) { disconnection_queue.push_back(sock); } connection receive_data(config& cfg, connection connection_num, unsigned int timeout, bandwidth_in_ptr* bandwidth_in) { unsigned int start_ticks = SDL_GetTicks(); while(true) { const connection res = receive_data( cfg,connection_num, bandwidth_in); if(res != 0) { return res; } if(timeout > SDL_GetTicks() - start_ticks) { SDL_Delay(1); } else { break; } } return 0; } connection receive_data(config& cfg, connection connection_num, bandwidth_in_ptr* bandwidth_in) { if(!socket_set) { return 0; } check_error(); if(disconnection_queue.empty() == false) { const network::connection sock = disconnection_queue.front(); disconnection_queue.pop_front(); throw error("",sock); } if(bad_sockets.count(connection_num) || bad_sockets.count(0)) { return 0; } if(sockets.empty()) { return 0; } const int res = SDLNet_CheckSockets(socket_set,0); for(std::set<network::connection>::iterator i = waiting_sockets.begin(); res != 0 && i != waiting_sockets.end(); ) { connection_details& details = get_connection_details(*i); const TCPsocket sock = details.sock; if(SDLNet_SocketReady(sock)) { // See if this socket is still waiting for it to be assigned its remote handle. // If it is, then the first 4 bytes must be the remote handle. if(is_pending_remote_handle(*i)) { union { char data[4] ALIGN_4; } buf; int len = SDLNet_TCP_Recv(sock,&buf,4); if(len != 4) { throw error("Remote host disconnected",*i); } const int remote_handle = SDLNet_Read32(&buf); set_remote_handle(*i,remote_handle); continue; } waiting_sockets.erase(i++); SDLNet_TCP_DelSocket(socket_set,sock); network_worker_pool::receive_data(sock); } else { ++i; } } TCPsocket sock = connection_num == 0 ? 0 : get_socket(connection_num); TCPsocket s = sock; bandwidth_in_ptr temp; if (!bandwidth_in) { bandwidth_in = &temp; } try { sock = network_worker_pool::get_received_data(sock,cfg, *bandwidth_in); } catch(const config::error& e) { TCPsocket const * err_sock = boost::get_error_info<tcpsocket_info>(e); if(err_sock == nullptr) throw; connection err_connection = 0; for(connection_map::const_iterator i = connections.begin(); i != connections.end(); ++i) { if(i->second.sock == *err_sock) { err_connection = i->first; } } if(err_connection) { throw e << connection_info(err_connection); } throw; } if (sock == nullptr) { if (!is_server() && last_ping != 0 && ping_timeout != 0) { if (connection_num == 0) { s = get_socket(sockets.back()); } if (!network_worker_pool::is_locked(s)) { check_timeout(); } } return 0; } int set_res = SDLNet_TCP_AddSocket(socket_set,sock); if (set_res == -1) { ERR_NW << "Socket set is full! Disconnecting " << sock << " connection" << std::endl; SDLNet_TCP_Close(sock); return 0; } connection result = 0; for(connection_map::const_iterator j = connections.begin(); j != connections.end(); ++j) { if(j->second.sock == sock) { result = j->first; break; } } if(!cfg.empty()) { DBG_NW << "RECEIVED from: " << result << ": " << cfg; } assert(result != 0); waiting_sockets.insert(result); if(!is_server()) { const time_t& now = time(nullptr); if (cfg.has_attribute("ping")) { LOG_NW << "Lag: " << (now - lexical_cast<time_t>(cfg["ping"])) << "\n"; last_ping = now; } else if (last_ping != 0) { last_ping = now; } } return result; } connection receive_data(std::vector<char>& buf, bandwidth_in_ptr* bandwidth_in) { if(!socket_set) { return 0; } check_error(); if(disconnection_queue.empty() == false) { const network::connection sock = disconnection_queue.front(); disconnection_queue.pop_front(); throw error("",sock); } if(bad_sockets.count(0)) { return 0; } if(sockets.empty()) { return 0; } const int res = SDLNet_CheckSockets(socket_set,0); for(std::set<network::connection>::iterator i = waiting_sockets.begin(); res != 0 && i != waiting_sockets.end(); ) { connection_details& details = get_connection_details(*i); const TCPsocket sock = details.sock; if(SDLNet_SocketReady(sock)) { // See if this socket is still waiting for it to be assigned its remote handle. // If it is, then the first 4 bytes must be the remote handle. if(is_pending_remote_handle(*i)) { union { char data[4] ALIGN_4; } buf; int len = SDLNet_TCP_Recv(sock,&buf,4); if(len != 4) { throw error("Remote host disconnected",*i); } const int remote_handle = SDLNet_Read32(&buf); set_remote_handle(*i,remote_handle); continue; } waiting_sockets.erase(i++); SDLNet_TCP_DelSocket(socket_set,sock); network_worker_pool::receive_data(sock); } else { ++i; } } TCPsocket sock = network_worker_pool::get_received_data(buf); if (sock == nullptr) { return 0; } { bandwidth_in_ptr temp; if (!bandwidth_in) { bandwidth_in = &temp; } const int headers = 4; bandwidth_in->reset(new network::bandwidth_in(buf.size() + headers)); } int set_res = SDLNet_TCP_AddSocket(socket_set,sock); if (set_res == -1) { ERR_NW << "Socket set is full! Disconnecting " << sock << " connection" << std::endl; SDLNet_TCP_Close(sock); return 0; } connection result = 0; for(connection_map::const_iterator j = connections.begin(); j != connections.end(); ++j) { if(j->second.sock == sock) { result = j->first; break; } } assert(result != 0); waiting_sockets.insert(result); return result; } struct bandwidth_stats { int out_packets; int out_bytes; int in_packets; int in_bytes; int day; const static size_t type_width = 16; const static size_t packet_width = 7; const static size_t bytes_width = 10; bandwidth_stats& operator+=(const bandwidth_stats& a) { out_packets += a.out_packets; out_bytes += a.out_bytes; in_packets += a.in_packets; in_bytes += a.in_bytes; return *this; } }; typedef std::map<const std::string, bandwidth_stats> bandwidth_map; typedef std::vector<bandwidth_map> hour_stats_vector; static hour_stats_vector hour_stats(24); static bandwidth_map::iterator add_bandwidth_entry(const std::string& packet_type) { time_t now = time(0); struct tm * timeinfo = localtime(&now); int hour = timeinfo->tm_hour; int day = timeinfo->tm_mday; assert(hour < 24 && hour >= 0); std::pair<bandwidth_map::iterator,bool> insertion = hour_stats[hour].insert(std::make_pair(packet_type, bandwidth_stats())); bandwidth_map::iterator inserted = insertion.first; if (!insertion.second && day != inserted->second.day) { // clear previuos day stats hour_stats[hour].clear(); //insert again to cleared map insertion = hour_stats[hour].insert(std::make_pair(packet_type, bandwidth_stats())); inserted = insertion.first; } inserted->second.day = day; return inserted; } typedef boost::shared_ptr<bandwidth_stats> bandwidth_stats_ptr; struct bandwidth_stats_output { bandwidth_stats_output(std::stringstream& ss) : ss_(ss), totals_(new bandwidth_stats()) {} void operator()(const bandwidth_map::value_type& stats) { // name ss_ << " " << std::setw(bandwidth_stats::type_width) << stats.first << "| " << std::setw(bandwidth_stats::packet_width)<< stats.second.out_packets << "| " << std::setw(bandwidth_stats::bytes_width) << stats.second.out_bytes/1024 << "| " << std::setw(bandwidth_stats::packet_width)<< stats.second.in_packets << "| " << std::setw(bandwidth_stats::bytes_width) << stats.second.in_bytes/1024 << "\n"; *totals_ += stats.second; } void output_totals() { (*this)(std::make_pair(std::string("total"), *totals_)); } private: std::stringstream& ss_; bandwidth_stats_ptr totals_; }; std::string get_bandwidth_stats_all() { std::string result; for (int hour = 0; hour < 24; ++hour) { result += get_bandwidth_stats(hour); } return result; } std::string get_bandwidth_stats() { time_t now = time(0); struct tm * timeinfo = localtime(&now); int hour = timeinfo->tm_hour - 1; if (hour < 0) hour = 23; return get_bandwidth_stats(hour); } std::string get_bandwidth_stats(int hour) { assert(hour < 24 && hour >= 0); std::stringstream ss; ss << "Hour stat starting from " << hour << "\n " << std::left << std::setw(bandwidth_stats::type_width) << "Type of packet" << "| " << std::setw(bandwidth_stats::packet_width)<< "out #" << "| " << std::setw(bandwidth_stats::bytes_width) << "out KiB" << "| " << std::setw(bandwidth_stats::packet_width)<< "in #" << "| " << std::setw(bandwidth_stats::bytes_width) << "in KiB" << "\n"; bandwidth_stats_output outputer(ss); std::for_each(hour_stats[hour].begin(), hour_stats[hour].end(), outputer); outputer.output_totals(); return ss.str(); } void add_bandwidth_out(const std::string& packet_type, size_t len) { bandwidth_map::iterator itor = add_bandwidth_entry(packet_type); itor->second.out_bytes += len; ++(itor->second.out_packets); } void add_bandwidth_in(const std::string& packet_type, size_t len) { bandwidth_map::iterator itor = add_bandwidth_entry(packet_type); itor->second.in_bytes += len; ++(itor->second.in_packets); } bandwidth_in::~bandwidth_in() { add_bandwidth_in(type_, len_); } void send_file(const std::string& filename, connection connection_num, const std::string& packet_type) { assert(connection_num > 0); if(bad_sockets.count(connection_num) || bad_sockets.count(0)) { return; } const connection_map::iterator info = connections.find(connection_num); if (info == connections.end()) { ERR_NW << "Error: socket: " << connection_num << "\tnot found in connection_map. Not sending...\n"; return; } const int size = filesystem::file_size(filename); if(size < 0) { ERR_NW << "Could not determine size of file " << filename << ", not sending." << std::endl; return; } const int packet_headers = 4; add_bandwidth_out(packet_type, size + packet_headers); network_worker_pool::queue_file(info->second.sock, filename); } size_t send_data(const config& cfg, connection connection_num, const std::string& packet_type) { DBG_NW << "in send_data()...\n"; if(cfg.empty()) { return 0; } if(bad_sockets.count(connection_num) || bad_sockets.count(0)) { return 0; } // log_scope2(network, "sending data"); if(!connection_num) { DBG_NW << "sockets: " << sockets.size() << "\n"; size_t size = 0; for(sockets_list::const_iterator i = sockets.begin(); i != sockets.end(); ++i) { DBG_NW << "server socket: " << server_socket << "\ncurrent socket: " << *i << "\n"; size = send_data(cfg,*i, packet_type); } return size; } const connection_map::iterator info = connections.find(connection_num); if (info == connections.end()) { ERR_NW << "Error: socket: " << connection_num << "\tnot found in connection_map. Not sending...\n"; return 0; } LOG_NW << "SENDING to: " << connection_num << ": " << cfg; return network_worker_pool::queue_data(info->second.sock, cfg, packet_type); } void send_raw_data(const char* buf, int len, connection connection_num, const std::string& packet_type) { if(len == 0) { return; } if(bad_sockets.count(connection_num) || bad_sockets.count(0)) { return; } if(!connection_num) { for(sockets_list::const_iterator i = sockets.begin(); i != sockets.end(); ++i) { send_raw_data(buf, len, *i, packet_type); } return; } const connection_map::iterator info = connections.find(connection_num); if (info == connections.end()) { ERR_NW << "Error: socket: " << connection_num << "\tnot found in connection_map. Not sending...\n"; return; } const int packet_headers = 4; add_bandwidth_out(packet_type, len + packet_headers); network_worker_pool::queue_raw_data(info->second.sock, buf, len); } void process_send_queue(connection, size_t) { check_error(); } void send_data_all_except(const config& cfg, connection connection_num, const std::string& packet_type) { for(sockets_list::const_iterator i = sockets.begin(); i != sockets.end(); ++i) { if(*i == connection_num) { continue; } send_data(cfg,*i, packet_type); } } std::string ip_address(connection connection_num) { std::stringstream str; const IPaddress* const ip = SDLNet_TCP_GetPeerAddress(get_socket(connection_num)); if(ip != nullptr) { const unsigned char* buf = reinterpret_cast<const unsigned char*>(&ip->host); for(int i = 0; i != sizeof(ip->host); ++i) { str << int(buf[i]); if(i+1 != sizeof(ip->host)) { str << '.'; } } } return str.str(); } statistics get_send_stats(connection handle) { return network_worker_pool::get_current_transfer_stats(handle == 0 ? get_socket(sockets.back()) : get_socket(handle)).first; } statistics get_receive_stats(connection handle) { const statistics result = network_worker_pool::get_current_transfer_stats(handle == 0 ? get_socket(sockets.back()) : get_socket(handle)).second; return result; } } // end namespace network
suxinde2009/wesnoth
src/network.cpp
C++
gpl-2.0
30,162
<?php /* Plugin Name: Contact Form Plugin Plugin URI: http://bestwebsoft.com/plugin/ Description: Plugin for Contact Form. Author: BestWebSoft Version: 3.61 Author URI: http://bestwebsoft.com/ License: GPLv2 or later */ /* Copyright 2011 BestWebSoft ( http://support.bestwebsoft.com ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ require_once( dirname( __FILE__ ) . '/bws_menu/bws_menu.php' ); // Add option page in admin menu if( ! function_exists( 'cntctfrm_admin_menu' ) ) { function cntctfrm_admin_menu() { add_menu_page( 'BWS Plugins', 'BWS Plugins', 'edit_themes', 'bws_plugins', 'bws_add_menu_render', plugins_url( "images/px.png", __FILE__ ), 1001); add_submenu_page('bws_plugins', __( 'Contact Form Settings', 'contact_form' ), __( 'Contact Form', 'contact_form' ), 'edit_themes', "contact_form.php", 'cntctfrm_settings_page'); add_submenu_page('contact_form.php', __( 'Contact Form Pro Extra Settings', 'contact_form' ), __( 'Contact Form Pro', 'contact_form' ), 'edit_themes', "contact_form_pro_extra.php", 'cntctfrm_settings_page_extra'); //call register settings function add_action( 'admin_init', 'cntctfrm_settings' ); } } // Register settings for plugin if( ! function_exists( 'cntctfrm_settings' ) ) { function cntctfrm_settings() { global $wpmu, $cntctfrm_options, $cntctfrm_option_defaults, $wpdb; $cntctfrm_option_defaults = array( 'cntctfrm_user_email' => 'admin', 'cntctfrm_custom_email' => '', 'cntctfrm_select_email' => 'user', 'cntctfrm_from_email' => 'user', 'cntctfrm_custom_from_email' => '', 'cntctfrm_additions_options' => 0, 'cntctfrm_attachment' => 0, 'cntctfrm_attachment_explanations' => 1, 'cntctfrm_send_copy' => 0, 'cntctfrm_from_field' => get_bloginfo( 'name' ), 'cntctfrm_select_from_field' => 'custom', 'cntctfrm_display_phone_field' => 0, 'cntctfrm_display_address_field' => 0, 'cntctfrm_required_name_field' => 1, 'cntctfrm_required_address_field' => 0, 'cntctfrm_required_email_field' => 1, 'cntctfrm_required_phone_field' => 0, 'cntctfrm_required_subject_field' => 1, 'cntctfrm_required_message_field' => 1, 'cntctfrm_required_symbol' => 1, 'cntctfrm_display_add_info' => 1, 'cntctfrm_display_sent_from' => 1, 'cntctfrm_display_date_time' => 1, 'cntctfrm_mail_method' => 'wp-mail', 'cntctfrm_display_coming_from' => 1, 'cntctfrm_display_user_agent' => 1, 'cntctfrm_language' => array(), 'cntctfrm_change_label' => 0, 'cntctfrm_name_label' => array( 'en' => __( "Name:", 'contact_form' ) ), 'cntctfrm_address_label' => array( 'en' => __( "Address:", 'contact_form' ) ), 'cntctfrm_email_label' => array( 'en' => __( "Email Address:", 'contact_form' ) ), 'cntctfrm_phone_label' => array( 'en' => __( "Phone number:", 'contact_form' ) ), 'cntctfrm_subject_label' => array( 'en' => __( "Subject:", 'contact_form' ) ), 'cntctfrm_message_label' => array( 'en' => __( "Message:", 'contact_form' ) ), 'cntctfrm_attachment_label' => array( 'en' => __( "Attachment:", 'contact_form' ) ), 'cntctfrm_send_copy_label' => array( 'en' => __( "Send me a copy", 'contact_form' ) ), 'cntctfrm_submit_label' => array( 'en' => __( "Submit", 'contact_form' ) ), 'cntctfrm_name_error' => array( 'en' => __( "Your name is required.", 'contact_form' ) ), 'cntctfrm_address_error' => array( 'en' => __( "Address is required.", 'contact_form' ) ), 'cntctfrm_email_error' => array( 'en' => __( "A valid email address is required.", 'contact_form' ) ), 'cntctfrm_phone_error' => array( 'en' => __( "Phone number is required.", 'contact_form' ) ), 'cntctfrm_subject_error' => array( 'en' => __( "Subject is required.", 'contact_form' ) ), 'cntctfrm_message_error' => array( 'en' => __( "Message text is required.", 'contact_form' ) ), 'cntctfrm_attachment_error' => array( 'en' => __( "File format is not valid.", 'contact_form' ) ), 'cntctfrm_attachment_upload_error' => array( 'en' => __( "File upload error.", 'contact_form' ) ), 'cntctfrm_attachment_move_error' => array( 'en' => __( "The file could not be uploaded.", 'contact_form' ) ), 'cntctfrm_attachment_size_error' => array( 'en' => __( "This file is too large.", 'contact_form' ) ), 'cntctfrm_captcha_error' => array( 'en' => __( "Please fill out the CAPTCHA.", 'contact_form' ) ), 'cntctfrm_form_error' => array( 'en' => __( "Please make corrections below and try again.", 'contact_form' ) ), 'cntctfrm_action_after_send' => 1, 'cntctfrm_thank_text' => array( 'en' => __( "Thank you for contacting us.", 'contact_form' ) ), 'cntctfrm_redirect_url' => '', 'cntctfrm_delete_attached_file' => '0' ); // install the option defaults if ( 1 == $wpmu ) { if ( !get_site_option( 'cntctfrm_options' ) ) { add_site_option( 'cntctfrm_options', $cntctfrm_option_defaults, '', 'yes' ); } } else { if ( !get_option( 'cntctfrm_options' ) ) add_option( 'cntctfrm_options', $cntctfrm_option_defaults, '', 'yes' ); } // get options from the database if ( 1 == $wpmu ) $cntctfrm_options = get_site_option( 'cntctfrm_options' ); // get options from the database else $cntctfrm_options = get_option( 'cntctfrm_options' );// get options from the database if ( empty( $cntctfrm_options['cntctfrm_language'] ) && ! is_array( $cntctfrm_options['cntctfrm_name_label'] ) ) { $cntctfrm_options['cntctfrm_name_label'] = array( 'en' => $cntctfrm_options['cntctfrm_name_label'] ); $cntctfrm_options['cntctfrm_address_label'] = array( 'en' => $cntctfrm_options['cntctfrm_address_label'] ); $cntctfrm_options['cntctfrm_email_label'] = array( 'en' => $cntctfrm_options['cntctfrm_email_label'] ); $cntctfrm_options['cntctfrm_phone_label'] = array( 'en' => $cntctfrm_options['cntctfrm_phone_label'] ); $cntctfrm_options['cntctfrm_subject_label'] = array( 'en' => $cntctfrm_options['cntctfrm_subject_label'] ); $cntctfrm_options['cntctfrm_message_label'] = array( 'en' => $cntctfrm_options['cntctfrm_message_label'] ); $cntctfrm_options['cntctfrm_attachment_label'] = array( 'en' => $cntctfrm_options['cntctfrm_attachment_label'] ); $cntctfrm_options['cntctfrm_send_copy_label'] = array( 'en' => $cntctfrm_options['cntctfrm_send_copy_label'] ); $cntctfrm_options['cntctfrm_thank_text'] = array( 'en' => $cntctfrm_options['cntctfrm_thank_text'] ); $cntctfrm_options['cntctfrm_submit_label'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_submit_label']['en'] ); $cntctfrm_options['cntctfrm_name_error'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_name_error']['en'] ); $cntctfrm_options['cntctfrm_address_error'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_address_error']['en'] ); $cntctfrm_options['cntctfrm_email_error'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_email_error']['en'] ); $cntctfrm_options['cntctfrm_phone_error'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_phone_error']['en'] ); $cntctfrm_options['cntctfrm_subject_error'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_subject_error']['en'] ); $cntctfrm_options['cntctfrm_message_error'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_message_error']['en'] ); $cntctfrm_options['cntctfrm_attachment_error'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_attachment_error']['en'] ); $cntctfrm_options['cntctfrm_attachment_upload_error'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_attachment_upload_error']['en'] ); $cntctfrm_options['cntctfrm_attachment_move_error'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_attachment_move_error']['en'] ); $cntctfrm_options['cntctfrm_attachment_size_error'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_attachment_size_error']['en'] ); $cntctfrm_options['cntctfrm_captcha_error'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_captcha_error']['en'] ); $cntctfrm_options['cntctfrm_form_error'] = array( 'en' => $cntctfrm_option_defaults['cntctfrm_form_error']['en'] ); } $cntctfrm_options = array_merge( $cntctfrm_option_defaults, $cntctfrm_options ); update_option( 'cntctfrm_options', $cntctfrm_options ); // create db table of fields list $wpdb->query("DROP TABLE IF EXISTS " . $wpdb->prefix . "cntctfrm_field" ); $sql = "CREATE TABLE IF NOT EXISTS `" . $wpdb->prefix . "cntctfrm_field` ( id int NOT NULL AUTO_INCREMENT, name CHAR(100) NOT NULL, UNIQUE KEY id (id) );"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); $fields = array( 'name', 'email', 'subject', 'message', 'address', 'phone', 'attachment', 'attachment_explanations', 'send_copy', 'sent_from', 'date_time', 'coming_from', 'user_agent' ); foreach ( $fields as $key => $value ) { $db_row = $wpdb->get_row( "SELECT * FROM " . $wpdb->prefix . "cntctfrm_field WHERE `name` = '" . $value . "'", ARRAY_A ); if ( !isset( $db_row ) || empty( $db_row ) ) { $wpdb->insert( $wpdb->prefix . "cntctfrm_field", array( 'name' => $value ), array( '%s' ) ); } } } } // Add settings page in admin area if( ! function_exists( 'cntctfrm_settings_page' ) ) { function cntctfrm_settings_page() { global $cntctfrm_options, $wpdb, $cntctfrm_option_defaults, $wp_version; $plugin_info = get_plugin_data( __FILE__ ); /* Get Captcha options */ if ( get_option( 'cptch_options' ) ) $cptch_options = get_option( 'cptch_options' ); if ( get_option( 'cptchpr_options' ) ) $cptchpr_options = get_option( 'cptchpr_options' ); /* Get Contact Form to DB options */ if ( get_option( 'cntctfrmtdb_options' ) ) $cntctfrmtdb_options = get_option( 'cntctfrmtdb_options' ); if ( get_option( 'cntctfrmtdbpr_options' ) ) $cntctfrmtdbpr_options = get_option( 'cntctfrmtdbpr_options' ); $userslogin = $wpdb->get_col( "SELECT user_login FROM $wpdb->users ", 0 ); $error = ""; // Save data for settings page if( isset( $_POST['cntctfrm_form_submit'] ) && check_admin_referer( plugin_basename(__FILE__), 'cntctfrm_nonce_name' ) ) { $cntctfrm_options_submit['cntctfrm_user_email'] = $_POST['cntctfrm_user_email']; $cntctfrm_options_submit['cntctfrm_custom_email'] = stripslashes( $_POST['cntctfrm_custom_email'] ); $cntctfrm_options_submit['cntctfrm_select_email'] = $_POST['cntctfrm_select_email']; $cntctfrm_options_submit['cntctfrm_from_email'] = $_POST['cntctfrm_from_email']; $cntctfrm_options_submit['cntctfrm_custom_from_email'] = stripslashes( $_POST['cntctfrm_custom_from_email'] ); $cntctfrm_options_submit['cntctfrm_additions_options'] = isset( $_POST['cntctfrm_additions_options']) ? $_POST['cntctfrm_additions_options'] : 0; if ( $cntctfrm_options_submit['cntctfrm_additions_options'] == 0 ) { $cntctfrm_options_submit['cntctfrm_attachment'] = 0; $cntctfrm_options_submit['cntctfrm_attachment_explanations'] = 1; $cntctfrm_options_submit['cntctfrm_send_copy'] = 0; $cntctfrm_options_submit['cntctfrm_from_field'] = get_bloginfo( 'name' ); $cntctfrm_options_submit['cntctfrm_select_from_field'] = 'custom'; $cntctfrm_options_submit['cntctfrm_display_address_field'] = 0; $cntctfrm_options_submit['cntctfrm_display_phone_field'] = 0; $cntctfrm_options_submit['cntctfrm_required_name_field'] = 1; $cntctfrm_options_submit['cntctfrm_required_address_field'] = 0; $cntctfrm_options_submit['cntctfrm_required_email_field'] = 1; $cntctfrm_options_submit['cntctfrm_required_phone_field'] = 0; $cntctfrm_options_submit['cntctfrm_required_subject_field'] = 1; $cntctfrm_options_submit['cntctfrm_required_message_field'] = 1; $cntctfrm_options_submit['cntctfrm_required_symbol'] = 1; $cntctfrm_options_submit['cntctfrm_display_add_info'] = 1; $cntctfrm_options_submit['cntctfrm_display_sent_from'] = 1; $cntctfrm_options_submit['cntctfrm_display_date_time'] = 1; $cntctfrm_options_submit['cntctfrm_mail_method'] = 'wp-mail'; $cntctfrm_options_submit['cntctfrm_display_coming_from'] = 1; $cntctfrm_options_submit['cntctfrm_display_user_agent'] = 1; $cntctfrm_options_submit['cntctfrm_change_label'] = 0; $cntctfrm_options_submit['cntctfrm_action_after_send'] = 1; $cntctfrm_options_submit['cntctfrm_delete_attached_file'] = 0; if ( empty( $cntctfrm_options['cntctfrm_language'] ) ) { $cntctfrm_options_submit['cntctfrm_name_label'] = $cntctfrm_option_defaults['cntctfrm_name_label']; $cntctfrm_options_submit['cntctfrm_address_label'] = $cntctfrm_option_defaults['cntctfrm_address_label']; $cntctfrm_options_submit['cntctfrm_email_label'] = $cntctfrm_option_defaults['cntctfrm_email_label']; $cntctfrm_options_submit['cntctfrm_phone_label'] = $cntctfrm_option_defaults['cntctfrm_phone_label']; $cntctfrm_options_submit['cntctfrm_subject_label'] = $cntctfrm_option_defaults['cntctfrm_subject_label']; $cntctfrm_options_submit['cntctfrm_message_label'] = $cntctfrm_option_defaults['cntctfrm_message_label']; $cntctfrm_options_submit['cntctfrm_attachment_label'] = $cntctfrm_option_defaults['cntctfrm_attachment_label']; $cntctfrm_options_submit['cntctfrm_send_copy_label'] = $cntctfrm_option_defaults['cntctfrm_send_copy_label']; $cntctfrm_options_submit['cntctfrm_thank_text'] = $cntctfrm_option_defaults['cntctfrm_thank_text']; $cntctfrm_options_submit['cntctfrm_submit_label'] = $cntctfrm_option_defaults['cntctfrm_submit_label']; $cntctfrm_options_submit['cntctfrm_name_error'] = $cntctfrm_option_defaults['cntctfrm_name_error']; $cntctfrm_options_submit['cntctfrm_address_error'] = $cntctfrm_option_defaults['cntctfrm_address_error']; $cntctfrm_options_submit['cntctfrm_email_error'] = $cntctfrm_option_defaults['cntctfrm_email_error']; $cntctfrm_options_submit['cntctfrm_phone_error'] = $cntctfrm_option_defaults['cntctfrm_phone_error']; $cntctfrm_options_submit['cntctfrm_subject_error'] = $cntctfrm_option_defaults['cntctfrm_subject_error']; $cntctfrm_options_submit['cntctfrm_message_error'] = $cntctfrm_option_defaults['cntctfrm_message_error']; $cntctfrm_options_submit['cntctfrm_attachment_error'] = $cntctfrm_option_defaults['cntctfrm_attachment_error']; $cntctfrm_options_submit['cntctfrm_attachment_upload_error'] = $cntctfrm_option_defaults['cntctfrm_attachment_upload_error']; $cntctfrm_options_submit['cntctfrm_attachment_move_error'] = $cntctfrm_option_defaults['cntctfrm_attachment_move_error']; $cntctfrm_options_submit['cntctfrm_attachment_size_error'] = $cntctfrm_option_defaults['cntctfrm_attachment_size_error']; $cntctfrm_options_submit['cntctfrm_captcha_error'] = $cntctfrm_option_defaults['cntctfrm_captcha_error']; $cntctfrm_options_submit['cntctfrm_form_error'] = $cntctfrm_option_defaults['cntctfrm_form_error']; } else { $cntctfrm_options_submit['cntctfrm_name_label']['en'] = $cntctfrm_option_defaults['cntctfrm_name_label']['en']; $cntctfrm_options_submit['cntctfrm_address_label']['en'] = $cntctfrm_option_defaults['cntctfrm_address_label']['en']; $cntctfrm_options_submit['cntctfrm_email_label']['en'] = $cntctfrm_option_defaults['cntctfrm_email_label']['en']; $cntctfrm_options_submit['cntctfrm_phone_label']['en'] = $cntctfrm_option_defaults['cntctfrm_phone_label']['en']; $cntctfrm_options_submit['cntctfrm_subject_label']['en'] = $cntctfrm_option_defaults['cntctfrm_subject_label']['en']; $cntctfrm_options_submit['cntctfrm_message_label']['en'] = $cntctfrm_option_defaults['cntctfrm_message_label']['en']; $cntctfrm_options_submit['cntctfrm_attachment_label']['en'] = $cntctfrm_option_defaults['cntctfrm_attachment_label']['en']; $cntctfrm_options_submit['cntctfrm_send_copy_label']['en'] = $cntctfrm_option_defaults['cntctfrm_send_copy_label']['en']; $cntctfrm_options_submit['cntctfrm_thank_text']['en'] = $cntctfrm_option_defaults['cntctfrm_thank_text']['en']; $cntctfrm_options_submit['cntctfrm_submit_label']['en'] = $cntctfrm_option_defaults['cntctfrm_submit_label']['en']; $cntctfrm_options_submit['cntctfrm_name_error']['en'] = $cntctfrm_option_defaults['cntctfrm_name_error']['en']; $cntctfrm_options_submit['cntctfrm_address_error']['en'] = $cntctfrm_option_defaults['cntctfrm_address_error']['en']; $cntctfrm_options_submit['cntctfrm_email_error']['en'] = $cntctfrm_option_defaults['cntctfrm_email_error']['en']; $cntctfrm_options_submit['cntctfrm_phone_error']['en'] = $cntctfrm_option_defaults['cntctfrm_phone_error']['en']; $cntctfrm_options_submit['cntctfrm_subject_error']['en'] = $cntctfrm_option_defaults['cntctfrm_subject_error']['en']; $cntctfrm_options_submit['cntctfrm_message_error']['en'] = $cntctfrm_option_defaults['cntctfrm_message_error']['en']; $cntctfrm_options_submit['cntctfrm_attachment_error']['en'] = $cntctfrm_option_defaults['cntctfrm_attachment_error']['en']; $cntctfrm_options_submit['cntctfrm_attachment_upload_error']['en'] = $cntctfrm_option_defaults['cntctfrm_attachment_upload_error']['en']; $cntctfrm_options_submit['cntctfrm_attachment_move_error']['en'] = $cntctfrm_option_defaults['cntctfrm_attachment_move_error']['en']; $cntctfrm_options_submit['cntctfrm_attachment_size_error']['en'] = $cntctfrm_option_defaults['cntctfrm_attachment_size_error']['en']; $cntctfrm_options_submit['cntctfrm_captcha_error']['en'] = $cntctfrm_option_defaults['cntctfrm_captcha_error']['en']; $cntctfrm_options_submit['cntctfrm_form_error']['en'] = $cntctfrm_option_defaults['cntctfrm_form_error']['en']; } $cntctfrm_options_submit['cntctfrm_redirect_url'] = ''; } else { $cntctfrm_options_submit['cntctfrm_mail_method'] = $_POST['cntctfrm_mail_method']; $cntctfrm_options_submit['cntctfrm_from_field'] = $_POST['cntctfrm_from_field']; $cntctfrm_options_submit['cntctfrm_select_from_field'] = $_POST['cntctfrm_select_from_field']; $cntctfrm_options_submit['cntctfrm_display_address_field'] = isset( $_POST['cntctfrm_display_address_field']) ? 1 : 0; $cntctfrm_options_submit['cntctfrm_display_phone_field'] = isset( $_POST['cntctfrm_display_phone_field']) ? 1 : 0; $cntctfrm_options_submit['cntctfrm_attachment'] = isset( $_POST['cntctfrm_attachment']) ? $_POST['cntctfrm_attachment'] : 0; $cntctfrm_options_submit['cntctfrm_attachment_explanations'] = isset( $_POST['cntctfrm_attachment_explanations']) ? $_POST['cntctfrm_attachment_explanations'] : 0; $cntctfrm_options_submit['cntctfrm_send_copy'] = isset( $_POST['cntctfrm_send_copy']) ? $_POST['cntctfrm_send_copy'] : 0; $cntctfrm_options_submit['cntctfrm_delete_attached_file'] = isset( $_POST['cntctfrm_delete_attached_file']) ? $_POST['cntctfrm_delete_attached_file'] : 0; if ( isset( $_POST['cntctfrm_display_captcha'] ) ) { if ( get_option( 'cptch_options' ) ) { $cptch_options['cptch_contact_form'] = 1; update_option( 'cptch_options', $cptch_options, '', 'yes' ); } if ( get_option( 'cptchpr_options' ) ) { $cptchpr_options['cptchpr_contact_form'] = 1; update_option( 'cptchpr_options', $cptchpr_options, '', 'yes' ); } } else { if ( get_option( 'cptch_options' ) ) { $cptch_options['cptch_contact_form'] = 0; update_option( 'cptch_options', $cptch_options, '', 'yes' ); } if ( get_option( 'cptchpr_options' ) ) { $cptchpr_options['cptchpr_contact_form'] = 0; update_option( 'cptchpr_options', $cptchpr_options, '', 'yes' ); } } if ( isset( $_POST['cntctfrm_save_email_to_db'] ) ) { if ( get_option( 'cntctfrmtdb_options' ) ) { $cntctfrmtdb_options['cntctfrmtdb_save_messages_to_db'] = 1; update_option( 'cntctfrmtdb_options', $cntctfrmtdb_options, '', 'yes' ); } if ( get_option( 'cntctfrmtdbpr_options' ) ) { $cntctfrmtdbpr_options['save_messages_to_db'] = 1; update_option( 'cntctfrmtdbpr_options', $cntctfrmtdbpr_options, '', 'yes' ); } } else { if ( get_option( 'cntctfrmtdb_options' ) ) { $cntctfrmtdb_options['cntctfrmtdb_save_messages_to_db'] = 0; update_option( 'cntctfrmtdb_options', $cntctfrmtdb_options, '', 'yes' ); } if ( get_option( 'cntctfrmtdbpr_options' ) ) { $cntctfrmtdbpr_options['save_messages_to_db'] = 0; update_option( 'cntctfrmtdbpr_options', $cntctfrmtdbpr_options, '', 'yes' ); } } $cntctfrm_options_submit['cntctfrm_required_name_field'] = isset( $_POST['cntctfrm_required_name_field']) ? 1 : 0; if ( $cntctfrm_options_submit['cntctfrm_display_address_field'] == 0 ) { $cntctfrm_options_submit['cntctfrm_required_address_field'] = 0; } else { $cntctfrm_options_submit['cntctfrm_required_address_field'] = isset( $_POST['cntctfrm_required_address_field']) ? 1 : 0; } $cntctfrm_options_submit['cntctfrm_required_email_field'] = isset( $_POST['cntctfrm_required_email_field']) ? 1 : 0; if ( $cntctfrm_options_submit['cntctfrm_display_phone_field'] == 0 ) { $cntctfrm_options_submit['cntctfrm_required_phone_field'] = 0; } else { $cntctfrm_options_submit['cntctfrm_required_phone_field'] = isset( $_POST['cntctfrm_required_phone_field']) ? 1 : 0; } $cntctfrm_options_submit['cntctfrm_required_subject_field'] = isset( $_POST['cntctfrm_required_subject_field']) ? 1 : 0; $cntctfrm_options_submit['cntctfrm_required_message_field'] = isset( $_POST['cntctfrm_required_message_field']) ? 1 : 0; $cntctfrm_options_submit['cntctfrm_required_symbol'] = isset( $_POST['cntctfrm_required_symbol']) ? 1 : 0; $cntctfrm_options_submit['cntctfrm_display_add_info'] = isset( $_POST['cntctfrm_display_add_info']) ? 1 : 0; if ( $cntctfrm_options_submit['cntctfrm_display_add_info'] == 1 ) { $cntctfrm_options_submit['cntctfrm_display_sent_from'] = isset( $_POST['cntctfrm_display_sent_from']) ? 1 : 0; $cntctfrm_options_submit['cntctfrm_display_date_time'] = isset( $_POST['cntctfrm_display_date_time']) ? 1 : 0; $cntctfrm_options_submit['cntctfrm_display_coming_from'] = isset( $_POST['cntctfrm_display_coming_from']) ? 1 : 0; $cntctfrm_options_submit['cntctfrm_display_user_agent'] = isset( $_POST['cntctfrm_display_user_agent']) ? 1 : 0; } else { $cntctfrm_options_submit['cntctfrm_display_sent_from'] = 1; $cntctfrm_options_submit['cntctfrm_display_date_time'] = 1; $cntctfrm_options_submit['cntctfrm_display_coming_from'] = 1; $cntctfrm_options_submit['cntctfrm_display_user_agent'] = 1; } $cntctfrm_options_submit['cntctfrm_change_label'] = isset( $_POST['cntctfrm_change_label']) ? 1 : 0; if ( $cntctfrm_options_submit['cntctfrm_change_label'] == 1 ) { foreach( $_POST['cntctfrm_name_label'] as $key=>$val ){ $cntctfrm_options_submit['cntctfrm_name_label'][$key] = $_POST['cntctfrm_name_label'][$key]; $cntctfrm_options_submit['cntctfrm_address_label'][$key] = $_POST['cntctfrm_address_label'][$key]; $cntctfrm_options_submit['cntctfrm_email_label'][$key] = $_POST['cntctfrm_email_label'][$key]; $cntctfrm_options_submit['cntctfrm_phone_label'][$key] = $_POST['cntctfrm_phone_label'][$key]; $cntctfrm_options_submit['cntctfrm_subject_label'][$key] = $_POST['cntctfrm_subject_label'][$key]; $cntctfrm_options_submit['cntctfrm_message_label'][$key] = $_POST['cntctfrm_message_label'][$key]; $cntctfrm_options_submit['cntctfrm_attachment_label'][$key] = $_POST['cntctfrm_attachment_label'][$key]; $cntctfrm_options_submit['cntctfrm_send_copy_label'][$key] = $_POST['cntctfrm_send_copy_label'][$key]; $cntctfrm_options_submit['cntctfrm_thank_text'][$key] = $_POST['cntctfrm_thank_text'][$key]; $cntctfrm_options_submit['cntctfrm_submit_label'][$key] = $_POST['cntctfrm_submit_label'][$key]; $cntctfrm_options_submit['cntctfrm_name_error'][$key] = $_POST['cntctfrm_name_error'][$key]; $cntctfrm_options_submit['cntctfrm_address_error'][$key] = $_POST['cntctfrm_address_error'][$key]; $cntctfrm_options_submit['cntctfrm_email_error'][$key] = $_POST['cntctfrm_email_error'][$key]; $cntctfrm_options_submit['cntctfrm_phone_error'][$key] = $_POST['cntctfrm_phone_error'][$key]; $cntctfrm_options_submit['cntctfrm_subject_error'][$key] = $_POST['cntctfrm_subject_error'][$key]; $cntctfrm_options_submit['cntctfrm_message_error'][$key] = $_POST['cntctfrm_message_error'][$key]; $cntctfrm_options_submit['cntctfrm_attachment_error'][$key] = $_POST['cntctfrm_attachment_error'][$key]; $cntctfrm_options_submit['cntctfrm_attachment_upload_error'][$key] = $_POST['cntctfrm_attachment_upload_error'][$key]; $cntctfrm_options_submit['cntctfrm_attachment_move_error'][$key] = $_POST['cntctfrm_attachment_move_error'][$key]; $cntctfrm_options_submit['cntctfrm_attachment_size_error'][$key] = $_POST['cntctfrm_attachment_size_error'][$key]; $cntctfrm_options_submit['cntctfrm_captcha_error'][$key] = $_POST['cntctfrm_captcha_error'][$key]; $cntctfrm_options_submit['cntctfrm_form_error'][$key] = $_POST['cntctfrm_form_error'][$key]; } } else { if( empty( $cntctfrm_options['cntctfrm_language'] ) ) { $cntctfrm_options_submit['cntctfrm_name_label'] = $cntctfrm_option_defaults['cntctfrm_name_label']; $cntctfrm_options_submit['cntctfrm_address_label'] = $cntctfrm_option_defaults['cntctfrm_address_label']; $cntctfrm_options_submit['cntctfrm_email_label'] = $cntctfrm_option_defaults['cntctfrm_email_label']; $cntctfrm_options_submit['cntctfrm_phone_label'] = $cntctfrm_option_defaults['cntctfrm_phone_label']; $cntctfrm_options_submit['cntctfrm_subject_label'] = $cntctfrm_option_defaults['cntctfrm_subject_label']; $cntctfrm_options_submit['cntctfrm_message_label'] = $cntctfrm_option_defaults['cntctfrm_message_label']; $cntctfrm_options_submit['cntctfrm_attachment_label'] = $cntctfrm_option_defaults['cntctfrm_attachment_label']; $cntctfrm_options_submit['cntctfrm_send_copy_label'] = $cntctfrm_option_defaults['cntctfrm_send_copy_label']; // $cntctfrm_options_submit['cntctfrm_thank_text'] = $cntctfrm_option_defaults['cntctfrm_thank_text']; $cntctfrm_options_submit['cntctfrm_thank_text'] = $_POST['cntctfrm_thank_text']; $cntctfrm_options_submit['cntctfrm_submit_label'] = $cntctfrm_option_defaults['cntctfrm_submit_label']; $cntctfrm_options_submit['cntctfrm_name_error'] = $cntctfrm_option_defaults['cntctfrm_name_error']; $cntctfrm_options_submit['cntctfrm_address_error'] = $cntctfrm_option_defaults['cntctfrm_address_error']; $cntctfrm_options_submit['cntctfrm_email_error'] = $cntctfrm_option_defaults['cntctfrm_email_error']; $cntctfrm_options_submit['cntctfrm_phone_error'] = $cntctfrm_option_defaults['cntctfrm_phone_error']; $cntctfrm_options_submit['cntctfrm_subject_error'] = $cntctfrm_option_defaults['cntctfrm_subject_error']; $cntctfrm_options_submit['cntctfrm_message_error'] = $cntctfrm_option_defaults['cntctfrm_message_error']; $cntctfrm_options_submit['cntctfrm_attachment_error'] = $cntctfrm_option_defaults['cntctfrm_attachment_error']; $cntctfrm_options_submit['cntctfrm_attachment_upload_error'] = $cntctfrm_option_defaults['cntctfrm_attachment_upload_error']; $cntctfrm_options_submit['cntctfrm_attachment_move_error'] = $cntctfrm_option_defaults['cntctfrm_attachment_move_error']; $cntctfrm_options_submit['cntctfrm_attachment_size_error'] = $cntctfrm_option_defaults['cntctfrm_attachment_size_error']; $cntctfrm_options_submit['cntctfrm_captcha_error'] = $cntctfrm_option_defaults['cntctfrm_captcha_error']; $cntctfrm_options_submit['cntctfrm_form_error'] = $cntctfrm_option_defaults['cntctfrm_form_error']; } else{ $cntctfrm_options_submit['cntctfrm_name_label']['en'] = $cntctfrm_option_defaults['cntctfrm_name_label']['en']; $cntctfrm_options_submit['cntctfrm_address_label']['en'] = $cntctfrm_option_defaults['cntctfrm_address_label']['en']; $cntctfrm_options_submit['cntctfrm_email_label']['en'] = $cntctfrm_option_defaults['cntctfrm_email_label']['en']; $cntctfrm_options_submit['cntctfrm_phone_label']['en'] = $cntctfrm_option_defaults['cntctfrm_phone_label']['en']; $cntctfrm_options_submit['cntctfrm_subject_label']['en'] = $cntctfrm_option_defaults['cntctfrm_subject_label']['en']; $cntctfrm_options_submit['cntctfrm_message_label']['en'] = $cntctfrm_option_defaults['cntctfrm_message_label']['en']; $cntctfrm_options_submit['cntctfrm_attachment_label']['en'] = $cntctfrm_option_defaults['cntctfrm_attachment_label']['en']; $cntctfrm_options_submit['cntctfrm_send_copy_label']['en'] = $cntctfrm_option_defaults['cntctfrm_send_copy_label']['en']; // $cntctfrm_options_submit['cntctfrm_thank_text']['en'] = $cntctfrm_option_defaults['cntctfrm_thank_text']['en']; $cntctfrm_options_submit['cntctfrm_submit_label']['en'] = $cntctfrm_option_defaults['cntctfrm_submit_label']['en']; $cntctfrm_options_submit['cntctfrm_name_error']['en'] = $cntctfrm_option_defaults['cntctfrm_name_error']['en']; $cntctfrm_options_submit['cntctfrm_address_error']['en'] = $cntctfrm_option_defaults['cntctfrm_address_error']['en']; $cntctfrm_options_submit['cntctfrm_email_error']['en'] = $cntctfrm_option_defaults['cntctfrm_email_error']['en']; $cntctfrm_options_submit['cntctfrm_phone_error']['en'] = $cntctfrm_option_defaults['cntctfrm_phone_error']['en']; $cntctfrm_options_submit['cntctfrm_subject_error']['en'] = $cntctfrm_option_defaults['cntctfrm_subject_error']['en']; $cntctfrm_options_submit['cntctfrm_message_error']['en'] = $cntctfrm_option_defaults['cntctfrm_message_error']['en']; $cntctfrm_options_submit['cntctfrm_attachment_error']['en'] = $cntctfrm_option_defaults['cntctfrm_attachment_error']['en']; $cntctfrm_options_submit['cntctfrm_attachment_upload_error']['en'] = $cntctfrm_option_defaults['cntctfrm_attachment_upload_error']['en']; $cntctfrm_options_submit['cntctfrm_attachment_move_error']['en'] = $cntctfrm_option_defaults['cntctfrm_attachment_move_error']['en']; $cntctfrm_options_submit['cntctfrm_attachment_size_error']['en'] = $cntctfrm_option_defaults['cntctfrm_attachment_size_error']['en']; $cntctfrm_options_submit['cntctfrm_captcha_error']['en'] = $cntctfrm_option_defaults['cntctfrm_captcha_error']['en']; $cntctfrm_options_submit['cntctfrm_form_error']['en'] = $cntctfrm_option_defaults['cntctfrm_form_error']['en']; foreach( $_POST['cntctfrm_thank_text'] as $key => $val ) { $cntctfrm_options_submit['cntctfrm_thank_text'][$key] = $_POST['cntctfrm_thank_text'][$key]; } } } $cntctfrm_options_submit['cntctfrm_action_after_send'] = $_POST['cntctfrm_action_after_send']; $cntctfrm_options_submit['cntctfrm_redirect_url'] = $_POST['cntctfrm_redirect_url']; } $cntctfrm_options = array_merge( $cntctfrm_options, $cntctfrm_options_submit ); if( $cntctfrm_options_submit['cntctfrm_action_after_send'] == 0 && ( trim( $cntctfrm_options_submit['cntctfrm_redirect_url'] ) == "" || !preg_match( '@^(?:http://)?([^/]+)@i', trim( $cntctfrm_options_submit['cntctfrm_redirect_url'] ) ) ) ) { $error .=__( "If the 'Redirect to page' option is selected then the URL field should be in the following format", 'contact_form' )." <code>http://your_site/your_page</code>"; $cntctfrm_options['cntctfrm_action_after_send'] = 1; } if ( 'user' == $cntctfrm_options_submit['cntctfrm_select_email'] ) { if ( '3.3' > $wp_version && function_exists('get_userdatabylogin') && false !== get_userdatabylogin( $cntctfrm_options_submit['cntctfrm_user_email'] ) ) { // } else if( false !== get_user_by( 'login', $cntctfrm_options_submit['cntctfrm_user_email'] ) ) { // } else { $error .=__( "Such user does not exist. Settings are not saved.", 'contact_form' ); } } else { if( $cntctfrm_options_submit['cntctfrm_custom_email'] == "" || !preg_match( "/^((?:[a-z0-9_']+(?:[a-z0-9\-_\.']+)?@[a-z0-9]+(?:[a-z0-9\-\.]+)?\.[a-z]{2,5})[, ]*)+$/i", trim( $cntctfrm_options_submit['cntctfrm_custom_email'] ) ) ){ $error .= __( "Please enter a valid email address in the 'FROM' field. Settings are not saved.", 'contact_form' ); } } if ( 'custom' == $cntctfrm_options_submit['cntctfrm_from_email'] ) { if( $cntctfrm_options_submit['cntctfrm_custom_from_email'] == "" && !preg_match( "/^((?:[a-z0-9_']+(?:[a-z0-9\-_\.']+)?@[a-z0-9]+(?:[a-z0-9\-\.]+)?\.[a-z]{2,5})[, ]*)+$/i", trim( $cntctfrm_options_submit['cntctfrm_custom_from_email'] ) ) ) { $error .= __( "Please enter a valid email address in the 'FROM' field. Settings are not saved.", 'contact_form' ); } } if ( $error == '' ) { update_option( 'cntctfrm_options', $cntctfrm_options, '', 'yes' ); $message = __( "Settings saved.", 'contact_form' ); } } // Display form on the setting page $lang_codes = array( 'aa' => 'Afar', 'ab' => 'Abkhazian', 'af' => 'Afrikaans', 'ak' => 'Akan', 'sq' => 'Albanian', 'am' => 'Amharic', 'ar' => 'Arabic', 'an' => 'Aragonese', 'hy' => 'Armenian', 'as' => 'Assamese', 'av' => 'Avaric', 'ae' => 'Avestan', 'ay' => 'Aymara', 'az' => 'Azerbaijani', 'ba' => 'Bashkir', 'bm' => 'Bambara', 'eu' => 'Basque', 'be' => 'Belarusian', 'bn' => 'Bengali', 'bh' => 'Bihari', 'bi' => 'Bislama', 'bs' => 'Bosnian', 'br' => 'Breton', 'bg' => 'Bulgarian', 'my' => 'Burmese', 'ca' => 'Catalan; Valencian', 'ch' => 'Chamorro', 'ce' => 'Chechen', 'zh' => 'Chinese', 'cu' => 'Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic', 'cv' => 'Chuvash', 'kw' => 'Cornish', 'co' => 'Corsican', 'cr' => 'Cree', 'cs' => 'Czech', 'da' => 'Danish', 'dv' => 'Divehi; Dhivehi; Maldivian', 'nl' => 'Dutch; Flemish', 'dz' => 'Dzongkha', 'eo' => 'Esperanto', 'et' => 'Estonian', 'ee' => 'Ewe', 'fo' => 'Faroese', 'fj' => 'Fijjian', 'fi' => 'Finnish', 'fr' => 'French', 'fy' => 'Western Frisian', 'ff' => 'Fulah', 'ka' => 'Georgian', 'de' => 'German', 'gd' => 'Gaelic; Scottish Gaelic', 'ga' => 'Irish', 'gl' => 'Galician', 'gv' => 'Manx', 'el' => 'Greek, Modern', 'gn' => 'Guarani', 'gu' => 'Gujarati', 'ht' => 'Haitian; Haitian Creole', 'ha' => 'Hausa', 'he' => 'Hebrew', 'hz' => 'Herero', 'hi' => 'Hindi', 'ho' => 'Hiri Motu', 'hu' => 'Hungarian', 'ig' => 'Igbo', 'is' => 'Icelandic', 'io' => 'Ido', 'ii' => 'Sichuan Yi', 'iu' => 'Inuktitut', 'ie' => 'Interlingue', 'ia' => 'Interlingua (International Auxiliary Language Association)', 'id' => 'Indonesian', 'ik' => 'Inupiaq', 'it' => 'Italian', 'jv' => 'Javanese', 'ja' => 'Japanese', 'kl' => 'Kalaallisut; Greenlandic', 'kn' => 'Kannada', 'ks' => 'Kashmiri', 'kr' => 'Kanuri', 'kk' => 'Kazakh', 'km' => 'Central Khmer', 'ki' => 'Kikuyu; Gikuyu', 'rw' => 'Kinyarwanda', 'ky' => 'Kirghiz; Kyrgyz', 'kv' => 'Komi', 'kg' => 'Kongo', 'ko' => 'Korean', 'kj' => 'Kuanyama; Kwanyama', 'ku' => 'Kurdish', 'lo' => 'Lao', 'la' => 'Latin', 'lv' => 'Latvian', 'li' => 'Limburgan; Limburger; Limburgish', 'ln' => 'Lingala', 'lt' => 'Lithuanian', 'lb' => 'Luxembourgish; Letzeburgesch', 'lu' => 'Luba-Katanga', 'lg' => 'Ganda', 'mk' => 'Macedonian', 'mh' => 'Marshallese', 'ml' => 'Malayalam', 'mi' => 'Maori', 'mr' => 'Marathi', 'ms' => 'Malay', 'mg' => 'Malagasy', 'mt' => 'Maltese', 'mo' => 'Moldavian', 'mn' => 'Mongolian', 'na' => 'Nauru', 'nv' => 'Navajo; Navaho', 'nr' => 'Ndebele, South; South Ndebele', 'nd' => 'Ndebele, North; North Ndebele', 'ng' => 'Ndonga', 'ne' => 'Nepali', 'nn' => 'Norwegian Nynorsk; Nynorsk, Norwegian', 'nb' => 'Bokmål, Norwegian, Norwegian Bokmål', 'no' => 'Norwegian', 'ny' => 'Chichewa; Chewa; Nyanja', 'oc' => 'Occitan, Provençal', 'oj' => 'Ojibwa', 'or' => 'Oriya', 'om' => 'Oromo', 'os' => 'Ossetian; Ossetic', 'pa' => 'Panjabi; Punjabi', 'fa' => 'Persian', 'pi' => 'Pali', 'pl' => 'Polish', 'pt' => 'Portuguese', 'ps' => 'Pushto', 'qu' => 'Quechua', 'rm' => 'Romansh', 'ro' => 'Romanian', 'rn' => 'Rundi', 'ru' => 'Russian', 'sg' => 'Sango', 'sa' => 'Sanskrit', 'sr' => 'Serbian', 'hr' => 'Croatian', 'si' => 'Sinhala; Sinhalese', 'sk' => 'Slovak', 'sl' => 'Slovenian', 'se' => 'Northern Sami', 'sm' => 'Samoan', 'sn' => 'Shona', 'sd' => 'Sindhi', 'so' => 'Somali', 'st' => 'Sotho, Southern', 'es' => 'Spanish; Castilian', 'sc' => 'Sardinian', 'ss' => 'Swati', 'su' => 'Sundanese', 'sw' => 'Swahili', 'sv' => 'Swedish', 'ty' => 'Tahitian', 'ta' => 'Tamil', 'tt' => 'Tatar', 'te' => 'Telugu', 'tg' => 'Tajik', 'tl' => 'Tagalog', 'th' => 'Thai', 'bo' => 'Tibetan', 'ti' => 'Tigrinya', 'to' => 'Tonga (Tonga Islands)', 'tn' => 'Tswana', 'ts' => 'Tsonga', 'tk' => 'Turkmen', 'tr' => 'Turkish', 'tw' => 'Twi', 'ug' => 'Uighur; Uyghur', 'uk' => 'Ukrainian', 'ur' => 'Urdu', 'uz' => 'Uzbek', 've' => 'Venda', 'vi' => 'Vietnamese', 'vo' => 'Volapük', 'cy' => 'Welsh','wa' => 'Walloon','wo' => 'Wolof', 'xh' => 'Xhosa', 'yi' => 'Yiddish', 'yo' => 'Yoruba', 'za' => 'Zhuang; Chuang', 'zu' => 'Zulu' ); ?> <div class="wrap"> <div class="icon32 icon32-bws" id="icon-options-general"></div> <h2><?php _e( "Contact Form Settings", 'contact_form' ); ?></h2> <div class="updated fade" <?php if( ! isset( $_POST['cntctfrm_form_submit'] ) || $error != "" ) echo "style=\"display:none\""; ?>><p><strong><?php echo $message; ?></strong></p></div> <div class="error" <?php if( "" == $error ) echo "style=\"display:none\""; ?>><p><strong><?php echo $error; ?></strong></p></div> <ul class="subsubsub"> <li><a class="current" href="admin.php?page=contact_form.php"><?php _e( 'Settings', 'contact_form' ); ?></a></li> | <li><a href="admin.php?page=contact_form_pro_extra.php"><?php _e( 'Extra settings', 'contact_form' ); ?></a></li> </ul> <div class="clear"></div> <form method="post" action="admin.php?page=contact_form.php"> <span style="margin-bottom:15px;"> <p><?php _e( "If you would like to add the Contact Form to your website, just copy and paste this shortcode to your post or page or widget:", 'contact_form' ); ?> [contact_form] <?php _e( "or", 'contact_form' ); ?> [contact_form lang=en]<br /> <?php _e( "If have any problems with the standard shortcode [contact_form], you should use the shortcode", 'contact_form' ); ?> [bws_contact_form] (<?php _e( "or", 'contact_form' ); ?> [bws_contact_form lang=en]) <?php _e( "or", 'contact_form' ); ?> [bestwebsoft_contact_form] (<?php _e( "or", 'contact_form' ); ?> [bestwebsoft_contact_form lang=en]). <?php _e( "They work the same way.", 'contact_form' ); ?></p> <?php _e( "If you leave the fields empty, the messages will be sent to the email address specified during registration.", 'contact_form' ); ?> </span> <table class="form-table" style="width:auto;" > <tr valign="top"> <th scope="row" style="width:200px;"><?php _e( "The user's email address:", 'contact_form' ); ?> </th> <td colspan="2" style="width:750px;"> <input type="radio" id="cntctfrm_select_email_user" name="cntctfrm_select_email" value="user" <?php if($cntctfrm_options['cntctfrm_select_email'] == 'user') echo "checked=\"checked\" "; ?>/> <select name="cntctfrm_user_email"> <option disabled><?php _e( "Create a username", 'contact_form' ); ?></option> <?php while( list( $key, $value ) = each( $userslogin ) ) { ?> <option value="<?php echo $value; ?>" <?php if( $cntctfrm_options['cntctfrm_user_email'] == $value ) echo "selected=\"selected\" "; ?>><?php echo $value; ?></option> <?php } ?> </select> <span class="cntctfrm_info"><?php _e( "Enter a username of the person who should get the messages from the contact form.", 'contact_form' ); ?></span> </td> </tr> <tr valign="top"> <th scope="row" style="width:200px;"><?php _e( "Use this email address:", 'contact_form' ); ?> </th> <td colspan="2"> <input type="radio" id="cntctfrm_select_email_custom" name="cntctfrm_select_email" value="custom" <?php if($cntctfrm_options['cntctfrm_select_email'] == 'custom') echo "checked=\"checked\" "; ?>/> <input type="text" name="cntctfrm_custom_email" value="<?php echo $cntctfrm_options['cntctfrm_custom_email']; ?>" onfocus="document.getElementById('cntctfrm_select_email_custom').checked = true;" /> <span class="cntctfrm_info"><?php _e( "Enter the email address you want the messages forwarded to.", 'contact_form' ); ?></span> </td> </tr> <tr valign="top" id="cntctfrmpr_pro_version"> <th scope="row" style="width:200px;"><?php _e( "Add department selectbox to the contact form:", 'contact_form_pro' ); ?></th> <td colspan="2"> <div class="cntctfrmpr_pro_version_tooltip_settings"> <?php _e( 'This functionality is available in the Pro version of the plugin. For more details, please follow the link', 'contact_form' ); ?> <a title="Contact Form Pro" target="_blank" href="http://bestwebsoft.com/plugin/contact-form-pro/?k=697c5e74f39779ce77850e11dbe21962&pn=77&v=<?php echo $plugin_info["Version"]; ?>"> <?php _e( 'Contact Form Pro', 'contact_form' ); ?></a> </div> <input type="radio" id="cntctfrmpr_select_email_department" name="cntctfrmpr_select_email" value="departments" disabled="disabled" /> <div class="cntctfrmpr_department_table"><img src="<?php echo plugins_url( 'images/pro_screen_1.png', __FILE__ ); ?>" alt="" /></div> </td> </tr> <tr valign="top"> <th colspan="3" scope="row" style="width:200px;"><input type="checkbox" id="cntctfrm_additions_options" name="cntctfrm_additions_options" value="1" <?php if($cntctfrm_options['cntctfrm_additions_options'] == '1') echo "checked=\"checked\" "; ?> /> <?php _e( "Additional options", 'contact_form' ); ?></th> </tr> <tr class="cntctfrm_additions_block <?php if($cntctfrm_options['cntctfrm_additions_options'] == '0') echo "cntctfrm_hidden"; ?>"> <th rowspan="2"><?php _e( 'What to use?', 'contact_form' ); ?></th> <td colspan="2"> <input type='radio' name='cntctfrm_mail_method' value='wp-mail' <?php if( $cntctfrm_options['cntctfrm_mail_method'] == 'wp-mail' ) echo "checked=\"checked\" "; ?>/> <?php _e( 'Wp-mail', 'contact_form' ); ?> <span class="cntctfrm_info">(<?php _e( 'You can use the wp_mail function for mailing', 'contact_form' ); ?>)</span> </td> </tr> <tr class="cntctfrm_additions_block <?php if($cntctfrm_options['cntctfrm_additions_options'] == '0') echo "cntctfrm_hidden"; ?>"> <td colspan="2"> <input type='radio' name='cntctfrm_mail_method' value='mail' <?php if($cntctfrm_options['cntctfrm_mail_method'] == 'mail') echo "checked=\"checked\" "; ?>/> <?php _e( 'Mail', 'contact_form' ); ?> <span class="cntctfrm_info">(<?php _e( 'To send mail you can use the php mail function', 'contact_form' ); ?>)</span> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if ( $cntctfrm_options['cntctfrm_additions_options'] == '0') echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "The text in the 'From' field", 'contact_form' ); ?></th> <td colspan="2"> <input type="radio" id="cntctfrm_select_from_field" name="cntctfrm_select_from_field" value="user_name" <?php if ( $cntctfrm_options['cntctfrm_select_from_field'] == 'user_name') echo "checked=\"checked\" "; ?>/> <?php _e( "User name", 'contact_form' ); ?> <span class="cntctfrm_info">(<?php _e( "The name of the user who fills the form will be used in the field 'From'.", 'contact_form' ); ?>)</span><br/> <input type="radio" id="cntctfrm_select_from_field" name="cntctfrm_select_from_field" value="custom" <?php if ( $cntctfrm_options['cntctfrm_select_from_field'] == 'custom') echo "checked=\"checked\" "; ?>/> <input type="text" style="width:200px;" name="cntctfrm_from_field" value="<?php echo stripslashes( $cntctfrm_options['cntctfrm_from_field'] ); ?>" /> <span class="cntctfrm_info">(<?php _e( "This text will be used in the 'FROM' field", 'contact_form' ); ?>)</span> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if($cntctfrm_options['cntctfrm_additions_options'] == '0') echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "The email address in the 'From' field", 'contact_form' ); ?></th> <td colspan="2"> <input type="radio" id="cntctfrm_from_email" name="cntctfrm_from_email" value="user" <?php if( $cntctfrm_options['cntctfrm_from_email'] == 'user' ) echo "checked=\"checked\" "; ?>/> <?php _e( "User email", 'contact_form' ); ?> <span class="cntctfrm_info">(<?php _e( "The email address of the user who fills the form will be used in the field 'From'.", 'contact_form' ); ?>)</span><br /> <input type="radio" id="cntctfrm_from_custom_email" name="cntctfrm_from_email" value="custom" <?php if($cntctfrm_options['cntctfrm_from_email'] == 'custom') echo "checked=\"checked\" "; ?>/> <input type="text" name="cntctfrm_custom_from_email" value="<?php echo $cntctfrm_options['cntctfrm_custom_from_email']; ?>" onfocus="document.getElementById('cntctfrm_from_custom_email').checked = true;" /> <span class="cntctfrm_info">(<?php _e( "This email address will be used in the 'From' field.", 'contact_form' ); ?>)</span> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if($cntctfrm_options['cntctfrm_additions_options'] == '0') echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "Display fields", 'contact_form' ); ?></th> <td colspan="2"> <input type="checkbox" id="cntctfrm_display_address_field" name="cntctfrm_display_address_field" value="1" <?php if($cntctfrm_options['cntctfrm_display_address_field'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Address", 'contact_form' ); ?><br /> <input type="checkbox" id="cntctfrm_display_phone_field" name="cntctfrm_display_phone_field" value="1" <?php if($cntctfrm_options['cntctfrm_display_phone_field'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Phone", 'contact_form' ); ?><br /> <input type="checkbox" id="cntctfrm_attachment" name="cntctfrm_attachment" value="1" <?php if($cntctfrm_options['cntctfrm_attachment'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Attachment block", 'contact_form' ); ?> <span class="cntctfrm_info">(<?php echo __( "Users can attach the following file formats", 'contact_form' ) . ": html, txt, css, gif, png, jpeg, jpg, tiff, bmp, ai, eps, ps, rtf, pdf, doc, docx, xls, zip, rar, wav, mp3, ppt"; ?>)</span><br /> <?php $all_plugins = get_plugins(); if ( is_multisite() ) { $active_plugins = (array) array_keys( get_site_option( 'active_sitewide_plugins', array() ) ); $active_plugins = array_merge( $active_plugins , get_option('active_plugins') ); } else { $active_plugins = get_option('active_plugins'); } if ( array_key_exists( 'captcha/captcha.php', $all_plugins ) || array_key_exists( 'captcha-pro/captcha_pro.php', $all_plugins ) ) { if ( 0 < count( preg_grep( '/captcha\/captcha.php/', $active_plugins ) ) || 0 < count( preg_grep( '/captcha-pro\/captcha_pro.php/', $active_plugins ) ) ) { ?> <input type="checkbox" name="cntctfrm_display_captcha" value="1" <?php if ( ( isset( $cptch_options ) && 1 == $cptch_options["cptch_contact_form"] ) || ( isset( $cptchpr_options ) && 1 == $cptchpr_options["cptchpr_contact_form"] ) ) echo "checked=\"checked\""; ?> /> <label for="cntctfrm_display_captcha"><?php _e( "Captcha", 'contact_form' ); ?></label> <span style="color: #888888;font-size: 10px;">(<?php _e( 'powered by', 'contact_form' ); ?> <a href="http://bestwebsoft.com/plugin/">bestwebsoft.com</a>)</span> <?php } else { ?> <input disabled="disabled" type="checkbox" name="cntctfrm_display_captcha" value="1" <?php if ( ( isset( $cptch_options ) && 1 == $cptch_options["cptch_contact_form"] ) || ( isset( $cptchpr_options ) && 1 == $cptchpr_options["cptchpr_contact_form"] ) ) echo "checked=\"checked\""; ?> /> <label for="cntctfrm_display_captcha"><?php _e( 'Captcha', 'contact_form' ); ?></label> <span style="color: #888888;font-size: 10px;">(<?php _e( 'powered by', 'contact_form' ); ?> <a href="http://bestwebsoft.com/plugin/">bestwebsoft.com</a>) <a href="<?php echo bloginfo("url"); ?>/wp-admin/plugins.php"><?php _e( 'Activate captcha', 'contact_form' ); ?></a></span> <?php } } else { ?> <input disabled="disabled" type="checkbox" name="cntctfrm_display_captcha" value="1" /> <label for="cntctfrm_display_captcha"><?php _e( 'Captcha', 'contact_form' ); ?></label> <span style="color: #888888;font-size: 10px;">(<?php _e( 'powered by', 'contact_form' ); ?> <a href="http://bestwebsoft.com/plugin/">bestwebsoft.com</a>) <a href="http://bestwebsoft.com/plugin/captcha-pro/?k=19ac1e9b23bea947cfc4a9b8e3326c03&pn=77&v=<?php echo $plugin_info["Version"]; ?>"><?php _e( 'Download captcha', 'contact_form' ); ?></a></span> <?php } ?> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if ( $cntctfrm_options['cntctfrm_additions_options'] == '0' ) echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "Display tips below the Attachment block", 'contact_form' ); ?></th> <td colspan="2"> <input type="checkbox" id="cntctfrm_attachment_explanations" name="cntctfrm_attachment_explanations" value="1" <?php if ( $cntctfrm_options['cntctfrm_attachment_explanations'] == '1' && $cntctfrm_options['cntctfrm_attachment'] == '1' ) echo "checked=\"checked\" "; ?>/> <div class="cntctfrmpr_help_box" style="margin: -25px 35px 0;float:none;"> <div class="cntctfrmpr_hidden_help_text" style="display: none;width: auto;"><img title="" src="<?php echo plugins_url( 'images/tooltip_attachment_tips.png', __FILE__ ); ?>" alt=""/></div> </div> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if ( $cntctfrm_options['cntctfrm_additions_options'] == '0' ) echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "Delete an attachment file from the server after the email is sent", 'contact_form' ); ?> </th> <td colspan="2"> <input type="checkbox" id="cntctfrm_delete_attached_file" name="cntctfrm_delete_attached_file" value="1" <?php if($cntctfrm_options['cntctfrm_delete_attached_file'] == '1') echo "checked=\"checked\" "; ?>/> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if ( $cntctfrm_options['cntctfrm_additions_options'] == '0' ) echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "Save emails to the database", 'contact_form' ); ?> </th> <td colspan="2"> <?php $all_plugins = get_plugins(); if ( is_multisite() ) { $active_plugins = (array) array_keys( get_site_option( 'active_sitewide_plugins', array() ) ); $active_plugins = array_merge( $active_plugins , get_option( 'active_plugins' ) ); } else { $active_plugins = get_option( 'active_plugins' ); } if ( array_key_exists( 'contact-form-to-db/contact_form_to_db.php', $all_plugins ) || array_key_exists( 'contact-form-to-db-pro/contact_form_to_db_pro.php', $all_plugins ) ) { if ( 0 < count( preg_grep( '/contact-form-to-db\/contact_form_to_db.php/', $active_plugins ) ) || 0 < count( preg_grep( '/contact-form-to-db-pro\/contact_form_to_db_pro.php/', $active_plugins ) ) ) { ?> <input type="checkbox" name="cntctfrm_save_email_to_db" value="1" <?php if ( ( isset( $cntctfrmtdb_options ) && 1 == $cntctfrmtdb_options["cntctfrmtdb_save_messages_to_db"] ) || ( isset( $cntctfrmtdbpr_options ) && 1 == $cntctfrmtdbpr_options["save_messages_to_db"] ) ) echo "checked=\"checked\""; ?> /> <span style="color: #888888;font-size: 10px;"> (<?php _e( 'Using Contact Form to DB powered by', 'contact_form' ); ?> <a href="http://bestwebsoft.com/plugin/">bestwebsoft.com</a>)</span> <?php } else { ?> <input disabled="disabled" type="checkbox" name="cntctfrm_save_email_to_db" value="1" <?php if ( ( isset( $cntctfrmtdb_options ) && 1 == $cntctfrmtdb_options["cntctfrmtdb_save_messages_to_db"] ) || ( isset( $cntctfrmtdbpr_options ) && 1 == $cntctfrmtdbpr_options["save_messages_to_db"] ) ) echo "checked=\"checked\""; ?> /> <span style="color: #888888;font-size: 10px;">(<?php _e( 'Using Contact Form to DB powered by', 'contact_form' ); ?> <a href="http://bestwebsoft.com/plugin/">bestwebsoft.com</a>) <a href="<?php echo bloginfo("url"); ?>/wp-admin/plugins.php"><?php _e( 'Activate Contact Form to DB', 'contact_form' ); ?></a></span> <?php } } else { ?> <input disabled="disabled" type="checkbox" name="cntctfrm_save_email_to_db" value="1" /> <span style="color: #888888;font-size: 10px;">(<?php _e( 'Using Contact Form to DB powered by', 'contact_form' ); ?> <a href="http://bestwebsoft.com/plugin/">bestwebsoft.com</a>) <a href="http://bestwebsoft.com/plugin/contact-form-to-db-pro/?k=19d806f45d866e70545de83169b274f2&pn=77&v=<?php echo $plugin_info["Version"]; ?>"><?php _e( 'Download Contact Form to DB', 'contact_form' ); ?></a></span> <?php } ?> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if ( $cntctfrm_options['cntctfrm_additions_options'] == '0' ) echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "Display 'Send me a copy' block", 'contact_form' ); ?> </th> <td colspan="2"> <input type="checkbox" id="cntctfrm_send_copy" name="cntctfrm_send_copy" value="1" <?php if($cntctfrm_options['cntctfrm_send_copy'] == '1') echo "checked=\"checked\" "; ?>/> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if ( $cntctfrm_options['cntctfrm_additions_options'] == '0' ) echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "Required fields", 'contact_form' ); ?></th> <td colspan="2"> <input type="checkbox" id="cntctfrm_required_name_field" name="cntctfrm_required_name_field" value="1" <?php if($cntctfrm_options['cntctfrm_required_name_field'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Name", 'contact_form' ); ?><br /> <input type="checkbox" id="cntctfrm_required_address_field" name="cntctfrm_required_address_field" value="1" <?php if($cntctfrm_options['cntctfrm_required_address_field'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Address", 'contact_form' ); ?><br /> <input type="checkbox" id="cntctfrm_required_email_field" name="cntctfrm_required_email_field" value="1" <?php if($cntctfrm_options['cntctfrm_required_email_field'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Email Address", 'contact_form' ); ?><br /> <input type="checkbox" id="cntctfrm_required_phone_field" name="cntctfrm_required_phone_field" value="1" <?php if($cntctfrm_options['cntctfrm_required_phone_field'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Phone", 'contact_form' ); ?><br /> <input type="checkbox" id="cntctfrm_required_subject_field" name="cntctfrm_required_subject_field" value="1" <?php if($cntctfrm_options['cntctfrm_required_subject_field'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Subject", 'contact_form' ); ?><br /> <input type="checkbox" id="cntctfrm_required_message_field" name="cntctfrm_required_message_field" value="1" <?php if($cntctfrm_options['cntctfrm_required_message_field'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Message", 'contact_form' ); ?> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if ( $cntctfrm_options['cntctfrm_additions_options'] == '0' ) echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "Display the asterisk near required fields", 'contact_form' ); ?></th> <td colspan="2"> <input type="checkbox" id="cntctfrm_required_symbol" name="cntctfrm_required_symbol" value="1" <?php if ( $cntctfrm_options['cntctfrm_required_symbol'] == '1' ) echo "checked=\"checked\" "; ?>/> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if( $cntctfrm_options['cntctfrm_additions_options'] == '0' ) echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "Display additional info in the email", 'contact_form' ); ?></th> <td style="width:15px;"> <input type="checkbox" id="cntctfrm_display_add_info" name="cntctfrm_display_add_info" value="1" <?php if($cntctfrm_options['cntctfrm_display_add_info'] == '1') echo "checked=\"checked\" "; ?>/> </td> <td style="max-width:150px;" class="cntctfrm_display_add_info_block <?php if( $cntctfrm_options['cntctfrm_display_add_info'] == '0' ) echo "cntctfrm_hidden"; ?>"> <input type="checkbox" id="cntctfrm_display_sent_from" name="cntctfrm_display_sent_from" value="1" <?php if($cntctfrm_options['cntctfrm_display_sent_from'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Sent from (ip address)", 'contact_form' ); ?> <span style="color: #888888;font-size: 10px;"><?php _e( "Example: Sent from (IP address): 127.0.0.1", 'contact_form' ); ?></span><br /> <input type="checkbox" id="cntctfrm_display_date_time" name="cntctfrm_display_date_time" value="1" <?php if($cntctfrm_options['cntctfrm_display_date_time'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Date/Time", 'contact_form' ); ?> <span style="color: #888888;font-size: 10px;"><?php _e( "Example: Date/Time: August 19, 2013 8:50 pm", 'contact_form' ); ?></span><br /> <input type="checkbox" id="cntctfrm_display_coming_from" name="cntctfrm_display_coming_from" value="1" <?php if($cntctfrm_options['cntctfrm_display_coming_from'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Sent from (referer)", 'contact_form' ); ?> <span style="color: #888888;font-size: 10px;"><?php _e( "Example: Sent from (referer): http://bestwebsoft.com/contacts/contact-us/", 'contact_form' ); ?></span><br /> <input type="checkbox" id="cntctfrm_display_user_agent" name="cntctfrm_display_user_agent" value="1" <?php if($cntctfrm_options['cntctfrm_display_user_agent'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Using (user agent)", 'contact_form' ); ?> <span style="color: #888888;font-size: 10px;"><?php _e( "Example: Using (user agent): Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36", 'contact_form' ); ?></span><br /> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if($cntctfrm_options['cntctfrm_additions_options'] == '0') echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "Language settings for the field names in the form", 'contact_form' ); ?></th> <td colspan="2"> <select name="cntctfrm_languages" id="cntctfrm_languages" style="width:300px;"> <?php foreach ( $lang_codes as $key=>$val ) { if( in_array( $key, $cntctfrm_options['cntctfrm_language'] ) ) continue; echo '<option value="' . esc_attr( $key ) . '"> ' . esc_html ( $val ) . '</option>'; } ?> </select> <input type="button" class="button-primary" id="cntctfrm_add_language_button" value="<?php _e('Add a language', 'contact_form'); ?>" /> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if($cntctfrm_options['cntctfrm_additions_options'] == '0') echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "Change the names of the contact form fields and error messages", 'contact_form' ); ?></th> <td style="width:15px;"> <input type="checkbox" id="cntctfrm_change_label" name="cntctfrm_change_label" value="1" <?php if($cntctfrm_options['cntctfrm_change_label'] == '1') echo "checked=\"checked\" "; ?>/> </td> <td class="cntctfrm_change_label_block <?php if($cntctfrm_options['cntctfrm_change_label'] == '0') echo "cntctfrm_hidden"; ?>"> <div class="cntctfrm_label_language_tab cntctfrm_active" id="cntctfrm_label_en"><?php _e('English', 'contact_form'); ?></div> <?php if( ! empty( $cntctfrm_options['cntctfrm_language'] ) ){ foreach( $cntctfrm_options['cntctfrm_language'] as $val ) { echo '<div class="cntctfrm_label_language_tab" id="cntctfrm_label_'.$val.'">'.$lang_codes[$val].' <span class="cntctfrm_delete" rel="'.$val.'">X</span></div>'; } } ?> <div class="clear"></div> <div class="cntctfrm_language_tab cntctfrm_tab_en"> <div class="cntctfrm_language_tab_block_mini" style="display:none;"><br/></div> <div class="cntctfrm_language_tab_block"> <input type="text" name="cntctfrm_name_label[en]" value="<?php echo $cntctfrm_options['cntctfrm_name_label']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Name:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_address_label[en]" value="<?php echo $cntctfrm_options['cntctfrm_address_label']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Address:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_email_label[en]" value="<?php echo $cntctfrm_options['cntctfrm_email_label']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Email Address:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_phone_label[en]" value="<?php echo $cntctfrm_options['cntctfrm_phone_label']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Phone number:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_subject_label[en]" value="<?php echo $cntctfrm_options['cntctfrm_subject_label']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Subject:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_message_label[en]" value="<?php echo $cntctfrm_options['cntctfrm_message_label']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Message:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_attachment_label[en]" value="<?php echo $cntctfrm_options['cntctfrm_attachment_label']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Attachment:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_send_copy_label[en]" value="<?php echo $cntctfrm_options['cntctfrm_send_copy_label']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Send me a copy", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_submit_label[en]" value="<?php echo $cntctfrm_options['cntctfrm_submit_label']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Submit", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_name_error[en]" value="<?php echo $cntctfrm_options['cntctfrm_name_error']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Name field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_address_error[en]" value="<?php echo $cntctfrm_options['cntctfrm_address_error']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Address field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_email_error[en]" value="<?php echo $cntctfrm_options['cntctfrm_email_error']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Email field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_phone_error[en]" value="<?php echo $cntctfrm_options['cntctfrm_phone_error']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Phone field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_subject_error[en]" value="<?php echo $cntctfrm_options['cntctfrm_subject_error']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Subject field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_message_error[en]" value="<?php echo $cntctfrm_options['cntctfrm_message_error']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Message field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_attachment_error[en]" value="<?php echo $cntctfrm_options['cntctfrm_attachment_error']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message about the file type for the Attachment field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_attachment_upload_error[en]" value="<?php echo $cntctfrm_options['cntctfrm_attachment_upload_error']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message while uploading a file for the Attachment field to the server", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_attachment_move_error[en]" value="<?php echo $cntctfrm_options['cntctfrm_attachment_move_error']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message while moving the file for the Attachment field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_attachment_size_error[en]" value="<?php echo $cntctfrm_options['cntctfrm_attachment_size_error']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message when file size limit for the Attachment field is exceeded", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_captcha_error[en]" value="<?php echo $cntctfrm_options['cntctfrm_captcha_error']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Captcha field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_form_error[en]" value="<?php echo $cntctfrm_options['cntctfrm_form_error']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the whole form", 'contact_form' ); ?></span><br /> </div> <span class="cntctfrm_info" style="margin-left: 5px;"><?php _e( "Use shortcode", 'contact_form' ); echo " [bestwebsoft_contact_form lang=en] " . __( "or", 'contact_form' ) . " [bestwebsoft_contact_form] "; _e( "for this language", 'contact_form' ); ?></span> </div> <?php if( ! empty( $cntctfrm_options['cntctfrm_language'] ) ){ foreach( $cntctfrm_options['cntctfrm_language'] as $val ) { ?> <div class="cntctfrm_language_tab hidden cntctfrm_tab_<?php echo $val; ?>"> <div class="cntctfrm_language_tab_block_mini" style="display:none;"><br/></div> <div class="cntctfrm_language_tab_block"> <input type="text" name="cntctfrm_name_label[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_name_label'][$val] ) ) echo $cntctfrm_options['cntctfrm_name_label'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Name:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_address_label[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_address_label'][$val] ) ) echo $cntctfrm_options['cntctfrm_address_label'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Address:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_email_label[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_email_label'][$val] ) ) echo $cntctfrm_options['cntctfrm_email_label'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Email Address:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_phone_label[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_phone_label'][$val] ) ) echo $cntctfrm_options['cntctfrm_phone_label'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Phone number:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_subject_label[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_subject_label'][$val] ) ) echo $cntctfrm_options['cntctfrm_subject_label'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Subject:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_message_label[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_message_label'][$val] ) ) echo $cntctfrm_options['cntctfrm_message_label'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Message:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_attachment_label[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_attachment_label'][$val] ) ) echo $cntctfrm_options['cntctfrm_attachment_label'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Attachment:", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_send_copy_label[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_send_copy_label'][$val] ) ) echo $cntctfrm_options['cntctfrm_send_copy_label'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Send me a copy", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_submit_label[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_submit_label'][$val] ) ) echo $cntctfrm_options['cntctfrm_submit_label'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Submit", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_name_error[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_name_error'][$val] ) ) echo $cntctfrm_options['cntctfrm_name_error'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Name field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_address_error[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_address_error'][$val] ) ) echo $cntctfrm_options['cntctfrm_address_error'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Address field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_email_error[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_email_error'][$val] ) ) echo $cntctfrm_options['cntctfrm_email_error'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Email field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_phone_error[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_phone_error'][$val] ) ) echo $cntctfrm_options['cntctfrm_phone_error'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Phone field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_subject_error[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_subject_error'][$val] ) ) echo $cntctfrm_options['cntctfrm_subject_error'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Subject field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_message_error[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_message_error'][$val] ) ) echo $cntctfrm_options['cntctfrm_message_error'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Message field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_attachment_error[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_attachment_error'][$val] ) ) echo $cntctfrm_options['cntctfrm_attachment_error'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message about the file type for the Attachment field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_attachment_upload_error[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_attachment_upload_error'][$val] ) ) echo $cntctfrm_options['cntctfrm_attachment_upload_error'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message while uploading a file for the Attachment field to the server", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_attachment_move_error[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_attachment_move_error'][$val] ) ) echo $cntctfrm_options['cntctfrm_attachment_move_error'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message while moving the file for the Attachment field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_attachment_size_error[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_attachment_size_error'][$val] ) ) echo $cntctfrm_options['cntctfrm_attachment_size_error'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message when file size limit for the Attachment field is exceeded", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_captcha_error[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_captcha_error'][$val] ) ) echo $cntctfrm_options['cntctfrm_captcha_error'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the Captcha field", 'contact_form' ); ?></span><br /> <input type="text" name="cntctfrm_form_error[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_form_error'][$val] ) ) echo $cntctfrm_options['cntctfrm_form_error'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Error message for the whole form", 'contact_form' ); ?></span><br /> </div> <span class="cntctfrm_info" style="margin-left: 5px;"><?php _e( "Use shortcode", 'contact_form' ); echo " [bestwebsoft_contact_form lang=".$val."] "; _e( "for this language", 'contact_form' ); ?></span> </div> <?php } } ?> </td> </tr> <tr valign="top" class="cntctfrm_additions_block <?php if($cntctfrm_options['cntctfrm_additions_options'] == '0') echo "cntctfrm_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "Action after email is sent", 'contact_form' ); ?></th> <td colspan="2" class="cntctfrm_action_after_send_block"> <input type="radio" id="cntctfrm_action_after_send" name="cntctfrm_action_after_send" value="1" <?php if($cntctfrm_options['cntctfrm_action_after_send'] == '1') echo "checked=\"checked\" "; ?>/> <?php _e( "Display text", 'contact_form' ); ?><br /> <div class="cntctfrm_label_language_tab cntctfrm_active" id="cntctfrm_text_en"><?php _e('English', 'contact_form'); ?></div> <?php if( ! empty( $cntctfrm_options['cntctfrm_language'] ) ){ foreach( $cntctfrm_options['cntctfrm_language'] as $val ) { echo '<div class="cntctfrm_label_language_tab" id="cntctfrm_text_'.$val.'">'.$lang_codes[$val].' <span class="cntctfrm_delete" rel="'.$val.'">X</span></div>'; } } ?> <div class="clear"></div> <div class="cntctfrm_language_tab cntctfrm_tab_en" style=" padding: 5px 10px 5px 5px;"> <input type="text" name="cntctfrm_thank_text[en]" value="<?php echo $cntctfrm_options['cntctfrm_thank_text']['en']; ?>" /> <span class="cntctfrm_info"><?php _e( "Text", 'contact_form' ); ?></span><br /> <span class="cntctfrm_info"><?php _e( "Use shortcode", 'contact_form' ); echo " [bestwebsoft_contact_form=en] " . __( "or", 'contact_form' ) . " [bestwebsoft_contact_form] "; _e( "for this language", 'contact_form' ); ?></span> </div> <?php if( ! empty( $cntctfrm_options['cntctfrm_language'] ) ){ foreach( $cntctfrm_options['cntctfrm_language'] as $val ) { ?> <div class="cntctfrm_language_tab hidden cntctfrm_tab_<?php echo $val; ?>" style=" padding: 5px 10px 5px 5px;"> <input type="text" name="cntctfrm_thank_text[<?php echo $val; ?>]" value="<?php if( isset( $cntctfrm_options['cntctfrm_thank_text'][$val] ) ) echo $cntctfrm_options['cntctfrm_thank_text'][$val]; ?>" /> <span class="cntctfrm_info"><?php _e( "Text", 'contact_form' ); ?></span><br /> <span class="cntctfrm_info"><?php _e( "Use shortcode", 'contact_form' ); echo " [bestwebsoft_contact_form lang=".$val."] "; _e( "for this language", 'contact_form' ); ?></span> </div> <?php } } ?> <div id="cntctfrm_before"></div> <br /> <input type="radio" id="cntctfrm_action_after_send" name="cntctfrm_action_after_send" value="0" <?php if($cntctfrm_options['cntctfrm_action_after_send'] == '0') echo "checked=\"checked\" "; ?>/> <?php _e( "Redirect to the page", 'contact_form' ); ?><br /> <input type="text" name="cntctfrm_redirect_url" value="<?php echo $cntctfrm_options['cntctfrm_redirect_url']; ?>" /> <span class="cntctfrm_info"><?php _e( "Url", 'contact_form' ); ?></span><br /> </td> </table> <input type="hidden" name="cntctfrm_form_submit" value="submit" /> <p class="submit"> <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" /> </p> <?php wp_nonce_field( plugin_basename(__FILE__), 'cntctfrm_nonce_name' ); ?> </form> </div> <?php } } // Add settings page in admin area if ( ! function_exists( 'cntctfrm_settings_page_extra' ) ) { function cntctfrm_settings_page_extra() { global $wpdb, $wp_version, $cntctfrm_options; $plugin_info = get_plugin_data( __FILE__ ); ?> <div class="wrap"> <div class="icon32 icon32-bws" id="icon-options-general"></div> <h2><?php _e( "Contact Form Pro | Extra Settings", 'contact_form' ); ?></h2> <ul class="subsubsub"> <li><a href="admin.php?page=contact_form.php"><?php _e( 'Settings', 'contact_form' ); ?></a></li> | <li><a class="current" href="admin.php?page=contact_form_pro_extra.php"><?php _e( 'Extra settings', 'contact_form' ); ?></a></li> </ul> <div class="clear"></div> <div class="cntctfrmpr_pro_version_tooltip"> <?php _e( 'This functionality is available in the Pro version of the plugin. For more details, please follow the link', 'contact_form' ); ?> <a title="Contact Form Pro" target="_blank" href="http://bestwebsoft.com/plugin/contact-form-pro/?k=697c5e74f39779ce77850e11dbe21962&pn=77&v=<?php echo $plugin_info["Version"]; ?>"> <?php _e( 'Contact Form Pro', 'contact_form' ); ?></a> </div> <div id="cntctfrmpr_pro_version"> <div id="cntctfrmpr_left_table"> <table class="form-table" style="width:auto;" > <tr valign="top"> <th scope="row" style="width:200px;"><?php _e( "Errors output", 'contact_form' ); ?></th> <td colspan="2"> <select name="cntctfrmpr_error_displaying"> <option value="labels"><?php _e( "Display error messages", 'contact_form' ); ?></option> <option value="input_colors"><?php _e( "Color of the input field errors.", 'contact_form' ); ?></option> <option value="both" selected="selected"><?php _e( "Display error messages & color of the input field errors", 'contact_form' ); ?></option> </select> </td> </tr> <tr valign="top"> <th scope="row" style="width:200px;"><?php _e( "Add placeholder to the input blocks", 'contact_form' ); ?></th> <td colspan="2"> <input disabled='disabled' type="checkbox" name="cntctfrmpr_placeholder" value="1" checked="checked"/> </td> </tr> <tr valign="top"> <th scope="row" style="width:200px;"><?php _e( "Add tooltips", 'contact_form' ); ?></th> <td colspan="2"> <div> <input disabled='disabled' type="checkbox" name="cntctfrmpr_tooltip_display_name" value="1" checked="checked"/> <label class="cntctfrmpr_tooltip_label" for="cntctfrmpr_tooltip_display_name"><?php _e( "Name", 'contact_form' ); ?></label> </div> <?php if ( $cntctfrm_options['cntctfrm_display_address_field'] == '1' ) { ?> <div> <input disabled='disabled' type="checkbox" name="cntctfrmpr_tooltip_display_address" value="1" checked="checked"/> <label class="cntctfrmpr_tooltip_label" for="cntctfrmpr_tooltip_display_address"><?php _e( "Address", 'contact_form' ); ?></label> </div> <?php } ?> <div> <input disabled='disabled' type="checkbox" name="cntctfrmpr_tooltip_display_email" value="1" checked="checked"/> <label class="cntctfrmpr_tooltip_label" for="cntctfrmpr_tooltip_display_email"><?php _e( "Email address", 'contact_form' ); ?></label> </div> <?php if ( $cntctfrm_options['cntctfrm_display_phone_field'] == '1' ) { ?> <div> <input disabled='disabled' type="checkbox" name="cntctfrmpr_tooltip_display_phone" value="1" checked="checked"/> <label class="cntctfrmpr_tooltip_label" for="cntctfrmpr_tooltip_display_phone"><?php _e( "Phone Number", 'contact_form' ); ?></label> </div> <?php } ?> <div> <input disabled='disabled' type="checkbox" name="cntctfrmpr_tooltip_display_subject" value="1" checked="checked"/> <label class="cntctfrmpr_tooltip_label" for="cntctfrmpr_tooltip_display_subject"><?php _e( "Subject", 'contact_form' ); ?></label> </div> <div> <input disabled='disabled' type="checkbox" name="cntctfrmpr_tooltip_display_message" value="1" checked="checked"/> <label class="cntctfrmpr_tooltip_label" for="cntctfrmpr_tooltip_display_message"><?php _e( "Message", 'contact_form' ); ?></label> </div> <?php if ( $cntctfrm_options['cntctfrm_attachment_explanations'] == '1' ) { ?> <div> <input disabled='disabled' type="checkbox" name="cntctfrmpr_tooltip_display_attachment" value="1" checked="checked"/> <label class="cntctfrmpr_tooltip_label" for="cntctfrmpr_tooltip_display_attachment"><?php _e( "Attachment", 'contact_form' ); ?></label> </div> <?php } ?> <div> <input disabled='disabled' type="checkbox" name="cntctfrmpr_tooltip_display_captcha" value="1" /> <label class="cntctfrmpr_tooltip_label" for="cntctfrmpr_tooltip_display_captcha"><?php _e( "Captcha", 'contact_form' ); ?></label><span style="color: #888888;font-size: 10px;"><?php _e( '(powered by bestwebsoft.com)', 'contact_form' ); ?></span> </div> </td> </tr> <tr valign="top"> <th colspan="3" scope="row" style="width:200px;"><input disabled='disabled' type="checkbox" id="cntctfrmpr_style_options" name="cntctfrmpr_style_options" value="1" checked="checked" /> <?php _e( "Style options", 'contact_form' ); ?></th> </tr> <tr valign="top" class="cntctfrmpr_style_block <?php if ( $cntctfrm_options['style_options'] == '0') echo "cntctfrmpr_hidden"; ?>"> <th scope="row" style="width:200px;"><?php _e( "Text color", 'contact_form' ); ?></th> <td colspan="2"> <div> <input disabled='disabled' type="button" class="cntctfrmpr_default button-small button" value="<?php _e('Default', 'contact_form'); ?>" /> <input disabled='disabled' type="text" name="cntctfrmpr_label_color" value="" class="cntctfrmpr_colorPicker" /> <?php _e( 'Label text color', 'contact_form' ); ?> </div> <div> <input disabled='disabled' type="button" class="cntctfrmpr_default button-small button" value="<?php _e('Default', 'contact_form'); ?>" /> <input disabled='disabled' type="text" name="cntctfrmpr_input_placeholder_color" value="" class="cntctfrmpr_colorPicker" /> <?php _e( "Placeholder color", 'contact_form' ); ?> </div> </td> </tr> <tr valign="top" class="cntctfrmpr_style_block"> <th scope="row" style="width:200px;"><?php _e( "Errors color", 'contact_form' ); ?></th> <td colspan="2"> <div> <input disabled='disabled' type="button" class="cntctfrmpr_default button-small button" value="<?php _e('Default', 'contact_form'); ?>" /> <input disabled='disabled' type="text" name="cntctfrmpr_error_color" value="" class="cntctfrmpr_colorPicker" /> <?php _e( 'Error text color', 'contact_form' ); ?> </div> <div> <input disabled='disabled' type="button" class="cntctfrmpr_default button-small button" value="<?php _e('Default', 'contact_form'); ?>" /> <input disabled='disabled' type="text" name="cntctfrmpr_error_input_color" value="" class="cntctfrmpr_colorPicker" /> <?php _e( 'Background color of the input field errors', 'contact_form' ); ?> </div> <div> <input disabled='disabled' type="button" class="cntctfrmpr_default button-small button" value="<?php _e('Default', 'contact_form'); ?>" /> <input disabled='disabled' type="text" name="cntctfrmpr_error_input_border_color" value="" class="cntctfrmpr_colorPicker" /> <?php _e( 'Border color of the input field errors', 'contact_form' ); ?> </div> <div> <input disabled='disabled' type="button" class="cntctfrmpr_default button-small button" id="" value="<?php _e('Default', 'contact_form'); ?>" /> <input disabled='disabled' type="text" name="cntctfrmpr_input_placeholder_error_color" value="" class="cntctfrmpr_colorPicker " /> <?php _e( "Placeholder color of the input field errors", 'contact_form' ); ?> </div> </td> </tr> <tr valign="top" class="cntctfrmpr_style_block"> <th scope="row" style="width:200px;"><?php _e( "Input fields", 'contact_form' ); ?></th> <td colspan="2"> <div> <input disabled='disabled' type="button" class="cntctfrmpr_default button-small button" id="" value="<?php _e('Default', 'contact_form'); ?>" /> <input disabled='disabled' type="text" name="cntctfrmpr_input_background" value="" class="cntctfrmpr_colorPicker" /> <?php _e( "Input fields background color", 'contact_form' ); ?> </div> <div> <input disabled='disabled' type="button" class="cntctfrmpr_default button-small button" value="<?php _e('Default', 'contact_form'); ?>" /> <input disabled='disabled' type="text" name="cntctfrmpr_input_color" value="" class="cntctfrmpr_colorPicker" /> <?php _e( "Text fields color", 'contact_form' ); ?> </div> <input style="margin-left: 66px;" size="8" type="text" value="" name="cntctfrmpr_border_input_width" /> <?php _e( 'Border width in px, numbers only', 'contact_form' ); ?><br /> <div> <input disabled='disabled' type="button" class="cntctfrmpr_default button-small button" value="<?php _e('Default', 'contact_form'); ?>" /> <input disabled='disabled' type="text" name="cntctfrmpr_border_input_color" value="" class="cntctfrmpr_colorPicker" /> <?php _e( 'Border color', 'contact_form' ); ?> </div> </td> </tr> <tr valign="top" class="cntctfrmpr_style_block"> <th scope="row" style="width:200px;"><?php _e( "Submit button", 'contact_form' ); ?></th> <td colspan="2"> <input style="margin-left: 66px;" size="8" type="text" value="" name="cntctfrmpr_button_width" /> <?php _e( 'Width in px, numbers only', 'contact_form' ); ?><br /> <div> <input disabled='disabled' type="button" class="cntctfrmpr_default button-small button" value="<?php _e('Default', 'contact_form'); ?>" /> <input disabled='disabled' type="text" name="cntctfrmpr_button_backgroud" value="" class="cntctfrmpr_colorPicker" /> <?php _e( 'Button color', 'contact_form' ); ?> </div> <div> <input disabled='disabled' type="button" class="cntctfrmpr_default button-small button" value="<?php _e('Default', 'contact_form'); ?>" /> <input disabled='disabled' type="text" name="cntctfrmpr_button_color" value="" class="cntctfrmpr_colorPicker" /> <?php _e( "Button text color", 'contact_form' ); ?> </div> <div> <input disabled='disabled' type="button" class="cntctfrmpr_default button-small button" value="<?php _e('Default', 'contact_form'); ?>" /> <input disabled='disabled' type="text" name="cntctfrmpr_border_button_color" value="" class="cntctfrmpr_colorPicker" /> <?php _e( 'Border color', 'contact_form' ); ?> </div> </td> </tr> </table> <input type="hidden" name="cntctfrmpr_form_submit" value="submit" /> <p class="submit"> <input disabled='disabled' type="button" class="button-primary" value="<?php _e('Save Changes') ?>" /> </p> </div> <div id="cntctfrmpr_right_table"> <h3><?php _e( "Contact Form Pro | Preview", 'contact_form' ); ?></h3> <div id="cntctfrmpr_contact_form"> <div id="cntctfrmpr_show_errors_block"> <input disabled="" type="checkbox" id="cntctfrmpr_show_errors" name="cntctfrmpr_show_errors" /> <?php _e( "Show with errors", 'contact_form' ); ?> </div> <div class="cntctfrmpr_error_text hidden" style="text-align: left;"><?php echo $cntctfrm_options['cntctfrm_form_error']['en']; ?></div> <div style="text-align: left; padding-top: 5px;"> <label for="cntctfrmpr_contact_name"><?php echo $cntctfrm_options['cntctfrm_name_label']['en']; if ( $cntctfrm_options['cntctfrm_required_name_field'] == 1 ) echo '<span class="required"> *</span>'; ?></label> </div> <div class="cntctfrmpr_error_text hidden" style="text-align: left;"><?php echo $cntctfrm_options['cntctfrm_name_error']['en']; ?></div> <div style="text-align: left;"> <input placeholder="<?php _e( "Please enter your full name...", 'contact_form' ); ?>" class="text" type="text" size="40" value="" name="cntctfrmpr_contact_name" id="cntctfrmpr_contact_name" style="text-align: left; margin: 0;" /> <div class="cntctfrmpr_help_box"> <div class="cntctfrmpr_hidden_help_text" style="font-size: 12px; display: none;"><?php _e( "Please enter your full name...", 'contact_form' ); ?></div> </div> </div> <?php if ( $cntctfrm_options['cntctfrm_display_address_field'] == 1 ) { ?> <div style="text-align: left;"> <label for="cntctfrmpr_contact_address"><?php echo $cntctfrm_options['cntctfrm_address_label']['en']; if ( $cntctfrm_options['cntctfrm_required_address_field'] == 1 ) echo '<span class="required"> *</span>'; ?></label> </div> <?php if ( $cntctfrm_options['cntctfrm_required_address_field'] == 1 ) { ?> <div class="cntctfrmpr_error_text hidden" style="text-align: left;"><?php echo $cntctfrm_options['cntctfrm_address_error']['en']; ?></div> <?php } ?> <div style="text-align: left;"> <input placeholder="<?php _e( "Please enter your address...", 'contact_form' ); ?>" class="text" type="text" size="40" value="" name="cntctfrmpr_contact_address" id="cntctfrmpr_contact_address" style="text-align: left; margin: 0;" /> <div class="cntctfrmpr_help_box"> <div class="cntctfrmpr_hidden_help_text" style="font-size: 12px; display: none;"><?php _e( "Please enter your address...", 'contact_form' ); ?></div> </div> </div> <?php } ?> <div style="text-align: left;"> <label for="cntctfrmpr_contact_email"><?php echo $cntctfrm_options['cntctfrm_email_label']['en']; if ( $cntctfrm_options['cntctfrm_required_email_field'] == 1 ) echo '<span class="required"> *</span>'; ?></label> </div> <div class="cntctfrmpr_error_text hidden" style="text-align: left;"><?php echo $cntctfrm_options['cntctfrm_email_error']['en']; ?></div> <div style="text-align: left;"> <input placeholder="<?php _e( "Please enter your email address...", 'contact_form' ); ?>" class="text" type="text" size="40" value="" name="cntctfrmpr_contact_email" id="cntctfrmpr_contact_email" style="text-align: left; margin: 0;" /> <div class="cntctfrmpr_help_box"> <div class="cntctfrmpr_hidden_help_text" style="font-size: 12px; display: none;"><?php _e( "Please enter your email address...", 'contact_form' ); ?></div> </div> </div> <?php if ( $cntctfrm_options['cntctfrm_display_phone_field'] == 1 ) { ?> <div style="text-align: left;"> <label for="cntctfrmpr_contact_phone"><?php echo $cntctfrm_options['cntctfrm_phone_label']['en']; if ( $cntctfrm_options['cntctfrm_required_phone_field'] == 1 ) echo '<span class="required"> *</span>'; ?></label> </div> <div class="cntctfrmpr_error_text hidden" style="text-align: left;"><?php echo $cntctfrm_options['phone_error']['en']; ?></div> <div style="text-align: left;"> <input placeholder="<?php _e( "Please enter your phone number...", 'contact_form' ); ?>" class="text" type="text" size="40" value="" name="cntctfrmpr_contact_phone" id="cntctfrmpr_contact_phone" style="text-align: left; margin: 0;" /> <div class="cntctfrmpr_help_box"> <div class="cntctfrmpr_hidden_help_text" style="font-size: 12px; display: none;"><?php _e( "Please enter your phone number...", 'contact_form' ); ?></div> </div> </div> <?php } ?> <div style="text-align: left;"> <label for="cntctfrmpr_contact_subject"><?php echo $cntctfrm_options['cntctfrm_subject_label']['en']; if ( $cntctfrm_options['cntctfrm_required_subject_field'] == 1 ) echo '<span class="required"> *</span>'; ?></label> </div> <div class="cntctfrmpr_error_text hidden" style="text-align: left;"><?php echo $cntctfrm_options['cntctfrm_subject_error']['en']; ?></div> <div style="text-align: left;"> <input placeholder="<?php _e( "Please enter subject...", 'contact_form' ); ?>" class="text" type="text" size="40" value="" name="cntctfrmpr_contact_subject" id="cntctfrmpr_contact_subject" style="text-align: left; margin: 0;" /> <div class="cntctfrmpr_help_box"> <div class="cntctfrmpr_hidden_help_text" style="font-size: 12px; display: none;"><?php _e( "Please enter subject...", 'contact_form' ); ?></div> </div> </div> <div style="text-align: left;"> <label for="cntctfrmpr_contact_message"><?php echo $cntctfrm_options['cntctfrm_message_label']['en']; if ( $cntctfrm_options['cntctfrm_required_message_field'] == 1 ) echo '<span class="required"> *</span>'; ?></label> </div> <div class="cntctfrmpr_error_text hidden" style="text-align: left;"><?php echo $cntctfrm_options['cntctfrm_message_error']['en']; ?></div> <div style="text-align: left;"> <textarea placeholder="<?php _e( "Please enter your message...", 'contact_form' ); ?>" rows="5" cols="30" name="cntctfrmpr_contact_message" id="cntctfrmpr_contact_message"></textarea> <div class="cntctfrmpr_help_box"> <div class="cntctfrmpr_hidden_help_text" style="font-size: 12px; display: none;"><?php _e( "Please enter your message...", 'contact_form' ); ?></div> </div> </div> <?php if ( $cntctfrm_options['cntctfrm_attachment'] == 1 ) { ?> <div style="text-align: left;"> <label for="cntctfrmpr_contact_attachment"><?php echo $cntctfrm_options['cntctfrm_attachment_label']['en']; ?></label> </div> <div class="cntctfrmpr_error_text hidden" style="text-align: left;"><?php echo $cntctfrm_options['cntctfrm_attachment_error']['en']; ?></div> <div style="text-align: left;"> <input type="file" name="cntctfrmpr_contact_attachment" id="cntctfrmpr_contact_attachment" style="float:left;" /> <?php if ( $cntctfrm_options['cntctfrm_attachment_explanations'] == 1 ) { ?> <div class="cntctfrmpr_help_box cntctfrmpr_hidden_help_text_attach"><div class="cntctfrmpr_hidden_help_text" style="font-size: 12px; display: none;"><?php _e( "Supported file types: HTML, TXT, CSS, GIF, PNG, JPEG, JPG, TIFF, BMP, AI, EPS, PS, RTF, PDF, DOC, DOCX, XLS, ZIP, RAR, WAV, MP3, PPT. Max file size: 2MB", 'contact_form' ); ?></div></div> <?php } ?> </div> <?php } ?> <?php if ( $cntctfrm_options['cntctfrm_send_copy'] == 1 ) { ?> <div style="text-align: left;"> <input type="checkbox" value="1" name="cntctfrmpr_contact_send_copy" id="cntctfrmpr_contact_send_copy" style="text-align: left; margin: 0;" /> <label for="cntctfrmpr_contact_send_copy"><?php echo $cntctfrm_options['cntctfrm_send_copy_label']['en']; ?></label> </div> <?php } ?> <div style="text-align: left; padding-top: 8px;"> <input type="submit" value="<?php echo $cntctfrm_options['cntctfrm_submit_label']['en']; ?>" style="cursor: pointer; margin: 0pt; text-align: center;margin-bottom:10px;" /> </div> </div> <div id="cntctfrmpr_shortcode"> <?php _e( "If you would like to add the Contact Form to your website, just copy and paste this shortcode to your post or page or widget:", 'contact_form' ); ?><br/> <div> <code id="cntctfrmpr_shortcode_code"> [bestwebsoft_contact_form] </code> </div> </div> </div> <div class="clear"></div> </div> </div> <?php } } // Display contact form in front end - page or post if( ! function_exists( 'cntctfrm_display_form' ) ) { function cntctfrm_display_form( $atts = array( 'lang' => 'en' ) ) { global $error_message, $cntctfrm_options, $cntctfrm_result; extract( shortcode_atts( array( 'lang' => 'en' ), $atts ) ); $cntctfrm_options = get_option( 'cntctfrm_options' ); $content = ""; if ( '80' != $_SERVER["SERVER_PORT"] ) $page_url = $page_url = ( isset( $_SERVER["HTTPS"] ) && $_SERVER["HTTPS"] == "on" ? "https://" : "http://" ).$_SERVER["SERVER_NAME"].':'. $_SERVER["SERVER_PORT"].strip_tags( $_SERVER["REQUEST_URI"] ); else $page_url = ( isset( $_SERVER["HTTPS"] ) && $_SERVER["HTTPS"] == "on" ? "https://" : "http://" ).$_SERVER["SERVER_NAME"].strip_tags( $_SERVER["REQUEST_URI"] ); // If contact form submited $name = isset( $_POST['cntctfrm_contact_name'] ) ? htmlspecialchars( $_POST['cntctfrm_contact_name'] ) : ""; $address = isset( $_POST['cntctfrm_contact_address'] ) ? htmlspecialchars( $_POST['cntctfrm_contact_address'] ) : ""; $email = isset( $_POST['cntctfrm_contact_email'] ) ? htmlspecialchars( stripslashes( $_POST['cntctfrm_contact_email'] ) ) : ""; $subject = isset( $_POST['cntctfrm_contact_subject'] ) ? htmlspecialchars( $_POST['cntctfrm_contact_subject'] ) : ""; $message = isset( $_POST['cntctfrm_contact_message'] ) ? htmlspecialchars( $_POST['cntctfrm_contact_message'] ) : ""; $phone = isset( $_POST['cntctfrm_contact_phone'] ) ? htmlspecialchars( $_POST['cntctfrm_contact_phone'] ) : ""; $name = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $name ) ) ); $address = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $address ) ) ); $email = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $email ) ) ); $subject = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $subject ) ) ); $message = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $message ) ) ); $phone = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $phone ) ) ); $send_copy = isset( $_POST['cntctfrm_contact_send_copy'] ) ? $_POST['cntctfrm_contact_send_copy'] : ""; // If it is good if ( true === $cntctfrm_result ) { $_SESSION['cntctfrm_send_mail'] = true; if ( $cntctfrm_options['cntctfrm_action_after_send'] == 1 ) $content .= '<div id="cntctfrm_thanks">' . $cntctfrm_options['cntctfrm_thank_text'][$lang] . '</div>'; else $content .= "<script type='text/javascript'>window.location.href = '".$cntctfrm_options['cntctfrm_redirect_url']."';</script>"; } else if ( false === $cntctfrm_result ) { // If email not be delivered $error_message['error_form'] = __( "Sorry, email message could not be delivered.", 'contact_form' ); } if ( true !== $cntctfrm_result ) { $_SESSION['cntctfrm_send_mail'] = false; // Output form $content .= '<form method="post" id="cntctfrm_contact_form" action="'.$page_url.'" enctype="multipart/form-data">'; if ( isset( $error_message['error_form'] ) ) { $content .= '<div style="text-align: left; color: red;">'.$error_message['error_form'].'</div>'; } $content .= '<div style="text-align: left; padding-top: 5px;"> <label for="cntctfrm_contact_name">'. $cntctfrm_options['cntctfrm_name_label'][$lang] . ( $cntctfrm_options['cntctfrm_required_name_field'] == 1 && $cntctfrm_options['cntctfrm_required_symbol'] == 1 ? '<span class="required"> *</span></label>' : '</label>' ) . ' </div>'; if ( isset( $error_message['error_name'] ) ) { $content .= '<div style="text-align: left; color: red;">'.$error_message['error_name'].'</div>'; } $content .= '<div style="text-align: left;"> <input class="text" type="text" size="40" value="'.$name.'" name="cntctfrm_contact_name" id="cntctfrm_contact_name" style="text-align: left; margin: 0;" /> </div>'; if ( $cntctfrm_options['cntctfrm_display_address_field'] == 1 ) { $content .= '<div style="text-align: left;"> <label for="cntctfrm_contact_address">'. $cntctfrm_options['cntctfrm_address_label'][$lang] . ( $cntctfrm_options['cntctfrm_required_address_field'] == 1 && $cntctfrm_options['cntctfrm_required_symbol'] == 1 ? '<span class="required"> *</span></label>' : '</label>' ) . ' </div>'; if( isset( $error_message['error_address'] ) ) { $content .= '<div style="text-align: left; color: red;">'.$error_message['error_address'].'</div>'; } $content .= '<div style="text-align: left;"> <input class="text" type="text" size="40" value="'.$address.'" name="cntctfrm_contact_address" id="cntctfrm_contact_address" style="text-align: left; margin: 0;" /> </div> '; } $content .= '<div style="text-align: left;"> <label for="cntctfrm_contact_email">'. $cntctfrm_options['cntctfrm_email_label'][$lang] . ( $cntctfrm_options['cntctfrm_required_email_field'] == 1 && $cntctfrm_options['cntctfrm_required_symbol'] == 1 ? '<span class="required"> *</span></label>' : '</label>' ) . ' </div>'; if ( isset( $error_message['error_email'] ) ) { $content .= '<div style="text-align: left; color: red;">'.$error_message['error_email'].'</div>'; } $content .= '<div style="text-align: left;"> <input class="text" type="text" size="40" value="'.$email.'" name="cntctfrm_contact_email" id="cntctfrm_contact_email" style="text-align: left; margin: 0;" /> </div> '; if ( $cntctfrm_options['cntctfrm_display_phone_field'] == 1 ) { $content .= '<div style="text-align: left;"> <label for="cntctfrm_contact_phone">'. $cntctfrm_options['cntctfrm_phone_label'][$lang] . ( $cntctfrm_options['cntctfrm_required_phone_field'] == 1 && $cntctfrm_options['cntctfrm_required_symbol'] == 1 ? '<span class="required"> *</span></label>' : '</label>' ) . ' </div>'; if( isset( $error_message['error_phone'] ) ) { $content .= '<div style="text-align: left; color: red;">'.$error_message['error_phone'].'</div>'; } $content .= '<div style="text-align: left;"> <input class="text" type="text" size="40" value="'.$phone.'" name="cntctfrm_contact_phone" id="cntctfrm_contact_phone" style="text-align: left; margin: 0;" /> </div> '; } $content .= '<div style="text-align: left;"> <label for="cntctfrm_contact_subject">'. $cntctfrm_options['cntctfrm_subject_label'][$lang] . ( $cntctfrm_options['cntctfrm_required_subject_field'] == 1 && $cntctfrm_options['cntctfrm_required_symbol'] == 1 ? '<span class="required"> *</span></label>' : '</label>' ) . ' </div>'; if ( isset( $error_message['error_subject'] ) ) { $content .= '<div style="text-align: left; color: red;">'.$error_message['error_subject'].'</div>'; } $content .= '<div style="text-align: left;"> <input class="text" type="text" size="40" value="'.$subject.'" name="cntctfrm_contact_subject" id="cntctfrm_contact_subject" style="text-align: left; margin: 0;" /> </div> <div style="text-align: left;"> <label for="cntctfrm_contact_message">'. $cntctfrm_options['cntctfrm_message_label'][$lang] . ( $cntctfrm_options['cntctfrm_required_message_field'] == 1 && $cntctfrm_options['cntctfrm_required_symbol'] == 1 ? '<span class="required"> *</span></label>' : '</label>' ) . ' </div>'; if ( isset( $error_message['error_message'] ) ) { $content .= '<div style="text-align: left; color: red;">'.$error_message['error_message'].'</div>'; } $content .= '<div style="text-align: left;"> <textarea rows="5" cols="30" name="cntctfrm_contact_message" id="cntctfrm_contact_message">'.$message.'</textarea> </div>'; if ( $cntctfrm_options['cntctfrm_attachment'] == 1 ) { $content .= '<div style="text-align: left;"> <label for="cntctfrm_contact_attachment">'. $cntctfrm_options['cntctfrm_attachment_label'][$lang] . '</label> </div>'; if( isset( $error_message['error_attachment'] ) ) { $content .= '<div style="text-align: left; color: red;">'.$error_message['error_attachment'].'</div>'; } $content .= '<div style="text-align: left;"> <input type="file" name="cntctfrm_contact_attachment" id="cntctfrm_contact_attachment"'.( isset( $error_message['error_attachment'] ) ? "class='error'": "" ).' />'; if( $cntctfrm_options['cntctfrm_attachment_explanations'] == 1 ){ $content .= '<label style="font-size:10px;"><br />'. __( "You can attach the following file formats", 'contact_form' ) . ': html, txt, css, gif, png, jpeg, jpg, tiff, bmp, ai, eps, ps, rtf, pdf, doc, docx, xls, zip, rar, wav, mp3, ppt</label>'; } $content .= ' </div>'; } if ( $cntctfrm_options['cntctfrm_send_copy'] == 1 ) { $content .= '<div style="text-align: left;"> <input type="checkbox" value="1" name="cntctfrm_contact_send_copy" id="cntctfrm_contact_send_copy" style="text-align: left; margin: 0;" '.( $send_copy == '1' ? " checked=\"checked\" " : "" ).' /> <label for="cntctfrm_contact_send_copy">'. $cntctfrm_options['cntctfrm_send_copy_label'][$lang] . '</label> </div>'; } if ( has_filter( 'cntctfrm_display_captcha' ) ) { $content .= apply_filters( 'cntctfrm_display_captcha' , $error_message ); } $content .= '<div style="text-align: left; padding-top: 8px;"> <input type="hidden" value="send" name="cntctfrm_contact_action"><input type="hidden" value="Version: 3.30" /> <input type="hidden" value="'.$lang.'" name="cntctfrm_language"> <input type="submit" value="'. $cntctfrm_options['cntctfrm_submit_label'][$lang]. '" style="cursor: pointer; margin: 0pt; text-align: center;margin-bottom:10px;" /> </div> </form>'; } return $content ; } } if ( ! function_exists( 'cntctfrm_check_and_send' ) ) { function cntctfrm_check_and_send() { global $cntctfrm_result; $cntctfrm_options = get_option( 'cntctfrm_options' ); if( isset( $_POST['cntctfrm_contact_action'] ) ){ // Check all input data $cntctfrm_result = cntctfrm_check_form(); } // If it is good if( true === $cntctfrm_result ) { $_SESSION['cntctfrm_send_mail'] = true; if( $cntctfrm_options['cntctfrm_action_after_send'] == 0 ){ wp_redirect( $cntctfrm_options['cntctfrm_redirect_url'] ); exit; } } } } // Check all input data if ( ! function_exists( 'cntctfrm_check_form' ) ) { function cntctfrm_check_form() { global $error_message; global $cntctfrm_options; $language = isset( $_POST['cntctfrm_language'] ) ? $_POST['cntctfrm_language'] : 'en'; $path_of_uploaded_file = ''; if ( empty( $cntctfrm_options ) ) $cntctfrm_options = get_option( 'cntctfrm_options' ); $cntctfrm_result = ""; // Error messages array $error_message = array(); $name = isset( $_POST['cntctfrm_contact_name'] ) ? htmlspecialchars( $_POST['cntctfrm_contact_name'] ) : ""; $address = isset( $_POST['cntctfrm_contact_address'] ) ? htmlspecialchars( $_POST['cntctfrm_contact_address'] ) : ""; $email = isset( $_POST['cntctfrm_contact_email'] ) ? htmlspecialchars( stripslashes( $_POST['cntctfrm_contact_email'] ) ) : ""; $subject = isset( $_POST['cntctfrm_contact_subject'] ) ? htmlspecialchars( $_POST['cntctfrm_contact_subject'] ) : ""; $message = isset( $_POST['cntctfrm_contact_message'] ) ? htmlspecialchars( $_POST['cntctfrm_contact_message'] ) : ""; $phone = isset( $_POST['cntctfrm_contact_phone'] ) ? htmlspecialchars( $_POST['cntctfrm_contact_phone'] ) : ""; $name = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $name ) ) ); $address = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $address ) ) ); $email = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $email ) ) ); $subject = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $subject ) ) ); $message = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $message ) ) ); $phone = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $phone ) ) ); if ( $cntctfrm_options['cntctfrm_required_name_field'] == 1 ) $error_message['error_name'] = $cntctfrm_options['cntctfrm_name_error'][$language]; if ( $cntctfrm_options['cntctfrm_required_address_field'] == 1 && $cntctfrm_options['cntctfrm_display_address_field'] == 1 ) $error_message['error_address'] = $cntctfrm_options['cntctfrm_address_error'][$language]; if ( $cntctfrm_options['cntctfrm_required_email_field'] == 1 ) $error_message['error_email'] = $cntctfrm_options['cntctfrm_email_error'][$language]; if ( $cntctfrm_options['cntctfrm_required_subject_field'] == 1 ) $error_message['error_subject'] = $cntctfrm_options['cntctfrm_subject_error'][$language]; if ( $cntctfrm_options['cntctfrm_required_message_field'] == 1 ) $error_message['error_message'] = $cntctfrm_options['cntctfrm_message_error'][$language]; if ( $cntctfrm_options['cntctfrm_required_phone_field'] == 1 && $cntctfrm_options['cntctfrm_display_phone_field'] == 1 ) $error_message['error_phone'] = $cntctfrm_options['cntctfrm_phone_error'][$language]; $error_message['error_form'] = $cntctfrm_options['cntctfrm_form_error'][$language]; if ( $cntctfrm_options['cntctfrm_attachment'] == 1 ) { global $path_of_uploaded_file, $mime_type; $mime_type= array( 'html'=>'text/html', 'htm'=>'text/html', 'txt'=>'text/plain', 'css'=>'text/css', 'gif'=>'image/gif', 'png'=>'image/x-png', 'jpeg'=>'image/jpeg', 'jpg'=>'image/jpeg', 'JPG'=>'image/jpeg', 'jpe'=>'image/jpeg', 'TIFF'=>'image/tiff', 'tiff'=>'image/tiff', 'tif'=>'image/tiff', 'TIF'=>'image/tiff', 'bmp'=>'image/x-ms-bmp', 'BMP'=>'image/x-ms-bmp', 'ai'=>'application/postscript', 'eps'=>'application/postscript', 'ps'=>'application/postscript', 'rtf'=>'application/rtf', 'pdf'=>'application/pdf', 'doc'=>'application/msword', 'docx'=>'application/msword', 'xls'=>'application/vnd.ms-excel', 'zip'=>'application/zip', 'rar'=>'application/rar', 'wav'=>'audio/wav', 'mp3'=>'audio/mp3', 'ppt'=>'application/vnd.ms-powerpoint'); $error_message['error_attachment'] = $cntctfrm_options['cntctfrm_attachment_error'][ $language ]; } // Check information wich was input in fields if( $cntctfrm_options['cntctfrm_required_name_field'] == 1 && "" != $name ) unset( $error_message['error_name'] ); if( $cntctfrm_options['cntctfrm_display_address_field'] == 1 && $cntctfrm_options['cntctfrm_required_address_field'] == 1 && "" != $address ) unset( $error_message['error_address'] ); if( $cntctfrm_options['cntctfrm_required_email_field'] == 1 && "" != $email && preg_match( "/^(?:[a-z0-9_']+(?:[a-z0-9\-_\.']+)?@[a-z0-9]+(?:[a-z0-9\-\.]+)?\.[a-z]{2,5})$/i", trim( stripslashes( $email ) ) ) ) unset( $error_message['error_email'] ); if( $cntctfrm_options['cntctfrm_required_subject_field'] == 1 && "" != $subject ) unset( $error_message['error_subject'] ); if( $cntctfrm_options['cntctfrm_required_message_field'] == 1 && "" != $message ) unset( $error_message['error_message'] ); if( $cntctfrm_options['cntctfrm_display_phone_field'] == 1 && $cntctfrm_options['cntctfrm_required_phone_field'] == 1 && "" != $phone ) unset( $error_message['error_phone'] ); // If captcha plugin exists if ( ! apply_filters( 'cntctfrm_check_form', $_POST ) ) $error_message['error_captcha'] = $cntctfrm_options['cntctfrm_captcha_error'][ $language ]; if ( isset( $_FILES["cntctfrm_contact_attachment"]["tmp_name"] ) && $_FILES["cntctfrm_contact_attachment"]["tmp_name"] != "" ) { if( is_multisite() ){ if ( defined('UPLOADS') ) { if( ! is_dir( ABSPATH . UPLOADS ) ) { wp_mkdir_p( ABSPATH . UPLOADS ); } $path_of_uploaded_file = ABSPATH . UPLOADS . $_FILES["cntctfrm_contact_attachment"]["name"]; } else if ( defined( 'BLOGUPLOADDIR' ) ) { if ( ! is_dir( BLOGUPLOADDIR ) ) { wp_mkdir_p( BLOGUPLOADDIR ); } $path_of_uploaded_file = BLOGUPLOADDIR . $_FILES["cntctfrm_contact_attachment"]["name"]; } else { $uploads = wp_upload_dir(); if ( ! isset( $uploads['path'] ) && isset ( $uploads['error'] ) ) $error_message['error_attachment'] = $uploads['error']; else $path_of_uploaded_file = $uploads['path'] . "/" . $_FILES["cntctfrm_contact_attachment"]["name"]; } } else { $uploads = wp_upload_dir(); if ( ! isset( $uploads['path'] ) && isset ( $uploads['error'] ) ) $error_message['error_attachment'] = $uploads['error']; else $path_of_uploaded_file = $uploads['path'] . "/" . $_FILES["cntctfrm_contact_attachment"]["name"]; } $tmp_path = $_FILES["cntctfrm_contact_attachment"]["tmp_name"]; $path_info = pathinfo( $path_of_uploaded_file ); if ( array_key_exists ( $path_info['extension'], $mime_type ) ) { if ( is_uploaded_file( $tmp_path ) ) { if ( move_uploaded_file( $tmp_path, $path_of_uploaded_file ) ) { do_action( 'cntctfrm_get_attachment_data', $path_of_uploaded_file ); unset( $error_message['error_attachment'] ); } else { $letter_upload_max_size = substr( ini_get('upload_max_filesize'), -1); $upload_max_size = substr( ini_get('upload_max_filesize'), 0, -1); $upload_max_size= '1'; switch( strtoupper( $letter_upload_max_size ) ) { case 'P': $upload_max_size *= 1024; case 'T': $upload_max_size *= 1024; case 'G': $upload_max_size *= 1024; case 'M': $upload_max_size *= 1024; case 'K': $upload_max_size *= 1024; break; } if ( isset( $upload_max_size ) && isset( $_FILES["cntctfrm_contact_attachment"]["size"] ) && $_FILES["cntctfrm_contact_attachment"]["size"] <= $upload_max_size ) { $error_message['error_attachment'] = $cntctfrm_options['cntctfrm_attachment_move_error'][ $language ]; } else { $error_message['error_attachment'] = $cntctfrm_options['cntctfrm_attachment_size_error'][ $language ]; } } } else { $error_message['error_attachment'] = $cntctfrm_options['cntctfrm_attachment_upload_error'][ $language ]; } } } else { unset( $error_message['error_attachment'] ); } if( 1 == count( $error_message ) ) { unset( $error_message['error_form'] ); // If all is good - send mail $cntctfrm_result = cntctfrm_send_mail(); do_action( 'cntctfrm_check_dispatch', $cntctfrm_result ); } return $cntctfrm_result; } } // Send mail function if( ! function_exists( 'cntctfrm_send_mail' ) ) { function cntctfrm_send_mail() { global $cntctfrm_options, $path_of_uploaded_file, $wp_version; $to = ""; $name = isset( $_POST['cntctfrm_contact_name'] ) ? $_POST['cntctfrm_contact_name'] : ""; $address = isset( $_POST['cntctfrm_contact_address'] ) ? $_POST['cntctfrm_contact_address'] : ""; $email = isset( $_POST['cntctfrm_contact_email'] ) ? stripslashes( $_POST['cntctfrm_contact_email'] ) : ""; $subject = isset( $_POST['cntctfrm_contact_subject'] ) ? $_POST['cntctfrm_contact_subject'] : ""; $message = isset( $_POST['cntctfrm_contact_message'] ) ? $_POST['cntctfrm_contact_message'] : ""; $phone = isset( $_POST['cntctfrm_contact_phone'] ) ? $_POST['cntctfrm_contact_phone'] : ""; $user_agent = cntctfrm_clean_input( $_SERVER['HTTP_USER_AGENT'] ); $name = stripslashes( strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $name ) ) ) ); $address = stripslashes( strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $address ) ) ) ); $email = stripslashes( strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $email ) ) ) ); $subject = stripslashes( strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $subject ) ) ) ); $message = stripslashes( strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $message ) ) ) ); $phone = stripslashes( strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', $phone ) ) ) ); if ( isset( $_SESSION['cntctfrm_send_mail'] ) && $_SESSION['cntctfrm_send_mail'] == true ) return true; if ( $cntctfrm_options['cntctfrm_select_email'] == 'user' ) { if ( '3.3' > $wp_version && function_exists('get_userdatabylogin') && false !== $user = get_userdatabylogin( $cntctfrm_options['cntctfrm_user_email'] ) ) { $to = $user->user_email; } elseif ( false !== $user = get_user_by( 'login', $cntctfrm_options['cntctfrm_user_email'] ) ) $to = $user->user_email; } else { $to = $cntctfrm_options['cntctfrm_custom_email']; } if ( "" == $to ) { // If email options are not certain choose admin email $to = get_option("admin_email"); } if ( "" != $to ) { $user_info_string = ''; $userdomain = ''; $form_action_url = ''; $attachments = array(); $headers = ""; if ( getenv('HTTPS') == 'on' ) { $form_action_url = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; } else { $form_action_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; } if ( $cntctfrm_options['cntctfrm_display_add_info'] == 1) { $userdomain = @gethostbyaddr($_SERVER['REMOTE_ADDR']); if ( $cntctfrm_options['cntctfrm_display_add_info'] == 1 || $cntctfrm_options['cntctfrm_display_sent_from'] == 1 || $cntctfrm_options['cntctfrm_display_coming_from'] == 1 || $cntctfrm_options['cntctfrm_display_user_agent'] == 1 ) { $user_info_string .= '<tr> <td><br /></td><td><br /></td> </tr>'; } if ( $cntctfrm_options['cntctfrm_display_sent_from'] == 1) { $user_info_string .= '<tr> <td>'.__('Sent from (ip address)', 'contact_form').':</td><td>'.$_SERVER['REMOTE_ADDR']." ( ". $userdomain ." )".'</td> </tr>'; } if ( $cntctfrm_options['cntctfrm_display_date_time'] == 1) { $user_info_string .= '<tr> <td>'.__('Date/Time', 'contact_form').':</td><td>'.date_i18n( get_option( 'date_format' ).' '.get_option( 'time_format' ), strtotime( current_time( 'mysql' ) ) ).'</td> </tr>'; } if ( $cntctfrm_options['cntctfrm_display_coming_from'] == 1) { $user_info_string .= '<tr> <td>'.__('Sent from (referer)', 'contact_form').':</td><td>'.$form_action_url.'</td> </tr>'; } if ( $cntctfrm_options['cntctfrm_display_user_agent'] == 1) { $user_info_string .= '<tr> <td>'.__('Using (user agent)', 'contact_form').':</td><td>'.$user_agent.'</td> </tr>'; } } // message $message_text = ' <html> <head> <title>'. __( "Contact from", 'contact_form' ) . get_bloginfo('name').'</title> </head> <body> <table> <tr> <td width="160">'. __( "Name", 'contact_form' ) . '</td><td>'. $name .'</td> </tr> '; if ( $cntctfrm_options['cntctfrm_display_address_field'] == 1 ) $message_text .= '<tr> <td>'. __( "Address", 'contact_form' ) . '</td><td>'. $address .'</td> </tr>'; $message_text .= '<tr> <td>'. __( "Email", 'contact_form' ) .'</td><td>'. $email .'</td> </tr> '; if ( $cntctfrm_options['cntctfrm_display_phone_field'] == 1 ) $message_text .= '<tr> <td>'. __( "Phone", 'contact_form' ) . '</td><td>'. $phone .'</td> </tr>'; $message_text .= '<tr> <td>'. __( "Subject", 'contact_form' ) . '</td><td>'. $subject .'</td> </tr> <tr> <td>'. __( "Message", 'contact_form' ) . '</td><td>'. $message .'</td> </tr> <tr> <td>'. __( "Site", 'contact_form' ) . '</td><td>'.get_bloginfo("url").'</td> </tr> <tr> <td><br /></td><td><br /></td> </tr> '; $message_text_for_user = $message_text . '</table></body></html>'; $message_text .= $user_info_string . '</table></body></html>'; do_action( 'cntctfrm_get_mail_data', $to, $name, $email, $address, $phone, $subject, $message, $form_action_url, $user_agent, $userdomain ); if ( $cntctfrm_options['cntctfrm_mail_method'] == 'wp-mail' ) { // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\n"; // Additional headers if( 'custom' == $cntctfrm_options['cntctfrm_from_email'] ) $headers .= 'From: '.stripslashes( $cntctfrm_options['cntctfrm_custom_from_email'] ). ''; else $headers .= 'From: '. $email . ''; if ( $cntctfrm_options['cntctfrm_attachment'] == 1 && isset( $_FILES["cntctfrm_contact_attachment"]["tmp_name"] ) && $_FILES["cntctfrm_contact_attachment"]["tmp_name"] != "" ) { $attachments = array( $path_of_uploaded_file ); } if ( isset( $_POST['cntctfrm_contact_send_copy'] ) && $_POST['cntctfrm_contact_send_copy'] == 1 ) wp_mail( $email, $subject, $message_text_for_user, $headers, $attachments ); // Mail it $mail_result = wp_mail( $to, $subject, $message_text, $headers, $attachments ); // delete attachment if ( $cntctfrm_options['cntctfrm_attachment'] == 1 && isset( $_FILES["cntctfrm_contact_attachment"]["tmp_name"] ) && $_FILES["cntctfrm_contact_attachment"]["tmp_name"] != "" && $cntctfrm_options['cntctfrm_delete_attached_file'] == '1' ) { @unlink( $path_of_uploaded_file ); } return $mail_result; } else { if ( $cntctfrm_options['cntctfrm_attachment'] == 1 && isset( $_FILES["cntctfrm_contact_attachment"]["tmp_name"] ) && $_FILES["cntctfrm_contact_attachment"]["tmp_name"] != "") { global $path_of_uploaded_file; $headers = ""; $message_block = $message_text; if ( 'custom' == $cntctfrm_options['cntctfrm_select_from_field'] ) $from_field_name = stripslashes( $cntctfrm_options['cntctfrm_from_field'] ); else $from_field_name = $name; // Additional headers if ( 'custom' == $cntctfrm_options['cntctfrm_from_email'] ) $headers .= 'From: '.$from_field_name.' <'.stripslashes( $cntctfrm_options['cntctfrm_custom_from_email'] ). '>' . "\n"; else $headers .= 'From: '.$from_field_name.' <'.stripslashes( $email ). '>' . "\n"; $bound_text = "jimmyP123"; $bound = "--".$bound_text.""; $bound_last = "--".$bound_text."--"; $headers .= "MIME-Version: 1.0\n". "Content-Type: multipart/mixed; boundary=\"$bound_text\""; $message_text = __( "If you can see this MIME, it means that the MIME type is not supported by your email client!", "contact_form" ) . "\n"; $message_text .= $bound."\n" . "Content-Type: text/html; charset=\"utf-8\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message_block . "\n\n"; $file = file_get_contents($path_of_uploaded_file); $message_text .= $bound."\n"; $message_text .= "Content-Type: application/octet-stream; name=\"".basename($path_of_uploaded_file)."\"\n" . "Content-Description: ".basename($path_of_uploaded_file)."\n" . "Content-Disposition: attachment;\n" . " filename=\"".basename($path_of_uploaded_file)."\"; size=".filesize($path_of_uploaded_file).";\n" . "Content-Transfer-Encoding: base64\n\n" . chunk_split( base64_encode( $file ) ) . "\n\n"; $message_text .= $bound_last; } else { // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\n"; if ( 'custom' == $cntctfrm_options['cntctfrm_select_from_field'] ) $from_field_name = stripslashes( $cntctfrm_options['cntctfrm_from_field'] ); else $from_field_name = $name; // Additional headers if( 'custom' == $cntctfrm_options['cntctfrm_from_email'] ) $headers .= 'From: '.$from_field_name.' <'.stripslashes( $cntctfrm_options['cntctfrm_custom_from_email'] ). '>' . "\n"; else $headers .= 'From: '.$from_field_name.' <'.$email. '>' . "\n"; } if ( isset( $_POST['cntctfrm_contact_send_copy'] ) && $_POST['cntctfrm_contact_send_copy'] == 1 ) @mail( $email, $subject, $message_text_for_user, $headers ); $mail_result = @mail( $to, $subject , $message_text, $headers); // delete attachment if ( $cntctfrm_options['cntctfrm_attachment'] == 1 && isset( $_FILES["cntctfrm_contact_attachment"]["tmp_name"] ) && $_FILES["cntctfrm_contact_attachment"]["tmp_name"] != "" && $cntctfrm_options['cntctfrm_delete_attached_file'] == '1' ) { @unlink( $path_of_uploaded_file ); } return $mail_result; } } return false; } } if ( ! function_exists ( 'cntctfrm_plugin_action_links' ) ) { function cntctfrm_plugin_action_links( $links, $file ) { //Static so we don't call plugin_basename on every plugin row. static $this_plugin; if ( ! $this_plugin ) $this_plugin = plugin_basename(__FILE__); if ( $file == $this_plugin ){ $settings_link = '<a href="admin.php?page=contact_form.php">' . __('Settings', 'contact_form') . '</a>'; array_unshift( $links, $settings_link ); } return $links; } } // end function cntctfrm_plugin_action_links if ( ! function_exists ( 'cntctfrm_register_plugin_links' ) ) { function cntctfrm_register_plugin_links( $links, $file ) { $base = plugin_basename(__FILE__); if ( $file == $base ) { $links[] = '<a href="admin.php?page=contact_form.php">' . __( 'Settings','contact_form' ) . '</a>'; $links[] = '<a href="http://wordpress.org/extend/plugins/contact-form-plugin/faq/" target="_blank">' . __( 'FAQ','contact_form' ) . '</a>'; $links[] = '<a href="http://support.bestwebsoft.com">' . __( 'Support','contact_form' ) . '</a>'; } return $links; } } if ( ! function_exists ( 'cntctfrm_clean_input' ) ) { function cntctfrm_clean_input( $string, $preserve_space = 0 ) { if ( is_string( $string ) ) { if ( $preserve_space ) { return cntctfrm_sanitize_string( strip_tags( stripslashes( $string ) ), $preserve_space ); } return trim( cntctfrm_sanitize_string( strip_tags( stripslashes( $string ) ) ) ); } else if ( is_array( $string ) ) { reset( $string ); while ( list($key, $value ) = each( $string ) ) { $string[$key] = cntctfrm_clean_input($value,$preserve_space); } return $string; } else { return $string; } } } // end function ctf_clean_input // functions for protecting and validating form vars if ( ! function_exists ( 'cntctfrm_sanitize_string' ) ) { function cntctfrm_sanitize_string( $string, $preserve_space = 0 ) { if( ! $preserve_space ) $string = preg_replace("/ +/", ' ', trim( $string ) ); return preg_replace( "/[<>]/", '_', $string ); } } //Function '_plugin_init' are using to add language files. if ( ! function_exists ( 'cntctfrm_plugin_init' ) ) { function cntctfrm_plugin_init() { if ( ! session_id() ) @session_start(); load_plugin_textdomain( 'contact_form', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' ); load_plugin_textdomain( 'bestwebsoft', false, dirname( plugin_basename( __FILE__ ) ) . '/bws_menu/languages/' ); } } // end function cntctfrm_plugin_init if ( ! function_exists ( 'cntctfrm_admin_head' ) ) { function cntctfrm_admin_head() { global $wp_version; wp_enqueue_style( 'cntctfrmStylesheet', plugins_url( 'css/style.css', __FILE__ ) ); if ( isset( $_REQUEST['page'] ) && ( $_REQUEST['page'] == 'contact_form.php' || $_REQUEST['page'] == 'contact_form_pro_extra.php' ) ) { if ( $wp_version < 3.5 ) { wp_enqueue_script( 'cntctfrmScript', plugins_url( 'js/script_wp_before_3.5.js', __FILE__ ) ); } else { wp_enqueue_script( 'cntctfrmprScript', plugins_url( 'js/script.js', __FILE__ ) ); } echo '<script type="text/javascript">var confirm_text = "'.__('Are you sure that you want to delete this language data?', 'contact_form').'"</script>'; } if ( isset( $_GET['page'] ) && $_GET['page'] == "bws_plugins" ) wp_enqueue_script( 'bws_menu_script', plugins_url( 'js/bws_menu.js' , __FILE__ ) ); } } if ( ! function_exists ( 'cntctfrm_wp_head' ) ) { function cntctfrm_wp_head() { wp_enqueue_style( 'cntctfrmStylesheet', plugins_url( 'css/style.css', __FILE__ ) ); } } if ( ! function_exists ( 'cntctfrm_email_name_filter' ) ) { function cntctfrm_email_name_filter( $data ){ global $cntctfrm_options; if ( isset( $_POST['cntctfrm_contact_name'] ) && 'custom' != $cntctfrm_options['cntctfrm_select_from_field'] ) { $name = stripslashes( strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', trim( $_POST['cntctfrm_contact_name'] ) ) ) ) ); if ( $name != '' ) return $name; else return $data; } elseif ( isset( $cntctfrm_options['cntctfrm_from_field'] ) && trim( $cntctfrm_options['cntctfrm_from_field'] ) != "" ) return stripslashes( $cntctfrm_options['cntctfrm_from_field'] ); else return $data; } } if ( ! function_exists ( 'cntctfrm_add_language' ) ) { function cntctfrm_add_language(){ $lang = strip_tags( preg_replace ( '/<[^>]*>/', '', preg_replace ( '/<script.*<\/[^>]*>/', '', htmlspecialchars( $_REQUEST['lang'] ) ) ) ); $cntctfrm_options = get_option( 'cntctfrm_options' ); $cntctfrm_options['cntctfrm_language'][] = $lang; update_option( 'cntctfrm_options', $cntctfrm_options, '', 'yes' ); die(); } } if ( ! function_exists ( 'cntctfrm_remove_language' ) ) { function cntctfrm_remove_language(){ $cntctfrm_options = get_option( 'cntctfrm_options' ); if( $key = array_search( $_REQUEST['lang'], $cntctfrm_options['cntctfrm_language'] ) !== false ) $cntctfrm_options['cntctfrm_language'] = array_diff( $cntctfrm_options['cntctfrm_language'], array( $_REQUEST['lang'] ) ); if( isset( $cntctfrm_options['cntctfrm_name_label'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_name_label'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_address_label'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_address_label'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_email_label'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_email_label'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_phone_label'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_phone_label'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_subject_label'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_subject_label'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_message_label'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_message_label'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_attachment_label'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_attachment_label'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_send_copy_label'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_send_copy_label'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_thank_text'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_thank_text'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_submit_label'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_submit_label'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_name_error'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_name_error'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_address_error'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_address_error'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_email_error'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_email_error'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_phone_error'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_phone_error'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_subject_error'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_subject_error'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_message_error'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_message_error'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_attachment_error'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_attachment_error'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_attachment_upload_error'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_attachment_upload_error'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_attachment_move_error'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_attachment_move_error'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_attachment_size_error'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_attachment_size_error'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_captcha_error'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_captcha_error'][$_REQUEST['lang']]); if( isset( $cntctfrm_options['cntctfrm_form_error'][$_REQUEST['lang']] ) ) unset( $cntctfrm_options['cntctfrm_form_error'][$_REQUEST['lang']]); update_option( 'cntctfrm_options', $cntctfrm_options ); die(); } } // Function for delete options if ( ! function_exists ( 'cntctfrm_delete_options' ) ) { function cntctfrm_delete_options() { global $wpdb; delete_option( 'cntctfrm_options' ); } } if ( ! function_exists ( 'cntctfrm_plugin_banner' ) ) { function cntctfrm_plugin_banner() { global $hook_suffix; $plugin_info = get_plugin_data( __FILE__ ); if ( $hook_suffix == 'plugins.php' ) { echo '<div class="updated" style="padding: 0; margin: 0; border: none; background: none;"> <script type="text/javascript" src="'.plugins_url( 'js/c_o_o_k_i_e.js', __FILE__ ).'"></script> <script type="text/javascript"> (function($){ $(document).ready(function(){ var hide_message = $.cookie("cntctfrm_hide_banner_on_plugin_page"); if ( hide_message == "true") { $(".cntctfrm_message").css("display", "none"); }; $(".cntctfrm_close_icon").click(function() { $(".cntctfrm_message").css("display", "none"); $.cookie( "cntctfrm_hide_banner_on_plugin_page", "true", { expires: 32 } ); }); }); })(jQuery); </script> <div class="cntctfrm_message"> <img class="cntctfrm_close_icon" title="" src="' . plugins_url( 'images/close_banner.png', __FILE__ ) . '" alt=""/> <img class="cntctfrm_icon" title="" src="' . plugins_url( 'images/banner.png', __FILE__ ) . '" alt=""/> <div class="cntctfrm_text"> It’s time to upgrade your <strong>Contact Form plugin</strong> to <strong>PRO</strong> version!<br /> <span>Extend standard plugin functionality with new great options.</span> </div> <a class="button cntctfrm_button" target="_blank" href="http://bestwebsoft.com/plugin/contact-form-pro/?k=f575dc39cba54a9de88df346eed52101&pn=77&v=' . $plugin_info["Version"] . '">Learn More</a> </div> </div>'; } } } add_action( 'init', 'cntctfrm_plugin_init' ); add_action( 'init', 'cntctfrm_check_and_send' ); add_action( 'admin_enqueue_scripts', 'cntctfrm_admin_head' ); add_action( 'wp_enqueue_scripts', 'cntctfrm_wp_head' ); // adds "Settings" link to the plugin action page add_filter( 'plugin_action_links', 'cntctfrm_plugin_action_links',10,2); //Additional links on the plugin page add_filter( 'plugin_row_meta', 'cntctfrm_register_plugin_links',10,2); add_shortcode( 'contact_form', 'cntctfrm_display_form' ); add_shortcode( 'bws_contact_form', 'cntctfrm_display_form' ); add_shortcode( 'bestwebsoft_contact_form', 'cntctfrm_display_form' ); add_action( 'admin_menu', 'cntctfrm_admin_menu' ); add_filter( 'widget_text', 'do_shortcode' ); add_filter( 'wp_mail_from_name', 'cntctfrm_email_name_filter', 10, 1); add_action( 'wp_ajax_cntctfrm_add_language', 'cntctfrm_add_language' ); add_action( 'wp_ajax_cntctfrm_remove_language', 'cntctfrm_remove_language' ); register_uninstall_hook( __FILE__, 'cntctfrm_delete_options' ); add_action('admin_notices', 'cntctfrm_plugin_banner'); ?>
Andykmcc/amrci
wp-content/plugins/contact-form-plugin/contact_form.php
PHP
gpl-2.0
138,328
<?php // $Id: linker.cnr.php 14358 2013-01-24 12:35:36Z zefredz $ // vim: expandtab sw=4 ts=4 sts=4: /** * Resource Resolver for the Annoucements tool * * @version $Revision: 14358 $ * @copyright (c) 2001-2011, Universite catholique de Louvain (UCL) * @license http://www.gnu.org/copyleft/gpl.html (GPL) GENERAL PUBLIC LICENSE * @author Claroline Team <cvs@claroline.net> * @package CLANN */ FromKernel::uses('fileManage.lib', 'file.lib'); class CLANN_Resolver implements ModuleResourceResolver { public function resolve ( ResourceLocator $locator ) { if ( $locator->hasResourceId() ) { return get_module_entry_url('CLANN') . "#ann{$locator->getResourceId()}"; } else { return get_module_entry_url('CLANN'); } } public function getResourceName( ResourceLocator $locator) { if ( ! $locator->hasResourceId() ) { return false; } $tbl = get_module_course_tbl( array('announcement'), $locator->getCourseId() ); $sql = "SELECT `title`\n" . "FROM `{$tbl['announcement']}`\n" . "WHERE `id`=". Claroline::getDatabase()->escape( $locator->getResourceId() ) ; $res = Claroline::getDatabase()->query($sql); $res->setFetchMode(Database_ResultSet::FETCH_VALUE); $title = $res->fetch(); if ( $title ) { $title = trim ( $title ); if ( empty( $title ) ) { $title = get_lang('Untitled'); } return $title; } else { Console::debug ("Cannot load ressource " . var_export( $locator, true ) . " in " . __CLASS__ . " : query returned " . var_export( $title, true ) ); return null; } } } class CLANN_Navigator implements ModuleResourceNavigator { public function getResourceId( $params = array() ) { if ( isset( $params['id'] ) ) { return $params['id']; } else { return false; } } public function isNavigable( ResourceLocator $locator ) { if ( $locator->hasResourceId() ) { return false; } else { return $locator->inModule() && $locator->getModuleLabel() == 'CLANN'; } } public function getParentResourceId( ResourceLocator $locator ) { return false; } public function getResourceList( ResourceLocator $locator ) { $tbl = get_module_course_tbl( array('announcement'), $locator->getCourseId() ); $sql = "SELECT `id`, `title`, `visibility`\n" . "FROM `{$tbl['announcement']}`" ; $res = Claroline::getDatabase()->query($sql); $resourceList = new LinkerResourceIterator; foreach ( $res as $annoucement ) { $annoucementLoc = new ClarolineResourceLocator( $locator->getCourseId(), 'CLANN', (int) $annoucement['id'] ); $annoucementResource = new LinkerResource( ( empty( $annoucement['title'] ) ? get_lang('Untitled') : $annoucement['title'] ), $annoucementLoc, true, ( $annoucement['visibility'] == 'HIDE' ? false : true ), false ); $resourceList->addResource( $annoucementResource ); } return $resourceList; } }
HimNG/cooltutor
claroline/announcements/connector/linker.cnr.php
PHP
gpl-2.0
3,834
# -*- coding: utf-8 -*- """ *************************************************************************** r_colors_stddev.py ------------------ Date : February 2016 Copyright : (C) 2016 by Médéric Ribreux Email : medspx at medspx dot fr *************************************************************************** * * * 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. * * * *************************************************************************** """ __author__ = 'Médéric Ribreux' __date__ = 'February 2016' __copyright__ = '(C) 2016, Médéric Ribreux' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' def processInputs(alg): # We need to import all the bands and to preserve color table raster = alg.getParameterValue('map') if raster in alg.exportedLayers.keys(): return alg.setSessionProjectionFromLayer(raster, alg.commands) destFilename = alg.getTempFilename() alg.exportedLayers[raster] = destFilename command = 'r.in.gdal input={} output={} --overwrite -o'.format(raster, destFilename) alg.commands.append(command) alg.setSessionProjectionFromProject(alg.commands) region = unicode(alg.getParameterValue(alg.GRASS_REGION_EXTENT_PARAMETER)) regionCoords = region.split(',') command = 'g.region' command += ' -a' command += ' n=' + unicode(regionCoords[3]) command += ' s=' + unicode(regionCoords[2]) command += ' e=' + unicode(regionCoords[1]) command += ' w=' + unicode(regionCoords[0]) cellsize = alg.getParameterValue(alg.GRASS_REGION_CELLSIZE_PARAMETER) if cellsize: command += ' res=' + unicode(cellsize) else: command += ' res=' + unicode(alg.getDefaultCellsize()) alignToResolution = alg.getParameterValue(alg.GRASS_REGION_ALIGN_TO_RESOLUTION) if alignToResolution: command += ' -a' alg.commands.append(command) def processCommand(alg): # We need to remove output output = alg.getOutputFromName('output') alg.exportedLayers[output.value] = output.name + alg.uniqueSufix alg.removeOutputFromName('output') alg.processCommand() alg.addOutput(output) def processOutputs(alg): # We need to export the raster with all its bands and its color table output = alg.getOutputValue('output') raster = alg.getParameterFromName('map') # Get the list of rasters matching the basename command = "r.out.gdal -t input={} output=\"{}\" createopt=\"TFW=YES,COMPRESS=LZW\"".format( alg.exportedLayers[raster.value], output) alg.commands.append(command) alg.outputCommands.append(command)
alexbruy/QGIS
python/plugins/processing/algs/grass7/ext/r_colors_stddev.py
Python
gpl-2.0
3,090
/* smplayer, GUI front-end for mplayer. Copyright (C) 2006-2014 Ricardo Villalba <rvm@users.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 "translator.h" #include "paths.h" #include <QTranslator> #include <QLocale> #include <QApplication> Translator::Translator() { qApp->installTranslator( &app_trans ); qApp->installTranslator( &qt_trans ); } Translator::~Translator() { } bool Translator::loadCatalog(QTranslator & t, QString name, QString locale, QString dir) { QString s = name + "_" + locale; //.toLower(); bool r = t.load(s, dir); if (r) qDebug("Translator::loadCatalog: successfully loaded %s from %s", s.toUtf8().data(), dir.toUtf8().data()); else qDebug("Translator::loadCatalog: can't load %s from %s", s.toUtf8().data(), dir.toUtf8().data()); return r; } void Translator::load(QString locale) { if (locale.isEmpty()) { locale = QLocale::system().name(); } QString trans_path = Paths::translationPath(); QString qt_trans_path = Paths::qtTranslationPath(); #if defined(Q_OS_WIN) || defined(Q_OS_OS2) // In windows and OS2 try to load the qt translation from the app path, as // most users won't have Qt installed. loadCatalog(qt_trans, "qt", locale, trans_path ); #else // In linux try to load it first from app path (in case there's an updated // translation), if it fails it will try then from the Qt path. if (! loadCatalog(qt_trans, "qt", locale, trans_path ) ) { loadCatalog(qt_trans, "qt", locale, qt_trans_path); } #endif loadCatalog(app_trans, "smplayer", locale, trans_path); }
saga64/smplayer
src/translator.cpp
C++
gpl-2.0
2,258
// we create the global game object, an instance of Phaser.Game var game = new Phaser.Game(800, 500, Phaser.AUTO, 'world',null,true,true,null); // the first parameter is the key you use to jump between stated // the key must be unique within the state manager // the second parameter is the object that contains the state code // these come from the js files we included in the head tag in the html file game.state.add('State001', bonsanto.State001); game.state.add('State002', bonsanto.State002); game.state.add('State003', bonsanto.State003); game.state.start('State001');
Techbot/JiGS-PHP-RPG-engine
legacy/components/com_battle/views/plate/tmpl/026a_bonsanto/script.js
JavaScript
gpl-2.0
584
<?php global $theme_options; ?> <?php get_header(); ?> <div class="page-content padding-small" id="woocommerce-container"> <div class="container"> <?php if($theme_options['woocommerce-sidebar'] == "left"): echo '<div class="row">'; echo '<div class="md-column col-main col-md-9 col-md-right col-sm-left content-full"><section class="woocommerce-content columns-'.$theme_options['woocommerce-products-cols'].'">'; woocommerce_content(); echo '</section></div>'; echo '<div class="md-column col-side col-md-3 col-md-left col-sm-right">'; get_sidebar('shop'); echo '</div>'; echo '</div>'; elseif ($theme_options['woocommerce-sidebar'] == "right"): echo '<div class="row">'; echo '<div class="md-column col-main col-md-9 col-md-left col-sm-left content-full"><section class="woocommerce-content columns-'.$theme_options['woocommerce-products-cols'].'">'; woocommerce_content(); echo '</section></div>'; echo '<div class="md-column col-side col-md-3 col-md-right col-sm-right">'; get_sidebar('shop'); echo '</div>'; echo '</div>'; else: echo '<section class="woocommerce-content columns-'.$theme_options['woocommerce-products-cols'].'">'; woocommerce_content(); echo '</section>'; endif; ?> </div> </div> <?php get_footer(); ?>
areaw3/rv
wp-content/themes/rv/woocommerce/single-product.php
PHP
gpl-2.0
1,354
/*************************************************************************** qgslayoutitempicture.cpp ------------------------ begin : October 2017 copyright : (C) 2017 by Nyall Dawson email : nyall dot dawson at gmail dot 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. * * * ***************************************************************************/ #include "qgslayoutitempicture.h" #include "qgslayoutitemregistry.h" #include "qgslayout.h" #include "qgslayoutrendercontext.h" #include "qgslayoutreportcontext.h" #include "qgslayoutitemmap.h" #include "qgslayoututils.h" #include "qgsproject.h" #include "qgsexpression.h" #include "qgsvectorlayer.h" #include "qgsmessagelog.h" #include "qgspathresolver.h" #include "qgsproperty.h" #include "qgsnetworkcontentfetcher.h" #include "qgssymbollayerutils.h" #include "qgssvgcache.h" #include "qgslogger.h" #include "qgsbearingutils.h" #include "qgsmapsettings.h" #include "qgsreadwritecontext.h" #include <QDomDocument> #include <QDomElement> #include <QFileInfo> #include <QImageReader> #include <QPainter> #include <QSvgRenderer> #include <QNetworkRequest> #include <QNetworkReply> #include <QEventLoop> #include <QCoreApplication> QgsLayoutItemPicture::QgsLayoutItemPicture( QgsLayout *layout ) : QgsLayoutItem( layout ) { //default to no background setBackgroundEnabled( false ); //connect some signals //connect to atlas feature changing //to update the picture source expression connect( &layout->reportContext(), &QgsLayoutReportContext::changed, this, [ = ] { refreshPicture(); } ); //connect to layout print resolution changing connect( &layout->renderContext(), &QgsLayoutRenderContext::dpiChanged, this, &QgsLayoutItemPicture::recalculateSize ); connect( this, &QgsLayoutItem::sizePositionChanged, this, &QgsLayoutItemPicture::shapeChanged ); } int QgsLayoutItemPicture::type() const { return QgsLayoutItemRegistry::LayoutPicture; } QIcon QgsLayoutItemPicture::icon() const { return QgsApplication::getThemeIcon( QStringLiteral( "/mLayoutItemPicture.svg" ) ); } QgsLayoutItemPicture *QgsLayoutItemPicture::create( QgsLayout *layout ) { return new QgsLayoutItemPicture( layout ); } void QgsLayoutItemPicture::draw( QgsLayoutItemRenderContext &context ) { QPainter *painter = context.renderContext().painter(); painter->save(); // painter is scaled to dots, so scale back to layout units painter->scale( context.renderContext().scaleFactor(), context.renderContext().scaleFactor() ); //picture resizing if ( mMode != FormatUnknown ) { double boundRectWidthMM; double boundRectHeightMM; QRect imageRect; if ( mResizeMode == QgsLayoutItemPicture::Zoom || mResizeMode == QgsLayoutItemPicture::ZoomResizeFrame ) { boundRectWidthMM = mPictureWidth; boundRectHeightMM = mPictureHeight; imageRect = QRect( 0, 0, mImage.width(), mImage.height() ); } else if ( mResizeMode == QgsLayoutItemPicture::Stretch ) { boundRectWidthMM = rect().width(); boundRectHeightMM = rect().height(); imageRect = QRect( 0, 0, mImage.width(), mImage.height() ); } else if ( mResizeMode == QgsLayoutItemPicture::Clip ) { boundRectWidthMM = rect().width(); boundRectHeightMM = rect().height(); int imageRectWidthPixels = mImage.width(); int imageRectHeightPixels = mImage.height(); imageRect = clippedImageRect( boundRectWidthMM, boundRectHeightMM, QSize( imageRectWidthPixels, imageRectHeightPixels ) ); } else { boundRectWidthMM = rect().width(); boundRectHeightMM = rect().height(); imageRect = QRect( 0, 0, mLayout->convertFromLayoutUnits( rect().width(), QgsUnitTypes::LayoutMillimeters ).length() * mLayout->renderContext().dpi() / 25.4, mLayout->convertFromLayoutUnits( rect().height(), QgsUnitTypes::LayoutMillimeters ).length() * mLayout->renderContext().dpi() / 25.4 ); } //zoom mode - calculate anchor point and rotation if ( mResizeMode == Zoom ) { //TODO - allow placement modes with rotation set. for now, setting a rotation //always places picture in center of frame if ( !qgsDoubleNear( mPictureRotation, 0.0 ) ) { painter->translate( rect().width() / 2.0, rect().height() / 2.0 ); painter->rotate( mPictureRotation ); painter->translate( -boundRectWidthMM / 2.0, -boundRectHeightMM / 2.0 ); } else { //shift painter to edge/middle of frame depending on placement double diffX = rect().width() - boundRectWidthMM; double diffY = rect().height() - boundRectHeightMM; double dX = 0; double dY = 0; switch ( mPictureAnchor ) { case UpperLeft: case MiddleLeft: case LowerLeft: //nothing to do break; case UpperMiddle: case Middle: case LowerMiddle: dX = diffX / 2.0; break; case UpperRight: case MiddleRight: case LowerRight: dX = diffX; break; } switch ( mPictureAnchor ) { case UpperLeft: case UpperMiddle: case UpperRight: //nothing to do break; case MiddleLeft: case Middle: case MiddleRight: dY = diffY / 2.0; break; case LowerLeft: case LowerMiddle: case LowerRight: dY = diffY; break; } painter->translate( dX, dY ); } } else if ( mResizeMode == ZoomResizeFrame ) { if ( !qgsDoubleNear( mPictureRotation, 0.0 ) ) { painter->translate( rect().width() / 2.0, rect().height() / 2.0 ); painter->rotate( mPictureRotation ); painter->translate( -boundRectWidthMM / 2.0, -boundRectHeightMM / 2.0 ); } } if ( mMode == FormatSVG ) { mSVG.render( painter, QRectF( 0, 0, boundRectWidthMM, boundRectHeightMM ) ); } else if ( mMode == FormatRaster ) { painter->drawImage( QRectF( 0, 0, boundRectWidthMM, boundRectHeightMM ), mImage, imageRect ); } } painter->restore(); } QSizeF QgsLayoutItemPicture::applyItemSizeConstraint( const QSizeF targetSize ) { QSizeF currentPictureSize = pictureSize(); QSizeF newSize = targetSize; if ( mResizeMode == QgsLayoutItemPicture::Clip ) { mPictureWidth = targetSize.width(); mPictureHeight = targetSize.height(); } else { if ( mResizeMode == ZoomResizeFrame && !rect().isEmpty() && !( currentPictureSize.isEmpty() ) ) { QSizeF targetImageSize; if ( qgsDoubleNear( mPictureRotation, 0.0 ) ) { targetImageSize = currentPictureSize; } else { //calculate aspect ratio of bounds of rotated image QTransform tr; tr.rotate( mPictureRotation ); QRectF rotatedBounds = tr.mapRect( QRectF( 0, 0, currentPictureSize.width(), currentPictureSize.height() ) ); targetImageSize = QSizeF( rotatedBounds.width(), rotatedBounds.height() ); } //if height has changed more than width, then fix width and set height correspondingly //else, do the opposite if ( std::fabs( rect().width() - targetSize.width() ) < std::fabs( rect().height() - targetSize.height() ) ) { newSize.setHeight( targetImageSize.height() * newSize.width() / targetImageSize.width() ); } else { newSize.setWidth( targetImageSize.width() * newSize.height() / targetImageSize.height() ); } } else if ( mResizeMode == FrameToImageSize ) { if ( !( currentPictureSize.isEmpty() ) ) { QgsLayoutSize sizeMM = mLayout->convertFromLayoutUnits( currentPictureSize, QgsUnitTypes::LayoutMillimeters ); newSize.setWidth( sizeMM.width() * 25.4 / mLayout->renderContext().dpi() ); newSize.setHeight( sizeMM.height() * 25.4 / mLayout->renderContext().dpi() ); } } //find largest scaling of picture with this rotation which fits in item if ( mResizeMode == Zoom || mResizeMode == ZoomResizeFrame ) { QRectF rotatedImageRect = QgsLayoutUtils::largestRotatedRectWithinBounds( QRectF( 0, 0, currentPictureSize.width(), currentPictureSize.height() ), QRectF( 0, 0, newSize.width(), newSize.height() ), mPictureRotation ); mPictureWidth = rotatedImageRect.width(); mPictureHeight = rotatedImageRect.height(); } else { mPictureWidth = newSize.width(); mPictureHeight = newSize.height(); } if ( newSize != targetSize ) { emit changed(); } } return newSize; } QRect QgsLayoutItemPicture::clippedImageRect( double &boundRectWidthMM, double &boundRectHeightMM, QSize imageRectPixels ) { int boundRectWidthPixels = boundRectWidthMM * mLayout->renderContext().dpi() / 25.4; int boundRectHeightPixels = boundRectHeightMM * mLayout->renderContext().dpi() / 25.4; //update boundRectWidth/Height so that they exactly match pixel bounds boundRectWidthMM = boundRectWidthPixels * 25.4 / mLayout->renderContext().dpi(); boundRectHeightMM = boundRectHeightPixels * 25.4 / mLayout->renderContext().dpi(); //calculate part of image which fits in bounds int leftClip = 0; int topClip = 0; //calculate left crop switch ( mPictureAnchor ) { case UpperLeft: case MiddleLeft: case LowerLeft: leftClip = 0; break; case UpperMiddle: case Middle: case LowerMiddle: leftClip = ( imageRectPixels.width() - boundRectWidthPixels ) / 2; break; case UpperRight: case MiddleRight: case LowerRight: leftClip = imageRectPixels.width() - boundRectWidthPixels; break; } //calculate top crop switch ( mPictureAnchor ) { case UpperLeft: case UpperMiddle: case UpperRight: topClip = 0; break; case MiddleLeft: case Middle: case MiddleRight: topClip = ( imageRectPixels.height() - boundRectHeightPixels ) / 2; break; case LowerLeft: case LowerMiddle: case LowerRight: topClip = imageRectPixels.height() - boundRectHeightPixels; break; } return QRect( leftClip, topClip, boundRectWidthPixels, boundRectHeightPixels ); } void QgsLayoutItemPicture::refreshPicture( const QgsExpressionContext *context ) { QgsExpressionContext scopedContext = createExpressionContext(); const QgsExpressionContext *evalContext = context ? context : &scopedContext; QString source = mSourcePath; //data defined source set? mHasExpressionError = false; if ( mDataDefinedProperties.isActive( QgsLayoutObject::PictureSource ) ) { bool ok = false; source = mDataDefinedProperties.valueAsString( QgsLayoutObject::PictureSource, *evalContext, source, &ok ); if ( ok ) { source = source.trimmed(); QgsDebugMsg( QStringLiteral( "exprVal PictureSource:%1" ).arg( source ) ); } else { mHasExpressionError = true; source = QString(); QgsMessageLog::logMessage( tr( "Picture expression eval error" ) ); } } loadPicture( source ); } void QgsLayoutItemPicture::loadRemotePicture( const QString &url ) { //remote location QgsNetworkContentFetcher fetcher; QEventLoop loop; connect( &fetcher, &QgsNetworkContentFetcher::finished, &loop, &QEventLoop::quit ); fetcher.fetchContent( QUrl( url ) ); //wait until picture fetched loop.exec( QEventLoop::ExcludeUserInputEvents ); QNetworkReply *reply = fetcher.reply(); if ( reply ) { QImageReader imageReader( reply ); mImage = imageReader.read(); mMode = FormatRaster; } else { mMode = FormatUnknown; } } void QgsLayoutItemPicture::loadLocalPicture( const QString &path ) { QFile pic; pic.setFileName( path ); if ( !pic.exists() ) { mMode = FormatUnknown; } else { QFileInfo sourceFileInfo( pic ); QString sourceFileSuffix = sourceFileInfo.suffix(); if ( sourceFileSuffix.compare( QLatin1String( "svg" ), Qt::CaseInsensitive ) == 0 ) { //try to open svg QgsExpressionContext context = createExpressionContext(); QColor fillColor = mDataDefinedProperties.valueAsColor( QgsLayoutObject::PictureSvgBackgroundColor, context, mSvgFillColor ); QColor strokeColor = mDataDefinedProperties.valueAsColor( QgsLayoutObject::PictureSvgStrokeColor, context, mSvgStrokeColor ); double strokeWidth = mDataDefinedProperties.valueAsDouble( QgsLayoutObject::PictureSvgStrokeWidth, context, mSvgStrokeWidth ); const QByteArray &svgContent = QgsApplication::svgCache()->svgContent( path, rect().width(), fillColor, strokeColor, strokeWidth, 1.0 ); mSVG.load( svgContent ); if ( mSVG.isValid() ) { mMode = FormatSVG; QRect viewBox = mSVG.viewBox(); //take width/height ratio from view box instead of default size mDefaultSvgSize.setWidth( viewBox.width() ); mDefaultSvgSize.setHeight( viewBox.height() ); } else { mMode = FormatUnknown; } } else { //try to open raster with QImageReader QImageReader imageReader( pic.fileName() ); if ( imageReader.read( &mImage ) ) { mMode = FormatRaster; } else { mMode = FormatUnknown; } } } } void QgsLayoutItemPicture::disconnectMap( QgsLayoutItemMap *map ) { if ( map ) { disconnect( map, &QgsLayoutItemMap::mapRotationChanged, this, &QgsLayoutItemPicture::updateMapRotation ); disconnect( map, &QgsLayoutItemMap::extentChanged, this, &QgsLayoutItemPicture::updateMapRotation ); } } void QgsLayoutItemPicture::updateMapRotation() { if ( !mRotationMap ) return; // take map rotation double rotation = mRotationMap->mapRotation(); // handle true north switch ( mNorthMode ) { case GridNorth: break; // nothing to do case TrueNorth: { QgsPointXY center = mRotationMap->extent().center(); QgsCoordinateReferenceSystem crs = mRotationMap->crs(); QgsCoordinateTransformContext transformContext = mLayout->project()->transformContext(); try { double bearing = QgsBearingUtils::bearingTrueNorth( crs, transformContext, center ); rotation += bearing; } catch ( QgsException &e ) { Q_UNUSED( e ) QgsDebugMsg( QStringLiteral( "Caught exception %1" ).arg( e.what() ) ); } break; } } rotation += mNorthOffset; setPictureRotation( rotation ); } void QgsLayoutItemPicture::loadPicture( const QString &path ) { mIsMissingImage = false; mEvaluatedPath = path; if ( path.startsWith( QLatin1String( "http" ) ) ) { //remote location loadRemotePicture( path ); } else { //local location loadLocalPicture( path ); } if ( mMode != FormatUnknown ) //make sure we start with a new QImage { recalculateSize(); } else if ( mHasExpressionError || !( path.isEmpty() ) ) { //trying to load an invalid file or bad expression, show cross picture mMode = FormatSVG; mIsMissingImage = true; QString badFile( QStringLiteral( ":/images/composer/missing_image.svg" ) ); mSVG.load( badFile ); if ( mSVG.isValid() ) { mMode = FormatSVG; QRect viewBox = mSVG.viewBox(); //take width/height ratio from view box instead of default size mDefaultSvgSize.setWidth( viewBox.width() ); mDefaultSvgSize.setHeight( viewBox.height() ); recalculateSize(); } } update(); emit changed(); } QRectF QgsLayoutItemPicture::boundedImageRect( double deviceWidth, double deviceHeight ) { double imageToDeviceRatio; if ( mImage.width() / deviceWidth > mImage.height() / deviceHeight ) { imageToDeviceRatio = deviceWidth / mImage.width(); double height = imageToDeviceRatio * mImage.height(); return QRectF( 0, 0, deviceWidth, height ); } else { imageToDeviceRatio = deviceHeight / mImage.height(); double width = imageToDeviceRatio * mImage.width(); return QRectF( 0, 0, width, deviceHeight ); } } QRectF QgsLayoutItemPicture::boundedSVGRect( double deviceWidth, double deviceHeight ) { double imageToSvgRatio; if ( deviceWidth / mDefaultSvgSize.width() > deviceHeight / mDefaultSvgSize.height() ) { imageToSvgRatio = deviceHeight / mDefaultSvgSize.height(); double width = mDefaultSvgSize.width() * imageToSvgRatio; return QRectF( 0, 0, width, deviceHeight ); } else { imageToSvgRatio = deviceWidth / mDefaultSvgSize.width(); double height = mDefaultSvgSize.height() * imageToSvgRatio; return QRectF( 0, 0, deviceWidth, height ); } } QSizeF QgsLayoutItemPicture::pictureSize() { if ( mMode == FormatSVG ) { return mDefaultSvgSize; } else if ( mMode == FormatRaster ) { return QSizeF( mImage.width(), mImage.height() ); } else { return QSizeF( 0, 0 ); } } bool QgsLayoutItemPicture::isMissingImage() const { return mIsMissingImage; } QString QgsLayoutItemPicture::evaluatedPath() const { return mEvaluatedPath; } void QgsLayoutItemPicture::shapeChanged() { if ( mMode == FormatSVG && !mLoadingSvg ) { mLoadingSvg = true; refreshPicture(); mLoadingSvg = false; } } void QgsLayoutItemPicture::setPictureRotation( double rotation ) { double oldRotation = mPictureRotation; mPictureRotation = rotation; if ( mResizeMode == Zoom ) { //find largest scaling of picture with this rotation which fits in item QSizeF currentPictureSize = pictureSize(); QRectF rotatedImageRect = QgsLayoutUtils::largestRotatedRectWithinBounds( QRectF( 0, 0, currentPictureSize.width(), currentPictureSize.height() ), rect(), mPictureRotation ); mPictureWidth = rotatedImageRect.width(); mPictureHeight = rotatedImageRect.height(); update(); } else if ( mResizeMode == ZoomResizeFrame ) { QSizeF currentPictureSize = pictureSize(); QRectF oldRect = QRectF( pos().x(), pos().y(), rect().width(), rect().height() ); //calculate actual size of image inside frame QRectF rotatedImageRect = QgsLayoutUtils::largestRotatedRectWithinBounds( QRectF( 0, 0, currentPictureSize.width(), currentPictureSize.height() ), rect(), oldRotation ); //rotate image rect by new rotation and get bounding box QTransform tr; tr.rotate( mPictureRotation ); QRectF newRect = tr.mapRect( QRectF( 0, 0, rotatedImageRect.width(), rotatedImageRect.height() ) ); //keep the center in the same location newRect.moveCenter( oldRect.center() ); attemptSetSceneRect( newRect ); emit changed(); } emit pictureRotationChanged( mPictureRotation ); } void QgsLayoutItemPicture::setLinkedMap( QgsLayoutItemMap *map ) { if ( mRotationMap ) { disconnectMap( mRotationMap ); } if ( !map ) //disable rotation from map { mRotationMap = nullptr; } else { mPictureRotation = map->mapRotation(); connect( map, &QgsLayoutItemMap::mapRotationChanged, this, &QgsLayoutItemPicture::updateMapRotation ); connect( map, &QgsLayoutItemMap::extentChanged, this, &QgsLayoutItemPicture::updateMapRotation ); mRotationMap = map; updateMapRotation(); emit pictureRotationChanged( mPictureRotation ); } } void QgsLayoutItemPicture::setResizeMode( QgsLayoutItemPicture::ResizeMode mode ) { mResizeMode = mode; if ( mode == QgsLayoutItemPicture::ZoomResizeFrame || mode == QgsLayoutItemPicture::FrameToImageSize || ( mode == QgsLayoutItemPicture::Zoom && !qgsDoubleNear( mPictureRotation, 0.0 ) ) ) { //call set scene rect to force item to resize to fit picture recalculateSize(); } update(); } void QgsLayoutItemPicture::recalculateSize() { //call set scene rect with current position/size, as this will trigger the //picture item to recalculate its frame and image size attemptSetSceneRect( QRectF( pos().x(), pos().y(), rect().width(), rect().height() ) ); } void QgsLayoutItemPicture::refreshDataDefinedProperty( const QgsLayoutObject::DataDefinedProperty property ) { if ( property == QgsLayoutObject::PictureSource || property == QgsLayoutObject::PictureSvgBackgroundColor || property == QgsLayoutObject::PictureSvgStrokeColor || property == QgsLayoutObject::PictureSvgStrokeWidth || property == QgsLayoutObject::AllProperties ) { QgsExpressionContext context = createExpressionContext(); refreshPicture( &context ); } QgsLayoutItem::refreshDataDefinedProperty( property ); } void QgsLayoutItemPicture::setPicturePath( const QString &path ) { mSourcePath = path; refreshPicture(); } QString QgsLayoutItemPicture::picturePath() const { return mSourcePath; } bool QgsLayoutItemPicture::writePropertiesToElement( QDomElement &elem, QDomDocument &, const QgsReadWriteContext &context ) const { QString imagePath = mSourcePath; // convert from absolute path to relative. For SVG we also need to consider system SVG paths QgsPathResolver pathResolver = context.pathResolver(); if ( imagePath.endsWith( QLatin1String( ".svg" ), Qt::CaseInsensitive ) ) imagePath = QgsSymbolLayerUtils::svgSymbolPathToName( imagePath, pathResolver ); else imagePath = pathResolver.writePath( imagePath ); elem.setAttribute( QStringLiteral( "file" ), imagePath ); elem.setAttribute( QStringLiteral( "pictureWidth" ), QString::number( mPictureWidth ) ); elem.setAttribute( QStringLiteral( "pictureHeight" ), QString::number( mPictureHeight ) ); elem.setAttribute( QStringLiteral( "resizeMode" ), QString::number( static_cast< int >( mResizeMode ) ) ); elem.setAttribute( QStringLiteral( "anchorPoint" ), QString::number( static_cast< int >( mPictureAnchor ) ) ); elem.setAttribute( QStringLiteral( "svgFillColor" ), QgsSymbolLayerUtils::encodeColor( mSvgFillColor ) ); elem.setAttribute( QStringLiteral( "svgBorderColor" ), QgsSymbolLayerUtils::encodeColor( mSvgStrokeColor ) ); elem.setAttribute( QStringLiteral( "svgBorderWidth" ), QString::number( mSvgStrokeWidth ) ); //rotation elem.setAttribute( QStringLiteral( "pictureRotation" ), QString::number( mPictureRotation ) ); if ( !mRotationMap ) { elem.setAttribute( QStringLiteral( "mapUuid" ), QString() ); } else { elem.setAttribute( QStringLiteral( "mapUuid" ), mRotationMap->uuid() ); } elem.setAttribute( QStringLiteral( "northMode" ), mNorthMode ); elem.setAttribute( QStringLiteral( "northOffset" ), mNorthOffset ); return true; } bool QgsLayoutItemPicture::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &, const QgsReadWriteContext &context ) { mPictureWidth = itemElem.attribute( QStringLiteral( "pictureWidth" ), QStringLiteral( "10" ) ).toDouble(); mPictureHeight = itemElem.attribute( QStringLiteral( "pictureHeight" ), QStringLiteral( "10" ) ).toDouble(); mResizeMode = QgsLayoutItemPicture::ResizeMode( itemElem.attribute( QStringLiteral( "resizeMode" ), QStringLiteral( "0" ) ).toInt() ); //when loading from xml, default to anchor point of middle to match pre 2.4 behavior mPictureAnchor = static_cast< QgsLayoutItem::ReferencePoint >( itemElem.attribute( QStringLiteral( "anchorPoint" ), QString::number( QgsLayoutItem::Middle ) ).toInt() ); mSvgFillColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "svgFillColor" ), QgsSymbolLayerUtils::encodeColor( QColor( 255, 255, 255 ) ) ) ); mSvgStrokeColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "svgBorderColor" ), QgsSymbolLayerUtils::encodeColor( QColor( 0, 0, 0 ) ) ) ); mSvgStrokeWidth = itemElem.attribute( QStringLiteral( "svgBorderWidth" ), QStringLiteral( "0.2" ) ).toDouble(); QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) ); if ( !composerItemList.isEmpty() ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); if ( !qgsDoubleNear( composerItemElem.attribute( QStringLiteral( "rotation" ), QStringLiteral( "0" ) ).toDouble(), 0.0 ) ) { //in versions prior to 2.1 picture rotation was stored in the rotation attribute mPictureRotation = composerItemElem.attribute( QStringLiteral( "rotation" ), QStringLiteral( "0" ) ).toDouble(); } } mDefaultSvgSize = QSize( 0, 0 ); if ( itemElem.hasAttribute( QStringLiteral( "sourceExpression" ) ) ) { //update pre 2.5 picture expression to use data defined expression QString sourceExpression = itemElem.attribute( QStringLiteral( "sourceExpression" ), QString() ); QString useExpression = itemElem.attribute( QStringLiteral( "useExpression" ) ); bool expressionActive; expressionActive = ( useExpression.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ); mDataDefinedProperties.setProperty( QgsLayoutObject::PictureSource, QgsProperty::fromExpression( sourceExpression, expressionActive ) ); } QString imagePath = itemElem.attribute( QStringLiteral( "file" ) ); // convert from relative path to absolute. For SVG we also need to consider system SVG paths QgsPathResolver pathResolver = context.pathResolver(); if ( imagePath.endsWith( QLatin1String( ".svg" ), Qt::CaseInsensitive ) ) imagePath = QgsSymbolLayerUtils::svgSymbolNameToPath( imagePath, pathResolver ); else imagePath = pathResolver.readPath( imagePath ); mSourcePath = imagePath; //picture rotation if ( !qgsDoubleNear( itemElem.attribute( QStringLiteral( "pictureRotation" ), QStringLiteral( "0" ) ).toDouble(), 0.0 ) ) { mPictureRotation = itemElem.attribute( QStringLiteral( "pictureRotation" ), QStringLiteral( "0" ) ).toDouble(); } //rotation map mNorthMode = static_cast< NorthMode >( itemElem.attribute( QStringLiteral( "northMode" ), QStringLiteral( "0" ) ).toInt() ); mNorthOffset = itemElem.attribute( QStringLiteral( "northOffset" ), QStringLiteral( "0" ) ).toDouble(); disconnectMap( mRotationMap ); mRotationMap = nullptr; mRotationMapUuid = itemElem.attribute( QStringLiteral( "mapUuid" ) ); return true; } QgsLayoutItemMap *QgsLayoutItemPicture::linkedMap() const { return mRotationMap; } void QgsLayoutItemPicture::setNorthMode( QgsLayoutItemPicture::NorthMode mode ) { mNorthMode = mode; updateMapRotation(); } void QgsLayoutItemPicture::setNorthOffset( double offset ) { mNorthOffset = offset; updateMapRotation(); } void QgsLayoutItemPicture::setPictureAnchor( ReferencePoint anchor ) { mPictureAnchor = anchor; update(); } void QgsLayoutItemPicture::setSvgFillColor( const QColor &color ) { mSvgFillColor = color; refreshPicture(); } void QgsLayoutItemPicture::setSvgStrokeColor( const QColor &color ) { mSvgStrokeColor = color; refreshPicture(); } void QgsLayoutItemPicture::setSvgStrokeWidth( double width ) { mSvgStrokeWidth = width; refreshPicture(); } void QgsLayoutItemPicture::finalizeRestoreFromXml() { if ( !mLayout || mRotationMapUuid.isEmpty() ) { mRotationMap = nullptr; } else { if ( mRotationMap ) { disconnectMap( mRotationMap ); } if ( ( mRotationMap = qobject_cast< QgsLayoutItemMap * >( mLayout->itemByUuid( mRotationMapUuid, true ) ) ) ) { connect( mRotationMap, &QgsLayoutItemMap::mapRotationChanged, this, &QgsLayoutItemPicture::updateMapRotation ); connect( mRotationMap, &QgsLayoutItemMap::extentChanged, this, &QgsLayoutItemPicture::updateMapRotation ); } } refreshPicture(); }
mj10777/QGIS
src/core/layout/qgslayoutitempicture.cpp
C++
gpl-2.0
28,266
/* * This file is part of the libCEC(R) library. * * libCEC(R) is Copyright (C) 2011-2015 Pulse-Eight Limited. All rights reserved. * libCEC(R) is an original work, containing original code. * * libCEC(R) is a trademark of Pulse-Eight Limited. * * This program is dual-licensed; 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 * * * Alternatively, you can license this library under a commercial license, * please contact Pulse-Eight Licensing for more information. * * For more information contact: * Pulse-Eight Licensing <license@pulse-eight.com> * http://www.pulse-eight.com/ * http://www.pulse-eight.net/ */ #include "env.h" #include "adl-edid.h" // for dlsym and friends #if defined(__WINDOWS__) #include "platform/windows/dlfcn-win32.h" #endif using namespace PLATFORM; CADLEdidParser::CADLEdidParser(void) : m_bOpen(false), m_handle(NULL) { Initialise(); } CADLEdidParser::~CADLEdidParser(void) { CloseLibrary(); } bool CADLEdidParser::OpenLibrary(void) { CloseLibrary(); #if !defined(__WINDOWS__) m_handle = dlopen("libatiadlxx.so", RTLD_LAZY|RTLD_GLOBAL); #else m_handle = LoadLibrary("atiadlxx.dll"); // try 32 bit if (!m_handle) m_handle = LoadLibrary("atiadlxy.dll"); #endif return m_handle != NULL; } void CADLEdidParser::CloseLibrary(void) { if (LibOpen()) ADL_Main_Control_Destroy(); if (m_handle) dlclose(m_handle); m_handle = NULL; } void *__stdcall ADL_AllocMemory(int iSize) { void* lpBuffer = malloc(iSize); return lpBuffer; } void CADLEdidParser::Initialise(void) { if (OpenLibrary()) { // dlsym the methods we need ADL_Main_Control_Create = (ADL_MAIN_CONTROL_CREATE) dlsym(m_handle, "ADL_Main_Control_Create"); ADL_Main_Control_Destroy = (ADL_MAIN_CONTROL_DESTROY) dlsym(m_handle, "ADL_Main_Control_Destroy"); ADL_Adapter_NumberOfAdapters_Get = (ADL_ADAPTER_NUMBEROFADAPTERS_GET) dlsym(m_handle, "ADL_Adapter_NumberOfAdapters_Get"); ADL_Adapter_AdapterInfo_Get = (ADL_ADAPTER_ADAPTERINFO_GET) dlsym(m_handle, "ADL_Adapter_AdapterInfo_Get"); ADL_Display_DisplayInfo_Get = (ADL_DISPLAY_DISPLAYINFO_GET) dlsym(m_handle, "ADL_Display_DisplayInfo_Get"); ADL_Display_EdidData_Get = (ADL_DISPLAY_EDIDDATA_GET) dlsym(m_handle, "ADL_Display_EdidData_Get"); // check whether they could all be resolved if (ADL_Main_Control_Create && ADL_Main_Control_Destroy && ADL_Adapter_NumberOfAdapters_Get && ADL_Adapter_AdapterInfo_Get && ADL_Display_DisplayInfo_Get && ADL_Display_EdidData_Get) { // and try to initialise it m_bOpen = (ADL_OK == ADL_Main_Control_Create(ADL_AllocMemory, 1)); } } } int CADLEdidParser::GetNumAdapters(void) { int iNumAdapters(0); if (!LibOpen() || ADL_OK != ADL_Adapter_NumberOfAdapters_Get(&iNumAdapters)) iNumAdapters = 0; return iNumAdapters; } LPAdapterInfo CADLEdidParser::GetAdapterInfo(int iNumAdapters) { // validate input if (iNumAdapters <= 0) return NULL; LPAdapterInfo adapterInfo = (LPAdapterInfo)malloc(sizeof(AdapterInfo) * iNumAdapters); memset(adapterInfo, 0, sizeof(AdapterInfo) * iNumAdapters); // get the info ADL_Adapter_AdapterInfo_Get(adapterInfo, sizeof(AdapterInfo) * iNumAdapters); return adapterInfo; } bool CADLEdidParser::GetAdapterEDID(int iAdapterIndex, int iDisplayIndex, ADLDisplayEDIDData *data) { // validate input if (iAdapterIndex < 0 || iDisplayIndex < 0) return false; memset(data, 0, sizeof(ADLDisplayEDIDData)); data->iSize = sizeof(ADLDisplayEDIDData); data->iBlockIndex = 1; return (ADL_Display_EdidData_Get(iAdapterIndex, iDisplayIndex, data) == ADL_OK); } uint16_t CADLEdidParser::GetPhysicalAddress(void) { uint16_t iPA(0); // get the number of adapters int iNumAdapters = GetNumAdapters(); if (iNumAdapters <= 0) return 0; // get the adapter info LPAdapterInfo adapterInfo = GetAdapterInfo(iNumAdapters); if (!adapterInfo) return 0; // iterate over it for (int iAdapterPtr = 0; iAdapterPtr < iNumAdapters; iAdapterPtr++) { int iNumDisplays(-1); LPADLDisplayInfo displayInfo(NULL); int iAdapterIndex = adapterInfo[iAdapterPtr].iAdapterIndex; // get the display info if (ADL_OK != ADL_Display_DisplayInfo_Get(iAdapterIndex, &iNumDisplays, &displayInfo, 0)) continue; // iterate over it for (int iDisplayPtr = 0; iDisplayPtr < iNumDisplays; iDisplayPtr++) { // check whether the display is connected if ((displayInfo[iDisplayPtr].iDisplayInfoValue & ADL_DISPLAY_CONNECTED) != ADL_DISPLAY_CONNECTED) continue; int iDisplayIndex = displayInfo[iDisplayPtr].displayID.iDisplayLogicalIndex; // try to get the EDID ADLDisplayEDIDData edidData; if (GetAdapterEDID(iAdapterIndex, iDisplayIndex, &edidData)) { // try to get the PA from the EDID iPA = CEDIDParser::GetPhysicalAddressFromEDID(edidData.cEDIDData, edidData.iEDIDSize); // found it if (iPA != 0) break; } } free(displayInfo); } free(adapterInfo); return iPA; }
lornix/libcec
src/libcec/platform/adl/adl-edid.cpp
C++
gpl-2.0
5,819
<?php /** * Plugin Name: WooCommerce Dynamic Pricing & Discounts * Plugin URI: http://www.rightpress.net/woocommerce-dynamic-pricing-and-discounts * Description: Control your WooCommerce product pricing and cart discounts. * Version: 1.0.16 * Author: RightPress * Author URI: http://www.rightpress.net * Requires at least: 3.5 * Tested up to: 3.9 * * Text Domain: rp_wcdpd * Domain Path: /languages * * @package WooCommerce Dynamic Pricing And Discounts * @category Core * @author RightPress */ // Exit if accessed directly if (!defined('ABSPATH')) { exit; } // Define Constants define('RP_WCDPD_PLUGIN_PATH', plugin_dir_path(__FILE__)); define('RP_WCDPD_PLUGIN_URL', plugins_url(basename(plugin_dir_path(__FILE__)), basename(__FILE__))); define('RP_WCDPD_VERSION', '1.0.16'); define('RP_WCDPD_OPTIONS_VERSION', '1'); if (!class_exists('RP_WCDPD')) { /** * Main plugin class * * @package WooCommerce Dynamic Pricing Pro * @author RightPress */ class RP_WCDPD { private static $instance = false; public $discounts_applied = false; /** * Singleton control */ public static function get_instance() { if (!self::$instance) { self::$instance = new self(); } return self::$instance; } /** * Class constructor * * @access public * @return void */ public function __construct() { // Load translation load_plugin_textdomain('rp_wcdpd', false, dirname(plugin_basename(__FILE__)) . '/languages/'); // Activation hook register_activation_hook(__FILE__, array($this, 'activate')); // Initialize plugin configuration $this->plugin_config_init(); // Load plugin settings, pricing and discount setup $this->opt = $this->get_options(); // Set up settings page if (is_admin() && !defined('DOING_AJAX')) { // Additional Plugins page links add_filter('plugin_action_links_'.plugin_basename(__FILE__), array($this, 'plugins_page_links')); // Add settings page menu link add_action('admin_menu', array($this, 'add_admin_menu')); add_action('admin_init', array($this, 'plugin_options_setup')); // Load scripts/styles conditionally if (preg_match('/page=wc_pricing_and_discounts/i', $_SERVER['QUERY_STRING'])) { add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts_and_styles')); } } // Load frontend scripts/styles and hook into WooCommerce else { // Enqueue scripts and styles add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts_and_styles')); // Change prices and totals in cart (and mini cart) add_action('woocommerce_cart_loaded_from_session', array($this, 'apply_discounts'), 100); add_action('woocommerce_ajax_added_to_cart', array($this, 'apply_discounts'), 100); // Change prices on product pages (cosmetic change) add_filter('woocommerce_price_html', array($this, 'replace_visible_prices'), 10, 2); add_filter('woocommerce_variable_price_html', array($this, 'replace_visible_prices'), 10, 2); add_filter('woocommerce_grouped_price_html', array($this, 'replace_visible_prices'), 10, 2); add_filter('woocommerce_sale_price_html', array($this, 'replace_visible_prices'), 10, 2); add_filter('woocommerce_empty_price_html', array($this, 'replace_visible_prices'), 10, 2); add_filter('woocommerce_variation_price_html', array($this, 'replace_visible_prices'), 10, 2); add_filter('woocommerce_variation_sale_price_html', array($this, 'replace_visible_prices'), 10, 2); // Display pricing table or anchor to open pricing table as modal if (isset($this->opt['settings']['display_position']) && !empty($this->opt['settings']['display_position'])) { add_action($this->opt['settings']['display_position'], array($this, 'product_page_pricing_table')); } } // Some hooks need to be attached after init is triggered add_action('init', array($this, 'on_init')); } /** * Function hooked to init * * @access public * @return void */ public function on_init() { if (is_admin() && !defined('DOING_AJAX')) { } else { // Change prices in cart (cosmetic change) $cart_price_hook = $this->wc_version_gte('2.1') ? 'woocommerce_cart_item_price' : 'woocommerce_cart_item_price_html'; add_filter($cart_price_hook, array($this, 'replace_visible_prices_cart'), 100, 3); } } /** * Replace original prices with discounted product prices in output html * This only makes sense when a basic quantity pricing table is used (with no further conditions) * * @access public * @param string $product_price * @param object $product * @return string */ public function replace_visible_prices($product_price, $product) { return $product_price; } /** * Replace original prices with discounted item prices in cart html * * @access public * @param string $item_price * @param array $cart_item * @param string $cart_item_key * @return string */ public function replace_visible_prices_cart($item_price, $cart_item, $cart_item_key) { if (!isset($cart_item['rp_wcdpd'])) { return $item_price; } // Get price to display $price = get_option('woocommerce_tax_display_cart') == 'excl' ? $cart_item['data']->get_price_excluding_tax() : $cart_item['data']->get_price_including_tax(); // Format price to display $price_to_display = $this->wc_version_gte('2.1') ? wc_price($price) : woocommerce_price($price); $original_price_to_display = $this->wc_version_gte('2.1') ? wc_price($cart_item['rp_wcdpd']['original_price']) : woocommerce_price($cart_item['rp_wcdpd']['original_price']); $item_price = '<span class="rp_wcdpd_cart_price"><del>' . $original_price_to_display . '</del> <ins>' . $price_to_display . '</ins></span>'; return $item_price; } /** * Apply discounts to cart * * @access public * @return void */ public function apply_discounts() { global $woocommerce; // Already applied and not Ajax request? if (($this->discounts_applied && current_filter() != 'woocommerce_ajax_added_to_cart') || empty($woocommerce->cart->cart_contents)) { return; } // Load required classes require_once RP_WCDPD_PLUGIN_PATH . 'includes/classes/Pricing.php'; require_once RP_WCDPD_PLUGIN_PATH . 'includes/classes/Discounts.php'; // Sort cart by price ascending $cart_contents = $this->sort_cart_by_price($woocommerce->cart->cart_contents, 'asc'); // Process item pricing rules $this->pricing = new RP_WCDPD_Pricing($cart_contents, $this->opt); foreach ($cart_contents as $cart_item_key => $cart_item) { if ($adjustment = $this->pricing->get($cart_item_key)) { $this->apply_pricing_adjustment($cart_item_key, $adjustment); } else if (isset($woocommerce->cart->cart_contents[$cart_item_key]['rp_wcdpd'])) { unset($woocommerce->cart->cart_contents[$cart_item_key]['rp_wcdpd']); } } // Process cart discount rules $this->discounts = new RP_WCDPD_Discounts($this->opt, $this->pricing); // Apply cart discounts (if any) if ($this->cart_discount_to_apply = $this->discounts->get()) { add_filter('woocommerce_get_shop_coupon_data', array($this, 'maybe_add_virtual_coupon'), 10, 2); add_action('woocommerce_before_calculate_totals', array($this, 'apply_fake_coupon')); } // Remove cart discounts (if previously applied but no longer valid) else { // Check if we don't have real coupon by the same name $coupon = new WC_Coupon($this->opt['settings']['cart_discount_title']); // Remove coupon if it does not exist but is applied to cart if (!$coupon->id && $woocommerce->cart->has_discount($this->opt['settings']['cart_discount_title'])) { add_filter('woocommerce_coupons_enabled', array($this, 'woocommerce_enable_coupons')); $this->remove_woocommerce_coupon($this->opt['settings']['cart_discount_title']); remove_filter('woocommerce_coupons_enabled', array($this, 'woocommerce_enable_coupons')); } } // Recalculate totals for mini cart (since totals are only updated when loading cart from session which runs before adding a new product to cart) if (current_filter() == 'woocommerce_ajax_added_to_cart' || defined('DOING_AJAX')) { $woocommerce->cart->calculate_totals(); } $this->discounts_applied = true; } /** * Temporary enable coupons to remove any when needed * * @access public * @return string */ public function woocommerce_enable_coupons() { return 'yes'; } /** * Remove single coupon by name * Support for pre-2.1 WooCommerce * * @access public * @param string $coupon * @return void */ public function remove_woocommerce_coupon($coupon) { global $woocommerce; if (self::wc_version_gte('2.1')) { $woocommerce->cart->remove_coupon($coupon); } else { $coupon = apply_filters('woocommerce_coupon_code', $coupon); $position = array_search($coupon, $woocommerce->cart->applied_coupons); if ($position !== false) { unset($woocommerce->cart->applied_coupons[$position]); } WC()->session->set('applied_coupons', $woocommerce->cart->applied_coupons); } } /** * Apply fake coupon to cart * * @access public * @return void */ public function apply_fake_coupon() { global $woocommerce; $the_coupon = new WC_Coupon(apply_filters('woocommerce_coupon_code', $this->opt['settings']['cart_discount_title'])); if ($the_coupon->is_valid() && !$woocommerce->cart->has_discount($this->opt['settings']['cart_discount_title'])) { // Do not apply coupon with individual use coupon already applied if ($woocommerce->cart->applied_coupons) { foreach ($woocommerce->cart->applied_coupons as $code) { $coupon = new WC_Coupon($code); if ($coupon->individual_use == 'yes') { return false; } } } $woocommerce->cart->applied_coupons[] = apply_filters('woocommerce_coupon_code', $this->opt['settings']['cart_discount_title']); return true; } } /** * Maybe add virtual coupon for cart discounts * * @access public * @param bool $unknown_param * @param string $coupon_code * @return mixed */ public function maybe_add_virtual_coupon($unknown_param, $coupon_code) { if ($coupon_code == apply_filters('woocommerce_coupon_code', $this->opt['settings']['cart_discount_title'])) { $coupon = array( 'id' => 2147483647, 'type' => 'fixed_cart', 'amount' => $this->cart_discount_to_apply['discount'], 'individual_use' => 'no', 'product_ids' => array(), 'exclude_product_ids' => array(), 'usage_limit' => '', 'usage_limit_per_user' => '', 'limit_usage_to_x_items' => '', 'usage_count' => '', 'expiry_date' => '', 'apply_before_tax' => ((isset($this->opt['settings']['apply_cart_discounts']) && $this->opt['settings']['apply_cart_discounts'] == 'incl_tax') ? 'no' : 'yes'), 'free_shipping' => 'no', 'product_categories' => array(), 'exclude_product_categories' => array(), 'exclude_sale_items' => 'no', 'minimum_amount' => '', 'maximum_amount' => '', 'customer_email' => '', ); return $coupon; } } /** * Actually apply calculated pricing adjustment * * @access public * @param string $cart_item_key * @param array $adjustment * @return void */ public function apply_pricing_adjustment($cart_item_key, $adjustment) { global $woocommerce; // Make sure item exists in cart if (!isset($woocommerce->cart->cart_contents[$cart_item_key])) { return; } // Log changes $woocommerce->cart->cart_contents[$cart_item_key]['rp_wcdpd'] = array( 'original_price' => get_option('woocommerce_tax_display_cart') == 'excl' ? $woocommerce->cart->cart_contents[$cart_item_key]['data']->get_price_excluding_tax() : $woocommerce->cart->cart_contents[$cart_item_key]['data']->get_price_including_tax(), 'log' => $adjustment['log'], ); // Actually adjust price in cart $woocommerce->cart->cart_contents[$cart_item_key]['data']->price = $adjustment['price']; } /** * Sort cart by price * * @access public * @param array $cart * @param string $order * @return array */ public function sort_cart_by_price($cart, $order) { $cart_sorted = array(); foreach ($cart as $cart_item_key => $cart_item) { $cart_sorted[$cart_item_key] = $cart_item; } uasort($cart_sorted, array($this, 'sort_cart_by_price_method_' . $order)); return $cart_sorted; } /** * Sort cart by price uasort collable - ascending * * @access public * @param mixed $first * @param mixed $second * @return bool */ public function sort_cart_by_price_method_asc($first, $second) { if ($first['data']->get_price() == $second['data']->get_price()) { return 0; } return ($first['data']->get_price() < $second['data']->get_price()) ? -1 : 1; } /** * Sort cart by price uasort collable - descending * * @access public * @param mixed $first * @param mixed $second * @return bool */ public function sort_cart_by_price_method_desc($first, $second) { if ($first['data']->get_price() == $second['data']->get_price()) { return 0; } return ($first['data']->get_price() > $second['data']->get_price()) ? -1 : 1; } /** * Sort pricing table - ascending * * @access public * @param mixed $first * @param mixed $second * @return bool */ public static function sort_pricing_table_method_asc($first, $second) { return ($first['min'] < $second['min']) ? -1 : 1; } /** * Normalize quantity pricing table (add 1-X row etc) * * @access public * @param array $original_table * @return bool */ public static function normalize_quantity_pricing_table($original_table) { if (empty($original_table) || !is_array($original_table)) { return false; } $table = array(); // Track ranges to make sure we don't have overlaps $used_ranges = array(); // Iterate over original elements foreach ($original_table as $current_row) { $row = $current_row; // Min quantity if (!is_numeric($row['min']) || ($row['min'] < 0)) { if ($row['min'] == '*') { $row['min'] = 1; } else { return false; } } // Max quantity if (!is_numeric($row['max']) || ($row['max'] < 0)) { if ($row['max'] == '*') { $row['max'] = defined(PHP_INT_MAX) ? PHP_INT_MAX : 2147483647; } else { return false; } } // Min must be smaller than max if ($row['min'] > $row['max']) { return false; } // Range must not overlap with existing ranges foreach ($used_ranges as $range) { if ($row['min'] == $range['min']) { return false; } else if ($row['min'] < $range['min']) { if ($row['max'] >= $range['min']) { return false; } } else if ($row['min'] > $range['min']) { if ($row['min'] <= $range['max'] || $row['max'] <= $range['max']) { return false; } } } $used_ranges[] = array('min' => $row['min'], 'max' => $row['max']); // Adjustment type if (!isset($row['type']) || !in_array($row['type'], array('percentage', 'price', 'fixed'))) { return false; } // Value if (!is_numeric($row['value'])) { return false; } else if ($row['type'] == 'percentage' && ($row['value'] < 0 || $row['value'] > 100)) { return false; } else if (in_array($row['type'], array('price', 'fixed')) && $row['value'] < 0) { return false; } $table[] = $row; } if (empty($table)) { return false; } // Sort table ascending uasort($table, array('self', 'sort_pricing_table_method_asc')); // Check/fix min $first_row_values = array_values($table); $first_row = array_shift($first_row_values); if ($first_row['min'] > 1) { array_unshift($table, array( 'min' => 1, 'max' => ($first_row['min'] - 1), 'type' => 'percentage', 'value' => 0, 'added' => true )); } // Check/fix max $last_row_values = array_values($table); $last_row = array_pop($last_row_values); if ($last_row['max'] < (defined(PHP_INT_MAX) ? PHP_INT_MAX : 2147483647)) { array_push($table, array( 'min' => ($last_row['max'] + 1), 'max' => (defined(PHP_INT_MAX) ? PHP_INT_MAX : 2147483647), 'type' => 'percentage', 'value' => 0, 'added' => true )); } return $table; } /** * Maybe display pricing table or anchor to display pricing table in modal * * @access public * @return void */ public function product_page_pricing_table() { if ($this->opt['settings']['display_table'] == 'hide' && (!isset($this->opt['settings']['display_offers']) || $this->opt['settings']['display_offers'] == 'hide')) { return; } global $product; if (!$product) { return; } // Load required classes require_once RP_WCDPD_PLUGIN_PATH . 'includes/classes/Pricing.php'; $selected_rule = null; // Iterate over pricing rules and use the first one that has this product in conditions (or does not have if condition "not in list") if (isset($this->opt['pricing']['sets']) && count($this->opt['pricing']['sets'])) { foreach ($this->opt['pricing']['sets'] as $rule_key => $rule) { if ($rule['method'] == 'quantity' && $validated_rule = RP_WCDPD_Pricing::validate_rule($rule)) { if ($validated_rule['selection_method'] == 'all' && $this->user_matches_rule($validated_rule)) { $selected_rule = $validated_rule; break; } if ($validated_rule['selection_method'] == 'categories_include' && count(array_intersect($this->get_product_categories($product->id), $validated_rule['categories'])) > 0 && $this->user_matches_rule($validated_rule)) { $selected_rule = $validated_rule; break; } if ($validated_rule['selection_method'] == 'categories_exclude' && count(array_intersect($this->get_product_categories($product->id), $validated_rule['categories'])) == 0 && $this->user_matches_rule($validated_rule)) { $selected_rule = $validated_rule; break; } if ($validated_rule['selection_method'] == 'products_include' && in_array($product->id, $validated_rule['products']) && $this->user_matches_rule($validated_rule)) { $selected_rule = $validated_rule; break; } if ($validated_rule['selection_method'] == 'products_exclude' && !in_array($product->id, $validated_rule['products']) && $this->user_matches_rule($validated_rule)) { $selected_rule = $validated_rule; break; } } } } if (is_array($selected_rule)) { // Quantity if ($selected_rule['method'] == 'quantity' && in_array($this->opt['settings']['display_table'], array('modal', 'inline')) && isset($selected_rule['pricing'])) { if ($product->product_type == 'variable') { $product_variations = $product->get_available_variations(); } // For variable products only - check if prices differ for different variations $multiprice_variable_product = false; if ($product->product_type == 'variable' && !empty($product_variations)) { $last_product_variation = array_slice($product_variations, -1); $last_product_variation_object = new WC_Product_Variable($last_product_variation[0]['variation_id']); $last_product_variation_price = $last_product_variation_object->get_price(); foreach ($product_variations as $variation) { $variation_object = new WC_Product_Variable($variation['variation_id']); if ($variation_object->get_price() != $last_product_variation_price) { $multiprice_variable_product = true; } } } if ($multiprice_variable_product) { $variation_table_data = array(); foreach ($product_variations as $variation) { $variation_product = new WC_Product_Variation($variation['variation_id']); $variation_table_data[$variation['variation_id']] = $this->pricing_table_calculate_adjusted_prices($selected_rule['pricing'], $variation_product->get_price()); } require_once RP_WCDPD_PLUGIN_PATH . 'includes/views/frontend/table-variable.php'; } else { if ($product->product_type == 'variable' && !empty($product_variations)) { $variation_product = new WC_Product_Variation($last_product_variation[0]['variation_id']); $table_data = $this->pricing_table_calculate_adjusted_prices($selected_rule['pricing'], $variation_product->get_price()); } else { $table_data = $this->pricing_table_calculate_adjusted_prices($selected_rule['pricing'], $product->get_price()); } require_once RP_WCDPD_PLUGIN_PATH . 'includes/views/frontend/table-' . $this->opt['settings']['display_table'] . '-' . $this->opt['settings']['pricing_table_style'] . '.php'; } } } } /** * Check if user matches rule requirements * * @access public * @param array $rule * @return bool */ public function user_matches_rule($rule) { if ($rule['user_method'] == 'roles_include') { if (count(array_intersect(self::current_user_roles(), $rule['roles'])) < 1) { return false; } } if ($rule['user_method'] == 'roles_exclude') { if (count(array_intersect(self::current_user_roles(), $rule['roles'])) > 0) { return false; } } if ($rule['user_method'] == 'capabilities_include') { if (count(array_intersect(self::current_user_capabilities(), $rule['capabilities'])) < 1) { return false; } } if ($rule['user_method'] == 'capabilities_exclude') { if (count(array_intersect(self::current_user_capabilities(), $rule['capabilities'])) > 0) { return false; } } if ($rule['user_method'] == 'users_include') { if (!in_array(get_current_user_id(), $rule['users'])) { return false; } } if ($rule['user_method'] == 'users_exclude') { if (in_array(get_current_user_id(), $rule['users'])) { return false; } } return true; } /** * Calculate prices to display for pricing tables * * @access public * @param array $table_data * @param float $original_price * @return void */ public function pricing_table_calculate_adjusted_prices($table_data, $original_price) { foreach ($table_data as $row_key => $row) { $current_adjusted_price = $original_price - RP_WCDPD_Pricing::apply_adjustment($original_price, array('type' => $row['type'], 'value' => $row['value'])); $current_adjusted_price = ($current_adjusted_price < 0) ? 0 : $current_adjusted_price; $table_data[$row_key]['display_price'] = $this->format_price($current_adjusted_price); } return $table_data; } /** * Format price to WooCommerce standards * * @access public * @param float $price * @return string */ public function format_price($price) { $num_decimals = absint(get_option('woocommerce_price_num_decimals')); $currency_symbol = get_woocommerce_currency_symbol(); $decimal_sep = wp_specialchars_decode(stripslashes(get_option('woocommerce_price_decimal_sep')), ENT_QUOTES); $thousands_sep = wp_specialchars_decode(stripslashes(get_option('woocommerce_price_thousand_sep')), ENT_QUOTES); $price = number_format($price, $num_decimals, $decimal_sep, $thousands_sep); if (apply_filters('woocommerce_price_trim_zeros', false) && $num_decimals > 0) { $price = preg_replace('/' . preg_quote(get_option('woocommerce_price_decimal_sep' ), '/') . '0++$/', '', $price); } return sprintf(get_woocommerce_price_format(), $currency_symbol, $price); } /** * WordPress activation hook * * @access public * @return void */ public function activate() { if (!get_option('rp_wcdpd_options')) { add_option('rp_wcdpd_options', array(RP_WCDPD_OPTIONS_VERSION => $this->default_options)); } } /** * Get some preconfigured values (usually constants that do not change) * * @access public * @return void */ public function plugin_config_init() { // Define settings page structure $this->settings_page_tabs = array( 'pricing' => array( 'title' => __('Pricing Rules', 'rp_wcdpd'), 'icon' => 'tags' ), 'discounts' => array( 'title' => __('Cart Discounts', 'rp_wcdpd'), 'icon' => 'shopping-cart' ), 'settings' => array( 'title' => __('Settings', 'rp_wcdpd'), 'icon' => 'cogs' ), 'localization' => array( 'title' => __('Localization', 'rp_wcdpd'), 'icon' => 'font' ) ); // Define default options (until real options are saved) $this->default_options = array( 'pricing' => array( 'apply_multiple' => 'first', 'sets' => array( 1 => array( 'description' => '', 'method' => 'quantity', 'quantities_based_on' => 'exclusive_product', 'if_matched' => 'all', 'valid_from' => '', 'valid_until' => '', 'selection_method' => 'all', 'categories' => array(), 'products' => array(), 'user_method' => 'all', 'roles' => array(), 'capabilities' => array(), 'users' => array(), 'pricing' => array( 1 => array( 'min' => '', 'max' => '', 'type' => 'percentage', 'value' => '', ) ), 'quantity_products_to_adjust' => 'matched', 'quantity_categories' => array(), 'quantity_products' => array(), 'special_purchase' => '', 'special_products_to_adjust' => 'matched', 'special_categories' => array(), 'special_products' => array(), 'special_adjust' => '', 'special_type' => 'percentage', 'special_value' => '', 'special_repeat' => 0, ) ), ), 'discounts' => array( 'apply_multiple' => 'first', 'sets' => array( 1 => array( 'description' => '', 'valid_from' => '', 'valid_until' => '', 'only_if_pricing_not_adjusted' => 0, 'conditions' => array( 1 => array( 'key' => 'subtotal_bottom', 'value' => '', 'products' => array(), 'categories' => array(), 'users' => array(), 'roles' => array(), 'capabilities' => array(), 'shipping_countries' => array(), ) ), 'type' => 'percentage', 'value' => '', ) ), ), 'settings' => array( 'cart_discount_title' => 'DISCOUNT', 'apply_cart_discounts' => 'excl_tax', 'display_table' => 'hide', 'pricing_table_style' => 'horizontal', 'display_position' => 'woocommerce_before_add_to_cart_form', ), 'localization' => array( 'quantity' => __('Quantity', 'rp_wcdpd'), 'price' => __('Price', 'rp_wcdpd'), 'quantity_discounts' => __('Quantity discounts', 'rp_wcdpd'), 'special_offers' => __('Special offers', 'rp_wcdpd'), ) ); // Properties to pass to Javascript $this->to_javascript = array( 'labels' => array( 'pricing_rule' => __('Pricing Rule #', 'rp_wcdpd'), 'discounts_rule' => __('Discount Rule #', 'rp_wcdpd'), ), 'conditional_fields' => array( '.rp_wcdpd_selection_method_field' => array( 'all' => array( 'show' => array(), 'hide' => array('.rp_wcdpd_categories_field', '.rp_wcdpd_products_field'), ), 'categories_include' => array( 'show' => array('.rp_wcdpd_categories_field'), 'hide' => array('.rp_wcdpd_products_field'), ), 'categories_exclude' => array( 'show' => array('.rp_wcdpd_categories_field'), 'hide' => array('.rp_wcdpd_products_field'), ), 'products_include' => array( /*'values' => array('products_include', 'products_exclude'),*/ 'show' => array('.rp_wcdpd_products_field'), 'hide' => array('.rp_wcdpd_categories_field'), ), 'products_exclude' => array( 'show' => array('.rp_wcdpd_products_field'), 'hide' => array('.rp_wcdpd_categories_field'), ), ), '.rp_wcdpd_user_method_field' => array( 'all' => array( 'show' => array(), 'hide' => array('.rp_wcdpd_roles_field', '.rp_wcdpd_users_field', '.rp_wcdpd_capabilities_field'), ), 'roles_include' => array( 'show' => array('.rp_wcdpd_roles_field'), 'hide' => array('.rp_wcdpd_users_field', '.rp_wcdpd_capabilities_field'), ), 'roles_exclude' => array( 'show' => array('.rp_wcdpd_roles_field'), 'hide' => array('.rp_wcdpd_users_field', '.rp_wcdpd_capabilities_field'), ), 'capabilities_include' => array( 'show' => array('.rp_wcdpd_capabilities_field'), 'hide' => array('.rp_wcdpd_users_field', '.rp_wcdpd_roles_field'), ), 'capabilities_exclude' => array( 'show' => array('.rp_wcdpd_capabilities_field'), 'hide' => array('.rp_wcdpd_users_field', '.rp_wcdpd_roles_field'), ), 'users_include' => array( 'show' => array('.rp_wcdpd_users_field'), 'hide' => array('.rp_wcdpd_roles_field', '.rp_wcdpd_capabilities_field'), ), 'users_exclude' => array( 'show' => array('.rp_wcdpd_users_field'), 'hide' => array('.rp_wcdpd_roles_field', '.rp_wcdpd_capabilities_field'), ), ), '.rp_wcdpd_quantity_products_to_adjust_field' => array( 'matched' => array( 'show' => array(), 'hide' => array('.rp_wcdpd_quantity_categories_field', '.rp_wcdpd_quantity_products_field'), ), 'other_categories' => array( 'show' => array('.rp_wcdpd_quantity_categories_field'), 'hide' => array('.rp_wcdpd_quantity_products_field'), ), 'other_products' => array( 'show' => array('.rp_wcdpd_quantity_products_field'), 'hide' => array('.rp_wcdpd_quantity_categories_field'), ), ), '.rp_wcdpd_special_products_to_adjust_field' => array( 'matched' => array( 'show' => array(), 'hide' => array('.rp_wcdpd_special_categories_field', '.rp_wcdpd_special_products_field'), ), 'other_categories' => array( 'show' => array('.rp_wcdpd_special_categories_field'), 'hide' => array('.rp_wcdpd_special_products_field'), ), 'other_products' => array( 'show' => array('.rp_wcdpd_special_products_field'), 'hide' => array('.rp_wcdpd_special_categories_field'), ), ), '.rp_wcdpd_conditions_key_field' => array( 'subtotal_bottom' => array( 'show' => array('.rp_wcdpd_conditions_value_field'), 'hide' => array('.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'subtotal_top' => array( 'show' => array('.rp_wcdpd_conditions_value_field'), 'hide' => array('.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'item_count_bottom' => array( 'show' => array('.rp_wcdpd_conditions_value_field'), 'hide' => array('.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'item_count_top' => array( 'show' => array('.rp_wcdpd_conditions_value_field'), 'hide' => array('.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'quantity_bottom' => array( 'show' => array('.rp_wcdpd_conditions_value_field'), 'hide' => array('.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'quantity_top' => array( 'show' => array('.rp_wcdpd_conditions_value_field'), 'hide' => array('.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'history_count' => array( 'show' => array('.rp_wcdpd_conditions_value_field'), 'hide' => array('.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'history_amount' => array( 'show' => array('.rp_wcdpd_conditions_value_field'), 'hide' => array('.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'products' => array( 'show' => array('.rp_wcdpd_conditions_products_field'), 'hide' => array('.rp_wcdpd_conditions_value_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'products_not' => array( 'show' => array('.rp_wcdpd_conditions_products_field'), 'hide' => array('.rp_wcdpd_conditions_value_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'categories' => array( 'show' => array('.rp_wcdpd_conditions_categories_field'), 'hide' => array('.rp_wcdpd_conditions_value_field', '.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'categories_not' => array( 'show' => array('.rp_wcdpd_conditions_categories_field'), 'hide' => array('.rp_wcdpd_conditions_value_field', '.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'users' => array( 'show' => array('.rp_wcdpd_conditions_users_field'), 'hide' => array('.rp_wcdpd_conditions_value_field', '.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'roles' => array( 'show' => array('.rp_wcdpd_conditions_roles_field'), 'hide' => array('.rp_wcdpd_conditions_value_field', '.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_capabilities_field'), ), 'capabilities' => array( 'show' => array('.rp_wcdpd_conditions_capabilities_field'), 'hide' => array('.rp_wcdpd_conditions_value_field', '.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_shipping_countries_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field'), ), 'shipping_countries' => array( 'show' => array('.rp_wcdpd_conditions_shipping_countries_field'), 'hide' => array('.rp_wcdpd_conditions_value_field', '.rp_wcdpd_conditions_products_field', '.rp_wcdpd_conditions_categories_field', '.rp_wcdpd_conditions_users_field', '.rp_wcdpd_conditions_roles_field', '.rp_wcdpd_conditions_capabilities_field'), ), ), ), 'hints' => array( 'pricing' => array( // Top right field //'rp_wcdpd_apply_multiple_field' => __('', 'rp_wcdpd'), // General settings 'rp_wcdpd_description_field' => __('This will only be used for your own reference.', 'rp_wcdpd'), 'rp_wcdpd_method_field' => __('All three pricing rule methods are completely different:<br /><br /><i>Quantity discount</i> is used to set up tiered discounts that depend on quantity of specific product purchased.<br /><br /><i>Special offer</i> is used to set up <i>buy two get one free</i> and similar scenarios.<br /><br /><i>Exclude matched items</i> is used to exclude specific products or categories from other, usually more general rules (e.g. exlude specific product from a category rule).', 'rp_wcdpd'), 'rp_wcdpd_quantities_based_on_field' => __('Use cumulative methods when you wish to set up scenarios like <i>get 10% discount on Product X when you buy any 10 items from Category Y</i>.', 'rp_wcdpd'), //'rp_wcdpd_if_matched_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_pricing_valid_from_field' => __('', 'rp_wcdpd'), // Conditions //'rp_wcdpd_selection_method_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_categories_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_products_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_user_method_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_roles_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_capabilities_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_users_field' => __('', 'rp_wcdpd'), // Quantity //'rp_wcdpd_sets_quantity' => __('', 'rp_wcdpd'), 'rp_wcdpd_quantity_products_to_adjust_field' => __('Please note that if you select other cart items to adjust, quantities of matched items (not items to adjust) will be used to determine pricing tier. Biggest quantity of all quantities will be used.', 'rp_wcdpd'), //'rp_wcdpd_quantity_categories_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_quantity_products_field' => __('', 'rp_wcdpd'), // Special Offer //'rp_wcdpd_sets_special' => __('', 'rp_wcdpd'), //'rp_wcdpd_special_purchase_field' => __('', 'rp_wcdpd'), 'rp_wcdpd_special_products_to_adjust_field' => __('Please note that if you select other cart items to adjust, quantities of matched items (not items to adjust) will be taken into account. Biggest quantity of all quantities will be used.', 'rp_wcdpd'), //'rp_wcdpd_special_categories_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_special_products_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_special_adjust_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_special_type_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_special_value_field' => __('', 'rp_wcdpd'), 'rp_wcdpd_special_repeat_field' => __('Whether to apply the same rule multiple times (if quantities allow) or not.<br /><br />For example, if you set up <i>buy 2 get 1 free</i> rule and leave <i>Repeat</i> unchecked, then 10 products at full price will earn only 1 free product.<br /><br />On the other hand, if you set <i>Repeat</i> to active, 10 products at full price will earn 5 free products.', 'rp_wcdpd'), ), 'discounts' => array( // Top right field //'rp_wcdpd_apply_multiple_field' => __('', 'rp_wcdpd'), // General settings 'rp_wcdpd_description_field' => __('This will only be used for your own reference.', 'rp_wcdpd'), //'rp_wcdpd_discounts_valid_from_field' => __('', 'rp_wcdpd'), 'rp_wcdpd_discounts_only_if_pricing_not_adjusted_field' => __('If checked, this cart discount will not be applied if cart contains at least one item which price was adjusted by pricing rules.', 'rp_wcdpd'), // Conditions //'rp_wcdpd_sets_section_discounts_conditions' => __('', 'rp_wcdpd'), // Discount //'rp_wcdpd_discounts_type_field' => __('', 'rp_wcdpd'), //'rp_wcdpd_discounts_value_field' => __('', 'rp_wcdpd'), ), 'settings' => array( // General settings 'rp_wcdpd_settings_cart_discount_title_field' => __('On newer versions of WooCommerce, this will appear on the totals block as a discount title (similar to coupon code).', 'rp_wcdpd'), //'rp_wcdpd_settings_apply_cart_discounts_field' => __('', 'rp_wcdpd'), // Quantity pricing table 'rp_wcdpd_settings_display_table_field' => __('Whether or not to display a pricing table on products that have quantity discount rule configured for them.<br /><br />This setting also allows you to choose whether table should be displayed inline or opened in a modal.<br /><br />It is important to understand that if you have any other rules and/or conditions in addition to the very basic <i>Quantity discount</i> table, the final price may differ from what is displayed in the pricing table. It is your own responsibility to determine whether displaying a quantity pricing table on a product page for marketing purposes will work fine in your unique setup.', 'rp_wcdpd'), //'rp_wcdpd_settings_pricing_table_style_field' => __('', 'rp_wcdpd'), 'rp_wcdpd_settings_display_position_field' => __('Choose position on the product page where pricing table (or link to open a modal) should appear. Not all of positions will work with all themes.', 'rp_wcdpd'), ), ), ); } /** * Get options saved to database or default options if no options saved * * @access public * @return array */ public function get_options() { // Get options from database $saved_options = get_option('rp_wcdpd_options', array()); // Get current version (for major updates in future) if (!empty($saved_options)) { if (isset($saved_options[RP_WCDPD_OPTIONS_VERSION])) { $saved_options = $saved_options[RP_WCDPD_OPTIONS_VERSION]; } else { // Migrate options here if needed... } } // Merge with default options foreach (array('pricing', 'discounts', 'settings', 'localization') as $tab) { if (isset($saved_options[$tab])) { $options[$tab] = array_merge($this->default_options[$tab], $saved_options[$tab]); } else { $options[$tab] = $this->default_options[$tab]; } } return $options; } /** * Check if current user can manage plugin options * * @access public * @return bool */ public function user_can_manage() { $user_role = @array_shift(self::current_user_roles()); return in_array($user_role, array('administrator', 'shop_manager')) ? true : false; } /** * Get list of roles assigned to current user * * @access public * @return array */ public static function current_user_roles() { global $current_user; get_currentuserinfo(); return $current_user->roles; } /** * Get list of capabilities assigned to current user * * @access public * @return array */ public static function current_user_capabilities() { // Groups plugin active? if (class_exists('Groups_User') && class_exists('Groups_Wordpress')) { $groups_user = new Groups_User(get_current_user_id()); if ($groups_user) { return $groups_user->capabilities_deep; } else { return array(); } } // Get regular WP capabilities else { global $current_user; get_currentuserinfo(); $all_current_user_capabilities = $current_user->allcaps; $current_user_capabilities = array(); if (is_array($all_current_user_capabilities)) { foreach ($all_current_user_capabilities as $capability => $status) { if ($status) { $current_user_capabilities[] = $capability; } } } return $current_user_capabilities; } } /** * Add link to admin page under Woocommerce menu * * @access public * @return void */ public function add_admin_menu() { if (!$this->user_can_manage()) { return; } global $submenu; if (isset($submenu['woocommerce'])) { add_submenu_page( 'woocommerce', __('Pricing & Discounts', 'woo_pdf'), __('Pricing & Discounts', 'woo_pdf'), 'edit_posts', 'wc_pricing_and_discounts', array($this, 'set_up_admin_page') ); } } /** * Set up admin page * * @access public * @return void */ public function set_up_admin_page() { $current_tab = $this->get_current_settings_tab(); // Print notices settings_errors('rp_wcdpd'); // Load lists for selection if (in_array($current_tab, array('pricing', 'discounts'))) { $all_products = $this->get_all_product_list(); $all_categories = $this->get_all_category_list(); $all_countries = $this->get_all_country_list(); $all_roles = $this->get_all_role_list(); $all_capabilities = $this->get_all_capability_list(); $all_users = $this->get_all_user_list(); } // Print header (tabs) require_once RP_WCDPD_PLUGIN_PATH . 'includes/views/admin/header.php'; // Print settings page content require_once RP_WCDPD_PLUGIN_PATH . 'includes/views/admin/' . $current_tab . '.php'; // Print footer require_once RP_WCDPD_PLUGIN_PATH . 'includes/views/admin/footer.php'; // Pass some variables to Javascript require_once RP_WCDPD_PLUGIN_PATH . 'includes/views/admin/javascript.php'; } /** * Set up plugin options validation etc * * @access public * @return void */ public function plugin_options_setup() { if (!$this->user_can_manage()) { return; } foreach(array('pricing', 'discounts', 'settings', 'localization') as $tab) { register_setting( 'rp_wcdpd_opt_group_' . $tab, 'rp_wcdpd_options', array($this, 'options_validate') ); } } /** * Validate options * * @access public * @param array $input * @return array */ public function options_validate($input) { // Get current settings $output = $this->opt; // Track errors $error = null; // Do we know which tab this is? if (isset($input['current_tab']) && isset($this->default_options[$input['current_tab']])) { // Validate fields of this tab $validation_results = $this->options_validate_fields($input['current_tab'], $input[$input['current_tab']], $output[$input['current_tab']]); // Save to output or set error if (is_array($validation_results)) { $output[$input['current_tab']] = $validation_results; } else if (is_string($validation_results)) { $error = $validation_results; } else { $error = __('Something went wrong. Please try again.', 'rp_wcdpd'); } } else { $error = __('Something went wrong. Please try again.', 'rp_wcdpd'); } // Display errors or success message if ($error === null) { add_settings_error( 'rp_wcdpd', 'updated', 'Your settings have been saved.', 'updated' ); } else { add_settings_error( 'rp_wcdpd', 'rp_wcdpd_error', $error ); } return array(RP_WCDPD_OPTIONS_VERSION => $output); } /** * Validate option fields * * @access public * @param string $context * @param array $input * @param array $output * @return array */ public function options_validate_fields($context, $input, $output) { $error = null; if ($context == 'pricing') { // Check if basic data structure is ok if (!isset($input['apply_multiple']) || !isset($input['sets']) || !is_array($input['sets']) || empty($input['sets'])) { return __('Invalid data structure.', 'rp_wcdpd'); } // Apply rule $output['apply_multiple'] = in_array($input['apply_multiple'], array('first', 'all', 'biggest')) ? $input['apply_multiple'] : 'first'; // Iterate over sets $output['sets'] = array(); $current_set_key = 1; foreach ($input['sets'] as $set_key => $set) { $opt = array(); // Rule description $opt['description'] = (isset($set['description']) && is_string($set['description']) && !empty($set['description'])) ? $set['description'] : ''; // Method $opt['method'] = (isset($set['method']) && in_array($set['method'], array('quantity', 'special', 'exclude'))) ? $set['method'] : 'quantity'; // Quantities based on $opt['quantities_based_on'] = (isset($set['quantities_based_on']) && in_array($set['quantities_based_on'], array('exclusive_product', 'exclusive_variation', 'exclusive_configuration', 'cumulative_categories', 'cumulative_all'))) ? $set['quantities_based_on'] : 'exclusive_product'; // If conditions are matched $opt['if_matched'] = (isset($set['if_matched']) && in_array($set['if_matched'], array('all', 'this', 'other'))) ? $set['if_matched'] : 'all'; // Valid from $opt['valid_from'] = (isset($set['valid_from']) && strtotime($set['valid_from'])) ? $set['valid_from'] : ''; // Valid until $opt['valid_until'] = (isset($set['valid_until']) && strtotime($set['valid_until'])) ? $set['valid_until'] : ''; // Apply to $opt['selection_method'] = (isset($set['selection_method']) && in_array($set['selection_method'], array('all', 'categories_include', 'categories_exclude', 'products_include', 'products_exclude'))) ? $set['selection_method'] : 'all'; // Category list (Apply to) if (isset($set['categories']) && is_array($set['categories']) && !empty($set['categories'])) { $opt['categories'] = $set['categories']; } else { $opt['categories'] = array(); } // Product list (Apply to) if (isset($set['products']) && is_array($set['products']) && !empty($set['products'])) { $opt['products'] = $set['products']; } else { $opt['products'] = array(); } // Customers $opt['user_method'] = (isset($set['user_method']) && in_array($set['user_method'], array('all', 'roles_include', 'roles_exclude', 'capabilities_include', 'capabilities_exclude', 'users_include', 'users_exclude'))) ? $set['user_method'] : 'all'; // Role list (Customers) if (isset($set['roles']) && is_array($set['roles']) && !empty($set['roles'])) { $opt['roles'] = $set['roles']; } else { $opt['roles'] = array(); } // Capability list (Customers) if (isset($set['capabilities']) && is_array($set['capabilities']) && !empty($set['capabilities'])) { $opt['capabilities'] = $set['capabilities']; } else { $opt['capabilities'] = array(); } // Customer list (Customers) if (isset($set['users']) && is_array($set['users']) && !empty($set['users'])) { $opt['users'] = $set['users']; } else { $opt['users'] = array(); } // (Quantity Discount) Products to adjust $opt['quantity_products_to_adjust'] = (isset($set['quantity_products_to_adjust']) && in_array($set['quantity_products_to_adjust'], array('matched', 'other_categories', 'other_products'))) ? $set['quantity_products_to_adjust'] : 'matched'; // (Quantity Discount) Category list (Products to adjust) if (isset($set['quantity_categories']) && is_array($set['quantity_categories']) && !empty($set['quantity_categories'])) { $opt['quantity_categories'] = $set['quantity_categories']; } else { $opt['quantity_categories'] = array(); } // (Quantity Discount) Product list (Products to adjust) if (isset($set['quantity_products']) && is_array($set['quantity_products']) && !empty($set['quantity_products'])) { $opt['quantity_products'] = $set['quantity_products']; } else { $opt['quantity_products'] = array(); } // (Special Offer) Amount to purchase if (isset($set['special_purchase']) && $set['special_purchase'] != '') { $opt['special_purchase'] = (int) preg_replace('/[^0-9]/', '', $set['special_purchase']); } else { $opt['special_purchase'] = ''; } // (Special Offer) Products to adjust $opt['special_products_to_adjust'] = (isset($set['special_products_to_adjust']) && in_array($set['special_products_to_adjust'], array('matched', 'other_categories', 'other_products'))) ? $set['special_products_to_adjust'] : 'matched'; // (Special Offer) Category list (Products to adjust) if (isset($set['special_categories']) && is_array($set['special_categories']) && !empty($set['special_categories'])) { $opt['special_categories'] = $set['special_categories']; } else { $opt['special_categories'] = array(); } // (Special Offer) Product list (Products to adjust) if (isset($set['special_products']) && is_array($set['special_products']) && !empty($set['special_products'])) { $opt['special_products'] = $set['special_products']; } else { $opt['special_products'] = array(); } // (Special Offer) Amount to adjust if (isset($set['special_adjust']) && $set['special_adjust'] != '') { $opt['special_adjust'] = (int) preg_replace('/[^0-9]/', '', $set['special_adjust']); } else { $opt['special_adjust'] = ''; } // (Special Offer) Adjustment type $opt['special_type'] = (isset($set['special_type']) && in_array($set['special_type'], array('percentage', 'price', 'fixed'))) ? $set['special_type'] : 'percentage'; // (Special Offer) Adjustment value if (isset($set['special_value']) && $set['special_value'] != '' && !preg_match('/,/', $set['special_value'])) { $opt['special_value'] = (float) preg_replace('/[^0-9\.]/', '', $set['special_value']); } else { $opt['special_value'] = ''; } // (Special Offer) Repeat $opt['special_repeat'] = (isset($set['special_repeat']) && $set['special_repeat']) ? 1 : 0; // (Quantity Discount) PRICING TABLE $is_ok = true; if (isset($set['pricing']) && is_array($set['pricing']) && !empty($set['pricing'])) { $rows = array(); $current_row_key = 1; foreach ($set['pricing'] as $pricing_key => $pricing) { $row = array(); // Min quantity if (isset($pricing['min']) && !in_array($pricing['min'], array('', '*'))) { $row['min'] = (int) preg_replace('/[^0-9]/', '', $pricing['min']); } else if ($pricing['min'] == '*') { $row['min'] = '*'; } else { $row['min'] = ''; } // Max quantity if (isset($pricing['max']) && !in_array($pricing['max'], array('', '*'))) { $row['max'] = (int) preg_replace('/[^0-9]/', '', $pricing['max']); } else if ($pricing['max'] == '*') { $row['max'] = '*'; } else { $row['max'] = ''; } // Adjustment type $row['type'] = (isset($pricing['type']) && in_array($pricing['type'], array('percentage', 'price', 'fixed'))) ? $pricing['type'] : 'percentage'; // Value if (isset($pricing['value']) && $pricing['value'] != '' && !preg_match('/,/', $pricing['value'])) { $row['value'] = (float) preg_replace('/[^0-9\.]/', '', $pricing['value']); } else { $row['value'] = ''; } $rows[$current_row_key] = $row; $current_row_key++; } $opt['pricing'] = $rows; } else { $opt['pricing'] = array( 1 => array( 'min' => '', 'max' => '', 'type' => '', 'value' => '', ) ); } if (!$is_ok) { $error = __('Pricing rule configuration did not pass validation. Reverted to previous state.', 'rp_wcdpd'); break; } // Save to main output array $output['sets'][$current_set_key] = $opt; $current_set_key++; } } else if ($context == 'discounts') { // Check if basic data structure is ok if (!isset($input['apply_multiple']) || !isset($input['sets']) || !is_array($input['sets']) || empty($input['sets'])) { return __('Invalid data structure.', 'rp_wcdpd'); } // Apply rule $output['apply_multiple'] = in_array($input['apply_multiple'], array('first', 'all', 'biggest')) ? $input['apply_multiple'] : 'first'; // Iterate over sets $output['sets'] = array(); $current_set_key = 1; foreach ($input['sets'] as $set_key => $set) { $opt = array(); // Rule description $opt['description'] = (isset($set['description']) && is_string($set['description']) && !empty($set['description'])) ? $set['description'] : ''; // Valid from $opt['valid_from'] = (isset($set['valid_from']) && strtotime($set['valid_from'])) ? $set['valid_from'] : ''; // Valid until $opt['valid_until'] = (isset($set['valid_until']) && strtotime($set['valid_until'])) ? $set['valid_until'] : ''; // Only if pricing not adjusted $opt['only_if_pricing_not_adjusted'] = (isset($set['only_if_pricing_not_adjusted']) && $set['only_if_pricing_not_adjusted']) ? 1 : 0; // Discount type $opt['type'] = (isset($set['type']) && in_array($set['type'], array('percentage', 'price'))) ? $set['type'] : 'percentage'; // Value if (isset($set['value']) && $set['value'] != '' && !preg_match('/,/', $set['value'])) { $opt['value'] = (float) preg_replace('/[^0-9\.]/', '', $set['value']); } else { $opt['value'] = ''; } // CONDITIONS TABLE $is_ok = true; if (isset($set['conditions']) && is_array($set['conditions']) && !empty($set['conditions'])) { $rows = array(); $current_row_key = 1; foreach ($set['conditions'] as $condition_key => $condition) { $row = array(); // Field $row['key'] = (isset($condition['key']) && in_array($condition['key'], array('subtotal_bottom', 'subtotal_top', 'products', 'products_not', 'categories', 'categories_not', 'item_count_bottom', 'item_count_top', 'quantity_bottom', 'quantity_top', 'users', 'roles', 'capabilities', 'history_count', 'history_amount', 'shipping_countries'))) ? $condition['key'] : 'subtotal_bottom'; // Value if (isset($condition['value']) && $condition['value'] != '' && !preg_match('/,/', $condition['value'])) { $row['value'] = (float) preg_replace('/[^0-9\.]/', '', $condition['value']); } else { $row['value'] = ''; } // Products if (isset($condition['products']) && is_array($condition['products']) && !empty($condition['products'])) { $row['products'] = $condition['products']; } else { $row['products'] = array(); } // Categories if (isset($condition['categories']) && is_array($condition['categories']) && !empty($condition['categories'])) { $row['categories'] = $condition['categories']; } else { $row['categories'] = array(); } // Users if (isset($condition['users']) && is_array($condition['users']) && !empty($condition['users'])) { $row['users'] = $condition['users']; } else { $row['users'] = array(); } // Roles if (isset($condition['roles']) && is_array($condition['roles']) && !empty($condition['roles'])) { $row['roles'] = $condition['roles']; } else { $row['roles'] = array(); } // Capabilities if (isset($condition['capabilities']) && is_array($condition['capabilities']) && !empty($condition['capabilities'])) { $row['capabilities'] = $condition['capabilities']; } else { $row['capabilities'] = array(); } // Shipping countries if (isset($condition['shipping_countries']) && is_array($condition['shipping_countries']) && !empty($condition['shipping_countries'])) { $row['shipping_countries'] = $condition['shipping_countries']; } else { $row['shipping_countries'] = array(); } $rows[$current_row_key] = $row; $current_row_key++; } $opt['conditions'] = $rows; } else { $opt['conditions'] = array( 1 => array( 'key' => '', 'value' => '', 'products' => array(), 'categories' => array(), 'users' => array(), 'roles' => array(), 'capabilities' => array(), 'shipping_countries' => array(), ) ); } if (!$is_ok) { $error = __('Pricing rule configuration did not pass validation. Reverted to previous state.', 'rp_wcdpd'); break; } // Save to main output array $output['sets'][$current_set_key] = $opt; $current_set_key++; } } else if ($context == 'settings') { // Cart discount title $output['cart_discount_title'] = (isset($input['cart_discount_title']) && !empty($input['cart_discount_title'])) ? $input['cart_discount_title'] : 'DISCOUNT'; // Apply cart discounts $output['apply_cart_discounts'] = (isset($input['apply_cart_discounts']) && in_array($input['apply_cart_discounts'], array('excl_tax', 'incl_tax'))) ? $input['apply_cart_discounts'] : 'excl_tax'; // Display pricing table $output['display_table'] = (isset($input['display_table']) && in_array($input['display_table'], array('hide', 'modal', 'inline'))) ? $input['display_table'] : 'hide'; // Display special offers $output['display_offers'] = (isset($input['display_offers']) && in_array($input['display_offers'], array('hide', 'modal', 'inline'))) ? $input['display_offers'] : 'hide'; // Display position $output['display_position'] = (isset($input['display_position']) && in_array($input['display_position'], array('woocommerce_before_add_to_cart_form', 'woocommerce_after_add_to_cart_form', 'woocommerce_single_product_summary', 'woocommerce_after_single_product_summary', 'woocommerce_product_meta_end', 'woocommerce_after_main_content'))) ? $input['display_position'] : 'woocommerce_before_add_to_cart_form'; // Color scheme $output['pricing_table_style'] = (isset($input['pricing_table_style']) && in_array($input['pricing_table_style'], array('horizontal', 'vertical'))) ? $input['pricing_table_style'] : 'horizontal'; } else if ($context == 'localization') { // Quantity discounts $output['quantity_discounts'] = (isset($input['quantity_discounts']) && is_string($input['quantity_discounts']) && !empty($input['quantity_discounts'])) ? $input['quantity_discounts'] : ''; // Special offers $output['special_offers'] = (isset($input['special_offers']) && is_string($input['special_offers']) && !empty($input['special_offers'])) ? $input['special_offers'] : ''; // Quantity $output['quantity'] = (isset($input['quantity']) && is_string($input['quantity']) && !empty($input['quantity'])) ? $input['quantity'] : ''; // Price $output['price'] = (isset($input['price']) && is_string($input['price']) && !empty($input['price'])) ? $input['price'] : ''; } return $error ? $error : $output; } /** * Get current settings page tab * * @access public * @return string */ public function get_current_settings_tab() { // Check if requested settings page tab exists if (isset($_GET['tab']) && in_array($_GET['tab'], array_merge(array_keys($this->settings_page_tabs), array('help')))) { return $_GET['tab']; } else { $keys = array_keys($this->settings_page_tabs); return $keys[0]; } } /** * Add settings link on plugins page * * @access public * @param array $links * @return void */ public function plugins_page_links($links) { $settings_link = '<a href="http://support.rightpress.net/" target="_blank">'.__('Support', 'rp_wcdpd').'</a>'; array_unshift($links, $settings_link); $settings_link = '<a href="admin.php?page=wc_pricing_and_discounts">'.__('Settings', 'rp_wcdpd').'</a>'; array_unshift($links, $settings_link); return $links; } /** * Load scripts and styles required for admin * * @access public * @return void */ public function enqueue_admin_scripts_and_styles() { // Our own scripts and styles wp_register_script('rp-wcdpd-admin-scripts', RP_WCDPD_PLUGIN_URL . '/assets/js/scripts-admin.js', array('jquery'), RP_WCDPD_VERSION); wp_register_style('rp-wcdpd-admin-styles', RP_WCDPD_PLUGIN_URL . '/assets/css/style-admin.css', array(), RP_WCDPD_VERSION); // Custom jQuery UI styles wp_register_style('rp-wcdpd-jquery-ui-styles', RP_WCDPD_PLUGIN_URL . '/assets/css/jquery-ui.css', array(), RP_WCDPD_VERSION); // Chosen scripts and styles (advanced form fields) wp_register_script('rp-wcdpd-jquery-chosen', RP_WCDPD_PLUGIN_URL . '/assets/js/chosen.jquery.js', array('jquery'), '1.0.0'); wp_register_style('rp-wcdpd-jquery-chosen-css', RP_WCDPD_PLUGIN_URL . '/assets/css/chosen.min.css', array(), RP_WCDPD_VERSION); // Font awesome (icons) wp_register_style('rp-wcdpd-font-awesome', RP_WCDPD_PLUGIN_URL . '/assets/font-awesome/css/font-awesome.min.css', array(), '4.0.3'); // Scripts wp_enqueue_script('jquery'); wp_enqueue_script('jquery-ui-accordion'); wp_enqueue_script('jquery-ui-sortable'); wp_enqueue_script('jquery-ui-tooltip'); wp_enqueue_script('jquery-ui-datepicker'); wp_enqueue_script('rp-wcdpd-jquery-chosen'); wp_enqueue_script('rp-wcdpd-admin-scripts'); // Styles wp_enqueue_style('rp-wcdpd-font-awesome'); wp_enqueue_style('rp-wcdpd-jquery-ui-styles'); wp_enqueue_style('rp-wcdpd-jquery-chosen-css'); wp_enqueue_style('rp-wcdpd-font-awesome'); wp_enqueue_style('rp-wcdpd-admin-styles'); } /** * Load scripts and styles required for frontend * * @access public * @return void */ public function enqueue_frontend_scripts_and_styles() { // Our own scripts and styles wp_register_script('rp-wcdpd-frontend-scripts', RP_WCDPD_PLUGIN_URL . '/assets/js/scripts-frontend.js', array('jquery'), RP_WCDPD_VERSION); wp_register_style('rp-wcdpd-frontend-styles', RP_WCDPD_PLUGIN_URL . '/assets/css/style-frontend.css', array(), RP_WCDPD_VERSION); // Scripts wp_enqueue_script('jquery'); wp_enqueue_script('rp-wcdpd-frontend-scripts'); // Styles wp_enqueue_style('rp-wcdpd-frontend-styles'); } /** * Get all product list for select field * * @access public * @return array */ public function get_all_product_list() { $result = array('' => ''); $posts_raw = get_posts(array( 'posts_per_page' => -1, 'post_type' => 'product', 'post_status' => array('publish', 'pending', 'draft', 'future', 'private', 'inherit'), 'fields' => 'ids', )); foreach ($posts_raw as $post_id) { $result[$post_id] = '#' . $post_id . ' ' . get_the_title($post_id); } return $result; } /** * Get all category list for select field * * @access public * @return array */ public function get_all_category_list() { $result = array('' => ''); $post_categories_raw = get_terms(array('product_cat'), array('hide_empty' => 0)); $post_categories_raw_count = count($post_categories_raw); foreach ($post_categories_raw as $post_cat_key => $post_cat) { $category_name = $post_cat->name; if ($post_cat->parent) { $parent_id = $post_cat->parent; $has_parent = true; // Make sure we don't have an infinite loop here (happens with some kind of "ghost" categories) $found = false; $i = 0; while ($has_parent && ($i < $post_categories_raw_count || $found)) { // Reset each time $found = false; $i = 0; foreach ($post_categories_raw as $parent_post_cat_key => $parent_post_cat) { $i++; if ($parent_post_cat->term_id == $parent_id) { $category_name = $parent_post_cat->name . ' &rarr; ' . $category_name; $found = true; if ($parent_post_cat->parent) { $parent_id = $parent_post_cat->parent; } else { $has_parent = false; } break; } } } } $result[$post_cat->term_id] = $category_name; } return $result; } /** * Get all country list for select field * * @access public * @return array */ public function get_all_country_list() { $countries = new WC_Countries(); if ($countries && is_array($countries->countries)) { return array_merge(array('' => ''), $countries->countries); } else { return array('' => ''); } } /** * Get all user role list for select field * * @access public * @return array */ public function get_all_role_list() { global $wp_roles; if (!isset($wp_roles)) { $wp_roles = new WP_Roles(); } return array_merge(array('' => ''), $wp_roles->get_names()); } /** * Get all capability list for select field * * @access public * @return array */ public function get_all_capability_list() { $capabilities = array(); // Groups plugin active? if (class_exists('Groups_User') && class_exists('Groups_Wordpress') && function_exists('_groups_get_tablename')) { global $wpdb; $capability_table = _groups_get_tablename('capability'); $all_capabilities = $wpdb->get_results('SELECT capability FROM ' . $capability_table); if ($all_capabilities) { foreach ($all_capabilities as $capability) { $capabilities[$capability->capability] = $capability->capability; } } } // Get standard WP capabilities else { global $wp_roles; if (!isset($wp_roles)) { get_role('administrator'); } $roles = $wp_roles->roles; if (is_array($roles)) { foreach ($roles as $rolename => $atts) { if (isset($atts['capabilities']) && is_array($atts['capabilities'])) { foreach ($atts['capabilities'] as $capability => $value) { if (!in_array($capability, $capabilities)) { $capabilities[$capability] = $capability; } } } } } } return apply_filters('rp_wcdpd_capability_list', array_merge(array('' => ''), $capabilities)); } /** * Get all user list for select field * * @access public * @return array */ public function get_all_user_list() { $result = array('' => ''); foreach(get_users() as $user) { $result[$user->ID] = '#' . $user->ID . ' ' . $user->user_email; } return $result; } /** * Get product categories * * @access public * @param array $product_id * @return array */ public function get_product_categories($product_id) { $categories = array(); $current_categories = wp_get_post_terms($product_id, 'product_cat'); foreach ($current_categories as $category) { $categories[] = $category->term_id; } return $categories; } /** * Check WooCommerce version * * @access public * @param string $version * @return bool */ public function wc_version_gte($version) { if (defined('WC_VERSION') && WC_VERSION) { return version_compare(WC_VERSION, $version, '>='); } else if (defined('WOOCOMMERCE_VERSION') && WOOCOMMERCE_VERSION) { return version_compare(WOOCOMMERCE_VERSION, $version, '>='); } else { return false; } } } $GLOBALS['RP_WCDPD'] = RP_WCDPD::get_instance(); }
ardiqghenatya/web4
wp-content/plugins/wc-dynamic-pricing-and-discounts/wc-dynamic-pricing-and-discounts.php
PHP
gpl-2.0
95,639
#! /usr/bin/python # a script to preare PiSi source tarball from svn # author: exa #TODO: arguments for svn snapshot with rev number, or a tag to override default import sys import os import shutil def run(cmd): print 'running', cmd os.system(cmd) sys.path.insert(0, '.') import pisi if not os.path.exists('svndist'): os.makedirs('svndist') ver = pisi.__version__ if os.path.exists('svndist/pisi-%s' % ver): shutil.rmtree('svndist/pisi-%s' % ver) print 'Exporting svn directory' run('svn export http://svn.uludag.org.tr/uludag/trunk/pisi svndist/pisi-%s' % ver) os.chdir('svndist') run('tar cjvf pisi-%s.tar.bz2 pisi-%s' % (ver, ver)) print 'Have a look at svndist directory'
Pardus-Linux/pisi
scripts/svndist.py
Python
gpl-2.0
709
<?php /** * Subclase para crear funcionalidades específicas de busqueda y actualización en la tabla 'cattipviv'. * * * * @package Roraima * @subpackage lib.model.catastro * @author $Author$ <desarrollo@cidesa.com.ve> * @version SVN: $Id$ * * @copyright Copyright 2007, Cide S.A. * @license http://opensource.org/licenses/gpl-2.0.php GPLv2 */ class CattipvivPeer extends BaseCattipvivPeer { }
cidesa/roraima
lib/model/catastro/CattipvivPeer.php
PHP
gpl-2.0
421
/** * 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.common; import java.io.Serializable; /** A simple (ordered) pair of two objects. Elements may be null. */ public final class Pair<A,B> implements Comparable<Pair<A,B>>, Serializable { private final A first; private final B second; public Pair(A first, B second) { this.first = first; this.second = second; } public A getFirst() { return first; } public B getSecond() { return second; } public Pair<B, A> swap() { return new Pair<>(second, first); } public static <A,B> Pair<A,B> of(A a, B b) { return new Pair<>(a, b); } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair<?, ?>)) { return false; } Pair<?, ?> otherPair = (Pair<?, ?>) obj; return isEqualOrNulls(first, otherPair.getFirst()) && isEqualOrNulls(second, otherPair.getSecond()); } private static boolean isEqualOrNulls(Object obj1, Object obj2) { return obj1 == null ? obj2 == null : obj1.equals(obj2); } @Override public int hashCode() { int firstHash = hashCodeNull(first); // Flip top and bottom 16 bits; this makes the hash function probably different // for (a,b) versus (b,a) return (firstHash >>> 16 | firstHash << 16) ^ hashCodeNull(second); } private static int hashCodeNull(Object obj) { return obj == null ? 0 : obj.hashCode(); } @Override public String toString() { return '(' + String.valueOf(first) + ',' + second + ')'; } /** * Defines an ordering on pairs that sorts by first value's natural ordering, ascending, * and then by second value's natural ordering. * * @throws ClassCastException if types are not actually {@link Comparable} */ @Override public int compareTo(Pair<A,B> other) { Comparable<A> thisFirst = (Comparable<A>) first; A thatFirst = other.getFirst(); int compare = thisFirst.compareTo(thatFirst); if (compare != 0) { return compare; } Comparable<B> thisSecond = (Comparable<B>) second; B thatSecond = other.getSecond(); return thisSecond.compareTo(thatSecond); } }
huran2014/huran.github.io
program_learning/Java/MyEclipseProfessional2014/mr/src/main/java/org/apache/mahout/common/Pair.java
Java
gpl-2.0
2,940
FD50.plugin("bootstrap3", function($) { var jQuery = $; /*! * Bootstrap v3.0.3 (http://getbootstrap.com) * Copyright 2015 Twitter, Inc. * Licensed under http://www.apache.org/licenses/LICENSE-2.0 */ if (window["Foundry5/Bootstrap"]) { throw new Error("An instance of Bootstrap has been initialized before this.") } else { window["Foundry5/Bootstrap"] = { version: "3.0.3", foundry: jQuery } } /* ======================================================================== * Bootstrap: transition.js v3.0.3 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd otransitionend' , 'transition' : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false, $el = this $(this).one($.support.transition.end, function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.0.3 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-bp-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.hasClass('alert') ? $this : $this.parent() } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent.trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one($.support.transition.end, removeElement) .emulateTransitionEnd(150) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.0.3 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) } Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (!data.resetText) $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout(function () { state == 'loadingText' ? $el.addClass(d).attr(d, d) : $el.removeClass(d).removeAttr(d); }, 0) } Button.prototype.toggle = function () { var $parent = this.$element.closest('[data-bp-toggle="buttons"]') var changed = true if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') === 'radio') { // see if clicking on current one if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } if (changed) this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document).on('click.bs.button.data-api', '[data-bp-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') e.preventDefault() }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.0.3 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.DEFAULTS = { interval: 5000 , pause: 'hover' , wrap: true } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getActiveIndex = function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getActiveIndex() if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || $active[type]() var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var fallback = type == 'next' ? 'first' : 'last' var that = this if (!$next.length) { if (!this.options.wrap) return $next = this.$element.find('.item')[fallback]() } this.sliding = true isCycling && this.pause() var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid.bs.carousel', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid.bs.carousel') }, 0) }) .emulateTransitionEnd(600) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid.bs.carousel') } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= $(document).on('click.bs.carousel.data-api', '[data-bp-slide], [data-bp-slide-to]', function (e) { var $this = $(this), href var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-bp-slide-to') if (slideIndex) options.interval = false $target.carousel(options) if (slideIndex = $this.attr('data-bp-slide-to')) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() }) $(window).on('load', function () { $('[data-bp-ride="carousel"]').each(function () { var $carousel = $(this) $carousel.carousel($carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.0.3 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(this.options.parent) if (this.options.toggle) this.toggle() } Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var startEvent = $.Event('show.bs.collapse') this.$element.triggerHandler(startEvent) if (startEvent.isDefaultPrevented()) return var actives = this.$parent && this.$parent.find('> .panel > .in') if (actives && actives.length) { var hasData = actives.data('bs.collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing') [dimension](0) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('in') [dimension]('auto') this.transitioning = 0 this.$element.trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) [dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.triggerHandler(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element [dimension](this.$element[dimension]()) [0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse') .removeClass('in') this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .trigger('hidden.bs.collapse') .removeClass('collapsing') .addClass('collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } // COLLAPSE PLUGIN DEFINITION // ========================== var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-bp-toggle=collapse]', function (e) { var $this = $(this), href var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 var $target = $(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-bp-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } $target.collapse(option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.0.3 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-bp-toggle=dropdown]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } $parent.triggerHandler(e = $.Event('show.bs.dropdown')) if (e.isDefaultPrevented()) return $parent .toggleClass('open') .trigger('shown.bs.dropdown') $this.focus() } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27)/.test(e.keyCode)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } var $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return var index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index=0 $items.eq(index).focus() } function clearMenus() { $(backdrop).remove() $(toggle).each(function (e) { var $parent = getParent($(this)) if (!$parent.hasClass('open')) return $parent.triggerHandler(e = $.Event('hide.bs.dropdown')) if (e.isDefaultPrevented()) return $parent.removeClass('open').trigger('hidden.bs.dropdown') }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown_ form, .dropdown-static', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.0.3 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$element = $(element) this.$backdrop = this.isShown = null if (this.options.remote) this.$element.load(this.options.remote) } Modal.DEFAULTS = { backdrop: true , keyboard: true , show: true } Modal.prototype.toggle = function (_relatedTarget) { return this[!this.isShown ? 'show' : 'hide'](_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.triggerHandler(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.$element.on('click.dismiss.modal', '[data-bp-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) // don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one($.support.transition.end, function () { that.$element.focus().trigger(e) }) .emulateTransitionEnd(300) : that.$element.focus().trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.triggerHandler(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one($.support.transition.end, $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.focus() } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$element.on('click.dismiss.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (callback) { callback() } } // MODAL PLUGIN DEFINITION // ======================= var old = $.fn.modal $.fn.modal = function (option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-bp-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 var option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option, this) .one('hide', function () { $this.is(':visible') && $this.focus() }) }) $(document) .on('show.bs.modal', '.modal.bs', function () { $(document.body).addClass('modal-open') }) .on('hidden.bs.modal', '.modal.bs', function () { $(document.body).removeClass('modal-open') }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.0.3 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.DEFAULTS = { animation: true , placement: 'top' , selector: false , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' , trigger: 'hover focus' , title: '' , delay: 0 , html: false , container: false } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focus' var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay , hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.'+ this.type) if (this.hasContent() && this.enabled) { this.$element.triggerHandler(e) if (e.isDefaultPrevented()) return var $tip = this.tip() this.setContent() if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement.split('-')[0]); this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var $parent = this.$element.parent() var orgPlacement = placement var docScroll = document.documentElement.scrollTop || document.body.scrollTop var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth() var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight() var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' : placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' : placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' : placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) this.$element.trigger('shown.bs.' + this.type) } } Tooltip.prototype.applyPlacement = function(offset, placement) { var replace var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft $tip .offset(offset) .addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { replace = true offset.top = offset.top + height - actualHeight } if (['top', 'bottom'].indexOf(placement.split('-')[0]) === 0) { var delta = 0 if (offset.left < 0) { delta = offset.left * -2 offset.left = 0 $tip.offset(offset) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight } this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') } if (['left', 'right'].indexOf(placement.split('-')[0]) === 0) { this.replaceArrow(actualHeight - height, actualHeight, 'top') } if (replace) $tip.offset(offset) } Tooltip.prototype.replaceArrow = function(delta, dimension, position) { this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function () { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() } this.$element.triggerHandler(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete() this.$element.trigger('hidden.bs.' + this.type) return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function () { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth , height: el.offsetHeight }, this.$element.offset()) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'left-top' ? { top: pos.top, left: pos.left - actualWidth } : placement == 'left-bottom' ? { top: pos.top + pos.height - actualHeight, left: pos.left - actualWidth } : placement == 'right-top' ? { top: pos.top, left: pos.left + pos.width } : placement == 'right-bottom' ? { top: pos.top + pos.height - actualHeight, left: pos.left + pos.width } : placement == 'top-left' ? { top: pos.top - actualHeight, left: pos.left } : placement == 'top-right' ? { top: pos.top - actualHeight, left: pos.left + pos.width - actualWidth } : placement == 'bottom-left' ? { top: pos.top + pos.height, left: pos.left } : placement == 'bottom-right' ? { top: pos.top + pos.height, left: pos.left + pos.width - actualWidth } : placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.tip = function () { return this.$tip = this.$tip || $(this.options.template) } Tooltip.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow') } Tooltip.prototype.validate = function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { this.hide().$element.off('.' + this.type).removeData('bs.' + this.type) } // TOOLTIP PLUGIN DEFINITION // ========================= var old = $.fn.tooltip $.fn.tooltip = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.0.3 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.DEFAULTS = $.extend({} , $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right' , trigger: 'click' , content: '' , template: '<div id="fd" class="fd-popover"><div class="arrow"></div><h3 class="fd-popover-title"></h3><div class="fd-popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.fd-popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.fd-popover-content')[this.options.html ? 'html' : 'text'](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.fd-popover-title').html()) $tip.find('.fd-popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.arrow') } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.0.3 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var href var process = $.proxy(this.process, this) this.$element = $(element).is('body') ? $(window) : $(element) this.$body = $('body') this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.offsets = $([]) this.targets = $([]) this.activeTarget = null this.refresh() this.process() } ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.refresh = function () { var offsetMethod = this.$element[0] == window ? 'offset' : 'position' this.offsets = $([]) this.targets = $([]) var self = this var $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#\w/.test(href) && $(href) return ($href && $href.length && [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight var maxScroll = scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate(i) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target $(this.selector) .parents('.active') .removeClass('active') var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } // SCROLLSPY PLUGIN DEFINITION // =========================== var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load', function () { $('[data-bp-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.0.3 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ($this.parent('li').hasClass('active')) return var previous = $ul.find('.active:last a')[0] var e = $.Event('show.bs.tab', { relatedTarget: previous }) $this.triggerHandler(e) if (e.isDefaultPrevented()) return var $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown.bs.tab' , relatedTarget: previous }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active .one($.support.transition.end, next) .emulateTransitionEnd(150) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ $(document).on('click.bs.tab.data-api', '[data-bp-toggle="tab"], [data-bp-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.0.3 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2013 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$window = $(window) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = null this.checkPosition() } Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0 } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() var scrollTop = this.$window.scrollTop() var position = this.$element.offset() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false if (this.affixed === affix) return if (this.unpin) this.$element.css('top', '') this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : '')) if (affix == 'bottom') { this.$element.offset({ top: document.body.offsetHeight - offsetBottom - this.$element.height() }) } } // AFFIX PLUGIN DEFINITION // ======================= var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-bp-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom) data.offset.bottom = data.offsetBottom if (data.offsetTop) data.offset.top = data.offsetTop $spy.affix(data) }) }) }(jQuery); /** * bootstrap-notify.js v1.0 * -- * http://twitter.com/nijikokun * Copyright 2012 Nijiko Yonskai, Goodybag * -- * 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. */ !function ($) { var Notification = function (element, options) { // Element collection this.$element = $(element); this.$note = $('<div class="alert"></div>'); this.options = $.extend(true, $.fn.notify.defaults, options); // Setup from options if(this.options.transition) if(this.options.transition == 'fade') this.$note.addClass('in').addClass(this.options.transition); else this.$note.addClass(this.options.transition); else this.$note.addClass('fade').addClass('in'); if(this.options.type) this.$note.addClass('alert-' + this.options.type); else this.$note.addClass('alert-success'); if(!this.options.message && this.$element.data("message") !== '') // dom text this.$note.html(this.$element.data("message")); else if(typeof this.options.message === 'object') if(this.options.message.html) this.$note.html(this.options.message.html); else if(this.options.message.text) this.$note.text(this.options.message.text); else this.$note.html(this.options.message); if(this.options.closable) var link = $('<a class="close pull-right" href="javascript: void(0);">&times;</a>'); $(link).on('click', $.proxy(onClose, this)); this.$note.prepend(link); return this; }; onClose = function() { this.options.onClose(); $(this.$note).remove(); this.options.onClosed(); }; Notification.prototype.show = function () { if(this.options.fadeOut.enabled) this.$note.delay(this.options.fadeOut.delay || 3000).fadeOut('slow', $.proxy(onClose, this)); this.$element.append(this.$note); this.$note.alert(); }; Notification.prototype.hide = function () { if(this.options.fadeOut.enabled) this.$note.delay(this.options.fadeOut.delay || 3000).fadeOut('slow', $.proxy(onClose, this)); else onClose.call(this); }; $.fn.notify = function (options) { return new Notification(this, options); }; $.fn.notify.defaults = { type: 'success', closable: true, transition: 'fade', fadeOut: { enabled: true, delay: 3000 }, message: null, onClose: function () {}, onClosed: function () {} } }($); });
BetterBetterBetter/B3App
media/foundry/5.0/scripts/bootstrap3.js
JavaScript
gpl-2.0
62,727
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NeoComp.NeuralNetworks; using NeoComp; using System.ComponentModel; using NeoComp.Activities.Design; using System.Activities; using NeoComp.Activities.Internal; using NeoComp.NeuralNetworks.ActivationFunctions; using NeoComp.NeuralNetworks.Learning.Algorithms; namespace NeoComp.Activities.NeuralNetworks { public class ActivationNeuronFactoryBlueprint : NeuralOperationNodeFactoryBlueprint<ActivationNeuron> { [Serializable] sealed class ActivationNeuronFactory : FactoryBase<ActivationNeuron> { internal IActivationFunction ActivationFunction { get; set; } internal LearningRule[] LearningRules { get; set; } public override ActivationNeuron Create() { return new ActivationNeuron(ActivationFunction, LearningRules); } } [Browsable(false)] [ActivityDelegateMetadata(ObjectName = "Activation Function")] [BlueprintFunc] public ActivityFunc<IActivationFunction> ActivationFunction { get; set; } [Browsable(false)] [ActivityDelegateMetadata(ObjectName = "Learning Rules")] [BlueprintFunc] public ActivityFunc<LearningRule[]> LearningRules { get; set; } protected override void CacheMetadata(NativeActivityMetadata metadata) { if (ActivationFunction.IsNull()) metadata.AddValidationError("Activation Function is expected."); if (LearningRules.IsNull()) metadata.AddValidationError("Learning Rules are expected."); base.CacheMetadata(metadata); } protected override IFactory<ActivationNeuron> CreateNeuralOperationNodeFactory(NativeActivityContext context) { var af = GetFuncResult<IActivationFunction>(context, "ActivationFunction"); var rules = GetFuncResult<LearningRule[]>(context, "LearningRules"); if (af == null) throw new InvalidOperationException("Activation Function is expected."); if (rules == null || rules.Length == 0) throw new InvalidOperationException("Learning Rules are expected."); return new ActivationNeuronFactory { ActivationFunction = af, LearningRules = rules }; } protected override Activity CreateActivityTemplate(System.Windows.DependencyObject target) { return new ActivationNeuronFactoryBlueprint { DisplayName = "Activation Neuron" }; } } }
unbornchikken/Neuroflow
_vault/NFBak/Neuroflow_vsonline/Neuroflow/OldStuff/NeoComp/NeoComp 1.0/NeoComp.Activities/NeuralNetworks/ActivationNeuronFactoryBlueprint.cs
C#
gpl-3.0
2,558
/* Switch-spec.js * * copyright (c) 2010-2022, Christian Mayer and the CometVisu contributers. * * 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, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ /** * Unit tests for switch widget * * @author Tobias Bräutigam * @since 2016 */ describe('testing a switch', function() { it('should test the switch creator', function() { var res = this.createTestElement('switch', {flavour: 'potassium'}, '<label>Test</label>'); var switchWidget = Array.from(res.getDomElement().children).filter(function(m) { return m.matches('.switch'); })[0]; expect(switchWidget).toHaveFlavour('potassium'); var actor = res.getActor(); expect(actor).not.toBeNull(); expect(actor).toHaveClass('switchUnpressed'); expect(actor).not.toHaveClass('switchPressed'); var value = res.getValueElement(); expect(value).not.toBeNull(); expect(value.innerText).toBe('-'); var label = Array.from(switchWidget.children).filter(function(m) { return m.matches('.label'); })[0]; expect(label).not.toBeNull(); expect(label.innerText).toBe('Test'); expect(res.getOnValue()).toBe('1'); expect(res.getOffValue()).toBe('0'); }); it('should test the switch creator with different on/off values', function() { var res = this.createTestElement('switch', {on_value: 'turn_on', off_value: 'turn_off'}); expect(res.getOnValue()).toBe('turn_on'); expect(res.getOffValue()).toBe('turn_off'); }); it('should update a switch', function() { var res = this.createTestElement('switch', {}, '<label>Test</label>'); res.update('12/7/37', 1); var actor = res.getActor(); expect(actor).not.toBe(null); expect(actor).toHaveClass('switchPressed'); expect(actor).not.toHaveClass('switchUnpressed'); res.update('12/7/37', 0); expect(actor).toHaveClass('switchUnpressed'); expect(actor).not.toHaveClass('switchPressed'); }); it('should trigger the switch action', function() { var res = this.createTestElement('switch', {}, '<label>Test</label>'); this.initWidget(res); spyOn(res, 'sendToBackend'); var actor = res.getActor(); expect(actor).not.toBe(null); var Reg = qx.event.Registration; res.update('12/7/37', 0); Reg.fireEvent(actor, 'tap', qx.event.type.Event, []); expect(res.sendToBackend).toHaveBeenCalledWith('1'); res.update('12/7/37', 1); Reg.fireEvent(actor, 'tap', qx.event.type.Event, []); expect(res.sendToBackend).toHaveBeenCalledWith('0'); }); });
ChristianMayer/CometVisu
source/test/karma/ui/structure/pure/Switch-spec.js
JavaScript
gpl-3.0
3,171
/* * Copyright (C) 2010 Pavel Stastny * * 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 cz.incad.kramerius.service.guice; import com.google.inject.AbstractModule; import com.google.inject.Scopes; import cz.incad.kramerius.service.Mailer; import cz.incad.kramerius.service.impl.MailerImpl; public class MailModule extends AbstractModule { @Override protected void configure() { bind(Mailer.class).to(MailerImpl.class).in(Scopes.SINGLETON); } }
ceskaexpedice/kramerius
shared/common/src/main/java/cz/incad/kramerius/service/guice/MailModule.java
Java
gpl-3.0
1,081
# coding=UTF-8 __author__ = 'wanghongfei' import mysql.connector, sys CLEAR_DB = False args = sys.argv[1:] if len(args) == 1: if args[0] == 'clear': CLEAR_DB = True else: print 'wrong parameter!' sys.exit(1) config = { 'user': 'root', 'password': '111111', 'host': 'localhost', 'database': 'taolijie', 'raise_on_warnings': True } def build_connection(conf): connection = mysql.connector.connect(**conf) return connection def close_connection(conn): conn.close() # 清空所有数据 def clear_data(): sqls = [ "DELETE FROM member_role", "DELETE FROM role", "DELETE FROM job_post", "DELETE FROM second_hand_post", "DELETE FROM job_post_category", "DELETE FROM second_hand_post_category", "DELETE FROM resume", "DELETE FROM academy", "DELETE FROM school", "DELETE FROM news", "DELETE FROM member", ] for sql in sqls: cursor.execute(sql) conn.commit() def insert_role_data(cursor): sql = "INSERT INTO role(rolename, memo) VALUES (%s, %s)" data = [ ('ADMIN', '管理员'), ('STUDENT', '学生'), ('EMPLOYER', '商家') ] cursor.executemany(sql, data) def insert_member_data(cursor): sql = "INSERT INTO member(username, password, age) VALUES (%(username)s, %(password)s, %(age)s )" data = [ { 'username': 'wanghongfei', 'password': '3d4f2bf07dc1be38b20cd6e46949a1071f9d0e3d', 'age': 22 }, { 'username': 'wangfucheng', 'password': '3d4f2bf07dc1be38b20cd6e46949a1071f9d0e3d', 'age': 21 }, { 'username': 'abc', 'password': '3d4f2bf07dc1be38b20cd6e46949a1071f9d0e3d', 'age': 18 } ] cursor.executemany(sql, data) def insert_member_role_data(cursor): sql = "INSERT INTO member_role(member_id, role_rid) VALUES ( %(member_id)s, %(role_rid)s )" data = [ { 'member_id': query_member_id('wanghongfei'), 'role_rid': query_role_id('ADMIN') }, { 'member_id': query_member_id('wangfucheng'), 'role_rid': query_role_id('STUDENT') }, { 'member_id': query_member_id('abc'), 'role_rid': query_role_id('EMPLOYER') } ] cursor.executemany(sql, data) def insert_school_data(): sql = "INSERT INTO school(short_name, full_name, province) VALUES ( %(short_name)s, %(full_name)s, %(province)s )" data = [ { 'short_name': '理工大', 'full_name': '山东理工大学', 'province': '山东' } ] cursor.executemany(sql, data) def insert_academy_data(): sql = "INSERT INTO academy(college_id, short_name, full_name) VALUES (%(college_id)s, %(short_name)s, %(full_name)s )" data = [ { 'college_id': query_school_id('山东理工大学'), 'short_name': '计院', 'full_name': '计算机学院' }, { 'college_id': query_school_id('山东理工大学'), 'short_name': '商学院', 'full_name': '商学院' }, { 'college_id': query_school_id('山东理工大学'), 'short_name': '电气学院', 'full_name': '电气与电子工程学院' } ] cursor.executemany(sql, data) def insert_news_data(): sql = "INSERT INTO news(title, content, member_id) VALUE ( %(title)s, %(content)s, %(member_id)s) " data = [ { 'title': '死人了1', 'content': '哪里死人了?', 'member_id': query_member_id('wanghongfei') }, { 'title': '死人了2', 'content': '哪里死人了?', 'member_id': query_member_id('wangfucheng') }, { 'title': '死人了3', 'content': '哪里死人了?', 'member_id': query_member_id('abc') } ] cursor.executemany(sql, data) def query_school_id(school_name): sql = "SELECT id FROM school WHERE full_name = %(full_name)s" data = { 'full_name': school_name } cursor.execute(sql, data) res = cursor.fetchone() return res[0] def query_role_id(rolename): sql = "SELECT rid FROM role WHERE rolename = %(rolename)s" data = { 'rolename': rolename } cursor.execute(sql, data) res = cursor.fetchone() return res[0] def query_member_id(username): sql = "SELECT id FROM member WHERE username = %(username)s" data = { 'username': username } cursor.execute(sql, data) res = cursor.fetchone() return res[0] def insert_category_data(): sql = "INSERT INTO job_post_category (name, memo) VALUES (%(name)s, %(memo)s )" data = [ { 'name': '发传单', 'memo': '' }, { 'name': '送快递', 'memo': '' }, { 'name': '家政', 'memo': '' } ] cursor.executemany(sql, data) sql = "INSERT INTO second_hand_post_category (name, memo) VALUES (%(name)s, %(memo)s )" data = [ { 'name': '手机', 'memo': '' }, { 'name': '电脑', 'memo': '' }, { 'name': '自行车', 'memo': '' } ] cursor.executemany(sql, data) def insert_resume_data(cursor, usernames): for username in usernames: sql = "INSERT INTO resume (member_id, name, gender, access_authority) VALUES ( %(member_id)s, %(name)s, %(gender)s, %(access_authority)s )" data = [ { 'member_id': query_member_id(username), 'name': '王鸿飞', 'gender': '男', 'access_authority': 'GLOBAL' }, { 'member_id': query_member_id(username), 'name': '王鸿飞2', 'gender': '男', 'access_authority': 'GLOBAL' } ] cursor.executemany(sql, data) def query_job_category_id(name): sql = "SELECT id FROM job_post_category WHERE name = %(name)s" data = ({'name': name}) cursor.execute(sql, data) res = cursor.fetchone() return res[0] def query_sh_category_id(name): sql = "SELECT id FROM second_hand_post_category WHERE name = %(name)s" data = ({'name': name}) cursor.execute(sql, data) res = cursor.fetchone() return res[0] def insert_sh_data(name_list): for name in name_list: sql = "INSERT INTO second_hand_post (member_id, second_hand_post_category_id, title, description) VALUES (%(member_id)s, %(second_hand_post_category_id)s, %(title)s, %(description)s) " data = [ { 'member_id': query_member_id(name), 'second_hand_post_category_id': query_sh_category_id('自行车'), 'title': '出售二手山地车', 'description': '9成新' }, { 'member_id': query_member_id(name), 'second_hand_post_category_id': query_sh_category_id('手机'), 'title': '出售二手iphone', 'description': '8成新' }, { 'member_id': query_member_id(name), 'second_hand_post_category_id': query_sh_category_id('电脑'), 'title': '出售二手macbook', 'description': '5成新' } ] cursor.executemany(sql, data) def insert_job_data(name_list): for name in name_list: sql = "INSERT INTO job_post (member_id, job_post_category_id, title, introduce) VALUES ( %(member_id)s, %(job_post_category_id)s, %(title)s, %(introduce)s )" data = [ { 'member_id': query_member_id(name), 'job_post_category_id': query_job_category_id('送快递'), 'title': '送快递', 'introduce': '998' } ] cursor.executemany(sql, data) # build connection conn = build_connection(config) cursor = conn.cursor() if CLEAR_DB: clear_data() print 'done clearing' sys.exit(0) users = ['wanghongfei', 'wangfucheng', 'abc'] # insert data print 'inserting into role table' insert_role_data(cursor) print 'done' print 'inserting into member table' insert_member_data(cursor) print 'done' print 'inserting into member_role table' insert_member_role_data(cursor) print 'done' print 'inserting into category table' insert_category_data() print 'done' print 'inserting into resume table' insert_resume_data(cursor, users) print 'done' print 'inserting into job table' insert_job_data(users) print 'done' print 'inserting into second_hand table' insert_sh_data(users) print 'done' print 'inserting into school table' insert_school_data() print 'done' print 'inserting into academy table' insert_academy_data() print 'done' print 'inserting into news table' insert_news_data() print 'done' conn.commit() close_connection(conn)
lankeren/taolijie
script/insert-data.py
Python
gpl-3.0
9,304
<?php /** * Layout: list row buttons - rendered as a Bootstrap dropdown * * @package Joomla * @subpackage Fabrik * @copyright Copyright (C) 2005-2015 fabrikar.com - All rights reserved. * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html * @since 3.0 */ // No direct access defined('_JEXEC') or die('Restricted access'); $d = $displayData; ?> <a data-loadmethod="<?php echo $d->loadMethod; ?>" class="<?php echo $d->class;?> btn-default" <?php echo $d->editAttributes;?> data-list="<?php echo $d->dataList;?>" href="<?php echo $d->editLink;?>" title="<?php echo $d->editLabel;?>"> <?php echo FabrikHelperHTML::image('edit.png', 'list', '', array('alt' => $d->editLabel));?> <?php echo $d->editText; ?></a>
techfreaque/Joomla_fabrik_fanzy_list
fanzy-list/listactions/fabrik-edit-button.php
PHP
gpl-3.0
738
var classgr__base__error__handler = [ [ "gr_base_error_handler", "classgr__base__error__handler.html#ad4b18ebae96256e537650772dd3cb1f6", null ], [ "count_error", "classgr__base__error__handler.html#a840a56a5d19b2269ea9328ba54bd4236", null ], [ "nerrors", "classgr__base__error__handler.html#a828a9e2ea41d6e6a6a5f46f2097a67c7", null ], [ "nwarnings", "classgr__base__error__handler.html#a7567f2ef1370cb0f71d2ea204fd16968", null ], [ "reset_counts", "classgr__base__error__handler.html#a6d7cc692da78d6eeece40d0733e3998a", null ] ];
aviralchandra/Sandhi
build/gr36/docs/doxygen/html/classgr__base__error__handler.js
JavaScript
gpl-3.0
549
from django.core.urlresolvers import reverse from decision_test_case import DecisionTestCase from publicweb.forms import DecisionForm from mock import patch from django.dispatch.dispatcher import Signal from django.db.models import signals from publicweb.models import Decision, decision_signal_handler # TODO: This class is a bit stumpy... merge with other (web) tests. class EditDecisionTest(DecisionTestCase): def test_edit_description_form_displays_title(self): decision = self.create_and_return_decision() response = self.load_add_decision_and_return_response(decision.id) self.assertContains(response, u"Update Proposal #%s" % decision.id) def load_add_decision_and_return_response(self, idd): return self.client.get(reverse('publicweb_decision_update', args=[idd])) @patch('publicweb.models.ObservationManager.send_notifications') def test_email_not_sent_when_watcher_removed(self, notifications): dispatch_uid = "publicweb.models.decision_signal_handler" Signal.disconnect(signals.post_save, sender=Decision, dispatch_uid=dispatch_uid) decision = self.create_and_return_decision() data = { 'description': decision.description, 'status': decision.status, 'deadline': decision.deadline, 'people': decision.people, 'watch': True } form = DecisionForm(data, instance=decision) form.watch = False form.is_valid() form.save() Signal.connect( signals.post_save, sender=Decision, receiver=decision_signal_handler, dispatch_uid=dispatch_uid ) self.assertFalse(notifications.called)
aptivate/econsensus
django/econsensus/publicweb/tests/edit_decision_test.py
Python
gpl-3.0
1,773
<?php /** * This file is part of OXID eShop Community Edition. * * OXID eShop Community Edition 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. * * OXID eShop Community Edition 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 OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.oxid-esales.com * @package core * @copyright (C) OXID eSales AG 2003-2013 * @version OXID eShop CE * @version SVN: $Id$l */ /** * Implements search * * @package model */ class oxSearch extends oxSuperCfg { /** * Active language id * * @var int */ protected $_iLanguage = 0; /** * Class constructor. Executes search lenguage setter * * @return null */ public function __construct() { $this->setLanguage(); } /** * Search language setter. If no param is passed, will be taken default shop language * * @param string $iLanguage string (default null) * * @return null; */ public function setLanguage( $iLanguage = null ) { if ( !isset( $iLanguage ) ) { $this->_iLanguage = oxRegistry::getLang()->getBaseLanguage(); } else { $this->_iLanguage = $iLanguage; } } /** * Returns a list of articles according to search parameters. Returns matched * * @param string $sSearchParamForQuery query parameter * @param string $sInitialSearchCat initial category to seearch in * @param string $sInitialSearchVendor initial vendor to seearch for * @param string $sInitialSearchManufacturer initial Manufacturer to seearch for * @param string $sSortBy sort by * * @return oxarticlelist */ public function getSearchArticles( $sSearchParamForQuery = false, $sInitialSearchCat = false, $sInitialSearchVendor = false, $sInitialSearchManufacturer = false, $sSortBy = false ) { // sets active page $this->iActPage = (int) oxConfig::getParameter( 'pgNr' ); $this->iActPage = ($this->iActPage < 0)?0:$this->iActPage; // load only articles which we show on screen //setting default values to avoid possible errors showing article list $iNrofCatArticles = $this->getConfig()->getConfigParam( 'iNrofCatArticles' ); $iNrofCatArticles = $iNrofCatArticles?$iNrofCatArticles:10; $oArtList = oxNew( 'oxarticlelist' ); $oArtList->setSqlLimit( $iNrofCatArticles * $this->iActPage, $iNrofCatArticles ); $sSelect = $this->_getSearchSelect( $sSearchParamForQuery, $sInitialSearchCat, $sInitialSearchVendor, $sInitialSearchManufacturer, $sSortBy ); if ( $sSelect ) { $oArtList->selectString( $sSelect ); } return $oArtList; } /** * Returns the amount of articles according to search parameters. * * @param string $sSearchParamForQuery query parameter * @param string $sInitialSearchCat initial category to seearch in * @param string $sInitialSearchVendor initial vendor to seearch for * @param string $sInitialSearchManufacturer initial Manufacturer to seearch for * * @return int */ public function getSearchArticleCount( $sSearchParamForQuery = false, $sInitialSearchCat = false, $sInitialSearchVendor = false, $sInitialSearchManufacturer = false ) { $iCnt = 0; $sSelect = $this->_getSearchSelect( $sSearchParamForQuery, $sInitialSearchCat, $sInitialSearchVendor, $sInitialSearchManufacturer, false ); if ( $sSelect ) { $sPartial = substr( $sSelect, strpos( $sSelect, ' from ' ) ); $sSelect = "select count( ".getViewName( 'oxarticles', $this->_iLanguage ).".oxid ) $sPartial "; $iCnt = oxDb::getDb()->getOne( $sSelect ); } return $iCnt; } /** * Returns the appropriate SQL select for a search according to search parameters * * @param string $sSearchParamForQuery query parameter * @param string $sInitialSearchCat initial category to search in * @param string $sInitialSearchVendor initial vendor to search for * @param string $sInitialSearchManufacturer initial Manufacturer to search for * @param string $sSortBy sort by * * @return string */ protected function _getSearchSelect( $sSearchParamForQuery = false, $sInitialSearchCat = false, $sInitialSearchVendor = false, $sInitialSearchManufacturer = false, $sSortBy = false) { $oDb = oxDb::getDb(); // performance if ( $sInitialSearchCat ) { // lets search this category - is no such category - skip all other code $oCategory = oxNew( 'oxcategory' ); $sCatTable = $oCategory->getViewName(); $sQ = "select 1 from $sCatTable where $sCatTable.oxid = ".$oDb->quote( $sInitialSearchCat )." "; $sQ .= "and ".$oCategory->getSqlActiveSnippet(); if ( !$oDb->getOne( $sQ ) ) { return; } } // performance: if ( $sInitialSearchVendor ) { // lets search this vendor - if no such vendor - skip all other code $oVendor = oxNew( 'oxvendor' ); $sVndTable = $oVendor->getViewName(); $sQ = "select 1 from $sVndTable where $sVndTable.oxid = ".$oDb->quote( $sInitialSearchVendor )." "; $sQ .= "and ".$oVendor->getSqlActiveSnippet(); if ( !$oDb->getOne( $sQ ) ) { return; } } // performance: if ( $sInitialSearchManufacturer ) { // lets search this Manufacturer - if no such Manufacturer - skip all other code $oManufacturer = oxNew( 'oxmanufacturer' ); $sManTable = $oManufacturer->getViewName(); $sQ = "select 1 from $sManTable where $sManTable.oxid = ".$oDb->quote( $sInitialSearchManufacturer )." "; $sQ .= "and ".$oManufacturer->getSqlActiveSnippet(); if ( !$oDb->getOne( $sQ ) ) { return; } } $sWhere = null; if ( $sSearchParamForQuery ) { $sWhere = $this->_getWhere( $sSearchParamForQuery ); } elseif ( !$sInitialSearchCat && !$sInitialSearchVendor && !$sInitialSearchManufacturer ) { //no search string return null; } $oArticle = oxNew( 'oxarticle' ); $sArticleTable = $oArticle->getViewName(); $sO2CView = getViewName( 'oxobject2category' ); $sSelectFields = $oArticle->getSelectFields(); // longdesc field now is kept on different table $sDescJoin = ''; if ( is_array( $aSearchCols = $this->getConfig()->getConfigParam( 'aSearchCols' ) ) ) { if ( in_array( 'oxlongdesc', $aSearchCols ) || in_array( 'oxtags', $aSearchCols ) ) { $sDescView = getViewName( 'oxartextends', $this->_iLanguage ); $sDescJoin = " LEFT JOIN {$sDescView} ON {$sArticleTable}.oxid={$sDescView}.oxid "; } } //select articles $sSelect = "select {$sSelectFields} from {$sArticleTable} {$sDescJoin} where "; // must be additional conditions in select if searching in category if ( $sInitialSearchCat ) { $sCatView = getViewName( 'oxcategories', $this->_iLanguage ); $sInitialSearchCatQuoted = $oDb->quote( $sInitialSearchCat ); $sSelectCat = "select oxid from {$sCatView} where oxid = $sInitialSearchCatQuoted and (oxpricefrom != '0' or oxpriceto != 0)"; if ( $oDb->getOne($sSelectCat) ) { $sSelect = "select {$sSelectFields} from {$sArticleTable} $sDescJoin " . "where {$sArticleTable}.oxid in ( select {$sArticleTable}.oxid as id from {$sArticleTable}, {$sO2CView} as oxobject2category, {$sCatView} as oxcategories " . "where (oxobject2category.oxcatnid=$sInitialSearchCatQuoted and oxobject2category.oxobjectid={$sArticleTable}.oxid) or (oxcategories.oxid=$sInitialSearchCatQuoted and {$sArticleTable}.oxprice >= oxcategories.oxpricefrom and {$sArticleTable}.oxprice <= oxcategories.oxpriceto )) and "; } else { $sSelect = "select {$sSelectFields} from {$sO2CView} as oxobject2category, {$sArticleTable} {$sDescJoin} where oxobject2category.oxcatnid=$sInitialSearchCatQuoted and oxobject2category.oxobjectid={$sArticleTable}.oxid and "; } } $sSelect .= $oArticle->getSqlActiveSnippet(); $sSelect .= " and {$sArticleTable}.oxparentid = '' and {$sArticleTable}.oxissearch = 1 "; if ( $sInitialSearchVendor ) { $sSelect .= " and {$sArticleTable}.oxvendorid = " . $oDb->quote( $sInitialSearchVendor ) . " "; } if ( $sInitialSearchManufacturer ) { $sSelect .= " and {$sArticleTable}.oxmanufacturerid = " . $oDb->quote( $sInitialSearchManufacturer ) . " "; } $sSelect .= $sWhere; if ( $sSortBy ) { $sSelect .= " order by {$sSortBy} "; } return $sSelect; } /** * Forms and returns SQL query string for search in DB. * * @param string $sSearchString searching string * * @return string */ protected function _getWhere( $sSearchString ) { $oDb = oxDb::getDb(); $myConfig = $this->getConfig(); $blSep = false; $sArticleTable = getViewName( 'oxarticles', $this->_iLanguage ); $aSearchCols = $myConfig->getConfigParam( 'aSearchCols' ); if ( !(is_array( $aSearchCols ) && count( $aSearchCols ) ) ) { return ''; } $oTempArticle = oxNew( 'oxarticle' ); $sSearchSep = $myConfig->getConfigParam( 'blSearchUseAND' )?'and ':'or '; $aSearch = explode( ' ', $sSearchString ); $sSearch = ' and ( '; $myUtilsString = oxRegistry::get("oxUtilsString"); $oLang = oxRegistry::getLang(); foreach ( $aSearch as $sSearchString ) { if ( !strlen( $sSearchString ) ) { continue; } if ( $blSep ) { $sSearch .= $sSearchSep; } $blSep2 = false; $sSearch .= '( '; foreach ( $aSearchCols as $sField ) { if ( $blSep2 ) { $sSearch .= ' or '; } // as long description now is on different table table must differ if ( $sField == 'oxlongdesc' || $sField == 'oxtags' ) { $sSearchField = getViewName( 'oxartextends', $this->_iLanguage ).".{$sField}"; } else { $sSearchField = "{$sArticleTable}.{$sField}"; } $sSearch .= " {$sSearchField} like ".$oDb->quote( "%$sSearchString%" ); // special chars ? if ( ( $sUml = $myUtilsString->prepareStrForSearch( $sSearchString ) ) ) { $sSearch .= " or {$sSearchField} like ".$oDb->quote( "%$sUml%" ); } $blSep2 = true; } $sSearch .= ' ) '; $blSep = true; } $sSearch .= ' ) '; return $sSearch; } }
apnfq/oxid_test
application/models/oxsearch.php
PHP
gpl-3.0
11,995
/*! * Bootstrap v3.3.6 (http://getbootstrap.com) * Copyright 2011-2015 Twitter, Inc. * Licensed under the MIT license */ if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') } +function ($) { 'use strict'; var version = $.fn.jquery.split(' ')[0].split('.') if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 2)) { throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3') } }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.3.6 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return {end: transEndEventNames[name]} } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function (e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.3.6 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.3.6' Alert.TRANSITION_DURATION = 150 Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.3.6 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.3.6' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state += 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) // push to event loop to allow forms to submit setTimeout($.proxy(function () { $el[val](data[state] == null ? this.options[state] : data[state]) if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked')) changed = false $parent.find('.active').removeClass('active') this.$element.addClass('active') } else if ($input.prop('type') == 'checkbox') { if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false this.$element.toggleClass('active') } $input.prop('checked', this.$element.hasClass('active')) if (changed) $input.trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) this.$element.toggleClass('active') } } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') Plugin.call($btn, 'toggle') if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault() }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.3.6 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = null this.sliding = null this.interval = null this.$active = null this.$items = null this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.3.6' Carousel.TRANSITION_DURATION = 600 Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } Carousel.prototype.keydown = function (e) { if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.getItemForDirection = function (direction, active) { var activeIndex = this.getItemIndex(active) var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)) if (willWrap && !this.options.wrap) return active var delta = direction == 'prev' ? -1 : 1 var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var that = this if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', {relatedTarget: relatedTarget, direction: direction}) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= var clickHandler = function (e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.3.6 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' + '[data-toggle="collapse"][data-target="#' + element.id + '"]') this.transitioning = null if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.3.6' Collapse.TRANSITION_DURATION = 350 Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var activesData var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing') if (actives && actives.length) { activesData = actives.data('bs.collapse') if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (actives && actives.length) { Plugin.call(actives, 'hide') activesData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true) this.$trigger .removeClass('collapsed') .attr('aria-expanded', true) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false) this.$trigger .addClass('collapsed') .attr('aria-expanded', false) this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } Collapse.prototype.getParent = function () { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function (i, element) { var $element = $(element) this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() } Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) { var isOpen = $element.hasClass('in') $element.attr('aria-expanded', isOpen) $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) } function getTargetFromTrigger($trigger) { var href var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var $this = $(this) if (!$this.attr('data-target')) e.preventDefault() var $target = getTargetFromTrigger($this) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.3.6 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle="dropdown"]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.VERSION = '3.3.6' function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } function clearMenus(e) { if (e && e.which === 3) return $(backdrop).remove() $(toggle).each(function () { var $this = $(this) var $parent = getParent($this) var relatedTarget = {relatedTarget: this} if (!$parent.hasClass('open')) return if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this.attr('aria-expanded', 'false') $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget)) }) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $(document.createElement('div')) .addClass('dropdown-backdrop') .insertAfter($(this)) .on('click', clearMenus) } var relatedTarget = {relatedTarget: this} $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this .trigger('focus') .attr('aria-expanded', 'true') $parent .toggleClass('open') .trigger($.Event('shown.bs.dropdown', relatedTarget)) } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive && e.which != 27 || isActive && e.which == 27) { if (e.which == 27) $parent.find(toggle).trigger('focus') return $this.trigger('click') } var desc = ' li:not(.disabled):visible a' var $items = $parent.find('.dropdown-menu' + desc) if (!$items.length) return var index = $items.index(e.target) if (e.which == 38 && index > 0) index-- // up if (e.which == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).trigger('focus') } // DROPDOWN PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown $.fn.dropdown = Plugin $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.3.6 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$dialog = this.$element.find('.modal-dialog') this.$backdrop = null this.isShown = null this.originalBodyPad = null this.scrollbarWidth = 0 this.ignoreBackdropClick = false if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.3.6' Modal.TRANSITION_DURATION = 300 Modal.BACKDROP_TRANSITION_DURATION = 150 Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', {relatedTarget: _relatedTarget}) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.setScrollbar() this.$body.addClass('modal-open') this.escape() this.resize() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.$dialog.on('mousedown.dismiss.bs.modal', function () { that.$element.one('mouseup.dismiss.bs.modal', function (e) { if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true }) }) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) // don't move modals dom position } that.$element .show() .scrollTop(0) that.adjustDialog() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element.addClass('in') that.enforceFocus() var e = $.Event('shown.bs.modal', {relatedTarget: _relatedTarget}) transition ? that.$dialog // wait for modal to slide in .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() this.resize() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .off('click.dismiss.bs.modal') .off('mouseup.dismiss.bs.modal') this.$dialog.off('mousedown.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } } Modal.prototype.resize = function () { if (this.isShown) { $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) } else { $(window).off('resize.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.$body.removeClass('modal-open') that.resetAdjustments() that.resetScrollbar() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $(document.createElement('div')) .addClass('modal-backdrop ' + animate) .appendTo(this.$body) this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) { if (this.ignoreBackdropClick) { this.ignoreBackdropClick = false return } if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus() : this.hide() }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function () { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove() } else if (callback) { callback() } } // these following methods are used to handle overflowing modals Modal.prototype.handleUpdate = function () { this.adjustDialog() } Modal.prototype.adjustDialog = function () { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) } Modal.prototype.resetAdjustments = function () { this.$element.css({ paddingLeft: '', paddingRight: '' }) } Modal.prototype.checkScrollbar = function () { var fullWindowWidth = window.innerWidth if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8 var documentElementRect = document.documentElement.getBoundingClientRect() fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left) } this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth this.scrollbarWidth = this.measureScrollbar() } Modal.prototype.setScrollbar = function () { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) this.originalBodyPad = document.body.style.paddingRight || '' if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function () { this.$body.css('padding-right', this.originalBodyPad) } Modal.prototype.measureScrollbar = function () { // thx walsh var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({remote: !/#/.test(href) && href}, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function (showEvent) { if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function () { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.3.6 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = null this.options = null this.enabled = null this.timeout = null this.hoverState = null this.$element = null this.inState = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.3.6' Tooltip.TRANSITION_DURATION = 150 Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport)) this.inState = {click: false, hover: false, focus: false} if (this.$element[0] instanceof document.constructor && !this.options.selector) { throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!') } var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--; ) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, {trigger: 'manual', selector: ''})) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true } if (self.tip().hasClass('in') || self.hoverState == 'in') { self.hoverState = 'in' return } clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.isInStateTrue = function () { for (var key in this.inState) { if (this.inState[key]) return true } return false } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false } if (self.isInStateTrue()) return clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) this.$element.attr('aria-describedby', tipId) this.$element.attr('id', tipId) var popoverid = "#" + tipId var myelement = $(popoverid).attr("data-class") $tip.addClass(myelement); if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({top: 0, left: 0, display: 'block'}) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) this.$element.trigger('inserted.bs.' + this.type) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var viewportDim = this.getPosition(this.$viewport) placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function () { var prevHoverState = that.hoverState that.$element.trigger('shown.bs.' + that.type) that.hoverState = null if (prevHoverState == 'out') that.leave(that) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top += marginTop offset.left += marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) if (delta.left) offset.left += delta.left else offset.top += delta.top var isVertical = /top|bottom/.test(placement) var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) } Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) { this.arrow() .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isVertical ? 'top' : 'left', '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function (callback) { var that = this var $tip = $(this.$tip) var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) callback && callback() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && $tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function ($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' var elRect = el.getBoundingClientRect() if (elRect.width == null) { // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 elRect = $.extend({}, elRect, {width: elRect.right - elRect.left, height: elRect.bottom - elRect.top}) } var elOffset = isBody ? {top: 0, left: 0} : $element.offset() var scroll = {scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop()} var outerDims = isBody ? {width: $(window).width(), height: $(window).height()} : null return $.extend({}, elRect, scroll, outerDims, elOffset) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} : placement == 'top' ? {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2} : placement == 'left' ? {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth} : /* placement == 'right' */ {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width} } Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) { var delta = {top: 0, left: 0} if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var viewportDimensions = this.getPosition(this.$viewport) if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding var rightEdgeOffset = pos.left + viewportPadding + actualWidth if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function (prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function () { if (!this.$tip) { this.$tip = $(this.options.template) if (this.$tip.length != 1) { throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!') } } return this.$tip } Tooltip.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } if (e) { self.inState.click = !self.inState.click if (self.isInStateTrue()) self.enter(self) else self.leave(self) } else { self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } } Tooltip.prototype.destroy = function () { var that = this clearTimeout(this.timeout) this.hide(function () { that.$element.off('.' + that.type).removeData('bs.' + that.type) if (that.$tip) { that.$tip.detach() } that.$tip = null that.$arrow = null that.$viewport = null }) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.3.6 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.VERSION = '3.3.6' Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) } // POPOVER PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.popover $.fn.popover = Plugin $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.3.6 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { this.$body = $(document.body) this.$scrollElement = $(element).is(document.body) ? $(window) : $(element) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || '') + ' .nav li > a' this.offsets = [] this.targets = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this)) this.refresh() this.process() } ScrollSpy.VERSION = '3.3.6' ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) } ScrollSpy.prototype.refresh = function () { var that = this var offsetMethod = 'offset' var offsetBase = 0 this.offsets = [] this.targets = [] this.scrollHeight = this.getScrollHeight() if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position' offsetBase = this.$scrollElement.scrollTop() } this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[$href[offsetMethod]().top + offsetBase, href]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { that.offsets.push(this[0]) that.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.getScrollHeight() var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop < offsets[0]) { this.activeTarget = null return this.clear() } for (i = offsets.length; i--; ) { activeTarget != targets[i] && scrollTop >= offsets[i] && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target this.clear() var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } ScrollSpy.prototype.clear = function () { $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') } // SCROLLSPY PLUGIN DEFINITION // =========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy $.fn.scrollspy = Plugin $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load.bs.scrollspy.data-api', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) Plugin.call($spy, $spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.3.6 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { // jscs:disable requireDollarBeforejQueryAssignment this.element = $(element) // jscs:enable requireDollarBeforejQueryAssignment } Tab.VERSION = '3.3.6' Tab.TRANSITION_DURATION = 150 Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } if ($this.parent('li').hasClass('active')) return var $previous = $ul.find('.active:last a') var hideEvent = $.Event('hide.bs.tab', { relatedTarget: $this[0] }) var showEvent = $.Event('show.bs.tab', { relatedTarget: $previous[0] }) $previous.trigger(hideEvent) $this.trigger(showEvent) if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return var $target = $(selector) this.activate($this.closest('li'), $ul) this.activate($target, $target.parent(), function () { $previous.trigger({ type: 'hidden.bs.tab', relatedTarget: $this[0] }) $this.trigger({ type: 'shown.bs.tab', relatedTarget: $previous[0] }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length) function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', false) element .addClass('active') .find('[data-toggle="tab"]') .attr('aria-expanded', true) if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu').length) { element .closest('li.dropdown') .addClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', true) } callback && callback() } $active.length && transition ? $active .one('bsTransitionEnd', next) .emulateTransitionEnd(Tab.TRANSITION_DURATION) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tab $.fn.tab = Plugin $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ var clickHandler = function (e) { e.preventDefault() Plugin.call($(this), 'show') } $(document) .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.3.6 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$target = $(this.options.target) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = null this.unpin = null this.pinnedOffset = null this.checkPosition() } Affix.VERSION = '3.3.6' Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0, target: window } Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) { var scrollTop = this.$target.scrollTop() var position = this.$element.offset() var targetHeight = this.$target.height() if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false if (this.affixed == 'bottom') { if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom' return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom' } var initializing = this.affixed == null var colliderTop = initializing ? scrollTop : position.top var colliderHeight = initializing ? targetHeight : height if (offsetTop != null && scrollTop <= offsetTop) return 'top' if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom' return false } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$target.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var height = this.$element.height() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom var scrollHeight = Math.max($(document).height(), $(document.body).height()) if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom) if (this.affixed != affix) { if (this.unpin != null) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger(affixType.replace('affix', 'affixed') + '.bs.affix') } if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - height - offsetBottom }) } } // AFFIX PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.affix $.fn.affix = Plugin $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom if (data.offsetTop != null) data.offset.top = data.offsetTop Plugin.call($spy, data) }) }) }(jQuery);
shazic/FirstWordPress
wp-content/themes/evolve/library/media/js/bootstrap/js/bootstrap.js
JavaScript
gpl-3.0
78,255
using System; using System.Collections.Generic; using UnityEngine; namespace MuMech { public class MechJebModuleScriptActionSAS : MechJebModuleScriptAction { public static String NAME = "SAS"; private List<Part> commandParts = new List<Part>(); private List<String> commandPartsNames = new List<String>(); [Persistent(pass = (int)Pass.Type)] private int actionType; [Persistent(pass = (int)Pass.Type)] private bool onActiveVessel = true; [Persistent(pass = (int)Pass.Type)] private EditableInt selectedPartIndex = 0; [Persistent(pass = (int)Pass.Type)] private uint selectedPartFlightID = 0; bool partHighlighted = false; private List<String> actionTypes = new List<String>(); public MechJebModuleScriptActionSAS (MechJebModuleScript scriptModule, MechJebCore core, MechJebModuleScriptActionsList actionsList):base(scriptModule, core, actionsList, NAME) { this.actionTypes.Clear(); this.actionTypes.Add("Enable"); this.actionTypes.Add("Disable"); this.commandParts.Clear(); this.commandPartsNames.Clear(); foreach (Vessel vessel in FlightGlobals.Vessels) { if (vessel.state != Vessel.State.DEAD) { foreach (Part part in vessel.Parts) { if (part.HasModule<ModuleCommand>() && !part.name.Contains("mumech")) { commandParts.Add(part); commandPartsNames.Add(part.name); } } } } } override public void activateAction() { base.activateAction(); Vessel vessel; if (onActiveVessel) { vessel = FlightGlobals.ActiveVessel; } else { vessel = commandParts[selectedPartIndex].vessel; } if (actionType == 0) { vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, true); } else { vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false); } this.endAction(); } override public void endAction() { base.endAction(); } override public void WindowGUI(int windowID) { base.preWindowGUI(windowID); base.WindowGUI(windowID); GUILayout.Label ("SAS"); actionType = GuiUtils.ComboBox.Box(actionType, actionTypes.ToArray(), actionTypes); onActiveVessel = GUILayout.Toggle(onActiveVessel, "On active Vessel"); if (!onActiveVessel) { selectedPartIndex = GuiUtils.ComboBox.Box(selectedPartIndex, commandPartsNames.ToArray(), commandPartsNames); if (commandParts[selectedPartIndex] != null) { if (!partHighlighted) { if (GUILayout.Button(GameDatabase.Instance.GetTexture("MechJeb2/Icons/view", true), GUILayout.ExpandWidth(false))) { partHighlighted = true; commandParts[selectedPartIndex].SetHighlight(true, false); } } else { if (GUILayout.Button(GameDatabase.Instance.GetTexture("MechJeb2/Icons/view_a", true), GUILayout.ExpandWidth(false))) { partHighlighted = false; commandParts[selectedPartIndex].SetHighlight(false, false); } } } } if (selectedPartIndex < commandParts.Count) { this.selectedPartFlightID = commandParts[selectedPartIndex].flightID; } base.postWindowGUI(windowID); } override public void postLoad(ConfigNode node) { if (selectedPartFlightID != 0) //We check if a previous flightID was set on the parts. When switching MechJeb Cores and performing save/load of the script, the port order may change so we try to rely on the flight ID to select the right part. { int i = 0; foreach (Part part in commandParts) { if (part.flightID == selectedPartFlightID) { this.selectedPartIndex = i; } i++; } } } } }
Meumeu/MechJeb2
MechJeb2/ScriptsModule/MechJebModuleScriptActionSAS.cs
C#
gpl-3.0
3,606
#region Using directives using System; using System.Reflection; using System.Runtime.InteropServices; #endregion // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PokeMaster.Translator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PokeMaster.Translator")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // This sets the default COM visibility of types in the assembly to invisible. // If you need to expose a type to COM, use [ComVisible(true)] on that type. [assembly: ComVisible(false)] // The assembly version has following format : // // Major.Minor.Build.Revision // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")]
Ar1i/PokemonGo-Bot
PokemonGo.RocketAPI.Translator/Properties/AssemblyInfo.cs
C#
gpl-3.0
1,068
package cz.incad.Kramerius; import java.awt.Desktop.Action; import java.io.IOException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.StringTokenizer; import java.util.logging.Level; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.antlr.stringtemplate.StringTemplate; import org.apache.commons.lang3.StringEscapeUtils; import com.google.inject.Inject; import com.google.inject.Provider; import cz.incad.Kramerius.backend.guice.GuiceServlet; import cz.incad.kramerius.intconfig.InternalConfiguration; import cz.incad.kramerius.pdf.GeneratePDFService; import cz.incad.kramerius.processes.DefinitionManager; import cz.incad.kramerius.processes.LRProcessManager; import cz.incad.kramerius.service.ResourceBundleService; import cz.incad.kramerius.service.TextsService; import cz.incad.kramerius.utils.ApplicationURL; /** * This servlet produces bundles as properties or as xml via http protocol. <br> * This is useful for xslt transformations * * @author pavels */ public class I18NServlet extends GuiceServlet { public static final java.util.logging.Logger LOGGER = java.util.logging.Logger .getLogger(I18NServlet.class.getName()); @Inject TextsService textsService; @Inject ResourceBundleService resourceBundleService; @Inject GeneratePDFService generatePDFService; @Inject Provider<Locale> provider; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = req.getParameter("action"); if (action == null) action = Actions.text.name(); Actions selectedAction = Actions.valueOf(action); selectedAction.doAction(getServletContext(), req, resp, this.textsService, this.resourceBundleService, this.provider); } public static String i18nServlet(HttpServletRequest request) { return ApplicationURL.urlOfPath(request, InternalConfiguration.get() .getProperties().getProperty("servlets.mapping.i18n")); } static enum Formats { xml, json; public static Formats find(String val) { Formats[] vals = values(); for (Formats f : vals) { if (f.name().equals(val)) return f; } return xml; } } static enum Actions { text { @Override public void doAction(ServletContext context, HttpServletRequest req, HttpServletResponse resp, TextsService tserv, ResourceBundleService rserv, Provider<Locale> provider) { try { String parameter = req.getParameter("name"); String format = req.getParameter("format"); Locale locale = locale(req, provider); String text = tserv.getText(parameter, locale); Formats foundFormat = Formats.find(format); if (foundFormat == Formats.xml) { StringBuffer formatBundle = formatTextToXML(text, parameter); resp.setContentType("application/xhtml+xml"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().write(formatBundle.toString()); } else { String json = formatTextToJSON(text, parameter); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json"); resp.getWriter().write(json); } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException e1) { } } } }, bundle { @Override public void doAction(ServletContext context, HttpServletRequest req, HttpServletResponse resp, TextsService tserv, ResourceBundleService rserv, Provider<Locale> provider) { try { String parameter = req.getParameter("name"); String format = req.getParameter("format"); Locale locale = locale(req, provider); ResourceBundle resourceBundle = rserv.getResourceBundle( parameter, locale); Formats foundFormat = Formats.find(format); String renderedBundle = null; if (foundFormat == Formats.xml) { renderedBundle = formatBundleToXML(resourceBundle, parameter).toString(); resp.setContentType("application/xhtml+xml"); } else { resp.setContentType("application/json"); renderedBundle = formatBundleToJSON(resourceBundle, parameter); } resp.setCharacterEncoding("UTF-8"); resp.getWriter().write(renderedBundle); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException e1) { } } } }; abstract void doAction(ServletContext context, HttpServletRequest req, HttpServletResponse resp, TextsService tserv, ResourceBundleService rserv, Provider<Locale> provider); static Locale locale(HttpServletRequest req, Provider<Locale> provider) { String lang = req.getParameter("lang"); String country = req.getParameter("country"); if ((lang != null) && (country != null)) { Locale locale = new Locale(lang, country); return locale; } else { return provider.get(); } } static String formatBundleToJSON(ResourceBundle bundle, String bundleName) { Map<String, String> map = new HashMap<String, String>(); Set<String> keySet = bundle.keySet(); for (String key : keySet) { String changedValue = bundle.getString(key); if (changedValue.contains("\"")) { changedValue = changedValue.replace("\"", "\\\""); } changedValue = changedValue.replace("\n", "\\n"); map.put(key, changedValue); } StringTemplate template = new StringTemplate( "{\"bundle\":{\n" + " $bundle.keys:{k| \"$k$\":\"$bundle.(k)$\" };separator=\",\\n\"$" + "\n}}"); template.setAttribute("bundle", map); return template.toString(); } static StringBuffer formatBundleToXML(ResourceBundle bundle, String bundleName) { StringBuffer buffer = new StringBuffer( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<bundle name='").append(bundleName).append("'>\n"); Set<String> keySet = bundle.keySet(); for (String key : keySet) { buffer.append("<value key='" + key + "'>") .append(bundle.getString(key)).append("</value>"); } buffer.append("\n</bundle>"); return buffer; } static StringBuffer formatTextToXML(String text, String textName) { StringBuffer buffer = new StringBuffer( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<text name='").append(textName).append("'>\n"); buffer.append(text); buffer.append("\n</text>"); return buffer; } static String formatTextToJSON(String text, String textName) { Map<String, String> map = new HashMap<String, String>(); map.put("name", textName); String escaped = StringEscapeUtils.escapeJson(text); map.put("value", escaped); StringTemplate template = new StringTemplate("{\"text\":{\n" + " \"name\":\"$data.name$\"," + " \"value\":\"$data.value$\"" + "\n}}"); template.setAttribute("data", map); return template.toString(); } } }
ceskaexpedice/kramerius
search/src/java/cz/incad/Kramerius/I18NServlet.java
Java
gpl-3.0
9,063
/* Copyright 2013 Red Hat, Inc. and/or its affiliates. This file is part of lightblue. 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 com.redhat.lightblue.mongo.crud; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; /** * Sequence generation using a MongoDB collection. * * Each sequence is a document uniquely identified by the sequence name. The * document contains initial value for the sequence, the increment, and the * value. */ public class MongoSequenceGenerator { public static final String NAME = "name"; public static final String INIT = "initialValue"; public static final String INC = "increment"; public static final String VALUE = "value"; private static final Logger LOGGER = LoggerFactory.getLogger(MongoSequenceGenerator.class); private final DBCollection coll; // a set of sequances collections which were already initialized private static Set<String> initializedCollections = new CopyOnWriteArraySet<>(); public MongoSequenceGenerator(DBCollection coll) { this.coll = coll; if (!initializedCollections.contains(coll.getFullName())) { // Here, we also make sure we have the indexes setup properly initIndex(); initializedCollections.add(coll.getFullName()); LOGGER.info("Initialized sequances collection {}", coll.getFullName()); } } private void initIndex() { // Make sure we have a unique index on name BasicDBObject keys = new BasicDBObject(NAME, 1); BasicDBObject options = new BasicDBObject("unique", 1); // ensureIndex was deprecated, changed to an alias of createIndex, and removed in a more recent version coll.createIndex(keys, options); } /** * Atomically increments and returns the sequence value. If this is the * first use of the sequence, the sequence is created * * @param name The sequence name * @param init The initial value of the sequence. Used only if the sequence * does not exists prior to this call * @param inc The increment, Could be negative or positive. If 0, it is * assumed to be 1. Used only if the sequence does not exist prior to this * call * * If the sequence already exists, the <code>init</code> and * <code>inc</code> are ignored. * * @return The value of the sequence before the call */ public long getNextSequenceValue(String name, long init, long inc) { LOGGER.debug("getNextSequenceValue({})", name); // Read the sequence document BasicDBObject q = new BasicDBObject(NAME, name); DBObject doc = coll.findOne(q,null,ReadPreference.primary()); if (doc == null) { // Sequence document does not exist. Insert a new document using the init and inc LOGGER.debug("inserting sequence record name={}, init={}, inc={}", name, init, inc); if (inc == 0) { inc = 1; } BasicDBObject u = new BasicDBObject(). append(NAME, name). append(INIT, init). append(INC, inc). append(VALUE, init); try { coll.insert(u, WriteConcern.ACKNOWLEDGED); } catch (Exception e) { // Someone else might have inserted already, try to re-read LOGGER.debug("Insertion failed with {}, trying to read", e); } doc = coll.findOne(q,null,ReadPreference.primary()); if (doc == null) { throw new RuntimeException("Cannot generate value for " + name); } } LOGGER.debug("Sequence doc={}", doc); Long increment = (Long) doc.get(INC); BasicDBObject u = new BasicDBObject(). append("$inc", new BasicDBObject(VALUE, increment)); // This call returns the unmodified document doc = coll.findAndModify(q, u); Long l = (Long) doc.get(VALUE); LOGGER.debug("{} -> {}", name, l); return l; } }
bserdar/lightblue-mongo
mongo/src/main/java/com/redhat/lightblue/mongo/crud/MongoSequenceGenerator.java
Java
gpl-3.0
4,918
<?php namespace Drupal\search_api_test_backend\Plugin\search_api\data_type; use Drupal\search_api\DataType\DataTypePluginBase; /** * Provides a dummy data type for testing purposes. * * @SearchApiDataType( * id = "search_api_test_data_type", * label = @Translation("Test data type"), * description = @Translation("Dummy data type implementation") * ) */ class TestDataType extends DataTypePluginBase { }
willroche/astonmartin
modules/search_api/tests/search_api_test_backend/src/Plugin/search_api/data_type/TestDataType.php
PHP
gpl-3.0
422
<?php /** * PEAR_Command_Install (install, upgrade, upgrade-all, uninstall, bundle, run-scripts commands) * * 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 Greg Beaver <cellog@php.net> * @copyright 1997-2006 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: Install.php,v 1.115 2006/03/02 18:14:13 cellog Exp $ * @link http://pear.php.net/package/PEAR * @since File available since Release 0.1 */ /** * base class */ require_once 'PEAR/Command/Common.php'; /** * PEAR commands for installation or deinstallation/upgrading of * packages. * * @category pear * @package PEAR * @author Stig Bakken <ssb@php.net> * @author Greg Beaver <cellog@php.net> * @copyright 1997-2006 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: 1.4.9 * @link http://pear.php.net/package/PEAR * @since Class available since Release 0.1 */ class PEAR_Command_Install extends PEAR_Command_Common { // {{{ properties var $commands = array( 'install' => array( 'summary' => 'Install Package', 'function' => 'doInstall', 'shortcut' => 'i', 'options' => array( 'force' => array( 'shortopt' => 'f', 'doc' => 'will overwrite newer installed packages', ), 'loose' => array( 'shortopt' => 'l', 'doc' => 'do not check for recommended dependency version', ), 'nodeps' => array( 'shortopt' => 'n', 'doc' => 'ignore dependencies, install anyway', ), 'register-only' => array( 'shortopt' => 'r', 'doc' => 'do not install files, only register the package as installed', ), 'soft' => array( 'shortopt' => 's', 'doc' => 'soft install, fail silently, or upgrade if already installed', ), 'nobuild' => array( 'shortopt' => 'B', 'doc' => 'don\'t build C extensions', ), 'nocompress' => array( 'shortopt' => 'Z', 'doc' => 'request uncompressed files when downloading', ), 'installroot' => array( 'shortopt' => 'R', 'arg' => 'DIR', 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT), use packagingroot for RPM', ), 'packagingroot' => array( 'shortopt' => 'P', 'arg' => 'DIR', 'doc' => 'root directory used when packaging files, like RPM packaging', ), 'ignore-errors' => array( 'doc' => 'force install even if there were errors', ), 'alldeps' => array( 'shortopt' => 'a', 'doc' => 'install all required and optional dependencies', ), 'onlyreqdeps' => array( 'shortopt' => 'o', 'doc' => 'install all required dependencies', ), 'offline' => array( 'shortopt' => 'O', 'doc' => 'do not attempt to download any urls or contact channels', ), 'pretend' => array( 'shortopt' => 'p', 'doc' => 'Only list the packages that would be downloaded', ), ), 'doc' => '[channel/]<package> ... Installs one or more PEAR packages. You can specify a package to install in four ways: "Package-1.0.tgz" : installs from a local file "http://example.com/Package-1.0.tgz" : installs from anywhere on the net. "package.xml" : installs the package described in package.xml. Useful for testing, or for wrapping a PEAR package in another package manager such as RPM. "Package[-version/state][.tar]" : queries your default channel\'s server ({config master_server}) and downloads the newest package with the preferred quality/state ({config preferred_state}). To retrieve Package version 1.1, use "Package-1.1," to retrieve Package state beta, use "Package-beta." To retrieve an uncompressed file, append .tar (make sure there is no file by the same name first) To download a package from another channel, prefix with the channel name like "channel/Package" More than one package may be specified at once. It is ok to mix these four ways of specifying packages. '), 'upgrade' => array( 'summary' => 'Upgrade Package', 'function' => 'doInstall', 'shortcut' => 'up', 'options' => array( 'force' => array( 'shortopt' => 'f', 'doc' => 'overwrite newer installed packages', ), 'loose' => array( 'shortopt' => 'l', 'doc' => 'do not check for recommended dependency version', ), 'nodeps' => array( 'shortopt' => 'n', 'doc' => 'ignore dependencies, upgrade anyway', ), 'register-only' => array( 'shortopt' => 'r', 'doc' => 'do not install files, only register the package as upgraded', ), 'nobuild' => array( 'shortopt' => 'B', 'doc' => 'don\'t build C extensions', ), 'nocompress' => array( 'shortopt' => 'Z', 'doc' => 'request uncompressed files when downloading', ), 'installroot' => array( 'shortopt' => 'R', 'arg' => 'DIR', 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT), use packagingroot for RPM', ), 'packagingroot' => array( 'shortopt' => 'P', 'arg' => 'DIR', 'doc' => 'root directory used when packaging files, like RPM packaging', ), 'ignore-errors' => array( 'doc' => 'force install even if there were errors', ), 'alldeps' => array( 'shortopt' => 'a', 'doc' => 'install all required and optional dependencies', ), 'onlyreqdeps' => array( 'shortopt' => 'o', 'doc' => 'install all required dependencies', ), 'offline' => array( 'shortopt' => 'O', 'doc' => 'do not attempt to download any urls or contact channels', ), 'pretend' => array( 'shortopt' => 'p', 'doc' => 'Only list the packages that would be downloaded', ), ), 'doc' => '<package> ... Upgrades one or more PEAR packages. See documentation for the "install" command for ways to specify a package. When upgrading, your package will be updated if the provided new package has a higher version number (use the -f option if you need to upgrade anyway). More than one package may be specified at once. '), 'upgrade-all' => array( 'summary' => 'Upgrade All Packages', 'function' => 'doInstall', 'shortcut' => 'ua', 'options' => array( 'nodeps' => array( 'shortopt' => 'n', 'doc' => 'ignore dependencies, upgrade anyway', ), 'register-only' => array( 'shortopt' => 'r', 'doc' => 'do not install files, only register the package as upgraded', ), 'nobuild' => array( 'shortopt' => 'B', 'doc' => 'don\'t build C extensions', ), 'nocompress' => array( 'shortopt' => 'Z', 'doc' => 'request uncompressed files when downloading', ), 'installroot' => array( 'shortopt' => 'R', 'arg' => 'DIR', 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT), use packagingroot for RPM', ), 'ignore-errors' => array( 'doc' => 'force install even if there were errors', ), 'loose' => array( 'doc' => 'do not check for recommended dependency version', ), ), 'doc' => ' Upgrades all packages that have a newer release available. Upgrades are done only if there is a release available of the state specified in "preferred_state" (currently {config preferred_state}), or a state considered more stable. '), 'uninstall' => array( 'summary' => 'Un-install Package', 'function' => 'doUninstall', 'shortcut' => 'un', 'options' => array( 'nodeps' => array( 'shortopt' => 'n', 'doc' => 'ignore dependencies, uninstall anyway', ), 'register-only' => array( 'shortopt' => 'r', 'doc' => 'do not remove files, only register the packages as not installed', ), 'installroot' => array( 'shortopt' => 'R', 'arg' => 'DIR', 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', ), 'ignore-errors' => array( 'doc' => 'force install even if there were errors', ), 'offline' => array( 'shortopt' => 'O', 'doc' => 'do not attempt to uninstall remotely', ), ), 'doc' => '[channel/]<package> ... Uninstalls one or more PEAR packages. More than one package may be specified at once. Prefix with channel name to uninstall from a channel not in your default channel ({config default_channel}) '), 'bundle' => array( 'summary' => 'Unpacks a Pecl Package', 'function' => 'doBundle', 'shortcut' => 'bun', 'options' => array( 'destination' => array( 'shortopt' => 'd', 'arg' => 'DIR', 'doc' => 'Optional destination directory for unpacking (defaults to current path or "ext" if exists)', ), 'force' => array( 'shortopt' => 'f', 'doc' => 'Force the unpacking even if there were errors in the package', ), ), 'doc' => '<package> Unpacks a Pecl Package into the selected location. It will download the package if needed. '), 'run-scripts' => array( 'summary' => 'Run Post-Install Scripts bundled with a package', 'function' => 'doRunScripts', 'shortcut' => 'rs', 'options' => array( ), 'doc' => '<package> Run post-installation scripts in package <package>, if any exist. '), ); // }}} // {{{ constructor /** * PEAR_Command_Install constructor. * * @access public */ function PEAR_Command_Install(&$ui, &$config) { parent::PEAR_Command_Common($ui, $config); } // }}} /** * For unit testing purposes */ function &getDownloader(&$ui, $options, &$config) { if (!class_exists('PEAR_Downloader')) { require_once 'PEAR/Downloader.php'; } $a = &new PEAR_Downloader($ui, $options, $config); return $a; } /** * For unit testing purposes */ function &getInstaller(&$ui) { if (!class_exists('PEAR_Installer')) { require_once 'PEAR/Installer.php'; } $a = &new PEAR_Installer($ui); return $a; } // {{{ doInstall() function doInstall($command, $options, $params) { if (empty($this->installer)) { $this->installer = &$this->getInstaller($this->ui); } if ($command == 'upgrade') { $options['upgrade'] = true; } if (isset($options['installroot']) && isset($options['packagingroot'])) { return $this->raiseError('ERROR: cannot use both --installroot and --packagingroot'); } if (isset($options['packagingroot']) && $this->config->get('verbose') > 2) { $this->ui->outputData('using package root: ' . $options['packagingroot']); } $reg = &$this->config->getRegistry(); if ($command == 'upgrade-all') { $options['upgrade'] = true; $reg = &$this->config->getRegistry(); $savechannel = $this->config->get('default_channel'); $params = array(); foreach ($reg->listChannels() as $channel) { if ($channel == '__uri') { continue; } $this->config->set('default_channel', $channel); $chan = &$reg->getChannel($channel); if (PEAR::isError($chan)) { return $this->raiseError($chan); } if ($chan->supportsREST($this->config->get('preferred_mirror')) && $base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror'))) { $dorest = true; unset($remote); } else { $dorest = false; $remote = &$this->config->getRemote($this->config); } $state = $this->config->get('preferred_state'); $installed = array_flip($reg->listPackages($channel)); PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN); if ($dorest) { $rest = &$this->config->getREST('1.0', array()); $latest = $rest->listLatestUpgrades($base, $state, $installed, $channel, $reg); } else { if (empty($state) || $state == 'any') { $latest = $remote->call("package.listLatestReleases"); } else { $latest = $remote->call("package.listLatestReleases", $state); } } PEAR::staticPopErrorHandling(); if (PEAR::isError($latest) || !is_array($latest)) { continue; } foreach ($latest as $package => $info) { $package = strtolower($package); if (!isset($installed[$package])) { // skip packages we don't have installed continue; } $inst_version = $reg->packageInfo($package, 'version', $channel); if (version_compare("$info[version]", "$inst_version", "le")) { // installed version is up-to-date continue; } $params[] = $reg->parsedPackageNameToString(array('package' => $package, 'channel' => $channel)); $this->ui->outputData(array('data' => "Will upgrade $package"), $command); } } $this->config->set('default_channel', $savechannel); } $this->downloader = &$this->getDownloader($this->ui, $options, $this->config); $errors = array(); $downloaded = array(); $downloaded = &$this->downloader->download($params); $errors = $this->downloader->getErrorMsgs(); if (count($errors)) { foreach ($errors as $error) { $err['data'][] = array($error); } $err['headline'] = 'Install Errors'; $this->ui->outputData($err); if (!count($downloaded)) { return $this->raiseError("$command failed"); } } $data = array( 'headline' => 'Packages that would be Installed' ); if (isset($options['pretend'])) { foreach ($downloaded as $package) { $data['data'][] = array($reg->parsedPackageNameToString($package->getParsedPackage())); } $this->ui->outputData($data, 'pretend'); return true; } $this->installer->setOptions($options); $this->installer->sortPackagesForInstall($downloaded); if (PEAR::isError($err = $this->installer->setDownloadedPackages($downloaded))) { $this->raiseError($err->getMessage()); return true; } $extrainfo = array(); foreach ($downloaded as $param) { PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN); $info = $this->installer->install($param, $options); PEAR::staticPopErrorHandling(); if (PEAR::isError($info)) { $oldinfo = $info; $pkg = &$param->getPackageFile(); if ($info->getCode() != PEAR_INSTALLER_NOBINARY) { if (!($info = $pkg->installBinary($this->installer))) { $this->ui->outputData('ERROR: ' .$oldinfo->getMessage()); continue; } // we just installed a different package than requested, // let's change the param and info so that the rest of this works $param = $info[0]; $info = $info[1]; } } if (is_array($info)) { if ($param->getPackageType() == 'extsrc' || $param->getPackageType() == 'extbin') { $pkg = &$param->getPackageFile(); if ($instbin = $pkg->getInstalledBinary()) { $instpkg = &$reg->getPackage($instbin, $pkg->getChannel()); } else { $instpkg = &$reg->getPackage($pkg->getPackage(), $pkg->getChannel()); } foreach ($instpkg->getFilelist() as $name => $atts) { $pinfo = pathinfo($atts['installed_as']); if (!isset($pinfo['extension']) || in_array($pinfo['extension'], array('c', 'h'))) { continue; // make sure we don't match php_blah.h } if ((strpos($pinfo['basename'], 'php_') === 0 && $pinfo['extension'] == 'dll') || // most unices $pinfo['extension'] == 'so' || // hp-ux $pinfo['extension'] == 'sl') { $extrainfo[] = 'You should add "extension=' . $pinfo['basename'] . '" to php.ini'; break; } } } if ($this->config->get('verbose') > 0) { $channel = $param->getChannel(); $label = $reg->parsedPackageNameToString( array( 'channel' => $channel, 'package' => $param->getPackage(), 'version' => $param->getVersion(), )); $out = array('data' => "$command ok: $label"); if (isset($info['release_warnings'])) { $out['release_warnings'] = $info['release_warnings']; } $this->ui->outputData($out, $command); if (!isset($options['register-only']) && !isset($options['offline'])) { if ($this->config->isDefinedLayer('ftp')) { PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN); $info = $this->installer->ftpInstall($param); PEAR::staticPopErrorHandling(); if (PEAR::isError($info)) { $this->ui->outputData($info->getMessage()); $this->ui->outputData("remote install failed: $label"); } else { $this->ui->outputData("remote install ok: $label"); } } } } $deps = $param->getDeps(); if ($deps) { if (isset($deps['group'])) { $groups = $deps['group']; if (!isset($groups[0])) { $groups = array($groups); } foreach ($groups as $group) { if ($group['attribs']['name'] == 'default') { // default group is always installed, unless the user // explicitly chooses to install another group continue; } $this->ui->outputData($param->getPackage() . ': Optional feature ' . $group['attribs']['name'] . ' available (' . $group['attribs']['hint'] . ')'); } $extrainfo[] = 'To install use "pear install ' . $reg->parsedPackageNameToString( array('package' => $param->getPackage(), 'channel' => $param->getChannel()), true) . '#featurename"'; } } if (isset($options['installroot'])) { $reg = &$this->config->getRegistry(); } $pkg = &$reg->getPackage($param->getPackage(), $param->getChannel()); // $pkg may be NULL if install is a 'fake' install via --packagingroot if (is_object($pkg)) { $pkg->setConfig($this->config); if ($list = $pkg->listPostinstallScripts()) { $pn = $reg->parsedPackageNameToString(array('channel' => $param->getChannel(), 'package' => $param->getPackage()), true); $extrainfo[] = $pn . ' has post-install scripts:'; foreach ($list as $file) { $extrainfo[] = $file; } $extrainfo[] = 'Use "pear run-scripts ' . $pn . '" to run'; $extrainfo[] = 'DO NOT RUN SCRIPTS FROM UNTRUSTED SOURCES'; } } } else { return $this->raiseError("$command failed"); } } if (count($extrainfo)) { foreach ($extrainfo as $info) { $this->ui->outputData($info); } } return true; } // }}} // {{{ doUninstall() function doUninstall($command, $options, $params) { if (empty($this->installer)) { $this->installer = &$this->getInstaller($this->ui); } if (isset($options['remoteconfig'])) { $e = $this->config->readFTPConfigFile($options['remoteconfig']); if (!PEAR::isError($e)) { $this->installer->setConfig($this->config); } } if (sizeof($params) < 1) { return $this->raiseError("Please supply the package(s) you want to uninstall"); } $reg = &$this->config->getRegistry(); $newparams = array(); $badparams = array(); foreach ($params as $pkg) { $channel = $this->config->get('default_channel'); PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN); $parsed = $reg->parsePackageName($pkg, $channel); PEAR::staticPopErrorHandling(); if (!$parsed || PEAR::isError($parsed)) { $badparams[] = $pkg; continue; } $package = $parsed['package']; $channel = $parsed['channel']; $info = &$reg->getPackage($package, $channel); if ($info === null && ($channel == 'pear.php.net' || $channel == 'pecl.php.net')) { // make sure this isn't a package that has flipped from pear to pecl but // used a package.xml 1.0 $testc = ($channel == 'pear.php.net') ? 'pecl.php.net' : 'pear.php.net'; $info = &$reg->getPackage($package, $testc); if ($info !== null) { $channel = $testc; } } if ($info === null) { $badparams[] = $pkg; } else { $newparams[] = &$info; // check for binary packages (this is an alias for those packages if so) if ($installedbinary = $info->getInstalledBinary()) { $this->ui->log('adding binary package ' . $reg->parsedPackageNameToString(array('channel' => $channel, 'package' => $installedbinary), true)); $newparams[] = &$reg->getPackage($installedbinary, $channel); } // add the contents of a dependency group to the list of installed packages if (isset($parsed['group'])) { $group = $info->getDependencyGroup($parsed['group']); if ($group) { $installed = &$reg->getInstalledGroup($group); if ($installed) { foreach ($installed as $i => $p) { $newparams[] = &$installed[$i]; } } } } } } $err = $this->installer->sortPackagesForUninstall($newparams); if (PEAR::isError($err)) { $this->ui->outputData($err->getMessage(), $command); return true; } $params = $newparams; // twist this to use it to check on whether dependent packages are also being uninstalled // for circular dependencies like subpackages $this->installer->setUninstallPackages($newparams); $params = array_merge($params, $badparams); foreach ($params as $pkg) { $this->installer->pushErrorHandling(PEAR_ERROR_RETURN); if ($err = $this->installer->uninstall($pkg, $options)) { $this->installer->popErrorHandling(); if (PEAR::isError($err)) { $this->ui->outputData($err->getMessage(), $command); continue; } $savepkg = $pkg; if ($this->config->get('verbose') > 0) { if (is_object($pkg)) { $pkg = $reg->parsedPackageNameToString($pkg); } $this->ui->outputData("uninstall ok: $pkg", $command); } if (!isset($options['offline']) && is_object($savepkg) && defined('PEAR_REMOTEINSTALL_OK')) { if ($this->config->isDefinedLayer('ftp')) { $this->installer->pushErrorHandling(PEAR_ERROR_RETURN); $info = $this->installer->ftpUninstall($savepkg); $this->installer->popErrorHandling(); if (PEAR::isError($info)) { $this->ui->outputData($info->getMessage()); $this->ui->outputData("remote uninstall failed: $pkg"); } else { $this->ui->outputData("remote uninstall ok: $pkg"); } } } } else { $this->installer->popErrorHandling(); if (is_object($pkg)) { $pkg = $reg->parsedPackageNameToString($pkg); } return $this->raiseError("uninstall failed: $pkg"); } } return true; } // }}} // }}} // {{{ doBundle() /* (cox) It just downloads and untars the package, does not do any check that the PEAR_Installer::_installFile() does. */ function doBundle($command, $options, $params) { $downloader = &$this->getDownloader($this->ui, array('force' => true, 'nodeps' => true, 'soft' => true), $this->config); $reg = &$this->config->getRegistry(); if (sizeof($params) < 1) { return $this->raiseError("Please supply the package you want to bundle"); } if (isset($options['destination'])) { if (!is_dir($options['destination'])) { System::mkdir('-p ' . $options['destination']); } $dest = realpath($options['destination']); } else { $pwd = getcwd(); if (is_dir($pwd . DIRECTORY_SEPARATOR . 'ext')) { $dest = $pwd . DIRECTORY_SEPARATOR . 'ext'; } else { $dest = $pwd; } } $downloader->setDownloadDir($dest); $result = &$downloader->download(array($params[0])); if (PEAR::isError($result)) { return $result; } $pkgfile = &$result[0]->getPackageFile(); $pkgname = $pkgfile->getName(); $pkgversion = $pkgfile->getVersion(); // Unpacking ------------------------------------------------- $dest .= DIRECTORY_SEPARATOR . $pkgname; $orig = $pkgname . '-' . $pkgversion; $tar = &new Archive_Tar($pkgfile->getArchiveFile()); if (!@$tar->extractModify($dest, $orig)) { return $this->raiseError('unable to unpack ' . $pkgfile->getArchiveFile()); } $this->ui->outputData("Package ready at '$dest'"); // }}} } // }}} function doRunScripts($command, $options, $params) { if (!isset($params[0])) { return $this->raiseError('run-scripts expects 1 parameter: a package name'); } $reg = &$this->config->getRegistry(); PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN); $parsed = $reg->parsePackageName($params[0], $this->config->get('default_channel')); PEAR::staticPopErrorHandling(); if (PEAR::isError($parsed)) { return $this->raiseError($parsed); } $package = &$reg->getPackage($parsed['package'], $parsed['channel']); if (is_object($package)) { $package->setConfig($this->config); $package->runPostinstallScripts(); } else { return $this->raiseError('Could not retrieve package "' . $params[0] . '" from registry'); } $this->ui->outputData('Install scripts complete', $command); return true; } } ?>
syboor/openimsce
openims/libs/pear/PEAR/Command/Install.php
PHP
gpl-3.0
32,608
package org.thoughtcrime.securesms.ringrtc; import android.annotation.TargetApi; import android.content.Context; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CameraMetadata; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.annimon.stream.Stream; import org.signal.core.util.logging.Log; import org.signal.ringrtc.CameraControl; import org.thoughtcrime.securesms.components.webrtc.EglBaseWrapper; import org.webrtc.Camera1Enumerator; import org.webrtc.Camera2Capturer; import org.webrtc.Camera2Enumerator; import org.webrtc.CameraEnumerator; import org.webrtc.CameraVideoCapturer; import org.webrtc.CapturerObserver; import org.webrtc.SurfaceTextureHelper; import org.webrtc.VideoFrame; import java.util.LinkedList; import java.util.List; import static org.thoughtcrime.securesms.ringrtc.CameraState.Direction.BACK; import static org.thoughtcrime.securesms.ringrtc.CameraState.Direction.FRONT; import static org.thoughtcrime.securesms.ringrtc.CameraState.Direction.NONE; import static org.thoughtcrime.securesms.ringrtc.CameraState.Direction.PENDING; /** * Encapsulate the camera functionality needed for video calling. */ public class Camera implements CameraControl, CameraVideoCapturer.CameraSwitchHandler { private static final String TAG = Log.tag(Camera.class); @NonNull private final Context context; @Nullable private final CameraVideoCapturer capturer; @NonNull private final CameraEventListener cameraEventListener; @NonNull private final EglBaseWrapper eglBase; private final int cameraCount; @NonNull private CameraState.Direction activeDirection; private boolean enabled; private boolean isInitialized; private int orientation; public Camera(@NonNull Context context, @NonNull CameraEventListener cameraEventListener, @NonNull EglBaseWrapper eglBase, @NonNull CameraState.Direction desiredCameraDirection) { this.context = context; this.cameraEventListener = cameraEventListener; this.eglBase = eglBase; CameraEnumerator enumerator = getCameraEnumerator(context); cameraCount = enumerator.getDeviceNames().length; CameraState.Direction firstChoice = desiredCameraDirection.isUsable() ? desiredCameraDirection : FRONT; CameraVideoCapturer capturerCandidate = createVideoCapturer(enumerator, firstChoice); if (capturerCandidate != null) { activeDirection = firstChoice; } else { CameraState.Direction secondChoice = firstChoice.switchDirection(); capturerCandidate = createVideoCapturer(enumerator, secondChoice); if (capturerCandidate != null) { activeDirection = secondChoice; } else { activeDirection = NONE; } } capturer = capturerCandidate; } @Override public void initCapturer(@NonNull CapturerObserver observer) { if (capturer != null) { eglBase.performWithValidEglBase(base -> { capturer.initialize(SurfaceTextureHelper.create("WebRTC-SurfaceTextureHelper", base.getEglBaseContext()), context, new CameraCapturerWrapper(observer)); capturer.setOrientation(orientation); isInitialized = true; }); } } @Override public boolean hasCapturer() { return capturer != null; } @Override public void flip() { if (capturer == null || cameraCount < 2) { throw new AssertionError("Tried to flip the camera, but we only have " + cameraCount + " of them."); } activeDirection = PENDING; capturer.switchCamera(this); } @Override public void setOrientation(@Nullable Integer orientation) { this.orientation = orientation; if (isInitialized && capturer != null) { capturer.setOrientation(orientation); } } @Override public void setEnabled(boolean enabled) { Log.i(TAG, "setEnabled(): " + enabled); this.enabled = enabled; if (capturer == null) { return; } try { if (enabled) { Log.i(TAG, "setEnabled(): starting capture"); capturer.startCapture(1280, 720, 30); } else { Log.i(TAG, "setEnabled(): stopping capture"); capturer.stopCapture(); } } catch (InterruptedException e) { Log.w(TAG, "Got interrupted while trying to stop video capture", e); } } public void dispose() { if (capturer != null) { capturer.dispose(); isInitialized = false; } } int getCount() { return cameraCount; } @NonNull CameraState.Direction getActiveDirection() { return enabled ? activeDirection : NONE; } @NonNull public CameraState getCameraState() { return new CameraState(getActiveDirection(), getCount()); } @Nullable CameraVideoCapturer getCapturer() { return capturer; } public boolean isInitialized() { return isInitialized; } private @Nullable CameraVideoCapturer createVideoCapturer(@NonNull CameraEnumerator enumerator, @NonNull CameraState.Direction direction) { String[] deviceNames = enumerator.getDeviceNames(); for (String deviceName : deviceNames) { if ((direction == FRONT && enumerator.isFrontFacing(deviceName)) || (direction == BACK && enumerator.isBackFacing(deviceName))) { return enumerator.createCapturer(deviceName, null); } } return null; } private @NonNull CameraEnumerator getCameraEnumerator(@NonNull Context context) { boolean camera2EnumeratorIsSupported = false; try { camera2EnumeratorIsSupported = Camera2Enumerator.isSupported(context); } catch (final Throwable throwable) { Log.w(TAG, "Camera2Enumator.isSupport() threw.", throwable); } Log.i(TAG, "Camera2 enumerator supported: " + camera2EnumeratorIsSupported); return camera2EnumeratorIsSupported ? new FilteredCamera2Enumerator(context) : new Camera1Enumerator(true); } @Override public void onCameraSwitchDone(boolean isFrontFacing) { activeDirection = isFrontFacing ? FRONT : BACK; cameraEventListener.onCameraSwitchCompleted(new CameraState(getActiveDirection(), getCount())); } @Override public void onCameraSwitchError(String errorMessage) { Log.e(TAG, "onCameraSwitchError: " + errorMessage); cameraEventListener.onCameraSwitchCompleted(new CameraState(getActiveDirection(), getCount())); } @TargetApi(21) private static class FilteredCamera2Enumerator extends Camera2Enumerator { private static final String TAG = Log.tag(Camera2Enumerator.class); @NonNull private final Context context; @Nullable private final CameraManager cameraManager; @Nullable private String[] deviceNames; FilteredCamera2Enumerator(@NonNull Context context) { super(context); this.context = context; this.cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); this.deviceNames = null; } private static boolean isMonochrome(@NonNull String deviceName, @NonNull CameraManager cameraManager) { try { CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(deviceName); int[] capabilities = characteristics.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES); if (capabilities != null) { for (int capability : capabilities) { if (capability == CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) { return true; } } } } catch (CameraAccessException e) { return false; } return false; } private static boolean isLensFacing(@NonNull String deviceName, @NonNull CameraManager cameraManager, @NonNull Integer facing) { try { CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(deviceName); Integer lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING); return facing.equals(lensFacing); } catch (CameraAccessException e) { return false; } } @Override public @NonNull String[] getDeviceNames() { if (deviceNames != null) { return deviceNames; } try { List<String> cameraList = new LinkedList<>(); if (cameraManager != null) { List<String> devices = Stream.of(cameraManager.getCameraIdList()) .filterNot(id -> isMonochrome(id, cameraManager)) .toList(); String frontCamera = Stream.of(devices) .filter(id -> isLensFacing(id, cameraManager, CameraMetadata.LENS_FACING_FRONT)) .findFirst() .orElse(null); if (frontCamera != null) { cameraList.add(frontCamera); } String backCamera = Stream.of(devices) .filter(id -> isLensFacing(id, cameraManager, CameraMetadata.LENS_FACING_BACK)) .findFirst() .orElse(null); if (backCamera != null) { cameraList.add(backCamera); } } this.deviceNames = cameraList.toArray(new String[0]); } catch (CameraAccessException e) { Log.e(TAG, "Camera access exception: " + e); this.deviceNames = new String[] {}; } return deviceNames; } @Override public @NonNull CameraVideoCapturer createCapturer(@Nullable String deviceName, @Nullable CameraVideoCapturer.CameraEventsHandler eventsHandler) { return new Camera2Capturer(context, deviceName, eventsHandler, new FilteredCamera2Enumerator(context)); } } private class CameraCapturerWrapper implements CapturerObserver { private final CapturerObserver observer; public CameraCapturerWrapper(@NonNull CapturerObserver observer) { this.observer = observer; } @Override public void onCapturerStarted(boolean success) { observer.onCapturerStarted(success); if (success) { cameraEventListener.onFullyInitialized(); } } @Override public void onCapturerStopped() { observer.onCapturerStopped(); } @Override public void onFrameCaptured(VideoFrame videoFrame) { observer.onFrameCaptured(videoFrame); } } }
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/ringrtc/Camera.java
Java
gpl-3.0
10,995
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * 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 com.watabou.pixeldungeon.effects; import com.watabou.noosa.Image; import com.watabou.pixeldungeon.Assets; public class BannerSprites { public enum Type { PIXEL_DUNGEON, BOSS_SLAIN, GAME_OVER, SELECT_YOUR_HERO }; public static Image get( Type type ) { Image icon = new Image( Assets.BANNERS ); switch (type) { case PIXEL_DUNGEON: icon.frame( icon.texture.uvRect( 0, 0, 128, 70 ) ); break; case BOSS_SLAIN: icon.frame( icon.texture.uvRect( 0, 70, 128, 105 ) ); break; case GAME_OVER: icon.frame( icon.texture.uvRect( 0, 105, 128, 140 ) ); break; case SELECT_YOUR_HERO: icon.frame( icon.texture.uvRect( 0, 140, 128, 161 ) ); break; } return icon; } }
sloanr333/opd-vanilla
src/com/watabou/pixeldungeon/effects/BannerSprites.java
Java
gpl-3.0
1,425
<?php // $Id: insert_cloze.php,v 1.4 2013/18/03 define('NO_MOODLE_COOKIES', true); // Session not used here. require(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . '/config.php'); $PAGE->set_context(context_system::instance()); $PAGE->set_url('/lib/editor/tinymce/plugins/clozeeditor/dialog.php'); $stringmanager = get_string_manager(); $editor = get_texteditor('tinymce'); $plugin = $editor->get_plugin('clozeeditor'); $htmllang = get_html_lang(); header('Content-Type: text/html; charset=utf-8'); header('X-UA-Compatible: IE=edge'); ?> <!DOCTYPE html> <html <?php echo $htmllang ?> <head> <title><?php print_string('clozeeditor:desc', 'tinymce_clozeeditor'); ?></title> <script type="text/javascript" src="<?php echo $editor->get_tinymce_base_url(); ?>/tiny_mce_popup.js"></script> <script type="text/javascript" src="<?php echo $plugin->get_tinymce_file_url('js/dialog1.js'); ?>"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="<?php echo $plugin->get_tinymce_file_url('js/encode.js'); ?>"></script> <script type="text/javascript" src="<?php echo $plugin->get_tinymce_file_url('js/parse.js'); ?>"></script> <script type="text/javascript" src="<?php echo $plugin->get_tinymce_file_url('js/parseHelper.js'); ?>"></script> <script type="text/javascript" src="<?php echo $plugin->get_tinymce_file_url('js/parseAnswer.js'); ?>"></script> <script type="text/javascript" src="<?php echo $plugin->get_tinymce_file_url('js/parseFeedback.js'); ?>"></script> <script type="text/javascript" src="<?php echo $plugin->get_tinymce_file_url('js/parsePercentage.js'); ?>"></script> <script type="text/javascript" src="<?php echo $plugin->get_tinymce_file_url('js/parseThrottle.js'); ?>"></script> <script type="text/javascript" src="<?php echo $plugin->get_tinymce_file_url('js/popup.js'); ?>"></script> <link rel="stylesheet" type="text/css" href="dialog.css"> </head> <body onload="Init(); "> <form name="Formular"> <fieldset > <legend class="title">{#clozeeditor.titleclozeeditor}</legend> <label for="quiz_type">{#clozeeditor.chooseclozeformat}</label><br /> <select name="quizType" onchange="toggleThrottle(); " > <option value="SHORTANSWER"><?php echo get_string('shortanswer', 'quiz'); ?></option> <option value="SHORTANSWER_C"><?php echo get_string('shortanswer', 'quiz')." (".get_string('casesensitive', 'quiz').")"; ?></option> <option value="MULTICHOICE" ><?php echo get_string('layoutselectinline', 'qtype_multianswer'); ?></option> <option value="MULTICHOICE_V"><?php echo get_string('layoutvertical', 'qtype_multianswer'); ?></option> <option value="MULTICHOICE_H"><?php echo get_string('layouthorizontal', 'qtype_multianswer'); ?></option> <option value="NUMERICAL"><?php echo get_string('numerical', 'quiz'); ?></option> </select> <br /> <label for="weighting"><?php echo get_string('defaultgrade', 'quiz'); ?></label> <input size=4 type="text" name="weighting" style="margin-top: 8px; margin-bottom: 4px; " /> <br /> <table id="main_table"> <tbody> <tr> <td class="table_value"></td> <td class="table_value"><?php echo get_string('answer', 'moodle'); ?></td> <td class="table_value_throttle"><?php echo get_string('tolerance', 'qtype_calculated'); ?></td> <td class="table_value"><?php echo get_string('correct', 'quiz'); ?></td> <td class="table_value"><?php echo get_string('percentcorrect', 'quiz'); ?></td> <td class="table_value"><?php echo get_string('feedback', 'qtype_multichoice'); ?></td> </tr> </tbody> </table> <input type="button" name="addline" value="<?php echo get_string('addfields', 'form', 1); ?>" onclick="addRow('main_table');" style="margin-top: 5px; " /> <!-- <input type="button" name="formaction" value="encode" onclick="encode()" style="margin-left: 8px; margin-top: 5px; " /> --> <br /> <input type="text" name="output" style="display: none; width: 456px; margin-top: 8px; " /> </form> <form onsubmit="clozeeditorDialog.insert();return false;" action="#"> <div class="mceActionPanel"> <input type="button" id="insert" name="insert" value="{#insert}" onclick="clozeeditorDialog.insert();" /> <input type="button" id="cancel" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" /> </div> </form> </body> </html>
mcisse3007/moodle_esco_master
lib/editor/tinymce/plugins/clozeeditor/dialog.php
PHP
gpl-3.0
4,475
/* ### * IP: GHIDRA * * 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. */ // Lets user choose a specific FID database and output file, then, for every function, // dumps the executable domain path and function name. //@category FunctionID import java.io.*; import java.util.List; import ghidra.app.script.GhidraScript; import ghidra.feature.fid.db.*; import ghidra.util.Msg; import ghidra.util.exception.VersionException; public class ListFunctions extends GhidraScript { private void writeFunctions(FidDB fidDb, Writer outWriter) throws IOException { long hash = Long.MIN_VALUE; for (;;) { Long longObj = fidDb.findFullHashValueAtOrAfter(hash); if (longObj == null) { break; } hash = longObj.longValue() + 1; List<FunctionRecord> funcList = fidDb.findFunctionsByFullHash(longObj.longValue()); for (FunctionRecord rec : funcList) { outWriter.write(rec.getDomainPath()); outWriter.write(' '); outWriter.write(rec.getName()); outWriter.write('\n'); } } } @Override protected void run() throws Exception { FidFileManager fidFileManager = FidFileManager.getInstance(); List<FidFile> userFid = fidFileManager.getFidFiles(); if (userFid.isEmpty()) { return; } FidFile fidFile = askChoice("List Functions", "Choose FID database", userFid, userFid.get(0)); try (FidDB fidDb = fidFile.getFidDB(true)) { File outFile = askFile("Output file", "Choose output file: "); if (outFile == null) { return; } try (FileWriter out = new FileWriter(outFile)) { writeFunctions(fidDb, out); } } catch (VersionException e) { // Version upgrades are not supported Msg.showError(this, null, "Failed to open FidDb", "Failed to open incompatible FidDb (may need to regenerate with this version of Ghidra): " + fidFile.getPath()); return; } } }
cliffe/SecGen
modules/utilities/unix/audit_tools/ghidra/files/release/Ghidra/Features/FunctionID/ghidra_scripts/ListFunctions.java
Java
gpl-3.0
2,351
<?php /** * This file has been @generated by a phing task by {@link BuildMetadataPHPFromXml}. * See [README.md](README.md#generating-data) for more information. * * Pull requests changing data in these files will not be accepted. See the * [FAQ in the README](README.md#problems-with-invalid-numbers] on how to make * metadata changes. * * Do not modify this file directly! */ return array ( 'generalDesc' => array ( 'NationalNumberPattern' => '1\\d{2,3}', 'PossibleLength' => array ( 0 => 3, 1 => 4, ), 'PossibleLengthLocalOnly' => array ( ), ), 'tollFree' => array ( 'PossibleLength' => array ( 0 => -1, ), 'PossibleLengthLocalOnly' => array ( ), ), 'premiumRate' => array ( 'PossibleLength' => array ( 0 => -1, ), 'PossibleLengthLocalOnly' => array ( ), ), 'emergency' => array ( 'NationalNumberPattern' => '1(?:1[78]|220)', 'ExampleNumber' => '1220', 'PossibleLength' => array ( ), 'PossibleLengthLocalOnly' => array ( ), ), 'shortCode' => array ( 'NationalNumberPattern' => '1(?:1[478]|220)', 'ExampleNumber' => '117', 'PossibleLength' => array ( ), 'PossibleLengthLocalOnly' => array ( ), ), 'standardRate' => array ( 'PossibleLength' => array ( 0 => -1, ), 'PossibleLengthLocalOnly' => array ( ), ), 'carrierSpecific' => array ( 'PossibleLength' => array ( 0 => -1, ), 'PossibleLengthLocalOnly' => array ( ), ), 'smsServices' => array ( 'PossibleLength' => array ( 0 => -1, ), 'PossibleLengthLocalOnly' => array ( ), ), 'id' => 'CF', 'countryCode' => 0, 'internationalPrefix' => '', 'sameMobileAndFixedLinePattern' => false, 'numberFormat' => array ( ), 'intlNumberFormat' => array ( ), 'mainCountryForCode' => false, 'leadingZeroPossible' => false, 'mobileNumberPortableRegion' => false, );
FreePBX/contactmanager
vendor/giggsey/libphonenumber-for-php/src/data/ShortNumberMetadata_CF.php
PHP
gpl-3.0
2,064
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2012 OpenFOAM Foundation \\/ 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 3 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, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "fanFvPatchFields.H" #include "addToRunTimeSelectionTable.H" #include "volFields.H" #include "surfaceFields.H" #include "Tuple2.H" #include "polynomial.H" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // namespace Foam { makeTemplatePatchTypeField ( fvPatchScalarField, fanFvPatchScalarField ); } // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // template<> void Foam::fanFvPatchField<Foam::scalar>::calcFanJump() { if (this->cyclicPatch().owner()) { const surfaceScalarField& phi = db().lookupObject<surfaceScalarField>("phi"); const fvsPatchField<scalar>& phip = patch().patchField<surfaceScalarField, scalar>(phi); scalarField Un(max(phip/patch().magSf(), scalar(0))); if (phi.dimensions() == dimDensity*dimVelocity*dimArea) { Un /= patch().lookupPatchField<volScalarField, scalar>("rho"); } this->jump_ = max(this->jumpTable_->value(Un), scalar(0)); } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // template<> Foam::fanFvPatchField<Foam::scalar>::fanFvPatchField ( const fvPatch& p, const DimensionedField<scalar, volMesh>& iF, const dictionary& dict ) : uniformJumpFvPatchField<scalar>(p, iF) { if (this->cyclicPatch().owner()) { if (dict.found("f")) { // Backwards compatibility Istream& is = dict.lookup("f"); is.format(IOstream::ASCII); scalarList f(is); label nPows = 0; forAll(f, powI) { if (mag(f[powI]) > VSMALL) { nPows++; } } List<Tuple2<scalar, scalar> > coeffs(nPows); nPows = 0; forAll(f, powI) { if (mag(f[powI]) > VSMALL) { coeffs[nPows++] = Tuple2<scalar, scalar>(f[powI], powI); } } this->jumpTable_.reset ( new polynomial("jumpTable", coeffs) ); } else { // Generic input constructed from dictionary this->jumpTable_ = DataEntry<scalar>::New("jumpTable", dict); } } if (dict.found("value")) { fvPatchScalarField::operator= ( scalarField("value", dict, p.size()) ); } else { this->evaluate(Pstream::blocking); } } // ************************************************************************* //
firelab/OpenFOAM-2.2.x
src/finiteVolume/fields/fvPatchFields/derived/fan/fanFvPatchFields.C
C++
gpl-3.0
3,838
// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "core/fpdfapi/page/cpdf_pattern.h" CPDF_Pattern::CPDF_Pattern(PatternType type, CPDF_Document* pDoc, CPDF_Object* pObj, const CFX_Matrix& parentMatrix) : m_PatternType(type), m_pDocument(pDoc), m_pPatternObj(pObj), m_ParentMatrix(parentMatrix) {} CPDF_Pattern::~CPDF_Pattern() {}
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/pdfium/core/fpdfapi/page/cpdf_pattern.cpp
C++
gpl-3.0
636
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2000, 2015 Oracle and/or its affiliates. All rights reserved. * */ package com.sleepycat.collections; import com.sleepycat.db.DatabaseEntry; import com.sleepycat.db.DatabaseException; /** * An interface implemented to assign new primary key values. * An implementation of this interface is passed to the {@link StoredMap} * or {@link StoredSortedMap} constructor to assign primary keys for that * store. Key assignment occurs when <code>StoredMap.append()</code> is called. * * @author Mark Hayes */ public interface PrimaryKeyAssigner { /** * Assigns a new primary key value into the given data buffer. */ void assignKey(DatabaseEntry keyData) throws DatabaseException; }
apavlo/h-store
third_party/cpp/berkeleydb/lang/java/src/com/sleepycat/collections/PrimaryKeyAssigner.java
Java
gpl-3.0
793
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ package com.sun.star.lib.uno.bridges.java_remote; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import com.sun.star.bridge.XBridge; import com.sun.star.bridge.XInstanceProvider; import com.sun.star.connection.XConnection; import com.sun.star.lang.DisposedException; import com.sun.star.lang.EventObject; import com.sun.star.lang.XComponent; import com.sun.star.lang.XEventListener; import com.sun.star.lib.uno.environments.java.java_environment; import com.sun.star.lib.uno.environments.remote.IProtocol; import com.sun.star.lib.uno.environments.remote.IReceiver; import com.sun.star.lib.uno.environments.remote.IThreadPool; import com.sun.star.lib.uno.environments.remote.Job; import com.sun.star.lib.uno.environments.remote.Message; import com.sun.star.lib.uno.environments.remote.ThreadId; import com.sun.star.lib.uno.environments.remote.ThreadPoolManager; import com.sun.star.lib.uno.typedesc.MethodDescription; import com.sun.star.lib.uno.typedesc.TypeDescription; import com.sun.star.lib.util.DisposeListener; import com.sun.star.lib.util.DisposeNotifier; import com.sun.star.uno.Any; import com.sun.star.uno.IBridge; import com.sun.star.uno.IEnvironment; import com.sun.star.uno.Type; import com.sun.star.uno.TypeClass; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; /** * This class implements a remote bridge. * * <p>Therefore various interfaces are implemented.</p> * * <p>The protocol to used is passed by name, the bridge * then looks for it under <code>com.sun.star.lib.uno.protocols</code>.</p> * * @since UDK1.0 */ public class java_remote_bridge implements IBridge, IReceiver, RequestHandler, XBridge, XComponent, DisposeNotifier { /** * When set to true, enables various debugging output. */ private static final boolean DEBUG = false; private final class MessageDispatcher extends Thread { public MessageDispatcher() { super("MessageDispatcher"); } @Override public void run() { try { for (;;) { synchronized (this) { if (terminate) { break; } } Message msg = _iProtocol.readMessage(); Object obj = null; if (msg.isRequest()) { String oid = msg.getObjectId(); Type type = new Type(msg.getType()); int fid = msg.getMethod().getIndex(); if (fid == MethodDescription.ID_RELEASE) { _java_environment.revokeInterface(oid, type); remRefHolder(type, oid); if (msg.isSynchronous()) { sendReply(false, msg.getThreadId(), null); } continue; } obj = _java_environment.getRegisteredInterface( oid, type); if (obj == null && fid == MethodDescription.ID_QUERY_INTERFACE) { if (_xInstanceProvider == null) { sendReply( true, msg.getThreadId(), new com.sun.star.uno.RuntimeException( "unknown OID " + oid)); continue; } else { UnoRuntime.setCurrentContext( msg.getCurrentContext()); try { obj = _xInstanceProvider.getInstance(oid); } catch (com.sun.star.uno.RuntimeException e) { sendReply(true, msg.getThreadId(), e); continue; } catch (Exception e) { sendReply( true, msg.getThreadId(), new com.sun.star.uno.RuntimeException( e.toString())); continue; } finally { UnoRuntime.setCurrentContext(null); } } } } _iThreadPool.putJob( new Job(obj, java_remote_bridge.this, msg)); } } catch (Throwable e) { dispose(e); } } public synchronized void terminate() { terminate = true; } private boolean terminate = false; } protected XConnection _xConnection; protected XInstanceProvider _xInstanceProvider; protected String _name = "remote"; private final String protocol; protected IProtocol _iProtocol; protected IEnvironment _java_environment; protected MessageDispatcher _messageDispatcher; protected final AtomicInteger _life_count = new AtomicInteger(); // determines if this bridge is alive, which is controlled by acquire and release calls private final ArrayList<XEventListener> _listeners = new ArrayList<XEventListener>(); protected IThreadPool _iThreadPool; // Variable disposed must only be used while synchronized on this object: private boolean disposed = false; /** * This method is for testing only. */ int getLifeCount() { return _life_count.get(); } /** * This method is for testing only. */ IProtocol getProtocol() { return _iProtocol; } /** * The ref holder stuff strongly holds objects mapped out via this bridge * (the java_environment only holds them weakly). * * <p>When this bridge is disposed, all remaining ref holder entries are * released.</p> */ private static final class RefHolder { public RefHolder(Type type, Object object) { this.type = type; this.object = object; } public Type getType() { return type; } public void acquire() { ++count; } public boolean release() { return --count == 0; } private final Type type; @SuppressWarnings("unused") private final Object object; private int count = 1; } private final HashMap<String, LinkedList<RefHolder>> refHolders = new HashMap<String, LinkedList<RefHolder>>(); // from OID (String) to LinkedList of RefHolder private boolean hasRefHolder(String oid, Type type) { synchronized (refHolders) { LinkedList<RefHolder> l = refHolders.get(oid); if (l != null) { for (RefHolder rh : l) { if (type.isSupertypeOf(rh.getType())) { return true; } } } } return false; } final void addRefHolder(Object obj, Type type, String oid) { synchronized (refHolders) { LinkedList<RefHolder> l = refHolders.get(oid); if (l == null) { l = new LinkedList<RefHolder>(); refHolders.put(oid, l); } boolean found = false; for (Iterator<RefHolder> i = l.iterator(); !found && i.hasNext();) { RefHolder rh = i.next(); if (rh.getType().equals(type)) { found = true; rh.acquire(); } } if (!found) { l.add(new RefHolder(type, obj)); } } acquire(); } final void remRefHolder(Type type, String oid) { synchronized (refHolders) { LinkedList<RefHolder> l = refHolders.get(oid); if (l == null) { return; } for (RefHolder rh : l) { if (rh.getType().equals(type)) { try { if (rh.release()) { l.remove(rh); if (l.isEmpty()) { refHolders.remove(oid); } } } finally { release(); } break; } } } } final void freeHolders() { synchronized (refHolders) { for (Iterator<Map.Entry<String,LinkedList<RefHolder>>> i1 = refHolders.entrySet().iterator(); i1.hasNext();) { Map.Entry<String,LinkedList<RefHolder>> e = i1.next(); String oid = e.getKey(); LinkedList<RefHolder> l = e.getValue(); for (Iterator<RefHolder> i2 = l.iterator(); i2.hasNext();) { RefHolder rh = i2.next(); for (boolean done = false; !done;) { done = rh.release(); _java_environment.revokeInterface(oid, rh.getType()); release(); } } } refHolders.clear(); } } public java_remote_bridge( IEnvironment java_environment, IEnvironment remote_environment, Object[] args) throws Exception { _java_environment = java_environment; String proto = (String) args[0]; _xConnection = (XConnection) args[1]; _xInstanceProvider = (XInstanceProvider) args[2]; if (args.length > 3) { _name = (String) args[3]; } String attr; int i = proto.indexOf(','); if (i >= 0) { protocol = proto.substring(0, i); attr = proto.substring(i + 1); } else { protocol = proto; attr = null; } _iProtocol = (IProtocol) Class.forName( "com.sun.star.lib.uno.protocols." + protocol + "." + protocol). getConstructor( new Class[] { IBridge.class, String.class, InputStream.class, OutputStream.class }). newInstance( new Object[] { this, attr, new XConnectionInputStream_Adapter(_xConnection), new XConnectionOutputStream_Adapter(_xConnection) }); proxyFactory = new ProxyFactory(this, this); _iThreadPool = ThreadPoolManager.create(); _messageDispatcher = new MessageDispatcher(); _messageDispatcher.start(); _iProtocol.init(); } private void notifyListeners() { EventObject eventObject = new EventObject(this); Iterator<XEventListener> elements = _listeners.iterator(); while(elements.hasNext()) { XEventListener xEventListener = elements.next(); try { xEventListener.disposing(eventObject); } catch(com.sun.star.uno.RuntimeException runtimeException) { // we are here not interested in any exceptions } } } /** * Constructs a new bridge. * <p> This method is not part of the provided <code>api</code> * and should only be used by the UNO runtime.</p> * * @param args the custom parameters: arg[0] == protocol_name, * arg[1] == xConnection, arg[2] == xInstanceProvider. * * @deprecated as of UDK 1.0 */ public java_remote_bridge(Object args[]) throws Exception { this(UnoRuntime.getEnvironment("java", null), UnoRuntime.getEnvironment("remote", null), args); } /** * * @see com.sun.star.uno.IBridge#mapInterfaceTo */ public Object mapInterfaceTo(Object object, Type type) { checkDisposed(); if (object == null) { return null; } else { String[] oid = new String[1]; object = _java_environment.registerInterface(object, oid, type); if (!proxyFactory.isProxy(object)) { // This branch must be taken iff object either is no proxy at // all or a proxy from some other bridge. There are objects // that behave like objects for this bridge but that are not // detected as such by proxyFactory.isProxy. The only known // case of such objects is com.sun.star.comp.beans.Wrapper, // which implements com.sun.star.lib.uno.Proxy and effectively // is a second proxy around a proxy that can be from this // bridge. For that case, there is no problem, however: Since // the proxies generated by ProxyFactory send each // queryInterface to the original object (i.e., they do not // short-circuit requests for a super-interface to themselves), // there will always be an appropriate ProxyFactory-proxy // registered at the _java_environment, so that the object // returned by _java_environment.registerInterface will never be // a com.sun.star.comp.beans.Wrapper. addRefHolder(object, type, oid[0]); } return oid[0]; } } /** * Maps an object from destination environment to the source environment. * * @param oId the object to map. * @param type the interface under which is to be mapped. * @return the object in the source environment. * * @see com.sun.star.uno.IBridge#mapInterfaceFrom */ public Object mapInterfaceFrom(Object oId, Type type) { checkDisposed(); // TODO What happens if an exception is thrown after the call to // acquire, but before it is guaranteed that a pairing release will be // called eventually? acquire(); String oid = (String) oId; Object object = _java_environment.getRegisteredInterface(oid, type); if (object == null) { object = _java_environment.registerInterface( proxyFactory.create(oid, type), new String[] { oid }, type); // the proxy sends a release when finalized } else if (!hasRefHolder(oid, type)) { sendInternalRequest(oid, type, "release", null); } return object; } /** * Gives the source environment. * * @return the source environment of this bridge. * @see com.sun.star.uno.IBridge#getSourceEnvironment */ public IEnvironment getSourceEnvironment() { return _java_environment; } /** * Gives the destination environment. * * @return the destination environment of this bridge. * @see com.sun.star.uno.IBridge#getTargetEnvironment */ public IEnvironment getTargetEnvironment() { return null; } /** * Increases the life count. * * @see com.sun.star.uno.IBridge#acquire */ public void acquire() { if(DEBUG) { int x = _life_count.incrementAndGet(); System.err.println("##### " + getClass().getName() + ".acquire:" + x); } else { _life_count.incrementAndGet(); } } /** * Decreases the life count. * * <p>If the life count drops to zero, the bridge disposes itself.</p> * * @see com.sun.star.uno.IBridge#release */ public void release() { int x = _life_count.decrementAndGet(); if (x <= 0) { dispose(new Throwable("end of life")); } } public void dispose() { dispose(new Throwable("user dispose")); } private void dispose(Throwable throwable) { synchronized (this) { if (disposed) { return; } disposed = true; } notifyListeners(); for (Iterator<DisposeListener> i = disposeListeners.iterator(); i.hasNext();) { i.next().notifyDispose(this); } _iProtocol.terminate(); try { _messageDispatcher.terminate(); try { _xConnection.close(); } catch (com.sun.star.io.IOException e) { System.err.println( getClass().getName() + ".dispose - IOException:" + e); } if (Thread.currentThread() != _messageDispatcher && _messageDispatcher.isAlive()) { _messageDispatcher.join(1000); if (_messageDispatcher.isAlive()) { _messageDispatcher.interrupt(); _messageDispatcher.join(); } } // interrupt all jobs queued by this bridge _iThreadPool.dispose(throwable); // release all out-mapped objects and all in-mapped proxies: freeHolders(); // assert _java_environment instanceof java_environment; ((java_environment) _java_environment).revokeAllProxies(); proxyFactory.dispose(); if (DEBUG) { if (_life_count.get() != 0) { System.err.println(getClass().getName() + ".dispose - life count (proxies left):" + _life_count); } _java_environment.list(); } // clear members _xConnection = null; _java_environment = null; _messageDispatcher = null; } catch (InterruptedException e) { System.err.println(getClass().getName() + ".dispose - InterruptedException:" + e); } } /** * * @see com.sun.star.bridge.XBridge#getInstance */ public Object getInstance(String instanceName) { Type t = new Type(XInterface.class); return sendInternalRequest( instanceName, t, "queryInterface", new Object[] { t }); } /** * Gives the name of this bridge. * * @return the name of this bridge. * @see com.sun.star.bridge.XBridge#getName */ public String getName() { return _name; } /** * Gives a description of the connection type and protocol used. * * @return connection type and protocol. * @see com.sun.star.bridge.XBridge#getDescription */ public String getDescription() { return protocol + "," + _xConnection.getDescription(); } public void sendReply(boolean exception, ThreadId threadId, Object result) { if (DEBUG) { System.err.println("##### " + getClass().getName() + ".sendReply: " + exception + " " + result); } checkDisposed(); try { _iProtocol.writeReply(exception, threadId, result); } catch (IOException e) { dispose(e); throw (DisposedException) (new DisposedException("unexpected " + e).initCause(e)); } catch (RuntimeException e) { dispose(e); throw e; } catch (Error e) { dispose(e); throw e; } } public Object sendRequest( String oid, Type type, String operation, Object[] params) throws Throwable { Object result = null; checkDisposed(); ThreadId threadId = _iThreadPool.getThreadId(); Object handle = _iThreadPool.attach(threadId); try { boolean sync; try { sync = _iProtocol.writeRequest( oid, TypeDescription.getTypeDescription(type), operation, threadId, params); } catch (IOException e) { dispose(e); throw (DisposedException) new DisposedException(e.toString()).initCause(e); } if (sync && Thread.currentThread() != _messageDispatcher) { result = _iThreadPool.enter(handle, threadId); } } finally { _iThreadPool.detach(handle, threadId); if(operation.equals("release")) release(); // kill this bridge, if this was the last proxy } if(DEBUG) System.err.println("##### " + getClass().getName() + ".sendRequest left:" + result); // On the wire (at least in URP), the result of queryInterface is // transported as an ANY, but in Java it shall be transported as a // direct reference to the UNO object (represented as a Java Object), // never boxed in a com.sun.star.uno.Any: if (operation.equals("queryInterface") && result instanceof Any) { Any a = (Any) result; if (a.getType().getTypeClass() == TypeClass.INTERFACE) { result = a.getObject(); } else { result = null; // should never happen } } return result; } private Object sendInternalRequest( String oid, Type type, String operation, Object[] arguments) { try { return sendRequest(oid, type, operation, arguments); } catch (Error e) { throw e; } catch (RuntimeException e) { throw e; } catch (Throwable e) { throw new RuntimeException("Unexpected " + e); } } /** * Methods XComponent. */ public void addEventListener(XEventListener xEventListener) { _listeners.add(xEventListener); } public void removeEventListener(XEventListener xEventListener) { _listeners.remove(xEventListener); } /** * * @see DisposeNotifier#addDisposeListener */ public void addDisposeListener(DisposeListener listener) { synchronized (this) { if (!disposed) { disposeListeners.add(listener); return; } } listener.notifyDispose(this); } /** * This function must only be called while synchronized on this object. */ private synchronized void checkDisposed() { if (disposed) { throw new DisposedException("java_remote_bridge " + this + " is disposed"); } } private final ProxyFactory proxyFactory; // Access to disposeListeners must be synchronized on <CODE>this</CODE>: private final ArrayList<DisposeListener> disposeListeners = new ArrayList<DisposeListener>(); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
beppec56/core
jurt/com/sun/star/lib/uno/bridges/java_remote/java_remote_bridge.java
Java
gpl-3.0
24,276
using System; using System.Collections.Generic; using System.Text; namespace eid_trust_service_sdk_dotnet { public class RevocationDataNotFoundException : Exception { } }
Renaud-V/eid-trust-service
eid-trust-service-sdk-dotnet/src/main/eid-trust-service-sdk-dotnet/eid-trust-service-sdk-dotnet/src/main/cs/RevocationDataNotFoundException.cs
C#
gpl-3.0
197
<?php /* Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com> * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005 Marc Barilley <marc@ocebo.com> * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@capnetworks.com> * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr> * Copyright (C) 2008 Raphael Bertrand <raphael.bertrand@resultic.fr> * Copyright (C) 2010-2014 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2010-2011 Philippe Grand <philippe.grand@atoo-net.com> * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr> * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr> * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro> * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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/>. */ /** * \file htdocs/comm/propal/class/propal.class.php * \brief File of class to manage proposals */ require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; require_once DOL_DOCUMENT_ROOT ."/core/class/commonobjectline.class.php"; require_once DOL_DOCUMENT_ROOT .'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT .'/margin/lib/margins.lib.php'; /** * Class to manage proposals */ class Propal extends CommonObject { public $element='propal'; public $table_element='propal'; public $table_element_line='propaldet'; public $fk_element='fk_propal'; protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe /** * {@inheritdoc} */ protected $table_ref_field = 'ref'; var $id; /** * ID of the client * @var int */ var $socid; /** * Client (loaded by fetch_client) * @var Societe */ var $client; var $contactid; var $fk_project; var $author; var $ref; var $ref_client; /** * Status of the quote * @var int * @see Propal::STATUS_DRAFT, Propal::STATUS_VALIDATED, Propal::STATUS_SIGNED, Propal::STATUS_NOTSIGNED, Propal::STATUS_BILLED */ var $statut; /** * @deprecated * @see date_creation */ var $datec; /** * Creation date * @var int */ public $date_creation; /** * @deprecated * @see date_validation */ var $datev; /** * Validation date * @var int */ public $date_validation; /** * Date of the quote * @var */ var $date; /** * @deprecated * @see date */ var $datep; var $date_livraison; var $fin_validite; var $user_author_id; var $user_valid_id; var $user_close_id; var $total_ht; // Total net of tax var $total_tva; // Total VAT var $total_localtax1; // Total Local Taxes 1 var $total_localtax2; // Total Local Taxes 2 var $total_ttc; // Total with tax /** * @deprecated * @see total_ht */ var $price; /** * @deprecated * @see total_tva */ var $tva; /** * @deprecated * @see total_ttc */ var $total; var $cond_reglement_id; var $cond_reglement_code; var $fk_account; // Id of bank account var $mode_reglement_id; var $mode_reglement_code; var $remise; var $remise_percent; var $remise_absolue; /** * @deprecated * @see note_private, note_public */ var $note; var $note_private; var $note_public; /** * @deprecated */ var $fk_delivery_address; var $fk_address; var $address_type; var $address; var $shipping_method_id; var $availability_id; var $availability_code; var $demand_reason_id; var $demand_reason_code; var $products=array(); var $extraparams=array(); /** * @var PropaleLigne[] */ var $lines = array(); var $line; var $origin; var $origin_id; var $labelstatut=array(); var $labelstatut_short=array(); var $specimen; //Incorterms var $fk_incoterms; var $location_incoterms; var $libelle_incoterms; //Used into tooltip /** * Draft status */ const STATUS_DRAFT = 0; /** * Validated status */ const STATUS_VALIDATED = 1; /** * Signed quote */ const STATUS_SIGNED = 2; /** * Not signed quote */ const STATUS_NOTSIGNED = 3; /** * Billed quote */ const STATUS_BILLED = 4; /** * Constructor * * @param DoliDB $db Database handler * @param int $socid Id third party * @param int $propalid Id proposal */ function __construct($db, $socid="", $propalid=0) { global $conf,$langs; $this->db = $db; $this->socid = $socid; $this->id = $propalid; $this->products = array(); $this->remise = 0; $this->remise_percent = 0; $this->remise_absolue = 0; $this->duree_validite=$conf->global->PROPALE_VALIDITY_DURATION; $langs->load("propal"); $this->labelstatut[0]=(! empty($conf->global->PROPAL_STATUS_DRAFT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFT_LABEL : $langs->trans("PropalStatusDraft")); $this->labelstatut[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATED_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATED_LABEL : $langs->trans("PropalStatusValidated")); $this->labelstatut[2]=(! empty($conf->global->PROPAL_STATUS_SIGNED_LABEL) ? $conf->global->PROPAL_STATUS_SIGNED_LABEL : $langs->trans("PropalStatusSigned")); $this->labelstatut[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNED_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNED_LABEL : $langs->trans("PropalStatusNotSigned")); $this->labelstatut[4]=(! empty($conf->global->PROPAL_STATUS_BILLED_LABEL) ? $conf->global->PROPAL_STATUS_BILLED_LABEL : $langs->trans("PropalStatusBilled")); $this->labelstatut_short[0]=(! empty($conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL : $langs->trans("PropalStatusDraftShort")); $this->labelstatut_short[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL : $langs->trans("Opened")); $this->labelstatut_short[2]=(! empty($conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL : $langs->trans("PropalStatusSignedShort")); $this->labelstatut_short[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL : $langs->trans("PropalStatusNotSignedShort")); $this->labelstatut_short[4]=(! empty($conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL : $langs->trans("PropalStatusBilledShort")); } /** * Add line into array products * $this->client doit etre charge * * @param int $idproduct Product Id to add * @param int $qty Quantity * @param int $remise_percent Discount effected on Product * @return int <0 if KO, >0 if OK * * TODO Remplacer les appels a cette fonction par generation objet Ligne * insere dans tableau $this->products */ function add_product($idproduct, $qty, $remise_percent=0) { global $conf, $mysoc; if (! $qty) $qty = 1; dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent"); if ($idproduct > 0) { $prod=new Product($this->db); $prod->fetch($idproduct); $productdesc = $prod->description; $tva_tx = get_default_tva($mysoc,$this->client,$prod->id); // local taxes $localtax1_tx = get_default_localtax($mysoc,$this->client,1,$prod->tva_tx); $localtax2_tx = get_default_localtax($mysoc,$this->client,2,$prod->tva_tx); // multiprix if($conf->global->PRODUIT_MULTIPRICES && $this->client->price_level) { $price = $prod->multiprices[$this->client->price_level]; } else { $price = $prod->price; } $line = new PropaleLigne($this->db); $line->fk_product=$idproduct; $line->desc=$productdesc; $line->qty=$qty; $line->subprice=$price; $line->remise_percent=$remise_percent; $line->tva_tx=$tva_tx; $line->fk_unit=$prod->fk_unit; $this->lines[]=$line; } } /** * Adding line of fixed discount in the proposal in DB * * @param int $idremise Id of fixed discount * @return int >0 if OK, <0 if KO */ function insert_discount($idremise) { global $langs; include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $this->db->begin(); $remise=new DiscountAbsolute($this->db); $result=$remise->fetch($idremise); if ($result > 0) { if ($remise->fk_facture) // Protection against multiple submission { $this->error=$langs->trans("ErrorDiscountAlreadyUsed"); $this->db->rollback(); return -5; } $line=new PropaleLigne($this->db); $this->line->context = $this->context; $line->fk_propal=$this->id; $line->fk_remise_except=$remise->id; $line->desc=$remise->description; // Description ligne $line->tva_tx=$remise->tva_tx; $line->subprice=-$remise->amount_ht; $line->fk_product=0; // Id produit predefini $line->qty=1; $line->remise=0; $line->remise_percent=0; $line->rang=-1; $line->info_bits=2; // TODO deprecated $line->price=-$remise->amount_ht; $line->total_ht = -$remise->amount_ht; $line->total_tva = -$remise->amount_tva; $line->total_ttc = -$remise->amount_ttc; $result=$line->insert(); if ($result > 0) { $result=$this->update_price(1); if ($result > 0) { $this->db->commit(); return 1; } else { $this->db->rollback(); return -1; } } else { $this->error=$line->error; $this->db->rollback(); return -2; } } else { $this->db->rollback(); return -2; } } /** * Add a proposal line into database (linked to product/service or not) * Les parametres sont deja cense etre juste et avec valeurs finales a l'appel * de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,'',produit) * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue) * * @param string $desc Description de la ligne * @param float $pu_ht Prix unitaire * @param float $qty Quantite * @param float $txtva Taux de tva * @param float $txlocaltax1 Local tax 1 rate * @param float $txlocaltax2 Local tax 2 rate * @param int $fk_product Id du produit/service predefini * @param float $remise_percent Pourcentage de remise de la ligne * @param string $price_base_type HT or TTC * @param float $pu_ttc Prix unitaire TTC * @param int $info_bits Bits de type de lignes * @param int $type Type of line (product, service) * @param int $rang Position of line * @param int $special_code Special code (also used by externals modules!) * @param int $fk_parent_line Id of parent line * @param int $fk_fournprice Id supplier price * @param int $pa_ht Buying price without tax * @param string $label ??? * @param int $date_start Start date of the line * @param int $date_end End date of the line * @param array $array_options extrafields array * @param string $fk_unit Code of the unit to use. Null to use the default one * @return int >0 if OK, <0 if KO * * @see add_product */ function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=0, $pa_ht=0, $label='',$date_start='', $date_end='',$array_options=0, $fk_unit=null) { global $mysoc; dol_syslog(get_class($this)."::addline propalid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_except=$remise_percent, price_base_type=$price_base_type, pu_ttc=$pu_ttc, info_bits=$info_bits, type=$type"); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters if (empty($remise_percent)) $remise_percent=0; if (empty($qty)) $qty=0; if (empty($info_bits)) $info_bits=0; if (empty($rang)) $rang=0; if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0; $remise_percent=price2num($remise_percent); $qty=price2num($qty); $pu_ht=price2num($pu_ht); $pu_ttc=price2num($pu_ttc); $txtva=price2num($txtva); $txlocaltax1=price2num($txlocaltax1); $txlocaltax2=price2num($txlocaltax2); $pa_ht=price2num($pa_ht); if ($price_base_type=='HT') { $pu=$pu_ht; } else { $pu=$pu_ttc; } // Check parameters if ($type < 0) return -1; if ($this->statut == self::STATUS_DRAFT) { $this->db->begin(); // Calcul du total TTC et de la TVA pour la ligne a partir de // qty, pu, remise_percent et txtva // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type); $total_ht = $tabprice[0]; $total_tva = $tabprice[1]; $total_ttc = $tabprice[2]; $total_localtax1 = $tabprice[9]; $total_localtax2 = $tabprice[10]; // Rang to use $rangtouse = $rang; if ($rangtouse == -1) { $rangmax = $this->line_max($fk_parent_line); $rangtouse = $rangmax + 1; } // TODO A virer // Anciens indicateurs: $price, $remise (a ne plus utiliser) $price = $pu; $remise = 0; if ($remise_percent > 0) { $remise = round(($pu * $remise_percent / 100), 2); $price = $pu - $remise; } // Insert line $this->line=new PropaleLigne($this->db); $this->line->context = $this->context; $this->line->fk_propal=$this->id; $this->line->label=$label; $this->line->desc=$desc; $this->line->qty=$qty; $this->line->tva_tx=$txtva; $this->line->localtax1_tx=$txlocaltax1; $this->line->localtax2_tx=$txlocaltax2; $this->line->localtax1_type = $localtaxes_type[0]; $this->line->localtax2_type = $localtaxes_type[2]; $this->line->fk_product=$fk_product; $this->line->remise_percent=$remise_percent; $this->line->subprice=$pu_ht; $this->line->rang=$rangtouse; $this->line->info_bits=$info_bits; $this->line->total_ht=$total_ht; $this->line->total_tva=$total_tva; $this->line->total_localtax1=$total_localtax1; $this->line->total_localtax2=$total_localtax2; $this->line->total_ttc=$total_ttc; $this->line->product_type=$type; $this->line->special_code=$special_code; $this->line->fk_parent_line=$fk_parent_line; $this->line->fk_unit=$fk_unit; $this->line->date_start=$date_start; $this->line->date_end=$date_end; // infos marge if (!empty($fk_product) && empty($fk_fournprice) && empty($pa_ht)) { // by external module, take lowest buying price include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $productFournisseur = new ProductFournisseur($this->db); $productFournisseur->find_min_price_product_fournisseur($fk_product); $this->line->fk_fournprice = $productFournisseur->product_fourn_price_id; } else { $this->line->fk_fournprice = $fk_fournprice; } $this->line->pa_ht = $pa_ht; // Mise en option de la ligne if (empty($qty) && empty($special_code)) $this->line->special_code=3; // TODO deprecated $this->line->price=$price; $this->line->remise=$remise; if (is_array($array_options) && count($array_options)>0) { $this->line->array_options=$array_options; } $result=$this->line->insert(); if ($result > 0) { // Reorder if child line if (! empty($fk_parent_line)) $this->line_order(true,'DESC'); // Mise a jour informations denormalisees au niveau de la propale meme $result=$this->update_price(1,'auto'); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. if ($result > 0) { $this->db->commit(); return $this->line->rowid; } else { $this->error=$this->db->error(); $this->db->rollback(); return -1; } } else { $this->error=$this->line->error; $this->db->rollback(); return -2; } } } /** * Update a proposal line * * @param int $rowid Id de la ligne * @param float $pu Prix unitaire (HT ou TTC selon price_base_type) * @param float $qty Quantity * @param float $remise_percent Remise effectuee sur le produit * @param float $txtva Taux de TVA * @param float $txlocaltax1 Local tax 1 rate * @param float $txlocaltax2 Local tax 2 rate * @param string $desc Description * @param string $price_base_type HT ou TTC * @param int $info_bits Miscellaneous informations * @param int $special_code Special code (also used by externals modules!) * @param int $fk_parent_line Id of parent line (0 in most cases, used by modules adding sublevels into lines). * @param int $skip_update_total Keep fields total_xxx to 0 (used for special lines by some modules) * @param int $fk_fournprice Id of origin supplier price * @param int $pa_ht Price (without tax) of product when it was bought * @param string $label ??? * @param int $type 0/1=Product/service * @param int $date_start Start date of the line * @param int $date_end End date of the line * @param array $array_options extrafields array * @param string $fk_unit Code of the unit to use. Null to use the default one * @return int 0 if OK, <0 if KO */ function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $desc='', $price_base_type='HT', $info_bits=0, $special_code=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=0, $pa_ht=0, $label='', $type=0, $date_start='', $date_end='', $array_options=0, $fk_unit=null) { global $mysoc; dol_syslog(get_class($this)."::updateLine rowid=$rowid, pu=$pu, qty=$qty, remise_percent=$remise_percent, txtva=$txtva, desc=$desc, price_base_type=$price_base_type, info_bits=$info_bits, special_code=$special_code, fk_parent_line=$fk_parent_line, pa_ht=$a_ht, type=$type, date_start=$date_start, date_end=$date_end"); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters $remise_percent=price2num($remise_percent); $qty=price2num($qty); $pu = price2num($pu); $txtva = price2num($txtva); $txlocaltax1=price2num($txlocaltax1); $txlocaltax2=price2num($txlocaltax2); $pa_ht=price2num($pa_ht); if (empty($qty) && empty($special_code)) $special_code=3; // Set option tag if (! empty($qty) && $special_code == 3) $special_code=0; // Remove option tag if ($this->statut == self::STATUS_DRAFT) { $this->db->begin(); // Calcul du total TTC et de la TVA pour la ligne a partir de // qty, pu, remise_percent et txtva // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type); $total_ht = $tabprice[0]; $total_tva = $tabprice[1]; $total_ttc = $tabprice[2]; $total_localtax1 = $tabprice[9]; $total_localtax2 = $tabprice[10]; // Anciens indicateurs: $price, $remise (a ne plus utiliser) $price = $pu; if ($remise_percent > 0) { $remise = round(($pu * $remise_percent / 100), 2); $price = $pu - $remise; } //Fetch current line from the database and then clone the object and set it in $oldline property $line = new PropaleLigne($this->db); $line->fetch($rowid); $staticline = clone $line; $line->oldline = $staticline; $this->line = $line; $this->line->context = $this->context; // Reorder if fk_parent_line change if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) { $rangmax = $this->line_max($fk_parent_line); $this->line->rang = $rangmax + 1; } $this->line->rowid = $rowid; $this->line->label = $label; $this->line->desc = $desc; $this->line->qty = $qty; $this->line->product_type = $type; $this->line->tva_tx = $txtva; $this->line->localtax1_tx = $txlocaltax1; $this->line->localtax2_tx = $txlocaltax2; $this->line->localtax1_type = $localtaxes_type[0]; $this->line->localtax2_type = $localtaxes_type[2]; $this->line->remise_percent = $remise_percent; $this->line->subprice = $pu; $this->line->info_bits = $info_bits; $this->line->total_ht = $total_ht; $this->line->total_tva = $total_tva; $this->line->total_localtax1 = $total_localtax1; $this->line->total_localtax2 = $total_localtax2; $this->line->total_ttc = $total_ttc; $this->line->special_code = $special_code; $this->line->fk_parent_line = $fk_parent_line; $this->line->skip_update_total = $skip_update_total; $this->line->fk_unit = $fk_unit; // infos marge if (!empty($fk_product) && empty($fk_fournprice) && empty($pa_ht)) { // by external module, take lowest buying price include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $productFournisseur = new ProductFournisseur($this->db); $productFournisseur->find_min_price_product_fournisseur($fk_product); $this->line->fk_fournprice = $productFournisseur->product_fourn_price_id; } else { $this->line->fk_fournprice = $fk_fournprice; } $this->line->pa_ht = $pa_ht; $this->line->date_start=$date_start; $this->line->date_end=$date_end; // TODO deprecated $this->line->price=$price; $this->line->remise=$remise; if (is_array($array_options) && count($array_options)>0) { $this->line->array_options=$array_options; } $result=$this->line->update(); if ($result > 0) { // Reorder if child line if (! empty($fk_parent_line)) $this->line_order(true,'DESC'); $this->update_price(1); $this->fk_propal = $this->id; $this->rowid = $rowid; $this->db->commit(); return $result; } else { $this->error=$this->line->error; $this->db->rollback(); return -1; } } else { dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action"); return -2; } } /** * Delete detail line * * @param int $lineid Id of line to delete * @return int >0 if OK, <0 if KO */ function deleteline($lineid) { if ($this->statut == self::STATUS_DRAFT) { $line=new PropaleLigne($this->db); // For triggers $line->fetch($lineid); if ($line->delete() > 0) { $this->update_price(1); return 1; } else { return -1; } } else { return -2; } } /** * Create commercial proposal into database * this->ref can be set or empty. If empty, we will use "(PROVid)" * * @param User $user User that create * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers * @return int <0 if KO, >=0 if OK */ function create($user, $notrigger=0) { global $langs,$conf,$mysoc,$hookmanager; $error=0; $now=dol_now(); // Clean parameters if (empty($this->date)) $this->date=$this->datep; $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600); if (empty($this->availability_id)) $this->availability_id=0; if (empty($this->demand_reason_id)) $this->demand_reason_id=0; dol_syslog(get_class($this)."::create"); // Check parameters $result=$this->fetch_thirdparty(); if ($result < 0) { $this->error="Failed to fetch company"; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -3; } // Check parameters if (! empty($this->ref)) // We check that ref is not already used { $result=self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used if ($result > 0) { $this->error='ErrorRefAlreadyExists'; dol_syslog(get_class($this)."::create ".$this->error,LOG_WARNING); $this->db->rollback(); return -1; } } if (empty($this->date)) { $this->error="Date of proposal is required"; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -4; } $this->db->begin(); // Insert into database $sql = "INSERT INTO ".MAIN_DB_PREFIX."propal ("; $sql.= "fk_soc"; $sql.= ", price"; $sql.= ", remise"; $sql.= ", remise_percent"; $sql.= ", remise_absolue"; $sql.= ", tva"; $sql.= ", total"; $sql.= ", datep"; $sql.= ", datec"; $sql.= ", ref"; $sql.= ", fk_user_author"; $sql.= ", note_private"; $sql.= ", note_public"; $sql.= ", model_pdf"; $sql.= ", fin_validite"; $sql.= ", fk_cond_reglement"; $sql.= ", fk_mode_reglement"; $sql.= ", fk_account"; $sql.= ", ref_client"; $sql.= ", date_livraison"; $sql.= ", fk_shipping_method"; $sql.= ", fk_availability"; $sql.= ", fk_input_reason"; $sql.= ", fk_projet"; $sql.= ", fk_incoterms"; $sql.= ", location_incoterms"; $sql.= ", entity"; $sql.= ") "; $sql.= " VALUES ("; $sql.= $this->socid; $sql.= ", 0"; $sql.= ", ".$this->remise; $sql.= ", ".($this->remise_percent?$this->db->escape($this->remise_percent):'null'); $sql.= ", ".($this->remise_absolue?$this->db->escape($this->remise_absolue):'null'); $sql.= ", 0"; $sql.= ", 0"; $sql.= ", '".$this->db->idate($this->date)."'"; $sql.= ", '".$this->db->idate($now)."'"; $sql.= ", '(PROV)'"; $sql.= ", ".($user->id > 0 ? "'".$user->id."'":"null"); $sql.= ", '".$this->db->escape($this->note_private)."'"; $sql.= ", '".$this->db->escape($this->note_public)."'"; $sql.= ", '".$this->db->escape($this->modelpdf)."'"; $sql.= ", ".($this->fin_validite!=''?"'".$this->db->idate($this->fin_validite)."'":"null"); $sql.= ", ".$this->cond_reglement_id; $sql.= ", ".$this->mode_reglement_id; $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); $sql.= ", '".$this->db->escape($this->ref_client)."'"; $sql.= ", ".($this->date_livraison!=''?"'".$this->db->idate($this->date_livraison)."'":"null"); $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL'); $sql.= ", ".$this->availability_id; $sql.= ", ".$this->demand_reason_id; $sql.= ", ".($this->fk_project?$this->fk_project:"null"); $sql.= ", ".(int) $this->fk_incoterms; $sql.= ", '".$this->db->escape($this->location_incoterms)."'"; $sql.= ", ".$conf->entity; $sql.= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal"); if ($this->id) { $this->ref='(PROV'.$this->id.')'; $sql = 'UPDATE '.MAIN_DB_PREFIX."propal SET ref='".$this->ref."' WHERE rowid=".$this->id; dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) $error++; /* * Insertion du detail des produits dans la base */ if (! $error) { $fk_parent_line=0; $num=count($this->lines); for ($i=0;$i<$num;$i++) { // Reset fk_parent_line for no child products and special product if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) { $fk_parent_line = 0; } $result = $this->addline( $this->lines[$i]->desc, $this->lines[$i]->subprice, $this->lines[$i]->qty, $this->lines[$i]->tva_tx, $this->lines[$i]->localtax1_tx, $this->lines[$i]->localtax2_tx, $this->lines[$i]->fk_product, $this->lines[$i]->remise_percent, 'HT', 0, 0, $this->lines[$i]->product_type, $this->lines[$i]->rang, $this->lines[$i]->special_code, $fk_parent_line, $this->lines[$i]->fk_fournprice, $this->lines[$i]->pa_ht, $this->lines[$i]->label, $this->lines[$i]->date_start, $this->lines[$i]->date_end, $this->lines[$i]->array_options, $this->lines[$i]->fk_unit ); if ($result < 0) { $error++; $this->error=$this->db->error; dol_print_error($this->db); break; } // Defined the new fk_parent_line if ($result > 0 && $this->lines[$i]->product_type == 9) { $fk_parent_line = $result; } } } // Add linked object if (! $error && $this->origin && $this->origin_id) { $ret = $this->add_object_linked(); if (! $ret) dol_print_error($this->db); } // Set delivery address if (! $error && $this->fk_delivery_address) { $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; $sql.= " SET fk_delivery_address = ".$this->fk_delivery_address; $sql.= " WHERE ref = '".$this->ref."'"; $sql.= " AND entity = ".$conf->entity; $result=$this->db->query($sql); } if (! $error) { // Mise a jour infos denormalisees $resql=$this->update_price(1); if ($resql) { $action='update'; // Actions on extra fields (by external module or standard code) // TODO le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('propaldao')); $parameters=array('socid'=>$this->id); $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { $result=$this->insertExtraFields(); if ($result < 0) { $error++; } } } else if ($reshook < 0) $error++; if (! $notrigger) { // Call trigger $result=$this->call_trigger('PROPAL_CREATE',$user); if ($result < 0) { $error++; } // End call triggers } } else { $this->error=$this->db->lasterror(); $error++; } } } else { $this->error=$this->db->lasterror(); $error++; } if (! $error) { $this->db->commit(); dol_syslog(get_class($this)."::create done id=".$this->id); return $this->id; } else { $this->db->rollback(); return -2; } } else { $this->error=$this->db->lasterror(); $this->db->rollback(); return -1; } } /** * Insert into DB a proposal object completely defined by its data members (ex, results from copy). * * @param User $user User that create * @return int Id of the new object if ok, <0 if ko * @see create */ function create_from($user) { $this->products=$this->lines; return $this->create($user); } /** * Load an object from its id and create a new one in database * * @param int $socid Id of thirdparty * @return int New id of clone */ function createFromClone($socid=0) { global $db, $user,$langs,$conf,$hookmanager; dol_include_once('/projet/class/project.class.php'); $this->context['createfromclone']='createfromclone'; $error=0; $now=dol_now(); $this->db->begin(); // get extrafields so they will be clone foreach($this->lines as $line) $line->fetch_optionals($line->rowid); // Load dest object $clonedObj = clone $this; $objsoc=new Societe($this->db); // Change socid if needed if (! empty($socid) && $socid != $clonedObj->socid) { if ($objsoc->fetch($socid) > 0) { $clonedObj->socid = $objsoc->id; $clonedObj->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); $clonedObj->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); $clonedObj->fk_delivery_address = ''; $project = new Project($db); if ($this->fk_project > 0 && $project->fetch($this->fk_project)) { if ($project->socid <= 0) $clonedObj->fk_project = $this->fk_project; else $clonedObj->fk_project = ''; } else { $clonedObj->fk_project = ''; } } // reset ref_client $clonedObj->ref_client = ''; // TODO Change product price if multi-prices } else { $objsoc->fetch($clonedObj->socid); } $clonedObj->id=0; $clonedObj->statut=self::STATUS_DRAFT; if (empty($conf->global->PROPALE_ADDON) || ! is_readable(DOL_DOCUMENT_ROOT ."/core/modules/propale/".$conf->global->PROPALE_ADDON.".php")) { $this->error='ErrorSetupNotComplete'; return -1; } // Clear fields $clonedObj->user_author = $user->id; $clonedObj->user_valid = ''; $clonedObj->date = $now; $clonedObj->datep = $now; // deprecated $clonedObj->fin_validite = $clonedObj->date + ($clonedObj->duree_validite * 24 * 3600); if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $clonedObj->ref_client = ''; // Set ref require_once DOL_DOCUMENT_ROOT ."/core/modules/propale/".$conf->global->PROPALE_ADDON.'.php'; $obj = $conf->global->PROPALE_ADDON; $modPropale = new $obj; $clonedObj->ref = $modPropale->getNextValue($objsoc,$clonedObj); // Create clone $result=$clonedObj->create($user); if ($result < 0) $error++; else { // copy internal contacts if ($clonedObj->copy_linked_contact($this, 'internal') < 0) $error++; // copy external contacts if same company elseif ($this->socid == $clonedObj->socid) { if ($clonedObj->copy_linked_contact($this, 'external') < 0) $error++; } } if (! $error) { // Hook of thirdparty module if (is_object($hookmanager)) { $parameters=array('objFrom'=>$this,'clonedObj'=>$clonedObj); $action=''; $reshook=$hookmanager->executeHooks('createFrom',$parameters,$clonedObj,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) $error++; } // Call trigger $result=$clonedObj->call_trigger('PROPAL_CLONE',$user); if ($result < 0) { $error++; } // End call triggers } unset($this->context['createfromclone']); // End if (! $error) { $this->db->commit(); return $clonedObj->id; } else { $this->db->rollback(); return -1; } } /** * Load a proposal from database and its ligne array * * @param int $rowid id of object to load * @param string $ref Ref of proposal * @return int >0 if OK, <0 if KO */ function fetch($rowid,$ref='') { global $conf; $sql = "SELECT p.rowid, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc"; $sql.= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; $sql.= ", p.datec"; $sql.= ", p.date_valid as datev"; $sql.= ", p.datep as dp"; $sql.= ", p.fin_validite as dfv"; $sql.= ", p.date_livraison as date_livraison"; $sql.= ", p.model_pdf, p.ref_client, p.extraparams"; $sql.= ", p.note_private, p.note_public"; $sql.= ", p.fk_projet, p.fk_statut"; $sql.= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture"; $sql.= ", p.fk_delivery_address"; $sql.= ", p.fk_availability"; $sql.= ", p.fk_input_reason"; $sql.= ", p.fk_cond_reglement"; $sql.= ", p.fk_mode_reglement"; $sql.= ', p.fk_account'; $sql.= ", p.fk_shipping_method"; $sql.= ", p.fk_incoterms, p.location_incoterms"; $sql.= ", i.libelle as libelle_incoterms"; $sql.= ", c.label as statut_label"; $sql.= ", ca.code as availability_code, ca.label as availability"; $sql.= ", dr.code as demand_reason_code, dr.label as demand_reason"; $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."propal as p"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid'; $sql.= " WHERE p.fk_statut = c.id"; $sql.= " AND p.entity IN (".getEntity('propal', 1).")"; if ($ref) $sql.= " AND p.ref='".$ref."'"; else $sql.= " AND p.rowid=".$rowid; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; $this->ref = $obj->ref; $this->ref_client = $obj->ref_client; $this->remise = $obj->remise; $this->remise_percent = $obj->remise_percent; $this->remise_absolue = $obj->remise_absolue; $this->total = $obj->total; // TODO deprecated $this->total_ht = $obj->total_ht; $this->total_tva = $obj->tva; $this->total_localtax1 = $obj->localtax1; $this->total_localtax2 = $obj->localtax2; $this->total_ttc = $obj->total; $this->socid = $obj->fk_soc; $this->fk_project = $obj->fk_projet; $this->modelpdf = $obj->model_pdf; $this->note = $obj->note_private; // TODO deprecated $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; $this->statut = $obj->fk_statut; $this->statut_libelle = $obj->statut_label; $this->datec = $this->db->jdate($obj->datec); // TODO deprecated $this->datev = $this->db->jdate($obj->datev); // TODO deprecated $this->date_creation = $this->db->jdate($obj->datec); //Creation date $this->date_validation = $this->db->jdate($obj->datev); //Validation date $this->date = $this->db->jdate($obj->dp); // Proposal date $this->datep = $this->db->jdate($obj->dp); // deprecated $this->fin_validite = $this->db->jdate($obj->dfv); $this->date_livraison = $this->db->jdate($obj->date_livraison); $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; $this->availability_id = $obj->fk_availability; $this->availability_code = $obj->availability_code; $this->availability = $obj->availability; $this->demand_reason_id = $obj->fk_input_reason; $this->demand_reason_code = $obj->demand_reason_code; $this->demand_reason = $obj->demand_reason; $this->fk_address = $obj->fk_delivery_address; $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; $this->mode_reglement = $obj->mode_reglement; $this->fk_account = ($obj->fk_account>0)?$obj->fk_account:null; $this->cond_reglement_id = $obj->fk_cond_reglement; $this->cond_reglement_code = $obj->cond_reglement_code; $this->cond_reglement = $obj->cond_reglement; $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; $this->extraparams = (array) json_decode($obj->extraparams, true); $this->user_author_id = $obj->fk_user_author; $this->user_valid_id = $obj->fk_user_valid; $this->user_close_id = $obj->fk_user_cloture; //Incoterms $this->fk_incoterms = $obj->fk_incoterms; $this->location_incoterms = $obj->location_incoterms; $this->libelle_incoterms = $obj->libelle_incoterms; if ($obj->fk_statut == self::STATUS_DRAFT) { $this->brouillon = 1; } // Retreive all extrafield for invoice // fetch optionals attributes and labels require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields=new ExtraFields($this->db); $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); $this->fetch_optionals($this->id,$extralabels); $this->db->free($resql); $this->lines = array(); /* * Lignes propales liees a un produit ou non */ $sql = "SELECT d.rowid, d.fk_propal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,"; $sql.= " d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,"; $sql.= " d.fk_unit,"; $sql.= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,'; $sql.= ' d.date_start, d.date_end'; $sql.= " FROM ".MAIN_DB_PREFIX."propaldet as d"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid"; $sql.= " WHERE d.fk_propal = ".$this->id; $sql.= " ORDER by d.rang"; $result = $this->db->query($sql); if ($result) { require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafieldsline=new ExtraFields($this->db); $line = new PropaleLigne($this->db); $extralabelsline=$extrafieldsline->fetch_name_optionals_label($line->table_element,true); $num = $this->db->num_rows($result); $i = 0; while ($i < $num) { $objp = $this->db->fetch_object($result); $line = new PropaleLigne($this->db); $line->rowid = $objp->rowid; //Deprecated $line->id = $objp->rowid; $line->fk_propal = $objp->fk_propal; $line->fk_parent_line = $objp->fk_parent_line; $line->product_type = $objp->product_type; $line->label = $objp->custom_label; $line->desc = $objp->description; // Description ligne $line->qty = $objp->qty; $line->tva_tx = $objp->tva_tx; $line->localtax1_tx = $objp->localtax1_tx; $line->localtax2_tx = $objp->localtax2_tx; $line->subprice = $objp->subprice; $line->fk_remise_except = $objp->fk_remise_except; $line->remise_percent = $objp->remise_percent; $line->price = $objp->price; // TODO deprecated $line->info_bits = $objp->info_bits; $line->total_ht = $objp->total_ht; $line->total_tva = $objp->total_tva; $line->total_localtax1 = $objp->total_localtax1; $line->total_localtax2 = $objp->total_localtax2; $line->total_ttc = $objp->total_ttc; $line->fk_fournprice = $objp->fk_fournprice; $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht); $line->pa_ht = $marginInfos[0]; $line->marge_tx = $marginInfos[1]; $line->marque_tx = $marginInfos[2]; $line->special_code = $objp->special_code; $line->rang = $objp->rang; $line->fk_product = $objp->fk_product; $line->ref = $objp->product_ref; // TODO deprecated $line->product_ref = $objp->product_ref; $line->libelle = $objp->product_label; // TODO deprecated $line->product_label = $objp->product_label; $line->product_desc = $objp->product_desc; // Description produit $line->fk_product_type = $objp->fk_product_type; $line->fk_unit = $objp->fk_unit; $line->date_start = $objp->date_start; $line->date_end = $objp->date_end; $line->fetch_optionals($line->id,$extralabelsline); $this->lines[$i] = $line; //dol_syslog("1 ".$line->fk_product); //print "xx $i ".$this->lines[$i]->fk_product; $i++; } $this->db->free($result); } else { $this->error=$this->db->error(); return -1; } return 1; } $this->error="Record Not Found"; return 0; } else { $this->error=$this->db->error(); return -1; } } /** * Update value of extrafields on the proposal * * @param User $user Object user that modify * @return int <0 if ko, >0 if ok */ function update_extrafields($user) { $action='update'; // Actions on extra fields (by external module or standard code) // TODO le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('propaldao')); $parameters=array('id'=>$this->id); $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { $result=$this->insertExtraFields(); if ($result < 0) { $error++; } } } else if ($reshook < 0) $error++; if (!$error) { return 1; } else { return -1; } } /** * Set status to validated * * @param User $user Object user that validate * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers * @return int <0 if KO, >=0 if OK */ function valid($user, $notrigger=0) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; global $conf,$langs; $error=0; $now=dol_now(); if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))) { $this->db->begin(); // Numbering module definition $soc = new Societe($this->db); $soc->fetch($this->socid); // Define new ref if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life { $num = $this->getNextNumRef($soc); } else { $num = $this->ref; } $this->newref = $num; $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; $sql.= " SET ref = '".$num."',"; $sql.= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; dol_syslog(get_class($this)."::valid", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { dol_print_error($this->db); $error++; } // Trigger calls if (! $error && ! $notrigger) { // Call trigger $result=$this->call_trigger('PROPAL_VALIDATE',$user); if ($result < 0) { $error++; } // End call triggers } if (! $error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Rename of propal directory ($this->ref = old ref, $num = new ref) // to not lose the linked files $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->propal->dir_output.'/'.$oldref; $dirdest = $conf->propal->dir_output.'/'.$newref; if (file_exists($dirsource)) { dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); foreach($listoffiles as $fileentry) { $dirsource=$fileentry['name']; $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); $dirsource=$fileentry['path'].'/'.$dirsource; $dirdest=$fileentry['path'].'/'.$dirdest; @rename($dirsource, $dirdest); } } } } $this->ref=$num; $this->brouillon=0; $this->statut = self::STATUS_VALIDATED; $this->user_valid_id=$user->id; $this->datev=$now; $this->db->commit(); return 1; } else { $this->db->rollback(); return -1; } } } /** * Define proposal date * * @param User $user Object user that modify * @param int $date Date * @return int <0 if KO, >0 if OK */ function set_date($user, $date) { if (empty($date)) { $this->error='ErrorBadParameter'; dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR); return -1; } if (! empty($user->rights->propal->creer)) { $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET datep = '".$this->db->idate($date)."'"; $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; dol_syslog(get_class($this)."::set_date", LOG_DEBUG); if ($this->db->query($sql) ) { $this->date = $date; $this->datep = $date; // deprecated return 1; } else { $this->error=$this->db->lasterror(); return -1; } } } /** * Define end validity date * * @param User $user Object user that modify * @param int $date_fin_validite End of validity date * @return int <0 if KO, >0 if OK */ function set_echeance($user, $date_fin_validite) { if (! empty($user->rights->propal->creer)) { $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_fin_validite!=''?"'".$this->db->idate($date_fin_validite)."'":'null'); $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; if ($this->db->query($sql) ) { $this->fin_validite = $date_fin_validite; return 1; } else { $this->error=$this->db->error(); return -1; } } } /** * Set delivery date * * @param User $user Object user that modify * @param int $date_livraison Delivery date * @return int <0 if ko, >0 if ok */ function set_date_livraison($user, $date_livraison) { if (! empty($user->rights->propal->creer)) { $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; $sql.= " SET date_livraison = ".($date_livraison!=''?"'".$this->db->idate($date_livraison)."'":'null'); $sql.= " WHERE rowid = ".$this->id; if ($this->db->query($sql)) { $this->date_livraison = $date_livraison; return 1; } else { $this->error=$this->db->error(); dol_syslog(get_class($this)."::set_date_livraison Erreur SQL"); return -1; } } } /** * Set delivery * * @param User $user Object user that modify * @param int $id Availability id * @return int <0 if KO, >0 if OK */ function set_availability($user, $id) { if (! empty($user->rights->propal->creer)) { $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; $sql.= " SET fk_availability = '".$id."'"; $sql.= " WHERE rowid = ".$this->id; if ($this->db->query($sql)) { $this->fk_availability = $id; return 1; } else { $this->error=$this->db->error(); dol_syslog(get_class($this)."::set_availability Erreur SQL"); return -1; } } } /** * Set source of demand * * @param User $user Object user that modify * @param int $id Input reason id * @return int <0 if KO, >0 if OK */ function set_demand_reason($user, $id) { if (! empty($user->rights->propal->creer)) { $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; $sql.= " SET fk_input_reason = '".$id."'"; $sql.= " WHERE rowid = ".$this->id; if ($this->db->query($sql)) { $this->fk_input_reason = $id; return 1; } else { $this->error=$this->db->error(); dol_syslog(get_class($this)."::set_demand_reason Erreur SQL"); return -1; } } } /** * Set customer reference number * * @param User $user Object user that modify * @param string $ref_client Customer reference * @return int <0 if ko, >0 if ok */ function set_ref_client($user, $ref_client) { if (! empty($user->rights->propal->creer)) { dol_syslog('Propale::set_ref_client this->id='.$this->id.', ref_client='.$ref_client); $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\''); $sql.= ' WHERE rowid = '.$this->id; if ($this->db->query($sql) ) { $this->ref_client = $ref_client; return 1; } else { $this->error=$this->db->error(); dol_syslog('Propale::set_ref_client Erreur '.$this->error.' - '.$sql); return -2; } } else { return -1; } } /** * Set an overall discount on the proposal * * @param User $user Object user that modify * @param double $remise Amount discount * @return int <0 if ko, >0 if ok */ function set_remise_percent($user, $remise) { $remise=trim($remise)?trim($remise):0; if (! empty($user->rights->propal->creer)) { $remise = price2num($remise); $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET remise_percent = ".$remise; $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; if ($this->db->query($sql) ) { $this->remise_percent = $remise; $this->update_price(1); return 1; } else { $this->error=$this->db->error(); return -1; } } } /** * Set an absolute overall discount on the proposal * * @param User $user Object user that modify * @param double $remise Amount discount * @return int <0 if ko, >0 if ok */ function set_remise_absolue($user, $remise) { $remise=trim($remise)?trim($remise):0; if (! empty($user->rights->propal->creer)) { $remise = price2num($remise); $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; $sql.= " SET remise_absolue = ".$remise; $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; if ($this->db->query($sql) ) { $this->remise_absolue = $remise; $this->update_price(1); return 1; } else { $this->error=$this->db->error(); return -1; } } } /** * Reopen the commercial proposal * * @param User $user Object user that close * @param int $statut Statut * @param string $note Comment * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers * @return int <0 if KO, >0 if OK */ function reopen($user, $statut, $note='', $notrigger=0) { global $langs,$conf; $this->statut = $statut; $error=0; $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; $sql.= " SET fk_statut = ".$this->statut.","; if (! empty($note)) $sql.= " note_private = '".$this->db->escape($note)."',"; $sql.= " date_cloture=NULL, fk_user_cloture=NULL"; $sql.= " WHERE rowid = ".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::reopen", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } if (! $error) { if (! $notrigger) { // Call trigger $result=$this->call_trigger('PROPAL_REOPEN',$user); if ($result < 0) { $error++; } // End call triggers } } // Commit or rollback if ($error) { if (!empty($this->errors)) { foreach($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error.=($this->error?', '.$errmsg:$errmsg); } } $this->db->rollback(); return -1*$error; } else { $this->db->commit(); return 1; } } /** * Close the commercial proposal * * @param User $user Object user that close * @param int $statut Statut * @param string $note Comment * @return int <0 if KO, >0 if OK */ function cloture($user, $statut, $note) { global $langs,$conf; $error=0; $now=dol_now(); $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; $sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; $sql.= " WHERE rowid = ".$this->id; $resql=$this->db->query($sql); if ($resql) { $modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED?$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED:$this->modelpdf; $trigger_name='PROPAL_CLOSE_REFUSED'; if ($statut == self::STATUS_SIGNED) { $trigger_name='PROPAL_CLOSE_SIGNED'; $modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL?$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL:$this->modelpdf; // The connected company is classified as a client $soc=new Societe($this->db); $soc->id = $this->socid; $result=$soc->set_as_client(); if ($result < 0) { $this->error=$this->db->lasterror(); $this->db->rollback(); return -2; } } if ($statut == self::STATUS_BILLED) { $trigger_name='PROPAL_CLASSIFY_BILLED'; } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; if (! empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("",$conf); $newlang=(GETPOST('lang_id') ? GETPOST('lang_id') : $this->client->default_lang); $outputlangs->setDefaultLang($newlang); } //$ret=$object->fetch($id); // Reload to get new records $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } // Call trigger $result=$this->call_trigger($trigger_name,$user); if ($result < 0) { $error++; } // End call triggers if ( ! $error ) { $this->statut = $statut; $this->db->commit(); return 1; } else { $this->db->rollback(); return -1; } } else { $this->error=$this->db->lasterror(); $this->db->rollback(); return -1; } } /** * Class invoiced the Propal * * @return int <0 si ko, >0 si ok */ function classifyBilled() { $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET fk_statut = '.self::STATUS_BILLED; $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT.' ;'; if ($this->db->query($sql) ) { $this->statut=self::STATUS_BILLED; return 1; } else { dol_print_error($this->db); } } /** * Class invoiced the Propal * * @return int <0 si ko, >0 si ok * @deprecated * @see classifyBilled() */ function classer_facturee() { dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING); return $this->classifyBilled(); } /** * Set draft status * * @param User $user Object user that modify * @return int <0 if KO, >0 if OK */ function set_draft($user) { $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fk_statut = ".self::STATUS_DRAFT; $sql.= " WHERE rowid = ".$this->id; if ($this->db->query($sql)) { $this->statut = self::STATUS_DRAFT; $this->brouillon = 1; return 1; } else { return -1; } } /** * Return list of proposal (eventually filtered on user) into an array * * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name) * @param int $draft 0=not draft, 1=draft * @param int $notcurrentuser 0=all user, 1=not current user * @param int $socid Id third pary * @param int $limit For pagination * @param int $offset For pagination * @param string $sortfield Sort criteria * @param string $sortorder Sort order * @return int -1 if KO, array with result if OK */ function liste_array($shortlist=0, $draft=0, $notcurrentuser=0, $socid=0, $limit=0, $offset=0, $sortfield='p.datep', $sortorder='DESC') { global $conf,$user; $ga = array(); $sql = "SELECT s.rowid, s.nom as name, s.client,"; $sql.= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; $sql.= " p.datep as dp, p.fin_validite as datelimite"; if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c"; if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE p.entity IN (".getEntity('propal', 1).")"; $sql.= " AND p.fk_soc = s.rowid"; $sql.= " AND p.fk_statut = c.id"; if (! $user->rights->societe->client->voir && ! $socid) //restriction { $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; } if ($socid) $sql.= " AND s.rowid = ".$socid; if ($draft) $sql.= " AND p.fk_statut = ".self::STATUS_DRAFT; if ($notcurrentuser > 0) $sql.= " AND p.fk_user_author <> ".$user->id; $sql.= $this->db->order($sortfield,$sortorder); $sql.= $this->db->plimit($limit,$offset); $result=$this->db->query($sql); if ($result) { $num = $this->db->num_rows($result); if ($num) { $i = 0; while ($i < $num) { $obj = $this->db->fetch_object($result); if ($shortlist == 1) { $ga[$obj->propalid] = $obj->ref; } else if ($shortlist == 2) { $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')'; } else { $ga[$i]['id'] = $obj->propalid; $ga[$i]['ref'] = $obj->ref; $ga[$i]['name'] = $obj->name; } $i++; } } return $ga; } else { dol_print_error($this->db); return -1; } } /** * Returns an array with the numbers of related invoices * * @return array Array of invoices */ function getInvoiceArrayList() { return $this->InvoiceArrayList($this->id); } /** * Returns an array with id and ref of related invoices * * @param int $id Id propal * @return array Array of invoices id */ function InvoiceArrayList($id) { $ga = array(); $linkedInvoices = array(); $this->fetchObjectLinked($id,$this->element); foreach($this->linkedObjectsIds as $objecttype => $objectid) { // Nouveau système du comon object renvoi des rowid et non un id linéaire de 1 à n // On parcourt donc une liste d'objets en tant qu'objet unique foreach($objectid as $key => $object) { // Cas des factures liees directement if ($objecttype == 'facture') { $linkedInvoices[] = $object; } // Cas des factures liees par un autre objet (ex: commande) else { $this->fetchObjectLinked($object,$objecttype); foreach($this->linkedObjectsIds as $subobjecttype => $subobjectid) { foreach($subobjectid as $subkey => $subobject) { if ($subobjecttype == 'facture') { $linkedInvoices[] = $subobject; } } } } } } if (count($linkedInvoices) > 0) { $sql= "SELECT rowid as facid, facnumber, total, datef as df, fk_user_author, fk_statut, paye"; $sql.= " FROM ".MAIN_DB_PREFIX."facture"; $sql.= " WHERE rowid IN (".implode(',',$linkedInvoices).")"; dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $tab_sqlobj=array(); $nump = $this->db->num_rows($resql); for ($i = 0;$i < $nump;$i++) { $sqlobj = $this->db->fetch_object($resql); $tab_sqlobj[] = $sqlobj; } $this->db->free($resql); $nump = count($tab_sqlobj); if ($nump) { $i = 0; while ($i < $nump) { $obj = array_shift($tab_sqlobj); $ga[$i] = $obj; $i++; } } return $ga; } else { return -1; } } else return $ga; } /** * Delete proposal * * @param User $user Object user that delete * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers * @return int 1 if ok, otherwise if error */ function delete($user, $notrigger=0) { global $conf,$langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $error=0; $this->db->begin(); if (! $notrigger) { // Call trigger $result=$this->call_trigger('PROPAL_DELETE',$user); if ($result < 0) { $error++; } // End call triggers } if (! $error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal = ".$this->id; if ($this->db->query($sql)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal WHERE rowid = ".$this->id; if ($this->db->query($sql)) { // Delete linked object $res = $this->deleteObjectLinked(); if ($res < 0) $error++; // Delete linked contacts $res = $this->delete_linked_contact(); if ($res < 0) $error++; if (! $error) { // We remove directory $ref = dol_sanitizeFileName($this->ref); if ($conf->propal->dir_output && !empty($this->ref)) { $dir = $conf->propal->dir_output . "/" . $ref ; $file = $dir . "/" . $ref . ".pdf"; if (file_exists($file)) { dol_delete_preview($this); if (! dol_delete_file($file,0,0,0,$this)) // For triggers { $this->error='ErrorFailToDeleteFile'; $this->errors=array('ErrorFailToDeleteFile'); $this->db->rollback(); return 0; } } if (file_exists($dir)) { $res=@dol_delete_dir_recursive($dir); if (! $res) { $this->error='ErrorFailToDeleteDir'; $this->errors=array('ErrorFailToDeleteDir'); $this->db->rollback(); return 0; } } } } // Removed extrafields if (! $error) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { $result=$this->deleteExtraFields(); if ($result < 0) { $error++; $errorflag=-4; dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR); } } } if (! $error) { dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG); $this->db->commit(); return 1; } else { $this->error=$this->db->lasterror(); $this->db->rollback(); return 0; } } else { $this->error=$this->db->lasterror(); $this->db->rollback(); return -3; } } else { $this->error=$this->db->lasterror(); $this->db->rollback(); return -2; } } else { $this->db->rollback(); return -1; } } /** * Change the delivery time * * @param int $availability_id Id of new delivery time * @return int >0 if OK, <0 if KO */ function availability($availability_id) { dol_syslog('Propale::availability('.$availability_id.')'); if ($this->statut >= self::STATUS_DRAFT) { $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal'; $sql .= ' SET fk_availability = '.$availability_id; $sql .= ' WHERE rowid='.$this->id; if ( $this->db->query($sql) ) { $this->availability_id = $availability_id; return 1; } else { dol_syslog('Propale::availability Erreur '.$sql.' - '.$this->db->error()); $this->error=$this->db->error(); return -1; } } else { dol_syslog('Propale::availability, etat propale incompatible'); $this->error='Etat propale incompatible '.$this->statut; return -2; } } /** * Change source demand * * @param int $demand_reason_id Id of new source demand * @return int >0 si ok, <0 si ko */ function demand_reason($demand_reason_id) { dol_syslog('Propale::demand_reason('.$demand_reason_id.')'); if ($this->statut >= self::STATUS_DRAFT) { $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal'; $sql .= ' SET fk_input_reason = '.$demand_reason_id; $sql .= ' WHERE rowid='.$this->id; if ( $this->db->query($sql) ) { $this->demand_reason_id = $demand_reason_id; return 1; } else { dol_syslog('Propale::demand_reason Erreur '.$sql.' - '.$this->db->error()); $this->error=$this->db->error(); return -1; } } else { dol_syslog('Propale::demand_reason, etat propale incompatible'); $this->error='Etat propale incompatible '.$this->statut; return -2; } } /** * Object Proposal Information * * @param int $id Proposal id * @return void */ function info($id) { $sql = "SELECT c.rowid, "; $sql.= " c.datec, c.date_valid as datev, c.date_cloture as dateo,"; $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture"; $sql.= " FROM ".MAIN_DB_PREFIX."propal as c"; $sql.= " WHERE c.rowid = ".$id; $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; $this->date_creation = $this->db->jdate($obj->datec); $this->date_validation = $this->db->jdate($obj->datev); $this->date_cloture = $this->db->jdate($obj->dateo); $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; } } $this->db->free($result); } else { dol_print_error($this->db); } } /** * Return label of status of proposal (draft, validated, ...) * * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto * @return string Label */ function getLibStatut($mode=0) { return $this->LibStatut($this->statut,$mode); } /** * Return label of a status (draft, validated, ...) * * @param int $statut id statut * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto * @return string Label */ function LibStatut($statut,$mode=1) { global $langs; $langs->load("propal"); if ($statut==self::STATUS_DRAFT) $statuttrans='statut0'; if ($statut==self::STATUS_VALIDATED) $statuttrans='statut1'; if ($statut==self::STATUS_SIGNED) $statuttrans='statut3'; if ($statut==self::STATUS_NOTSIGNED) $statuttrans='statut5'; if ($statut==self::STATUS_BILLED) $statuttrans='statut6'; if ($mode == 0) return $this->labelstatut[$statut]; if ($mode == 1) return $this->labelstatut_short[$statut]; if ($mode == 2) return img_picto($this->labelstatut_short[$statut], $statuttrans).' '.$this->labelstatut_short[$statut]; if ($mode == 3) return img_picto($this->labelstatut[$statut], $statuttrans); if ($mode == 4) return img_picto($this->labelstatut[$statut],$statuttrans).' '.$this->labelstatut[$statut]; if ($mode == 5) return '<span class="hideonsmartphone">'.$this->labelstatut_short[$statut].' </span>'.img_picto($this->labelstatut_short[$statut],$statuttrans); } /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * * @param User $user Object user * @param int $mode "opened" for proposal to close, "signed" for proposal to invoice * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK */ function load_board($user,$mode) { global $conf, $user, $langs; $clause = " WHERE"; $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin"; $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; if (!$user->rights->societe->client->voir && !$user->societe_id) { $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc"; $sql.= " WHERE sc.fk_user = " .$user->id; $clause = " AND"; } $sql.= $clause." p.entity IN (".getEntity('propal', 1).")"; if ($mode == 'opened') $sql.= " AND p.fk_statut = ".self::STATUS_VALIDATED; if ($mode == 'signed') $sql.= " AND p.fk_statut = ".self::STATUS_SIGNED; if ($user->societe_id) $sql.= " AND p.fk_soc = ".$user->societe_id; $resql=$this->db->query($sql); if ($resql) { $langs->load("propal"); $now=dol_now(); if ($mode == 'opened') { $delay_warning=$conf->propal->cloture->warning_delay; $statut = self::STATUS_VALIDATED; $label = $langs->trans("PropalsToClose"); } if ($mode == 'signed') { $delay_warning=$conf->propal->facturation->warning_delay; $statut = self::STATUS_SIGNED; $label = $langs->trans("PropalsToBill"); } $response = new WorkboardResponse(); $response->warning_delay = $delay_warning/60/60/24; $response->label = $label; $response->url = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut; $response->img = img_object($langs->trans("Propals"),"propal"); // This assignment in condition is not a bug. It allows walking the results. while ($obj=$this->db->fetch_object($resql)) { $response->nbtodo++; if ($mode == 'opened') { $datelimit = $this->db->jdate($obj->datefin); if ($datelimit < ($now - $delay_warning)) { $response->nbtodolate++; } } // TODO Definir regle des propales a facturer en retard // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++; } return $response; } else { $this->error=$this->db->error(); return -1; } } /** * Initialise an instance with random values. * Used to build previews or test instances. * id must be 0 if object instance is a specimen. * * @return void */ function initAsSpecimen() { global $user,$langs,$conf; // Charge tableau des produits prodids $prodids = array(); $sql = "SELECT rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."product"; $sql.= " WHERE entity IN (".getEntity('product', 1).")"; $resql = $this->db->query($sql); if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; } } // Initialise parametres $this->id=0; $this->ref = 'SPECIMEN'; $this->ref_client='NEMICEPS'; $this->specimen=1; $this->socid = 1; $this->date = time(); $this->fin_validite = $this->date+3600*24*30; $this->cond_reglement_id = 1; $this->cond_reglement_code = 'RECEP'; $this->mode_reglement_id = 7; $this->mode_reglement_code = 'CHQ'; $this->availability_id = 1; $this->availability_code = 'AV_NOW'; $this->demand_reason_id = 1; $this->demand_reason_code = 'SRC_00'; $this->note_public='This is a comment (public)'; $this->note_private='This is a comment (private)'; // Lines $nbp = 5; $xnbp = 0; while ($xnbp < $nbp) { $line=new PropaleLigne($this->db); $line->desc=$langs->trans("Description")." ".$xnbp; $line->qty=1; $line->subprice=100; $line->price=100; $line->tva_tx=19.6; $line->localtax1_tx=0; $line->localtax2_tx=0; if ($xnbp == 2) { $line->total_ht=50; $line->total_ttc=59.8; $line->total_tva=9.8; $line->remise_percent=50; } else { $line->total_ht=100; $line->total_ttc=119.6; $line->total_tva=19.6; $line->remise_percent=00; } $prodid = rand(1, $num_prods); $line->fk_product=$prodids[$prodid]; $this->lines[$xnbp]=$line; $this->total_ht += $line->total_ht; $this->total_tva += $line->total_tva; $this->total_ttc += $line->total_ttc; $xnbp++; } } /** * Charge indicateurs this->nb de tableau de bord * * @return int <0 if ko, >0 if ok */ function load_state_board() { global $conf, $user; $this->nb=array(); $clause = "WHERE"; $sql = "SELECT count(p.rowid) as nb"; $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; if (!$user->rights->societe->client->voir && !$user->societe_id) { $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql.= " WHERE sc.fk_user = " .$user->id; $clause = "AND"; } $sql.= " ".$clause." p.entity IN (".getEntity('propal', 1).")"; $resql=$this->db->query($sql); if ($resql) { // This assignment in condition is not a bug. It allows walking the results. while ($obj=$this->db->fetch_object($resql)) { $this->nb["proposals"]=$obj->nb; } $this->db->free($resql); return 1; } else { dol_print_error($this->db); $this->error=$this->db->error(); return -1; } } /** * Returns the reference to the following non used Proposal used depending on the active numbering module * defined into PROPALE_ADDON * * @param Societe $soc Object thirdparty * @return string Reference libre pour la propale */ function getNextNumRef($soc) { global $conf, $db, $langs; $langs->load("propal"); if (! empty($conf->global->PROPALE_ADDON)) { $mybool=false; $file = $conf->global->PROPALE_ADDON.".php"; $classname = $conf->global->PROPALE_ADDON; // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/propale/"); // Load file with numbering class (if found) $mybool|=@include_once $dir.$file; } if (! $mybool) { dol_print_error('',"Failed to include file ".$file); return ''; } $obj = new $classname(); $numref = ""; $numref = $obj->getNextValue($soc,$this); if ($numref != "") { return $numref; } else { $this->error=$obj->error; //dol_print_error($db,"Propale::getNextNumRef ".$obj->error); return ""; } } else { $langs->load("errors"); print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete"); return ""; } } /** * Return clicable link of object (with eventually picto) * * @param int $withpicto Add picto into link * @param string $option Where point the link ('expedition', 'document', ...) * @param string $get_params Parametres added to url * @return string String with URL */ function getNomUrl($withpicto=0,$option='', $get_params='') { global $langs; $result=''; $label = '<u>' . $langs->trans("ShowPropal") . '</u>'; if (! empty($this->ref)) $label.= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref; if (! empty($this->ref_client)) $label.= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client; if (! empty($this->total_ht)) $label.= '<br><b>' . $langs->trans('AmountHT') . ':</b> ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); if (! empty($this->total_tva)) $label.= '<br><b>' . $langs->trans('TVA') . ':</b> ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); if (! empty($this->total_ttc)) $label.= '<br><b>' . $langs->trans('AmountTTC') . ':</b> ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; if ($option == '') { $link = '<a href="'.DOL_URL_ROOT.'/comm/propal.php?id='.$this->id. $get_params .$linkclose; } if ($option == 'compta') { // deprecated $link = '<a href="'.DOL_URL_ROOT.'/comm/propal.php?id='.$this->id. $get_params .$linkclose; } if ($option == 'expedition') { $link = '<a href="'.DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id. $get_params .$linkclose; } if ($option == 'document') { $link = '<a href="'.DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id. $get_params .$linkclose; } $linkend='</a>'; $picto='propal'; if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); if ($withpicto && $withpicto != 2) $result.=' '; $result.=$link.$this->ref.$linkend; return $result; } /** * Retrieve an array of propal lines * * @return int <0 if ko, >0 if ok */ function getLinesArray() { $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,'; $sql.= ' pt.qty, pt.tva_tx, pt.remise_percent, pt.subprice, pt.info_bits,'; $sql.= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code, pt.localtax1_tx, pt.localtax2_tx,'; $sql.= ' pt.date_start, pt.date_end, pt.product_type, pt.rang, pt.fk_parent_line,'; $sql.= ' pt.fk_unit,'; $sql.= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid,'; $sql.= ' p.description as product_desc,'; $sql.= ' p.entity'; $sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pt'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid'; $sql.= ' WHERE pt.fk_propal = '.$this->id; $sql.= ' ORDER BY pt.rang ASC, pt.rowid'; dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); $i = 0; while ($i < $num) { $obj = $this->db->fetch_object($resql); $this->lines[$i] = new PropaleLigne($this->db); $this->lines[$i]->id = $obj->rowid; // for backward compatibility $this->lines[$i]->rowid = $obj->rowid; $this->lines[$i]->label = $obj->custom_label; $this->lines[$i]->description = $obj->description; $this->lines[$i]->fk_product = $obj->fk_product; $this->lines[$i]->ref = $obj->ref; $this->lines[$i]->entity = $obj->entity; // Product entity $this->lines[$i]->product_label = $obj->product_label; $this->lines[$i]->product_desc = $obj->product_desc; $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated $this->lines[$i]->product_type = $obj->product_type; $this->lines[$i]->qty = $obj->qty; $this->lines[$i]->subprice = $obj->subprice; $this->lines[$i]->fk_remise_except = $obj->fk_remise_except; $this->lines[$i]->remise_percent = $obj->remise_percent; $this->lines[$i]->tva_tx = $obj->tva_tx; $this->lines[$i]->info_bits = $obj->info_bits; $this->lines[$i]->total_ht = $obj->total_ht; $this->lines[$i]->total_tva = $obj->total_tva; $this->lines[$i]->total_ttc = $obj->total_ttc; $this->lines[$i]->fk_fournprice = $obj->fk_fournprice; $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht); $this->lines[$i]->pa_ht = $marginInfos[0]; $this->lines[$i]->marge_tx = $marginInfos[1]; $this->lines[$i]->marque_tx = $marginInfos[2]; $this->lines[$i]->fk_parent_line = $obj->fk_parent_line; $this->lines[$i]->special_code = $obj->special_code; $this->lines[$i]->rang = $obj->rang; $this->lines[$i]->date_start = $this->db->jdate($obj->date_start); $this->lines[$i]->date_end = $this->db->jdate($obj->date_end); $this->lines[$i]->fk_unit = $obj->fk_unit; $i++; } $this->db->free($resql); return 1; } else { $this->error=$this->db->error(); return -1; } } /** * Create a document onto disk according to template module. * * @param string $modele Force model to use ('' to not force) * @param Translate $outputlangs Object langs to use for output * @param int $hidedetails Hide details of lines * @param int $hidedesc Hide description * @param int $hideref Hide ref * @return int 0 if KO, 1 if OK */ public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) { global $conf,$user,$langs; $langs->load("propale"); // Positionne le modele sur le nom du modele a utiliser if (! dol_strlen($modele)) { if (! empty($conf->global->PROPALE_ADDON_PDF)) { $modele = $conf->global->PROPALE_ADDON_PDF; } else { $modele = 'azur'; } } $modelpath = "core/modules/propale/doc/"; return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); } /** * Function used to replace a thirdparty id with another one. * * @param DoliDB $db Database handler * @param int $origin_id Old thirdparty id * @param int $dest_id New thirdparty id * @return bool */ public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id) { $tables = array( 'propal' ); return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); } } /** * \class PropaleLigne * \brief Class to manage commercial proposal lines */ class PropaleLigne extends CommonObjectLine { public $element='propaldet'; public $table_element='propaldet'; var $oldline; // From llx_propaldet var $fk_propal; var $fk_parent_line; var $desc; // Description ligne var $fk_product; // Id produit predefini /** * @deprecated * @see product_type */ var $fk_product_type; /** * Product type. * @var int * @see Product::TYPE_PRODUCT, Product::TYPE_SERVICE */ var $product_type = Product::TYPE_PRODUCT; var $qty; var $tva_tx; var $subprice; var $remise_percent; var $fk_remise_except; var $rang = 0; var $fk_fournprice; var $pa_ht; var $marge_tx; var $marque_tx; var $special_code; // Tag for special lines (exlusive tags) // 1: frais de port // 2: ecotaxe // 3: option line (when qty = 0) var $info_bits = 0; // Liste d'options cumulables: // Bit 0: 0 si TVA normal - 1 si TVA NPR // Bit 1: 0 ligne normale - 1 si ligne de remise fixe var $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne var $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne var $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne /** * @deprecated * @see $remise_percent, $fk_remise_except */ var $remise; /** * @deprecated * @see subprice */ var $price; // From llx_product /** * @deprecated * @see product_ref */ var $ref; /** * Product reference * @var string */ public $product_ref; /** * @deprecated * @see product_label */ var $libelle; /** * Product label * @var string */ public $product_label; /** * Product description * @var string */ public $product_desc; var $localtax1_tx; // Local tax 1 var $localtax2_tx; // Local tax 2 var $localtax1_type; // Local tax 1 type var $localtax2_type; // Local tax 2 type var $total_localtax1; // Line total local tax 1 var $total_localtax2; // Line total local tax 2 var $date_start; var $date_end; var $skip_update_total; // Skip update price total for special lines /** * Class line Contructor * * @param DoliDB $db Database handler */ function __construct($db) { $this->db= $db; } /** * Retrieve the propal line object * * @param int $rowid Propal line id * @return int <0 if KO, >0 if OK */ function fetch($rowid) { $sql = 'SELECT pd.rowid, pd.fk_propal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.tva_tx,'; $sql.= ' pd.remise, pd.remise_percent, pd.fk_remise_except, pd.subprice,'; $sql.= ' pd.info_bits, pd.total_ht, pd.total_tva, pd.total_ttc, pd.fk_product_fournisseur_price as fk_fournprice, pd.buy_price_ht as pa_ht, pd.special_code, pd.rang,'; $sql.= ' pd.fk_unit,'; $sql.= ' pd.localtax1_tx, pd.localtax2_tx, pd.total_localtax1, pd.total_localtax2,'; $sql.= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,'; $sql.= ' pd.date_start, pd.date_end, pd.product_type'; $sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pd'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pd.fk_product = p.rowid'; $sql.= ' WHERE pd.rowid = '.$rowid; $result = $this->db->query($sql); if ($result) { $objp = $this->db->fetch_object($result); $this->id = $objp->rowid; $this->rowid = $objp->rowid; // deprecated $this->fk_propal = $objp->fk_propal; $this->fk_parent_line = $objp->fk_parent_line; $this->label = $objp->custom_label; $this->desc = $objp->description; $this->qty = $objp->qty; $this->price = $objp->price; // deprecated $this->subprice = $objp->subprice; $this->tva_tx = $objp->tva_tx; $this->remise = $objp->remise; // deprecated $this->remise_percent = $objp->remise_percent; $this->fk_remise_except = $objp->fk_remise_except; $this->fk_product = $objp->fk_product; $this->info_bits = $objp->info_bits; $this->total_ht = $objp->total_ht; $this->total_tva = $objp->total_tva; $this->total_ttc = $objp->total_ttc; $this->fk_fournprice = $objp->fk_fournprice; $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht); $this->pa_ht = $marginInfos[0]; $this->marge_tx = $marginInfos[1]; $this->marque_tx = $marginInfos[2]; $this->special_code = $objp->special_code; $this->product_type = $objp->product_type; $this->rang = $objp->rang; $this->ref = $objp->product_ref; // deprecated $this->product_ref = $objp->product_ref; $this->libelle = $objp->product_label; // deprecated $this->product_label = $objp->product_label; $this->product_desc = $objp->product_desc; $this->fk_unit = $objp->fk_unit; $this->date_start = $this->db->jdate($objp->date_start); $this->date_end = $this->db->jdate($objp->date_end); $this->db->free($result); return 1; } else { return -1; } } /** * Insert object line propal in database * * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers * @return int <0 if KO, >0 if OK */ function insert($notrigger=0) { global $conf,$langs,$user; $error=0; dol_syslog(get_class($this)."::insert rang=".$this->rang); // Clean parameters if (empty($this->tva_tx)) $this->tva_tx=0; if (empty($this->localtax1_tx)) $this->localtax1_tx=0; if (empty($this->localtax2_tx)) $this->localtax2_tx=0; if (empty($this->localtax1_type)) $this->localtax1_type=0; if (empty($this->localtax2_type)) $this->localtax2_type=0; if (empty($this->total_localtax1)) $this->total_localtax1=0; if (empty($this->total_localtax2)) $this->total_localtax2=0; if (empty($this->rang)) $this->rang=0; if (empty($this->remise)) $this->remise=0; if (empty($this->remise_percent) || ! is_numeric($this->remise_percent)) $this->remise_percent=0; if (empty($this->info_bits)) $this->info_bits=0; if (empty($this->special_code)) $this->special_code=0; if (empty($this->fk_parent_line)) $this->fk_parent_line=0; if (empty($this->fk_fournprice)) $this->fk_fournprice=0; if (! is_numeric($this->qty)) $this->qty = 0; if (empty($this->pa_ht)) $this->pa_ht=0; // si prix d'achat non renseigne et utilise pour calcul des marges alors prix achat = prix vente if ($this->pa_ht == 0) { if ($this->subprice > 0 && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) $this->pa_ht = $this->subprice * (1 - $this->remise_percent / 100); } // Check parameters if ($this->product_type < 0) return -1; $this->db->begin(); // Insert line into database $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'propaldet'; $sql.= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,'; $sql.= ' fk_remise_except, qty, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; $sql.= ' subprice, remise_percent, '; $sql.= ' info_bits, '; $sql.= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,'; $sql.= ' fk_unit,'; $sql.= ' date_start, date_end)'; $sql.= " VALUES (".$this->fk_propal.","; $sql.= " ".($this->fk_parent_line>0?"'".$this->fk_parent_line."'":"null").","; $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").","; $sql.= " '".$this->db->escape($this->desc)."',"; $sql.= " ".($this->fk_product?"'".$this->fk_product."'":"null").","; $sql.= " '".$this->product_type."',"; $sql.= " ".($this->fk_remise_except?"'".$this->fk_remise_except."'":"null").","; $sql.= " ".price2num($this->qty).","; $sql.= " ".price2num($this->tva_tx).","; $sql.= " ".price2num($this->localtax1_tx).","; $sql.= " ".price2num($this->localtax2_tx).","; $sql.= " '".$this->localtax1_type."',"; $sql.= " '".$this->localtax2_type."',"; $sql.= " ".($this->subprice?price2num($this->subprice):"null").","; $sql.= " ".price2num($this->remise_percent).","; $sql.= " ".(isset($this->info_bits)?"'".$this->info_bits."'":"null").","; $sql.= " ".price2num($this->total_ht).","; $sql.= " ".price2num($this->total_tva).","; $sql.= " ".price2num($this->total_localtax1).","; $sql.= " ".price2num($this->total_localtax2).","; $sql.= " ".price2num($this->total_ttc).","; $sql.= " ".(!empty($this->fk_fournprice)?"'".$this->fk_fournprice."'":"null").","; $sql.= " ".(isset($this->pa_ht)?"'".price2num($this->pa_ht)."'":"null").","; $sql.= ' '.$this->special_code.','; $sql.= ' '.$this->rang.','; $sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit).','; $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").','; $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); $sql.= ')'; dol_syslog(get_class($this).'::insert', LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet'); if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { $this->id=$this->rowid; $result=$this->insertExtraFields(); if ($result < 0) { $error++; } } if (! $notrigger) { // Call trigger $result=$this->call_trigger('LINEPROPAL_INSERT',$user); if ($result < 0) { $this->db->rollback(); return -1; } // End call triggers } $this->db->commit(); return 1; } else { $this->error=$this->db->error()." sql=".$sql; $this->db->rollback(); return -1; } } /** * Delete line in database * * @return int <0 if ko, >0 if ok */ function delete() { global $conf,$langs,$user; $error=0; $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE rowid = ".$this->rowid; dol_syslog("PropaleLigne::delete", LOG_DEBUG); if ($this->db->query($sql) ) { // Remove extrafields if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used { $this->id=$this->rowid; $result=$this->deleteExtraFields(); if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); } } // Call trigger $result=$this->call_trigger('LINEPROPAL_DELETE',$user); if ($result < 0) { $this->db->rollback(); return -1; } // End call triggers $this->db->commit(); return 1; } else { $this->error=$this->db->error()." sql=".$sql; $this->db->rollback(); return -1; } } /** * Update propal line object into DB * * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers * @return int <0 if ko, >0 if ok */ function update($notrigger=0) { global $conf,$langs,$user; $error=0; // Clean parameters if (empty($this->tva_tx)) $this->tva_tx=0; if (empty($this->localtax1_tx)) $this->localtax1_tx=0; if (empty($this->localtax2_tx)) $this->localtax2_tx=0; if (empty($this->total_localtax1)) $this->total_localtax1=0; if (empty($this->total_localtax2)) $this->total_localtax2=0; if (empty($this->localtax1_type)) $this->localtax1_type=0; if (empty($this->localtax2_type)) $this->localtax2_type=0; if (empty($this->marque_tx)) $this->marque_tx=0; if (empty($this->marge_tx)) $this->marge_tx=0; if (empty($this->price)) $this->price=0; // TODO A virer if (empty($this->remise)) $this->remise=0; // TODO A virer if (empty($this->remise_percent)) $this->remise_percent=0; if (empty($this->info_bits)) $this->info_bits=0; if (empty($this->special_code)) $this->special_code=0; if (empty($this->fk_parent_line)) $this->fk_parent_line=0; if (empty($this->fk_fournprice)) $this->fk_fournprice=0; if (empty($this->subprice)) $this->subprice=0; if (empty($this->pa_ht)) $this->pa_ht=0; // si prix d'achat non renseigne et utilise pour calcul des marges alors prix achat = prix vente if ($this->pa_ht == 0) { if ($this->subprice > 0 && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) $this->pa_ht = $this->subprice * (1 - $this->remise_percent / 100); } $this->db->begin(); // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; $sql.= " description='".$this->db->escape($this->desc)."'"; $sql.= " , label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); $sql.= " , product_type=".$this->product_type; $sql.= " , tva_tx='".price2num($this->tva_tx)."'"; $sql.= " , localtax1_tx=".price2num($this->localtax1_tx); $sql.= " , localtax2_tx=".price2num($this->localtax2_tx); $sql.= " , localtax1_type='".$this->localtax1_type."'"; $sql.= " , localtax2_type='".$this->localtax2_type."'"; $sql.= " , qty='".price2num($this->qty)."'"; $sql.= " , subprice=".price2num($this->subprice).""; $sql.= " , remise_percent=".price2num($this->remise_percent).""; $sql.= " , price=".price2num($this->price).""; // TODO A virer $sql.= " , remise=".price2num($this->remise).""; // TODO A virer $sql.= " , info_bits='".$this->info_bits."'"; if (empty($this->skip_update_total)) { $sql.= " , total_ht=".price2num($this->total_ht).""; $sql.= " , total_tva=".price2num($this->total_tva).""; $sql.= " , total_ttc=".price2num($this->total_ttc).""; $sql.= " , total_localtax1=".price2num($this->total_localtax1).""; $sql.= " , total_localtax2=".price2num($this->total_localtax2).""; } $sql.= " , fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->fk_fournprice."'":"null"); $sql.= " , buy_price_ht=".price2num($this->pa_ht); if (strlen($this->special_code)) $sql.= " , special_code=".$this->special_code; $sql.= " , fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null"); if (! empty($this->rang)) $sql.= ", rang=".$this->rang; $sql.= " , date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null"); $sql.= " , date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); $sql.= " , fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); $sql.= " WHERE rowid = ".$this->rowid; dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { $this->id=$this->rowid; $result=$this->insertExtraFields(); if ($result < 0) { $error++; } } if (! $notrigger) { // Call trigger $result=$this->call_trigger('LINEPROPAL_UPDATE',$user); if ($result < 0) { $this->db->rollback(); return -1; } // End call triggers } $this->db->commit(); return 1; } else { $this->error=$this->db->error(); $this->db->rollback(); return -2; } } /** * Update DB line fields total_xxx * Used by migration * * @return int <0 if ko, >0 if ok */ function update_total() { $this->db->begin(); // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; $sql.= " total_ht=".price2num($this->total_ht,'MT').""; $sql.= ",total_tva=".price2num($this->total_tva,'MT').""; $sql.= ",total_ttc=".price2num($this->total_ttc,'MT').""; $sql.= " WHERE rowid = ".$this->rowid; dol_syslog("PropaleLigne::update_total", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $this->db->commit(); return 1; } else { $this->error=$this->db->error(); $this->db->rollback(); return -2; } } }
maestrano/dolibarr
htdocs/comm/propal/class/propal.class.php
PHP
gpl-3.0
122,130
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ #include "_cv.h" static const double eps = 1e-6; static CvStatus icvFitLine2D_wods( CvPoint2D32f * points, int _count, float *weights, float *line ) { double x = 0, y = 0, x2 = 0, y2 = 0, xy = 0, w = 0; double dx2, dy2, dxy; int i; int count = _count; float t; /* Calculating the average of x and y... */ if( weights == 0 ) { for( i = 0; i < count; i += 1 ) { x += points[i].x; y += points[i].y; x2 += points[i].x * points[i].x; y2 += points[i].y * points[i].y; xy += points[i].x * points[i].y; } w = (float) count; } else { for( i = 0; i < count; i += 1 ) { x += weights[i] * points[i].x; y += weights[i] * points[i].y; x2 += weights[i] * points[i].x * points[i].x; y2 += weights[i] * points[i].y * points[i].y; xy += weights[i] * points[i].x * points[i].y; w += weights[i]; } } x /= w; y /= w; x2 /= w; y2 /= w; xy /= w; dx2 = x2 - x * x; dy2 = y2 - y * y; dxy = xy - x * y; t = (float) atan2( 2 * dxy, dx2 - dy2 ) / 2; line[0] = (float) cos( t ); line[1] = (float) sin( t ); line[2] = (float) x; line[3] = (float) y; return CV_NO_ERR; } static CvStatus icvFitLine3D_wods( CvPoint3D32f * points, int count, float *weights, float *line ) { int i; float w0 = 0; float x0 = 0, y0 = 0, z0 = 0; float x2 = 0, y2 = 0, z2 = 0, xy = 0, yz = 0, xz = 0; float dx2, dy2, dz2, dxy, dxz, dyz; float *v; float n; float det[9], evc[9], evl[3]; memset( evl, 0, 3*sizeof(evl[0])); memset( evc, 0, 9*sizeof(evl[0])); if( weights ) { for( i = 0; i < count; i++ ) { float x = points[i].x; float y = points[i].y; float z = points[i].z; float w = weights[i]; x2 += x * x * w; xy += x * y * w; xz += x * z * w; y2 += y * y * w; yz += y * z * w; z2 += z * z * w; x0 += x * w; y0 += y * w; z0 += z * w; w0 += w; } } else { for( i = 0; i < count; i++ ) { float x = points[i].x; float y = points[i].y; float z = points[i].z; x2 += x * x; xy += x * y; xz += x * z; y2 += y * y; yz += y * z; z2 += z * z; x0 += x; y0 += y; z0 += z; } w0 = (float) count; } x2 /= w0; xy /= w0; xz /= w0; y2 /= w0; yz /= w0; z2 /= w0; x0 /= w0; y0 /= w0; z0 /= w0; dx2 = x2 - x0 * x0; dxy = xy - x0 * y0; dxz = xz - x0 * z0; dy2 = y2 - y0 * y0; dyz = yz - y0 * z0; dz2 = z2 - z0 * z0; det[0] = dz2 + dy2; det[1] = -dxy; det[2] = -dxz; det[3] = det[1]; det[4] = dx2 + dz2; det[5] = -dyz; det[6] = det[2]; det[7] = det[5]; det[8] = dy2 + dx2; /* Searching for a eigenvector of det corresponding to the minimal eigenvalue */ #if 1 { CvMat _det = cvMat( 3, 3, CV_32F, det ); CvMat _evc = cvMat( 3, 3, CV_32F, evc ); CvMat _evl = cvMat( 3, 1, CV_32F, evl ); cvEigenVV( &_det, &_evc, &_evl, 0 ); i = evl[0] < evl[1] ? (evl[0] < evl[2] ? 0 : 2) : (evl[1] < evl[2] ? 1 : 2); } #else { CvMat _det = cvMat( 3, 3, CV_32F, det ); CvMat _evc = cvMat( 3, 3, CV_32F, evc ); CvMat _evl = cvMat( 1, 3, CV_32F, evl ); cvSVD( &_det, &_evl, &_evc, 0, CV_SVD_MODIFY_A+CV_SVD_U_T ); } i = 2; #endif v = &evc[i * 3]; n = (float) sqrt( (double)v[0] * v[0] + (double)v[1] * v[1] + (double)v[2] * v[2] ); n = (float)MAX(n, eps); line[0] = v[0] / n; line[1] = v[1] / n; line[2] = v[2] / n; line[3] = x0; line[4] = y0; line[5] = z0; return CV_NO_ERR; } static double icvCalcDist2D( CvPoint2D32f * points, int count, float *_line, float *dist ) { int j; float px = _line[2], py = _line[3]; float nx = _line[1], ny = -_line[0]; double sum_dist = 0.; for( j = 0; j < count; j++ ) { float x, y; x = points[j].x - px; y = points[j].y - py; dist[j] = (float) fabs( nx * x + ny * y ); sum_dist += dist[j]; } return sum_dist; } static double icvCalcDist3D( CvPoint3D32f * points, int count, float *_line, float *dist ) { int j; float px = _line[3], py = _line[4], pz = _line[5]; float vx = _line[0], vy = _line[1], vz = _line[2]; double sum_dist = 0.; for( j = 0; j < count; j++ ) { float x, y, z; double p1, p2, p3; x = points[j].x - px; y = points[j].y - py; z = points[j].z - pz; p1 = vy * z - vz * y; p2 = vz * x - vx * z; p3 = vx * y - vy * x; dist[j] = (float) sqrt( p1*p1 + p2*p2 + p3*p3 ); sum_dist += dist[j]; } return sum_dist; } static void icvWeightL1( float *d, int count, float *w ) { int i; for( i = 0; i < count; i++ ) { double t = fabs( (double) d[i] ); w[i] = (float)(1. / MAX(t, eps)); } } static void icvWeightL12( float *d, int count, float *w ) { int i; for( i = 0; i < count; i++ ) { w[i] = 1.0f / (float) sqrt( 1 + (double) (d[i] * d[i] * 0.5) ); } } static void icvWeightHuber( float *d, int count, float *w, float _c ) { int i; const float c = _c <= 0 ? 1.345f : _c; for( i = 0; i < count; i++ ) { if( d[i] < c ) w[i] = 1.0f; else w[i] = c/d[i]; } } static void icvWeightFair( float *d, int count, float *w, float _c ) { int i; const float c = _c == 0 ? 1 / 1.3998f : 1 / _c; for( i = 0; i < count; i++ ) { w[i] = 1 / (1 + d[i] * c); } } static void icvWeightWelsch( float *d, int count, float *w, float _c ) { int i; const float c = _c == 0 ? 1 / 2.9846f : 1 / _c; for( i = 0; i < count; i++ ) { w[i] = (float) exp( -d[i] * d[i] * c * c ); } } /* Takes an array of 2D points, type of distance (including user-defined distance specified by callbacks, fills the array of four floats with line parameters A, B, C, D, where (A, B) is the normalized direction vector, (C, D) is the point that belongs to the line. */ static CvStatus icvFitLine2D( CvPoint2D32f * points, int count, int dist, float _param, float reps, float aeps, float *line ) { double EPS = count*FLT_EPSILON; void (*calc_weights) (float *, int, float *) = 0; void (*calc_weights_param) (float *, int, float *, float) = 0; float *w; /* weights */ float *r; /* square distances */ int i, j, k; float _line[6], _lineprev[6]; float rdelta = reps != 0 ? reps : 1.0f; float adelta = aeps != 0 ? aeps : 0.01f; double min_err = DBL_MAX, err = 0; CvRNG rng = cvRNG(-1); memset( line, 0, 4*sizeof(line[0]) ); switch (dist) { case CV_DIST_L2: return icvFitLine2D_wods( points, count, 0, line ); case CV_DIST_L1: calc_weights = icvWeightL1; break; case CV_DIST_L12: calc_weights = icvWeightL12; break; case CV_DIST_FAIR: calc_weights_param = icvWeightFair; break; case CV_DIST_WELSCH: calc_weights_param = icvWeightWelsch; break; case CV_DIST_HUBER: calc_weights_param = icvWeightHuber; break; /*case CV_DIST_USER: calc_weights = (void ( * )(float *, int, float *)) _PFP.fp; break;*/ default: return CV_BADFACTOR_ERR; } w = (float *) cvAlloc( count * sizeof( float )); r = (float *) cvAlloc( count * sizeof( float )); for( k = 0; k < 20; k++ ) { int first = 1; for( i = 0; i < count; i++ ) w[i] = 0.f; for( i = 0; i < MIN(count,10); ) { j = cvRandInt(&rng) % count; if( w[j] < FLT_EPSILON ) { w[j] = 1.f; i++; } } icvFitLine2D_wods( points, count, w, _line ); for( i = 0; i < 30; i++ ) { double sum_w = 0; if( first ) { first = 0; } else { double t = _line[0] * _lineprev[0] + _line[1] * _lineprev[1]; t = MAX(t,-1.); t = MIN(t,1.); if( fabs(acos(t)) < adelta ) { float x, y, d; x = (float) fabs( _line[2] - _lineprev[2] ); y = (float) fabs( _line[3] - _lineprev[3] ); d = x > y ? x : y; if( d < rdelta ) break; } } /* calculate distances */ err = icvCalcDist2D( points, count, _line, r ); if( err < EPS ) break; /* calculate weights */ if( calc_weights ) calc_weights( r, count, w ); else calc_weights_param( r, count, w, _param ); for( j = 0; j < count; j++ ) sum_w += w[j]; if( fabs(sum_w) > FLT_EPSILON ) { sum_w = 1./sum_w; for( j = 0; j < count; j++ ) w[j] = (float)(w[j]*sum_w); } else { for( j = 0; j < count; j++ ) w[j] = 1.f; } /* save the line parameters */ memcpy( _lineprev, _line, 4 * sizeof( float )); /* Run again... */ icvFitLine2D_wods( points, count, w, _line ); } if( err < min_err ) { min_err = err; memcpy( line, _line, 4 * sizeof(line[0])); if( err < EPS ) break; } } cvFree( &w ); cvFree( &r ); return CV_OK; } /* Takes an array of 3D points, type of distance (including user-defined distance specified by callbacks, fills the array of four floats with line parameters A, B, C, D, E, F, where (A, B, C) is the normalized direction vector, (D, E, F) is the point that belongs to the line. */ static CvStatus icvFitLine3D( CvPoint3D32f * points, int count, int dist, float _param, float reps, float aeps, float *line ) { double EPS = count*FLT_EPSILON; void (*calc_weights) (float *, int, float *) = 0; void (*calc_weights_param) (float *, int, float *, float) = 0; float *w; /* weights */ float *r; /* square distances */ int i, j, k; float _line[6], _lineprev[6]; float rdelta = reps != 0 ? reps : 1.0f; float adelta = aeps != 0 ? aeps : 0.01f; double min_err = DBL_MAX, err = 0; CvRNG rng = cvRNG(-1); memset( line, 0, 6*sizeof(line[0]) ); switch (dist) { case CV_DIST_L2: return icvFitLine3D_wods( points, count, 0, line ); case CV_DIST_L1: calc_weights = icvWeightL1; break; case CV_DIST_L12: calc_weights = icvWeightL12; break; case CV_DIST_FAIR: calc_weights_param = icvWeightFair; break; case CV_DIST_WELSCH: calc_weights_param = icvWeightWelsch; break; case CV_DIST_HUBER: calc_weights_param = icvWeightHuber; break; /*case CV_DIST_USER: _PFP.p = param; calc_weights = (void ( * )(float *, int, float *)) _PFP.fp; break;*/ default: return CV_BADFACTOR_ERR; } w = (float *) cvAlloc( count * sizeof( float )); r = (float *) cvAlloc( count * sizeof( float )); for( k = 0; k < 20; k++ ) { int first = 1; for( i = 0; i < count; i++ ) w[i] = 0.f; for( i = 0; i < MIN(count,10); ) { j = cvRandInt(&rng) % count; if( w[j] < FLT_EPSILON ) { w[j] = 1.f; i++; } } icvFitLine3D_wods( points, count, w, _line ); for( i = 0; i < 30; i++ ) { double sum_w = 0; if( first ) { first = 0; } else { double t = _line[0] * _lineprev[0] + _line[1] * _lineprev[1] + _line[2] * _lineprev[2]; t = MAX(t,-1.); t = MIN(t,1.); if( fabs(acos(t)) < adelta ) { float x, y, z, ax, ay, az, dx, dy, dz, d; x = _line[3] - _lineprev[3]; y = _line[4] - _lineprev[4]; z = _line[5] - _lineprev[5]; ax = _line[0] - _lineprev[0]; ay = _line[1] - _lineprev[1]; az = _line[2] - _lineprev[2]; dx = (float) fabs( y * az - z * ay ); dy = (float) fabs( z * ax - x * az ); dz = (float) fabs( x * ay - y * ax ); d = dx > dy ? (dx > dz ? dx : dz) : (dy > dz ? dy : dz); if( d < rdelta ) break; } } /* calculate distances */ if( icvCalcDist3D( points, count, _line, r ) < FLT_EPSILON*count ) break; /* calculate weights */ if( calc_weights ) calc_weights( r, count, w ); else calc_weights_param( r, count, w, _param ); for( j = 0; j < count; j++ ) sum_w += w[j]; if( fabs(sum_w) > FLT_EPSILON ) { sum_w = 1./sum_w; for( j = 0; j < count; j++ ) w[j] = (float)(w[j]*sum_w); } else { for( j = 0; j < count; j++ ) w[j] = 1.f; } /* save the line parameters */ memcpy( _lineprev, _line, 6 * sizeof( float )); /* Run again... */ icvFitLine3D_wods( points, count, w, _line ); } if( err < min_err ) { min_err = err; memcpy( line, _line, 6 * sizeof(line[0])); if( err < EPS ) break; } } // Return... cvFree( &w ); cvFree( &r ); return CV_OK; } CV_IMPL void cvFitLine( const CvArr* array, int dist, double param, double reps, double aeps, float *line ) { cv::AutoBuffer<schar> buffer; schar* points = 0; union { CvContour contour; CvSeq seq; } header; CvSeqBlock block; CvSeq* ptseq = (CvSeq*)array; int type; if( !line ) CV_Error( CV_StsNullPtr, "NULL pointer to line parameters" ); if( CV_IS_SEQ(ptseq) ) { type = CV_SEQ_ELTYPE(ptseq); if( ptseq->total == 0 ) CV_Error( CV_StsBadSize, "The sequence has no points" ); if( (type!=CV_32FC2 && type!=CV_32FC3 && type!=CV_32SC2 && type!=CV_32SC3) || CV_ELEM_SIZE(type) != ptseq->elem_size ) CV_Error( CV_StsUnsupportedFormat, "Input sequence must consist of 2d points or 3d points" ); } else { CvMat* mat = (CvMat*)array; type = CV_MAT_TYPE(mat->type); if( !CV_IS_MAT(mat)) CV_Error( CV_StsBadArg, "Input array is not a sequence nor matrix" ); if( !CV_IS_MAT_CONT(mat->type) || (type!=CV_32FC2 && type!=CV_32FC3 && type!=CV_32SC2 && type!=CV_32SC3) || (mat->width != 1 && mat->height != 1)) CV_Error( CV_StsBadArg, "Input array must be 1d continuous array of 2d or 3d points" ); ptseq = cvMakeSeqHeaderForArray( CV_SEQ_KIND_GENERIC|type, sizeof(CvContour), CV_ELEM_SIZE(type), mat->data.ptr, mat->width + mat->height - 1, &header.seq, &block ); } if( reps < 0 || aeps < 0 ) CV_Error( CV_StsOutOfRange, "Both reps and aeps must be non-negative" ); if( CV_MAT_DEPTH(type) == CV_32F && ptseq->first->next == ptseq->first ) { /* no need to copy data in this case */ points = ptseq->first->data; } else { buffer.allocate(ptseq->total*CV_ELEM_SIZE(type)); points = buffer; cvCvtSeqToArray( ptseq, points, CV_WHOLE_SEQ ); if( CV_MAT_DEPTH(type) != CV_32F ) { int i, total = ptseq->total*CV_MAT_CN(type); assert( CV_MAT_DEPTH(type) == CV_32S ); for( i = 0; i < total; i++ ) ((float*)points)[i] = (float)((int*)points)[i]; } } if( dist == CV_DIST_USER ) CV_Error( CV_StsBadArg, "User-defined distance is not allowed" ); if( CV_MAT_CN(type) == 2 ) { IPPI_CALL( icvFitLine2D( (CvPoint2D32f*)points, ptseq->total, dist, (float)param, (float)reps, (float)aeps, line )); } else { IPPI_CALL( icvFitLine3D( (CvPoint3D32f*)points, ptseq->total, dist, (float)param, (float)reps, (float)aeps, line )); } } /* End of file. */
samuto/UnityOpenCV
opencv/src/cv/cvlinefit.cpp
C++
gpl-3.0
19,525
<?php /** * $Header$ * $Horde: horde/lib/Log.php,v 1.15 2000/06/29 23:39:45 jon Exp $ * * @version $Revision: 293929 $ * @package Log */ define('PEAR_LOG_EMERG', 0); /* System is unusable */ define('PEAR_LOG_ALERT', 1); /* Immediate action required */ define('PEAR_LOG_CRIT', 2); /* Critical conditions */ define('PEAR_LOG_ERR', 3); /* Error conditions */ define('PEAR_LOG_WARNING', 4); /* Warning conditions */ define('PEAR_LOG_NOTICE', 5); /* Normal but significant */ define('PEAR_LOG_INFO', 6); /* Informational */ define('PEAR_LOG_DEBUG', 7); /* Debug-level messages */ define('PEAR_LOG_ALL', 0xffffffff); /* All messages */ define('PEAR_LOG_NONE', 0x00000000); /* No message */ /* Log types for PHP's native error_log() function. */ define('PEAR_LOG_TYPE_SYSTEM', 0); /* Use PHP's system logger */ define('PEAR_LOG_TYPE_MAIL', 1); /* Use PHP's mail() function */ define('PEAR_LOG_TYPE_DEBUG', 2); /* Use PHP's debugging connection */ define('PEAR_LOG_TYPE_FILE', 3); /* Append to a file */ define('PEAR_LOG_TYPE_SAPI', 4); /* Use the SAPI logging handler */ /** * The Log:: class implements both an abstraction for various logging * mechanisms and the Subject end of a Subject-Observer pattern. * * @author Chuck Hagenbuch <chuck@horde.org> * @author Jon Parise <jon@php.net> * @since Horde 1.3 * @package Log */ class Log { /** * Indicates whether or not the log can been opened / connected. * * @var boolean * @access protected */ var $_opened = false; /** * Instance-specific unique identification number. * * @var integer * @access protected */ var $_id = 0; /** * The label that uniquely identifies this set of log messages. * * @var string * @access protected */ var $_ident = ''; /** * The default priority to use when logging an event. * * @var integer * @access protected */ var $_priority = PEAR_LOG_INFO; /** * The bitmask of allowed log levels. * * @var integer * @access protected */ var $_mask = PEAR_LOG_ALL; /** * Holds all Log_observer objects that wish to be notified of new messages. * * @var array * @access protected */ var $_listeners = array(); /** * Maps canonical format keys to position arguments for use in building * "line format" strings. * * @var array * @access protected */ var $_formatMap = array('%{timestamp}' => '%1$s', '%{ident}' => '%2$s', '%{priority}' => '%3$s', '%{message}' => '%4$s', '%{file}' => '%5$s', '%{line}' => '%6$s', '%{function}' => '%7$s', '%{class}' => '%8$s', '%\{' => '%%{'); /** * Attempts to return a concrete Log instance of type $handler. * * @param string $handler The type of concrete Log subclass to return. * Attempt to dynamically include the code for * this subclass. Currently, valid values are * 'console', 'syslog', 'sql', 'file', and 'mcal'. * * @param string $name The name of the actually log file, table, or * other specific store to use. Defaults to an * empty string, with which the subclass will * attempt to do something intelligent. * * @param string $ident The identity reported to the log system. * * @param array $conf A hash containing any additional configuration * information that a subclass might need. * * @param int $level Log messages up to and including this level. * * @return object Log The newly created concrete Log instance, or * null on an error. * @access public * @since Log 1.0 */ function &factory($handler, $name = '', $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { $handler = strtolower($handler); $class = 'Log_' . $handler; $classfile = 'Log/' . $handler . '.php'; /* * Attempt to include our version of the named class, but don't treat * a failure as fatal. The caller may have already included their own * version of the named class. */ if (!class_exists($class, false)) { include_once $classfile; } /* If the class exists, return a new instance of it. */ if (class_exists($class, false)) { $obj = new $class($name, $ident, $conf, $level); return $obj; } $null = null; return $null; } /** * Attempts to return a reference to a concrete Log instance of type * $handler, only creating a new instance if no log instance with the same * parameters currently exists. * * You should use this if there are multiple places you might create a * logger, you don't want to create multiple loggers, and you don't want to * check for the existance of one each time. The singleton pattern does all * the checking work for you. * * <b>You MUST call this method with the $var = &Log::singleton() syntax. * Without the ampersand (&) in front of the method name, you will not get * a reference, you will get a copy.</b> * * @param string $handler The type of concrete Log subclass to return. * Attempt to dynamically include the code for * this subclass. Currently, valid values are * 'console', 'syslog', 'sql', 'file', and 'mcal'. * * @param string $name The name of the actually log file, table, or * other specific store to use. Defaults to an * empty string, with which the subclass will * attempt to do something intelligent. * * @param string $ident The identity reported to the log system. * * @param array $conf A hash containing any additional configuration * information that a subclass might need. * * @param int $level Log messages up to and including this level. * * @return object Log The newly created concrete Log instance, or * null on an error. * @access public * @since Log 1.0 */ function &singleton($handler, $name = '', $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { static $instances; if (!isset($instances)) $instances = array(); $signature = serialize(array($handler, $name, $ident, $conf, $level)); if (!isset($instances[$signature])) { $instances[$signature] = &Log::factory($handler, $name, $ident, $conf, $level); } return $instances[$signature]; } /** * Abstract implementation of the open() method. * @since Log 1.0 */ function open() { return false; } /** * Abstract implementation of the close() method. * @since Log 1.0 */ function close() { return false; } /** * Abstract implementation of the flush() method. * @since Log 1.8.2 */ function flush() { return false; } /** * Abstract implementation of the log() method. * @since Log 1.0 */ function log($message, $priority = null) { return false; } /** * A convenience function for logging a emergency event. It will log a * message at the PEAR_LOG_EMERG log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function emerg($message) { return $this->log($message, PEAR_LOG_EMERG); } /** * A convenience function for logging an alert event. It will log a * message at the PEAR_LOG_ALERT log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function alert($message) { return $this->log($message, PEAR_LOG_ALERT); } /** * A convenience function for logging a critical event. It will log a * message at the PEAR_LOG_CRIT log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function crit($message) { return $this->log($message, PEAR_LOG_CRIT); } /** * A convenience function for logging a error event. It will log a * message at the PEAR_LOG_ERR log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function err($message) { return $this->log($message, PEAR_LOG_ERR); } /** * A convenience function for logging a warning event. It will log a * message at the PEAR_LOG_WARNING log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function warning($message) { return $this->log($message, PEAR_LOG_WARNING); } /** * A convenience function for logging a notice event. It will log a * message at the PEAR_LOG_NOTICE log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function notice($message) { return $this->log($message, PEAR_LOG_NOTICE); } /** * A convenience function for logging a information event. It will log a * message at the PEAR_LOG_INFO log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function info($message) { return $this->log($message, PEAR_LOG_INFO); } /** * A convenience function for logging a debug event. It will log a * message at the PEAR_LOG_DEBUG log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function debug($message) { return $this->log($message, PEAR_LOG_DEBUG); } /** * Returns the string representation of the message data. * * If $message is an object, _extractMessage() will attempt to extract * the message text using a known method (such as a PEAR_Error object's * getMessage() method). If a known method, cannot be found, the * serialized representation of the object will be returned. * * If the message data is already a string, it will be returned unchanged. * * @param mixed $message The original message data. This may be a * string or any object. * * @return string The string representation of the message. * * @access protected */ function _extractMessage($message) { /* * If we've been given an object, attempt to extract the message using * a known method. If we can't find such a method, default to the * "human-readable" version of the object. * * We also use the human-readable format for arrays. */ if (is_object($message)) { if (method_exists($message, 'getmessage')) { $message = $message->getMessage(); } else if (method_exists($message, 'tostring')) { $message = $message->toString(); } else if (method_exists($message, '__tostring')) { $message = (string)$message; } else { $message = var_export($message, true); } } else if (is_array($message)) { if (isset($message['message'])) { if (is_scalar($message['message'])) { $message = $message['message']; } else { $message = var_export($message['message'], true); } } else { $message = var_export($message, true); } } else if (is_bool($message) || $message === NULL) { $message = var_export($message, true); } /* Otherwise, we assume the message is a string. */ return $message; } /** * Using debug_backtrace(), returns the file, line, and enclosing function * name of the source code context from which log() was invoked. * * @param int $depth The initial number of frames we should step * back into the trace. * * @return array Array containing four strings: the filename, the line, * the function name, and the class name from which log() * was called. * * @access private * @since Log 1.9.4 */ function _getBacktraceVars($depth) { /* Start by generating a backtrace from the current call (here). */ $bt = debug_backtrace(); /* * If we were ultimately invoked by the composite handler, we need to * increase our depth one additional level to compensate. */ $class = isset($bt[$depth+1]['class']) ? $bt[$depth+1]['class'] : null; if ($class !== null && strcasecmp($class, 'Log_composite') == 0) { $depth++; $class = isset($bt[$depth + 1]) ? $bt[$depth + 1]['class'] : null; } /* * We're interested in the frame which invoked the log() function, so * we need to walk back some number of frames into the backtrace. The * $depth parameter tells us where to start looking. We go one step * further back to find the name of the encapsulating function from * which log() was called. */ $file = isset($bt[$depth]) ? $bt[$depth]['file'] : null; $line = isset($bt[$depth]) ? $bt[$depth]['line'] : 0; $func = isset($bt[$depth + 1]) ? $bt[$depth + 1]['function'] : null; /* * However, if log() was called from one of our "shortcut" functions, * we're going to need to go back an additional step. */ if (in_array($func, array('emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug'))) { $file = isset($bt[$depth + 1]) ? $bt[$depth + 1]['file'] : null; $line = isset($bt[$depth + 1]) ? $bt[$depth + 1]['line'] : 0; $func = isset($bt[$depth + 2]) ? $bt[$depth + 2]['function'] : null; $class = isset($bt[$depth + 2]) ? $bt[$depth + 2]['class'] : null; } /* * If we couldn't extract a function name (perhaps because we were * executed from the "main" context), provide a default value. */ if (is_null($func)) { $func = '(none)'; } /* Return a 4-tuple containing (file, line, function, class). */ return array($file, $line, $func, $class); } /** * Produces a formatted log line based on a format string and a set of * variables representing the current log record and state. * * @return string Formatted log string. * * @access protected * @since Log 1.9.4 */ function _format($format, $timestamp, $priority, $message) { /* * If the format string references any of the backtrace-driven * variables (%5 %6,%7,%8), generate the backtrace and fetch them. */ if (preg_match('/%[5678]/', $format)) { list($file, $line, $func, $class) = $this->_getBacktraceVars(2); } /* * Build the formatted string. We use the sprintf() function's * "argument swapping" capability to dynamically select and position * the variables which will ultimately appear in the log string. */ return sprintf($format, $timestamp, $this->_ident, $this->priorityToString($priority), $message, isset($file) ? $file : '', isset($line) ? $line : '', isset($func) ? $func : '', isset($class) ? $class : ''); } /** * Returns the string representation of a PEAR_LOG_* integer constant. * * @param int $priority A PEAR_LOG_* integer constant. * * @return string The string representation of $level. * * @access public * @since Log 1.0 */ function priorityToString($priority) { $levels = array( PEAR_LOG_EMERG => 'emergency', PEAR_LOG_ALERT => 'alert', PEAR_LOG_CRIT => 'critical', PEAR_LOG_ERR => 'error', PEAR_LOG_WARNING => 'warning', PEAR_LOG_NOTICE => 'notice', PEAR_LOG_INFO => 'info', PEAR_LOG_DEBUG => 'debug' ); return $levels[$priority]; } /** * Returns the the PEAR_LOG_* integer constant for the given string * representation of a priority name. This function performs a * case-insensitive search. * * @param string $name String containing a priority name. * * @return string The PEAR_LOG_* integer contstant corresponding * the the specified priority name. * * @access public * @since Log 1.9.0 */ function stringToPriority($name) { $levels = array( 'emergency' => PEAR_LOG_EMERG, 'alert' => PEAR_LOG_ALERT, 'critical' => PEAR_LOG_CRIT, 'error' => PEAR_LOG_ERR, 'warning' => PEAR_LOG_WARNING, 'notice' => PEAR_LOG_NOTICE, 'info' => PEAR_LOG_INFO, 'debug' => PEAR_LOG_DEBUG ); return $levels[strtolower($name)]; } /** * Calculate the log mask for the given priority. * * This method may be called statically. * * @param integer $priority The priority whose mask will be calculated. * * @return integer The calculated log mask. * * @access public * @since Log 1.7.0 */ function MASK($priority) { return (1 << $priority); } /** * Calculate the log mask for all priorities up to the given priority. * * This method may be called statically. * * @param integer $priority The maximum priority covered by this mask. * * @return integer The resulting log mask. * * @access public * @since Log 1.7.0 * * @deprecated deprecated since Log 1.9.4; use Log::MAX() instead */ function UPTO($priority) { return Log::MAX($priority); } /** * Calculate the log mask for all priorities greater than or equal to the * given priority. In other words, $priority will be the lowest priority * matched by the resulting mask. * * This method may be called statically. * * @param integer $priority The minimum priority covered by this mask. * * @return integer The resulting log mask. * * @access public * @since Log 1.9.4 */ function MIN($priority) { return PEAR_LOG_ALL ^ ((1 << $priority) - 1); } /** * Calculate the log mask for all priorities less than or equal to the * given priority. In other words, $priority will be the highests priority * matched by the resulting mask. * * This method may be called statically. * * @param integer $priority The maximum priority covered by this mask. * * @return integer The resulting log mask. * * @access public * @since Log 1.9.4 */ function MAX($priority) { return ((1 << ($priority + 1)) - 1); } /** * Set and return the level mask for the current Log instance. * * @param integer $mask A bitwise mask of log levels. * * @return integer The current level mask. * * @access public * @since Log 1.7.0 */ function setMask($mask) { $this->_mask = $mask; return $this->_mask; } /** * Returns the current level mask. * * @return interger The current level mask. * * @access public * @since Log 1.7.0 */ function getMask() { return $this->_mask; } /** * Check if the given priority is included in the current level mask. * * @param integer $priority The priority to check. * * @return boolean True if the given priority is included in the current * log mask. * * @access protected * @since Log 1.7.0 */ function _isMasked($priority) { return (Log::MASK($priority) & $this->_mask); } /** * Returns the current default priority. * * @return integer The current default priority. * * @access public * @since Log 1.8.4 */ function getPriority() { return $this->_priority; } /** * Sets the default priority to the specified value. * * @param integer $priority The new default priority. * * @access public * @since Log 1.8.4 */ function setPriority($priority) { $this->_priority = $priority; } /** * Adds a Log_observer instance to the list of observers that are listening * for messages emitted by this Log instance. * * @param object $observer The Log_observer instance to attach as a * listener. * * @param boolean True if the observer is successfully attached. * * @access public * @since Log 1.0 */ function attach(&$observer) { if (!is_a($observer, 'Log_observer')) { return false; } $this->_listeners[$observer->_id] = &$observer; return true; } /** * Removes a Log_observer instance from the list of observers. * * @param object $observer The Log_observer instance to detach from * the list of listeners. * * @param boolean True if the observer is successfully detached. * * @access public * @since Log 1.0 */ function detach($observer) { if (!is_a($observer, 'Log_observer') || !isset($this->_listeners[$observer->_id])) { return false; } unset($this->_listeners[$observer->_id]); return true; } /** * Informs each registered observer instance that a new message has been * logged. * * @param array $event A hash describing the log event. * * @access protected */ function _announce($event) { foreach ($this->_listeners as $id => $listener) { if ($event['priority'] <= $this->_listeners[$id]->_priority) { $this->_listeners[$id]->notify($event); } } } /** * Indicates whether this is a composite class. * * @return boolean True if this is a composite class. * * @access public * @since Log 1.0 */ function isComposite() { return false; } /** * Sets this Log instance's identification string. * * @param string $ident The new identification string. * * @access public * @since Log 1.6.3 */ function setIdent($ident) { $this->_ident = $ident; } /** * Returns the current identification string. * * @return string The current Log instance's identification string. * * @access public * @since Log 1.6.3 */ function getIdent() { return $this->_ident; } }
andysaurin/ezNGS
includes/Log.php
PHP
gpl-3.0
25,878
const NUMBER_OF_CLOUDS = 30; // clouds to show on screen const NUMBER_OF_IMAGES = 13; // images + 1 function init() { var container = document.getElementById("fogContainer"); for (var i = 0; i < NUMBER_OF_CLOUDS; i++) { container.appendChild(createACloud())} } function randomInteger(low, high) { return low + Math.floor(Math.random() * (high - low)); } function randomFloat(low, high) { return low + Math.random() * (high - low); } function pixelValue(value) { return value + "px"; } function durationValue(value) { return value + "s"; } function createACloud() { var cloudDiv = document.createElement("div"); var image = document.createElement("img"); image.src = "Haze_night/Private/images/fog" + randomInteger(4, NUMBER_OF_IMAGES) + ".png"; cloudDiv.style.top = pixelValue(randomInteger(-200, 350)); cloudDiv.style.left = pixelValue(randomInteger(-110, -110)); var spinAnimationName = (Math.random() < 0.5) ? "clockwiseSpin" : "counterclockwiseSpinAndFlip"; cloudDiv.style.webkitAnimationName = "float"; image.style.webkitAnimationName = spinAnimationName; var fadeAndfloatDuration = durationValue(randomFloat(40, 70)); var spinDuration = durationValue(randomFloat(30, 80)); cloudDiv.style.webkitAnimationDuration = fadeAndfloatDuration + ", " + fadeAndfloatDuration; image.style.webkitAnimationDuration = spinDuration; cloudDiv.appendChild(image); return cloudDiv; } window.addEventListener("load", init, false);
eweiman/HTC-Animated-Weather-iPhone
com.ludacrisvp.htcweather6Plus.iwidget/var/mobile/Library/iWidgets/HTC Weather iPhone 6 Plus/Private/Animations/Haze_night/Private/includes/fog.js
JavaScript
gpl-3.0
1,500
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'PrivatePost.text_html' db.add_column(u'mp_privatepost', 'text_html', self.gf('django.db.models.fields.TextField')(default='Old MP text not parsed in markdown'), keep_default=False) def backwards(self, orm): # Deleting field 'PrivatePost.text_html' db.delete_column(u'mp_privatepost', 'text_html') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'mp.privatepost': { 'Meta': {'object_name': 'PrivatePost'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'privateposts'", 'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'position_in_topic': ('django.db.models.fields.IntegerField', [], {}), 'privatetopic': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mp.PrivateTopic']"}), 'pubdate': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'text': ('django.db.models.fields.TextField', [], {}), 'text_html': ('django.db.models.fields.TextField', [], {}), 'update': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, u'mp.privatetopic': { 'Meta': {'object_name': 'PrivateTopic'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'author'", 'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_message': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'last_message'", 'null': 'True', 'to': u"orm['mp.PrivatePost']"}), 'participants': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'participants'", 'symmetrical': 'False', 'to': u"orm['auth.User']"}), 'pubdate': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'subtitle': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '80'}) }, u'mp.privatetopicread': { 'Meta': {'object_name': 'PrivateTopicRead'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'privatepost': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mp.PrivatePost']"}), 'privatetopic': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mp.PrivateTopic']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'privatetopics_read'", 'to': u"orm['auth.User']"}) } } complete_apps = ['mp']
Florianboux/zds-site
zds/mp/migrations/0002_auto__add_field_privatepost_text_html.py
Python
gpl-3.0
6,206
#include "ofMath.h" #include "ofAppRunner.h" #include "float.h" #ifndef TARGET_WIN32 #include <sys/time.h> #endif #include "ofNoise.h" //-------------------------------------------------- int ofNextPow2(int a){ // from nehe.gamedev.net lesson 43 int rval=1; while(rval<a) rval<<=1; return rval; } //-------------------------------------------------- void ofSeedRandom() { // good info here: // http://stackoverflow.com/questions/322938/recommended-way-to-initialize-srand #ifdef TARGET_WIN32 srand(GetTickCount()); #else // use XOR'd second, microsecond precision AND pid as seed struct timeval tv; gettimeofday(&tv, 0); long int n = (tv.tv_sec ^ tv.tv_usec) ^ getpid(); srand(n); #endif } //-------------------------------------------------- void ofSeedRandom(int val) { srand((long) val); } //-------------------------------------------------- float ofRandom(float x, float y) { float high = 0; float low = 0; float randNum = 0; // if there is no range, return the value if (x == y) return x; // float == ?, wise? epsilon? high = MAX(x,y); low = MIN(x,y); randNum = low + ((high-low) * rand()/(RAND_MAX + 1.0)); return randNum; } //-------------------------------------------------- float ofRandomf() { float randNum = 0; randNum = (rand()/(RAND_MAX + 1.0)) * 2.0 - 1.0; return randNum; } //-------------------------------------------------- float ofRandomuf() { float randNum = 0; randNum = rand()/(RAND_MAX + 1.0); return randNum; } //---- new to 006 //from the forums http://www.openframeworks.cc/forum/viewtopic.php?t=1413 //-------------------------------------------------- float ofNormalize(float value, float min, float max){ return ofClamp( (value - min) / (max - min), 0, 1); } //check for division by zero??? //-------------------------------------------------- float ofMap(float value, float inputMin, float inputMax, float outputMin, float outputMax, bool clamp) { if (fabs(inputMin - inputMax) < FLT_EPSILON){ ofLog(OF_LOG_WARNING, "ofMap: avoiding possible divide by zero, check inputMin and inputMax\n"); return outputMin; } else { float outVal = ((value - inputMin) / (inputMax - inputMin) * (outputMax - outputMin) + outputMin); if( clamp ){ if(outputMax < outputMin){ if( outVal < outputMax )outVal = outputMax; else if( outVal > outputMin )outVal = outputMin; }else{ if( outVal > outputMax )outVal = outputMax; else if( outVal < outputMin )outVal = outputMin; } } return outVal; } } //-------------------------------------------------- float ofDist(float x1, float y1, float x2, float y2) { return sqrt(double((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))); } //-------------------------------------------------- float ofDistSquared(float x1, float y1, float x2, float y2) { return ( (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) ); } //-------------------------------------------------- float ofClamp(float value, float min, float max) { return value < min ? min : value > max ? max : value; } // return sign of the number //-------------------------------------------------- int ofSign(float n) { if( n > 0 ) return 1; else if(n < 0) return -1; else return 0; } //-------------------------------------------------- bool ofInRange(float t, float min, float max) { return t>=min && t<=max; } //-------------------------------------------------- float ofRadToDeg(float radians) { return radians * RAD_TO_DEG; } //-------------------------------------------------- float ofDegToRad(float degrees) { return degrees * DEG_TO_RAD; } //-------------------------------------------------- float ofLerp(float start, float stop, float amt) { return start + (stop-start) * amt; } //-------------------------------------------------- float ofRandomWidth() { return ofRandom(0, ofGetWidth()); } //-------------------------------------------------- float ofRandomHeight() { return ofRandom(0, ofGetHeight()); } //-------------------------------------------------- float ofNoise(float x){ return _slang_library_noise1(x)*0.5f + 0.5f; } //-------------------------------------------------- float ofNoise(float x, float y){ return _slang_library_noise2(x,y)*0.5f + 0.5f; } //-------------------------------------------------- float ofNoise(float x, float y, float z){ return _slang_library_noise3(x,y,z)*0.5f + 0.5f; } //-------------------------------------------------- float ofNoise(float x, float y, float z, float w){ return _slang_library_noise4(x,y,z,w)*0.5f + 0.5f; } //-------------------------------------------------- float ofSignedNoise(float x){ return _slang_library_noise1(x); } //-------------------------------------------------- float ofSignedNoise(float x, float y){ return _slang_library_noise2(x,y); } //-------------------------------------------------- float ofSignedNoise(float x, float y, float z){ return _slang_library_noise3(x,y,z); } //-------------------------------------------------- float ofSignedNoise(float x, float y, float z, float w){ return _slang_library_noise4(x,y,z,w); }
broxtronix/phosphoressence
src/OpenFrameworks/utils/ofMath.cpp
C++
gpl-3.0
5,062
// // SuperTuxKart - a fun racing game with go-kart // Copyright (C) 2006-2015 Joerg Henrichs // // 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, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "config/stk_config.hpp" #include <stdexcept> #include <stdio.h> #include <sstream> #include "audio/music_information.hpp" #include "io/file_manager.hpp" #include "io/xml_node.hpp" #include "items/item.hpp" #include "karts/kart_properties.hpp" #include "utils/log.hpp" STKConfig* stk_config=0; float STKConfig::UNDEFINED = -99.9f; //----------------------------------------------------------------------------- /** Constructor, which only initialises the object. The actual work is done * by calling load(). */ STKConfig::STKConfig() { m_has_been_loaded = false; m_title_music = NULL; m_default_kart_properties = new KartProperties(); } // STKConfig //----------------------------------------------------------------------------- STKConfig::~STKConfig() { if(m_title_music) delete m_title_music; if(m_default_kart_properties) delete m_default_kart_properties; for(std::map<std::string, KartProperties*>::iterator it = m_kart_properties.begin(); it != m_kart_properties.end(); ++it) { if (it->second) delete it->second; } } // ~STKConfig //----------------------------------------------------------------------------- /** Loads the stk configuration file. After loading it checks if all necessary * values are actually defined, otherwise an error message is printed and STK * is aborted. * /param filename Name of the configuration file to load. */ void STKConfig::load(const std::string &filename) { // Avoid loading the default config file if a user-specific // config file has already been loaded. if(m_has_been_loaded) return; m_has_been_loaded = true; init_defaults(); XMLNode *root = 0; try { root = new XMLNode(filename); if(!root || root->getName()!="config") { if(root) delete root; std::ostringstream msg; msg << "Couldn't load config '" << filename << "': no config node."; throw std::runtime_error(msg.str()); } getAllData(root); } catch(std::exception& err) { Log::error("StkConfig", "FATAL ERROR while reading '%s':", filename.c_str()); Log::fatal("StkConfig", " %s", err.what()); } delete root; // Check that all necessary values are indeed set // ----------------------------------------------- #define CHECK_NEG( a,strA) if(a<=UNDEFINED) { \ Log::fatal("StkConfig", "Missing default value for '%s' in '%s'.", \ strA,filename.c_str()); \ } if(m_score_increase.size()==0 || (int)m_score_increase.size()!=m_max_karts) { Log::fatal("StkConfig", "Not or not enough scores defined in stk_config"); } if(m_leader_intervals.size()==0) { Log::fatal("StkConfig", "No follow leader interval(s) defined in stk_config"); } if(m_switch_items.size()!=Item::ITEM_LAST-Item::ITEM_FIRST+1) { Log::fatal("StkConfig", "Wrong number of item switches defined in stk_config"); } CHECK_NEG(m_max_karts, "<karts max=..." ); CHECK_NEG(m_item_switch_time, "item-switch-time" ); CHECK_NEG(m_bubblegum_counter, "bubblegum disappear counter"); CHECK_NEG(m_explosion_impulse_objects, "explosion-impulse-objects" ); CHECK_NEG(m_max_skidmarks, "max-skidmarks" ); CHECK_NEG(m_min_kart_version, "<kart-version min...>" ); CHECK_NEG(m_max_kart_version, "<kart-version max=...>" ); CHECK_NEG(m_min_track_version, "min-track-version" ); CHECK_NEG(m_max_track_version, "max-track-version" ); CHECK_NEG(m_skid_fadeout_time, "skid-fadeout-time" ); CHECK_NEG(m_near_ground, "near-ground" ); CHECK_NEG(m_delay_finish_time, "delay-finish-time" ); CHECK_NEG(m_music_credit_time, "music-credit-time" ); CHECK_NEG(m_leader_time_per_kart, "leader time-per-kart" ); CHECK_NEG(m_penalty_time, "penalty-time" ); CHECK_NEG(m_max_display_news, "max-display-news" ); CHECK_NEG(m_replay_max_time, "replay max-time" ); CHECK_NEG(m_replay_delta_angle, "replay delta-angle" ); CHECK_NEG(m_replay_delta_pos2, "replay delta-position" ); CHECK_NEG(m_replay_dt, "replay delta-t" ); CHECK_NEG(m_smooth_angle_limit, "physics smooth-angle-limit" ); // Square distance to make distance checks cheaper (no sqrt) m_replay_delta_pos2 *= m_replay_delta_pos2; m_default_kart_properties->checkAllSet(filename); } // load // ----------------------------------------------------------------------------- /** Init all values with invalid defaults, which are tested later. This * guarantees that all parameters will indeed be initialised, and helps * finding typos. */ void STKConfig::init_defaults() { m_bomb_time = m_bomb_time_increase = m_explosion_impulse_objects = m_music_credit_time = m_delay_finish_time = m_skid_fadeout_time = m_near_ground = m_item_switch_time = m_smooth_angle_limit = m_penalty_time = UNDEFINED; m_bubblegum_counter = -100; m_shield_restrict_weapos = false; m_max_karts = -100; m_max_skidmarks = -100; m_min_kart_version = -100; m_max_kart_version = -100; m_min_track_version = -100; m_max_track_version = -100; m_max_display_news = -100; m_replay_max_time = -100; m_replay_delta_angle = -100; m_replay_delta_pos2 = -100; m_replay_dt = -100; m_title_music = NULL; m_enable_networking = true; m_smooth_normals = false; m_same_powerup_mode = POWERUP_MODE_ONLY_IF_SAME; m_ai_acceleration = 1.0f; m_disable_steer_while_unskid = false; m_camera_follow_skid = false; m_cutscene_fov = 0.61f; m_score_increase.clear(); m_leader_intervals.clear(); m_switch_items.clear(); m_normal_ttf.clear(); m_digit_ttf.clear(); } // init_defaults //----------------------------------------------------------------------------- /** Extracts the actual information from a xml file. * \param xml Pointer to the xml data structure. */ void STKConfig::getAllData(const XMLNode * root) { // Get the values which are not part of the default KartProperties // --------------------------------------------------------------- if(const XMLNode *kart_node = root->getNode("kart-version")) { kart_node->get("min", &m_min_kart_version); kart_node->get("max", &m_max_kart_version); } if(const XMLNode *node = root->getNode("track-version")) { node->get("min", &m_min_track_version); node->get("max", &m_max_track_version); } if(const XMLNode *kart_node = root->getNode("karts")) kart_node->get("max-number", &m_max_karts); if(const XMLNode *gp_node = root->getNode("grand-prix")) { for(unsigned int i=0; i<gp_node->getNumNodes(); i++) { const XMLNode *pn=gp_node->getNode(i); int from=-1; pn->get("from", &from); int to=-1; pn->get("to", &to); if(to<0) to=m_max_karts; int points=-1; pn->get("points", &points); if(points<0 || from<0 || from>to|| (int)m_score_increase.size()!=from-1) { Log::error("StkConfig", "Incorrect GP point specification:"); Log::fatal("StkConfig", "from: %d to: %d points: %d", from, to, points); } for(int j=from; j<=to; j++) m_score_increase.push_back(points); } } if(const XMLNode *leader_node= root->getNode("follow-the-leader")) { leader_node->get("intervals", &m_leader_intervals ); leader_node->get("time-per-kart", &m_leader_time_per_kart); } if (const XMLNode *physics_node= root->getNode("physics")) { physics_node->get("smooth-normals", &m_smooth_normals ); physics_node->get("smooth-angle-limit", &m_smooth_angle_limit); } if (const XMLNode *startup_node= root->getNode("startup")) { startup_node->get("penalty", &m_penalty_time ); } if (const XMLNode *news_node= root->getNode("news")) { news_node->get("max-display", &m_max_display_news); } if (const XMLNode *steer_node= root->getNode("steer")) { steer_node->get("disable-while-unskid", &m_disable_steer_while_unskid); steer_node->get("camera-follow-skid", &m_camera_follow_skid ); } if (const XMLNode *camera = root->getNode("camera")) { camera->get("fov-1", &m_camera_fov[0]); camera->get("fov-2", &m_camera_fov[1]); camera->get("fov-3", &m_camera_fov[2]); camera->get("fov-4", &m_camera_fov[3]); camera->get("cutscene-fov", &m_cutscene_fov); } if (const XMLNode *music_node = root->getNode("music")) { std::string title_music; music_node->get("title", &title_music); assert(title_music.size() > 0); title_music = file_manager->getAsset(FileManager::MUSIC, title_music); m_title_music = MusicInformation::create(title_music); if(!m_title_music) Log::error("StkConfig", "Cannot load title music : %s", title_music.c_str()); } if(const XMLNode *skidmarks_node = root->getNode("skid-marks")) { skidmarks_node->get("max-number", &m_max_skidmarks ); skidmarks_node->get("fadeout-time", &m_skid_fadeout_time); } if(const XMLNode *near_ground_node = root->getNode("near-ground")) near_ground_node->get("distance", &m_near_ground); if(const XMLNode *delay_finish_node= root->getNode("delay-finish")) delay_finish_node->get("time", &m_delay_finish_time); if(const XMLNode *credits_node= root->getNode("credits")) credits_node->get("music", &m_music_credit_time); if(const XMLNode *bomb_node= root->getNode("bomb")) { bomb_node->get("time", &m_bomb_time); bomb_node->get("time-increase", &m_bomb_time_increase); } if(const XMLNode *powerup_node= root->getNode("powerup")) { std::string s; powerup_node->get("collect-mode", &s); if(s=="same") m_same_powerup_mode = POWERUP_MODE_SAME; else if(s=="new") m_same_powerup_mode = POWERUP_MODE_NEW; else if(s=="only-if-same") m_same_powerup_mode = POWERUP_MODE_ONLY_IF_SAME; else { Log::warn("StkConfig", "Invalid item mode '%s' - ignored.", s.c_str()); } } if(const XMLNode *switch_node= root->getNode("switch")) { switch_node->get("items", &m_switch_items ); switch_node->get("time", &m_item_switch_time); } if(const XMLNode *bubblegum_node= root->getNode("bubblegum")) { bubblegum_node->get("disappear-counter", &m_bubblegum_counter ); bubblegum_node->get("restrict-weapons", &m_shield_restrict_weapos); } if(const XMLNode *explosion_node= root->getNode("explosion")) { explosion_node->get("impulse-objects", &m_explosion_impulse_objects); } if(const XMLNode *ai_node = root->getNode("ai")) { ai_node->get("acceleration", &m_ai_acceleration); } if(const XMLNode *networking_node= root->getNode("networking")) networking_node->get("enable", &m_enable_networking); if(const XMLNode *replay_node = root->getNode("replay")) { replay_node->get("delta-angle", &m_replay_delta_angle); replay_node->get("delta-pos", &m_replay_delta_pos2 ); replay_node->get("delta-t", &m_replay_dt ); replay_node->get("max-time", &m_replay_max_time ); } if (const XMLNode *fonts_list = root->getNode("fonts-list")) { fonts_list->get("normal-ttf", &m_normal_ttf); fonts_list->get("digit-ttf", &m_digit_ttf ); } // Get the default KartProperties // ------------------------------ const XMLNode *node = root -> getNode("general-kart-defaults"); if(!node) { std::ostringstream msg; msg << "Couldn't load general-kart-defaults: no node."; throw std::runtime_error(msg.str()); } m_default_kart_properties->getAllData(node); const XMLNode *child_node = node->getNode("kart-type"); for (unsigned int i = 0; i < child_node->getNumNodes(); ++i) { const XMLNode* type = child_node->getNode(i); m_kart_properties[type->getName()] = new KartProperties(); m_kart_properties[type->getName()]->copyFrom(m_default_kart_properties); m_kart_properties[type->getName()]->getAllData(type); } } // getAllData // ---------------------------------------------------------------------------- /** Defines the points for each position for a race with a given number * of karts. * \param all_scores A vector which will be resized to take num_karts * elements and which on return contains the number of points * for each position. * \param num_karts Number of karts. */ void STKConfig::getAllScores(std::vector<int> *all_scores, int num_karts) { if (num_karts == 0) return; assert(num_karts <= m_max_karts); all_scores->resize(num_karts); (*all_scores)[num_karts-1] = 1; // last position gets one point // Must be signed, in case that num_karts==1 for(int i=num_karts-2; i>=0; i--) { (*all_scores)[i] = (*all_scores)[i+1] + m_score_increase[i]; } } // getAllScores
huimiao638/stk-code
src/config/stk_config.cpp
C++
gpl-3.0
15,005
/* Copyright 2013-2015 Matt Tytel * * mopo 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. * * mopo 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 mopo. If not, see <http://www.gnu.org/licenses/>. */ #include "midi_lookup.h" namespace mopo { const MidiLookupSingleton MidiLookup::lookup_; } // namespace mopo
mtytel/cursynth
mopo/src/midi_lookup.cpp
C++
gpl-3.0
777
#include "statuslabel.h" #include "../utility/font.h" StatusLabel::StatusLabel(QWidget *parent, std::size_t id, const QString &initial) : QLabel(initial, parent), m_id(id) { setFont(qfont::courier()); } std::size_t StatusLabel::id() const { return m_id; }
Controls-UWNRG/minotaur-cpp
code/camera/statuslabel.cpp
C++
gpl-3.0
274