repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
slackero/phpwcms
|
include/inc_module/mod_seolog/backend.default.php
|
1358
|
<?php
/**
* phpwcms content management system
*
* @author Oliver Georgi <og@phpwcms.org>
* @copyright Copyright (c) 2002-2022, Oliver Georgi
* @license http://opensource.org/licenses/GPL-2.0 GNU GPL-2
* @link http://www.phpwcms.org
*
**/
// ----------------------------------------------------------------
// obligate check for phpwcms constants
if (!defined('PHPWCMS_ROOT')) {
die("You Cannot Access This Script Directly, Have a Nice Day.");
}
// ----------------------------------------------------------------
/*
* module glossary
* ===============
*
* some defaults for modules: $phpwcms['modules'][$module]
* store all related in here and holds some default values
* ['path'], ['type'], ['name']
* language values are store in $BL['modules'][$module]
* as defined in lang/en.lang.php
* but maybe to keep default language file more lightweight
* you can use own language definitions starting within this file
*
*/
// first check if neccessary db exists
if(isset($phpwcms['modules'][$module]['path'])) {
// module default stuff
// put translation back to have easier access to it - use it as relation
$BLM = & $BL['modules'][$module];
define('MODULE_HREF', 'phpwcms.php?'.get_token_get_string().'&do=modules&module='.$module);
// listing
include_once $phpwcms['modules'][$module]['path'].'backend.listing.php';
}
|
gpl-2.0
|
ya790206/temp_hg
|
hgext/factotum.py
|
4290
|
# factotum.py - Plan 9 factotum integration for Mercurial
#
# Copyright (C) 2012 Steven Stallion <sstallion@gmail.com>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
'''http authentication with factotum
This extension allows the factotum(4) facility on Plan 9 from Bell Labs
platforms to provide authentication information for HTTP access. Configuration
entries specified in the auth section as well as authentication information
provided in the repository URL are fully supported. If no prefix is specified,
a value of "*" will be assumed.
By default, keys are specified as::
proto=pass service=hg prefix=<prefix> user=<username> !password=<password>
If the factotum extension is unable to read the required key, one will be
requested interactively.
A configuration section is available to customize runtime behavior. By
default, these entries are::
[factotum]
executable = /bin/auth/factotum
mountpoint = /mnt/factotum
service = hg
The executable entry defines the full path to the factotum binary. The
mountpoint entry defines the path to the factotum file service. Lastly, the
service entry controls the service name used when reading keys.
'''
from mercurial.i18n import _
from mercurial.url import passwordmgr
from mercurial import httpconnection, util
import os, urllib2
ERRMAX = 128
_executable = _mountpoint = _service = None
def auth_getkey(self, params):
if not self.ui.interactive():
raise util.Abort(_('factotum not interactive'))
if 'user=' not in params:
params = '%s user?' % params
params = '%s !password?' % params
os.system("%s -g '%s'" % (_executable, params))
def auth_getuserpasswd(self, getkey, params):
params = 'proto=pass %s' % params
while True:
fd = os.open('%s/rpc' % _mountpoint, os.O_RDWR)
try:
try:
os.write(fd, 'start %s' % params)
l = os.read(fd, ERRMAX).split()
if l[0] == 'ok':
os.write(fd, 'read')
l = os.read(fd, ERRMAX).split()
if l[0] == 'ok':
return l[1:]
except (OSError, IOError):
raise util.Abort(_('factotum not responding'))
finally:
os.close(fd)
getkey(self, params)
def monkeypatch_method(cls):
def decorator(func):
setattr(cls, func.__name__, func)
return func
return decorator
@monkeypatch_method(passwordmgr)
def find_user_password(self, realm, authuri):
user, passwd = urllib2.HTTPPasswordMgrWithDefaultRealm.find_user_password(
self, realm, authuri)
if user and passwd:
self._writedebug(user, passwd)
return (user, passwd)
prefix = ''
res = httpconnection.readauthforuri(self.ui, authuri, user)
if res:
_, auth = res
prefix = auth.get('prefix')
user, passwd = auth.get('username'), auth.get('password')
if not user or not passwd:
if not prefix:
prefix = realm.split(' ')[0].lower()
params = 'service=%s prefix=%s' % (_service, prefix)
if user:
params = '%s user=%s' % (params, user)
user, passwd = auth_getuserpasswd(self, auth_getkey, params)
self.add_password(realm, authuri, user, passwd)
self._writedebug(user, passwd)
return (user, passwd)
def uisetup(ui):
global _executable
_executable = ui.config('factotum', 'executable', '/bin/auth/factotum')
global _mountpoint
_mountpoint = ui.config('factotum', 'mountpoint', '/mnt/factotum')
global _service
_service = ui.config('factotum', 'service', 'hg')
|
gpl-2.0
|
codebysd/codebysd.github.io
|
libs/markdown.js
|
439
|
var marked = require('marked');
/**
* Module to work with markdown parsing.
*/
function markdown(){}
/**
* @type {markdown}
*/
module.exports = markdown;
/**
* Parse given string to markdown.
* @param {String} mdString - markdown string.
* @returns {String} html string.
*/
markdown.parse = function(mdString){
try{
return marked(mdString);
}catch(e){
console.error('Error parsing markdown.',e);
}
};
|
gpl-2.0
|
Fojar/aseprite
|
src/app/ui/home_view.cpp
|
4852
|
// Aseprite
// Copyright (C) 2001-2015 David Capello
//
// 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.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "app/ui/home_view.h"
#include "app/app.h"
#include "app/app_menus.h"
#include "app/commands/commands.h"
#include "app/commands/params.h"
#include "app/ui/data_recovery_view.h"
#include "app/ui/main_window.h"
#include "app/ui/news_listbox.h"
#include "app/ui/recent_listbox.h"
#include "app/ui/skin/skin_style_property.h"
#include "app/ui/skin/skin_theme.h"
#include "app/ui/workspace.h"
#include "app/ui/workspace_tabs.h"
#include "app/ui_context.h"
#include "base/bind.h"
#include "base/exception.h"
#include "ui/label.h"
#include "ui/resize_event.h"
#include "ui/system.h"
#include "ui/textbox.h"
#include "ui/view.h"
namespace app {
using namespace ui;
using namespace app::skin;
HomeView::HomeView()
: m_files(new RecentFilesListBox)
, m_folders(new RecentFoldersListBox)
, m_news(new NewsListBox)
, m_dataRecovery(nullptr)
, m_dataRecoveryView(nullptr)
{
SkinTheme* theme = static_cast<SkinTheme*>(this->theme());
setBgColor(theme->colors.workspace());
setChildSpacing(8 * guiscale());
newFile()->Click.connect(base::Bind(&HomeView::onNewFile, this));
openFile()->Click.connect(base::Bind(&HomeView::onOpenFile, this));
recoverSprites()->Click.connect(base::Bind(&HomeView::onRecoverSprites, this));
filesView()->attachToView(m_files);
foldersView()->attachToView(m_folders);
newsView()->attachToView(m_news);
checkUpdate()->setVisible(false);
recoverSpritesPlaceholder()->setVisible(false);
}
HomeView::~HomeView()
{
#ifdef ENABLE_DATA_RECOVERY
if (m_dataRecoveryView) {
if (m_dataRecoveryView->parent())
App::instance()->getMainWindow()->getWorkspace()->removeView(m_dataRecoveryView);
delete m_dataRecoveryView;
}
#endif
}
void HomeView::showDataRecovery(crash::DataRecovery* dataRecovery)
{
#ifdef ENABLE_DATA_RECOVERY
m_dataRecovery = dataRecovery;
recoverSpritesPlaceholder()->setVisible(true);
#endif
}
std::string HomeView::getTabText()
{
return "Home";
}
TabIcon HomeView::getTabIcon()
{
return TabIcon::HOME;
}
bool HomeView::onCloseView(Workspace* workspace)
{
workspace->removeView(this);
return true;
}
void HomeView::onTabPopup(Workspace* workspace)
{
Menu* menu = AppMenus::instance()->getTabPopupMenu();
if (!menu)
return;
menu->showPopup(ui::get_mouse_position());
}
void HomeView::onWorkspaceViewSelected()
{
}
void HomeView::onNewFile()
{
Command* command = CommandsModule::instance()->getCommandByName(CommandId::NewFile);
UIContext::instance()->executeCommand(command);
}
void HomeView::onOpenFile()
{
Command* command = CommandsModule::instance()->getCommandByName(CommandId::OpenFile);
UIContext::instance()->executeCommand(command);
}
void HomeView::onResize(ui::ResizeEvent& ev)
{
headerPlaceholder()->setVisible(ev.bounds().h > 200*ui::guiscale());
foldersPlaceholder()->setVisible(ev.bounds().h > 150*ui::guiscale());
newsPlaceholder()->setVisible(ev.bounds().w > 200*ui::guiscale());
ui::VBox::onResize(ev);
}
#ifdef ENABLE_UPDATER
void HomeView::onCheckingUpdates()
{
checkUpdate()->setText("Checking Updates...");
checkUpdate()->setVisible(true);
layout();
}
void HomeView::onUpToDate()
{
checkUpdate()->setText(PACKAGE " is up to date");
checkUpdate()->setVisible(true);
layout();
}
void HomeView::onNewUpdate(const std::string& url, const std::string& version)
{
SkinTheme* theme = static_cast<SkinTheme*>(this->theme());
checkUpdate()->setText("New " PACKAGE " v" + version + " available!");
checkUpdate()->setUrl(url);
checkUpdate()->setProperty(
SkinStylePropertyPtr(new SkinStyleProperty(theme->styles.workspaceUpdateLink())));
// TODO this should be in a skin.xml's <style>
gfx::Size iconSize = theme->styles.workspaceUpdateLink()->sizeHint(
nullptr, Style::State());
checkUpdate()->setBorder(gfx::Border(6*guiscale())+gfx::Border(
0, 0, iconSize.w, 0));
checkUpdate()->setVisible(true);
layout();
}
#endif // ENABLE_UPDATER
void HomeView::onRecoverSprites()
{
#ifdef ENABLE_DATA_RECOVERY
if (!m_dataRecoveryView) {
m_dataRecoveryView = new DataRecoveryView(m_dataRecovery);
// Hide the "Recover Lost Sprites" button when the
// DataRecoveryView is empty.
m_dataRecoveryView->Empty.connect(
[this]{
recoverSpritesPlaceholder()->setVisible(false);
layout();
});
}
if (!m_dataRecoveryView->parent())
App::instance()->getMainWindow()->getWorkspace()->addView(m_dataRecoveryView);
App::instance()->getMainWindow()->getTabsBar()->selectTab(m_dataRecoveryView);
#endif
}
} // namespace app
|
gpl-2.0
|
Felli/fireside
|
core/controllers/ETSitemapController.class.php
|
5748
|
<?php
// Copyright 2011 Toby Zerner, Simon Zerner
// This file is part of esoTalk. Please see the included license file for usage information.
// Sitemap: generates necessary sitemap files and outputs sitemap.xml.
define("IN_ESOTALK", 1);
// Include our config files.
require "config.default.php";
@include "config/config.php";
if (!isset($config)) {
exit;
}
// Combine config.default.php and config/config.php into $config (the latter will overwrite the former.)
$config = array_merge($defaultConfig, $config);
// Compare the hardcoded version of esoTalk (ESOTALK_VERSION) to the installed one ($versions["esoTalk"]).
// If they're out-of-date, stop page execution.
require "config/versions.php";
if ($versions["esoTalk"] != ESOTALK_VERSION) {
exit;
}
require "lib/functions.php";
// If sitemap.xml is recent then we'll just use the cached version.
// Otherwise, we'll regenerate all the sitemap files.
if (!file_exists("sitemap.xml") or filemtime("sitemap.xml") < time() - $config["sitemapCacheTime"] - 200) {
// If there are lots of conversations, this might take a while...
set_time_limit(0);
// Connect to the database.
require "lib/database.php";
$db = new Database();
if (!$db->connect($config["mysqlHost"], $config["mysqlUser"], $config["mysqlPass"], $config["mysqlDB"])) {
exit;
}
// Does sitemap.general.xml exist? If not, create it.
if (!file_exists("sitemap.general.xml")) {
writeFile("sitemap.general.xml", "<?xml version='1.0' encoding='UTF-8'?><urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'><url><loc>{$config["baseURL"]}</loc><changefreq>hourly</changefreq><priority>1.0</priority></url></urlset>");
}
// Initiate the counter and some settings.
$i = 1;
define("URLS_PER_SITEMAP", 40000); // 40,000 almost definitely will not exceed the 10MB sitemap limit.
define("ZLIB", extension_loaded("zlib") ? ".gz" : null);
// Generate conversation sitemap files until we run out of conversations.
while (true) {
// Set the filename with the counter.
$filename = "sitemap.conversations.$i.xml" . ZLIB;
// Get the next batch of public conversations from the database.
$r = mysql_query("SELECT conversationId, slug, posts / ((UNIX_TIMESTAMP() - startTime) / 86400) AS postsPerDay, IF(lastActionTime, lastActionTime, startTime) AS lastUpdated, posts FROM " . config("esoTalk.database.prefix") . "conversations WHERE !private LIMIT " . (($i - 1) * URLS_PER_SITEMAP) . "," . URLS_PER_SITEMAP);
// If there are no conversations left, break from the loop.
if (!mysql_num_rows($r)) {
break;
}
// Otherwise let's make the sitemap file.
else {
$urlset = "<?xml version='1.0' encoding='UTF-8'?><urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>";
// Create a <url> tag for each conversation in the result set.
while (list($conversationId, $slug, $postsPerDay, $lastUpdated, $posts) = mysql_fetch_row($r)) {
$urlset .= "<url><loc>{$config["baseURL"]}" . makeLink($conversationId, $slug) . "</loc><lastmod>" . gmdate("Y-m-d\TH:i:s+00:00", $lastUpdated) . "</lastmod><changefreq>";
// How often should we tell them to check for updates?
if ($postsPerDay < 0.006) {
$urlset .= "yearly";
} elseif ($postsPerDay < 0.07) {
$urlset .= "monthly";
} elseif ($postsPerDay < 0.3) {
$urlset .= "weekly";
} elseif ($postsPerDay < 3) {
$urlset .= "daily";
} else {
$urlset .= "hourly";
}
$urlset .= "</changefreq>";
// Estimate the conversation's importance based upon the number of posts.
if ($posts < 50); // Default priority is 0.5, so specifying it is redundant.
elseif ($posts < 100) {
$urlset .= "<priority>0.6</priority>";
} elseif ($posts < 500) {
$urlset .= "<priority>0.7</priority>";
} elseif ($posts < 1000) {
$urlset .= "<priority>0.8</priority>";
} else {
$urlset .= "<priority>0.9</priority>";
}
$urlset .= "</url>";
}
// [Encode, and] write out the file.
$urlset .= "</urlset>";
if (ZLIB) {
$urlset = gzencode($urlset, 9);
}
writeFile($filename, $urlset);
// And increment the counter for the next cycle.
$i++;
}
}
// Now we're gonna generate the sitemap index.
$sitemap = "<?xml version='1.0' encoding='UTF-8'?><sitemapindex xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'><sitemap><loc>{$config["baseURL"]}sitemap.general.xml</loc></sitemap>";
// For each conversation sitemap that we wrote, up until we break'd, add a <sitemap> entry to the index.
for ($j = 1; $j < $i; $j++) {
$sitemap .= "<sitemap><loc>{$config["baseURL"]}sitemap.conversations.$j.xml" . ZLIB . "</loc><lastmod>" . gmdate("Y-m-d\TH:i:s+00:00") . "</lastmod></sitemap>";
}
$sitemap .= "</sitemapindex>";
// And write out!
writeFile("sitemap.xml", $sitemap);
}
// Whether we generated new sitemaps or are using a cached version, let's include the sitemap index and serve it as xml.
header("Content-type: text/xml");
$handle = fopen("sitemap.xml", "r");
echo fread($handle, filesize("sitemap.xml"));
fclose($handle);
|
gpl-2.0
|
DsgnDvlp/personalWebsite
|
pages/dettaglio.php
|
4160
|
<?php
$path = "";
include("database.php");
$connection = connect();
//USER CONTROLLER PER L'HEAD
function head($path){ ?>
<!--ROYAL SLIDER -->
<link rel="stylesheet" href="css/royalslider.css">
<!-- skin stylesheet (change it if you use another) -->
<!--<link rel="stylesheet" href="royalslider/skins/default/rs-default.css">-->
<!-- Main slider JS script file -->
<!-- Create it with slider online build tool for better performance. -->
<script type="text/javascript" src="js/jquery.easings.min.js"></script>
<script type="text/javascript" src="js/jquery.royalslider.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/dettaglio.css"/>
<script type="text/javascript" src="js/dettaglio.js"></script>
<?php }
//user controll per il content..
function content($path){ ?>
<!-- CONTENUTO DELLA PAGINA -->
<?php
global $connection;
$result = $connection -> query("select * from Progetti p join Categorie c on p.category = c.id where p.id = '".$_GET["i"]."'");
$project = mysqli_fetch_array($result);
$nextPrevious = $connection -> query("select * from Progetti p where id != '".$_GET["i"]."'");
$previous = mysqli_fetch_array($nextPrevious);
$next = mysqli_fetch_array($nextPrevious);
?>
<div id="fullpage">
<div class="royalSlider rsDefault">
<!-- simple image slide -->
<img class="rsImg" src="projects/<?=$project['Title']?>/slide1.png" alt="image desc" />
<!-- <img class="rsImg" src="projects/<?=$project['Title']?>/slide2.png" alt="image desc" /> -->
<!-- <img class="rsImg" src="projects/<?=$project['Title']?>/slide3.png" alt="image desc" /> -->
<img class="rsImg mobileSlideImage" src="projects/<?=$project['Title']?>/slide1Mobile.png" alt="image desc" />
</div>
<p class="category"><?= $project["Name"]?></p>
<p class="title"><?= $project["Title"] ?></p>
<p class="subtitle"><?= $project["Subtitle_".$_SESSION["lang"]] ?></p>
<div class="detailsRow">
<div class="detailsItem">
<p class="detailTitle"><?=tr_("dettaglioInfo")?></p>
<p class="detailContent"><?= $project["Info_".$_SESSION["lang"]]?></p>
</div>
<div class="detailsItem">
<p class="detailTitle"><?=tr_("dettaglioRole")?></p>
<p class="detailContent"><?= $project["Role"]?></p>
</div>
<div class="detailsItem">
<p class="detailTitle"><?=tr_("dettaglioYear")?></p>
<p class="detailContent"><?= $project["Year"]?></p>
</div>
</div>
<div class="imageContainer">
<img class="fullWidth" src="projects/<?=$project['Title']?>/1.png"/>
<img class="fullWidth" src="projects/<?=$project['Title']?>/2.png"/>
<img class="middleWidth left" src="projects/<?=$project['Title']?>/3.png"/>
<img class="middleWidth right" src="projects/<?=$project['Title']?>/4.png"/>
<div class="clearFix"></div>
<img class="fullWidth" src="projects/<?=$project['Title']?>/5.png"/>
<img class="fullWidth mobileImage" src="projects/<?=$project['Title']?>/mobile1.png"/>
<img class="fullWidth mobileImage" src="projects/<?=$project['Title']?>/mobile2.png"/>
<img class="fullWidth mobileImage" src="projects/<?=$project['Title']?>/mobile3.png"/>
</div>
<div class="behanceContainer">
<?=tr_("dettaglioBehanceText")?>
</div>
<div class="prevNextContainer">
<div class="previous">
<a class="prevNextLink" href="projectDetails?i=<?=$previous['id']?>">
<img class="prevNextImg" src = "projects/<?=$previous["Title"]?>/front.png">
<p class="prevNextText"><?=tr_("dettaglioPreviousButton")?></p>
</a>
</div>
<div class="center">
<p class="bottomRowText"><?=tr_("dettaglioLostText")?></p>
<a class="bottomRowButton" href="contact"><?=tr_("dettaglioContactButton")?></a>
</div>
<div class="next">
<a class="prevNextLink" href="projectDetails?i=<?=$next['id']?>">
<img class="prevNextImg" src = "projects/<?=$next["Title"]?>/front.png">
<p class="prevNextText"><?=tr_("dettaglioNextButton")?></p>
</a>
</div>
</div>
</div>
<?php }
//chiamata alla masterPage
require($path."master.php");
?>
|
gpl-2.0
|
fobia/srv-tools-phpmyadmin
|
examples/config.inc.php
|
2612
|
<?php
/*
* Generated configuration file
* Generated by: phpMyAdmin 3.5.5 setup script
* Date: Fri, 31 May 2013 23:27:53 +0400
*/
/* Servers configuration */
$i = 0;
/* Server: root [2] */
$i++;
$cfg['Servers'][$i]['verbose'] = 'root';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['nopassword'] = true;
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['CountTables'] = true;
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = 'pmapass';
$cfg['Servers'][$i]['verbose_check'] = false;
$cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][$i]['relation'] = 'pma_relation';
$cfg['Servers'][$i]['userconfig'] = 'pma_userconfig';
$cfg['Servers'][$i]['table_info'] = 'pma_table_info';
$cfg['Servers'][$i]['column_info'] = 'pma_column_info';
$cfg['Servers'][$i]['history'] = 'pma_history';
$cfg['Servers'][$i]['recent'] = 'pma_recent';
$cfg['Servers'][$i]['table_uiprefs'] = 'pma_table_uiprefs';
$cfg['Servers'][$i]['tracking'] = 'pma_tracking';
$cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
/* Server: host [3] */
$i++;
$cfg['Servers'][$i]['verbose'] = 'host';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = '';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['AllowRoot'] = false;
$cfg['Servers'][$i]['CountTables'] = true;
/* End of servers configuration */
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';
$cfg['BZipDump'] = false;
$cfg['DefaultLang'] = 'ru';
$cfg['ThemeDefault'] = 'original';
$cfg['ServerDefault'] = 1;
$cfg['CompressOnFly'] = false;
$cfg['UserprefsDeveloperTab'] = true;
$cfg['HideStructureActions'] = false;
$cfg['LoginCookieDeleteAll'] = false;
$cfg['QueryHistoryDB'] = true;
$cfg['RetainQueryBox'] = true;
$cfg['blowfish_secret'] = '51a360783193d3.45092927';
$cfg['LeftDefaultTabTable'] = 'tbl_select.php';
$cfg['MaxTableList'] = 500;
?>
|
gpl-2.0
|
mymengyu/8Comic-Viewer
|
8ComicViewer.user.js
|
4344
|
// ==UserScript==
// @name 8Comic Viewer
// @namespace https://knowlet3389.blogspot.tw/
// @version 1.70
// @description Auto load 8comic pic.
// @author KNowlet
// @include /^http[s]?\:\/\/.*\/online\/(best_|comic-|manga_|a-|b-)\d+\.html(\?ch=\d+.*)?$/
// @grant none
// @downloadURL https://github.com/knowlet/8Comic-Viewer/raw/master/8ComicViewer.user.js
// ==/UserScript==
(function() {
var a = document.getElementById("TheImg").parentNode, b = false;
// resize table
a.parentNode.parentNode.parentNode.width = "100%";
document.getElementById("TheImg").remove();
// Memory Vol.
localStorage.getItem(ti) > ch && confirm("你上次已經看到第" + localStorage.getItem(ti) + "話(卷)囉!\n是否要前往呢?") ? jv(localStorage.getItem(ti)) : localStorage.setItem(ti, ch);
// Load Pic
var z = document.body.innerHTML.match(/\'\/\/img.*\'\.jpg\'/);
if(z == null){
z = document.body.innerHTML.match(/\.src\=unescape\(.*?\);/);
z[0] = z[0].replace(".src=","");
}
var images = document.createDocumentFragment();
if (z === null) {
for (var d = 1; d <= ps; ++d) {
var image = document.createElement("img");
image.setAttribute("src", "//img" + su(tmkqp, 0, 1) + ".8comic.com/" + su(tmkqp, 1, 1) + "/" + ti + "/" + vnnlw + "/" + nn(d) + "_" + su(cewds, mm(d), 3) + ".jpg");
images.appendChild(image);
images.appendChild(document.createElement("br"));
}
}
else {
for (var p = 1; p <= ps; ++p) {
var image = document.createElement("img");
image.setAttribute("src", eval(z[0]));
images.appendChild(image);
images.appendChild(document.createElement("br"));
}
}
a.appendChild(images);
// Load CSS
a = document.createElement("link");
a.setAttribute("rel", "stylesheet");
a.setAttribute("type", "text/css");
a.setAttribute("href", "https://8comic.knowlet.me/files/css/style.css");
document.head.appendChild(a);
// Create Navbar
var navX, navY;
document.body.innerHTML = document.getElementById("Form1").innerHTML + "<nav id='nb'><span id='btDrag'>x</span><ul><li id='btPrev'><img src='//8comic.knowlet.me/files/img/pv.png' alt='上一卷(話)' /></li><li id='btMenu'><img src='//8comic.knowlet.me/files/img/mu.png' alt='全集列表' /></li><li id='btNext'><img src='//8comic.knowlet.me/files/img/nv.png' alr='下一卷(話)' /></li><li id='Scroll'><img src='//8comic.knowlet.me/files/img/sc.png' alr='自動捲頁' /></li></ul></nav>";
parseInt(localStorage.navX) < document.body.clientWidth && parseInt(localStorage.navY) < document.body.clientHeight && parseInt(localStorage.navX) > 0 && parseInt(localStorage.navY) > 0 && (navX = localStorage.navX, navY = localStorage.navY) && (nb.style.left = navX, nb.style.top = navY);
// Drag Events
document.onmousemove = function(a) {
b && (nb.style.left = navX = a.clientX + "px", nb.style.top = navY = a.clientY - 10 + "px");
};
btDrag.onmousedown = function() {
b = true;
};
document.onmouseup = function() {
b && (localStorage.setItem("navX", navX), localStorage.setItem("navY", navY));
b = false;
};
// Btn Events
btPrev.onclick = function() {
1 >= ch ? alert("前面沒有東西喔!") : (localStorage.setItem(ti,pi), pv());
};
btMenu.onclick = function() {
location.assign("http://www.8comic.com/html/" + ti.toString() + ".html");
};
btNext.onclick = function() {
nv();
ch >= chs && alert("您已看完了!") && localStorage.removeItem(ti);
};
// Auto load next page
window.onscroll = function() {
scrollY == document.body.scrollHeight - document.body.clientHeight && setTimeout(function() {
btNext.click();
}, 800);
};
// Recover contextMenu
document.oncontextmenu = null;
// Auto scrolling
var speed = 0;
var intervalHandle;
Scroll.onclick = function() {
++speed;
clearInterval(intervalHandle);
intervalHandle = setInterval(function() { window.scrollBy(0, speed); }, 1);
};
Scroll.onmouseout = function() {
speed = 0;
clearInterval(intervalHandle);
};
})();
|
gpl-2.0
|
FatherShawn/oauth2-formassembly
|
src/Provider/Exception/FormAssemblyIdentityProviderException.php
|
2085
|
<?php
/**
* @author Shawn P. Duncan <code@sd.shawnduncan.org>
* @date 7/29/17, 7:59 AM
*
* @brief
*
* Copyright 2017 by Shawn P. Duncan. This code is
* released under the GNU General Public License.
* Which means that it 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.
* http://www.gnu.org/licenses/gpl.html
*/
namespace Fathershawn\OAuth2\Client\Provider;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Psr\Http\Message\ResponseInterface;
class FormAssemblyIdentityProviderException extends IdentityProviderException
{
/**
* Creates client exception from response.
*
* @param ResponseInterface $response
* @param array|string $data Parsed response data
*
* @return IdentityProviderException
*/
public static function clientException(ResponseInterface $response, $data)
{
return static::fromResponse(
$response,
isset($data['message']) ? $data['message'] : $response->getReasonPhrase()
);
}
/**
* Creates oauth exception from response.
*
* @param ResponseInterface $response
* @param array|string $data Parsed response data
*
* @return IdentityProviderException
*/
public static function oauthException(ResponseInterface $response, $data)
{
return static::fromResponse(
$response,
isset($data['error']) ? $data['error'] : $response->getReasonPhrase()
);
}
/**
* Creates identity exception from response.
*
* @param ResponseInterface $response
* @param string $message
*
* @return IdentityProviderException
*/
protected static function fromResponse(
ResponseInterface $response,
$message = null
) {
return new static($message, $response->getStatusCode(),
(string)$response->getBody());
}
}
|
gpl-2.0
|
papillon-cendre/d8
|
core/modules/views/src/Plugin/views/field/EntityLabel.php
|
3797
|
<?php
/**
* @file
* Contains \Drupal\views\Plugin\views\field\EntityLabel.
*/
namespace Drupal\views\Plugin\views\field;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Field handler to display entity label optionally linked to entity page.
*
* @ViewsField("entity_label")
*/
class EntityLabel extends FieldPluginBase {
/**
* Array of entities that reference to file.
*
* @var array
*/
protected $loadedReferencers = array();
/**
* EntityManager class.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* Constructs a EntityLabel object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityManagerInterface $manager
* EntityManager that is stored internally and used to load nodes.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityManager = $manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity.manager')
);
}
/**
* {@inheritdoc}
*/
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
parent::init($view, $display, $options);
$this->additional_fields[$this->definition['entity type field']] = $this->definition['entity type field'];
}
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['link_to_entity'] = array('default' => FALSE);
return $options;
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['link_to_entity'] = array(
'#title' => $this->t('Link to entity'),
'#description' => $this->t('Make entity label a link to entity page.'),
'#type' => 'checkbox',
'#default_value' => !empty($this->options['link_to_entity']),
);
parent::buildOptionsForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function render(ResultRow $values) {
$type = $this->getValue($values, $this->definition['entity type field']);
$value = $this->getValue($values);
if (empty($this->loadedReferencers[$type][$value])) {
return;
}
/** @var $entity \Drupal\Core\Entity\EntityInterface */
$entity = $this->loadedReferencers[$type][$value];
if (!empty($this->options['link_to_entity'])) {
$this->options['alter']['make_link'] = TRUE;
$this->options['alter']['url'] = $entity->urlInfo();
}
return $this->sanitizeValue($entity->label());
}
/**
* {@inheritdoc}
*/
public function preRender(&$values) {
parent::preRender($values);
$entity_ids_per_type = array();
foreach ($values as $value) {
if ($type = $this->getValue($value, 'type')) {
$entity_ids_per_type[$type][] = $this->getValue($value);
}
}
foreach ($entity_ids_per_type as $type => $ids) {
$this->loadedReferencers[$type] = $this->entityManager->getStorage($type)->loadMultiple($ids);
}
}
}
|
gpl-2.0
|
lazyphp/PESCMS-TEAM
|
Public/Theme/Team/Default/User_group/User_group_index_operate.php
|
1687
|
<?php
/**
* 本模板为通用编辑按钮,若没有特殊需求,请加载本模板
*/
$echoEditUrl = empty($editUrl) ? $label->url(GROUP . '-' . MODULE . '-action', array('id' => $value["{$fieldPrefix}id"], 'back_url' => base64_encode($_SERVER['REQUEST_URI']))) : $editUrl;
$echoCopyUrl = empty($editUrl) ? $label->url(GROUP . '-' . MODULE . '-action', array('id' => $value["{$fieldPrefix}id"], 'copy' => '1', 'back_url' => base64_encode($_SERVER['REQUEST_URI']))) : $editUrl;
$echoDeleteUrl = empty($deleteUrl) ? $label->url(GROUP . '-' . MODULE . '-action', array('id' => $value["{$fieldPrefix}id"], 'method' => 'DELETE', 'back_url' => base64_encode($_SERVER['REQUEST_URI']))) : $deleteUrl;
?>
<a class="am-text-secondary" href="<?= $echoEditUrl ?>"><span class="am-icon-pencil-square-o"></span> 编辑</a>
<i class="am-margin-left-xs am-margin-right-xs">|</i>
<a class="am-text-primary" href="<?= $echoCopyUrl ?>"><span class="am-icon-copy"></span> 复制</a>
<i class="am-margin-left-xs am-margin-right-xs">|</i>
<a class="am-text-success dialog" href="<?= $label->url(GROUP . '-' . MODULE . '-setMenu', ['id' => $value['user_group_id']]) ?>"><span class="am-icon-hdd-o"></span> 设置菜单</a>
<i class="am-margin-left-xs am-margin-right-xs">|</i>
<a class="am-text-warning dialog" href="<?= $label->url(GROUP . '-' . MODULE . '-setAuth', ['id' => $value['user_group_id']]) ?>"><span class="am-icon-puzzle-piece"></span> 设置权限</a>
<i class="am-margin-left-xs am-margin-right-xs">|</i>
<a class="am-text-danger ajax-click ajax-dialog" msg="确定删除吗?将无法恢复的!"
href="<?= $echoDeleteUrl; ?>"><span class="am-icon-trash-o"></span> 删除</a>
|
gpl-2.0
|
aosm/gcc_40
|
libjava/java/lang/reflect/Field.java
|
7450
|
/* Copyright (C) 1998, 1999, 2000, 2001, 2003 Free Software Foundation
This file is part of libgcj.
This software is copyrighted work licensed under the terms of the
Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
details. */
package java.lang.reflect;
/**
* @author Per Bothner <bothner@cygnus.com>
* @date September 1998; February 1999.
*/
public final class Field extends AccessibleObject implements Member
{
private Class declaringClass;
// This is filled in by getName.
private String name;
// Offset in bytes from the start of declaringClass's fields array.
private int offset;
// This is instantiated by Class sometimes, but it uses C++ and
// avoids the Java protection check.
Field ()
{
}
public boolean equals (Object fld)
{
if (! (fld instanceof Field))
return false;
Field f = (Field) fld;
return declaringClass == f.declaringClass && offset == f.offset;
}
public Class getDeclaringClass ()
{
return declaringClass;
}
public native String getName ();
public native Class getType ();
public native int getModifiers ();
public int hashCode()
{
return (declaringClass.hashCode() ^ offset);
}
public boolean getBoolean (Object obj)
throws IllegalArgumentException, IllegalAccessException
{
return getBoolean(null, obj);
}
public char getChar (Object obj)
throws IllegalArgumentException, IllegalAccessException
{
return getChar(null, obj);
}
public byte getByte (Object obj)
throws IllegalArgumentException, IllegalAccessException
{
return getByte(null, obj);
}
public short getShort (Object obj)
throws IllegalArgumentException, IllegalAccessException
{
return getShort(null, obj);
}
public int getInt (Object obj)
throws IllegalArgumentException, IllegalAccessException
{
return getInt(null, obj);
}
public long getLong (Object obj)
throws IllegalArgumentException, IllegalAccessException
{
return getLong(null, obj);
}
public float getFloat (Object obj)
throws IllegalArgumentException, IllegalAccessException
{
return getFloat(null, obj);
}
public double getDouble (Object obj)
throws IllegalArgumentException, IllegalAccessException
{
return getDouble(null, obj);
}
public Object get (Object obj)
throws IllegalArgumentException, IllegalAccessException
{
return get(null, obj);
}
private native boolean getBoolean (Class caller, Object obj)
throws IllegalArgumentException, IllegalAccessException;
private native char getChar (Class caller, Object obj)
throws IllegalArgumentException, IllegalAccessException;
private native byte getByte (Class caller, Object obj)
throws IllegalArgumentException, IllegalAccessException;
private native short getShort (Class caller, Object obj)
throws IllegalArgumentException, IllegalAccessException;
private native int getInt (Class caller, Object obj)
throws IllegalArgumentException, IllegalAccessException;
private native long getLong (Class caller, Object obj)
throws IllegalArgumentException, IllegalAccessException;
private native float getFloat (Class caller, Object obj)
throws IllegalArgumentException, IllegalAccessException;
private native double getDouble (Class caller, Object obj)
throws IllegalArgumentException, IllegalAccessException;
private native Object get (Class caller, Object obj)
throws IllegalArgumentException, IllegalAccessException;
public void setByte (Object obj, byte b)
throws IllegalArgumentException, IllegalAccessException
{
setByte(null, obj, b);
}
public void setShort (Object obj, short s)
throws IllegalArgumentException, IllegalAccessException
{
setShort(null, obj, s);
}
public void setInt (Object obj, int i)
throws IllegalArgumentException, IllegalAccessException
{
setInt(null, obj, i);
}
public void setLong (Object obj, long l)
throws IllegalArgumentException, IllegalAccessException
{
setLong(null, obj, l);
}
public void setFloat (Object obj, float f)
throws IllegalArgumentException, IllegalAccessException
{
setFloat(null, obj, f);
}
public void setDouble (Object obj, double d)
throws IllegalArgumentException, IllegalAccessException
{
setDouble(null, obj, d);
}
public void setChar (Object obj, char c)
throws IllegalArgumentException, IllegalAccessException
{
setChar(null, obj, c);
}
public void setBoolean (Object obj, boolean b)
throws IllegalArgumentException, IllegalAccessException
{
setBoolean(null, obj, b);
}
private native void setByte (Class caller, Object obj, byte b)
throws IllegalArgumentException, IllegalAccessException;
private native void setShort (Class caller, Object obj, short s)
throws IllegalArgumentException, IllegalAccessException;
private native void setInt (Class caller, Object obj, int i)
throws IllegalArgumentException, IllegalAccessException;
private native void setLong (Class caller, Object obj, long l)
throws IllegalArgumentException, IllegalAccessException;
private native void setFloat (Class caller, Object obj, float f)
throws IllegalArgumentException, IllegalAccessException;
private native void setDouble (Class caller, Object obj, double d)
throws IllegalArgumentException, IllegalAccessException;
private native void setChar (Class caller, Object obj, char c)
throws IllegalArgumentException, IllegalAccessException;
private native void setBoolean (Class caller, Object obj, boolean b)
throws IllegalArgumentException, IllegalAccessException;
private native void set (Class caller, Object obj, Object val, Class type)
throws IllegalArgumentException, IllegalAccessException;
public void set (Object object, Object value)
throws IllegalArgumentException, IllegalAccessException
{
set(null, object, value);
}
private void set (Class caller, Object object, Object value)
throws IllegalArgumentException, IllegalAccessException
{
Class type = getType();
if (! type.isPrimitive())
set(caller, object, value, type);
else if (value instanceof Byte)
setByte(caller, object, ((Byte) value).byteValue());
else if (value instanceof Short)
setShort (caller, object, ((Short) value).shortValue());
else if (value instanceof Integer)
setInt(caller, object, ((Integer) value).intValue());
else if (value instanceof Long)
setLong(caller, object, ((Long) value).longValue());
else if (value instanceof Float)
setFloat(caller, object, ((Float) value).floatValue());
else if (value instanceof Double)
setDouble(caller, object, ((Double) value).doubleValue());
else if (value instanceof Character)
setChar(caller, object, ((Character) value).charValue());
else if (value instanceof Boolean)
setBoolean(caller, object, ((Boolean) value).booleanValue());
else
throw new IllegalArgumentException();
}
public String toString ()
{
StringBuffer sbuf = new StringBuffer ();
int mods = getModifiers();
if (mods != 0)
{
Modifier.toString(mods, sbuf);
sbuf.append(' ');
}
Method.appendClassName (sbuf, getType ());
sbuf.append(' ');
Method.appendClassName (sbuf, getDeclaringClass());
sbuf.append('.');
sbuf.append(getName());
return sbuf.toString();
}
}
|
gpl-2.0
|
JonathanPierce/MIPSStudio
|
parser.js
|
9133
|
/* global TextParser */
var Parser = (function () {
// Constants
var regex_useless = /;|,|\r|\v|\f|(^\s*\n)|^\s+/gim;
var regex_spaces = /\ \ +|\t+/gmi;
var regex_comment = /^(#|\/\/)(.*)/im;
var regex_multicomment = /\/\*((.|\n)*)\*\//gim;
var regex_linelabel = /^[a-zA-Z_][a-zA-Z0-9_]*:$/im;
var regex_constant = /^([a-zA-Z_][a-zA-Z0-9_]*)\ ?=\ ?(.+)/im;
// Cleanup: Removes whitespace and comments, aligns labels.
// Results in line #/line/comment pairs
var cleanup = function (input) {
// Remove multiline comments /* ... */
input = input.replace(regex_multicomment, "");
// Split stuff up
var split = input.split("\n");
var result = [];
// Create the objects (after some cleanup)
for (var i = 0; i < split.length; i++) {
// ignore global directives for now
split[i] = split[i].replace(/\.globl\ .*/, "");
// Remove full-line comments
if (regex_comment.test(split[i])) {
split[i] = "";
}
// Split the comment from the body
var raw_comment = Utils.Parser.extract_comment(split[i]);
// Remove whitespace from the line
raw_comment.without = raw_comment.without.replace(regex_useless, "");
while (regex_spaces.test(raw_comment.without)) {
raw_comment.without = raw_comment.without.replace(regex_spaces, " ");
}
raw_comment.without = raw_comment.without.replace(/(.*)\s+$/im, "$1");
// Escape strings (for now, we'll unescape later)
raw_comment.without = Utils.Parser.escape_strings(raw_comment.without);
// Are we blank?
if (raw_comment.without === "") {
continue;
}
result.push({ line: (i + 1), text: raw_comment.without, comment: raw_comment.comment });
}
// inline labels with the line they are labeling
for (var i = 0; i < result.length - 1; i++) {
if (regex_linelabel.test(result[i].text)) {
result[i + 1].text = result[i].text + " " + result[i + 1].text;
result[i].text = "";
}
}
// postprocess and return the result
var new_result = [];
for (var i = 0; i < result.length; i++) {
if (result[i].text !== "") {
new_result.push(result[i]);
}
}
return new_result;
};
// ParseConstants: Parses and removes constants, then applies various substitutions
// Note: Input must have been 'cleaned up'.
var parse_constants = function (input) {
var constants = {};
for (var i = 0; i < input.length; i++) {
if (regex_constant.test(input[i].text)) {
var name = input[i].text.replace(regex_constant, "$1");
var value = Utils.Parser.const_to_val(input[i].text.replace(regex_constant, "$2"));
if (value === null) {
// FAIL
throw Utils.get_error(0, [input[i].text, input[i].line]);
}
constants[name] = value;
input[i].text = "";
}
}
// postprocess and return the result
var result = [];
for (var i = 0; i < input.length; i++) {
if (input[i].text !== "") {
result.push(input[i]);
}
}
// apply the substituions
result = subst_constants(result, constants);
return {text: result, constants: constants};
};
// Substitues constants for their values in a string.
// Also handles register converstions from named to numbered
var subst_constants = function (input, constants) {
var regs = {
"$zero": "$0",
"$r0": "$0",
"$at": "$1",
"$v0": "$2",
"$v1": "$3",
"$a0": "$4",
"$a1": "$5",
"$a2": "$6",
"$a3": "$7",
"$t0": "$8",
"$t1": "$9",
"$t2": "$10",
"$t3": "$11",
"$t4": "$12",
"$t5": "$13",
"$t6": "$14",
"$t7": "$15",
"$s0": "$16",
"$s1": "$17",
"$s2": "$18",
"$s3": "$19",
"$s4": "$20",
"$s5": "$21",
"$s6": "$22",
"$s7": "$23",
"$t8": "$24",
"$t9": "$25",
"$k0": "$26",
"$k1": "$27",
"$gp": "$28",
"$sp": "$29",
"$fp": "$30",
"$ra": "$31"
};
for (var i = 0; i < input.length; i++) {
var current = input[i].text.split(" ");
for (var j = 0; j < current.length; j++) {
var prop = current[j];
// Is this an offset?
var offset = Utils.Parser.parse_offset(prop);
if (offset) {
if (Utils.get(constants, offset.offset) !== null) {
offset.offset = constants[offset.offset].toString();
}
if (Utils.get(regs, offset.reg.toLowerCase()) !== null) {
offset.reg = regs[offset.reg.toLowerCase()];
}
// Convert the offset into two arguments (by separating with a space)
current[j] = offset.offset + " " + offset.reg;
} else {
// Handle constants
if (Utils.get(constants,prop) !== null) {
current[j] = constants[prop].toString();
}
// Handle registers
if (Utils.get(regs,prop.toLowerCase()) !== null) {
current[j] = regs[prop.toLowerCase()];
}
}
}
input[i].text = current.join(" ");
}
return input;
};
// Segment: Splits the assembly into the various segments, and verifies them
// Note: Input should have been cleaned up and had constants removed
var segment = function (input) {
var hasData = false;
var regexp_data = /^\.data$/gim;
var regexp_text = /^\.text$/gim;
var joined = Utils.Parser.join_by_prop(input, "text", "\n");
// Verify <= 1 data segments.
if (Utils.Parser.apply_regex(regexp_data, joined).length > 0) {
hasData = true;
if (Utils.Parser.apply_regex(regexp_data, joined).length > 1) {
// FAIL
throw Utils.get_error(1);
}
}
// Verify exactly 1 text segment
if (Utils.Parser.apply_regex(regexp_text, joined).length !== 1) {
// FAIL
throw Utils.get_error(2);
}
// Verify data (if any) comes before text
if(hasData && joined.indexOf(".data") > 0) {
// FAIL
throw Utils.get_error(3);
}
// If there is not data, .text should be on the first line.
if(!hasData && joined.indexOf(".text") > 0) {
// FAIL
throw Utils.get_error(3);
}
// Remove .data and .text directives, split into two arrays, and return.
var data = [];
var text = [];
var text_index = -1;
for (var i = 0; i < input.length; i++) {
if (input[i].text === ".text") {
text_index = i;
break;
}
}
data = input.slice(1, text_index);
text = input.slice(text_index + 1, input.length);
return {data: data, text: text};
};
// Parse: Performs a full parse into executable data and text segments
// Note: This makes use of cleanup, parse_constants, and segment
var parse = function (input) {
try {
// Start the chain
var cleanup_result = cleanup(input);
var constant_result = parse_constants(cleanup_result);
var segment_result = segment(constant_result.text);
// Parse the data
var data_result = DataParser.parse(segment_result.data);
var text_result = TextParser.parse(segment_result.text, data_result.labels);
return {
error: false,
constants: constant_result.constants,
data: data_result,
text: text_result
};
} catch (e) {
// Something went wrong! :(
e.error = true;
return e;
}
};
// Return out the interface
return {
cleanup: cleanup,
parse_constants: parse_constants,
segment: segment,
parse: parse
};
})();
|
gpl-2.0
|
openfoodfoundation/openfoodnetwork-wp
|
wp-content/plugins/c-project/includes/option-tree/includes/ot-settings-api.php
|
29391
|
<?php if ( ! defined( 'OT_VERSION') ) exit( 'No direct script access allowed' );
/**
* OptionTree Settings API
*
* This class loads all the methods and helpers specific to a Settings page.
*
* @package OptionTree
* @author Derek Herman <derek@valendesigns.com>
* @copyright Copyright (c) 2013, Derek Herman
*/
if ( ! class_exists( 'OT_Settings' ) ) {
class OT_Settings {
/* the options array */
private $options;
/* hooks for targeting admin pages */
private $page_hook;
/**
* Constructor
*
* @param array An array of options
* @return void
*
* @access public
* @since 2.0
*/
public function __construct( $args ) {
$this->options = $args;
/* return early if not viewing an admin page or no options */
if ( ! is_admin() || ! is_array( $this->options ) )
return false;
/* load everything */
$this->hooks();
}
/**
* Execute the WordPress Hooks
*
* @return void
*
* @access public
* @since 2.0
*/
public function hooks() {
/* add pages & menu items */
add_action( 'admin_menu', array( $this, 'add_page' ) );
/* register sections */
add_action( 'admin_init', array( $this, 'add_sections' ) );
/* register settings */
add_action( 'admin_init', array( $this, 'add_settings' ) );
/* reset options */
add_action( 'admin_init', array( $this, 'reset_options' ), 10 );
/* initialize settings */
add_action( 'admin_init', array( $this, 'initialize_settings' ), 11 );
}
/**
* Loads each admin page
*
* @return void
*
* @access public
* @since 2.0
*/
public function add_page() {
/* loop through options */
foreach( (array) $this->options as $option ) {
/* loop through pages */
foreach( (array) $this->get_pages( $option ) as $page ) {
/**
* Theme Check... stop nagging me about this kind of stuff.
* The damn admin pages are required for OT to function, duh!
*/
$theme_check_bs = 'add_menu_page';
$theme_check_bs2 = 'add_submenu_page';
/* load page in WP top level menu */
if ( ! isset( $page['parent_slug'] ) || empty( $page['parent_slug'] ) ) {
$page_hook = $theme_check_bs(
$page['page_title'],
$page['menu_title'],
$page['capability'],
$page['menu_slug'],
array( $this, 'display_page' ),
$page['icon_url'],
$page['position']
);
/* load page in WP sub menu */
} else {
$page_hook = $theme_check_bs2(
$page['parent_slug'],
$page['page_title'],
$page['menu_title'],
$page['capability'],
$page['menu_slug'],
array( $this, 'display_page' )
);
}
/* only load if not a hidden page */
if ( ! isset( $page['hidden_page'] ) ) {
/* associate $page_hook with page id */
$this->page_hook[$page['id']] = $page_hook;
/* add scripts */
add_action( 'admin_print_scripts-' . $page_hook, array( $this, 'scripts' ) );
/* add styles */
add_action( 'admin_print_styles-' . $page_hook, array( $this, 'styles' ) );
/* add contextual help */
add_action( 'load-' . $page_hook, array( $this, 'help' ) );
}
}
}
return false;
}
/**
* Loads the scripts
*
* @return void
*
* @access public
* @since 2.0
*/
public function scripts() {
ot_admin_scripts();
}
/**
* Loads the styles
*
* @return void
*
* @access public
* @since 2.0
*/
public function styles() {
ot_admin_styles();
}
/**
* Loads the contextual help for each page
*
* @return void
*
* @access public
* @since 2.0
*/
public function help() {
$screen = get_current_screen();
/* loop through options */
foreach( (array) $this->options as $option ) {
/* loop through pages */
foreach( (array) $this->get_pages( $option ) as $page ) {
/* verify page */
if ( ! isset( $page['hidden_page'] ) && $screen->id == $this->page_hook[$page['id']] ) {
/* set up the help tabs */
if ( ! empty( $page['contextual_help']['content'] ) ) {
foreach( $page['contextual_help']['content'] as $contextual_help ) {
$screen->add_help_tab(
array(
'id' => esc_attr( $contextual_help['id'] ),
'title' => esc_attr( $contextual_help['title'] ),
'content' => htmlspecialchars_decode( $contextual_help['content'] ),
)
);
}
}
/* set up the help sidebar */
if ( ! empty( $page['contextual_help']['sidebar'] ) ) {
$screen->set_help_sidebar( htmlspecialchars_decode( $page['contextual_help']['sidebar'] ) );
}
}
}
}
return false;
}
/**
* Loads the content for each page
*
* @return string
*
* @access public
* @since 2.0
*/
public function display_page() {
$screen = get_current_screen();
/* loop through settings */
foreach( (array) $this->options as $option ) {
/* loop through pages */
foreach( (array) $this->get_pages( $option ) as $page ) {
/* verify page */
if ( ! isset( $page['hidden_page'] ) && $screen->id == $this->page_hook[$page['id']] ) {
$show_buttons = isset( $page['show_buttons'] ) && $page['show_buttons'] == false ? false : true;
/* update active layout content */
if ( isset( $_REQUEST['settings-updated'] ) && $_REQUEST['settings-updated'] == 'true' ) {
$layouts = get_option( 'option_tree_layouts' );
/* has active layout */
if ( isset( $layouts['active_layout'] ) ) {
$option_tree = get_option( $option['id'] );
$layouts[$layouts['active_layout']] = ot_encode( serialize( $option_tree ) );
update_option( 'option_tree_layouts', $layouts );
}
}
echo '<div class="wrap settings-wrap" id ="page-' . $page['id'] . '">';
screen_icon( ( isset( $page['screen_icon'] ) ? $page['screen_icon'] : 'options-general' ) );
echo '<h2>' . $page['page_title'] . '</h2>';
echo ot_alert_message( $page );
settings_errors( 'option-tree' );
/* Header */
echo '<div id="option-tree-header-wrap">';
echo '<ul id="option-tree-header">';
echo '<li id="option-tree-logo"><a href="http://wordpress.org/extend/plugins/option-tree/" target="_blank">OptionTree</a></li>';
echo '<li id="option-tree-version"><span>Version ' . OT_VERSION . '</span></li>';
echo '</ul>';
/* layouts form */
if ( $page['id'] == 'ot_theme_options' && OT_SHOW_NEW_LAYOUT == true )
ot_theme_options_layouts_form();
echo '</div>';
/* remove forms on the custom settings pages */
if ( $show_buttons ) {
echo '<form action="options.php" method="post" id="option-tree-settings-api">';
settings_fields( $option['id'] );
} else {
echo '<div id="option-tree-settings-api">';
}
/* Sub Header */
echo '<div id="option-tree-sub-header">';
if ( $show_buttons )
echo '<button class="option-tree-ui-button blue right">' . $page['button_text'] . '</button>';
echo '</div>';
/* Navigation */
echo '<div class="ui-tabs">';
/* check for sections */
if ( isset( $page['sections'] ) && count( $page['sections'] ) > 0 ) {
echo '<ul class="ui-tabs-nav">';
/* loop through page sections */
foreach( (array) $page['sections'] as $section ) {
echo '<li id="tab_' . $section['id'] . '"><a href="#section_' . $section['id'] . '">' . $section['title'] . '</a></li>';
}
echo '</ul>';
}
/* sections */
echo '<div id="poststuff" class="metabox-holder">';
echo '<div id="post-body">';
echo '<div id="post-body-content">';
$this->do_settings_sections( $_GET['page'] );
echo '</div>';
echo '</div>';
echo '</div>';
echo '<div class="clear"></div>';
echo '</div>';
/* buttons */
if ( $show_buttons ) {
echo '<div class="option-tree-ui-buttons">';
echo '<button class="option-tree-ui-button blue right">' . $page['button_text'] . '</button>';
echo '</div>';
}
echo $show_buttons ? '</form>' : '</div>';
/* reset button */
if ( $show_buttons ) {
echo '<form method="post" action="' . str_replace( '&settings-updated=true', '', $_SERVER["REQUEST_URI"] ) . '">';
/* form nonce */
wp_nonce_field( 'option_tree_reset_form', 'option_tree_reset_nonce' );
echo '<input type="hidden" name="action" value="reset" />';
echo '<button type="submit" class="option-tree-ui-button red left reset-settings" title="' . __( 'Reset Options', 'option-tree' ) . '">' . __( 'Reset Options', 'option-tree' ) . '</button>';
echo '</form>';
}
echo '</div>';
}
}
}
return false;
}
/**
* Adds sections to the page
*
* @return void
*
* @access public
* @since 2.0
*/
public function add_sections() {
/* loop through options */
foreach( (array) $this->options as $option ) {
/* loop through pages */
foreach( (array) $this->get_pages( $option ) as $page ) {
/* loop through page sections */
foreach( (array) $this->get_sections( $page ) as $section ) {
/* add each section */
add_settings_section(
$section['id'],
$section['title'],
array( $this, 'display_section' ),
$page['menu_slug']
);
}
}
}
return false;
}
/**
* Callback for add_settings_section()
*
* @return string
*
* @access public
* @since 2.0
*/
public function display_section() {
/* currently pointless */
}
/**
* Add settings the the page
*
* @return void
*
* @access public
* @since 2.0
*/
public function add_settings() {
/* loop through options */
foreach( (array) $this->options as $option ) {
register_setting( $option['id'], $option['id'], array ( $this, 'sanitize_callback' ) );
/* loop through pages */
foreach( (array) $this->get_pages( $option ) as $page ) {
/* loop through page settings */
foreach( (array) $this->get_the_settings( $page ) as $setting ) {
/* skip if no setting ID */
if ( ! isset( $setting['id'] ) )
continue;
/* add get_option param to the array */
$setting['get_option'] = $option['id'];
/* add each setting */
add_settings_field(
$setting['id'],
$setting['label'],
array( $this, 'display_setting' ),
$page['menu_slug'],
$setting['section'],
$setting
);
}
}
}
return false;
}
/**
* Callback for add_settings_field() to build each setting by type
*
* @param array Setting object array
* @return string
*
* @access public
* @since 2.0
*/
public function display_setting( $args = array() ) {
extract( $args );
/* get current saved data */
$options = get_option( $get_option, false );
// Set field value
$field_value = isset( $options[$id] ) ? $options[$id] : '';
/* set standard value */
if ( isset( $std ) ) {
$field_value = ot_filter_std_value( $field_value, $std );
}
// Allow the descriptions to be filtered before being displayed
$desc = apply_filters( 'ot_filter_description', ( isset( $desc ) ? $desc : '' ), $id );
/* build the arguments array */
$_args = array(
'type' => $type,
'field_id' => $id,
'field_name' => $get_option . '[' . $id . ']',
'field_value' => $field_value,
'field_desc' => $desc,
'field_std' => isset( $std ) ? $std : '',
'field_rows' => isset( $rows ) && ! empty( $rows ) ? $rows : 15,
'field_post_type' => isset( $post_type ) && ! empty( $post_type ) ? $post_type : 'post',
'field_taxonomy' => isset( $taxonomy ) && ! empty( $taxonomy ) ? $taxonomy : 'category',
'field_min_max_step'=> isset( $min_max_step ) && ! empty( $min_max_step ) ? $min_max_step : '0,100,1',
'field_condition' => isset( $condition ) && ! empty( $condition ) ? $condition : '',
'field_operator' => isset( $operator ) && ! empty( $operator ) ? $operator : 'and',
'field_class' => isset( $class ) ? $class : '',
'field_choices' => isset( $choices ) && ! empty( $choices ) ? $choices : array(),
'field_settings' => isset( $settings ) && ! empty( $settings ) ? $settings : array(),
'post_id' => ot_get_media_post_ID(),
'get_option' => $get_option,
);
/* get the option HTML */
echo ot_display_by_type( $_args );
}
/**
* Sets the option standards if nothing yet exists.
*
* @return void
*
* @access public
* @since 2.0
*/
public function initialize_settings() {
/* loop through options */
foreach( (array) $this->options as $option ) {
/* skip if option is already set */
if ( isset( $option['id'] ) && get_option( $option['id'], false ) ) {
return false;
}
$defaults = array();
/* loop through pages */
foreach( (array) $this->get_pages( $option ) as $page ) {
/* loop through page settings */
foreach( (array) $this->get_the_settings( $page ) as $setting ) {
if ( isset( $setting['std'] ) ) {
$defaults[$setting['id']] = ot_validate_setting( $setting['std'], $setting['type'], $setting['id'] );
}
}
}
update_option( $option['id'], $defaults );
}
return false;
}
/**
* Sanitize callback for register_setting()
*
* @return string
*
* @access public
* @since 2.0
*/
public function sanitize_callback( $input ) {
/* loop through options */
foreach( (array) $this->options as $option ) {
/* loop through pages */
foreach( (array) $this->get_pages( $option ) as $page ) {
/* loop through page settings */
foreach( (array) $this->get_the_settings( $page ) as $setting ) {
/* verify setting has a type & value */
if ( isset( $setting['type'] ) && isset( $input[$setting['id']] ) ) {
/* get the defaults */
$current_settings = get_option( 'option_tree_settings' );
$current_options = get_option( $option['id'] );
/* validate setting */
if ( is_array( $input[$setting['id']] ) && in_array( $setting['type'], array( 'list-item', 'slider' ) ) ) {
/* required title setting */
$required_setting = array(
array(
'id' => 'title',
'label' => __( 'Title', 'option-tree' ),
'desc' => '',
'std' => '',
'type' => 'text',
'rows' => '',
'class' => 'option-tree-setting-title',
'post_type' => '',
'choices' => array()
)
);
/* get the settings array */
$settings = isset( $_POST[$setting['id'] . '_settings_array'] ) ? unserialize( ot_decode( $_POST[$setting['id'] . '_settings_array'] ) ) : array();
/* settings are empty for some odd ass reason get the defaults */
if ( empty( $settings ) ) {
$settings = 'slider' == $setting['type'] ?
ot_slider_settings( $setting['id'] ) :
ot_list_item_settings( $setting['id'] );
}
/* merge the two settings array */
$settings = array_merge( $required_setting, $settings );
/* create an empty WPML id array */
$wpml_ids = array();
foreach( $input[$setting['id']] as $k => $setting_array ) {
foreach( $settings as $sub_setting ) {
/* setup the WPML ID */
$wpml_id = $setting['id'] . '_' . $sub_setting['id'] . '_' . $k;
/* add id to array */
$wpml_ids[] = $wpml_id;
/* verify sub setting has a type & value */
if ( isset( $sub_setting['type'] ) && isset( $input[$setting['id']][$k][$sub_setting['id']] ) ) {
/* validate setting */
$input[$setting['id']][$k][$sub_setting['id']] = ot_validate_setting( $input[$setting['id']][$k][$sub_setting['id']], $sub_setting['type'], $sub_setting['id'], $wpml_id );
}
}
}
} else {
$input[$setting['id']] = ot_validate_setting( $input[$setting['id']], $setting['type'], $setting['id'], $setting['id'] );
}
}
/* unregister WPML strings that were deleted from lists and sliders */
if ( isset( $current_settings['settings'] ) && isset( $setting['type'] ) && in_array( $setting['type'], array( 'list-item', 'slider' ) ) ) {
if ( ! isset( $wpml_ids ) )
$wpml_ids = array();
foreach( $current_settings['settings'] as $check_setting ) {
if ( $setting['id'] == $check_setting['id'] && ! empty( $current_options[$setting['id']] ) ) {
foreach( $current_options[$setting['id']] as $key => $value ) {
foreach( $value as $ckey => $cvalue ) {
$id = $setting['id'] . '_' . $ckey . '_' . $key;
if ( ! in_array( $id, $wpml_ids ) ) {
ot_wpml_unregister_string( $id );
}
}
}
}
}
}
}
}
}
return $input;
}
/**
* Helper function to get the pages array for an option
*
* @param array Option array
* @return mixed
*
* @access public
* @since 2.0
*/
public function get_pages( $option = array() ) {
if ( empty( $option ) )
return false;
/* check for pages */
if ( isset( $option['pages'] ) && ! empty( $option['pages'] ) ) {
/* return pages array */
return $option['pages'];
}
return false;
}
/**
* Helper function to get the sections array for a page
*
* @param array Page array
* @return mixed
*
* @access public
* @since 2.0
*/
public function get_sections( $page = array() ) {
if ( empty( $page ) )
return false;
/* check for sections */
if ( isset( $page['sections'] ) && ! empty( $page['sections'] ) ) {
/* return sections array */
return $page['sections'];
}
return false;
}
/**
* Helper function to get the settings array for a page
*
* @param array Page array
* @return mixed
*
* @access public
* @since 2.0
*/
public function get_the_settings( $page = array() ) {
if ( empty( $page ) )
return false;
/* check for settings */
if ( isset( $page['settings'] ) && ! empty( $page['settings'] ) ) {
/* return settings array */
return $page['settings'];
}
return false;
}
/**
* Prints out all settings sections added to a particular settings page
*
* @global $wp_settings_sections Storage array of all settings sections added to admin pages
* @global $wp_settings_fields Storage array of settings fields and info about their pages/sections
*
* @param string The slug name of the page whos settings sections you want to output
* @return string
*
* @access public
* @since 2.0
*/
public function do_settings_sections( $page ) {
global $wp_settings_sections, $wp_settings_fields;
if ( ! isset( $wp_settings_sections ) || ! isset( $wp_settings_sections[$page] ) ) {
return false;
}
foreach ( (array) $wp_settings_sections[$page] as $section ) {
if ( ! isset( $section['id'] ) )
continue;
echo '<div id="section_' . $section['id'] . '" class="postbox ui-tabs-panel">';
call_user_func( $section['callback'], $section );
if ( ! isset( $wp_settings_fields ) || ! isset( $wp_settings_fields[$page] ) || ! isset( $wp_settings_fields[$page][$section['id']] ) )
continue;
echo '<div class="inside">';
$this->do_settings_fields( $page, $section['id'] );
echo '</div>';
echo '</div>';
}
}
/**
* Print out the settings fields for a particular settings section
*
* @global $wp_settings_fields Storage array of settings fields and their pages/sections
*
* @param string $page Slug title of the admin page who's settings fields you want to show.
* @param string $section Slug title of the settings section who's fields you want to show.
* @return string
*
* @access public
* @since 2.0
*/
public function do_settings_fields( $page, $section ) {
global $wp_settings_fields;
if ( !isset($wp_settings_fields) || !isset($wp_settings_fields[$page]) || !isset($wp_settings_fields[$page][$section]) )
return;
foreach ( (array) $wp_settings_fields[$page][$section] as $field ) {
$conditions = '';
if ( isset( $field['args']['condition'] ) && ! empty( $field['args']['condition'] ) ) {
$conditions = ' data-condition="' . $field['args']['condition'] . '"';
$conditions.= isset( $field['args']['operator'] ) && in_array( $field['args']['operator'], array( 'and', 'or' ) ) ? ' data-operator="' . $field['args']['operator'] . '"' : '';
}
echo '<div id="setting_' . $field['id'] . '" class="format-settings"' . $conditions . '>';
echo '<div class="format-setting-wrap">';
if ( $field['args']['type'] != 'textblock' && ! empty( $field['title'] ) ) {
echo '<div class="format-setting-label">';
echo '<h3 class="label">' . $field['title'] . '</h3>';
echo '</div>';
}
call_user_func( $field['callback'], $field['args'] );
echo '</div>';
echo '</div>';
}
}
/**
* Resets page options before the screen is displayed
*
* @return void
*
* @access public
* @since 2.0
*/
public function reset_options() {
/* check for reset action */
if ( isset( $_POST['option_tree_reset_nonce'] ) && wp_verify_nonce( $_POST['option_tree_reset_nonce'], 'option_tree_reset_form' ) ) {
/* loop through options */
foreach( (array) $this->options as $option ) {
/* loop through pages */
foreach( (array) $this->get_pages( $option ) as $page ) {
/* verify page */
if ( isset( $_GET['page'] ) && $_GET['page'] == $page['menu_slug'] ) {
/* reset options */
delete_option( $option['id'] );
}
}
}
}
return false;
}
}
}
/**
* This method instantiates the settings class & builds the UI.
*
* @uses OT_Settings()
*
* @param array Array of arguments to create settings
* @return void
*
* @access public
* @since 2.0
*/
if ( ! function_exists( 'ot_register_settings' ) ) {
function ot_register_settings( $args ) {
if ( ! $args )
return;
$ot_settings = new OT_Settings( $args );
}
}
/* End of file ot-settings-api.php */
/* Location: ./includes/ot-settings-api.php */
|
gpl-2.0
|
Annoa/WorkshopWA
|
WorkshopProjects/ws_shop_skel/src/main/java/edu/chl/hajo/wss/WSShopContextResolver.java
|
1117
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.chl.hajo.wss;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
/**
* This is used to remove '@'s from attribute names when serializing to JSON
* and also produce an array of objects (if list returned)
* The default serialization is "mapped" (badgerfish) here changed to "natural", see code
*
* Need dependency on jersey-json see pom.
*
* @author hajo
*/
@Provider
public class WSShopContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
private Class[] types = {ProductProxy.class};
public WSShopContextResolver() throws Exception {
this.context = new JSONJAXBContext(JSONConfiguration.natural().build(),
types);
}
@Override
public JAXBContext getContext(Class<?> objectType) {
return (types[0].equals(objectType)) ? context : null;
}
}
|
gpl-2.0
|
kunj1988/Magento2
|
app/code/Magento/Customer/Model/AttributeMetadataConverter.php
|
4946
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Model;
use Magento\Customer\Api\Data\OptionInterfaceFactory;
use Magento\Customer\Api\Data\ValidationRuleInterfaceFactory;
use Magento\Customer\Api\Data\AttributeMetadataInterfaceFactory;
use Magento\Eav\Api\Data\AttributeDefaultValueInterface;
/**
* Converter for AttributeMetadata
*/
class AttributeMetadataConverter
{
/**
* @var OptionInterfaceFactory
*/
private $optionFactory;
/**
* @var ValidationRuleInterfaceFactory
*/
private $validationRuleFactory;
/**
* @var AttributeMetadataInterfaceFactory
*/
private $attributeMetadataFactory;
/**
* @var \Magento\Framework\Api\DataObjectHelper
*/
protected $dataObjectHelper;
/**
* Initialize the Converter
*
* @param OptionInterfaceFactory $optionFactory
* @param ValidationRuleInterfaceFactory $validationRuleFactory
* @param AttributeMetadataInterfaceFactory $attributeMetadataFactory
* @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper
*/
public function __construct(
OptionInterfaceFactory $optionFactory,
ValidationRuleInterfaceFactory $validationRuleFactory,
AttributeMetadataInterfaceFactory $attributeMetadataFactory,
\Magento\Framework\Api\DataObjectHelper $dataObjectHelper
) {
$this->optionFactory = $optionFactory;
$this->validationRuleFactory = $validationRuleFactory;
$this->attributeMetadataFactory = $attributeMetadataFactory;
$this->dataObjectHelper = $dataObjectHelper;
}
/**
* Create AttributeMetadata Data object from the Attribute Model
*
* @param \Magento\Customer\Model\Attribute $attribute
* @return \Magento\Customer\Api\Data\AttributeMetadataInterface
*/
public function createMetadataAttribute($attribute)
{
$options = [];
if ($attribute->usesSource()) {
foreach ($attribute->getSource()->getAllOptions() as $option) {
$optionDataObject = $this->optionFactory->create();
if (!is_array($option['value'])) {
$optionDataObject->setValue($option['value']);
} else {
$optionArray = [];
foreach ($option['value'] as $optionArrayValues) {
$optionObject = $this->optionFactory->create();
$this->dataObjectHelper->populateWithArray(
$optionObject,
$optionArrayValues,
\Magento\Customer\Api\Data\OptionInterface::class
);
$optionArray[] = $optionObject;
}
$optionDataObject->setOptions($optionArray);
}
$optionDataObject->setLabel($option['label']);
$options[] = $optionDataObject;
}
}
$validationRules = [];
foreach ((array)$attribute->getValidateRules() as $name => $value) {
$validationRule = $this->validationRuleFactory->create()
->setName($name)
->setValue($value);
$validationRules[] = $validationRule;
}
$attributeMetaData = $this->attributeMetadataFactory->create();
if ($attributeMetaData instanceof AttributeDefaultValueInterface) {
$attributeMetaData->setDefaultValue($attribute->getDefaultValue());
}
return $attributeMetaData->setAttributeCode($attribute->getAttributeCode())
->setFrontendInput($attribute->getFrontendInput())
->setInputFilter((string)$attribute->getInputFilter())
->setStoreLabel($attribute->getStoreLabel())
->setValidationRules($validationRules)
->setIsVisible((boolean)$attribute->getIsVisible())
->setIsRequired((boolean)$attribute->getIsRequired())
->setMultilineCount((int)$attribute->getMultilineCount())
->setDataModel((string)$attribute->getDataModel())
->setOptions($options)
->setFrontendClass($attribute->getFrontend()->getClass())
->setFrontendLabel($attribute->getFrontendLabel())
->setNote((string)$attribute->getNote())
->setIsSystem((boolean)$attribute->getIsSystem())
->setIsUserDefined((boolean)$attribute->getIsUserDefined())
->setBackendType($attribute->getBackendType())
->setSortOrder((int)$attribute->getSortOrder())
->setIsUsedInGrid($attribute->getIsUsedInGrid())
->setIsVisibleInGrid($attribute->getIsVisibleInGrid())
->setIsFilterableInGrid($attribute->getIsFilterableInGrid())
->setIsSearchableInGrid($attribute->getIsSearchableInGrid());
}
}
|
gpl-2.0
|
yurikoneve/UserFrosting_Academic_Dashboard
|
cache/cbtpl/90/f0/90f0178c81f71f25701c4254b6eb065a.php
|
922
|
<div class="header">
<nav role="navigation">
<ul class="skip-links" id="prelude">
<li><a href="#main"><?php echo __('To content'); ?></a></li>
<li><a href="#blognav"><?php echo __('To menu'); ?></a></li>
<li><a href="#search"><?php echo __('To search'); ?></a></li>
</ul>
</nav>
<div class="banner" role="banner">
<h1 class="site-title"><a class="site-title__link"
href="<?php echo context::global_filter($core->blog->url,0,0,0,0,0,0,'BlogURL'); ?>"><span class="site-title__text"><?php echo context::global_filter($core->blog->name,1,0,0,0,0,0,'BlogName'); ?></span></a></h1>
<p class="site-baseline"><?php echo context::global_filter($core->blog->desc,0,0,0,0,0,0,'BlogDescription'); ?></p>
</div>
<?php if ($core->hasBehavior('publicTopAfterContent')) { $core->callBehavior('publicTopAfterContent',$core,$_ctx);} ?>
<?php echo tplSimpleMenu::displayMenu('nav header__nav','',''); ?>
</div>
|
gpl-2.0
|
mulligaj/hubzero-cms
|
core/components/com_members/models/quota.php
|
5336
|
<?php
/**
* HUBzero CMS
*
* Copyright 2005-2015 HUBzero Foundation, LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* HUBzero is a registered trademark of Purdue University.
*
* @package hubzero-cms
* @copyright Copyright 2005-2015 HUBzero Foundation, LLC.
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Components\Members\Models;
use Hubzero\Database\Relational;
use Components\Members\Models\Quota\Category;
use Components\Members\Models\Quota\Log;
use User;
use Lang;
include_once __DIR__ . DS . 'quota' . DS . 'category.php';
include_once __DIR__ . DS . 'member.php';
/**
* User quota model
*/
class Quota extends Relational
{
/**
* The table namespace
*
* @var string
*/
protected $namespace = 'users';
/**
* Default order by for model
*
* @var string
*/
public $orderBy = 'user_id';
/**
* Default order direction for select queries
*
* @var string
*/
public $orderDir = 'asc';
/**
* Fields and their validation criteria
*
* @var array
*/
protected $rules = array(
'user_id' => 'positive|nonzero'
);
/**
* Get parent user
*
* @return object
*/
public function member()
{
return $this->belongsToOne('Member', 'user_id');
}
/**
* Get parent quota category
*
* @return object
*/
public function category()
{
return $this->oneToOne('Components\Members\Models\Quota\Category', 'class_id');
}
/**
* Override save to add logging
*
* @return boolean
*/
public function save()
{
// Use getInstance, rather than User::get('username'), as existing
// user object won't get the right username if it was just updated
$username = $this->member()->get('username');
// Don't try to save quotas for auth link temp accounts (negative number usernames)
if (is_numeric($username) && $username < 0)
{
return false;
}
$action = ($this->get('id') ? 'modify' : 'add');
$result = parent::save();
if ($result)
{
$command = "update_quota '" . $this->get('user_id') . "' '" . $this->get('soft_blocks') . "' '" . $this->get('hard_blocks') . "'";
$cmd = "/bin/sh " . \Component::path('com_tools') . "/scripts/mw {$command} 2>&1 </dev/null";
exec($cmd, $results, $status);
// Check exec status
if (!isset($status) || $status != 0)
{
// Something went wrong
$this->addError(Lang::txt('COM_MEMBERS_QUOTA_USER_FAILED_TO_SAVE_TO_FILESYSTEM'));
return false;
}
$log = Log::blank();
$log->set('object_type', 'class');
$log->set('object_id', (int)$this->get('id'));
$log->set('name', (string)$this->get('alias'));
$log->set('action', (string)$action);
$log->set('actor_id', (int)User::get('id'));
$log->set('soft_blocks', (int)$this->get('soft_blocks'));
$log->set('hard_blocks', (int)$this->get('hard_blocks'));
$log->set('soft_files', (int)$this->get('soft_files'));
$log->set('hard_files', (int)$this->get('hard_files'));
$log->save();
}
return $result;
}
/**
* Upon deletion of a class, restore all users of that class to the default class
*
* @param integer $id
* @return boolean
*/
public static function restoreDefaultClass($id)
{
$deflt = Category::defaultEntry();
if (!$deflt->get('id'))
{
return false;
}
$records = self::all()
->whereEquals('class_id', $id)
->rows();
if ($records->count() > 0)
{
// Build an array of ids
$ids = array();
foreach ($records as $record)
{
// Update their class id, and their actual quota will be
// updated the next time they log in.
$record->set('class_id', (int)$deflt->get('id'));
$record->save();
}
}
return true;
}
/**
* Set default class for given set of users
*
* @param array $users
* @return bool
*/
public static function setDefaultClass($users)
{
$deflt = Category::defaultEntry();
if (!$deflt->get('id'))
{
return false;
}
if ($users && count($users) > 0)
{
$model = self::blank();
// Update their class id, and their actual quota will be
// updated the next time they log in.
$result = $model->getQuery()
->update($model->getTableName())
->set(array('class_id' => (int)$deflt->get('id')))
->whereIn('id', $users)
->execute();
if (!$result)
{
return false;
}
}
return true;
}
}
|
gpl-2.0
|
akadim/igate
|
modules/mod_vertical_scrolling_images/tmpl/default.php
|
2623
|
<?php
/**
* Vertical scrolling images Module
*
* @package Vertical scrolling images
* @subpackage Vertical scrolling images
* @version 3.0 February, 2012
* @author Gopi http://www.gopiplus.com
* @copyright Copyright (C) 2010 - 2012 www.gopiplus.com, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*
*/
// no direct access
defined('_JEXEC') or die;
if ( ! empty($images) )
{
$ivrss_count = 0;
$ivrss_html = "";
$ivrss_js = "";
$ivrss_scrollercount = $scrollercount;
if(!is_numeric($height))
{
$height = 80;
}
if(!is_numeric($ivrss_scrollercount))
{
$ivrss_scrollercount = 5;
}
foreach ( $images as $images )
{
$ivrss_path = JURI::base().$folder .DS. $images->name;
$ivrss_path = str_replace('\\', '/', $ivrss_path);
$dis_height = $height."px";
$ivrss_html = $ivrss_html . "<div class='cas_div' style='height:@$dis_height;padding:2px 0px 2px 0px;'>";
$ivrss_html = $ivrss_html . "<a style='text-decoration:none' target='_blank' class='cas_div' href='$link'><img border='0' src='$ivrss_path'></a>";
$ivrss_html = $ivrss_html . "</div>";
$ivrss_js = $ivrss_js . "ivrss_array[$ivrss_count] = '<div class=\'cas_div\' style=\'height:$dis_height;padding:2px 0px 2px 0px;\'><a style=\'text-decoration:none\' target=\'_blank\' class=\'cas_div\' href=\'$link\'><img border=\'0\' src=\'$ivrss_path\'></a></div>'; ";
$ivrss_count++;
}
$height = $height + 4;
if($ivrss_count >= $ivrss_scrollercount)
{
$ivrss_count = $ivrss_scrollercount;
$ivrss_height = ($height * $ivrss_scrollercount);
}
else
{
$ivrss_count = $ivrss_count;
$ivrss_height = ($ivrss_count*$height);
}
$ivrss_height1 = $height."px";
}
?>
<div style="padding-top:8px;padding-bottom:8px;">
<div style="text-align:left;vertical-align:middle;text-decoration: none;overflow: hidden; position: relative; margin-left: 1px; height: <?php echo $ivrss_height1; ?>;" id="ivrss_holder1_<?php echo $moduleclass_sfx; ?>"> <?php echo $ivrss_html; ?> </div>
</div>
<script type="text/javascript" language="javascript">
var ivrss_array = new Array();
var ivrss_obj = '';
var ivrss_scrollPos = '';
var ivrss_numScrolls = '';
var ivrss_heightOfElm = '<?php echo $height; ?>';
var ivrss_numberOfElm = '<?php echo $ivrss_count; ?>';
var ivrss_scrollOn = 'true';
function ivrss_createscroll()
{
<?php echo $ivrss_js; ?>
ivrss_obj = document.getElementById('ivrss_holder1_<?php echo $moduleclass_sfx; ?>');
ivrss_obj.style.height = (ivrss_numberOfElm * ivrss_heightOfElm) + 'px';
ivrss_content();
}
</script>
<script type="text/javascript">
ivrss_createscroll();
</script>
|
gpl-2.0
|
antipodeman/getChildrenCount
|
code.php
|
1217
|
<?php
$count = 0;
$parent = isset($parent) ? (integer) $parent : 0;
$published = isset($published) ? (bool) $published : true;
$deleted = isset($deleted) ? (bool) $deleted : false;
$delimeter = isset($delimeter) ? $delimeter : '|';
$dictonary = isset($dictonary) ? explode($delimeter, $dictonary) : false;
$modifier = isset($modifier) ? $modifier : 0;
$string_delimeter = isset($string_delimeter) ? $string_delimeter : ' ';
if ($parent > 0) {
$criteria = array(
'parent' => $parent,
'deleted' => $deleted,
'published' => $published,
);
$count = $modx->getCount('modResource', $criteria) - $modifier;
}
if(count($dictonary)){
$count = (string) $count;
$last_index = strlen($count)-1;
$second_last_index = $last_index > 0 ? $last_index-1 : false;
$last_symbol = $count[$last_index];
if( ($second_last_index !== false && $count[$second_last_index] == 1) || $last_symbol == 0 || $last_symbol > 4 ){
return (string) $count.$string_delimeter.$dictonary[2];
}else if($last_symbol == 1){
return (string) $count.$string_delimeter.$dictonary[0];
}else if($last_symbol > 1 && $last_symbol < 5){
return (string) $count.$string_delimeter.$dictonary[1];
}
}
return (string) $count;
|
gpl-2.0
|
diqiu50/ice-dev
|
Ice/testers/Testing/sort.cpp
|
801
|
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <algorithm>
#include <time.h>
using namespace std;
inline int cmp(const void *l, const void *r)
{
return *(int*)l - *(int*)r;
}
int main()
{
const int LEN = 10;
int *nums = new int[LEN];
for (int i=0; i<LEN; i++)
{
nums[i] = rand()%LEN;
}
sort(nums, nums+LEN);
return 0;
/*
int *nums2 = new int[LEN];
memcpy(nums2, nums, LEN*4);
int *nums3 = new int[LEN];
memcpy(nums3, nums, LEN*4);
clock_t t = clock();
stable_sort(nums2, nums2+LEN);
cout << "stable sort:" << clock() - t << endl;
t = clock();
sort(nums3, nums3+LEN);
cout << "quick sort :" << clock() - t << endl;
t = clock();
qsort(nums, LEN, sizeof(int), cmp);
cout << "cquick sort :" << clock() - t << endl;
return 0;
*/
}
|
gpl-2.0
|
xlsuite/xlsuite
|
app/models/other_payment_helper.rb
|
176
|
#- XLsuite, an integrated CMS, CRM and ERP for medium businesses
#- Copyright 2005-2009 iXLd Media Inc. See LICENSE for details.
class OtherPaymentHelper < PaymentHelper
end
|
gpl-2.0
|
leblanc-simon/gesdon2
|
src/Gesdon2Bundle/Gesdon2Bundle.php
|
121
|
<?php
namespace Gesdon2Bundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class Gesdon2Bundle extends Bundle
{
}
|
gpl-2.0
|
Ced-le-pingouin/esprit-mirror
|
src/database/projet_resp.tbl.php
|
2350
|
<?php
// This file is part of Esprit, a web Learning Management System, developped
// by the Unite de Technologie de l'Education, Universite de Mons, Belgium.
//
// Esprit 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, you can get one from the web page
// http://www.gnu.org/licenses/gpl.html
//
// Copyright (C) 2001-2006 Unite de Technologie de l'Education,
// Universite de Mons-Hainaut, Belgium.
/*
** Fichier ................: projet_resp.tbl.php
** Description ............:
** Date de création .......: 20-09-2002
** Dernière modification ..: 24-09-2002
** Auteurs ................: Filippo PORCO
** Emails .................: ute@umh.ac.be
**
** Copyright (c) 2001-2002 UTE. All rights reserved.
**
*/
class CProjet_Resp
{
var $oBdd;
var $aoPersonnes;
function CProjet_Resp (&$v_oBdd)
{
$this->oBdd = &$v_oBdd;
}
function ajouter ($v_iIdPers)
{
if ($v_iIdPers < 0)
return;
$sRequeteSql = "REPLACE INTO Projet_Resp SET"
." IdPers={$v_iIdPers}";
$this->oBdd->executerRequete ($sRequeteSql);
}
function effacer ($v_iIdPers)
{
if ($v_iIdPers < 0)
return;
$sRequeteSql = "DELETE FROM Projet_Resp WHERE IdPers={$v_iIdPers}";
$this->oBdd->executerRequete ($sRequeteSql);
}
function initResponsables ($v_sModeTri="ASC")
{
$idx = 0;
$this->aoPersonnes = array ();
//$sRequeteSql = "SELECT * FROM Projet_Resp";
$sRequeteSql = "SELECT Personne.* FROM Projet_Resp"
." LEFT JOIN Personne USING(IdPers)"
." ORDER BY Personne.Nom {$v_sModeTri}, Personne.Prenom ASC";
$hResult = $this->oBdd->executerRequete ($sRequeteSql);
while ($oEnreg = $this->oBdd->retEnregSuiv ($hResult))
{
$this->aoPersonnes[$idx] = new CPersonne ($this->oBdd,$oEnreg->IdPers);
$idx++;
}
$this->oBdd->libererResult ($hResult);
return $idx;
}
}
?>
|
gpl-2.0
|
literarymachine/LibRDF
|
LibRDF/Node.php
|
14537
|
<?php
/* $Id: Node.php 171 2006-06-15 23:24:18Z das-svn $ */
/**
* LibRDF_Node, a node or arc in an RDF graph.
*
* A LibRDF_Node is the type of the {@link LibRDF_Statement} triples.
*
* PHP version 5
*
* Copyright (C) 2006, David Shea <david@gophernet.org>
*
* LICENSE: This package is Free Software and a derivative work of Redland
* http://librdf.org/. This package is not endorsed by Dave Beckett or the
* University of Bristol. It is licensed under the following three licenses as
* alternatives:
* 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version
* 2. GNU General Public License (GPL) V2 or any newer version
* 3. Apache License, V2.0 or any newer version
*
* You may not use this file except in compliance with at least one of the
* above three licenses.
*
* See LICENSE.txt at the top of this package for the complete terms and futher
* detail along with the license tests for the licenses in COPYING.LIB, COPYING
* and LICENSE-2.0.txt repectively.
*
* @package LibRDF
* @author David Shea <david@gophernet.org>
* @copyright 2006 David Shea
* @license LGPL/GPL/APACHE
* @version Release: 1.0.0
* @link http://www.gophernet.org/projects/redland-php/
*/
/**
*/
require_once(dirname(__FILE__) . '/Error.php');
require_once(dirname(__FILE__) . '/URI.php');
/**
* A wrapper around the librdf_node datatype.
*
* The values of nodes come from three potential, disjoint sets: URIs,
* literal strings and blank identifiers. These types are represented by
* {@link LibRDF_URINode}, {@link LibRDF_LiteralNode} and
* {@link LibRDF_BlankNode}, respectively.
*
* @package LibRDF
* @author David Shea <david@gophernet.org>
* @copyright 2006 David Shea
* @license LGPL/GPL/APACHE
* @version Release: 1.0.0
* @link http://www.gophernet.org/projects/redland-php/
*/
abstract class LibRDF_Node
{
/**
* The underlying librdf_node resource.
*
* This value must be set by the constructors for the concrete node types.
*
* @var resource
* @access protected
*/
protected $node;
/**
* Destroy the Node object.
*
* @return void
* @access public
*/
public function __destruct()
{
if ($this->node) {
librdf_free_node($this->node);
}
}
/**
* Create a new node object from an existing node.
*
* @return void
* @throws LibRDF_Error If unable to copy the node
* @access public
*/
public function __clone()
{
$this->node = librdf_new_node_from_node($this->node);
if (!$this->node) {
throw new LibRDF_Error("Unable to create new Node from Node");
}
}
/**
* Return a string representation of the node.
*
* @return string A string representation of the node
* @access public
*/
public function __toString()
{
$rs = librdf_node_to_string($this->node);
if ("1.0.11" > librdf_version_string_get()) {
if (librdf_node_is_resource($this->node)) {
$rs = '<' . substr($rs, 1, -1) . '>';
} elseif (librdf_node_is_literal($this->node)) {
$rs = '"' . $rs . '"';
} elseif (librdf_node_is_blank($this->node)) {
$rs = '_:' . substr($rs, 1, -1);
}
}
return $rs;
}
/**
* Compare this node with another node for equality.
*
* Nodes of different types are not equal; thus, a URI of
* http://example.org/ and a literal string of http://example.org are not
* equal, even though they contain the same string. Similarly, literal
* nodes must match in both type and language to be considered equal.
*
* @param LibRDF_Node $node The node against which to compare
* @return boolean Whether the nodes are equal
* @access public
*/
public function isEqual(LibRDF_Node $node)
{
return (boolean) librdf_node_equals($this->node, $node->node);
}
/**
* Return the underlying librdf_node resource.
*
* This function is intended for other LibRDF classes and should not
* be called.
*
* @return resource The wrapped node
* @access public
*/
public function getNode()
{
return $this->node;
}
/**
* Wrap a librdf_node resource in the correct Node object.
*
* This function is intended for use by LibRDF classes, allowing them
* to easily convert a librdf_node resource into the correct type of
* LibRDF_Node object.
*
* @param resource $node The librdf_node to convert
* @return LibRDF_Node A concrete object implementing Node
* @throws LibRDF_Error If unable to create a new node
* @access public
* @static
*/
public static function makeNode($node)
{
if (!is_resource($node)) {
throw new LibRDF_Error("Argument must be a librdf_node resource");
}
if (librdf_node_is_resource($node)) {
return new LibRDF_URINode($node);
} elseif (librdf_node_is_literal($node)) {
return new LibRDF_LiteralNode($node);
} elseif (librdf_node_is_blank($node)) {
return new LibRDF_BlankNode($node);
} else {
throw new LibRDF_Error("Unknown query results type");
}
}
}
/**
* A specialized version of {@link LibRDF_Node} representing a URI.
*
* @package LibRDF
* @author David Shea <david@gophernet.org>
* @copyright 2006 David Shea
* @license LGPL/GPL/APACHE
* @version Release: 1.0.0
* @link http://www.gophernet.org/projects/redland-php/
*/
class LibRDF_URINode extends LibRDF_Node
{
/**
* Create a new URINode from a URI object.
*
* @param mixed $uri The URI string or librdf_node value to use
* @return void
* @throws LibRDF_Error If unable to create a new URI
* @access public
*/
public function __construct($uri)
{
if (is_string($uri)) {
$uri = new LibRDF_URI($uri);
$this->node = librdf_new_node_from_uri(librdf_php_get_world(),
$uri->getURI());
} elseif ((is_resource($uri)) and librdf_node_is_resource($uri)) {
$this->node = $uri;
} else {
throw new LibRDF_Error("Argument is not a string or
librdf_node resource");
}
if (!$this->node) {
throw new LibRDF_Error("Unable to create new URI node");
}
}
/**
* Get the namespace of a URI
*
* @return LibRDF_NS The namespace
*/
public function getNamespace() {
$split = strrpos($this, '#');
if (!$split) {
$split = strrpos($this, '/');
}
return new LibRDF_NS(substr($this, 1, $split));
}
/**
* Get the local part of a URI
*
* @return string The local part
*/
public function getLocalPart() {
$split = strrpos($this, '#');
if (!$split) {
$split = strrpos($this, '/');
}
return substr($this, $split + 1, -1);
}
/**
* Return the plain string of this URI
*
* @return string The URI's value
*/
public function getValue()
{
return substr($this, 1, -1);
}
}
class LibRDF_NS extends LibRDF_URINode
{
/**
* Return a new URINode based on this one
*
* @return LibRDF_URINode
* @access public
*/
public function __get($localPart) {
$str = $this->__toString();
return new LibRDF_URINode(
substr($str, 1, -1) . $localPart
);
}
}
/**
* A representation of a blank node.
*
* @package LibRDF
* @author David Shea <david@gophernet.org>
* @copyright 2006 David Shea
* @license LGPL/GPL/APACHE
* @version Release: 1.0.0
* @link http://www.gophernet.org/projects/redland-php/
*/
class LibRDF_BlankNode extends LibRDF_Node
{
/**
* Create a new blank node with an optional identifier.
*
* @param mixed $nodeId The nodeId value or librdf_node resource
* @return void
* @throws LibRDF_Error If unable to create a new node
* @access public
*/
public function __construct($nodeId=NULL)
{
if ($nodeId !== NULL) {
if (is_resource($nodeId)) {
if (librdf_node_is_blank($nodeId)) {
$this->node = $nodeId;
} else {
throw new LibRDF_Error("Resource argument not a valid" .
" librdf_node blank node");
}
} else {
$this->node = librdf_new_node_from_blank_identifier(librdf_php_get_world(),
$nodeId);
}
} else {
$this->node = librdf_new_node(librdf_php_get_world());
}
if (!$this->node) {
throw new LibRDF_Error("Unable to create new blank node");
}
}
/**
* Return the plain string of this bnode
*
* @return string The bnode's value
*/
public function getValue()
{
return "$this";
}
}
/**
* A representation of a literal node.
*
* Literal nodes can have a type and a language, but not both.
*
* @package LibRDF
* @author David Shea <david@gophernet.org>
* @copyright 2006 David Shea
* @license LGPL/GPL/APACHE
* @version Release: 1.0.0
* @link http://www.gophernet.org/projects/redland-php/
*/
class LibRDF_LiteralNode extends LibRDF_Node
{
/**
* Create a new Literal node.
*
* Both the $language and $datatype parameters are optional.
*
* The value of the literal node can either be a string or an XML literal
* in the form of a DOMNodeList object. If using XML, a datatype of
* http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral is implied, so
* the datatype parameter cannot be used with XML. A literal cannot have
* both a language and a datatype.
*
* @param mixed $value The literal value, either a string, a DOMNodeList or a librdf_node resource
* @param string $datatype An optional datatype URI for the literal value
* @param string $language An option language for the literal value
* @return void
* @throws LibRDF_Error If unabel to create a new node
* @access public
*/
public function __construct()
{
$valuestr = "";
$is_xml = 0;
// possible parameter lists are either LibRDF_Node $resource or
// string $value, $datatype=NULL, string $language=NULL
$num_args = func_num_args();
if (($num_args < 1) or ($num_args > 3)) {
throw new LibRDF_Error("Invalid number of arguments");
}
$value = func_get_arg(0);
if ($num_args >= 2) {
$datatype = func_get_arg(1);
if ($datatype) {
$datatype = new LibRDF_URI($datatype);
}
} else {
$datatype = NULL;
}
if ($num_args >= 3) {
$language = func_get_arg(2);
} else {
$language = NULL;
}
if (($num_args == 1) and (is_resource($value))) {
if (!librdf_node_is_literal($value)) {
throw new LibRDF_Error("Argument 1 not a valid librdf_node " .
" literal node");
} else {
$this->node = $value;
}
} else {
// value is XML, convert to a string and set the datatype
if ($value instanceof DOMNodeList) {
// XML values imply a datatype of
// http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral, so
// specifying a different datatype is an error
if (($datatype !== NULL) and
($datatype->__toString() !== "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral")) {
throw new LibRDF_Error("Cannot override datatype for XML literal");
} else {
$datatype = NULL;
}
$valuestr = "";
foreach ($value as $item) {
$valuestr .= $item->ownerDocument->saveXML($item);
}
$is_xml = 1;
} else {
$valuestr = (string) $value;
$is_xml = 0;
}
if ($datatype !== NULL) {
$datatype_uri = $datatype->getURI();
} else {
$datatype_uri = NULL;
}
if (($is_xml) or (($datatype === NULL) and ($language === NULL))) {
$this->node = librdf_new_node_from_literal(librdf_php_get_world(),
$valuestr, $language, $is_xml);
} else {
$this->node = librdf_new_node_from_typed_literal(librdf_php_get_world(),
$valuestr, $language, $datatype_uri);
}
}
if (!$this->node) {
throw new LibRDF_Error("Unable to create new literal node");
}
}
/**
* Return the datattype URI or NULL if this literal has no datatype.
*
* @return string The datatype URI
* @access public
*/
public function getDatatype()
{
$uri = librdf_node_get_literal_value_datatype_uri($this->node);
if ($uri !== NULL) {
return librdf_uri_to_string($uri);
} else {
return NULL;
}
}
/**
* Return the language of this literal or NULL if the literal has no
* language.
*
* @return string The literal's language
* @access public
*/
public function getLanguage()
{
return librdf_node_get_literal_value_language($this->node);
}
/**
* Return the plain string of this literal
*
* @return string The literal's value
*/
public function getValue()
{
if ($postfix = $this->getLanguage()) {
$output = substr($this, 1, 0 - strlen($postfix) - 2);
} else if ($postfix = $this->getDatatype()) {
$output = substr($this, 1, 0 - strlen($postfix) - 5);
} else {
$output = substr($this, 1, -1);
}
return json_decode('"'.$output.'"');
}
}
?>
|
gpl-2.0
|
jcicero518/ExcelsiorWP
|
wp-content/plugins/client-rest/admin/uf-api/check/checkUnique.php
|
471
|
<?php
require '../classes/StreamRepository.php';
// We're expecting JSON from this service, set the header accordingly
header( 'Content-type: application/json' );
// prevent JSON hijacking.. technically makes the JSON invalid but Angular strips it out
//echo ")]}'\n";
$field = $_GET['field'];
$fval = $_GET['fval'];
if ( isset( $field ) && isset( $fval ) && $fval != 'undefined' ) {
$results = StreamRepository::checkWidgetsFor( $field, $fval );
echo $results;
}
|
gpl-2.0
|
le-darshan/fitness
|
wp-content/themes/gameplan/woocommerce/single-product/sale-flash.php
|
415
|
<?php
/**
* Single Product Sale Flash
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $post, $product;
?>
<?php if ($product->is_on_sale()) : ?>
<?php //echo apply_filters('woocommerce_sale_flash', '<span class="onsale">'.__( 'Sale', 'cactusthemes' ).'</span>', $post, $product); ?>
<?php endif; ?>
|
gpl-2.0
|
michaeluno/amazon-auto-links
|
include/library/apf/factory/post_type/_controller/AdminPageFramework_Link_post_type.php
|
1963
|
<?php
/**
Admin Page Framework v3.9.0b09 by Michael Uno
Generated by PHP Class Files Script Generator <https://github.com/michaeluno/PHP-Class-Files-Script-Generator>
<http://en.michaeluno.jp/amazon-auto-links>
Copyright (c) 2013-2021, Michael Uno; Licensed under MIT <http://opensource.org/licenses/MIT> */
class AmazonAutoLinks_AdminPageFramework_Link_post_type extends AmazonAutoLinks_AdminPageFramework_Link_Base {
public function __construct($oProp, $oMsg = null) {
parent::__construct($oProp, $oMsg);
if (isset($_GET['post_type']) && $_GET['post_type'] === $this->oProp->sPostType) {
add_action('get_edit_post_link', array($this, '_replyToAddPostTypeQueryInEditPostLink'), 10, 3);
}
}
public function _replyToAddSettingsLinkInPluginListingPage($aLinks) {
$_sLinkLabel = $this->getElement($this->oProp->aPostTypeArgs, array('labels', 'plugin_listing_table_title_cell_link'), $this->oMsg->get('manage'));
$_sLinkLabel = $this->getElement($this->oProp->aPostTypeArgs, array('labels', 'plugin_action_link'), $_sLinkLabel);
if (!$_sLinkLabel) {
return $aLinks;
}
array_unshift($aLinks, '<a ' . $this->getAttributes(array('href' => esc_url("edit.php?post_type={$this->oProp->sPostType}"), 'class' => 'apf-plugin-title-action-link apf-admin-page',)) . '>' . $_sLinkLabel . "</a>");
return $aLinks;
}
public function _replyToSetFooterInfo() {
if (!$this->isPostDefinitionPage($this->oProp->sPostType) && !$this->isPostListingPage($this->oProp->sPostType) && !$this->isCustomTaxonomyPage($this->oProp->sPostType)) {
return;
}
parent::_replyToSetFooterInfo();
}
public function _replyToAddPostTypeQueryInEditPostLink($sURL, $iPostID = null, $sContext = null) {
return add_query_arg(array('post' => $iPostID, 'action' => 'edit', 'post_type' => $this->oProp->sPostType), $sURL);
}
}
|
gpl-2.0
|
mikewongtkd/freescoretkd
|
trunk/frontend/html/include/js/jquery.brackets.js
|
3203
|
$.widget( "freescore.brackets", {
options: { autoShow: true },
_create: function() {
var o = this.options;
var e = this.options.elements = {};
var html = o.html = FreeScore.html;
},
_init: function( ) {
var o = this.options;
var e = this.options.elements;
var w = this.element;
var html = o.html;
var drawing = html.div.clone().addClass( 'drawing' );
var division = new Division( o.division );
var brackets = division.brackets();
var athletes = division.athletes();
var current = html.div.clone().addClass( 'current' ).html( '<span class="fa fa-location-arrow"></span>' );
var line = {
connect : html.div.clone().addClass( 'connect' ).append( html.div.clone().addClass( 'line-down' ), html.div.clone().addClass( 'line-up' ),html.div.clone().addClass( 'line-across' )),
dot : html.div.clone().html( '<span class="fa fa-circle"></span>' ),
};
line.connect.append( line.dot.clone().addClass( 'start-high' ), line.dot.clone().addClass( 'start-low' ), line.dot.clone().addClass( 'stop' ));
var sum = function( acc, cur ) { return acc + cur; }
for( var j = 0; j < brackets.length; j++ ) {
var round = brackets[ j ];
var x = j * 300;
for( var i = 0; i < round.length; i++ ) {
var block = 400/(4/Math.pow( 2, j ));
var y = (i + 0.5) * block - 50;
var bracket = round[ i ];
var blue = { athlete : defined( bracket.blue.athlete ) ? athletes[ bracket.blue.athlete ] : new Athlete()};
var red = { athlete : defined( bracket.red.athlete ) ? athletes[ bracket.red.athlete ] : new Athlete()};
var match = html.div.clone().addClass( 'match' ).css({ top: y + 'px', left: x + 'px' });
blue.votes = bracket.blue.votes.reduce( sum );
red.votes = bracket.red.votes.reduce( sum );
var complete = blue.votes + red.votes == division.judges();
blue.lost = ! defined( bracket.blue.athlete ) || (blue.votes < red.votes && complete);
blue.won = defined( bracket.blue.athlete ) && (blue.votes > red.votes && complete);
red.lost = ! defined( bracket.red.athlete ) || (red.votes < blue.votes && complete);
red.won = defined( bracket.red.athlete ) && (red.votes > blue.votes && complete);
blue.label = html.div.clone().addClass( 'athlete chung' ).html( blue.athlete.display.name() );
red.label = html.div.clone().addClass( 'athlete hong' ).html( red.athlete.display.name() );
if( blue.lost ) { blue.label.addClass( 'lost' ); }
if( red.lost ) { red.label.addClass( 'lost' ); }
blue.score = html.div.clone().addClass( 'chung score' ).html( blue.votes );
red.score = html.div.clone().addClass( 'hong score' ).html( red.votes );
if( bracket === division.current.bracket()) { match.append( current ); }
match.append( blue.label, red.label );
match.append( blue.score, red.score );
drawing.append( match );
if( i % 2 ) {
var cx = x + 180;
var cy = y - (100 * j) - 62;
var height = (j + 1) * 100 - 4;
drawing.append( line.connect.clone().css({ top: cy, left: cx, height: height + 'px', width: '120px' }));
}
}
}
w.append( drawing );
}
});
|
gpl-2.0
|
VinceRafale/lifeguide
|
wp-content/plugins/Tevolution-Directory/functions/manage_category_customfields.php
|
4448
|
<?php
/*
* Add The listing custom categories fields for
*/
add_action( 'init', 'directory_category_custom_field');
function directory_category_custom_field()
{
global $wpdb;
/*
* created and edit the listing custom post type category custom field store in term table
*/
add_action('edited_listingcategory','directory_custom_fields_AlterFields');
add_action('created_listingcategory','directory_custom_fields_AlterFields');
/*add_action('edited_listingtags','directory_custom_fields_AlterFields');
add_action('created_listingtags','directory_custom_fields_AlterFields');*/
add_filter('manage_listingcategory_custom_column', 'manage_directory_category_columns', 10, 3);
//add_filter('manage_listingtags_custom_column', 'manage_directory_category_columns', 10, 3);
add_filter('manage_edit-listingcategory_columns', 'directory_category_columns');
//add_filter('manage_edit-listingtags_columns', 'directory_category_columns');
/*
* created and edit the event custom post type category custom field store in term table
*/
//if(isset($_GET['taxonomy']) && ($_GET['taxonomy']== 'listingcategory' || $_GET['taxonomy']== 'listingtags'))
if(isset($_GET['taxonomy']) && ($_GET['taxonomy']== 'listingcategory'))
{
$taxnow=$_GET['taxonomy'];
add_action($taxnow.'_edit_form_fields','directory_custom_fields_EditFields',11);
add_action($taxnow.'_add_form_fields','directory_custom_fields_AddFieldsAction',11);
}
}
function directory_custom_fields_EditFields($tag)
{
directory_custom_fields_AddFields($tag,'edit');
}
function directory_custom_fields_AddFieldsAction($tag)
{
directory_custom_fields_AddFields($tag,'add');
}
/*
* Function Name: directory_custom_fields_AddFields
* display custom field in event and listing category page
*/
function directory_custom_fields_AddFields($tag,$screen)
{
$tax = @$tag->taxonomy;
?>
<div class="form-field-category">
<tr class="form-field form-field-category">
<th scope="row" valign="top"><label for="cat_icon"><?php _e("Map Marker", DOMAIN); ?></label></th>
<td>
<input id="cat_icon" type="text" size="60" name="cat_icon" value="<?php echo (@$tag->term_icon)? @$tag->term_icon:''; ?>"/>
<?php _e('Or',DOMAIN);?>
<a class="button upload_button" title="Add city background image" id="cat_icon" data-editor="cat_upload_icon" href="#">
<span class="wp-media-buttons-icon"></span><?php _e('Browse',DOMAIN);?> </a>
<p class="description"><?php _e('It will appear on the homepage Google map for listings placed in this category. ',DOMAIN);?></p>
</td>
</tr>
</div>
<?php
}
/*
* Function Name: directory_custom_fields_AlterFields
* add/ edit listing and event custom taxonomy custom field
*/
function directory_custom_fields_AlterFields($termId)
{
global $wpdb;
$term_table=$wpdb->prefix."terms";
$cat_icon=$_POST['cat_icon'];
//update the service price value in terms table field
if(isset($_POST['cat_icon']) && $_POST['cat_icon']!=''){
$sql="update $term_table set term_icon='".$cat_icon."' where term_id=".$termId;
$wpdb->query($sql);
}
}
/*
* Function Name: directory_category_columns
* manage columns for event and listing custom taxonomy
*/
function directory_category_columns($columns)
{
$columns['icon'] = __('Map Marker',DOMAIN);
if(isset($_GET['taxonomy']) && $_GET['taxonomy']=='ecategory')
$columns['posts'] = __('Events',DOMAIN);
if(isset($_GET['taxonomy']) && $_GET['taxonomy']=='listingcategory')
$columns['posts'] = __('Listings',DOMAIN);
return $columns;
}
/*
* Function Name: manage_directory_category_columns
* display listing and event custom taxonomy custom field display in category columns
*/
function manage_directory_category_columns($out, $column_name, $term_id){
global $wpdb;
$term_table=$wpdb->prefix."terms";
$sql="select * from $term_table where term_id=".$term_id;
$term=$wpdb->get_results($sql);
switch ($column_name) {
case 'icon':
$out= ($term[0]->term_icon)?'<img src="'.$term[0]->term_icon.'" >':'<img src="'.TEVOLUTION_DIRECTORY_URL.'images/pin.png" >';
break;
default:
break;
}
return $out;
}
add_filter( 'manage_edit-listing_sortable_columns', 'templatic_edit_listing_columns',11 ) ;
function templatic_edit_listing_columns( $columns ) {
$columns['address'] = 'address';
$columns['posted_on'] = 'posted_on';
return $columns;
}
?>
|
gpl-2.0
|
Arom/RSSFeed
|
src/Feed.java
|
4375
|
/*
RSSFeed v .0.1 - Used to parse and output the RSS feed.
Developed for my IRC Bot project, however can be implemented anywhere you like.
Copyright (C) 2013 Christopher Ilkow
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.
*/
//Rome is used to fetch the RSS feed and get various properties of it
//Bit.ly import for shortening the long links into more compact use
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import com.rosaloves.bitlyj.Url;
import static com.rosaloves.bitlyj.Bitly.*;
import java.util.Date;
public class Feed {
private Url shortUrl;
private URL url;
private int today;
private Date lastUpdated;
private List<SyndEntry> entries;
/*
Obvious, checks for updates, compares the time of the last update to the current time and displays if finds
something new.
*/
public void checkUpdates() {
System.out.println("Last updated on: " + lastUpdated);
Iterator<SyndEntry> newEntries = getFeed(url.toString(), false);
while (newEntries.hasNext()) {
SyndEntry entry = newEntries.next();
if (entry.getPublishedDate().after(this.lastUpdated)) {
lastUpdated = entry.getPublishedDate();
System.out.println(entry.getTitle() + " " + shortUrl.getShortUrl());
//You should enter your own details in the method below, register at bit.ly to get those.
shortUrl = as("rssshort", "R_6d831dc36b5b3497feec2dc671bdec13").call(shorten(entry.getLink()));
System.out.println();
}
}
}
/*
Gets the feed from the link using Rome library. Also if true, will set the new update date, usually needed
the first time the Feed is requested.
//TODO replace deprecated getDay() method, used for simplicity for now.
*/
public Iterator<SyndEntry> getFeed(String feedUrl, boolean updateDate) {
this.today = new Date().getDay();
try{
this.url = new URL(feedUrl);
}catch(MalformedURLException ex){
System.err.print("Incorrect URL has been entered, feed could not be fetched");
}
try{
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(httpConnection));
entries = feed.getEntries();
}catch(IOException ex){
System.err.print("Error opening the connection to the URL" +ex.getStackTrace());
}catch(FeedException ex){
System.err.print("Error while fetching the feed" + ex.getStackTrace());
}
Iterator<SyndEntry> itEntries = entries.iterator();
if (updateDate) {
lastUpdated = entries.get(0).getPublishedDate();
}
return itEntries;
}
/*
Prints the feed, requires the iterator from getFeed() method.
Will print out <FeedTitle> <shortenedLink>
*/
public void printFeed(Iterator<SyndEntry> itEntries) {
while (itEntries.hasNext()) {
SyndEntry entry = itEntries.next();
if (entry.getPublishedDate().getDay() == today) {
shortUrl = as("rssshort", "R_6d831dc36b5b3497feec2dc671bdec13").call(shorten(entry.getLink()));
System.out.println(entry.getTitle() + " : " + shortUrl.getShortUrl());
System.out.println("------------------------------------------");
}
}
}
}
|
gpl-2.0
|
saces/fred
|
src/freenet/client/filter/HTMLFilter.java
|
79051
|
/* -*- Mode: java; c-basic-indent: 4; tab-width: 4 -*- */
package freenet.client.filter;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Map.Entry;
import freenet.clients.http.ToadletContextImpl;
import freenet.l10n.NodeL10n;
import freenet.support.HTMLDecoder;
import freenet.support.HTMLEncoder;
import freenet.support.Logger;
import freenet.support.URLDecoder;
import freenet.support.URLEncodedFormatException;
import freenet.support.Logger.LogLevel;
import freenet.support.io.NullWriter;
public class HTMLFilter implements ContentDataFilter, CharsetExtractor {
private static boolean logMINOR;
private static boolean logDEBUG;
private static boolean deleteWierdStuff = true;
private static boolean deleteErrors = true;
/** If true, allow documents that don't have an <html> tag or have other tags before it.
* In all cases we disallow text before the first valid tag. This is because if we don't,
* charset detection can be ambiguous, potentially resulting in attacks. */
private static boolean allowNoHTMLTag = true;
// FIXME make these configurable on a per-document level.
// Maybe by merging with TagReplacerCallback???
// For now they're just global.
/** -1 means don't allow it */
public static int metaRefreshSamePageMinInterval = 1;
/** -1 means don't allow it */
public static int metaRefreshRedirectMinInterval = 30;
@Override
public void readFilter(InputStream input, OutputStream output, String charset, HashMap<String, String> otherParams,
FilterCallback cb) throws DataFilterException, IOException {
if(cb == null) cb = new NullFilterCallback();
logMINOR = Logger.shouldLog(LogLevel.MINOR, this);
logDEBUG = Logger.shouldLog(LogLevel.DEBUG, this);
if(logMINOR) Logger.minor(this, "readFilter(): charset="+charset);
BufferedInputStream bis = new BufferedInputStream(input, 4096);
BufferedOutputStream bos = new BufferedOutputStream(output, 4096);
Reader r = null;
Writer w = null;
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
isr = new InputStreamReader(bis, charset);
osw = new OutputStreamWriter(bos, charset);
r = new BufferedReader(isr, 4096);
w = new BufferedWriter(osw, 4096);
} catch(UnsupportedEncodingException e) {
throw UnknownCharsetException.create(e, charset);
}
HTMLParseContext pc = new HTMLParseContext(r, w, charset, cb, false);
pc.run();
w.flush();
}
@Override
public void writeFilter(InputStream input, OutputStream output, String charset, HashMap<String, String> otherParams,
FilterCallback cb) throws DataFilterException, IOException {
throw new UnsupportedOperationException();
}
@Override
public String getCharset(byte[] input, int length, String parseCharset) throws DataFilterException, IOException {
logMINOR = Logger.shouldLog(LogLevel.MINOR, this);
if(logMINOR) Logger.minor(this, "getCharset(): default="+parseCharset);
if(length > getCharsetBufferSize() && Logger.shouldLog(LogLevel.MINOR, this)) {
Logger.minor(this, "More data than was strictly needed was passed to the charset extractor for extraction");
}
ByteArrayInputStream strm = new ByteArrayInputStream(input, 0, length);
Writer w = new NullWriter();
Reader r;
try {
r = new BufferedReader(new InputStreamReader(strm, parseCharset), 4096);
} catch (UnsupportedEncodingException e) {
strm.close();
throw e;
}
HTMLParseContext pc = new HTMLParseContext(r, w, null, new NullFilterCallback(), true);
try {
pc.run();
} catch (MalformedInputException e) {
// Not this charset
return null;
} catch (IOException e) {
throw e;
} catch (Throwable t) {
// Ignore ALL errors
if(logMINOR) Logger.minor(this, "Caught "+t+" trying to detect MIME type with "+parseCharset);
}
try {
r.close();
} catch (IOException e) {
throw e;
} catch (Throwable t) {
if(logMINOR) Logger.minor(this, "Caught "+t+" closing stream after trying to detect MIME type with "+parseCharset);
}
if(logMINOR) Logger.minor(this, "Returning charset "+pc.detectedCharset);
return pc.detectedCharset;
}
class HTMLParseContext {
Reader r;
Writer w;
String charset;
String detectedCharset;
final FilterCallback cb;
final boolean onlyDetectingCharset;
boolean isXHTML=false;
Stack<String> openElements;
boolean failedDetectCharset;
/** If <head> is found, then it is true. It is needed that if <title> or <meta> is found outside <head> or if a <body> is found first, then insert a <head> too*/
boolean wasHeadElementFound=false;
/** We can only have <head> once, and <meta>/<title> can't be outside it. This helps with robustness against charset attacks and allows us to stop looking for <meta> as soon as we see </head> when detecting charset. */
boolean headEnded=false;
HTMLParseContext(Reader r, Writer w, String charset, FilterCallback cb, boolean onlyDetectingCharset) {
this.r = r;
this.w = w;
this.charset = charset;
this.cb = cb;
this.onlyDetectingCharset = onlyDetectingCharset;
openElements=new Stack<String>();
}
public void setisXHTML(boolean value) {
isXHTML=value;
}
public boolean getisXHTML() {
return isXHTML;
}
public void pushElementInStack(String element) {
openElements.push(element);
}
public String popElementFromStack() {
if(openElements.size()>0)
return openElements.pop();
else
return null;
}
public String peekTopElement() {
if(openElements.isEmpty()) return null;
return openElements.peek();
}
void run() throws IOException, DataFilterException {
/**
* TOKENIZE Modes:
* <p>0) in text transitions: '<' ->(1) 1) in tag, not in
* quotes/comment/whitespace transitions: whitespace -> (4) (save
* current element) '"' -> (2) '--' at beginning of tag -> (3) '>' ->
* process whole tag 2) in tag, in quotes transitions: '"' -> (1)
* '>' -> grumble about markup in quotes in tag might confuse older
* user-agents (stay in current state) 3) in tag, in comment
* transitions: '-->' -> save/ignore comment, go to (0) '<' or '>' ->
* grumble about markup in comments 4) in tag, in whitespace
* transitions: '"' -> (2) '>' -> save tag, (0) anything else not
* whitespace -> (1)
* </p>
*/
StringBuilder b = new StringBuilder(100);
StringBuilder balt = new StringBuilder(4000);
List<String> splitTag = new ArrayList<String>();
String currentTag = null;
char pprevC = 0;
char prevC = 0;
char c = 0;
mode = INTEXT;
// No text before <html>
boolean textAllowed = false;
boolean firstChar = true;
while (true) {
// If detecting charset, stop after </head> even if haven't found <meta> charset tag.
if(onlyDetectingCharset && failedDetectCharset)
return;
// If detecting charset, and found it, stop afterwards.
if(onlyDetectingCharset && detectedCharset != null)
return;
int x;
try {
x = r.read();
}
/**
* libgcj up to at least 4.2.2 has a bug: InputStreamReader.refill() throws this exception when BufferedInputReader.refill() returns false for EOF. See:
* line 299 at InputStreamReader.java (in refill()): http://www.koders.com/java/fidD8F7E2EB1E4C22DA90EBE0130306AE30F876AB00.aspx?s=refill#L279
* line 355 at BufferedInputStream.java (in refill()): http://www.koders.com/java/fid1949641524FAC0083432D79793F554CD85F46759.aspx?s=refill#L355
* TODO: remove this when the gcj bug is fixed and the affected gcj versions are outdated.
*/
catch(java.io.CharConversionException cce) {
if(freenet.node.Node.checkForGCJCharConversionBug()) /* only ignore the exception on affected libgcj */
x = -1;
else
throw cce;
}
if (x == -1) {
switch (mode) {
case INTEXT :
if(textAllowed) {
saveText(b, currentTag, w, this);
} else {
if(!b.toString().trim().equals(""))
throwFilterException(l10n("textBeforeHTML"));
}
break;
case INTAG:
w.write("<!-- truncated page: last tag not unfinished -->");
break;
case INTAGQUOTES:
w.write("<!-- truncated page: deleted unfinished tag: still in quotes -->");
break;
case INTAGSQUOTES:
w.write("<!-- truncated page: deleted unfinished tag: still in single quotes -->");
break;
case INTAGWHITESPACE:
w.write("<!-- truncated page: deleted unfinished tag: still in whitespace -->");
break;
case INTAGCOMMENT:
w.write("<!-- truncated page: deleted unfinished comment -->");
break;
case INTAGCOMMENTCLOSING:
w.write("<!-- truncated page: deleted unfinished comment, might be closing -->");
break;
default:
// Dump unfinished tag
break;
}
break;
} else {
pprevC = prevC;
prevC = c;
c = (char) x;
if(c == 0xFEFF) {
if(firstChar) {
// BOM
if(w != null)
w.write(c);
} else {
// Null character (zero width non breaking space). Get rid.
}
continue;
}
if(c == 0) {
// Delete nulls. They can cause all sorts of problems and also can result from messing around with charsets.
continue;
}
firstChar = false;
switch (mode) {
case INTEXT :
if (c == '<') {
if(textAllowed) {
saveText(b, currentTag, w, this);
} else {
if(!b.toString().trim().equals(""))
throwFilterException(l10n("textBeforeHTML"));
}
b.setLength(0);
balt.setLength(0);
mode = INTAG;
} else {
b.append(c);
}
break;
case INTAG :
balt.append(c);
if (HTMLDecoder.isWhitespace(c)) {
splitTag.add(b.toString());
mode = INTAGWHITESPACE;
b.setLength(0);
} else if ((c == '<') && Character.isWhitespace(balt.charAt(0))) {
// Previous was an un-escaped < in a script.
if(textAllowed) {
saveText(b, currentTag, w, this);
} else {
if(!b.toString().trim().equals(""))
throwFilterException(l10n("textBeforeHTML"));
}
balt.setLength(0);
b.setLength(0);
splitTag.clear();
} else if (c == '>') {
splitTag.add(b.toString());
b.setLength(0);
String s = processTag(splitTag, w, this);
currentTag = s;
splitTag.clear();
balt.setLength(0);
mode = INTEXT;
if(s != null && (allowNoHTMLTag || (s.equals("html") || (!isXHTML) && s.equalsIgnoreCase("html"))))
textAllowed = true;
} else if (
(b.length() == 2)
&& (c == '-')
&& (prevC == '-')
&& (pprevC == '!')) {
mode = INTAGCOMMENT;
b.append(c);
} else if (c == '"') {
mode = INTAGQUOTES;
b.append(c);
} else if (c == '\'') {
mode = INTAGSQUOTES;
b.append(c);
} else if (c == '/') { /* Probable end tag */
currentTag = null; /* We didn't remember what was the last tag, so ... */
b.append(c);
} else {
b.append(c);
}
break;
case INTAGQUOTES :
// Inside double-quotes, single quotes are just another character, perfectly legal in a URL.
if (c == '"') {
mode = INTAG;
b.append(c); // Part of the element
} else if (c == '>') {
b.append(">");
} else if (c == '<') {
b.append("<");
// } else if (c=='&') {
// b.append("&");
} else if (c== '\u00A0') {
b.append(" ");
}
else {
b.append(c);
}
break;
case INTAGSQUOTES :
if (c == '\'') {
mode = INTAG;
b.append(c); // Part of the element
} else if (c == '<') {
b.append("<");
} else if (c == '>') {
b.append(">");
// }else if (c=='&') {
// b.append("&");
} else if (c== '\u00A0') {
b.append(" ");
}
else {
b.append(c);
}
break;
/*
* Comments are often used to temporarily disable
* markup; I shall allow it. (avian) White space is
* not permitted between the markup declaration
* open delimiter ("
* <!") and the comment open delimiter ("--"), but
* is permitted between the comment close delimiter
* ("--") and the markup declaration close
* delimiter (">"). A common error is to include a
* string of hyphens ("---") within a comment.
* Authors should avoid putting two or more
* adjacent hyphens inside comments. However, the
* only browser that actually gets it right is IE
* (others either don't allow it or allow other
* chars as well). The only safe course of action
* is to allow any and all chars, but eat them.
* (avian)
*/
case INTAGCOMMENT :
if ((b.length() >= 4) && (c == '-') && (prevC == '-')) {
b.append(c);
mode = INTAGCOMMENTCLOSING;
} else
b.append(c);
break;
case INTAGCOMMENTCLOSING :
if (c == '>') {
saveComment(b, w, this);
b.setLength(0);
mode = INTEXT;
} else {
b.append(c);
if(c != '-')
mode = INTAGCOMMENT;
}
break;
case INTAGWHITESPACE :
if (c == '"') {
mode = INTAGQUOTES;
b.append(c);
} else if (c == '\'') {
// e.g. <div align = 'center'> (avian)
// This will be converted automatically to double quotes \"
// Note that SINGLE QUOTES ARE LEGAL IN URLS ...
// If we have single quotes inside single quotes, we could get into a major mess here... but that's really malformed code, and it will still be safe, it will just be unreadable.
mode = INTAGSQUOTES;
b.append(c);
} else if (c == '>') {
if (!killTag)
currentTag = processTag(splitTag, w, this);
else
currentTag = null;
killTag = false;
splitTag.clear();
b.setLength(0);
balt.setLength(0);
mode = INTEXT;
if(currentTag != null && (allowNoHTMLTag || (currentTag.equals("html") || (!isXHTML) && currentTag.equalsIgnoreCase("html"))))
textAllowed = true;
} else if ((c == '<') && Character.isWhitespace(balt.charAt(0))) {
// Previous was an un-escaped < in a script.
if(textAllowed) {
saveText(b, currentTag, w, this);
} else {
if(!b.toString().trim().equals(""))
throwFilterException(l10n("textBeforeHTML"));
}
balt.setLength(0);
b.setLength(0);
splitTag.clear();
mode = INTAG;
} else if (HTMLDecoder.isWhitespace(c)) {
// More whitespace, what fun
} else {
mode = INTAG;
b.append(c);
}
}
}
}
/**While detecting the charset, if head is not closed inside
* the interval which we are examining, something is wrong, and it's
* possible that the file has been given a freakishly large head, so
* that we'll miss a charset declaration.*/
if(onlyDetectingCharset && openElements.contains("head")) {
throw new MalformedInputException(1024*64);
}
//Writing the remaining tags for XHTML if any
if(getisXHTML())
{
while(openElements.size()>0)
w.write("</"+openElements.pop()+">");
}
w.flush();
return;
}
int mode;
static final int INTEXT = 0;
static final int INTAG = 1;
static final int INTAGQUOTES = 2;
static final int INTAGSQUOTES = 3;
static final int INTAGCOMMENT = 4;
static final int INTAGCOMMENTCLOSING = 5;
static final int INTAGWHITESPACE = 6;
boolean killTag = false; // just this one
boolean writeStyleScriptWithTag = false; // just this one
boolean expectingBadComment = false;
// has to be set on or off explicitly by tags
boolean inStyle = false; // has to be set on or off explicitly by tags
boolean inScript = false; // has to be set on or off explicitly by tags
boolean killText = false; // has to be set on or off explicitly by tags
boolean killStyle = false;
int styleScriptRecurseCount = 0;
String currentStyleScriptChunk = "";
StringBuilder writeAfterTag = new StringBuilder(1024);
public void closeXHTMLTag(String element, Writer w) throws IOException {
// Assume that missing closes are way more common than extra closes.
if(openElements.isEmpty()) return;
if(element.equals(openElements.peek())) {
w.write("</"+openElements.pop()+">");
}
else {
if(openElements.contains(element)) {
while(true) {
String top = openElements.pop();
w.write("</"+top+">");
if(top.equals(element)) return;
}
} // Else it has already been closed.
}
}
}
void saveText(StringBuilder s, String tagName, Writer w, HTMLParseContext pc)
throws IOException {
if(pc.onlyDetectingCharset) return;
if(logDEBUG) Logger.debug(this, "Saving text: "+s.toString());
if (pc.killText) {
return;
}
StringBuilder out = new StringBuilder(s.length()*2);
for(int i=0;i<s.length();i++) {
char c = s.charAt(i);
if(c == '<' && !(pc.inStyle || pc.inScript)) {
//Scripts and styles parsed elsewhere
out.append("<");
}
else if((c < 32) && (c != '\t') && (c != '\n') && (c != '\r')) {
// Not a real character
// STRONGLY suggests somebody is using a bogus charset.
// This could be in order to break the filter.
if(logDEBUG) Logger.debug(this, "Removing '"+c+"' from the output stream");
continue;
}
else {
out.append(c);
}
}
String sout = out.toString();
if (pc.inStyle || pc.inScript) {
pc.currentStyleScriptChunk += sout;
return; // is parsed and written elsewhere
}
if(pc.cb != null)
pc.cb.onText(HTMLDecoder.decode(sout), tagName); /* Tag name is given as type for the text */
w.write(sout);
}
String processTag(List<String> splitTag, Writer w, HTMLParseContext pc)
throws IOException, DataFilterException {
// First, check that it is a recognized tag
if(logDEBUG) {
for(int i=0;i<splitTag.size();i++)
Logger.debug(this, "Tag["+i+"]="+splitTag.get(i));
}
ParsedTag t = new ParsedTag(splitTag);
if (!pc.killTag) {
t = t.sanitize(pc);
if (t != null) {
// We have to check whether <head> exists etc even if we are just checking the charset.
// This enables us to quit when we see </head>.
//We need to make sure that <head> is present in the document. If it is not, then GWT javascript won't get loaded.
//To achieve this, we keep track whether we processed the <head>
if(t.element.compareTo("head")==0 && !t.startSlash){
pc.wasHeadElementFound=true;
} else if(t.element.compareTo("head")==0 && t.startSlash) {
pc.headEnded = true;
if(pc.onlyDetectingCharset) pc.failedDetectCharset = true;
//If we found a <title> or a <meta> without a <head>, then we need to add them to a <head>
}else if((t.element.compareTo("meta")==0 || t.element.compareTo("title")==0) && pc.wasHeadElementFound==false){
pc.openElements.push("head");
pc.wasHeadElementFound=true;
String headContent=pc.cb.processTag(new ParsedTag("head", new HashMap<String, String>()));
if(headContent!=null && !pc.onlyDetectingCharset){
w.write(headContent);
}
}else if((t.element.compareTo("meta")==0 || t.element.compareTo("title")==0) && pc.headEnded){
throwFilterException(l10n("metaOutsideHead"));
//If we found a <body> and haven't closed <head> already, then we do
}else if(t.element.compareTo("body") == 0 && pc.openElements.contains("head")){
if(!pc.onlyDetectingCharset) w.write("</head>");
pc.headEnded = true;
if(pc.onlyDetectingCharset) pc.failedDetectCharset = true;
pc.openElements.pop();
//If we found a <body> and no <head> before it, then we insert it
}else if(t.element.compareTo("body")==0 && pc.wasHeadElementFound==false){
pc.wasHeadElementFound=true;
String headContent=pc.cb.processTag(new ParsedTag("head", new HashMap<String, String>()));
if(headContent!=null){
if(!pc.onlyDetectingCharset) w.write(headContent+"</head>");
pc.headEnded = true;
if(pc.onlyDetectingCharset) pc.failedDetectCharset = true;
}
}
if(!pc.onlyDetectingCharset) {
//If the tag needs replacement, then replace it
String newContent=pc.cb.processTag(t);
if(newContent!=null){
w.write(newContent);
if(t.endSlash==false){
pc.openElements.push(t.element);
}
}else{
if (pc.writeStyleScriptWithTag) {
pc.writeStyleScriptWithTag = false;
String style = pc.currentStyleScriptChunk;
if ((style == null) || (style.length() == 0))
pc.writeAfterTag.append("<!-- "+l10n("deletedUnknownStyle")+" -->");
else
w.write(style);
pc.currentStyleScriptChunk = "";
}
t.write(w,pc);
if (pc.writeAfterTag.length() > 0) {
w.write(pc.writeAfterTag.toString());
pc.writeAfterTag = new StringBuilder(1024);
}
}
} else
pc.writeStyleScriptWithTag = false;
}
if(t == null || t.startSlash || t.endSlash) {
if(!pc.openElements.isEmpty())
return pc.openElements.peek();
if (pc.writeAfterTag.length() > 0) {
w.write(pc.writeAfterTag.toString());
pc.writeAfterTag = new StringBuilder(1024);
}
return null;
} else return t.element;
} else {
pc.killTag = false;
pc.writeStyleScriptWithTag = false;
return null;
}
}
void saveComment(StringBuilder s, Writer w, HTMLParseContext pc)
throws IOException {
if(pc.onlyDetectingCharset) return;
if((s.length() > 3) && (s.charAt(0) == '!') && (s.charAt(1) == '-') && (s.charAt(2) == '-')) {
s.delete(0, 3);
if(s.charAt(s.length()-1) == '-')
s.setLength(s.length()-1);
if(s.charAt(s.length()-1) == '-')
s.setLength(s.length()-1);
}
if(logDEBUG) Logger.debug(this, "Saving comment: "+s.toString());
if (pc.expectingBadComment)
return; // ignore it
if (pc.inStyle || pc.inScript) {
pc.currentStyleScriptChunk += s;
return; // </style> handler should write
}
if (pc.killTag) {
pc.killTag = false;
return;
}
StringBuilder sb = new StringBuilder();
for(int i=0;i<s.length();i++) {
char c = s.charAt(i);
if(c == '<') {
sb.append("<");
} else if(c == '>') {
sb.append(">");
} else {
sb.append(c);
}
}
s = sb;
w.write("<!-- ");
w.write(s.toString());
w.write(" -->");
}
static void throwFilterException(String msg) throws DataFilterException {
// FIXME
String longer = l10n("failedToParseLabel");
throw new DataFilterException(longer, longer, msg);
}
public static class ParsedTag {
public final String element;
public final String[] unparsedAttrs;
final boolean startSlash;
final boolean endSlash;
/*
* public ParsedTag(ParsedTag t) { this.element = t.element;
* this.unparsedAttrs = (String[]) t.unparsedAttrs.clone();
* this.startSlash = t.startSlash; this.endSlash = t.endSlash; }
*/
public ParsedTag(String elementName,Map<String,String> attributes){
this.element=elementName;
startSlash=false;
endSlash=true;
String[] attrs=new String[attributes.size()];
int pos=0;
for(Entry<String,String> entry:attributes.entrySet()){
attrs[pos++]=entry.getKey()+"=\""+entry.getValue()+"\"";
}
this.unparsedAttrs = attrs;
}
public ParsedTag(ParsedTag t, String[] outAttrs) {
this.element = t.element;
this.unparsedAttrs = outAttrs;
this.startSlash = t.startSlash;
this.endSlash = t.endSlash;
}
public ParsedTag(ParsedTag t, Map<String,String> attributes){
String[] attrs=new String[attributes.size()];
int pos=0;
for(Entry<String,String> entry:attributes.entrySet()){
attrs[pos++]=entry.getKey()+"=\""+entry.getValue()+"\"";
}
this.element = t.element;
this.unparsedAttrs = attrs;
this.startSlash = t.startSlash;
this.endSlash = t.endSlash;
}
public ParsedTag(List<String> v) {
int len = v.size();
if (len == 0) {
element = null;
unparsedAttrs = new String[0];
startSlash = endSlash = false;
return;
}
String s = v.get(len - 1);
if (((len - 1 != 0) || (s.length() > 1)) && s.endsWith("/")) {
s = s.substring(0, s.length() - 1);
v.set(len - 1, s);
if (s.length() == 0)
len--;
endSlash = true;
// Don't need to set it back because everything is an I-value
} else endSlash = false;
s = v.get(0);
if ((s.length() > 1) && s.startsWith("/")) {
s = s.substring(1);
v.set(0, s);
startSlash = true;
} else startSlash = false;
element = v.get(0);
if (len > 1) {
unparsedAttrs = new String[len - 1];
for (int x = 1; x < len; x++)
unparsedAttrs[x - 1] = v.get(x);
} else
unparsedAttrs = new String[0];
if(logDEBUG) Logger.debug(this, "Element = "+element);
}
public ParsedTag sanitize(HTMLParseContext pc) throws DataFilterException {
TagVerifier tv =
allowedTagsVerifiers.get(element.toLowerCase());
if(logDEBUG) Logger.debug(this, "Got verifier: "+tv+" for "+element);
if (tv == null) {
if (deleteWierdStuff) {
return null;
} else {
String err = "<!-- "+HTMLEncoder.encode(l10n("unknownTag", "tag", element))+ " -->";
if (!deleteErrors)
throwFilterException(l10n("unknownTagLabel") + ' ' + err);
return null;
}
}
return tv.sanitize(this, pc);
}
@Override
public String toString() {
if (element == null)
return "";
StringBuilder sb = new StringBuilder("<");
if (startSlash)
sb.append('/');
sb.append(element);
if (unparsedAttrs != null) {
int n = unparsedAttrs.length;
for (int i = 0; i < n; i++) {
sb.append(' ').append(unparsedAttrs[i]);
}
}
if (endSlash)
sb.append(" /");
sb.append('>');
return sb.toString();
}
public Map<String,String> getAttributesAsMap(){
Map<String,String> map=new HashMap<String, String>();
for(int i=0;i<unparsedAttrs.length;i++){
String attr=unparsedAttrs[i];
String name=attr.substring(0,attr.indexOf("="));
String value=attr.substring(attr.indexOf("=")+2,attr.length()-1);
map.put(name, value);
}
return map;
}
public void htmlwrite(Writer w,HTMLParseContext pc) throws IOException {
String s = toString();
if(pc.getisXHTML())
{
if(ElementInfo.isVoidElement(element) && s.charAt(s.length()-2)!='/')
{
s=s.substring(0,s.length()-1)+" />";
}
}
if (s != null) {
w.write(s);
}
}
public void write(Writer w,HTMLParseContext pc) throws IOException {
if(!startSlash)
{
if(ElementInfo.tryAutoClose(element) && element.equals(pc.peekTopElement()))
pc.closeXHTMLTag(element, w);
if(pc.getisXHTML() && !ElementInfo.isVoidElement(element))
pc.pushElementInStack(element);
htmlwrite(w,pc);
}
else
{
if(pc.getisXHTML())
{
pc.closeXHTMLTag(element, w);
}
else
{
htmlwrite(w,pc);
}
}
}
}
static final Map<String, TagVerifier> allowedTagsVerifiers = new LinkedHashMap<String, TagVerifier>();
static final String[] emptyStringArray = new String[0];
static {
allowedTagsVerifiers.put("?xml", new XmlTagVerifier());
allowedTagsVerifiers.put(
"!doctype",
new DocTypeTagVerifier("!doctype"));
allowedTagsVerifiers.put("html", new HtmlTagVerifier());
allowedTagsVerifiers.put(
"head",
new TagVerifier(
"head",
new String[] { "id" },
// Don't support profiles.
// We don't know what format they might be in, whether they will be parsed even though they have bogus MIME types (which seems likely), etc.
new String[] { /*"profile"*/ },
null));
allowedTagsVerifiers.put(
"title",
new TagVerifier("title", new String[] { "id" }));
allowedTagsVerifiers.put("meta", new MetaTagVerifier());
allowedTagsVerifiers.put(
"body",
new CoreTagVerifier(
"body",
new String[] { "bgcolor", "text", "link", "vlink", "alink" },
null,
new String[] { "background" },
new String[] { "onload", "onunload" }));
String[] group =
{ "div", "h1", "h2", "h3", "h4", "h5", "h6", "p", "caption" };
for (int x = 0; x < group.length; x++)
allowedTagsVerifiers.put(
group[x],
new CoreTagVerifier(
group[x],
new String[] { "align" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
String[] group2 =
{
"span",
"address",
"em",
"strong",
"dfn",
"code",
"samp",
"kbd",
"var",
"cite",
"abbr",
"acronym",
"sub",
"sup",
"dt",
"dd",
"tt",
"i",
"b",
"big",
"small",
"strike",
"s",
"u",
"noframes",
"fieldset",
// Delete <noscript> / </noscript>. So we can at least see the non-scripting code.
// "noscript",
"xmp",
"listing",
"plaintext",
"center",
"bdo",
"aside",
"header",
"nav",
"footer",
"article",
"section",
"hgroup"};
for (int x = 0; x < group2.length; x++)
allowedTagsVerifiers.put(
group2[x],
new CoreTagVerifier(
group2[x],
emptyStringArray,
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"blockquote",
new CoreTagVerifier(
"blockquote",
emptyStringArray,
new String[] { "cite" },
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"q",
new CoreTagVerifier(
"q",
emptyStringArray,
new String[] { "cite" },
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"br",
new BaseCoreTagVerifier(
"br",
new String[] { "clear" },
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"pre",
new CoreTagVerifier(
"pre",
new String[] { "width", "xml:space" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"ins",
new CoreTagVerifier(
"ins",
new String[] { "datetime" },
new String[] { "cite" },
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"del",
new CoreTagVerifier(
"del",
new String[] { "datetime" },
new String[] { "cite" },
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"ul",
new CoreTagVerifier(
"ul",
new String[] { "type", "compact" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"ol",
new CoreTagVerifier(
"ol",
new String[] { "type", "compact", "start" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"li",
new CoreTagVerifier(
"li",
new String[] { "type", "value" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"dl",
new CoreTagVerifier(
"dl",
new String[] { "compact" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"dir",
new CoreTagVerifier(
"dir",
new String[] { "compact" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"menu",
new CoreTagVerifier(
"menu",
new String[] { "compact" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"table",
new CoreTagVerifier(
"table",
new String[] {
"summary",
"width",
"border",
"frame",
"rules",
"cellspacing",
"cellpadding",
"align",
"bgcolor" },
emptyStringArray,
new String[] { "background" },
emptyStringArray));
allowedTagsVerifiers.put(
"thead",
new CoreTagVerifier(
"thead",
new String[] { "align", "char", "charoff", "valign" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"tfoot",
new CoreTagVerifier(
"tfoot",
new String[] { "align", "char", "charoff", "valign" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"tbody",
new CoreTagVerifier(
"tbody",
new String[] { "align", "char", "charoff", "valign" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"colgroup",
new CoreTagVerifier(
"colgroup",
new String[] {
"span",
"width",
"align",
"char",
"charoff",
"valign" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"col",
new CoreTagVerifier(
"col",
new String[] {
"span",
"width",
"align",
"char",
"charoff",
"valign" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"tr",
new CoreTagVerifier(
"tr",
new String[] {
"align",
"char",
"charoff",
"valign",
"bgcolor" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"th",
new CoreTagVerifier(
"th",
new String[] {
"abbr",
"axis",
"headers",
"scope",
"rowspan",
"colspan",
"align",
"char",
"charoff",
"valign",
"nowrap",
"bgcolor",
"width",
"height" },
emptyStringArray,
new String[] { "background" },
emptyStringArray));
allowedTagsVerifiers.put(
"td",
new CoreTagVerifier(
"td",
new String[] {
"abbr",
"axis",
"headers",
"scope",
"rowspan",
"colspan",
"align",
"char",
"charoff",
"valign",
"nowrap",
"bgcolor",
"width",
"height" },
emptyStringArray,
new String[] { "background" },
emptyStringArray));
allowedTagsVerifiers.put(
"a",
new LinkTagVerifier(
"a",
new String[] {
"accesskey",
"tabindex",
"name",
"shape",
"coords",
"target" },
emptyStringArray,
emptyStringArray,
new String[] { "onfocus", "onblur" }));
allowedTagsVerifiers.put(
"link",
new LinkTagVerifier(
"link",
new String[] { "media", "target" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"base",
new BaseHrefTagVerifier(
"base",
new String[] { "id", "target" },
new String[] { /* explicitly sanitized by class */ }));
allowedTagsVerifiers.put(
"img",
new CoreTagVerifier(
"img",
new String[] {
"alt",
"name",
"height",
"width",
"ismap",
"align",
"border",
"hspace",
"vspace" },
new String[] { "longdesc", "usemap" },
new String[] { "src" },
emptyStringArray));
// FIXME: object tag -
// http://www.w3.org/TR/html4/struct/objects.html#h-13.3
// FIXME: param tag -
// http://www.w3.org/TR/html4/struct/objects.html#h-13.3.2
// applet tag PROHIBITED - we do not support applets (FIXME?)
allowedTagsVerifiers.put(
"map",
new CoreTagVerifier(
"map",
new String[] { "name" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"area",
new CoreTagVerifier(
"area",
new String[] {
"accesskey",
"tabindex",
"shape",
"coords",
"nohref",
"alt",
"target" },
new String[] { "href" },
emptyStringArray,
new String[] { "onfocus", "onblur" }));
allowedTagsVerifiers.put("style", new StyleTagVerifier());
allowedTagsVerifiers.put(
"font",
new BaseCoreTagVerifier(
"font",
new String[] { "size", "color", "face" },
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"basefont",
new BaseCoreTagVerifier(
"basefont",
new String[] { "size", "color", "face" },
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"hr",
new CoreTagVerifier(
"hr",
new String[] { "align", "noshade", "size", "width" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"frameset",
new CoreTagVerifier(
"frameset",
new String[] { "rows", "cols" },
emptyStringArray,
emptyStringArray,
new String[] { "onload", "onunload" },
false));
allowedTagsVerifiers.put(
"frame",
new BaseCoreTagVerifier(
"frame",
new String[] {
"name",
"frameborder",
"marginwidth",
"marginheight",
"noresize",
"scrolling" },
new String[] { "longdesc" },
new String[] { "src" }));
allowedTagsVerifiers.put(
"iframe",
new BaseCoreTagVerifier(
"iframe",
new String[] {
"name",
"frameborder",
"marginwidth",
"marginheight",
"scrolling",
"align",
"height",
"width" },
new String[] { "longdesc"},
new String[] { "src" }));
allowedTagsVerifiers.put(
"form",
new FormTagVerifier(
"form",
new String[] {
"name" }, // FIXME add a whitelist filter for accept
// All other attributes are handled by FormTagVerifier.
new String[] { },
new String[] { "onsubmit", "onreset" }));
allowedTagsVerifiers.put(
"input",
new InputTagVerifier(
"input",
new String[] {
"accesskey",
"tabindex",
"type",
"name",
"value",
"checked",
"disabled",
"readonly",
"size",
"maxlength",
"alt",
"ismap",
"accept",
"align" },
new String[] { "usemap" },
new String[] { "src" },
new String[] { "onfocus", "onblur", "onselect", "onchange" }));
allowedTagsVerifiers.put(
"button",
new CoreTagVerifier(
"button",
new String[] {
"accesskey",
"tabindex",
"name",
"value",
"type",
"disabled" },
emptyStringArray,
emptyStringArray,
new String[] { "onfocus", "onblur" }));
allowedTagsVerifiers.put(
"select",
new CoreTagVerifier(
"select",
new String[] {
"name",
"size",
"multiple",
"disabled",
"tabindex" },
emptyStringArray,
emptyStringArray,
new String[] { "onfocus", "onblur", "onchange" }));
allowedTagsVerifiers.put(
"optgroup",
new CoreTagVerifier(
"optgroup",
new String[] { "disabled", "label" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"option",
new CoreTagVerifier(
"option",
new String[] { "selected", "disabled", "label", "value" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"textarea",
new CoreTagVerifier(
"textarea",
new String[] {
"accesskey",
"tabindex",
"name",
"rows",
"cols",
"disabled",
"readonly" },
emptyStringArray,
emptyStringArray,
new String[] { "onfocus", "onblur", "onselect", "onchange" }));
allowedTagsVerifiers.put(
"isindex",
new BaseCoreTagVerifier(
"isindex",
new String[] { "prompt" },
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put(
"label",
new CoreTagVerifier(
"label",
new String[] { "for", "accesskey" },
emptyStringArray,
emptyStringArray,
new String[] { "onfocus", "onblur" }));
allowedTagsVerifiers.put(
"legend",
new CoreTagVerifier(
"legend",
new String[] { "accesskey", "align" },
emptyStringArray,
emptyStringArray,
emptyStringArray));
allowedTagsVerifiers.put("script", new ScriptTagVerifier());
}
static class TagVerifier {
final String tag;
//Attributes which need no sanitation
final HashSet<String> allowedAttrs;
//Attributes which will be sanitized by child classes
final HashSet<String> parsedAttrs;
final HashSet<String> uriAttrs;
final HashSet<String> inlineURIAttrs;
TagVerifier(String tag, String[] allowedAttrs) {
this(tag, allowedAttrs, null, null);
}
TagVerifier(String tag, String[] allowedAttrs, String[] uriAttrs, String[] inlineURIAttrs) {
this.tag = tag;
this.allowedAttrs = new HashSet<String>();
this.parsedAttrs = new HashSet<String>();
if (allowedAttrs != null) {
for (int x = 0; x < allowedAttrs.length; x++)
this.allowedAttrs.add(allowedAttrs[x]);
}
this.uriAttrs = new HashSet<String>();
if (uriAttrs != null) {
for (int x = 0; x < uriAttrs.length; x++)
this.uriAttrs.add(uriAttrs[x]);
}
this.inlineURIAttrs = new HashSet<String>();
if (inlineURIAttrs != null) {
for (int x = 0; x < inlineURIAttrs.length; x++)
this.inlineURIAttrs.add(inlineURIAttrs[x]);
}
}
ParsedTag sanitize(ParsedTag t, HTMLParseContext pc) throws DataFilterException {
Map<String, Object> h = new LinkedHashMap<String, Object>();
boolean equals = false;
String prevX = "";
if (t.unparsedAttrs != null)
for (int i = 0; i < t.unparsedAttrs.length; i++) {
String s = t.unparsedAttrs[i];
if (equals) {
equals = false;
s = stripQuotes(s);
h.remove(prevX);
h.put(prevX, s);
prevX = "";
} else {
int idx = s.indexOf('=');
if (idx == s.length() - 1) {
equals = true;
if (idx == 0) {
// prevX already set
} else {
prevX = s.substring(0, s.length() - 1);
prevX = prevX.toLowerCase();
}
} else if (idx > -1) {
String x = s.substring(0, idx);
if (x.length() == 0)
x = prevX;
x = x.toLowerCase();
String y;
if (idx == s.length() - 1)
y = "";
else
y = s.substring(idx + 1, s.length());
y = stripQuotes(y);
h.remove(x);
h.put(x, y);
prevX = x;
} else {
h.remove(s);
h.put(s, new Object());
prevX = s;
}
}
}
h = sanitizeHash(h, t, pc);
if (h == null) return null;
//Remove any blank entries
for(Iterator<Entry<String, Object>> it = h.entrySet().iterator(); it.hasNext();){
Map.Entry<String, Object> entry = it.next();
if(entry.getValue() == null || entry.getValue().equals("") && pc.isXHTML){
it.remove();
}
}
//If the tag has no attributes, and this is not allowable, remove it
if(h.isEmpty() && expungeTagIfNoAttributes()) return null;
if (t.startSlash)
return new ParsedTag(t, (String[])null);
String[] outAttrs = new String[h.size()];
int i = 0;
for (Map.Entry<String, Object> entry : h.entrySet()) {
String x = entry.getKey();
Object o = entry.getValue();
String y;
if (o instanceof String)
y = (String) o;
else
y = null;
StringBuilder out = new StringBuilder(x);
if (y != null)
out.append( "=\"" ).append( y ).append( '"' );
outAttrs[i++] = out.toString();
}
return new ParsedTag(t, outAttrs);
}
Map<String, Object> sanitizeHash(Map<String, Object> h,
ParsedTag p,
HTMLParseContext pc) throws DataFilterException {
Map<String, Object> hn = new LinkedHashMap<String, Object>();
for (Map.Entry<String, Object> entry : h.entrySet()) {
if(logDEBUG) Logger.debug(this, "HTML Filter is sanitizing: "+entry.getKey()+" = "+entry.getValue());
String x = entry.getKey();
Object o = entry.getValue();
boolean inline = inlineURIAttrs.contains(x);
//URI attributes require additional processing
if (uriAttrs.contains(x) || inline) {
if(!inline) {
if(logMINOR) Logger.minor(this, "Non-inline URI attribute: "+x);
} else {
if(logMINOR) Logger.minor(this, "Inline URI attribute: "+x);
}
// URI
if (o instanceof String) {
// Java's URL handling doesn't seem suitable
String uri = (String) o;
uri = HTMLDecoder.decode(uri);
uri = htmlSanitizeURI(uri, null, null, null, pc.cb, pc, inline);
if (uri == null) {
continue;
}
uri = HTMLEncoder.encode(uri);
o = uri;
}
// FIXME: rewrite absolute URLs, handle ?date= etc
if(logDEBUG) Logger.debug(this, "HTML Filter is putting "+(inline?"inline":"")+" uri attribute: "+x+" = "+o);
hn.put(x, o);
continue;
}
/*We create a placeholder for each parsed attribute in the
* sanitized output. This ensures the order of the attributes.
* Subclasses will take care of parsing and replacing these values.
* If they don't, we'll remove the placeholder later.*/
if(parsedAttrs.contains(x)) {
hn.put(x, null);
continue;
}
/*If the attribute is to be passed through without sanitation*/
if(allowedAttrs.contains(x)) {
hn.put(x, o);
continue;
}
// lang, xml:lang and dir can go on anything
// lang or xml:lang = language [ "-" country [ "-" variant ] ]
// The variant can be just about anything; no way to test (avian)
if (x.equals("xml:lang") ||x.equals("lang") || (x.equals("dir") && (((String)o).equalsIgnoreCase("ltr") || ((String)o).equalsIgnoreCase("rtl")))) {
if(logDEBUG) Logger.debug(this, "HTML Filter is putting attribute: "+x+" = "+o);
hn.put(x, o);
}
}
return hn;
}
/*If this function returns true, this tag will be removed from
* the sanitized output if it has no attributes*/
protected boolean expungeTagIfNoAttributes() {
return false;
}
}
static String stripQuotes(String s) {
final String quotes = "\"'";
if (s.length() >= 2) {
int n = quotes.length();
for (int x = 0; x < n; x++) {
char cc = quotes.charAt(x);
if ((s.charAt(0) == cc) && (s.charAt(s.length() - 1) == cc)) {
if (s.length() > 2)
s = s.substring(1, s.length() - 1);
else
s = "";
break;
}
}
}
return s;
}
// static String[] titleString = new String[] {"title"};
static abstract class ScriptStyleTagVerifier extends TagVerifier {
ScriptStyleTagVerifier(
String tag,
String[] allowedAttrs,
String[] uriAttrs) {
super(tag, allowedAttrs, uriAttrs, null);
}
abstract void setStyle(boolean b, HTMLParseContext pc);
abstract boolean getStyle(HTMLParseContext pc);
abstract void processStyle(HTMLParseContext pc);
@Override
Map<String, Object> sanitizeHash(Map<String, Object> h,
ParsedTag p,
HTMLParseContext pc) throws DataFilterException {
Map<String, Object> hn = super.sanitizeHash(h, p, pc);
if (p.startSlash) {
return finish(h, hn, pc);
} else {
return start(h, hn, pc);
}
}
Map<String, Object> finish(Map<String, Object> h, Map<String, Object> hn,
HTMLParseContext pc) throws DataFilterException {
if(logDEBUG) Logger.debug(this, "Finishing script/style");
// Finishing
setStyle(false, pc);
pc.styleScriptRecurseCount--;
if (pc.styleScriptRecurseCount < 0) {
if (deleteErrors)
pc.writeAfterTag.append(
"<!-- " + l10n("tooManyNestedStyleOrScriptTags") + " -->");
else
throwFilterException(l10n("tooManyNestedStyleOrScriptTagsLong"));
return null;
}
if(!pc.killStyle) {
processStyle(pc);
pc.writeStyleScriptWithTag = true;
} else {
pc.killStyle = false;
pc.currentStyleScriptChunk = "";
}
pc.expectingBadComment = false;
// Pass it on, no params for </style>
return hn;
}
Map<String, Object> start(Map<String, Object> h, Map<String, Object> hn, HTMLParseContext pc)
throws DataFilterException {
if(logDEBUG) Logger.debug(this, "Starting script/style");
pc.styleScriptRecurseCount++;
if (pc.styleScriptRecurseCount > 1) {
if (deleteErrors)
pc.writeAfterTag.append("<!-- " + l10n("tooManyNestedStyleOrScriptTags") + " -->");
else
throwFilterException(l10n("tooManyNestedStyleOrScriptTagsLong"));
return null;
}
setStyle(true, pc);
String type = getHashString(h, "type");
if (type != null) {
if (!type.equalsIgnoreCase("text/css") /* FIXME */
) {
pc.killStyle = true;
pc.expectingBadComment = true;
return null; // kill the tag
}
hn.put("type", "text/css");
}
return hn;
}
}
static class StyleTagVerifier extends ScriptStyleTagVerifier {
StyleTagVerifier() {
super(
"style",
new String[] { "id", "media", "title", "xml:space" },
emptyStringArray);
}
@Override
void setStyle(boolean b, HTMLParseContext pc) {
pc.inStyle = b;
}
@Override
boolean getStyle(HTMLParseContext pc) {
return pc.inStyle;
}
@Override
void processStyle(HTMLParseContext pc) {
try {
pc.currentStyleScriptChunk =
sanitizeStyle(pc.currentStyleScriptChunk, pc.cb, pc, false);
} catch (DataFilterException e) {
Logger.error(this, "Error parsing style: "+e, e);
pc.currentStyleScriptChunk = "";
}
}
}
static class ScriptTagVerifier extends ScriptStyleTagVerifier {
ScriptTagVerifier() {
super(
"script",
new String[] {
"id",
"charset",
"type",
"language",
"defer",
"xml:space" },
new String[] { "src" });
/*
* FIXME: src not supported type ignored (we will need to check
* this when if/when we support scripts charset ignored
*/
}
@Override
Map<String, Object> sanitizeHash(Map<String, Object> hn, ParsedTag p, HTMLParseContext pc)
throws DataFilterException {
// Call parent so we swallow the scripting
super.sanitizeHash(hn, p, pc);
return null; // Lose the tags
}
@Override
void setStyle(boolean b, HTMLParseContext pc) {
pc.inScript = b;
}
@Override
boolean getStyle(HTMLParseContext pc) {
return pc.inScript;
}
@Override
void processStyle(HTMLParseContext pc) {
pc.currentStyleScriptChunk =
sanitizeScripting(pc.currentStyleScriptChunk);
}
}
static class BaseCoreTagVerifier extends TagVerifier {
static final String[] locallyVerifiedAttrs = new String[] {
"id",
"class",
"style"
};
BaseCoreTagVerifier(
String tag,
String[] allowedAttrs,
String[] uriAttrs,
String[] inlineURIAttrs) {
super(tag, allowedAttrs, uriAttrs, inlineURIAttrs);
for(String attr : locallyVerifiedAttrs) {
this.parsedAttrs.add(attr);
}
}
@Override
Map<String, Object> sanitizeHash(Map<String, Object> h,
ParsedTag p,
HTMLParseContext pc) throws DataFilterException {
Map<String, Object> hn = super.sanitizeHash(h, p, pc);
// %i18n dealt with by TagVerifier
// %coreattrs
String id = getHashString(h, "id");
if (id != null) {
hn.put("id", id);
// hopefully nobody will be stupid enough to encode URLs into
// the unique ID... :)
}
String classNames = getHashString(h, "class");
if (classNames != null) {
hn.put("class", classNames);
// ditto
}
String style = getHashString(h, "style");
if (style != null) {
style = sanitizeStyle(style, pc.cb, pc, true);
if (style != null)
style = escapeQuotes(style);
if (style != null)
hn.put("style", style);
}
String title = getHashString(h, "title");
if (title != null) {
// PARANOIA: title is PLAIN TEXT, right? In all user agents? :)
hn.put("title", title);
}
return hn;
}
}
static class CoreTagVerifier extends BaseCoreTagVerifier {
final HashSet<String> eventAttrs;
static final String[] stdEvents =
new String[] {
"onclick",
"ondblclick",
"onmousedown",
"onmouseup",
"onmouseover",
"onmousemove",
"onmouseout",
"onkeypress",
"onkeydown",
"onkeyup",
"onload",
"onfocus",
"onblur",
"oncontextmenu",
"onresize",
"onscroll",
"onunload",
"onmouseenter",
"onchange",
"onreset",
"onselect",
"onsubmit",
"onerror",
};
CoreTagVerifier(
String tag,
String[] allowedAttrs,
String[] uriAttrs,
String[] inlineURIAttrs,
String[] eventAttrs) {
this(tag, allowedAttrs, uriAttrs, inlineURIAttrs, eventAttrs, true);
}
CoreTagVerifier(
String tag,
String[] allowedAttrs,
String[] uriAttrs,
String[] inlineURIAttrs,
String[] eventAttrs,
boolean addStdEvents) {
super(tag, allowedAttrs, uriAttrs, inlineURIAttrs);
this.eventAttrs = new HashSet<String>();
if (eventAttrs != null) {
for (int x = 0; x < eventAttrs.length; x++) {
this.eventAttrs.add(eventAttrs[x]);
this.parsedAttrs.add(eventAttrs[x]);
}
}
if (addStdEvents) {
for (int x = 0; x < stdEvents.length; x++) {
this.eventAttrs.add(stdEvents[x]);
this.parsedAttrs.add(stdEvents[x]);
}
}
}
@Override
Map<String, Object> sanitizeHash(Map<String, Object> h,
ParsedTag p,
HTMLParseContext pc) throws DataFilterException {
Map<String, Object> hn = super.sanitizeHash(h, p, pc);
// events (default and added)
for (Iterator<String> e = eventAttrs.iterator(); e.hasNext();) {
String name = e.next();
String arg = getHashString(h, name);
if (arg != null) {
arg = sanitizeScripting(arg);
if (arg != null)
hn.put(name, arg);
}
}
return hn;
}
}
static class LinkTagVerifier extends CoreTagVerifier {
static final String[] locallyVerifiedAttrs = new String[] {
"type",
"charset",
"rel",
"rev",
"media",
"hreflang",
"href"
};
LinkTagVerifier(
String tag,
String[] allowedAttrs,
String[] uriAttrs,
String[] inlineURIAttrs,
String[] eventAttrs) {
super(tag, allowedAttrs, uriAttrs, inlineURIAttrs, eventAttrs);
for(String attr : locallyVerifiedAttrs) {
this.parsedAttrs.add(attr);
}
}
@Override
Map<String, Object> sanitizeHash(Map<String, Object> h,
ParsedTag p,
HTMLParseContext pc) throws DataFilterException {
Map<String, Object> hn = super.sanitizeHash(h, p, pc);
String hreflang = getHashString(h, "hreflang");
String charset = null;
String maybecharset = null;
String type = getHashString(h, "type");
if (type != null) {
String[] typesplit = splitType(type);
type = typesplit[0];
if ((typesplit[1] != null) && (typesplit[1].length() > 0))
charset = typesplit[1];
if(logDEBUG)
Logger.debug(
this,
"Processing link tag, type="
+ type
+ ", charset="
+ charset);
}
String c = getHashString(h, "charset");
if (c != null)
charset = c;
if(charset != null) {
try {
charset = URLDecoder.decode(charset, false);
} catch (URLEncodedFormatException e) {
charset = null;
}
}
if(charset != null && charset.indexOf('&') != -1)
charset = null;
if(charset != null && !Charset.isSupported(charset))
charset = null;
// Is it a style sheet?
// Also, sanitise rel type
// If neither rel nor rev, return null
String rel = getHashString(h, "rel");
String parsedRel = "", parsedRev = "";
boolean isStylesheet = false;
if(rel != null) {
rel = rel.toLowerCase();
StringTokenizer tok = new StringTokenizer(rel, " ");
int i=0;
String prevToken = null;
StringBuffer sb = new StringBuffer(rel.length());
while (tok.hasMoreTokens()) {
String token = tok.nextToken();
if(token.equalsIgnoreCase("stylesheet")) {
if(token.equalsIgnoreCase("stylesheet")) {
isStylesheet = true;
if(!((i == 0 || i == 1 && prevToken != null && prevToken.equalsIgnoreCase("alternate"))))
return null;
if(tok.hasMoreTokens())
return null; // Disallow extra tokens after "stylesheet"
}
} else if(!isStandardLinkType(token)) continue;
i++;
if(sb.length() == 0)
sb.append(token);
else {
sb.append(' ');
sb.append(token);
}
prevToken = token;
}
parsedRel = sb.toString();
}
String rev = getHashString(h, "rev");
if(rev != null) {
StringBuffer sb = new StringBuffer(rev.length());
rev = rev.toLowerCase();
StringTokenizer tok = new StringTokenizer(rev, " ");
int i=0;
sb = new StringBuffer(rev.length());
while (tok.hasMoreTokens()) {
String token = tok.nextToken();
if(!isStandardLinkType(token)) continue;
i++;
if(sb.length() == 0)
sb.append(token);
else {
sb.append(' ');
sb.append(token);
}
}
parsedRev = sb.toString();
}
// Allow no rel or rev, even on <link>, as per HTML spec.
if(parsedRel.length() != 0)
hn.put("rel", parsedRel);
if(parsedRev.length() != 0)
hn.put("rev", parsedRev);
if(rel != null) {
if(rel.equals("stylesheet") || rel.equals("alternate stylesheet"))
isStylesheet = true;
} else {
// Not a stylesheet.
if(type != null && type.startsWith("text/css"))
return null; // Not a stylesheet, so can't take a stylesheet type.
}
if(isStylesheet) {
if(charset == null) {
// Browser will use the referring document's charset if there
// is no BOM and we don't specify one in HTTP.
// So we need to pass this information to the filter.
// We cannot force the mime type with the charset, because if
// we do that, we might be wrong - if there is a BOM or @charset
// we want to use that. E.g. chinese pages might have the
// page in GB18030 and the borrowed CSS in ISO-8859-1 or UTF-8.
maybecharset = pc.charset;
}
String media = getHashString(h, "media");
if(media != null)
media = CSSReadFilter.filterMediaList(media);
if(media != null)
hn.put("media", media);
if(type != null && !type.startsWith("text/css"))
return null; // Different style language e.g. XSL, not supported.
type = "text/css";
}
String href = getHashString(h, "href");
if (href != null) {
href = HTMLDecoder.decode(href);
href = htmlSanitizeURI(href, type, charset, maybecharset, pc.cb, pc, false);
if (href != null) {
href = HTMLEncoder.encode(href);
hn.put("href", href);
if (type != null)
hn.put("type", type);
if (charset != null)
hn.put("charset", charset);
if ((charset != null) && (hreflang != null))
hn.put("hreflang", hreflang);
}
}
// FIXME: allow these if the charset and encoding are encoded into
// the URL
return hn;
}
// Does not include stylesheet
private static final HashSet<String> standardRelTypes = new HashSet<String>();
static {
for(String s : new String[] {
"alternate",
"start",
"next",
"prev",
"contents",
"index",
"glossary",
"copyright",
"chapter",
"section",
"subsection",
"appendix",
"help",
"bookmark"
}) standardRelTypes.add(s);
}
private boolean isStandardLinkType(String token) {
return standardRelTypes.contains(token.toLowerCase());
}
}
// We do not allow forms to act anywhere else than on /
static class FormTagVerifier extends CoreTagVerifier{
static final String[] locallyVerifiedAttrs = new String[] {
"method",
"action",
"enctype",
"accept-charset"
};
FormTagVerifier(
String tag,
String[] allowedAttrs,
String[] uriAttrs,
String[] eventAttrs) {
super(tag, allowedAttrs, uriAttrs, null, eventAttrs);
for(String attr : locallyVerifiedAttrs) {
this.parsedAttrs.add(attr);
}
}
@Override
Map<String, Object> sanitizeHash(Map<String, Object> h,
ParsedTag p,
HTMLParseContext pc) throws DataFilterException {
Map<String, Object> hn = super.sanitizeHash(h, p, pc);
if(p.startSlash) {
// Allow, but only with standard elements
return hn;
}
String method = (String) h.get("method");
String action = (String) h.get("action");
String finalAction;
try {
finalAction = pc.cb.processForm(method, action);
} catch (CommentException e) {
pc.writeAfterTag.append("<!-- ").append(HTMLEncoder.encode(e.toString())).append(" -->");
return null;
}
if(finalAction == null) return null;
hn.put("method", method);
hn.put("action", finalAction);
// Force enctype and accept-charset to acceptable values.
hn.put("enctype", "multipart/form-data");
hn.put("accept-charset", "UTF-8");
return hn;
}
}
static class InputTagVerifier extends CoreTagVerifier{
final HashSet<String> allowedTypes;
String[] types = new String[]{
"text",
"password",
"checkbox",
"radio",
"submit",
"reset,",
// no ! file
"hidden",
"image",
"button"
};
InputTagVerifier(
String tag,
String[] allowedAttrs,
String[] uriAttrs,
String[] inlineURIAttrs,
String[] eventAttrs) {
super(tag, allowedAttrs, uriAttrs, inlineURIAttrs, eventAttrs);
this.allowedTypes = new HashSet<String>();
if (types != null) {
for (int x = 0; x < types.length; x++) {
this.allowedTypes.add(types[x]);
}
}
}
@Override
Map<String, Object> sanitizeHash(Map<String, Object> h,
ParsedTag p,
HTMLParseContext pc) throws DataFilterException {
Map<String, Object> hn = super.sanitizeHash(h, p, pc);
// We drop the whole <input> if type isn't allowed
if(!allowedTypes.contains(hn.get("type"))){
return null;
}
return hn;
}
}
static class MetaTagVerifier extends TagVerifier {
static final String[] allowedContentTypes = ContentFilter.HTML_MIME_TYPES;
static final String[] locallyVerifiedAttrs = {
"http-equiv",
"name",
"content"
};
MetaTagVerifier() {
super("meta", new String[] { "id" });
for(String attr : locallyVerifiedAttrs) {
this.parsedAttrs.add(attr);
}
}
@Override
Map<String, Object> sanitizeHash(Map<String, Object> h,
ParsedTag p,
HTMLParseContext pc) throws DataFilterException {
Map<String, Object> hn = super.sanitizeHash(h, p, pc);
/*
* Several possibilities: a) meta http-equiv=X content=Y b) meta
* name=X content=Y
*/
String http_equiv = getHashString(h, "http-equiv");
String name = getHashString(h, "name");
String content = getHashString(h, "content");
String scheme = getHashString(h, "scheme");
if(logMINOR) Logger.minor(this, "meta: name="+name+", content="+content+", http-equiv="+http_equiv+", scheme="+scheme);
if (content != null) {
if ((name != null) && (http_equiv == null)) {
if (name.equalsIgnoreCase("Author")) {
hn.put("name", name);
hn.put("content", content);
} else if (name.equalsIgnoreCase("Keywords")) {
hn.put("name", name);
hn.put("content", content);
} else if (name.equalsIgnoreCase("Description")) {
hn.put("name", name);
hn.put("content", content);
}
} else if ((http_equiv != null) && (name == null)) {
if (http_equiv.equalsIgnoreCase("Expires")) {
try {
Date d = ToadletContextImpl.parseHTTPDate(content);
hn.put("http-equiv", http_equiv);
hn.put("content", content);
} catch (ParseException e) {
// Delete it.
return null;
}
} else if (
http_equiv.equalsIgnoreCase("Content-Script-Type")) {
// We don't support script at this time.
} else if (
http_equiv.equalsIgnoreCase("Content-Style-Type")) {
// FIXME: charsets
if (content.equalsIgnoreCase("text/css")) {
// FIXME: selectable style languages - only matters
// when we have implemented more than one
// FIXME: if we ever do allow it... the spec
// http://www.w3.org/TR/html4/present/styles.html#h-14.2.1
// says only the last definition counts...
// but it only counts if it's in the HEAD section,
// so we DONT need to parse the whole doc
hn.put("http-equiv", http_equiv);
hn.put("content", content);
}
// FIXME: add some more headers - Dublin Core?
} else if (http_equiv.equalsIgnoreCase("Content-Type")) {
if(logMINOR) Logger.minor(this, "Found http-equiv content-type="+content);
String[] typesplit = splitType(content);
if(logDEBUG) {
for(int i=0;i<typesplit.length;i++)
Logger.debug(this, "["+i+"] = "+typesplit[i]);
}
boolean detected = false;
for (int i = 0; i < allowedContentTypes.length; i++) {
if (typesplit[0].equalsIgnoreCase(allowedContentTypes[i])) {
if((typesplit[1] == null) || (pc.charset != null && typesplit[1]
.equalsIgnoreCase(pc.charset))) {
hn.put("http-equiv", http_equiv);
hn.put("content", typesplit[0]
+ (typesplit[1] != null ? "; charset="
+ typesplit[1] : ""));
} else if(typesplit[1] != null && pc.charset != null && !typesplit[1].equalsIgnoreCase(pc.charset)) {
throwFilterException(l10n("wrongCharsetInMeta"));
} else if(typesplit[1] != null) {
if(pc.detectedCharset != null)
throwFilterException(l10n("multipleCharsetsInMeta"));
pc.detectedCharset = typesplit[1].trim();
}
detected = true;
break;
}
}
if(!detected)
throwFilterException(l10n("invalidMetaType"));
} else if (
http_equiv.equalsIgnoreCase("Content-Language")) {
if(content.matches("([a-zA-Z0-9]*(-[A-Za-z0-9]*)*(,\\s*)?)*")) {
hn.put("http-equiv", "Content-Language");
hn.put("content", content);
}
} else if (http_equiv.equalsIgnoreCase("refresh")) {
int idx = content.indexOf(';');
if(idx == -1 && metaRefreshSamePageMinInterval >= 0) {
try {
int seconds = Integer.parseInt(content);
if(seconds < 0) return null;
if(seconds < metaRefreshSamePageMinInterval)
seconds = metaRefreshSamePageMinInterval;
hn.put("http-equiv", "refresh");
hn.put("content", Integer.toString(seconds));
} catch (NumberFormatException e) {
// Delete.
pc.writeAfterTag.append("<!-- doesn't parse as number in meta refresh -->");
return null;
}
} else if(metaRefreshRedirectMinInterval >= 0) {
int seconds;
String before = content.substring(0, idx);
String after = content.substring(idx+1).trim();
try {
seconds = Integer.parseInt(before);
if(seconds < 0) return null;
if(seconds < metaRefreshRedirectMinInterval) seconds = metaRefreshRedirectMinInterval;
if(!after.toLowerCase().startsWith("url=")) {
pc.writeAfterTag.append("<!-- no url but doesn't parse as number in meta refresh -->");
return null;
}
after = after.substring("url=".length()).trim();
try {
String url = sanitizeURI(after, null, null, null, pc.cb, false);
hn.put("http-equiv", "refresh");
hn.put("content", ""+seconds+"; url="+HTMLEncoder.encode(url));
} catch (CommentException e) {
pc.writeAfterTag.append("<!-- "+e.getMessage()+"-->");
// Delete
return null;
}
} catch (NumberFormatException e) {
pc.writeAfterTag.append("<!-- doesn't parse as number in meta refresh possibly with url -->");
// Delete.
return null;
}
}
}
}
}
return hn;
}
@Override
protected boolean expungeTagIfNoAttributes() {
return true;
}
}
static class DocTypeTagVerifier extends TagVerifier {
DocTypeTagVerifier(String tag) {
super(tag, null);
}
static final Map<String, Object> DTDs = new HashMap<String, Object>();
static {
DTDs.put(
"-//W3C//DTD XHTML 1.0 Strict//EN",
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");
DTDs.put(
"-//W3C//DTD XHTML 1.0 Transitional//EN",
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");
DTDs.put(
"-//W3C//DTD XHTML 1.0 Frameset//EN",
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd");
DTDs.put(
"-//W3C//DTD XHTML 1.1//EN",
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd");
DTDs.put(
"-//W3C//DTD HTML 4.01//EN",
"http://www.w3.org/TR/html4/strict.dtd");
DTDs.put(
"-//W3C//DTD HTML 4.01 Transitional//EN",
"http://www.w3.org/TR/html4/loose.dtd");
DTDs.put(
"-//W3C//DTD HTML 4.01 Frameset//EN",
"http://www.w3.org/TR/html4/frameset.dtd");
DTDs.put("-//W3C//DTD HTML 3.2 Final//EN", new Object());
}
@Override
ParsedTag sanitize(ParsedTag t, HTMLParseContext pc) {
// HTML5 is just <!doctype html>
if(t.unparsedAttrs.length == 1) {
if (!t.unparsedAttrs[0].equalsIgnoreCase("html"))
return null;
return t;
}
if (!((t.unparsedAttrs.length == 3) || (t.unparsedAttrs.length == 4)))
return null;
if (!t.unparsedAttrs[0].equalsIgnoreCase("html"))
return null;
if(t.unparsedAttrs[1].equalsIgnoreCase("system") && t.unparsedAttrs.length == 3) {
// HTML5 allows <!DOCTYPE html SYSTEM "about:legacy-compat"> (either kind of quotes)
String s = stripQuotes(t.unparsedAttrs[2]);
if(s.equals("about:legacy-compat") && t.unparsedAttrs.length == 3) {
return t;
} else return null;
}
if (!t.unparsedAttrs[1].equalsIgnoreCase("public"))
return null;
String s = stripQuotes(t.unparsedAttrs[2]);
if (!DTDs.containsKey(s))
return null;
if (t.unparsedAttrs.length == 4) {
String ss = stripQuotes(t.unparsedAttrs[3]);
String spec = getHashString(DTDs, s);
if ((spec != null) && !spec.equals(ss))
return null;
}
return t;
}
}
static class XmlTagVerifier extends TagVerifier {
XmlTagVerifier() {
super("?xml", null);
}
@Override
ParsedTag sanitize(ParsedTag t, HTMLParseContext pc) throws DataFilterException {
if (t.unparsedAttrs.length != 2 && t.unparsedAttrs.length != 3) {
if (logMINOR) Logger.minor(this, "Deleting xml declaration, invalid length");
return null;
}
if (t.unparsedAttrs.length == 3 && !t.unparsedAttrs[2].equals("?")) {
if (logMINOR) Logger.minor(this, "Deleting xml declaration, invalid ending (length 2)");
return null;
}
if (t.unparsedAttrs.length == 2 && !t.unparsedAttrs[1].endsWith("?")) {
if (logMINOR) Logger.minor(this, "Deleting xml declaration, invalid ending (length 3)");
return null;
}
if (!(t.unparsedAttrs[0].equals("version=\"1.0\"") || t.unparsedAttrs[0].equals("version='1.0'"))) {
if (logMINOR) Logger.minor(this, "Deleting xml declaration, invalid version");
return null;
}
String encodingAttr = t.unparsedAttrs[1];
if(encodingAttr.startsWith("encoding=\"")) {
if(!encodingAttr.endsWith("\"")) {
if (logMINOR) Logger.minor(this, "Deleting xml declaration, invalid encoding");
return null;
}
} else if(encodingAttr.startsWith("encoding='")) {
if(!encodingAttr.endsWith("'")) {
if (logMINOR) Logger.minor(this, "Deleting xml declaration, invalid encoding");
return null;
}
} else {
if (logMINOR) Logger.minor(this, "Deleting xml declaration, invalid encoding");
return null;
}
String charset = encodingAttr.substring("encoding='".length(), encodingAttr.length()-1);
if (!charset.equalsIgnoreCase(pc.charset)) {
if(pc.charset != null && !charset.equalsIgnoreCase(pc.charset)) {
if (logMINOR) Logger.minor(this, "Deleting xml declaration (invalid charset "
+ charset + " should be "+pc.charset + ")");
return null;
} else if(pc.detectedCharset != null) {
throwFilterException(l10n("multipleCharsetsInMeta"));
} else {
pc.detectedCharset = charset;
}
}
return t;
}
}
static class HtmlTagVerifier extends TagVerifier {
static final String[] locallyVerifiedAttrs = new String[] { "xmlns" };
HtmlTagVerifier() {
super("html", new String[] { "id", "version" });
for(String attr : locallyVerifiedAttrs) {
parsedAttrs.add(attr);
}
}
@Override
Map<String, Object> sanitizeHash(Map<String, Object> h,
ParsedTag p,
HTMLParseContext pc) throws DataFilterException {
Map<String, Object> hn = super.sanitizeHash(h, p, pc);
String xmlns = getHashString(h, "xmlns");
if ((xmlns != null) && xmlns.equals("http://www.w3.org/1999/xhtml")) {
hn.put("xmlns", xmlns);
pc.setisXHTML(true);
}
return hn;
}
}
static class BaseHrefTagVerifier extends TagVerifier {
static final String[] locallyVerifiedAttrs = new String[] {
"href"};
BaseHrefTagVerifier(String string, String[] strings, String[] strings2) {
super(string, strings, strings2, null);
for(String attr : locallyVerifiedAttrs) {
this.parsedAttrs.add(attr);
}
}
@Override
Map<String, Object> sanitizeHash(Map<String, Object> h,
ParsedTag p,
HTMLParseContext pc) throws DataFilterException {
Map<String, Object> hn = super.sanitizeHash(h, p, pc);
String baseHref = getHashString(h, "href");
if(baseHref != null) {
// Decode and encode for the same reason we do in sanitizeHash().
baseHref = HTMLDecoder.decode(baseHref);
String ref = pc.cb.onBaseHref(baseHref);
if(ref != null) {
hn.put("href", HTMLEncoder.encode(ref));
return hn;
}
}
pc.writeAfterTag.append("<!-- deleted invalid base href -->");
return null;
}
}
static String sanitizeStyle(String style, FilterCallback cb, HTMLParseContext hpc, boolean isInline) throws DataFilterException {
if(style == null) return null;
if(hpc.onlyDetectingCharset) return null;
Reader r = new StringReader(style);
Writer w = new StringWriter();
style = style.trim();
if(logMINOR) Logger.minor(HTMLFilter.class, "Sanitizing style: " + style);
CSSParser pc = new CSSParser(r, w, false, cb, hpc.charset, false, isInline);
try {
pc.parse();
} catch (IOException e) {
Logger.error(
HTMLFilter.class,
"IOException parsing inline CSS!");
} catch (Error e) {
if (e.getMessage().equals("Error: could not match input")) {
// this sucks, it should be a proper exception
Logger.normal(
HTMLFilter.class,
"CSS Parse Error!",
e);
return "/* "+l10n("couldNotParseStyle")+" */";
} else
throw e;
}
String s = w.toString();
if ((s == null) || (s.length() == 0))
return null;
// Core.logger.log(SaferFilter.class, "Style now: " + s, LogLevel.DEBUG);
if(logMINOR) Logger.minor(HTMLFilter.class, "Style finally: " + s);
return s;
}
static String escapeQuotes(String s) {
StringBuilder buf = new StringBuilder(s.length());
for (int x = 0; x < s.length(); x++) {
char c = s.charAt(x);
if (c == '\"') {
buf.append(""");
} else {
buf.append(c);
}
}
return buf.toString();
}
static String sanitizeScripting(String script) {
// Kill it. At some point we may want to allow certain recipes - FIXME
return null;
}
static String sanitizeURI(String uri, FilterCallback cb, boolean inline) throws CommentException {
return sanitizeURI(uri, null, null, null, cb, inline);
}
/*
* While we're only interested in the type and the charset, the format is a
* lot more flexible than that. (avian) TEXT/PLAIN; format=flowed;
* charset=US-ASCII IMAGE/JPEG; name=test.jpeg; x-unix-mode=0644
*/
public static String[] splitType(String type) {
StringFieldParser sfp;
String charset = null, param, name, value;
int x;
sfp = new StringFieldParser(type, ';');
type = sfp.nextField().trim();
while (sfp.hasMoreFields()) {
param = sfp.nextField();
x = param.indexOf('=');
if (x != -1) {
name = param.substring(0, x).trim();
value = param.substring(x + 1).trim();
if (name.equals("charset"))
charset = value;
}
}
return new String[] { type, charset };
}
// A simple string splitter
// StringTokenizer doesn't work well for our purpose. (avian)
static class StringFieldParser {
private String str;
private int maxPos, curPos;
private char c;
public StringFieldParser(String str) {
this(str, '\t');
}
public StringFieldParser(String str, char c) {
this.str = str;
this.maxPos = str.length();
this.curPos = 0;
this.c = c;
}
public boolean hasMoreFields() {
return curPos <= maxPos;
}
public String nextField() {
int start, end;
if (curPos > maxPos)
return null;
start = curPos;
while ((curPos < maxPos) && (str.charAt(curPos) != c))
curPos++;
end = curPos;
curPos++;
return str.substring(start, end);
}
}
static String htmlSanitizeURI(
String suri,
String overrideType,
String overrideCharset,
String maybeCharset,
FilterCallback cb,
HTMLParseContext pc,
boolean inline) {
try {
return sanitizeURI(suri, overrideType, overrideCharset, maybeCharset, cb, inline);
} catch (CommentException e) {
pc.writeAfterTag.append("<!-- ").append(HTMLEncoder.encode(e.toString())).append(" -->");
return null;
}
}
static String sanitizeURI(
String suri,
String overrideType,
String overrideCharset,
String maybeCharset,
FilterCallback cb, boolean inline) throws CommentException {
if(logMINOR)
Logger.minor(HTMLFilter.class, "Sanitizing URI: "+suri+" ( override type "+overrideType +" override charset "+overrideCharset+" ) inline="+inline, new Exception("debug"));
boolean addMaybe = false;
if((overrideCharset != null) && (overrideCharset.length() > 0))
overrideType += "; charset="+overrideCharset;
else if(maybeCharset != null)
addMaybe = true;
String retval = cb.processURI(suri, overrideType, false, inline);
if(addMaybe) {
if(retval.indexOf('?') != -1)
retval += "&maybecharset="+maybeCharset;
else
retval += "?maybecharset="+maybeCharset;
}
return retval;
}
static String getHashString(Map<String, Object> h, String key) {
Object o = h.get(key);
if (o == null)
return null;
if (o instanceof String)
return (String) o;
else
return null;
}
private static String l10n(String key) {
return NodeL10n.getBase().getString("HTMLFilter."+key);
}
private static String l10n(String key, String pattern, String value) {
return NodeL10n.getBase().getString("HTMLFilter."+key, pattern, value);
}
@Override
public BOMDetection getCharsetByBOM(byte[] input, int length) throws DataFilterException {
// No enhanced BOMs.
// FIXME XML BOMs???
return null;
}
@Override
public int getCharsetBufferSize() {
//Read in 64 kilobytes. The charset could be defined anywhere in the head section
return 1024*64;
}
}
|
gpl-2.0
|
hferrada/rmq
|
includes/Basic_rmq.cpp
|
4397
|
#include "Basic_rmq.h"
namespace rmqrmm {
// sets bit i-ht in e (left to right)
void setBit64(ulong *e, ulong i) {
e[i>>BW64] |= (maskW63>>(i%W64));
}
// cleans bit i-ht in e (left to right)
void cleanBit64(ulong * e, ulong i) {
e[i>>BW64] &= ~(maskW63>>(i%W64));
}
// print the last cantBits of unisned int x
void printBitsNum(uint x, uint cantBits){
uint mask = 1 << (cantBits-1);
for(uint cnt=1; cnt<=cantBits; ++cnt){
putchar(((x & mask) == 0) ? '0' : '1');
mask >>= 1;
}
}
// print the last cantBits of unisned long int x
void printBitsNum64(ulong x, uint cantBits){
ulong mask = 1 << (cantBits-1);
for(uint cnt=1; cnt<=cantBits; ++cnt){
putchar(((x & mask) == 0) ? '0' : '1');
mask >>= 1;
}
}
// print W64 bits of unsigned long int x
void printBitsUlong(ulong x){
uint cnt = 0;
ulong mask = 0x8000000000000000;
for(cnt=0;cnt<W64;++cnt){
putchar(((x & mask) == 0) ? '0' : '1');
mask >>= 1;
}
}
// compute ceiling to logarithm base k for num
uint ceilingLog64(ulong num, uint k){
uint lg = 0;
float lgB = log(num)/log(k);
if((lgB - (uint)lgB) > 0)
lg = (uint)lgB + 1;
else
lg = (uint)lgB;
return lg;
}
// return (in a unsigned long integer) the number in A from bits of position 'ini' to 'ini+len-1'
ulong getNum64(ulong *A, ulong ini, uint len){
ulong i=ini>>BW64, j=ini-(i<<BW64);
ulong result = (A[i] << j) >> (W64-len);
if (j+len > W64)
result = result | (A[i+1] >> (WW64-j-len));
return result;
}
long int getNumLI64(long int *A, ulong ini, uint len){
ulong i=ini>>BW64, j=ini-(i<<BW64);
long int result = (A[i] << j) >> (W64-len);
if (j+len > W64)
result = result | (A[i+1] >> (WW64-j-len));
return result;
}
// Extract n cells: A[sp,...,sp+n-1] and stores values in B[0,...,n-1], where each cell has lenCell bits.
void extractUlongs(ulong *A, ulong sp, ulong n, uint lenCell, ulong *B) {
ulong i = sp*(lenCell>>BW64); // byte i of A
ulong j = (sp*lenCell)%W64; // offset j inside byte i in A
ulong k=0;
while (k<n){
B[k] = (A[i] << j) >> (W64-lenCell);
if (j+lenCell > W64)
B[k] = B[k] | (A[i+1] >> (WW64-j-lenCell));
j+=lenCell;
if(j>=W64){
j-=W64;
i++;
}
k++;
}
}
// set the number x as a bitstring sequence in *A. In the range of bits [ini, .. ini+len-1] of *A. Here x has len bits
void setNum64(ulong *A, ulong ini, uint len, ulong x) {
ulong i=ini>>BW64, j=ini-(i<<BW64);
if ((j+len)>W64){
ulong myMask = ~(~0ul >> j);
A[i] = (A[i] & myMask) | (x >> (j+len-W64));
myMask = ~0ul >> (j+len-W64);
A[i+1] = (A[i+1] & myMask) | (x << (WW64-j-len));
}else{
ulong myMask = (~0ul >> j) ^ (~0ul << (W64-j-len)); // XOR: 1^1=0^0=0; 0^1=1^0=1
A[i] = (A[i] & myMask) | (x << (W64-j-len));
/*ulong q =(~0ul >> j);
printBitsUlong(q);
std::cout << std::endl;
q = (~0ul << (W64-j-len));
printBitsUlong(~0ul << (W64-j-len));
std::cout << std::endl;
printBitsUlong(myMask);
std::cout << std::endl;*/
}
}
void setNumLI64(long int *A, ulong ini, uint len, long int x) {
ulong i=ini>>BW64, j=ini-(i<<BW64);
if ((j+len)>W64){
ulong myMask = ~(~0ul >> j);
A[i] = (A[i] & myMask) | (x >> (j+len-W64));
myMask = ~0ul >> (j+len-W64);
A[i+1] = (A[i+1] & myMask) | (x << (WW64-j-len));
}else{
ulong myMask = (~0ul >> j) ^ (~0ul << (W64-j-len)); // XOR: 1^1=0^0=0; 0^1=1^0=1
A[i] = (A[i] & myMask) | (x << (W64-j-len));
}
}
// return in Milliseconds
double getTime_ms(){
double usertime, systime;
struct rusage usage;
getrusage (RUSAGE_SELF, &usage);
usertime = (double) usage.ru_utime.tv_sec * 1000.0 +
(double) usage.ru_utime.tv_usec / 1000.0;
systime = (double) usage.ru_stime.tv_sec * 1000.0 +
(double) usage.ru_stime.tv_usec / 1000.0;
return (usertime + systime);
}
uint popcount_Rank32(uint x){
return __popcount_tab[(x >> 0) & 0xff] + __popcount_tab[(x >> 8) & 0xff]
+ __popcount_tab[(x >> 16) & 0xff] + __popcount_tab[(x >> 24) & 0xff];
}
uint popcount_Rank64(ulong x){
return __popcount_tab[x & 0xffUL] + __popcount_tab[(x >> 8) & 0xffUL] +
__popcount_tab[(x >> 16) & 0xffUL] + __popcount_tab[(x >> 24) & 0xffUL] +
__popcount_tab[(x >> 32) & 0xffUL] + __popcount_tab[(x >> 40) & 0xffUL] +
__popcount_tab[(x >> 48) & 0xffUL] + __popcount_tab[(x >> 56) & 0xffUL];
}
} /* namespace rmqrmm */
|
gpl-2.0
|
Yeremenko-Roman/Geekhub-Roman-E
|
wp-content/plugins/wptuner/wptunersetup.php
|
25687
|
<?php
/* Copyright 2008 ICTA / Mr Pete (email : WPTuner at ICTA dot net)
I have not yet chosen a license for this software.
For now, if you have received specific written permission from me
to use this software, then you are free to use it personally according
to the terms I gave you. You may not redistribute it to others.
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.
*/
?>
<?php
wptuner_localize(); // Activate localization on admin/settings page
if (!function_exists('file_put_contents')) { // Backwards php4 compatibility
function file_put_contents($filename, $data) {
$f = @fopen($filename, 'w');
if (!$f) {
return false;
} else {
$bytes = fwrite($f, $data);
fclose($f);
return $bytes;
}
}
}
//
// If an option begins with certain letters, it can be used for admin settings
// b = boolean
// f = float
// i = integer
// s = string
global $wptuner_options, $wptuner_presets, $wptuner_preset_names;
//
// Here are the available WP options -- this array controls adding/removing from the DB, and reset to defaults
$wptuner_options = array(
'version' => WPTUNER_VERSION,
'minor_version' => WPTUNER_MINOR_VERSION,
'bShowLog' => true, // show the debug log
'bShowTime' => true, // show performance stats
'bShowSQL' => true, // show sql queries
'bShowAll' => false, // True: all queries shown; False: only slow and bad queries shown
'bShowDetail' => true, // True: show detailed query analysis for any queries shown
'bShowOverview' => true, // True: show one line overview
'bChargePlugins' => true, // True: charge core DB queries to plugins; False: charge to core
'bUninstallOnDeactivate' => true, // True: Uninstall (remove all traces) upon deactivation
'fSlowTime' => 0.5, // Any element slower than this (seconds) will be highlighted
'iDebugLevel' => 0, // wpTuner debugging. Normally zero; can set to higher values to discover why wpTuner is misbehaving
'bAvoidQueryTesting' => false // True: never examine queries to see if valid, to record table usage, or (optionally) examine for optimization hints
);
// Same set as above, except these are presets. Hitting a preset button will redo all of these
$wptuner_presets = array(
// Minimize Warn Times Slow Dev All
'bShowLog' => array( false, true, true, true, true, true ), // show the debug log
'bShowTime' => array( false, false, true, true, true, true ), // show performance stats
'bShowSQL' => array( false, true, true, true, true, true ), // show SQL queries
'bShowAll' => array( false, false, false, false, false,true ), // True: all queries shown; False: only slow and bad queries shown
'bShowDetail' => array( false, false, false, true, true, true ), // True: show detailed query analysis for any queries shown
'bShowOverview' => array( true, true, true, true, true, true ), // True: show one line overview
'bChargePlugins' => array( true, true, true, true, true, true ) // True: charge core DB queries to plugins; False: charge to core
);
// Key is the name, in order to be displayed
// Value is the array index above, from 0 to n
$wptuner_preset_names = array(
__('Minimal (Admin) Footer','wptuner') => 0,
__('Errors and Warnings', 'wptuner') => 1,
__('Analyze Timing','wptuner') => 2,
__('Find Slow Elements', 'wptuner') => 3,
__('Developer Basic', 'wptuner') => 4,
__('Show Everything', 'wptuner') => 5
);
function wptuner_auto_update() {
global $wpdb;
// Update sets... not needed here actually
//if(get_option(WPTOPTBASE.'version') <= 1.0) {
//include_once('updates/update-to-something.php');
//}
if((get_option(WPTOPTBASE.'version') < WPTUNER_VERSION) ||
(get_option(WPTOPTBASE.'version') == WPTUNER_VERSION) &&
(get_option(WPTOPTBASE.'minor_version') < WPTUNER_MINOR_VERSION)) {
update_option(WPTOPTBASE.'version', WPTUNER_VERSION);
update_option(WPTOPTBASE.'minor_version', WPTUNER_MINOR_VERSION);
}
}
function wptuner_install()
{
global $wptuner_options,$wpdb, $user_level, $wp_rewrite, $wp_version;
if($wp_version < 2.1) {
get_currentuserinfo();
if($user_level < 8) {
return;
}
}
foreach($wptuner_options as $key => $val) {
if (get_option(WPTOPTBASE.$key) == null)
add_option(WPTOPTBASE.$key, $val);
}
wptuner_wpconfig_inject();
}
function wptuner_uninstall() {
global $wpdb, $wptuner_options;
if(current_user_can('edit_plugins')) {
if (get_option(WPTOPTBASE.'bUninstallOnDeactivate'))
{
foreach($wptuner_options as $key => $val) {
delete_option(WPTOPTBASE.$key);
}
wptuner_wpconfig_remove(); // remove the wpconfig code
}
}
}
function wptuner_wpconfig_perm() {
return substr(sprintf('%o', fileperms(ABSPATH.'wp-config.php')), -4);
}
function wptuner_root_perm() {
return substr(sprintf('%o', fileperms(ABSPATH)), -4);
}
function wptuner_wpconfig_check() {
$cfgName = ABSPATH.'wp-config.php';
$configFile = file($cfgName);
$insLine=-1;
$startLine=0;
$endLine=0;
$bOK = true;
// First pass: discover if any bits of WP Tuner are in place, and where it should be installed
//
foreach ($configFile as $line_num => $line) {
$test=trim( substr($line,0,16));
if (substr($test,0,7)=='$base =')
$test = '$base =';
switch ($test) {
case "define('DB_HOST'":
case "define('DB_CHARS":
case "define('DB_COLLA":
case "define('VHOST',":
case "define ('WPLANG'";
case "define('WPLANG',";
case '$table_prefix =':
case '$table_prefix =':
case '$table_prefix':
case '$base =':
//echo '<pre>'.$line.'</pre><br/>';
$insLine = max( $line_num, $insLine ); break;
case "/* That's all, s": // This is the MOST preferred place. Right before the end...
case "/* That's all,":
$insLine = max( $line_num-1, $insLine ); break;
case "//-WP Tuner Plug";
$startLine=$line_num; break;
case "//-END WP Tuner";
$endLine =$line_num; break;
default:
break;
}
}
if ($insLine < 0)
{
define('WPTUNER_ERR_NOCFGFILE',1); // can't read config file
$bOK=false;
} else {
if ($startLine || $endLine)
{
define('WPTUNER_ERR_WPT_TRASH',1); // wp-config has leftover WP Tuner trash (might be good trash)
$bOK=false;
}
if (!@chmod($cfgName, 0777))
{
define('WPTUNER_ERR_CFG_NOWRITE',1); // wp-config can't be written
$bOK=false;
}
@chmod($cfgName, 0644);
}
if ($bOK)
return $insLine;
else
return false;
}
// Returns TRUE if injected ok, FALSE if any problem
function wptuner_wpconfig_inject() {
$configFile = file( ABSPATH.'wp-config.php' );
$outFile = ABSPATH.'wp-config.php';
$configCopy = ABSPATH.'wp-config.WPTunerOrig.php';
$insLine= wptuner_wpconfig_check();
if (!$insLine)
return false;
// Copy the config file as-is
if (!file_put_contents( $configCopy, $configFile ))
{
define('WPTUNER_ERR_CFG_NOBACKUP',1); // can't back up wp-config
return false;
}
$myStr = <<<EOT
//-WP Tuner Plugin by MrPete------------
//--------------------------------------
\$wpTunerStart = microtime(); // get start time as early as we can
if ( function_exists( 'getrusage' ) ) { \$wpTunerStartCPU = getrusage(); }
@include_once(dirname(__FILE__).'/wp-content/plugins/wptuner/wptunertop.php'); // fire up WPTuner
//--------------------------------------
//-END WP Tuner Plugin------------------
EOT;
$outStr = implode(array_slice($configFile,0,$insLine+1)) . $myStr . "\n".implode(array_slice($configFile, $insLine+1));
@chmod($outFile, 0777);
if (!file_put_contents($outFile, $outStr))
{
define('WPTUNER_ERR_CFG_NODATA',1); // can't write data into config file; like NOWRITE but data level
return false;
}
chmod($outFile, 0644);
}
function wptuner_wpconfig_removecheck() {
$cfgName = ABSPATH.'wp-config.php';
$configFile = file($cfgName);
$startLine=0;
$endLine=0;
$bOK = true;
// Find start and end of WP Tuner in wp-config
//
foreach ($configFile as $line_num => $line) {
$test=trim( substr($line,0,16));
switch ($test) {
case "//-WP Tuner Plug";
$startLine=$line_num; break;
case "//-END WP Tuner";
$endLine =$line_num; break;
default:
break;
}
}
if (!$startLine || !$endLine)
{
define('WPTUNER_ERR_WPT_NOTFUND',1); // strange. Can't remove WPT from wp-config; markers not found
$bOK=false;
}
if (!@chmod($cfgName, 0777))
{
define('WPTUNER_ERR_CFG_NOWRITE',1); // wp-config can't be written
$bOK=false;
}
@chmod($cfgName, 0644);
if ($bOK)
return array($startLine,$endLine);
else
return null;
}
// Returns TRUE if removed ok, FALSE if any problem
function wptuner_wpconfig_remove() {
$configFile = file( ABSPATH.'wp-config.php' );
$outFile = ABSPATH.'wp-config.php';
$configCopy = ABSPATH.'wp-config.WPTunerFinal.php';
$wptLines= wptuner_wpconfig_removecheck();
if (!isset($wptLines))
return false;
// Copy the config file as-is
if (!file_put_contents( $configCopy, $configFile ))
{
define('WPTUNER_ERR_CFG_NOBACKUP',1); // can't back up wp-config
return false;
}
$outStr = implode(array_slice($configFile,0,$wptLines[0])) .implode(array_slice($configFile, $wptLines[1]+1));
@chmod($outFile, 0777);
if (!file_put_contents($outFile, $outStr))
{
define('WPTUNER_ERR_CFG_NODATA',1); // can't write data into config file; like NOWRITE but data level
return false;
}
chmod($outFile, 0644);
}
function wptuner_show_admin_page() {
global $wptuner_options, $wptuner_preset_names, $wptuner_presets, $wptunershow;
//
// Every time admin page shows, attempt to auto-inject into wp-config, if necessary
//
if (WPTUNER_NOTCONFIG+WPTUNER_BADCONFIG+WPTUNER_NOQUERIES)
{
wptuner_wpconfig_inject();
}
$sText = "";
// Debugging queries from users...
//$wpt_dbgqry = array("q1","q2")
// foreach ( $wpt_dbgqry as $qry)
// {
// global $wpdb;
// $wpdb->query($qry);
//}
// foreach ($wptuner_options as $key => $val) {
// $wptunershow->{$key} = get_option(WPTOPTBASE.$key);
// }
if(isset($_POST["wptuner_action"])) {
foreach ($wptuner_options as $key => $val) {
if (FALSE===strpos('bfis',$key[0]))
continue; // skip options not settable by users
if ($_POST[$key] !== NULL) {
$val = $_POST[$key];
switch ($key[0] ) {
case 'i':
case 'b': $val = intval($val); break;
case 'f': $val = floatval($val); break;
case 's': $val = $val; break; // clean up once we have a str to save
}
$wptunershow->{$key} = $val;
update_option(WPTOPTBASE.$key, $val);
} else {
if (0) { // there should be no reason to do this. Bad side effect: disabled items in UI get reset!
if ($key[0] == 'b')
{
$val = 0;
$wptunershow->{$key} = $val;
update_option(WPTOPTBASE.$key, $val);
}
}
}
}
$sText .= "<div id='message' class='updated fade'><p>".__('WP Tuner options successfully updated.','wptuner')."</p></div>";
}
if(isset($_POST["wptuner_default"])) {
foreach ($wptuner_options as $key => $val) {
if (FALSE===strpos('bfis',$key[0]))
continue; // skip options not settable by users
$wptunershow->{$key} = $val;
update_option(WPTOPTBASE.$key, $val);
}
$sText .= "<div id='message' class='updated fade'><p>".__('WP Tuner options successfully reset to default values.','wptuner')."</p></div>";
}
if(isset($_POST["wptuner_preset"])) {
$preset_val = $_POST["wptuner_preset"]; // value is array key
if (isset($wptuner_preset_names[$preset_val]))
{
$preset_idx = $wptuner_preset_names[$preset_val]; // convert from name to index
foreach($wptuner_presets as $key=> $ary)
{
if (FALSE===strpos('bfis',$key[0]))
continue; // skip nonusable rose
$wptunershow->{$key} = $ary[$preset_idx];
update_option(WPTOPTBASE.$key, $ary[$preset_idx]);
}
}
$sText .= "<div id='message' class='updated fade'><p>".sprintf(__('WP Tuner options successfully preset to <em>%s</em>.','wptuner'), $preset_val)."</p></div>";
}
echo <<<EOT
<div class="wrap">
<h2>WP Tuner Options and Hints</h2>
EOT;
if ($sText <> "") {
print "<p>\n";
print $sText;
print "</p>\n";
}
_e("<p>At minimum, WP Tuner does a basic performance analysis: time, database use, memory use and server load.</p><p><em>Note:</em> If your pages take a long time to generate, yet the server load is <em>low</em>, something <em>else</em> is slowing down your site! A plugin may be trying to get data from a slow or missing site, or your web host may by slowed by other sites running on the same CPU.",'wptuner');
$cSlow = $wptunershow->fSlowTime;
$strReset =__('Reset to defaults','wptuner');
$strUpdate =__('Save Changes','wptuner');
function wpt_emit_radioval( $key, $val, $cVal, $sPrompt, $sHint )
{
$sText = "<label><input name='$key' type='radio' value='".intval($val)."'";
if (intval($val) == intval($cVal))
$sText.= ' CHECKED="CHECKED" ';
$sText .= " /> {$sPrompt}</label><br />\n";
if (strlen($sHint))
$sText .= " <small>($sHint)</small><br/>\n";
return $sText;
}
function wpt_show_radio( $key, $sTitle, $sFalsePrompt, $sFalseHint,$sTruePrompt, $sTrueHint )
{
global $wptuner_options, $wptunershow;
$cVal = $wptunershow->{$key};
print "<tr valign='top'>\n<th scope='row'>{$sTitle}</th>\n<td>\n";
print wpt_emit_radioval( $key, 0, $cVal, $sFalsePrompt, $sFalseHint );
print wpt_emit_radioval( $key, 1, $cVal, $sTruePrompt, $sTrueHint );
print "</td></tr>\n";
}
print '<form method="post" action="">'."\n";
print "<style type='text/css'>
.wptuner_presets { float: left; width: 19%; }
.wptuner_options { float: right; width:79%; padding: 0 0 10px 10px; border-left: 1px solid black;}
.wptuner_options a.notsubmit { color: #2583ad; }
.wptuner_options ul.condensed { margin-top: 0; }
.wptuner_foot { clear: both; border-top: 1px solid black; margin-top: 2px;}
</style>\n";
print '<div><div class="wptuner_presets">';
//
// First column: Easy Presets
_e('<h3>Presets</h3>','wptuner');
echo '<p class="submit"><input type="submit" name="wptuner_default" value="'.$strReset.'" /><br/><br/>';
foreach ($wptuner_preset_names as $key => $val)
{
echo '<input type="submit" name="wptuner_preset" value="'.$key.'" /><br/><br/>';
}
print '</p></div><div class="wptuner_options">';
//
// Second column: Custom settings
//
_e('<h3>Custom Settings</h3>','wptuner');
echo "<p class='submit'>
<input type='submit' name='wptuner_action' value='".$strUpdate."' />
<em>(<a class='notsubmit' href='#wptuner'>".__('View current WP Tuner output','wptuner')."</a>)</em></p>\n";
print '<table class="form-table">'."\n";
print "<tr valign='top'>\n<th scope='row'>".__('Install / Uninstall','wptuner')."</th>\n
<td>";
$configErrCount= WPTUNER_NOTCONFIG+WPTUNER_BADCONFIG+WPTUNER_NOQUERIES;
$ru_available =function_exists('getrusage');
$mem_available=function_exists("memory_get_usage");
$missing = '';
if (!$configErrCount) {
_e('WP Tuner is correctly installed.<br/>','wptuner');
}
$bUninstallOnDeactivate = get_option(WPTOPTBASE.'bUninstallOnDeactivate');
print "<label><input name='bUninstallOnDeactivate' type='checkbox' value='1'";
if (intval($bUninstallOnDeactivate))
print ' CHECKED="CHECKED" ';
print " /> ".__('Uninstall (remove all settings) when plugin is deactivated.','wptuner').' <em>['.__('Not affected by Presets','wptuner')."]</em></label>\n";
$iDebugLevel = get_option(WPTOPTBASE.'iDebugLevel');
print '<br/><label><input type="number" name="iDebugLevel" value="'.$iDebugLevel.'" maxlength="3" size="3" /> ';
print __('Debug Level (normally 0, ask MrPete for other values if wpTuner is misbehaving)','wptuner').
"</label>\n";
if (!$configErrCount) {
//
// No errors; give some extra notes for tech-minded people
//
if (!($ru_available && $mem_available))
{
print '<br/><br/>'.__("<em>Note:</em> Your web environment is unable to provide me with the following information:",'wptuner'). "<ul class='condensed'>\n";
if (!$ru_available)
print '<li> '.__('<em>Server load (CPU time):</em> probably a windows server?','wptuner')."</li>\n";
if (!$mem_available)
print '<li> '.__('<em>Memory used:</em> probably running older PHP (before 5.2) on a system with no memory limit configured.','wptuner')."</li>\n";
print "</ul>\n";
}
global $wp_version;
print '<br/><br/>'.sprintf(__('<em>Note:</em> Because you are running WP version %s, WP Tuner has enhanced the following built-in WordPress function(s):','wptuner'),$wp_version). "<ul class='condensed'>\n";
if (!function_exists('current_filter')) {
print '<li> '.__('<em>current_filter()</em> function emulation, so filters can be tracked (WP versions before 2.5)','wptuner')."</li>\n";
}
if (defined('WPTUNER_USING_ALTQUERY')) {
print '<li> '.__('<em>DB query()</em> function, so performance can be tracked (WP versions 2.0.6 to 2.3.2)','wptuner')."</li>\n";
}
print '<li> '.__('<em>DB get_caller()</em> function, so specific DB access can be tracked (WP versions 2.0.6 to present)','wptuner')."</li>\n";
print "</ul>\n";
} else {
// There's at least one problem.
print '<br/><b>'.__('Configuration Incomplete. Number of errors: ','wptuner').$configErrCount."</b>
<br/><em>(".__('Fix issues in the order presented. One issue may be the actual cause of all errors. Reload this page two+ times after making any change. If the problem is not resolved, deactivate and reactivate again.','wptuner').")</em><ul>\n";
$errFound = false;
if (WPTUNER_NOTCONFIG) {
if (defined('WPTUNER_ERR_NOCFGFILE')) // can't read config file
{
printf(__("<li>wp-config.php can't be read. Permissions are %s, and should be at least 0644. Check your wordpress folder permissions as well.</li>\n",'wptuner'),wptuner_wpconfig_perm());
$errFound=true;
}
if (defined('WPTUNER_ERR_WPT_TRASH')) // wp-config has leftover WP Tuner trash (might be good trash)
{
_e("<li>wp-config.php contains WP Tuner markers, but they are <i>after</i> the ABSPATH definition. Please clean up the file and reinstall WP Tuner.</li>\n",'wptuner');
$errFound=true;
}
if (defined('WPTUNER_ERR_CFG_NOWRITE')) // wp-config can't be written - write permission
{
printf(__("<li>wp-config.php can't be written. Permissions are %s, and should be at least 0644. Check your wordpress folder permissions as well.</li>\n",'wptuner'),wptuner_wpconfig_perm());
$errFound=true;
}
if (defined('WPTUNER_ERR_CFG_NOBACKUP')) // wp-config can't be backed up (for inject or remove)
{
printf(__("<li>wp-config.php can't be backed up. Your wordpress directory (%s) permissions are %s, and should be at least 0755.</li>\n",'wptuner'),ABSPATH,wptuner_root_perm());
$errFound=true;
}
if (defined('WPTUNER_ERR_CFG_NODATA')) // wp-config can't be written - data not written
{
_e("<li>No data can be written to wp-config.php -- Please check disk space.</li>\n",'wptuner');
$errFound=true;
}
$errFound=true;
_e("<li>If Auto-config remains broken, please find a way to add the following code after your DB_* definitions in wp-config.php:<br/>
<pre style='padding:3px;line-height:11px;background-color:#eee'>
//-WP Tuner Plugin by MrPete------------
//--------------------------------------
\$wpTunerStart = microtime(); // get start time as early as we can
if ( function_exists( 'getrusage' ) ) { \$wpTunerStartCPU = getrusage(); }
@include_once(dirname(__FILE__).'/wp-content/plugins/wptuner/wptunertop.php'); // fire up WPTuner
//--------------------------------------
//-END WP Tuner Plugin------------------
</pre></li>\n",'wptuner');
}
if (WPTUNER_BADCONFIG) {
$errFound=true;
_e("<li>WP-Config code badly placed: please check your wp-config.php file. wptunertop.php is loaded <em>too early</em>. The DB_* constants must be defined before wptunertop is included.</li>\n",'wptuner');
}
if (!$errFound && WPTUNER_NOQUERIES){
_e("<li>Technical issue: Configuration appears correct, yet WP Tuner could not be loaded before wp-db.php, so SAVEQUERIES is not defined. WP Tuner is unable to analyze your database use. If you need further help, please contact MrPete.</li>\n",'wptuner');
}
print '</ul>';
}
print "</td></tr>\n";
if (0) { // hide this option for now-- always set!
//wpt_show_radio( 'bShowOverview',__('Show WP Tuner Overview','wptuner'),
// __('No.','wptuner'), '',
// __('Yes, show a one-line performance summary','wptuner'), __('Turn this on, and everything else off, to ensure WP Tuner\'s output is minimal. (Slow queries will still be shown.)','wptuner') );
}
echo '
<tr valign="top">
<th scope="row">'.__('Slow Query Threshold','wptuner').'</th>
<td>'.
sprintf(__('Highlight anything that takes longer than %s seconds.','wptuner'),
'<input type="number" name="fSlowTime" value="'.$cSlow.'" maxlength="10" size="3" />').
' <em>['.__('Not affected by Presets','wptuner')."]</em><br/>\n".
__('<small>(Normally, 0.5 seconds is a good setting. If your whole site is slow, set a higher number.)</small>','wptuner').
'</td></tr>';
wpt_show_radio( 'bAvoidQueryTesting',__('Ignore Query Contents','wptuner'),
__('No.','wptuner'), '',
__('Yes, cut WP Tuner overhead to bare minimum.','wptuner'), __('Disables query optimization hints, per-table stats, and invalid query detection. Slow queries will still be seen.','wptuner').' <em>['.__('Not affected by Presets','wptuner')."]</em>" );
echo '</table>';
print '<h3>'.__('Performance Analysis','wptuner')."</h3>". __('This section summarizes: overall WordPress performance, per-plugin DB performance, and per-table performance. Helps find plugins and tables that need optimization or better indexes.','wptuner')."\n";
print '<table class="form-table">'."\n";
wpt_show_radio( 'bShowTime',__('Show Performance Analysis','wptuner'),
__('No.','wptuner'), '',
__('Yes, display time and database performance','wptuner'), '' );
print '</table><h3>'.__('SQL Query Analysis','wptuner')."</h3>".__('This section shows each query: what is it, how quickly it runs, detailed explanation usable for optimization. From these you may learn details of speeding up specific database queries. <em>This is mostly of use to developers.</em>','wptuner')."\n";
print '<table class="form-table">'."\n";
wpt_show_radio( 'bShowSQL',__('Show SQL Query Analysis','wptuner'),
__('No.','wptuner'), '',
__('Yes, display query analysis','wptuner'), '' );
wpt_show_radio( 'bShowAll',__('Show All Queries','wptuner'),
__('No, only display slow or invalid database queries','wptuner'), '',
__('Yes, always show every query','wptuner'), __('Typically used by developers to understand database use in more detail.','wptuner') );
wpt_show_radio( 'bShowDetail',__('Explain Each Query, With Optimization Hints','wptuner'),
__('No. Show query text, but no detailed analysis','wptuner'), '',
__('Yes, show which indexes are used and more','wptuner'), __('This helps when trying to speed up a slow query. <a href="http://dev.mysql.com/doc/refman/5.0/en/using-explain.html">The MySQL Site</a> provides helpful hints on using the detail you see.','wptuner') );
wpt_show_radio( 'bChargePlugins',__('"Charge" queries to Plugins or Core?','wptuner'),
__('<em>Core:</em> when plugins trigger DB queries through core functions, allocate the time used to Core.','wptuner'),
__('Developers sometimes find this setting helpful: it always records the exact file/line where queries are made.','wptuner'),
__('<em>Plugins:</em> time is allocated to the plugin for any DB query it triggers, even if indirectly.','wptuner'),
__('This is the best way to determine overhead cost of a plugin.','wptuner'), '' );
print '</table><h3>'.__('Debug Log','wptuner')."</h3>".__('Displays WP Tuner error messages. Also available for developer use: <code>wpTuneLog(\'text\');</code> will capture anything you like, and tie it to file and line number.','wptuner') ."\n";
print '<table class="form-table">'."\n";
wpt_show_radio( 'bShowLog',__('Show Debug Log','wptuner'),
__('No','wptuner'), '',
__('Yes, display WP Tuner log entries','wptuner'),'' );
echo '</table>';
echo '<p class="submit">
<input type="submit" name="wptuner_action" value="'.$strUpdate.'" />
</p>';
echo "</div></div>\n"; // End of two columns
echo "<div class='wptuner_foot'>\n";
print '<p id="pluginauthor">'.sprintf(__("<em><b>This plugin is only visible to site admins.</b></em><br/>
Like it? Tell a friend. Hate it? Tell %sMr Pete%s. Did it help? Tell %syour story%s. Love it? Help fill the %sTip Jar%s. Your generosity helps Mr Pete and his team meet people's needs around the world!",'wptuner'),
"<a href='http://blogs.icta.net/plugins/wptuner'>","</a>",
"<a href='http://blogs.icta.net/plugins/wptuner'>","</a>",
"<a href='http://blogs.icta.net/plugins/tipjar'>","</a>").
((__('Translator Name','wptuner') == 'Translator Name') ? '' : '<br/>'.sprintf(__('Credit: MrPete is grateful to <a href="%s">%s</a> for this %s translation!','wptuner'),__('http://Translator.Website','wptuner'),__('Translator Name','wptuner'),__('Translator Language','wptuner'))).'
</p>
</div>
</form>
</div>';
}
?>
|
gpl-2.0
|
sagoyanfisic/Proyecto_DS
|
estilos/login/login.php
|
2786
|
<?php
/*****************************
File: login.php
Written by: Frost of Slunked.com
Tutorial: User Registration and Login System
******************************/
require($_SERVER['localhost'] . 'login/includes/config.php');
// If the user is logging in or out
// then lets execute the proper functions
if (isset($_GET['action'])) {
switch (strtolower($_GET['action'])) {
case 'login':
if (isset($_POST['username']) && isset($_POST['password'])) {
// We have both variables. Pass them to our validation function
if (!validateUser($_POST['username'], $_POST['password'])) {
// Well there was an error. Set the message and unset
// the action so the normal form appears.
$_SESSION['error'] = "Bad username or password supplied.";
unset($_GET['action']);
}
}else {
$_SESSION['error'] = "Username and Password are required to login.";
unset($_GET['action']);
}
break;
case 'logout':
// If they are logged in log them out.
// If they are not logged in, well nothing needs to be done.
if (loggedIn()) {
logoutUser();
$sOutput .= '<h1>Logged out!</h1><br />You have been logged out successfully.
<br /><h4>Would you like to go to <a href="index.php">site index</a>?</h4>';
}else {
// unset the action to display the login form.
unset($_GET['action']);
}
break;
}
}
$sOutput .= '<div id="index-body">';
// See if the user is logged in. If they are greet them
// and provide them with a means to logout.
if (loggedIn()) {
$sOutput .= '<h1>Logged In!</h1><br /><br />
Hello, ' . $_SESSION["username"] . ' how are you today?<br /><br />
<h4>Would you like to <a href="login.php?action=logout">logout</a>?</h4>
<h4>Would you like to go to <a href="index.php">site index</a>?</h4>';
}elseif (!isset($_GET['action'])) {
// incase there was an error
// see if we have a previous username
$sUsername = "";
if (isset($_POST['username'])) {
$sUsername = $_POST['username'];
}
$sError = "";
if (isset($_SESSION['error'])) {
$sError = '<span id="error">' . $_SESSION['error'] . '</span><br />';
}
$sOutput .= '<h2>Login to our site</h2><br />
<div id="login-form">
' . $sError . '
<form name="login" method="post" action="login.php?action=login">
Username: <input type="text" name="username" value="' . $sUsername . '" /><br />
Password: <input type="password" name="password" value="" /><br /><br />
<input type="submit" name="submit" value="Login!" />
</form>
</div>
<h4>Would you like to <a href="login.php">login</a>?</h4>
<h4>Create a new <a href="register.php">account</a>?</h4>';
}
$sOutput .= '</div>';
// lets display our output string.
echo $sOutput;
?>
|
gpl-2.0
|
Linaro/lava-dispatcher
|
lava_dispatcher/test/test_menus.py
|
7913
|
# Copyright (C) 2015 Linaro Limited
#
# Author: Neil Williams <neil.williams@linaro.org>
#
# This file is part of LAVA Dispatcher.
#
# LAVA Dispatcher 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.
#
# LAVA Dispatcher 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>.
import os
import re
import logging
from lava_dispatcher.device import NewDevice
from lava_dispatcher.parser import JobParser
from lava_dispatcher.action import Timeout, JobError
from lava_dispatcher.shell import ShellSession, ShellCommand
from lava_dispatcher.test.test_basic import Factory, StdoutTestCase
from lava_dispatcher.test.utils import DummyLogger
from lava_dispatcher.utils.strings import substitute
from lava_dispatcher.menus.menus import SelectorMenu
# pylint: disable=too-many-public-methods
class TestSelectorMenu(StdoutTestCase):
def setUp(self):
super(TestSelectorMenu, self).setUp()
self.menu = SelectorMenu()
self.menu.item_markup = (r'\[', r'\]')
self.menu.item_class = '0-9'
self.menu.separator = ' '
self.menu.label_class = 'a-zA-Z0-9'
self.menu.prompt = None
def test_menu_parser(self):
pattern = "%s([%s]+)%s%s([%s]*)" % (
re.escape(self.menu.item_markup[0]),
self.menu.item_class,
re.escape(self.menu.item_markup[1]),
self.menu.separator,
self.menu.label_class
)
serial_input = """
[1] debian
[2] tester
[3] Shell
[4] Boot Manager
[5] Reboot
[6] Shutdown
Start:
"""
selection = self.menu.select(serial_input, 'Shell')
self.assertEqual(
self.menu.pattern,
pattern
)
for line in serial_input.split('\n'):
match = re.search(pattern, line)
if match:
if match.group(2) == "Shell":
self.assertEqual(match.group(1), selection)
class MenuFactory(Factory): # pylint: disable=too-few-public-methods
"""
Not Model based, this is not a Django factory.
Factory objects are dispatcher based classes, independent
of any database objects.
"""
def create_uefi_job(self, filename): # pylint: disable=no-self-use
device = NewDevice(os.path.join(os.path.dirname(__file__), '../devices/mustang-uefi.yaml'))
mustang_yaml = os.path.join(os.path.dirname(__file__), filename)
with open(mustang_yaml) as sample_job_data:
parser = JobParser()
job = parser.parse(sample_job_data, device, 0, None, dispatcher_config="")
job.logger = DummyLogger()
return job
class TestUefi(StdoutTestCase): # pylint: disable=too-many-public-methods
def setUp(self):
super(TestUefi, self).setUp()
factory = MenuFactory()
self.job = factory.create_uefi_job('sample_jobs/mustang-menu-ramdisk.yaml')
def test_check_char(self):
shell = ShellCommand("%s\n" % 'ls', Timeout('fake', 30), logger=logging.getLogger())
if shell.exitstatus:
raise JobError("%s command exited %d: %s" % ('ls', shell.exitstatus, shell.readlines()))
connection = ShellSession(self.job, shell)
self.assertFalse(hasattr(shell, 'check_char'))
self.assertTrue(hasattr(connection, 'check_char'))
self.assertIsNotNone(connection.check_char)
def test_selector(self):
self.assertIsNotNone(self.job)
self.job.validate()
uefi_menu = [action for action in self.job.pipeline.actions if action.name == 'uefi-menu-action'][0]
selector = [action for action in uefi_menu.internal_pipeline.actions if action.name == 'uefi-menu-selector'][0]
params = self.job.device['actions']['boot']['methods']['uefi-menu']['parameters']
self.assertEqual(selector.selector.item_markup, params['item_markup'])
self.assertEqual(selector.selector.item_class, params['item_class'])
self.assertEqual(selector.selector.separator, params['separator'])
self.assertEqual(selector.selector.label_class, params['label_class'])
self.assertEqual(selector.selector.prompt, params['bootloader_prompt']) # initial prompt
self.assertEqual(selector.boot_message, params['boot_message']) # final prompt
self.assertEqual(
selector.character_delay,
self.job.device['character_delays']['boot'])
def test_uefi_job(self):
self.assertIsNotNone(self.job)
self.job.validate()
uefi_menu = [action for action in self.job.pipeline.actions if action.name == 'uefi-menu-action'][0]
selector = [action for action in uefi_menu.internal_pipeline.actions if action.name == 'uefi-menu-selector'][0]
self.assertEqual(
selector.selector.prompt,
"Start:"
)
self.assertIsInstance(selector.items, list)
description_ref = self.pipeline_reference('mustang-uefi.yaml')
self.assertEqual(description_ref, self.job.pipeline.describe(False))
# just dummy strings
substitution_dictionary = {
'{SERVER_IP}': '10.4.0.1',
'{RAMDISK}': None,
'{KERNEL}': 'uImage',
'{DTB}': 'mustang.dtb',
'{NFSROOTFS}': 'tmp/tmp21dfed/',
'{TEST_MENU_NAME}': 'LAVA NFS Test Image'
}
for block in selector.items:
if 'select' in block:
if 'enter' in block['select']:
block['select']['enter'] = substitute([block['select']['enter']], substitution_dictionary)
if 'items' in block['select']:
block['select']['items'] = substitute(block['select']['items'], substitution_dictionary)
count = 0
check_block = [
{'items': ['Boot Manager'], 'wait': 'Choice:'},
{'items': ['Remove Boot Device Entry'], 'fallback': 'Return to Main Menu', 'wait': 'Delete entry'},
{'items': ['LAVA NFS Test Image'], 'wait': 'Choice:'},
{'items': ['Add Boot Device Entry'], 'wait': 'Select the Boot Device:'},
{'items': ['TFTP on MAC Address: 00:01:73:69:5A:EF'], 'wait': 'Get the IP address from DHCP:'},
{'enter': ['y'], 'wait': 'Get the TFTP server IP address:'},
{'enter': ['10.4.0.1'], 'wait': 'File path of the EFI Application or the kernel :'},
{'enter': ['uImage'], 'wait': 'Is an EFI Application?'},
{'enter': ['n'], 'wait': 'Boot Type:'},
{'enter': ['f'], 'wait': 'Add an initrd:'},
{'enter': ['n'], 'wait': 'Get the IP address from DHCP:'},
{'enter': ['y'], 'wait': 'Get the TFTP server IP address:'},
{'enter': ['10.4.0.1'], 'wait': 'File path of the FDT :'},
{'enter': ['mustang.dtb'], 'wait': 'Arguments to pass to the binary:'},
{'enter': ['console=ttyS0,115200 earlyprintk=uart8250-32bit,0x1c020000 debug root=/dev/nfs rw '
'nfsroot=10.4.0.1:tmp/tmp21dfed/,tcp,hard,intr ip=dhcp'], 'wait': 'Description for this new Entry:'},
{'enter': ['LAVA NFS Test Image'], 'wait': 'Choice:'},
{'items': ['Return to main menu'], 'wait': 'Start:'},
{'items': ['LAVA NFS Test Image']},
]
for item in selector.items:
self.assertEqual(
item['select'],
check_block[count])
count += 1
|
gpl-2.0
|
smarr/Truffle
|
tools/src/org.graalvm.tools.lsp/src/org/graalvm/tools/lsp/server/types/DidChangeConfigurationParams.java
|
2697
|
/*
* Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.tools.lsp.server.types;
import com.oracle.truffle.tools.utils.json.JSONObject;
import java.util.Objects;
/**
* The parameters of a change configuration notification.
*/
public class DidChangeConfigurationParams extends JSONBase {
DidChangeConfigurationParams(JSONObject jsonData) {
super(jsonData);
}
/**
* The actual changed settings.
*/
public Object getSettings() {
return jsonData.get("settings");
}
public DidChangeConfigurationParams setSettings(Object settings) {
jsonData.put("settings", settings);
return this;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
DidChangeConfigurationParams other = (DidChangeConfigurationParams) obj;
if (!Objects.equals(this.getSettings(), other.getSettings())) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + Objects.hashCode(this.getSettings());
return hash;
}
public static DidChangeConfigurationParams create(Object settings) {
final JSONObject json = new JSONObject();
json.put("settings", settings);
return new DidChangeConfigurationParams(json);
}
}
|
gpl-2.0
|
ratt-ru/CubiCal
|
cubical/data_handler/__init__.py
|
2455
|
# CubiCal: a radio interferometric calibration suite
# (c) 2017 Rhodes University & Jonathan S. Kenyon
# http://github.com/ratt-ru/CubiCal
# This code is distributed under the terms of GPLv2, see LICENSE.md for details
import numpy as np
import sys
def uniquify(values):
"""
Helper function. Given a vector of values (e.g. times), finds the set of unique values,
and computes a vector of indices (e.g. timeslots) of the same size, as well as rmap: a map from the
unique values to their index numbers.
Returns tuple of indices, unique_values, rmap
"""
uniq = np.unique(values) #np.array(sorted(set(values)))
rmap = {x: i for i, x in enumerate(uniq)}
# apply this map to the time column to construct a timestamp column
indices = np.fromiter(list(map(rmap.__getitem__, values)), int)
return indices, uniq, rmap
# Try to import montblanc: if not successful, remember error for later.
def import_montblanc():
"""
Tries to import montblanc. Returns tuple of montblanc_module, None on success, or
None, exc_info on error
"""
try:
import montblanc
# all of these potentially fall over if Montblanc is the wrong version or something, so moving them here
# for now
from .MBTiggerSim import simulate, MSSourceProvider, ColumnSinkProvider
from .TiggerSourceProvider import TiggerSourceProvider
from montblanc.impl.rime.tensorflow.sources import CachedSourceProvider, FitsBeamSourceProvider
return montblanc, None
except:
return None, sys.exc_info()
# Try to import ddfacet: if not successful, remember error for later.
def import_ddfacet():
"""
Tries to import ddfacet. Returns tuple of ddfacet_module, None on success, or
None, exc_info on error
"""
try:
import DDFacet
return DDFacet, None
except:
return None, sys.exc_info()
class Metadata(object):
"""This class holds metadata from an MS"""
def __init__(self):
self.num_corrs = 0
self.num_antennas = 0
self.num_baselines = 0
self.antenna_name = [] # p -> antenna name
self.antenna_index = {} # antenna name -> p
self.baseline_name = {} # p,q -> baseline name
self.baseline_length = {} # p,q -> baseline length
self.feeds = "xy" # "xy" or "rl"
self.ra0 = 0
self.dec0 = 0
|
gpl-2.0
|
imadkaf/lsdoEZ4
|
kernel/url/edit.php
|
2318
|
<?php
//
// Created on: <04-Jul-2003 10:30:48 wy>
//
// ## BEGIN COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
// SOFTWARE NAME: eZ Publish Community Project
// SOFTWARE RELEASE: 4.2011
// COPYRIGHT NOTICE: Copyright (C) 1999-2011 eZ Systems AS
// SOFTWARE LICENSE: GNU General Public License v2.0
// NOTICE: >
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2.0 of the GNU General
// Public License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of version 2.0 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.
// ## END COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
//
/*! \file
*/
$Module = $Params['Module'];
$urlID = null;
if ( isset( $Params["ID"] ) )
$urlID = $Params["ID"];
if ( is_numeric( $urlID ) )
{
$url = eZURL::fetch( $urlID );
if ( !$url )
{
return $Module->handleError( eZError::KERNEL_NOT_AVAILABLE, 'kernel' );
}
}
else
{
return $Module->handleError( eZError::KERNEL_NOT_AVAILABLE, 'kernel' );
}
$http = eZHTTPTool::instance();
if ( $Module->isCurrentAction( 'Cancel' ) )
{
$Module->redirectToView( 'list' );
return;
}
if ( $Module->isCurrentAction( 'Store' ) )
{
if ( $http->hasPostVariable( 'link' ) )
{
$link = $http->postVariable( 'link' );
$url->setAttribute( 'url', $link );
$url->store();
eZURLObjectLink::clearCacheForObjectLink( $urlID );
}
$Module->redirectToView( 'list' );
return;
}
$Module->setTitle( "Edit link " . $url->attribute( "id" ) );
// Template handling
$tpl = eZTemplate::factory();
$tpl->setVariable( "Module", $Module );
$tpl->setVariable( "url", $url );
$Result = array();
$Result['content'] = $tpl->fetch( "design:url/edit.tpl" );
$Result['path'] = array( array( 'url' => '/url/edit/',
'text' => ezpI18n::tr( 'kernel/url', 'URL edit' ) ) );
?>
|
gpl-2.0
|
simonpoole/openstreetmap-website
|
test/controllers/issues_controller_test.rb
|
4379
|
require "test_helper"
class IssuesControllerTest < ActionController::TestCase
def test_index
# Access issues list without login
get :index
assert_response :redirect
assert_redirected_to login_path(:referer => issues_path)
# Access issues list as normal user
session[:user] = create(:user).id
get :index
assert_response :redirect
assert_redirected_to root_path
# Access issues list as administrator
session[:user] = create(:administrator_user).id
get :index
assert_response :success
# Access issues list as moderator
session[:user] = create(:moderator_user).id
get :index
assert_response :success
end
def test_show
target_user = create(:user)
issue = create(:issue, :reportable => target_user, :reported_user => target_user)
# Access issue without login
get :show, :params => { :id => issue.id }
assert_response :redirect
assert_redirected_to login_path(:referer => issue_path(issue))
# Access issue as normal user
session[:user] = create(:user).id
get :show, :params => { :id => issue.id }
assert_response :redirect
assert_redirected_to root_path
# Access issue as administrator
session[:user] = create(:administrator_user).id
get :show, :params => { :id => issue.id }
assert_response :success
# Access issue as moderator
session[:user] = create(:moderator_user).id
get :show, :params => { :id => issue.id }
assert_response :success
end
def test_resolve
target_user = create(:user)
issue = create(:issue, :reportable => target_user, :reported_user => target_user)
# Resolve issue without login
get :resolve, :params => { :id => issue.id }
assert_response :redirect
assert_redirected_to login_path(:referer => resolve_issue_path(issue))
# Resolve issue as normal user
session[:user] = create(:user).id
get :resolve, :params => { :id => issue.id }
assert_response :redirect
assert_redirected_to root_path
# Resolve issue as administrator
session[:user] = create(:administrator_user).id
get :resolve, :params => { :id => issue.id }
assert_response :redirect
assert_equal true, issue.reload.resolved?
issue.reopen!
# Resolve issue as moderator
session[:user] = create(:moderator_user).id
get :resolve, :params => { :id => issue.id }
assert_response :redirect
assert_equal true, issue.reload.resolved?
end
def test_ignore
target_user = create(:user)
issue = create(:issue, :reportable => target_user, :reported_user => target_user)
# Ignore issue without login
get :ignore, :params => { :id => issue.id }
assert_response :redirect
assert_redirected_to login_path(:referer => ignore_issue_path(issue))
# Ignore issue as normal user
session[:user] = create(:user).id
get :ignore, :params => { :id => issue.id }
assert_response :redirect
assert_redirected_to root_path
# Ignore issue as administrator
session[:user] = create(:administrator_user).id
get :ignore, :params => { :id => issue.id }
assert_response :redirect
assert_equal true, issue.reload.ignored?
issue.reopen!
# Ignore issue as moderator
session[:user] = create(:moderator_user).id
get :ignore, :params => { :id => issue.id }
assert_response :redirect
assert_equal true, issue.reload.ignored?
end
def test_reopen
target_user = create(:user)
issue = create(:issue, :reportable => target_user, :reported_user => target_user)
issue.resolve!
# Reopen issue without login
get :reopen, :params => { :id => issue.id }
assert_response :redirect
assert_redirected_to login_path(:referer => reopen_issue_path(issue))
# Reopen issue as normal user
session[:user] = create(:user).id
get :reopen, :params => { :id => issue.id }
assert_response :redirect
assert_redirected_to root_path
# Reopen issue as administrator
session[:user] = create(:administrator_user).id
get :reopen, :params => { :id => issue.id }
assert_response :redirect
assert_equal true, issue.reload.open?
issue.resolve!
# Reopen issue as moderator
session[:user] = create(:moderator_user).id
get :reopen, :params => { :id => issue.id }
assert_response :redirect
assert_equal true, issue.reload.open?
end
end
|
gpl-2.0
|
MyRealityCoding/acid-snake
|
acid-snake/src/de/myreality/acidsnake/google/DesktopInterface.java
|
2073
|
/* Acid - Provides a Java cell API to display fancy cell boxes.
* Copyright (C) 2013 Miguel Gonzalez
*
* 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
*/
package de.myreality.acidsnake.google;
/**
* Desktop implementation of the google interface
*
* @author Miguel Gonzalez <miguel-gonzalez@gmx.de>
* @since 1.0
* @version 1.0
*/
public class DesktopInterface implements GoogleInterface {
@Override
public void login() {
System.out.println("Desktop: would of logged in here");
}
@Override
public void logout() {
System.out.println("Desktop: would of logged out here");
}
@Override
public boolean getSignedIn() {
System.out.println("Desktop: getSignIn()");
return false;
}
public void submitScore(int score) {
System.out.println("Desktop: submitScore: " + score);
}
@Override
public void getScoresData() {
System.out.println("Desktop: getScoresData()");
}
@Override
public void submitAchievement(String id) {
System.out.println("Archieved: " + id);
}
@Override
public boolean isConnected() {
return false;
}
@Override
public void showAchievements() {
System.out.println("Show achievements");
}
@Override
public void showScores() {
System.out.println("Desktop: getScores()");
}
@Override
public void incrementAchievement(String id, int steps) {
System.out.println("Increment achievement with id: " + id + " by " + steps);
}
}
|
gpl-2.0
|
stereokrauts/stereoscope
|
stereoscope/src/test/java/tests/simulation/OscSurfaceChangeSimulationTest.java
|
7065
|
package tests.simulation;
import static org.junit.Assert.assertEquals;
import model.protocol.osc.DummySender;
import model.protocol.osc.IOscMessage;
import model.protocol.osc.OscAddress;
import model.protocol.osc.OscObjectUtil;
import model.protocol.osc.impl.OscMessage;
import model.surface.touchosc.TouchOscSurface;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import tests.mixer.MixerWithState;
import com.stereokrauts.stereoscope.model.messaging.dispatching.CoreMessageDispatcher;
import com.stereokrauts.stereoscope.model.messaging.dispatching.CoreMessageDispatcherFactory;
public class OscSurfaceChangeSimulationTest {
/**
* the maximum expected message delay in milliseconds
*/
private static final int MAXIMUM_MESSAGE_DELAY_MS = 60;
private static final int MAXIMUM_ERROR_PERCENTAGE = 1;
private static int errorsOccured = 0;
private static final float FLOAT_MAX_DELTA = 0.01f;
private static final int HOWMANY_CHANNELS = 72;
private static final int HOWMANY_AUXS = 24;
private static final int HOWMANY_BUSSES = 24;
private static final int HOWMANY_OUTPUTS = 24;
private static final int HOWMANY_GEQS = 8;
private static final String FILENAME = "simulation.txt";
static TouchOscSurface simulatedMessageSink;
static CoreMessageDispatcher updateManager;
static MixerWithState mixer;
private static DummySender simulatedMessageSource;
private static SimulationDataAggregator aggregator;
@Ignore
public static void init() throws Exception {
aggregator = new SimulationDataAggregator();
simulatedMessageSource = new DummySender();
simulatedMessageSink = new TouchOscSurface(false);
mixer = new MixerWithState(HOWMANY_CHANNELS, HOWMANY_AUXS, HOWMANY_BUSSES, HOWMANY_OUTPUTS, HOWMANY_GEQS);
updateManager = CoreMessageDispatcherFactory.getInstance("standard-dispatcher");
updateManager.registerObserver(mixer);
mixer.registerObserver(updateManager);
updateManager.registerObserver(simulatedMessageSink.getOscMessageSender());
simulatedMessageSink.registerObserver(updateManager);
simulatedMessageSink.connect();
final SimulationDataReader data = new SimulationDataReader(FILENAME);
SimulationMessage msg;
System.out.println("Processing " + FILENAME + "...");
int messageCounter = 0;
while ((msg = data.getNextMessage()) != null) {
final String oscAddress = msg.convertToOscAddress();
if (messageCounter % 1000 == 0) {
System.out.println("Simulation will send message " + msg.convertToOscAddress());
}
if (msg.getMessageType() == SimulationMessage.MESSAGE_TYPE_AUXMASTER ||
msg.getMessageType() == SimulationMessage.MESSAGE_TYPE_CHAUXLEVEL) {
final IOscMessage m = new OscMessage(new OscAddress("/stereoscope/system/state/selectedAux/changeTo/" + (msg.getAuxNumber() + 1)));
simulatedMessageSource.sendMessage(m);
} else if (msg.getMessageType() == SimulationMessage.MESSAGE_TYPE_GEQBAND ||
msg.getMessageType() == SimulationMessage.MESSAGE_TYPE_GEQBANDRESET ||
msg.getMessageType() == SimulationMessage.MESSAGE_TYPE_GEQFULLRESET) {
final IOscMessage m = new OscMessage(new OscAddress("/stereoscope/system/state/selectedGEQ/changeTo/" + (msg.getGeqNumber() + 1)));
simulatedMessageSource.sendMessage(m);
}
if (msg.getMessageType() == SimulationMessage.MESSAGE_TYPE_GEQFULLRESET) {
/* message has to be sent twice in (doubletouch neccesary) */
final String addr = "/stereoscope/stateful/dsp/geq/resetGeq";
IOscMessage m = new OscMessage(new OscAddress(addr));
m.add(OscObjectUtil.createOscObject(1.0f));
simulatedMessageSource.sendMessage(m);
m = new OscMessage(new OscAddress(addr));
m.add(OscObjectUtil.createOscObject(0.0f));
simulatedMessageSource.sendMessage(m);
m = new OscMessage(new OscAddress(addr));
m.add(OscObjectUtil.createOscObject(1.0f));
simulatedMessageSource.sendMessage(m);
m = new OscMessage(new OscAddress(addr));
m.add(OscObjectUtil.createOscObject(0.0f));
simulatedMessageSource.sendMessage(m);
} else {
final IOscMessage m = new OscMessage(new OscAddress(oscAddress));
m.add(OscObjectUtil.createOscObject(msg.getLevel()));
simulatedMessageSource.sendMessage(m);
}
aggregator.addMessage(msg);
if (messageCounter % 1000 == 0) {
System.out.println("Message in line: " + (messageCounter + 1) + " - type: " + msg.getMessageType());
}
messageCounter++;
//mixer.waitForMessage(msg.getMessageType());
Thread.sleep(MAXIMUM_MESSAGE_DELAY_MS);
switch(msg.getMessageType()) {
case SimulationMessage.MESSAGE_TYPE_CHLEVEL:
if (Math.abs(msg.getLevel() - mixer.getMixerState().getChannelLevel(msg.getChannelNumber())) > FLOAT_MAX_DELTA) {
foundError();
}
break;
}
}
Assert.assertTrue("Error rate within percentage", ((errorsOccured/messageCounter)*100) < MAXIMUM_ERROR_PERCENTAGE);
}
private static void foundError()
{
errorsOccured++;
}
@Test
public final void testChannelLevel() {
// assertEquals("ChannelOn message", msg.isChannelOn(), mixer.getMixerState().getChannelOnButtons(msg.getChannelNumber()));
//
// assertEquals("GeqBand message", msg.getLevel(), mixer.getMixerState().getGeqBandLevels(msg.getGeqNumber(), msg.isRightGeq(),
// msg.getBandNumber()), FLOAT_MAX_DELTA);
//
// assertEquals("GeqBandReset message", 0.0f, mixer.getMixerState().getGeqBandLevels(msg.getGeqNumber(), msg.isRightGeq(),
// msg.getBandNumber()), FLOAT_MAX_DELTA);
//
// for (int i = 0; i < mixer.getGeqCount(); i++) {
// for (int j = 0; j < MixerState.GEQ_NUMBER_OF_BANDS; j++) {
// assertEquals("GeqFullReset message (left)", 0.0f, mixer.getMixerState().getGeqBandLevels(i, false, j), FLOAT_MAX_DELTA);
// assertEquals("GeqFullReset message (right)", 0.0f, mixer.getMixerState().getGeqBandLevels(i, true, j), FLOAT_MAX_DELTA);
// }
// }
}
@Ignore
public final void testChannelAuxLevel() {
SimulationMessage msg;
msg = aggregator.getLastMessageOfType(SimulationMessage.MESSAGE_TYPE_CHAUXLEVEL);
assertEquals("ChannelAuxLevel message", msg.getLevel(), mixer.getMixerState().getChannelAuxSend(msg.getAuxNumber(), msg.getChannelNumber()), FLOAT_MAX_DELTA);
}
@Ignore
public final void testMasterLevel() {
SimulationMessage msg;
msg = aggregator.getLastMessageOfType(SimulationMessage.MESSAGE_TYPE_MASTER);
assertEquals("MasterLevel message", msg.getLevel(), mixer.getMixerState().getMasterLevel(), FLOAT_MAX_DELTA);
}
@Ignore
public final void testAuxMasterLevel() {
SimulationMessage msg;
msg = aggregator.getLastMessageOfType(SimulationMessage.MESSAGE_TYPE_AUXMASTER);
assertEquals("AuxMasterLevel message", msg.getLevel(), mixer.getMixerState().getAuxMasters(msg.getAuxNumber()), FLOAT_MAX_DELTA);
}
public void oscEvent(final IOscMessage theIOscMessage) {
// What is being sent to the surface? normaly, just ignore it...
//System.out.println("The simulation message source has received a message: " + theIOscMessage);
}
}
|
gpl-2.0
|
Distrotech/system-config-printer
|
jobviewer.py
|
97312
|
## Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Red Hat, Inc.
## Authors:
## Tim Waugh <twaugh@redhat.com>
## Jiri Popelka <jpopelka@redhat.com>
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import asyncconn
import authconn
import cups
import dbus
import dbus.glib
import dbus.service
import threading
from gi.repository import Notify
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository import Gtk
from gui import GtkGUI
import monitor
import os, shutil
from gi.repository import Pango
import pwd
import smburi
import subprocess
import sys
import time
import urllib.parse
from xml.sax import saxutils
from debug import *
import config
import statereason
import errordialogs
from functools import reduce
cups.require("1.9.47")
try:
from gi.repository import GnomeKeyring
USE_KEYRING=True
except ImportError:
USE_KEYRING=False
import gettext
gettext.install(domain=config.PACKAGE, localedir=config.localedir)
from statereason import StateReason
pkgdata = config.pkgdatadir
ICON="printer"
ICON_SIZE=22
SEARCHING_ICON="document-print-preview"
# We need to call Notify.init before we can check the server for caps
Notify.init('System Config Printer Notification')
class PrinterURIIndex:
def __init__ (self, names=[]):
self.printer = {}
self.names = names
self._collect_names ()
def _collect_names (self, connection=None):
if not self.names:
return
if not connection:
try:
c = cups.Connection ()
except RuntimeError:
return
for name in self.names:
self.add_printer (name, connection=c)
self.names = []
def add_printer (self, printer, connection=None):
try:
self._map_printer (name=printer, connection=connection)
except KeyError:
return
def update_from_attrs (self, printer, attrs):
uris = []
if 'printer-uri-supported' in attrs:
uri_supported = attrs['printer-uri-supported']
if type (uri_supported) != list:
uri_supported = [uri_supported]
uris.extend (uri_supported)
if 'notify-printer-uri' in attrs:
uris.append (attrs['notify-printer-uri'])
if 'printer-more-info' in attrs:
uris.append (attrs['printer-more-info'])
for uri in uris:
self.printer[uri] = printer
def remove_printer (self, printer):
# Remove references to this printer in the URI map.
self._collect_names ()
uris = list(self.printer.keys ())
for uri in uris:
if self.printer[uri] == printer:
del self.printer[uri]
def lookup (self, uri, connection=None):
self._collect_names ()
try:
return self.printer[uri]
except KeyError:
return self._map_printer (uri=uri, connection=connection)
def all_printer_names (self):
self._collect_names ()
return set (self.printer.values ())
def lookup_cached_by_name (self, name):
self._collect_names ()
for uri, printer in self.printer.items ():
if printer == name:
return uri
raise KeyError
def _map_printer (self, uri=None, name=None, connection=None):
try:
if connection == None:
connection = cups.Connection ()
r = ['printer-name', 'printer-uri-supported', 'printer-more-info']
if uri != None:
attrs = connection.getPrinterAttributes (uri=uri,
requested_attributes=r)
else:
attrs = connection.getPrinterAttributes (name,
requested_attributes=r)
except RuntimeError:
# cups.Connection() failed
raise KeyError
except cups.IPPError:
# URI not known.
raise KeyError
name = attrs['printer-name']
self.update_from_attrs (name, attrs)
if uri != None:
self.printer[uri] = name
return name
class CancelJobsOperation(GObject.GObject):
__gsignals__ = {
'destroy': (GObject.SignalFlags.RUN_LAST, None, ()),
'job-deleted': (GObject.SignalFlags.RUN_LAST, None, (int,)),
'ipp-error': (GObject.SignalFlags.RUN_LAST, None,
(int, GObject.TYPE_PYOBJECT)),
'finished': (GObject.SignalFlags.RUN_LAST, None, ())
}
def __init__ (self, parent, host, port, encryption, jobids, purge_job):
GObject.GObject.__init__ (self)
self.jobids = list (jobids)
self.purge_job = purge_job
self.host = host
self.port = port
self.encryption = encryption
if purge_job:
if len(self.jobids) > 1:
dialog_title = _("Delete Jobs")
dialog_label = _("Do you really want to delete these jobs?")
else:
dialog_title = _("Delete Job")
dialog_label = _("Do you really want to delete this job?")
else:
if len(self.jobids) > 1:
dialog_title = _("Cancel Jobs")
dialog_label = _("Do you really want to cancel these jobs?")
else:
dialog_title = _("Cancel Job")
dialog_label = _("Do you really want to cancel this job?")
dialog = Gtk.Dialog (title=dialog_title, transient_for=parent,
modal=True, destroy_with_parent=True)
dialog.add_buttons (_("Keep Printing"), Gtk.ResponseType.NO,
dialog_title, Gtk.ResponseType.YES)
dialog.set_default_response (Gtk.ResponseType.NO)
dialog.set_border_width (6)
dialog.set_resizable (False)
hbox = Gtk.HBox.new (False, 12)
image = Gtk.Image ()
image.set_from_stock (Gtk.STOCK_DIALOG_QUESTION, Gtk.IconSize.DIALOG)
image.set_alignment (0.0, 0.0)
hbox.pack_start (image, False, False, 0)
label = Gtk.Label(label=dialog_label)
label.set_line_wrap (True)
label.set_alignment (0.0, 0.0)
hbox.pack_start (label, False, False, 0)
dialog.vbox.pack_start (hbox, False, False, 0)
dialog.connect ("response", self.on_job_cancel_prompt_response)
dialog.connect ("delete-event", self.on_job_cancel_prompt_delete)
dialog.show_all ()
self.dialog = dialog
self.connection = None
debugprint ("+%s" % self)
def __del__ (self):
debugprint ("-%s" % self)
def do_destroy (self):
if self.connection:
self.connection.destroy ()
self.connection = None
if self.dialog:
self.dialog.destroy ()
self.dialog = None
debugprint ("DESTROY: %s" % self)
def destroy (self):
self.emit ('destroy')
def on_job_cancel_prompt_delete (self, dialog, event):
self.on_job_cancel_prompt_response (dialog, Gtk.ResponseType.NO)
def on_job_cancel_prompt_response (self, dialog, response):
dialog.destroy ()
self.dialog = None
if response != Gtk.ResponseType.YES:
self.emit ('finished')
return
if len(self.jobids) == 0:
self.emit ('finished')
return
asyncconn.Connection (host=self.host,
port=self.port,
encryption=self.encryption,
reply_handler=self._connected,
error_handler=self._connect_failed)
def _connect_failed (self, connection, exc):
debugprint ("CancelJobsOperation._connect_failed %s:%s" % (connection, repr (exc)))
def _connected (self, connection, result):
self.connection = connection
if self.purge_job:
operation = _("deleting job")
else:
operation = _("canceling job")
self.connection._begin_operation (operation)
self.connection.cancelJob (self.jobids[0], self.purge_job,
reply_handler=self.cancelJob_finish,
error_handler=self.cancelJob_error)
def cancelJob_error (self, connection, exc):
debugprint ("cancelJob_error %s:%s" % (connection, repr (exc)))
if type (exc) == cups.IPPError:
(e, m) = exc.args
if (e != cups.IPP_NOT_POSSIBLE and
e != cups.IPP_NOT_FOUND):
self.emit ('ipp-error', self.jobids[0], exc)
self.cancelJob_finish(connection, None)
else:
self.connection._end_operation ()
self.connection.destroy ()
self.connection = None
self.emit ('ipp-error', self.jobids[0], exc)
# Give up.
self.emit ('finished')
return
def cancelJob_finish (self, connection, result):
debugprint ("cancelJob_finish %s:%s" % (connection, repr (result)))
self.emit ('job-deleted', self.jobids[0])
del self.jobids[0]
if not self.jobids:
# Last job canceled.
self.connection._end_operation ()
self.connection.destroy ()
self.connection = None
self.emit ('finished')
return
else:
# there are other jobs to cancel/delete
connection.cancelJob (self.jobids[0], self.purge_job,
reply_handler=self.cancelJob_finish,
error_handler=self.cancelJob_error)
class JobViewer (GtkGUI):
required_job_attributes = set(['job-k-octets',
'job-name',
'job-originating-user-name',
'job-printer-uri',
'job-state',
'time-at-creation',
'auth-info-required',
'job-preserved'])
__gsignals__ = {
'finished': (GObject.SignalFlags.RUN_LAST, None, ())
}
def __init__(self, bus=None, loop=None,
applet=False, suppress_icon_hide=False,
my_jobs=True, specific_dests=None,
parent=None):
GObject.GObject.__init__ (self)
self.loop = loop
self.applet = applet
self.suppress_icon_hide = suppress_icon_hide
self.my_jobs = my_jobs
self.specific_dests = specific_dests
notify_caps = Notify.get_server_caps ()
self.notify_has_actions = "actions" in notify_caps
self.notify_has_persistence = "persistence" in notify_caps
self.jobs = {}
self.jobiters = {}
self.jobids = []
self.jobs_attrs = {} # dict of jobid->(GtkListStore, page_index)
self.active_jobs = set() # of job IDs
self.stopped_job_prompts = set() # of job IDs
self.printer_state_reasons = {}
self.num_jobs_when_hidden = 0
self.connecting_to_device = {} # dict of printer->time first seen
self.state_reason_notifications = {}
self.auth_info_dialogs = {} # by job ID
self.job_creation_times_timer = None
self.new_printer_notifications = {}
self.completed_job_notifications = {}
self.authenticated_jobs = set() # of job IDs
self.ops = []
self.getWidgets ({"JobsWindow":
["JobsWindow",
"treeview",
"statusbar",
"toolbar"],
"statusicon_popupmenu":
["statusicon_popupmenu"]},
domain=config.PACKAGE)
job_action_group = Gtk.ActionGroup (name="JobActionGroup")
job_action_group.add_actions ([
("cancel-job", Gtk.STOCK_CANCEL, _("_Cancel"), None,
_("Cancel selected jobs"), self.on_job_cancel_activate),
("delete-job", Gtk.STOCK_DELETE, _("_Delete"), None,
_("Delete selected jobs"), self.on_job_delete_activate),
("hold-job", Gtk.STOCK_MEDIA_PAUSE, _("_Hold"), None,
_("Hold selected jobs"), self.on_job_hold_activate),
("release-job", Gtk.STOCK_MEDIA_PLAY, _("_Release"), None,
_("Release selected jobs"), self.on_job_release_activate),
("reprint-job", Gtk.STOCK_REDO, _("Re_print"), None,
_("Reprint selected jobs"), self.on_job_reprint_activate),
("retrieve-job", Gtk.STOCK_SAVE_AS, _("Re_trieve"), None,
_("Retrieve selected jobs"), self.on_job_retrieve_activate),
("move-job", None, _("_Move To"), None, None, None),
("authenticate-job", None, _("_Authenticate"), None, None,
self.on_job_authenticate_activate),
("job-attributes", None, _("_View Attributes"), None, None,
self.on_job_attributes_activate),
("close", Gtk.STOCK_CLOSE, None, "<ctrl>w",
_("Close this window"), self.on_delete_event)
])
self.job_ui_manager = Gtk.UIManager ()
self.job_ui_manager.insert_action_group (job_action_group, -1)
self.job_ui_manager.add_ui_from_string (
"""
<ui>
<accelerator action="cancel-job"/>
<accelerator action="delete-job"/>
<accelerator action="hold-job"/>
<accelerator action="release-job"/>
<accelerator action="reprint-job"/>
<accelerator action="retrieve-job"/>
<accelerator action="move-job"/>
<accelerator action="authenticate-job"/>
<accelerator action="job-attributes"/>
<accelerator action="close"/>
</ui>
"""
)
self.job_ui_manager.ensure_update ()
self.JobsWindow.add_accel_group (self.job_ui_manager.get_accel_group ())
self.job_context_menu = Gtk.Menu ()
for action_name in ["cancel-job",
"delete-job",
"hold-job",
"release-job",
"reprint-job",
"retrieve-job",
"move-job",
None,
"authenticate-job",
"job-attributes"]:
if not action_name:
item = Gtk.SeparatorMenuItem ()
else:
action = job_action_group.get_action (action_name)
action.set_sensitive (False)
item = action.create_menu_item ()
if action_name == 'move-job':
self.move_job_menuitem = item
printers = Gtk.Menu ()
item.set_submenu (printers)
item.show ()
self.job_context_menu.append (item)
for action_name in ["cancel-job",
"delete-job",
"hold-job",
"release-job",
"reprint-job",
"retrieve-job",
"close"]:
action = job_action_group.get_action (action_name)
action.set_sensitive (action_name == "close")
action.set_is_important (action_name == "close")
item = action.create_tool_item ()
item.show ()
self.toolbar.insert (item, -1)
for skip, ellipsize, name, setter in \
[(False, False, _("Job"), self._set_job_job_number_text),
(True, False, _("User"), self._set_job_user_text),
(False, True, _("Document"), self._set_job_document_text),
(False, True, _("Printer"), self._set_job_printer_text),
(False, False, _("Size"), self._set_job_size_text)]:
if applet and skip:
# Skip the user column when running as applet.
continue
cell = Gtk.CellRendererText()
if ellipsize:
# Ellipsize the 'Document' and 'Printer' columns.
cell.set_property ("ellipsize", Pango.EllipsizeMode.END)
cell.set_property ("width-chars", 20)
column = Gtk.TreeViewColumn(name, cell)
column.set_cell_data_func (cell, setter, None)
column.set_resizable(True)
self.treeview.append_column(column)
cell = Gtk.CellRendererText ()
column = Gtk.TreeViewColumn (_("Time submitted"), cell, text=1)
column.set_resizable (True)
self.treeview.append_column (column)
column = Gtk.TreeViewColumn (_("Status"))
icon = Gtk.CellRendererPixbuf ()
column.pack_start (icon, False)
text = Gtk.CellRendererText ()
text.set_property ("ellipsize", Pango.EllipsizeMode.END)
text.set_property ("width-chars", 20)
column.pack_start (text, True)
column.set_cell_data_func (icon, self._set_job_status_icon, None)
column.set_cell_data_func (text, self._set_job_status_text, None)
self.treeview.append_column (column)
self.store = Gtk.TreeStore(int, str)
self.store.set_sort_column_id (0, Gtk.SortType.DESCENDING)
self.treeview.set_model(self.store)
self.treeview.set_rules_hint (True)
self.selection = self.treeview.get_selection()
self.selection.set_mode(Gtk.SelectionMode.MULTIPLE)
self.selection.connect('changed', self.on_selection_changed)
self.treeview.connect ('button_release_event',
self.on_treeview_button_release_event)
self.treeview.connect ('popup-menu', self.on_treeview_popup_menu)
self.JobsWindow.set_icon_name (ICON)
self.JobsWindow.hide ()
if specific_dests:
the_dests = reduce (lambda x, y: x + ", " + y, specific_dests)
if my_jobs:
if specific_dests:
title = _("my jobs on %s") % the_dests
else:
title = _("my jobs")
else:
if specific_dests:
title = "%s" % the_dests
else:
title = _("all jobs")
self.JobsWindow.set_title (_("Document Print Status (%s)") % title)
if parent:
self.JobsWindow.set_transient_for (parent)
def load_icon(theme, icon):
try:
pixbuf = theme.load_icon (icon, ICON_SIZE, 0)
except GObject.GError:
debugprint ("No %s icon available" % icon)
# Just create an empty pixbuf.
pixbuf = GdkPixbuf.Pixbuf.new (GdkPixbuf.Colorspace.RGB,
True, 8, ICON_SIZE, ICON_SIZE)
pixbuf.fill (0)
return pixbuf
theme = Gtk.IconTheme.get_default ()
self.icon_jobs = load_icon (theme, ICON)
self.icon_jobs_processing = load_icon (theme, "printer-printing")
self.icon_no_jobs = self.icon_jobs.copy ()
self.icon_no_jobs.fill (0)
self.icon_jobs.composite (self.icon_no_jobs,
0, 0,
self.icon_no_jobs.get_width(),
self.icon_no_jobs.get_height(),
0, 0,
1.0, 1.0,
GdkPixbuf.InterpType.BILINEAR,
127)
if self.applet and not self.notify_has_persistence:
self.statusicon = Gtk.StatusIcon ()
self.statusicon.set_from_pixbuf (self.icon_no_jobs)
self.statusicon.connect ('activate', self.toggle_window_display)
self.statusicon.connect ('popup-menu', self.on_icon_popupmenu)
self.statusicon.set_visible (False)
# D-Bus
if bus == None:
bus = dbus.SystemBus ()
self.connect_signals ()
self.set_process_pending (True)
self.host = cups.getServer ()
self.port = cups.getPort ()
self.encryption = cups.getEncryption ()
self.monitor = monitor.Monitor (bus=bus, my_jobs=my_jobs,
specific_dests=specific_dests,
host=self.host, port=self.port,
encryption=self.encryption)
self.monitor.connect ('refresh', self.on_refresh)
self.monitor.connect ('job-added', self.job_added)
self.monitor.connect ('job-event', self.job_event)
self.monitor.connect ('job-removed', self.job_removed)
self.monitor.connect ('state-reason-added', self.state_reason_added)
self.monitor.connect ('state-reason-removed', self.state_reason_removed)
self.monitor.connect ('still-connecting', self.still_connecting)
self.monitor.connect ('now-connected', self.now_connected)
self.monitor.connect ('printer-added', self.printer_added)
self.monitor.connect ('printer-event', self.printer_event)
self.monitor.connect ('printer-removed', self.printer_removed)
self.monitor.refresh ()
self.my_monitor = None
if not my_jobs:
self.my_monitor = monitor.Monitor(bus=bus, my_jobs=True,
host=self.host, port=self.port,
encryption=self.encryption)
self.my_monitor.connect ('job-added', self.job_added)
self.my_monitor.connect ('job-event', self.job_event)
self.my_monitor.refresh ()
if not self.applet:
self.JobsWindow.show ()
self.JobsAttributesWindow = Gtk.Window()
self.JobsAttributesWindow.set_title (_("Job attributes"))
self.JobsAttributesWindow.set_position(Gtk.WindowPosition.MOUSE)
self.JobsAttributesWindow.set_default_size(600, 600)
self.JobsAttributesWindow.set_transient_for (self.JobsWindow)
self.JobsAttributesWindow.connect("delete_event",
self.job_attributes_on_delete_event)
self.JobsAttributesWindow.add_accel_group (self.job_ui_manager.get_accel_group ())
attrs_action_group = Gtk.ActionGroup (name="AttrsActionGroup")
attrs_action_group.add_actions ([
("close", Gtk.STOCK_CLOSE, None, "<ctrl>w",
_("Close this window"), self.job_attributes_on_delete_event)
])
self.attrs_ui_manager = Gtk.UIManager ()
self.attrs_ui_manager.insert_action_group (attrs_action_group, -1)
self.attrs_ui_manager.add_ui_from_string (
"""
<ui>
<accelerator action="close"/>
</ui>
"""
)
self.attrs_ui_manager.ensure_update ()
self.JobsAttributesWindow.add_accel_group (self.attrs_ui_manager.get_accel_group ())
vbox = Gtk.VBox ()
self.JobsAttributesWindow.add (vbox)
toolbar = Gtk.Toolbar ()
action = self.attrs_ui_manager.get_action ("/close")
item = action.create_tool_item ()
item.set_is_important (True)
toolbar.insert (item, 0)
vbox.pack_start (toolbar, False, False, 0)
self.notebook = Gtk.Notebook()
vbox.pack_start (self.notebook, True, True, 0)
def cleanup (self):
self.monitor.cleanup ()
if self.my_monitor:
self.my_monitor.cleanup ()
self.JobsWindow.hide ()
# Close any open notifications.
for l in [self.new_printer_notifications.values (),
self.state_reason_notifications.values ()]:
for notification in l:
if getattr (notification, 'closed', None) != True:
try:
notification.close ()
except GLib.GError:
# Can fail if the notification wasn't even shown
# yet (as in bug #571603).
pass
notification.closed = True
if self.job_creation_times_timer != None:
GLib.source_remove (self.job_creation_times_timer)
self.job_creation_times_timer = None
for op in self.ops:
op.destroy ()
if self.applet and not self.notify_has_persistence:
self.statusicon.set_visible (False)
self.emit ('finished')
def set_process_pending (self, whether):
self.process_pending_events = whether
def on_delete_event(self, *args):
if self.applet or not self.loop:
self.JobsWindow.hide ()
self.JobsWindow.visible = False
if not self.applet:
# Being run from main app, not applet
self.cleanup ()
else:
self.loop.quit ()
return True
def job_attributes_on_delete_event(self, widget, event=None):
for page in range(self.notebook.get_n_pages()):
self.notebook.remove_page(-1)
self.jobs_attrs = {}
self.JobsAttributesWindow.hide()
return True
def show_IPP_Error(self, exception, message):
return errordialogs.show_IPP_Error (exception, message, self.JobsWindow)
def toggle_window_display(self, icon, force_show=False):
visible = getattr (self.JobsWindow, 'visible', None)
if force_show:
visible = False
if self.notify_has_persistence:
if visible:
self.JobsWindow.hide ()
else:
self.JobsWindow.show ()
else:
if visible:
w = self.JobsWindow.get_window()
aw = self.JobsAttributesWindow.get_window()
(loc, s, area, o) = self.statusicon.get_geometry ()
if loc:
w.set_skip_taskbar_hint (True)
if aw != None:
aw.set_skip_taskbar_hint (True)
self.JobsWindow.iconify ()
else:
self.JobsWindow.set_visible (False)
else:
self.JobsWindow.present ()
self.JobsWindow.set_skip_taskbar_hint (False)
aw = self.JobsAttributesWindow.get_window()
if aw != None:
aw.set_skip_taskbar_hint (False)
self.JobsWindow.visible = not visible
def on_show_completed_jobs_clicked(self, toggletoolbutton):
if toggletoolbutton.get_active():
which_jobs = "all"
else:
which_jobs = "not-completed"
self.monitor.refresh(which_jobs=which_jobs, refresh_all=False)
if self.my_monitor:
self.my_monitor.refresh(which_jobs=which_jobs, refresh_all=False)
def update_job_creation_times(self):
now = time.time ()
need_update = False
for job, data in self.jobs.items():
t = _("Unknown")
if 'time-at-creation' in data:
created = data['time-at-creation']
ago = now - created
need_update = True
if ago < 2 * 60:
t = _("a minute ago")
elif ago < 60 * 60:
mins = int (ago / 60)
t = _("%d minutes ago") % mins
elif ago < 24 * 60 * 60:
hours = int (ago / (60 * 60))
if hours == 1:
t = _("an hour ago")
else:
t = _("%d hours ago") % hours
elif ago < 7 * 24 * 60 * 60:
days = int (ago / (24 * 60 * 60))
if days == 1:
t = _("yesterday")
else:
t = _("%d days ago") % days
elif ago < 6 * 7 * 24 * 60 * 60:
weeks = int (ago / (7 * 24 * 60 * 60))
if weeks == 1:
t = _("last week")
else:
t = _("%d weeks ago") % weeks
else:
need_update = False
t = time.strftime ("%B %Y", time.localtime (created))
if job in self.jobiters:
iter = self.jobiters[job]
self.store.set_value (iter, 1, t)
if need_update and not self.job_creation_times_timer:
def update_times_with_locking ():
Gdk.threads_enter ()
ret = self.update_job_creation_times ()
Gdk.threads_leave ()
return ret
t = GLib.timeout_add_seconds (60, update_times_with_locking)
self.job_creation_times_timer = t
if not need_update:
if self.job_creation_times_timer:
GLib.source_remove (self.job_creation_times_timer)
self.job_creation_times_timer = None
# Return code controls whether the timeout will recur.
return need_update
def print_error_dialog_response(self, dialog, response, jobid):
dialog.hide ()
dialog.destroy ()
self.stopped_job_prompts.remove (jobid)
if response == Gtk.ResponseType.NO:
# Diagnose
if 'troubleshooter' not in self.__dict__:
import troubleshoot
troubleshooter = troubleshoot.run (self.on_troubleshoot_quit)
self.troubleshooter = troubleshooter
def on_troubleshoot_quit(self, troubleshooter):
del self.troubleshooter
def add_job (self, job, data, connection=None):
self.update_job (job, data, connection=connection)
# There may have been an error fetching additional attributes,
# in which case we need to give up.
if job not in self.jobs:
return
store = self.store
iter = self.store.append (None)
store.set_value (iter, 0, job)
debugprint ("Job %d added" % job)
self.jobiters[job] = iter
range = self.treeview.get_visible_range ()
if range != None:
(start, end) = range
if (self.store.get_sort_column_id () == (0,
Gtk.SortType.DESCENDING) and
start == Gtk.TreePath(1)):
# This job was added job above the visible range, and
# we are sorting by descending job ID. Scroll to it.
self.treeview.scroll_to_cell (Gtk.TreePath(), None,
False, 0.0, 0.0)
if not self.job_creation_times_timer:
def start_updating_job_creation_times():
Gdk.threads_enter ()
self.update_job_creation_times ()
Gdk.threads_leave ()
return False
GLib.timeout_add (500, start_updating_job_creation_times)
def update_monitor (self):
self.monitor.update ()
if self.my_monitor:
self.my_monitor.update ()
def update_job (self, job, data, connection=None):
# Fetch required attributes for this job if they are missing.
r = self.required_job_attributes - set (data.keys ())
# If we are showing attributes of this job at this moment, update them.
if job in self.jobs_attrs:
self.update_job_attributes_viewer(job)
if r:
attrs = None
try:
if connection == None:
connection = cups.Connection (host=self.host,
port=self.port,
encryption=self.encryption)
debugprint ("requesting %s" % r)
r = list (r)
attrs = connection.getJobAttributes (job,
requested_attributes=r)
except RuntimeError:
pass
except AttributeError:
pass
except cups.IPPError:
# someone else may have purged the job
return
if attrs:
data.update (attrs)
self.jobs[job] = data
job_requires_auth = False
try:
jstate = data.get ('job-state', cups.IPP_JOB_PROCESSING)
s = int (jstate)
if s in [cups.IPP_JOB_HELD, cups.IPP_JOB_STOPPED]:
jattrs = ['job-state', 'job-hold-until', 'job-printer-uri']
pattrs = ['auth-info-required', 'device-uri']
# The current job-printer-uri may differ from the one that
# is returned when we request it over the connection.
# So while we use it to query the printer attributes we
# Update it afterwards to make sure that we really
# have the one cups uses in the job attributes.
uri = data.get ('job-printer-uri')
c = authconn.Connection (self.JobsWindow,
host=self.host,
port=self.port,
encryption=self.encryption)
attrs = c.getPrinterAttributes (uri = uri,
requested_attributes=pattrs)
try:
auth_info_required = attrs['auth-info-required']
except KeyError:
debugprint ("No auth-info-required attribute; "
"guessing instead")
auth_info_required = ['username', 'password']
if not isinstance (auth_info_required, list):
auth_info_required = [auth_info_required]
attrs['auth-info-required'] = auth_info_required
data.update (attrs)
attrs = c.getJobAttributes (job,
requested_attributes=jattrs)
data.update (attrs)
jstate = data.get ('job-state', cups.IPP_JOB_PROCESSING)
s = int (jstate)
except ValueError:
pass
except RuntimeError:
pass
except cups.IPPError:
pass
# Invalidate the cached status description and redraw the treeview.
try:
del data['_status_text']
except KeyError:
pass
self.treeview.queue_draw ()
# Check whether authentication is required.
job_requires_auth = (s == cups.IPP_JOB_HELD and
data.get ('job-hold-until', 'none') ==
'auth-info-required')
if job_requires_auth:
# Try to get the authentication information. If we are not
# running as an applet just try to get the information silently
# and not prompt the user.
self.get_authentication (job, data.get ('device-uri'),
data.get ('job-printer-uri'),
data.get ('auth-info-required', []),
self.applet)
self.submenu_set = False
self.update_sensitivity ()
def get_authentication (self, job, device_uri, printer_uri,
auth_info_required, show_dialog):
# Check if we have requested authentication for this job already
if job not in self.auth_info_dialogs:
try:
cups.require ("1.9.37")
except:
debugprint ("Authentication required but "
"authenticateJob() not available")
return
# Find out which auth-info is required.
try_keyring = USE_KEYRING
informational_attrs = dict()
auth_info = None
if try_keyring and 'password' in auth_info_required:
(scheme, rest) = urllib.parse.splittype (device_uri)
if scheme == 'smb':
uri = smburi.SMBURI (uri=device_uri)
(group, server, share,
user, password) = uri.separate ()
informational_attrs["domain"] = str (group)
else:
(serverport, rest) = urllib.parse.splithost (rest)
if serverport == None:
server = None
else:
(server, port) = urllib.parse.splitnport (serverport)
if scheme == None or server == None:
try_keyring = False
else:
informational_attrs.update ({ "server": str (server.lower ()),
"protocol": str (scheme)})
if job in self.authenticated_jobs:
# We've already tried to authenticate this job before.
try_keyring = False
# To increase compatibility and resolve problems with
# multiple printers on one host we use the printers URI
# as the identifying attribute. Versions <= 1.4.4 used
# a combination of domain / server / protocol instead.
# The old attributes are still used as a fallback for identifying
# the secret but are otherwise only informational.
identifying_attrs = { "uri": str (printer_uri) }
if try_keyring and 'password' in auth_info_required:
type = GnomeKeyring.ItemType.NETWORK_PASSWORD
for keyring_attrs in [identifying_attrs, informational_attrs]:
attrs = GnomeKeyring.Attribute.list_new ()
for key, val in keyring_attrs.items ():
GnomeKeyring.Attribute.list_append_string (attrs,
key,
val)
(result, items) = GnomeKeyring.find_items_sync (type,
attrs)
if result == GnomeKeyring.Result.OK:
auth_info = ['' for x in auth_info_required]
ind = auth_info_required.index ('username')
for attr in GnomeKeyring.attribute_list_to_glist (
items[0].attributes):
# It might be safe to assume here that the
# user element is always the second item in a
# NETWORK_PASSWORD element but lets make sure.
if attr.name == 'user':
auth_info[ind] = attr.get_string()
break
else:
debugprint ("Did not find username keyring "
"attributes.")
ind = auth_info_required.index ('password')
auth_info[ind] = items[0].secret
break
else:
debugprint ("Failed to find secret in keyring.")
if try_keyring:
try:
c = authconn.Connection (self.JobsWindow,
host=self.host,
port=self.port,
encryption=self.encryption)
except RuntimeError:
try_keyring = False
if try_keyring and auth_info != None:
try:
c._begin_operation (_("authenticating job"))
c.authenticateJob (job, auth_info)
c._end_operation ()
self.update_monitor ()
debugprint ("Automatically authenticated job %d" % job)
self.authenticated_jobs.add (job)
return
except cups.IPPError:
c._end_operation ()
nonfatalException ()
return
except:
c._end_operation ()
nonfatalException ()
if auth_info_required and show_dialog:
username = pwd.getpwuid (os.getuid ())[0]
keyring_attrs = informational_attrs.copy()
keyring_attrs.update(identifying_attrs)
keyring_attrs["user"] = str (username)
self.display_auth_info_dialog (job, keyring_attrs)
def display_auth_info_dialog (self, job, keyring_attrs=None):
data = self.jobs[job]
auth_info_required = data['auth-info-required']
dialog = authconn.AuthDialog (auth_info_required=auth_info_required,
allow_remember=USE_KEYRING)
dialog.keyring_attrs = keyring_attrs
dialog.auth_info_required = auth_info_required
dialog.set_position (Gtk.WindowPosition.CENTER)
# Pre-fill 'username' field.
auth_info = ['' for x in auth_info_required]
username = pwd.getpwuid (os.getuid ())[0]
if 'username' in auth_info_required:
try:
ind = auth_info_required.index ('username')
auth_info[ind] = username
dialog.set_auth_info (auth_info)
except:
nonfatalException ()
# Focus on the first empty field.
index = 0
for field in auth_info_required:
if auth_info[index] == '':
dialog.field_grab_focus (field)
break
index += 1
dialog.set_prompt (_("Authentication required for "
"printing document `%s' (job %d)") %
(data.get('job-name', _("Unknown")),
job))
self.auth_info_dialogs[job] = dialog
dialog.connect ('response', self.auth_info_dialog_response)
dialog.connect ('delete-event', self.auth_info_dialog_delete)
dialog.job_id = job
dialog.show_all ()
dialog.set_keep_above (True)
dialog.show_now ()
def auth_info_dialog_delete (self, dialog, event):
self.auth_info_dialog_response (dialog, Gtk.ResponseType.CANCEL)
def auth_info_dialog_response (self, dialog, response):
jobid = dialog.job_id
del self.auth_info_dialogs[jobid]
if response != Gtk.ResponseType.OK:
dialog.destroy ()
return
auth_info = dialog.get_auth_info ()
try:
c = authconn.Connection (self.JobsWindow,
host=self.host,
port=self.port,
encryption=self.encryption)
except RuntimeError:
debugprint ("Error connecting to CUPS for authentication")
return
remember = False
c._begin_operation (_("authenticating job"))
try:
c.authenticateJob (jobid, auth_info)
remember = dialog.get_remember_password ()
self.authenticated_jobs.add (jobid)
self.update_monitor ()
except cups.IPPError as e:
(e, m) = e.args
self.show_IPP_Error (e, m)
c._end_operation ()
if remember:
try:
(result, keyring) = GnomeKeyring.get_default_keyring_sync ()
type = GnomeKeyring.ItemType.NETWORK_PASSWORD
keyring_attrs = getattr (dialog,
"keyring_attrs",
None)
auth_info_required = getattr (dialog,
"auth_info_required",
None)
if keyring_attrs != None and auth_info_required != None:
try:
ind = auth_info_required.index ('username')
keyring_attrs['user'] = auth_info[ind]
except IndexError:
pass
name = "%s@%s (%s)" % (keyring_attrs.get ("user"),
keyring_attrs.get ("server"),
keyring_attrs.get ("protocol"))
ind = auth_info_required.index ('password')
secret = auth_info[ind]
attrs = GnomeKeyring.Attribute.list_new ()
for key, val in keyring_attrs.items ():
GnomeKeyring.Attribute.list_append_string (attrs,
key,
val)
(result, id) = GnomeKeyring.item_create_sync (keyring,
type,
name,
attrs,
secret,
True)
debugprint ("keyring: created id %d for %s" % (id, name))
except:
nonfatalException ()
dialog.destroy ()
def set_statusicon_visibility (self):
if not self.applet:
return
if self.suppress_icon_hide:
# Avoid hiding the icon if we've been woken up to notify
# about a new printer.
self.suppress_icon_hide = False
return
open_notifications = len (self.new_printer_notifications.keys ())
open_notifications += len (self.completed_job_notifications.keys ())
for reason, notification in self.state_reason_notifications.items():
if getattr (notification, 'closed', None) != True:
open_notifications += 1
num_jobs = len (self.active_jobs)
debugprint ("open notifications: %d" % open_notifications)
debugprint ("num_jobs: %d" % num_jobs)
debugprint ("num_jobs_when_hidden: %d" % self.num_jobs_when_hidden)
if self.notify_has_persistence:
return
# Don't handle tooltips during the mainloop recursion at the
# end of this function as it seems to cause havoc (bug #664044,
# bug #739745).
self.statusicon.set_has_tooltip (False)
self.statusicon.set_visible (open_notifications > 0 or
num_jobs > self.num_jobs_when_hidden)
# Let the icon show/hide itself before continuing.
while self.process_pending_events and Gtk.events_pending ():
Gtk.main_iteration ()
def on_treeview_popup_menu (self, treeview):
event = Gdk.Event (Gdk.EventType.NOTHING)
self.show_treeview_popup_menu (treeview, event, 0)
def on_treeview_button_release_event(self, treeview, event):
if event.button == 3:
self.show_treeview_popup_menu (treeview, event, event.button)
def update_sensitivity (self, selection = None):
if (selection is None):
selection = self.treeview.get_selection ()
(model, pathlist) = selection.get_selected_rows()
cancel = self.job_ui_manager.get_action ("/cancel-job")
delete = self.job_ui_manager.get_action ("/delete-job")
hold = self.job_ui_manager.get_action ("/hold-job")
release = self.job_ui_manager.get_action ("/release-job")
reprint = self.job_ui_manager.get_action ("/reprint-job")
retrieve = self.job_ui_manager.get_action ("/retrieve-job")
authenticate = self.job_ui_manager.get_action ("/authenticate-job")
attributes = self.job_ui_manager.get_action ("/job-attributes")
move = self.job_ui_manager.get_action ("/move-job")
if len (pathlist) == 0:
for widget in [cancel, delete, hold, release, reprint, retrieve,
move, authenticate, attributes]:
widget.set_sensitive (False)
return
cancel_sensitive = True
hold_sensitive = True
release_sensitive = True
reprint_sensitive = True
authenticate_sensitive = True
move_sensitive = False
other_printers = self.printer_uri_index.all_printer_names ()
job_printers = dict()
self.jobids = []
for path in pathlist:
iter = self.store.get_iter (path)
jobid = self.store.get_value (iter, 0)
self.jobids.append(jobid)
job = self.jobs[jobid]
if 'job-state' in job:
s = job['job-state']
if s >= cups.IPP_JOB_CANCELED:
cancel_sensitive = False
if s != cups.IPP_JOB_PENDING:
hold_sensitive = False
if s != cups.IPP_JOB_HELD:
release_sensitive = False
if (not job.get('job-preserved', False)):
reprint_sensitive = False
if (job.get ('job-state',
cups.IPP_JOB_CANCELED) != cups.IPP_JOB_HELD or
job.get ('job-hold-until', 'none') != 'auth-info-required'):
authenticate_sensitive = False
uri = job.get ('job-printer-uri', None)
if uri:
try:
printer = self.printer_uri_index.lookup (uri)
except KeyError:
printer = uri
job_printers[printer] = uri
if len (job_printers.keys ()) == 1:
try:
other_printers.remove (list(job_printers.keys ())[0])
except KeyError:
pass
if len (other_printers) > 0:
printers_menu = Gtk.Menu ()
other_printers = list (other_printers)
other_printers.sort ()
for printer in other_printers:
try:
uri = self.printer_uri_index.lookup_cached_by_name (printer)
except KeyError:
uri = None
menuitem = Gtk.MenuItem (label=printer)
menuitem.set_sensitive (uri != None)
menuitem.show ()
self._submenu_connect_hack (menuitem,
self.on_job_move_activate,
uri)
printers_menu.append (menuitem)
self.move_job_menuitem.set_submenu (printers_menu)
move_sensitive = True
cancel.set_sensitive(cancel_sensitive)
delete.set_sensitive(not cancel_sensitive)
hold.set_sensitive(hold_sensitive)
release.set_sensitive(release_sensitive)
reprint.set_sensitive(reprint_sensitive)
retrieve.set_sensitive(reprint_sensitive)
move.set_sensitive (move_sensitive)
authenticate.set_sensitive(authenticate_sensitive)
attributes.set_sensitive(True)
def on_selection_changed (self, selection):
self.update_sensitivity (selection)
def show_treeview_popup_menu (self, treeview, event, event_button):
# Right-clicked.
self.job_context_menu.popup (None, None, None, None, event_button,
event.get_time ())
def on_icon_popupmenu(self, icon, button, time):
self.statusicon_popupmenu.popup (None, None, None, None, button, time)
def on_icon_hide_activate(self, menuitem):
self.num_jobs_when_hidden = len (self.jobs.keys ())
self.set_statusicon_visibility ()
def on_icon_configure_printers_activate(self, menuitem):
env = {}
for name, value in os.environ.items ():
if name == "SYSTEM_CONFIG_PRINTER_UI":
continue
env[name] = value
p = subprocess.Popen ([ "system-config-printer" ],
close_fds=True, env=env)
GLib.timeout_add_seconds (10, self.poll_subprocess, p)
def poll_subprocess(self, process):
returncode = process.poll ()
return returncode == None
def on_icon_quit_activate (self, menuitem):
self.cleanup ()
if self.loop:
self.loop.quit ()
def on_job_cancel_activate(self, menuitem):
self.on_job_cancel_activate2(False)
def on_job_delete_activate(self, menuitem):
self.on_job_cancel_activate2(True)
def on_job_cancel_activate2(self, purge_job):
if self.jobids:
op = CancelJobsOperation (self.JobsWindow, self.host, self.port,
self.encryption, self.jobids, purge_job)
self.ops.append (op)
op.connect ('finished', self.on_canceljobs_finished)
op.connect ('ipp-error', self.on_canceljobs_error)
def on_canceljobs_finished (self, canceljobsoperation):
canceljobsoperation.destroy ()
i = self.ops.index (canceljobsoperation)
del self.ops[i]
self.update_monitor ()
def on_canceljobs_error (self, canceljobsoperation, jobid, exc):
self.update_monitor ()
if type (exc) == cups.IPPError:
(e, m) = exc.args
if (e != cups.IPP_NOT_POSSIBLE and
e != cups.IPP_NOT_FOUND):
self.show_IPP_Error (e, m)
return
raise exc
def on_job_hold_activate(self, menuitem):
try:
c = authconn.Connection (self.JobsWindow,
host=self.host,
port=self.port,
encryption=self.encryption)
except RuntimeError:
return
for jobid in self.jobids:
c._begin_operation (_("holding job"))
try:
c.setJobHoldUntil (jobid, "indefinite")
except cups.IPPError as e:
(e, m) = e.args
if (e != cups.IPP_NOT_POSSIBLE and
e != cups.IPP_NOT_FOUND):
self.show_IPP_Error (e, m)
self.update_monitor ()
c._end_operation ()
return
c._end_operation ()
del c
self.update_monitor ()
def on_job_release_activate(self, menuitem):
try:
c = authconn.Connection (self.JobsWindow,
host=self.host,
port=self.port,
encryption=self.encryption)
except RuntimeError:
return
for jobid in self.jobids:
c._begin_operation (_("releasing job"))
try:
c.setJobHoldUntil (jobid, "no-hold")
except cups.IPPError as e:
(e, m) = e.args
if (e != cups.IPP_NOT_POSSIBLE and
e != cups.IPP_NOT_FOUND):
self.show_IPP_Error (e, m)
self.update_monitor ()
c._end_operation ()
return
c._end_operation ()
del c
self.update_monitor ()
def on_job_reprint_activate(self, menuitem):
try:
c = authconn.Connection (self.JobsWindow,
host=self.host,
port=self.port,
encryption=self.encryption)
for jobid in self.jobids:
c.restartJob (jobid)
del c
except cups.IPPError as e:
(e, m) = e.args
self.show_IPP_Error (e, m)
self.update_monitor ()
return
except RuntimeError:
return
self.update_monitor ()
def on_job_retrieve_activate(self, menuitem):
try:
c = authconn.Connection (self.JobsWindow,
host=self.host,
port=self.port,
encryption=self.encryption)
except RuntimeError:
return
for jobid in self.jobids:
try:
attrs=c.getJobAttributes(jobid)
printer_uri=attrs['job-printer-uri']
try:
document_count = attrs['number-of-documents']
except KeyError:
document_count = attrs.get ('document-count', 0)
for document_number in range(1, document_count+1):
document=c.getDocument(printer_uri, jobid, document_number)
tempfile = document.get('file')
name = document.get('document-name')
format = document.get('document-format', '')
# if there's no document-name retrieved
if name == None:
# give the default filename some meaningful name
name = _("retrieved")+str(document_number)
# add extension according to format
if format == 'application/postscript':
name = name + ".ps"
elif format.find('application/vnd.') != -1:
name = name + format.replace('application/vnd', '')
elif format.find('application/') != -1:
name = name + format.replace('application/', '.')
if tempfile != None:
dialog = Gtk.FileChooserDialog (title=_("Save File"),
transient_for=self.JobsWindow,
action=Gtk.FileChooserAction.SAVE)
dialog.add_buttons (
Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_SAVE, Gtk.ResponseType.OK)
dialog.set_current_name(name)
dialog.set_do_overwrite_confirmation(True)
response = dialog.run()
if response == Gtk.ResponseType.OK:
file_to_save = dialog.get_filename()
try:
shutil.copyfile(tempfile, file_to_save)
except (IOError, shutil.Error):
debugprint("Unable to save file "+file_to_save)
elif response == Gtk.ResponseType.CANCEL:
pass
dialog.destroy()
os.unlink(tempfile)
else:
debugprint("Unable to retrieve file from job file")
return
except cups.IPPError as e:
(e, m) = e.args
self.show_IPP_Error (e, m)
self.update_monitor ()
return
del c
self.update_monitor ()
def _submenu_connect_hack (self, item, callback, *args):
# See https://bugzilla.gnome.org/show_bug.cgi?id=695488
only_once = threading.Semaphore (1)
def handle_event (item, event=None):
if only_once.acquire (False):
GObject.idle_add (callback, item, *args)
return (item.connect ('button-press-event', handle_event),
item.connect ('activate', handle_event))
def on_job_move_activate(self, menuitem, job_printer_uri):
try:
c = authconn.Connection (self.JobsWindow,
host=self.host,
port=self.port,
encryption=self.encryption)
for jobid in self.jobids:
c.moveJob (job_id=jobid, job_printer_uri=job_printer_uri)
del c
except cups.IPPError as e:
(e, m) = e.args
self.show_IPP_Error (e, m)
self.update_monitor ()
return
except RuntimeError:
return
self.update_monitor ()
def on_job_authenticate_activate(self, menuitem):
try:
c = cups.Connection (host=self.host,
port=self.port,
encryption=self.encryption)
except RuntimeError:
return False
jattrs_req = ['job-printer-uri']
pattrs_req = ['auth-info-required', 'device-uri']
for jobid in self.jobids:
# Get the requried attributes for this job
jattrs = c.getJobAttributes (jobid,
requested_attributes=jattrs_req)
uri = jattrs.get ('job-printer-uri')
pattrs = c.getPrinterAttributes (uri = uri,
requested_attributes=pattrs_req)
try:
auth_info_required = pattrs['auth-info-required']
except KeyError:
debugprint ("No auth-info-required attribute; "
"guessing instead")
auth_info_required = ['username', 'password']
self.get_authentication (jobid, pattrs.get ('device-uri'),
uri, auth_info_required, True)
def on_refresh_clicked(self, toolbutton):
self.monitor.refresh ()
if self.my_monitor:
self.my_monitor.refresh ()
self.update_job_creation_times ()
def on_job_attributes_activate(self, menuitem):
""" For every selected job create notebook page with attributes. """
try:
c = cups.Connection (host=self.host,
port=self.port,
encryption=self.encryption)
except RuntimeError:
return False
for jobid in self.jobids:
if jobid not in self.jobs_attrs:
# add new notebook page with scrollable treeview
scrolledwindow = Gtk.ScrolledWindow()
label = Gtk.Label(label=str(jobid)) # notebook page has label with jobid
page_index = self.notebook.append_page(scrolledwindow, label)
attr_treeview = Gtk.TreeView()
scrolledwindow.add(attr_treeview)
cell = Gtk.CellRendererText ()
attr_treeview.insert_column_with_attributes(0, _("Name"),
cell, text=0)
cell = Gtk.CellRendererText ()
attr_treeview.insert_column_with_attributes(1, _("Value"),
cell, text=1)
attr_store = Gtk.ListStore(str, str)
attr_treeview.set_model(attr_store)
attr_treeview.get_selection().set_mode(Gtk.SelectionMode.NONE)
attr_store.set_sort_column_id (0, Gtk.SortType.ASCENDING)
self.jobs_attrs[jobid] = (attr_store, page_index)
self.update_job_attributes_viewer (jobid, conn=c)
self.JobsAttributesWindow.show_all ()
def update_job_attributes_viewer(self, jobid, conn=None):
""" Update attributes store with new values. """
if conn != None:
c = conn
else:
try:
c = cups.Connection (host=self.host,
port=self.port,
encryption=self.encryption)
except RuntimeError:
return False
if jobid in self.jobs_attrs:
(attr_store, page) = self.jobs_attrs[jobid]
try:
attrs = c.getJobAttributes(jobid) # new attributes
except AttributeError:
return
except cups.IPPError:
# someone else may have purged the job,
# remove jobs notebook page
self.notebook.remove_page(page)
del self.jobs_attrs[jobid]
return
attr_store.clear() # remove old attributes
for name, value in attrs.items():
if name in ['job-id', 'job-printer-up-time']:
continue
attr_store.append([name, str(value)])
def job_is_active (self, jobdata):
state = jobdata.get ('job-state', cups.IPP_JOB_CANCELED)
if state >= cups.IPP_JOB_CANCELED:
return False
return True
## Icon manipulation
def add_state_reason_emblem (self, pixbuf, printer=None):
worst_reason = None
if printer == None and self.worst_reason != None:
# Check that it's valid.
printer = self.worst_reason.get_printer ()
found = False
for reason in self.printer_state_reasons.get (printer, []):
if reason == self.worst_reason:
worst_reason = self.worst_reason
break
if worst_reason == None:
self.worst_reason = None
if printer != None:
for reason in self.printer_state_reasons.get (printer, []):
if worst_reason == None:
worst_reason = reason
elif reason > worst_reason:
worst_reason = reason
if worst_reason != None:
level = worst_reason.get_level ()
if level > StateReason.REPORT:
# Add an emblem to the icon.
icon = StateReason.LEVEL_ICON[level]
pixbuf = pixbuf.copy ()
try:
theme = Gtk.IconTheme.get_default ()
emblem = theme.load_icon (icon, 22, 0)
emblem.composite (pixbuf,
pixbuf.get_width () / 2,
pixbuf.get_height () / 2,
emblem.get_width () / 2,
emblem.get_height () / 2,
pixbuf.get_width () / 2,
pixbuf.get_height () / 2,
0.5, 0.5,
GdkPixbuf.InterpType.BILINEAR, 255)
except GObject.GError:
debugprint ("No %s icon available" % icon)
return pixbuf
def get_icon_pixbuf (self, have_jobs=None):
if not self.applet:
return
if have_jobs == None:
have_jobs = len (self.jobs.keys ()) > 0
if have_jobs:
pixbuf = self.icon_jobs
for jobid, jobdata in self.jobs.items ():
jstate = jobdata.get ('job-state', cups.IPP_JOB_PENDING)
if jstate == cups.IPP_JOB_PROCESSING:
pixbuf = self.icon_jobs_processing
break
else:
pixbuf = self.icon_no_jobs
try:
pixbuf = self.add_state_reason_emblem (pixbuf)
except:
nonfatalException ()
return pixbuf
def set_statusicon_tooltip (self, tooltip=None):
if not self.applet:
return
if tooltip == None:
num_jobs = len (self.jobs)
if num_jobs == 0:
tooltip = _("No documents queued")
elif num_jobs == 1:
tooltip = _("1 document queued")
else:
tooltip = _("%d documents queued") % num_jobs
self.statusicon.set_tooltip_markup (tooltip)
def update_status (self, have_jobs=None):
# Found out which printer state reasons apply to our active jobs.
upset_printers = set()
for printer, reasons in self.printer_state_reasons.items ():
if len (reasons) > 0:
upset_printers.add (printer)
debugprint ("Upset printers: %s" % upset_printers)
my_upset_printers = set()
if len (upset_printers):
my_upset_printers = set()
for jobid in self.active_jobs:
# 'job-printer-name' is set by job_added/job_event
printer = self.jobs[jobid]['job-printer-name']
if printer in upset_printers:
my_upset_printers.add (printer)
debugprint ("My upset printers: %s" % my_upset_printers)
my_reasons = []
for printer in my_upset_printers:
my_reasons.extend (self.printer_state_reasons[printer])
# Find out which is the most problematic.
self.worst_reason = None
if len (my_reasons) > 0:
worst_reason = my_reasons[0]
for reason in my_reasons:
if reason > worst_reason:
worst_reason = reason
self.worst_reason = worst_reason
debugprint ("Worst reason: %s" % worst_reason)
Gdk.threads_enter ()
self.statusbar.pop (0)
if self.worst_reason != None:
(title, tooltip) = self.worst_reason.get_description ()
self.statusbar.push (0, tooltip)
else:
tooltip = None
status_message = ""
processing = 0
pending = 0
for jobid in self.active_jobs:
try:
job_state = self.jobs[jobid]['job-state']
except KeyError:
continue
if job_state == cups.IPP_JOB_PROCESSING:
processing = processing + 1
elif job_state == cups.IPP_JOB_PENDING:
pending = pending + 1
if ((processing > 0) or (pending > 0)):
status_message = _("processing / pending: %d / %d") % (processing, pending)
self.statusbar.push(0, status_message)
if self.applet and not self.notify_has_persistence:
pixbuf = self.get_icon_pixbuf (have_jobs=have_jobs)
self.statusicon.set_from_pixbuf (pixbuf)
self.set_statusicon_visibility ()
self.set_statusicon_tooltip (tooltip=tooltip)
Gdk.threads_leave ()
## Notifications
def notify_printer_state_reason_if_important (self, reason):
level = reason.get_level ()
if level < StateReason.WARNING:
# Not important enough to justify a notification.
return
blacklist = [
# Some printers report 'other-warning' for no apparent
# reason, e.g. Canon iR 3170C, Epson AL-CX11NF.
# See bug #520815.
"other",
# This seems to be some sort of 'magic' state reason that
# is for internal use only.
"com.apple.print.recoverable",
# Human-readable text for this reason has misleading wording,
# suppress it.
"connecting-to-device",
# "cups-remote-..." reasons have no human-readable text yet and
# so get considered as errors, suppress them, too.
"cups-remote-pending",
"cups-remote-pending-held",
"cups-remote-processing",
"cups-remote-stopped",
"cups-remote-canceled",
"cups-remote-aborted",
"cups-remote-completed"
]
if reason.get_reason () in blacklist:
return
self.notify_printer_state_reason (reason)
def notify_printer_state_reason (self, reason):
tuple = reason.get_tuple ()
if tuple in self.state_reason_notifications:
debugprint ("Already sent notification for %s" % repr (reason))
return
level = reason.get_level ()
if (level == StateReason.ERROR or
reason.get_reason () == "connecting-to-device"):
urgency = Notify.Urgency.NORMAL
else:
urgency = Notify.Urgency.LOW
(title, text) = reason.get_description ()
notification = Notify.Notification.new (title, text, 'printer')
reason.user_notified = True
notification.set_urgency (urgency)
if self.notify_has_actions:
notification.set_timeout (Notify.EXPIRES_NEVER)
notification.connect ('closed',
self.on_state_reason_notification_closed)
self.state_reason_notifications[reason.get_tuple ()] = notification
self.set_statusicon_visibility ()
try:
notification.show ()
except GObject.GError:
nonfatalException ()
def on_state_reason_notification_closed (self, notification, reason=None):
debugprint ("Notification %s closed" % repr (notification))
notification.closed = True
self.set_statusicon_visibility ()
return
def notify_completed_job (self, jobid):
job = self.jobs.get (jobid, {})
document = job.get ('job-name', _("Unknown"))
printer_uri = job.get ('job-printer-uri')
if printer_uri != None:
# Determine if this printer is remote. There's no need to
# show a notification if the printer is connected to this
# machine.
# Find out the device URI. We might already have
# determined this if authentication was required.
device_uri = job.get ('device-uri')
if device_uri == None:
pattrs = ['device-uri']
c = authconn.Connection (self.JobsWindow,
host=self.host,
port=self.port,
encryption=self.encryption)
try:
attrs = c.getPrinterAttributes (uri=printer_uri,
requested_attributes=pattrs)
except cups.IPPError:
return
device_uri = attrs.get ('device-uri')
if device_uri != None:
(scheme, rest) = urllib.parse.splittype (device_uri)
if scheme not in ['socket', 'ipp', 'http', 'smb']:
return
printer = job.get ('job-printer-name', _("Unknown"))
notification = Notify.Notification.new (_("Document printed"),
_("Document `%s' has been sent "
"to `%s' for printing.") %
(document,
printer),
'printer')
notification.set_urgency (Notify.Urgency.LOW)
notification.connect ('closed',
self.on_completed_job_notification_closed)
notification.jobid = jobid
self.completed_job_notifications[jobid] = notification
self.set_statusicon_visibility ()
try:
notification.show ()
except GObject.GError:
nonfatalException ()
def on_completed_job_notification_closed (self, notification, reason=None):
jobid = notification.jobid
del self.completed_job_notifications[jobid]
self.set_statusicon_visibility ()
## Monitor signal handlers
def on_refresh (self, mon):
self.store.clear ()
self.jobs = {}
self.active_jobs = set()
self.jobiters = {}
self.printer_uri_index = PrinterURIIndex ()
def job_added (self, mon, jobid, eventname, event, jobdata):
uri = jobdata.get ('job-printer-uri', '')
try:
printer = self.printer_uri_index.lookup (uri)
except KeyError:
printer = uri
if self.specific_dests and printer not in self.specific_dests:
return
jobdata['job-printer-name'] = printer
# We may be showing this job already, perhaps because we are showing
# completed jobs and one was reprinted.
if jobid not in self.jobiters:
self.add_job (jobid, jobdata)
elif mon == self.my_monitor:
# Copy over any missing attributes such as user and title.
for attr, value in jobdata.items ():
if attr not in self.jobs[jobid]:
self.jobs[jobid][attr] = value
debugprint ("Add %s=%s (my job)" % (attr, value))
# If we failed to get required attributes for the job, bail.
if jobid not in self.jobiters:
return
if self.job_is_active (jobdata):
self.active_jobs.add (jobid)
elif jobid in self.active_jobs:
self.active_jobs.remove (jobid)
self.update_status (have_jobs=True)
if self.applet:
if not self.job_is_active (jobdata):
return
for reason in self.printer_state_reasons.get (printer, []):
if not reason.user_notified:
self.notify_printer_state_reason_if_important (reason)
def job_event (self, mon, jobid, eventname, event, jobdata):
uri = jobdata.get ('job-printer-uri', '')
try:
printer = self.printer_uri_index.lookup (uri)
except KeyError:
printer = uri
if self.specific_dests and printer not in self.specific_dests:
return
jobdata['job-printer-name'] = printer
if self.job_is_active (jobdata):
self.active_jobs.add (jobid)
elif jobid in self.active_jobs:
self.active_jobs.remove (jobid)
self.update_job (jobid, jobdata)
self.update_status ()
# Check that the job still exists, as update_status re-enters
# the main loop in order to paint/hide the tray icon. Really
# that should probably be deferred to the idle handler, but
# for the moment just deal with the fact that the job might
# have gone (bug #640904).
if jobid not in self.jobs:
return
jobdata = self.jobs[jobid]
# If the job has finished, let the user know.
if self.applet and (eventname == 'job-completed' or
(eventname == 'job-state-changed' and
event['job-state'] == cups.IPP_JOB_COMPLETED)):
reasons = event['job-state-reasons']
if type (reasons) != list:
reasons = [reasons]
canceled = False
for reason in reasons:
if reason.startswith ("job-canceled"):
canceled = True
break
if not canceled:
self.notify_completed_job (jobid)
# Look out for stopped jobs.
if (self.applet and
(eventname == 'job-stopped' or
(eventname == 'job-state-changed' and
event['job-state'] in [cups.IPP_JOB_STOPPED,
cups.IPP_JOB_PENDING])) and
not jobid in self.stopped_job_prompts):
# Why has the job stopped? It might be due to a job error
# of some sort, or it might be that the backend requires
# authentication. If the latter, the job will be held not
# stopped, and the job-hold-until attribute will be
# 'auth-info-required'. This was already checked for in
# update_job.
may_be_problem = True
jstate = jobdata['job-state']
if (jstate == cups.IPP_JOB_PROCESSING or
(jstate == cups.IPP_JOB_HELD and
jobdata['job-hold-until'] == 'auth-info-required')):
# update_job already dealt with this.
may_be_problem = False
else:
# Other than that, unfortunately the only
# clue we get is the notify-text, which is not
# translated into our native language. We'd better
# try parsing it. In CUPS-1.3.6 the possible strings
# are:
#
# "Job stopped due to filter errors; please consult
# the error_log file for details."
#
# "Job stopped due to backend errors; please consult
# the error_log file for details."
#
# "Job held due to backend errors; please consult the
# error_log file for details."
#
# "Authentication is required for job %d."
# [This case is handled in the update_job method.]
#
# "Job stopped due to printer being paused"
# [This should be ignored, as the job was doing just
# fine until the printer was stopped for other reasons.]
notify_text = event['notify-text']
document = jobdata['job-name']
if notify_text.find ("backend errors") != -1:
message = (_("There was a problem sending document `%s' "
"(job %d) to the printer.") %
(document, jobid))
elif notify_text.find ("filter errors") != -1:
message = _("There was a problem processing document `%s' "
"(job %d).") % (document, jobid)
elif (notify_text.find ("being paused") != -1 or
jstate != cups.IPP_JOB_STOPPED):
may_be_problem = False
else:
# Give up and use the provided message untranslated.
message = (_("There was a problem printing document `%s' "
"(job %d): `%s'.") %
(document, jobid, notify_text))
if may_be_problem:
debugprint ("Problem detected")
self.toggle_window_display (None, force_show=True)
dialog = Gtk.Dialog (title=_("Print Error"),
transient_for=self.JobsWindow)
dialog.add_buttons (_("_Diagnose"), Gtk.ResponseType.NO,
Gtk.STOCK_OK, Gtk.ResponseType.OK)
dialog.set_default_response (Gtk.ResponseType.OK)
dialog.set_border_width (6)
dialog.set_resizable (False)
dialog.set_icon_name (ICON)
hbox = Gtk.HBox.new (False, 12)
hbox.set_border_width (6)
image = Gtk.Image ()
image.set_from_stock (Gtk.STOCK_DIALOG_ERROR,
Gtk.IconSize.DIALOG)
hbox.pack_start (image, False, False, 0)
vbox = Gtk.VBox.new (False, 12)
markup = ('<span weight="bold" size="larger">' +
_("Print Error") + '</span>\n\n' +
saxutils.escape (message))
try:
if event['printer-state'] == cups.IPP_PRINTER_STOPPED:
name = event['printer-name']
markup += ' '
markup += (_("The printer called `%s' has "
"been disabled.") % name)
except KeyError:
pass
label = Gtk.Label(label=markup)
label.set_use_markup (True)
label.set_line_wrap (True)
label.set_alignment (0, 0)
vbox.pack_start (label, False, False, 0)
hbox.pack_start (vbox, False, False, 0)
dialog.vbox.pack_start (hbox, False, False, 0)
dialog.connect ('response',
self.print_error_dialog_response, jobid)
self.stopped_job_prompts.add (jobid)
dialog.show_all ()
def job_removed (self, mon, jobid, eventname, event):
# If the job has finished, let the user know.
if self.applet and (eventname == 'job-completed' or
(eventname == 'job-state-changed' and
event['job-state'] == cups.IPP_JOB_COMPLETED)):
reasons = event['job-state-reasons']
debugprint (reasons)
if type (reasons) != list:
reasons = [reasons]
canceled = False
for reason in reasons:
if reason.startswith ("job-canceled"):
canceled = True
break
if not canceled:
self.notify_completed_job (jobid)
if jobid in self.jobiters:
self.store.remove (self.jobiters[jobid])
del self.jobiters[jobid]
del self.jobs[jobid]
if jobid in self.active_jobs:
self.active_jobs.remove (jobid)
if jobid in self.jobs_attrs:
del self.jobs_attrs[jobid]
self.update_status ()
def state_reason_added (self, mon, reason):
(title, text) = reason.get_description ()
printer = reason.get_printer ()
try:
l = self.printer_state_reasons[printer]
except KeyError:
l = []
self.printer_state_reasons[printer] = l
reason.user_notified = False
l.append (reason)
self.update_status ()
self.treeview.queue_draw ()
if not self.applet:
return
# Find out if the user has jobs queued for that printer.
for job, data in self.jobs.items ():
if not self.job_is_active (data):
continue
if data['job-printer-name'] == printer:
# Yes! Notify them of the state reason, if necessary.
self.notify_printer_state_reason_if_important (reason)
break
def state_reason_removed (self, mon, reason):
printer = reason.get_printer ()
try:
reasons = self.printer_state_reasons[printer]
except KeyError:
debugprint ("Printer not found")
return
try:
i = reasons.index (reason)
except IndexError:
debugprint ("Reason not found")
return
del reasons[i]
self.update_status ()
self.treeview.queue_draw ()
if not self.applet:
return
tuple = reason.get_tuple ()
try:
notification = self.state_reason_notifications[tuple]
if getattr (notification, 'closed', None) != True:
try:
notification.close ()
except GLib.GError:
# Can fail if the notification wasn't even shown
# yet (as in bug #545733).
pass
del self.state_reason_notifications[tuple]
self.set_statusicon_visibility ()
except KeyError:
pass
def still_connecting (self, mon, reason):
if not self.applet:
return
self.notify_printer_state_reason (reason)
def now_connected (self, mon, printer):
if not self.applet:
return
# Find the connecting-to-device state reason.
try:
reasons = self.printer_state_reasons[printer]
reason = None
for r in reasons:
if r.get_reason () == "connecting-to-device":
reason = r
break
except KeyError:
debugprint ("Couldn't find state reason (no reasons)!")
if reason != None:
tuple = reason.get_tuple ()
else:
debugprint ("Couldn't find state reason in list!")
tuple = None
for (level,
p,
r) in self.state_reason_notifications.keys ():
if p == printer and r == "connecting-to-device":
debugprint ("Found from notifications list")
tuple = (level, p, r)
break
if tuple == None:
debugprint ("Unexpected now_connected signal "
"(reason not in notifications list)")
return
try:
notification = self.state_reason_notifications[tuple]
except KeyError:
debugprint ("Unexpected now_connected signal")
return
if getattr (notification, 'closed', None) != True:
try:
notification.close ()
except GLib.GError:
# Can fail if the notification wasn't even shown
pass
notification.closed = True
def printer_added (self, mon, printer):
self.printer_uri_index.add_printer (printer)
def printer_event (self, mon, printer, eventname, event):
self.printer_uri_index.update_from_attrs (printer, event)
def printer_removed (self, mon, printer):
self.printer_uri_index.remove_printer (printer)
### Cell data functions
def _set_job_job_number_text (self, column, cell, model, iter, *data):
cell.set_property("text", str (model.get_value (iter, 0)))
def _set_job_user_text (self, column, cell, model, iter, *data):
jobid = model.get_value (iter, 0)
try:
job = self.jobs[jobid]
except KeyError:
return
cell.set_property("text", job.get ('job-originating-user-name',
_("Unknown")))
def _set_job_document_text (self, column, cell, model, iter, *data):
jobid = model.get_value (iter, 0)
try:
job = self.jobs[jobid]
except KeyError:
return
cell.set_property("text", job.get('job-name', _("Unknown")))
def _set_job_printer_text (self, column, cell, model, iter, *data):
jobid = model.get_value (iter, 0)
try:
reasons = self.jobs[jobid].get('job-state-reasons')
except KeyError:
return
if reasons == 'printer-stopped':
reason = ' - ' + _("disabled")
else:
reason = ''
cell.set_property("text", self.jobs[jobid]['job-printer-name']+reason)
def _set_job_size_text (self, column, cell, model, iter, *data):
jobid = model.get_value (iter, 0)
try:
job = self.jobs[jobid]
except KeyError:
return
size = _("Unknown")
if 'job-k-octets' in job:
size = str (job['job-k-octets']) + 'k'
cell.set_property("text", size)
def _find_job_state_text (self, job):
try:
data = self.jobs[job]
except KeyError:
return
jstate = data.get ('job-state', cups.IPP_JOB_PROCESSING)
s = int (jstate)
job_requires_auth = (s == cups.IPP_JOB_HELD and
data.get ('job-hold-until', 'none') ==
'auth-info-required')
state = None
if job_requires_auth:
state = _("Held for authentication")
elif s == cups.IPP_JOB_HELD:
state = _("Held")
until = data.get ('job-hold-until')
if until != None:
try:
colon1 = until.find (':')
if colon1 != -1:
now = time.gmtime ()
hh = int (until[:colon1])
colon2 = until[colon1 + 1:].find (':')
if colon2 != -1:
colon2 += colon1 + 1
mm = int (until[colon1 + 1:colon2])
ss = int (until[colon2 + 1:])
else:
mm = int (until[colon1 + 1:])
ss = 0
day = now.tm_mday
if (hh < now.tm_hour or
(hh == now.tm_hour and
(mm < now.tm_min or
(mm == now.tm_min and ss < now.tm_sec)))):
day += 1
hold = (now.tm_year, now.tm_mon, day,
hh, mm, ss, 0, 0, -1)
old_tz = os.environ.get("TZ")
os.environ["TZ"] = "UTC"
simpletime = time.mktime (hold)
if old_tz == None:
del os.environ["TZ"]
else:
os.environ["TZ"] = old_tz
local = time.localtime (simpletime)
state = (_("Held until %s") %
time.strftime ("%X", local))
except ValueError:
pass
if until == "day-time":
state = _("Held until day-time")
elif until == "evening":
state = _("Held until evening")
elif until == "night":
state = _("Held until night-time")
elif until == "second-shift":
state = _("Held until second shift")
elif until == "third-shift":
state = _("Held until third shift")
elif until == "weekend":
state = _("Held until weekend")
else:
try:
state = { cups.IPP_JOB_PENDING: _("Pending"),
cups.IPP_JOB_PROCESSING: _("Processing"),
cups.IPP_JOB_STOPPED: _("Stopped"),
cups.IPP_JOB_CANCELED: _("Canceled"),
cups.IPP_JOB_ABORTED: _("Aborted"),
cups.IPP_JOB_COMPLETED: _("Completed") }[s]
except KeyError:
pass
if state == None:
state = _("Unknown")
return state
def _set_job_status_icon (self, column, cell, model, iter, *data):
jobid = model.get_value (iter, 0)
try:
data = self.jobs[jobid]
except KeyError:
return
jstate = data.get ('job-state', cups.IPP_JOB_PROCESSING)
s = int (jstate)
if s == cups.IPP_JOB_PROCESSING:
icon = self.icon_jobs_processing
else:
icon = self.icon_jobs
if s == cups.IPP_JOB_HELD:
try:
theme = Gtk.IconTheme.get_default ()
emblem = theme.load_icon (Gtk.STOCK_MEDIA_PAUSE, 22 / 2, 0)
copy = icon.copy ()
emblem.composite (copy, 0, 0,
copy.get_width (),
copy.get_height (),
copy.get_width () / 2 - 1,
copy.get_height () / 2 - 1,
1.0, 1.0,
GdkPixbuf.InterpType.BILINEAR, 255)
icon = copy
except GObject.GError:
debugprint ("No %s icon available" % Gtk.STOCK_MEDIA_PAUSE)
else:
# Check state reasons.
printer = data['job-printer-name']
icon = self.add_state_reason_emblem (icon, printer=printer)
cell.set_property ("pixbuf", icon)
def _set_job_status_text (self, column, cell, model, iter, *data):
jobid = model.get_value (iter, 0)
try:
data = self.jobs[jobid]
except KeyError:
return
try:
text = data['_status_text']
except KeyError:
text = self._find_job_state_text (jobid)
data['_status_text'] = text
printer = data['job-printer-name']
reasons = self.printer_state_reasons.get (printer, [])
if len (reasons) > 0:
worst_reason = reasons[0]
for reason in reasons[1:]:
if reason > worst_reason:
worst_reason = reason
(title, unused) = worst_reason.get_description ()
text += " - " + title
cell.set_property ("text", text)
|
gpl-2.0
|
yurikoneve/UserFrosting_Academic_Dashboard
|
admin/post_media.php
|
2738
|
<?php
# -- BEGIN LICENSE BLOCK ---------------------------------------
#
# This file is part of Dotclear 2.
#
# Copyright (c) 2003-2013 Olivier Meunier & Association Dotclear
# Licensed under the GPL version 2.0 license.
# See LICENSE file or
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
#
# -- END LICENSE BLOCK -----------------------------------------
require dirname(__FILE__).'/../inc/admin/prepend.php';
dcPage::check('usage,contentadmin');
$post_id = !empty($_REQUEST['post_id']) ? (integer) $_REQUEST['post_id'] : null;
$media_id = !empty($_REQUEST['media_id']) ? (integer) $_REQUEST['media_id'] : null;
$link_type = !empty($_REQUEST['link_type']) ? $_REQUEST['link_type'] : null;
if (!$post_id) {
exit;
}
$rs = $core->blog->getPosts(array('post_id' => $post_id,'post_type'=>''));
if ($rs->isEmpty()) {
exit;
}
try {
if ($post_id && $media_id && !empty($_REQUEST['attach']))
{
$core->media = new dcMedia($core);
$core->media->addPostMedia($post_id,$media_id,$link_type);
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
header('Content-type: application/json');
echo json_encode(array('url' => $core->getPostAdminURL($rs->post_type,$post_id,false)));
exit();
} else {
http::redirect($core->getPostAdminURL($rs->post_type,$post_id,false));
}
}
$core->media = new dcMedia($core);
$f = $core->media->getPostMedia($post_id,$media_id,$link_type);
if (empty($f)) {
$post_id = $media_id = null;
throw new Exception(__('This attachment does not exist'));
}
$f = $f[0];
} catch (Exception $e) {
$core->error->add($e->getMessage());
}
# Remove a media from en
if (($post_id && $media_id) || $core->error->flag())
{
if (!empty($_POST['remove']))
{
$core->media->removePostMedia($post_id,$media_id,$link_type);
dcPage::addSuccessNotice(__('Attachment has been successfully removed.'));
http::redirect($core->getPostAdminURL($rs->post_type,$post_id,false));
}
elseif (isset($_POST['post_id'])) {
http::redirect($core->getPostAdminURL($rs->post_type,$post_id,false));
}
if (!empty($_GET['remove']))
{
dcPage::open(__('Remove attachment'));
echo '<h2>'.__('Attachment').' › <span class="page-title">'.__('confirm removal').'</span></h2>';
echo
'<form action="'.$core->adminurl->get("admin.post.media").'" method="post">'.
'<p>'.__('Are you sure you want to remove this attachment?').'</p>'.
'<p><input type="submit" class="reset" value="'.__('Cancel').'" /> '.
' <input type="submit" class="delete" name="remove" value="'.__('Yes').'" />'.
form::hidden('post_id',$post_id).
form::hidden('media_id',$media_id).
$core->formNonce().'</p>'.
'</form>';
dcPage::close();
exit;
}
}
|
gpl-2.0
|
bedatadriven/renjin
|
core/src/main/java/org/renjin/primitives/matrix/AbstractMatrixBuilder.java
|
2295
|
/*
* Renjin : JVM-based interpreter for the R language for the statistical analysis
* Copyright © 2010-2019 BeDataDriven Groep B.V. and contributors
*
* 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, a copy is available at
* https://www.gnu.org/licenses/gpl-2.0.txt
*/
package org.renjin.primitives.matrix;
import org.renjin.primitives.Indexes;
import org.renjin.sexp.*;
import java.util.Collection;
class AbstractMatrixBuilder<B extends Vector.Builder, V extends Vector> {
protected final B builder;
private final int nrows;
private final int ncols;
private Vector rowNames = Null.INSTANCE;
private Vector colNames = Null.INSTANCE;
public AbstractMatrixBuilder(Vector.Type vectorType, int nrows, int ncols) {
this.nrows = nrows;
this.ncols = ncols;
builder = (B) vectorType.newBuilderWithInitialSize(nrows * ncols);
builder.setAttribute(Symbols.DIM, new IntArrayVector(nrows, ncols));
}
public void setRowNames(Vector names) {
rowNames = names;
}
public void setRowNames(Collection<String> names) {
rowNames = new StringArrayVector(names);
}
public void setColNames(Vector names) {
colNames = names;
}
public void setColNames(Collection<String> names) {
colNames = new StringArrayVector(names);
}
public int getRows() {
return nrows;
}
public int getCols() {
return ncols;
}
protected final int computeIndex(int row, int col) {
return Indexes.matrixIndexToVectorIndex(row, col, nrows, ncols);
}
public V build() {
if(rowNames != Null.INSTANCE || colNames != Null.INSTANCE) {
builder.setAttribute(Symbols.DIMNAMES, new ListVector(rowNames, colNames));
}
return (V)builder.build();
}
}
|
gpl-2.0
|
MESH-Dev/Smooth-Ambler---WordPress
|
partials/twitter.php
|
846
|
<?php
ini_set('display_errors', 1);
require_once(__DIR__.'/../partials/TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "83915658-9luHDoL9Jtvkn46HLTYehtoQtaCKYiseRyprI6qmO",
'oauth_access_token_secret' => "NBus2GZxKJ7onUq58q2VHYD1zuWmypKgcg0hRG2VVe46r",
'consumer_key' => "BZrJakIcIfNofC4nFcTh4D8nu",
'consumer_secret' => "C2Ouu7mU7nGrJZY9JI7bCLvzJCki42wF0vPG0KM2bAJMVdojLu"
);
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=SmoothAmbler&count=1';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$result = json_decode($response, true);
echo $result[0]['text'];
// var_dump(json_decode($response));
?>
|
gpl-2.0
|
openvsip/openvsip
|
src/ovxx/view.hpp
|
408
|
//
// Copyright (c) 2013 Stefan Seefeld
// All rights reserved.
//
// This file is part of OpenVSIP. It is made available under the
// license contained in the accompanying LICENSE.BSD file.
#ifndef ovxx_view_hpp_
#define ovxx_view_hpp_
#include <ovxx/view/traits.hpp>
#include <ovxx/view/view.hpp>
#include <ovxx/view/operators.hpp>
#include <ovxx/view/functors.hpp>
#include <ovxx/view/cast.hpp>
#endif
|
gpl-2.0
|
pawohl/studip
|
db/migrations/150_help_tours_and_content.php
|
91328
|
<?php
/**
* Adds help tours and help content.
*/
class HelpToursAndContent extends Migration
{
function description()
{
return 'Adds help tours and help content.';
}
function up()
{
$this->addHelpTours();
$this->addHelpContent();
$this->addHelpContentEN();
// set version in config
$version = '3.1';
// see migrate_help_content.php
if (!Config::get()->getValue('HELP_CONTENT_CURRENT_VERSION')) {
Config::get()->create('HELP_CONTENT_CURRENT_VERSION', array(
'value' => $version,
'is_default' => 0,
'type' => 'string',
'range' => 'global',
'section' => 'global',
'description' => _('Aktuelle Version der Helpbar-Einträge in Stud.IP')
));
} else {
Config::get()->store('HELP_CONTENT_CURRENT_VERSION', $version);
}
}
function down()
{
DBManager::get()->exec("TRUNCATE TABLE `help_content`");
DBManager::get()->exec("TRUNCATE TABLE `help_tours`");
DBManager::get()->exec("TRUNCATE TABLE `help_tour_settings`");
DBManager::get()->exec("TRUNCATE TABLE `help_tour_steps`");
}
function addHelpTours() {
// add tour data
$query = "INSERT IGNORE INTO `help_tours` (`tour_id`, `name`, `description`, `type`, `roles`, `version`, `language`, `studip_version`, `installation_id`, `mkdate`) VALUES
('96ea422f286fb5bbf9e41beadb484a9a', 'Profilseite', 'In dieser Tour werden die Grundfunktionen und Bereiche der Profilseite vorgestellt.', 'tour', 'autor,dozent,root', 1, 'de', '3.1', '', 1406722657),
('25e7421f286fc5bdf9e41beadb484ffa', 'Eigenes Bild hochladen', 'In der Tour wird erklärt, wie Nutzende ein eigenes Profilbild hochladen können.', 'tour', 'autor,tutor,dozent,admin,root', 1, 'de', '3.1', '', 1406722657),
('3629493a16bf2680de64361f07cab096', 'Blubber', 'In der Tour wird die Nutzung von Blubber erklärt.', 'tour', 'autor,tutor,dozent,admin,root', 1, 'de', '3.1', '', 1406709759),
('21f487fa74e3bfc7789886f40fe4131a', 'Forum nutzen', 'Die Inhalte dieser Tour stammen aus der alten Tour des Forums (Sidebar > Aktionen > Tour starten).', 'tour', 'autor,tutor,dozent,admin,root', 1, 'de', '3.1', '', 1405415746),
('44f859c50648d3410c39207048ddd833', 'Forum verwalten', 'Die Inhalte dieser Tour stammen aus der alten Tour des Forums (Sidebar > Aktionen > Tour starten).', 'tour', 'tutor,dozent,admin,root', 1, 'de', '3.1', '', 1405417901),
('3a717a468afb0822cb1455e0ae6b6fce', 'Blubber', 'In der Tour wird die Nutzung von Blubber erklärt.', 'tour', 'autor,tutor,dozent,admin,root', 1, 'de', '3.1', '', 1406709041),
('ef5092ba722c81c37a5a6bd703890bd9', 'Blubber', 'In der Tour wird die Nutzung von Blubber erklärt.', 'tour', 'autor,tutor,dozent,admin,root', 1, 'de', '3.1', '', 1405507317),
('6849293baa05be5bef8ff438dc7c438b', 'Suche', 'In dieser Feature-Tour werden die wichtigsten Funktionen der Suche vorgestellt.', 'tour', 'autor,tutor,dozent,admin,root', 1, 'de', '3.1', '', 1405519609),
('b74f8459dce2437463096d56db7c73b9', 'Meine Veranstaltungen (Studierende)', 'In dieser Tour werden die wichtigsten Funktionen der Seite \"Meine Veranstaltungen\" vorgestellt.', 'tour', 'autor,admin,root', 1, 'de', '3.1', '', 1405521073),
('154e711257d4d32d865fb8f5fb70ad72', 'Meine Dateien', 'In dieser Tour wird der persönliche Dateibereich vorgestellt.', 'tour', 'autor,tutor,dozent,admin,root', 1, 'de', '3.1', '', 1405592618),
('19ac063e8319310d059d28379139b1cf', 'Studiengruppe anlegen', 'In dieser Tour wird das Anlegen von Studiengruppen erklärt.', 'tour', 'autor,tutor,dozent,admin,root', 1, 'de', '3.1', '', 1405684299),
('edfcf78c614869724f93488c4ed09582', 'Teilnehmerverwaltung', 'In dieser Tour werden die Verwaltungsoptionen der Teilnehmerverwaltung erklärt.', 'tour', 'tutor,dozent,admin,root', 1, 'de', '3.1', '', 1405688156),
('977f41c5c5239c4e86f04c3df27fae38', 'Was ist neu in Stud.IP 3.1?', 'In dieser Tour werden die Neuerungen in Stud.IP 3.1 überblicksartig vorgestellt.', 'tour', 'autor,tutor,dozent,admin', 1, 'de', '3.1', '', 1405932260),
('49604a77654617a745e29ad6b253e491', 'Gestaltung der Startseite', 'In dieser Tour werden die Funktionen und Gestaltungsmöglichkeiten der Startseite vorgestellt.', 'tour', 'autor,tutor,dozent,admin,root', 1, 'de', '3.1', '', 1405934780),
('7cccbe3b22dfa745c17cb776fb04537c', 'Meine Veranstaltungen (Dozierende)', 'In dieser Tour werden die wichtigsten Funktionen der Seite \"Meine Veranstaltungen\" vorgestellt.', 'tour', 'tutor,dozent,admin,root', 1, 'de', '3.1', '', 1406125685);
";
DBManager::get()->exec($query);
// add steps
$query = "INSERT IGNORE INTO `help_tour_steps` (`tour_id`, `step`, `title`, `tip`, `orientation`, `interactive`, `css_selector`, `route`, `author_id`, `mkdate`) VALUES
('96ea422f286fb5bbf9e41beadb484a9a', 3, 'Stud.IP-Score', 'Der Stud.IP-Score wächst mit den Aktivitäten in Stud.IP und repräsentiert so die Erfahrung mit Stud.IP.', 'BL', 0, '#layout_content TABLE:eq(0) TBODY:eq(0) TR:eq(0) TD:eq(0) A:eq(0)', 'dispatch.php/profile', '', 1406722657),
('96ea422f286fb5bbf9e41beadb484a9a', 5, 'Neue Ankündigung', 'Klicken Sie auf das Plus-Zeichen, wenn Sie eine Ankündigung erstellen möchten.', 'BR', 0, '.contentbox:eq(0) header img:eq(1)', 'dispatch.php/profile', '', 1406722657),
('96ea422f286fb5bbf9e41beadb484a9a', 1, 'Profil-Tour', 'Diese Tour gibt Ihnen einen Überblick über die wichtigsten Funktionen des \"Profils\".\r\n\r\nUm auf den nächsten Schritt zu kommen, klicken Sie bitte rechts unten auf \"Weiter\".', 'T', 0, '', 'dispatch.php/profile', '', 1406722657),
('96ea422f286fb5bbf9e41beadb484a9a', 6, 'Persönliche Daten', 'Das Bild sowie weitere Nutzerdaten können über diese Seiten geändert werden.', 'BL', 0, '#tabs li:eq(2)', 'dispatch.php/profile', '', 1406722657),
('96ea422f286fb5bbf9e41beadb484a9a', 2, 'Persönliches Bild', 'Wenn ein Bild hochgeladen wurde, wird es hier angezeigt. Dieses kann jederzeit geändert werden.', 'RT', 0, '.avatar-normal', 'dispatch.php/profile', '', 1406722657),
('25e7421f286fc5bdf9e41beadb484ffa', 1, 'Profil', 'Diese Tour gibt Ihnen einen Überblick über die wichtigsten Funktionen des \"Profils\".\r\n\r\nUm auf den nächsten Schritt zu kommen, klicken Sie bitte rechts unten auf \"Weiter\".', 'B', 0, '', 'dispatch.php/profile', '', 1406722657),
('25e7421f286fc5bdf9e41beadb484ffa', 2, 'Bild hochladen', 'Auf dieser Seite lässt sich ein Profilbild hochladen.', 'BL', 0, '#nav_profile_avatar A SPAN', 'dispatch.php/settings/avatar', '', 1406722657),
('25e7421f286fc5bdf9e41beadb484ffa', 3, 'Bild auswählen', 'Dafür kann eine beliebige Bilddatei hochgeladen werden.', 'L', 0, 'input[name=imgfile]', 'dispatch.php/settings/avatar', '', 1406722657),
('96ea422f286fb5bbf9e41beadb484a9a', 4, 'Ankündigungen', 'Sie können auf dieser Seite persönliche Ankündigungen veröffentlichen.', 'B', 0, '#layout_content SECTION HEADER H1 :eq(0)', 'dispatch.php/profile', '', 1406722657),
('3629493a16bf2680de64361f07cab096', 3, 'Text gestalten', 'Der Text kann formatiert und mit Smileys versehen werden.\r\nEs können die üblichen Formatierungen verwendet werden, wie z. B. **fett** oder %%kursiv%%.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/forum', '', 1405508371),
('6849293baa05be5bef8ff438dc7c438b', 4, 'Navigation', 'Falls nur in einem bestimmten Bereich (wie z.B. Lehre) gesucht werden soll, kann dieser hier ausgewählt werden.', 'R', 0, '#layout-sidebar SECTION DIV DIV.sidebar-widget-header :eq(0)', 'dispatch.php/search/courses', '', 1406121826),
('3a717a468afb0822cb1455e0ae6b6fce', 3, 'Text gestalten', 'Der Text kann formatiert und mit Smileys versehen werden.\r\nEs können die üblichen Formatierungen verwendet werden, wie z. B. **fett** oder %%kursiv%%.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/profile', '', 1405508371),
('3629493a16bf2680de64361f07cab096', 9, 'Beitrag verlinken', 'Wird der Mauszeiger auf dem ersten Diskussionsbeitrag positioniert, erscheint links neben dem Datum ein Link-Icon. Wenn dieses mit der rechten Maustaste angeklickt wird, kann der Link auf diesen Beitrag kopiert werden, um ihn an anderer Stelle einfügen zu können.', 'BR', 0, 'DIV DIV A.permalink', 'plugins.php/blubber/streams/forum', '', 1405508281),
('3629493a16bf2680de64361f07cab096', 8, 'Beitrag ändern', 'Wird der Mauszeiger auf einem beliebigen Beitrag positioniert, erscheint dessen Datum. Bei eigenen Beiträgen erscheint außerdem rechts neben dem Datum ein Icon, mit dem der Beitrag nachträglich geändert werden kann.', 'BR', 0, 'DIV DIV A SPAN.time', 'plugins.php/blubber/streams/forum', '', 1405507901),
('21f487fa74e3bfc7789886f40fe4131a', 1, 'Forum', 'Diese Tour gibt einen Überblick über die Elemente und Interaktionsmöglichkeiten des Forums.\r\n\r\nUm zum nächsten Schritt zu gelangen, klicken Sie bitte rechts unten auf \"Weiter\".', 'BL', 0, '', 'plugins.php/coreforum', '', 1405415772),
('21f487fa74e3bfc7789886f40fe4131a', 2, 'Sie befinden sich hier:...', 'An dieser Stelle wird angezeigt, welcher Bereich des Forums gerade betrachtet wird.', 'BL', 0, 'DIV#tutorBreadcrumb', 'plugins.php/coreforum', '', 1405415875),
('44f859c50648d3410c39207048ddd833', 1, 'Forum verwalten', 'Sie haben die Möglichkeit sich eine Tour zur Verwaltung des Forums anzuschauen.\r\n\r\nUm die Tour zu beginnen, klicken Sie bitte unten rechts auf \"Weiter\".', 'TL', 0, '', 'plugins.php/coreforum', '', 1405418008),
('21f487fa74e3bfc7789886f40fe4131a', 3, 'Kategorie', 'Das Forum ist unterteilt in Kategorien, Themen und Beiträge. Eine Kategorie fasst Forumsbereiche in größere Sinneinheiten zusammen.', 'BL', 0, '#layout_content #forum #sortable_areas TABLE CAPTION .category_name :eq(0)', 'plugins.php/coreforum', '', 1405416611),
('21f487fa74e3bfc7789886f40fe4131a', 4, 'Bereich', 'Das ist ein Bereich innerhalb einer Kategorie. Bereiche beinhalten die Diskussionstränge. Bereiche können mit per drag & drop in ihrer Reihenfolge verschoben werden.', 'BL', 0, '#layout_content #forum TABLE THEAD TR TH :eq(0)', 'plugins.php/coreforum', '', 1405416664),
('21f487fa74e3bfc7789886f40fe4131a', 5, 'Info-Icon', 'Dieses Icon färbt sich rot, sobald es etwas neues in diesem Bereich gibt.', 'B', 0, 'IMG#tutorNotificationIcon', 'plugins.php/coreforum', '', 1405416705),
('21f487fa74e3bfc7789886f40fe4131a', 7, 'Forum abonnieren', 'Das gesamte Forum, oder einzelne Themen können abonniert werden. Dann wird bei jedem neuen Beitrag in diesem Forum eine Benachrichtigung angezeigt und eine Nachricht versendet.', 'B', 0, '#layout-sidebar SECTION DIV DIV UL LI A :eq(5)', 'plugins.php/coreforum', '', 1405416795),
('21f487fa74e3bfc7789886f40fe4131a', 6, 'Suchen', 'Hier können sämtliche Inhalte dieses Forums durchsucht werden.\r\nUnterstützt werden auch Mehrwortsuchen. Außerdem kann die Suche auf eine beliebige Kombination aus Titel, Inhalt und Autor eingeschränkt werden.', 'BL', 0, '#layout-sidebar SECTION #tutorSearchInfobox DIV #tutorSearchInfobox UL LI INPUT :eq(1)', 'plugins.php/coreforum', '', 1405417134),
('44f859c50648d3410c39207048ddd833', 2, 'Kategorie bearbeiten', 'Mit diesen Icons kann der Name der Kategorie geändert oder aber die gesamte Kategorie gelöscht werden. Die Bereiche werden in diesem Fall in die Kategorie \"Allgemein\" verschoben und bleiben somit erhalten.\r\n\r\nDie Kategorie \"Allgemein\" kann nicht gelöscht werden und ist daher in jedem Forum enthalten.', 'BR', 0, '#forum #sortable_areas TABLE CAPTION #tutorCategoryIcons', 'plugins.php/coreforum', '', 1405424216),
('44f859c50648d3410c39207048ddd833', 3, 'Bereich bearbeiten', 'Wird der Mauszeiger auf einem Bereich positioniert, erscheinen Aktions-Icons.\r\nMit diesen Icons kann der Name und die Beschreibung eines Bereiches geändert oder auch der gesamte Bereich gelöscht werden.\r\nDas Löschen eines Bereichs, führt dazu, dass alle enthaltenen Themen gelöscht werden.', 'B', 0, 'IMG.edit-area', 'plugins.php/coreforum', '', 1405424346),
('44f859c50648d3410c39207048ddd833', 4, 'Bereiche sortieren', 'Mit dieser schraffierten Fläche können Bereiche an einer beliebigen Stelle durch Klicken-und-Ziehen einsortiert werden. Dies kann einerseits dazu verwendet werden, um Bereiche innerhalb einer Kategorie zu sortieren, andererseits können Bereiche in andere Kategorien verschoben werden.', 'BR', 0, 'HTML #plugins #layout_wrapper #layout_page #layout_container #layout_content #forum #sortable_areas TABLE TBODY #tutorArea TD IMG#tutorMoveArea.handle.js :eq(1)', 'plugins.php/coreforum', '', 1405424379),
('44f859c50648d3410c39207048ddd833', 5, 'Neuen Bereich hinzufügen', 'Hier können neue Bereiche zu einer Kategorie hinzugefügt werden.', 'BR', 0, 'TFOOT TR TD A SPAN', 'plugins.php/coreforum', '', 1405424421),
('44f859c50648d3410c39207048ddd833', 6, 'Neue Kategorie erstellen', 'Hier kann eine neue Kategorie im Forum erstellt werden. Geben Sie hierfür den Titel der neuen Kategorie ein.', 'TL', 0, '#tutorAddCategory H2', 'plugins.php/coreforum', '', 1405424458),
('ef5092ba722c81c37a5a6bd703890bd9', 1, 'Was ist Blubbern?', 'Diese Tour gibt Ihnen einen Überblick über die wichtigsten Funktionen von \"Blubber\".\r\n\r\nUm auf den nächsten Schritt zu kommen, klicken Sie bitte rechts unten auf \"Weiter\".', 'TL', 0, '', 'plugins.php/blubber/streams/global', '', 1405507364),
('ef5092ba722c81c37a5a6bd703890bd9', 2, 'Beitrag erstellen', 'Hier kann eine Diskussion durch Schreiben von Text begonnen werden. Absätze lassen sich durch Drücken von Umschalt+Eingabe erzeugen. Der Text wird durch Drücken von Eingabe abgeschickt.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/global', '', 1405507478),
('ef5092ba722c81c37a5a6bd703890bd9', 8, 'Beitrag ändern', 'Wird der Mauszeiger auf einem beliebigen Beitrag positioniert, erscheint dessen Datum. Bei eigenen Beiträgen erscheint außerdem rechts neben dem Datum ein Icon, mit dem der Beitrag nachträglich geändert werden kann.', 'BR', 0, 'DIV DIV A SPAN.time', 'plugins.php/blubber/streams/global', '', 1405507901),
('ef5092ba722c81c37a5a6bd703890bd9', 9, 'Beitrag verlinken', 'Wird der Mauszeiger auf dem ersten Diskussionsbeitrag positioniert, erscheint links neben dem Datum ein Link-Icon. Wenn dieses mit der rechten Maustaste angeklickt wird, kann der Link auf diesen Beitrag kopiert werden, um ihn an anderer Stelle einfügen zu können.', 'BR', 0, 'DIV DIV A.permalink', 'plugins.php/blubber/streams/global', '', 1405508281),
('ef5092ba722c81c37a5a6bd703890bd9', 3, 'Text gestalten', 'Der Text kann formatiert und mit Smileys versehen werden.\r\nEs können die üblichen Formatierungen verwendet werden, wie z. B. **fett** oder %%kursiv%%.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/global', '', 1405508371),
('ef5092ba722c81c37a5a6bd703890bd9', 5, 'Datei hinzufügen', 'Dateien können in einen Beitrag eingefügt werden, indem sie per Drag&Drop in ein Eingabefeld gezogen werden.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/global', '', 1405508401),
('ef5092ba722c81c37a5a6bd703890bd9', 6, 'Schlagworte', 'Beiträge können mit Schlagworten (engl. \"Hashtags\") versehen werden, indem einem beliebigen Wort des Beitrags ein # vorangestellt wird.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/global', '', 1405508442),
('ef5092ba722c81c37a5a6bd703890bd9', 7, 'Schlagwortwolke', 'Durch Anklicken eines Schlagwortes werden alle Beiträge aufgelistet, die dieses Schlagwort enthalten.', 'RT', 0, '#layout-sidebar SECTION DIV DIV.sidebar-widget-header :eq(1)', 'plugins.php/blubber/streams/global', '', 1405508505),
('3a717a468afb0822cb1455e0ae6b6fce', 9, 'Beitrag verlinken', 'Wird der Mauszeiger auf dem ersten Diskussionsbeitrag positioniert, erscheint links neben dem Datum ein Link-Icon. Wenn dieses mit der rechten Maustaste angeklickt wird, kann der Link auf diesen Beitrag kopiert werden, um ihn an anderer Stelle einfügen zu können.', 'BR', 0, 'DIV DIV A.permalink', 'plugins.php/blubber/streams/profile', '', 1405508281),
('6849293baa05be5bef8ff438dc7c438b', 1, 'Suche', 'Diese Tour gibt Ihnen einen Überblick über die wichtigsten Funktionen der \"Suche\".\r\n\r\nUm auf den nächsten Schritt zu kommen, klicken Sie bitte rechts unten auf \"Weiter\".', 'TL', 0, '', 'dispatch.php/search/courses', '', 1405519865),
('6849293baa05be5bef8ff438dc7c438b', 2, 'Suchbegriff eingeben', 'In dieses Eingabefeld kann ein Suchbegriff (wie z.B. der Veranstaltungsname, Dozent) eingegeben werden.', 'B', 0, 'INPUT#search_sem_quick_search_1.ui-autocomplete-input', 'dispatch.php/search/courses', '', 1405520106),
('6849293baa05be5bef8ff438dc7c438b', 3, 'Semesterauswahl', 'Durch einen Klick auf das Drop-Down Menü kann bestimmt werden, auf welches Semester sich der Suchbegriff beziehen soll. \r\n\r\nStandardgemäß ist das aktuelle Semester eingestellt.', 'TL', 0, 'SELECT#search_sem_sem', 'dispatch.php/search/courses', '', 1405520208),
('6849293baa05be5bef8ff438dc7c438b', 5, 'Erweiterte Suche', 'Mit der Erweiterten Suche kann die Suche um weitere Optionen erweitert werden.', 'R', 0, 'A.options-checkbox.options-unchecked', 'dispatch.php/search/courses', '', 1405520436),
('6849293baa05be5bef8ff438dc7c438b', 6, 'Schnellsuche', 'Die Schnellsuche ist auch auf anderen Seiten von Stud.IP jederzeit verfügbar. Nach der Eingabe eines Stichwortes, wird mit \"Enter\" bestätigt, oder auf die Lupe rechts neben dem Feld geklickt.', 'B', 0, 'INPUT#search_sem_quick_search_2.quicksearchbox.ui-autocomplete-input', 'dispatch.php/search/courses', '', 1405520634),
('6849293baa05be5bef8ff438dc7c438b', 7, 'Weitere Suchmöglichkeiten', 'Neben Veranstaltungen besteht auch die Möglichkeit, im Archiv, nach Personen, nach Einrichtungen oder nach Ressourcen zu suchen.', 'R', 0, '#nav_search_resources A SPAN', 'dispatch.php/search/courses', '', 1405520751),
('b74f8459dce2437463096d56db7c73b9', 1, 'Hilfe-Tour \"Meine Veranstaltungen\"', 'Diese Tour gibt einen Überblick über die wichtigsten Funktionen der Seite \"Meine Veranstaltungen\".\r\n\r\nUm auf den nächsten Schritt zu kommen, klicken Sie bitte rechts unten auf \"Weiter\".', 'TL', 0, '', 'dispatch.php/my_courses', '', 1405521184),
('b74f8459dce2437463096d56db7c73b9', 2, 'Veranstaltungsüberblick', 'Hier werden die Veranstaltungen des aktuellen und vergangenen Semesters angezeigt. Neue Veranstaltungen erscheinen zunächst in rot.', 'T', 0, '#my_seminars TABLE THEAD TR TH :eq(2)', 'dispatch.php/my_courses', '', 1405521244),
('154e711257d4d32d865fb8f5fb70ad72', 1, 'Meine Dateien', 'Meine Dateien ist der persönliche Dateibereich. Hier können Dateien auf Stud.IP gespeichert werden, um sie von dort auf andere Rechner herunterladen zu können.\r\n\r\nAndere Studierende oder Dozierende erhalten keinen Zugriff auf Dateien, die in den persönlichen Dateibereich hochgeladen werden.\r\n\r\nUm auf den nächsten Schritt zu kommen, klicken Sie bitte rechts unten auf \"Weiter\".', 'TL', 0, '', 'dispatch.php/document/files', '', 1405592884),
('154e711257d4d32d865fb8f5fb70ad72', 4, 'Dateiübersicht', 'Alle Dateien und Verzeichnisse werden tabellarisch aufgelistet. Neben dem Namen werden noch weitere Informationen wie der Dateityp oder die Dateigröße angezeigt.', 'TL', 0, '#layout_content FORM TABLE THEAD TR TH :eq(3)', 'dispatch.php/document/files', '', 1405593089),
('154e711257d4d32d865fb8f5fb70ad72', 3, 'Neue Dateien und Verzeichnisse', 'Hier können neue Dateien von dem Computer in den persönlichen Dateibereich hochgeladen und neue Verzeichnisse erstellt werden.', 'TL', 0, '#layout-sidebar SECTION DIV DIV UL LI A :eq(0)', 'dispatch.php/document/files', '', 1405593409),
('ef5092ba722c81c37a5a6bd703890bd9', 4, 'Personen erwähnen', 'Andere können über einen Beitrag informiert werden, indem sie per @benutzername oder @\"Vorname Nachname\" im Beitrag erwähnt werden.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/global', '', 1405672301),
('154e711257d4d32d865fb8f5fb70ad72', 6, 'Export', 'Hier besteht die Möglichkeit einzelne Ordner oder den vollständigen Dateibereich als ZIP-Datei herunterzuladen. Darin sind alle Dateien und Verzeichnisse enthalten.', 'TL', 0, '#layout-sidebar SECTION DIV DIV.sidebar-widget-header :eq(1)', 'dispatch.php/document/files', '', 1405593708),
('154e711257d4d32d865fb8f5fb70ad72', 5, 'Aktionen', 'Bereits hochgeladene Dateien und Ordner können hier bearbeitet, heruntergeladen, verschoben, kopiert und gelöscht werden.', 'TR', 0, '#layout_content FORM TABLE THEAD TR TH :eq(7)', 'dispatch.php/document/files', '', 1405594079),
('154e711257d4d32d865fb8f5fb70ad72', 2, 'Verfügbarer Speicherplatz', 'Der Speicherplatz des persönlichen Dateibereichs ist begrenzt. Es wird angezeigt, wie viel Speicherplatz noch verfügbar ist.', 'BR', 0, 'DIV.caption-actions', 'dispatch.php/document/files', '', 1405594184),
('edfcf78c614869724f93488c4ed09582', 5, 'Rundmail an Nutzergruppe versenden', 'Weiterhin besteht die Möglichkeit eine Rundmail an einzelne Nutzergruppen zu versenden.', 'BR', 0, '#layout_container #layout_content TABLE CAPTION SPAN A IMG :eq(0)', 'dispatch.php/course/members', '', 1406637123),
('25e7421f286fc5bdf9e41beadb484ffa', 4, 'Voraussetzungen', 'Eine Bilddatei muss im **.jpg**, **.png** oder **.gif** Format vorliegen.\r\nDie Dateigröße darf 700 KB nicht überschreiten.', 'L', 0, '#layout_content #edit_avatar TBODY TR TD FORM B :eq(2)', 'dispatch.php/settings/avatar', '', 1406722657),
('19ac063e8319310d059d28379139b1cf', 1, 'Studiengruppe anlegen', 'Studiengruppen ermöglichen die Zusammenarbeit mit KommilitonInnen oder KolegInnen. Diese Tour gibt Ihnen einen Überblick darüber wie Sie Studiengruppen anlegen können.\r\n\r\nUm zum nächsten Schritt zu gelangen, klicken Sie bitte rechts unten auf \"Weiter\".', 'R', 0, '', 'dispatch.php/my_studygroups', '', 1405684423),
('19ac063e8319310d059d28379139b1cf', 2, 'Studiengruppe anlegen', 'Mit Klick auf \"Neue Studiengruppe anlegen\" kann eine neue Studiengruppe angelegt werden.', 'R', 0, 'A#nav_browse_new', 'dispatch.php/my_studygroups', '', 1406017730),
('19ac063e8319310d059d28379139b1cf', 3, 'Studiengruppe benennen', 'Der Name einer Studiengruppe sollte aussagekräftig sein und einmalig im gesamten Stud.IP.', 'R', 0, 'INPUT#groupname', 'dispatch.php/course/studygroup/new', '', 1405684720),
('19ac063e8319310d059d28379139b1cf', 4, 'Beschreibung hinzufügen', 'Die Beschreibung ermöglicht es weitere Informationen anzuzeigen und somit das Auffinden der Gruppe zu erleichtern.', 'R', 0, 'TEXTAREA#groupdescription', 'dispatch.php/course/studygroup/new', '', 1405684806),
('19ac063e8319310d059d28379139b1cf', 8, 'Studiengruppe speichern', 'Nach dem Speichern einer Studiengruppe erscheint diese unter \"Veranstaltungen > Meine Studiengruppen\".', 'L', 0, '#layout_content FORM TABLE TBODY TR TD :eq(14)', 'dispatch.php/course/studygroup/new', '', 1405686068),
('19ac063e8319310d059d28379139b1cf', 5, 'Inhaltselemente zuordnen', 'Hier können Inhaltselemente aktiviert werden, welche innerhalb der Studiengruppe zur Verfügung stehen sollen. Das Fragezeichen gibt nähere Informationen zur Bedeutung der einzelnen Inhaltselemente.', 'L', 0, '#layout_content FORM TABLE TBODY TR TD :eq(5)', 'dispatch.php/course/studygroup/new', '', 1405685093),
('19ac063e8319310d059d28379139b1cf', 6, 'Zugang festlegen', 'Mit diesem Drop-down-Menü kann der Zugang zur Studiengruppe eingeschränkt werden.\r\n\r\nBeim Zugang \"offen für alle\" können sich alle Studierenden frei eintragen und an der Gruppe beteiligen.\r\n\r\nBeim Zugang \"Auf Anfrage\" müssen Teilnehmer durch den Gruppengründer hinzugefügt werden.', 'R', 0, 'SELECT#groupaccess', 'dispatch.php/course/studygroup/new', '', 1405685334),
('19ac063e8319310d059d28379139b1cf', 7, 'Nutzungsbedingungen akzeptieren', 'Bei der Erstellung einer Studiengruppe müssen die Nutzungsbedingungen akzeptiert werden.', 'R', 0, 'P LABEL', 'dispatch.php/course/studygroup/new', '', 1405685652),
('edfcf78c614869724f93488c4ed09582', 6, 'Gruppen erstellen', 'Hier können die TeilnehmerInnen der Veranstaltung in Gruppen eingeteilt werden.', 'R', 0, 'A#nav_course_edit_groups', 'dispatch.php/course/members', '', 1405689311),
('b74f8459dce2437463096d56db7c73b9', 3, 'Veranstaltungsdetails', 'Mit Klick auf das \"i\" erscheint ein Fenster mit den wichtigsten Eckdaten der Veranstaltung.', 'T', 0, '#my_seminars TABLE THEAD TR TH :eq(3)', 'dispatch.php/my_courses', '', 1405931069),
('edfcf78c614869724f93488c4ed09582', 7, 'Gruppe benennen', 'Sie können in den Vorlagen nach einem passenden Gruppennamen suchen und ihn mit dem gelben Doppelpfeil auswählen. Alternativ haben Sie auch die Möglichkeit, einen neuen Gruppennamen zu bestimmen, indem Sie im rechten Feld den Namen direkt eintragen.', 'B', 0, 'SELECT', 'admin_statusgruppe.php', '', 1405689541),
('edfcf78c614869724f93488c4ed09582', 1, 'Teilnehmerverwaltung', 'Diese Tour gibt einen Überblick über die Teilnehmerverwaltung einer Veranstaltung.\r\n\r\nUm zum nächsten Schritt zu gelangen, klicken Sie bitte rechts unten auf \"Weiter\".', 'B', 0, '', 'dispatch.php/course/members', '', 1405688399),
('edfcf78c614869724f93488c4ed09582', 2, 'Personen eintragen', 'Mit diesen Funktionen können entweder einzelne Personen in Stud.IP gesucht und direkt als DozentIn, TutorIn oder AutorIn eintragen werden. Es ist auch möglich eine Teilnehmerliste einzugeben, um viele Personen auf einmal als TutorIn der Veranstaltung zuzuordnen.', 'R', 0, '#layout-sidebar SECTION DIV.sidebar-widget :eq(1)', 'dispatch.php/course/members', '', 1405688707),
('edfcf78c614869724f93488c4ed09582', 4, 'Rundmail verschicken', 'Hier kann eine Rundmail an alle Teilnehmende der Veranstaltung verschickt werden.', 'R', 0, '#layout-sidebar SECTION DIV DIV UL LI A :eq(3)', 'dispatch.php/course/members', '', 1406636964),
('edfcf78c614869724f93488c4ed09582', 8, 'Gruppengröße', 'Mit dem Feld \"Gruppengröße\" können Sie die maximale Anzahl der Teilnehmer einer Gruppe festlegen. Wenn Sie dies nicht benötigen, lassen Sie das Feld einfach leer.', 'B', 0, 'INPUT#role_size', 'admin_statusgruppe.php', '', 1405689763),
('edfcf78c614869724f93488c4ed09582', 9, 'Selbsteintrag', 'Wenn Sie die Funktion \"Selbsteintrag\" aktivieren, können sich die Teilnehmenden der Veranstaltung selbst in die Gruppen eintragen.', 'B', 0, 'INPUT#self_assign', 'admin_statusgruppe.php', '', 1405689852),
('edfcf78c614869724f93488c4ed09582', 10, 'Dateiordner', 'Wenn Sie die Funktion \"Dateiordner\" aktivieren, wird zusätzlich ein Dateiordner pro Gruppe neu angelegt. In diesen Ordner können gruppenspezifische Dateien hochgeladen werden.', 'B', 0, 'INPUT#group_folder', 'admin_statusgruppe.php', '', 1405689936),
('edfcf78c614869724f93488c4ed09582', 3, 'Hochstufen / Herabstufen', 'Um eine bereits eingetragene Person zum/zur TutorIn hochzustufen oder zum/zur LeserIn herabzustufen, wählen Sie diese Person in der Liste aus und führen Sie mit Hilfe des Dropdown-Menü die gewünschte Aktion aus.', 'T', 0, '#autor CAPTION', 'dispatch.php/course/members', '', 1405690324),
('3a717a468afb0822cb1455e0ae6b6fce', 7, 'Schlagwortwolke', 'Durch Anklicken eines Schlagwortes werden alle Beiträge aufgelistet, die dieses Schlagwort enthalten.', 'RT', 0, 'DIV.sidebar-widget-header', 'plugins.php/blubber/streams/profile', '', 1405508505),
('b74f8459dce2437463096d56db7c73b9', 4, 'Veranstaltungsinhalte', 'Hier werden alle Inhalte (wie z.B. ein Forum) durch entsprechende Symbole angezeigt.\r\nFalls es seit dem letzten Login Neuigkeiten gab, erscheinen diese in rot.', 'LT', 0, '#my_seminars TABLE THEAD TR TH :eq(4)', 'dispatch.php/my_courses', '', 1405931225),
('b74f8459dce2437463096d56db7c73b9', 5, 'Verlassen der Veranstaltung', 'Ein Klick auf das Tür-Icon ermöglicht eine direkte Austragung aus der Veranstaltung.', 'TR', 0, '#my_seminars TABLE THEAD TR TH :eq(5)', 'dispatch.php/my_courses', '', 1405931272),
('b74f8459dce2437463096d56db7c73b9', 6, 'Zugriff auf archivierte Veranstaltungen', 'Falls Veranstaltungen archiviert sind, kann hier auf diese zugegriffen werden.', 'RT', 0, 'A#nav_browse_archive', 'dispatch.php/my_courses', '', 1405931431),
('3a717a468afb0822cb1455e0ae6b6fce', 2, 'Beitrag erstellen', 'Hier kann eine Diskussion durch Schreiben von Text begonnen werden. Absätze lassen sich durch Drücken von Umschalt+Eingabe erzeugen. Der Text wird durch Drücken von Eingabe abgeschickt.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/profile', '', 1405507478),
('b74f8459dce2437463096d56db7c73b9', 7, 'Anpassung der Veranstaltungsansicht', 'Zur Anpassung der Veranstaltungsübersicht, kann man die Veranstaltungen nach bestimmten Kriterien (wie z.B. Studienbereiche, Dozenten oder Farben) gliedern.', 'R', 0, '#layout-sidebar SECTION DIV DIV.sidebar-widget-header :eq(2)', 'dispatch.php/my_courses', '', 1405932131),
('b74f8459dce2437463096d56db7c73b9', 8, 'Zugriff auf Veranstaltung vergangener und zukünftiger Semester', 'Durch Klick auf das Drop-Down Menü können beispielsweise Veranstaltung aus vergangenen Semestern angezeigt werden.', 'R', 0, '#layout-sidebar SECTION DIV DIV.sidebar-widget-header :eq(3)', 'dispatch.php/my_courses', '', 1405932230),
('b74f8459dce2437463096d56db7c73b9', 9, 'Weitere mögliche Aktionen', 'Hier können Sie alle Neuigkeiten als gelesen markieren, Farbgruppierungen nach Belieben ändern oder\r\nauch die Benachrichtigungen über Aktivitäten in den einzelnen Veranstaltungen anpassen.', 'R', 0, '#layout-sidebar SECTION DIV DIV.sidebar-widget-header :eq(1)', 'dispatch.php/my_courses', '', 1405932320),
('977f41c5c5239c4e86f04c3df27fae38', 1, 'Willkommen im neuen Stud.IP 3.1', 'Dies ist eine Hilfe-Tour, die die wichtigsten Neuerungen in Stud.IP vorstellt. \r\n\r\nUm auf den nächsten Schritt zu kommen, klicken Sie bitte rechts unten auf \"Weiter\". Eine Hilfe-Tour kann jederzeit durch einen Klick auf \"Beenden\" beendet werden.', 'TL', 0, '', 'dispatch.php/start', '', 1405932373),
('977f41c5c5239c4e86f04c3df27fae38', 2, 'Hilfelasche', 'Auf jeder Seite findet sich die Hilfe von nun an in der sogenannten Hilfelasche. Diese öffnet sich mit einem Klick auf das Fragezeichen. \r\n\r\nHier findet sich kurz und knapp zu jeder Seite die wichtigsten Informationen, Links zur ausführlichen Hilfeseite mit Anleitungsvideos und gegebenenfalls Hilfe-Touren.', 'BR', 0, 'DIV.helpbar-container .helpbar-title', 'dispatch.php/start', '', 1405932475),
('977f41c5c5239c4e86f04c3df27fae38', 3, 'Gliederung der Startseite', 'Die Startseite im neuen Stud.IP ist standardmäßig so gegliedert wie die alte Version. Neu ist, dass jedes Element (\"Widget\") individuell entfernt und verschoben werden kann. Darüber hinaus können noch weitere Widgets hinzugefügt werden. Hierzu gibt es eine separate Hilfe-Tour und die Hinweise in der Hilfe.', 'TL', 0, '', 'dispatch.php/start', '', 1405932516),
('b74f8459dce2437463096d56db7c73b9', 10, 'Studiengruppen und Einrichtungen', 'Es besteht zudem die Möglichkeit auf persönliche Studiengruppen oder Einrichtungen zuzugreifen.', 'R', 0, '#nav_browse_my_institutes A', 'dispatch.php/my_courses', '', 1405932519),
('977f41c5c5239c4e86f04c3df27fae38', 4, 'Sidebar', 'Auf allen Seiten ist nun links die Sidebar positioniert. Sie enthält Funktionen für die aktuelle Seite.\r\nIm alten Stud.IP gab es mit der Infobox auf der rechten Seite etwas Ähnliches.', 'R', 0, 'SECTION.sidebar', 'dispatch.php/start', '', 1405932633),
('977f41c5c5239c4e86f04c3df27fae38', 5, 'Änderung der Navigation', 'Häufig ist die Reiternavigation vom alten Stud.IP nun in der Sidebar zu finden. Auf dieser Seite sind das zum Beispiel die Punkte \"Neue Nachricht schreiben\" und der Gesendet-Ordner.', 'R', 0, 'SECTION.sidebar ', 'dispatch.php/messages/overview', '', 1405932671),
('977f41c5c5239c4e86f04c3df27fae38', 6, 'Studiengruppen und Einrichtungen', 'Die Einrichtungen, die früher unter den Veranstaltungen standen und die Studiengruppen, die früher zwischen den Veranstaltungen standen, finden sich nun in eigenen Reitern wieder.', 'R', 0, '#nav_browse_my_institutes A SPAN', 'dispatch.php/my_courses', '', 1405932830),
('977f41c5c5239c4e86f04c3df27fae38', 7, 'Hinweise zu den Anmeldeverfahren', 'Im neuen Stud.IP haben sich die Zugangsberechtigungen und Anmeldeverfahren geändert. Das betrifft sowohl Studierende als auch Dozierende. Hierzu gibt es separate Feature-Touren und die Hinweise in der Hilfe.', 'TL', 0, '', 'dispatch.php/my_courses', '', 1405932890),
('3a717a468afb0822cb1455e0ae6b6fce', 1, 'Was ist Blubbern?', 'Diese Tour gibt Ihnen einen Überblick über die wichtigsten Funktionen von \"Blubber\".\r\n\r\nUm auf den nächsten Schritt zu kommen, klicken Sie bitte rechts unten auf \"Weiter\".', 'TL', 0, '', 'plugins.php/blubber/streams/profile', '', 1405507364),
('3a717a468afb0822cb1455e0ae6b6fce', 6, 'Schlagworte', 'Beiträge können mit Schlagworten (engl. \"Hashtags\") versehen werden, indem einem beliebigen Wort des Beitrags ein # vorangestellt wird.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/profile', '', 1405508442),
('49604a77654617a745e29ad6b253e491', 1, 'Funktionen und Gestaltungs-möglichkeiten der Startseite', '\r\nDiese Tour gibt Ihnen einen Überblick über die wichtigsten Funktionen der \"Startseite\".\r\n\r\nUm auf den nächsten Schritt zu kommen, klicken Sie bitte rechts unten auf \"Weiter\".', 'TL', 0, '', 'dispatch.php/start', '', 1405934926),
('49604a77654617a745e29ad6b253e491', 2, 'Individuelle Gestaltung der Startseite', 'Die Startseite ist standardmäßig so konfiguriert, dass die Elemente \"Schnellzugriff\", \"Ankündigungen\", \"Meine aktuellen Termine\" und \"Umfragen\" angezeigt werden. Die Elemente werden Widgets genannt und können entfernt, hinzugefügt und verschoben werde.n Jedes Widget kann individuell hinzugefügt, entfernt und verschoben werden.', 'TL', 0, '', 'dispatch.php/start', '', 1405934970),
('49604a77654617a745e29ad6b253e491', 3, 'Widget hinzufügen', 'Hier können Widgets hinzugefügt werden. Zusätzlich zu den Standard-Widgets kann beispielsweise der persönliche Stundenplan auf der Startseite anzeigt werden. Neu hinzugefügte Widgets erscheinen ganz unten auf der Startseite. Darüber hinaus kann in der Sidebar direkt zu jedem Widget gesprungen werden.', 'R', 0, '#layout-sidebar SECTION DIV DIV UL LI :eq(4)', 'dispatch.php/start', '', 1405935192),
('49604a77654617a745e29ad6b253e491', 5, 'Widget positionieren', 'Ein Widget kann per Drag&Drop an die gewünschte Position verschoben werden: Dazu wird in die Titelzeile eines Widgets geklickt, die Maustaste gedrückt gehalten und das Widget an die gewünschte Position gezogen.', 'B', 0, '.widget-header', 'dispatch.php/start', '', 1405935687),
('49604a77654617a745e29ad6b253e491', 7, 'Widget entfernen', 'Jedes Widget kann durch Klicken auf das X in der rechten oberen Ecke entfernt werden. Bei Bedarf kann es jederzeit wieder hinzugefügt werden.', 'R', 0, '.widget-header', 'dispatch.php/start', '', 1405935376),
('49604a77654617a745e29ad6b253e491', 6, 'Widget bearbeiten', 'Bei einigen Widgets wird neben dem X zum Schließen noch ein weiteres Symbol angezeigt. Der Schnellzugriff bspw. kann durch Klick auf diesen Button individuell angepasst, die Ankündigungen können abonniert und bei den aktuellen Terminen bzw. Stundenplan können Termine hinzugefügt werden.', 'L', 0, '#layout_content DIV UL DIV SPAN A IMG :eq(0)', 'dispatch.php/start', '', 1405935792),
('3629493a16bf2680de64361f07cab096', 1, 'Was ist Blubbern?', 'Diese Tour gibt Ihnen einen Überblick über die wichtigsten Funktionen von \"Blubber\".\r\n\r\nUm auf den nächsten Schritt zu kommen, klicken Sie bitte rechts unten auf \"Weiter\".', 'TL', 0, '', 'plugins.php/blubber/streams/forum', '', 1405507364),
('3a717a468afb0822cb1455e0ae6b6fce', 4, 'Personen erwähnen', 'Andere können über einen Beitrag informiert werden, indem sie per @benutzername oder @\"Vorname Nachname\" im Beitrag erwähnt werden.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/profile', '', 1405672301),
('3629493a16bf2680de64361f07cab096', 2, 'Beitrag erstellen', 'Hier kann eine Diskussion durch Schreiben von Text begonnen werden. Absätze lassen sich durch Drücken von Umschalt+Eingabe erzeugen. Der Text wird durch Drücken von Eingabe abgeschickt.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/forum', '', 1405507478),
('7cccbe3b22dfa745c17cb776fb04537c', 1, 'Hilfe-Tour \"Meine Veranstaltung\"', 'Diese Tour gibt einen Überblick über die wichtigsten Funktionen der Seite \"Meine Veranstaltungen\".\r\n\r\nUm auf den nächsten Schritt zu kommen, klicken Sie bitte rechts unten auf \"Weiter\".', 'TL', 0, '', 'dispatch.php/my_courses', '', 1406125847),
('7cccbe3b22dfa745c17cb776fb04537c', 2, 'Veranstaltungsüberblick', 'Hier werden die Veranstaltungen des aktuellen und vergangenen Semesters angezeigt. Neue Veranstaltungen erscheinen zunächst in rot.', 'TL', 0, '#my_seminars TABLE THEAD TR TH :eq(2)', 'dispatch.php/my_courses', '', 1406125908),
('7cccbe3b22dfa745c17cb776fb04537c', 3, 'Veranstaltungsdetails', 'Mit Klick auf das \"i\" erscheint ein Fenster mit den wichtigsten Eckdaten der Veranstaltung.', 'T', 0, '#my_seminars TABLE THEAD TR TH :eq(3)', 'dispatch.php/my_courses', '', 1406125992),
('7cccbe3b22dfa745c17cb776fb04537c', 4, 'Veranstaltungsinhalte', 'Hier werden alle Inhalte (wie z.B. ein Forum) durch entsprechende Symbole angezeigt.\r\nFalls es seit dem letzten Login Neuigkeiten gab, erscheinen diese in rot.', 'LT', 0, '#my_seminars TABLE THEAD TR TH :eq(4)', 'dispatch.php/my_courses', '', 1406126049),
('7cccbe3b22dfa745c17cb776fb04537c', 5, 'Bearbeitung oder Löschung einer Veranstaltung', 'Der Klick auf das Zahnrad ermöglicht die Bearbeitung einer Veranstaltung.\r\nFalls bei einer Veranstaltung Teilnehmerstatus besteht, kann hier eine Austragung, durch Klick auf dasTür-Icon, vorgenommen werden.', 'TR', 0, '#my_seminars TABLE THEAD TR TH :eq(5)', 'dispatch.php/my_courses', '', 1406126134),
('3a717a468afb0822cb1455e0ae6b6fce', 8, 'Beitrag ändern', 'Wird der Mauszeiger auf einem beliebigen Beitrag positioniert, erscheint dessen Datum. Bei eigenen Beiträgen erscheint außerdem rechts neben dem Datum ein Icon, mit dem der Beitrag nachträglich geändert werden kann.', 'BR', 0, 'DIV DIV A SPAN.time', 'plugins.php/blubber/streams/profile', '', 1405507901),
('7cccbe3b22dfa745c17cb776fb04537c', 6, 'Anpassung der Veranstaltungsansicht', 'Zur Anpassung der Veranstaltungsübersicht, kann man die Veranstaltungen nach bestimmten Kriterien (wie z.B. Studienbereiche, Dozenten oder Farben) gliedern.', 'R', 0, '#layout-sidebar SECTION DIV DIV.sidebar-widget-header :eq(2)', 'dispatch.php/my_courses', '', 1406126281),
('7cccbe3b22dfa745c17cb776fb04537c', 7, 'Zugriff auf Veranstaltung vergangener und zukünftiger Semester', 'Durch Klick auf das Drop-Down Menü können beispielsweise Veranstaltung aus vergangenen Semestern angezeigt werden.', 'R', 0, '#layout-sidebar SECTION DIV DIV.sidebar-widget-header :eq(3)', 'dispatch.php/my_courses', '', 1406126316),
('7cccbe3b22dfa745c17cb776fb04537c', 8, 'Weitere mögliche Aktionen', 'Hier können Sie alle Neuigkeiten als gelesen markieren, Farbgruppierungen nach Belieben ändern oder\r\nauch die Benachrichtigungen über Aktivitäten in den einzelnen Veranstaltungen anpassen.', 'R', 0, '#layout-sidebar SECTION DIV DIV.sidebar-widget-header :eq(1)', 'dispatch.php/my_courses', '', 1406126374),
('7cccbe3b22dfa745c17cb776fb04537c', 9, 'Studiengruppen und Einrichtungen', 'Es besteht zudem die Möglichkeit auf persönliche Studiengruppen oder Einrichtungen zuzugreifen.', 'R', 0, '#nav_browse_my_institutes A', 'dispatch.php/my_courses', '', 1406126415),
('3a717a468afb0822cb1455e0ae6b6fce', 5, 'Datei hinzufügen', 'Dateien können in einen Beitrag eingefügt werden, indem sie per Drag&Drop in ein Eingabefeld gezogen werden.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/profile', '', 1405508401),
('977f41c5c5239c4e86f04c3df27fae38', 8, 'Ende der Feature-Tour', 'Durch Klick auf \"Beenden\" in der Box rechts unten wird diese Tour beendet. Über die Hilfelasche lässt sich diese Tour jederzeit wieder starten.', 'TL', 0, '', 'dispatch.php/start', '', 1406539532),
('49604a77654617a745e29ad6b253e491', 4, 'Sprungmarken', 'Darüber hinaus kann mit Sprungmarken direkt zu jedem Widget gesprungen werden.', 'R', 0, '#layout-sidebar SECTION DIV DIV.sidebar-widget-header :eq(0)', 'dispatch.php/start', '', 1406623464),
('3629493a16bf2680de64361f07cab096', 5, 'Datei hinzufügen', 'Dateien können in einen Beitrag eingefügt werden, indem sie per Drag&Drop in ein Eingabefeld gezogen werden.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/forum', '', 1405508401),
('3629493a16bf2680de64361f07cab096', 6, 'Schlagworte', 'Beiträge können mit Schlagworten (engl. \"Hashtags\") versehen werden, indem einem beliebigen Wort des Beitrags ein # vorangestellt wird.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/forum', '', 1405508442),
('3629493a16bf2680de64361f07cab096', 7, 'Schlagwortwolke', 'Durch Anklicken eines Schlagwortes werden alle Beiträge aufgelistet, die dieses Schlagwort enthalten.', 'RT', 0, 'DIV.sidebar-widget-header', 'plugins.php/blubber/streams/forum', '', 1405508505),
('3629493a16bf2680de64361f07cab096', 4, 'Personen erwähnen', 'Andere können über einen Beitrag informiert werden, indem sie per @benutzername oder @\"Vorname Nachname\" im Beitrag erwähnt werden.', 'BL', 0, 'TEXTAREA#new_posting.autoresize', 'plugins.php/blubber/streams/forum', '', 1405672301);
";
DBManager::get()->exec($query);
// add settings
$query = "INSERT IGNORE INTO `help_tour_settings` (`tour_id`, `active`, `access`) VALUES
('96ea422f286fb5bbf9e41beadb484a9a', 1, 'standard'),
('25e7421f286fc5bdf9e41beadb484ffa', 1, 'standard'),
('3a717a468afb0822cb1455e0ae6b6fce', 1, 'standard'),
('21f487fa74e3bfc7789886f40fe4131a', 1, 'standard'),
('44f859c50648d3410c39207048ddd833', 1, 'standard'),
('ef5092ba722c81c37a5a6bd703890bd9', 1, 'standard'),
('6849293baa05be5bef8ff438dc7c438b', 1, 'standard'),
('b74f8459dce2437463096d56db7c73b9', 1, 'standard'),
('154e711257d4d32d865fb8f5fb70ad72', 1, 'standard'),
('19ac063e8319310d059d28379139b1cf', 1, 'standard'),
('edfcf78c614869724f93488c4ed09582', 1, 'standard'),
('977f41c5c5239c4e86f04c3df27fae38', 0, 'autostart_once'),
('49604a77654617a745e29ad6b253e491', 1, 'standard'),
('3629493a16bf2680de64361f07cab096', 1, 'standard'),
('7cccbe3b22dfa745c17cb776fb04537c', 1, 'standard');
";
DBManager::get()->exec($query);
}
function addHelpContent() {
$query = "INSERT IGNORE INTO `help_content` (`content_id`, `language`, `label`, `icon`, `content`, `route`, `studip_version`, `position`, `custom`, `visible`, `author_id`, `installation_id`, `mkdate`) VALUES
('5a90d1219dbeb07c124156592fb5d877', 'de', '', '', 'In den allgemeinen Einstellungen können verschiedene Anzeigeoptionen und Benachrichtigungsfunktionen ausgewählt und verändert werden.', 'dispatch.php/settings/general', '3.1', 0, 0, 1, '', '', 1406641688),
('a202eb75df0a1da2a309ad7a4abfac59', 'de', '', '', 'In den Privatsphäre-Einstellungen kann die Sichtbarkeit und Auffindbarkeit des eigenen Profils eingestellt werden.', 'dispatch.php/settings/privacy', '3.1', 0, 0, 1, '', '', 1406641688),
('845d1ce67a62d376ec26c8ffbb22d492', 'de', '', '', 'Die Einstellungen des Nachrichtensystems bieten die Möglichkeit z.B. eine Weiterleitung der in Stud.IP empfangenen Nachrichten an die E-Mail-Adresse zu veranlassen.', 'dispatch.php/settings/messaging', '3.1', 0, 0, 1, '', '', 1406641688),
('85cbaa1648af330cc4420b57df4be29c', 'de', '', '', 'Die Einstellungen des Terminkalenders bieten die Möglichkeit, diesen an eigene Bedürfnisse anzupassen.', 'dispatch.php/settings/calendar', '3.1', 0, 0, 1, '', '', 1406641688),
('1da144f3c6f52af0566c343151a6a6ff', 'de', '', '', 'In den Benachrichtigungseinstellungen kann ausgewählt werden, bei welchen Änderungen innerhalb einer Veranstaltung eine Benachrichtigung erfolgen soll.', 'dispatch.php/settings/notification', '3.1', 0, 0, 1, '', '', 1406641688),
('01ad8998268101ad186babf43dac30a4', 'de', '', '', 'In den Standard-Vertretungseinstellungen können Dozierende eine Standard-Vertretung festlegen, die alle Veranstaltungen des Dozierenden verwalten und ändern kann.', 'dispatch.php/settings/deputies', '3.1', 0, 0, 1, '', '', 1406641688),
('1c61657979ce22a9af023248a617f6b2', 'de', '', '', 'Die Startseite wird nach dem Einloggen angezeigt und kann an persönliche Bedürfnisse mit Hilfe von Widgets angepasst werden.', 'dispatch.php/start', '3.1', 0, 0, 1, '', '', 1406641688),
('74c1da86f33f5adfb43e10220bfad238', 'de', '', '', 'Die Veranstaltungsseite zeigt alle abonnierten Veranstaltungen (standardmäßig nur die der letzten beiden Semester), alle abonnierten Studiengruppen sowie alle Einrichtungen, denen man zugeordnet wurde. Die Anzeige lässt sich über Farbgruppierungen, Semesterfilter usw. anpassen.', 'dispatch.php/my_courses', '3.1', 0, 0, 1, '', '', 1406641688),
('437c83a27473ef8139b47198101067fb', 'de', '', '', 'Hier erscheinen archivierte Veranstaltungen, denen der Nutzer zugeordnet ist. Inhalte können nicht mehr verändert, jedoch hinterlegte Dateien als zip-Datei heruntergeladen werden.', 'dispatch.php/my_courses/archive', '3.1', 0, 0, 1, '', '', 1406641688),
('04457f9a66eab07618fe502d470a9711', 'de', '', '', 'In der Übersicht finden sich veranstaltungsbezogene Kurz- und Detail-Informationen, Ankündigungen, Termine und Umfragen.', 'dispatch.php/course/overview', '3.1', 0, 0, 1, '', '', 1406641688),
('1d1323471cf21637f51284f4e6f2d135', 'de', '', '', 'Detaillierte Informationen über die Veranstaltung werden angezeigt, wie z.B. die Veranstaltungsnummer, Zuordnungen, DozentInnen, TutorInnen etc. In den Detail-Informationen ist unter Aktionen das Eintragen in eine Veranstaltung möglich.', 'dispatch.php/course/details', '3.1', 0, 0, 1, '', '', 1406641688),
('7f4a1f5e3dfe2a459cf0eb357667d91c', 'de', '', '', 'Mit den Verwaltungsfunktionen lassen sich die Eigenschaften der Veranstaltung nachträglich ändern. Unter Aktionen ist die Simulation der Studierendenansicht möglich.', 'dispatch.php/course/management', '3.1', 0, 0, 1, '', '', 1406641688),
('4698cafeb9823735c50fd3a1745950ba', 'de', '', '', 'In den Grunddaten können Titel, Beschreibung, Dozierende etc. geändert werden. Die Bearbeitung kann teilweise gesperrt sein, wenn Daten aus anderen Systemen (z.B. LSF/ UniVZ) übernommen werden.', 'dispatch.php/course/basicdata/view', '3.1', 0, 0, 1, '', '', 1406641688),
('5fab81bbd1e19949f304df08ea21ca1b', 'de', '', '', 'Mit der Bild-Hochladen-Funktion lässt sich das Bild der Veranstaltung ändern, was Studierenden bei der Unterscheidung von Veranstaltungen auf der Meine-Veranstaltungen-Seite helfen kann.', 'dispatch.php/course/avatar/update', '3.1', 0, 0, 1, '', '', 1406641688),
('19c2bc232075602bd39efd4b6623d576', 'de', '', '', 'Mit der Studienbereiche-Funktion kann die Veranstaltung einem Studienbereich zugeordnet werden. Die Bearbeitung kann gesperrt sein, wenn Daten aus anderen Systemen (z.B. LSF/ UniVZ) übernommen werden.', 'dispatch.php/course/study_areas/show', '3.1', 0, 0, 1, '', '', 1406641688),
('70274c459a69e34bbf520e690a8e472b', 'de', '', '', 'Mit der Zeiten/Räume-Funktion können die Semester-, Termin- und Raumangaben der Veranstaltung geändert werden. Die Bearbeitung kann gesperrt sein, wenn Daten aus anderen Systemen (z.B. LSF/ UniVZ) übernommen werden.', 'raumzeit.php', '3.1', 0, 0, 1, '', '', 1406641688),
('19d47b782ac5c8b8b21bd1f94858a0fa', 'de', '', '', 'Mit Zugangsberechtigungen (Anmeldeverfahren) lässt sich z.B. durch Passwörter, Zeitsteuerung und TeilnehmerInnenbeschränkung der Zugang zu einer Veranstaltung regulieren.', 'dispatch.php/course/admission', '3.1', 0, 0, 1, '', '', 1406641688),
('e939ac70210674f49a36ac428167a9b8', 'de', '', '', 'Mit der Umfragen-und-Tests-Funktion lassen sich (zeitgesteuerte) Umfragen oder einzelne Multiple-/Single-Choice-Fragen für Veranstaltungen, Studiengruppen oder das Profil erstellen.', 'admin_vote.php', '3.1', 0, 0, 1, '', '', 1406641688),
('2689cecba24e021f05fcece5e4c96057', 'de', '', '', 'Mit der Evaluationen-Funktion lassen sich Befragungen mit Multiple-Choice, Likert- und Freitextfragen für Veranstaltungen, Studiengruppen, das eigene Profil oder Einrichtungen erstellen. Dabei können auch öffentliche Vorlagen anderer Personen verwendet werden. Es werden alle zukünftigen, laufenden und beendeten Evaluationen angezeigt.', 'admin_evaluation.php', '3.1', 0, 0, 1, '', '', 1406641688),
('194874212676ced8d45e1883da1ad456', 'de', '', '', 'Das Forum ist eine textbasierte, zeit- und ortsunabhängige Möglichkeit zum Austausch von Fragen, Meinungen und Erfahrungen. Beiträge können abonniert, exportiert, als Favoriten gekennzeichnet und editiert werden. Über die Navigation links können unterschieldiche Ansichten (z.B. Neue Beiträge seit letztem LogIn) gewählt werden.', 'plugins.php/coreforum', '3.1', 0, 0, 1, '', '', 1406641688),
('a20036992a06e97a984832626121d99a', 'de', '', '', 'Die TeilnehmerInnenliste zeigt eine Liste der Teilnehmenden dieser Veranstaltung. Weitere Teilnehmende können von Dozierenden hinzugefügt, entfernt, herabgestuft, heraufgestuft oder selbstdefinierten Gruppen zugeordnet werden.', 'dispatch.php/course/members', '3.1', 0, 0, 1, '', '', 1406641688),
('d79ca3bc4a8251862339b1c934504a54', 'de', '', '', 'Hier werden die selbstdefinierten Gruppen angezeigt. An diese können Nachrichten versendet werden. Ein Klick auf die orangenen Pfeile vor dem Gruppenname ordnet Sie der Gruppe zu.', 'statusgruppen.php', '3.1', 0, 0, 1, '', '', 1406641688),
('e22701c71b4425fb5a95adf725866097', 'de', '', '', 'Hier können Gruppen erstellt und verwaltet werden. Wenn der Selbsteintrag aktiviert ist, können sich TeilnehmerInnen selbst ein- und austragen.', 'admin_statusgruppe.php', '3.1', 0, 0, 1, '', '', 1406641688),
('aa77d5ee6e0f9a9e6f4a1bbabeaf4a7e', 'de', '', '', 'Die Anwesenheitsliste zeigt alle Sitzungstermine (Sitzung, Vorlesung, Übung, Praktikum) des Ablaufplans und ermöglicht das Eintragen von Studierenden durch die Dozierenden in Stud.IP sowie einen Export der Liste zur Übersicht oder als Grundlage handschriftlicher Eintragungen.', 'participantsattendanceplugin/show', '3.1', 0, 0, 1, '', '', 1406641688),
('ac7326260fd5ca4fa83c1154f2ffc7b9', 'de', '', '', 'Die Dateiverwaltung bietet die Möglichkeit zum Hochladen, Verlinken, Verwalten und Herunterladen von Dateien. ', 'folder.php', '3.1', 0, 0, 1, '', '', 1406641688),
('29c3bfa01ddbaaa998094d3ee975a06a', 'de', '', '', 'Der Ablaufplan zeigt Termine, Themen und Räume der Veranstaltung an. Einzelne Termine können bearbeitet werden, z.B. können Themen zu Terminen hinzugefügt werden.', 'dispatch.php/course/dates', '3.1', 0, 0, 1, '', '', 1406641688),
('c4dee277f741cfa7d5a65fa0c6bead4c', 'de', '', '', 'Hier können Termine mit Themen versehen werden oder bereits eingegebene Themen übernommen und bearbeitet werden.', 'dispatch.php/course/topics', '3.1', 0, 0, 1, '', '', 1406641688),
('c01725d6a3da568e1b07aee4e68a7e1f', 'de', '', '', 'Diese Seite ermöglicht das Hinterlegen von freien Informationen, Links etc.', 'dispatch.php/course/scm', '3.1', 0, 0, 1, '', '', 1406641688),
('be204bdd0fce91702f51597bf8428fba', 'de', '', '', 'Das Wiki ermöglicht ein gemeinsames, asynchrones Erstellen und Bearbeiten von Texten. Texte lassen sich formatieren und miteinander verknüpfen, so dass ein verzweigtes Nachschlagewerk entsteht. ', 'wiki.php', '3.1', 0, 0, 1, '', '', 1406641688),
('707b0db0e45fc3bab04be7eff38c1d32', 'de', '', '', 'Die Literaturseite bietet Lehrenden die Möglichkeit, Literaturlisten zu erstellen oder aus Literaturverwaltungsprogrammen zu importieren. Diese Listen können in Lehrveranstaltungen kopiert und sichtbar geschaltet werden. Je nach Anbindung kann im tatsächlichen Buchbestand der Hochschule recherchiert werden. ', 'dispatch.php/course/literature', '3.1', 0, 0, 1, '', '', 1406641688),
('8dd3b80d9f95218d67edc3cb570559ff', 'de', '', '', 'Hier lassen sich Literaturlisten bearbeiten und in der Veranstaltung sichtbar schalten (mit Klick auf das \"Auge\").', 'dispatch.php/literature/edit_list', '3.1', 0, 0, 1, '', '', 1406641688),
('e29098d188ae25c298d78978de50bf09', 'de', '', '', 'Hier kann in Katalogen nach Literatur gesucht und diese zur Merkliste hinzugefügt werden.', 'dispatch.php/literature/search', '3.1', 0, 0, 1, '', '', 1406641688),
('a1ea37130799a59f7774473f1a681141', 'de', '', '', 'Die Lernmodulschnittstelle ermöglicht es, Selbstlerneinheiten oder Tests aus externen Programmen wie ILIAS und LON-CAPA in Stud.IP zur Verfügung zu stellen.', 'dispatch.php/course/elearning/show', '3.1', 0, 0, 1, '', '', 1406641688),
('595c46d86f681f7da4bd2fae780db618', 'de', '', '', 'Wählen Sie das gewünschte System und anschließend das Lernmodul/ den Test aus. Schreibrechte bestimmen, wer zukünftig das Lernmodul bearbeiten darf. In der Sidebar befindet sich die Option \"Zuordnungen aktualisieren\", um geänderte Inhalte z.B. im ILIAS Kurs zu Stud.IP zu übertragen.', 'dispatch.php/course/elearning/edit', '3.1', 0, 0, 1, '', '', 1406641688),
('6529fd70b461fa4a9242e874fbf2a5d3', 'de', '', '', 'In DoIT! haben Lehrende die Möglichkeit, verschiedene Arten von Aufgaben zu stellen, inklusive Hochladen von Dateien, Multiple-Choice-Fragen und Peer Reviewing. Die Aufgabenbearbeitung kann zeitlich befristet werden und wahlweise in Gruppen erfolgen.', 'plugins.php/reloadedplugin/show', '3.1', 0, 0, 1, '', '', 1406641688),
('95ff3a2a68dae73bcb14a4a538a8e4b5', 'de', '', '', 'Blubbern ist eine Mischform aus Forum und Chat, bei dem Beiträge der Teilnehmenden in Echtzeit angezeigt werden. Andere können über einen Beitrag informiert werden, indem sie per @benutzername oder @\"Vorname Nachname\" im Beitrag erwähnt werden.', 'plugins.php/blubber/streams/forum', '3.1', 0, 0, 1, '', '', 1406641688),
('633dab120ce3969c42f33aeb3a59fcc1', 'de', '', '', 'Der Gruppenkalender bietet eine Übersicht über Veranstaltungstermine und personalisierte Zusatztermine für diese Veranstaltung. ', 'plugins.php/gruppenkalenderplugin/show', '3.1', 0, 0, 1, '', '', 1406641688),
('1058f03da5b6fc6a5ff3a08c9c1fa5f7', 'de', '', '', 'Hier können der Veranstaltung weitere Funktionen hinzugefügt werden.', 'dispatch.php/course/plus', '3.1', 0, 0, 1, '', '', 1406641688),
('8a1d7d04c70d93be44e8fe6a8e8c3443', 'de', '', '', 'Das Lerntagebuch unterstützt den selbstgesteuerten Lernprozess der Studierenden und wird von ihnen selbstständig geführt. Anfragen zu Arbeitsschritten an die Dozierenden sind möglich, bestimmte Daten können individualisiert freigegeben werden.', 'plugins.php/lerntagebuchplugin/overview', '3.1', 0, 0, 1, '', '', 1406641688),
('72cec29d985f3e6d7df2b5fabb7fe666', 'de', '', '', 'Konfiguation des Lerntagebuchs für Studierende und Anlegen eines Lerntagebuchs für die Dozierenden.', 'plugins.php/lerntagebuchplugin/admin_settings', '3.1', 0, 0, 1, '', '', 1406641688),
('2fcc672d91f2627ab5ca48499e8b1617', 'de', '', '', 'Möglichkeit zur Bereitstellung von Vorlesungsaufzeichnungen und Podcasts für Studierende der Veranstaltung (durch Verlinkung auf die Dateien auf dem Medienserver). ', 'plugins.php/mediacastsplugin/show', '3.1', 0, 0, 1, '', '', 1406641688),
('bd0770f9eef5c10fc211114ac35fbe9b', 'de', '', '', 'Diese Seite zeigt die Studiengruppen an, denen die/der NutzerIn zugeordnet ist. Studiengruppen sind eine einfache Möglichkeit, mit Mitstudierenden, KollegInnen und anderen zusammenzuarbeiten. Jede/r NutzerIn kann Studiengruppen anlegen oder nach ihnen suchen. Die Farbgruppierung kann individuell angepasst werden.', 'dispatch.php/my_studygroups', '3.1', 0, 0, 1, '', '', 1406641688),
('82a17a5f19d211268b1fa90a1ebe0894', 'de', '', '', 'Hier kann eine neue Studiengruppe angelegt werden. Jede/r Stud.IP-NutzerIn kann Studiengruppen anlegen und nach eigenen Bedürfnissen konfigurieren.', 'dispatch.php/course/studygroup/new', '3.1', 0, 0, 1, '', '', 1406641688),
('e03cec310c0a884aee80c2d1eea3a53e', 'de', '', '', 'Diese Seite zeigt alle Studiengruppen an, die in Stud.IP existieren. Studiengruppen sind eine einfache Möglichkeit, mit Mitstudierenden, KollegInnen und anderen zusammenzuarbeiten. Jede/r NutzerIn kann Studiengruppen anlegen oder nach ihnen suchen.', 'dispatch.php/studygroup/browse', '3.1', 0, 0, 1, '', '', 1406641688),
('f92b5422246f585f051de1a81602dd56', 'de', '', '', 'Hier können Name, Funktionen und Zugangsbeschränkung der Studiengruppe bearbeitet werden.', 'dispatch.php/course/studygroup/edit', '3.1', 0, 0, 1, '', '', 1406641688),
('1dca5b0b83f7bca92ec4add50d34b8c5', 'de', '', '', 'Hier können der Studiengruppe Mitglieder hinzugefügt und Nachrichten an diese versendet werden.', 'dispatch.php/course/studygroup/members', '3.1', 0, 0, 1, '', '', 1406641688),
('1f6e2f98affbffb1d12904355e9313e5', 'de', '', '', 'Diese Seite zeigt die Einrichtungen an, denen die/der NutzerIn zugeordnet ist.', 'dispatch.php/my_institutes', '3.1', 0, 0, 1, '', '', 1406641688),
('bf9eb8f2c3842865009342b89fd35476', 'de', '', '', 'Die Nachrichtenseite bietet einen Überblick über erhaltene, systeminterne Nachrichten, welche mit selbstgewählten Schlüsselwörtern (sog. Tags) versehen werden können, um sie später leichter wieder auffinden zu können.', 'dispatch.php/messages/overview', '3.1', 0, 0, 1, '', '', 1406641688),
('6acc653cfabd3a0d4433ff0ab417bf6a', 'de', '', '', 'Übersicht über gesendete, systeminterne Nachrichten, welche mit selbstgewählten Schlüsselwörtern (sog. Tags) versehen werden können, um sie später leichter wieder auffinden zu können. ', 'dispatch.php/messages/sent', '3.1', 0, 0, 1, '', '', 1406641688),
('690e6eff3e83a5f372ec99fc49cafeb2', 'de', '', '', 'Blubbern ist das Stud.IP Echtzeitforum, eine Mischform aus Forum und Chat. Andere können über einen Beitrag informiert werden, indem sie per @benutzername oder @\"Vorname Nachname\" im Beitrag erwähnt werden. Texte lassen sich formatieren und durch Smileys ergänzen.', 'plugins.php/blubber/streams/global', '3.1', 0, 0, 1, '', '', 1406641688),
('cd69b74cd46172785bf2147fb0582e3c', 'de', '', '', 'Hier kann ein benutzerdefinierter Blubber-Stream erstellt werden. Er besteht immer aus einer Sammlung von Beiträgen aus ausgewählten Veranstaltungen, Kontaktgruppen und Schlagwörten, die auf Basis einer Filterung noch weiter eingeschränkt werden können. Der neue benutzerdefinierte Stream findet sich nach dem Klick auf den Speichern-Button in der Navigation unter Globaler Stream.', 'plugins.php/blubber/streams/edit', '3.1', 0, 0, 1, '', '', 1406641688),
('394a45f94e1d84d3744027a5a69d9e3e', 'de', '', '', 'Auf dieser Seite lässt sich einsehen, welche Kontakte gerade online sind. Diesen Personen kann eine Nachricht geschickt werden. Das Klicken auf den Namen einer Person leitet zu deren Profil weiter.', 'dispatch.php/online', '3.1', 0, 0, 1, '', '', 1406641688),
('245ce01d7a0175ab0b977ae822821e9e', 'de', '', '', 'Diese Seite bietet die Möglichkeit Stud.IP-Nutzende in das eigene Adressbuch einzutragen und alle bereits im Adressbuch befindlichen Kontakte aufzulisten.', 'contact.php', '3.1', 0, 0, 1, '', '', 1406641688),
('752d441cd321b05c55c8a5d9aa48ddce', 'de', '', '', 'Auf dieser Seite können Kontakte aus dem Adressbuch in selbstdefinierte Gruppen sortiert werden.', 'contact_statusgruppen.php', '3.1', 0, 0, 1, '', '', 1406641688),
('94a193baa212abbc9004280a1498e724', 'de', '', '', 'Hier können Kontaktgruppen oder das gesamte Adressbuch exportiert werden, um sie in einem externen Programm importieren zu können.', 'contact_export.php', '3.1', 0, 0, 1, '', '', 1406641688),
('7ebdd278d06f9fc1d2659a54bb3171c1', 'de', '', '', 'Die Rangliste sortiert die Stud.IP-Nutzenden absteigend anhand ihrer Punktzahl. Die Punktzahl wächst mit den Aktivitäten in Stud.IP und repräsentiert so die Erfahrung der Nutzenden mit dem System. Indem das Kästchen links mit einem Haken versehen wird, wird der eigene Wert für andere NutzerInnen in der Rangliste sichtbar gemacht. In der Grundeinstellung ist der eigene Wert nicht öffentlich sichtbar.', 'dispatch.php/score', '3.1', 0, 0, 1, '', '', 1406641688),
('82537b14dd3714ec9636124ed5af3272', 'de', '', '', 'Die Profilseite ermöglicht die Änderung der eigenen Nutzerdaten inkl. Profilbild und Kategorien. Ähnlich wie in Facebook können Kommentare hinterlassen werden. Das Profil von Lehrenden enthält Sprechstunden und Raumangaben. Daneben bietet die Seite die Verwaltung eigener Dateien.', 'dispatch.php/profile', '3.1', 0, 0, 1, '', '', 1406641688),
('ebb5bc1d831d460c06e3c6662236c159', 'de', '', '', 'Hier kann ein Profilbild hochgeladen werden.', 'dispatch.php/settings/avatar', '3.1', 0, 0, 1, '', '', 1406641688),
('25255dc15fd0d6260bc1abd1f10aecc5', 'de', '', '', 'Individuelle Nutzerdaten, wie bspw. E-Mail-Adresse, können auf dieser Seite verändert und angepasst werden. ', 'dispatch.php/settings/account', '3.1', 0, 0, 1, '', '', 1406641688),
('d704267767d4c559aa9e552be60c49b5', 'de', '', '', 'Hier kann das Passwort für den Stud.IP-Account geändert werden.', 'dispatch.php/settings/password', '3.1', 0, 0, 1, '', '', 1406641688),
('cbd9b2b22fc00bc92df3589018644b70', 'de', '', '', 'Hier können vordefinierte Informationen über die eigene Person eingegeben werden, die auf der Profilseite erscheinen sollen. ', 'dispatch.php/settings/details', '3.1', 0, 0, 1, '', '', 1406641688),
('4e60dd9635f3d3fddecc78e0d1f646c7', 'de', '', '', 'Unter \"Studiendaten\" können manuell zusätzliche Studiengänge und Einrichtungen hinzugefügt werden, wenn sie nicht automatisch aus einem externen System (z.B. LSF/ UniVZ) übernommen wurden.', 'dispatch.php/settings/studies', '3.1', 0, 0, 1, '', '', 1406641688),
('462f1447b1a8a93ab7bdb2524f968b1a', 'de', '', '', 'Hier kann die Zugehörigkeit zu Nutzerdomänen eingesehen, aber nicht geändert werden.', 'dispatch.php/settings/userdomains', '3.1', 0, 0, 1, '', '', 1406641688),
('233564d01b8301ebec7ef2fe918d1290', 'de', '', '', 'Ansicht über die der/ dem Stud.IP-NutzerIn zugeordneten Einrichtungen.', 'dispatch.php/settings/statusgruppen', '3.1', 0, 0, 1, '', '', 1406641688),
('e315a4c547be7f17d427b227f0f9d982', 'de', '', '', 'Auf dieser Seite können selbstdefinierte Informationen über die eigene Person eingegeben werden, die auf der Profilseite erscheinen sollen. ', 'dispatch.php/settings/categories', '3.1', 0, 0, 1, '', '', 1406641688),
('ac5df1de9c75fc92af7718b2103d3037', 'de', '', '', 'Blubbern ist eine Mischform aus Forum und Chat. Nachrichten werden im öffentlichen Stream dargestellt. Andere Nutzer können über einen Beitrag informiert werden, indem sie per @benutzername oder @\"Vorname Nachname\" im Beitrag erwähnt werden.', 'plugins.php/blubber/streams/profile', '3.1', 0, 0, 1, '', '', 1406641688),
('4151003175042b71bea3529e5adc5a9e', 'de', '', '', 'Mit der Terminvergabe können Termine für Sprechstunden, Prüfungen usw. angelegt werden, in die sich Studierende selbst eintragen können.', 'plugins.php/homepageterminvergabeplugin/showadmin', '3.1', 0, 0, 1, '', '', 1406641688),
('63c2ecb12f30816aef0fb203eab4f40a', 'de', '', '', 'Hier können Termine angelegt und bearbeitet werden.', 'plugins.php/homepageterminvergabeplugin/show_category', '3.1', 0, 0, 1, '', '', 1406641688),
('164f77ab2cb7d38fd1ea20ed725834fd', 'de', '', '', 'Hier findet sich eine Übersicht über die Termine, die von Studierenden gebucht wurden.', 'plugins.php/homepageterminvergabeplugin/show_bookings', '3.1', 0, 0, 1, '', '', 1406641688),
('1289e991a93dce5a0b4edd678514325e', 'de', '', '', 'Hier können einzelne Inhaltselemente nachträglich aktiviert oder deaktiviert werden. Aktivierte Inhaltselemente fügen neue Funktionen zu Ihrem Profil oder Ihren Einstellungen hinzu. Diese werden meist als neuer Reiter im Menü erscheinen. Wenn Funktionalitäten nicht benötigt werden, können diese hier deaktiviert werden. Die entsprechenden Menüpunkte werden dann ausgeblendet.', 'dispatch.php/profilemodules', '3.1', 0, 0, 1, '', '', 1406641688),
('b677e8b5f1bd7e8acbe474177449c4e1', 'de', '', '', 'Die Dateiverwaltung bietet die Möglichkeit zum Hochladen, Verwalten und Herunterladen persönlicher Dateien, die nicht für andere einsehbar sind. ', 'dispatch.php/document/files', '3.1', 0, 0, 1, '', '', 1406641688),
('35b1860b95854a2533b6ecfbbf04ab71', 'de', '', '', 'Der Stundenplan besteht aus abonnierten Veranstaltungen, die ein- und ausgeblendet sowie in Darstellungsgröße und -form angepasst werden können.', 'dispatch.php/calendar/schedule', '3.1', 0, 0, 1, '', '', 1406641688),
('db5a995bd12ba8e2ae96adcabeb8c8f7', 'de', '', '', 'Der Terminkalender besteht aus abonnierten Veranstaltungen und eigenen Terminen. Er kann bearbeitet, in der Anzeige verändert und mit externen Programmen (z.B. Outlook) abgeglichen werden. ', 'calendar.php', '3.1', 0, 0, 1, '', '', 1406641688),
('87489a40097e5c26f1d1349c072610de', 'de', '', '', 'Mit der Veranstaltungssuche können Veranstaltungen, Studiengruppen usw. in verschiedenen Semestern und nach verschiedenen Suchkriterien (siehe \"Erweiterte Suche anzeigen\"in der Sidebar) gefunden werden. Das aktuelle Semester ist vorgewählt.', 'dispatch.php/search/courses', '3.1', 0, 0, 1, '', '', 1406641688),
('74863847eec53a3d4c8264d8de526be8', 'de', '', '', 'Mit der Archivsuche können Veranstaltungen gefunden werden, die bereits archiviert wurden.', 'archiv.php', '3.1', 0, 0, 1, '', '', 1406641688),
('14b77e9e0b7773c92db9e7344a23fcfc', 'de', '', '', 'Mit der Personensuche können NutzerInnen gefunden werden, solange deren Privatsphäre-Einstellung dies nicht verhindert. Die Suche kann auf bestimmte Veranstaltungen oder Einrichtungen begrenzt werden.', 'browse.php', '3.1', 0, 0, 1, '', '', 1406641688),
('4f9d79fe88e81486b8c1f192d70232d5', 'de', '', '', 'Mit der Einrichtungssuche können Einrichtungen über ein freies Suchfeld oder den Einrichtungsbaum gefunden werden.', 'institut_browse.php', '3.1', 0, 0, 1, '', '', 1406641688),
('014a2106d384c0ca55d9311597029ca0', 'de', '', '', 'Mit der Ressourcensuche können universitäre Ressourcen wie Räume, Gebäude etc. gefunden werden.', 'resources.php', '3.1', 0, 0, 1, '', '', 1406641688),
('60b6caf75d0004dfdb0a1adfd66027ed', 'de', '', '', 'Hier können Dozierende Ankündigungen für ihre Veranstaltungen, Einrichtungen und ihre Profilseite erstellen und anzeigen, wobei die Anzeige gefiltert werden kann.', 'dispatch.php/news/admin_news', '3.1', 0, 0, 1, '', '', 1406641688),
('f3deb7a01205637d71a66e2b90b24cba', 'de', '', '', 'Hier können RSS-Feeds, d.h. Nachrichtenströme von externen Internetseiten, auf der Startseite eingebunden werden. Je mehr Feeds eingebunden werden, desto länger dauert das Laden der Startseite.', 'dispatch.php/admin/rss_feeds', '3.1', 0, 0, 1, '', '', 1406641688),
('bc1d6ecab9364cfe2c549d262bfda437', 'de', '', '', 'Die Lernmodulschnittstelle ermöglicht es, Selbstlerneinheiten aus externen Programmen wie ILIAS und LON-CAPA in Stud.IP zur Verfügung zu stellen. Für jedes externe System wird ein eigener Benutzer-Account erstellt oder zugeordnet. Mit den entsprechenden Rechten können eigene Lernmodule erstellt werden.', 'dispatch.php/elearning/my_accounts', '3.1', 0, 0, 1, '', '', 1406641688),
('d1de152db139d8c12552610d2f7999c2', 'de', '', '', 'Mit dem Export können Daten über Veranstaltungen und MitarbeiterInnen in folgende Formate exportiert werden: RTF, TXT, CSV, PDF, HTML und XML.', 'export.php', '3.1', 0, 0, 1, '', '', 1406641688),
('2c55eab1f52d6f7d1021880836906f5b', 'de', '', '', 'Hier lassen sich Literaturlisten bearbeiten und in der Veranstaltung sichtbar schalten (mit Klick auf das \"Auge\").', 'dispatch.php/literature/edit_list.php', '3.1', 0, 0, 1, '', '', 1406641688);
";
DBManager::get()->exec($query);
}
function addHelpContentEN() {
$query = "
INSERT INTO `help_content` (`content_id`, `language`, `label`, `icon`, `content`, `route`, `studip_version`, `position`, `custom`, `visible`, `author_id`, `installation_id`, `mkdate`) VALUES
('c8e789a0efb73f00f00dacf565524c73', 'en', '', '', 'Various display options and notification features can be selected and changed in the general settings.', 'dispatch.php/settings/general', '3.1', 0, 0, 1, '', '', 1412942388),
('f5e59c4fc98e1df7fe29b8e9320853e7', 'en', '', '', 'The visibility and searchability for the own profile can be set in the privacy settings.', 'dispatch.php/settings/privacy', '3.1', 0, 0, 1, '', '', 1412942388),
('3b7a4c04017fef2984ee029610194f26', 'en', '', '', 'The settings of the message system offer the possibility e.g. to arrange for a forwarding of the messages received in Stud.IP to your e-mail address.', 'dispatch.php/settings/messaging', '3.1', 0, 0, 1, '', '', 1412942388),
('260ee12fdc7dccb30eca2cc075ef0096', 'en', '', '', 'The settings of the diary offer the possibility to adjust these to own needs .', 'dispatch.php/settings/calendar', '3.1', 0, 0, 1, '', '', 1412942388),
('43df8e33145c25eb6d941e4e845ada24', 'en', '', '', 'In the notification settings it is possible to select with which changes within a course notification is to be given.', 'dispatch.php/settings/notification', '3.1', 0, 0, 1, '', '', 1412942388),
('85c000e33732c5596d198776cb884860', 'en', '', '', 'In the standard substitution settings lecturers can stipulate a standard substitution, which can manage and change all courses of the lecturer.', 'dispatch.php/settings/deputies', '3.1', 0, 0, 1, '', '', 1412942388),
('b05b27450e363c38c6b4620b902b3496', 'en', '', '', 'The start page will be displayed after the log-in and can be customised to personal needs by using widgets.', 'dispatch.php/start', '3.1', 0, 0, 1, '', '', 1412942388),
('91d6f451c3ef8d8352a076773b0a19ee', 'en', '', '', 'The course page shows all subscribed courses (as a standard only those of the last two semesters), all subscribed study groups as well as all institutions, to which one was allocated. You can customise the display through colour groupings, semester filters, etc. ', 'dispatch.php/my_courses', '3.1', 0, 0, 1, '', '', 1412942388),
('0237ea35a203be81e44c979d82ef5ee6', 'en', '', '', 'Archived courses to which the user is allocated appear here. Contents can no longer be changed, however deposited documents can be downloaded as a zip file.', 'dispatch.php/my_courses/archive', '3.1', 0, 0, 1, '', '', 1412942388),
('d97eff1196f6aed8e94f7c5096ebd2a9', 'en', '', '', 'Course-related brief and detailed information, announcements, dates and surveys can be found in the overview.', 'dispatch.php/course/overview', '3.1', 0, 0, 1, '', '', 1412942388),
('357bbf06015b2738aae15837f581a07d', 'en', '', '', 'More detailed information about the course is displayed, such as e.g. the course number, allocations, lecturers, tutors, etc. In the detailed information it is possible to register for a course under actions.', 'dispatch.php/course/details', '3.1', 0, 0, 1, '', '', 1412942388),
('0c055cc6ae418a96ff3afa9db13098df', 'en', '', '', 'The properties of the course can be subsequently changed with the management functions. The simulation of the students view is possible under actions.', 'dispatch.php/course/management', '3.1', 0, 0, 1, '', '', 1412942388),
('615c1887f0ee080043f133681ebf0def', 'en', '', '', 'Title, description, lecturer, etc. can be changed in the basic data. The processing can partly be blocked if data are taken over from other systems (e.g. LSF/ UniVZ).', 'dispatch.php/course/basicdata/view', '3.1', 0, 0, 1, '', '', 1412942388),
('abfb5d03de288d02df436f9a8bb96d9d', 'en', '', '', 'The photo of the course, which can help students to distinguish between courses on the \"my courses\" page, can be changed with the photo-upload-function.', 'dispatch.php/course/avatar/update', '3.1', 0, 0, 1, '', '', 1412942388),
('eec46c5d8ea5523d959a8c334455c2ef', 'en', '', '', 'The course can be allocated to a field of study by using the field of study function. The processing can be blocked if data are taken over from other systems (e.g. LSF/ UniVZ).', 'dispatch.php/course/study_areas/show', '3.1', 0, 0, 1, '', '', 1412942388),
('85c709de75085bd56a739e4e8ac6fcad', 'en', '', '', 'The semester, date and room details of the course can be changed by using the time/room function. The processing can be blocked if data are taken over from other systems (e.g. LSF/ UniVZ).', 'raumzeit.php', '3.1', 0, 0, 1, '', '', 1412942388),
('4e14c94cda99e2ef6462f7fef06d9c91', 'en', '', '', 'The access to a course can be regulated with access authorisations (enrolment procedure) e.g. by passwords, time control and restriction to participants.', 'dispatch.php/course/admission', '3.1', 0, 0, 1, '', '', 1412942388),
('42060187921376807f90e52fad5f9822', 'en', '', '', '(Time-controlled) surveys or individual Multiple-/Single-Choice questions can be set up for courses, study groups or the profile by using the survey and test function.', 'admin_vote.php', '3.1', 0, 0, 1, '', '', 1412942388),
('5475d65b07fdaf5f234bf6eed3d5e4a9', 'en', '', '', 'With the evaluation function surveys can be set up with Multiple-Choice, Likert and free text questions for courses, study groups, the own profile or institutions. Public templates of other persons can be used hereby. All future, ongoing and ended evaluations are displayed.', 'admin_evaluation.php', '3.1', 0, 0, 1, '', '', 1412942388),
('80286432bf17df20e5f11f86b421b0a7', 'en', '', '', 'The forum is a text-based possibility, which is irrespective of time and place, to exchange questions, opinions and experience. Contributions can be subscribed to, exported, marked as favourites and edited. Various views (e.g. new contributions since the last login) can be chosen via the navigation links.', 'plugins.php/coreforum', '3.1', 0, 0, 1, '', '', 1412942388),
('3607d6daea679dcd7003e076fdd1660a', 'en', '', '', 'The list of participants shows a list of the participants of this course. Further participants can be added, removed, downgraded, upgraded or allocated to self-defined groups by lecturers.', 'dispatch.php/course/members', '3.1', 0, 0, 1, '', '', 1412942388),
('f529bca4d1626b43cbb8149feea41a84', 'en', '', '', 'The self-defined groups are displayed here. Messages can be sent to these. A click on the orange arrows before the group name will allocate you to the group.', 'statusgruppen.php', '3.1', 0, 0, 1, '', '', 1412942388),
('bd5df4fb7b84da79149c96c5f43de46c', 'en', '', '', 'Groups can be set up and managed here. If the self-entry is activated participants can enter and remove themselves.', 'admin_statusgruppe.php', '3.1', 0, 0, 1, '', '', 1412942388),
('8c2fc90bd8175e6d598f895944a8ddc2', 'en', '', '', 'The attendance list shows all meetings (meeting, lecture, exercise, internship) of the schedule and enables the entry of students in Stud.IP by the lecturers as well as an export of the list for the overview or as a basis for handwritten entries.', 'participantsattendanceplugin/show', '3.1', 0, 0, 1, '', '', 1412942388),
('ee91ec0f9085221ada06d171a27d2405', 'en', '', '', 'The document administration offers the possibility to upload, link, administer and download documents. ', 'folder.php', '3.1', 0, 0, 1, '', '', 1412942388),
('8c3067596811d3c6857d253299e01f6f', 'en', '', '', 'The schedule displays dates, topics and rooms of the course. Individual dates can be edited, e.g. topics can be added to dates.', 'dispatch.php/course/dates', '3.1', 0, 0, 1, '', '', 1412942388),
('1f216fe42d879c3fcbb582d67e9ad5a2', 'en', '', '', 'Dates can be allocated topics here or already entered topics can be taken over and edited.', 'dispatch.php/course/topics', '3.1', 0, 0, 1, '', '', 1412942388),
('abaa7b076e6923ac43120f3326322af0', 'en', '', '', 'This page enables the deposit of free information, links, etc.', 'dispatch.php/course/scm', '3.1', 0, 0, 1, '', '', 1412942388),
('7edc08f2f7b0786ca036f8c448441e07', 'en', '', '', 'The Wiki enables a joint, asynchronous creation and editing of texts. Texts can be formatted and linked with each other so that a branched reference work is produced. ', 'wiki.php', '3.1', 0, 0, 1, '', '', 1412942388),
('44edb997707d1458cbf8a3f8f316b908', 'en', '', '', 'The bibliography page offers lecturers the possibility to create bibliographies or to import these from bibliography management programmes. These lists can be copied and placed visibly in courses. Research can be conducted in the actual book stocks of the university depending on the connection. ', 'dispatch.php/course/literature', '3.1', 0, 0, 1, '', '', 1412942388),
('1cb8fd77427ebc092d751eea95454b0a', 'en', '', '', 'Bibliographies can be edited here and placed visibly in the course (with a click on the \"eye\").', 'dispatch.php/literature/edit_list', '3.1', 0, 0, 1, '', '', 1412942388),
('b283b58820db358284f4451dfb691678', 'en', '', '', 'A search can be conducted for literature in catalogues here and these added to the clipboard.', 'dispatch.php/literature/search', '3.1', 0, 0, 1, '', '', 1412942388),
('0d83ce036f2870f873446230c0118bb7', 'en', '', '', 'The learning module interface makes it possible for self-learning units or tests to be made available from external programmes such as ILIAS and LON-CAPA in Stud.IP.', 'dispatch.php/course/elearning/show', '3.1', 0, 0, 1, '', '', 1412942388),
('8b690f942bf0cc0322e5bea0f1b9abed', 'en', '', '', 'Select the requested system and subsequently the learning module/ the test. Writing rights determine who may edit the learning module in future. The option \"update allocations\" is located in the sidebar in order to transfer changed contents e.g. in the ILIAS course to Stud.IP.', 'dispatch.php/course/elearning/edit', '3.1', 0, 0, 1, '', '', 1412942388),
('0838a96b5678e2fc26be0ee38ae67619', 'en', '', '', 'In DoIT! lecturers have the possibility to set various types of tasks, including the uploading of files, Multiple-Choice questions and Peer Reviewing. The processing of tasks can be time limited and alternatively carried out in groups.', 'plugins.php/reloadedplugin/show', '3.1', 0, 0, 1, '', '', 1412942388),
('1804e526c2f6794b877a4b2096eaa67a', 'en', '', '', 'Blubbering is a mixed form of forum and chat, with which contributions of the participants are displayed in real time. Others can be informed about a contribution by the fact that they are mentioned in the contribution by @user name or @''first name''.', 'plugins.php/blubber/streams/forum', '3.1', 0, 0, 1, '', '', 1412942388),
('38d1a86517eb6cc195b2e921270c3035', 'en', '', '', 'The group calendar offers an overview of course dates and personalised additional dates for this course. ', 'plugins.php/gruppenkalenderplugin/show', '3.1', 0, 0, 1, '', '', 1412942388),
('852991dc733639dd2df05fb627abf3db', 'en', '', '', 'Further features can be added to the course here.', 'dispatch.php/course/plus', '3.1', 0, 0, 1, '', '', 1412942388),
('1ea099717ceb1b401aedcedc89814d9c', 'en', '', '', 'The learning diary supports the self-controlled learning process of the students and is kept independently by them. Enquiries for work steps to the lecturers are possible, certain data can be released individualised.', 'plugins.php/lerntagebuchplugin/overview', '3.1', 0, 0, 1, '', '', 1412942388),
('2075fe42f56207fbd153a810188f1beb', 'en', '', '', 'Configuration of the learning diary for students and creation of a learning diary for the lecturers.', 'plugins.php/lerntagebuchplugin/admin_settings', '3.1', 0, 0, 1, '', '', 1412942388),
('7465a4aeedb6a320d3455cf9ad0bebd0', 'en', '', '', 'Possibility for providing lecture recordings and pod casts for students of the course (by linking to the documents on the media server). ', 'plugins.php/mediacastsplugin/show', '3.1', 0, 0, 1, '', '', 1412942388),
('02b4e3ce7b8fe6b3e6a3586d410a51a1', 'en', '', '', 'This page displays the study groups to which the user is allocated. Study groups are a simple possibility to cooperate with fellow students, colleagues and others. Each user can create study groups or search for them. The colour grouping can be adjusted individually.', 'dispatch.php/my_studygroups', '3.1', 0, 0, 1, '', '', 1412942388),
('af7573cce1e898054db89a96284866f9', 'en', '', '', 'A new study group can be created here. Each Stud.IP user can create study groups and configure these according to own needs.', 'dispatch.php/course/studygroup/new', '3.1', 0, 0, 1, '', '', 1412942388),
('960d7bafb618853eced1b1b42a7dd412', 'en', '', '', 'This page displays all study groups, which exist in Stud.IP. Study groups are a simple possibility to cooperate with fellow students, colleagues and others. Each user can create study groups or search for them.', 'dispatch.php/studygroup/browse', '3.1', 0, 0, 1, '', '', 1412942388),
('3d040e95a8c29e733a8d5439ee9f5b59', 'en', '', '', 'The name, functions and access restriction of the study group can be edited here.', 'dispatch.php/course/studygroup/edit', '3.1', 0, 0, 1, '', '', 1412942388),
('b3bd33cb0babbb0cc51a4f429d15d438', 'en', '', '', 'Here you can add new memebers to the study group und send them messages.', 'dispatch.php/course/studygroup/members', '3.1', 0, 0, 1, '', '', 1412942388),
('438c4456f85afec29fd9f47c111136c1', 'en', '', '', 'This page displays the institutions to which the user is allocated.', 'dispatch.php/my_institutes', '3.1', 0, 0, 1, '', '', 1412942388),
('f966e348174927565b94e606bbcf064f', 'en', '', '', 'The message page offers an overview on received, system-internal messages, which can be issued with self-chosen key words (so-called tags) in order to subsequently be able to find them easier.', 'dispatch.php/messages/overview', '3.1', 0, 0, 1, '', '', 1412942388),
('ceb21257092b11dcf6897d5bb3085642', 'en', '', '', 'Overview on sent, system-internal messages, which can be issued with self-chosen key words (so-called \"tags\") in order to subsequently be able to find them easier. ', 'dispatch.php/messages/sent', '3.1', 0, 0, 1, '', '', 1412942388),
('b9586c280a0092f86f9392fe5b5ff2a0', 'en', '', '', 'Blubbering is the Stud.IP real time forum, a mixed form of forum and chat. Others can be informed about a contribution by the fact that they are mentioned in the contribution by @user name or @''first name''. Texts can be formatted and supplemented by Smileys.', 'plugins.php/blubber/streams/global', '3.1', 0, 0, 1, '', '', 1412942388),
('7cb7026818c4b90935009d0548300674', 'en', '', '', 'A user-defined blubber stream can be created here. It always consists of a collection of contributions from selected courses, contact groups and key words, which can be restricted even further based on a filtering. The new user-defined stream can be found after clicking on the save button in the navigation under global stream.', 'plugins.php/blubber/streams/edit', '3.1', 0, 0, 1, '', '', 1412942388),
('2f1602394a4e31c2e30706f0a0b3112f', 'en', '', '', 'On this page it can be viewed which contacts are online at the moment. A message can be sent to these persons. The clicking on the name of one person forwards to their profile.', 'dispatch.php/online', '3.1', 0, 0, 1, '', '', 1412942388),
('27c4d9837cfb1a9a40c079e16daac902', 'en', '', '', 'This page offers the possibility to enter Stud.IP users in the address book and to list all contacts who can already be found in the address book.', 'contact.php', '3.1', 0, 0, 1, '', '', 1412942388),
('362a67fff2ef7af8cca9f8e20583c9f2', 'en', '', '', 'Contacts from the address book can be displayed sorted according to the groups here.', '???', '3.1', 0, 0, 1, '', '', 1412942388),
('6b331f5cc2176daba82a0cc71aaa576f', 'en', '', '', 'Contacts from the address book can be sorted in self-defined groups on this page.', 'contact_statusgruppen.php', '3.1', 0, 0, 1, '', '', 1412942388),
('57f1b29d3c1a558f5cc799c1aade7f14', 'en', '', '', 'Contact groups or the whole address book can be exported here in order to be able to import them in an external programme.', 'contact_export.php', '3.1', 0, 0, 1, '', '', 1412942388),
('90ffbd715843b02b3961907f81caf208', 'en', '', '', 'The ranking sorts the Stud.IP users in descending order based on their number of points. The number of points will grow with the activities in Stud.IP and thus represents the experience of the users with the system. By entering a check mark in the little box on the left the own value will be made visible in the ranking for other users. The own value is not visible to the public in the basic settings.', 'dispatch.php/score', '3.1', 0, 0, 1, '', '', 1412942388),
('e5bff29f7adee43202a2aa8f3f0a6ec7', 'en', '', '', 'You can change your own user data incl. profile photo and categories here. Comments can be left similar to Facebook. The profile of lecturers includes consulting hours and room details. In addition the page offers the administration of own documents.', 'dispatch.php/profile', '3.1', 0, 0, 1, '', '', 1412942388),
('2a389c2472656121a76ca4f3b0e137d4', 'en', '', '', 'A profile photo can be uploaded here.', 'dispatch.php/settings/avatar', '3.1', 0, 0, 1, '', '', 1412942388),
('fe23b56f4d691c0f5e2f872e37ce38b5', 'en', '', '', 'You can change and customise your individual user data, such as for example mail address, on this page. ', 'dispatch.php/settings/account', '3.1', 0, 0, 1, '', '', 1412942388),
('b32cb2c4ec56e925b07a5cb0105a6888', 'en', '', '', 'The password for the Stud.IP-Account can be changed here.', 'dispatch.php/settings/password', '3.1', 0, 0, 1, '', '', 1412942388),
('83fd70727605c485a0d8f2c5ef94289b', 'en', '', '', 'Pre-defined information about the own person can be entered here, which is to appear on the profile page. ', 'dispatch.php/settings/details', '3.1', 0, 0, 1, '', '', 1412942388),
('970ebdf39ad5ca89083a52723c5c35f5', 'en', '', '', 'Additional courses of study and institutions can be added manually under \"study details\", if they are not automatically taken over from an external system (e.g. LSF/UniVZ).', 'dispatch.php/settings/studies', '3.1', 0, 0, 1, '', '', 1412942388),
('0e816d9428a3bc8a73fb0042fb2da540', 'en', '', '', 'The affiliation to user domains can be viewed, however not changed, here.', 'dispatch.php/settings/userdomains', '3.1', 0, 0, 1, '', '', 1412942388),
('d04ca1f9e867ee295a3025dac7ce9c7b', 'en', '', '', 'View of the institutions allocated to the Stud.IP user.', 'dispatch.php/settings/statusgruppen', '3.1', 0, 0, 1, '', '', 1412942388),
('8ad364363acd415631226d5574d5592a', 'en', '', '', 'Self-defined information about the own person can be entered on this page, which is to appear on the profile page. ', 'dispatch.php/settings/categories', '3.1', 0, 0, 1, '', '', 1412942388),
('51a0399250de6365619c961ec3669ad3', 'en', '', '', 'Blubbering is a mixed form of forum and chat. Messages are presented in the public stream. Other users can be informed about a contribution by the fact that they are mentioned in the contribution by @user name or @''first name last name''.', 'plugins.php/blubber/streams/profile', '3.1', 0, 0, 1, '', '', 1412942388),
('5ae72abc0822570bfe839e3ee24f0c81', 'en', '', '', 'With the allocation of dates, dates can be created for consulting hours, examinations, etc., in which students can enter themselves.', 'plugins.php/homepageterminvergabeplugin/showadmin', '3.1', 0, 0, 1, '', '', 1412942388),
('76195b21d485823fd7ca2fd499131c12', 'en', '', '', 'Dates can be created and edited here.', 'plugins.php/homepageterminvergabeplugin/show_category', '3.1', 0, 0, 1, '', '', 1412942388),
('0ad754cc62d1e86e97c1a28dd68ac40c', 'en', '', '', 'An overview on the dates, which were booked by students can be found here.', 'plugins.php/homepageterminvergabeplugin/show_bookings', '3.1', 0, 0, 1, '', '', 1412942388),
('b5fabb1e5aed7ff8520314e9a86c5c87', 'en', '', '', 'Individual content elements can be subsequently activated or deactivated here. Activated content elements add new functions to your profile or your settings. These will mostly appear as a new tab in the menu. If functionalities are not required these can be deactivated here. The corresponding menu tabs are then faded out.', 'dispatch.php/profilemodules/index', '3.1', 0, 0, 1, '', '', 1412942388),
('51b98d659590e1e37dae5e5e5cc028bb', 'en', '', '', 'The document administration offers the possibility to upload, manage and download personal documents,which cannot be viewed by others. ', 'dispatch.php/document/files', '3.1', 0, 0, 1, '', '', 1412942388),
('440e50f7fcc825368aa9026273d2cd0d', 'en', '', '', 'The schedule of studies consists of subscribed courses, which can be faded in and out as well as customised in the size and form of the presentation.', 'dispatch.php/calendar/schedule', '3.1', 0, 0, 1, '', '', 1412942388),
('dddf5fd4406da0d91c9f121fcae607ad', 'en', '', '', 'The diary consists of subscribed courses and own dates. It can be edited, change in the display and compared with external programmes (e.g. Outlook). ', 'calendar.php', '3.1', 0, 0, 1, '', '', 1412942388),
('a1e3da35edc9b605f670e9c7f5019888', 'en', '', '', 'With the course search courses, study groups, etc. can be found in various semesters and according to various search criteria (see \"display extended search\" in the sidebar). The current semester is pre-selected.', 'dispatch.php/search/courses', '3.1', 0, 0, 1, '', '', 1412942388),
('7d40379f54250b550065e062d71e8fd8', 'en', '', '', 'Various courses can be found with the archive search, which have already been archived.', 'archiv.php', '3.1', 0, 0, 1, '', '', 1412942388),
('ebcc460880b8a63af3f6e7eade97db78', 'en', '', '', 'Users can be found with the search for persons as long as their privacy setting does not prevent this. The search can be limited to certain courses or institutions.', 'browse.php', '3.1', 0, 0, 1, '', '', 1412942388),
('8a32ca4e602a68307d4ae6ae51fa667e', 'en', '', '', 'With the institution search institutions can be found via a free search field or the institution tree', 'institut_browse.php', '3.1', 0, 0, 1, '', '', 1412942388),
('e206a4257e31a0f32ac516cefb8e8331', 'en', '', '', 'University resources such as rooms, buildings, etc. can be found using the resource search.', 'resources.php', '3.1', 0, 0, 1, '', '', 1412942388),
('3318ee99a062079b463e902348ad520e', 'en', '', '', 'Lecturers can create and display announcements for their courses, institutions and their profile page here, whereby the display can be filtered.', 'dispatch.php/news/admin_news', '3.1', 0, 0, 1, '', '', 1412942388),
('bcdedaf1b4bd3b96ef574e8230095b28', 'en', '', '', 'RSS-Feeds, i.e. message streams of external websites, can be integrated onto the start page here. The more feeds are integrated, the longer the loading of the start page will take.', 'dispatch.php/admin/rss_feeds', '3.1', 0, 0, 1, '', '', 1412942388),
('bfb70d5f036769d740fb2342b0b58183', 'en', '', '', 'The learning module interface makes it possible for self-learning units to be made available from external programmes such as ILIAS and LON-CAPA in Stud.IP. An own user account will be created or allocated for each external system. Own learning modules can be created with the corresponding rights.', 'dispatch.php/elearning/my_accounts', '3.1', 0, 0, 1, '', '', 1412942388),
('7bf322a6c5f13db67e047b7afae83e58', 'en', '', '', 'With the export data about courses and employees can be exported in the following formats: RTF, TXT, CSV, PDF, HTML and XML.', 'export.php', '3.1', 0, 0, 1, '', '', 1412942388),
('fa4bf491690645a5f12556f77e51233c', 'en', '', '', 'Bibliographies can be edited here and placed visibly in the course (with a click on the \"eye\").', 'dispatch.php/literature/edit_list.php', '3.1', 0, 0, 1, '', '', 1412942388);
";
DBManager::get()->exec($query);
}
}
|
gpl-2.0
|
emabiz/e-works-codecpack
|
common/video/dll_misc_lib/bitstreamer.cpp
|
3046
|
#include "stdafx.h"
#include "bitstreamer.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
namespace ew {
//////////////////////////////////////////////////////////////////////
// BitWriter
//////////////////////////////////////////////////////////////////////
BitWriter::BitWriter(unsigned char *buffer, int buffer_byte_size)
: buffer_(buffer),
buffer_byte_size_(buffer_byte_size),
next_bit_in_byte_(0),
byte_pos_(0)
{
_ASSERT(NULL != buffer);
_ASSERT(buffer_byte_size > 0);
memset(buffer_, 0, buffer_byte_size_);
}
bool BitWriter::PutByteBits(unsigned char bits, int n_bits)
{
_ASSERT(1 <= n_bits && n_bits <= 8);
// numeric value must be inside specified bit number range
if (bits >= (1 << n_bits))
return false;
int bit_end = next_bit_in_byte_ + n_bits; // first available position for next step
if (bit_end > 8) {
bit_end -= 8;
if (byte_pos_ + 1 >= buffer_byte_size_)
return false;
unsigned char l_mask = 0xff << (8 - next_bit_in_byte_);
unsigned char r_mask = 0xff >> bit_end;
unsigned char l_value = bits >> (next_bit_in_byte_ - (8 - n_bits));
unsigned char r_value = bits << (8 - bit_end);
buffer_[byte_pos_] = (buffer_[byte_pos_] & l_mask) | l_value;
++byte_pos_;
buffer_[byte_pos_] = (buffer_[byte_pos_] & r_mask) | r_value;
next_bit_in_byte_ = bit_end;
} else {
unsigned char mask = 0xff << (8 - next_bit_in_byte_);
unsigned char value = bits << (8 - bit_end);
buffer_[byte_pos_] = (buffer_[byte_pos_] & mask) | value;
next_bit_in_byte_ += n_bits;
if (8 == next_bit_in_byte_) {
next_bit_in_byte_ = 0;
++byte_pos_;
}
}
return true;
}
//////////////////////////////////////////////////////////////////////
// BitReader
//////////////////////////////////////////////////////////////////////
BitReader::BitReader(const unsigned char *buffer, int buffer_byte_size)
: buffer_(buffer),
buffer_byte_size_(buffer_byte_size),
next_bit_in_byte_(0),
byte_pos_(0)
{
_ASSERT(NULL != buffer);
_ASSERT(buffer_byte_size > 0);
}
bool BitReader::GetByteBits(unsigned char *bits, int n_bits)
{
_ASSERT(NULL != bits);
_ASSERT(1 <= n_bits && n_bits <= 8);
int bit_end = next_bit_in_byte_ + n_bits; // next position to be read on next step
if (bit_end > 8) {
bit_end -= 8;
if (byte_pos_ + 1 >= buffer_byte_size_)
return false;
unsigned char l_mask = 0xff << (8 - next_bit_in_byte_);
unsigned char r_mask = 0xff >> bit_end;
unsigned char l_value = buffer_[byte_pos_] & ~l_mask;
++byte_pos_;
unsigned char r_value = buffer_[byte_pos_] & ~r_mask;
*bits = (l_value << (next_bit_in_byte_ - (8 - n_bits)))
| (r_value >> (8 - bit_end));
next_bit_in_byte_ = bit_end;
} else {
unsigned char mask = 0xff << (8 - next_bit_in_byte_);
unsigned char value = buffer_[byte_pos_] & ~mask;
*bits = value >> (8 - bit_end);
next_bit_in_byte_ += n_bits;
if (8 == next_bit_in_byte_) {
next_bit_in_byte_ = 0;
++byte_pos_;
}
}
return true;
}
} // namespace ew
|
gpl-2.0
|
EasyLovine/ZencTbi
|
js/script_marque.js
|
550
|
$(document).ready(function() {
/** Bottom **/
$(".blocBottom").hover(function(e){
$(this).find('.bottomButton').slideDown();
},function(e){
$(this).find('.bottomButton').slideUp();
});
/** Left **/
$(".blocLeft").hover(function(e){
$(this).find('.buttonLeft').css("width" , "100px");
},function(e){
$(this).find('.buttonLeft').css("width" , "0");
});
/** Right **/
$(".blocRight").hover(function(e){
$(this).find('.buttonRight').css("width" , "100px");
},function(e){
$(this).find('.buttonRight').css("width" , "0");
});
});
|
gpl-2.0
|
chorizon/mail_unix
|
models/models_mail.php
|
937
|
<?php
use PhangoApp\PhaModels\Webmodel;
use PhangoApp\PhaModels\CoreFields\ForeignKeyField;
use PhangoApp\PhaModels\CoreFields\IntegerField;
use PhangoApp\PhaModels\CoreFields\CharField;
use PhangoApp\PhaModels\CoreFields\BooleanField;
Webmodel::load_model('vendor/chorizon/theservers/models/models_servers');
Webmodel::load_model('vendor/chorizon/theusers/models/models_theusers');
$mail_server=new Webmodel('mail_server_unix');
$mail_server->register('domain', new CharField(255), true);
$mail_server->register('user', new ForeignKeyField(Webmodel::$model['theuser']), true);
$mail_server->set_field('user', array('name_field_to_field' => 'username'));
$mail_server->register('server', new ForeignKeyField(Webmodel::$model['server']), true);
$mail_server->register('quota', new IntegerField(11));
$mail_server->register('num_accounts', new IntegerField(11), false);
$mail_server->register('status', new BooleanField(11));
?>
|
gpl-2.0
|
inverse-inc/packetfence
|
html/pfappserver/root/src/views/Status/_router/index.js
|
1019
|
import acl from '@/utils/acl'
import store from '@/store'
import StatusView from '../'
import StatusStore from '../_store'
import ClusterRoutes from '../cluster/_router'
import DashboardRoutes from '../dashboard/_router'
import QueueRoutes from '../queue/_router'
import NetworkRoutes from '../network/_router'
import ServicesRoutes from '../services/_router'
const route = {
path: '/status',
name: 'status',
redirect: '/status/dashboard',
component: StatusView,
meta: {
can: () => acl.can('master tenant') || acl.$some('read', ['system', 'services']), // has ACL for 1+ children
transitionDelay: 300 * 2 // See _transitions.scss => $slide-bottom-duration
},
beforeEnter: (to, from, next) => {
if (!store.state.$_status) {
// Register store module only once
store.registerModule('$_status', StatusStore)
}
next()
},
children: [
...ClusterRoutes,
...DashboardRoutes,
...QueueRoutes,
...NetworkRoutes,
...ServicesRoutes,
]
}
export default route
|
gpl-2.0
|
mulligaj/hubzero-cms
|
core/components/com_tools/tables/sessionclassgroup.php
|
5918
|
<?php
/**
* HUBzero CMS
*
* Copyright 2005-2015 HUBzero Foundation, LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* HUBzero is a registered trademark of Purdue University.
*
* @package hubzero-cms
* @author Shawn Rice <zooley@purdue.edu>
* @copyright Copyright 2005-2015 HUBzero Foundation, LLC.
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Components\Tools\Tables;
use Hubzero\Database\Table;
use Lang;
/**
* Members quota classes db table class
*/
class SessionClassGroup extends Table
{
/**
* Constructor
*
* @param object &$db Database
* @return void
*/
public function __construct(&$db)
{
parent::__construct('#__tool_session_class_groups', 'id', $db);
}
/**
* Override the check function to do a little input cleanup
*
* @return boolean True if valid, False if not
*/
public function check()
{
if (!$this->class_id)
{
$this->setError(Lang::txt('COM_TOOLS_SESSION_CLASS_MUST_HAVE_CLASS_ID'));
}
if (!$this->class_id)
{
$this->setError(Lang::txt('COM_TOOLS_SESSION_CLASS_MUST_HAVE_GROUP_ID'));
}
if ($this->getError())
{
return false;
}
return true;
}
/**
* Build query method
*
* @param array $filters
* @return string Database query
*/
protected function _buildQuery($filters=array())
{
$query = "FROM $this->_tbl AS qcg";
$where = array();
if (isset($filters['group_id']))
{
if (!is_array($filters['group_id']))
{
$filters['group_id'] = array($filters['group_id']);
}
$filters['group_id'] = array_map('intval', $filters['group_id']);
$where[] = "`group_id` IN (" . implode(',', $filters['group_id']) . ")";
}
if (isset($filters['class_id']))
{
if (!is_array($filters['class_id']))
{
$filters['class_id'] = array($filters['class_id']);
}
$filters['class_id'] = array_map('intval', $filters['class_id']);
$where[] = "`class_id` IN (" . implode(',', $filters['class_id']) . ")";
}
if (count($where))
{
$query .= " WHERE " . implode(" AND ", $where);
}
return $query;
}
/**
* Return data based on a set of filters. Returned value
* can be integer, object, or array
*
* @param string $what
* @param array $filters
* @return mixed
*/
public function find($what='', $filters=array())
{
$what = strtolower(trim($what));
switch ($what)
{
case 'count':
$query = "SELECT COUNT(*) " . $this->_buildQuery($filters);
$this->_db->setQuery($query);
return $this->_db->loadResult();
break;
case 'one':
$filters['limit'] = 1;
$result = null;
if ($results = $this->find('list', $filters))
{
$result = $results[0];
}
return $result;
break;
case 'first':
$filters['start'] = 0;
$filters['limit'] = 1;
$result = null;
if ($results = $this->find('list', $filters))
{
$result = $results[0];
}
return $result;
break;
case 'all':
if (isset($filters['limit']))
{
unset($filters['limit']);
}
return $this->find('list', $filters);
break;
case 'list':
default:
$query = "SELECT qcg.* " . $this->_buildQuery($filters);
if (!isset($filters['sort']) || !$filters['sort'])
{
$filters['sort'] = 'id';
}
if (!isset($filters['sort_Dir']) || !$filters['sort_Dir'])
{
$filters['sort_Dir'] = 'ASC';
}
$query .= " ORDER BY " . $filters['sort'] . " " . $filters['sort_Dir'];
if (isset($filters['limit']) && $filters['limit'] > 0)
{
$filters['start'] = (isset($filters['start']) ? $filters['start'] : 0);
$query .= " LIMIT " . (int) $filters['start'] . "," . (int) $filters['limit'];
}
$this->_db->setQuery($query);
return $this->_db->loadObjectList();
break;
}
}
/**
* Delete records by class ID
*
* @param integer $class_id Quota Class ID
* @return boolean True on success
*/
public function deleteByClassId($class_id=null)
{
$class_id = $class_id ?: $this->class_id;
if (!$class_id)
{
$this->setError(Lang::txt('No class ID provided.'));
return false;
}
$this->_db->setQuery("DELETE FROM `$this->_tbl` WHERE `class_id`=" . $this->_db->quote($class_id));
if (!$this->_db->query())
{
$this->setError($this->_db->getErrorMsg());
return false;
}
return true;
}
/**
* Delete records by group ID
*
* @param integer $group_id User group ID
* @return boolean True on success
*/
public function deleteByGroupId($group_id=null)
{
$group_id = $group_id ?: $this->group_id;
if (!$group_id)
{
$this->setError(Lang::txt('No group ID provided.'));
return false;
}
$this->_db->setQuery("DELETE FROM `$this->_tbl` WHERE `group_id`=" . $this->_db->quote($group_id));
if (!$this->_db->query())
{
$this->setError($this->_db->getErrorMsg());
return false;
}
return true;
}
}
|
gpl-2.0
|
Ikizami/lolwtfzamodfgo
|
src/server/game/Entities/Unit/Unit.cpp
|
649257
|
/*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Unit.h"
#include "Common.h"
#include "Battlefield.h"
#include "BattlefieldMgr.h"
#include "Battleground.h"
#include "CellImpl.h"
#include "ConditionMgr.h"
#include "CreatureAI.h"
#include "CreatureAIImpl.h"
#include "CreatureGroups.h"
#include "Creature.h"
#include "Formulas.h"
#include "GridNotifiersImpl.h"
#include "Group.h"
#include "InstanceSaveMgr.h"
#include "InstanceScript.h"
#include "Log.h"
#include "MapManager.h"
#include "MoveSpline.h"
#include "MoveSplineInit.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Opcodes.h"
#include "OutdoorPvP.h"
#include "PassiveAI.h"
#include "PetAI.h"
#include "Pet.h"
#include "Player.h"
#include "QuestDef.h"
#include "ReputationMgr.h"
#include "SpellAuraEffects.h"
#include "SpellAuras.h"
#include "Spell.h"
#include "SpellInfo.h"
#include "SpellMgr.h"
#include "TemporarySummon.h"
#include "Totem.h"
#include "Transport.h"
#include "UpdateFieldFlags.h"
#include "Util.h"
#include "Vehicle.h"
#include "World.h"
#include "WorldPacket.h"
#include "MovementStructures.h"
#include "WorldSession.h"
#include <math.h>
float baseMoveSpeed[MAX_MOVE_TYPE] =
{
2.5f, // MOVE_WALK
7.0f, // MOVE_RUN
4.5f, // MOVE_RUN_BACK
4.722222f, // MOVE_SWIM
2.5f, // MOVE_SWIM_BACK
3.141594f, // MOVE_TURN_RATE
7.0f, // MOVE_FLIGHT
4.5f, // MOVE_FLIGHT_BACK
3.14f // MOVE_PITCH_RATE
};
float playerBaseMoveSpeed[MAX_MOVE_TYPE] =
{
2.5f, // MOVE_WALK
7.0f, // MOVE_RUN
4.5f, // MOVE_RUN_BACK
4.722222f, // MOVE_SWIM
2.5f, // MOVE_SWIM_BACK
3.141594f, // MOVE_TURN_RATE
7.0f, // MOVE_FLIGHT
4.5f, // MOVE_FLIGHT_BACK
3.14f // MOVE_PITCH_RATE
};
// Used for prepare can/can`t triggr aura
static bool InitTriggerAuraData();
// Define can trigger auras
static bool isTriggerAura[TOTAL_AURAS];
// Define can't trigger auras (need for disable second trigger)
static bool isNonTriggerAura[TOTAL_AURAS];
// Triggered always, even from triggered spells
static bool isAlwaysTriggeredAura[TOTAL_AURAS];
// Prepare lists
static bool procPrepared = InitTriggerAuraData();
DamageInfo::DamageInfo(Unit* _attacker, Unit* _victim, uint32 _damage, SpellInfo const* _spellInfo, SpellSchoolMask _schoolMask, DamageEffectType _damageType)
: m_attacker(_attacker), m_victim(_victim), m_damage(_damage), m_spellInfo(_spellInfo), m_schoolMask(_schoolMask),
m_damageType(_damageType), m_attackType(BASE_ATTACK)
{
m_absorb = 0;
m_resist = 0;
m_block = 0;
}
DamageInfo::DamageInfo(CalcDamageInfo& dmgInfo)
: m_attacker(dmgInfo.attacker), m_victim(dmgInfo.target), m_damage(dmgInfo.damage), m_spellInfo(NULL), m_schoolMask(SpellSchoolMask(dmgInfo.damageSchoolMask)),
m_damageType(DIRECT_DAMAGE), m_attackType(dmgInfo.attackType)
{
m_absorb = 0;
m_resist = 0;
m_block = 0;
}
void DamageInfo::ModifyDamage(int32 amount)
{
amount = std::min(amount, int32(GetDamage()));
m_damage += amount;
}
void DamageInfo::AbsorbDamage(uint32 amount)
{
amount = std::min(amount, GetDamage());
m_absorb += amount;
m_damage -= amount;
}
void DamageInfo::ResistDamage(uint32 amount)
{
amount = std::min(amount, GetDamage());
m_resist += amount;
m_damage -= amount;
}
void DamageInfo::BlockDamage(uint32 amount)
{
amount = std::min(amount, GetDamage());
m_block += amount;
m_damage -= amount;
}
ProcEventInfo::ProcEventInfo(Unit* actor, Unit* actionTarget, Unit* procTarget, uint32 typeMask, uint32 spellTypeMask, uint32 spellPhaseMask, uint32 hitMask, Spell* spell, DamageInfo* damageInfo, HealInfo* healInfo)
:_actor(actor), _actionTarget(actionTarget), _procTarget(procTarget), _typeMask(typeMask), _spellTypeMask(spellTypeMask), _spellPhaseMask(spellPhaseMask),
_hitMask(hitMask), _spell(spell), _damageInfo(damageInfo), _healInfo(healInfo)
{
}
// we can disable this warning for this since it only
// causes undefined behavior when passed to the base class constructor
#ifdef _MSC_VER
#pragma warning(disable:4355)
#endif
Unit::Unit(bool isWorldObject): WorldObject(isWorldObject)
, m_movedPlayer(NULL)
, m_lastSanctuaryTime(0)
, m_TempSpeed(0.0f)
, IsAIEnabled(false)
, NeedChangeAI(false)
, m_ControlledByPlayer(false)
, movespline(new Movement::MoveSpline())
, i_AI(NULL)
, i_disabledAI(NULL)
, m_AutoRepeatFirstCast(false)
, m_procDeep(0)
, m_removedAurasCount(0)
, i_motionMaster(this)
, m_ThreatManager(this)
, m_vehicle(NULL)
, m_vehicleKit(NULL)
, m_unitTypeMask(UNIT_MASK_NONE)
, m_HostileRefManager(this)
, _lastDamagedTime(0)
{
#ifdef _MSC_VER
#pragma warning(default:4355)
#endif
m_objectType |= TYPEMASK_UNIT;
m_objectTypeId = TYPEID_UNIT;
m_updateFlag = UPDATEFLAG_LIVING;
m_attackTimer[BASE_ATTACK] = 0;
m_attackTimer[OFF_ATTACK] = 0;
m_attackTimer[RANGED_ATTACK] = 0;
m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
m_extraAttacks = 0;
m_canDualWield = false;
m_rootTimes = 0;
m_state = 0;
m_deathState = ALIVE;
for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i)
m_currentSpells[i] = NULL;
m_addDmgOnce = 0;
for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
m_SummonSlot[i] = 0;
for (uint8 i = 0; i < MAX_GAMEOBJECT_SLOT; ++i)
m_ObjectSlot[i] = 0;
m_auraUpdateIterator = m_ownedAuras.end();
m_interruptMask = 0;
m_transform = 0;
m_canModifyStats = false;
for (uint8 i = 0; i < MAX_SPELL_IMMUNITY; ++i)
m_spellImmune[i].clear();
for (uint8 i = 0; i < UNIT_MOD_END; ++i)
{
m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
}
// implement 50% base damage from offhand
m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
for (uint8 i = 0; i < MAX_ATTACK; ++i)
{
m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
}
for (uint8 i = 0; i < MAX_STATS; ++i)
m_createStats[i] = 0.0f;
m_attacking = NULL;
m_modMeleeHitChance = 0.0f;
m_modRangedHitChance = 0.0f;
m_modSpellHitChance = 0.0f;
m_baseSpellCritChance = 5;
m_CombatTimer = 0;
for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
m_threatModifier[i] = 1.0f;
m_isSorted = true;
for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
m_speed_rate[i] = 1.0f;
m_charmInfo = NULL;
_redirectThreadInfo = RedirectThreatInfo();
// remove aurastates allowing special moves
for (uint8 i = 0; i < MAX_REACTIVE; ++i)
m_reactiveTimer[i] = 0;
m_cleanupDone = false;
m_duringRemoveFromWorld = false;
m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE);
_focusSpell = NULL;
_lastLiquid = NULL;
_isWalkingBeforeCharm = false;
}
////////////////////////////////////////////////////////////
// Methods of class GlobalCooldownMgr
bool GlobalCooldownMgr::HasGlobalCooldown(SpellInfo const* spellInfo) const
{
GlobalCooldownList::const_iterator itr = m_GlobalCooldowns.find(spellInfo->StartRecoveryCategory);
return itr != m_GlobalCooldowns.end() && itr->second.duration && getMSTimeDiff(itr->second.cast_time, getMSTime()) < itr->second.duration;
}
void GlobalCooldownMgr::AddGlobalCooldown(SpellInfo const* spellInfo, uint32 gcd)
{
m_GlobalCooldowns[spellInfo->StartRecoveryCategory] = GlobalCooldown(gcd, getMSTime());
}
void GlobalCooldownMgr::CancelGlobalCooldown(SpellInfo const* spellInfo)
{
m_GlobalCooldowns[spellInfo->StartRecoveryCategory].duration = 0;
}
////////////////////////////////////////////////////////////
// Methods of class Unit
Unit::~Unit()
{
// set current spells as deletable
for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i)
if (m_currentSpells[i])
{
m_currentSpells[i]->SetReferencedFromCurrent(false);
m_currentSpells[i] = NULL;
}
_DeleteRemovedAuras();
delete m_charmInfo;
delete movespline;
ASSERT(!m_duringRemoveFromWorld);
ASSERT(!m_attacking);
ASSERT(m_attackers.empty());
ASSERT(m_sharedVision.empty());
ASSERT(m_Controlled.empty());
ASSERT(m_appliedAuras.empty());
ASSERT(m_ownedAuras.empty());
ASSERT(m_removedAuras.empty());
ASSERT(m_gameObj.empty());
ASSERT(m_dynObj.empty());
}
void Unit::Update(uint32 p_time)
{
// WARNING! Order of execution here is important, do not change.
// Spells must be processed with event system BEFORE they go to _UpdateSpells.
// Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
m_Events.Update(p_time);
if (!IsInWorld())
return;
_UpdateSpells(p_time);
// If this is set during update SetCantProc(false) call is missing somewhere in the code
// Having this would prevent spells from being proced, so let's crash
ASSERT(!m_procDeep);
if (CanHaveThreatList() && getThreatManager().isNeedUpdateToClient(p_time))
SendThreatListUpdate();
// update combat timer only for players and pets (only pets with PetAI)
if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || (ToCreature()->isPet() && IsControlledByPlayer())))
{
// Check UNIT_STATE_MELEE_ATTACKING or UNIT_STATE_CHASE (without UNIT_STATE_FOLLOW in this case) so pets can reach far away
// targets without stopping half way there and running off.
// These flags are reset after target dies or another command is given.
if (m_HostileRefManager.isEmpty())
{
// m_CombatTimer set at aura start and it will be freeze until aura removing
if (m_CombatTimer <= p_time)
ClearInCombat();
else
m_CombatTimer -= p_time;
}
}
// not implemented before 3.0.2
if (uint32 base_att = getAttackTimer(BASE_ATTACK))
setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time));
if (uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time));
if (uint32 off_att = getAttackTimer(OFF_ATTACK))
setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time));
// update abilities available only for fraction of time
UpdateReactives(p_time);
if (isAlive())
{
ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, HealthBelowPct(20));
ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, HealthBelowPct(35));
ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, HealthAbovePct(75));
}
UpdateSplineMovement(p_time);
i_motionMaster.UpdateMotion(p_time);
}
bool Unit::haveOffhandWeapon() const
{
if (GetTypeId() == TYPEID_PLAYER)
return ToPlayer()->GetWeaponForAttack(OFF_ATTACK, true);
else
return m_canDualWield;
}
void Unit::MonsterMoveWithSpeed(float x, float y, float z, float speed, bool generatePath, bool forceDestination)
{
Movement::MoveSplineInit init(this);
init.MoveTo(x, y, z, generatePath, forceDestination);
init.SetVelocity(speed);
init.Launch();
}
void Unit::UpdateSplineMovement(uint32 t_diff)
{
if (movespline->Finalized())
return;
movespline->updateState(t_diff);
bool arrived = movespline->Finalized();
if (arrived)
DisableSpline();
m_movesplineTimer.Update(t_diff);
if (m_movesplineTimer.Passed() || arrived)
UpdateSplinePosition();
}
void Unit::UpdateSplinePosition()
{
uint32 const positionUpdateDelay = 400;
m_movesplineTimer.Reset(positionUpdateDelay);
Movement::Location loc = movespline->ComputePosition();
if (GetTransGUID())
{
Position& pos = m_movementInfo.t_pos;
pos.m_positionX = loc.x;
pos.m_positionY = loc.y;
pos.m_positionZ = loc.z;
pos.SetOrientation(loc.orientation);
if (Unit* vehicle = GetVehicleBase())
{
loc.x += vehicle->GetPositionX();
loc.y += vehicle->GetPositionY();
loc.z += vehicle->GetPositionZMinusOffset();
loc.orientation = vehicle->GetOrientation();
}
else if (TransportBase* transport = GetDirectTransport())
transport->CalculatePassengerPosition(loc.x, loc.y, loc.z, loc.orientation);
}
if (HasUnitState(UNIT_STATE_CANNOT_TURN))
loc.orientation = GetOrientation();
UpdatePosition(loc.x, loc.y, loc.z, loc.orientation);
}
void Unit::DisableSpline()
{
m_movementInfo.RemoveMovementFlag(MOVEMENTFLAG_FORWARD);
movespline->_Interrupt();
}
void Unit::resetAttackTimer(WeaponAttackType type)
{
m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
}
bool Unit::IsWithinCombatRange(const Unit* obj, float dist2compare) const
{
if (!obj || !IsInMap(obj) || !InSamePhase(obj))
return false;
float dx = GetPositionX() - obj->GetPositionX();
float dy = GetPositionY() - obj->GetPositionY();
float dz = GetPositionZ() - obj->GetPositionZ();
float distsq = dx * dx + dy * dy + dz * dz;
float sizefactor = GetCombatReach() + obj->GetCombatReach();
float maxdist = dist2compare + sizefactor;
return distsq < maxdist * maxdist;
}
bool Unit::IsWithinMeleeRange(const Unit* obj, float dist) const
{
if (!obj || !IsInMap(obj) || !InSamePhase(obj))
return false;
float dx = GetPositionX() - obj->GetPositionX();
float dy = GetPositionY() - obj->GetPositionY();
float dz = GetPositionZ() - obj->GetPositionZ();
float distsq = dx*dx + dy*dy + dz*dz;
float sizefactor = GetMeleeReach() + obj->GetMeleeReach();
float maxdist = dist + sizefactor;
return distsq < maxdist * maxdist;
}
void Unit::GetRandomContactPoint(const Unit* obj, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const
{
float combat_reach = GetCombatReach();
if (combat_reach < 0.1f) // sometimes bugged for players
combat_reach = DEFAULT_COMBAT_REACH;
uint32 attacker_number = getAttackers().size();
if (attacker_number > 0)
--attacker_number;
GetNearPoint(obj, x, y, z, obj->GetCombatReach(), distance2dMin+(distance2dMax-distance2dMin) * (float)rand_norm()
, GetAngle(obj) + (attacker_number ? (static_cast<float>(M_PI/2) - static_cast<float>(M_PI) * (float)rand_norm()) * float(attacker_number) / combat_reach * 0.3f : 0));
}
void Unit::UpdateInterruptMask()
{
m_interruptMask = 0;
for (AuraApplicationList::const_iterator i = m_interruptableAuras.begin(); i != m_interruptableAuras.end(); ++i)
m_interruptMask |= (*i)->GetBase()->GetSpellInfo()->AuraInterruptFlags;
if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL])
if (spell->getState() == SPELL_STATE_CASTING)
m_interruptMask |= spell->m_spellInfo->ChannelInterruptFlags;
}
bool Unit::HasAuraTypeWithFamilyFlags(AuraType auraType, uint32 familyName, uint32 familyFlags) const
{
if (!HasAuraType(auraType))
return false;
AuraEffectList const& auras = GetAuraEffectsByType(auraType);
for (AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
if (SpellInfo const* iterSpellProto = (*itr)->GetSpellInfo())
if (iterSpellProto->SpellFamilyName == familyName && iterSpellProto->SpellFamilyFlags[0] & familyFlags)
return true;
return false;
}
bool Unit::HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura) const
{
AuraEffectList const& auras = GetAuraEffectsByType(type);
for (AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
if ((!excludeAura || excludeAura != (*itr)->GetSpellInfo()->Id) && //Avoid self interrupt of channeled Crowd Control spells like Seduction
((*itr)->GetSpellInfo()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_TAKE_DAMAGE))
return true;
return false;
}
bool Unit::HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel) const
{
uint32 excludeAura = 0;
if (Spell* currentChanneledSpell = excludeCasterChannel ? excludeCasterChannel->GetCurrentSpell(CURRENT_CHANNELED_SPELL) : NULL)
excludeAura = currentChanneledSpell->GetSpellInfo()->Id; //Avoid self interrupt of channeled Crowd Control spells like Seduction
return ( HasBreakableByDamageAuraType(SPELL_AURA_MOD_CONFUSE, excludeAura)
|| HasBreakableByDamageAuraType(SPELL_AURA_MOD_FEAR, excludeAura)
|| HasBreakableByDamageAuraType(SPELL_AURA_MOD_STUN, excludeAura)
|| HasBreakableByDamageAuraType(SPELL_AURA_MOD_ROOT, excludeAura)
|| HasBreakableByDamageAuraType(SPELL_AURA_TRANSFORM, excludeAura));
}
void Unit::DealDamageMods(Unit* victim, uint32 &damage, uint32* absorb)
{
if (!victim || !victim->isAlive() || victim->HasUnitState(UNIT_STATE_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode()))
{
if (absorb)
*absorb += damage;
damage = 0;
}
}
uint32 Unit::DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellInfo const* spellProto, bool durabilityLoss)
{
if (victim->IsAIEnabled)
victim->GetAI()->DamageTaken(this, damage);
if (IsAIEnabled)
GetAI()->DamageDealt(victim, damage, damagetype);
if (victim->GetTypeId() == TYPEID_PLAYER && this != victim)
{
// Signal to pets that their owner was attacked
Pet* pet = victim->ToPlayer()->GetPet();
if (pet && pet->isAlive())
pet->AI()->OwnerAttackedBy(this);
if (victim->ToPlayer()->GetCommandStatus(CHEAT_GOD))
return 0;
}
// Signal the pet it was attacked so the AI can respond if needed
if (victim->GetTypeId() == TYPEID_UNIT && this != victim && victim->isPet() && victim->isAlive())
victim->ToPet()->AI()->AttackedBy(this);
if (damagetype != NODAMAGE)
{
// interrupting auras with AURA_INTERRUPT_FLAG_DAMAGE before checking !damage (absorbed damage breaks that type of auras)
if (spellProto)
{
if (!(spellProto->AttributesEx4 & SPELL_ATTR4_DAMAGE_DOESNT_BREAK_AURAS))
victim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TAKE_DAMAGE, spellProto->Id);
}
else
victim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TAKE_DAMAGE, 0);
// We're going to call functions which can modify content of the list during iteration over it's elements
// Let's copy the list so we can prevent iterator invalidation
AuraEffectList vCopyDamageCopy(victim->GetAuraEffectsByType(SPELL_AURA_SHARE_DAMAGE_PCT));
// copy damage to casters of this aura
for (AuraEffectList::iterator i = vCopyDamageCopy.begin(); i != vCopyDamageCopy.end(); ++i)
{
// Check if aura was removed during iteration - we don't need to work on such auras
if (!((*i)->GetBase()->IsAppliedOnTarget(victim->GetGUID())))
continue;
// check damage school mask
if (((*i)->GetMiscValue() & damageSchoolMask) == 0)
continue;
Unit* shareDamageTarget = (*i)->GetCaster();
if (!shareDamageTarget)
continue;
SpellInfo const* spell = (*i)->GetSpellInfo();
uint32 share = CalculatePct(damage, (*i)->GetAmount());
// TODO: check packets if damage is done by victim, or by attacker of victim
DealDamageMods(shareDamageTarget, share, NULL);
DealDamage(shareDamageTarget, share, NULL, NODAMAGE, spell->GetSchoolMask(), spell, false);
}
}
// Rage from Damage made (only from direct weapon damage)
if (cleanDamage && damagetype == DIRECT_DAMAGE && this != victim && getPowerType() == POWER_RAGE)
{
uint32 rage = uint32(GetAttackTime(cleanDamage->attackType) / 1000 * 8.125f);
switch (cleanDamage->attackType)
{
case OFF_ATTACK:
rage /= 2;
case BASE_ATTACK:
RewardRage(rage, true);
break;
default:
break;
}
}
if (!damage)
{
// Rage from absorbed damage
if (cleanDamage && cleanDamage->absorbed_damage && victim->getPowerType() == POWER_RAGE)
victim->RewardRage(cleanDamage->absorbed_damage, false);
return 0;
}
sLog->outDebug(LOG_FILTER_UNITS, "DealDamageStart");
uint32 health = victim->GetHealth();
sLog->outDebug(LOG_FILTER_UNITS, "Unit " UI64FMTD " dealt %u damage to unit " UI64FMTD, GetGUID(), damage, victim->GetGUID());
// duel ends when player has 1 or less hp
bool duel_hasEnded = false;
bool duel_wasMounted = false;
if (victim->GetTypeId() == TYPEID_PLAYER && victim->ToPlayer()->duel && damage >= (health-1))
{
// prevent kill only if killed in duel and killed by opponent or opponent controlled creature
if (victim->ToPlayer()->duel->opponent == this || victim->ToPlayer()->duel->opponent->GetGUID() == GetOwnerGUID())
damage = health - 1;
duel_hasEnded = true;
}
else if (victim->IsVehicle() && damage >= (health-1) && victim->GetCharmer() && victim->GetCharmer()->GetTypeId() == TYPEID_PLAYER)
{
Player* victimRider = victim->GetCharmer()->ToPlayer();
if (victimRider && victimRider->duel && victimRider->duel->isMounted)
{
// prevent kill only if killed in duel and killed by opponent or opponent controlled creature
if (victimRider->duel->opponent == this || victimRider->duel->opponent->GetGUID() == GetCharmerGUID())
damage = health - 1;
duel_wasMounted = true;
duel_hasEnded = true;
}
}
if (GetTypeId() == TYPEID_PLAYER && this != victim)
{
Player* killer = ToPlayer();
// in bg, count dmg if victim is also a player
if (victim->GetTypeId() == TYPEID_PLAYER)
if (Battleground* bg = killer->GetBattleground())
bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE, damage, 0, 0, victim);
killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage);
}
if (victim->GetTypeId() == TYPEID_PLAYER)
victim->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage);
else if (!victim->IsControlledByPlayer() || victim->IsVehicle())
{
if (!victim->ToCreature()->hasLootRecipient())
victim->ToCreature()->SetLootRecipient(this);
if (IsControlledByPlayer())
victim->ToCreature()->LowerPlayerDamageReq(health < damage ? health : damage);
}
if (health <= damage)
{
sLog->outDebug(LOG_FILTER_UNITS, "DealDamage: victim just died");
if (victim->GetTypeId() == TYPEID_PLAYER && victim != this)
victim->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health);
Kill(victim, durabilityLoss);
}
else
{
sLog->outDebug(LOG_FILTER_UNITS, "DealDamageAlive");
if (victim->GetTypeId() == TYPEID_PLAYER)
victim->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage);
victim->ModifyHealth(- (int32)damage);
if (damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
victim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE, spellProto ? spellProto->Id : 0);
if (victim->GetTypeId() != TYPEID_PLAYER)
victim->AddThreat(this, float(damage), damageSchoolMask, spellProto);
else // victim is a player
{
// random durability for items (HIT TAKEN)
if (roll_chance_f(sWorld->getRate(RATE_DURABILITY_LOSS_DAMAGE)))
{
EquipmentSlots slot = EquipmentSlots(urand(0, EQUIPMENT_SLOT_END-1));
victim->ToPlayer()->DurabilityPointLossForEquipSlot(slot);
}
}
// Rage from damage received
if (this != victim && victim->getPowerType() == POWER_RAGE)
{
uint32 rage_damage = damage + (cleanDamage ? cleanDamage->absorbed_damage : 0);
victim->RewardRage(rage_damage, false);
}
if (GetTypeId() == TYPEID_PLAYER)
{
// random durability for items (HIT DONE)
if (roll_chance_f(sWorld->getRate(RATE_DURABILITY_LOSS_DAMAGE)))
{
EquipmentSlots slot = EquipmentSlots(urand(0, EQUIPMENT_SLOT_END-1));
ToPlayer()->DurabilityPointLossForEquipSlot(slot);
}
}
if (damagetype != NODAMAGE && damage)
{
if (victim != this && victim->GetTypeId() == TYPEID_PLAYER) // does not support creature push_back
{
if (damagetype != DOT)
if (Spell* spell = victim->m_currentSpells[CURRENT_GENERIC_SPELL])
if (spell->getState() == SPELL_STATE_PREPARING)
{
uint32 interruptFlags = spell->m_spellInfo->InterruptFlags;
if (interruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
victim->InterruptNonMeleeSpells(false);
else if (interruptFlags & SPELL_INTERRUPT_FLAG_PUSH_BACK)
spell->Delayed();
}
if (Spell* spell = victim->m_currentSpells[CURRENT_CHANNELED_SPELL])
if (spell->getState() == SPELL_STATE_CASTING)
{
uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
if (((channelInterruptFlags & CHANNEL_FLAG_DELAY) != 0) && (damagetype != DOT))
spell->DelayedChannel();
}
}
}
// last damage from duel opponent
if (duel_hasEnded)
{
Player* he = duel_wasMounted ? victim->GetCharmer()->ToPlayer() : victim->ToPlayer();
ASSERT(he && he->duel);
if (duel_wasMounted) // In this case victim==mount
victim->SetHealth(1);
else
he->SetHealth(1);
he->duel->opponent->CombatStopWithPets(true);
he->CombatStopWithPets(true);
he->CastSpell(he, 7267, true); // beg
he->DuelComplete(DUEL_WON);
}
}
sLog->outDebug(LOG_FILTER_UNITS, "DealDamageEnd returned %d damage", damage);
return damage;
}
void Unit::CastStop(uint32 except_spellid)
{
for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id != except_spellid)
InterruptSpell(CurrentSpellTypes(i), false);
}
void Unit::CastSpell(SpellCastTargets const& targets, SpellInfo const* spellInfo, CustomSpellValues const* value, TriggerCastFlags triggerFlags, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
if (!spellInfo)
{
sLog->outError(LOG_FILTER_UNITS, "CastSpell: unknown spell by caster: %s %u)", (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
return;
}
// TODO: this is a workaround - not needed anymore, but required for some scripts :(
if (!originalCaster && triggeredByAura)
originalCaster = triggeredByAura->GetCasterGUID();
Spell* spell = new Spell(this, spellInfo, triggerFlags, originalCaster);
if (value)
for (CustomSpellValues::const_iterator itr = value->begin(); itr != value->end(); ++itr)
spell->SetSpellValue(itr->first, itr->second);
spell->m_CastItem = castItem;
spell->prepare(&targets, triggeredByAura);
}
void Unit::CastSpell(Unit* victim, uint32 spellId, bool triggered, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
CastSpell(victim, spellId, triggered ? TRIGGERED_FULL_MASK : TRIGGERED_NONE, castItem, triggeredByAura, originalCaster);
}
void Unit::CastSpell(Unit* victim, uint32 spellId, TriggerCastFlags triggerFlags /*= TRIGGER_NONE*/, Item* castItem /*= NULL*/, AuraEffect const* triggeredByAura /*= NULL*/, uint64 originalCaster /*= 0*/)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
{
sLog->outError(LOG_FILTER_UNITS, "CastSpell: unknown spell id %u by caster: %s %u)", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
return;
}
CastSpell(victim, spellInfo, triggerFlags, castItem, triggeredByAura, originalCaster);
}
void Unit::CastSpell(Unit* victim, SpellInfo const* spellInfo, bool triggered, Item* castItem/*= NULL*/, AuraEffect const* triggeredByAura /*= NULL*/, uint64 originalCaster /*= 0*/)
{
CastSpell(victim, spellInfo, triggered ? TRIGGERED_FULL_MASK : TRIGGERED_NONE, castItem, triggeredByAura, originalCaster);
}
void Unit::CastSpell(Unit* victim, SpellInfo const* spellInfo, TriggerCastFlags triggerFlags, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
SpellCastTargets targets;
targets.SetUnitTarget(victim);
CastSpell(targets, spellInfo, NULL, triggerFlags, castItem, triggeredByAura, originalCaster);
}
void Unit::CastCustomSpell(Unit* target, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
CustomSpellValues values;
if (bp0)
values.AddSpellMod(SPELLVALUE_BASE_POINT0, *bp0);
if (bp1)
values.AddSpellMod(SPELLVALUE_BASE_POINT1, *bp1);
if (bp2)
values.AddSpellMod(SPELLVALUE_BASE_POINT2, *bp2);
CastCustomSpell(spellId, values, target, triggered ? TRIGGERED_FULL_MASK : TRIGGERED_NONE, castItem, triggeredByAura, originalCaster);
}
void Unit::CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* target, bool triggered, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
CustomSpellValues values;
values.AddSpellMod(mod, value);
CastCustomSpell(spellId, values, target, triggered ? TRIGGERED_FULL_MASK : TRIGGERED_NONE, castItem, triggeredByAura, originalCaster);
}
void Unit::CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* target, TriggerCastFlags triggerFlags, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
CustomSpellValues values;
values.AddSpellMod(mod, value);
CastCustomSpell(spellId, values, target, triggerFlags, castItem, triggeredByAura, originalCaster);
}
void Unit::CastCustomSpell(uint32 spellId, CustomSpellValues const& value, Unit* victim, TriggerCastFlags triggerFlags, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
{
sLog->outError(LOG_FILTER_UNITS, "CastSpell: unknown spell id %u by caster: %s %u)", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
return;
}
SpellCastTargets targets;
targets.SetUnitTarget(victim);
CastSpell(targets, spellInfo, &value, triggerFlags, castItem, triggeredByAura, originalCaster);
}
void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
{
sLog->outError(LOG_FILTER_UNITS, "CastSpell: unknown spell id %u by caster: %s %u)", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
return;
}
SpellCastTargets targets;
targets.SetDst(x, y, z, GetOrientation());
CastSpell(targets, spellInfo, NULL, triggered ? TRIGGERED_FULL_MASK : TRIGGERED_NONE, castItem, triggeredByAura, originalCaster);
}
void Unit::CastSpell(GameObject* go, uint32 spellId, bool triggered, Item* castItem, AuraEffect* triggeredByAura, uint64 originalCaster)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
{
sLog->outError(LOG_FILTER_UNITS, "CastSpell: unknown spell id %u by caster: %s %u)", spellId, (GetTypeId() == TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"), (GetTypeId() == TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
return;
}
SpellCastTargets targets;
targets.SetGOTarget(go);
CastSpell(targets, spellInfo, NULL, triggered ? TRIGGERED_FULL_MASK : TRIGGERED_NONE, castItem, triggeredByAura, originalCaster);
}
// Obsolete func need remove, here only for comotability vs another patches
uint32 Unit::SpellNonMeleeDamageLog(Unit* victim, uint32 spellID, uint32 damage)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellID);
SpellNonMeleeDamage damageInfo(this, victim, spellInfo->Id, spellInfo->SchoolMask);
damage = SpellDamageBonusDone(victim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
damage = victim->SpellDamageBonusTaken(this, spellInfo, damage, SPELL_DIRECT_DAMAGE);
CalculateSpellDamageTaken(&damageInfo, damage, spellInfo);
DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb);
SendSpellNonMeleeDamageLog(&damageInfo);
DealSpellDamage(&damageInfo, true);
return damageInfo.damage;
}
void Unit::CalculateSpellDamageTaken(SpellNonMeleeDamage* damageInfo, int32 damage, SpellInfo const* spellInfo, WeaponAttackType attackType, bool crit)
{
if (damage < 0)
return;
Unit* victim = damageInfo->target;
if (!victim || !victim->isAlive())
return;
SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
if (IsDamageReducedByArmor(damageSchoolMask, spellInfo))
damage = CalcArmorReducedDamage(victim, damage, spellInfo, attackType);
bool blocked = false;
// Per-school calc
switch (spellInfo->DmgClass)
{
// Melee and Ranged Spells
case SPELL_DAMAGE_CLASS_RANGED:
case SPELL_DAMAGE_CLASS_MELEE:
{
// Physical Damage
if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL)
{
// Get blocked status
blocked = isSpellBlocked(victim, spellInfo, attackType);
}
if (crit)
{
damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT;
// Calculate crit bonus
uint32 crit_bonus = damage;
// Apply crit_damage bonus for melee spells
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
damage += crit_bonus;
// Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
float critPctDamageMod = 0.0f;
if (attackType == RANGED_ATTACK)
critPctDamageMod += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
else
critPctDamageMod += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
// Increase crit damage from SPELL_AURA_MOD_CRIT_DAMAGE_BONUS
critPctDamageMod += (GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, spellInfo->GetSchoolMask()) - 1.0f) * 100;
if (critPctDamageMod != 0)
AddPct(damage, critPctDamageMod);
}
// Spell weapon based damage CAN BE crit & blocked at same time
if (blocked)
{
// double blocked amount if block is critical
uint32 value = victim->GetBlockPercent();
if (victim->isBlockCritical())
value *= 2; // double blocked percent
damageInfo->blocked = CalculatePct(damage, value);
damage -= damageInfo->blocked;
}
ApplyResilience(victim, &damage, crit);
break;
}
// Magical Attacks
case SPELL_DAMAGE_CLASS_NONE:
case SPELL_DAMAGE_CLASS_MAGIC:
{
// If crit add critical bonus
if (crit)
{
damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT;
damage = SpellCriticalDamageBonus(spellInfo, damage, victim);
}
ApplyResilience(victim, &damage, crit);
break;
}
default:
break;
}
// Script Hook For CalculateSpellDamageTaken -- Allow scripts to change the Damage post class mitigation calculations
sScriptMgr->ModifySpellDamageTaken(damageInfo->target, damageInfo->attacker, damage);
// Calculate absorb resist
if (damage > 0)
{
CalcAbsorbResist(victim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist, spellInfo);
damage -= damageInfo->absorb + damageInfo->resist;
}
else
damage = 0;
damageInfo->damage = damage;
}
void Unit::DealSpellDamage(SpellNonMeleeDamage* damageInfo, bool durabilityLoss)
{
if (damageInfo == 0)
return;
Unit* victim = damageInfo->target;
if (!victim)
return;
if (!victim->isAlive() || victim->HasUnitState(UNIT_STATE_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode()))
return;
SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(damageInfo->SpellID);
if (spellProto == NULL)
{
sLog->outDebug(LOG_FILTER_UNITS, "Unit::DealSpellDamage has wrong damageInfo->SpellID: %u", damageInfo->SpellID);
return;
}
// Call default DealDamage
CleanDamage cleanDamage(damageInfo->cleanDamage, damageInfo->absorb, BASE_ATTACK, MELEE_HIT_NORMAL);
DealDamage(victim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
}
// TODO for melee need create structure as in
void Unit::CalculateMeleeDamage(Unit* victim, uint32 damage, CalcDamageInfo* damageInfo, WeaponAttackType attackType)
{
damageInfo->attacker = this;
damageInfo->target = victim;
damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
damageInfo->attackType = attackType;
damageInfo->damage = 0;
damageInfo->cleanDamage = 0;
damageInfo->absorb = 0;
damageInfo->resist = 0;
damageInfo->blocked_amount = 0;
damageInfo->TargetState = 0;
damageInfo->HitInfo = 0;
damageInfo->procAttacker = PROC_FLAG_NONE;
damageInfo->procVictim = PROC_FLAG_NONE;
damageInfo->procEx = PROC_EX_NONE;
damageInfo->hitOutCome = MELEE_HIT_EVADE;
if (!victim)
return;
if (!isAlive() || !victim->isAlive())
return;
// Select HitInfo/procAttacker/procVictim flag based on attack type
switch (attackType)
{
case BASE_ATTACK:
damageInfo->procAttacker = PROC_FLAG_DONE_MELEE_AUTO_ATTACK | PROC_FLAG_DONE_MAINHAND_ATTACK;
damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK;
break;
case OFF_ATTACK:
damageInfo->procAttacker = PROC_FLAG_DONE_MELEE_AUTO_ATTACK | PROC_FLAG_DONE_OFFHAND_ATTACK;
damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK;
damageInfo->HitInfo = HITINFO_OFFHAND;
break;
default:
return;
}
// Physical Immune check
if (damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
{
damageInfo->HitInfo |= HITINFO_NORMALSWING;
damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
damageInfo->procEx |= PROC_EX_IMMUNE;
damageInfo->damage = 0;
damageInfo->cleanDamage = 0;
return;
}
damage += CalculateDamage(damageInfo->attackType, false, true);
// Add melee damage bonus
damage = MeleeDamageBonusDone(damageInfo->target, damage, damageInfo->attackType);
damage = damageInfo->target->MeleeDamageBonusTaken(this, damage, damageInfo->attackType);
// Script Hook For CalculateMeleeDamage -- Allow scripts to change the Damage pre class mitigation calculations
sScriptMgr->ModifyMeleeDamage(damageInfo->target, damageInfo->attacker, damage);
// Calculate armor reduction
if (IsDamageReducedByArmor((SpellSchoolMask)(damageInfo->damageSchoolMask)))
{
damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage, NULL, damageInfo->attackType);
damageInfo->cleanDamage += damage - damageInfo->damage;
}
else
damageInfo->damage = damage;
damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
switch (damageInfo->hitOutCome)
{
case MELEE_HIT_EVADE:
damageInfo->HitInfo |= HITINFO_MISS | HITINFO_SWINGNOHITSOUND;
damageInfo->TargetState = VICTIMSTATE_EVADES;
damageInfo->procEx |= PROC_EX_EVADE;
damageInfo->damage = 0;
damageInfo->cleanDamage = 0;
return;
case MELEE_HIT_MISS:
damageInfo->HitInfo |= HITINFO_MISS;
damageInfo->TargetState = VICTIMSTATE_INTACT;
damageInfo->procEx |= PROC_EX_MISS;
damageInfo->damage = 0;
damageInfo->cleanDamage = 0;
break;
case MELEE_HIT_NORMAL:
damageInfo->TargetState = VICTIMSTATE_HIT;
damageInfo->procEx |= PROC_EX_NORMAL_HIT;
break;
case MELEE_HIT_CRIT:
{
damageInfo->HitInfo |= HITINFO_CRITICALHIT;
damageInfo->TargetState = VICTIMSTATE_HIT;
damageInfo->procEx |= PROC_EX_CRITICAL_HIT;
// Crit bonus calc
damageInfo->damage += damageInfo->damage;
float mod = 0.0f;
// Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
if (damageInfo->attackType == RANGED_ATTACK)
mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
else
mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
// Increase crit damage from SPELL_AURA_MOD_CRIT_DAMAGE_BONUS
mod += (GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, damageInfo->damageSchoolMask) - 1.0f) * 100;
if (mod != 0)
AddPct(damageInfo->damage, mod);
break;
}
case MELEE_HIT_PARRY:
damageInfo->TargetState = VICTIMSTATE_PARRY;
damageInfo->procEx |= PROC_EX_PARRY;
damageInfo->cleanDamage += damageInfo->damage;
damageInfo->damage = 0;
break;
case MELEE_HIT_DODGE:
damageInfo->TargetState = VICTIMSTATE_DODGE;
damageInfo->procEx |= PROC_EX_DODGE;
damageInfo->cleanDamage += damageInfo->damage;
damageInfo->damage = 0;
break;
case MELEE_HIT_BLOCK:
damageInfo->TargetState = VICTIMSTATE_HIT;
damageInfo->HitInfo |= HITINFO_BLOCK;
damageInfo->procEx |= PROC_EX_BLOCK | PROC_EX_NORMAL_HIT;
// 30% damage blocked, double blocked amount if block is critical
damageInfo->blocked_amount = CalculatePct(damageInfo->damage, damageInfo->target->isBlockCritical() ? damageInfo->target->GetBlockPercent() * 2 : damageInfo->target->GetBlockPercent());
damageInfo->damage -= damageInfo->blocked_amount;
damageInfo->cleanDamage += damageInfo->blocked_amount;
break;
case MELEE_HIT_GLANCING:
{
damageInfo->HitInfo |= HITINFO_GLANCING;
damageInfo->TargetState = VICTIMSTATE_HIT;
damageInfo->procEx |= PROC_EX_NORMAL_HIT;
int32 leveldif = int32(victim->getLevel()) - int32(getLevel());
if (leveldif > 3)
leveldif = 3;
float reducePercent = 1 - leveldif * 0.1f;
damageInfo->cleanDamage += damageInfo->damage - uint32(reducePercent * damageInfo->damage);
damageInfo->damage = uint32(reducePercent * damageInfo->damage);
break;
}
case MELEE_HIT_CRUSHING:
damageInfo->HitInfo |= HITINFO_CRUSHING;
damageInfo->TargetState = VICTIMSTATE_HIT;
damageInfo->procEx |= PROC_EX_NORMAL_HIT;
// 150% normal damage
damageInfo->damage += (damageInfo->damage / 2);
break;
default:
break;
}
// Always apply HITINFO_AFFECTS_VICTIM in case its not a miss
if (!(damageInfo->HitInfo & HITINFO_MISS))
damageInfo->HitInfo |= HITINFO_AFFECTS_VICTIM;
int32 resilienceReduction = damageInfo->damage;
ApplyResilience(victim, &resilienceReduction, damageInfo->hitOutCome == MELEE_HIT_CRIT);
resilienceReduction = damageInfo->damage - resilienceReduction;
damageInfo->damage -= resilienceReduction;
damageInfo->cleanDamage += resilienceReduction;
// Calculate absorb resist
if (int32(damageInfo->damage) > 0)
{
damageInfo->procVictim |= PROC_FLAG_TAKEN_DAMAGE;
// Calculate absorb & resists
CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
if (damageInfo->absorb)
{
damageInfo->HitInfo |= (damageInfo->damage - damageInfo->absorb == 0 ? HITINFO_FULL_ABSORB : HITINFO_PARTIAL_ABSORB);
damageInfo->procEx |= PROC_EX_ABSORB;
}
if (damageInfo->resist)
damageInfo->HitInfo |= (damageInfo->damage - damageInfo->resist == 0 ? HITINFO_FULL_RESIST : HITINFO_PARTIAL_RESIST);
damageInfo->damage -= damageInfo->absorb + damageInfo->resist;
}
else // Impossible get negative result but....
damageInfo->damage = 0;
}
void Unit::DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss)
{
Unit* victim = damageInfo->target;
if (!victim->isAlive() || victim->HasUnitState(UNIT_STATE_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode()))
return;
// Hmmmm dont like this emotes client must by self do all animations
if (damageInfo->HitInfo & HITINFO_CRITICALHIT)
victim->HandleEmoteCommand(EMOTE_ONESHOT_WOUND_CRITICAL);
if (damageInfo->blocked_amount && damageInfo->TargetState != VICTIMSTATE_BLOCKS)
victim->HandleEmoteCommand(EMOTE_ONESHOT_PARRY_SHIELD);
if (damageInfo->TargetState == VICTIMSTATE_PARRY)
{
// Get attack timers
float offtime = float(victim->getAttackTimer(OFF_ATTACK));
float basetime = float(victim->getAttackTimer(BASE_ATTACK));
// Reduce attack time
if (victim->haveOffhandWeapon() && offtime < basetime)
{
float percent20 = victim->GetAttackTime(OFF_ATTACK) * 0.20f;
float percent60 = 3.0f * percent20;
if (offtime > percent20 && offtime <= percent60)
victim->setAttackTimer(OFF_ATTACK, uint32(percent20));
else if (offtime > percent60)
{
offtime -= 2.0f * percent20;
victim->setAttackTimer(OFF_ATTACK, uint32(offtime));
}
}
else
{
float percent20 = victim->GetAttackTime(BASE_ATTACK) * 0.20f;
float percent60 = 3.0f * percent20;
if (basetime > percent20 && basetime <= percent60)
victim->setAttackTimer(BASE_ATTACK, uint32(percent20));
else if (basetime > percent60)
{
basetime -= 2.0f * percent20;
victim->setAttackTimer(BASE_ATTACK, uint32(basetime));
}
}
}
// Call default DealDamage
CleanDamage cleanDamage(damageInfo->cleanDamage, damageInfo->absorb, damageInfo->attackType, damageInfo->hitOutCome);
DealDamage(victim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
// If this is a creature and it attacks from behind it has a probability to daze it's victim
if ((damageInfo->hitOutCome == MELEE_HIT_CRIT || damageInfo->hitOutCome == MELEE_HIT_CRUSHING || damageInfo->hitOutCome == MELEE_HIT_NORMAL || damageInfo->hitOutCome == MELEE_HIT_GLANCING) &&
GetTypeId() != TYPEID_PLAYER && !ToCreature()->IsControlledByPlayer() && !victim->HasInArc(M_PI, this)
&& (victim->GetTypeId() == TYPEID_PLAYER || !victim->ToCreature()->isWorldBoss())&& !victim->IsVehicle())
{
// -probability is between 0% and 40%
// 20% base chance
float Probability = 20.0f;
// there is a newbie protection, at level 10 just 7% base chance; assuming linear function
if (victim->getLevel() < 30)
Probability = 0.65f * victim->getLevel() + 0.5f;
uint32 VictimDefense = victim->GetMaxSkillValueForLevel(this);
uint32 AttackerMeleeSkill = GetMaxSkillValueForLevel();
Probability *= AttackerMeleeSkill/(float)VictimDefense*0.16;
if (Probability < 0)
Probability = 0;
if (Probability > 40.0f)
Probability = 40.0f;
if (roll_chance_f(Probability))
CastSpell(victim, 1604, true);
}
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->CastItemCombatSpell(victim, damageInfo->attackType, damageInfo->procVictim, damageInfo->procEx);
// Do effect if any damage done to target
if (damageInfo->damage)
{
// We're going to call functions which can modify content of the list during iteration over it's elements
// Let's copy the list so we can prevent iterator invalidation
AuraEffectList vDamageShieldsCopy(victim->GetAuraEffectsByType(SPELL_AURA_DAMAGE_SHIELD));
for (AuraEffectList::const_iterator dmgShieldItr = vDamageShieldsCopy.begin(); dmgShieldItr != vDamageShieldsCopy.end(); ++dmgShieldItr)
{
SpellInfo const* i_spellProto = (*dmgShieldItr)->GetSpellInfo();
// Damage shield can be resisted...
if (SpellMissInfo missInfo = victim->SpellHitResult(this, i_spellProto, false))
{
victim->SendSpellMiss(this, i_spellProto->Id, missInfo);
continue;
}
// ...or immuned
if (IsImmunedToDamage(i_spellProto))
{
victim->SendSpellDamageImmune(this, i_spellProto->Id);
continue;
}
uint32 damage = (*dmgShieldItr)->GetAmount();
if (Unit* caster = (*dmgShieldItr)->GetCaster())
{
damage = caster->SpellDamageBonusDone(this, i_spellProto, damage, SPELL_DIRECT_DAMAGE);
damage = this->SpellDamageBonusTaken(caster, i_spellProto, damage, SPELL_DIRECT_DAMAGE);
}
// No Unit::CalcAbsorbResist here - opcode doesn't send that data - this damage is probably not affected by that
victim->DealDamageMods(this, damage, NULL);
// TODO: Move this to a packet handler
WorldPacket data(SMSG_SPELLDAMAGESHIELD, 8 + 8 + 4 + 4 + 4 + 4 + 4);
data << uint64(victim->GetGUID());
data << uint64(GetGUID());
data << uint32(i_spellProto->Id);
data << uint32(damage); // Damage
int32 overkill = int32(damage) - int32(GetHealth());
data << uint32(overkill > 0 ? overkill : 0); // Overkill
data << uint32(i_spellProto->SchoolMask);
data << uint32(0); // FIX ME: Send resisted damage, both fully resisted and partly resisted
victim->SendMessageToSet(&data, true);
victim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, i_spellProto->GetSchoolMask(), i_spellProto, true);
}
}
}
void Unit::HandleEmoteCommand(uint32 anim_id)
{
WorldPacket data(SMSG_EMOTE, 4 + 8);
data << uint32(anim_id);
data << uint64(GetGUID());
SendMessageToSet(&data, true);
}
bool Unit::IsDamageReducedByArmor(SpellSchoolMask schoolMask, SpellInfo const* spellInfo, uint8 effIndex)
{
// only physical spells damage gets reduced by armor
if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0)
return false;
if (spellInfo)
{
// there are spells with no specific attribute but they have "ignores armor" in tooltip
if (spellInfo->AttributesCu & SPELL_ATTR0_CU_IGNORE_ARMOR)
return false;
// bleeding effects are not reduced by armor
if (effIndex != MAX_SPELL_EFFECTS)
{
if (spellInfo->Effects[effIndex].ApplyAuraName == SPELL_AURA_PERIODIC_DAMAGE ||
spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_SCHOOL_DAMAGE)
if (spellInfo->GetEffectMechanicMask(effIndex) & (1<<MECHANIC_BLEED))
return false;
}
}
return true;
}
uint32 Unit::CalcArmorReducedDamage(Unit* victim, const uint32 damage, SpellInfo const* spellInfo, WeaponAttackType /*attackType*/)
{
uint32 newdamage = 0;
float armor = float(victim->GetArmor());
// bypass enemy armor by SPELL_AURA_BYPASS_ARMOR_FOR_CASTER
int32 armorBypassPct = 0;
AuraEffectList const & reductionAuras = victim->GetAuraEffectsByType(SPELL_AURA_BYPASS_ARMOR_FOR_CASTER);
for (AuraEffectList::const_iterator i = reductionAuras.begin(); i != reductionAuras.end(); ++i)
if ((*i)->GetCasterGUID() == GetGUID())
armorBypassPct += (*i)->GetAmount();
armor = CalculatePct(armor, 100 - std::min(armorBypassPct, 100));
// Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
if (spellInfo)
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_IGNORE_ARMOR, armor);
AuraEffectList const& ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST);
for (AuraEffectList::const_iterator j = ResIgnoreAuras.begin(); j != ResIgnoreAuras.end(); ++j)
{
if ((*j)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
armor = floor(AddPct(armor, -(*j)->GetAmount()));
}
// Apply Player CR_ARMOR_PENETRATION rating
if (GetTypeId() == TYPEID_PLAYER)
{
float maxArmorPen = 0;
if (victim->getLevel() < 60)
maxArmorPen = float(400 + 85 * victim->getLevel());
else
maxArmorPen = 400 + 85 * victim->getLevel() + 4.5f * 85 * (victim->getLevel() - 59);
// Cap armor penetration to this number
maxArmorPen = std::min((armor + maxArmorPen) / 3, armor);
// Figure out how much armor do we ignore
float armorPen = CalculatePct(maxArmorPen, ToPlayer()->GetRatingBonusValue(CR_ARMOR_PENETRATION));
// Got the value, apply it
armor -= std::min(armorPen, maxArmorPen);
}
if (armor < 0.0f)
armor = 0.0f;
float levelModifier = getLevel();
if (levelModifier > 59)
levelModifier = levelModifier + (4.5f * (levelModifier - 59));
float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
tmpvalue = tmpvalue / (1.0f + tmpvalue);
if (tmpvalue < 0.0f)
tmpvalue = 0.0f;
if (tmpvalue > 0.75f)
tmpvalue = 0.75f;
newdamage = uint32(damage - (damage * tmpvalue));
return (newdamage > 1) ? newdamage : 1;
}
void Unit::CalcAbsorbResist(Unit* victim, SpellSchoolMask schoolMask, DamageEffectType damagetype, uint32 const damage, uint32 *absorb, uint32 *resist, SpellInfo const* spellInfo)
{
if (!victim || !victim->isAlive() || !damage)
return;
DamageInfo dmgInfo = DamageInfo(this, victim, damage, spellInfo, schoolMask, damagetype);
// Magic damage, check for resists
// Ignore spells that cant be resisted
if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0 && (!spellInfo || (spellInfo->AttributesEx4 & SPELL_ATTR4_IGNORE_RESISTANCES) == 0))
{
float victimResistance = float(victim->GetResistance(schoolMask));
victimResistance += float(GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask));
if (Player* player = ToPlayer())
victimResistance -= float(player->GetSpellPenetrationItemMod());
// Resistance can't be lower then 0.
if (victimResistance < 0.0f)
victimResistance = 0.0f;
static uint32 const BOSS_LEVEL = 83;
static float const BOSS_RESISTANCE_CONSTANT = 510.0f;
uint32 level = victim->getLevel();
float resistanceConstant = 0.0f;
if (level == BOSS_LEVEL)
resistanceConstant = BOSS_RESISTANCE_CONSTANT;
else
resistanceConstant = level * 5.0f;
float averageResist = victimResistance / (victimResistance + resistanceConstant);
float discreteResistProbability[11];
for (uint32 i = 0; i < 11; ++i)
{
discreteResistProbability[i] = 0.5f - 2.5f * fabs(0.1f * i - averageResist);
if (discreteResistProbability[i] < 0.0f)
discreteResistProbability[i] = 0.0f;
}
if (averageResist <= 0.1f)
{
discreteResistProbability[0] = 1.0f - 7.5f * averageResist;
discreteResistProbability[1] = 5.0f * averageResist;
discreteResistProbability[2] = 2.5f * averageResist;
}
float r = float(rand_norm());
uint32 i = 0;
float probabilitySum = discreteResistProbability[0];
while (r >= probabilitySum && i < 10)
probabilitySum += discreteResistProbability[++i];
float damageResisted = float(damage * i / 10);
AuraEffectList const& ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST);
for (AuraEffectList::const_iterator j = ResIgnoreAuras.begin(); j != ResIgnoreAuras.end(); ++j)
if ((*j)->GetMiscValue() & schoolMask)
AddPct(damageResisted, -(*j)->GetAmount());
dmgInfo.ResistDamage(uint32(damageResisted));
}
// Ignore Absorption Auras
float auraAbsorbMod = 0;
AuraEffectList const& AbsIgnoreAurasA = GetAuraEffectsByType(SPELL_AURA_MOD_TARGET_ABSORB_SCHOOL);
for (AuraEffectList::const_iterator itr = AbsIgnoreAurasA.begin(); itr != AbsIgnoreAurasA.end(); ++itr)
{
if (!((*itr)->GetMiscValue() & schoolMask))
continue;
if ((*itr)->GetAmount() > auraAbsorbMod)
auraAbsorbMod = float((*itr)->GetAmount());
}
AuraEffectList const& AbsIgnoreAurasB = GetAuraEffectsByType(SPELL_AURA_MOD_TARGET_ABILITY_ABSORB_SCHOOL);
for (AuraEffectList::const_iterator itr = AbsIgnoreAurasB.begin(); itr != AbsIgnoreAurasB.end(); ++itr)
{
if (!((*itr)->GetMiscValue() & schoolMask))
continue;
if (((*itr)->GetAmount() > auraAbsorbMod) && (*itr)->IsAffectingSpell(spellInfo))
auraAbsorbMod = float((*itr)->GetAmount());
}
RoundToInterval(auraAbsorbMod, 0.0f, 100.0f);
// We're going to call functions which can modify content of the list during iteration over it's elements
// Let's copy the list so we can prevent iterator invalidation
AuraEffectList vSchoolAbsorbCopy(victim->GetAuraEffectsByType(SPELL_AURA_SCHOOL_ABSORB));
vSchoolAbsorbCopy.sort(Trinity::AbsorbAuraOrderPred());
// absorb without mana cost
for (AuraEffectList::iterator itr = vSchoolAbsorbCopy.begin(); (itr != vSchoolAbsorbCopy.end()) && (dmgInfo.GetDamage() > 0); ++itr)
{
AuraEffect* absorbAurEff = *itr;
// Check if aura was removed during iteration - we don't need to work on such auras
AuraApplication const* aurApp = absorbAurEff->GetBase()->GetApplicationOfTarget(victim->GetGUID());
if (!aurApp)
continue;
if (!(absorbAurEff->GetMiscValue() & schoolMask))
continue;
// get amount which can be still absorbed by the aura
int32 currentAbsorb = absorbAurEff->GetAmount();
// aura with infinite absorb amount - let the scripts handle absorbtion amount, set here to 0 for safety
if (currentAbsorb < 0)
currentAbsorb = 0;
uint32 tempAbsorb = uint32(currentAbsorb);
bool defaultPrevented = false;
absorbAurEff->GetBase()->CallScriptEffectAbsorbHandlers(absorbAurEff, aurApp, dmgInfo, tempAbsorb, defaultPrevented);
currentAbsorb = tempAbsorb;
if (defaultPrevented)
continue;
// Apply absorb mod auras
AddPct(currentAbsorb, -auraAbsorbMod);
// absorb must be smaller than the damage itself
currentAbsorb = RoundToInterval(currentAbsorb, 0, int32(dmgInfo.GetDamage()));
dmgInfo.AbsorbDamage(currentAbsorb);
tempAbsorb = currentAbsorb;
absorbAurEff->GetBase()->CallScriptEffectAfterAbsorbHandlers(absorbAurEff, aurApp, dmgInfo, tempAbsorb);
// Check if our aura is using amount to count damage
if (absorbAurEff->GetAmount() >= 0)
{
// Reduce shield amount
absorbAurEff->SetAmount(absorbAurEff->GetAmount() - currentAbsorb);
// Aura cannot absorb anything more - remove it
if (absorbAurEff->GetAmount() <= 0)
absorbAurEff->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL);
}
}
// absorb by mana cost
AuraEffectList vManaShieldCopy(victim->GetAuraEffectsByType(SPELL_AURA_MANA_SHIELD));
for (AuraEffectList::const_iterator itr = vManaShieldCopy.begin(); (itr != vManaShieldCopy.end()) && (dmgInfo.GetDamage() > 0); ++itr)
{
AuraEffect* absorbAurEff = *itr;
// Check if aura was removed during iteration - we don't need to work on such auras
AuraApplication const* aurApp = absorbAurEff->GetBase()->GetApplicationOfTarget(victim->GetGUID());
if (!aurApp)
continue;
// check damage school mask
if (!(absorbAurEff->GetMiscValue() & schoolMask))
continue;
// get amount which can be still absorbed by the aura
int32 currentAbsorb = absorbAurEff->GetAmount();
// aura with infinite absorb amount - let the scripts handle absorbtion amount, set here to 0 for safety
if (currentAbsorb < 0)
currentAbsorb = 0;
uint32 tempAbsorb = currentAbsorb;
bool defaultPrevented = false;
absorbAurEff->GetBase()->CallScriptEffectManaShieldHandlers(absorbAurEff, aurApp, dmgInfo, tempAbsorb, defaultPrevented);
currentAbsorb = tempAbsorb;
if (defaultPrevented)
continue;
AddPct(currentAbsorb, -auraAbsorbMod);
// absorb must be smaller than the damage itself
currentAbsorb = RoundToInterval(currentAbsorb, 0, int32(dmgInfo.GetDamage()));
int32 manaReduction = currentAbsorb;
// lower absorb amount by talents
if (float manaMultiplier = absorbAurEff->GetSpellInfo()->Effects[absorbAurEff->GetEffIndex()].CalcValueMultiplier(absorbAurEff->GetCaster()))
manaReduction = int32(float(manaReduction) * manaMultiplier);
int32 manaTaken = -victim->ModifyPower(POWER_MANA, -manaReduction);
// take case when mana has ended up into account
currentAbsorb = currentAbsorb ? int32(float(currentAbsorb) * (float(manaTaken) / float(manaReduction))) : 0;
dmgInfo.AbsorbDamage(currentAbsorb);
tempAbsorb = currentAbsorb;
absorbAurEff->GetBase()->CallScriptEffectAfterManaShieldHandlers(absorbAurEff, aurApp, dmgInfo, tempAbsorb);
// Check if our aura is using amount to count damage
if (absorbAurEff->GetAmount() >= 0)
{
absorbAurEff->SetAmount(absorbAurEff->GetAmount() - currentAbsorb);
if ((absorbAurEff->GetAmount() <= 0))
absorbAurEff->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL);
}
}
// split damage auras - only when not damaging self
if (victim != this)
{
// We're going to call functions which can modify content of the list during iteration over it's elements
// Let's copy the list so we can prevent iterator invalidation
AuraEffectList vSplitDamagePctCopy(victim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_PCT));
for (AuraEffectList::iterator itr = vSplitDamagePctCopy.begin(), next; (itr != vSplitDamagePctCopy.end()) && (dmgInfo.GetDamage() > 0); ++itr)
{
// Check if aura was removed during iteration - we don't need to work on such auras
AuraApplication const* aurApp = (*itr)->GetBase()->GetApplicationOfTarget(victim->GetGUID());
if (!aurApp)
continue;
// check damage school mask
if (!((*itr)->GetMiscValue() & schoolMask))
continue;
// Damage can be splitted only if aura has an alive caster
Unit* caster = (*itr)->GetCaster();
if (!caster || (caster == victim) || !caster->IsInWorld() || !caster->isAlive())
continue;
uint32 splitDamage = CalculatePct(dmgInfo.GetDamage(), (*itr)->GetAmount());
(*itr)->GetBase()->CallScriptEffectSplitHandlers((*itr), aurApp, dmgInfo, splitDamage);
// absorb must be smaller than the damage itself
splitDamage = RoundToInterval(splitDamage, uint32(0), uint32(dmgInfo.GetDamage()));
dmgInfo.AbsorbDamage(splitDamage);
uint32 splitted = splitDamage;
uint32 split_absorb = 0;
DealDamageMods(caster, splitted, &split_absorb);
SendSpellNonMeleeDamageLog(caster, (*itr)->GetSpellInfo()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false);
CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL);
DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*itr)->GetSpellInfo(), false);
}
}
*resist = dmgInfo.GetResist();
*absorb = dmgInfo.GetAbsorb();
}
void Unit::CalcHealAbsorb(Unit* victim, const SpellInfo* healSpell, uint32 &healAmount, uint32 &absorb)
{
if (!healAmount)
return;
int32 RemainingHeal = healAmount;
// Need remove expired auras after
bool existExpired = false;
// absorb without mana cost
AuraEffectList const& vHealAbsorb = victim->GetAuraEffectsByType(SPELL_AURA_SCHOOL_HEAL_ABSORB);
for (AuraEffectList::const_iterator i = vHealAbsorb.begin(); i != vHealAbsorb.end() && RemainingHeal > 0; ++i)
{
if (!((*i)->GetMiscValue() & healSpell->SchoolMask))
continue;
// Max Amount can be absorbed by this aura
int32 currentAbsorb = (*i)->GetAmount();
// Found empty aura (impossible but..)
if (currentAbsorb <= 0)
{
existExpired = true;
continue;
}
// currentAbsorb - damage can be absorbed by shield
// If need absorb less damage
if (RemainingHeal < currentAbsorb)
currentAbsorb = RemainingHeal;
RemainingHeal -= currentAbsorb;
// Reduce shield amount
(*i)->SetAmount((*i)->GetAmount() - currentAbsorb);
// Need remove it later
if ((*i)->GetAmount() <= 0)
existExpired = true;
}
// Remove all expired absorb auras
if (existExpired)
{
for (AuraEffectList::const_iterator i = vHealAbsorb.begin(); i != vHealAbsorb.end();)
{
AuraEffect* auraEff = *i;
++i;
if (auraEff->GetAmount() <= 0)
{
uint32 removedAuras = victim->m_removedAurasCount;
auraEff->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL);
if (removedAuras+1 < victim->m_removedAurasCount)
i = vHealAbsorb.begin();
}
}
}
absorb = RemainingHeal > 0 ? (healAmount - RemainingHeal) : healAmount;
healAmount = RemainingHeal;
}
void Unit::AttackerStateUpdate (Unit* victim, WeaponAttackType attType, bool extra)
{
if (HasUnitState(UNIT_STATE_CANNOT_AUTOATTACK) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
return;
if (!victim->isAlive())
return;
if ((attType == BASE_ATTACK || attType == OFF_ATTACK) && !IsWithinLOSInMap(victim))
return;
CombatStart(victim);
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MELEE_ATTACK);
if (attType != BASE_ATTACK && attType != OFF_ATTACK)
return; // ignore ranged case
// melee attack spell casted at main hand attack only - no normal melee dmg dealt
if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL] && !extra)
m_currentSpells[CURRENT_MELEE_SPELL]->cast();
else
{
// attack can be redirected to another target
victim = GetMeleeHitRedirectTarget(victim);
CalcDamageInfo damageInfo;
CalculateMeleeDamage(victim, 0, &damageInfo, attType);
// Send log damage message to client
DealDamageMods(victim, damageInfo.damage, &damageInfo.absorb);
SendAttackStateUpdate(&damageInfo);
//TriggerAurasProcOnEvent(damageInfo);
ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
DealMeleeDamage(&damageInfo, true);
if (GetTypeId() == TYPEID_PLAYER)
sLog->outDebug(LOG_FILTER_UNITS, "AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
GetGUIDLow(), victim->GetGUIDLow(), victim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
else
sLog->outDebug(LOG_FILTER_UNITS, "AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
GetGUIDLow(), victim->GetGUIDLow(), victim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
}
}
void Unit::HandleProcExtraAttackFor(Unit* victim)
{
while (m_extraAttacks)
{
AttackerStateUpdate(victim, BASE_ATTACK, true);
--m_extraAttacks;
}
}
MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* victim, WeaponAttackType attType) const
{
// This is only wrapper
// Miss chance based on melee
//float miss_chance = MeleeMissChanceCalc(victim, attType);
float miss_chance = MeleeSpellMissChance(victim, attType, 0);
// Critical hit chance
float crit_chance = GetUnitCriticalChance(attType, victim);
// stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
float dodge_chance = victim->GetUnitDodgeChance();
float block_chance = victim->GetUnitBlockChance();
float parry_chance = victim->GetUnitParryChance();
// Useful if want to specify crit & miss chances for melee, else it could be removed
sLog->outDebug(LOG_FILTER_UNITS, "MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance, crit_chance, dodge_chance, parry_chance, block_chance);
return RollMeleeOutcomeAgainst(victim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100), int32(parry_chance*100), int32(block_chance*100));
}
MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit* victim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
{
if (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode())
return MELEE_HIT_EVADE;
int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(victim);
int32 victimMaxSkillValueForLevel = victim->GetMaxSkillValueForLevel(this);
// bonus from skills is 0.04%
int32 skillBonus = 4 * (attackerMaxSkillValueForLevel - victimMaxSkillValueForLevel);
int32 sum = 0, tmp = 0;
int32 roll = urand (0, 10000);
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
tmp = miss_chance;
if (tmp > 0 && roll < (sum += tmp))
{
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: MISS");
return MELEE_HIT_MISS;
}
// always crit against a sitting target (except 0 crit chance)
if (victim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !victim->IsStandState())
{
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: CRIT (sitting victim)");
return MELEE_HIT_CRIT;
}
// Dodge chance
// only players can't dodge if attacker is behind
if (victim->GetTypeId() == TYPEID_PLAYER && !victim->HasInArc(M_PI, this) && !victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
{
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
}
else
{
// Reduce dodge chance by attacker expertise rating
if (GetTypeId() == TYPEID_PLAYER)
dodge_chance -= int32(ToPlayer()->GetExpertiseDodgeOrParryReduction(attType) * 100);
else
dodge_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25;
// Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE) * 100;
dodge_chance = int32 (float (dodge_chance) * GetTotalAuraMultiplier(SPELL_AURA_MOD_ENEMY_DODGE));
tmp = dodge_chance;
if ((tmp > 0) // check if unit _can_ dodge
&& ((tmp -= skillBonus) > 0)
&& roll < (sum += tmp))
{
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
return MELEE_HIT_DODGE;
}
}
// parry & block chances
// check if attack comes from behind, nobody can parry or block if attacker is behind
if (!victim->HasInArc(M_PI, this) && !victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: attack came from behind.");
else
{
// Reduce parry chance by attacker expertise rating
if (GetTypeId() == TYPEID_PLAYER)
parry_chance -= int32(ToPlayer()->GetExpertiseDodgeOrParryReduction(attType) * 100);
else
parry_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25;
if (victim->GetTypeId() == TYPEID_PLAYER || !(victim->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY))
{
int32 tmp2 = int32(parry_chance);
if (tmp2 > 0 // check if unit _can_ parry
&& (tmp2 -= skillBonus) > 0
&& roll < (sum += tmp2))
{
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp2, sum);
return MELEE_HIT_PARRY;
}
}
if (victim->GetTypeId() == TYPEID_PLAYER || !(victim->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK))
{
tmp = block_chance;
if (tmp > 0 // check if unit _can_ block
&& (tmp -= skillBonus) > 0
&& roll < (sum += tmp))
{
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
return MELEE_HIT_BLOCK;
}
}
}
// Critical chance
tmp = crit_chance;
if (tmp > 0 && roll < (sum += tmp))
{
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
if (GetTypeId() == TYPEID_UNIT && (ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRIT))
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: CRIT DISABLED)");
else
return MELEE_HIT_CRIT;
}
// Max 40% chance to score a glancing blow against mobs that are higher level (can do only players and pets and not with ranged weapon)
if (attType != RANGED_ATTACK &&
(GetTypeId() == TYPEID_PLAYER || ToCreature()->isPet()) &&
victim->GetTypeId() != TYPEID_PLAYER && !victim->ToCreature()->isPet() &&
getLevel() < victim->getLevelForTarget(this))
{
// cap possible value (with bonuses > max skill)
int32 skill = attackerMaxSkillValueForLevel;
tmp = (10 + (victimMaxSkillValueForLevel - skill)) * 100;
tmp = tmp > 4000 ? 4000 : tmp;
if (roll < (sum += tmp))
{
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
return MELEE_HIT_GLANCING;
}
}
// mobs can score crushing blows if they're 4 or more levels above victim
if (getLevelForTarget(victim) >= victim->getLevelForTarget(this) + 4 &&
// can be from by creature (if can) or from controlled player that considered as creature
!IsControlledByPlayer() &&
!(GetTypeId() == TYPEID_UNIT && ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH))
{
// when their weapon skill is 15 or more above victim's defense skill
tmp = victimMaxSkillValueForLevel;
// tmp = mob's level * 5 - player's current defense skill
tmp = attackerMaxSkillValueForLevel - tmp;
if (tmp >= 15)
{
// add 2% chance per lacking skill point, min. is 15%
tmp = tmp * 200 - 1500;
if (roll < (sum += tmp))
{
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
return MELEE_HIT_CRUSHING;
}
}
}
sLog->outDebug(LOG_FILTER_UNITS, "RollMeleeOutcomeAgainst: NORMAL");
return MELEE_HIT_NORMAL;
}
uint32 Unit::CalculateDamage(WeaponAttackType attType, bool normalized, bool addTotalPct)
{
float min_damage, max_damage;
if (GetTypeId() == TYPEID_PLAYER && (normalized || !addTotalPct))
ToPlayer()->CalculateMinMaxDamage(attType, normalized, addTotalPct, min_damage, max_damage);
else
{
switch (attType)
{
case RANGED_ATTACK:
min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
break;
case BASE_ATTACK:
min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
break;
case OFF_ATTACK:
min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
break;
// Just for good manner
default:
min_damage = 0.0f;
max_damage = 0.0f;
break;
}
}
if (min_damage > max_damage)
std::swap(min_damage, max_damage);
if (max_damage == 0.0f)
max_damage = 5.0f;
return urand((uint32)min_damage, (uint32)max_damage);
}
float Unit::CalculateLevelPenalty(SpellInfo const* spellProto) const
{
if (spellProto->SpellLevel <= 0 || spellProto->SpellLevel >= spellProto->MaxLevel)
return 1.0f;
float LvlPenalty = 0.0f;
if (spellProto->SpellLevel < 20)
LvlPenalty = 20.0f - spellProto->SpellLevel * 3.75f;
float LvlFactor = (float(spellProto->SpellLevel) + 6.0f) / float(getLevel());
if (LvlFactor > 1.0f)
LvlFactor = 1.0f;
return AddPct(LvlFactor, -LvlPenalty);
}
void Unit::SendMeleeAttackStart(Unit* victim)
{
WorldPacket data(SMSG_ATTACKSTART, 8 + 8);
data << uint64(GetGUID());
data << uint64(victim->GetGUID());
SendMessageToSet(&data, true);
sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Sent SMSG_ATTACKSTART");
}
void Unit::SendMeleeAttackStop(Unit* victim)
{
WorldPacket data(SMSG_ATTACKSTOP, (8+8+4));
data.append(GetPackGUID());
data.append(victim ? victim->GetPackGUID() : 0);
data << uint32(0); //! Can also take the value 0x01, which seems related to updating rotation
SendMessageToSet(&data, true);
sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Sent SMSG_ATTACKSTOP");
if (victim)
sLog->outInfo(LOG_FILTER_UNITS, "%s %u stopped attacking %s %u", (GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), GetGUIDLow(), (victim->GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), victim->GetGUIDLow());
else
sLog->outInfo(LOG_FILTER_UNITS, "%s %u stopped attacking", (GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), GetGUIDLow());
}
bool Unit::isSpellBlocked(Unit* victim, SpellInfo const* spellProto, WeaponAttackType /*attackType*/)
{
// These spells can't be blocked
if (spellProto && spellProto->Attributes & SPELL_ATTR0_IMPOSSIBLE_DODGE_PARRY_BLOCK)
return false;
if (victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION) || victim->HasInArc(M_PI, this))
{
// Check creatures flags_extra for disable block
if (victim->GetTypeId() == TYPEID_UNIT &&
victim->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK)
return false;
if (roll_chance_f(victim->GetUnitBlockChance()))
return true;
}
return false;
}
bool Unit::isBlockCritical()
{
if (roll_chance_i(GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_CRIT_CHANCE)))
return true;
return false;
}
int32 Unit::GetMechanicResistChance(const SpellInfo* spell)
{
if (!spell)
return 0;
int32 resist_mech = 0;
for (uint8 eff = 0; eff < MAX_SPELL_EFFECTS; ++eff)
{
if (!spell->Effects[eff].IsEffect())
break;
int32 effect_mech = spell->GetEffectMechanic(eff);
if (effect_mech)
{
int32 temp = GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
if (resist_mech < temp)
resist_mech = temp;
}
}
return resist_mech;
}
// Melee based spells hit result calculations
SpellMissInfo Unit::MeleeSpellHitResult(Unit* victim, SpellInfo const* spell)
{
// Spells with SPELL_ATTR3_IGNORE_HIT_RESULT will additionally fully ignore
// resist and deflect chances
if (spell->AttributesEx3 & SPELL_ATTR3_IGNORE_HIT_RESULT)
return SPELL_MISS_NONE;
WeaponAttackType attType = BASE_ATTACK;
// Check damage class instead of attack type to correctly handle judgements
// - they are meele, but can't be dodged/parried/deflected because of ranged dmg class
if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
attType = RANGED_ATTACK;
uint32 roll = urand (0, 10000);
uint32 missChance = uint32(MeleeSpellMissChance(victim, attType, spell->Id) * 100.0f);
// Roll miss
uint32 tmp = missChance;
if (roll < tmp)
return SPELL_MISS_MISS;
// Chance resist mechanic (select max value from every mechanic spell effect)
int32 resist_mech = 0;
// Get effects mechanic and chance
for (uint8 eff = 0; eff < MAX_SPELL_EFFECTS; ++eff)
{
int32 effect_mech = spell->GetEffectMechanic(eff);
if (effect_mech)
{
int32 temp = victim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
if (resist_mech < temp*100)
resist_mech = temp*100;
}
}
// Roll chance
tmp += resist_mech;
if (roll < tmp)
return SPELL_MISS_RESIST;
bool canDodge = true;
bool canParry = true;
bool canBlock = spell->AttributesEx3 & SPELL_ATTR3_BLOCKABLE_SPELL;
// Same spells cannot be parry/dodge
if (spell->Attributes & SPELL_ATTR0_IMPOSSIBLE_DODGE_PARRY_BLOCK)
return SPELL_MISS_NONE;
// Chance resist mechanic
int32 resist_chance = victim->GetMechanicResistChance(spell) * 100;
tmp += resist_chance;
if (roll < tmp)
return SPELL_MISS_RESIST;
// Ranged attacks can only miss, resist and deflect
if (attType == RANGED_ATTACK)
{
canParry = false;
canDodge = false;
// only if in front
if (victim->HasInArc(M_PI, this) || victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
{
int32 deflect_chance = victim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS) * 100;
tmp+=deflect_chance;
if (roll < tmp)
return SPELL_MISS_DEFLECT;
}
return SPELL_MISS_NONE;
}
// Check for attack from behind
if (!victim->HasInArc(M_PI, this))
{
if (!victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
{
// Can`t dodge from behind in PvP (but its possible in PvE)
if (victim->GetTypeId() == TYPEID_PLAYER)
canDodge = false;
// Can`t parry or block
canParry = false;
canBlock = false;
}
else // Only deterrence as of 3.3.5
{
if (spell->AttributesCu & SPELL_ATTR0_CU_REQ_CASTER_BEHIND_TARGET)
canParry = false;
}
}
// Check creatures flags_extra for disable parry
if (victim->GetTypeId() == TYPEID_UNIT)
{
uint32 flagEx = victim->ToCreature()->GetCreatureTemplate()->flags_extra;
if (flagEx & CREATURE_FLAG_EXTRA_NO_PARRY)
canParry = false;
// Check creatures flags_extra for disable block
if (flagEx & CREATURE_FLAG_EXTRA_NO_BLOCK)
canBlock = false;
}
// Ignore combat result aura
AuraEffectList const& ignore = GetAuraEffectsByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
for (AuraEffectList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
{
if (!(*i)->IsAffectingSpell(spell))
continue;
switch ((*i)->GetMiscValue())
{
case MELEE_HIT_DODGE: canDodge = false; break;
case MELEE_HIT_BLOCK: canBlock = false; break;
case MELEE_HIT_PARRY: canParry = false; break;
default:
sLog->outDebug(LOG_FILTER_UNITS, "Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT has unhandled state %d", (*i)->GetId(), (*i)->GetMiscValue());
break;
}
}
if (canDodge)
{
// Roll dodge
int32 dodgeChance = int32(victim->GetUnitDodgeChance() * 100.0f);
// Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
dodgeChance += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE) * 100;
dodgeChance = int32(float(dodgeChance) * GetTotalAuraMultiplier(SPELL_AURA_MOD_ENEMY_DODGE));
// Reduce dodge chance by attacker expertise rating
if (GetTypeId() == TYPEID_PLAYER)
dodgeChance -= int32(ToPlayer()->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
else
dodgeChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25;
if (dodgeChance < 0)
dodgeChance = 0;
if (roll < (tmp += dodgeChance))
return SPELL_MISS_DODGE;
}
if (canParry)
{
// Roll parry
int32 parryChance = int32(victim->GetUnitParryChance() * 100.0f);
// Reduce parry chance by attacker expertise rating
if (GetTypeId() == TYPEID_PLAYER)
parryChance -= int32(ToPlayer()->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
else
parryChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25;
if (parryChance < 0)
parryChance = 0;
tmp += parryChance;
if (roll < tmp)
return SPELL_MISS_PARRY;
}
if (canBlock)
{
int32 blockChance = int32(victim->GetUnitBlockChance() * 100.0f);
if (blockChance < 0)
blockChance = 0;
tmp += blockChance;
if (roll < tmp)
return SPELL_MISS_BLOCK;
}
return SPELL_MISS_NONE;
}
// TODO need use unit spell resistances in calculations
SpellMissInfo Unit::MagicSpellHitResult(Unit* victim, SpellInfo const* spell)
{
// Can`t miss on dead target (on skinning for example)
if (!victim->isAlive() && victim->GetTypeId() != TYPEID_PLAYER)
return SPELL_MISS_NONE;
SpellSchoolMask schoolMask = spell->GetSchoolMask();
// PvP - PvE spell misschances per leveldif > 2
int32 lchance = victim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
int32 thisLevel = getLevelForTarget(victim);
if (GetTypeId() == TYPEID_UNIT && ToCreature()->isTrigger())
thisLevel = std::max<int32>(thisLevel, spell->SpellLevel);
int32 leveldif = int32(victim->getLevelForTarget(this)) - thisLevel;
// Base hit chance from attacker and victim levels
int32 modHitChance;
if (leveldif < 3)
modHitChance = 96 - leveldif;
else
modHitChance = 94 - (leveldif - 2) * lchance;
// Spellmod from SPELLMOD_RESIST_MISS_CHANCE
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
// Spells with SPELL_ATTR3_IGNORE_HIT_RESULT will ignore target's avoidance effects
if (!(spell->AttributesEx3 & SPELL_ATTR3_IGNORE_HIT_RESULT))
{
// Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
modHitChance += victim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
}
int32 HitChance = modHitChance * 100;
// Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
HitChance += int32(m_modSpellHitChance * 100.0f);
if (HitChance < 100)
HitChance = 100;
else if (HitChance > 10000)
HitChance = 10000;
int32 tmp = 10000 - HitChance;
int32 rand = irand(0, 10000);
if (rand < tmp)
return SPELL_MISS_MISS;
// Spells with SPELL_ATTR3_IGNORE_HIT_RESULT will additionally fully ignore
// resist and deflect chances
if (spell->AttributesEx3 & SPELL_ATTR3_IGNORE_HIT_RESULT)
return SPELL_MISS_NONE;
// Chance resist mechanic (select max value from every mechanic spell effect)
int32 resist_chance = victim->GetMechanicResistChance(spell) * 100;
tmp += resist_chance;
// Roll chance
if (rand < tmp)
return SPELL_MISS_RESIST;
// cast by caster in front of victim
if (victim->HasInArc(M_PI, this) || victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))
{
int32 deflect_chance = victim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS) * 100;
tmp += deflect_chance;
if (rand < tmp)
return SPELL_MISS_DEFLECT;
}
return SPELL_MISS_NONE;
}
// Calculate spell hit result can be:
// Every spell can: Evade/Immune/Reflect/Sucesful hit
// For melee based spells:
// Miss
// Dodge
// Parry
// For spells
// Resist
SpellMissInfo Unit::SpellHitResult(Unit* victim, SpellInfo const* spell, bool CanReflect)
{
// Check for immune
if (victim->IsImmunedToSpell(spell))
return SPELL_MISS_IMMUNE;
// All positive spells can`t miss
// TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
if (spell->IsPositive()
&&(!IsHostileTo(victim))) // prevent from affecting enemy by "positive" spell
return SPELL_MISS_NONE;
// Check for immune
if (victim->IsImmunedToDamage(spell))
return SPELL_MISS_IMMUNE;
if (this == victim)
return SPELL_MISS_NONE;
// Return evade for units in evade mode
if (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode())
return SPELL_MISS_EVADE;
// Try victim reflect spell
if (CanReflect)
{
int32 reflectchance = victim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
Unit::AuraEffectList const& mReflectSpellsSchool = victim->GetAuraEffectsByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
for (Unit::AuraEffectList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
if ((*i)->GetMiscValue() & spell->GetSchoolMask())
reflectchance += (*i)->GetAmount();
if (reflectchance > 0 && roll_chance_i(reflectchance))
{
// Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
ProcDamageAndSpell(victim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
return SPELL_MISS_REFLECT;
}
}
switch (spell->DmgClass)
{
case SPELL_DAMAGE_CLASS_RANGED:
case SPELL_DAMAGE_CLASS_MELEE:
return MeleeSpellHitResult(victim, spell);
case SPELL_DAMAGE_CLASS_NONE:
return SPELL_MISS_NONE;
case SPELL_DAMAGE_CLASS_MAGIC:
return MagicSpellHitResult(victim, spell);
}
return SPELL_MISS_NONE;
}
float Unit::GetUnitDodgeChance() const
{
if (IsNonMeleeSpellCasted(false) || HasUnitState(UNIT_STATE_CONTROLLED))
return 0.0f;
if (GetTypeId() == TYPEID_PLAYER)
return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
else
{
if (ToCreature()->isTotem())
return 0.0f;
else
{
float dodge = 5.0f;
dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
return dodge > 0.0f ? dodge : 0.0f;
}
}
}
float Unit::GetUnitParryChance() const
{
if (IsNonMeleeSpellCasted(false) || HasUnitState(UNIT_STATE_CONTROLLED))
return 0.0f;
float chance = 0.0f;
if (Player const* player = ToPlayer())
{
if (player->CanParry())
{
Item* tmpitem = player->GetWeaponForAttack(BASE_ATTACK, true);
if (!tmpitem)
tmpitem = player->GetWeaponForAttack(OFF_ATTACK, true);
if (tmpitem)
chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
}
}
else if (GetTypeId() == TYPEID_UNIT)
{
if (GetCreatureType() == CREATURE_TYPE_HUMANOID)
{
chance = 5.0f;
chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
}
}
return chance > 0.0f ? chance : 0.0f;
}
float Unit::GetUnitMissChance(WeaponAttackType attType) const
{
float miss_chance = 5.00f;
if (attType == RANGED_ATTACK)
miss_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
else
miss_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
return miss_chance;
}
float Unit::GetUnitBlockChance() const
{
if (IsNonMeleeSpellCasted(false) || HasUnitState(UNIT_STATE_CONTROLLED))
return 0.0f;
if (Player const* player = ToPlayer())
{
if (player->CanBlock())
{
Item* tmpitem = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
if (tmpitem && !tmpitem->IsBroken())
return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
}
// is player but has no block ability or no not broken shield equipped
return 0.0f;
}
else
{
if (ToCreature()->isTotem())
return 0.0f;
else
{
float block = 5.0f;
block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
return block > 0.0f ? block : 0.0f;
}
}
}
float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit* victim) const
{
float crit;
if (GetTypeId() == TYPEID_PLAYER)
{
switch (attackType)
{
case BASE_ATTACK:
crit = GetFloatValue(PLAYER_CRIT_PERCENTAGE);
break;
case OFF_ATTACK:
crit = GetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE);
break;
case RANGED_ATTACK:
crit = GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE);
break;
// Just for good manner
default:
crit = 0.0f;
break;
}
}
else
{
crit = 5.0f;
crit += GetTotalAuraModifier(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT);
crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT);
}
// flat aura mods
if (attackType == RANGED_ATTACK)
crit += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
else
crit += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
crit += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
if (crit < 0.0f)
crit = 0.0f;
return crit;
}
void Unit::_DeleteRemovedAuras()
{
while (!m_removedAuras.empty())
{
delete m_removedAuras.front();
m_removedAuras.pop_front();
}
}
void Unit::_UpdateSpells(uint32 time)
{
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
_UpdateAutoRepeatSpell();
// remove finished spells from current pointers
for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
{
if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
{
m_currentSpells[i]->SetReferencedFromCurrent(false);
m_currentSpells[i] = NULL; // remove pointer
}
}
// m_auraUpdateIterator can be updated in indirect called code at aura remove to skip next planned to update but removed auras
for (m_auraUpdateIterator = m_ownedAuras.begin(); m_auraUpdateIterator != m_ownedAuras.end();)
{
Aura* i_aura = m_auraUpdateIterator->second;
++m_auraUpdateIterator; // need shift to next for allow update if need into aura update
i_aura->UpdateOwner(time, this);
}
// remove expired auras - do that after updates(used in scripts?)
for (AuraMap::iterator i = m_ownedAuras.begin(); i != m_ownedAuras.end();)
{
if (i->second->IsExpired())
RemoveOwnedAura(i, AURA_REMOVE_BY_EXPIRE);
else
++i;
}
for (VisibleAuraMap::iterator itr = m_visibleAuras.begin(); itr != m_visibleAuras.end(); ++itr)
if (itr->second->IsNeedClientUpdate())
itr->second->ClientUpdate();
_DeleteRemovedAuras();
if (!m_gameObj.empty())
{
GameObjectList::iterator itr;
for (itr = m_gameObj.begin(); itr != m_gameObj.end();)
{
if (!(*itr)->isSpawned())
{
(*itr)->SetOwnerGUID(0);
(*itr)->SetRespawnTime(0);
(*itr)->Delete();
m_gameObj.erase(itr++);
}
else
++itr;
}
}
}
void Unit::_UpdateAutoRepeatSpell()
{
// check "realtime" interrupts
// don't cancel spells which are affected by a SPELL_AURA_CAST_WHILE_WALKING effect
if (((GetTypeId() == TYPEID_PLAYER && ToPlayer()->isMoving()) || IsNonMeleeSpellCasted(false, false, true, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == 75)) &&
!HasAuraTypeWithAffectMask(SPELL_AURA_CAST_WHILE_WALKING, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo))
{
// cancel wand shoot
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75)
InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
m_AutoRepeatFirstCast = true;
return;
}
// apply delay (Auto Shot (spellID 75) not affected)
if (m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 && m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75)
setAttackTimer(RANGED_ATTACK, 500);
m_AutoRepeatFirstCast = false;
// castroutine
if (isAttackReady(RANGED_ATTACK))
{
// Check if able to cast
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
{
InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
return;
}
// we want to shoot
Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, TRIGGERED_FULL_MASK);
spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
// all went good, reset attack
resetAttackTimer(RANGED_ATTACK);
}
}
void Unit::SetCurrentCastedSpell(Spell* pSpell)
{
ASSERT(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer();
if (pSpell == m_currentSpells[CSpellType]) // avoid breaking self
return;
// break same type spell if it is not delayed
InterruptSpell(CSpellType, false);
// special breakage effects:
switch (CSpellType)
{
case CURRENT_GENERIC_SPELL:
{
// generic spells always break channeled not delayed spells
InterruptSpell(CURRENT_CHANNELED_SPELL, false);
// autorepeat breaking
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
{
// break autorepeat if not Auto Shot
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75)
InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
m_AutoRepeatFirstCast = true;
}
if (pSpell->m_spellInfo->CalcCastTime(this) > 0)
AddUnitState(UNIT_STATE_CASTING);
break;
}
case CURRENT_CHANNELED_SPELL:
{
// channel spells always break generic non-delayed and any channeled spells
InterruptSpell(CURRENT_GENERIC_SPELL, false);
InterruptSpell(CURRENT_CHANNELED_SPELL);
// it also does break autorepeat if not Auto Shot
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75)
InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
AddUnitState(UNIT_STATE_CASTING);
break;
}
case CURRENT_AUTOREPEAT_SPELL:
{
// only Auto Shoot does not break anything
if (pSpell->m_spellInfo->Id != 75)
{
// generic autorepeats break generic non-delayed and channeled non-delayed spells
InterruptSpell(CURRENT_GENERIC_SPELL, false);
InterruptSpell(CURRENT_CHANNELED_SPELL, false);
}
// special action: set first cast flag
m_AutoRepeatFirstCast = true;
break;
}
default:
break; // other spell types don't break anything now
}
// current spell (if it is still here) may be safely deleted now
if (m_currentSpells[CSpellType])
m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
// set new current spell
m_currentSpells[CSpellType] = pSpell;
pSpell->SetReferencedFromCurrent(true);
pSpell->m_selfContainer = &(m_currentSpells[pSpell->GetCurrentContainer()]);
}
void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed, bool withInstant)
{
ASSERT(spellType < CURRENT_MAX_SPELL);
//sLog->outDebug(LOG_FILTER_UNITS, "Interrupt spell for unit %u.", GetEntry());
Spell* spell = m_currentSpells[spellType];
if (spell
&& (withDelayed || spell->getState() != SPELL_STATE_DELAYED)
&& (withInstant || spell->GetCastTime() > 0))
{
// for example, do not let self-stun aura interrupt itself
if (!spell->IsInterruptable())
return;
// send autorepeat cancel message for autorepeat spells
if (spellType == CURRENT_AUTOREPEAT_SPELL)
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SendAutoRepeatCancel(this);
if (spell->getState() != SPELL_STATE_FINISHED)
spell->cancel();
m_currentSpells[spellType] = NULL;
spell->SetReferencedFromCurrent(false);
}
}
void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/)
{
Spell* spell = m_currentSpells[spellType];
if (!spell)
return;
if (spellType == CURRENT_CHANNELED_SPELL)
spell->SendChannelUpdate(0);
spell->finish(ok);
}
bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat, bool isAutoshoot, bool skipInstant) const
{
// We don't do loop here to explicitly show that melee spell is excluded.
// Maybe later some special spells will be excluded too.
// if skipInstant then instant spells shouldn't count as being casted
if (skipInstant && m_currentSpells[CURRENT_GENERIC_SPELL] && !m_currentSpells[CURRENT_GENERIC_SPELL]->GetCastTime())
return false;
// generic spells are casted when they are not finished and not delayed
if (m_currentSpells[CURRENT_GENERIC_SPELL] &&
(m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
(withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED))
{
if (!isAutoshoot || !(m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS))
return true;
}
// channeled spells may be delayed, but they are still considered casted
else if (!skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
(m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED))
{
if (!isAutoshoot || !(m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS))
return true;
}
// autorepeat spells may be finished or delayed, but they are still considered casted
else if (!skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
return true;
return false;
}
void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id, bool withInstant)
{
// generic spells are interrupted if they are not finished or delayed
if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id == spell_id))
InterruptSpell(CURRENT_GENERIC_SPELL, withDelayed, withInstant);
// autorepeat spells are interrupted if they are not finished or delayed
if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == spell_id))
InterruptSpell(CURRENT_AUTOREPEAT_SPELL, withDelayed, withInstant);
// channeled spells are interrupted if they are not finished, even if they are delayed
if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id == spell_id))
InterruptSpell(CURRENT_CHANNELED_SPELL, true, true);
}
Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
{
for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id == spell_id)
return m_currentSpells[i];
return NULL;
}
int32 Unit::GetCurrentSpellCastTime(uint32 spell_id) const
{
if (Spell const* spell = FindCurrentSpellBySpellId(spell_id))
return spell->GetCastTime();
return 0;
}
bool Unit::isInFrontInMap(Unit const* target, float distance, float arc) const
{
return IsWithinDistInMap(target, distance) && HasInArc(arc, target);
}
bool Unit::isInBackInMap(Unit const* target, float distance, float arc) const
{
return IsWithinDistInMap(target, distance) && !HasInArc(2 * M_PI - arc, target);
}
bool Unit::isInAccessiblePlaceFor(Creature const* c) const
{
if (IsInWater())
return c->canSwim();
else
return c->canWalk() || c->CanFly();
}
bool Unit::IsInWater() const
{
return GetBaseMap()->IsInWater(GetPositionX(), GetPositionY(), GetPositionZ());
}
bool Unit::IsUnderWater() const
{
return GetBaseMap()->IsUnderWater(GetPositionX(), GetPositionY(), GetPositionZ());
}
void Unit::UpdateUnderwaterState(Map* m, float x, float y, float z)
{
if (!isPet() && !IsVehicle())
return;
LiquidData liquid_status;
ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
if (!res)
{
if (_lastLiquid && _lastLiquid->SpellId)
RemoveAurasDueToSpell(_lastLiquid->SpellId);
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
_lastLiquid = NULL;
return;
}
if (uint32 liqEntry = liquid_status.entry)
{
LiquidTypeEntry const* liquid = sLiquidTypeStore.LookupEntry(liqEntry);
if (_lastLiquid && _lastLiquid->SpellId && _lastLiquid->Id != liqEntry)
RemoveAurasDueToSpell(_lastLiquid->SpellId);
if (liquid && liquid->SpellId)
{
if (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER))
{
if (!HasAura(liquid->SpellId))
CastSpell(this, liquid->SpellId, true);
}
else
RemoveAurasDueToSpell(liquid->SpellId);
}
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_ABOVEWATER);
_lastLiquid = liquid;
}
else if (_lastLiquid && _lastLiquid->SpellId)
{
RemoveAurasDueToSpell(_lastLiquid->SpellId);
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
_lastLiquid = NULL;
}
}
void Unit::DeMorph()
{
SetDisplayId(GetNativeDisplayId());
}
Aura* Unit::_TryStackingOrRefreshingExistingAura(SpellInfo const* newAura, uint8 effMask, Unit* caster, int32* baseAmount /*= NULL*/, Item* castItem /*= NULL*/, uint64 casterGUID /*= 0*/)
{
ASSERT(casterGUID || caster);
// Check if these can stack anyway
if (!casterGUID && !newAura->IsStackableOnOneSlotWithDifferentCasters())
casterGUID = caster->GetGUID();
// passive and Incanter's Absorption and auras with different type can stack with themselves any number of times
if (!newAura->IsMultiSlotAura())
{
// check if cast item changed
uint64 castItemGUID = 0;
if (castItem)
castItemGUID = castItem->GetGUID();
// find current aura from spell and change it's stackamount, or refresh it's duration
if (Aura* foundAura = GetOwnedAura(newAura->Id, casterGUID, (newAura->AttributesCu & SPELL_ATTR0_CU_ENCHANT_PROC) ? castItemGUID : 0, 0))
{
// effect masks do not match
// extremely rare case
// let's just recreate aura
if (effMask != foundAura->GetEffectMask())
return NULL;
// update basepoints with new values - effect amount will be recalculated in ModStackAmount
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (!foundAura->HasEffect(i))
continue;
int bp;
if (baseAmount)
bp = *(baseAmount + i);
else
bp = foundAura->GetSpellInfo()->Effects[i].BasePoints;
int32* oldBP = const_cast<int32*>(&(foundAura->GetEffect(i)->m_baseAmount));
*oldBP = bp;
}
// correct cast item guid if needed
if (castItemGUID != foundAura->GetCastItemGUID())
{
uint64* oldGUID = const_cast<uint64 *>(&foundAura->m_castItemGuid);
*oldGUID = castItemGUID;
}
// try to increase stack amount
foundAura->ModStackAmount(1);
return foundAura;
}
}
return NULL;
}
void Unit::_AddAura(UnitAura* aura, Unit* caster)
{
ASSERT(!m_cleanupDone);
m_ownedAuras.insert(AuraMap::value_type(aura->GetId(), aura));
_RemoveNoStackAurasDueToAura(aura);
if (aura->IsRemoved())
return;
aura->SetIsSingleTarget(caster && aura->GetSpellInfo()->IsSingleTarget());
if (aura->IsSingleTarget())
{
ASSERT((IsInWorld() && !IsDuringRemoveFromWorld()) || (aura->GetCasterGUID() == GetGUID()));
// register single target aura
caster->GetSingleCastAuras().push_back(aura);
// remove other single target auras
Unit::AuraList& scAuras = caster->GetSingleCastAuras();
for (Unit::AuraList::iterator itr = scAuras.begin(); itr != scAuras.end();)
{
if ((*itr) != aura &&
(*itr)->GetSpellInfo()->IsSingleTargetWith(aura->GetSpellInfo()))
{
(*itr)->Remove();
itr = scAuras.begin();
}
else
++itr;
}
}
}
// creates aura application instance and registers it in lists
// aura application effects are handled separately to prevent aura list corruption
AuraApplication * Unit::_CreateAuraApplication(Aura* aura, uint8 effMask)
{
// can't apply aura on unit which is going to be deleted - to not create a memory leak
ASSERT(!m_cleanupDone);
// aura musn't be removed
ASSERT(!aura->IsRemoved());
// aura mustn't be already applied on target
ASSERT (!aura->IsAppliedOnTarget(GetGUID()) && "Unit::_CreateAuraApplication: aura musn't be applied on target");
SpellInfo const* aurSpellInfo = aura->GetSpellInfo();
uint32 aurId = aurSpellInfo->Id;
// ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
if (!isAlive() && !aurSpellInfo->IsDeathPersistent() &&
(GetTypeId() != TYPEID_PLAYER || !ToPlayer()->GetSession()->PlayerLoading()))
return NULL;
Unit* caster = aura->GetCaster();
AuraApplication * aurApp = new AuraApplication(this, caster, aura, effMask);
m_appliedAuras.insert(AuraApplicationMap::value_type(aurId, aurApp));
if (aurSpellInfo->AuraInterruptFlags)
{
m_interruptableAuras.push_back(aurApp);
AddInterruptMask(aurSpellInfo->AuraInterruptFlags);
}
if (AuraStateType aState = aura->GetSpellInfo()->GetAuraState())
m_auraStateAuras.insert(AuraStateAurasMap::value_type(aState, aurApp));
aura->_ApplyForTarget(this, caster, aurApp);
return aurApp;
}
void Unit::_ApplyAuraEffect(Aura* aura, uint8 effIndex)
{
ASSERT(aura);
ASSERT(aura->HasEffect(effIndex));
AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID());
ASSERT(aurApp);
if (!aurApp->GetEffectMask())
_ApplyAura(aurApp, 1<<effIndex);
else
aurApp->_HandleEffect(effIndex, true);
}
// handles effects of aura application
// should be done after registering aura in lists
void Unit::_ApplyAura(AuraApplication * aurApp, uint8 effMask)
{
Aura* aura = aurApp->GetBase();
_RemoveNoStackAurasDueToAura(aura);
if (aurApp->GetRemoveMode())
return;
// Update target aura state flag
if (AuraStateType aState = aura->GetSpellInfo()->GetAuraState())
ModifyAuraState(aState, true);
if (aurApp->GetRemoveMode())
return;
// Sitdown on apply aura req seated
if (aura->GetSpellInfo()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED && !IsSitState())
SetStandState(UNIT_STAND_STATE_SIT);
Unit* caster = aura->GetCaster();
if (aurApp->GetRemoveMode())
return;
aura->HandleAuraSpecificMods(aurApp, caster, true, false);
// apply effects of the aura
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (effMask & 1<<i && (!aurApp->GetRemoveMode()))
aurApp->_HandleEffect(i, true);
}
}
// removes aura application from lists and unapplies effects
void Unit::_UnapplyAura(AuraApplicationMap::iterator &i, AuraRemoveMode removeMode)
{
AuraApplication * aurApp = i->second;
ASSERT(aurApp);
ASSERT(!aurApp->GetRemoveMode());
ASSERT(aurApp->GetTarget() == this);
aurApp->SetRemoveMode(removeMode);
Aura* aura = aurApp->GetBase();
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Aura %u now is remove mode %d", aura->GetId(), removeMode);
// dead loop is killing the server probably
ASSERT(m_removedAurasCount < 0xFFFFFFFF);
++m_removedAurasCount;
Unit* caster = aura->GetCaster();
// Remove all pointers from lists here to prevent possible pointer invalidation on spellcast/auraapply/auraremove
m_appliedAuras.erase(i);
if (aura->GetSpellInfo()->AuraInterruptFlags)
{
m_interruptableAuras.remove(aurApp);
UpdateInterruptMask();
}
bool auraStateFound = false;
AuraStateType auraState = aura->GetSpellInfo()->GetAuraState();
if (auraState)
{
bool canBreak = false;
// Get mask of all aurastates from remaining auras
for (AuraStateAurasMap::iterator itr = m_auraStateAuras.lower_bound(auraState); itr != m_auraStateAuras.upper_bound(auraState) && !(auraStateFound && canBreak);)
{
if (itr->second == aurApp)
{
m_auraStateAuras.erase(itr);
itr = m_auraStateAuras.lower_bound(auraState);
canBreak = true;
continue;
}
auraStateFound = true;
++itr;
}
}
aurApp->_Remove();
aura->_UnapplyForTarget(this, caster, aurApp);
// remove effects of the spell - needs to be done after removing aura from lists
for (uint8 itr = 0; itr < MAX_SPELL_EFFECTS; ++itr)
{
if (aurApp->HasEffect(itr))
aurApp->_HandleEffect(itr, false);
}
// all effect mustn't be applied
ASSERT(!aurApp->GetEffectMask());
// Remove totem at next update if totem loses its aura
if (aurApp->GetRemoveMode() == AURA_REMOVE_BY_EXPIRE && GetTypeId() == TYPEID_UNIT && ToCreature()->isTotem()&& ToTotem()->GetSummonerGUID() == aura->GetCasterGUID())
{
if (ToTotem()->GetSpell() == aura->GetId() && ToTotem()->GetTotemType() == TOTEM_PASSIVE)
ToTotem()->setDeathState(JUST_DIED);
}
// Remove aurastates only if were not found
if (!auraStateFound)
ModifyAuraState(auraState, false);
aura->HandleAuraSpecificMods(aurApp, caster, false, false);
// only way correctly remove all auras from list
//if (removedAuras != m_removedAurasCount) new aura may be added
i = m_appliedAuras.begin();
}
void Unit::_UnapplyAura(AuraApplication * aurApp, AuraRemoveMode removeMode)
{
// aura can be removed from unit only if it's applied on it, shouldn't happen
ASSERT(aurApp->GetBase()->GetApplicationOfTarget(GetGUID()) == aurApp);
uint32 spellId = aurApp->GetBase()->GetId();
AuraApplicationMapBoundsNonConst range = m_appliedAuras.equal_range(spellId);
for (AuraApplicationMap::iterator iter = range.first; iter != range.second;)
{
if (iter->second == aurApp)
{
_UnapplyAura(iter, removeMode);
return;
}
else
++iter;
}
ASSERT(false);
}
void Unit::_RemoveNoStackAurasDueToAura(Aura* aura)
{
SpellInfo const* spellProto = aura->GetSpellInfo();
// passive spell special case (only non stackable with ranks)
if (spellProto->IsPassiveStackableWithRanks())
return;
bool remove = false;
for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i)
{
if (remove)
{
remove = false;
i = m_appliedAuras.begin();
}
if (aura->CanStackWith(i->second->GetBase()))
continue;
RemoveAura(i, AURA_REMOVE_BY_DEFAULT);
if (i == m_appliedAuras.end())
break;
remove = true;
}
}
void Unit::_RegisterAuraEffect(AuraEffect* aurEff, bool apply)
{
if (apply)
m_modAuras[aurEff->GetAuraType()].push_back(aurEff);
else
m_modAuras[aurEff->GetAuraType()].remove(aurEff);
}
// All aura base removes should go threw this function!
void Unit::RemoveOwnedAura(AuraMap::iterator &i, AuraRemoveMode removeMode)
{
Aura* aura = i->second;
ASSERT(!aura->IsRemoved());
// if unit currently update aura list then make safe update iterator shift to next
if (m_auraUpdateIterator == i)
++m_auraUpdateIterator;
m_ownedAuras.erase(i);
m_removedAuras.push_back(aura);
// Unregister single target aura
if (aura->IsSingleTarget())
aura->UnregisterSingleTarget();
aura->_Remove(removeMode);
i = m_ownedAuras.begin();
}
void Unit::RemoveOwnedAura(uint32 spellId, uint64 casterGUID, uint8 reqEffMask, AuraRemoveMode removeMode)
{
for (AuraMap::iterator itr = m_ownedAuras.lower_bound(spellId); itr != m_ownedAuras.upper_bound(spellId);)
if (((itr->second->GetEffectMask() & reqEffMask) == reqEffMask) && (!casterGUID || itr->second->GetCasterGUID() == casterGUID))
{
RemoveOwnedAura(itr, removeMode);
itr = m_ownedAuras.lower_bound(spellId);
}
else
++itr;
}
void Unit::RemoveOwnedAura(Aura* aura, AuraRemoveMode removeMode)
{
if (aura->IsRemoved())
return;
ASSERT(aura->GetOwner() == this);
uint32 spellId = aura->GetId();
AuraMapBoundsNonConst range = m_ownedAuras.equal_range(spellId);
for (AuraMap::iterator itr = range.first; itr != range.second; ++itr)
{
if (itr->second == aura)
{
RemoveOwnedAura(itr, removeMode);
return;
}
}
ASSERT(false);
}
Aura* Unit::GetOwnedAura(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, Aura* except) const
{
AuraMapBounds range = m_ownedAuras.equal_range(spellId);
for (AuraMap::const_iterator itr = range.first; itr != range.second; ++itr)
{
if (((itr->second->GetEffectMask() & reqEffMask) == reqEffMask)
&& (!casterGUID || itr->second->GetCasterGUID() == casterGUID)
&& (!itemCasterGUID || itr->second->GetCastItemGUID() == itemCasterGUID)
&& (!except || except != itr->second))
{
return itr->second;
}
}
return NULL;
}
void Unit::RemoveAura(AuraApplicationMap::iterator &i, AuraRemoveMode mode)
{
AuraApplication * aurApp = i->second;
// Do not remove aura which is already being removed
if (aurApp->GetRemoveMode())
return;
Aura* aura = aurApp->GetBase();
_UnapplyAura(i, mode);
// Remove aura - for Area and Target auras
if (aura->GetOwner() == this)
aura->Remove(mode);
}
void Unit::RemoveAura(uint32 spellId, uint64 caster, uint8 reqEffMask, AuraRemoveMode removeMode)
{
AuraApplicationMapBoundsNonConst range = m_appliedAuras.equal_range(spellId);
for (AuraApplicationMap::iterator iter = range.first; iter != range.second;)
{
Aura const* aura = iter->second->GetBase();
if (((aura->GetEffectMask() & reqEffMask) == reqEffMask)
&& (!caster || aura->GetCasterGUID() == caster))
{
RemoveAura(iter, removeMode);
return;
}
else
++iter;
}
}
void Unit::RemoveAura(AuraApplication * aurApp, AuraRemoveMode mode)
{
// we've special situation here, RemoveAura called while during aura removal
// this kind of call is needed only when aura effect removal handler
// or event triggered by it expects to remove
// not yet removed effects of an aura
if (aurApp->GetRemoveMode())
{
// remove remaining effects of an aura
for (uint8 itr = 0; itr < MAX_SPELL_EFFECTS; ++itr)
{
if (aurApp->HasEffect(itr))
aurApp->_HandleEffect(itr, false);
}
return;
}
// no need to remove
if (aurApp->GetBase()->GetApplicationOfTarget(GetGUID()) != aurApp || aurApp->GetBase()->IsRemoved())
return;
uint32 spellId = aurApp->GetBase()->GetId();
AuraApplicationMapBoundsNonConst range = m_appliedAuras.equal_range(spellId);
for (AuraApplicationMap::iterator iter = range.first; iter != range.second;)
{
if (aurApp == iter->second)
{
RemoveAura(iter, mode);
return;
}
else
++iter;
}
}
void Unit::RemoveAura(Aura* aura, AuraRemoveMode mode)
{
if (aura->IsRemoved())
return;
if (AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID()))
RemoveAura(aurApp, mode);
}
void Unit::RemoveAurasDueToSpell(uint32 spellId, uint64 casterGUID, uint8 reqEffMask, AuraRemoveMode removeMode)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
{
Aura const* aura = iter->second->GetBase();
if (((aura->GetEffectMask() & reqEffMask) == reqEffMask)
&& (!casterGUID || aura->GetCasterGUID() == casterGUID))
{
RemoveAura(iter, removeMode);
iter = m_appliedAuras.lower_bound(spellId);
}
else
++iter;
}
}
void Unit::RemoveAuraFromStack(uint32 spellId, uint64 casterGUID, AuraRemoveMode removeMode)
{
AuraMapBoundsNonConst range = m_ownedAuras.equal_range(spellId);
for (AuraMap::iterator iter = range.first; iter != range.second;)
{
Aura* aura = iter->second;
if ((aura->GetType() == UNIT_AURA_TYPE)
&& (!casterGUID || aura->GetCasterGUID() == casterGUID))
{
aura->ModStackAmount(-1, removeMode);
return;
}
else
++iter;
}
}
void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint32 dispellerSpellId, uint64 casterGUID, Unit* dispeller, uint8 chargesRemoved/*= 1*/)
{
AuraMapBoundsNonConst range = m_ownedAuras.equal_range(spellId);
for (AuraMap::iterator iter = range.first; iter != range.second;)
{
Aura* aura = iter->second;
if (aura->GetCasterGUID() == casterGUID)
{
DispelInfo dispelInfo(dispeller, dispellerSpellId, chargesRemoved);
// Call OnDispel hook on AuraScript
aura->CallScriptDispel(&dispelInfo);
if (aura->GetSpellInfo()->AttributesEx7 & SPELL_ATTR7_DISPEL_CHARGES)
aura->ModCharges(-dispelInfo.GetRemovedCharges(), AURA_REMOVE_BY_ENEMY_SPELL);
else
aura->ModStackAmount(-dispelInfo.GetRemovedCharges(), AURA_REMOVE_BY_ENEMY_SPELL);
// Call AfterDispel hook on AuraScript
aura->CallScriptAfterDispel(&dispelInfo);
return;
}
else
++iter;
}
}
void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit* stealer)
{
AuraMapBoundsNonConst range = m_ownedAuras.equal_range(spellId);
for (AuraMap::iterator iter = range.first; iter != range.second;)
{
Aura* aura = iter->second;
if (aura->GetCasterGUID() == casterGUID)
{
int32 damage[MAX_SPELL_EFFECTS];
int32 baseDamage[MAX_SPELL_EFFECTS];
uint8 effMask = 0;
uint8 recalculateMask = 0;
Unit* caster = aura->GetCaster();
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (aura->GetEffect(i))
{
baseDamage[i] = aura->GetEffect(i)->GetBaseAmount();
damage[i] = aura->GetEffect(i)->GetAmount();
effMask |= (1<<i);
if (aura->GetEffect(i)->CanBeRecalculated())
recalculateMask |= (1<<i);
}
else
{
baseDamage[i] = 0;
damage[i] = 0;
}
}
bool stealCharge = aura->GetSpellInfo()->AttributesEx7 & SPELL_ATTR7_DISPEL_CHARGES;
// Cast duration to unsigned to prevent permanent aura's such as Righteous Fury being permanently added to caster
uint32 dur = std::min(2u * MINUTE * IN_MILLISECONDS, uint32(aura->GetDuration()));
if (Aura* oldAura = stealer->GetAura(aura->GetId(), aura->GetCasterGUID()))
{
if (stealCharge)
oldAura->ModCharges(1);
else
oldAura->ModStackAmount(1);
oldAura->SetDuration(int32(dur));
}
else
{
// single target state must be removed before aura creation to preserve existing single target aura
if (aura->IsSingleTarget())
aura->UnregisterSingleTarget();
if (Aura* newAura = Aura::TryRefreshStackOrCreate(aura->GetSpellInfo(), effMask, stealer, NULL, &baseDamage[0], NULL, aura->GetCasterGUID()))
{
// created aura must not be single target aura,, so stealer won't loose it on recast
if (newAura->IsSingleTarget())
{
newAura->UnregisterSingleTarget();
// bring back single target aura status to the old aura
aura->SetIsSingleTarget(true);
caster->GetSingleCastAuras().push_back(aura);
}
// FIXME: using aura->GetMaxDuration() maybe not blizzlike but it fixes stealing of spells like Innervate
newAura->SetLoadedState(aura->GetMaxDuration(), int32(dur), stealCharge ? 1 : aura->GetCharges(), 1, recalculateMask, &damage[0]);
newAura->ApplyForTargets();
}
}
if (stealCharge)
aura->ModCharges(-1, AURA_REMOVE_BY_ENEMY_SPELL);
else
aura->ModStackAmount(-1, AURA_REMOVE_BY_ENEMY_SPELL);
return;
}
else
++iter;
}
}
void Unit::RemoveAurasDueToItemSpell(uint32 spellId, uint64 castItemGuid)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);)
{
if (iter->second->GetBase()->GetCastItemGUID() == castItemGuid)
{
RemoveAura(iter);
iter = m_appliedAuras.lower_bound(spellId);
}
else
++iter;
}
}
void Unit::RemoveAurasByType(AuraType auraType, uint64 casterGUID, Aura* except, bool negative, bool positive)
{
for (AuraEffectList::iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end();)
{
Aura* aura = (*iter)->GetBase();
AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID());
++iter;
if (aura != except && (!casterGUID || aura->GetCasterGUID() == casterGUID)
&& ((negative && !aurApp->IsPositive()) || (positive && aurApp->IsPositive())))
{
uint32 removedAuras = m_removedAurasCount;
RemoveAura(aurApp);
if (m_removedAurasCount > removedAuras + 1)
iter = m_modAuras[auraType].begin();
}
}
}
void Unit::RemoveAurasWithAttribute(uint32 flags)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
SpellInfo const* spell = iter->second->GetBase()->GetSpellInfo();
if (spell->Attributes & flags)
RemoveAura(iter);
else
++iter;
}
}
void Unit::RemoveNotOwnSingleTargetAuras(uint32 newPhase)
{
// single target auras from other casters
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
AuraApplication const* aurApp = iter->second;
Aura const* aura = aurApp->GetBase();
if (aura->GetCasterGUID() != GetGUID() && aura->GetSpellInfo()->IsSingleTarget())
{
if (!newPhase)
RemoveAura(iter);
else
{
Unit* caster = aura->GetCaster();
if (!caster || !caster->InSamePhase(newPhase))
RemoveAura(iter);
else
++iter;
}
}
else
++iter;
}
// single target auras at other targets
AuraList& scAuras = GetSingleCastAuras();
for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end();)
{
Aura* aura = *iter;
if (aura->GetUnitOwner() != this && !aura->GetUnitOwner()->InSamePhase(newPhase))
{
aura->Remove();
iter = scAuras.begin();
}
else
++iter;
}
}
void Unit::RemoveAurasWithInterruptFlags(uint32 flag, uint32 except)
{
if (!(m_interruptMask & flag))
return;
// interrupt auras
for (AuraApplicationList::iterator iter = m_interruptableAuras.begin(); iter != m_interruptableAuras.end();)
{
Aura* aura = (*iter)->GetBase();
++iter;
if ((aura->GetSpellInfo()->AuraInterruptFlags & flag) && (!except || aura->GetId() != except))
{
uint32 removedAuras = m_removedAurasCount;
RemoveAura(aura);
if (m_removedAurasCount > removedAuras + 1)
iter = m_interruptableAuras.begin();
}
}
// interrupt channeled spell
if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL])
if (spell->getState() == SPELL_STATE_CASTING
&& (spell->m_spellInfo->ChannelInterruptFlags & flag)
&& spell->m_spellInfo->Id != except)
InterruptNonMeleeSpells(false);
UpdateInterruptMask();
}
void Unit::RemoveAurasWithFamily(SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
Aura const* aura = iter->second->GetBase();
if (!casterGUID || aura->GetCasterGUID() == casterGUID)
{
SpellInfo const* spell = aura->GetSpellInfo();
if (spell->SpellFamilyName == uint32(family) && spell->SpellFamilyFlags.HasFlag(familyFlag1, familyFlag2, familyFlag3))
{
RemoveAura(iter);
continue;
}
}
++iter;
}
}
void Unit::RemoveMovementImpairingAuras()
{
RemoveAurasWithMechanic((1<<MECHANIC_SNARE)|(1<<MECHANIC_ROOT));
}
void Unit::RemoveAurasWithMechanic(uint32 mechanic_mask, AuraRemoveMode removemode, uint32 except)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
Aura const* aura = iter->second->GetBase();
if (!except || aura->GetId() != except)
{
if (aura->GetSpellInfo()->GetAllEffectsMechanicMask() & mechanic_mask)
{
RemoveAura(iter, removemode);
continue;
}
}
++iter;
}
}
void Unit::RemoveAreaAurasDueToLeaveWorld()
{
// make sure that all area auras not applied on self are removed - prevent access to deleted pointer later
for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
{
Aura* aura = iter->second;
++iter;
Aura::ApplicationMap const& appMap = aura->GetApplicationMap();
for (Aura::ApplicationMap::const_iterator itr = appMap.begin(); itr!= appMap.end();)
{
AuraApplication * aurApp = itr->second;
++itr;
Unit* target = aurApp->GetTarget();
if (target == this)
continue;
target->RemoveAura(aurApp);
// things linked on aura remove may apply new area aura - so start from the beginning
iter = m_ownedAuras.begin();
}
}
// remove area auras owned by others
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
if (iter->second->GetBase()->GetOwner() != this)
{
RemoveAura(iter);
}
else
++iter;
}
}
void Unit::RemoveAllAuras()
{
// this may be a dead loop if some events on aura remove will continiously apply aura on remove
// we want to have all auras removed, so use your brain when linking events
while (!m_appliedAuras.empty() || !m_ownedAuras.empty())
{
AuraApplicationMap::iterator aurAppIter;
for (aurAppIter = m_appliedAuras.begin(); aurAppIter != m_appliedAuras.end();)
_UnapplyAura(aurAppIter, AURA_REMOVE_BY_DEFAULT);
AuraMap::iterator aurIter;
for (aurIter = m_ownedAuras.begin(); aurIter != m_ownedAuras.end();)
RemoveOwnedAura(aurIter);
}
}
void Unit::RemoveArenaAuras()
{
// in join, remove positive buffs, on end, remove negative
// used to remove positive visible auras in arenas
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
AuraApplication const* aurApp = iter->second;
Aura const* aura = aurApp->GetBase();
if (!(aura->GetSpellInfo()->AttributesEx4 & SPELL_ATTR4_UNK21) // don't remove stances, shadowform, pally/hunter auras
&& !aura->IsPassive() // don't remove passive auras
&& (aurApp->IsPositive() || !(aura->GetSpellInfo()->AttributesEx3 & SPELL_ATTR3_DEATH_PERSISTENT))) // not negative death persistent auras
RemoveAura(iter);
else
++iter;
}
}
void Unit::RemoveAllAurasOnDeath()
{
// used just after dieing to remove all visible auras
// and disable the mods for the passive ones
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
Aura const* aura = iter->second->GetBase();
if (!aura->IsPassive() && !aura->IsDeathPersistent())
_UnapplyAura(iter, AURA_REMOVE_BY_DEATH);
else
++iter;
}
for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
{
Aura* aura = iter->second;
if (!aura->IsPassive() && !aura->IsDeathPersistent())
RemoveOwnedAura(iter, AURA_REMOVE_BY_DEATH);
else
++iter;
}
}
void Unit::RemoveAllAurasRequiringDeadTarget()
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
Aura const* aura = iter->second->GetBase();
if (!aura->IsPassive() && aura->GetSpellInfo()->IsRequiringDeadTarget())
_UnapplyAura(iter, AURA_REMOVE_BY_DEFAULT);
else
++iter;
}
for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
{
Aura* aura = iter->second;
if (!aura->IsPassive() && aura->GetSpellInfo()->IsRequiringDeadTarget())
RemoveOwnedAura(iter, AURA_REMOVE_BY_DEFAULT);
else
++iter;
}
}
void Unit::RemoveAllAurasExceptType(AuraType type)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();)
{
Aura const* aura = iter->second->GetBase();
if (!aura->GetSpellInfo()->HasAura(type))
_UnapplyAura(iter, AURA_REMOVE_BY_DEFAULT);
else
++iter;
}
for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
{
Aura* aura = iter->second;
if (!aura->GetSpellInfo()->HasAura(type))
RemoveOwnedAura(iter, AURA_REMOVE_BY_DEFAULT);
else
++iter;
}
}
void Unit::DelayOwnedAuras(uint32 spellId, uint64 caster, int32 delaytime)
{
AuraMapBoundsNonConst range = m_ownedAuras.equal_range(spellId);
for (; range.first != range.second; ++range.first)
{
Aura* aura = range.first->second;
if (!caster || aura->GetCasterGUID() == caster)
{
if (aura->GetDuration() < delaytime)
aura->SetDuration(0);
else
aura->SetDuration(aura->GetDuration() - delaytime);
// update for out of range group members (on 1 slot use)
aura->SetNeedClientUpdateForTargets();
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Aura %u partially interrupted on unit %u, new duration: %u ms", aura->GetId(), GetGUIDLow(), aura->GetDuration());
}
}
}
void Unit::_RemoveAllAuraStatMods()
{
for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i)
(*i).second->GetBase()->HandleAllEffects(i->second, AURA_EFFECT_HANDLE_STAT, false);
}
void Unit::_ApplyAllAuraStatMods()
{
for (AuraApplicationMap::iterator i = m_appliedAuras.begin(); i != m_appliedAuras.end(); ++i)
(*i).second->GetBase()->HandleAllEffects(i->second, AURA_EFFECT_HANDLE_STAT, true);
}
AuraEffect* Unit::GetAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster) const
{
AuraApplicationMapBounds range = m_appliedAuras.equal_range(spellId);
for (AuraApplicationMap::const_iterator itr = range.first; itr != range.second; ++itr)
{
if (itr->second->HasEffect(effIndex)
&& (!caster || itr->second->GetBase()->GetCasterGUID() == caster))
{
return itr->second->GetBase()->GetEffect(effIndex);
}
}
return NULL;
}
AuraEffect* Unit::GetAuraEffectOfRankedSpell(uint32 spellId, uint8 effIndex, uint64 caster) const
{
uint32 rankSpell = sSpellMgr->GetFirstSpellInChain(spellId);
while (rankSpell)
{
if (AuraEffect* aurEff = GetAuraEffect(rankSpell, effIndex, caster))
return aurEff;
rankSpell = sSpellMgr->GetNextSpellInChain(rankSpell);
}
return NULL;
}
AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames name, uint32 iconId, uint8 effIndex) const
{
AuraEffectList const& auras = GetAuraEffectsByType(type);
for (Unit::AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
{
if (effIndex != (*itr)->GetEffIndex())
continue;
SpellInfo const* spell = (*itr)->GetSpellInfo();
if (spell->SpellIconID == iconId && spell->SpellFamilyName == uint32(name) && !spell->SpellFamilyFlags)
return *itr;
}
return NULL;
}
AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID)
{
AuraEffectList const& auras = GetAuraEffectsByType(type);
for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
SpellInfo const* spell = (*i)->GetSpellInfo();
if (spell->SpellFamilyName == uint32(family) && spell->SpellFamilyFlags.HasFlag(familyFlag1, familyFlag2, familyFlag3))
{
if (casterGUID && (*i)->GetCasterGUID() != casterGUID)
continue;
return (*i);
}
}
return NULL;
}
AuraApplication * Unit::GetAuraApplication(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, AuraApplication * except) const
{
AuraApplicationMapBounds range = m_appliedAuras.equal_range(spellId);
for (; range.first != range.second; ++range.first)
{
AuraApplication* app = range.first->second;
Aura const* aura = app->GetBase();
if (((aura->GetEffectMask() & reqEffMask) == reqEffMask)
&& (!casterGUID || aura->GetCasterGUID() == casterGUID)
&& (!itemCasterGUID || aura->GetCastItemGUID() == itemCasterGUID)
&& (!except || except != app))
{
return app;
}
}
return NULL;
}
Aura* Unit::GetAura(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask) const
{
AuraApplication * aurApp = GetAuraApplication(spellId, casterGUID, itemCasterGUID, reqEffMask);
return aurApp ? aurApp->GetBase() : NULL;
}
AuraApplication * Unit::GetAuraApplicationOfRankedSpell(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, AuraApplication* except) const
{
uint32 rankSpell = sSpellMgr->GetFirstSpellInChain(spellId);
while (rankSpell)
{
if (AuraApplication * aurApp = GetAuraApplication(rankSpell, casterGUID, itemCasterGUID, reqEffMask, except))
return aurApp;
rankSpell = sSpellMgr->GetNextSpellInChain(rankSpell);
}
return NULL;
}
Aura* Unit::GetAuraOfRankedSpell(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask) const
{
AuraApplication * aurApp = GetAuraApplicationOfRankedSpell(spellId, casterGUID, itemCasterGUID, reqEffMask);
return aurApp ? aurApp->GetBase() : NULL;
}
void Unit::GetDispellableAuraList(Unit* caster, uint32 dispelMask, DispelChargesList& dispelList)
{
// we should not be able to dispel diseases if the target is affected by unholy blight
if (dispelMask & (1 << DISPEL_DISEASE) && HasAura(50536))
dispelMask &= ~(1 << DISPEL_DISEASE);
AuraMap const& auras = GetOwnedAuras();
for (AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
{
Aura* aura = itr->second;
AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID());
if (!aurApp)
continue;
// don't try to remove passive auras
if (aura->IsPassive())
continue;
if (aura->GetSpellInfo()->GetDispelMask() & dispelMask)
{
if (aura->GetSpellInfo()->Dispel == DISPEL_MAGIC)
{
// do not remove positive auras if friendly target
// negative auras if non-friendly target
if (aurApp->IsPositive() == IsFriendlyTo(caster))
continue;
}
// The charges / stack amounts don't count towards the total number of auras that can be dispelled.
// Ie: A dispel on a target with 5 stacks of Winters Chill and a Polymorph has 1 / (1 + 1) -> 50% chance to dispell
// Polymorph instead of 1 / (5 + 1) -> 16%.
bool dispel_charges = aura->GetSpellInfo()->AttributesEx7 & SPELL_ATTR7_DISPEL_CHARGES;
uint8 charges = dispel_charges ? aura->GetCharges() : aura->GetStackAmount();
if (charges > 0)
dispelList.push_back(std::make_pair(aura, charges));
}
}
}
bool Unit::HasAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster) const
{
AuraApplicationMapBounds range = m_appliedAuras.equal_range(spellId);
for (AuraApplicationMap::const_iterator itr = range.first; itr != range.second; ++itr)
{
if (itr->second->HasEffect(effIndex)
&& (!caster || itr->second->GetBase()->GetCasterGUID() == caster))
{
return true;
}
}
return false;
}
uint32 Unit::GetAuraCount(uint32 spellId) const
{
uint32 count = 0;
AuraApplicationMapBounds range = m_appliedAuras.equal_range(spellId);
for (AuraApplicationMap::const_iterator itr = range.first; itr != range.second; ++itr)
{
if (itr->second->GetBase()->GetStackAmount() == 0)
++count;
else
count += (uint32)itr->second->GetBase()->GetStackAmount();
}
return count;
}
bool Unit::HasAura(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask) const
{
if (GetAuraApplication(spellId, casterGUID, itemCasterGUID, reqEffMask))
return true;
return false;
}
bool Unit::HasAuraType(AuraType auraType) const
{
return (!m_modAuras[auraType].empty());
}
bool Unit::HasAuraTypeWithCaster(AuraType auratype, uint64 caster) const
{
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
if (caster == (*i)->GetCasterGUID())
return true;
return false;
}
bool Unit::HasAuraTypeWithMiscvalue(AuraType auratype, int32 miscvalue) const
{
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
if (miscvalue == (*i)->GetMiscValue())
return true;
return false;
}
bool Unit::HasAuraTypeWithAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const
{
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
if ((*i)->IsAffectingSpell(affectedSpell))
return true;
return false;
}
bool Unit::HasAuraTypeWithValue(AuraType auratype, int32 value) const
{
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
if (value == (*i)->GetAmount())
return true;
return false;
}
bool Unit::HasNegativeAuraWithInterruptFlag(uint32 flag, uint64 guid)
{
if (!(m_interruptMask & flag))
return false;
for (AuraApplicationList::iterator iter = m_interruptableAuras.begin(); iter != m_interruptableAuras.end(); ++iter)
{
if (!(*iter)->IsPositive() && (*iter)->GetBase()->GetSpellInfo()->AuraInterruptFlags & flag && (!guid || (*iter)->GetBase()->GetCasterGUID() == guid))
return true;
}
return false;
}
bool Unit::HasNegativeAuraWithAttribute(uint32 flag, uint64 guid)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end(); ++iter)
{
Aura const* aura = iter->second->GetBase();
if (!iter->second->IsPositive() && aura->GetSpellInfo()->Attributes & flag && (!guid || aura->GetCasterGUID() == guid))
return true;
}
return false;
}
bool Unit::HasAuraWithMechanic(uint32 mechanicMask)
{
for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end(); ++iter)
{
SpellInfo const* spellInfo = iter->second->GetBase()->GetSpellInfo();
if (spellInfo->Mechanic && (mechanicMask & (1 << spellInfo->Mechanic)))
return true;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (iter->second->HasEffect(i) && spellInfo->Effects[i].Effect && spellInfo->Effects[i].Mechanic)
if (mechanicMask & (1 << spellInfo->Effects[i].Mechanic))
return true;
}
return false;
}
AuraEffect* Unit::IsScriptOverriden(SpellInfo const* spell, int32 script) const
{
AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
if ((*i)->GetMiscValue() == script)
if ((*i)->IsAffectingSpell(spell))
return (*i);
}
return NULL;
}
uint32 Unit::GetDiseasesByCaster(uint64 casterGUID, bool remove)
{
static const AuraType diseaseAuraTypes[] =
{
SPELL_AURA_PERIODIC_DAMAGE, // Frost Fever and Blood Plague
SPELL_AURA_LINKED, // Crypt Fever and Ebon Plague
SPELL_AURA_NONE
};
uint32 diseases = 0;
for (AuraType const* itr = &diseaseAuraTypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
{
for (AuraEffectList::iterator i = m_modAuras[*itr].begin(); i != m_modAuras[*itr].end();)
{
// Get auras with disease dispel type by caster
if ((*i)->GetSpellInfo()->Dispel == DISPEL_DISEASE
&& (*i)->GetCasterGUID() == casterGUID)
{
++diseases;
if (remove)
{
RemoveAura((*i)->GetId(), (*i)->GetCasterGUID());
i = m_modAuras[*itr].begin();
continue;
}
}
++i;
}
}
return diseases;
}
uint32 Unit::GetDoTsByCaster(uint64 casterGUID) const
{
static const AuraType diseaseAuraTypes[] =
{
SPELL_AURA_PERIODIC_DAMAGE,
SPELL_AURA_PERIODIC_DAMAGE_PERCENT,
SPELL_AURA_NONE
};
uint32 dots = 0;
for (AuraType const* itr = &diseaseAuraTypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
{
Unit::AuraEffectList const& auras = GetAuraEffectsByType(*itr);
for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
// Get auras by caster
if ((*i)->GetCasterGUID() == casterGUID)
++dots;
}
}
return dots;
}
int32 Unit::GetTotalAuraModifier(AuraType auratype) const
{
std::map<SpellGroup, int32> SameEffectSpellGroup;
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
if (!sSpellMgr->AddSameEffectStackRuleSpellGroups((*i)->GetSpellInfo(), (*i)->GetAmount(), SameEffectSpellGroup))
modifier += (*i)->GetAmount();
for (std::map<SpellGroup, int32>::const_iterator itr = SameEffectSpellGroup.begin(); itr != SameEffectSpellGroup.end(); ++itr)
modifier += itr->second;
return modifier;
}
float Unit::GetTotalAuraMultiplier(AuraType auratype) const
{
float multiplier = 1.0f;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
AddPct(multiplier, (*i)->GetAmount());
return multiplier;
}
int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype)
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetAmount() > modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
if ((*i)->GetAmount() < modifier)
modifier = (*i)->GetAmount();
return modifier;
}
int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
{
std::map<SpellGroup, int32> SameEffectSpellGroup;
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
if ((*i)->GetMiscValue() & misc_mask)
if (!sSpellMgr->AddSameEffectStackRuleSpellGroups((*i)->GetSpellInfo(), (*i)->GetAmount(), SameEffectSpellGroup))
modifier += (*i)->GetAmount();
for (std::map<SpellGroup, int32>::const_iterator itr = SameEffectSpellGroup.begin(); itr != SameEffectSpellGroup.end(); ++itr)
modifier += itr->second;
return modifier;
}
float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
{
std::map<SpellGroup, int32> SameEffectSpellGroup;
float multiplier = 1.0f;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if (((*i)->GetMiscValue() & misc_mask))
{
// Check if the Aura Effect has a the Same Effect Stack Rule and if so, use the highest amount of that SpellGroup
// If the Aura Effect does not have this Stack Rule, it returns false so we can add to the multiplier as usual
if (!sSpellMgr->AddSameEffectStackRuleSpellGroups((*i)->GetSpellInfo(), (*i)->GetAmount(), SameEffectSpellGroup))
AddPct(multiplier, (*i)->GetAmount());
}
}
// Add the highest of the Same Effect Stack Rule SpellGroups to the multiplier
for (std::map<SpellGroup, int32>::const_iterator itr = SameEffectSpellGroup.begin(); itr != SameEffectSpellGroup.end(); ++itr)
AddPct(multiplier, itr->second);
return multiplier;
}
int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask, const AuraEffect* except) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if (except != (*i) && (*i)->GetMiscValue()& misc_mask && (*i)->GetAmount() > modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetMiscValue()& misc_mask && (*i)->GetAmount() < modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
{
std::map<SpellGroup, int32> SameEffectSpellGroup;
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetMiscValue() == misc_value)
if (!sSpellMgr->AddSameEffectStackRuleSpellGroups((*i)->GetSpellInfo(), (*i)->GetAmount(), SameEffectSpellGroup))
modifier += (*i)->GetAmount();
}
for (std::map<SpellGroup, int32>::const_iterator itr = SameEffectSpellGroup.begin(); itr != SameEffectSpellGroup.end(); ++itr)
modifier += itr->second;
return modifier;
}
float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
{
std::map<SpellGroup, int32> SameEffectSpellGroup;
float multiplier = 1.0f;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetMiscValue() == misc_value)
if (!sSpellMgr->AddSameEffectStackRuleSpellGroups((*i)->GetSpellInfo(), (*i)->GetAmount(), SameEffectSpellGroup))
AddPct(multiplier, (*i)->GetAmount());
}
for (std::map<SpellGroup, int32>::const_iterator itr = SameEffectSpellGroup.begin(); itr != SameEffectSpellGroup.end(); ++itr)
AddPct(multiplier, itr->second);
return multiplier;
}
int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetMiscValue() == misc_value && (*i)->GetAmount() > modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->GetMiscValue() == misc_value && (*i)->GetAmount() < modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
int32 Unit::GetTotalAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const
{
std::map<SpellGroup, int32> SameEffectSpellGroup;
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->IsAffectingSpell(affectedSpell))
if (!sSpellMgr->AddSameEffectStackRuleSpellGroups((*i)->GetSpellInfo(), (*i)->GetAmount(), SameEffectSpellGroup))
modifier += (*i)->GetAmount();
}
for (std::map<SpellGroup, int32>::const_iterator itr = SameEffectSpellGroup.begin(); itr != SameEffectSpellGroup.end(); ++itr)
modifier += itr->second;
return modifier;
}
float Unit::GetTotalAuraMultiplierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const
{
std::map<SpellGroup, int32> SameEffectSpellGroup;
float multiplier = 1.0f;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->IsAffectingSpell(affectedSpell))
if (!sSpellMgr->AddSameEffectStackRuleSpellGroups((*i)->GetSpellInfo(), (*i)->GetAmount(), SameEffectSpellGroup))
AddPct(multiplier, (*i)->GetAmount());
}
for (std::map<SpellGroup, int32>::const_iterator itr = SameEffectSpellGroup.begin(); itr != SameEffectSpellGroup.end(); ++itr)
AddPct(multiplier, itr->second);
return multiplier;
}
int32 Unit::GetMaxPositiveAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->IsAffectingSpell(affectedSpell) && (*i)->GetAmount() > modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
int32 Unit::GetMaxNegativeAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const
{
int32 modifier = 0;
AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype);
for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i)
{
if ((*i)->IsAffectingSpell(affectedSpell) && (*i)->GetAmount() < modifier)
modifier = (*i)->GetAmount();
}
return modifier;
}
void Unit::_RegisterDynObject(DynamicObject* dynObj)
{
m_dynObj.push_back(dynObj);
}
void Unit::_UnregisterDynObject(DynamicObject* dynObj)
{
m_dynObj.remove(dynObj);
}
DynamicObject* Unit::GetDynObject(uint32 spellId)
{
if (m_dynObj.empty())
return NULL;
for (DynObjectList::const_iterator i = m_dynObj.begin(); i != m_dynObj.end();++i)
{
DynamicObject* dynObj = *i;
if (dynObj->GetSpellId() == spellId)
return dynObj;
}
return NULL;
}
void Unit::RemoveDynObject(uint32 spellId)
{
if (m_dynObj.empty())
return;
for (DynObjectList::iterator i = m_dynObj.begin(); i != m_dynObj.end();)
{
DynamicObject* dynObj = *i;
if (dynObj->GetSpellId() == spellId)
{
dynObj->Remove();
i = m_dynObj.begin();
}
else
++i;
}
}
void Unit::RemoveAllDynObjects()
{
while (!m_dynObj.empty())
m_dynObj.front()->Remove();
}
GameObject* Unit::GetGameObject(uint32 spellId) const
{
for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i)
if ((*i)->GetSpellId() == spellId)
return *i;
return NULL;
}
void Unit::AddGameObject(GameObject* gameObj)
{
if (!gameObj || !gameObj->GetOwnerGUID() == 0)
return;
m_gameObj.push_back(gameObj);
gameObj->SetOwnerGUID(GetGUID());
if (GetTypeId() == TYPEID_PLAYER && gameObj->GetSpellId())
{
SpellInfo const* createBySpell = sSpellMgr->GetSpellInfo(gameObj->GetSpellId());
// Need disable spell use for owner
if (createBySpell && createBySpell->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE)
// note: item based cooldowns and cooldown spell mods with charges ignored (unknown existing cases)
ToPlayer()->AddSpellAndCategoryCooldowns(createBySpell, 0, NULL, true);
}
}
void Unit::RemoveGameObject(GameObject* gameObj, bool del)
{
if (!gameObj || gameObj->GetOwnerGUID() != GetGUID())
return;
gameObj->SetOwnerGUID(0);
for (uint8 i = 0; i < MAX_GAMEOBJECT_SLOT; ++i)
{
if (m_ObjectSlot[i] == gameObj->GetGUID())
{
m_ObjectSlot[i] = 0;
break;
}
}
// GO created by some spell
if (uint32 spellid = gameObj->GetSpellId())
{
RemoveAurasDueToSpell(spellid);
if (GetTypeId() == TYPEID_PLAYER)
{
SpellInfo const* createBySpell = sSpellMgr->GetSpellInfo(spellid);
// Need activate spell use for owner
if (createBySpell && createBySpell->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE)
// note: item based cooldowns and cooldown spell mods with charges ignored (unknown existing cases)
ToPlayer()->SendCooldownEvent(createBySpell);
}
}
m_gameObj.remove(gameObj);
if (del)
{
gameObj->SetRespawnTime(0);
gameObj->Delete();
}
}
void Unit::RemoveGameObject(uint32 spellid, bool del)
{
if (m_gameObj.empty())
return;
GameObjectList::iterator i, next;
for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
{
next = i;
if (spellid == 0 || (*i)->GetSpellId() == spellid)
{
(*i)->SetOwnerGUID(0);
if (del)
{
(*i)->SetRespawnTime(0);
(*i)->Delete();
}
next = m_gameObj.erase(i);
}
else
++next;
}
}
void Unit::RemoveAllGameObjects()
{
// remove references to unit
while (!m_gameObj.empty())
{
GameObjectList::iterator i = m_gameObj.begin();
(*i)->SetOwnerGUID(0);
(*i)->SetRespawnTime(0);
(*i)->Delete();
m_gameObj.erase(i);
}
}
void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage* log)
{
WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+4+1+4+4+1+1+4+4+1)); // we guess size
data.append(log->target->GetPackGUID());
data.append(log->attacker->GetPackGUID());
data << uint32(log->SpellID);
data << uint32(log->damage); // damage amount
int32 overkill = log->damage - log->target->GetHealth();
data << uint32(overkill > 0 ? overkill : 0); // overkill
data << uint8 (log->schoolMask); // damage school
data << uint32(log->absorb); // AbsorbedDamage
data << uint32(log->resist); // resist
data << uint8 (log->physicalLog); // if 1, then client show spell name (example: %s's ranged shot hit %s for %u school or %s suffers %u school damage from %s's spell_name
data << uint8 (log->unused); // unused
data << uint32(log->blocked); // blocked
data << uint32(log->HitInfo);
data << uint8 (0); // flag to use extend data
SendMessageToSet(&data, true);
}
void Unit::SendSpellNonMeleeDamageLog(Unit* target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
{
SpellNonMeleeDamage log(this, target, SpellID, damageSchoolMask);
log.damage = Damage - AbsorbedDamage - Resist - Blocked;
log.absorb = AbsorbedDamage;
log.resist = Resist;
log.physicalLog = PhysicalDamage;
log.blocked = Blocked;
log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6;
if (CriticalHit)
log.HitInfo |= SPELL_HIT_TYPE_CRIT;
SendSpellNonMeleeDamageLog(&log);
}
void Unit::ProcDamageAndSpell(Unit* victim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellInfo const* procSpell, SpellInfo const* procAura)
{
// Not much to do if no flags are set.
if (procAttacker)
ProcDamageAndSpellFor(false, victim, procAttacker, procExtra, attType, procSpell, amount, procAura);
// Now go on with a victim's events'n'auras
// Not much to do if no flags are set or there is no victim
if (victim && victim->isAlive() && procVictim)
victim->ProcDamageAndSpellFor(true, this, procVictim, procExtra, attType, procSpell, amount, procAura);
}
void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo* pInfo)
{
AuraEffect const* aura = pInfo->auraEff;
WorldPacket data(SMSG_PERIODICAURALOG, 30);
data.append(GetPackGUID());
data.appendPackGUID(aura->GetCasterGUID());
data << uint32(aura->GetId()); // spellId
data << uint32(1); // count
data << uint32(aura->GetAuraType()); // auraId
switch (aura->GetAuraType())
{
case SPELL_AURA_PERIODIC_DAMAGE:
case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
data << uint32(pInfo->damage); // damage
data << uint32(pInfo->overDamage); // overkill?
data << uint32(aura->GetSpellInfo()->GetSchoolMask());
data << uint32(pInfo->absorb); // absorb
data << uint32(pInfo->resist); // resist
data << uint8(pInfo->critical); // new 3.1.2 critical tick
break;
case SPELL_AURA_PERIODIC_HEAL:
case SPELL_AURA_OBS_MOD_HEALTH:
data << uint32(pInfo->damage); // damage
data << uint32(pInfo->overDamage); // overheal
data << uint32(pInfo->absorb); // absorb
data << uint8(pInfo->critical); // new 3.1.2 critical tick
break;
case SPELL_AURA_OBS_MOD_POWER:
case SPELL_AURA_PERIODIC_ENERGIZE:
data << uint32(aura->GetMiscValue()); // power type
data << uint32(pInfo->damage); // damage
break;
case SPELL_AURA_PERIODIC_MANA_LEECH:
data << uint32(aura->GetMiscValue()); // power type
data << uint32(pInfo->damage); // amount
data << float(pInfo->multiplier); // gain multiplier
break;
default:
sLog->outError(LOG_FILTER_UNITS, "Unit::SendPeriodicAuraLog: unknown aura %u", uint32(aura->GetAuraType()));
return;
}
SendMessageToSet(&data, true);
}
void Unit::SendSpellMiss(Unit* target, uint32 spellID, SpellMissInfo missInfo)
{
WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
data << uint32(spellID);
data << uint64(GetGUID());
data << uint8(0); // can be 0 or 1
data << uint32(1); // target count
// for (i = 0; i < target count; ++i)
data << uint64(target->GetGUID()); // target GUID
data << uint8(missInfo);
// end loop
SendMessageToSet(&data, true);
}
void Unit::SendSpellDamageResist(Unit* target, uint32 spellId)
{
WorldPacket data(SMSG_PROCRESIST, 8+8+4+1);
data << uint64(GetGUID());
data << uint64(target->GetGUID());
data << uint32(spellId);
data << uint8(0); // bool - log format: 0-default, 1-debug
SendMessageToSet(&data, true);
}
void Unit::SendSpellDamageImmune(Unit* target, uint32 spellId)
{
WorldPacket data(SMSG_SPELLORDAMAGE_IMMUNE, 8+8+4+1);
data << uint64(GetGUID());
data << uint64(target->GetGUID());
data << uint32(spellId);
data << uint8(0); // bool - log format: 0-default, 1-debug
SendMessageToSet(&data, true);
}
void Unit::SendAttackStateUpdate(CalcDamageInfo* damageInfo)
{
sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
uint32 count = 1;
size_t maxsize = 4+5+5+4+4+1+4+4+4+4+4+1+4+4+4+4+4*12;
WorldPacket data(SMSG_ATTACKERSTATEUPDATE, maxsize); // we guess size
data << uint32(damageInfo->HitInfo);
data.append(damageInfo->attacker->GetPackGUID());
data.append(damageInfo->target->GetPackGUID());
data << uint32(damageInfo->damage); // Full damage
int32 overkill = damageInfo->damage - damageInfo->target->GetHealth();
data << uint32(overkill < 0 ? 0 : overkill); // Overkill
data << uint8(count); // Sub damage count
for (uint32 i = 0; i < count; ++i)
{
data << uint32(damageInfo->damageSchoolMask); // School of sub damage
data << float(damageInfo->damage); // sub damage
data << uint32(damageInfo->damage); // Sub Damage
}
if (damageInfo->HitInfo & (HITINFO_FULL_ABSORB | HITINFO_PARTIAL_ABSORB))
{
for (uint32 i = 0; i < count; ++i)
data << uint32(damageInfo->absorb); // Absorb
}
if (damageInfo->HitInfo & (HITINFO_FULL_RESIST | HITINFO_PARTIAL_RESIST))
{
for (uint32 i = 0; i < count; ++i)
data << uint32(damageInfo->resist); // Resist
}
data << uint8(damageInfo->TargetState);
data << uint32(0); // Unknown attackerstate
data << uint32(0); // Melee spellid
if (damageInfo->HitInfo & HITINFO_BLOCK)
data << uint32(damageInfo->blocked_amount);
if (damageInfo->HitInfo & HITINFO_RAGE_GAIN)
data << uint32(0);
//! Probably used for debugging purposes, as it is not known to appear on retail servers
if (damageInfo->HitInfo & HITINFO_UNK1)
{
data << uint32(0);
data << float(0);
data << float(0);
data << float(0);
data << float(0);
data << float(0);
data << float(0);
data << float(0);
data << float(0);
for (uint8 i = 0; i < 2; ++i)
{
data << float(0);
data << float(0);
}
data << uint32(0);
}
SendMessageToSet(&data, true);
}
void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit* target, uint8 /*SwingType*/, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
{
CalcDamageInfo dmgInfo;
dmgInfo.HitInfo = HitInfo;
dmgInfo.attacker = this;
dmgInfo.target = target;
dmgInfo.damage = Damage - AbsorbDamage - Resist - BlockedAmount;
dmgInfo.damageSchoolMask = damageSchoolMask;
dmgInfo.absorb = AbsorbDamage;
dmgInfo.resist = Resist;
dmgInfo.TargetState = TargetState;
dmgInfo.blocked_amount = BlockedAmount;
SendAttackStateUpdate(&dmgInfo);
}
bool Unit::HandleAuraProcOnPowerAmount(Unit* victim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 /*procEx*/, uint32 cooldown)
{
// Get triggered aura spell info
SpellInfo const* auraSpellInfo = triggeredByAura->GetSpellInfo();
// Get effect index used for the proc
uint32 effIndex = triggeredByAura->GetEffIndex();
// Power amount required to proc the spell
int32 powerAmountRequired = triggeredByAura->GetAmount();
// Power type required to proc
Powers powerRequired = Powers(auraSpellInfo->Effects[triggeredByAura->GetEffIndex()].MiscValue);
// Set trigger spell id, target, custom basepoints
uint32 trigger_spell_id = auraSpellInfo->Effects[triggeredByAura->GetEffIndex()].TriggerSpell;
Unit* target = NULL;
int32 basepoints0 = 0;
Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
/* Try handle unknown trigger spells or with invalid power amount or misc value
if (sSpellMgr->GetSpellInfo(trigger_spell_id) == NULL || powerAmountRequired == NULL || powerRequired >= MAX_POWER)
{
switch (auraSpellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
break;
}
}
}*/
// All ok. Check current trigger spell
SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(trigger_spell_id);
if (triggerEntry == NULL)
{
// Not cast unknown spell
// sLog->outError("Unit::HandleAuraProcOnPowerAmount: Spell %u have 0 in EffectTriggered[%d], not handled custom case?", auraSpellInfo->Id, triggeredByAura->GetEffIndex());
return false;
}
// not allow proc extra attack spell at extra attack
if (m_extraAttacks && triggerEntry->HasEffect(SPELL_EFFECT_ADD_EXTRA_ATTACKS))
return false;
if (!powerRequired || !powerAmountRequired)
{
sLog->outError(LOG_FILTER_SPELLS_AURAS, "Unit::HandleAuraProcOnPowerAmount: Spell %u have 0 powerAmountRequired in EffectAmount[%d] or 0 powerRequired in EffectMiscValue, not handled custom case?", auraSpellInfo->Id, triggeredByAura->GetEffIndex());
return false;
}
if (GetPower(powerRequired) != powerAmountRequired)
return false;
// Custom requirements (not listed in procEx) Warning! damage dealing after this
// Custom triggered spells
switch (auraSpellInfo->SpellFamilyName)
{
case SPELLFAMILY_DRUID:
{
// Eclipse Mastery Driver Passive
if (auraSpellInfo->Id == 79577)
{
uint32 solarEclipseMarker = 67483;
uint32 lunarEclipseMarker = 67484;
switch (effIndex)
{
case 0:
{
// Do not proc if proc spell isnt starfire and starsurge
if (procSpell->Id != 2912 && procSpell->Id != 78674)
return false;
if (HasAura(solarEclipseMarker))
{
RemoveAurasDueToSpell(solarEclipseMarker);
CastSpell(this, lunarEclipseMarker, true);
}
break;
}
case 1:
{
// Do not proc if proc spell isnt wrath and starsurge
if (procSpell->Id != 5176 && procSpell->Id != 78674)
return false;
if (HasAura(lunarEclipseMarker))
{
RemoveAurasDueToSpell(lunarEclipseMarker);
CastSpell(this, solarEclipseMarker, true);
}
break;
}
}
}
break;
}
}
if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(trigger_spell_id))
return false;
// try detect target manually if not set
if (target == NULL)
target = !(procFlag & (PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS)) && triggerEntry && triggerEntry->IsPositive() ? this : victim;
if (basepoints0)
CastCustomSpell(target, trigger_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
else
CastSpell(target, trigger_spell_id, true, castItem, triggeredByAura);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(trigger_spell_id, 0, time(NULL) + cooldown);
return true;
}
//victim may be NULL
bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
{
SpellInfo const* dummySpell = triggeredByAura->GetSpellInfo();
uint32 effIndex = triggeredByAura->GetEffIndex();
int32 triggerAmount = triggeredByAura->GetAmount();
Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
uint32 triggered_spell_id = 0;
uint32 cooldown_spell_id = 0; // for random trigger, will be one of the triggered spell to avoid repeatable triggers
// otherwise, it's the triggered_spell_id by default
Unit* target = victim;
int32 basepoints0 = 0;
uint64 originalCaster = 0;
switch (dummySpell->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (dummySpell->Id)
{
// Unstable Power
case 24658:
{
if (!procSpell || procSpell->Id == 24659)
return false;
// Need remove one 24659 aura
RemoveAuraFromStack(24659);
return true;
}
// Restless Strength
case 24661:
{
// Need remove one 24662 aura
RemoveAuraFromStack(24662);
return true;
}
// Mark of Malice
case 33493:
{
// Cast finish spell at last charge
if (triggeredByAura->GetBase()->GetCharges() > 1)
return false;
target = this;
triggered_spell_id = 33494;
break;
}
// Twisted Reflection (boss spell)
case 21063:
triggered_spell_id = 21064;
break;
// Vampiric Aura (boss spell)
case 38196:
{
basepoints0 = 3 * damage; // 300%
if (basepoints0 < 0)
return false;
triggered_spell_id = 31285;
target = this;
break;
}
// Aura of Madness (Darkmoon Card: Madness trinket)
//=====================================================
// 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
// 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
// 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
// 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
// 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
// 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
// 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
// 41011 Martyr Complex: +35 stamina (All classes)
// 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
// 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
case 39446:
{
if (GetTypeId() != TYPEID_PLAYER || !isAlive())
return false;
// Select class defined buff
switch (getClass())
{
case CLASS_PALADIN: // 39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409
case CLASS_DRUID: // 39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409
triggered_spell_id = RAND(39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409);
cooldown_spell_id = 39511;
break;
case CLASS_ROGUE: // 39511, 40997, 40998, 41002, 41005, 41011
case CLASS_WARRIOR: // 39511, 40997, 40998, 41002, 41005, 41011
case CLASS_DEATH_KNIGHT:
triggered_spell_id = RAND(39511, 40997, 40998, 41002, 41005, 41011);
cooldown_spell_id = 39511;
break;
case CLASS_PRIEST: // 40999, 41002, 41005, 41009, 41011, 41406, 41409
case CLASS_SHAMAN: // 40999, 41002, 41005, 41009, 41011, 41406, 41409
case CLASS_MAGE: // 40999, 41002, 41005, 41009, 41011, 41406, 41409
case CLASS_WARLOCK: // 40999, 41002, 41005, 41009, 41011, 41406, 41409
triggered_spell_id = RAND(40999, 41002, 41005, 41009, 41011, 41406, 41409);
cooldown_spell_id = 40999;
break;
case CLASS_HUNTER: // 40997, 40999, 41002, 41005, 41009, 41011, 41406, 41409
triggered_spell_id = RAND(40997, 40999, 41002, 41005, 41009, 41011, 41406, 41409);
cooldown_spell_id = 40997;
break;
default:
return false;
}
target = this;
if (roll_chance_i(10))
ToPlayer()->Say("This is Madness!", LANG_UNIVERSAL); // TODO: It should be moved to database, shouldn't it?
break;
}
// Sunwell Exalted Caster Neck (??? neck)
// cast ??? Light's Wrath if Exalted by Aldor
// cast ??? Arcane Bolt if Exalted by Scryers
case 46569:
return false; // old unused version
// Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
// cast 45479 Light's Wrath if Exalted by Aldor
// cast 45429 Arcane Bolt if Exalted by Scryers
case 45481:
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
// Get Aldor reputation rank
if (ToPlayer()->GetReputationRank(932) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45479;
break;
}
// Get Scryers reputation rank
if (ToPlayer()->GetReputationRank(934) == REP_EXALTED)
{
// triggered at positive/self casts also, current attack target used then
if (target && IsFriendlyTo(target))
{
target = getVictim();
if (!target)
{
uint64 selected_guid = ToPlayer()->GetSelection();
target = ObjectAccessor::GetUnit(*this, selected_guid);
if (!target)
return false;
}
if (IsFriendlyTo(target))
return false;
}
triggered_spell_id = 45429;
break;
}
return false;
}
// Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
// cast 45480 Light's Strength if Exalted by Aldor
// cast 45428 Arcane Strike if Exalted by Scryers
case 45482:
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
// Get Aldor reputation rank
if (ToPlayer()->GetReputationRank(932) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45480;
break;
}
// Get Scryers reputation rank
if (ToPlayer()->GetReputationRank(934) == REP_EXALTED)
{
triggered_spell_id = 45428;
break;
}
return false;
}
// Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
// cast 45431 Arcane Insight if Exalted by Aldor
// cast 45432 Light's Ward if Exalted by Scryers
case 45483:
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
// Get Aldor reputation rank
if (ToPlayer()->GetReputationRank(932) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45432;
break;
}
// Get Scryers reputation rank
if (ToPlayer()->GetReputationRank(934) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45431;
break;
}
return false;
}
// Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
// cast 45478 Light's Salvation if Exalted by Aldor
// cast 45430 Arcane Surge if Exalted by Scryers
case 45484:
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
// Get Aldor reputation rank
if (ToPlayer()->GetReputationRank(932) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45478;
break;
}
// Get Scryers reputation rank
if (ToPlayer()->GetReputationRank(934) == REP_EXALTED)
{
triggered_spell_id = 45430;
break;
}
return false;
}
// Kill command
case 58914:
{
// Remove aura stack from pet
RemoveAuraFromStack(58914);
Unit* owner = GetOwner();
if (!owner)
return true;
// reduce the owner's aura stack
owner->RemoveAuraFromStack(34027);
return true;
}
// Vampiric Touch (generic, used by some boss)
case 52723:
case 60501:
{
triggered_spell_id = 52724;
basepoints0 = damage / 2;
target = this;
break;
}
// Shadowfiend Death (Gain mana if pet dies with Glyph of Shadowfiend)
case 57989:
{
Unit* owner = GetOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return false;
// Glyph of Shadowfiend (need cast as self cast for owner, no hidden cooldown)
owner->CastSpell(owner, 58227, true, castItem, triggeredByAura);
return true;
}
// Divine purpose
case 31871:
case 31872:
{
// Roll chane
if (!victim || !victim->isAlive() || !roll_chance_i(triggerAmount))
return false;
// Remove any stun effect on target
victim->RemoveAurasWithMechanic(1<<MECHANIC_STUN, AURA_REMOVE_BY_ENEMY_SPELL);
return true;
}
// Glyph of Scourge Strike
case 58642:
{
triggered_spell_id = 69961; // Glyph of Scourge Strike
break;
}
// Glyph of Life Tap
case 63320:
{
triggered_spell_id = 63321; // Life Tap
break;
}
// Purified Shard of the Scale - Onyxia 10 Caster Trinket
case 69755:
{
triggered_spell_id = (procFlag & PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS) ? 69733 : 69729;
break;
}
// Shiny Shard of the Scale - Onyxia 25 Caster Trinket
case 69739:
{
triggered_spell_id = (procFlag & PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS) ? 69734 : 69730;
break;
}
case 71519: // Deathbringer's Will Normal
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
std::vector<uint32> RandomSpells;
switch (getClass())
{
case CLASS_WARRIOR:
case CLASS_PALADIN:
case CLASS_DEATH_KNIGHT:
RandomSpells.push_back(71484);
RandomSpells.push_back(71491);
RandomSpells.push_back(71492);
break;
case CLASS_SHAMAN:
case CLASS_ROGUE:
RandomSpells.push_back(71486);
RandomSpells.push_back(71485);
RandomSpells.push_back(71492);
break;
case CLASS_DRUID:
RandomSpells.push_back(71484);
RandomSpells.push_back(71485);
RandomSpells.push_back(71492);
break;
case CLASS_HUNTER:
RandomSpells.push_back(71486);
RandomSpells.push_back(71491);
RandomSpells.push_back(71485);
break;
default:
return false;
}
if (RandomSpells.empty()) // shouldn't happen
return false;
uint8 rand_spell = irand(0, (RandomSpells.size() - 1));
CastSpell(target, RandomSpells[rand_spell], true, castItem, triggeredByAura, originalCaster);
for (std::vector<uint32>::iterator itr = RandomSpells.begin(); itr != RandomSpells.end(); ++itr)
{
if (!ToPlayer()->HasSpellCooldown(*itr))
ToPlayer()->AddSpellCooldown(*itr, 0, time(NULL) + cooldown);
}
break;
}
case 71562: // Deathbringer's Will Heroic
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
std::vector<uint32> RandomSpells;
switch (getClass())
{
case CLASS_WARRIOR:
case CLASS_PALADIN:
case CLASS_DEATH_KNIGHT:
RandomSpells.push_back(71561);
RandomSpells.push_back(71559);
RandomSpells.push_back(71560);
break;
case CLASS_SHAMAN:
case CLASS_ROGUE:
RandomSpells.push_back(71558);
RandomSpells.push_back(71556);
RandomSpells.push_back(71560);
break;
case CLASS_DRUID:
RandomSpells.push_back(71561);
RandomSpells.push_back(71556);
RandomSpells.push_back(71560);
break;
case CLASS_HUNTER:
RandomSpells.push_back(71558);
RandomSpells.push_back(71559);
RandomSpells.push_back(71556);
break;
default:
return false;
}
if (RandomSpells.empty()) // shouldn't happen
return false;
uint8 rand_spell = irand(0, (RandomSpells.size() - 1));
CastSpell(target, RandomSpells[rand_spell], true, castItem, triggeredByAura, originalCaster);
for (std::vector<uint32>::iterator itr = RandomSpells.begin(); itr != RandomSpells.end(); ++itr)
{
if (!ToPlayer()->HasSpellCooldown(*itr))
ToPlayer()->AddSpellCooldown(*itr, 0, time(NULL) + cooldown);
}
break;
}
case 65032: // Boom aura (321 Boombot)
{
if (victim->GetEntry() != 33343) // Scrapbot
return false;
InstanceScript* instance = GetInstanceScript();
if (!instance)
return false;
instance->DoCastSpellOnPlayers(65037); // Achievement criteria marker
break;
}
case 47020: // Enter vehicle XT-002 (Scrapbot)
{
if (GetTypeId() != TYPEID_UNIT)
return false;
Unit* vehicleBase = GetVehicleBase();
if (!vehicleBase)
return false;
// Todo: Check if this amount is blizzlike
vehicleBase->ModifyHealth(int32(vehicleBase->CountPctFromMaxHealth(1)));
break;
}
}
break;
}
case SPELLFAMILY_MAGE:
{
// Magic Absorption
if (dummySpell->SpellIconID == 459) // only this spell has SpellIconID == 459 and dummy aura
{
if (getPowerType() != POWER_MANA)
return false;
// mana reward
basepoints0 = CalculatePct(GetMaxPower(POWER_MANA), triggerAmount);
target = this;
triggered_spell_id = 29442;
break;
}
// Arcane Potency
if (dummySpell->SpellIconID == 2120)
{
if (!procSpell)
return false;
target = this;
switch (dummySpell->Id)
{
case 31571: triggered_spell_id = 57529; break;
case 31572: triggered_spell_id = 57531; break;
default:
sLog->outError(LOG_FILTER_UNITS, "Unit::HandleDummyAuraProc: non handled spell id: %u", dummySpell->Id);
return false;
}
break;
}
// Hot Streak & Improved Hot Streak
if (dummySpell->SpellIconID == 2999)
{
if (effIndex != 0)
return false;
AuraEffect* counter = triggeredByAura->GetBase()->GetEffect(EFFECT_1);
if (!counter)
return true;
// Count spell criticals in a row in second aura
if (procEx & PROC_EX_CRITICAL_HIT)
{
counter->SetAmount(counter->GetAmount() * 2);
if (counter->GetAmount() < 100 && dummySpell->Id != 44445) // not enough or Hot Streak spell
return true;
// Crititcal counted -> roll chance
if (roll_chance_i(triggerAmount))
CastSpell(this, 48108, true, castItem, triggeredByAura);
}
counter->SetAmount(25);
return true;
}
// Incanter's Regalia set (add trigger chance to Mana Shield)
if (dummySpell->SpellFamilyFlags[0] & 0x8000)
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
target = this;
triggered_spell_id = 37436;
break;
}
switch (dummySpell->Id)
{
// Glyph of Polymorph
case 56375:
{
if (!target)
return false;
target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE, 0, target->GetAura(32409)); // SW:D shall not be removed.
target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE_PERCENT);
target->RemoveAurasByType(SPELL_AURA_PERIODIC_LEECH);
return true;
}
// Glyph of Icy Veins
case 56374:
{
RemoveAurasByType(SPELL_AURA_HASTE_SPELLS, 0, 0, true, false);
RemoveAurasByType(SPELL_AURA_MOD_DECREASE_SPEED);
return true;
}
// Glyph of Ice Block
case 56372:
{
Player* player = ToPlayer();
if (!player)
return false;
// Remove Frost Nova cooldown
player->RemoveSpellCooldown(122, true);
break;
}
// Permafrost
case 11175:
case 12569:
case 12571:
{
if (!GetGuardianPet())
return false;
// heal amount
basepoints0 = CalculatePct(damage, triggerAmount);
target = this;
triggered_spell_id = 91394;
break;
}
}
break;
}
case SPELLFAMILY_WARRIOR:
{
switch (dummySpell->Id)
{
// Victorious
case 32216:
{
RemoveAura(dummySpell->Id);
return false;
}
}
// Retaliation
if (dummySpell->SpellFamilyFlags[1] & 0x8)
{
// check attack comes not from behind
if (!HasInArc(M_PI, victim))
return false;
triggered_spell_id = 22858;
break;
}
// Second Wind
if (dummySpell->SpellIconID == 1697)
{
// only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == victim)
return false;
// Need stun or root mechanic
if (!(procSpell->GetAllEffectsMechanicMask() & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_STUN))))
return false;
switch (dummySpell->Id)
{
case 29838: triggered_spell_id=29842; break;
case 29834: triggered_spell_id=29841; break;
case 42770: triggered_spell_id=42771; break;
default:
sLog->outError(LOG_FILTER_UNITS, "Unit::HandleDummyAuraProc: non handled spell id: %u (SW)", dummySpell->Id);
return false;
}
target = this;
break;
}
// Glyph of Sunder Armor
if (dummySpell->Id == 58387)
{
if (!victim || !victim->isAlive() || !procSpell)
return false;
target = SelectNearbyTarget(victim);
if (!target)
return false;
triggered_spell_id = 58567;
break;
}
break;
}
case SPELLFAMILY_WARLOCK:
{
// Seed of Corruption
if (dummySpell->SpellFamilyFlags[1] & 0x00000010)
{
if (procSpell && procSpell->SpellFamilyFlags[1] & 0x8000)
return false;
// if damage is more than need or target die from damage deal finish spell
if (triggeredByAura->GetAmount() <= int32(damage) || GetHealth() <= damage)
{
// remember guid before aura delete
uint64 casterGuid = triggeredByAura->GetCasterGUID();
// Remove aura (before cast for prevent infinite loop handlers)
RemoveAurasDueToSpell(triggeredByAura->GetId());
uint32 spell = sSpellMgr->GetSpellWithRank(27285, dummySpell->GetRank());
// Cast finish spell (triggeredByAura already not exist!)
if (Unit* caster = GetUnit(*this, casterGuid))
caster->CastSpell(this, spell, true, castItem);
return true; // no hidden cooldown
}
// Damage counting
triggeredByAura->SetAmount(triggeredByAura->GetAmount() - damage);
return true;
}
// Seed of Corruption (Mobs cast) - no die req
if (dummySpell->SpellFamilyFlags.IsEqual(0, 0, 0) && dummySpell->SpellIconID == 1932)
{
// if damage is more than need deal finish spell
if (triggeredByAura->GetAmount() <= int32(damage))
{
// remember guid before aura delete
uint64 casterGuid = triggeredByAura->GetCasterGUID();
// Remove aura (before cast for prevent infinite loop handlers)
RemoveAurasDueToSpell(triggeredByAura->GetId());
// Cast finish spell (triggeredByAura already not exist!)
if (Unit* caster = GetUnit(*this, casterGuid))
caster->CastSpell(this, 32865, true, castItem);
return true; // no hidden cooldown
}
// Damage counting
triggeredByAura->SetAmount(triggeredByAura->GetAmount() - damage);
return true;
}
switch (dummySpell->Id)
{
// Glyph of Shadowflame
case 63310:
{
triggered_spell_id = 63311;
break;
}
// Nightfall
case 18094:
case 18095:
// Glyph of corruption
case 56218:
{
target = this;
triggered_spell_id = 17941;
break;
}
// Soul Leech
case 30293:
case 30295:
{
basepoints0 = CalculatePct(int32(damage), triggerAmount);
target = this;
triggered_spell_id = 30294;
// Replenishment
CastSpell(this, 57669, true, castItem, triggeredByAura);
break;
}
// Shadowflame (Voidheart Raiment set bonus)
case 37377:
{
triggered_spell_id = 37379;
break;
}
// Pet Healing (Corruptor Raiment or Rift Stalker Armor)
case 37381:
{
target = GetGuardianPet();
if (!target)
return false;
// heal amount
basepoints0 = CalculatePct(int32(damage), triggerAmount);
triggered_spell_id = 37382;
break;
}
// Shadowflame Hellfire (Voidheart Raiment set bonus)
case 39437:
{
triggered_spell_id = 37378;
break;
}
// Glyph of Succubus
case 56250:
{
if (!target)
return false;
target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE, 0, target->GetAura(32409)); // SW:D shall not be removed.
target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE_PERCENT);
target->RemoveAurasByType(SPELL_AURA_PERIODIC_LEECH);
return true;
}
}
break;
}
case SPELLFAMILY_PRIEST:
{
// Vampiric Touch
if (dummySpell->SpellFamilyFlags[1] & 0x00000400)
{
if (!victim || !victim->isAlive())
return false;
if (effIndex != 0)
return false;
// victim is caster of aura
if (triggeredByAura->GetCasterGUID() != victim->GetGUID())
return false;
// Energize 1% of max. mana
victim->CastSpell(victim, 57669, true, castItem, triggeredByAura);
return true; // no hidden cooldown
}
// Body and Soul
if (dummySpell->SpellIconID == 2218)
{
// Proc only from Cure Disease on self cast
if (procSpell->Id != 528 || victim != this || !roll_chance_i(triggerAmount))
return false;
triggered_spell_id = 64136;
target = this;
break;
}
switch (dummySpell->Id)
{
// Vampiric Embrace
case 15286:
{
if (!victim || !victim->isAlive() || procSpell->SpellFamilyFlags[1] & 0x80000)
return false;
// heal amount
int32 self = CalculatePct(int32(damage), triggerAmount);
int32 team = CalculatePct(int32(damage), triggerAmount / 2);
CastCustomSpell(this, 15290, &team, &self, NULL, true, castItem, triggeredByAura);
return true; // no hidden cooldown
}
// Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
case 40438:
{
// Shadow Word: Pain
if (procSpell->SpellFamilyFlags[0] & 0x8000)
triggered_spell_id = 40441;
// Renew
else if (procSpell->SpellFamilyFlags[0] & 0x40)
triggered_spell_id = 40440;
else
return false;
target = this;
break;
}
// Phantasm
case 47569:
case 47570:
{
if (!roll_chance_i(triggerAmount))
return false;
RemoveMovementImpairingAuras();
break;
}
// Glyph of Dispel Magic
case 55677:
{
if (!target || !target->IsFriendlyTo(this))
return false;
basepoints0 = int32(target->CountPctFromMaxHealth(triggerAmount));
triggered_spell_id = 56131;
break;
}
// Oracle Healing Bonus ("Garments of the Oracle" set)
case 26169:
{
// heal amount
basepoints0 = int32(CalculatePct(damage, 10));
target = this;
triggered_spell_id = 26170;
break;
}
// Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
case 39372:
{
if (!procSpell || (procSpell->GetSchoolMask() & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW)) == 0)
return false;
// heal amount
basepoints0 = CalculatePct(int32(damage), triggerAmount);
target = this;
triggered_spell_id = 39373;
break;
}
// Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
case 28809:
{
triggered_spell_id = 28810;
break;
}
// Priest T10 Healer 2P Bonus
case 70770:
// Flash Heal
if (procSpell->SpellFamilyFlags[0] & 0x800)
{
triggered_spell_id = 70772;
SpellInfo const* blessHealing = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!blessHealing)
return false;
basepoints0 = int32(CalculatePct(damage, triggerAmount) / (blessHealing->GetMaxDuration() / blessHealing->Effects[0].Amplitude));
}
break;
}
break;
}
case SPELLFAMILY_DRUID:
{
switch (dummySpell->Id)
{
// Glyph of Innervate
case 54832:
{
if (procSpell->SpellIconID != 62)
return false;
basepoints0 = int32(CalculatePct(GetCreatePowers(POWER_MANA), triggerAmount) / 5);
triggered_spell_id = 54833;
target = this;
break;
}
// Glyph of Starfire
case 54845:
{
triggered_spell_id = 54846;
break;
}
// Glyph of Bloodletting
case 54815:
{
if (!target)
return false;
// try to find spell Rip on the target
if (AuraEffect const* AurEff = target->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00800000, 0x0, 0x0, GetGUID()))
{
// Rip's max duration, note: spells which modifies Rip's duration also counted
uint32 CountMin = AurEff->GetBase()->GetMaxDuration();
// just Rip's max duration without other spells
uint32 CountMax = AurEff->GetSpellInfo()->GetMaxDuration();
// add possible auras' and Glyph of Shred's max duration
CountMax += 3 * triggerAmount * IN_MILLISECONDS; // Glyph of Bloodletting -> +6 seconds
CountMax += HasAura(60141) ? 4 * IN_MILLISECONDS : 0; // Rip Duration/Lacerate Damage -> +4 seconds
// if min < max -> that means caster didn't cast 3 shred yet
// so set Rip's duration and max duration
if (CountMin < CountMax)
{
AurEff->GetBase()->SetDuration(AurEff->GetBase()->GetDuration() + triggerAmount * IN_MILLISECONDS);
AurEff->GetBase()->SetMaxDuration(CountMin + triggerAmount * IN_MILLISECONDS);
return true;
}
}
// if not found Rip
return false;
}
// Leader of the Pack
case 24932:
{
if (triggerAmount <= 0)
return false;
basepoints0 = int32(CountPctFromMaxHealth(triggerAmount));
target = this;
triggered_spell_id = 34299;
// Regenerate 4% mana
int32 mana = CalculatePct(GetCreateMana(), triggerAmount);
CastCustomSpell(this, 68285, &mana, NULL, NULL, true, castItem, triggeredByAura);
break;
}
// Healing Touch (Dreamwalker Raiment set)
case 28719:
{
// mana back
basepoints0 = int32(CalculatePct(procSpell->ManaCost, 30));
target = this;
triggered_spell_id = 28742;
break;
}
// Healing Touch Refund (Idol of Longevity trinket)
case 28847:
{
target = this;
triggered_spell_id = 28848;
break;
}
// Mana Restore (Malorne Raiment set / Malorne Regalia set)
case 37288:
case 37295:
{
target = this;
triggered_spell_id = 37238;
break;
}
// Druid Tier 6 Trinket
case 40442:
{
float chance;
// Starfire
if (procSpell->SpellFamilyFlags[0] & 0x4)
{
triggered_spell_id = 40445;
chance = 25.0f;
}
// Rejuvenation
else if (procSpell->SpellFamilyFlags[0] & 0x10)
{
triggered_spell_id = 40446;
chance = 25.0f;
}
// Mangle (Bear) and Mangle (Cat)
else if (procSpell->SpellFamilyFlags[1] & 0x00000440)
{
triggered_spell_id = 40452;
chance = 40.0f;
}
else
return false;
if (!roll_chance_f(chance))
return false;
target = this;
break;
}
// Maim Interrupt
case 44835:
{
// Deadly Interrupt Effect
triggered_spell_id = 32747;
break;
}
// Item - Druid T10 Balance 4P Bonus
case 70723:
{
// Wrath & Starfire
if ((procSpell->SpellFamilyFlags[0] & 0x5) && (procEx & PROC_EX_CRITICAL_HIT))
{
triggered_spell_id = 71023;
SpellInfo const* triggeredSpell = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggeredSpell)
return false;
basepoints0 = CalculatePct(int32(damage), triggerAmount) / (triggeredSpell->GetMaxDuration() / triggeredSpell->Effects[0].Amplitude);
// Add remaining ticks to damage done
basepoints0 += victim->GetRemainingPeriodicAmount(GetGUID(), triggered_spell_id, SPELL_AURA_PERIODIC_DAMAGE);
}
break;
}
// Item - Druid T10 Restoration 4P Bonus (Rejuvenation)
case 70664:
{
// Proc only from normal Rejuvenation
if (procSpell->SpellVisual[0] != 32)
return false;
Player* caster = ToPlayer();
if (!caster)
return false;
if (!caster->GetGroup() && victim == this)
return false;
CastCustomSpell(70691, SPELLVALUE_BASE_POINT0, damage, victim, true);
return true;
}
}
break;
}
case SPELLFAMILY_ROGUE:
{
switch (dummySpell->Id)
{
case 32748: // Deadly Throw Interrupt
{
// Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
if (this == victim)
return false;
triggered_spell_id = 32747;
break;
}
}
switch (dummySpell->SpellIconID)
{
case 2909: // Cut to the Chase
{
// "refresh your Slice and Dice duration to its 5 combo point maximum"
// lookup Slice and Dice
if (Aura* aur = GetAura(5171))
{
aur->SetDuration(aur->GetSpellInfo()->GetMaxDuration(), true);
return true;
}
return false;
}
case 2963: // Deadly Brew
{
triggered_spell_id = 3409;
break;
}
}
break;
}
case SPELLFAMILY_HUNTER:
{
switch (dummySpell->SpellIconID)
{
case 267: // Improved Mend Pet
{
if (!roll_chance_i(triggerAmount))
return false;
triggered_spell_id = 24406;
break;
}
case 2236: // Thrill of the Hunt
{
if (!procSpell)
return false;
basepoints0 = CalculatePct(procSpell->CalcPowerCost(this, SpellSchoolMask(procSpell->SchoolMask)), triggerAmount);
if (basepoints0 <= 0)
return false;
target = this;
triggered_spell_id = 34720;
break;
}
case 3560: // Rapid Recuperation
{
// This effect only from Rapid Killing (focus regen)
if (!(procSpell->SpellFamilyFlags[1] & 0x01000000))
return false;
target = this;
triggered_spell_id = 58883;
basepoints0 = CalculatePct(GetMaxPower(POWER_FOCUS), triggerAmount);
break;
}
}
break;
}
case SPELLFAMILY_PALADIN:
{
// Light's Beacon - Beacon of Light
if (dummySpell->Id == 53651)
{
if (!victim)
return false;
triggered_spell_id = 0;
Unit* beaconTarget = NULL;
if (GetTypeId() != TYPEID_PLAYER)
{
beaconTarget = triggeredByAura->GetBase()->GetCaster();
if (!beaconTarget || beaconTarget == this || !(beaconTarget->GetAura(53563, victim->GetGUID())))
return false;
basepoints0 = int32(damage);
triggered_spell_id = procSpell->IsRankOf(sSpellMgr->GetSpellInfo(635)) ? 53652 : 53654;
}
else
{ // Check Party/Raid Group
if (Group* group = ToPlayer()->GetGroup())
{
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
if (Player* member = itr->getSource())
{
// check if it was heal by paladin which casted this beacon of light
if (member->GetAura(53563, victim->GetGUID()))
{
// do not proc when target of beacon of light is healed
if (member == this)
return false;
beaconTarget = member;
basepoints0 = int32(damage);
triggered_spell_id = procSpell->IsRankOf(sSpellMgr->GetSpellInfo(635)) ? 53652 : 53654;
break;
}
}
}
}
}
if (triggered_spell_id && beaconTarget)
{
int32 percent = 0;
switch (procSpell->Id)
{
case 85673: // Word of Glory
case 20473: // Holy Shock
case 19750: // Flash of Light
case 82326: // Divine Light
case 85222: // Light of Dawn
percent = triggerAmount; // 50% heal from these spells
break;
case 635: // Holy Light
percent = triggerAmount * 2; // 100% heal from Holy Light
break;
}
basepoints0 = CalculatePct(damage, percent);
victim->CastCustomSpell(beaconTarget, triggered_spell_id, &basepoints0, NULL, NULL, true, 0, triggeredByAura);
return true;
}
return false;
}
// Judgements of the Wise
if (dummySpell->SpellIconID == 3017)
{
target = this;
triggered_spell_id = 31930;
break;
}
switch (dummySpell->Id)
{
// Sacred Shield
case 53601:
{
if (procFlag & PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS)
return false;
if (damage > 0)
triggered_spell_id = 58597;
// Item - Paladin T8 Holy 4P Bonus
if (Unit* caster = triggeredByAura->GetCaster())
if (AuraEffect const* aurEff = caster->GetAuraEffect(64895, 0))
cooldown = aurEff->GetAmount();
target = this;
break;
}
if (!victim)
return false;
// Holy Power (Redemption Armor set)
case 28789:
{
if (!victim)
return false;
// Set class defined buff
switch (victim->getClass())
{
case CLASS_PALADIN:
case CLASS_PRIEST:
case CLASS_SHAMAN:
case CLASS_DRUID:
triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
break;
case CLASS_MAGE:
case CLASS_WARLOCK:
triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
break;
case CLASS_HUNTER:
case CLASS_ROGUE:
triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
break;
case CLASS_WARRIOR:
triggered_spell_id = 28790; // Increases the friendly target's armor
break;
default:
return false;
}
break;
}
case 31801:
{
if (effIndex != 0) // effect 2 used by seal unleashing code
return false;
// At melee attack or Hammer of the Righteous spell damage considered as melee attack
bool stacker = !procSpell || procSpell->Id == 53595;
// spells with SPELL_DAMAGE_CLASS_MELEE excluding Judgements
bool damager = procSpell && (procSpell->EquippedItemClass != -1 || (procSpell->SpellIconID == 243 && procSpell->SpellVisual[0] == 39));
if (!stacker && !damager)
return false;
triggered_spell_id = 31803;
// On target with 5 stacks of Censure direct damage is done
if (Aura* aur = victim->GetAura(triggered_spell_id, GetGUID()))
{
if (aur->GetStackAmount() == 5)
{
if (stacker)
aur->RefreshDuration();
CastSpell(victim, 42463, true);
return true;
}
}
if (!stacker)
return false;
break;
}
// Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
case 40470:
{
if (!procSpell)
return false;
float chance;
// Flash of light/Holy light
if (procSpell->SpellFamilyFlags[0] & 0xC0000000)
{
triggered_spell_id = 40471;
chance = 15.0f;
}
// Judgement (any)
else if (procSpell->GetSpellSpecific() == SPELL_SPECIFIC_JUDGEMENT)
{
triggered_spell_id = 40472;
chance = 50.0f;
}
else
return false;
if (!roll_chance_f(chance))
return false;
break;
}
// Item - Paladin T8 Holy 2P Bonus
case 64890:
{
triggered_spell_id = 64891;
basepoints0 = triggerAmount * damage / 300;
break;
}
case 71406: // Tiny Abomination in a Jar
case 71545: // Tiny Abomination in a Jar (Heroic)
{
if (!victim || !victim->isAlive())
return false;
CastSpell(this, 71432, true, NULL, triggeredByAura);
Aura const* dummy = GetAura(71432);
if (!dummy || dummy->GetStackAmount() < (dummySpell->Id == 71406 ? 8 : 7))
return false;
RemoveAurasDueToSpell(71432);
triggered_spell_id = 71433; // default main hand attack
// roll if offhand
if (Player const* player = ToPlayer())
if (player->GetWeaponForAttack(OFF_ATTACK, true) && urand(0, 1))
triggered_spell_id = 71434;
target = victim;
break;
}
// Item - Icecrown 25 Normal Dagger Proc
case 71880:
{
switch (getPowerType())
{
case POWER_MANA:
triggered_spell_id = 71881;
break;
case POWER_RAGE:
triggered_spell_id = 71883;
break;
case POWER_ENERGY:
triggered_spell_id = 71882;
break;
case POWER_RUNIC_POWER:
triggered_spell_id = 71884;
break;
default:
return false;
}
break;
}
// Item - Icecrown 25 Heroic Dagger Proc
case 71892:
{
switch (getPowerType())
{
case POWER_MANA:
triggered_spell_id = 71888;
break;
case POWER_RAGE:
triggered_spell_id = 71886;
break;
case POWER_ENERGY:
triggered_spell_id = 71887;
break;
case POWER_RUNIC_POWER:
triggered_spell_id = 71885;
break;
default:
return false;
}
break;
}
}
break;
}
case SPELLFAMILY_SHAMAN:
{
switch (dummySpell->Id)
{
// Totemic Power (The Earthshatterer set)
case 28823:
{
if (!victim)
return false;
// Set class defined buff
switch (victim->getClass())
{
case CLASS_PALADIN:
case CLASS_PRIEST:
case CLASS_SHAMAN:
case CLASS_DRUID:
triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
break;
case CLASS_MAGE:
case CLASS_WARLOCK:
triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
break;
case CLASS_HUNTER:
case CLASS_ROGUE:
triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
break;
case CLASS_WARRIOR:
triggered_spell_id = 28827; // Increases the friendly target's armor
break;
default:
return false;
}
break;
}
// Lesser Healing Wave (Totem of Flowing Water Relic)
case 28849:
{
target = this;
triggered_spell_id = 28850;
break;
}
// Windfury Weapon (Passive) 1-8 Ranks
case 33757:
{
Player* player = ToPlayer();
if (!player || !castItem || !castItem->IsEquipped() || !victim || !victim->isAlive())
return false;
// custom cooldown processing case
if (cooldown && player->HasSpellCooldown(dummySpell->Id))
return false;
if (triggeredByAura->GetBase() && castItem->GetGUID() != triggeredByAura->GetBase()->GetCastItemGUID())
return false;
WeaponAttackType attType = WeaponAttackType(player->GetAttackBySlot(castItem->GetSlot()));
if ((attType != BASE_ATTACK && attType != OFF_ATTACK)
|| (attType == BASE_ATTACK && procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK)
|| (attType == OFF_ATTACK && procFlag & PROC_FLAG_DONE_MAINHAND_ATTACK))
return false;
// Now compute real proc chance...
uint32 chance = 20;
player->ApplySpellMod(dummySpell->Id, SPELLMOD_CHANCE_OF_SUCCESS, chance);
Item* addWeapon = player->GetWeaponForAttack(attType == BASE_ATTACK ? OFF_ATTACK : BASE_ATTACK, true);
uint32 enchant_id_add = addWeapon ? addWeapon->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)) : 0;
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id_add);
if (pEnchant && pEnchant->spellid[0] == dummySpell->Id)
chance += 14;
if (!roll_chance_i(chance))
return false;
// Now amount of extra power stored in 1 effect of Enchant spell
uint32 spellId = 8232;
SpellInfo const* windfurySpellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!windfurySpellInfo)
{
sLog->outError(LOG_FILTER_UNITS, "Unit::HandleDummyAuraProc: non-existing spell id: %u (Windfury)", spellId);
return false;
}
int32 extra_attack_power = CalculateSpellDamage(victim, windfurySpellInfo, 1);
// Value gained from additional AP
basepoints0 = int32(extra_attack_power / 14.0f * GetAttackTime(attType) / 1000);
if (procFlag & PROC_FLAG_DONE_MAINHAND_ATTACK)
triggered_spell_id = 25504;
if (procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK)
triggered_spell_id = 33750;
// apply cooldown before cast to prevent processing itself
if (cooldown)
player->AddSpellCooldown(dummySpell->Id, 0, time(NULL) + cooldown);
// Attack Twice
for (uint32 i = 0; i < 2; ++i)
CastCustomSpell(victim, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
return true;
}
// Shaman Tier 6 Trinket
case 40463:
{
if (!procSpell)
return false;
float chance;
if (procSpell->SpellFamilyFlags[0] & 0x1)
{
triggered_spell_id = 40465; // Lightning Bolt
chance = 15.0f;
}
else if (procSpell->SpellFamilyFlags[0] & 0x80)
{
triggered_spell_id = 40465; // Lesser Healing Wave
chance = 10.0f;
}
else if (procSpell->SpellFamilyFlags[1] & 0x00000010)
{
triggered_spell_id = 40466; // Stormstrike
chance = 50.0f;
}
else
return false;
if (!roll_chance_f(chance))
return false;
target = this;
break;
}
// Glyph of Healing Wave
case 55440:
{
// Not proc from self heals
if (this == victim)
return false;
basepoints0 = CalculatePct(int32(damage), triggerAmount);
target = this;
triggered_spell_id = 55533;
break;
}
// Spirit Hunt
case 58877:
{
// Cast on owner
target = GetOwner();
if (!target)
return false;
basepoints0 = CalculatePct(int32(damage), triggerAmount);
triggered_spell_id = 58879;
// Cast on spirit wolf
CastCustomSpell(this, triggered_spell_id, &basepoints0, NULL, NULL, true, NULL, triggeredByAura);
break;
}
// Shaman T8 Elemental 4P Bonus
case 64928:
{
basepoints0 = CalculatePct(int32(damage), triggerAmount);
triggered_spell_id = 64930; // Electrified
break;
}
// Shaman T9 Elemental 4P Bonus
case 67228:
{
// Lava Burst
if (procSpell->SpellFamilyFlags[1] & 0x1000)
{
triggered_spell_id = 71824;
SpellInfo const* triggeredSpell = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggeredSpell)
return false;
basepoints0 = CalculatePct(int32(damage), triggerAmount) / (triggeredSpell->GetMaxDuration() / triggeredSpell->Effects[0].Amplitude);
}
break;
}
// Item - Shaman T10 Restoration 4P Bonus
case 70808:
{
// Chain Heal
if ((procSpell->SpellFamilyFlags[0] & 0x100) && (procEx & PROC_EX_CRITICAL_HIT))
{
triggered_spell_id = 70809;
SpellInfo const* triggeredSpell = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggeredSpell)
return false;
basepoints0 = CalculatePct(int32(damage), triggerAmount) / (triggeredSpell->GetMaxDuration() / triggeredSpell->Effects[0].Amplitude);
// Add remaining ticks to healing done
basepoints0 += GetRemainingPeriodicAmount(GetGUID(), triggered_spell_id, SPELL_AURA_PERIODIC_HEAL);
}
break;
}
// Item - Shaman T10 Elemental 2P Bonus
case 70811:
{
// Lightning Bolt & Chain Lightning
if (procSpell->SpellFamilyFlags[0] & 0x3)
{
if (ToPlayer()->HasSpellCooldown(16166))
{
uint32 newCooldownDelay = ToPlayer()->GetSpellCooldownDelay(16166);
if (newCooldownDelay < 3)
newCooldownDelay = 0;
else
newCooldownDelay -= 2;
ToPlayer()->AddSpellCooldown(16166, 0, uint32(time(NULL) + newCooldownDelay));
WorldPacket data(SMSG_MODIFY_COOLDOWN, 4+8+4);
data << uint32(16166); // Spell ID
data << uint64(GetGUID()); // Player GUID
data << int32(-2000); // Cooldown mod in milliseconds
ToPlayer()->GetSession()->SendPacket(&data);
return true;
}
}
return false;
}
// Item - Shaman T10 Elemental 4P Bonus
case 70817:
{
if (!target)
return false;
// try to find spell Flame Shock on the target
if (AuraEffect const* aurEff = target->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x10000000, 0x0, 0x0, GetGUID()))
{
Aura* flameShock = aurEff->GetBase();
int32 maxDuration = flameShock->GetMaxDuration();
int32 newDuration = flameShock->GetDuration() + 2 * aurEff->GetAmplitude();
flameShock->SetDuration(newDuration);
// is it blizzlike to change max duration for FS?
if (newDuration > maxDuration)
flameShock->SetMaxDuration(newDuration);
return true;
}
// if not found Flame Shock
return false;
}
break;
}
// Frozen Power
if (dummySpell->SpellIconID == 3780)
{
if (!target)
return false;
if (GetDistance(target) < 15.0f)
return false;
float chance = (float)triggerAmount;
if (!roll_chance_f(chance))
return false;
triggered_spell_id = 63685;
break;
}
// Ancestral Awakening
if (dummySpell->SpellIconID == 3065)
{
triggered_spell_id = 52759;
basepoints0 = CalculatePct(int32(damage), triggerAmount);
target = this;
break;
}
// Flametongue Weapon (Passive)
if (dummySpell->SpellFamilyFlags[0] & 0x200000)
{
if (GetTypeId() != TYPEID_PLAYER || !victim || !victim->isAlive() || !castItem || !castItem->IsEquipped())
return false;
WeaponAttackType attType = WeaponAttackType(Player::GetAttackBySlot(castItem->GetSlot()));
if ((attType != BASE_ATTACK && attType != OFF_ATTACK)
|| (attType == BASE_ATTACK && procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK)
|| (attType == OFF_ATTACK && procFlag & PROC_FLAG_DONE_MAINHAND_ATTACK))
return false;
float fire_onhit = float(CalculatePct(dummySpell->Effects[EFFECT_0]. CalcValue(), 1.0f));
float add_spellpower = (float)(SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_FIRE)
+ victim->SpellBaseDamageBonusTaken(SPELL_SCHOOL_MASK_FIRE));
// 1.3speed = 5%, 2.6speed = 10%, 4.0 speed = 15%, so, 1.0speed = 3.84%
ApplyPct(add_spellpower, 3.84f);
// Enchant on Off-Hand and ready?
if (castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND && procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK)
{
float BaseWeaponSpeed = GetAttackTime(OFF_ATTACK) / 1000.0f;
// Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed
basepoints0 = int32((fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed));
triggered_spell_id = 10444;
}
// Enchant on Main-Hand and ready?
else if (castItem->GetSlot() == EQUIPMENT_SLOT_MAINHAND && procFlag & PROC_FLAG_DONE_MAINHAND_ATTACK)
{
float BaseWeaponSpeed = GetAttackTime(BASE_ATTACK) / 1000.0f;
// Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed
basepoints0 = int32((fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed));
triggered_spell_id = 10444;
}
// If not ready, we should return, shouldn't we?!
else
return false;
CastCustomSpell(victim, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
return true;
}
// Static Shock
if (dummySpell->SpellIconID == 3059)
{
// Lightning Shield
if (GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0x400, 0, 0))
{
uint32 spell = 26364;
// custom cooldown processing case
if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(spell))
ToPlayer()->RemoveSpellCooldown(spell);
CastSpell(target, spell, true, castItem, triggeredByAura);
return true;
}
return false;
}
break;
}
case SPELLFAMILY_DEATHKNIGHT:
{
// Blood-Caked Blade
if (dummySpell->SpellIconID == 138)
{
if (!target || !target->isAlive())
return false;
triggered_spell_id = dummySpell->Effects[effIndex].TriggerSpell;
break;
}
// Butchery
if (dummySpell->SpellIconID == 2664)
{
basepoints0 = triggerAmount;
triggered_spell_id = 50163;
target = this;
break;
}
// Dancing Rune Weapon
if (dummySpell->Id == 49028)
{
// 1 dummy aura for dismiss rune blade
if (effIndex != 1)
return false;
Unit* pPet = NULL;
for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) // Find Rune Weapon
if ((*itr)->GetEntry() == 27893)
{
pPet = *itr;
break;
}
if (pPet && pPet->getVictim() && damage && procSpell)
{
uint32 procDmg = damage / 2;
pPet->SendSpellNonMeleeDamageLog(pPet->getVictim(), procSpell->Id, procDmg, procSpell->GetSchoolMask(), 0, 0, false, 0, false);
pPet->DealDamage(pPet->getVictim(), procDmg, NULL, SPELL_DIRECT_DAMAGE, procSpell->GetSchoolMask(), procSpell, true);
break;
}
else
return false;
}
// Unholy Blight
if (dummySpell->Id == 49194)
{
triggered_spell_id = 50536;
SpellInfo const* unholyBlight = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!unholyBlight)
return false;
basepoints0 = CalculatePct(int32(damage), triggerAmount);
//Glyph of Unholy Blight
if (AuraEffect* glyph=GetAuraEffect(63332, 0))
AddPct(basepoints0, glyph->GetAmount());
basepoints0 = basepoints0 / (unholyBlight->GetMaxDuration() / unholyBlight->Effects[0].Amplitude);
basepoints0 += victim->GetRemainingPeriodicAmount(GetGUID(), triggered_spell_id, SPELL_AURA_PERIODIC_DAMAGE);
break;
}
// Threat of Thassarian
if (dummySpell->SpellIconID == 2023)
{
// Must Dual Wield
if (!procSpell || !haveOffhandWeapon())
return false;
// Chance as basepoints for dummy aura
if (!roll_chance_i(triggerAmount))
return false;
switch (procSpell->Id)
{
case 49020: triggered_spell_id = 66198; break; // Obliterate
case 49143: triggered_spell_id = 66196; break; // Frost Strike
case 45462: triggered_spell_id = 66216; break; // Plague Strike
case 49998: triggered_spell_id = 66188; break; // Death Strike
case 56815: triggered_spell_id = 66217; break; // Rune Strike
case 45902: triggered_spell_id = 66215; break; // Blood Strike
default:
return false;
}
break;
}
// Runic Power Back on Snare/Root
if (dummySpell->Id == 61257)
{
// only for spells and hit/crit (trigger start always) and not start from self casted spells
if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == victim)
return false;
// Need snare or root mechanic
if (!(procSpell->GetAllEffectsMechanicMask() & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_SNARE))))
return false;
triggered_spell_id = 61258;
target = this;
break;
}
break;
}
case SPELLFAMILY_POTION:
{
// alchemist's stone
if (dummySpell->Id == 17619)
{
if (procSpell->SpellFamilyName == SPELLFAMILY_POTION)
{
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++)
{
if (procSpell->Effects[i].Effect == SPELL_EFFECT_HEAL)
{
triggered_spell_id = 21399;
}
else if (procSpell->Effects[i].Effect == SPELL_EFFECT_ENERGIZE)
{
triggered_spell_id = 21400;
}
else
continue;
basepoints0 = int32(CalculateSpellDamage(this, procSpell, i) * 0.4f);
CastCustomSpell(this, triggered_spell_id, &basepoints0, NULL, NULL, true, NULL, triggeredByAura);
}
return true;
}
}
break;
}
case SPELLFAMILY_PET:
{
switch (dummySpell->SpellIconID)
{
// Guard Dog
case 201:
{
if (!victim)
return false;
triggered_spell_id = 54445;
target = this;
float addThreat = float(CalculatePct(procSpell->Effects[0].CalcValue(this), triggerAmount));
victim->AddThreat(this, addThreat);
break;
}
// Silverback
case 1582:
triggered_spell_id = dummySpell->Id == 62765 ? 62801 : 62800;
target = this;
break;
}
break;
}
default:
break;
}
// if not handled by custom case, get triggered spell from dummySpell proto
if (!triggered_spell_id)
triggered_spell_id = dummySpell->Effects[triggeredByAura->GetEffIndex()].TriggerSpell;
// processed charge only counting case
if (!triggered_spell_id)
return true;
SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggerEntry)
{
sLog->outError(LOG_FILTER_UNITS, "Unit::HandleDummyAuraProc: Spell %u has non-existing triggered spell %u", dummySpell->Id, triggered_spell_id);
return false;
}
if (cooldown_spell_id == 0)
cooldown_spell_id = triggered_spell_id;
if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(cooldown_spell_id))
return false;
if (basepoints0)
CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura, originalCaster);
else
CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura, originalCaster);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(cooldown_spell_id, 0, time(NULL) + cooldown);
return true;
}
/*
*/
// Used in case when access to whole aura is needed
// All procs should be handled like this...
bool Unit::HandleAuraProc(Unit* victim, uint32 /*damage*/, Aura* triggeredByAura, SpellInfo const* procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown, bool * handled)
{
SpellInfo const* dummySpell = triggeredByAura->GetSpellInfo();
switch (dummySpell->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
switch (dummySpell->Id)
{
// Nevermelting Ice Crystal
case 71564:
RemoveAuraFromStack(71564);
*handled = true;
break;
// Gaseous Bloat
case 70672:
case 72455:
case 72832:
case 72833:
{
*handled = true;
uint32 stack = triggeredByAura->GetStackAmount();
int32 const mod = (GetMap()->GetSpawnMode() & 1) ? 1500 : 1250;
int32 dmg = 0;
for (uint8 i = 1; i < stack; ++i)
dmg += mod * stack;
if (Unit* caster = triggeredByAura->GetCaster())
caster->CastCustomSpell(70701, SPELLVALUE_BASE_POINT0, dmg);
break;
}
// Ball of Flames Proc
case 71756:
case 72782:
case 72783:
case 72784:
RemoveAuraFromStack(dummySpell->Id);
*handled = true;
break;
// Discerning Eye of the Beast
case 59915:
{
CastSpell(this, 59914, true); // 59914 already has correct basepoints in DBC, no need for custom bp
*handled = true;
break;
}
// Swift Hand of Justice
case 59906:
{
int32 bp0 = CalculatePct(GetMaxHealth(), dummySpell->Effects[EFFECT_0]. CalcValue());
CastCustomSpell(this, 59913, &bp0, NULL, NULL, true);
*handled = true;
break;
}
}
break;
case SPELLFAMILY_PALADIN:
{
// Judgements of the Just
if (dummySpell->SpellIconID == 3015)
{
*handled = true;
CastSpell(victim, 68055, true);
return true;
}
// Glyph of Divinity
else if (dummySpell->Id == 54939)
{
*handled = true;
// Check if we are the target and prevent mana gain
if (victim && triggeredByAura->GetCasterGUID() == victim->GetGUID())
return false;
// Lookup base amount mana restore
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++)
{
if (procSpell->Effects[i].Effect == SPELL_EFFECT_ENERGIZE)
{
// value multiplied by 2 because you should get twice amount
int32 mana = procSpell->Effects[i].CalcValue() * 2;
CastCustomSpell(this, 54986, 0, &mana, NULL, true);
}
}
return true;
}
break;
}
case SPELLFAMILY_MAGE:
{
switch (dummySpell->Id)
{
// Empowered Fire
case 31656:
case 31657:
case 31658:
{
*handled = true;
SpellInfo const* spInfo = sSpellMgr->GetSpellInfo(67545);
if (!spInfo)
return false;
int32 bp0 = int32(CalculatePct(GetCreateMana(), spInfo->Effects[0].CalcValue()));
CastCustomSpell(this, 67545, &bp0, NULL, NULL, true, NULL, triggeredByAura->GetEffect(EFFECT_0), GetGUID());
return true;
}
}
break;
}
case SPELLFAMILY_DEATHKNIGHT:
{
// Blood of the North
// Reaping
// Death Rune Mastery
if (dummySpell->SpellIconID == 3041 || dummySpell->SpellIconID == 22 || dummySpell->SpellIconID == 2622)
{
*handled = true;
// Convert recently used Blood Rune to Death Rune
if (Player* player = ToPlayer())
{
if (player->getClass() != CLASS_DEATH_KNIGHT)
return false;
RuneType rune = ToPlayer()->GetLastUsedRune();
// can't proc from death rune use
if (rune == RUNE_DEATH)
return false;
AuraEffect* aurEff = triggeredByAura->GetEffect(EFFECT_0);
if (!aurEff)
return false;
// Reset amplitude - set death rune remove timer to 30s
aurEff->ResetPeriodic(true);
uint32 runesLeft;
if (dummySpell->SpellIconID == 2622)
runesLeft = 2;
else
runesLeft = 1;
for (uint8 i = 0; i < MAX_RUNES && runesLeft; ++i)
{
if (dummySpell->SpellIconID == 2622)
{
if (player->GetCurrentRune(i) == RUNE_DEATH ||
player->GetBaseRune(i) == RUNE_BLOOD)
continue;
}
else
{
if (player->GetCurrentRune(i) == RUNE_DEATH ||
player->GetBaseRune(i) != RUNE_BLOOD)
continue;
}
if (player->GetRuneCooldown(i) != player->GetRuneBaseCooldown(i))
continue;
--runesLeft;
// Mark aura as used
player->AddRuneByAuraEffect(i, RUNE_DEATH, aurEff);
}
return true;
}
return false;
}
switch (dummySpell->Id)
{
// Bone Shield cooldown
case 49222:
{
*handled = true;
if (cooldown && GetTypeId() == TYPEID_PLAYER)
{
if (ToPlayer()->HasSpellCooldown(100000))
return false;
ToPlayer()->AddSpellCooldown(100000, 0, time(NULL) + cooldown);
}
return true;
}
// Hungering Cold aura drop
case 51209:
*handled = true;
// Drop only in not disease case
if (procSpell && procSpell->Dispel == DISPEL_DISEASE)
return false;
return true;
}
break;
}
case SPELLFAMILY_WARRIOR:
{
switch (dummySpell->Id)
{
// Item - Warrior T10 Protection 4P Bonus
case 70844:
{
int32 basepoints0 = CalculatePct(GetMaxHealth(), dummySpell->Effects[EFFECT_1]. CalcValue());
CastCustomSpell(this, 70845, &basepoints0, NULL, NULL, true);
break;
}
// Recklessness
case 1719:
{
//! Possible hack alert
//! Don't drop charges on proc, they will be dropped on SpellMod removal
//! Before this change, it was dropping two charges per attack, one in ProcDamageAndSpellFor, and one in RemoveSpellMods.
//! The reason of this behaviour is Recklessness having three auras, 2 of them can not proc (isTriggeredAura array) but the other one can, making the whole spell proc.
*handled = true;
break;
}
default:
break;
}
break;
}
}
return false;
}
bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
{
// Get triggered aura spell info
SpellInfo const* auraSpellInfo = triggeredByAura->GetSpellInfo();
// Basepoints of trigger aura
int32 triggerAmount = triggeredByAura->GetAmount();
// Set trigger spell id, target, custom basepoints
uint32 trigger_spell_id = auraSpellInfo->Effects[triggeredByAura->GetEffIndex()].TriggerSpell;
Unit* target = NULL;
int32 basepoints0 = 0;
if (triggeredByAura->GetAuraType() == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
basepoints0 = triggerAmount;
Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
// Try handle unknown trigger spells
if (sSpellMgr->GetSpellInfo(trigger_spell_id) == NULL)
{
switch (auraSpellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
switch (auraSpellInfo->Id)
{
case 23780: // Aegis of Preservation (Aegis of Preservation trinket)
trigger_spell_id = 23781;
break;
case 33896: // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
trigger_spell_id = 33898;
break;
case 43820: // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
// Pct value stored in dummy
basepoints0 = victim->GetCreateHealth() * auraSpellInfo->Effects[1].CalcValue() / 100;
target = victim;
break;
case 57345: // Darkmoon Card: Greatness
{
float stat = 0.0f;
// strength
if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
// agility
if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
// intellect
if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
// spirit
if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; }
break;
}
case 64568: // Blood Reserve
{
if (HealthBelowPctDamaged(35, damage))
{
CastCustomSpell(this, 64569, &triggerAmount, NULL, NULL, true);
RemoveAura(64568);
}
return false;
}
case 67702: // Death's Choice, Item - Coliseum 25 Normal Melee Trinket
{
float stat = 0.0f;
// strength
if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708;stat = GetStat(STAT_STRENGTH); }
// agility
if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; }
break;
}
case 67771: // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket
{
float stat = 0.0f;
// strength
if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773;stat = GetStat(STAT_STRENGTH); }
// agility
if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; }
break;
}
// Mana Drain Trigger
case 27522:
case 40336:
{
// On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
if (isAlive())
CastSpell(this, 29471, true, castItem, triggeredByAura);
if (victim && victim->isAlive())
CastSpell(victim, 27526, true, castItem, triggeredByAura);
return true;
}
// Evasive Maneuvers
case 50240:
{
// Remove a Evasive Charge
Aura* charge = GetAura(50241);
if (charge && charge->ModStackAmount(-1, AURA_REMOVE_BY_ENEMY_SPELL))
RemoveAurasDueToSpell(50240);
}
// Warrior - Vigilance, SPELLFAMILY_GENERIC
if (auraSpellInfo->Id == 50720)
{
target = triggeredByAura->GetCaster();
if (!target)
return false;
}
}
break;
case SPELLFAMILY_MAGE:
if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
{
switch (auraSpellInfo->Id)
{
case 31641: // Rank 1
case 31642: // Rank 2
trigger_spell_id = 31643;
break;
default:
sLog->outError(LOG_FILTER_UNITS, "Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed", auraSpellInfo->Id);
return false;
}
}
break;
case SPELLFAMILY_WARRIOR:
if (auraSpellInfo->Id == 50421) // Scent of Blood
{
CastSpell(this, 50422, true);
RemoveAuraFromStack(auraSpellInfo->Id);
return false;
}
break;
case SPELLFAMILY_PRIEST:
{
// Greater Heal Refund
if (auraSpellInfo->Id == 37594)
trigger_spell_id = 37595;
break;
}
case SPELLFAMILY_DRUID:
{
switch (auraSpellInfo->Id)
{
// Druid Forms Trinket
case 37336:
{
switch (GetShapeshiftForm())
{
case FORM_NONE: trigger_spell_id = 37344; break;
case FORM_CAT: trigger_spell_id = 37341; break;
case FORM_BEAR: trigger_spell_id = 37340; break;
case FORM_TREE: trigger_spell_id = 37342; break;
case FORM_MOONKIN: trigger_spell_id = 37343; break;
default:
return false;
}
break;
}
// Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred)
case 67353:
{
switch (GetShapeshiftForm())
{
case FORM_CAT: trigger_spell_id = 67355; break;
case FORM_BEAR: trigger_spell_id = 67354; break;
default:
return false;
}
break;
}
default:
break;
}
break;
}
case SPELLFAMILY_HUNTER:
{
if (auraSpellInfo->SpellIconID == 3247) // Piercing Shots
{
switch (auraSpellInfo->Id)
{
case 53234: // Rank 1
case 53237: // Rank 2
case 53238: // Rank 3
trigger_spell_id = 63468;
break;
default:
sLog->outError(LOG_FILTER_UNITS, "Unit::HandleProcTriggerSpell: Spell %u miss posibly Piercing Shots", auraSpellInfo->Id);
return false;
}
SpellInfo const* TriggerPS = sSpellMgr->GetSpellInfo(trigger_spell_id);
if (!TriggerPS)
return false;
basepoints0 = CalculatePct(int32(damage), triggerAmount) / (TriggerPS->GetMaxDuration() / TriggerPS->Effects[0].Amplitude);
basepoints0 += victim->GetRemainingPeriodicAmount(GetGUID(), trigger_spell_id, SPELL_AURA_PERIODIC_DAMAGE);
break;
}
// Item - Hunter T9 4P Bonus
if (auraSpellInfo->Id == 67151)
{
trigger_spell_id = 68130;
target = this;
break;
}
break;
}
case SPELLFAMILY_PALADIN:
{
switch (auraSpellInfo->Id)
{
// Healing Discount
case 37705:
{
trigger_spell_id = 37706;
target = this;
break;
}
// Soul Preserver
case 60510:
{
switch (getClass())
{
case CLASS_DRUID:
trigger_spell_id = 60512;
break;
case CLASS_PALADIN:
trigger_spell_id = 60513;
break;
case CLASS_PRIEST:
trigger_spell_id = 60514;
break;
case CLASS_SHAMAN:
trigger_spell_id = 60515;
break;
}
target = this;
break;
}
case 37657: // Lightning Capacitor
case 54841: // Thunder Capacitor
case 67712: // Item - Coliseum 25 Normal Caster Trinket
case 67758: // Item - Coliseum 25 Heroic Caster Trinket
{
if (!victim || !victim->isAlive() || GetTypeId() != TYPEID_PLAYER)
return false;
uint32 stack_spell_id = 0;
switch (auraSpellInfo->Id)
{
case 37657:
stack_spell_id = 37658;
trigger_spell_id = 37661;
break;
case 54841:
stack_spell_id = 54842;
trigger_spell_id = 54843;
break;
case 67712:
stack_spell_id = 67713;
trigger_spell_id = 67714;
break;
case 67758:
stack_spell_id = 67759;
trigger_spell_id = 67760;
break;
}
CastSpell(this, stack_spell_id, true, NULL, triggeredByAura);
Aura* dummy = GetAura(stack_spell_id);
if (!dummy || dummy->GetStackAmount() < triggerAmount)
return false;
RemoveAurasDueToSpell(stack_spell_id);
target = victim;
break;
}
default:
break;
}
break;
}
case SPELLFAMILY_SHAMAN:
{
switch (auraSpellInfo->Id)
{
// Lightning Shield (The Ten Storms set)
case 23551:
{
trigger_spell_id = 23552;
target = victim;
break;
}
// Damage from Lightning Shield (The Ten Storms set)
case 23552:
{
trigger_spell_id = 27635;
break;
}
// Mana Surge (The Earthfury set)
case 23572:
{
if (!procSpell)
return false;
basepoints0 = int32(CalculatePct(procSpell->ManaCost, 35));
trigger_spell_id = 23571;
target = this;
break;
}
case 30881: // Nature's Guardian Rank 1
case 30883: // Nature's Guardian Rank 2
case 30884: // Nature's Guardian Rank 3
{
if (!HealthBelowPctDamaged(30, damage))
{
basepoints0 = int32(CountPctFromMaxHealth(triggerAmount));
target = this;
trigger_spell_id = 31616;
if (victim && victim->isAlive())
victim->getThreatManager().modifyThreatPercent(this, -10);
}
else
return false;
break;
}
}
break;
}
case SPELLFAMILY_DEATHKNIGHT:
{
// Item - Death Knight T10 Melee 4P Bonus
if (auraSpellInfo->Id == 70656)
{
if (GetTypeId() != TYPEID_PLAYER || getClass() != CLASS_DEATH_KNIGHT)
return false;
for (uint8 i = 0; i < MAX_RUNES; ++i)
if (ToPlayer()->GetRuneCooldown(i) == 0)
return false;
}
break;
}
case SPELLFAMILY_ROGUE:
{
switch (auraSpellInfo->Id)
{
// Rogue T10 2P bonus, should only proc on caster
case 70805:
{
if (victim != this)
return false;
break;
}
// Rogue T10 4P bonus, should proc on victim
case 70803:
{
target = victim;
break;
}
}
break;
}
default:
break;
}
}
// All ok. Check current trigger spell
SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(trigger_spell_id);
if (triggerEntry == NULL)
{
// Don't cast unknown spell
// sLog->outError(LOG_FILTER_UNITS, "Unit::HandleProcTriggerSpell: Spell %u has 0 in EffectTriggered[%d]. Unhandled custom case?", auraSpellInfo->Id, triggeredByAura->GetEffIndex());
return false;
}
// not allow proc extra attack spell at extra attack
if (m_extraAttacks && triggerEntry->HasEffect(SPELL_EFFECT_ADD_EXTRA_ATTACKS))
return false;
// Custom requirements (not listed in procEx) Warning! damage dealing after this
// Custom triggered spells
switch (auraSpellInfo->Id)
{
// Deep Wounds
case 12834:
case 12849:
case 12867:
{
if (GetTypeId() != TYPEID_PLAYER)
return false;
// now compute approximate weapon damage by formula from wowwiki.com
Item* item = NULL;
if (procFlags & PROC_FLAG_DONE_OFFHAND_ATTACK)
item = ToPlayer()->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
else
item = ToPlayer()->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
// dunno if it's really needed but will prevent any possible crashes
if (!item)
return false;
ItemTemplate const* weapon = item->GetTemplate();
float weaponDPS = weapon->DPS;
float attackPower = GetTotalAttackPowerValue(BASE_ATTACK) / 14.0f;
float weaponSpeed = float(weapon->Delay) / 1000.0f;
basepoints0 = int32((weaponDPS + attackPower) * weaponSpeed);
break;
}
// Persistent Shield (Scarab Brooch trinket)
// This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
case 26467:
{
basepoints0 = int32(CalculatePct(damage, 15));
target = victim;
trigger_spell_id = 26470;
break;
}
// Unyielding Knights (item exploit 29108\29109)
case 38164:
{
if (!victim || victim->GetEntry() != 19457) // Proc only if your target is Grillok
return false;
break;
}
// Deflection
case 52420:
{
if (!HealthBelowPctDamaged(35, damage))
return false;
break;
}
// Cheat Death
case 28845:
{
// When your health drops below 20%
if (HealthBelowPctDamaged(20, damage) || HealthBelowPct(20))
return false;
break;
}
// Greater Heal Refund (Avatar Raiment set)
case 37594:
{
if (!victim || !victim->isAlive())
return false;
// Doesn't proc if target already has full health
if (victim->IsFullHealth())
return false;
// If your Greater Heal brings the target to full health, you gain $37595s1 mana.
if (victim->GetHealth() + damage < victim->GetMaxHealth())
return false;
break;
}
// Bonus Healing (Crystal Spire of Karabor mace)
case 40971:
{
// If your target is below $s1% health
if (!victim || !victim->isAlive() || victim->HealthAbovePct(triggerAmount))
return false;
break;
}
// Rapid Recuperation
case 53228:
case 53232:
{
// This effect only from Rapid Fire (ability cast)
if (!(procSpell->SpellFamilyFlags[0] & 0x20))
return false;
break;
}
// Decimation
case 63156:
case 63158:
// Can proc only if target has hp below 25%
if (!victim || !victim->HealthBelowPct(auraSpellInfo->Effects[EFFECT_1].CalcValue()))
return false;
break;
// Deathbringer Saurfang - Blood Beast's Blood Link
case 72176:
basepoints0 = 3;
break;
// Professor Putricide - Ooze Spell Tank Protection
case 71770:
if (victim)
victim->CastSpell(victim, trigger_spell_id, true); // EffectImplicitTarget is self
return true;
case 45057: // Evasive Maneuvers (Commendation of Kael`thas trinket)
case 71634: // Item - Icecrown 25 Normal Tank Trinket 1
case 71640: // Item - Icecrown 25 Heroic Tank Trinket 1
case 75475: // Item - Chamber of Aspects 25 Normal Tank Trinket
case 75481: // Item - Chamber of Aspects 25 Heroic Tank Trinket
{
// Procs only if damage takes health below $s1%
if (!HealthBelowPctDamaged(triggerAmount, damage))
return false;
break;
}
default:
break;
}
// Custom basepoints/target for exist spell
// dummy basepoints or other customs
switch (trigger_spell_id)
{
// Auras which should proc on area aura source (caster in this case):
// Cast positive spell on enemy target
case 7099: // Curse of Mending
case 39703: // Curse of Mending
case 29494: // Temptation
case 20233: // Improved Lay on Hands (cast on target)
{
target = victim;
break;
}
// Finish movies that add combo
case 14189: // Seal Fate (Netherblade set)
case 14157: // Ruthlessness
{
if (!victim || victim == this)
return false;
// Need add combopoint AFTER finish movie (or they dropped in finish phase)
break;
}
// Item - Druid T10 Balance 2P Bonus
case 16870:
{
if (HasAura(70718))
CastSpell(this, 70721, true);
break;
}
// Enlightenment (trigger only from mana cost spells)
case 35095:
{
if (!procSpell || procSpell->PowerType != POWER_MANA || (procSpell->ManaCost == 0 && procSpell->ManaCostPercentage == 0 && procSpell->ManaCostPerlevel == 0))
return false;
break;
}
case 46916: // Slam! (Bloodsurge proc)
case 52437: // Sudden Death
{
// Item - Warrior T10 Melee 4P Bonus
if (AuraEffect const* aurEff = GetAuraEffect(70847, 0))
{
if (!roll_chance_i(aurEff->GetAmount()))
break;
CastSpell(this, 70849, true, castItem, triggeredByAura); // Extra Charge!
CastSpell(this, 71072, true, castItem, triggeredByAura); // Slam GCD Reduced
CastSpell(this, 71069, true, castItem, triggeredByAura); // Execute GCD Reduced
}
break;
}
// Sword and Board
case 50227:
{
// Remove cooldown on Shield Slam
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->RemoveSpellCategoryCooldown(1209, true);
break;
}
// Maelstrom Weapon
case 53817:
{
// has rank dependant proc chance, ignore too often cases
// PPM = 2.5 * (rank of talent),
uint32 rank = auraSpellInfo->GetRank();
// 5 rank -> 100% 4 rank -> 80% and etc from full rate
if (!roll_chance_i(20*rank))
return false;
// Item - Shaman T10 Enhancement 4P Bonus
if (AuraEffect const* aurEff = GetAuraEffect(70832, 0))
if (Aura const* maelstrom = GetAura(53817))
if ((maelstrom->GetStackAmount() == maelstrom->GetSpellInfo()->StackAmount - 1) && roll_chance_i(aurEff->GetAmount()))
CastSpell(this, 70831, true, castItem, triggeredByAura);
break;
}
// Glyph of Death's Embrace
case 58679:
{
// Proc only from healing part of Death Coil. Check is essential as all Death Coil spells have 0x2000 mask in SpellFamilyFlags
if (!procSpell || !(procSpell->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && procSpell->SpellFamilyFlags[0] == 0x80002000))
return false;
break;
}
// Glyph of Death Grip
case 58628:
{
// remove cooldown of Death Grip
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->RemoveSpellCooldown(49576, true);
return true;
}
// Savage Defense
case 62606:
{
basepoints0 = CalculatePct(triggerAmount, GetTotalAttackPowerValue(BASE_ATTACK));
break;
}
// Body and Soul
case 64128:
case 65081:
{
// Proc only from PW:S cast
if (!(procSpell->SpellFamilyFlags[0] & 0x00000001))
return false;
break;
}
// Culling the Herd
case 70893:
{
// check if we're doing a critical hit
if (!(procSpell->SpellFamilyFlags[1] & 0x10000000) && (procEx != PROC_EX_CRITICAL_HIT))
return false;
// check if we're procced by Claw, Bite or Smack (need to use the spell icon ID to detect it)
if (!(procSpell->SpellIconID == 262 || procSpell->SpellIconID == 1680 || procSpell->SpellIconID == 473))
return false;
break;
}
}
if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(trigger_spell_id))
return false;
// try detect target manually if not set
if (target == NULL)
target = !(procFlags & (PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS)) && triggerEntry && triggerEntry->IsPositive() ? this : victim;
if (basepoints0)
CastCustomSpell(target, trigger_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
else
CastSpell(target, trigger_spell_id, true, castItem, triggeredByAura);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(trigger_spell_id, 0, time(NULL) + cooldown);
return true;
}
bool Unit::HandleOverrideClassScriptAuraProc(Unit* victim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellInfo const* /*procSpell*/, uint32 cooldown)
{
int32 scriptId = triggeredByAura->GetMiscValue();
if (!victim || !victim->isAlive())
return false;
Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER
? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL;
uint32 triggered_spell_id = 0;
switch (scriptId)
{
case 4533: // Dreamwalker Raiment 2 pieces bonus
{
// Chance 50%
if (!roll_chance_i(50))
return false;
switch (victim->getPowerType())
{
case POWER_MANA: triggered_spell_id = 28722; break;
case POWER_RAGE: triggered_spell_id = 28723; break;
case POWER_ENERGY: triggered_spell_id = 28724; break;
default:
return false;
}
break;
}
case 4537: // Dreamwalker Raiment 6 pieces bonus
triggered_spell_id = 28750; // Blessing of the Claw
break;
default:
break;
}
// not processed
if (!triggered_spell_id)
return false;
// standard non-dummy case
SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!triggerEntry)
{
sLog->outError(LOG_FILTER_UNITS, "Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u", triggered_spell_id, scriptId);
return false;
}
if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(triggered_spell_id))
return false;
CastSpell(victim, triggered_spell_id, true, castItem, triggeredByAura);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->AddSpellCooldown(triggered_spell_id, 0, time(NULL) + cooldown);
return true;
}
void Unit::setPowerType(Powers new_powertype)
{
SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
if (GetTypeId() == TYPEID_PLAYER)
{
if (ToPlayer()->GetGroup())
ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
}
else if (Pet* pet = ToCreature()->ToPet())
{
if (pet->isControlled())
{
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
}
}
switch (new_powertype)
{
default:
case POWER_MANA:
break;
case POWER_RAGE:
SetMaxPower(POWER_RAGE, GetCreatePowers(POWER_RAGE));
SetPower(POWER_RAGE, 0);
break;
case POWER_FOCUS:
SetMaxPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS));
SetPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS));
break;
case POWER_ENERGY:
SetMaxPower(POWER_ENERGY, GetCreatePowers(POWER_ENERGY));
break;
}
}
FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
{
FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
if (!entry)
{
static uint64 guid = 0; // prevent repeating spam same faction problem
if (GetGUID() != guid)
{
if (Player const* player = ToPlayer())
sLog->outError(LOG_FILTER_UNITS, "Player %s has invalid faction (faction template id) #%u", player->GetName().c_str(), getFaction());
else if (Creature const* creature = ToCreature())
sLog->outError(LOG_FILTER_UNITS, "Creature (template id: %u) has invalid faction (faction template id) #%u", creature->GetCreatureTemplate()->Entry, getFaction());
else
sLog->outError(LOG_FILTER_UNITS, "Unit (name=%s, type=%u) has invalid faction (faction template id) #%u", GetName().c_str(), uint32(GetTypeId()), getFaction());
guid = GetGUID();
}
}
return entry;
}
// function based on function Unit::UnitReaction from 13850 client
ReputationRank Unit::GetReactionTo(Unit const* target) const
{
// always friendly to self
if (this == target)
return REP_FRIENDLY;
// always friendly to charmer or owner
if (GetCharmerOrOwnerOrSelf() == target->GetCharmerOrOwnerOrSelf())
return REP_FRIENDLY;
if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE))
{
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE))
{
Player const* selfPlayerOwner = GetAffectingPlayer();
Player const* targetPlayerOwner = target->GetAffectingPlayer();
if (selfPlayerOwner && targetPlayerOwner)
{
// always friendly to other unit controlled by player, or to the player himself
if (selfPlayerOwner == targetPlayerOwner)
return REP_FRIENDLY;
// duel - always hostile to opponent
if (selfPlayerOwner->duel && selfPlayerOwner->duel->opponent == targetPlayerOwner && selfPlayerOwner->duel->startTime != 0)
return REP_HOSTILE;
// same group - checks dependant only on our faction - skip FFA_PVP for example
if (selfPlayerOwner->IsInRaidWith(targetPlayerOwner))
return REP_FRIENDLY; // return true to allow config option AllowTwoSide.Interaction.Group to work
// however client seems to allow mixed group parties, because in 13850 client it works like:
// return GetFactionReactionTo(getFactionTemplateEntry(), target);
}
// check FFA_PVP
if (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP
&& target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP)
return REP_HOSTILE;
if (selfPlayerOwner)
{
if (FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry())
{
if (ReputationRank const* repRank = selfPlayerOwner->GetReputationMgr().GetForcedRankIfAny(targetFactionTemplateEntry))
return *repRank;
if (!selfPlayerOwner->HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_IGNORE_REPUTATION))
{
if (FactionEntry const* targetFactionEntry = sFactionStore.LookupEntry(targetFactionTemplateEntry->faction))
{
if (targetFactionEntry->CanHaveReputation())
{
// check contested flags
if (targetFactionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD
&& selfPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
return REP_HOSTILE;
// if faction has reputation, hostile state depends only from AtWar state
if (selfPlayerOwner->GetReputationMgr().IsAtWar(targetFactionEntry))
return REP_HOSTILE;
return REP_FRIENDLY;
}
}
}
}
}
}
}
// do checks dependant only on our faction
return GetFactionReactionTo(getFactionTemplateEntry(), target);
}
ReputationRank Unit::GetFactionReactionTo(FactionTemplateEntry const* factionTemplateEntry, Unit const* target)
{
// always neutral when no template entry found
if (!factionTemplateEntry)
return REP_NEUTRAL;
FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry();
if (!targetFactionTemplateEntry)
return REP_NEUTRAL;
if (Player const* targetPlayerOwner = target->GetAffectingPlayer())
{
// check contested flags
if (factionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD
&& targetPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
return REP_HOSTILE;
if (ReputationRank const* repRank = targetPlayerOwner->GetReputationMgr().GetForcedRankIfAny(factionTemplateEntry))
return *repRank;
if (!target->HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_IGNORE_REPUTATION))
{
if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction))
{
if (factionEntry->CanHaveReputation())
{
// CvP case - check reputation, don't allow state higher than neutral when at war
ReputationRank repRank = targetPlayerOwner->GetReputationMgr().GetRank(factionEntry);
if (targetPlayerOwner->GetReputationMgr().IsAtWar(factionEntry))
repRank = std::min(REP_NEUTRAL, repRank);
return repRank;
}
}
}
}
// common faction based check
if (factionTemplateEntry->IsHostileTo(*targetFactionTemplateEntry))
return REP_HOSTILE;
if (factionTemplateEntry->IsFriendlyTo(*targetFactionTemplateEntry))
return REP_FRIENDLY;
if (targetFactionTemplateEntry->IsFriendlyTo(*factionTemplateEntry))
return REP_FRIENDLY;
if (factionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_HOSTILE_BY_DEFAULT)
return REP_HOSTILE;
// neutral by default
return REP_NEUTRAL;
}
bool Unit::IsHostileTo(Unit const* unit) const
{
return GetReactionTo(unit) <= REP_HOSTILE;
}
bool Unit::IsFriendlyTo(Unit const* unit) const
{
return GetReactionTo(unit) >= REP_FRIENDLY;
}
bool Unit::IsHostileToPlayers() const
{
FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
if (!my_faction || !my_faction->faction)
return false;
FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
if (raw_faction && raw_faction->reputationListID >= 0)
return false;
return my_faction->IsHostileToPlayers();
}
bool Unit::IsNeutralToAll() const
{
FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
if (!my_faction || !my_faction->faction)
return true;
FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
if (raw_faction && raw_faction->reputationListID >= 0)
return false;
return my_faction->IsNeutralToAll();
}
bool Unit::Attack(Unit* victim, bool meleeAttack)
{
if (!victim || victim == this)
return false;
// dead units can neither attack nor be attacked
if (!isAlive() || !victim->IsInWorld() || !victim->isAlive())
return false;
// player cannot attack in mount state
if (GetTypeId() == TYPEID_PLAYER && IsMounted())
return false;
// nobody can attack GM in GM-mode
if (victim->GetTypeId() == TYPEID_PLAYER)
{
if (victim->ToPlayer()->isGameMaster())
return false;
}
else
{
if (victim->ToCreature()->IsInEvadeMode())
return false;
}
// remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
if (HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
RemoveAurasByType(SPELL_AURA_MOD_UNATTACKABLE);
if (m_attacking)
{
if (m_attacking == victim)
{
// switch to melee attack from ranged/magic
if (meleeAttack)
{
if (!HasUnitState(UNIT_STATE_MELEE_ATTACKING))
{
AddUnitState(UNIT_STATE_MELEE_ATTACKING);
SendMeleeAttackStart(victim);
return true;
}
}
else if (HasUnitState(UNIT_STATE_MELEE_ATTACKING))
{
ClearUnitState(UNIT_STATE_MELEE_ATTACKING);
SendMeleeAttackStop(victim);
return true;
}
return false;
}
// switch target
InterruptSpell(CURRENT_MELEE_SPELL);
if (!meleeAttack)
ClearUnitState(UNIT_STATE_MELEE_ATTACKING);
}
if (m_attacking)
m_attacking->_removeAttacker(this);
m_attacking = victim;
m_attacking->_addAttacker(this);
// Set our target
SetTarget(victim->GetGUID());
if (meleeAttack)
AddUnitState(UNIT_STATE_MELEE_ATTACKING);
// set position before any AI calls/assistance
//if (GetTypeId() == TYPEID_UNIT)
// ToCreature()->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
if (GetTypeId() == TYPEID_UNIT && !ToCreature()->isPet())
{
// should not let player enter combat by right clicking target - doesn't helps
SetInCombatWith(victim);
if (victim->GetTypeId() == TYPEID_PLAYER)
victim->SetInCombatWith(this);
AddThreat(victim, 0.0f);
ToCreature()->SendAIReaction(AI_REACTION_HOSTILE);
ToCreature()->CallAssistance();
}
// delay offhand weapon attack to next attack time
if (haveOffhandWeapon())
resetAttackTimer(OFF_ATTACK);
if (meleeAttack)
SendMeleeAttackStart(victim);
// Let the pet know we've started attacking someting. Handles melee attacks only
// Spells such as auto-shot and others handled in WorldSession::HandleCastSpellOpcode
if (this->GetTypeId() == TYPEID_PLAYER)
{
Pet* playerPet = this->ToPlayer()->GetPet();
if (playerPet && playerPet->isAlive())
playerPet->AI()->OwnerAttacked(victim);
}
return true;
}
bool Unit::AttackStop()
{
if (!m_attacking)
return false;
Unit* victim = m_attacking;
m_attacking->_removeAttacker(this);
m_attacking = NULL;
// Clear our target
SetTarget(0);
ClearUnitState(UNIT_STATE_MELEE_ATTACKING);
InterruptSpell(CURRENT_MELEE_SPELL);
// reset only at real combat stop
if (Creature* creature = ToCreature())
{
creature->SetNoCallAssistance(false);
if (creature->HasSearchedAssistance())
{
creature->SetNoSearchAssistance(false);
UpdateSpeed(MOVE_RUN, false);
}
}
SendMeleeAttackStop(victim);
return true;
}
void Unit::CombatStop(bool includingCast)
{
if (includingCast && IsNonMeleeSpellCasted(false))
InterruptNonMeleeSpells(false);
AttackStop();
RemoveAllAttackers();
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
ClearInCombat();
}
void Unit::CombatStopWithPets(bool includingCast)
{
CombatStop(includingCast);
for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
(*itr)->CombatStop(includingCast);
}
bool Unit::isAttackingPlayer() const
{
if (HasUnitState(UNIT_STATE_ATTACK_PLAYER))
return true;
for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
if ((*itr)->isAttackingPlayer())
return true;
for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
if (m_SummonSlot[i])
if (Creature* summon = GetMap()->GetCreature(m_SummonSlot[i]))
if (summon->isAttackingPlayer())
return true;
return false;
}
void Unit::RemoveAllAttackers()
{
while (!m_attackers.empty())
{
AttackerSet::iterator iter = m_attackers.begin();
if (!(*iter)->AttackStop())
{
sLog->outError(LOG_FILTER_UNITS, "WORLD: Unit has an attacker that isn't attacking it!");
m_attackers.erase(iter);
}
}
}
void Unit::ModifyAuraState(AuraStateType flag, bool apply)
{
if (apply)
{
if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
{
SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
if (GetTypeId() == TYPEID_PLAYER)
{
PlayerSpellMap const& sp_list = ToPlayer()->GetSpellMap();
for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
{
if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
if (!spellInfo || !spellInfo->IsPassive())
continue;
if (spellInfo->CasterAuraState == uint32(flag))
CastSpell(this, itr->first, true, NULL);
}
}
else if (Pet* pet = ToCreature()->ToPet())
{
for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
{
if (itr->second.state == PETSPELL_REMOVED)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first);
if (!spellInfo || !spellInfo->IsPassive())
continue;
if (spellInfo->CasterAuraState == uint32(flag))
CastSpell(this, itr->first, true, NULL);
}
}
}
}
else
{
if (HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
{
RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
if (flag != AURA_STATE_ENRAGE) // enrage aura state triggering continues auras
{
Unit::AuraApplicationMap& tAuras = GetAppliedAuras();
for (Unit::AuraApplicationMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
{
SpellInfo const* spellProto = (*itr).second->GetBase()->GetSpellInfo();
if (spellProto->CasterAuraState == uint32(flag))
RemoveAura(itr);
else
++itr;
}
}
}
}
}
uint32 Unit::BuildAuraStateUpdateForTarget(Unit* target) const
{
uint32 auraStates = GetUInt32Value(UNIT_FIELD_AURASTATE) &~(PER_CASTER_AURA_STATE_MASK);
for (AuraStateAurasMap::const_iterator itr = m_auraStateAuras.begin(); itr != m_auraStateAuras.end(); ++itr)
if ((1<<(itr->first-1)) & PER_CASTER_AURA_STATE_MASK)
if (itr->second->GetBase()->GetCasterGUID() == target->GetGUID())
auraStates |= (1<<(itr->first-1));
return auraStates;
}
bool Unit::HasAuraState(AuraStateType flag, SpellInfo const* spellProto, Unit const* Caster) const
{
if (Caster)
{
if (spellProto)
{
AuraEffectList const& stateAuras = Caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE);
for (AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j)
if ((*j)->IsAffectingSpell(spellProto))
return true;
}
// Check per caster aura state
// If aura with aurastate by caster not found return false
if ((1<<(flag-1)) & PER_CASTER_AURA_STATE_MASK)
{
AuraStateAurasMapBounds range = m_auraStateAuras.equal_range(flag);
for (AuraStateAurasMap::const_iterator itr = range.first; itr != range.second; ++itr)
if (itr->second->GetBase()->GetCasterGUID() == Caster->GetGUID())
return true;
return false;
}
}
return HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
}
void Unit::SetOwnerGUID(uint64 owner)
{
if (GetOwnerGUID() == owner)
return;
SetUInt64Value(UNIT_FIELD_SUMMONEDBY, owner);
if (!owner)
return;
// Update owner dependent fields
Player* player = ObjectAccessor::GetPlayer(*this, owner);
if (!player || !player->HaveAtClient(this)) // if player cannot see this unit yet, he will receive needed data with create object
return;
SetFieldNotifyFlag(UF_FLAG_OWNER);
UpdateData udata(GetMapId());
WorldPacket packet;
BuildValuesUpdateBlockForPlayer(&udata, player);
udata.BuildPacket(&packet);
player->SendDirectMessage(&packet);
RemoveFieldNotifyFlag(UF_FLAG_OWNER);
}
Unit* Unit::GetOwner() const
{
if (uint64 ownerid = GetOwnerGUID())
{
return ObjectAccessor::GetUnit(*this, ownerid);
}
return NULL;
}
Unit* Unit::GetCharmer() const
{
if (uint64 charmerid = GetCharmerGUID())
return ObjectAccessor::GetUnit(*this, charmerid);
return NULL;
}
Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself() const
{
uint64 guid = GetCharmerOrOwnerGUID();
if (IS_PLAYER_GUID(guid))
return ObjectAccessor::GetPlayer(*this, guid);
return GetTypeId() == TYPEID_PLAYER ? (Player*)this : NULL;
}
Player* Unit::GetAffectingPlayer() const
{
if (!GetCharmerOrOwnerGUID())
return GetTypeId() == TYPEID_PLAYER ? (Player*)this : NULL;
if (Unit* owner = GetCharmerOrOwner())
return owner->GetCharmerOrOwnerPlayerOrPlayerItself();
return NULL;
}
Minion *Unit::GetFirstMinion() const
{
if (uint64 pet_guid = GetMinionGUID())
{
if (Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, pet_guid))
if (pet->HasUnitTypeMask(UNIT_MASK_MINION))
return (Minion*)pet;
sLog->outError(LOG_FILTER_UNITS, "Unit::GetFirstMinion: Minion %u not exist.", GUID_LOPART(pet_guid));
const_cast<Unit*>(this)->SetMinionGUID(0);
}
return NULL;
}
Guardian* Unit::GetGuardianPet() const
{
if (uint64 pet_guid = GetPetGUID())
{
if (Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, pet_guid))
if (pet->HasUnitTypeMask(UNIT_MASK_GUARDIAN))
return (Guardian*)pet;
sLog->outFatal(LOG_FILTER_UNITS, "Unit::GetGuardianPet: Guardian " UI64FMTD " not exist.", pet_guid);
const_cast<Unit*>(this)->SetPetGUID(0);
}
return NULL;
}
Unit* Unit::GetCharm() const
{
if (uint64 charm_guid = GetCharmGUID())
{
if (Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
return pet;
sLog->outError(LOG_FILTER_UNITS, "Unit::GetCharm: Charmed creature %u not exist.", GUID_LOPART(charm_guid));
const_cast<Unit*>(this)->SetUInt64Value(UNIT_FIELD_CHARM, 0);
}
return NULL;
}
void Unit::SetMinion(Minion *minion, bool apply)
{
sLog->outDebug(LOG_FILTER_UNITS, "SetMinion %u for %u, apply %u", minion->GetEntry(), GetEntry(), apply);
if (apply)
{
if (minion->GetOwnerGUID())
{
sLog->outFatal(LOG_FILTER_UNITS, "SetMinion: Minion %u is not the minion of owner %u", minion->GetEntry(), GetEntry());
return;
}
minion->SetOwnerGUID(GetGUID());
m_Controlled.insert(minion);
if (GetTypeId() == TYPEID_PLAYER)
{
minion->m_ControlledByPlayer = true;
minion->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
}
// Can only have one pet. If a new one is summoned, dismiss the old one.
if (minion->IsGuardianPet())
{
if (Guardian* oldPet = GetGuardianPet())
{
if (oldPet != minion && (oldPet->isPet() || minion->isPet() || oldPet->GetEntry() != minion->GetEntry()))
{
// remove existing minion pet
if (oldPet->isPet())
((Pet*)oldPet)->Remove(PET_SAVE_AS_CURRENT);
else
oldPet->UnSummon();
SetPetGUID(minion->GetGUID());
SetMinionGUID(0);
}
}
else
{
SetPetGUID(minion->GetGUID());
SetMinionGUID(0);
}
}
if (minion->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
{
if (AddUInt64Value(UNIT_FIELD_SUMMON, minion->GetGUID()))
{
}
}
if (minion->m_Properties && minion->m_Properties->Type == SUMMON_TYPE_MINIPET)
{
SetCritterGUID(minion->GetGUID());
}
// PvP, FFAPvP
minion->SetByteValue(UNIT_FIELD_BYTES_2, 1, GetByteValue(UNIT_FIELD_BYTES_2, 1));
// FIXME: hack, speed must be set only at follow
if (GetTypeId() == TYPEID_PLAYER && minion->isPet())
for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
minion->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
// Ghoul pets have energy instead of mana (is anywhere better place for this code?)
if (minion->IsPetGhoul())
minion->setPowerType(POWER_ENERGY);
if (GetTypeId() == TYPEID_PLAYER)
{
// Send infinity cooldown - client does that automatically but after relog cooldown needs to be set again
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(minion->GetUInt32Value(UNIT_CREATED_BY_SPELL));
if (spellInfo && (spellInfo->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE))
ToPlayer()->AddSpellAndCategoryCooldowns(spellInfo, 0, NULL, true);
}
}
else
{
if (minion->GetOwnerGUID() != GetGUID())
{
sLog->outFatal(LOG_FILTER_UNITS, "SetMinion: Minion %u is not the minion of owner %u", minion->GetEntry(), GetEntry());
return;
}
m_Controlled.erase(minion);
if (minion->m_Properties && minion->m_Properties->Type == SUMMON_TYPE_MINIPET)
{
if (GetCritterGUID() == minion->GetGUID())
SetCritterGUID(0);
}
if (minion->IsGuardianPet())
{
if (GetPetGUID() == minion->GetGUID())
SetPetGUID(0);
}
else if (minion->isTotem())
{
// All summoned by totem minions must disappear when it is removed.
if (SpellInfo const* spInfo = sSpellMgr->GetSpellInfo(minion->ToTotem()->GetSpell()))
for (int i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (spInfo->Effects[i].Effect != SPELL_EFFECT_SUMMON)
continue;
RemoveAllMinionsByEntry(spInfo->Effects[i].MiscValue);
}
}
if (GetTypeId() == TYPEID_PLAYER)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(minion->GetUInt32Value(UNIT_CREATED_BY_SPELL));
// Remove infinity cooldown
if (spellInfo && (spellInfo->Attributes & SPELL_ATTR0_DISABLED_WHILE_ACTIVE))
ToPlayer()->SendCooldownEvent(spellInfo);
}
//if (minion->HasUnitTypeMask(UNIT_MASK_GUARDIAN))
{
if (RemoveUInt64Value(UNIT_FIELD_SUMMON, minion->GetGUID()))
{
// Check if there is another minion
for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
{
// do not use this check, creature do not have charm guid
//if (GetCharmGUID() == (*itr)->GetGUID())
if (GetGUID() == (*itr)->GetCharmerGUID())
continue;
//ASSERT((*itr)->GetOwnerGUID() == GetGUID());
if ((*itr)->GetOwnerGUID() != GetGUID())
{
OutDebugInfo();
(*itr)->OutDebugInfo();
ASSERT(false);
}
ASSERT((*itr)->GetTypeId() == TYPEID_UNIT);
if (!(*itr)->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
continue;
if (AddUInt64Value(UNIT_FIELD_SUMMON, (*itr)->GetGUID()))
{
// show another pet bar if there is no charm bar
if (GetTypeId() == TYPEID_PLAYER && !GetCharmGUID())
{
if ((*itr)->isPet())
ToPlayer()->PetSpellInitialize();
else
ToPlayer()->CharmSpellInitialize();
}
}
break;
}
}
}
}
}
void Unit::GetAllMinionsByEntry(std::list<Creature*>& Minions, uint32 entry)
{
for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end();)
{
Unit* unit = *itr;
++itr;
if (unit->GetEntry() == entry && unit->GetTypeId() == TYPEID_UNIT
&& unit->ToCreature()->isSummon()) // minion, actually
Minions.push_back(unit->ToCreature());
}
}
void Unit::RemoveAllMinionsByEntry(uint32 entry)
{
for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end();)
{
Unit* unit = *itr;
++itr;
if (unit->GetEntry() == entry && unit->GetTypeId() == TYPEID_UNIT
&& unit->ToCreature()->isSummon()) // minion, actually
unit->ToTempSummon()->UnSummon();
// i think this is safe because i have never heard that a despawned minion will trigger a same minion
}
}
void Unit::SetCharm(Unit* charm, bool apply)
{
if (apply)
{
if (GetTypeId() == TYPEID_PLAYER)
{
if (!AddUInt64Value(UNIT_FIELD_CHARM, charm->GetGUID()))
sLog->outFatal(LOG_FILTER_UNITS, "Player %s is trying to charm unit %u, but it already has a charmed unit " UI64FMTD "", GetName().c_str(), charm->GetEntry(), GetCharmGUID());
charm->m_ControlledByPlayer = true;
// TODO: maybe we can use this flag to check if controlled by player
charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
}
else
charm->m_ControlledByPlayer = false;
// PvP, FFAPvP
charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, GetByteValue(UNIT_FIELD_BYTES_2, 1));
if (!charm->AddUInt64Value(UNIT_FIELD_CHARMEDBY, GetGUID()))
sLog->outFatal(LOG_FILTER_UNITS, "Unit %u is being charmed, but it already has a charmer " UI64FMTD "", charm->GetEntry(), charm->GetCharmerGUID());
_isWalkingBeforeCharm = charm->IsWalking();
if (_isWalkingBeforeCharm)
{
charm->SetWalk(false);
charm->SendMovementFlagUpdate();
}
m_Controlled.insert(charm);
}
else
{
if (GetTypeId() == TYPEID_PLAYER)
{
if (!RemoveUInt64Value(UNIT_FIELD_CHARM, charm->GetGUID()))
sLog->outFatal(LOG_FILTER_UNITS, "Player %s is trying to uncharm unit %u, but it has another charmed unit " UI64FMTD "", GetName().c_str(), charm->GetEntry(), GetCharmGUID());
}
if (!charm->RemoveUInt64Value(UNIT_FIELD_CHARMEDBY, GetGUID()))
sLog->outFatal(LOG_FILTER_UNITS, "Unit %u is being uncharmed, but it has another charmer " UI64FMTD "", charm->GetEntry(), charm->GetCharmerGUID());
if (charm->GetTypeId() == TYPEID_PLAYER)
{
charm->m_ControlledByPlayer = true;
charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
charm->ToPlayer()->UpdatePvPState();
}
else if (Player* player = charm->GetCharmerOrOwnerPlayerOrPlayerItself())
{
charm->m_ControlledByPlayer = true;
charm->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, player->GetByteValue(UNIT_FIELD_BYTES_2, 1));
}
else
{
charm->m_ControlledByPlayer = false;
charm->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
charm->SetByteValue(UNIT_FIELD_BYTES_2, 1, 0);
}
if (charm->IsWalking() != _isWalkingBeforeCharm)
{
charm->SetWalk(_isWalkingBeforeCharm);
charm->SendMovementFlagUpdate(true); // send packet to self, to update movement state on player.
}
if (charm->GetTypeId() == TYPEID_PLAYER
|| !charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_MINION)
|| charm->GetOwnerGUID() != GetGUID())
m_Controlled.erase(charm);
}
}
int32 Unit::DealHeal(Unit* victim, uint32 addhealth)
{
int32 gain = 0;
if (victim->IsAIEnabled)
victim->GetAI()->HealReceived(this, addhealth);
if (IsAIEnabled)
GetAI()->HealDone(victim, addhealth);
if (addhealth)
gain = victim->ModifyHealth(int32(addhealth));
Unit* unit = this;
if (GetTypeId() == TYPEID_UNIT && ToCreature()->isTotem())
unit = GetOwner();
if (Player* player = unit->ToPlayer())
{
if (Battleground* bg = player->GetBattleground())
bg->UpdatePlayerScore(player, SCORE_HEALING_DONE, gain);
// use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria)
if (gain)
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, 0, victim);
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth);
}
if (Player* player = victim->ToPlayer())
{
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain);
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth);
}
return gain;
}
Unit* Unit::GetMagicHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo)
{
// Patch 1.2 notes: Spell Reflection no longer reflects abilities
if (spellInfo->Attributes & SPELL_ATTR0_ABILITY || spellInfo->AttributesEx & SPELL_ATTR1_CANT_BE_REDIRECTED || spellInfo->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
return victim;
Unit::AuraEffectList const& magnetAuras = victim->GetAuraEffectsByType(SPELL_AURA_SPELL_MAGNET);
for (Unit::AuraEffectList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
{
if (Unit* magnet = (*itr)->GetBase()->GetCaster())
if (spellInfo->CheckExplicitTarget(this, magnet) == SPELL_CAST_OK
&& spellInfo->CheckTarget(this, magnet, false) == SPELL_CAST_OK
&& _IsValidAttackTarget(magnet, spellInfo))
{
// TODO: handle this charge drop by proc in cast phase on explicit target
(*itr)->GetBase()->DropCharge(AURA_REMOVE_BY_EXPIRE);
return magnet;
}
}
return victim;
}
Unit* Unit::GetMeleeHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo)
{
AuraEffectList const& hitTriggerAuras = victim->GetAuraEffectsByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
for (AuraEffectList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
{
if (Unit* magnet = (*i)->GetBase()->GetCaster())
if (_IsValidAttackTarget(magnet, spellInfo) && magnet->IsWithinLOSInMap(this)
&& (!spellInfo || (spellInfo->CheckExplicitTarget(this, magnet) == SPELL_CAST_OK
&& spellInfo->CheckTarget(this, magnet, false) == SPELL_CAST_OK)))
if (roll_chance_i((*i)->GetAmount()))
{
(*i)->GetBase()->DropCharge(AURA_REMOVE_BY_EXPIRE);
return magnet;
}
}
return victim;
}
Unit* Unit::GetFirstControlled() const
{
// Sequence: charmed, pet, other guardians
Unit* unit = GetCharm();
if (!unit)
if (uint64 guid = GetMinionGUID())
unit = ObjectAccessor::GetUnit(*this, guid);
return unit;
}
void Unit::RemoveAllControlled()
{
// possessed pet and vehicle
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->StopCastingCharm();
while (!m_Controlled.empty())
{
Unit* target = *m_Controlled.begin();
m_Controlled.erase(m_Controlled.begin());
if (target->GetCharmerGUID() == GetGUID())
target->RemoveCharmAuras();
else if (target->GetOwnerGUID() == GetGUID() && target->isSummon())
target->ToTempSummon()->UnSummon();
else
sLog->outError(LOG_FILTER_UNITS, "Unit %u is trying to release unit %u which is neither charmed nor owned by it", GetEntry(), target->GetEntry());
}
if (GetPetGUID())
sLog->outFatal(LOG_FILTER_UNITS, "Unit %u is not able to release its pet " UI64FMTD, GetEntry(), GetPetGUID());
if (GetMinionGUID())
sLog->outFatal(LOG_FILTER_UNITS, "Unit %u is not able to release its minion " UI64FMTD, GetEntry(), GetMinionGUID());
if (GetCharmGUID())
sLog->outFatal(LOG_FILTER_UNITS, "Unit %u is not able to release its charm " UI64FMTD, GetEntry(), GetCharmGUID());
}
Unit* Unit::GetNextRandomRaidMemberOrPet(float radius)
{
Player* player = NULL;
if (GetTypeId() == TYPEID_PLAYER)
player = ToPlayer();
// Should we enable this also for charmed units?
else if (GetTypeId() == TYPEID_UNIT && ToCreature()->isPet())
player = GetOwner()->ToPlayer();
if (!player)
return NULL;
Group* group = player->GetGroup();
// When there is no group check pet presence
if (!group)
{
// We are pet now, return owner
if (player != this)
return IsWithinDistInMap(player, radius) ? player : NULL;
Unit* pet = GetGuardianPet();
// No pet, no group, nothing to return
if (!pet)
return NULL;
// We are owner now, return pet
return IsWithinDistInMap(pet, radius) ? pet : NULL;
}
std::vector<Unit*> nearMembers;
// reserve place for players and pets because resizing vector every unit push is unefficient (vector is reallocated then)
nearMembers.reserve(group->GetMembersCount() * 2);
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
if (Player* Target = itr->getSource())
{
// IsHostileTo check duel and controlled by enemy
if (Target != this && Target->isAlive() && IsWithinDistInMap(Target, radius) && !IsHostileTo(Target))
nearMembers.push_back(Target);
// Push player's pet to vector
if (Unit* pet = Target->GetGuardianPet())
if (pet != this && pet->isAlive() && IsWithinDistInMap(pet, radius) && !IsHostileTo(pet))
nearMembers.push_back(pet);
}
if (nearMembers.empty())
return NULL;
uint32 randTarget = urand(0, nearMembers.size()-1);
return nearMembers[randTarget];
}
// only called in Player::SetSeer
// so move it to Player?
void Unit::AddPlayerToVision(Player* player)
{
if (m_sharedVision.empty())
{
setActive(true);
SetWorldObject(true);
}
m_sharedVision.push_back(player);
}
// only called in Player::SetSeer
void Unit::RemovePlayerFromVision(Player* player)
{
m_sharedVision.remove(player);
if (m_sharedVision.empty())
{
setActive(false);
SetWorldObject(false);
}
}
void Unit::RemoveBindSightAuras()
{
RemoveAurasByType(SPELL_AURA_BIND_SIGHT);
}
void Unit::RemoveCharmAuras()
{
RemoveAurasByType(SPELL_AURA_MOD_CHARM);
RemoveAurasByType(SPELL_AURA_MOD_POSSESS_PET);
RemoveAurasByType(SPELL_AURA_MOD_POSSESS);
RemoveAurasByType(SPELL_AURA_AOE_CHARM);
}
void Unit::UnsummonAllTotems()
{
for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
{
if (!m_SummonSlot[i])
continue;
if (Creature* OldTotem = GetMap()->GetCreature(m_SummonSlot[i]))
if (OldTotem->isSummon())
OldTotem->ToTempSummon()->UnSummon();
}
}
void Unit::SendHealSpellLog(Unit* victim, uint32 SpellID, uint32 Damage, uint32 OverHeal, uint32 Absorb, bool critical)
{
// we guess size
WorldPacket data(SMSG_SPELLHEALLOG, 8+8+4+4+4+4+1+1);
data.append(victim->GetPackGUID());
data.append(GetPackGUID());
data << uint32(SpellID);
data << uint32(Damage);
data << uint32(OverHeal);
data << uint32(Absorb); // Absorb amount
data << uint8(critical ? 1 : 0);
data << uint8(0); // unused
SendMessageToSet(&data, true);
}
int32 Unit::HealBySpell(Unit* victim, SpellInfo const* spellInfo, uint32 addHealth, bool critical)
{
uint32 absorb = 0;
// calculate heal absorb and reduce healing
CalcHealAbsorb(victim, spellInfo, addHealth, absorb);
int32 gain = DealHeal(victim, addHealth);
SendHealSpellLog(victim, spellInfo->Id, addHealth, uint32(addHealth - gain), absorb, critical);
return gain;
}
void Unit::SendEnergizeSpellLog(Unit* victim, uint32 spellID, uint32 damage, Powers powerType)
{
WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
data.append(victim->GetPackGUID());
data.append(GetPackGUID());
data << uint32(spellID);
data << uint32(powerType);
data << uint32(damage);
SendMessageToSet(&data, true);
}
void Unit::EnergizeBySpell(Unit* victim, uint32 spellID, int32 damage, Powers powerType)
{
SendEnergizeSpellLog(victim, spellID, damage, powerType);
// needs to be called after sending spell log
victim->ModifyPower(powerType, damage);
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellID);
victim->getHostileRefManager().threatAssist(this, float(damage) * 0.5f, spellInfo);
}
uint32 Unit::SpellDamageBonusDone(Unit* victim, SpellInfo const* spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
{
if (!spellProto || !victim || damagetype == DIRECT_DAMAGE)
return pdamage;
// Some spells don't benefit from done mods
if (spellProto->AttributesEx3 & SPELL_ATTR3_NO_DONE_BONUS)
return pdamage;
// small exception for Deep Wounds, can't find any general rule
// should ignore ALL damage mods, they already calculated in trigger spell
if (spellProto->Id == 12721) // Deep Wounds
return pdamage;
// For totems get damage bonus from owner
if (GetTypeId() == TYPEID_UNIT && ToCreature()->isTotem())
if (Unit* owner = GetOwner())
return owner->SpellDamageBonusDone(victim, spellProto, pdamage, damagetype);
// Done total percent damage auras
float DoneTotalMod = 1.0f;
float ApCoeffMod = 1.0f;
int32 DoneTotal = 0;
// Pet damage?
if (GetTypeId() == TYPEID_UNIT && !ToCreature()->isPet())
DoneTotalMod *= ToCreature()->GetSpellDamageMod(ToCreature()->GetCreatureTemplate()->rank);
// Some spells don't benefit from pct done mods
if (!(spellProto->AttributesEx6 & SPELL_ATTR6_NO_DONE_PCT_DAMAGE_MODS) && !spellProto->IsRankOf(sSpellMgr->GetSpellInfo(12162)))
{
AuraEffectList const& mModDamagePercentDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
for (AuraEffectList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
{
if (spellProto->EquippedItemClass == -1 && (*i)->GetSpellInfo()->EquippedItemClass != -1) //prevent apply mods from weapon specific case to non weapon specific spells (Example: thunder clap and two-handed weapon specialization)
continue;
if ((*i)->GetMiscValue() & spellProto->GetSchoolMask())
{
if ((*i)->GetSpellInfo()->EquippedItemClass == -1)
AddPct(DoneTotalMod, (*i)->GetAmount());
else if (!((*i)->GetSpellInfo()->AttributesEx5 & SPELL_ATTR5_SPECIAL_ITEM_CLASS_CHECK) && ((*i)->GetSpellInfo()->EquippedItemSubClassMask == 0))
AddPct(DoneTotalMod, (*i)->GetAmount());
else if (ToPlayer() && ToPlayer()->HasItemFitToSpellRequirements((*i)->GetSpellInfo()))
AddPct(DoneTotalMod, (*i)->GetAmount());
}
}
}
uint32 creatureTypeMask = victim->GetCreatureTypeMask();
// Add flat bonus from spell damage versus
DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
AuraEffectList const& mDamageDoneVersus = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
for (AuraEffectList::const_iterator i = mDamageDoneVersus.begin(); i != mDamageDoneVersus.end(); ++i)
if (creatureTypeMask & uint32((*i)->GetMiscValue()))
AddPct(DoneTotalMod, (*i)->GetAmount());
// bonus against aurastate
AuraEffectList const& mDamageDoneVersusAurastate = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS_AURASTATE);
for (AuraEffectList::const_iterator i = mDamageDoneVersusAurastate.begin(); i != mDamageDoneVersusAurastate.end(); ++i)
if (victim->HasAuraState(AuraStateType((*i)->GetMiscValue())))
AddPct(DoneTotalMod, (*i)->GetAmount());
// Add SPELL_AURA_MOD_DAMAGE_DONE_FOR_MECHANIC percent bonus
AddPct(DoneTotalMod, GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DAMAGE_DONE_FOR_MECHANIC, spellProto->Mechanic));
// done scripted mod (take it from owner)
Unit* owner = GetOwner() ? GetOwner() : this;
AuraEffectList const& mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
{
if (!(*i)->IsAffectingSpell(spellProto))
continue;
switch ((*i)->GetMiscValue())
{
case 4920: // Molten Fury
case 4919:
{
if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
AddPct(DoneTotalMod, (*i)->GetAmount());
break;
}
case 6917: // Death's Embrace damage effect
case 6926:
case 6928:
{
// Health at 25% or less (25% stored at effect 2 of the spell)
if (victim->HealthBelowPct(CalculateSpellDamage(this, (*i)->GetSpellInfo(), EFFECT_2)))
AddPct(DoneTotalMod, (*i)->GetAmount());
}
case 6916: // Death's Embrace heal effect
case 6925:
case 6927:
if (HealthBelowPct(CalculateSpellDamage(this, (*i)->GetSpellInfo(), EFFECT_2)))
AddPct(DoneTotalMod, (*i)->GetAmount());
break;
// Soul Siphon
case 4992:
case 4993:
{
// effect 1 m_amount
int32 maxPercent = (*i)->GetAmount();
// effect 0 m_amount
int32 stepPercent = CalculateSpellDamage(this, (*i)->GetSpellInfo(), 0);
// count affliction effects and calc additional damage in percentage
int32 modPercent = 0;
AuraApplicationMap const& victimAuras = victim->GetAppliedAuras();
for (AuraApplicationMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
{
Aura const* aura = itr->second->GetBase();
SpellInfo const* spell = aura->GetSpellInfo();
if (spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(spell->SpellFamilyFlags[1] & 0x0004071B || spell->SpellFamilyFlags[0] & 0x8044C402))
continue;
modPercent += stepPercent * aura->GetStackAmount();
if (modPercent >= maxPercent)
{
modPercent = maxPercent;
break;
}
}
AddPct(DoneTotalMod, modPercent);
break;
}
case 5481: // Starfire Bonus
{
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x200002, 0, 0))
AddPct(DoneTotalMod, (*i)->GetAmount());
break;
}
case 4418: // Increased Shock Damage
case 4554: // Increased Lightning Damage
case 4555: // Improved Moonfire
case 5142: // Increased Lightning Damage
case 5147: // Improved Consecration / Libram of Resurgence
case 5148: // Idol of the Shooting Star
case 6008: // Increased Lightning Damage
case 8627: // Totem of Hex
{
DoneTotal += (*i)->GetAmount();
break;
}
}
}
// Custom scripted damage
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_MAGE:
// Ice Lance
if (spellProto->SpellIconID == 186)
if (victim->HasAuraState(AURA_STATE_FROZEN, spellProto, this))
DoneTotalMod *= 2.0f;
// Torment the weak
if (spellProto->GetSchoolMask() & SPELL_SCHOOL_MASK_ARCANE)
{
if (victim->HasAuraWithMechanic((1<<MECHANIC_SNARE)|(1<<MECHANIC_SLOW_ATTACK)))
{
AuraEffectList const& mDumyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (AuraEffectList::const_iterator i = mDumyAuras.begin(); i != mDumyAuras.end(); ++i)
{
if ((*i)->GetSpellInfo()->SpellIconID == 2215)
{
AddPct(DoneTotalMod, (*i)->GetAmount());
break;
}
}
}
}
break;
case SPELLFAMILY_PRIEST:
// Smite
if (spellProto->SpellFamilyFlags[0] & 0x80)
{
// Glyph of Smite
if (AuraEffect* aurEff = GetAuraEffect(55692, 0))
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x100000, 0, 0, GetGUID()))
AddPct(DoneTotalMod, aurEff->GetAmount());
}
break;
case SPELLFAMILY_WARLOCK:
// Fire and Brimstone
if (spellProto->SpellFamilyFlags[1] & 0x00020040)
if (victim->HasAuraState(AURA_STATE_CONFLAGRATE))
{
AuraEffectList const& mDumyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (AuraEffectList::const_iterator i = mDumyAuras.begin(); i != mDumyAuras.end(); ++i)
if ((*i)->GetSpellInfo()->SpellIconID == 3173)
{
AddPct(DoneTotalMod, (*i)->GetAmount());
break;
}
}
// Drain Soul - increased damage for targets under 25 % HP
if (spellProto->SpellFamilyFlags[0] & 0x00004000)
if (HasAura(100001))
DoneTotalMod *= 2;
// Shadow Bite (30% increase from each dot)
if (spellProto->SpellFamilyFlags[1] & 0x00400000 && isPet())
if (uint8 count = victim->GetDoTsByCaster(GetOwnerGUID()))
AddPct(DoneTotalMod, 30 * count);
break;
case SPELLFAMILY_DEATHKNIGHT:
// Sigil of the Vengeful Heart
if (spellProto->SpellFamilyFlags[0] & 0x2000)
if (AuraEffect* aurEff = GetAuraEffect(64962, EFFECT_1))
DoneTotal += aurEff->GetAmount();
break;
}
// Done fixed damage bonus auras
int32 DoneAdvertisedBenefit = SpellBaseDamageBonusDone(spellProto->GetSchoolMask());
// Pets just add their bonus damage to their spell damage
// note that their spell damage is just gain of their own auras
if (HasUnitTypeMask(UNIT_MASK_GUARDIAN))
DoneAdvertisedBenefit += ((Guardian*)this)->GetBonusDamage();
// Check for table values
float coeff = 0;
SpellBonusEntry const* bonus = sSpellMgr->GetSpellBonusData(spellProto->Id);
if (bonus)
{
if (damagetype == DOT)
{
coeff = bonus->dot_damage;
if (bonus->ap_dot_bonus > 0)
{
WeaponAttackType attType = (spellProto->IsRangedWeaponSpell() && spellProto->DmgClass != SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK;
float APbonus = float(victim->GetTotalAuraModifier(attType == BASE_ATTACK ? SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS : SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS));
APbonus += GetTotalAttackPowerValue(attType);
DoneTotal += int32(bonus->ap_dot_bonus * stack * ApCoeffMod * APbonus);
}
}
else
{
coeff = bonus->direct_damage;
if (bonus->ap_bonus > 0)
{
WeaponAttackType attType = (spellProto->IsRangedWeaponSpell() && spellProto->DmgClass != SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK;
float APbonus = float(victim->GetTotalAuraModifier(attType == BASE_ATTACK ? SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS : SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS));
APbonus += GetTotalAttackPowerValue(attType);
DoneTotal += int32(bonus->ap_bonus * stack * ApCoeffMod * APbonus);
}
}
}
// Default calculation
if (DoneAdvertisedBenefit)
{
if (!bonus || coeff < 0)
coeff = CalculateDefaultCoefficient(spellProto, damagetype) * int32(stack);
float factorMod = CalculateLevelPenalty(spellProto) * stack;
if (Player* modOwner = GetSpellModOwner())
{
coeff *= 100.0f;
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff);
coeff /= 100.0f;
}
DoneTotal += int32(DoneAdvertisedBenefit * coeff * factorMod);
}
float tmpDamage = (int32(pdamage) + DoneTotal) * DoneTotalMod;
// apply spellmod to Done damage (flat and pct)
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
return uint32(std::max(tmpDamage, 0.0f));
}
uint32 Unit::SpellDamageBonusTaken(Unit* caster, SpellInfo const* spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
{
if (!spellProto || damagetype == DIRECT_DAMAGE)
return pdamage;
int32 TakenTotal = 0;
float TakenTotalMod = 1.0f;
float TakenTotalCasterMod = 0.0f;
// get all auras from caster that allow the spell to ignore resistance (sanctified wrath)
AuraEffectList const& IgnoreResistAuras = caster->GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST);
for (AuraEffectList::const_iterator i = IgnoreResistAuras.begin(); i != IgnoreResistAuras.end(); ++i)
{
if ((*i)->GetMiscValue() & spellProto->GetSchoolMask())
TakenTotalCasterMod += (float((*i)->GetAmount()));
}
// from positive and negative SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN
// multiplicative bonus, for example Dispersion + Shadowform (0.10*0.85=0.085)
TakenTotalMod *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, spellProto->GetSchoolMask());
//.. taken pct: dummy auras
AuraEffectList const& mDummyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (AuraEffectList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
{
switch ((*i)->GetSpellInfo()->SpellIconID)
{
// Cheat Death
case 2109:
if ((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
{
if (GetTypeId() != TYPEID_PLAYER)
continue;
AddPct(TakenTotalMod, (*i)->GetAmount());
}
break;
}
}
// From caster spells
AuraEffectList const& mOwnerTaken = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
for (AuraEffectList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
if ((*i)->GetCasterGUID() == caster->GetGUID() && (*i)->IsAffectingSpell(spellProto))
AddPct(TakenTotalMod, (*i)->GetAmount());
// Mod damage from spell mechanic
if (uint32 mechanicMask = spellProto->GetAllEffectsMechanicMask())
{
AuraEffectList const& mDamageDoneMechanic = GetAuraEffectsByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
for (AuraEffectList::const_iterator i = mDamageDoneMechanic.begin(); i != mDamageDoneMechanic.end(); ++i)
if (mechanicMask & uint32(1<<((*i)->GetMiscValue())))
AddPct(TakenTotalMod, (*i)->GetAmount());
}
int32 TakenAdvertisedBenefit = SpellBaseDamageBonusTaken(spellProto->GetSchoolMask());
// Check for table values
float coeff = 0;
SpellBonusEntry const* bonus = sSpellMgr->GetSpellBonusData(spellProto->Id);
if (bonus)
coeff = (damagetype == DOT) ? bonus->dot_damage : bonus->direct_damage;
// Default calculation
if (TakenAdvertisedBenefit)
{
if (!bonus || coeff < 0)
coeff = CalculateDefaultCoefficient(spellProto, damagetype) * int32(stack);
float factorMod = CalculateLevelPenalty(spellProto) * stack;
// level penalty still applied on Taken bonus - is it blizzlike?
if (Player* modOwner = GetSpellModOwner())
{
coeff *= 100.0f;
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff);
coeff /= 100.0f;
}
TakenTotal+= int32(TakenAdvertisedBenefit * coeff * factorMod);
}
float tmpDamage = 0.0f;
if (TakenTotalCasterMod)
{
if (TakenTotal < 0)
{
if (TakenTotalMod < 1)
tmpDamage = ((float(CalculatePct(pdamage, TakenTotalCasterMod) + TakenTotal) * TakenTotalMod) + CalculatePct(pdamage, TakenTotalCasterMod));
else
tmpDamage = ((float(CalculatePct(pdamage, TakenTotalCasterMod) + TakenTotal) + CalculatePct(pdamage, TakenTotalCasterMod)) * TakenTotalMod);
}
else if (TakenTotalMod < 1)
tmpDamage = ((CalculatePct(float(pdamage) + TakenTotal, TakenTotalCasterMod) * TakenTotalMod) + CalculatePct(float(pdamage) + TakenTotal, TakenTotalCasterMod));
}
if (!tmpDamage)
tmpDamage = (float(pdamage) + TakenTotal) * TakenTotalMod;
return uint32(std::max(tmpDamage, 0.0f));
}
int32 Unit::SpellBaseDamageBonusDone(SpellSchoolMask schoolMask)
{
int32 DoneAdvertisedBenefit = 0;
AuraEffectList const& mDamageDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE);
for (AuraEffectList::const_iterator i = mDamageDone.begin(); i != mDamageDone.end(); ++i)
if (((*i)->GetMiscValue() & schoolMask) != 0 &&
(*i)->GetSpellInfo()->EquippedItemClass == -1 &&
// -1 == any item class (not wand then)
(*i)->GetSpellInfo()->EquippedItemInventoryTypeMask == 0)
// 0 == any inventory type (not wand then)
DoneAdvertisedBenefit += (*i)->GetAmount();
if (GetTypeId() == TYPEID_PLAYER)
{
// Base value
DoneAdvertisedBenefit += ToPlayer()->GetBaseSpellPowerBonus();
// Check if we are ever using mana - PaperDollFrame.lua
if (GetPowerIndex(POWER_MANA) != MAX_POWERS)
DoneAdvertisedBenefit += std::max(0, int32(GetStat(STAT_INTELLECT)) - 10); // spellpower from intellect
// Damage bonus from stats
AuraEffectList const& mDamageDoneOfStatPercent = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
for (AuraEffectList::const_iterator i = mDamageDoneOfStatPercent.begin(); i != mDamageDoneOfStatPercent.end(); ++i)
{
if ((*i)->GetMiscValue() & schoolMask)
{
// stat used stored in miscValueB for this aura
Stats usedStat = Stats((*i)->GetMiscValueB());
DoneAdvertisedBenefit += int32(CalculatePct(GetStat(usedStat), (*i)->GetAmount()));
}
}
// ... and attack power
AuraEffectList const& mDamageDonebyAP = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
for (AuraEffectList::const_iterator i =mDamageDonebyAP.begin(); i != mDamageDonebyAP.end(); ++i)
if ((*i)->GetMiscValue() & schoolMask)
DoneAdvertisedBenefit += int32(CalculatePct(GetTotalAttackPowerValue(BASE_ATTACK), (*i)->GetAmount()));
}
return DoneAdvertisedBenefit;
}
int32 Unit::SpellBaseDamageBonusTaken(SpellSchoolMask schoolMask)
{
int32 TakenAdvertisedBenefit = 0;
AuraEffectList const& mDamageTaken = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i)
if (((*i)->GetMiscValue() & schoolMask) != 0)
TakenAdvertisedBenefit += (*i)->GetAmount();
return TakenAdvertisedBenefit;
}
bool Unit::isSpellCrit(Unit* victim, SpellInfo const* spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType) const
{
//! Mobs can't crit with spells. Player Totems can
//! Fire Elemental (from totem) can too - but this part is a hack and needs more research
if (IS_CREATURE_GUID(GetGUID()) && !(isTotem() && IS_PLAYER_GUID(GetOwnerGUID())) && GetEntry() != 15438)
return false;
// not critting spell
if ((spellProto->AttributesEx2 & SPELL_ATTR2_CANT_CRIT))
return false;
float crit_chance = 0.0f;
switch (spellProto->DmgClass)
{
case SPELL_DAMAGE_CLASS_NONE:
// We need more spells to find a general way (if there is any)
switch (spellProto->Id)
{
case 379: // Earth Shield
case 33778: // Lifebloom Final Bloom
case 64844: // Divine Hymn
case 71607: // Item - Bauble of True Blood 10m
case 71646: // Item - Bauble of True Blood 25m
break;
default:
return false;
}
case SPELL_DAMAGE_CLASS_MAGIC:
{
if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
crit_chance = 0.0f;
// For other schools
else if (GetTypeId() == TYPEID_PLAYER)
crit_chance = GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
else
{
crit_chance = (float)m_baseSpellCritChance;
crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
}
// taken
if (victim)
{
if (!spellProto->IsPositive())
{
// Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
crit_chance += victim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
// Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
crit_chance += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
}
// scripted (increase crit chance ... against ... target by x%
AuraEffectList const& mOverrideClassScript = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
{
if (!((*i)->IsAffectingSpell(spellProto)))
continue;
switch ((*i)->GetMiscValue())
{
// Shatter
case 911:
if (!victim->HasAuraState(AURA_STATE_FROZEN, spellProto, this))
break;
AddPct(crit_chance, (*i)->GetAmount()*20);
break;
case 7917: // Glyph of Shadowburn
if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this))
crit_chance+=(*i)->GetAmount();
break;
case 7997: // Renewed Hope
case 7998:
if (victim->HasAura(6788))
crit_chance+=(*i)->GetAmount();
break;
default:
break;
}
}
// Custom crit by class
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_MAGE:
// Glyph of Fire Blast
if (spellProto->SpellFamilyFlags[0] == 0x2 && spellProto->SpellIconID == 12)
if (victim->HasAuraWithMechanic((1<<MECHANIC_STUN) | (1<<MECHANIC_KNOCKOUT)))
if (AuraEffect const* aurEff = GetAuraEffect(56369, EFFECT_0))
crit_chance += aurEff->GetAmount();
break;
case SPELLFAMILY_DRUID:
// Improved Faerie Fire
if (victim->HasAuraState(AURA_STATE_FAERIE_FIRE))
if (AuraEffect const* aurEff = GetDummyAuraEffect(SPELLFAMILY_DRUID, 109, 0))
crit_chance += aurEff->GetAmount();
// cumulative effect - don't break
// Starfire
if (spellProto->SpellFamilyFlags[0] & 0x4 && spellProto->SpellIconID == 1485)
{
// Improved Insect Swarm
if (AuraEffect const* aurEff = GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0))
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00000002, 0, 0))
crit_chance += aurEff->GetAmount();
break;
}
break;
case SPELLFAMILY_ROGUE:
// Shiv-applied poisons can't crit
if (FindCurrentSpellBySpellId(5938))
crit_chance = 0.0f;
break;
case SPELLFAMILY_PALADIN:
// Flash of light
if (spellProto->SpellFamilyFlags[0] & 0x40000000)
{
// Sacred Shield
if (AuraEffect const* aura = victim->GetAuraEffect(58597, 1, GetGUID()))
crit_chance += aura->GetAmount();
break;
}
// Exorcism
else if (spellProto->Category == 19)
{
if (victim->GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD)
return true;
break;
}
break;
case SPELLFAMILY_SHAMAN:
// Lava Burst
if (spellProto->SpellFamilyFlags[1] & 0x00001000)
{
if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x10000000, 0, 0, GetGUID()))
if (victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE) > -100)
return true;
break;
}
break;
}
}
break;
}
case SPELL_DAMAGE_CLASS_MELEE:
if (victim)
{
// Custom crit by class
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_DRUID:
// Rend and Tear - bonus crit chance for Ferocious Bite on bleeding targets
if (spellProto->SpellFamilyFlags[0] & 0x00800000
&& spellProto->SpellIconID == 1680
&& victim->HasAuraState(AURA_STATE_BLEEDING))
{
if (AuraEffect const* rendAndTear = GetDummyAuraEffect(SPELLFAMILY_DRUID, 2859, 1))
crit_chance += rendAndTear->GetAmount();
break;
}
break;
case SPELLFAMILY_WARRIOR:
// Victory Rush
if (spellProto->SpellFamilyFlags[1] & 0x100)
{
// Glyph of Victory Rush
if (AuraEffect const* aurEff = GetAuraEffect(58382, 0))
crit_chance += aurEff->GetAmount();
break;
}
break;
}
}
case SPELL_DAMAGE_CLASS_RANGED:
{
if (victim)
{
crit_chance += GetUnitCriticalChance(attackType, victim);
crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
}
break;
}
default:
return false;
}
// percent done
// only players use intelligence for critical chance computations
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
AuraEffectList const& critAuras = victim->GetAuraEffectsByType(SPELL_AURA_MOD_CRIT_CHANCE_FOR_CASTER);
for (AuraEffectList::const_iterator i = critAuras.begin(); i != critAuras.end(); ++i)
if ((*i)->GetCasterGUID() == GetGUID() && (*i)->IsAffectingSpell(spellProto))
crit_chance += (*i)->GetAmount();
crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
if (roll_chance_f(crit_chance))
return true;
return false;
}
uint32 Unit::SpellCriticalDamageBonus(SpellInfo const* spellProto, uint32 damage, Unit* /*victim*/)
{
// Calculate critical bonus
int32 crit_bonus = damage;
float crit_mod = 0.0f;
switch (spellProto->DmgClass)
{
case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
case SPELL_DAMAGE_CLASS_RANGED:
// TODO: write here full calculation for melee/ranged spells
crit_bonus += damage;
break;
default:
crit_bonus += damage / 2; // for spells is 50%
break;
}
crit_mod += (GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, spellProto->GetSchoolMask()) - 1.0f) * 100;
if (crit_bonus != 0)
AddPct(crit_bonus, crit_mod);
crit_bonus -= damage;
if (damage > uint32(crit_bonus))
{
// adds additional damage to critBonus (from talents)
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
}
crit_bonus += damage;
return crit_bonus;
}
uint32 Unit::SpellCriticalHealingBonus(SpellInfo const* /*spellProto*/, uint32 damage, Unit* /*victim*/)
{
// Calculate critical bonus
int32 crit_bonus = damage;
damage += crit_bonus;
damage = int32(float(damage) * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT));
return damage;
}
uint32 Unit::SpellHealingBonusDone(Unit* victim, SpellInfo const* spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
{
// For totems get healing bonus from owner (statue isn't totem in fact)
if (GetTypeId() == TYPEID_UNIT && isTotem())
if (Unit* owner = GetOwner())
return owner->SpellHealingBonusDone(victim, spellProto, healamount, damagetype, stack);
// No bonus healing for potion spells
if (spellProto->SpellFamilyName == SPELLFAMILY_POTION)
return healamount;
float DoneTotalMod = 1.0f;
int32 DoneTotal = 0;
// Healing done percent
AuraEffectList const& mHealingDonePct = GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
for (AuraEffectList::const_iterator i = mHealingDonePct.begin(); i != mHealingDonePct.end(); ++i)
AddPct(DoneTotalMod, (*i)->GetAmount());
// done scripted mod (take it from owner)
Unit* owner = GetOwner() ? GetOwner() : this;
AuraEffectList const& mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
{
if (!(*i)->IsAffectingSpell(spellProto))
continue;
switch ((*i)->GetMiscValue())
{
case 4415: // Increased Rejuvenation Healing
case 4953:
case 3736: // Hateful Totem of the Third Wind / Increased Lesser Healing Wave / LK Arena (4/5/6) Totem of the Third Wind / Savage Totem of the Third Wind
DoneTotal += (*i)->GetAmount();
break;
case 21: // Test of Faith
case 6935:
case 6918:
if (victim->HealthBelowPct(50))
AddPct(DoneTotalMod, (*i)->GetAmount());
break;
case 8477: // Nourish Heal Boost
{
int32 stepPercent = (*i)->GetAmount();
int32 modPercent = 0;
AuraApplicationMap const& victimAuras = victim->GetAppliedAuras();
for (AuraApplicationMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
{
Aura const* aura = itr->second->GetBase();
if (aura->GetCasterGUID() != GetGUID())
continue;
SpellInfo const* m_spell = aura->GetSpellInfo();
if (m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
!(m_spell->SpellFamilyFlags[1] & 0x00000010 || m_spell->SpellFamilyFlags[0] & 0x50))
continue;
modPercent += stepPercent * aura->GetStackAmount();
}
AddPct(DoneTotalMod, modPercent);
break;
}
default:
break;
}
}
// Done fixed damage bonus auras
int32 DoneAdvertisedBenefit = SpellBaseHealingBonusDone(spellProto->GetSchoolMask());
// Check for table values
SpellBonusEntry const* bonus = sSpellMgr->GetSpellBonusData(spellProto->Id);
float coeff = 0;
float factorMod = 1.0f;
if (bonus)
{
if (damagetype == DOT)
{
coeff = bonus->dot_damage;
if (bonus->ap_dot_bonus > 0)
DoneTotal += int32(bonus->ap_dot_bonus * stack * GetTotalAttackPowerValue(
(spellProto->IsRangedWeaponSpell() && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK));
}
else
{
coeff = bonus->direct_damage;
if (bonus->ap_bonus > 0)
DoneTotal += int32(bonus->ap_bonus * stack * GetTotalAttackPowerValue(
(spellProto->IsRangedWeaponSpell() && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK));
}
}
else
{
// No bonus healing for SPELL_DAMAGE_CLASS_NONE class spells by default
if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
return healamount;
}
// Default calculation
if (DoneAdvertisedBenefit)
{
if (!bonus || coeff < 0)
coeff = CalculateDefaultCoefficient(spellProto, damagetype) * int32(stack) * 1.88f; // As wowwiki says: C = (Cast Time / 3.5) * 1.88 (for healing spells)
factorMod *= CalculateLevelPenalty(spellProto) * stack;
if (Player* modOwner = GetSpellModOwner())
{
coeff *= 100.0f;
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff);
coeff /= 100.0f;
}
DoneTotal += int32(DoneAdvertisedBenefit * coeff * factorMod);
}
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
switch (spellProto->Effects[i].ApplyAuraName)
{
// Bonus healing does not apply to these spells
case SPELL_AURA_PERIODIC_LEECH:
case SPELL_AURA_PERIODIC_HEALTH_FUNNEL:
DoneTotal = 0;
break;
}
if (spellProto->Effects[i].Effect == SPELL_EFFECT_HEALTH_LEECH)
DoneTotal = 0;
}
// use float as more appropriate for negative values and percent applying
float heal = float(int32(healamount) + DoneTotal) * DoneTotalMod;
// apply spellmod to Done amount
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
return uint32(std::max(heal, 0.0f));
}
uint32 Unit::SpellHealingBonusTaken(Unit* caster, SpellInfo const* spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
{
float TakenTotalMod = 1.0f;
// Healing taken percent
float minval = float(GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT));
if (minval)
AddPct(TakenTotalMod, minval);
float maxval = float(GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT));
if (maxval)
AddPct(TakenTotalMod, maxval);
// Tenacity increase healing % taken
if (AuraEffect const* Tenacity = GetAuraEffect(58549, 0))
AddPct(TakenTotalMod, Tenacity->GetAmount());
// Healing Done
int32 TakenTotal = 0;
// Taken fixed damage bonus auras
int32 TakenAdvertisedBenefit = SpellBaseHealingBonusTaken(spellProto->GetSchoolMask());
// Nourish cast
if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags[1] & 0x2000000)
{
// Rejuvenation, Regrowth, Lifebloom, or Wild Growth
if (GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x50, 0x4000010, 0))
// increase healing by 20%
TakenTotalMod *= 1.2f;
}
// Check for table values
SpellBonusEntry const* bonus = sSpellMgr->GetSpellBonusData(spellProto->Id);
float coeff = 0;
float factorMod = 1.0f;
if (bonus)
coeff = (damagetype == DOT) ? bonus->dot_damage : bonus->direct_damage;
else
{
// No bonus healing for SPELL_DAMAGE_CLASS_NONE class spells by default
if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
{
healamount = uint32(std::max((float(healamount) * TakenTotalMod), 0.0f));
return healamount;
}
}
// Default calculation
if (TakenAdvertisedBenefit)
{
if (!bonus || coeff < 0)
coeff = CalculateDefaultCoefficient(spellProto, damagetype) * int32(stack) * 1.88f; // As wowwiki says: C = (Cast Time / 3.5) * 1.88 (for healing spells)
factorMod *= CalculateLevelPenalty(spellProto) * int32(stack);
if (Player* modOwner = GetSpellModOwner())
{
coeff *= 100.0f;
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff);
coeff /= 100.0f;
}
TakenTotal += int32(TakenAdvertisedBenefit * coeff * factorMod);
}
AuraEffectList const& mHealingGet= GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_RECEIVED);
for (AuraEffectList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
if (caster->GetGUID() == (*i)->GetCasterGUID() && (*i)->IsAffectingSpell(spellProto))
AddPct(TakenTotalMod, (*i)->GetAmount());
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
switch (spellProto->Effects[i].ApplyAuraName)
{
// Bonus healing does not apply to these spells
case SPELL_AURA_PERIODIC_LEECH:
case SPELL_AURA_PERIODIC_HEALTH_FUNNEL:
TakenTotal = 0;
break;
}
if (spellProto->Effects[i].Effect == SPELL_EFFECT_HEALTH_LEECH)
TakenTotal = 0;
}
float heal = float(int32(healamount) + TakenTotal) * TakenTotalMod;
return uint32(std::max(heal, 0.0f));
}
int32 Unit::SpellBaseHealingBonusDone(SpellSchoolMask schoolMask)
{
int32 AdvertisedBenefit = 0;
AuraEffectList const& mHealingDone = GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_DONE);
for (AuraEffectList::const_iterator i = mHealingDone.begin(); i != mHealingDone.end(); ++i)
if (!(*i)->GetMiscValue() || ((*i)->GetMiscValue() & schoolMask) != 0)
AdvertisedBenefit += (*i)->GetAmount();
// Healing bonus of spirit, intellect and strength
if (GetTypeId() == TYPEID_PLAYER)
{
// Base value
AdvertisedBenefit += ToPlayer()->GetBaseSpellPowerBonus();
// Check if we are ever using mana - PaperDollFrame.lua
if (GetPowerIndex(POWER_MANA) != MAX_POWERS)
AdvertisedBenefit += std::max(0, int32(GetStat(STAT_INTELLECT)) - 10); // spellpower from intellect
// Healing bonus from stats
AuraEffectList const& mHealingDoneOfStatPercent = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
for (AuraEffectList::const_iterator i = mHealingDoneOfStatPercent.begin(); i != mHealingDoneOfStatPercent.end(); ++i)
{
// stat used dependent from misc value (stat index)
Stats usedStat = Stats((*i)->GetSpellInfo()->Effects[(*i)->GetEffIndex()].MiscValue);
AdvertisedBenefit += int32(CalculatePct(GetStat(usedStat), (*i)->GetAmount()));
}
// ... and attack power
AuraEffectList const& mHealingDonebyAP = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
for (AuraEffectList::const_iterator i = mHealingDonebyAP.begin(); i != mHealingDonebyAP.end(); ++i)
if ((*i)->GetMiscValue() & schoolMask)
AdvertisedBenefit += int32(CalculatePct(GetTotalAttackPowerValue(BASE_ATTACK), (*i)->GetAmount()));
}
return AdvertisedBenefit;
}
int32 Unit::SpellBaseHealingBonusTaken(SpellSchoolMask schoolMask)
{
int32 AdvertisedBenefit = 0;
AuraEffectList const& mDamageTaken = GetAuraEffectsByType(SPELL_AURA_MOD_HEALING);
for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i)
if (((*i)->GetMiscValue() & schoolMask) != 0)
AdvertisedBenefit += (*i)->GetAmount();
return AdvertisedBenefit;
}
bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
{
// If m_immuneToSchool type contain this school type, IMMUNE damage.
SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
if (itr->type & shoolMask)
return true;
// If m_immuneToDamage type contain magic, IMMUNE damage.
SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
if (itr->type & shoolMask)
return true;
return false;
}
bool Unit::IsImmunedToDamage(SpellInfo const* spellInfo)
{
if (spellInfo->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
return false;
uint32 shoolMask = spellInfo->GetSchoolMask();
if (spellInfo->Id != 42292 && spellInfo->Id != 59752)
{
// If m_immuneToSchool type contain this school type, IMMUNE damage.
SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
if (itr->type & shoolMask && !spellInfo->CanPierceImmuneAura(sSpellMgr->GetSpellInfo(itr->spellId)))
return true;
}
// If m_immuneToDamage type contain magic, IMMUNE damage.
SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
if (itr->type & shoolMask)
return true;
return false;
}
bool Unit::IsImmunedToSpell(SpellInfo const* spellInfo)
{
if (!spellInfo)
return false;
// Single spell immunity.
SpellImmuneList const& idList = m_spellImmune[IMMUNITY_ID];
for (SpellImmuneList::const_iterator itr = idList.begin(); itr != idList.end(); ++itr)
if (itr->type == spellInfo->Id)
return true;
if (spellInfo->Attributes & SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
return false;
if (spellInfo->Dispel)
{
SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
for (SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
if (itr->type == spellInfo->Dispel)
return true;
}
// Spells that don't have effectMechanics.
if (spellInfo->Mechanic)
{
SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
if (itr->type == spellInfo->Mechanic)
return true;
}
bool immuneToAllEffects = true;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
// State/effect immunities applied by aura expect full spell immunity
// Ignore effects with mechanic, they are supposed to be checked separately
if (!spellInfo->Effects[i].IsEffect())
continue;
if (!IsImmunedToSpellEffect(spellInfo, i))
{
immuneToAllEffects = false;
break;
}
}
if (immuneToAllEffects) //Return immune only if the target is immune to all spell effects.
return true;
if (spellInfo->Id != 42292 && spellInfo->Id != 59752)
{
SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
{
SpellInfo const* immuneSpellInfo = sSpellMgr->GetSpellInfo(itr->spellId);
if ((itr->type & spellInfo->GetSchoolMask())
&& !(immuneSpellInfo && immuneSpellInfo->IsPositive() && spellInfo->IsPositive())
&& !spellInfo->CanPierceImmuneAura(immuneSpellInfo))
return true;
}
}
return false;
}
bool Unit::IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index) const
{
if (!spellInfo || !spellInfo->Effects[index].IsEffect())
return false;
// If m_immuneToEffect type contain this effect type, IMMUNE effect.
uint32 effect = spellInfo->Effects[index].Effect;
SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
if (itr->type == effect)
return true;
if (uint32 mechanic = spellInfo->Effects[index].Mechanic)
{
SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
if (itr->type == mechanic)
return true;
}
if (uint32 aura = spellInfo->Effects[index].ApplyAuraName)
{
SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
for (SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
if (itr->type == aura)
if (!(spellInfo->AttributesEx3 & SPELL_ATTR3_IGNORE_HIT_RESULT))
return true;
// Check for immune to application of harmful magical effects
AuraEffectList const& immuneAuraApply = GetAuraEffectsByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
for (AuraEffectList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
((*iter)->GetMiscValue() & spellInfo->GetSchoolMask()) && // Check school
!spellInfo->IsPositiveEffect(index)) // Harmful
return true;
}
return false;
}
uint32 Unit::MeleeDamageBonusDone(Unit* victim, uint32 pdamage, WeaponAttackType attType, SpellInfo const* spellProto)
{
if (!victim || pdamage == 0)
return 0;
uint32 creatureTypeMask = victim->GetCreatureTypeMask();
// Done fixed damage bonus auras
int32 DoneFlatBenefit = 0;
// ..done
AuraEffectList const& mDamageDoneCreature = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
for (AuraEffectList::const_iterator i = mDamageDoneCreature.begin(); i != mDamageDoneCreature.end(); ++i)
if (creatureTypeMask & uint32((*i)->GetMiscValue()))
DoneFlatBenefit += (*i)->GetAmount();
// ..done
// SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
// ..done (base at attack power for marked target and base at attack power for creature type)
int32 APbonus = 0;
if (attType == RANGED_ATTACK)
{
APbonus += victim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
// ..done (base at attack power and creature type)
AuraEffectList const& mCreatureAttackPower = GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
for (AuraEffectList::const_iterator i = mCreatureAttackPower.begin(); i != mCreatureAttackPower.end(); ++i)
if (creatureTypeMask & uint32((*i)->GetMiscValue()))
APbonus += (*i)->GetAmount();
}
else
{
APbonus += victim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
// ..done (base at attack power and creature type)
AuraEffectList const& mCreatureAttackPower = GetAuraEffectsByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
for (AuraEffectList::const_iterator i = mCreatureAttackPower.begin(); i != mCreatureAttackPower.end(); ++i)
if (creatureTypeMask & uint32((*i)->GetMiscValue()))
APbonus += (*i)->GetAmount();
}
if (APbonus != 0) // Can be negative
{
bool normalized = false;
if (spellProto)
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
if (spellProto->Effects[i].Effect == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
{
normalized = true;
break;
}
DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType, normalized));
}
// Done total percent damage auras
float DoneTotalMod = 1.0f;
// Some spells don't benefit from pct done mods
if (spellProto)
if (!(spellProto->AttributesEx6 & SPELL_ATTR6_NO_DONE_PCT_DAMAGE_MODS) && !spellProto->IsRankOf(sSpellMgr->GetSpellInfo(12162)))
{
AuraEffectList const& mModDamagePercentDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
for (AuraEffectList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
{
if ((*i)->GetMiscValue() & spellProto->GetSchoolMask() && !(spellProto->GetSchoolMask() & SPELL_SCHOOL_MASK_NORMAL))
{
if ((*i)->GetSpellInfo()->EquippedItemClass == -1)
AddPct(DoneTotalMod, (*i)->GetAmount());
else if (!((*i)->GetSpellInfo()->AttributesEx5 & SPELL_ATTR5_SPECIAL_ITEM_CLASS_CHECK) && ((*i)->GetSpellInfo()->EquippedItemSubClassMask == 0))
AddPct(DoneTotalMod, (*i)->GetAmount());
else if (ToPlayer() && ToPlayer()->HasItemFitToSpellRequirements((*i)->GetSpellInfo()))
AddPct(DoneTotalMod, (*i)->GetAmount());
}
}
}
AuraEffectList const& mDamageDoneVersus = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
for (AuraEffectList::const_iterator i = mDamageDoneVersus.begin(); i != mDamageDoneVersus.end(); ++i)
if (creatureTypeMask & uint32((*i)->GetMiscValue()))
AddPct(DoneTotalMod, (*i)->GetAmount());
// bonus against aurastate
AuraEffectList const& mDamageDoneVersusAurastate = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS_AURASTATE);
for (AuraEffectList::const_iterator i = mDamageDoneVersusAurastate.begin(); i != mDamageDoneVersusAurastate.end(); ++i)
if (victim->HasAuraState(AuraStateType((*i)->GetMiscValue())))
AddPct(DoneTotalMod, (*i)->GetAmount());
// Add SPELL_AURA_MOD_DAMAGE_DONE_FOR_MECHANIC percent bonus
if (spellProto)
AddPct(DoneTotalMod, GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DAMAGE_DONE_FOR_MECHANIC, spellProto->Mechanic));
// done scripted mod (take it from owner)
// Unit* owner = GetOwner() ? GetOwner() : this;
// AuraEffectList const& mOverrideClassScript = owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
float tmpDamage = float(int32(pdamage) + DoneFlatBenefit) * DoneTotalMod;
// apply spellmod to Done damage
if (spellProto)
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
// bonus result can be negative
return uint32(std::max(tmpDamage, 0.0f));
}
uint32 Unit::MeleeDamageBonusTaken(Unit* attacker, uint32 pdamage, WeaponAttackType attType, SpellInfo const* spellProto)
{
if (pdamage == 0)
return 0;
int32 TakenFlatBenefit = 0;
float TakenTotalCasterMod = 0.0f;
// get all auras from caster that allow the spell to ignore resistance (sanctified wrath)
SpellSchoolMask attackSchoolMask = spellProto ? spellProto->GetSchoolMask() : SPELL_SCHOOL_MASK_NORMAL;
AuraEffectList const& IgnoreResistAuras = attacker->GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST);
for (AuraEffectList::const_iterator i = IgnoreResistAuras.begin(); i != IgnoreResistAuras.end(); ++i)
{
if ((*i)->GetMiscValue() & attackSchoolMask)
TakenTotalCasterMod += (float((*i)->GetAmount()));
}
// ..taken
AuraEffectList const& mDamageTaken = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
for (AuraEffectList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i)
if ((*i)->GetMiscValue() & attacker->GetMeleeDamageSchoolMask())
TakenFlatBenefit += (*i)->GetAmount();
if (attType != RANGED_ATTACK)
TakenFlatBenefit += GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
else
TakenFlatBenefit += GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
// Taken total percent damage auras
float TakenTotalMod = 1.0f;
// ..taken
TakenTotalMod *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, attacker->GetMeleeDamageSchoolMask());
// .. taken pct (special attacks)
if (spellProto)
{
// From caster spells
AuraEffectList const& mOwnerTaken = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
for (AuraEffectList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
if ((*i)->GetCasterGUID() == attacker->GetGUID() && (*i)->IsAffectingSpell(spellProto))
AddPct(TakenTotalMod, (*i)->GetAmount());
// Mod damage from spell mechanic
uint32 mechanicMask = spellProto->GetAllEffectsMechanicMask();
// Shred, Maul - "Effects which increase Bleed damage also increase Shred damage"
if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags[0] & 0x00008800)
mechanicMask |= (1<<MECHANIC_BLEED);
if (mechanicMask)
{
AuraEffectList const& mDamageDoneMechanic = GetAuraEffectsByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
for (AuraEffectList::const_iterator i = mDamageDoneMechanic.begin(); i != mDamageDoneMechanic.end(); ++i)
if (mechanicMask & uint32(1<<((*i)->GetMiscValue())))
AddPct(TakenTotalMod, (*i)->GetAmount());
}
}
// .. taken pct: dummy auras
AuraEffectList const& mDummyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (AuraEffectList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
{
switch ((*i)->GetSpellInfo()->SpellIconID)
{
// Cheat Death
case 2109:
if ((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
{
if (GetTypeId() != TYPEID_PLAYER)
continue;
float mod = ToPlayer()->GetRatingBonusValue(CR_RESILIENCE_PLAYER_DAMAGE_TAKEN) * (-8.0f);
AddPct(TakenTotalMod, std::max(mod, float((*i)->GetAmount())));
}
break;
}
}
// .. taken pct: class scripts
//*AuraEffectList const& mclassScritAuras = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
//for (AuraEffectList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
//{
// switch ((*i)->GetMiscValue())
// {
// }
//}*/
if (attType != RANGED_ATTACK)
{
AuraEffectList const& mModMeleeDamageTakenPercent = GetAuraEffectsByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
for (AuraEffectList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
AddPct(TakenTotalMod, (*i)->GetAmount());
}
else
{
AuraEffectList const& mModRangedDamageTakenPercent = GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
for (AuraEffectList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
AddPct(TakenTotalMod, (*i)->GetAmount());
}
float tmpDamage = 0.0f;
if (TakenTotalCasterMod)
{
if (TakenFlatBenefit < 0)
{
if (TakenTotalMod < 1)
tmpDamage = ((float(CalculatePct(pdamage, TakenTotalCasterMod) + TakenFlatBenefit) * TakenTotalMod) + CalculatePct(pdamage, TakenTotalCasterMod));
else
tmpDamage = ((float(CalculatePct(pdamage, TakenTotalCasterMod) + TakenFlatBenefit) + CalculatePct(pdamage, TakenTotalCasterMod)) * TakenTotalMod);
}
else if (TakenTotalMod < 1)
tmpDamage = ((CalculatePct(float(pdamage) + TakenFlatBenefit, TakenTotalCasterMod) * TakenTotalMod) + CalculatePct(float(pdamage) + TakenFlatBenefit, TakenTotalCasterMod));
}
if (!tmpDamage)
tmpDamage = (float(pdamage) + TakenFlatBenefit) * TakenTotalMod;
// bonus result can be negative
return uint32(std::max(tmpDamage, 0.0f));
}
void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
{
if (apply)
{
for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
{
next = itr; ++next;
if (itr->type == type)
{
m_spellImmune[op].erase(itr);
next = m_spellImmune[op].begin();
}
}
SpellImmune Immune;
Immune.spellId = spellId;
Immune.type = type;
m_spellImmune[op].push_back(Immune);
}
else
{
for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
{
if (itr->spellId == spellId && itr->type == type)
{
m_spellImmune[op].erase(itr);
break;
}
}
}
}
void Unit::ApplySpellDispelImmunity(const SpellInfo* spellProto, DispelType type, bool apply)
{
ApplySpellImmune(spellProto->Id, IMMUNITY_DISPEL, type, apply);
if (apply && spellProto->AttributesEx & SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY)
{
// Create dispel mask by dispel type
uint32 dispelMask = SpellInfo::GetDispelMask(type);
// Dispel all existing auras vs current dispel type
AuraApplicationMap& auras = GetAppliedAuras();
for (AuraApplicationMap::iterator itr = auras.begin(); itr != auras.end();)
{
SpellInfo const* spell = itr->second->GetBase()->GetSpellInfo();
if (spell->GetDispelMask() & dispelMask)
{
// Dispel aura
RemoveAura(itr);
}
else
++itr;
}
}
}
float Unit::GetWeaponProcChance() const
{
// normalized proc chance for weapon attack speed
// (odd formula...)
if (isAttackReady(BASE_ATTACK))
return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
return 0;
}
float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellInfo* spellProto) const
{
// proc per minute chance calculation
if (PPM <= 0)
return 0.0f;
// Apply chance modifer aura
if (spellProto)
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_PROC_PER_MINUTE, PPM);
return floor((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
}
void Unit::Mount(uint32 mount, uint32 VehicleId, uint32 creatureEntry)
{
if (mount)
SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT);
if (Player* player = ToPlayer())
{
// mount as a vehicle
if (VehicleId)
{
if (CreateVehicleKit(VehicleId, creatureEntry))
{
// Send others that we now have a vehicle
WorldPacket data(SMSG_PLAYER_VEHICLE_DATA, GetPackGUID().size()+4);
data.appendPackGUID(GetGUID());
data << uint32(VehicleId);
SendMessageToSet(&data, true);
data.Initialize(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
player->GetSession()->SendPacket(&data);
// mounts can also have accessories
GetVehicleKit()->InstallAllAccessories(false);
}
}
// unsummon pet
Pet* pet = player->GetPet();
if (pet)
{
Battleground* bg = ToPlayer()->GetBattleground();
// don't unsummon pet in arena but SetFlag UNIT_FLAG_STUNNED to disable pet's interface
if (bg && bg->isArena())
pet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
else
player->UnsummonPetTemporaryIfAny();
}
player->SendMovementSetCollisionHeight(player->GetCollisionHeight(true));
}
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNT);
}
void Unit::Dismount()
{
if (!IsMounted())
return;
SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT);
if (Player* thisPlayer = ToPlayer())
thisPlayer->SendMovementSetCollisionHeight(thisPlayer->GetCollisionHeight(false));
WorldPacket data(SMSG_DISMOUNT, 8);
data.appendPackGUID(GetGUID());
SendMessageToSet(&data, true);
// dismount as a vehicle
if (GetTypeId() == TYPEID_PLAYER && GetVehicleKit())
{
// Send other players that we are no longer a vehicle
data.Initialize(SMSG_PLAYER_VEHICLE_DATA, 8+4);
data.appendPackGUID(GetGUID());
data << uint32(0);
ToPlayer()->SendMessageToSet(&data, true);
// Remove vehicle from player
RemoveVehicleKit();
}
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
// only resummon old pet if the player is already added to a map
// this prevents adding a pet to a not created map which would otherwise cause a crash
// (it could probably happen when logging in after a previous crash)
if (Player* player = ToPlayer())
{
if (Pet* pPet = player->GetPet())
{
if (pPet->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED) && !pPet->HasUnitState(UNIT_STATE_STUNNED))
pPet->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
}
else
player->ResummonPetTemporaryUnSummonedIfAny();
}
}
MountCapabilityEntry const* Unit::GetMountCapability(uint32 mountType) const
{
if (!mountType)
return NULL;
MountTypeEntry const* mountTypeEntry = sMountTypeStore.LookupEntry(mountType);
if (!mountTypeEntry)
return NULL;
uint32 zoneId, areaId;
GetZoneAndAreaId(zoneId, areaId);
uint32 ridingSkill = 5000;
if (GetTypeId() == TYPEID_PLAYER)
ridingSkill = ToPlayer()->GetSkillValue(SKILL_RIDING);
for (uint32 i = MAX_MOUNT_CAPABILITIES; i > 0; --i)
{
MountCapabilityEntry const* mountCapability = sMountCapabilityStore.LookupEntry(mountTypeEntry->MountCapability[i - 1]);
if (!mountCapability)
continue;
if (ridingSkill < mountCapability->RequiredRidingSkill)
continue;
if (HasExtraUnitMovementFlag(MOVEMENTFLAG2_FULL_SPEED_PITCHING))
{
if (!(mountCapability->Flags & MOUNT_FLAG_CAN_PITCH))
continue;
}
else if (HasUnitMovementFlag(MOVEMENTFLAG_SWIMMING))
{
if (!(mountCapability->Flags & MOUNT_FLAG_CAN_SWIM))
continue;
}
else if (!(mountCapability->Flags & 0x1)) // unknown flags, checked in 4.2.2 14545 client
{
if (!(mountCapability->Flags & 0x2))
continue;
}
if (mountCapability->RequiredMap != -1 && int32(GetMapId()) != mountCapability->RequiredMap)
continue;
if (mountCapability->RequiredArea && (mountCapability->RequiredArea != zoneId && mountCapability->RequiredArea != areaId))
continue;
if (mountCapability->RequiredAura && !HasAura(mountCapability->RequiredAura))
continue;
if (mountCapability->RequiredSpell && (GetTypeId() != TYPEID_PLAYER || !ToPlayer()->HasSpell(mountCapability->RequiredSpell)))
continue;
return mountCapability;
}
return NULL;
}
void Unit::SetInCombatWith(Unit* enemy)
{
Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
if (eOwner->IsPvP())
{
SetInCombatState(true, enemy);
return;
}
// check for duel
if (eOwner->GetTypeId() == TYPEID_PLAYER && eOwner->ToPlayer()->duel)
{
Unit const* myOwner = GetCharmerOrOwnerOrSelf();
if (((Player const*)eOwner)->duel->opponent == myOwner)
{
SetInCombatState(true, enemy);
return;
}
}
SetInCombatState(false, enemy);
}
void Unit::CombatStart(Unit* target, bool initialAggro)
{
if (initialAggro)
{
if (!target->IsStandState())
target->SetStandState(UNIT_STAND_STATE_STAND);
if (!target->isInCombat() && target->GetTypeId() != TYPEID_PLAYER
&& !target->ToCreature()->HasReactState(REACT_PASSIVE) && target->ToCreature()->IsAIEnabled)
{
if (target->isPet())
target->ToCreature()->AI()->AttackedBy(this); // PetAI has special handler before AttackStart()
else
target->ToCreature()->AI()->AttackStart(this);
}
SetInCombatWith(target);
target->SetInCombatWith(this);
}
Unit* who = target->GetCharmerOrOwnerOrSelf();
if (who->GetTypeId() == TYPEID_PLAYER)
SetContestedPvP(who->ToPlayer());
Player* me = GetCharmerOrOwnerPlayerOrPlayerItself();
if (me && who->IsPvP()
&& (who->GetTypeId() != TYPEID_PLAYER
|| !me->duel || me->duel->opponent != who))
{
me->UpdatePvP(true);
me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
}
}
void Unit::SetInCombatState(bool PvP, Unit* enemy)
{
// only alive units can be in combat
if (!isAlive())
return;
if (PvP)
m_CombatTimer = 5000;
if (isInCombat() || HasUnitState(UNIT_STATE_EVADE))
return;
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
if (Creature* creature = ToCreature())
{
// Set home position at place of engaging combat for escorted creatures
if ((IsAIEnabled && creature->AI()->IsEscorted()) ||
GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE ||
GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE)
creature->SetHomePosition(GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
if (enemy)
{
if (IsAIEnabled)
{
creature->AI()->EnterCombat(enemy);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); // unit has engaged in combat, remove immunity so players can fight back
}
if (creature->GetFormation())
creature->GetFormation()->MemberAttackStart(creature, enemy);
}
if (isPet())
{
UpdateSpeed(MOVE_RUN, true);
UpdateSpeed(MOVE_SWIM, true);
UpdateSpeed(MOVE_FLIGHT, true);
}
if (!(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_MOUNTED_COMBAT))
Dismount();
}
for (Unit::ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
{
(*itr)->SetInCombatState(PvP, enemy);
(*itr)->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
}
}
void Unit::ClearInCombat()
{
m_CombatTimer = 0;
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
// Player's state will be cleared in Player::UpdateContestedPvP
if (Creature* creature = ToCreature())
{
if (creature->GetCreatureTemplate() && creature->GetCreatureTemplate()->unit_flags & UNIT_FLAG_IMMUNE_TO_PC)
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); // set immunity state to the one from db on evade
ClearUnitState(UNIT_STATE_ATTACK_PLAYER);
if (HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED))
SetUInt32Value(UNIT_DYNAMIC_FLAGS, creature->GetCreatureTemplate()->dynamicflags);
if (creature->isPet())
{
if (Unit* owner = GetOwner())
for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
if (owner->GetSpeedRate(UnitMoveType(i)) > GetSpeedRate(UnitMoveType(i)))
SetSpeed(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i)), true);
}
else if (!isCharmed())
return;
}
else
ToPlayer()->UpdatePotionCooldown();
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
}
bool Unit::isTargetableForAttack(bool checkFakeDeath) const
{
if (!isAlive())
return false;
if (HasFlag(UNIT_FIELD_FLAGS,
UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC))
return false;
if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->isGameMaster())
return false;
return !HasUnitState(UNIT_STATE_UNATTACKABLE) && (!checkFakeDeath || !HasUnitState(UNIT_STATE_DIED));
}
bool Unit::IsValidAttackTarget(Unit const* target) const
{
return _IsValidAttackTarget(target, NULL);
}
// function based on function Unit::CanAttack from 13850 client
bool Unit::_IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, WorldObject const* obj) const
{
ASSERT(target);
// can't attack self
if (this == target)
return false;
// can't attack unattackable units or GMs
if (target->HasUnitState(UNIT_STATE_UNATTACKABLE)
|| (target->GetTypeId() == TYPEID_PLAYER && target->ToPlayer()->isGameMaster()))
return false;
// can't attack own vehicle or passenger
if (m_vehicle)
if (IsOnVehicle(target) || m_vehicle->GetBase()->IsOnVehicle(target))
return false;
// can't attack invisible (ignore stealth for aoe spells) also if the area being looked at is from a spell use the dynamic object created instead of the casting unit.
if ((!bySpell || !(bySpell->AttributesEx6 & SPELL_ATTR6_CAN_TARGET_INVISIBLE)) && (obj ? !obj->canSeeOrDetect(target, bySpell && bySpell->IsAffectingArea()) : !canSeeOrDetect(target, bySpell && bySpell->IsAffectingArea())))
return false;
// can't attack dead
if ((!bySpell || !bySpell->IsAllowingDeadTarget()) && !target->isAlive())
return false;
// can't attack untargetable
if ((!bySpell || !(bySpell->AttributesEx6 & SPELL_ATTR6_CAN_TARGET_UNTARGETABLE))
&& target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE))
return false;
if (Player const* playerAttacker = ToPlayer())
{
if (playerAttacker->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_UBER))
return false;
}
// check flags
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_TAXI_FLIGHT | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_UNK_16)
|| (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_NPC))
|| (!target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_NPC)))
return false;
if ((!bySpell || !(bySpell->AttributesEx8 & SPELL_ATTR8_ATTACK_IGNORE_IMMUNE_TO_PC_FLAG))
&& (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC))
// check if this is a world trigger cast - GOs are using world triggers to cast their spells, so we need to ignore their immunity flag here, this is a temp workaround, needs removal when go cast is implemented properly
&& GetEntry() != WORLD_TRIGGER)
return false;
// CvC case - can attack each other only when one of them is hostile
if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && !target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE))
return GetReactionTo(target) <= REP_HOSTILE || target->GetReactionTo(this) <= REP_HOSTILE;
// PvP, PvC, CvP case
// can't attack friendly targets
if ( GetReactionTo(target) > REP_NEUTRAL
|| target->GetReactionTo(this) > REP_NEUTRAL)
return false;
// Not all neutral creatures can be attacked
if (GetReactionTo(target) == REP_NEUTRAL &&
target->GetReactionTo(this) == REP_NEUTRAL)
{
if (!(target->GetTypeId() == TYPEID_PLAYER && GetTypeId() == TYPEID_PLAYER) &&
!(target->GetTypeId() == TYPEID_UNIT && GetTypeId() == TYPEID_UNIT))
{
Player const* player = target->GetTypeId() == TYPEID_PLAYER ? target->ToPlayer() : ToPlayer();
Unit const* creature = target->GetTypeId() == TYPEID_UNIT ? target : this;
if (FactionTemplateEntry const* factionTemplate = creature->getFactionTemplateEntry())
{
if (!(player->GetReputationMgr().GetForcedRankIfAny(factionTemplate)))
if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction))
if (FactionState const* repState = player->GetReputationMgr().GetState(factionEntry))
if (!(repState->Flags & FACTION_FLAG_AT_WAR))
return false;
}
}
}
Creature const* creatureAttacker = ToCreature();
if (creatureAttacker && creatureAttacker->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER)
return false;
Player const* playerAffectingAttacker = HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? GetAffectingPlayer() : NULL;
Player const* playerAffectingTarget = target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? target->GetAffectingPlayer() : NULL;
// check duel - before sanctuary checks
if (playerAffectingAttacker && playerAffectingTarget)
if (playerAffectingAttacker->duel && playerAffectingAttacker->duel->opponent == playerAffectingTarget && playerAffectingAttacker->duel->startTime != 0)
return true;
// PvP case - can't attack when attacker or target are in sanctuary
// however, 13850 client doesn't allow to attack when one of the unit's has sanctuary flag and is pvp
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)
&& ((target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_SANCTUARY) || (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_SANCTUARY)))
return false;
// additional checks - only PvP case
if (playerAffectingAttacker && playerAffectingTarget)
{
if (target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_PVP)
return true;
if (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP
&& target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP)
return true;
return (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_UNK1)
|| (target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_UNK1);
}
return true;
}
bool Unit::IsValidAssistTarget(Unit const* target) const
{
return _IsValidAssistTarget(target, NULL);
}
// function based on function Unit::CanAssist from 13850 client
bool Unit::_IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) const
{
ASSERT(target);
// can assist to self
if (this == target)
return true;
// can't assist unattackable units or GMs
if (target->HasUnitState(UNIT_STATE_UNATTACKABLE)
|| (target->GetTypeId() == TYPEID_PLAYER && target->ToPlayer()->isGameMaster()))
return false;
// can't assist own vehicle or passenger
if (m_vehicle)
if (IsOnVehicle(target) || m_vehicle->GetBase()->IsOnVehicle(target))
return false;
// can't assist invisible
if ((!bySpell || !(bySpell->AttributesEx6 & SPELL_ATTR6_CAN_TARGET_INVISIBLE)) && !canSeeOrDetect(target, bySpell && bySpell->IsAffectingArea()))
return false;
// can't assist dead
if ((!bySpell || !bySpell->IsAllowingDeadTarget()) && !target->isAlive())
return false;
// can't assist untargetable
if ((!bySpell || !(bySpell->AttributesEx6 & SPELL_ATTR6_CAN_TARGET_UNTARGETABLE))
&& target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE))
return false;
if (!bySpell || !(bySpell->AttributesEx6 & SPELL_ATTR6_ASSIST_IGNORE_IMMUNE_FLAG))
{
if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE))
{
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC))
return false;
}
else
{
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_NPC))
return false;
}
}
// can't assist non-friendly targets
if (GetReactionTo(target) <= REP_NEUTRAL
&& target->GetReactionTo(this) <= REP_NEUTRAL
&& (!ToCreature() || !(ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER)))
return false;
// PvP case
if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE))
{
Player const* targetPlayerOwner = target->GetAffectingPlayer();
if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE))
{
Player const* selfPlayerOwner = GetAffectingPlayer();
if (selfPlayerOwner && targetPlayerOwner)
{
// can't assist player which is dueling someone
if (selfPlayerOwner != targetPlayerOwner
&& targetPlayerOwner->duel)
return false;
}
// can't assist player in ffa_pvp zone from outside
if ((target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP)
&& !(GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP))
return false;
// can't assist player out of sanctuary from sanctuary if has pvp enabled
if (target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_PVP)
if ((GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_SANCTUARY) && !(target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_SANCTUARY))
return false;
}
}
// PvC case - player can assist creature only if has specific type flags
// !target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) &&
else if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)
&& (!bySpell || !(bySpell->AttributesEx6 & SPELL_ATTR6_ASSIST_IGNORE_IMMUNE_FLAG))
&& !((target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_PVP)))
{
if (Creature const* creatureTarget = target->ToCreature())
return creatureTarget->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER || creatureTarget->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_AID_PLAYERS;
}
return true;
}
int32 Unit::ModifyHealth(int32 dVal)
{
int32 gain = 0;
if (dVal == 0)
return 0;
// Part of Evade mechanics. Only track health lost, not gained.
if (dVal < 0 && GetTypeId() != TYPEID_PLAYER && !isPet())
SetLastDamagedTime(time(NULL));
int32 curHealth = (int32)GetHealth();
int32 val = dVal + curHealth;
if (val <= 0)
{
SetHealth(0);
return -curHealth;
}
int32 maxHealth = (int32)GetMaxHealth();
if (val < maxHealth)
{
SetHealth(val);
gain = val - curHealth;
}
else if (curHealth != maxHealth)
{
SetHealth(maxHealth);
gain = maxHealth - curHealth;
}
return gain;
}
int32 Unit::GetHealthGain(int32 dVal)
{
int32 gain = 0;
if (dVal == 0)
return 0;
int32 curHealth = (int32)GetHealth();
int32 val = dVal + curHealth;
if (val <= 0)
{
return -curHealth;
}
int32 maxHealth = (int32)GetMaxHealth();
if (val < maxHealth)
gain = dVal;
else if (curHealth != maxHealth)
gain = maxHealth - curHealth;
return gain;
}
// returns negative amount on power reduction
int32 Unit::ModifyPower(Powers power, int32 dVal)
{
int32 gain = 0;
if (dVal == 0)
return 0;
int32 curPower = GetPower(power);
int32 val = dVal + curPower;
if (val <= GetMinPower(power))
{
SetPower(power, GetMinPower(power));
return -curPower;
}
int32 maxPower = GetMaxPower(power);
if (val < maxPower)
{
SetPower(power, val);
gain = val - curPower;
}
else if (curPower != maxPower)
{
SetPower(power, maxPower);
gain = maxPower - curPower;
}
return gain;
}
// returns negative amount on power reduction
int32 Unit::ModifyPowerPct(Powers power, float pct, bool apply)
{
float amount = (float)GetMaxPower(power);
ApplyPercentModFloatVar(amount, pct, apply);
return ModifyPower(power, (int32)amount - GetMaxPower(power));
}
bool Unit::IsAlwaysVisibleFor(WorldObject const* seer) const
{
if (WorldObject::IsAlwaysVisibleFor(seer))
return true;
// Always seen by owner
if (uint64 guid = GetCharmerOrOwnerGUID())
if (seer->GetGUID() == guid)
return true;
if (Player const* seerPlayer = seer->ToPlayer())
if (Unit* owner = GetOwner())
if (Player* ownerPlayer = owner->ToPlayer())
if (ownerPlayer->IsGroupVisibleFor(seerPlayer))
return true;
return false;
}
bool Unit::IsAlwaysDetectableFor(WorldObject const* seer) const
{
if (WorldObject::IsAlwaysDetectableFor(seer))
return true;
if (HasAuraTypeWithCaster(SPELL_AURA_MOD_STALKED, seer->GetGUID()))
return true;
return false;
}
void Unit::SetVisible(bool x)
{
if (!x)
m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GM, SEC_GAMEMASTER);
else
m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GM, SEC_PLAYER);
UpdateObjectVisibility();
}
void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
{
int32 main_speed_mod = 0;
float stack_bonus = 1.0f;
float non_stack_bonus = 1.0f;
switch (mtype)
{
// Only apply debuffs
case MOVE_FLIGHT_BACK:
case MOVE_RUN_BACK:
case MOVE_SWIM_BACK:
break;
case MOVE_WALK:
return;
case MOVE_RUN:
{
if (IsMounted()) // Use on mount auras
{
main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK) / 100.0f;
}
else
{
main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK) / 100.0f;
}
break;
}
case MOVE_SWIM:
{
main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
break;
}
case MOVE_FLIGHT:
{
if (GetTypeId() == TYPEID_UNIT && IsControlledByPlayer()) // not sure if good for pet
{
main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED);
stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_VEHICLE_SPEED_ALWAYS);
// for some spells this mod is applied on vehicle owner
int32 owner_speed_mod = 0;
if (Unit* owner = GetCharmer())
owner_speed_mod = owner->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED);
main_speed_mod = std::max(main_speed_mod, owner_speed_mod);
}
else if (IsMounted())
{
main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED);
stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_FLIGHT_SPEED_ALWAYS);
}
else // Use not mount (shapeshift for example) auras (should stack)
main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) + GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED);
non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK) / 100.0f;
// Update speed for vehicle if available
if (GetTypeId() == TYPEID_PLAYER && GetVehicle())
GetVehicleBase()->UpdateSpeed(MOVE_FLIGHT, true);
break;
}
default:
sLog->outError(LOG_FILTER_UNITS, "Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
return;
}
// now we ready for speed calculation
float speed = std::max(non_stack_bonus, stack_bonus);
if (main_speed_mod)
AddPct(speed, main_speed_mod);
switch (mtype)
{
case MOVE_RUN:
case MOVE_SWIM:
case MOVE_FLIGHT:
{
// Set creature speed rate
if (GetTypeId() == TYPEID_UNIT)
{
Unit* pOwner = GetCharmerOrOwner();
if ((isPet() || isGuardian()) && !isInCombat() && pOwner) // Must check for owner or crash on "Tame Beast"
{
// For every yard over 5, increase speed by 0.01
// to help prevent pet from lagging behind and despawning
float dist = GetDistance(pOwner);
float base_rate = 1.00f; // base speed is 100% of owner speed
if (dist < 5)
dist = 5;
float mult = base_rate + ((dist - 5) * 0.01f);
speed *= pOwner->GetSpeedRate(mtype) * mult; // pets derive speed from owner when not in combat
}
else
speed *= ToCreature()->GetCreatureTemplate()->speed_run; // at this point, MOVE_WALK is never reached
}
// Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
// TODO: possible affect only on MOVE_RUN
if (int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
{
// Use speed from aura
float max_speed = normalization / (IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]);
if (speed > max_speed)
speed = max_speed;
}
break;
}
default:
break;
}
// for creature case, we check explicit if mob searched for assistance
if (GetTypeId() == TYPEID_UNIT)
{
if (ToCreature()->HasSearchedAssistance())
speed *= 0.66f; // best guessed value, so this will be 33% reduction. Based off initial speed, mob can then "run", "walk fast" or "walk".
}
// Apply strongest slow aura mod to speed
int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
if (slow)
{
AddPct(speed, slow);
if (float minSpeedMod = (float)GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MINIMUM_SPEED))
{
float min_speed = minSpeedMod / 100.0f;
if (speed < min_speed)
speed = min_speed;
}
}
SetSpeed(mtype, speed, forced);
}
float Unit::GetSpeed(UnitMoveType mtype) const
{
return m_speed_rate[mtype]*(IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]);
}
void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
{
if (rate < 0)
rate = 0.0f;
// Update speed only on change
if (m_speed_rate[mtype] == rate)
return;
m_speed_rate[mtype] = rate;
propagateSpeedChange();
WorldPacket data;
ObjectGuid guid = GetGUID();
if (!forced)
{
switch (mtype)
{
case MOVE_WALK:
data.Initialize(SMSG_SPLINE_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
data.WriteBit(guid[0]);
data.WriteBit(guid[6]);
data.WriteBit(guid[7]);
data.WriteBit(guid[3]);
data.WriteBit(guid[5]);
data.WriteBit(guid[1]);
data.WriteBit(guid[2]);
data.WriteBit(guid[4]);
data.FlushBits();
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[3]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[5]);
break;
case MOVE_RUN:
data.Initialize(SMSG_SPLINE_MOVE_SET_RUN_SPEED, 1 + 8 + 4);
data.WriteBit(guid[4]);
data.WriteBit(guid[0]);
data.WriteBit(guid[5]);
data.WriteBit(guid[7]);
data.WriteBit(guid[6]);
data.WriteBit(guid[3]);
data.WriteBit(guid[1]);
data.WriteBit(guid[2]);
data.FlushBits();
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[4]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[1]);
break;
case MOVE_RUN_BACK:
data.Initialize(SMSG_SPLINE_MOVE_SET_RUN_BACK_SPEED, 1 + 8 + 4);
data.WriteBit(guid[1]);
data.WriteBit(guid[2]);
data.WriteBit(guid[6]);
data.WriteBit(guid[0]);
data.WriteBit(guid[3]);
data.WriteBit(guid[7]);
data.WriteBit(guid[5]);
data.WriteBit(guid[4]);
data.FlushBits();
data.WriteByteSeq(guid[1]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[7]);
break;
case MOVE_SWIM:
data.Initialize(SMSG_SPLINE_MOVE_SET_SWIM_SPEED, 1 + 8 + 4);
data.WriteBit(guid[4]);
data.WriteBit(guid[2]);
data.WriteBit(guid[5]);
data.WriteBit(guid[0]);
data.WriteBit(guid[7]);
data.WriteBit(guid[6]);
data.WriteBit(guid[3]);
data.WriteBit(guid[1]);
data.FlushBits();
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[4]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[3]);
break;
case MOVE_SWIM_BACK:
data.Initialize(SMSG_SPLINE_MOVE_SET_SWIM_BACK_SPEED, 1 + 8 + 4);
data.WriteBit(guid[0]);
data.WriteBit(guid[1]);
data.WriteBit(guid[3]);
data.WriteBit(guid[6]);
data.WriteBit(guid[4]);
data.WriteBit(guid[5]);
data.WriteBit(guid[7]);
data.WriteBit(guid[2]);
data.FlushBits();
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[6]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[2]);
break;
case MOVE_TURN_RATE:
data.Initialize(SMSG_SPLINE_MOVE_SET_TURN_RATE, 1 + 8 + 4);
data.WriteBit(guid[2]);
data.WriteBit(guid[4]);
data.WriteBit(guid[6]);
data.WriteBit(guid[1]);
data.WriteBit(guid[3]);
data.WriteBit(guid[5]);
data.WriteBit(guid[7]);
data.WriteBit(guid[0]);
data.FlushBits();
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[0]);
break;
case MOVE_FLIGHT:
data.Initialize(SMSG_SPLINE_MOVE_SET_FLIGHT_SPEED, 1 + 8 + 4);
data.WriteBit(guid[7]);
data.WriteBit(guid[4]);
data.WriteBit(guid[0]);
data.WriteBit(guid[1]);
data.WriteBit(guid[3]);
data.WriteBit(guid[6]);
data.WriteBit(guid[5]);
data.WriteBit(guid[2]);
data.FlushBits();
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[6]);
data << float(GetSpeed(mtype));
break;
case MOVE_FLIGHT_BACK:
data.Initialize(SMSG_SPLINE_MOVE_SET_FLIGHT_BACK_SPEED, 1 + 8 + 4);
data.WriteBit(guid[2]);
data.WriteBit(guid[1]);
data.WriteBit(guid[6]);
data.WriteBit(guid[5]);
data.WriteBit(guid[0]);
data.WriteBit(guid[3]);
data.WriteBit(guid[4]);
data.WriteBit(guid[7]);
data.FlushBits();
data.WriteByteSeq(guid[5]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[4]);
break;
case MOVE_PITCH_RATE:
data.Initialize(SMSG_SPLINE_MOVE_SET_PITCH_RATE, 1 + 8 + 4);
data.WriteBit(guid[3]);
data.WriteBit(guid[5]);
data.WriteBit(guid[6]);
data.WriteBit(guid[1]);
data.WriteBit(guid[0]);
data.WriteBit(guid[4]);
data.WriteBit(guid[7]);
data.WriteBit(guid[2]);
data.FlushBits();
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[2]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[4]);
break;
default:
sLog->outError(LOG_FILTER_UNITS, "Unit::SetSpeed: Unsupported move type (%d), data not sent to client.", mtype);
return;
}
SendMessageToSet(&data, true);
}
else
{
if (GetTypeId() == TYPEID_PLAYER)
{
// register forced speed changes for WorldSession::HandleForceSpeedChangeAck
// and do it only for real sent packets and use run for run/mounted as client expected
++ToPlayer()->m_forced_speed_changes[mtype];
if (!isInCombat())
if (Pet* pet = ToPlayer()->GetPet())
pet->SetSpeed(mtype, m_speed_rate[mtype], forced);
}
switch (mtype)
{
case MOVE_WALK:
data.Initialize(SMSG_MOVE_SET_WALK_SPEED, 1 + 8 + 4 + 4);
data.WriteBit(guid[0]);
data.WriteBit(guid[4]);
data.WriteBit(guid[5]);
data.WriteBit(guid[2]);
data.WriteBit(guid[3]);
data.WriteBit(guid[1]);
data.WriteBit(guid[6]);
data.WriteBit(guid[7]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[5]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[2]);
data << uint32(0);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[3]);
break;
case MOVE_RUN:
data.Initialize(SMSG_MOVE_SET_RUN_SPEED, 1 + 8 + 4 + 4);
data.WriteBit(guid[6]);
data.WriteBit(guid[1]);
data.WriteBit(guid[5]);
data.WriteBit(guid[2]);
data.WriteBit(guid[7]);
data.WriteBit(guid[0]);
data.WriteBit(guid[3]);
data.WriteBit(guid[4]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[4]);
data << uint32(0);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[2]);
break;
case MOVE_RUN_BACK:
data.Initialize(SMSG_MOVE_SET_RUN_BACK_SPEED, 1 + 8 + 4 + 4);
data.WriteBit(guid[0]);
data.WriteBit(guid[6]);
data.WriteBit(guid[2]);
data.WriteBit(guid[1]);
data.WriteBit(guid[3]);
data.WriteBit(guid[4]);
data.WriteBit(guid[5]);
data.WriteBit(guid[7]);
data.WriteByteSeq(guid[5]);
data << uint32(0);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[6]);
break;
case MOVE_SWIM:
data.Initialize(SMSG_MOVE_SET_SWIM_SPEED, 1 + 8 + 4 + 4);
data.WriteBit(guid[5]);
data.WriteBit(guid[4]);
data.WriteBit(guid[7]);
data.WriteBit(guid[3]);
data.WriteBit(guid[2]);
data.WriteBit(guid[0]);
data.WriteBit(guid[1]);
data.WriteBit(guid[6]);
data.WriteByteSeq(guid[0]);
data << uint32(0);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[2]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[4]);
break;
case MOVE_SWIM_BACK:
data.Initialize(SMSG_MOVE_SET_SWIM_BACK_SPEED, 1 + 8 + 4 + 4);
data.WriteBit(guid[4]);
data.WriteBit(guid[2]);
data.WriteBit(guid[3]);
data.WriteBit(guid[6]);
data.WriteBit(guid[5]);
data.WriteBit(guid[1]);
data.WriteBit(guid[0]);
data.WriteBit(guid[7]);
data << uint32(0);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[1]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[2]);
break;
case MOVE_TURN_RATE:
data.Initialize(SMSG_MOVE_SET_TURN_RATE, 1 + 8 + 4 + 4);
data.WriteBit(guid[7]);
data.WriteBit(guid[2]);
data.WriteBit(guid[1]);
data.WriteBit(guid[0]);
data.WriteBit(guid[4]);
data.WriteBit(guid[5]);
data.WriteBit(guid[6]);
data.WriteBit(guid[3]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[2]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[0]);
data << uint32(0);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[4]);
break;
case MOVE_FLIGHT:
data.Initialize(SMSG_MOVE_SET_FLIGHT_SPEED, 1 + 8 + 4 + 4);
data.WriteBit(guid[0]);
data.WriteBit(guid[5]);
data.WriteBit(guid[1]);
data.WriteBit(guid[6]);
data.WriteBit(guid[3]);
data.WriteBit(guid[2]);
data.WriteBit(guid[7]);
data.WriteBit(guid[4]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[5]);
data << float(GetSpeed(mtype));
data << uint32(0);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[4]);
break;
case MOVE_FLIGHT_BACK:
data.Initialize(SMSG_MOVE_SET_FLIGHT_BACK_SPEED, 1 + 8 + 4 + 4);
data.WriteBit(guid[1]);
data.WriteBit(guid[2]);
data.WriteBit(guid[6]);
data.WriteBit(guid[4]);
data.WriteBit(guid[7]);
data.WriteBit(guid[3]);
data.WriteBit(guid[0]);
data.WriteBit(guid[5]);
data.WriteByteSeq(guid[3]);
data << uint32(0);
data.WriteByteSeq(guid[6]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[7]);
break;
case MOVE_PITCH_RATE:
data.Initialize(SMSG_MOVE_SET_PITCH_RATE, 1 + 8 + 4 + 4);
data.WriteBit(guid[1]);
data.WriteBit(guid[2]);
data.WriteBit(guid[6]);
data.WriteBit(guid[7]);
data.WriteBit(guid[0]);
data.WriteBit(guid[3]);
data.WriteBit(guid[5]);
data.WriteBit(guid[4]);
data << float(GetSpeed(mtype));
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[0]);
data << uint32(0);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[5]);
break;
default:
sLog->outError(LOG_FILTER_UNITS, "Unit::SetSpeed: Unsupported move type (%d), data not sent to client.", mtype);
return;
}
SendMessageToSet(&data, true);
}
}
void Unit::setDeathState(DeathState s)
{
if (s != ALIVE && s != JUST_RESPAWNED)
{
CombatStop();
DeleteThreatList();
getHostileRefManager().deleteReferences();
ClearComboPointHolders(); // any combo points pointed to unit lost at it death
if (IsNonMeleeSpellCasted(false))
InterruptNonMeleeSpells(false);
UnsummonAllTotems();
RemoveAllControlled();
RemoveAllAurasOnDeath();
}
if (s == JUST_DIED)
{
ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
// remove aurastates allowing special moves
ClearAllReactives();
ClearDiminishings();
if (IsInWorld())
{
// Only clear MotionMaster for entities that exists in world
// Avoids crashes in the following conditions :
// * Using 'call pet' on dead pets
// * Using 'call stabled pet'
// * Logging in with dead pets
GetMotionMaster()->Clear(false);
GetMotionMaster()->MoveIdle();
}
StopMoving();
DisableSpline();
// without this when removing IncreaseMaxHealth aura player may stuck with 1 hp
// do not why since in IncreaseMaxHealth currenthealth is checked
SetHealth(0);
SetPower(getPowerType(), 0);
// players in instance don't have ZoneScript, but they have InstanceScript
if (ZoneScript* zoneScript = GetZoneScript() ? GetZoneScript() : (ZoneScript*)GetInstanceScript())
zoneScript->OnUnitDeath(this);
}
else if (s == JUST_RESPAWNED)
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
m_deathState = s;
}
/*########################################
######## ########
######## AGGRO SYSTEM ########
######## ########
########################################*/
bool Unit::CanHaveThreatList() const
{
// only creatures can have threat list
if (GetTypeId() != TYPEID_UNIT)
return false;
// only alive units can have threat list
if (!isAlive() || isDying())
return false;
// totems can not have threat list
if (ToCreature()->isTotem())
return false;
// vehicles can not have threat list
//if (ToCreature()->IsVehicle())
// return false;
// summons can not have a threat list, unless they are controlled by a creature
if (HasUnitTypeMask(UNIT_MASK_MINION | UNIT_MASK_GUARDIAN | UNIT_MASK_CONTROLABLE_GUARDIAN) && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()))
return false;
return true;
}
//======================================================================
float Unit::ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask)
{
if (!HasAuraType(SPELL_AURA_MOD_THREAT) || fThreat < 0)
return fThreat;
SpellSchools school = GetFirstSchoolInMask(schoolMask);
return fThreat * m_threatModifier[school];
}
//======================================================================
void Unit::AddThreat(Unit* victim, float fThreat, SpellSchoolMask schoolMask, SpellInfo const* threatSpell)
{
// Only mobs can manage threat lists
if (CanHaveThreatList())
m_ThreatManager.addThreat(victim, fThreat, schoolMask, threatSpell);
}
//======================================================================
void Unit::DeleteThreatList()
{
if (CanHaveThreatList() && !m_ThreatManager.isThreatListEmpty())
SendClearThreatListOpcode();
m_ThreatManager.clearReferences();
}
//======================================================================
void Unit::TauntApply(Unit* taunter)
{
ASSERT(GetTypeId() == TYPEID_UNIT);
if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && taunter->ToPlayer()->isGameMaster()))
return;
if (!CanHaveThreatList())
return;
Creature* creature = ToCreature();
if (creature->HasReactState(REACT_PASSIVE))
return;
Unit* target = getVictim();
if (target && target == taunter)
return;
SetInFront(taunter);
if (creature->IsAIEnabled)
creature->AI()->AttackStart(taunter);
//m_ThreatManager.tauntApply(taunter);
}
//======================================================================
void Unit::TauntFadeOut(Unit* taunter)
{
ASSERT(GetTypeId() == TYPEID_UNIT);
if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && taunter->ToPlayer()->isGameMaster()))
return;
if (!CanHaveThreatList())
return;
Creature* creature = ToCreature();
if (creature->HasReactState(REACT_PASSIVE))
return;
Unit* target = getVictim();
if (!target || target != taunter)
return;
if (m_ThreatManager.isThreatListEmpty())
{
if (creature->IsAIEnabled)
creature->AI()->EnterEvadeMode();
return;
}
target = creature->SelectVictim(); // might have more taunt auras remaining
if (target && target != taunter)
{
SetInFront(target);
if (creature->IsAIEnabled)
creature->AI()->AttackStart(target);
}
}
//======================================================================
Unit* Creature::SelectVictim()
{
// function provides main threat functionality
// next-victim-selection algorithm and evade mode are called
// threat list sorting etc.
Unit* target = NULL;
// First checking if we have some taunt on us
AuraEffectList const& tauntAuras = GetAuraEffectsByType(SPELL_AURA_MOD_TAUNT);
if (!tauntAuras.empty())
{
Unit* caster = tauntAuras.back()->GetCaster();
// The last taunt aura caster is alive an we are happy to attack him
if (caster && caster->isAlive())
return getVictim();
else if (tauntAuras.size() > 1)
{
// We do not have last taunt aura caster but we have more taunt auras,
// so find first available target
// Auras are pushed_back, last caster will be on the end
AuraEffectList::const_iterator aura = --tauntAuras.end();
do
{
--aura;
caster = (*aura)->GetCaster();
if (caster && canSeeOrDetect(caster, true) && IsValidAttackTarget(caster) && caster->isInAccessiblePlaceFor(ToCreature()))
{
target = caster;
break;
}
} while (aura != tauntAuras.begin());
}
else
target = getVictim();
}
if (CanHaveThreatList())
{
if (!target && !m_ThreatManager.isThreatListEmpty())
// No taunt aura or taunt aura caster is dead standard target selection
target = m_ThreatManager.getHostilTarget();
}
else if (!HasReactState(REACT_PASSIVE))
{
// We have player pet probably
target = getAttackerForHelper();
if (!target && isSummon())
{
if (Unit* owner = ToTempSummon()->GetOwner())
{
if (owner->isInCombat())
target = owner->getAttackerForHelper();
if (!target)
{
for (ControlList::const_iterator itr = owner->m_Controlled.begin(); itr != owner->m_Controlled.end(); ++itr)
{
if ((*itr)->isInCombat())
{
target = (*itr)->getAttackerForHelper();
if (target)
break;
}
}
}
}
}
}
else
return NULL;
if (target && _IsTargetAcceptable(target) && canCreatureAttack(target))
{
SetInFront(target);
return target;
}
// Case where mob is being kited.
// Mob may not be in range to attack or may have dropped target. In any case,
// don't evade if damage received within the last 10 seconds
// Does not apply to world bosses to prevent kiting to cities
if (!isWorldBoss() && !GetInstanceId())
if (time(NULL) - GetLastDamagedTime() <= MAX_AGGRO_RESET_TIME)
return target;
// last case when creature must not go to evade mode:
// it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
// for example at owner command to pet attack some far away creature
// Note: creature does not have targeted movement generator but has attacker in this case
for (AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
{
if ((*itr) && !canCreatureAttack(*itr) && (*itr)->GetTypeId() != TYPEID_PLAYER
&& !(*itr)->ToCreature()->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
return NULL;
}
// TODO: a vehicle may eat some mob, so mob should not evade
if (GetVehicle())
return NULL;
// search nearby enemy before enter evade mode
if (HasReactState(REACT_AGGRESSIVE))
{
target = SelectNearestTargetInAttackDistance(m_CombatDistance ? m_CombatDistance : ATTACK_DISTANCE);
if (target && _IsTargetAcceptable(target) && canCreatureAttack(target))
return target;
}
Unit::AuraEffectList const& iAuras = GetAuraEffectsByType(SPELL_AURA_MOD_INVISIBILITY);
if (!iAuras.empty())
{
for (Unit::AuraEffectList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
{
if ((*itr)->GetBase()->IsPermanent())
{
AI()->EnterEvadeMode();
break;
}
}
return NULL;
}
// enter in evade mode in other case
AI()->EnterEvadeMode();
return NULL;
}
//======================================================================
//======================================================================
//======================================================================
float Unit::ApplyEffectModifiers(SpellInfo const* spellProto, uint8 effect_index, float value) const
{
if (Player* modOwner = GetSpellModOwner())
{
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_ALL_EFFECTS, value);
switch (effect_index)
{
case 0:
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT1, value);
break;
case 1:
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT2, value);
break;
case 2:
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT3, value);
break;
}
}
return value;
}
// function uses real base points (typically value - 1)
int32 Unit::CalculateSpellDamage(Unit const* target, SpellInfo const* spellProto, uint8 effect_index, int32 const* basePoints) const
{
return spellProto->Effects[effect_index].CalcValue(this, basePoints, target);
}
int32 Unit::CalcSpellDuration(SpellInfo const* spellProto)
{
uint8 comboPoints = m_movedPlayer ? m_movedPlayer->GetComboPoints() : 0;
int32 minduration = spellProto->GetDuration();
int32 maxduration = spellProto->GetMaxDuration();
int32 duration;
if (comboPoints && minduration != -1 && minduration != maxduration)
duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
else
duration = minduration;
return duration;
}
int32 Unit::ModSpellDuration(SpellInfo const* spellProto, Unit const* target, int32 duration, bool positive, uint32 effectMask)
{
// don't mod permanent auras duration
if (duration < 0)
return duration;
// cut duration only of negative effects
if (!positive)
{
int32 mechanic = spellProto->GetSpellMechanicMaskByEffectMask(effectMask);
int32 durationMod;
int32 durationMod_always = 0;
int32 durationMod_not_stack = 0;
for (uint8 i = 1; i <= MECHANIC_ENRAGED; ++i)
{
if (!(mechanic & 1<<i))
continue;
// Find total mod value (negative bonus)
int32 new_durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, i);
// Find max mod (negative bonus)
int32 new_durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, i);
// Check if mods applied before were weaker
if (new_durationMod_always < durationMod_always)
durationMod_always = new_durationMod_always;
if (new_durationMod_not_stack < durationMod_not_stack)
durationMod_not_stack = new_durationMod_not_stack;
}
// Select strongest negative mod
if (durationMod_always > durationMod_not_stack)
durationMod = durationMod_not_stack;
else
durationMod = durationMod_always;
if (durationMod != 0)
AddPct(duration, durationMod);
// there are only negative mods currently
durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL, spellProto->Dispel);
durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL_NOT_STACK, spellProto->Dispel);
durationMod = 0;
if (durationMod_always > durationMod_not_stack)
durationMod += durationMod_not_stack;
else
durationMod += durationMod_always;
if (durationMod != 0)
AddPct(duration, durationMod);
}
else
{
// else positive mods here, there are no currently
// when there will be, change GetTotalAuraModifierByMiscValue to GetTotalPositiveAuraModifierByMiscValue
// Mixology - duration boost
if (target->GetTypeId() == TYPEID_PLAYER)
{
if (spellProto->SpellFamilyName == SPELLFAMILY_POTION && (
sSpellMgr->IsSpellMemberOfSpellGroup(spellProto->Id, SPELL_GROUP_ELIXIR_BATTLE) ||
sSpellMgr->IsSpellMemberOfSpellGroup(spellProto->Id, SPELL_GROUP_ELIXIR_GUARDIAN)))
{
if (target->HasAura(53042) && target->HasSpell(spellProto->Effects[0].TriggerSpell))
duration *= 2;
}
}
}
// Glyphs which increase duration of selfcasted buffs
if (target == this)
{
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_DRUID:
if (spellProto->SpellFamilyFlags[0] & 0x100)
{
// Glyph of Thorns
if (AuraEffect* aurEff = GetAuraEffect(57862, 0))
duration += aurEff->GetAmount() * MINUTE * IN_MILLISECONDS;
}
break;
}
}
return std::max(duration, 0);
}
void Unit::ModSpellCastTime(SpellInfo const* spellProto, int32 & castTime, Spell* spell)
{
if (!spellProto || castTime < 0)
return;
// called from caster
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CASTING_TIME, castTime, spell);
if (!(spellProto->Attributes & (SPELL_ATTR0_ABILITY|SPELL_ATTR0_TRADESPELL)) && ((GetTypeId() == TYPEID_PLAYER && spellProto->SpellFamilyName) || GetTypeId() == TYPEID_UNIT))
castTime = int32(float(castTime) * GetFloatValue(UNIT_MOD_CAST_SPEED));
else if (spellProto->Attributes & SPELL_ATTR0_REQ_AMMO && !(spellProto->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG))
castTime = int32(float(castTime) * m_modAttackSpeedPct[RANGED_ATTACK]);
else if (spellProto->SpellVisual[0] == 3881 && HasAura(67556)) // cooking with Chef Hat.
castTime = 500;
}
DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
{
for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
{
if (i->DRGroup != group)
continue;
if (!i->hitCount)
return DIMINISHING_LEVEL_1;
if (!i->hitTime)
return DIMINISHING_LEVEL_1;
// If last spell was casted more than 15 seconds ago - reset the count.
if (i->stack == 0 && getMSTimeDiff(i->hitTime, getMSTime()) > 15000)
{
i->hitCount = DIMINISHING_LEVEL_1;
return DIMINISHING_LEVEL_1;
}
// or else increase the count.
else
return DiminishingLevels(i->hitCount);
}
return DIMINISHING_LEVEL_1;
}
void Unit::IncrDiminishing(DiminishingGroup group)
{
// Checking for existing in the table
for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
{
if (i->DRGroup != group)
continue;
if (int32(i->hitCount) < GetDiminishingReturnsMaxLevel(group))
i->hitCount += 1;
return;
}
m_Diminishing.push_back(DiminishingReturn(group, getMSTime(), DIMINISHING_LEVEL_2));
}
float Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration, Unit* caster, DiminishingLevels Level, int32 limitduration)
{
if (duration == -1 || group == DIMINISHING_NONE)
return 1.0f;
// test pet/charm masters instead pets/charmeds
Unit const* targetOwner = GetCharmerOrOwner();
Unit const* casterOwner = caster->GetCharmerOrOwner();
// Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
if (limitduration > 0 && duration > limitduration)
{
Unit const* target = targetOwner ? targetOwner : this;
Unit const* source = casterOwner ? casterOwner : caster;
if ((target->GetTypeId() == TYPEID_PLAYER
|| ((Creature*)target)->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH)
&& source->GetTypeId() == TYPEID_PLAYER)
duration = limitduration;
}
float mod = 1.0f;
if (group == DIMINISHING_TAUNT)
{
if (GetTypeId() == TYPEID_UNIT && (ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_TAUNT_DIMINISH))
{
DiminishingLevels diminish = Level;
switch (diminish)
{
case DIMINISHING_LEVEL_1: break;
case DIMINISHING_LEVEL_2: mod = 0.65f; break;
case DIMINISHING_LEVEL_3: mod = 0.4225f; break;
case DIMINISHING_LEVEL_4: mod = 0.274625f; break;
case DIMINISHING_LEVEL_TAUNT_IMMUNE: mod = 0.0f; break;
default: break;
}
}
}
// Some diminishings applies to mobs too (for example, Stun)
else if ((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER
&& ((targetOwner ? (targetOwner->GetTypeId() == TYPEID_PLAYER) : (GetTypeId() == TYPEID_PLAYER))
|| (GetTypeId() == TYPEID_UNIT && ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH)))
|| GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
{
DiminishingLevels diminish = Level;
switch (diminish)
{
case DIMINISHING_LEVEL_1: break;
case DIMINISHING_LEVEL_2: mod = 0.5f; break;
case DIMINISHING_LEVEL_3: mod = 0.25f; break;
case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f; break;
default: break;
}
}
duration = int32(duration * mod);
return mod;
}
void Unit::ApplyDiminishingAura(DiminishingGroup group, bool apply)
{
// Checking for existing in the table
for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
{
if (i->DRGroup != group)
continue;
if (apply)
i->stack += 1;
else if (i->stack)
{
i->stack -= 1;
// Remember time after last aura from group removed
if (i->stack == 0)
i->hitTime = getMSTime();
}
break;
}
}
float Unit::GetSpellMaxRangeForTarget(Unit const* target, SpellInfo const* spellInfo) const
{
if (!spellInfo->RangeEntry)
return 0;
if (spellInfo->RangeEntry->maxRangeFriend == spellInfo->RangeEntry->maxRangeHostile)
return spellInfo->GetMaxRange();
return spellInfo->GetMaxRange(!IsHostileTo(target));
}
float Unit::GetSpellMinRangeForTarget(Unit const* target, SpellInfo const* spellInfo) const
{
if (!spellInfo->RangeEntry)
return 0;
if (spellInfo->RangeEntry->minRangeFriend == spellInfo->RangeEntry->minRangeHostile)
return spellInfo->GetMinRange();
return spellInfo->GetMinRange(!IsHostileTo(target));
}
Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
{
return ObjectAccessor::GetUnit(object, guid);
}
Player* Unit::GetPlayer(WorldObject& object, uint64 guid)
{
return ObjectAccessor::GetPlayer(object, guid);
}
Creature* Unit::GetCreature(WorldObject& object, uint64 guid)
{
return object.GetMap()->GetCreature(guid);
}
uint32 Unit::GetCreatureType() const
{
if (GetTypeId() == TYPEID_PLAYER)
{
ShapeshiftForm form = GetShapeshiftForm();
SpellShapeshiftFormEntry const* ssEntry = sSpellShapeshiftFormStore.LookupEntry(form);
if (ssEntry && ssEntry->creatureType > 0)
return ssEntry->creatureType;
else
return CREATURE_TYPE_HUMANOID;
}
else
return ToCreature()->GetCreatureTemplate()->type;
}
/*#######################################
######## ########
######## STAT SYSTEM ########
######## ########
#######################################*/
bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
{
if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
{
sLog->outError(LOG_FILTER_UNITS, "ERROR in HandleStatModifier(): non-existing UnitMods or wrong UnitModifierType!");
return false;
}
switch (modifierType)
{
case BASE_VALUE:
case TOTAL_VALUE:
m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
break;
case BASE_PCT:
case TOTAL_PCT:
ApplyPercentModFloatVar(m_auraModifiersGroup[unitMod][modifierType], amount, apply);
break;
default:
break;
}
if (!CanModifyStats())
return false;
switch (unitMod)
{
case UNIT_MOD_STAT_STRENGTH:
case UNIT_MOD_STAT_AGILITY:
case UNIT_MOD_STAT_STAMINA:
case UNIT_MOD_STAT_INTELLECT:
case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
case UNIT_MOD_ARMOR: UpdateArmor(); break;
case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
case UNIT_MOD_MANA:
case UNIT_MOD_RAGE:
case UNIT_MOD_FOCUS:
case UNIT_MOD_ENERGY:
case UNIT_MOD_RUNE:
case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
case UNIT_MOD_RESISTANCE_HOLY:
case UNIT_MOD_RESISTANCE_FIRE:
case UNIT_MOD_RESISTANCE_NATURE:
case UNIT_MOD_RESISTANCE_FROST:
case UNIT_MOD_RESISTANCE_SHADOW:
case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
default:
break;
}
return true;
}
float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
{
if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
{
sLog->outError(LOG_FILTER_UNITS, "attempt to access non-existing modifier value from UnitMods!");
return 0.0f;
}
if (modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
return 0.0f;
return m_auraModifiersGroup[unitMod][modifierType];
}
float Unit::GetTotalStatValue(Stats stat) const
{
UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
if (m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
return 0.0f;
// value = ((base_value * base_pct) + total_value) * total_pct
float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
value *= m_auraModifiersGroup[unitMod][BASE_PCT];
value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
return value;
}
float Unit::GetTotalAuraModValue(UnitMods unitMod) const
{
if (unitMod >= UNIT_MOD_END)
{
sLog->outError(LOG_FILTER_UNITS, "attempt to access non-existing UnitMods in GetTotalAuraModValue()!");
return 0.0f;
}
if (m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
return 0.0f;
float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
value *= m_auraModifiersGroup[unitMod][BASE_PCT];
value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
return value;
}
SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
{
SpellSchools school = SPELL_SCHOOL_NORMAL;
switch (unitMod)
{
case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
default:
break;
}
return school;
}
Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
{
Stats stat = STAT_STRENGTH;
switch (unitMod)
{
case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
default:
break;
}
return stat;
}
Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
{
switch (unitMod)
{
case UNIT_MOD_RAGE: return POWER_RAGE;
case UNIT_MOD_FOCUS: return POWER_FOCUS;
case UNIT_MOD_ENERGY: return POWER_ENERGY;
case UNIT_MOD_RUNE: return POWER_RUNES;
case UNIT_MOD_RUNIC_POWER: return POWER_RUNIC_POWER;
default:
case UNIT_MOD_MANA: return POWER_MANA;
}
}
float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
{
if (attType == RANGED_ATTACK)
{
int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER);
if (ap < 0)
return 0.0f;
return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
}
else
{
int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER);
if (ap < 0)
return 0.0f;
return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
}
}
float Unit::GetWeaponDamageRange(WeaponAttackType attType, WeaponDamageRange type) const
{
if (attType == OFF_ATTACK && !haveOffhandWeapon())
return 0.0f;
return m_weaponDamage[attType][type];
}
void Unit::SetLevel(uint8 lvl)
{
SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
// group update
if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->GetGroup())
ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
if (GetTypeId() == TYPEID_PLAYER)
sWorld->UpdateCharacterNameDataLevel(ToPlayer()->GetGUIDLow(), lvl);
}
void Unit::SetHealth(uint32 val)
{
if (getDeathState() == JUST_DIED)
val = 0;
else if (GetTypeId() == TYPEID_PLAYER && getDeathState() == DEAD)
val = 1;
else
{
uint32 maxHealth = GetMaxHealth();
if (maxHealth < val)
val = maxHealth;
}
SetUInt32Value(UNIT_FIELD_HEALTH, val);
// group update
if (Player* player = ToPlayer())
{
if (player->GetGroup())
player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
}
else if (Pet* pet = ToCreature()->ToPet())
{
if (pet->isControlled())
{
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
}
}
}
void Unit::SetMaxHealth(uint32 val)
{
if (!val)
val = 1;
uint32 health = GetHealth();
SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
// group update
if (GetTypeId() == TYPEID_PLAYER)
{
if (ToPlayer()->GetGroup())
ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
}
else if (Pet* pet = ToCreature()->ToPet())
{
if (pet->isControlled())
{
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
}
}
if (val < health)
SetHealth(val);
}
int32 Unit::GetPower(Powers power) const
{
uint32 powerIndex = GetPowerIndex(power);
if (powerIndex == MAX_POWERS)
return 0;
return GetUInt32Value(UNIT_FIELD_POWER1 + powerIndex);
}
int32 Unit::GetMaxPower(Powers power) const
{
uint32 powerIndex = GetPowerIndex(power);
if (powerIndex == MAX_POWERS)
return 0;
return GetInt32Value(UNIT_FIELD_MAXPOWER1 + powerIndex);
}
void Unit::SetPower(Powers power, int32 val)
{
uint32 powerIndex = GetPowerIndex(power);
if (powerIndex == MAX_POWERS)
return;
int32 maxPower = int32(GetMaxPower(power));
if (maxPower < val)
val = maxPower;
SetInt32Value(UNIT_FIELD_POWER1 + powerIndex, val);
if (IsInWorld())
{
WorldPacket data(SMSG_POWER_UPDATE, 8 + 4 + 1 + 4);
data.append(GetPackGUID());
data << uint32(1); //power count
data << uint8(powerIndex);
data << int32(val);
SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
}
// group update
if (Player* player = ToPlayer())
{
if (player->GetGroup())
player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
}
else if (Pet* pet = ToCreature()->ToPet())
{
if (pet->isControlled())
{
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
}
}
}
void Unit::SetMaxPower(Powers power, int32 val)
{
uint32 powerIndex = GetPowerIndex(power);
if (powerIndex == MAX_POWERS)
return;
int32 cur_power = GetPower(power);
SetInt32Value(UNIT_FIELD_MAXPOWER1 + powerIndex, val);
// group update
if (GetTypeId() == TYPEID_PLAYER)
{
if (ToPlayer()->GetGroup())
ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
}
else if (Pet* pet = ToCreature()->ToPet())
{
if (pet->isControlled())
{
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
}
}
if (val < cur_power)
SetPower(power, val);
}
uint32 Unit::GetPowerIndex(uint32 powerType) const
{
/// This is here because hunter pets are of the warrior class.
/// With the current implementation, the core only gives them
/// POWER_RAGE, so we enforce the class to hunter so that they
/// effectively get focus power.
uint32 classId = getClass();
if (ToPet() && ToPet()->getPetType() == HUNTER_PET)
classId = CLASS_HUNTER;
return GetPowerIndexByClass(powerType, classId);
}
int32 Unit::GetCreatePowers(Powers power) const
{
switch (power)
{
case POWER_MANA:
return GetCreateMana();
case POWER_RAGE:
return 1000;
case POWER_FOCUS:
if (GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_HUNTER)
return 100;
return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType() != HUNTER_PET ? 0 : 100);
case POWER_ENERGY:
return 100;
case POWER_RUNIC_POWER:
return 1000;
case POWER_RUNES:
return 0;
case POWER_SOUL_SHARDS:
return 3;
case POWER_ECLIPSE:
return 100;
case POWER_HOLY_POWER:
return 3;
case POWER_HEALTH:
return 0;
default:
break;
}
return 0;
}
void Unit::AddToWorld()
{
if (!IsInWorld())
{
WorldObject::AddToWorld();
}
}
void Unit::RemoveFromWorld()
{
// cleanup
ASSERT(GetGUID());
if (IsInWorld())
{
m_duringRemoveFromWorld = true;
if (IsVehicle())
RemoveVehicleKit();
RemoveCharmAuras();
RemoveBindSightAuras();
RemoveNotOwnSingleTargetAuras();
RemoveAllGameObjects();
RemoveAllDynObjects();
ExitVehicle(); // Remove applied auras with SPELL_AURA_CONTROL_VEHICLE
UnsummonAllTotems();
RemoveAllControlled();
RemoveAreaAurasDueToLeaveWorld();
if (GetCharmerGUID())
{
sLog->outFatal(LOG_FILTER_UNITS, "Unit %u has charmer guid when removed from world", GetEntry());
ASSERT(false);
}
if (Unit* owner = GetOwner())
{
if (owner->m_Controlled.find(this) != owner->m_Controlled.end())
{
sLog->outFatal(LOG_FILTER_UNITS, "Unit %u is in controlled list of %u when removed from world", GetEntry(), owner->GetEntry());
ASSERT(false);
}
}
WorldObject::RemoveFromWorld();
m_duringRemoveFromWorld = false;
}
}
void Unit::CleanupBeforeRemoveFromMap(bool finalCleanup)
{
// This needs to be before RemoveFromWorld to make GetCaster() return a valid pointer on aura removal
InterruptNonMeleeSpells(true);
if (IsInWorld())
RemoveFromWorld();
ASSERT(GetGUID());
// A unit may be in removelist and not in world, but it is still in grid
// and may have some references during delete
RemoveAllAuras();
RemoveAllGameObjects();
if (finalCleanup)
m_cleanupDone = true;
m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
CombatStop();
ClearComboPointHolders();
DeleteThreatList();
getHostileRefManager().setOnlineOfflineState(false);
GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
}
void Unit::CleanupsBeforeDelete(bool finalCleanup)
{
CleanupBeforeRemoveFromMap(finalCleanup);
if (Creature* thisCreature = ToCreature())
if (GetTransport())
GetTransport()->RemovePassenger(thisCreature);
}
void Unit::UpdateCharmAI()
{
if (GetTypeId() == TYPEID_PLAYER)
return;
if (i_disabledAI) // disabled AI must be primary AI
{
if (!isCharmed())
{
delete i_AI;
i_AI = i_disabledAI;
i_disabledAI = NULL;
}
}
else
{
if (isCharmed())
{
i_disabledAI = i_AI;
if (isPossessed() || IsVehicle())
i_AI = new PossessedAI(ToCreature());
else
i_AI = new PetAI(ToCreature());
}
}
}
CharmInfo* Unit::InitCharmInfo()
{
if (!m_charmInfo)
m_charmInfo = new CharmInfo(this);
return m_charmInfo;
}
void Unit::DeleteCharmInfo()
{
if (!m_charmInfo)
return;
m_charmInfo->RestoreState();
delete m_charmInfo;
m_charmInfo = NULL;
}
CharmInfo::CharmInfo(Unit* unit)
: _unit(unit), _CommandState(COMMAND_FOLLOW), _petnumber(0), _barInit(false),
_isCommandAttack(false), _isAtStay(false), _isFollowing(false), _isReturning(false),
_stayX(0.0f), _stayY(0.0f), _stayZ(0.0f)
{
for (uint8 i = 0; i < MAX_SPELL_CHARM; ++i)
_charmspells[i].SetActionAndType(0, ACT_DISABLED);
if (_unit->GetTypeId() == TYPEID_UNIT)
{
_oldReactState = _unit->ToCreature()->GetReactState();
_unit->ToCreature()->SetReactState(REACT_PASSIVE);
}
}
CharmInfo::~CharmInfo()
{
}
void CharmInfo::RestoreState()
{
if (_unit->GetTypeId() == TYPEID_UNIT)
if (Creature* creature = _unit->ToCreature())
creature->SetReactState(_oldReactState);
}
void CharmInfo::InitPetActionBar()
{
// the first 3 SpellOrActions are attack, follow and stay
for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_START - ACTION_BAR_INDEX_START; ++i)
SetActionBar(ACTION_BAR_INDEX_START + i, COMMAND_ATTACK - i, ACT_COMMAND);
// middle 4 SpellOrActions are spells/special attacks/abilities
for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END-ACTION_BAR_INDEX_PET_SPELL_START; ++i)
SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i, 0, ACT_PASSIVE);
// last 3 SpellOrActions are reactions
for (uint32 i = 0; i < ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_PET_SPELL_END; ++i)
SetActionBar(ACTION_BAR_INDEX_PET_SPELL_END + i, COMMAND_ATTACK - i, ACT_REACTION);
}
void CharmInfo::InitEmptyActionBar(bool withAttack)
{
if (withAttack)
SetActionBar(ACTION_BAR_INDEX_START, COMMAND_ATTACK, ACT_COMMAND);
else
SetActionBar(ACTION_BAR_INDEX_START, 0, ACT_PASSIVE);
for (uint32 x = ACTION_BAR_INDEX_START+1; x < ACTION_BAR_INDEX_END; ++x)
SetActionBar(x, 0, ACT_PASSIVE);
}
void CharmInfo::InitPossessCreateSpells()
{
InitEmptyActionBar();
if (_unit->GetTypeId() == TYPEID_UNIT)
{
for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
{
uint32 spellId = _unit->ToCreature()->m_spells[i];
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (spellInfo && !(spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_DEAD))
{
if (spellInfo->IsPassive())
_unit->CastSpell(_unit, spellInfo, true);
else
AddSpellToActionBar(spellInfo, ACT_PASSIVE);
}
}
}
}
void CharmInfo::InitCharmCreateSpells()
{
if (_unit->GetTypeId() == TYPEID_PLAYER) // charmed players don't have spells
{
InitEmptyActionBar();
return;
}
InitPetActionBar();
for (uint32 x = 0; x < MAX_SPELL_CHARM; ++x)
{
uint32 spellId = _unit->ToCreature()->m_spells[x];
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo || spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_DEAD)
{
_charmspells[x].SetActionAndType(spellId, ACT_DISABLED);
continue;
}
if (spellInfo->IsPassive())
{
_unit->CastSpell(_unit, spellInfo, true);
_charmspells[x].SetActionAndType(spellId, ACT_PASSIVE);
}
else
{
_charmspells[x].SetActionAndType(spellId, ACT_DISABLED);
ActiveStates newstate = ACT_PASSIVE;
if (!spellInfo->IsAutocastable())
newstate = ACT_PASSIVE;
else
{
if (spellInfo->NeedsExplicitUnitTarget())
{
newstate = ACT_ENABLED;
ToggleCreatureAutocast(spellInfo, true);
}
else
newstate = ACT_DISABLED;
}
AddSpellToActionBar(spellInfo, newstate);
}
}
}
bool CharmInfo::AddSpellToActionBar(SpellInfo const* spellInfo, ActiveStates newstate)
{
uint32 spell_id = spellInfo->Id;
uint32 first_id = spellInfo->GetFirstRankSpell()->Id;
// new spell rank can be already listed
for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
{
if (uint32 action = PetActionBar[i].GetAction())
{
if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr->GetFirstSpellInChain(action) == first_id)
{
PetActionBar[i].SetAction(spell_id);
return true;
}
}
}
// or use empty slot in other case
for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
{
if (!PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
{
SetActionBar(i, spell_id, newstate == ACT_DECIDE ? spellInfo->IsAutocastable() ? ACT_DISABLED : ACT_PASSIVE : newstate);
return true;
}
}
return false;
}
bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id)
{
uint32 first_id = sSpellMgr->GetFirstSpellInChain(spell_id);
for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
{
if (uint32 action = PetActionBar[i].GetAction())
{
if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr->GetFirstSpellInChain(action) == first_id)
{
SetActionBar(i, 0, ACT_PASSIVE);
return true;
}
}
}
return false;
}
void CharmInfo::ToggleCreatureAutocast(SpellInfo const* spellInfo, bool apply)
{
if (spellInfo->IsPassive())
return;
for (uint32 x = 0; x < MAX_SPELL_CHARM; ++x)
if (spellInfo->Id == _charmspells[x].GetAction())
_charmspells[x].SetType(apply ? ACT_ENABLED : ACT_DISABLED);
}
void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
{
_petnumber = petnumber;
if (statwindow)
_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, _petnumber);
else
_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
}
void CharmInfo::LoadPetActionBar(const std::string& data)
{
InitPetActionBar();
Tokenizer tokens(data, ' ');
if (tokens.size() != (ACTION_BAR_INDEX_END-ACTION_BAR_INDEX_START) * 2)
return; // non critical, will reset to default
uint8 index = ACTION_BAR_INDEX_START;
Tokenizer::const_iterator iter = tokens.begin();
for (; index < ACTION_BAR_INDEX_END; ++iter, ++index)
{
// use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion
ActiveStates type = ActiveStates(atol(*iter));
++iter;
uint32 action = uint32(atol(*iter));
PetActionBar[index].SetActionAndType(action, type);
// check correctness
if (PetActionBar[index].IsActionBarForSpell())
{
SpellInfo const* spelInfo = sSpellMgr->GetSpellInfo(PetActionBar[index].GetAction());
if (!spelInfo)
SetActionBar(index, 0, ACT_PASSIVE);
else if (!spelInfo->IsAutocastable())
SetActionBar(index, PetActionBar[index].GetAction(), ACT_PASSIVE);
}
}
}
void CharmInfo::BuildActionBar(WorldPacket* data)
{
for (uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
*data << uint32(PetActionBar[i].packedData);
}
void CharmInfo::SetSpellAutocast(SpellInfo const* spellInfo, bool state)
{
for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
{
if (spellInfo->Id == PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
{
PetActionBar[i].SetType(state ? ACT_ENABLED : ACT_DISABLED);
break;
}
}
}
bool Unit::isFrozen() const
{
return HasAuraState(AURA_STATE_FROZEN);
}
struct ProcTriggeredData
{
ProcTriggeredData(Aura* _aura)
: aura(_aura)
{
effMask = 0;
spellProcEvent = NULL;
}
SpellProcEventEntry const* spellProcEvent;
Aura* aura;
uint32 effMask;
};
typedef std::list< ProcTriggeredData > ProcTriggeredList;
// List of auras that CAN be trigger but may not exist in spell_proc_event
// in most case need for drop charges
// in some types of aura need do additional check
// for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
bool InitTriggerAuraData()
{
for (uint16 i = 0; i < TOTAL_AURAS; ++i)
{
isTriggerAura[i] = false;
isNonTriggerAura[i] = false;
isAlwaysTriggeredAura[i] = false;
}
isTriggerAura[SPELL_AURA_PROC_ON_POWER_AMOUNT] = true;
isTriggerAura[SPELL_AURA_DUMMY] = true;
isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura does not have charges but needs to be removed on trigger
isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
isTriggerAura[SPELL_AURA_MOD_STEALTH] = true;
isTriggerAura[SPELL_AURA_MOD_FEAR] = true; // Aura does not have charges but needs to be removed on trigger
isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
isTriggerAura[SPELL_AURA_TRANSFORM] = true;
isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
isTriggerAura[SPELL_AURA_SCHOOL_ABSORB] = true; // Savage Defense untested
isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
isTriggerAura[SPELL_AURA_MOD_MELEE_HASTE] = true;
isTriggerAura[SPELL_AURA_MOD_MELEE_HASTE_3] = true;
isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE] = true;
isTriggerAura[SPELL_AURA_RAID_PROC_FROM_CHARGE] = true;
isTriggerAura[SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE] = true;
isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
isTriggerAura[SPELL_AURA_MOD_SPELL_CRIT_CHANCE] = true;
isTriggerAura[SPELL_AURA_ABILITY_IGNORE_AURASTATE] = true;
isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN] = true;
isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK] = true;
isAlwaysTriggeredAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
isAlwaysTriggeredAura[SPELL_AURA_MOD_FEAR] = true;
isAlwaysTriggeredAura[SPELL_AURA_MOD_ROOT] = true;
isAlwaysTriggeredAura[SPELL_AURA_MOD_STUN] = true;
isAlwaysTriggeredAura[SPELL_AURA_TRANSFORM] = true;
isAlwaysTriggeredAura[SPELL_AURA_SPELL_MAGNET] = true;
isAlwaysTriggeredAura[SPELL_AURA_SCHOOL_ABSORB] = true;
isAlwaysTriggeredAura[SPELL_AURA_MOD_STEALTH] = true;
return true;
}
uint32 createProcExtendMask(SpellNonMeleeDamage* damageInfo, SpellMissInfo missCondition)
{
uint32 procEx = PROC_EX_NONE;
// Check victim state
if (missCondition != SPELL_MISS_NONE)
switch (missCondition)
{
case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
default:
break;
}
else
{
// On block
if (damageInfo->blocked)
procEx|=PROC_EX_BLOCK;
// On absorb
if (damageInfo->absorb)
procEx|=PROC_EX_ABSORB;
// On crit
if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
procEx|=PROC_EX_CRITICAL_HIT;
else
procEx|=PROC_EX_NORMAL_HIT;
}
return procEx;
}
void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellInfo const* procSpell, uint32 damage, SpellInfo const* procAura)
{
// Player is loaded now - do not allow passive spell casts to proc
if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->GetSession()->PlayerLoading())
return;
// For melee/ranged based attack need update skills and set some Aura states if victim present
if (procFlag & MELEE_BASED_TRIGGER_MASK && target)
{
// If exist crit/parry/dodge/block need update aura state (for victim and attacker)
if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
{
// for victim
if (isVictim)
{
// if victim and dodge attack
if (procExtra & PROC_EX_DODGE)
{
// Update AURA_STATE on dodge
if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
{
ModifyAuraState(AURA_STATE_DEFENSE, true);
StartReactiveTimer(REACTIVE_DEFENSE);
}
}
// if victim and parry attack
if (procExtra & PROC_EX_PARRY)
{
// For Hunters only Counterattack (skip Mongoose bite)
if (getClass() == CLASS_HUNTER)
{
ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
StartReactiveTimer(REACTIVE_HUNTER_PARRY);
}
else
{
ModifyAuraState(AURA_STATE_DEFENSE, true);
StartReactiveTimer(REACTIVE_DEFENSE);
}
}
// if and victim block attack
if (procExtra & PROC_EX_BLOCK)
{
ModifyAuraState(AURA_STATE_DEFENSE, true);
StartReactiveTimer(REACTIVE_DEFENSE);
}
}
else // For attacker
{
// Overpower on victim dodge
if (procExtra & PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
{
ToPlayer()->AddComboPoints(target, 1);
StartReactiveTimer(REACTIVE_OVERPOWER);
}
}
}
}
Unit* actor = isVictim ? target : this;
Unit* actionTarget = !isVictim ? target : this;
DamageInfo damageInfo = DamageInfo(actor, actionTarget, damage, procSpell, procSpell ? SpellSchoolMask(procSpell->SchoolMask) : SPELL_SCHOOL_MASK_NORMAL, SPELL_DIRECT_DAMAGE);
HealInfo healInfo = HealInfo(actor, actionTarget, damage, procSpell, procSpell ? SpellSchoolMask(procSpell->SchoolMask) : SPELL_SCHOOL_MASK_NORMAL);
ProcEventInfo eventInfo = ProcEventInfo(actor, actionTarget, target, procFlag, 0, 0, procExtra, NULL, &damageInfo, &healInfo);
ProcTriggeredList procTriggered;
// Fill procTriggered list
for (AuraApplicationMap::const_iterator itr = GetAppliedAuras().begin(); itr!= GetAppliedAuras().end(); ++itr)
{
// Do not allow auras to proc from effect triggered by itself
if (procAura && procAura->Id == itr->first)
continue;
ProcTriggeredData triggerData(itr->second->GetBase());
// Defensive procs are active on absorbs (so absorption effects are not a hindrance)
bool active = damage || (procExtra & PROC_EX_BLOCK && isVictim);
if (isVictim)
procExtra &= ~PROC_EX_INTERNAL_REQ_FAMILY;
SpellInfo const* spellProto = itr->second->GetBase()->GetSpellInfo();
// only auras that has triggered spell should proc from fully absorbed damage
if (procExtra & PROC_EX_ABSORB && isVictim)
if (damage || spellProto->Effects[EFFECT_0].TriggerSpell || spellProto->Effects[EFFECT_1].TriggerSpell || spellProto->Effects[EFFECT_2].TriggerSpell)
active = true;
if (!IsTriggeredAtSpellProcEvent(target, triggerData.aura, procSpell, procFlag, procExtra, attType, isVictim, active, triggerData.spellProcEvent))
continue;
// do checks using conditions table
ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL_PROC, spellProto->Id);
ConditionSourceInfo condInfo = ConditionSourceInfo(eventInfo.GetActor(), eventInfo.GetActionTarget());
if (!sConditionMgr->IsObjectMeetToConditions(condInfo, conditions))
continue;
// AuraScript Hook
if (!triggerData.aura->CallScriptCheckProcHandlers(itr->second, eventInfo))
continue;
// Triggered spells not triggering additional spells
bool triggered = !(spellProto->AttributesEx3 & SPELL_ATTR3_CAN_PROC_WITH_TRIGGERED) ?
(procExtra & PROC_EX_INTERNAL_TRIGGERED && !(procFlag & PROC_FLAG_DONE_TRAP_ACTIVATION)) : false;
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (itr->second->HasEffect(i))
{
AuraEffect* aurEff = itr->second->GetBase()->GetEffect(i);
// Skip this auras
if (isNonTriggerAura[aurEff->GetAuraType()])
continue;
// If not trigger by default and spellProcEvent == NULL - skip
if (!isTriggerAura[aurEff->GetAuraType()] && triggerData.spellProcEvent == NULL)
continue;
// Some spells must always trigger
if (!triggered || isAlwaysTriggeredAura[aurEff->GetAuraType()])
triggerData.effMask |= 1<<i;
}
}
if (triggerData.effMask)
procTriggered.push_front(triggerData);
}
// Nothing found
if (procTriggered.empty())
return;
// Note: must SetCantProc(false) before return
if (procExtra & (PROC_EX_INTERNAL_TRIGGERED | PROC_EX_INTERNAL_CANT_PROC))
SetCantProc(true);
// Handle effects proceed this time
for (ProcTriggeredList::const_iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
{
// look for aura in auras list, it may be removed while proc event processing
if (i->aura->IsRemoved())
continue;
bool useCharges = i->aura->IsUsingCharges();
// no more charges to use, prevent proc
if (useCharges && !i->aura->GetCharges())
continue;
bool takeCharges = false;
SpellInfo const* spellInfo = i->aura->GetSpellInfo();
uint32 Id = i->aura->GetId();
AuraApplication* aurApp = i->aura->GetApplicationOfTarget(GetGUID());
bool prepare = i->aura->CallScriptPrepareProcHandlers(aurApp, eventInfo);
// For players set spell cooldown if need
uint32 cooldown = 0;
if (prepare && GetTypeId() == TYPEID_PLAYER && i->spellProcEvent && i->spellProcEvent->cooldown)
cooldown = i->spellProcEvent->cooldown;
// Note: must SetCantProc(false) before return
if (spellInfo->AttributesEx3 & SPELL_ATTR3_DISABLE_PROC)
SetCantProc(true);
i->aura->CallScriptProcHandlers(aurApp, eventInfo);
// This bool is needed till separate aura effect procs are still here
bool handled = false;
if (HandleAuraProc(target, damage, i->aura, procSpell, procFlag, procExtra, cooldown, &handled))
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), Id);
takeCharges = true;
}
if (!handled)
{
for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex)
{
if (!(i->effMask & (1<<effIndex)))
continue;
AuraEffect* triggeredByAura = i->aura->GetEffect(effIndex);
ASSERT(triggeredByAura);
bool prevented = i->aura->CallScriptEffectProcHandlers(triggeredByAura, aurApp, eventInfo);
if (prevented)
{
takeCharges = true;
continue;
}
switch (triggeredByAura->GetAuraType())
{
case SPELL_AURA_PROC_TRIGGER_SPELL:
case SPELL_AURA_PROC_TRIGGER_SPELL_2:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
// Don`t drop charge or add cooldown for not started trigger
if (HandleProcTriggerSpell(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
takeCharges = true;
break;
}
case SPELL_AURA_PROC_TRIGGER_DAMAGE:
{
// target has to be valid
if (!eventInfo.GetProcTarget())
break;
triggeredByAura->HandleProcTriggerDamageAuraProc(aurApp, eventInfo); // this function is part of the new proc system
takeCharges = true;
break;
}
case SPELL_AURA_MANA_SHIELD:
case SPELL_AURA_DUMMY:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
if (HandleDummyAuraProc(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
takeCharges = true;
break;
}
case SPELL_AURA_PROC_ON_POWER_AMOUNT:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
if (HandleAuraProcOnPowerAmount(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
takeCharges = true;
break;
}
case SPELL_AURA_OBS_MOD_POWER:
case SPELL_AURA_MOD_SPELL_CRIT_CHANCE:
case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN:
case SPELL_AURA_MOD_MELEE_HASTE:
case SPELL_AURA_MOD_MELEE_HASTE_3:
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, isVictim ? "a victim's" : "an attacker's", triggeredByAura->GetId());
takeCharges = true;
break;
case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
if (HandleOverrideClassScriptAuraProc(target, damage, triggeredByAura, procSpell, cooldown))
takeCharges = true;
break;
}
case SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
HandleAuraRaidProcFromChargeWithValue(triggeredByAura);
takeCharges = true;
break;
}
case SPELL_AURA_RAID_PROC_FROM_CHARGE:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
HandleAuraRaidProcFromCharge(triggeredByAura);
takeCharges = true;
break;
}
case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
if (HandleProcTriggerSpell(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
takeCharges = true;
break;
}
case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
// Skip melee hits or instant cast spells
if (procSpell && procSpell->CalcCastTime() != 0)
takeCharges = true;
break;
case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
// Skip Melee hits and spells ws wrong school
if (procSpell && (triggeredByAura->GetMiscValue() & procSpell->SchoolMask)) // School check
takeCharges = true;
break;
case SPELL_AURA_SPELL_MAGNET:
// Skip Melee hits and targets with magnet aura
if (procSpell && (triggeredByAura->GetBase()->GetUnitOwner()->ToUnit() == ToUnit())) // Magnet
takeCharges = true;
break;
case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
case SPELL_AURA_MOD_POWER_COST_SCHOOL:
// Skip melee hits and spells ws wrong school or zero cost
if (procSpell &&
(procSpell->ManaCost != 0 || procSpell->ManaCostPercentage != 0) && // Cost check
(triggeredByAura->GetMiscValue() & procSpell->SchoolMask)) // School check
takeCharges = true;
break;
case SPELL_AURA_MECHANIC_IMMUNITY:
// Compare mechanic
if (procSpell && procSpell->Mechanic == uint32(triggeredByAura->GetMiscValue()))
takeCharges = true;
break;
case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
// Compare mechanic
if (procSpell && procSpell->Mechanic == uint32(triggeredByAura->GetMiscValue()))
takeCharges = true;
break;
case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
// Compare casters
if (triggeredByAura->GetCasterGUID() == target->GetGUID())
takeCharges = true;
break;
// CC Auras which use their amount amount to drop
// Are there any more auras which need this?
case SPELL_AURA_MOD_CONFUSE:
case SPELL_AURA_MOD_FEAR:
case SPELL_AURA_MOD_STUN:
case SPELL_AURA_MOD_ROOT:
case SPELL_AURA_TRANSFORM:
{
// chargeable mods are breaking on hit
if (useCharges)
takeCharges = true;
else
{
// Spell own direct damage at apply wont break the CC
if (procSpell && (procSpell->Id == triggeredByAura->GetId()))
{
Aura* aura = triggeredByAura->GetBase();
// called from spellcast, should not have ticked yet
if (aura->GetDuration() == aura->GetMaxDuration())
break;
}
int32 damageLeft = triggeredByAura->GetAmount();
// No damage left
if (damageLeft < int32(damage))
i->aura->Remove();
else
triggeredByAura->SetAmount(damageLeft - damage);
}
break;
}
//case SPELL_AURA_ADD_FLAT_MODIFIER:
//case SPELL_AURA_ADD_PCT_MODIFIER:
// HandleSpellModAuraProc
//break;
default:
// nothing do, just charges counter
takeCharges = true;
break;
} // switch (triggeredByAura->GetAuraType())
i->aura->CallScriptAfterEffectProcHandlers(triggeredByAura, aurApp, eventInfo);
} // for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex)
} // if (!handled)
// Remove charge (aura can be removed by triggers)
if (prepare && useCharges && takeCharges)
i->aura->DropCharge();
i->aura->CallScriptAfterProcHandlers(aurApp, eventInfo);
if (spellInfo->AttributesEx3 & SPELL_ATTR3_DISABLE_PROC)
SetCantProc(false);
}
// Cleanup proc requirements
if (procExtra & (PROC_EX_INTERNAL_TRIGGERED | PROC_EX_INTERNAL_CANT_PROC))
SetCantProc(false);
}
void Unit::GetProcAurasTriggeredOnEvent(std::list<AuraApplication*>& aurasTriggeringProc, std::list<AuraApplication*>* procAuras, ProcEventInfo eventInfo)
{
// use provided list of auras which can proc
if (procAuras)
{
for (std::list<AuraApplication*>::iterator itr = procAuras->begin(); itr!= procAuras->end(); ++itr)
{
ASSERT((*itr)->GetTarget() == this);
if (!(*itr)->GetRemoveMode())
if ((*itr)->GetBase()->IsProcTriggeredOnEvent(*itr, eventInfo))
{
(*itr)->GetBase()->PrepareProcToTrigger(*itr, eventInfo);
aurasTriggeringProc.push_back(*itr);
}
}
}
// or generate one on our own
else
{
for (AuraApplicationMap::iterator itr = GetAppliedAuras().begin(); itr!= GetAppliedAuras().end(); ++itr)
{
if (itr->second->GetBase()->IsProcTriggeredOnEvent(itr->second, eventInfo))
{
itr->second->GetBase()->PrepareProcToTrigger(itr->second, eventInfo);
aurasTriggeringProc.push_back(itr->second);
}
}
}
}
void Unit::TriggerAurasProcOnEvent(CalcDamageInfo& damageInfo)
{
DamageInfo dmgInfo = DamageInfo(damageInfo);
TriggerAurasProcOnEvent(NULL, NULL, damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, 0, 0, damageInfo.procEx, NULL, &dmgInfo, NULL);
}
void Unit::TriggerAurasProcOnEvent(std::list<AuraApplication*>* myProcAuras, std::list<AuraApplication*>* targetProcAuras, Unit* actionTarget, uint32 typeMaskActor, uint32 typeMaskActionTarget, uint32 spellTypeMask, uint32 spellPhaseMask, uint32 hitMask, Spell* spell, DamageInfo* damageInfo, HealInfo* healInfo)
{
// prepare data for self trigger
ProcEventInfo myProcEventInfo = ProcEventInfo(this, actionTarget, actionTarget, typeMaskActor, spellTypeMask, spellPhaseMask, hitMask, spell, damageInfo, healInfo);
std::list<AuraApplication*> myAurasTriggeringProc;
GetProcAurasTriggeredOnEvent(myAurasTriggeringProc, myProcAuras, myProcEventInfo);
// prepare data for target trigger
ProcEventInfo targetProcEventInfo = ProcEventInfo(this, actionTarget, this, typeMaskActionTarget, spellTypeMask, spellPhaseMask, hitMask, spell, damageInfo, healInfo);
std::list<AuraApplication*> targetAurasTriggeringProc;
if (typeMaskActionTarget)
GetProcAurasTriggeredOnEvent(targetAurasTriggeringProc, targetProcAuras, targetProcEventInfo);
TriggerAurasProcOnEvent(myProcEventInfo, myAurasTriggeringProc);
if (typeMaskActionTarget)
TriggerAurasProcOnEvent(targetProcEventInfo, targetAurasTriggeringProc);
}
void Unit::TriggerAurasProcOnEvent(ProcEventInfo& eventInfo, std::list<AuraApplication*>& aurasTriggeringProc)
{
for (std::list<AuraApplication*>::iterator itr = aurasTriggeringProc.begin(); itr != aurasTriggeringProc.end(); ++itr)
{
if (!(*itr)->GetRemoveMode())
(*itr)->GetBase()->TriggerProcOnEvent(*itr, eventInfo);
}
}
SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
{
return SPELL_SCHOOL_MASK_NORMAL;
}
Player* Unit::GetSpellModOwner() const
{
if (GetTypeId() == TYPEID_PLAYER)
return (Player*)this;
if (ToCreature()->isPet() || ToCreature()->isTotem())
{
Unit* owner = GetOwner();
if (owner && owner->GetTypeId() == TYPEID_PLAYER)
return (Player*)owner;
}
return NULL;
}
///----------Pet responses methods-----------------
void Unit::SendPetCastFail(uint32 spellid, SpellCastResult result)
{
if (result == SPELL_CAST_OK)
return;
Unit* owner = GetCharmerOrOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return;
WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1);
data << uint8(0); // cast count
data << uint32(spellid);
data << uint8(result);
owner->ToPlayer()->GetSession()->SendPacket(&data);
}
void Unit::SendPetActionFeedback(uint8 msg)
{
Unit* owner = GetOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return;
WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
data << uint8(msg);
owner->ToPlayer()->GetSession()->SendPacket(&data);
}
void Unit::SendPetTalk(uint32 pettalk)
{
Unit* owner = GetOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return;
WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4);
data << uint64(GetGUID());
data << uint32(pettalk);
owner->ToPlayer()->GetSession()->SendPacket(&data);
}
void Unit::SendPetAIReaction(uint64 guid)
{
Unit* owner = GetOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return;
WorldPacket data(SMSG_AI_REACTION, 8 + 4);
data << uint64(guid);
data << uint32(AI_REACTION_HOSTILE);
owner->ToPlayer()->GetSession()->SendPacket(&data);
}
///----------End of Pet responses methods----------
void Unit::StopMoving()
{
ClearUnitState(UNIT_STATE_MOVING);
// not need send any packets if not in world or not moving
if (!IsInWorld() || movespline->Finalized())
return;
Movement::MoveSplineInit init(this);
init.MoveTo(GetPositionX(), GetPositionY(), GetPositionZMinusOffset(), false);
init.SetFacing(GetOrientation());
init.Launch();
}
void Unit::SendMovementFlagUpdate(bool self /* = false */)
{
WorldPacket data;
BuildHeartBeatMsg(&data);
SendMessageToSet(&data, self);
}
bool Unit::IsSitState() const
{
uint8 s = getStandState();
return
s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
s == UNIT_STAND_STATE_SIT;
}
bool Unit::IsStandState() const
{
uint8 s = getStandState();
return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
}
void Unit::SetStandState(uint8 state)
{
SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
if (IsStandState())
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
if (GetTypeId() == TYPEID_PLAYER)
{
WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
data << (uint8)state;
ToPlayer()->GetSession()->SendPacket(&data);
}
}
bool Unit::IsPolymorphed() const
{
uint32 transformId = getTransForm();
if (!transformId)
return false;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(transformId);
if (!spellInfo)
return false;
return spellInfo->GetSpellSpecific() == SPELL_SPECIFIC_MAGE_POLYMORPH;
}
void Unit::SetDisplayId(uint32 modelId)
{
SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
if (GetTypeId() == TYPEID_UNIT && ToCreature()->isPet())
{
Pet* pet = ToPet();
if (!pet->isControlled())
return;
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
}
}
void Unit::RestoreDisplayId()
{
AuraEffect* handledAura = NULL;
// try to receive model from transform auras
Unit::AuraEffectList const& transforms = GetAuraEffectsByType(SPELL_AURA_TRANSFORM);
if (!transforms.empty())
{
// iterate over already applied transform auras - from newest to oldest
for (Unit::AuraEffectList::const_reverse_iterator i = transforms.rbegin(); i != transforms.rend(); ++i)
{
if (AuraApplication const* aurApp = (*i)->GetBase()->GetApplicationOfTarget(GetGUID()))
{
if (!handledAura)
handledAura = (*i);
// prefer negative auras
if (!aurApp->IsPositive())
{
handledAura = (*i);
break;
}
}
}
}
// transform aura was found
if (handledAura)
handledAura->HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true);
// we've found shapeshift
else if (uint32 modelId = GetModelForForm(GetShapeshiftForm()))
SetDisplayId(modelId);
// no auras found - set modelid to default
else
SetDisplayId(GetNativeDisplayId());
}
void Unit::ClearComboPointHolders()
{
while (!m_ComboPointHolders.empty())
{
uint32 lowguid = *m_ComboPointHolders.begin();
Player* player = ObjectAccessor::FindPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
if (player && player->GetComboTarget() == GetGUID()) // recheck for safe
player->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
else
m_ComboPointHolders.erase(lowguid); // or remove manually
}
}
void Unit::ClearAllReactives()
{
for (uint8 i = 0; i < MAX_REACTIVE; ++i)
m_reactiveTimer[i] = 0;
if (HasAuraState(AURA_STATE_DEFENSE))
ModifyAuraState(AURA_STATE_DEFENSE, false);
if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->ClearComboPoints();
}
void Unit::UpdateReactives(uint32 p_time)
{
for (uint8 i = 0; i < MAX_REACTIVE; ++i)
{
ReactiveType reactive = ReactiveType(i);
if (!m_reactiveTimer[reactive])
continue;
if (m_reactiveTimer[reactive] <= p_time)
{
m_reactiveTimer[reactive] = 0;
switch (reactive)
{
case REACTIVE_DEFENSE:
if (HasAuraState(AURA_STATE_DEFENSE))
ModifyAuraState(AURA_STATE_DEFENSE, false);
break;
case REACTIVE_HUNTER_PARRY:
if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
break;
case REACTIVE_OVERPOWER:
if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
ToPlayer()->ClearComboPoints();
break;
default:
break;
}
}
else
{
m_reactiveTimer[reactive] -= p_time;
}
}
}
Unit* Unit::SelectNearbyTarget(Unit* exclude, float dist) const
{
std::list<Unit*> targets;
Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, dist);
Trinity::UnitListSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
VisitNearbyObject(dist, searcher);
// remove current target
if (getVictim())
targets.remove(getVictim());
if (exclude)
targets.remove(exclude);
// remove not LoS targets
for (std::list<Unit*>::iterator tIter = targets.begin(); tIter != targets.end();)
{
if (!IsWithinLOSInMap(*tIter) || (*tIter)->isTotem() || (*tIter)->isSpiritService() || (*tIter)->GetCreatureType() == CREATURE_TYPE_CRITTER)
targets.erase(tIter++);
else
++tIter;
}
// no appropriate targets
if (targets.empty())
return NULL;
// select random
return Trinity::Containers::SelectRandomContainerElement(targets);
}
void Unit::ApplyAttackTimePercentMod(WeaponAttackType att, float val, bool apply)
{
float remainingTimePct = (float)m_attackTimer[att] / (GetAttackTime(att) * m_modAttackSpeedPct[att]);
if (val > 0)
{
ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att, val, !apply);
if (GetTypeId() == TYPEID_PLAYER)
{
if (att == BASE_ATTACK)
ApplyPercentModFloatValue(PLAYER_FIELD_MOD_HASTE, val, !apply);
else if (att == RANGED_ATTACK)
ApplyPercentModFloatValue(PLAYER_FIELD_MOD_RANGED_HASTE, val, !apply);
}
}
else
{
ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att, -val, apply);
if (GetTypeId() == TYPEID_PLAYER)
{
if (att == BASE_ATTACK)
ApplyPercentModFloatValue(PLAYER_FIELD_MOD_HASTE, -val, apply);
else if (att == RANGED_ATTACK)
ApplyPercentModFloatValue(PLAYER_FIELD_MOD_RANGED_HASTE, -val, apply);
}
}
m_attackTimer[att] = uint32(GetAttackTime(att) * m_modAttackSpeedPct[att] * remainingTimePct);
}
void Unit::ApplyCastTimePercentMod(float val, bool apply)
{
if (val > 0)
{
ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED, val, !apply);
ApplyPercentModFloatValue(UNIT_MOD_CAST_HASTE, val, !apply);
}
else
{
ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED, -val, apply);
ApplyPercentModFloatValue(UNIT_MOD_CAST_HASTE, -val, apply);
}
}
uint32 Unit::GetCastingTimeForBonus(SpellInfo const* spellProto, DamageEffectType damagetype, uint32 CastingTime) const
{
// Not apply this to creature casted spells with casttime == 0
if (CastingTime == 0 && GetTypeId() == TYPEID_UNIT && !ToCreature()->isPet())
return 3500;
if (CastingTime > 7000) CastingTime = 7000;
if (CastingTime < 1500) CastingTime = 1500;
if (damagetype == DOT && !spellProto->IsChanneled())
CastingTime = 3500;
int32 overTime = 0;
uint8 effects = 0;
bool DirectDamage = false;
bool AreaEffect = false;
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; i++)
{
switch (spellProto->Effects[i].Effect)
{
case SPELL_EFFECT_SCHOOL_DAMAGE:
case SPELL_EFFECT_POWER_DRAIN:
case SPELL_EFFECT_HEALTH_LEECH:
case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
case SPELL_EFFECT_POWER_BURN:
case SPELL_EFFECT_HEAL:
DirectDamage = true;
break;
case SPELL_EFFECT_APPLY_AURA:
switch (spellProto->Effects[i].ApplyAuraName)
{
case SPELL_AURA_PERIODIC_DAMAGE:
case SPELL_AURA_PERIODIC_HEAL:
case SPELL_AURA_PERIODIC_LEECH:
if (spellProto->GetDuration())
overTime = spellProto->GetDuration();
break;
default:
// -5% per additional effect
++effects;
break;
}
default:
break;
}
if (spellProto->Effects[i].IsTargetingArea())
AreaEffect = true;
}
// Combined Spells with Both Over Time and Direct Damage
if (overTime > 0 && CastingTime > 0 && DirectDamage)
{
// mainly for DoTs which are 3500 here otherwise
uint32 OriginalCastTime = spellProto->CalcCastTime();
if (OriginalCastTime > 7000) OriginalCastTime = 7000;
if (OriginalCastTime < 1500) OriginalCastTime = 1500;
// Portion to Over Time
float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f));
if (damagetype == DOT)
CastingTime = uint32(CastingTime * PtOT);
else if (PtOT < 1.0f)
CastingTime = uint32(CastingTime * (1 - PtOT));
else
CastingTime = 0;
}
// Area Effect Spells receive only half of bonus
if (AreaEffect)
CastingTime /= 2;
// 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j)
{
if (spellProto->Effects[j].Effect == SPELL_EFFECT_HEALTH_LEECH ||
(spellProto->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA && spellProto->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_LEECH))
{
CastingTime /= 2;
break;
}
}
// -5% of total per any additional effect
for (uint8 i = 0; i < effects; ++i)
CastingTime *= 0.95f;
return CastingTime;
}
void Unit::UpdateAuraForGroup(uint8 slot)
{
if (slot >= MAX_AURAS) // slot not found, return
return;
if (Player* player = ToPlayer())
{
if (player->GetGroup())
{
player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
player->SetAuraUpdateMaskForRaid(slot);
}
}
else if (GetTypeId() == TYPEID_UNIT && ToCreature()->isPet())
{
Pet* pet = ((Pet*)this);
if (pet->isControlled())
{
Unit* owner = GetOwner();
if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && owner->ToPlayer()->GetGroup())
{
owner->ToPlayer()->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
pet->SetAuraUpdateMaskForRaid(slot);
}
}
}
}
float Unit::CalculateDefaultCoefficient(SpellInfo const* spellInfo, DamageEffectType damagetype) const
{
// Damage over Time spells bonus calculation
float DotFactor = 1.0f;
if (damagetype == DOT)
{
int32 DotDuration = spellInfo->GetDuration();
if (!spellInfo->IsChanneled() && DotDuration > 0)
DotFactor = DotDuration / 15000.0f;
if (uint32 DotTicks = spellInfo->GetMaxTicks())
DotFactor /= DotTicks;
}
int32 CastingTime = spellInfo->IsChanneled() ? spellInfo->GetDuration() : spellInfo->CalcCastTime();
// Distribute Damage over multiple effects, reduce by AoE
CastingTime = GetCastingTimeForBonus(spellInfo, damagetype, CastingTime);
// As wowwiki says: C = (Cast Time / 3.5)
return (CastingTime / 3500.0f) * DotFactor;
}
float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
{
if (!normalized || GetTypeId() != TYPEID_PLAYER)
return float(GetAttackTime(attType)) / 1000.0f;
Item* Weapon = ToPlayer()->GetWeaponForAttack(attType, true);
if (!Weapon)
return 2.4f; // fist attack
switch (Weapon->GetTemplate()->InventoryType)
{
case INVTYPE_2HWEAPON:
return 3.3f;
case INVTYPE_RANGED:
case INVTYPE_RANGEDRIGHT:
case INVTYPE_THROWN:
return 2.8f;
case INVTYPE_WEAPON:
case INVTYPE_WEAPONMAINHAND:
case INVTYPE_WEAPONOFFHAND:
default:
return Weapon->GetTemplate()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7f : 2.4f;
}
}
void Unit::SetContestedPvP(Player* attackedPlayer)
{
Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
if (!player || (attackedPlayer && (attackedPlayer == player || (player->duel && player->duel->opponent == attackedPlayer))))
return;
player->SetContestedPvPTimer(30000);
if (!player->HasUnitState(UNIT_STATE_ATTACK_PLAYER))
{
player->AddUnitState(UNIT_STATE_ATTACK_PLAYER);
player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
// call MoveInLineOfSight for nearby contested guards
UpdateObjectVisibility();
}
if (!HasUnitState(UNIT_STATE_ATTACK_PLAYER))
{
AddUnitState(UNIT_STATE_ATTACK_PLAYER);
// call MoveInLineOfSight for nearby contested guards
UpdateObjectVisibility();
}
}
void Unit::AddPetAura(PetAura const* petSpell)
{
if (GetTypeId() != TYPEID_PLAYER)
return;
m_petAuras.insert(petSpell);
if (Pet* pet = ToPlayer()->GetPet())
pet->CastPetAura(petSpell);
}
void Unit::RemovePetAura(PetAura const* petSpell)
{
if (GetTypeId() != TYPEID_PLAYER)
return;
m_petAuras.erase(petSpell);
if (Pet* pet = ToPlayer()->GetPet())
pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
}
Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget, uint32 spell_id)
{
if (GetTypeId() != TYPEID_PLAYER)
return NULL;
Pet* pet = new Pet((Player*)this, HUNTER_PET);
if (!pet->CreateBaseAtCreature(creatureTarget))
{
delete pet;
return NULL;
}
uint8 level = creatureTarget->getLevel() + 5 < getLevel() ? (getLevel() - 5) : creatureTarget->getLevel();
InitTamedPet(pet, level, spell_id);
return pet;
}
Pet* Unit::CreateTamedPetFrom(uint32 creatureEntry, uint32 spell_id)
{
if (GetTypeId() != TYPEID_PLAYER)
return NULL;
CreatureTemplate const* creatureInfo = sObjectMgr->GetCreatureTemplate(creatureEntry);
if (!creatureInfo)
return NULL;
Pet* pet = new Pet((Player*)this, HUNTER_PET);
if (!pet->CreateBaseAtCreatureInfo(creatureInfo, this) || !InitTamedPet(pet, getLevel(), spell_id))
{
delete pet;
return NULL;
}
return pet;
}
bool Unit::InitTamedPet(Pet* pet, uint8 level, uint32 spell_id)
{
pet->SetCreatorGUID(GetGUID());
pet->setFaction(getFaction());
pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
if (GetTypeId() == TYPEID_PLAYER)
pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
if (!pet->InitStatsForLevel(level))
{
sLog->outError(LOG_FILTER_UNITS, "Pet::InitStatsForLevel() failed for creature (Entry: %u)!", pet->GetEntry());
return false;
}
pet->GetCharmInfo()->SetPetNumber(sObjectMgr->GeneratePetNumber(), true);
// this enables pet details window (Shift+P)
pet->InitPetCreateSpells();
//pet->InitLevelupSpellsForLevel();
pet->SetFullHealth();
return true;
}
bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const* & spellProcEvent)
{
SpellInfo const* spellProto = aura->GetSpellInfo();
// let the aura be handled by new proc system if it has new entry
if (sSpellMgr->GetSpellProcEntry(spellProto->Id))
return false;
// Get proc Event Entry
spellProcEvent = sSpellMgr->GetSpellProcEvent(spellProto->Id);
// Get EventProcFlag
uint32 EventProcFlag;
if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
EventProcFlag = spellProcEvent->procFlags;
else
EventProcFlag = spellProto->ProcFlags; // else get from spell proto
// Continue if no trigger exist
if (!EventProcFlag)
return false;
// Additional checks for triggered spells (ignore trap casts)
if (procExtra & PROC_EX_INTERNAL_TRIGGERED && !(procFlag & PROC_FLAG_DONE_TRAP_ACTIVATION))
{
if (!(spellProto->AttributesEx3 & SPELL_ATTR3_CAN_PROC_WITH_TRIGGERED))
return false;
}
// Check spellProcEvent data requirements
if (!sSpellMgr->IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
return false;
// In most cases req get honor or XP from kill
if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
{
bool allow = false;
if (victim)
allow = ToPlayer()->isHonorOrXPTarget(victim);
// Shadow Word: Death - can trigger from every kill
if (aura->GetId() == 32409)
allow = true;
if (!allow)
return false;
}
// Aura added by spell can`t trigger from self (prevent drop charges/do triggers)
// But except periodic and kill triggers (can triggered from self)
if (procSpell && procSpell->Id == spellProto->Id
&& !(spellProto->ProcFlags&(PROC_FLAG_TAKEN_PERIODIC | PROC_FLAG_KILL)))
return false;
// Check if current equipment allows aura to proc
if (!isVictim && GetTypeId() == TYPEID_PLAYER)
{
Player* player = ToPlayer();
if (spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
{
Item* item = NULL;
if (attType == BASE_ATTACK)
item = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
else if (attType == OFF_ATTACK)
item = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
else
item = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
if (player->IsInFeralForm())
return false;
if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetTemplate()->SubClass) & spellProto->EquippedItemSubClassMask))
return false;
}
else if (spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
{
// Check if player is wearing shield
Item* item = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetTemplate()->SubClass) & spellProto->EquippedItemSubClassMask))
return false;
}
}
// Get chance from spell
float chance = float(spellProto->ProcChance);
// If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
if (spellProcEvent && spellProcEvent->customChance)
chance = spellProcEvent->customChance;
// If PPM exist calculate chance from PPM
if (spellProcEvent && spellProcEvent->ppmRate != 0)
{
if (!isVictim)
{
uint32 WeaponSpeed = GetAttackTime(attType);
chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate, spellProto);
}
else
{
uint32 WeaponSpeed = victim->GetAttackTime(attType);
chance = victim->GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate, spellProto);
}
}
// Apply chance modifer aura
if (Player* modOwner = GetSpellModOwner())
{
modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CHANCE_OF_SUCCESS, chance);
}
return roll_chance_f(chance);
}
bool Unit::HandleAuraRaidProcFromChargeWithValue(AuraEffect* triggeredByAura)
{
// aura can be deleted at casts
SpellInfo const* spellProto = triggeredByAura->GetSpellInfo();
int32 heal = triggeredByAura->GetAmount();
uint64 caster_guid = triggeredByAura->GetCasterGUID();
// Currently only Prayer of Mending
if (!(spellProto->SpellFamilyName == SPELLFAMILY_PRIEST && spellProto->SpellFamilyFlags[1] & 0x20))
{
sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Unit::HandleAuraRaidProcFromChargeWithValue, received not handled spell: %u", spellProto->Id);
return false;
}
// jumps
int32 jumps = triggeredByAura->GetBase()->GetCharges()-1;
// current aura expire
triggeredByAura->GetBase()->SetCharges(1); // will removed at next charges decrease
// next target selection
if (jumps > 0)
{
if (Unit* caster = triggeredByAura->GetCaster())
{
float radius = triggeredByAura->GetSpellInfo()->Effects[triggeredByAura->GetEffIndex()].CalcRadius(caster);
if (Unit* target = GetNextRandomRaidMemberOrPet(radius))
{
CastCustomSpell(target, spellProto->Id, &heal, NULL, NULL, true, NULL, triggeredByAura, caster_guid);
if (Aura* aura = target->GetAura(spellProto->Id, caster->GetGUID()))
aura->SetCharges(jumps);
}
}
}
// heal
CastCustomSpell(this, 33110, &heal, NULL, NULL, true, NULL, NULL, caster_guid);
return true;
}
bool Unit::HandleAuraRaidProcFromCharge(AuraEffect* triggeredByAura)
{
// aura can be deleted at casts
SpellInfo const* spellProto = triggeredByAura->GetSpellInfo();
uint32 damageSpellId;
switch (spellProto->Id)
{
case 57949: // shiver
damageSpellId = 57952;
//animationSpellId = 57951; dummy effects for jump spell have unknown use (see also 41637)
break;
case 59978: // shiver
damageSpellId = 59979;
break;
case 43593: // Cold Stare
damageSpellId = 43594;
break;
default:
sLog->outError(LOG_FILTER_UNITS, "Unit::HandleAuraRaidProcFromCharge, received unhandled spell: %u", spellProto->Id);
return false;
}
uint64 caster_guid = triggeredByAura->GetCasterGUID();
// jumps
int32 jumps = triggeredByAura->GetBase()->GetCharges()-1;
// current aura expire
triggeredByAura->GetBase()->SetCharges(1); // will removed at next charges decrease
// next target selection
if (jumps > 0)
{
if (Unit* caster = triggeredByAura->GetCaster())
{
float radius = triggeredByAura->GetSpellInfo()->Effects[triggeredByAura->GetEffIndex()].CalcRadius(caster);
if (Unit* target= GetNextRandomRaidMemberOrPet(radius))
{
CastSpell(target, spellProto, true, NULL, triggeredByAura, caster_guid);
if (Aura* aura = target->GetAura(spellProto->Id, caster->GetGUID()))
aura->SetCharges(jumps);
}
}
}
CastSpell(this, damageSpellId, true, NULL, triggeredByAura, caster_guid);
return true;
}
void Unit::SendDurabilityLoss(Player* receiver, uint32 percent)
{
WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 4);
data << uint32(percent);
receiver->GetSession()->SendPacket(&data);
}
void Unit::PlayOneShotAnimKit(uint32 id)
{
WorldPacket data(SMSG_PLAY_ONE_SHOT_ANIM_KIT, 7+2);
data.appendPackGUID(GetGUID());
data << uint16(id);
SendMessageToSet(&data, true);
}
void Unit::Kill(Unit* victim, bool durabilityLoss)
{
// Prevent killing unit twice (and giving reward from kill twice)
if (!victim->GetHealth())
return;
// find player: owner of controlled `this` or `this` itself maybe
Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
Creature* creature = victim->ToCreature();
bool isRewardAllowed = true;
if (creature)
{
isRewardAllowed = creature->IsDamageEnoughForLootingAndReward();
if (!isRewardAllowed)
creature->SetLootRecipient(NULL);
}
if (isRewardAllowed && creature && creature->GetLootRecipient())
player = creature->GetLootRecipient();
// Reward player, his pets, and group/raid members
// call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
if (isRewardAllowed && player && player != victim)
{
WorldPacket data(SMSG_PARTYKILLLOG, (8+8)); // send event PARTY_KILL
data << uint64(player->GetGUID()); // player with killing blow
data << uint64(victim->GetGUID()); // victim
Player* looter = player;
if (Group* group = player->GetGroup())
{
group->BroadcastPacket(&data, group->GetMemberGroup(player->GetGUID()));
if (creature)
{
group->UpdateLooterGuid(creature, true);
if (group->GetLooterGuid())
{
looter = ObjectAccessor::FindPlayer(group->GetLooterGuid());
if (looter)
{
creature->SetLootRecipient(looter); // update creature loot recipient to the allowed looter.
group->SendLooter(creature, looter);
}
else
group->SendLooter(creature, NULL);
}
else
group->SendLooter(creature, NULL);
group->UpdateLooterGuid(creature);
}
}
else
{
player->SendDirectMessage(&data);
if (creature)
{
WorldPacket data2(SMSG_LOOT_LIST, 8 + 1 + 1);
data2 << uint64(creature->GetGUID());
data2 << uint8(0); // unk1
data2 << uint8(0); // no group looter
player->SendMessageToSet(&data2, true);
}
}
if (creature)
{
Loot* loot = &creature->loot;
if (creature->lootForPickPocketed)
creature->lootForPickPocketed = false;
loot->clear();
if (uint32 lootid = creature->GetCreatureTemplate()->lootid)
loot->FillLoot(lootid, LootTemplates_Creature, looter, false, false, creature->GetLootMode());
loot->generateMoneyLoot(creature->GetCreatureTemplate()->mingold, creature->GetCreatureTemplate()->maxgold);
}
player->RewardPlayerAndGroupAtKill(victim, false);
}
// Do KILL and KILLED procs. KILL proc is called only for the unit who landed the killing blow (and its owner - for pets and totems) regardless of who tapped the victim
if (isPet() || isTotem())
if (Unit* owner = GetOwner())
owner->ProcDamageAndSpell(victim, PROC_FLAG_KILL, PROC_FLAG_NONE, PROC_EX_NONE, 0);
if (victim->GetCreatureType() != CREATURE_TYPE_CRITTER)
ProcDamageAndSpell(victim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
// Proc auras on death - must be before aura/combat remove
victim->ProcDamageAndSpell(NULL, PROC_FLAG_DEATH, PROC_FLAG_NONE, PROC_EX_NONE, 0, BASE_ATTACK, 0);
// update get killing blow achievements, must be done before setDeathState to be able to require auras on target
// and before Spirit of Redemption as it also removes auras
if (player)
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS, 1, 0, 0, victim);
// if talent known but not triggered (check priest class for speedup check)
bool spiritOfRedemption = false;
if (victim->GetTypeId() == TYPEID_PLAYER && victim->getClass() == CLASS_PRIEST)
{
AuraEffectList const& dummyAuras = victim->GetAuraEffectsByType(SPELL_AURA_DUMMY);
for (AuraEffectList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
{
if ((*itr)->GetSpellInfo()->SpellIconID == 1654)
{
AuraEffect const* aurEff = *itr;
// save value before aura remove
uint32 ressSpellId = victim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
if (!ressSpellId)
ressSpellId = victim->ToPlayer()->GetResurrectionSpellId();
// Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
victim->RemoveAllAurasOnDeath();
// restore for use at real death
victim->SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
// FORM_SPIRITOFREDEMPTION and related auras
victim->CastSpell(victim, 27827, true, NULL, aurEff);
spiritOfRedemption = true;
break;
}
}
}
if (!spiritOfRedemption)
{
sLog->outDebug(LOG_FILTER_UNITS, "SET JUST_DIED");
victim->setDeathState(JUST_DIED);
}
// Inform pets (if any) when player kills target)
// MUST come after victim->setDeathState(JUST_DIED); or pet next target
// selection will get stuck on same target and break pet react state
if (player)
{
Pet* pet = player->GetPet();
if (pet && pet->isAlive() && pet->isControlled())
pet->AI()->KilledUnit(victim);
}
// 10% durability loss on death
// clean InHateListOf
if (Player* plrVictim = victim->ToPlayer())
{
// remember victim PvP death for corpse type and corpse reclaim delay
// at original death (not at SpiritOfRedemtionTalent timeout)
plrVictim->SetPvPDeath(player != NULL);
// only if not player and not controlled by player pet. And not at BG
if ((durabilityLoss && !player && !victim->ToPlayer()->InBattleground()) || (player && sWorld->getBoolConfig(CONFIG_DURABILITY_LOSS_IN_PVP)))
{
double baseLoss = sWorld->getRate(RATE_DURABILITY_LOSS_ON_DEATH);
uint32 loss = uint32(baseLoss - (baseLoss * plrVictim->GetTotalAuraMultiplier(SPELL_AURA_MOD_DURABILITY_LOSS)));
sLog->outDebug(LOG_FILTER_UNITS, "We are dead, losing %u percent durability", loss);
// Durability loss is calculated more accurately again for each item in Player::DurabilityLoss
plrVictim->DurabilityLossAll(baseLoss, false);
// durability lost message
SendDurabilityLoss(plrVictim, loss);
}
// Call KilledUnit for creatures
if (GetTypeId() == TYPEID_UNIT && IsAIEnabled)
ToCreature()->AI()->KilledUnit(victim);
// last damage from non duel opponent or opponent controlled creature
if (plrVictim->duel)
{
plrVictim->duel->opponent->CombatStopWithPets(true);
plrVictim->CombatStopWithPets(true);
plrVictim->DuelComplete(DUEL_INTERRUPTED);
}
}
else // creature died
{
sLog->outDebug(LOG_FILTER_UNITS, "DealDamageNotPlayer");
if (!creature->isPet())
{
creature->DeleteThreatList();
CreatureTemplate const* cInfo = creature->GetCreatureTemplate();
if (cInfo && (cInfo->lootid || cInfo->maxgold > 0))
creature->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
}
// Call KilledUnit for creatures, this needs to be called after the lootable flag is set
if (GetTypeId() == TYPEID_UNIT && IsAIEnabled)
ToCreature()->AI()->KilledUnit(victim);
// Call creature just died function
if (creature->IsAIEnabled)
creature->AI()->JustDied(this);
if (TempSummon* summon = creature->ToTempSummon())
if (Unit* summoner = summon->GetSummoner())
if (summoner->ToCreature() && summoner->IsAIEnabled)
summoner->ToCreature()->AI()->SummonedCreatureDies(creature, this);
// Dungeon specific stuff, only applies to players killing creatures
if (creature->GetInstanceId())
{
Map* instanceMap = creature->GetMap();
Player* creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
// TODO: do instance binding anyway if the charmer/owner is offline
if (instanceMap->IsDungeon() && creditedPlayer)
{
if (instanceMap->IsRaidOrHeroicDungeon())
{
if (creature->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
((InstanceMap*)instanceMap)->PermBindAllPlayers(creditedPlayer);
}
else
{
// the reset time is set but not added to the scheduler
// until the players leave the instance
time_t resettime = creature->GetRespawnTimeEx() + 2 * HOUR;
if (InstanceSave* save = sInstanceSaveMgr->GetInstanceSave(creature->GetInstanceId()))
if (save->GetResetTime() < resettime) save->SetResetTime(resettime);
}
}
}
}
// outdoor pvp things, do these after setting the death state, else the player activity notify won't work... doh...
// handle player kill only if not suicide (spirit of redemption for example)
if (player && this != victim)
{
if (OutdoorPvP* pvp = player->GetOutdoorPvP())
pvp->HandleKill(player, victim);
if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId()))
bf->HandleKill(player, victim);
}
//if (victim->GetTypeId() == TYPEID_PLAYER)
// if (OutdoorPvP* pvp = victim->ToPlayer()->GetOutdoorPvP())
// pvp->HandlePlayerActivityChangedpVictim->ToPlayer();
// battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
if (player && player->InBattleground())
{
if (Battleground* bg = player->GetBattleground())
{
if (victim->GetTypeId() == TYPEID_PLAYER)
bg->HandleKillPlayer((Player*)victim, player);
else
bg->HandleKillUnit(victim->ToCreature(), player);
}
}
// achievement stuff
if (victim->GetTypeId() == TYPEID_PLAYER)
{
if (GetTypeId() == TYPEID_UNIT)
victim->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
else if (GetTypeId() == TYPEID_PLAYER && victim != this)
victim->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ToPlayer()->GetTeam());
}
// Hook for OnPVPKill Event
if (Player* killerPlr = ToPlayer())
{
if (Player* killedPlr = victim->ToPlayer())
sScriptMgr->OnPVPKill(killerPlr, killedPlr);
else if (Creature* killedCre = victim->ToCreature())
sScriptMgr->OnCreatureKill(killerPlr, killedCre);
}
else if (Creature* killerCre = ToCreature())
{
if (Player* killed = victim->ToPlayer())
sScriptMgr->OnPlayerKilledByCreature(killerCre, killed);
}
}
void Unit::SetControlled(bool apply, UnitState state)
{
if (apply)
{
if (HasUnitState(state))
return;
AddUnitState(state);
switch (state)
{
case UNIT_STATE_STUNNED:
SetStunned(true);
CastStop();
break;
case UNIT_STATE_ROOT:
if (!HasUnitState(UNIT_STATE_STUNNED))
SetRooted(true);
break;
case UNIT_STATE_CONFUSED:
if (!HasUnitState(UNIT_STATE_STUNNED))
{
ClearUnitState(UNIT_STATE_MELEE_ATTACKING);
SendMeleeAttackStop();
// SendAutoRepeatCancel ?
SetConfused(true);
CastStop();
}
break;
case UNIT_STATE_FLEEING:
if (!HasUnitState(UNIT_STATE_STUNNED | UNIT_STATE_CONFUSED))
{
ClearUnitState(UNIT_STATE_MELEE_ATTACKING);
SendMeleeAttackStop();
// SendAutoRepeatCancel ?
SetFeared(true);
CastStop();
}
break;
default:
break;
}
}
else
{
switch (state)
{
case UNIT_STATE_STUNNED:
if (HasAuraType(SPELL_AURA_MOD_STUN))
return;
SetStunned(false);
break;
case UNIT_STATE_ROOT:
if (HasAuraType(SPELL_AURA_MOD_ROOT) || GetVehicle())
return;
SetRooted(false);
break;
case UNIT_STATE_CONFUSED:
if (HasAuraType(SPELL_AURA_MOD_CONFUSE))
return;
SetConfused(false);
break;
case UNIT_STATE_FLEEING:
if (HasAuraType(SPELL_AURA_MOD_FEAR))
return;
SetFeared(false);
break;
default:
return;
}
ClearUnitState(state);
if (HasUnitState(UNIT_STATE_STUNNED))
SetStunned(true);
else
{
if (HasUnitState(UNIT_STATE_ROOT))
SetRooted(true);
if (HasUnitState(UNIT_STATE_CONFUSED))
SetConfused(true);
else if (HasUnitState(UNIT_STATE_FLEEING))
SetFeared(true);
}
}
}
void Unit::SendMoveRoot(uint32 value)
{
ObjectGuid guid = GetGUID();
WorldPacket data(SMSG_MOVE_ROOT, 1 + 8 + 4);
data.WriteBit(guid[2]);
data.WriteBit(guid[7]);
data.WriteBit(guid[6]);
data.WriteBit(guid[0]);
data.WriteBit(guid[5]);
data.WriteBit(guid[4]);
data.WriteBit(guid[1]);
data.WriteBit(guid[3]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[5]);
data << uint32(value);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[6]);
SendMessageToSet(&data, true);
}
void Unit::SendMoveUnroot(uint32 value)
{
ObjectGuid guid = GetGUID();
WorldPacket data(SMSG_MOVE_UNROOT, 1 + 8 + 4);
data.WriteBit(guid[0]);
data.WriteBit(guid[1]);
data.WriteBit(guid[3]);
data.WriteBit(guid[7]);
data.WriteBit(guid[5]);
data.WriteBit(guid[2]);
data.WriteBit(guid[4]);
data.WriteBit(guid[6]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[1]);
data << uint32(value);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[5]);
SendMessageToSet(&data, true);
}
void Unit::SetStunned(bool apply)
{
if (apply)
{
SetTarget(0);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
// MOVEMENTFLAG_ROOT cannot be used in conjunction with MOVEMENTFLAG_MASK_MOVING (tested 3.3.5a)
// this will freeze clients. That's why we remove MOVEMENTFLAG_MASK_MOVING before
// setting MOVEMENTFLAG_ROOT
RemoveUnitMovementFlag(MOVEMENTFLAG_MASK_MOVING);
AddUnitMovementFlag(MOVEMENTFLAG_ROOT);
// Creature specific
if (GetTypeId() != TYPEID_PLAYER)
ToCreature()->StopMoving();
else
SetStandState(UNIT_STAND_STATE_STAND);
SendMoveRoot(0);
CastStop();
}
else
{
if (isAlive() && getVictim())
SetTarget(getVictim()->GetGUID());
// don't remove UNIT_FLAG_STUNNED for pet when owner is mounted (disabled pet's interface)
Unit* owner = GetOwner();
if (!owner || (owner->GetTypeId() == TYPEID_PLAYER && !owner->ToPlayer()->IsMounted()))
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
if (!HasUnitState(UNIT_STATE_ROOT)) // prevent moving if it also has root effect
{
SendMoveUnroot(0);
RemoveUnitMovementFlag(MOVEMENTFLAG_ROOT);
}
}
}
void Unit::SetRooted(bool apply)
{
if (apply)
{
if (m_rootTimes > 0) // blizzard internal check?
m_rootTimes++;
// MOVEMENTFLAG_ROOT cannot be used in conjunction with MOVEMENTFLAG_MASK_MOVING (tested 3.3.5a)
// this will freeze clients. That's why we remove MOVEMENTFLAG_MASK_MOVING before
// setting MOVEMENTFLAG_ROOT
RemoveUnitMovementFlag(MOVEMENTFLAG_MASK_MOVING);
AddUnitMovementFlag(MOVEMENTFLAG_ROOT);
if (GetTypeId() == TYPEID_PLAYER)
SendMoveRoot(m_rootTimes);
else
{
ObjectGuid guid = GetGUID();
WorldPacket data(SMSG_SPLINE_MOVE_ROOT, 8);
data.WriteBit(guid[5]);
data.WriteBit(guid[4]);
data.WriteBit(guid[6]);
data.WriteBit(guid[1]);
data.WriteBit(guid[3]);
data.WriteBit(guid[7]);
data.WriteBit(guid[2]);
data.WriteBit(guid[0]);
data.FlushBits();
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[4]);
SendMessageToSet(&data, true);
StopMoving();
}
}
else
{
if (!HasUnitState(UNIT_STATE_STUNNED)) // prevent moving if it also has stun effect
{
if (GetTypeId() == TYPEID_PLAYER)
SendMoveUnroot(++m_rootTimes);
else
{
ObjectGuid guid = GetGUID();
WorldPacket data(SMSG_SPLINE_MOVE_UNROOT, 8);
data.WriteBit(guid[0]);
data.WriteBit(guid[1]);
data.WriteBit(guid[6]);
data.WriteBit(guid[5]);
data.WriteBit(guid[3]);
data.WriteBit(guid[2]);
data.WriteBit(guid[7]);
data.WriteBit(guid[4]);
data.FlushBits();
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[4]);
SendMessageToSet(&data, true);
}
RemoveUnitMovementFlag(MOVEMENTFLAG_ROOT);
}
}
}
void Unit::SetFeared(bool apply)
{
if (apply)
{
SetTarget(0);
Unit* caster = NULL;
Unit::AuraEffectList const& fearAuras = GetAuraEffectsByType(SPELL_AURA_MOD_FEAR);
if (!fearAuras.empty())
caster = ObjectAccessor::GetUnit(*this, fearAuras.front()->GetCasterGUID());
if (!caster)
caster = getAttackerForHelper();
GetMotionMaster()->MoveFleeing(caster, fearAuras.empty() ? sWorld->getIntConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY) : 0); // caster == NULL processed in MoveFleeing
}
else
{
if (isAlive())
{
if (GetMotionMaster()->GetCurrentMovementGeneratorType() == FLEEING_MOTION_TYPE)
GetMotionMaster()->MovementExpired();
if (getVictim())
SetTarget(getVictim()->GetGUID());
}
}
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SetClientControl(this, !apply);
}
void Unit::SetConfused(bool apply)
{
if (apply)
{
SetTarget(0);
GetMotionMaster()->MoveConfused();
}
else
{
if (isAlive())
{
if (GetMotionMaster()->GetCurrentMovementGeneratorType() == CONFUSED_MOTION_TYPE)
GetMotionMaster()->MovementExpired();
if (getVictim())
SetTarget(getVictim()->GetGUID());
}
}
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SetClientControl(this, !apply);
}
bool Unit::SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* aurApp)
{
if (!charmer)
return false;
// dismount players when charmed
if (GetTypeId() == TYPEID_PLAYER)
RemoveAurasByType(SPELL_AURA_MOUNTED);
if (charmer->GetTypeId() == TYPEID_PLAYER)
charmer->RemoveAurasByType(SPELL_AURA_MOUNTED);
ASSERT(type != CHARM_TYPE_POSSESS || charmer->GetTypeId() == TYPEID_PLAYER);
ASSERT((type == CHARM_TYPE_VEHICLE) == IsVehicle());
sLog->outDebug(LOG_FILTER_UNITS, "SetCharmedBy: charmer %u (GUID %u), charmed %u (GUID %u), type %u.", charmer->GetEntry(), charmer->GetGUIDLow(), GetEntry(), GetGUIDLow(), uint32(type));
if (this == charmer)
{
sLog->outFatal(LOG_FILTER_UNITS, "Unit::SetCharmedBy: Unit %u (GUID %u) is trying to charm itself!", GetEntry(), GetGUIDLow());
return false;
}
//if (HasUnitState(UNIT_STATE_UNATTACKABLE))
// return false;
if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->GetTransport())
{
sLog->outFatal(LOG_FILTER_UNITS, "Unit::SetCharmedBy: Player on transport is trying to charm %u (GUID %u)", GetEntry(), GetGUIDLow());
return false;
}
// Already charmed
if (GetCharmerGUID())
{
sLog->outFatal(LOG_FILTER_UNITS, "Unit::SetCharmedBy: %u (GUID %u) has already been charmed but %u (GUID %u) is trying to charm it!", GetEntry(), GetGUIDLow(), charmer->GetEntry(), charmer->GetGUIDLow());
return false;
}
CastStop();
CombatStop(); // TODO: CombatStop(true) may cause crash (interrupt spells)
DeleteThreatList();
// Charmer stop charming
if (charmer->GetTypeId() == TYPEID_PLAYER)
{
charmer->ToPlayer()->StopCastingCharm();
charmer->ToPlayer()->StopCastingBindSight();
}
// Charmed stop charming
if (GetTypeId() == TYPEID_PLAYER)
{
ToPlayer()->StopCastingCharm();
ToPlayer()->StopCastingBindSight();
}
// StopCastingCharm may remove a possessed pet?
if (!IsInWorld())
{
sLog->outFatal(LOG_FILTER_UNITS, "Unit::SetCharmedBy: %u (GUID %u) is not in world but %u (GUID %u) is trying to charm it!", GetEntry(), GetGUIDLow(), charmer->GetEntry(), charmer->GetGUIDLow());
return false;
}
// charm is set by aura, and aura effect remove handler was called during apply handler execution
// prevent undefined behaviour
if (aurApp && aurApp->GetRemoveMode())
return false;
// Set charmed
Map* map = GetMap();
if (!IsVehicle() || (IsVehicle() && map && !map->IsBattleground()))
setFaction(charmer->getFaction());
charmer->SetCharm(this, true);
if (GetTypeId() == TYPEID_UNIT)
{
ToCreature()->AI()->OnCharmed(true);
GetMotionMaster()->MoveIdle();
}
else
{
Player* player = ToPlayer();
if (player->isAFK())
player->ToggleAFK();
player->SetClientControl(this, 0);
}
// charm is set by aura, and aura effect remove handler was called during apply handler execution
// prevent undefined behaviour
if (aurApp && aurApp->GetRemoveMode())
return false;
// Pets already have a properly initialized CharmInfo, don't overwrite it.
if (type != CHARM_TYPE_VEHICLE && !GetCharmInfo())
{
InitCharmInfo();
if (type == CHARM_TYPE_POSSESS)
GetCharmInfo()->InitPossessCreateSpells();
else
GetCharmInfo()->InitCharmCreateSpells();
}
if (charmer->GetTypeId() == TYPEID_PLAYER)
{
switch (type)
{
case CHARM_TYPE_VEHICLE:
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
charmer->ToPlayer()->SetClientControl(this, 1);
charmer->ToPlayer()->SetMover(this);
charmer->ToPlayer()->SetViewpoint(this, true);
charmer->ToPlayer()->VehicleSpellInitialize();
break;
case CHARM_TYPE_POSSESS:
AddUnitState(UNIT_STATE_POSSESSED);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
charmer->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE);
charmer->ToPlayer()->SetClientControl(this, 1);
charmer->ToPlayer()->SetMover(this);
charmer->ToPlayer()->SetViewpoint(this, true);
charmer->ToPlayer()->PossessSpellInitialize();
break;
case CHARM_TYPE_CHARM:
if (GetTypeId() == TYPEID_UNIT && charmer->getClass() == CLASS_WARLOCK)
{
CreatureTemplate const* cinfo = ToCreature()->GetCreatureTemplate();
if (cinfo && cinfo->type == CREATURE_TYPE_DEMON)
{
// to prevent client crash
SetByteValue(UNIT_FIELD_BYTES_0, 1, (uint8)CLASS_MAGE);
// just to enable stat window
if (GetCharmInfo())
GetCharmInfo()->SetPetNumber(sObjectMgr->GeneratePetNumber(), true);
// if charmed two demons the same session, the 2nd gets the 1st one's name
SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL))); // cast can't be helped
}
}
charmer->ToPlayer()->CharmSpellInitialize();
break;
default:
case CHARM_TYPE_CONVERT:
break;
}
}
return true;
}
void Unit::RemoveCharmedBy(Unit* charmer)
{
if (!isCharmed())
return;
if (!charmer)
charmer = GetCharmer();
if (charmer != GetCharmer()) // one aura overrides another?
{
// sLog->outFatal(LOG_FILTER_UNITS, "Unit::RemoveCharmedBy: this: " UI64FMTD " true charmer: " UI64FMTD " false charmer: " UI64FMTD,
// GetGUID(), GetCharmerGUID(), charmer->GetGUID());
// ASSERT(false);
return;
}
CharmType type;
if (HasUnitState(UNIT_STATE_POSSESSED))
type = CHARM_TYPE_POSSESS;
else if (charmer && charmer->IsOnVehicle(this))
type = CHARM_TYPE_VEHICLE;
else
type = CHARM_TYPE_CHARM;
CastStop();
CombatStop(); // TODO: CombatStop(true) may cause crash (interrupt spells)
getHostileRefManager().deleteReferences();
DeleteThreatList();
Map* map = GetMap();
if (!IsVehicle() || (IsVehicle() && map && !map->IsBattleground()))
RestoreFaction();
GetMotionMaster()->InitDefault();
if (type == CHARM_TYPE_POSSESS)
{
ClearUnitState(UNIT_STATE_POSSESSED);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
}
if (Creature* creature = ToCreature())
{
if (creature->AI())
creature->AI()->OnCharmed(false);
if (type != CHARM_TYPE_VEHICLE) // Vehicles' AI is never modified
{
creature->AIM_Initialize();
if (creature->AI() && charmer && charmer->isAlive())
creature->AI()->AttackStart(charmer);
}
}
else
ToPlayer()->SetClientControl(this, 1);
// If charmer still exists
if (!charmer)
return;
ASSERT(type != CHARM_TYPE_POSSESS || charmer->GetTypeId() == TYPEID_PLAYER);
ASSERT(type != CHARM_TYPE_VEHICLE || (GetTypeId() == TYPEID_UNIT && IsVehicle()));
charmer->SetCharm(this, false);
if (charmer->GetTypeId() == TYPEID_PLAYER)
{
switch (type)
{
case CHARM_TYPE_VEHICLE:
charmer->ToPlayer()->SetClientControl(charmer, 1);
charmer->ToPlayer()->SetViewpoint(this, false);
charmer->ToPlayer()->SetClientControl(this, 0);
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SetMover(this);
break;
case CHARM_TYPE_POSSESS:
charmer->ToPlayer()->SetClientControl(charmer, 1);
charmer->ToPlayer()->SetViewpoint(this, false);
charmer->ToPlayer()->SetClientControl(this, 0);
charmer->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE);
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SetMover(this);
break;
case CHARM_TYPE_CHARM:
if (GetTypeId() == TYPEID_UNIT && charmer->getClass() == CLASS_WARLOCK)
{
CreatureTemplate const* cinfo = ToCreature()->GetCreatureTemplate();
if (cinfo && cinfo->type == CREATURE_TYPE_DEMON)
{
SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class));
if (GetCharmInfo())
GetCharmInfo()->SetPetNumber(0, true);
else
sLog->outError(LOG_FILTER_UNITS, "Aura::HandleModCharm: target="UI64FMTD" with typeid=%d has a charm aura but no charm info!", GetGUID(), GetTypeId());
}
}
break;
default:
case CHARM_TYPE_CONVERT:
break;
}
}
// a guardian should always have charminfo
if (charmer->GetTypeId() == TYPEID_PLAYER && this != charmer->GetFirstControlled())
charmer->ToPlayer()->SendRemoveControlBar();
else if (GetTypeId() == TYPEID_PLAYER || (GetTypeId() == TYPEID_UNIT && !ToCreature()->isGuardian()))
DeleteCharmInfo();
}
void Unit::RestoreFaction()
{
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->setFactionForRace(getRace());
else
{
if (HasUnitTypeMask(UNIT_MASK_MINION))
{
if (Unit* owner = GetOwner())
{
setFaction(owner->getFaction());
return;
}
}
if (CreatureTemplate const* cinfo = ToCreature()->GetCreatureTemplate()) // normal creature
{
FactionTemplateEntry const* faction = getFactionTemplateEntry();
setFaction((faction && faction->friendlyMask & 0x004) ? cinfo->faction_H : cinfo->faction_A);
}
}
}
bool Unit::CreateVehicleKit(uint32 id, uint32 creatureEntry)
{
VehicleEntry const* vehInfo = sVehicleStore.LookupEntry(id);
if (!vehInfo)
return false;
m_vehicleKit = new Vehicle(this, vehInfo, creatureEntry);
m_updateFlag |= UPDATEFLAG_VEHICLE;
m_unitTypeMask |= UNIT_MASK_VEHICLE;
return true;
}
void Unit::RemoveVehicleKit()
{
if (!m_vehicleKit)
return;
m_vehicleKit->Uninstall();
delete m_vehicleKit;
m_vehicleKit = NULL;
m_updateFlag &= ~UPDATEFLAG_VEHICLE;
m_unitTypeMask &= ~UNIT_MASK_VEHICLE;
RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_PLAYER_VEHICLE);
}
Unit* Unit::GetVehicleBase() const
{
return m_vehicle ? m_vehicle->GetBase() : NULL;
}
Creature* Unit::GetVehicleCreatureBase() const
{
if (Unit* veh = GetVehicleBase())
if (Creature* c = veh->ToCreature())
return c;
return NULL;
}
uint64 Unit::GetTransGUID() const
{
if (GetVehicle())
return GetVehicleBase()->GetGUID();
if (GetTransport())
return GetTransport()->GetGUID();
return 0;
}
TransportBase* Unit::GetDirectTransport() const
{
if (Vehicle* veh = GetVehicle())
return veh;
return GetTransport();
}
bool Unit::IsInPartyWith(Unit const* unit) const
{
if (this == unit)
return true;
const Unit* u1 = GetCharmerOrOwnerOrSelf();
const Unit* u2 = unit->GetCharmerOrOwnerOrSelf();
if (u1 == u2)
return true;
if (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_PLAYER)
return u1->ToPlayer()->IsInSameGroupWith(u2->ToPlayer());
else if ((u2->GetTypeId() == TYPEID_PLAYER && u1->GetTypeId() == TYPEID_UNIT && u1->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER) ||
(u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_UNIT && u2->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER))
return true;
else
return false;
}
bool Unit::IsInRaidWith(Unit const* unit) const
{
if (this == unit)
return true;
const Unit* u1 = GetCharmerOrOwnerOrSelf();
const Unit* u2 = unit->GetCharmerOrOwnerOrSelf();
if (u1 == u2)
return true;
if (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_PLAYER)
return u1->ToPlayer()->IsInSameRaidWith(u2->ToPlayer());
else if ((u2->GetTypeId() == TYPEID_PLAYER && u1->GetTypeId() == TYPEID_UNIT && u1->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER) ||
(u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_UNIT && u2->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER))
return true;
else
return false;
}
void Unit::GetPartyMembers(std::list<Unit*> &TagUnitMap)
{
Unit* owner = GetCharmerOrOwnerOrSelf();
Group* group = NULL;
if (owner->GetTypeId() == TYPEID_PLAYER)
group = owner->ToPlayer()->GetGroup();
if (group)
{
uint8 subgroup = owner->ToPlayer()->GetSubGroup();
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* Target = itr->getSource();
// IsHostileTo check duel and controlled by enemy
if (Target && Target->GetSubGroup() == subgroup && !IsHostileTo(Target))
{
if (Target->isAlive() && IsInMap(Target))
TagUnitMap.push_back(Target);
if (Guardian* pet = Target->GetGuardianPet())
if (pet->isAlive() && IsInMap(Target))
TagUnitMap.push_back(pet);
}
}
}
else
{
if (owner->isAlive() && (owner == this || IsInMap(owner)))
TagUnitMap.push_back(owner);
if (Guardian* pet = owner->GetGuardianPet())
if (pet->isAlive() && (pet == this || IsInMap(pet)))
TagUnitMap.push_back(pet);
}
}
Aura* Unit::AddAura(uint32 spellId, Unit* target)
{
if (!target)
return NULL;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo)
return NULL;
if (!target->isAlive() && !(spellInfo->Attributes & SPELL_ATTR0_PASSIVE) && !(spellInfo->AttributesEx2 & SPELL_ATTR2_CAN_TARGET_DEAD))
return NULL;
return AddAura(spellInfo, MAX_EFFECT_MASK, target);
}
Aura* Unit::AddAura(SpellInfo const* spellInfo, uint8 effMask, Unit* target)
{
if (!spellInfo)
return NULL;
if (target->IsImmunedToSpell(spellInfo))
return NULL;
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if (!(effMask & (1<<i)))
continue;
if (target->IsImmunedToSpellEffect(spellInfo, i))
effMask &= ~(1<<i);
}
if (Aura* aura = Aura::TryRefreshStackOrCreate(spellInfo, effMask, target, this))
{
aura->ApplyForTargets();
return aura;
}
return NULL;
}
void Unit::SetAuraStack(uint32 spellId, Unit* target, uint32 stack)
{
Aura* aura = target->GetAura(spellId, GetGUID());
if (!aura)
aura = AddAura(spellId, target);
if (aura && stack)
aura->SetStackAmount(stack);
}
void Unit::SendPlaySpellVisualKit(uint32 id, uint32 unkParam)
{
ObjectGuid guid = GetGUID();
WorldPacket data(SMSG_PLAY_SPELL_VISUAL_KIT, 4 + 4+ 4 + 8);
data << uint32(0);
data << uint32(id); // SpellVisualKit.dbc index
data << uint32(unkParam);
data.WriteBit(guid[4]);
data.WriteBit(guid[7]);
data.WriteBit(guid[5]);
data.WriteBit(guid[3]);
data.WriteBit(guid[1]);
data.WriteBit(guid[2]);
data.WriteBit(guid[0]);
data.WriteBit(guid[6]);
data.FlushBits();
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[5]);
SendMessageToSet(&data, true);
}
void Unit::ApplyResilience(Unit const* victim, int32* damage, bool isCrit) const
{
// player mounted on multi-passenger mount is also classified as vehicle
if (IsVehicle() || (victim->IsVehicle() && victim->GetTypeId() != TYPEID_PLAYER))
return;
// Don't consider resilience if not in PvP - player or pet
if (!GetCharmerOrOwnerPlayerOrPlayerItself())
return;
Unit const* target = NULL;
if (victim->GetTypeId() == TYPEID_PLAYER)
target = victim;
else if (victim->GetTypeId() == TYPEID_UNIT && victim->GetOwner() && victim->GetOwner()->GetTypeId() == TYPEID_PLAYER)
target = victim->GetOwner();
if (!target)
return;
if (isCrit)
*damage -= target->GetCritDamageReduction(*damage);
*damage -= target->GetDamageReduction(*damage);
}
// Melee based spells can be miss, parry or dodge on this step
// Crit or block - determined on damage calculation phase! (and can be both in some time)
float Unit::MeleeSpellMissChance(const Unit* victim, WeaponAttackType attType, uint32 spellId) const
{
//calculate miss chance
float missChance = victim->GetUnitMissChance(attType);
if (!spellId && haveOffhandWeapon())
missChance += 19;
// Calculate hit chance
float hitChance = 100.0f;
// Spellmod from SPELLMOD_RESIST_MISS_CHANCE
if (spellId)
{
if (Player* modOwner = GetSpellModOwner())
modOwner->ApplySpellMod(spellId, SPELLMOD_RESIST_MISS_CHANCE, hitChance);
}
missChance += hitChance - 100.0f;
if (attType == RANGED_ATTACK)
missChance -= m_modRangedHitChance;
else
missChance -= m_modMeleeHitChance;
// Limit miss chance from 0 to 60%
if (missChance < 0.0f)
return 0.0f;
if (missChance > 60.0f)
return 60.0f;
return missChance;
}
void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
{
if (newPhaseMask == GetPhaseMask())
return;
if (IsInWorld())
{
RemoveNotOwnSingleTargetAuras(newPhaseMask); // we can lost access to caster or target
// modify hostile references for new phasemask, some special cases deal with hostile references themselves
if (GetTypeId() == TYPEID_UNIT || (!ToPlayer()->isGameMaster() && !ToPlayer()->GetSession()->PlayerLogout()))
{
HostileRefManager& refManager = getHostileRefManager();
HostileReference* ref = refManager.getFirst();
while (ref)
{
if (Unit* unit = ref->getSource()->getOwner())
if (Creature* creature = unit->ToCreature())
refManager.setOnlineOfflineState(creature, creature->InSamePhase(newPhaseMask));
ref = ref->next();
}
// modify threat lists for new phasemask
if (GetTypeId() != TYPEID_PLAYER)
{
std::list<HostileReference*> threatList = getThreatManager().getThreatList();
std::list<HostileReference*> offlineThreatList = getThreatManager().getOfflineThreatList();
// merge expects sorted lists
threatList.sort();
offlineThreatList.sort();
threatList.merge(offlineThreatList);
for (std::list<HostileReference*>::const_iterator itr = threatList.begin(); itr != threatList.end(); ++itr)
if (Unit* unit = (*itr)->getTarget())
unit->getHostileRefManager().setOnlineOfflineState(ToCreature(), unit->InSamePhase(newPhaseMask));
}
}
}
WorldObject::SetPhaseMask(newPhaseMask, update);
if (!IsInWorld())
return;
for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
if ((*itr)->GetTypeId() == TYPEID_UNIT)
(*itr)->SetPhaseMask(newPhaseMask, true);
for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i)
if (m_SummonSlot[i])
if (Creature* summon = GetMap()->GetCreature(m_SummonSlot[i]))
summon->SetPhaseMask(newPhaseMask, true);
}
void Unit::UpdateObjectVisibility(bool forced)
{
if (!forced)
AddToNotify(NOTIFY_VISIBILITY_CHANGED);
else
{
WorldObject::UpdateObjectVisibility(true);
// call MoveInLineOfSight for nearby creatures
Trinity::AIRelocationNotifier notifier(*this);
VisitNearbyObject(GetVisibilityRange(), notifier);
}
}
void Unit::SendMoveKnockBack(Player* player, float speedXY, float speedZ, float vcos, float vsin)
{
ObjectGuid guid = GetGUID();
WorldPacket data(SMSG_MOVE_KNOCK_BACK, (1+8+4+4+4+4+4));
data.WriteBit(guid[0]);
data.WriteBit(guid[3]);
data.WriteBit(guid[6]);
data.WriteBit(guid[7]);
data.WriteBit(guid[2]);
data.WriteBit(guid[5]);
data.WriteBit(guid[1]);
data.WriteBit(guid[4]);
data.WriteByteSeq(guid[1]);
data << float(vsin);
data << uint32(0);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[7]);
data << float(speedXY);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[3]);
data << float(speedZ);
data << float(vcos);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[0]);
player->GetSession()->SendPacket(&data);
}
void Unit::KnockbackFrom(float x, float y, float speedXY, float speedZ)
{
Player* player = NULL;
if (GetTypeId() == TYPEID_PLAYER)
player = ToPlayer();
else if (Unit* charmer = GetCharmer())
{
player = charmer->ToPlayer();
if (player && player->m_mover != this)
player = NULL;
}
if (!player)
GetMotionMaster()->MoveKnockbackFrom(x, y, speedXY, speedZ);
else
{
float vcos, vsin;
GetSinCos(x, y, vsin, vcos);
SendMoveKnockBack(player, speedXY, -speedZ, vcos, vsin);
}
}
float Unit::GetCombatRatingReduction(CombatRating cr) const
{
if (Player const* player = ToPlayer())
return player->GetRatingBonusValue(cr);
// Player's pet get resilience from owner
else if (isPet() && GetOwner())
if (Player* owner = GetOwner()->ToPlayer())
return owner->GetRatingBonusValue(cr);
return 0.0f;
}
uint32 Unit::GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const
{
float percent = std::min(GetCombatRatingReduction(cr) * rate, cap);
return CalculatePct(damage, percent);
}
uint32 Unit::GetModelForForm(ShapeshiftForm form) const
{
if (GetTypeId() == TYPEID_PLAYER)
{
switch (form)
{
case FORM_CAT:
// Based on Hair color
if (getRace() == RACE_NIGHTELF)
{
uint8 hairColor = GetByteValue(PLAYER_BYTES, 3);
switch (hairColor)
{
case 7: // Violet
case 8:
return 29405;
case 3: // Light Blue
return 29406;
case 0: // Green
case 1: // Light Green
case 2: // Dark Green
return 29407;
case 4: // White
return 29408;
default: // original - Dark Blue
return 892;
}
}
else if (getRace() == RACE_TROLL)
{
uint8 hairColor = GetByteValue(PLAYER_BYTES, 3);
switch (hairColor)
{
case 0: // Red
case 1:
return 33668;
case 2: // Yellow
case 3:
return 33667;
case 4: // Blue
case 5:
case 6:
return 33666;
case 7: // Purple
case 10:
return 33665;
default: // original - white
return 33669;
}
}
else if (getRace() == RACE_WORGEN)
{
// Based on Skin color
uint8 skinColor = GetByteValue(PLAYER_BYTES, 0);
// Male
if (getGender() == GENDER_MALE)
{
switch (skinColor)
{
case 1: // Brown
return 33662;
case 2: // Black
case 7:
return 33661;
case 4: // yellow
return 33664;
case 3: // White
case 5:
return 33663;
default: // original - Gray
return 33660;
}
}
// Female
else
{
switch (skinColor)
{
case 5: // Brown
case 6:
return 33662;
case 7: // Black
case 8:
return 33661;
case 3: // yellow
case 4:
return 33664;
case 2: // White
return 33663;
default: // original - Gray
return 33660;
}
}
}
// Based on Skin color
else if (getRace() == RACE_TAUREN)
{
uint8 skinColor = GetByteValue(PLAYER_BYTES, 0);
// Male
if (getGender() == GENDER_MALE)
{
switch (skinColor)
{
case 12: // White
case 13:
case 14:
case 18: // Completly White
return 29409;
case 9: // Light Brown
case 10:
case 11:
return 29410;
case 6: // Brown
case 7:
case 8:
return 29411;
case 0: // Dark
case 1:
case 2:
case 3: // Dark Grey
case 4:
case 5:
return 29412;
default: // original - Grey
return 8571;
}
}
// Female
else
{
switch (skinColor)
{
case 10: // White
return 29409;
case 6: // Light Brown
case 7:
return 29410;
case 4: // Brown
case 5:
return 29411;
case 0: // Dark
case 1:
case 2:
case 3:
return 29412;
default: // original - Grey
return 8571;
}
}
}
else if (Player::TeamForRace(getRace()) == ALLIANCE)
return 892;
else
return 8571;
case FORM_BEAR:
// Based on Hair color
if (getRace() == RACE_NIGHTELF)
{
uint8 hairColor = GetByteValue(PLAYER_BYTES, 3);
switch (hairColor)
{
case 0: // Green
case 1: // Light Green
case 2: // Dark Green
return 29413; // 29415?
case 6: // Dark Blue
return 29414;
case 4: // White
return 29416;
case 3: // Light Blue
return 29417;
default: // original - Violet
return 2281;
}
}
else if (getRace() == RACE_TROLL)
{
uint8 hairColor = GetByteValue(PLAYER_BYTES, 3);
switch (hairColor)
{
case 0: // Red
case 1:
return 33657;
case 2: // Yellow
case 3:
return 33659;
case 7: // Purple
case 10:
return 33656;
case 8: // White
case 9:
case 11:
case 12:
return 33658;
default: // original - Blue
return 33655;
}
}
else if (getRace() == RACE_WORGEN)
{
// Based on Skin color
uint8 skinColor = GetByteValue(PLAYER_BYTES, 0);
// Male
if (getGender() == GENDER_MALE)
{
switch (skinColor)
{
case 1: // Brown
return 33652;
case 2: // Black
case 7:
return 33651;
case 4: // Yellow
return 33653;
case 3: // White
case 5:
return 33654;
default: // original - Gray
return 33650;
}
}
// Female
else
{
switch (skinColor)
{
case 5: // Brown
case 6:
return 33652;
case 7: // Black
case 8:
return 33651;
case 3: // yellow
case 4:
return 33654;
case 2: // White
return 33653;
default: // original - Gray
return 33650;
}
}
}
// Based on Skin color
else if (getRace() == RACE_TAUREN)
{
uint8 skinColor = GetByteValue(PLAYER_BYTES, 0);
// Male
if (getGender() == GENDER_MALE)
{
switch (skinColor)
{
case 0: // Dark (Black)
case 1:
case 2:
return 29418;
case 3: // White
case 4:
case 5:
case 12:
case 13:
case 14:
return 29419;
case 9: // Light Brown/Grey
case 10:
case 11:
case 15:
case 16:
case 17:
return 29420;
case 18: // Completly White
return 29421;
default: // original - Brown
return 2289;
}
}
// Female
else
{
switch (skinColor)
{
case 0: // Dark (Black)
case 1:
return 29418;
case 2: // White
case 3:
return 29419;
case 6: // Light Brown/Grey
case 7:
case 8:
case 9:
return 29420;
case 10: // Completly White
return 29421;
default: // original - Brown
return 2289;
}
}
}
else if (Player::TeamForRace(getRace()) == ALLIANCE)
return 2281;
else
return 2289;
case FORM_FLIGHT:
if (Player::TeamForRace(getRace()) == ALLIANCE)
return 20857;
return 20872;
case FORM_FLIGHT_EPIC:
if (Player::TeamForRace(getRace()) == ALLIANCE)
return 21243;
return 21244;
default:
break;
}
}
uint32 modelid = 0;
SpellShapeshiftFormEntry const* formEntry = sSpellShapeshiftFormStore.LookupEntry(form);
if (formEntry && formEntry->modelID_A)
{
// Take the alliance modelid as default
if (GetTypeId() != TYPEID_PLAYER)
return formEntry->modelID_A;
else
{
if (Player::TeamForRace(getRace()) == ALLIANCE)
modelid = formEntry->modelID_A;
else
modelid = formEntry->modelID_H;
// If the player is horde but there are no values for the horde modelid - take the alliance modelid
if (!modelid && Player::TeamForRace(getRace()) == HORDE)
modelid = formEntry->modelID_A;
}
}
return modelid;
}
uint32 Unit::GetModelForTotem(PlayerTotemType totemType)
{
switch (getRace())
{
case RACE_ORC:
{
switch (totemType)
{
case SUMMON_TYPE_TOTEM_FIRE: // fire
return 30758;
case SUMMON_TYPE_TOTEM_EARTH: // earth
return 30757;
case SUMMON_TYPE_TOTEM_WATER: // water
return 30759;
case SUMMON_TYPE_TOTEM_AIR: // air
return 30756;
}
break;
}
case RACE_DWARF:
{
switch (totemType)
{
case SUMMON_TYPE_TOTEM_FIRE: // fire
return 30754;
case SUMMON_TYPE_TOTEM_EARTH: // earth
return 30753;
case SUMMON_TYPE_TOTEM_WATER: // water
return 30755;
case SUMMON_TYPE_TOTEM_AIR: // air
return 30736;
}
break;
}
case RACE_TROLL:
{
switch (totemType)
{
case SUMMON_TYPE_TOTEM_FIRE: // fire
return 30762;
case SUMMON_TYPE_TOTEM_EARTH: // earth
return 30761;
case SUMMON_TYPE_TOTEM_WATER: // water
return 30763;
case SUMMON_TYPE_TOTEM_AIR: // air
return 30760;
}
break;
}
case RACE_TAUREN:
{
switch (totemType)
{
case SUMMON_TYPE_TOTEM_FIRE: // fire
return 4589;
case SUMMON_TYPE_TOTEM_EARTH: // earth
return 4588;
case SUMMON_TYPE_TOTEM_WATER: // water
return 4587;
case SUMMON_TYPE_TOTEM_AIR: // air
return 4590;
}
break;
}
case RACE_DRAENEI:
{
switch (totemType)
{
case SUMMON_TYPE_TOTEM_FIRE: // fire
return 19074;
case SUMMON_TYPE_TOTEM_EARTH: // earth
return 19073;
case SUMMON_TYPE_TOTEM_WATER: // water
return 19075;
case SUMMON_TYPE_TOTEM_AIR: // air
return 19071;
}
break;
}
case RACE_GOBLIN:
{
switch (totemType)
{
case SUMMON_TYPE_TOTEM_FIRE: // fire
return 30783;
case SUMMON_TYPE_TOTEM_EARTH: // earth
return 30782;
case SUMMON_TYPE_TOTEM_WATER: // water
return 30784;
case SUMMON_TYPE_TOTEM_AIR: // air
return 30781;
}
break;
}
}
return 0;
}
void Unit::JumpTo(float speedXY, float speedZ, bool forward)
{
float angle = forward ? 0 : M_PI;
if (GetTypeId() == TYPEID_UNIT)
GetMotionMaster()->MoveJumpTo(angle, speedXY, speedZ);
else
{
float vcos = std::cos(angle+GetOrientation());
float vsin = std::sin(angle+GetOrientation());
SendMoveKnockBack(ToPlayer(), speedXY, -speedZ, vcos, vsin);
}
}
void Unit::JumpTo(WorldObject* obj, float speedZ)
{
float x, y, z;
obj->GetContactPoint(this, x, y, z);
float speedXY = GetExactDist2d(x, y) * 10.0f / speedZ;
GetMotionMaster()->MoveJump(x, y, z, speedXY, speedZ);
}
bool Unit::HandleSpellClick(Unit* clicker, int8 seatId)
{
bool result = false;
uint32 spellClickEntry = GetVehicleKit() ? GetVehicleKit()->GetCreatureEntry() : GetEntry();
SpellClickInfoMapBounds clickPair = sObjectMgr->GetSpellClickInfoMapBounds(spellClickEntry);
for (SpellClickInfoContainer::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
{
//! First check simple relations from clicker to clickee
if (!itr->second.IsFitToRequirements(clicker, this))
continue;
//! Check database conditions
ConditionList conds = sConditionMgr->GetConditionsForSpellClickEvent(spellClickEntry, itr->second.spellId);
ConditionSourceInfo info = ConditionSourceInfo(clicker, this);
if (!sConditionMgr->IsObjectMeetToConditions(info, conds))
continue;
Unit* caster = (itr->second.castFlags & NPC_CLICK_CAST_CASTER_CLICKER) ? clicker : this;
Unit* target = (itr->second.castFlags & NPC_CLICK_CAST_TARGET_CLICKER) ? clicker : this;
uint64 origCasterGUID = (itr->second.castFlags & NPC_CLICK_CAST_ORIG_CASTER_OWNER) ? GetOwnerGUID() : clicker->GetGUID();
SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(itr->second.spellId);
// if (!spellEntry) should be checked at npc_spellclick load
if (seatId > -1)
{
uint8 i = 0;
bool valid = false;
while (i < MAX_SPELL_EFFECTS && !valid)
{
if (spellEntry->Effects[i].ApplyAuraName == SPELL_AURA_CONTROL_VEHICLE)
{
valid = true;
break;
}
++i;
}
if (!valid)
{
sLog->outError(LOG_FILTER_SQL, "Spell %u specified in npc_spellclick_spells is not a valid vehicle enter aura!", itr->second.spellId);
continue;
}
if (IsInMap(caster))
caster->CastCustomSpell(itr->second.spellId, SpellValueMod(SPELLVALUE_BASE_POINT0+i), seatId + 1, target, GetVehicleKit() ? TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE : TRIGGERED_NONE, NULL, NULL, origCasterGUID);
else // This can happen during Player::_LoadAuras
{
int32 bp0[MAX_SPELL_EFFECTS];
for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j)
bp0[j] = spellEntry->Effects[j].BasePoints;
bp0[i] = seatId;
Aura::TryRefreshStackOrCreate(spellEntry, MAX_EFFECT_MASK, this, clicker, bp0, NULL, origCasterGUID);
}
}
else
{
if (IsInMap(caster))
caster->CastSpell(target, spellEntry, GetVehicleKit() ? TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE : TRIGGERED_NONE, NULL, NULL, origCasterGUID);
else
Aura::TryRefreshStackOrCreate(spellEntry, MAX_EFFECT_MASK, this, clicker, NULL, NULL, origCasterGUID);
}
result = true;
}
if (result)
{
Creature* creature = ToCreature();
if (creature && creature->IsAIEnabled)
creature->AI()->OnSpellClick(clicker);
}
return result;
}
void Unit::EnterVehicle(Unit* base, int8 seatId)
{
CastCustomSpell(VEHICLE_SPELL_RIDE_HARDCODED, SPELLVALUE_BASE_POINT0, seatId + 1, base, TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE);
}
void Unit::_EnterVehicle(Vehicle* vehicle, int8 seatId, AuraApplication const* aurApp)
{
// Must be called only from aura handler
if (!isAlive() || GetVehicleKit() == vehicle || vehicle->GetBase()->IsOnVehicle(this))
return;
if (m_vehicle)
{
if (m_vehicle == vehicle)
{
if (seatId >= 0 && seatId != GetTransSeat())
{
sLog->outDebug(LOG_FILTER_VEHICLES, "EnterVehicle: %u leave vehicle %u seat %d and enter %d.", GetEntry(), m_vehicle->GetBase()->GetEntry(), GetTransSeat(), seatId);
ChangeSeat(seatId);
}
return;
}
else
{
sLog->outDebug(LOG_FILTER_VEHICLES, "EnterVehicle: %u exit %u and enter %u.", GetEntry(), m_vehicle->GetBase()->GetEntry(), vehicle->GetBase()->GetEntry());
ExitVehicle();
}
}
if (aurApp && aurApp->GetRemoveMode())
return;
if (Player* player = ToPlayer())
{
if (vehicle->GetBase()->GetTypeId() == TYPEID_PLAYER && player->isInCombat())
return;
}
ASSERT(!m_vehicle);
(void)vehicle->AddPassenger(this, seatId);
}
void Unit::ChangeSeat(int8 seatId, bool next)
{
if (!m_vehicle)
return;
// Don't change if current and new seat are identical
if (seatId == GetTransSeat())
return;
SeatMap::const_iterator seat = (seatId < 0 ? m_vehicle->GetNextEmptySeat(GetTransSeat(), next) : m_vehicle->Seats.find(seatId));
// The second part of the check will only return true if seatId >= 0. @Vehicle::GetNextEmptySeat makes sure of that.
if (seat == m_vehicle->Seats.end() || seat->second.Passenger)
return;
// Todo: the functions below could be consolidated and refactored to take
// SeatMap::const_iterator as parameter, to save redundant map lookups.
m_vehicle->RemovePassenger(this);
// Set m_vehicle to NULL before adding passenger as adding new passengers is handled asynchronously
// and someone may call ExitVehicle again before passenger is added to new seat
Vehicle* veh = m_vehicle;
m_vehicle = NULL;
if (!veh->AddPassenger(this, seatId))
ASSERT(false);
}
void Unit::ExitVehicle(Position const* /*exitPosition*/)
{
//! This function can be called at upper level code to initialize an exit from the passenger's side.
if (!m_vehicle)
return;
GetVehicleBase()->RemoveAurasByType(SPELL_AURA_CONTROL_VEHICLE, GetGUID());
//! The following call would not even be executed successfully as the
//! SPELL_AURA_CONTROL_VEHICLE unapply handler already calls _ExitVehicle without
//! specifying an exitposition. The subsequent call below would return on if (!m_vehicle).
/*_ExitVehicle(exitPosition);*/
//! To do:
//! We need to allow SPELL_AURA_CONTROL_VEHICLE unapply handlers in spellscripts
//! to specify exit coordinates and either store those per passenger, or we need to
//! init spline movement based on those coordinates in unapply handlers, and
//! relocate exiting passengers based on Unit::moveSpline data. Either way,
//! Coming Soon(TM)
}
void Unit::_ExitVehicle(Position const* exitPosition)
{
/// It's possible m_vehicle is NULL, when this function is called indirectly from @VehicleJoinEvent::Abort.
/// In that case it was not possible to add the passenger to the vehicle. The vehicle aura has already been removed
/// from the target in the aforementioned function and we don't need to do anything else at this point.
if (!m_vehicle)
return;
m_vehicle->RemovePassenger(this);
Player* player = ToPlayer();
// If player is on mouted duel and exits the mount should immediatly lose the duel
if (player && player->duel && player->duel->isMounted)
player->DuelComplete(DUEL_FLED);
// This should be done before dismiss, because there may be some aura removal
Vehicle* vehicle = m_vehicle;
m_vehicle = NULL;
SetControlled(false, UNIT_STATE_ROOT); // SMSG_MOVE_FORCE_UNROOT, ~MOVEMENTFLAG_ROOT
Position pos;
if (!exitPosition) // Exit position not specified
vehicle->GetBase()->GetPosition(&pos); // This should use passenger's current position, leaving it as it is now
// because we calculate positions incorrect (sometimes under map)
else
pos = *exitPosition;
AddUnitState(UNIT_STATE_MOVE);
if (player)
player->SetFallInformation(0, GetPositionZ());
else if (HasUnitMovementFlag(MOVEMENTFLAG_ROOT))
{
WorldPacket data(SMSG_SPLINE_MOVE_UNROOT, 8);
data.append(GetPackGUID());
SendMessageToSet(&data, false);
}
Movement::MoveSplineInit init(this);
init.MoveTo(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), false);
init.SetFacing(GetOrientation());
init.SetTransportExit();
init.Launch();
//GetMotionMaster()->MoveFall(); // Enable this once passenger positions are calculater properly (see above)
if (player)
player->ResummonPetTemporaryUnSummonedIfAny();
if (vehicle->GetBase()->HasUnitTypeMask(UNIT_MASK_MINION))
if (((Minion*)vehicle->GetBase())->GetOwner() == this)
vehicle->Dismiss();
if (HasUnitTypeMask(UNIT_MASK_ACCESSORY))
{
// Vehicle just died, we die too
if (vehicle->GetBase()->getDeathState() == JUST_DIED)
setDeathState(JUST_DIED);
// If for other reason we as minion are exiting the vehicle (ejected, master dismounted) - unsummon
else
ToTempSummon()->UnSummon(2000); // Approximation
}
}
void Unit::BuildMovementPacket(ByteBuffer *data) const
{
*data << uint32(GetUnitMovementFlags()); // movement flags
*data << uint16(GetExtraUnitMovementFlags()); // 2.3.0
*data << uint32(getMSTime()); // time / counter
*data << GetPositionX();
*data << GetPositionY();
*data << GetPositionZMinusOffset();
*data << GetOrientation();
bool onTransport = m_movementInfo.t_guid != 0;
bool hasInterpolatedMovement = m_movementInfo.flags2 & MOVEMENTFLAG2_INTERPOLATED_MOVEMENT;
bool time3 = false;
bool swimming = ((GetUnitMovementFlags() & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING))
|| (m_movementInfo.flags2 & MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING));
bool interPolatedTurning = m_movementInfo.flags2 & MOVEMENTFLAG2_INTERPOLATED_TURNING;
bool jumping = GetUnitMovementFlags() & MOVEMENTFLAG_FALLING;
bool splineElevation = GetUnitMovementFlags() & MOVEMENTFLAG_SPLINE_ELEVATION;
bool splineData = false;
data->WriteBits(GetUnitMovementFlags(), 30);
data->WriteBits(m_movementInfo.flags2, 12);
data->WriteBit(onTransport);
if (onTransport)
{
data->WriteBit(hasInterpolatedMovement);
data->WriteBit(time3);
}
data->WriteBit(swimming);
data->WriteBit(interPolatedTurning);
if (interPolatedTurning)
data->WriteBit(jumping);
data->WriteBit(splineElevation);
data->WriteBit(splineData);
data->FlushBits(); // reset bit stream
*data << uint64(GetGUID());
*data << uint32(getMSTime());
*data << float(GetPositionX());
*data << float(GetPositionY());
*data << float(GetPositionZ());
*data << float(GetOrientation());
if (onTransport)
{
if (m_vehicle)
*data << uint64(m_vehicle->GetBase()->GetGUID());
else if (GetTransport())
*data << uint64(GetTransport()->GetGUID());
else // probably should never happen
*data << (uint64)0;
*data << float (GetTransOffsetX());
*data << float (GetTransOffsetY());
*data << float (GetTransOffsetZ());
*data << float (GetTransOffsetO());
*data << uint8 (GetTransSeat());
*data << uint32(GetTransTime());
if (hasInterpolatedMovement)
*data << int32(0); // Transport Time 2
if (time3)
*data << int32(0); // Transport Time 3
}
if (swimming)
*data << (float)m_movementInfo.pitch;
if (interPolatedTurning)
{
*data << (uint32)m_movementInfo.fallTime;
*data << (float)m_movementInfo.j_zspeed;
if (jumping)
{
*data << (float)m_movementInfo.j_sinAngle;
*data << (float)m_movementInfo.j_cosAngle;
*data << (float)m_movementInfo.j_xyspeed;
}
}
if (splineElevation)
*data << (float)m_movementInfo.splineElevation;
}
void Unit::SetCanFly(bool apply)
{
if (apply)
AddUnitMovementFlag(MOVEMENTFLAG_CAN_FLY);
else
RemoveUnitMovementFlag(MOVEMENTFLAG_CAN_FLY);
}
void Unit::NearTeleportTo(float x, float y, float z, float orientation, bool casting /*= false*/)
{
DisableSpline();
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->TeleportTo(GetMapId(), x, y, z, orientation, TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET | (casting ? TELE_TO_SPELL : 0));
else
{
Position pos = {x, y, z, orientation};
SendTeleportPacket(pos);
UpdatePosition(x, y, z, orientation, true);
UpdateObjectVisibility();
}
}
void Unit::ReadMovementInfo(WorldPacket& data, MovementInfo* mi)
{
if (GetTypeId() != TYPEID_PLAYER)
return;
bool hasMovementFlags = false;
bool hasMovementFlags2 = false;
bool hasTimestamp = false;
bool hasOrientation = false;
bool hasTransportData = false;
bool hasTransportTime2 = false;
bool hasTransportTime3 = false;
bool hasPitch = false;
bool hasFallData = false;
bool hasFallDirection = false;
bool hasSplineElevation = false;
bool hasSpline = false;
MovementStatusElements* sequence = GetMovementStatusElementsSequence(data.GetOpcode());
if (sequence == NULL)
{
sLog->outError(LOG_FILTER_NETWORKIO, "WorldSession::ReadMovementInfo: No movement sequence found for opcode 0x%04X", uint32(data.GetOpcode()));
return;
}
ObjectGuid guid;
ObjectGuid tguid;
for (uint32 i = 0; i < MSE_COUNT; ++i)
{
MovementStatusElements element = sequence[i];
if (element == MSEEnd)
break;
if (element >= MSEHasGuidByte0 && element <= MSEHasGuidByte7)
{
guid[element - MSEHasGuidByte0] = data.ReadBit();
continue;
}
if (element >= MSEHasTransportGuidByte0 &&
element <= MSEHasTransportGuidByte7)
{
if (hasTransportData)
tguid[element - MSEHasTransportGuidByte0] = data.ReadBit();
continue;
}
if (element >= MSEGuidByte0 && element <= MSEGuidByte7)
{
data.ReadByteSeq(guid[element - MSEGuidByte0]);
continue;
}
if (element >= MSETransportGuidByte0 &&
element <= MSETransportGuidByte7)
{
if (hasTransportData)
data.ReadByteSeq(tguid[element - MSETransportGuidByte0]);
continue;
}
switch (element)
{
case MSEHasMovementFlags:
hasMovementFlags = !data.ReadBit();
break;
case MSEHasMovementFlags2:
hasMovementFlags2 = !data.ReadBit();
break;
case MSEHasTimestamp:
hasTimestamp = !data.ReadBit();
break;
case MSEHasOrientation:
hasOrientation = !data.ReadBit();
break;
case MSEHasTransportData:
hasTransportData = data.ReadBit();
break;
case MSEHasTransportTime2:
if (hasTransportData)
hasTransportTime2 = data.ReadBit();
break;
case MSEHasTransportTime3:
if (hasTransportData)
hasTransportTime3 = data.ReadBit();
break;
case MSEHasPitch:
hasPitch = !data.ReadBit();
break;
case MSEHasFallData:
hasFallData = data.ReadBit();
break;
case MSEHasFallDirection:
if (hasFallData)
hasFallDirection = data.ReadBit();
break;
case MSEHasSplineElevation:
hasSplineElevation = !data.ReadBit();
break;
case MSEHasSpline:
hasSpline = data.ReadBit();
break;
case MSEMovementFlags:
if (hasMovementFlags)
mi->flags = data.ReadBits(30);
break;
case MSEMovementFlags2:
if (hasMovementFlags2)
mi->flags2 = data.ReadBits(12);
break;
case MSETimestamp:
if (hasTimestamp)
data >> mi->time;
break;
case MSEPositionX:
data >> mi->pos.m_positionX;
break;
case MSEPositionY:
data >> mi->pos.m_positionY;
break;
case MSEPositionZ:
data >> mi->pos.m_positionZ;
break;
case MSEOrientation:
if (hasOrientation)
mi->pos.SetOrientation(data.read<float>());
break;
case MSETransportPositionX:
if (hasTransportData)
data >> mi->t_pos.m_positionX;
break;
case MSETransportPositionY:
if (hasTransportData)
data >> mi->t_pos.m_positionY;
break;
case MSETransportPositionZ:
if (hasTransportData)
data >> mi->t_pos.m_positionZ;
break;
case MSETransportOrientation:
if (hasTransportData)
mi->pos.SetOrientation(data.read<float>());
break;
case MSETransportSeat:
if (hasTransportData)
data >> mi->t_seat;
break;
case MSETransportTime:
if (hasTransportData)
data >> mi->t_time;
break;
case MSETransportTime2:
if (hasTransportData && hasTransportTime2)
data >> mi->t_time2;
break;
case MSETransportTime3:
if (hasTransportData && hasTransportTime3)
data >> mi->t_time3;
break;
case MSEPitch:
if (hasPitch)
data >> mi->pitch;
break;
case MSEFallTime:
if (hasFallData)
data >> mi->fallTime;
break;
case MSEFallVerticalSpeed:
if (hasFallData)
data >> mi->j_zspeed;
break;
case MSEFallCosAngle:
if (hasFallData && hasFallDirection)
data >> mi->j_cosAngle;
break;
case MSEFallSinAngle:
if (hasFallData && hasFallDirection)
data >> mi->j_sinAngle;
break;
case MSEFallHorizontalSpeed:
if (hasFallData && hasFallDirection)
data >> mi->j_xyspeed;
break;
case MSESplineElevation:
if (hasSplineElevation)
data >> mi->splineElevation;
break;
case MSEZeroBit:
case MSEOneBit:
data.ReadBit();
break;
default:
ASSERT(false && "Incorrect sequence element detected at ReadMovementInfo");
break;
}
}
mi->guid = guid;
mi->t_guid = tguid;
if (hasTransportData && mi->pos.m_positionX != mi->t_pos.m_positionX)
if (GetTransport())
GetTransport()->UpdatePosition(mi);
//! Anti-cheat checks. Please keep them in seperate if () blocks to maintain a clear overview.
//! Might be subject to latency, so just remove improper flags.
#ifdef TRINITY_DEBUG
#define REMOVE_VIOLATING_FLAGS(check, maskToRemove) \
{ \
if (check) \
{ \
sLog->outDebug(LOG_FILTER_UNITS, "WorldSession::ReadMovementInfo: Violation of MovementFlags found (%s). " \
"MovementFlags: %u, MovementFlags2: %u for player GUID: %u. Mask %u will be removed.", \
STRINGIZE(check), mi->GetMovementFlags(), mi->GetExtraMovementFlags(), GetGUIDLow(), maskToRemove); \
mi->RemoveMovementFlag((maskToRemove)); \
} \
}
#else
#define REMOVE_VIOLATING_FLAGS(check, maskToRemove) \
if (check) \
mi->RemoveMovementFlag((maskToRemove));
#endif
/*! This must be a packet spoofing attempt. MOVEMENTFLAG_ROOT sent from the client is not valid
in conjunction with any of the moving movement flags such as MOVEMENTFLAG_FORWARD.
It will freeze clients that receive this player's movement info.
*/
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_ROOT),
MOVEMENTFLAG_ROOT);
//! Cannot hover without SPELL_AURA_HOVER
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_HOVER) && !HasAuraType(SPELL_AURA_HOVER),
MOVEMENTFLAG_HOVER);
//! Cannot ascend and descend at the same time
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_ASCENDING) && mi->HasMovementFlag(MOVEMENTFLAG_DESCENDING),
MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING);
//! Cannot move left and right at the same time
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_LEFT) && mi->HasMovementFlag(MOVEMENTFLAG_RIGHT),
MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT);
//! Cannot strafe left and right at the same time
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_STRAFE_LEFT) && mi->HasMovementFlag(MOVEMENTFLAG_STRAFE_RIGHT),
MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT);
//! Cannot pitch up and down at the same time
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_PITCH_UP) && mi->HasMovementFlag(MOVEMENTFLAG_PITCH_DOWN),
MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN);
//! Cannot move forwards and backwards at the same time
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_FORWARD) && mi->HasMovementFlag(MOVEMENTFLAG_BACKWARD),
MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD);
//! Cannot walk on water without SPELL_AURA_WATER_WALK
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_WATERWALKING) && !HasAuraType(SPELL_AURA_WATER_WALK),
MOVEMENTFLAG_WATERWALKING);
//! Cannot feather fall without SPELL_AURA_FEATHER_FALL
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_FALLING_SLOW) && !HasAuraType(SPELL_AURA_FEATHER_FALL),
MOVEMENTFLAG_FALLING_SLOW);
/*! Cannot fly if no fly auras present. Exception is being a GM.
Note that we check for account level instead of Player::IsGameMaster() because in some
situations it may be feasable to use .gm fly on as a GM without having .gm on,
e.g. aerial combat.
*/
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_FLYING | MOVEMENTFLAG_CAN_FLY) && ToPlayer()->GetSession()->GetSecurity() == SEC_PLAYER &&
!ToPlayer()->m_mover->HasAuraType(SPELL_AURA_FLY) &&
!ToPlayer()->m_mover->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED),
MOVEMENTFLAG_FLYING | MOVEMENTFLAG_CAN_FLY);
#undef REMOVE_VIOLATING_FLAGS
}
void Unit::WriteMovementInfo(WorldPacket& data)
{
Unit* mover = GetCharmerGUID() ? GetCharmer() : this;
bool hasMovementFlags = mover->GetUnitMovementFlags() != 0;
bool hasMovementFlags2 = mover->GetExtraUnitMovementFlags() != 0;
bool hasTimestamp = GetTypeId() == TYPEID_PLAYER ? (mover->m_movementInfo.time != 0) : true;
bool hasOrientation = !G3D::fuzzyEq(mover->GetOrientation(), 0.0f);
bool hasTransportData = mover->GetTransport() != NULL;
bool hasTransportTime2 = mover->HasExtraUnitMovementFlag(MOVEMENTFLAG2_INTERPOLATED_MOVEMENT);
bool hasTransportTime3 = false;
bool hasPitch = mover->HasUnitMovementFlag(MovementFlags(MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING)) || mover->HasExtraUnitMovementFlag(MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING);
bool hasFallData = mover->HasExtraUnitMovementFlag(MOVEMENTFLAG2_INTERPOLATED_TURNING);
bool hasFallDirection = mover->HasUnitMovementFlag(MOVEMENTFLAG_FALLING);
bool hasSplineElevation = mover->HasUnitMovementFlag(MOVEMENTFLAG_SPLINE_ELEVATION);
bool hasSpline = false;
MovementStatusElements* sequence = GetMovementStatusElementsSequence(data.GetOpcode());
if (!sequence)
{
sLog->outError(LOG_FILTER_NETWORKIO, "WorldSession::WriteMovementInfo: No movement sequence found for opcode 0x%04X", uint32(data.GetOpcode()));
return;
}
ObjectGuid guid = mover->GetGUID();
ObjectGuid tguid = hasTransportData ? GetTransport()->GetGUID() : 0;
for (uint32 i = 0; i < MSE_COUNT; ++i)
{
MovementStatusElements element = sequence[i];
if (element == MSEEnd)
break;
if (element >= MSEHasGuidByte0 && element <= MSEHasGuidByte7)
{
data.WriteBit(guid[element - MSEHasGuidByte0]);
continue;
}
if (element >= MSEHasTransportGuidByte0 &&
element <= MSEHasTransportGuidByte7)
{
if (hasTransportData)
data.WriteBit(tguid[element - MSEHasTransportGuidByte0]);
continue;
}
if (element >= MSEGuidByte0 && element <= MSEGuidByte7)
{
data.WriteByteSeq(guid[element - MSEGuidByte0]);
continue;
}
if (element >= MSETransportGuidByte0 &&
element <= MSETransportGuidByte7)
{
if (hasTransportData)
data.WriteByteSeq(tguid[element - MSETransportGuidByte0]);
continue;
}
switch (element)
{
case MSEHasMovementFlags:
data.WriteBit(!hasMovementFlags);
break;
case MSEHasMovementFlags2:
data.WriteBit(!hasMovementFlags2);
break;
case MSEHasTimestamp:
data.WriteBit(!hasTimestamp);
break;
case MSEHasOrientation:
data.WriteBit(!hasOrientation);
break;
case MSEHasTransportData:
data.WriteBit(hasTransportData);
break;
case MSEHasTransportTime2:
if (hasTransportData)
data.WriteBit(hasTransportTime2);
break;
case MSEHasTransportTime3:
if (hasTransportData)
data.WriteBit(hasTransportTime3);
break;
case MSEHasPitch:
data.WriteBit(!hasPitch);
break;
case MSEHasFallData:
data.WriteBit(hasFallData);
break;
case MSEHasFallDirection:
if (hasFallData)
data.WriteBit(hasFallDirection);
break;
case MSEHasSplineElevation:
data.WriteBit(!hasSplineElevation);
break;
case MSEHasSpline:
data.WriteBit(hasSpline);
break;
case MSEMovementFlags:
if (hasMovementFlags)
data.WriteBits(mover->GetUnitMovementFlags(), 30);
break;
case MSEMovementFlags2:
if (hasMovementFlags2)
data.WriteBits(mover->GetExtraUnitMovementFlags(), 12);
break;
case MSETimestamp:
if (hasTimestamp)
data << getMSTime();
break;
case MSEPositionX:
data << mover->GetPositionX();
break;
case MSEPositionY:
data << mover->GetPositionY();
break;
case MSEPositionZ:
data << mover->GetPositionZ();
break;
case MSEOrientation:
if (hasOrientation)
data << mover->GetOrientation();
break;
case MSETransportPositionX:
if (hasTransportData)
data << mover->GetTransport()->GetPositionX();
break;
case MSETransportPositionY:
if (hasTransportData)
data << mover->GetTransport()->GetPositionY();
break;
case MSETransportPositionZ:
if (hasTransportData)
data << mover->GetTransport()->GetPositionZ();
break;
case MSETransportOrientation:
if (hasTransportData)
data << mover->GetTransport()->GetOrientation();
break;
case MSETransportSeat:
if (hasTransportData)
data << mover->GetTransSeat();
break;
case MSETransportTime:
if (hasTransportData)
data << mover->GetTransTime();
break;
case MSETransportTime2:
if (hasTransportData && hasTransportTime2)
data << mover->m_movementInfo.t_time2;
break;
case MSETransportTime3:
if (hasTransportData && hasTransportTime3)
data << mover->m_movementInfo.t_time3;
break;
case MSEPitch:
if (hasPitch)
data << mover->m_movementInfo.pitch;
break;
case MSEFallTime:
if (hasFallData)
data << mover->m_movementInfo.fallTime;
break;
case MSEFallVerticalSpeed:
if (hasFallData)
data << mover->m_movementInfo.j_zspeed;
break;
case MSEFallCosAngle:
if (hasFallData && hasFallDirection)
data << mover->m_movementInfo.j_cosAngle;
break;
case MSEFallSinAngle:
if (hasFallData && hasFallDirection)
data << mover->m_movementInfo.j_sinAngle;
break;
case MSEFallHorizontalSpeed:
if (hasFallData && hasFallDirection)
data << mover->m_movementInfo.j_xyspeed;
break;
case MSESplineElevation:
if (hasSplineElevation)
data << mover->m_movementInfo.splineElevation;
break;
case MSEZeroBit:
data.WriteBit(0);
break;
case MSEOneBit:
data.WriteBit(1);
break;
default:
ASSERT(false && "Incorrect sequence element detected at ReadMovementInfo");
break;
}
}
}
void Unit::SendTeleportPacket(Position& pos)
{
// MSG_MOVE_UPDATE_TELEPORT is sent to nearby players to signal the teleport
// MSG_MOVE_TELEPORT is sent to self in order to trigger MSG_MOVE_TELEPORT_ACK and update the position server side
// This oldPos actually contains the destination position if the Unit is a Player.
Position oldPos = {GetPositionX(), GetPositionY(), GetPositionZMinusOffset(), GetOrientation()};
if (GetTypeId() == TYPEID_UNIT)
Relocate(&pos); // Relocate the unit to its new position in order to build the packets correctly.
ObjectGuid guid = GetGUID();
ObjectGuid transGuid = GetTransGUID();
WorldPacket data(MSG_MOVE_UPDATE_TELEPORT, 38);
WriteMovementInfo(data);
if (GetTypeId() == TYPEID_PLAYER)
{
WorldPacket data2(MSG_MOVE_TELEPORT, 38);
data2.WriteBit(guid[6]);
data2.WriteBit(guid[0]);
data2.WriteBit(guid[3]);
data2.WriteBit(guid[2]);
data2.WriteBit(0); // unknown
data2.WriteBit(uint64(transGuid));
data2.WriteBit(guid[1]);
if (transGuid)
{
data2.WriteBit(transGuid[1]);
data2.WriteBit(transGuid[3]);
data2.WriteBit(transGuid[2]);
data2.WriteBit(transGuid[5]);
data2.WriteBit(transGuid[0]);
data2.WriteBit(transGuid[7]);
data2.WriteBit(transGuid[6]);
data2.WriteBit(transGuid[4]);
}
data2.WriteBit(guid[4]);
data2.WriteBit(guid[7]);
data2.WriteBit(guid[5]);
data2.FlushBits();
if (transGuid)
{
data2.WriteByteSeq(transGuid[6]);
data2.WriteByteSeq(transGuid[5]);
data2.WriteByteSeq(transGuid[1]);
data2.WriteByteSeq(transGuid[7]);
data2.WriteByteSeq(transGuid[0]);
data2.WriteByteSeq(transGuid[2]);
data2.WriteByteSeq(transGuid[4]);
data2.WriteByteSeq(transGuid[3]);
}
data2 << uint32(0); // counter
data2.WriteByteSeq(guid[1]);
data2.WriteByteSeq(guid[2]);
data2.WriteByteSeq(guid[3]);
data2.WriteByteSeq(guid[5]);
data2 << float(GetPositionX());
data2.WriteByteSeq(guid[4]);
data2 << float(GetOrientation());
data2.WriteByteSeq(guid[7]);
data2 << float(GetPositionZMinusOffset());
data2.WriteByteSeq(guid[0]);
data2.WriteByteSeq(guid[6]);
data2 << float(GetPositionY());
ToPlayer()->SendDirectMessage(&data2); // Send the MSG_MOVE_TELEPORT packet to self.
}
// Relocate the player/creature to its old position, so we can broadcast to nearby players correctly
if (GetTypeId() == TYPEID_PLAYER)
Relocate(&pos);
else
Relocate(&oldPos);
// Broadcast the packet to everyone except self.
SendMessageToSet(&data, false);
}
bool Unit::UpdatePosition(float x, float y, float z, float orientation, bool teleport)
{
// prevent crash when a bad coord is sent by the client
if (!Trinity::IsValidMapCoord(x, y, z, orientation))
{
sLog->outDebug(LOG_FILTER_UNITS, "Unit::UpdatePosition(%f, %f, %f) .. bad coordinates!", x, y, z);
return false;
}
bool turn = (GetOrientation() != orientation);
bool relocated = (teleport || GetPositionX() != x || GetPositionY() != y || GetPositionZ() != z);
if (turn)
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
if (relocated)
{
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE);
// move and update visible state if need
if (GetTypeId() == TYPEID_PLAYER)
GetMap()->PlayerRelocation(ToPlayer(), x, y, z, orientation);
else
GetMap()->CreatureRelocation(ToCreature(), x, y, z, orientation);
}
else if (turn)
UpdateOrientation(orientation);
// code block for underwater state update
UpdateUnderwaterState(GetMap(), x, y, z);
return (relocated || turn);
}
//! Only server-side orientation update, does not broadcast to client
void Unit::UpdateOrientation(float orientation)
{
SetOrientation(orientation);
if (IsVehicle())
GetVehicleKit()->RelocatePassengers();
}
//! Only server-side height update, does not broadcast to client
void Unit::UpdateHeight(float newZ)
{
Relocate(GetPositionX(), GetPositionY(), newZ);
if (IsVehicle())
GetVehicleKit()->RelocatePassengers();
}
void Unit::SendThreatListUpdate()
{
if (!getThreatManager().isThreatListEmpty())
{
uint32 count = getThreatManager().getThreatList().size();
sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Send SMSG_THREAT_UPDATE Message");
WorldPacket data(SMSG_THREAT_UPDATE, 8 + count * 8);
data.append(GetPackGUID());
data << uint32(count);
ThreatContainer::StorageType const &tlist = getThreatManager().getThreatList();
for (ThreatContainer::StorageType::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
{
data.appendPackGUID((*itr)->getUnitGuid());
data << uint32((*itr)->getThreat()*100);
}
SendMessageToSet(&data, false);
}
}
void Unit::SendChangeCurrentVictimOpcode(HostileReference* pHostileReference)
{
if (!getThreatManager().isThreatListEmpty())
{
uint32 count = getThreatManager().getThreatList().size();
sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Send SMSG_HIGHEST_THREAT_UPDATE Message");
WorldPacket data(SMSG_HIGHEST_THREAT_UPDATE, 8 + 8 + count * 8);
data.append(GetPackGUID());
data.appendPackGUID(pHostileReference->getUnitGuid());
data << uint32(count);
ThreatContainer::StorageType const &tlist = getThreatManager().getThreatList();
for (ThreatContainer::StorageType::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
{
data.appendPackGUID((*itr)->getUnitGuid());
data << uint32((*itr)->getThreat());
}
SendMessageToSet(&data, false);
}
}
void Unit::SendClearThreatListOpcode()
{
sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Send SMSG_THREAT_CLEAR Message");
WorldPacket data(SMSG_THREAT_CLEAR, 8);
data.append(GetPackGUID());
SendMessageToSet(&data, false);
}
void Unit::SendRemoveFromThreatListOpcode(HostileReference* pHostileReference)
{
sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Send SMSG_THREAT_REMOVE Message");
WorldPacket data(SMSG_THREAT_REMOVE, 8 + 8);
data.append(GetPackGUID());
data.appendPackGUID(pHostileReference->getUnitGuid());
SendMessageToSet(&data, false);
}
// baseRage means damage taken when attacker = false
void Unit::RewardRage(uint32 baseRage, bool attacker)
{
float addRage;
if (attacker)
{
addRage = baseRage;
// talent who gave more rage on attack
AddPct(addRage, GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT));
}
else
{
// Calculate rage from health and damage taken
//! ToDo: Check formula
addRage = floor(0.5f + (25.7f * baseRage / GetMaxHealth()));
// Berserker Rage effect
if (HasAura(18499))
addRage *= 2.0f;
}
addRage *= sWorld->getRate(RATE_POWER_RAGE_INCOME);
ModifyPower(POWER_RAGE, uint32(addRage * 10));
}
void Unit::StopAttackFaction(uint32 faction_id)
{
if (Unit* victim = getVictim())
{
if (victim->getFactionTemplateEntry()->faction == faction_id)
{
AttackStop();
if (IsNonMeleeSpellCasted(false))
InterruptNonMeleeSpells(false);
// melee and ranged forced attack cancel
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SendAttackSwingCancelAttack();
}
}
AttackerSet const& attackers = getAttackers();
for (AttackerSet::const_iterator itr = attackers.begin(); itr != attackers.end();)
{
if ((*itr)->getFactionTemplateEntry()->faction == faction_id)
{
(*itr)->AttackStop();
itr = attackers.begin();
}
else
++itr;
}
getHostileRefManager().deleteReferencesForFaction(faction_id);
for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
(*itr)->StopAttackFaction(faction_id);
}
void Unit::OutDebugInfo() const
{
sLog->outError(LOG_FILTER_UNITS, "Unit::OutDebugInfo");
sLog->outInfo(LOG_FILTER_UNITS, "GUID "UI64FMTD", entry %u, type %u, name %s", GetGUID(), GetEntry(), (uint32)GetTypeId(), GetName().c_str());
sLog->outInfo(LOG_FILTER_UNITS, "OwnerGUID "UI64FMTD", MinionGUID "UI64FMTD", CharmerGUID "UI64FMTD", CharmedGUID "UI64FMTD, GetOwnerGUID(), GetMinionGUID(), GetCharmerGUID(), GetCharmGUID());
sLog->outInfo(LOG_FILTER_UNITS, "In world %u, unit type mask %u", (uint32)(IsInWorld() ? 1 : 0), m_unitTypeMask);
if (IsInWorld())
sLog->outInfo(LOG_FILTER_UNITS, "Mapid %u", GetMapId());
std::ostringstream o;
o << "Summon Slot: ";
for (uint32 i = 0; i < MAX_SUMMON_SLOT; ++i)
o << m_SummonSlot[i] << ", ";
sLog->outInfo(LOG_FILTER_UNITS, "%s", o.str().c_str());
o.str("");
o << "Controlled List: ";
for (ControlList::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
o << (*itr)->GetGUID() << ", ";
sLog->outInfo(LOG_FILTER_UNITS, "%s", o.str().c_str());
o.str("");
o << "Aura List: ";
for (AuraApplicationMap::const_iterator itr = m_appliedAuras.begin(); itr != m_appliedAuras.end(); ++itr)
o << itr->first << ", ";
sLog->outInfo(LOG_FILTER_UNITS, "%s", o.str().c_str());
o.str("");
if (IsVehicle())
{
o << "Passenger List: ";
for (SeatMap::iterator itr = GetVehicleKit()->Seats.begin(); itr != GetVehicleKit()->Seats.end(); ++itr)
if (Unit* passenger = ObjectAccessor::GetUnit(*GetVehicleBase(), itr->second.Passenger))
o << passenger->GetGUID() << ", ";
sLog->outInfo(LOG_FILTER_UNITS, "%s", o.str().c_str());
}
if (GetVehicle())
sLog->outInfo(LOG_FILTER_UNITS, "On vehicle %u.", GetVehicleBase()->GetEntry());
}
uint32 Unit::GetRemainingPeriodicAmount(uint64 caster, uint32 spellId, AuraType auraType, uint8 effectIndex) const
{
uint32 amount = 0;
AuraEffectList const& periodicAuras = GetAuraEffectsByType(auraType);
for (AuraEffectList::const_iterator i = periodicAuras.begin(); i != periodicAuras.end(); ++i)
{
if ((*i)->GetCasterGUID() != caster || (*i)->GetId() != spellId || (*i)->GetEffIndex() != effectIndex || !(*i)->GetTotalTicks())
continue;
amount += uint32(((*i)->GetAmount() * std::max<int32>((*i)->GetTotalTicks() - int32((*i)->GetTickNumber()), 0)) / (*i)->GetTotalTicks());
break;
}
return amount;
}
void Unit::SendClearTarget()
{
WorldPacket data(SMSG_BREAK_TARGET, GetPackGUID().size());
data.append(GetPackGUID());
SendMessageToSet(&data, false);
}
uint32 Unit::GetResistance(SpellSchoolMask mask) const
{
int32 resist = -1;
for (int i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i)
if (mask & (1 << i) && (resist < 0 || resist > int32(GetResistance(SpellSchools(i)))))
resist = int32(GetResistance(SpellSchools(i)));
// resist value will never be negative here
return uint32(resist);
}
void CharmInfo::SetIsCommandAttack(bool val)
{
_isCommandAttack = val;
}
bool CharmInfo::IsCommandAttack()
{
return _isCommandAttack;
}
void CharmInfo::SetIsCommandFollow(bool val)
{
_isCommandFollow = val;
}
bool CharmInfo::IsCommandFollow()
{
return _isCommandFollow;
}
void CharmInfo::SaveStayPosition()
{
//! At this point a new spline destination is enabled because of Unit::StopMoving()
G3D::Vector3 const stayPos = _unit->movespline->FinalDestination();
_stayX = stayPos.x;
_stayY = stayPos.y;
_stayZ = stayPos.z;
}
void CharmInfo::GetStayPosition(float &x, float &y, float &z)
{
x = _stayX;
y = _stayY;
z = _stayZ;
}
void CharmInfo::SetIsAtStay(bool val)
{
_isAtStay = val;
}
bool CharmInfo::IsAtStay()
{
return _isAtStay;
}
void CharmInfo::SetIsFollowing(bool val)
{
_isFollowing = val;
}
bool CharmInfo::IsFollowing()
{
return _isFollowing;
}
void CharmInfo::SetIsReturning(bool val)
{
_isReturning = val;
}
bool CharmInfo::IsReturning()
{
return _isReturning;
}
void Unit::SetInFront(Unit const* target)
{
if (!HasUnitState(UNIT_STATE_CANNOT_TURN))
SetOrientation(GetAngle(target));
}
void Unit::SetFacingTo(float ori)
{
Movement::MoveSplineInit init(this);
init.MoveTo(GetPositionX(), GetPositionY(), GetPositionZMinusOffset(), false);
init.SetFacing(ori);
init.Launch();
}
void Unit::SetFacingToObject(WorldObject* object)
{
// never face when already moving
if (!IsStopped())
return;
// TODO: figure out under what conditions creature will move towards object instead of facing it where it currently is.
SetFacingTo(GetAngle(object));
}
bool Unit::SetWalk(bool enable)
{
if (enable == IsWalking())
return false;
if (enable)
AddUnitMovementFlag(MOVEMENTFLAG_WALKING);
else
RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING);
return true;
}
bool Unit::SetDisableGravity(bool disable, bool /*packetOnly = false*/)
{
if (disable == IsLevitating())
return false;
if (disable)
AddUnitMovementFlag(MOVEMENTFLAG_DISABLE_GRAVITY);
else
RemoveUnitMovementFlag(MOVEMENTFLAG_DISABLE_GRAVITY);
return true;
}
bool Unit::SetHover(bool enable)
{
if (enable == HasUnitMovementFlag(MOVEMENTFLAG_HOVER))
return false;
if (enable)
{
//! No need to check height on ascent
AddUnitMovementFlag(MOVEMENTFLAG_HOVER);
if (float hh = GetFloatValue(UNIT_FIELD_HOVERHEIGHT))
UpdateHeight(GetPositionZ() + hh);
}
else
{
RemoveUnitMovementFlag(MOVEMENTFLAG_HOVER);
if (float hh = GetFloatValue(UNIT_FIELD_HOVERHEIGHT))
{
float newZ = GetPositionZ() - hh;
UpdateAllowedPositionZ(GetPositionX(), GetPositionY(), newZ);
UpdateHeight(newZ);
}
}
return true;
}
void Unit::SendMovementHover()
{
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SendMovementSetHover(HasUnitMovementFlag(MOVEMENTFLAG_HOVER));
WorldPacket data(MSG_MOVE_HOVER, 64);
data.append(GetPackGUID());
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
}
void Unit::SendMovementWaterWalking()
{
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SendMovementSetWaterWalking(HasUnitMovementFlag(MOVEMENTFLAG_WATERWALKING));
WorldPacket data(MSG_MOVE_WATER_WALK, 64);
data.append(GetPackGUID());
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
}
void Unit::SendMovementFeatherFall()
{
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SendMovementSetFeatherFall(HasUnitMovementFlag(MOVEMENTFLAG_FALLING_SLOW));
WorldPacket data(MSG_MOVE_FEATHER_FALL, 64);
data.append(GetPackGUID());
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
}
void Unit::SendMovementGravityChange()
{
WorldPacket data(MSG_MOVE_GRAVITY_CHNG, 64);
data.append(GetPackGUID());
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
}
void Unit::SendMovementCanFlyChange()
{
/*!
if ( a3->MoveFlags & MOVEMENTFLAG_CAN_FLY )
{
v4->MoveFlags |= 0x1000000u;
result = 1;
}
else
{
if ( v4->MoveFlags & MOVEMENTFLAG_FLYING )
CMovement::DisableFlying(v4);
v4->MoveFlags &= 0xFEFFFFFFu;
result = 1;
}
*/
if (GetTypeId() == TYPEID_PLAYER)
ToPlayer()->SendMovementSetCanFly(CanFly());
WorldPacket data(MSG_MOVE_UPDATE_CAN_FLY, 64);
data.append(GetPackGUID());
BuildMovementPacket(&data);
SendMessageToSet(&data, false);
}
bool Unit::IsSplineEnabled() const
{
return movespline->Initialized();
}
void Unit::FocusTarget(Spell const* focusSpell, uint64 target)
{
// already focused
if (_focusSpell)
return;
_focusSpell = focusSpell;
SetUInt64Value(UNIT_FIELD_TARGET, target);
if (focusSpell->GetSpellInfo()->AttributesEx5 & SPELL_ATTR5_DONT_TURN_DURING_CAST)
AddUnitState(UNIT_STATE_ROTATING);
}
void Unit::ReleaseFocus(Spell const* focusSpell)
{
// focused to something else
if (focusSpell != _focusSpell)
return;
_focusSpell = NULL;
if (Unit* victim = getVictim())
SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
else
SetUInt64Value(UNIT_FIELD_TARGET, 0);
if (focusSpell->GetSpellInfo()->AttributesEx5 & SPELL_ATTR5_DONT_TURN_DURING_CAST)
ClearUnitState(UNIT_STATE_ROTATING);
}
|
gpl-2.0
|
carrer/campbus
|
androidStudio/campbus/campbus/src/main/java/com/carr3r/campbus/Definitions.java
|
147
|
package com.carr3r.campbus;
/**
* Created by carrer on 10/28/14.
*/
public class Definitions {
public static final boolean DEBUG = false;
}
|
gpl-2.0
|
aureka/devicr
|
src/DevicrSourceFinder.js
|
706
|
function DevicrSourceFinder(devicr_device) {
this.devicr_device = devicr_device;
}
DevicrSourceFinder.prototype.findHighestAvailableSource = function(devicr_element) {
var available_devices = devicr_element.getAvailableDevices();
if (available_devices.length === 0) {
return null;
}
return devicr_element.getSourceFor(available_devices.shift());
};
DevicrSourceFinder.prototype.findFirstHigherAvailableSource = function(devicr_element) {
var higher_available_devices = devicr_element.getHigherAvailableDevicesThan(this.devicr_device.getDevice());
if (higher_available_devices.length === 0) {
return null;
}
return devicr_element.getSourceFor(higher_available_devices.pop());
};
|
gpl-2.0
|
ladyka/webtehnology
|
work2v6/src/org/vurtatoo/Task1.java
|
1934
|
package org.vurtatoo;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class OrderInfo
*/
@WebServlet("/task1")
public class Task1 extends MyServlet {
private static final long serialVersionUID = 10L;
/**
* @see HttpServlet#HttpServlet()
*/
public Task1() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response, Statement statement) {
int orderId = getValueInt(request,"id");
ResultSet resultSet;
try {
resultSet = statement.executeQuery(SQLREQUESTS.getOrderInfoSQL(orderId));
List<ShipmentOrderView> orderViews = new ArrayList<ShipmentOrderView>();
int priceTotal = 0;
while (resultSet.next()) {
ShipmentOrderView orderView = new ShipmentOrderView(
resultSet.getInt(1),
resultSet.getString(2),
resultSet.getString(3),
resultSet.getString(4),
resultSet.getInt(5),
resultSet.getInt(6));
orderViews.add(orderView);
priceTotal += orderView.getCount()*orderView.getShipmentPrice();
}
request.setAttribute("priceTotal", priceTotal);
request.setAttribute("orderViews", orderViews);
request.getRequestDispatcher("/orders.jsp").forward(request,response);
} catch (SQLException | ServletException | IOException e) {
e.printStackTrace();
}
}
}
|
gpl-2.0
|
tomas-pluskal/mzmine3
|
src/main/java/io/github/mzmine/modules/visualization/kendrickmassplot/KendrickMassPlotXYDataset.java
|
4831
|
/*
* Copyright 2006-2020 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* MZmine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with MZmine; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.github.mzmine.modules.visualization.kendrickmassplot;
import io.github.mzmine.datamodel.features.FeatureList;
import io.github.mzmine.datamodel.features.FeatureListRow;
import org.jfree.data.xy.AbstractXYDataset;
import io.github.mzmine.parameters.ParameterSet;
import io.github.mzmine.util.FormulaUtils;
/**
* XYDataset for Kendrick mass plots
*
* @author Ansgar Korf (ansgar.korf@uni-muenster.de)
*/
class KendrickMassPlotXYDataset extends AbstractXYDataset {
private static final long serialVersionUID = 1L;
private FeatureListRow selectedRows[];
private String xAxisKMBase;
private String customYAxisKMBase;
private String customXAxisKMBase;
private double[] xValues;
private double[] yValues;
private ParameterSet parameters;
public KendrickMassPlotXYDataset(ParameterSet parameters) {
FeatureList featureList = parameters.getParameter(KendrickMassPlotParameters.featureList).getValue()
.getMatchingFeatureLists()[0];
this.parameters = parameters;
this.selectedRows =
parameters.getParameter(KendrickMassPlotParameters.selectedRows).getMatchingRows(featureList);
this.customYAxisKMBase =
parameters.getParameter(KendrickMassPlotParameters.yAxisCustomKendrickMassBase).getValue();
if (parameters.getParameter(KendrickMassPlotParameters.xAxisCustomKendrickMassBase)
.getValue() == true) {
this.customXAxisKMBase =
parameters.getParameter(KendrickMassPlotParameters.xAxisCustomKendrickMassBase)
.getEmbeddedParameter().getValue();
} else {
this.xAxisKMBase = parameters.getParameter(KendrickMassPlotParameters.xAxisValues).getValue();
}
// Calc xValues
xValues = new double[selectedRows.length];
if (parameters.getParameter(KendrickMassPlotParameters.xAxisCustomKendrickMassBase)
.getValue() == true) {
for (int i = 0; i < selectedRows.length; i++) {
xValues[i] =
Math.ceil(selectedRows[i].getAverageMZ() * getKendrickMassFactor(customXAxisKMBase))
- selectedRows[i].getAverageMZ() * getKendrickMassFactor(customXAxisKMBase);
}
} else {
for (int i = 0; i < selectedRows.length; i++) {
// simply plot m/z values as x axis
if (xAxisKMBase.equals("m/z")) {
xValues[i] = selectedRows[i].getAverageMZ();
}
// plot Kendrick masses as x axis
else if (xAxisKMBase.equals("KM")) {
xValues[i] = selectedRows[i].getAverageMZ() * getKendrickMassFactor(customYAxisKMBase);
}
}
}
// Calc yValues
yValues = new double[selectedRows.length];
for (int i = 0; i < selectedRows.length; i++) {
yValues[i] =
Math.ceil((selectedRows[i].getAverageMZ()) * getKendrickMassFactor(customYAxisKMBase))
- (selectedRows[i].getAverageMZ()) * getKendrickMassFactor(customYAxisKMBase);
}
}
public ParameterSet getParameters() {
return parameters;
}
public void setParameters(ParameterSet parameters) {
this.parameters = parameters;
}
@Override
public int getItemCount(int series) {
return selectedRows.length;
}
@Override
public Number getX(int series, int item) {
return xValues[item];
}
@Override
public Number getY(int series, int item) {
return yValues[item];
}
@Override
public int getSeriesCount() {
return 1;
}
public Comparable<?> getRowKey(int row) {
return selectedRows[row].toString();
}
@Override
public Comparable<?> getSeriesKey(int series) {
return getRowKey(series);
}
public double[] getxValues() {
return xValues;
}
public double[] getyValues() {
return yValues;
}
public void setxValues(double[] values) {
xValues = values;
}
public void setyValues(double[] values) {
yValues = values;
}
private double getKendrickMassFactor(String formula) {
double exactMassFormula = FormulaUtils.calculateExactMass(formula);
return ((int) (exactMassFormula + 0.5d)) / exactMassFormula;
}
}
|
gpl-2.0
|
olindata/node-puppet-hiera
|
adapters/git.js
|
2701
|
/**
* Git adapter for Puppet Hiera.
*
* @author rajkissu <rajkissu@gmail.com>
*/
/* jslint node: true */
'use strict';
var path, git, File;
path = require('path');
git = require('nodegit');
File = require('./file');
/**
* The Git adapter class.
*
* @class Git
*/
class Git extends File {
/**
* The Git constructor.
*
* @constructor
*
* @param {Object} config - configuration options.
*
* @example new Git({
* token : 'sometoken',
* repo : '/path/to/repo.git',
* signature : { name : 'Name', email : '<email>' }
* });
*/
constructor(config) {
super(config);
var signature = config.signature;
this.token = config.token;
this.repo = config.repo;
this.signature = git.Signature.create(
signature.name,
signature.email,
Math.floor((new Date).getTime() / 1000),
480
);
}
/**
* Writes a file.
*
* @method
*
* @param {string} file - the file path to write to.
* @param {string} data - the data to write to the file.
* @param {Function} cb - callback to invoke.
*
* @example
*/
writeFile(file, data, cb) {
var me, _repository, _oid;
me = this;
git.Repository.open(path.resolve(__dirname, me.repo))
.then(function (repo) {
_repository = repo;
return repo.openIndex();
})
.then(function (index) {
index.read();
index.addByPath(file);
index.write();
return index.writeTree();
})
.then(function (oid) {
_oid = oid;
return git.Reference.nameToId(_repository, 'HEAD');
})
.then(function (head) {
return _repository.getCommit(head);
})
.then(function (parent) {
return _repository.createCommit(
'HEAD', me.signature, me.signature,
'Saves ' + file, _oid, [ parent ]
);
})
.then(function () {
return git.Remote.lookup(_repository, 'origin')
.then(function (remote) {
remote.connect(git.Enums.DIRECTION.PUSH);
remote.setCallbacks({
credentials: function(url, userName) {
return git.Cred.userpassPlaintextNew(me.token, 'x-oauth-basic');
},
certificateCheck: function () {
return 1;
}
});
return remote;
})
.then(function (remote) {
var ref, refs;
ref = 'refs/heads/master';
refs = [ ref + ':' + ref ];
// Create the push object for this remote
return remote.push(
refs,
null,
me.signature,
'Push to master'
);
});
})
.done(cb);
}
}
module.exports = Git;
|
gpl-2.0
|
ericdum/niuble.com
|
other_sites/showcases/sixue/templates_c/fd33d9bdae3771c252299843aab4f2c16ec2278c.file.step3.php.cache.php
|
1759
|
<?php /* Smarty version Smarty-3.1.6, created on 2011-12-19 21:30:31
compiled from "/Users/ericdum/Sites/work/sixue365/1/templates/contents/register_includes/teacher/step3.php" */ ?>
<?php /*%%SmartyHeaderCode:10694164254eee7e64c49c98-85267441%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'fd33d9bdae3771c252299843aab4f2c16ec2278c' =>
array (
0 => '/Users/ericdum/Sites/work/sixue365/1/templates/contents/register_includes/teacher/step3.php',
1 => 1324255720,
2 => 'file',
),
),
'nocache_hash' => '10694164254eee7e64c49c98-85267441',
'function' =>
array (
),
'version' => 'Smarty-3.1.6',
'unifunc' => 'content_4eee7e64c4eec',
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_4eee7e64c4eec')) {function content_4eee7e64c4eec($_smarty_tpl) {?><div class="title clearfix">
<div class="textPhoneHelp"></div>
<div class="textNoMoreLess"></div>
</div>
<ul class="generalForm">
<li>
<label>简历:</label>
<input type="text" disabled/>
<a href="javascript:void(0)" class="browse">选择文件</a>
<input type="file" class="hiddenFile" name="name"/>
</li>
<li>
<label>资质证明:</label>
<input type="text" disabled/>
<a href="javascript:void(0)" class="browse">选择文件</a>
<input type="file" class="hiddenFile" name="name"/>
</li>
<li>
<label></label>
<a href="javascript:void(0);" class="grayButton Button40">跳过</a>
<a href="javascript:void(0);" class="generalButton Button40">上传</a>
</li>
<ul>
<?php }} ?>
|
gpl-2.0
|
keplerf/Partybuses.ca
|
customhomeTemp.php
|
9206
|
<?php
/**
* Template Name: Home Page TEMP
* Description: Custom Home Page for Silver Lady Limo
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php
/*
* Print the <title> tag based on what is being viewed.
*/
global $page, $paged;
wp_title( '|', true, 'right' );
// Add the blog name.
bloginfo( 'name' );
// Add the blog description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
echo " | $site_description";
// Add a page number if necessary:
if ( $paged >= 2 || $page >= 2 )
echo ' | ' . sprintf( __( 'Page %s', 'twentyeleven' ), max( $paged, $page ) );
?></title>
<link rel="shortcut icon" href="<?php bloginfo('url'); ?>/favicon.ico" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<![endif]-->
<?php
/* We add some JavaScript to pages with the comment form
* to support sites with threaded comments (when in use).
*/
if ( is_singular() && get_option( 'thread_comments' ) )
wp_enqueue_script( 'comment-reply' );
/* Always have wp_head() just before the closing </head>
* tag of your theme, or you will break many plugins, which
* generally use this hook to add elements to <head> such
* as styles, scripts, and meta tags.
*/
wp_head();
?>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1030054-37']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body <?php body_class(); ?> style="background:#000815;">
<div class="hfeed" id="page">
<div id="branding" style="display:none">
<div id="mainLogo">
<h3><a href="<?php bloginfo('url'); ?>/" title="Vancouver Party Limo Bus"><img src="<?php bloginfo('url'); ?>/imgs/sllLogo.png" alt="Vancouver Party Limo Bus" border="0" /></a> </h3>
</div>
<div id="silverHeader">
<div id="phone-header">
<p>RESERVE NOW! <img src="<?php bloginfo('template_url'); ?>/images/phone-icon.png" width="13" height="24" alt="Phone Vancouver Party Limo Bus"/> 604.520.2222 | 1.888.871.3326 </p>
</div>
</div>
<div id="access">
<div class="menu" id="nav">
<ul>
<li>
<a class="contact" href="<?php bloginfo('url'); ?>/contact/" title="Contact Us"><span>Contact Party Buses Vancouver </span></a>
</li>
<li>
<a class="reservations" href="https://book.mylimobiz.com/silverlady/" title="eReservations"><span>party bus Reservations</span></a>
</li>
<li>
<a class="quote" href="https://book.mylimobiz.com/silverlady/Quote" title="Get A Quote"> <span>party bus rental quote </span> </a>
</li>
<li>
<a class="specials" href="<?php bloginfo('url'); ?>/specials/" title="Specials"><span>Specials limousine services Vancouver Canada </span> </a>
</li>
<li>
<a class="fleet"href="<?php bloginfo('url'); ?>/party-buses/" title="The Fleet"> <span>Party Buses</span></a>
<ul class="dropdown">
<li> <a href="<?php bloginfo('url'); ?>/fleet/limo-buses/">Party Buses </a></li>
</ul>
</li>
</ul>
</div>
</div><!-- #access -->
</div><!-- #branding -->
<div id="main">
<div id="solcial-media-btn" style="display:none"> <a href="http://www.facebook.com/pages/Silver-Lady-Limo/278917805451723" target="_new"><img src="<?php bloginfo('template_url'); ?>/images/icon-facebook.jpg" width="21" height="22" alt="limousine limo services facebook Vancouver" /></a>
<a href="https://twitter.com/#!/SilverLadyLimo" target="_new"><img src="<?php bloginfo('template_url'); ?>/images/icon-twitter.jpg" width="21" height="22" alt="limousine limo services twitter Vancouver" /></a>
<a href="http://www.youtube.com/user/SilverLadyLimo" target="_new"><img src="<?php bloginfo('template_url'); ?>/images/icon-you.jpg" alt="limousine limo services youtube Vancouver" width="23" height="22" border="0" /></a>
<a href="https://plus.google.com/u/0/103068552791740585290/posts" target="_new"><img src="<?php bloginfo('template_url'); ?>/images/icon-google.jpg" width="22" height="22" alt="limousine limo services googleplus Vancouver" /></a>
</div>
<div id="home_content" style="display:none">
<table border="0" cellspacing="5">
<tbody>
<tr>
<td width="33%">
<h2><a href="/fleet/"><img class="size-full wp-image-226 " title="limousine-services-vancouver-party-bus" src="http://partybuses.ca/wp-content/uploads/2011/09/see-our-fleet.jpg" alt="limousine services in Vancouver BC Canada" width="177" height="138" /></a></h2>
</td>
<td width="33%"><a title="Specials" href="http://partybuses.ca/specials/"><img class="size-full wp-image-227" title="limousine-services-vancouver-special" src="http://partybuses.ca/wp-content/uploads/2011/09/special-deal.jpg" alt="Special limousine services in Vancouver BC Canada" width="177" height="138" /></a></td>
<td width="33%"><a href="https://book.mylimobiz.com/silverlady/Quote"><img class="size-full wp-image-228" title="limousine-services-vancouver-party-bus-canada" src="http://partybuses.ca/wp-content/uploads/2011/09/get-a-quote.jpg" alt="limousine services in Vancouver BC Canada" width="177" height="138" /></a></td>
</tr>
</tbody>
</table>
<h1><strong>Silver Lady Limousine Services</strong></h1>
is focused on presenting each and every client with a unique, one-of-a-kind extraordinary experience.
We have a long history of more than 25 years providing reliable, safe and professional service to corporate, consumer, and celebrity clientele who come back to us for:
<ul>
<li>Online Reservations and Quotations - 24/7/365</li>
<li>Vancouver's Largest Fleet of New S.U.V.'s and New Limo Party Buses</li>
<li>Professional, Experienced & Courteous Chauffeurs</li>
<li>Weekly & Monthly Specials, Low Mid-Week Rates & Group Discounts</li>
</ul>
</div>
<div style="width:960px; margin:auto; text-align:center; color:#CCCCCC; font-size:18px; padding: 150px 0"> <a href="http://partybuses.ca/"><img src="<?php bloginfo('template_url'); ?>/images/understru.jpg" alt="Vancouver Party Limo Bus" border="0"/></a>
<div>
<p style="font-size:23px"><a style="color:#CCCCCC; text-decoration:none" href="tel:16045202222">604.520.2222</a> | <a style="color:#CCCCCC;text-decoration:none" href="tel:18888713326">1.888.871.3326 </a></p>
<p><a style="color:#09F" href="mailto:info@silverladylimo.com">info@silverladylimo.com </a></p>
</div>
</div>
<div style="display:none">
<div id="colophon" class="footer">
<div class="go-logo"><img src="<?php bloginfo('template_url'); ?>/images/go.jpg" width="234" height="34" alt="limo vancouver" /></div>
<div id="footerlogo"> <a href="<?php bloginfo('url'); ?>"><img src="<?php bloginfo('template_url'); ?>/images/logo-footer.jpg" alt="Silver Lady Limousine Service Vancouver" width="217" height="103" border="0" /></a></div>
<div id="footerLinks">
<a href="<?php bloginfo('url'); ?>/">HOME</a> |
<a href="<?php bloginfo('url'); ?>/the-latest/">THE LATEST</a> |
<a href="<?php bloginfo('url'); ?>/fleet/">THE FLEET</a> |
<a href="<?php bloginfo('url'); ?>/specials/">SPECIALS</a> |
<a href="https://book.mylimobiz.com/silverlady/Quote">GET A QUOTE</a> |
<a href="https://book.mylimobiz.com/silverlady/">eRESERVATIONS</a> |
<a href="<?php bloginfo('url'); ?>/contact/">CONTACT US</a> |
<a href="<?php bloginfo('url'); ?>/caree/">CAREERS</a>
</div>
<div id="footerPaymentIMG">
<img style="margin:-5px 0 0 0; vertical-align:middle" src="<?php bloginfo('template_url'); ?>/images/bbb.jpg" width="74" height="38" alt="bbb Canada Vancouver" /> <img src="<?php bloginfo('url'); ?>/imgs/paymentOptions.png" alt="limousine services payment" class="paymentType" />
</div>
<div id="footerCopyright">
<p>Copyright © <?
//determine copyright year.
echo date("Y");
?> - <a href="http://silverladylimo.com/" title="limousine services vancouver">Silver Lady Limousine & S.U.V. Limousine Service</a> Ltd.<br />
<a href="<?php bloginfo('url'); ?>/terms-and-conditions/">Terms and Conditions</a> |
<a href="<?php bloginfo('url'); ?>/privacy-policy/">Privacy Policy</a> |
<a href="<?php bloginfo('url'); ?>/links">Links</a><br />
</p>
</div>
</div>
</div><!-- #colophon -->
</div>
|
gpl-2.0
|
svyatoslavteterin/belton.by
|
core/lexicon/cs/tv_widget.inc.php
|
8778
|
<?php
/**
* TV Widget English lexicon topic
*
* @language en
* @package modx
* @subpackage lexicon
*/
$_lang['attributes'] = 'Atributy';
$_lang['capitalize'] = 'Kapitálkami';
$_lang['checkbox'] = 'Zaškrtávací políčko';
$_lang['checkbox_columns'] = 'Sloupce';
$_lang['checkbox_columns_desc'] = 'Počet sloupců, ve kterých jsou zaškrtávací pole zobrazena.';
$_lang['class'] = 'Třída';
$_lang['combo_allowaddnewdata'] = 'Povolit přidání nových položek';
$_lang['combo_allowaddnewdata_desc'] = 'Pokud Ano, pak lze přidat nové položky, které dosud nejsou v seznamu. Výchozí nastavení je Ne.';
$_lang['combo_forceselection'] = 'Pouze položky ze seznamu';
$_lang['combo_forceselection_desc'] = 'Je-li aktivní našeptávač a tato volba nastavena na Ano, pak lze vybrat pouze položku ze seznamu.';
$_lang['combo_listempty_text'] = 'Text pokud není nápověda';
$_lang['combo_listempty_text_desc'] = 'Je-li aktivní našeptávač a uživatel zadá hodnotu, která není v seznamu zobrazí se mu tento text.';
$_lang['combo_listheight'] = 'Výška seznamu';
$_lang['combo_listheight_desc'] = 'Výška seznamu v pixelech. Výchozí hodnotou je výška rozbalovacího seznamu.';
$_lang['combo_listwidth'] = 'Šířka seznamu';
$_lang['combo_listwidth_desc'] = 'Šířka seznamu v pixelech. Výchozí hodnoutou je šířka seznamu v závislosti na délce nejdelší položky.';
$_lang['combo_maxheight'] = 'Maximální výška seznamu';
$_lang['combo_maxheight_desc'] = 'Maximální výška seznamu v pixelech než jsou zobrazeny posuvníky. Výchozí hodnota je 300.';
$_lang['combo_stackitems'] = 'Vybrané položky pod sebou';
$_lang['combo_stackitems_desc'] = 'Je-li tato volba nastavena na Ano, pak budou vybrané položky zobrazeny každá na jednom řádku pod sebou. Výchozí hodnota je Ne, pak jsou položky zobrazeny za sebou.';
$_lang['combo_title'] = 'Hlavička seznamu';
$_lang['combo_title_desc'] = 'Je-li vyplněna, bude na začátku seznamu zobrazen tento text.';
$_lang['combo_typeahead'] = 'Povolit našeptávač';
$_lang['combo_typeahead_desc'] = 'Je-li povolen, dochází automaticky pouze k zobrazení položek odpovídajících textu zadaného uživatelem v rámci nastavené prodlevy (Prodleva našeptávače). Výchozí hodnota je vypnuto.';
$_lang['combo_typeahead_delay'] = 'Prodleva našeptávače';
$_lang['combo_typeahead_delay_desc'] = 'Čas v milisekundách, po které je zobrazen výsledek našeptávače, pokud je našeptávač aktivní. Výchozí hodnota je 250.';
$_lang['date'] = 'Datum';
$_lang['date_format'] = 'Formát data';
$_lang['date_use_current'] = 'Pokud není definováno použij aktuální datum';
$_lang['default'] = 'Výchozí';
$_lang['delim'] = 'Odděl.';
$_lang['delimiter'] = 'Oddělovač';
$_lang['disabled_dates'] = 'Zakázané datumy';
$_lang['disabled_dates_desc'] = 'Čárkou oddělený seznam datumů, které mají být zakázány. Tyto řetězce se použijí k vygenerování regulárního výrazu. Například:<br />
- Přímo zakázané dny v jednom roce: 2003-03-08,2003-09-16<br />
- Zakázané dny každý rok: 03-08,09-16<br />
- Kontrolovat pouze začátky (Užitečné pokud používáte krátký zápis roku): ^03-08<br />
- Zakázání každého dne v březnu 2006: 03-..-2006<br />
- Zakázání všech dní v březnu každý rok: ^03<br />
Pozor na to, že formát zadávaných dat musí korespondovat s formátem nastaveným v konfiguraci systému. Pokud obsahuje požadovaný formát data tečku ".", je nutné ji vždy eskejpovat "\\.", jinak by došlo k problémům při vyhodnocování regulárního výrazu.';
$_lang['disabled_days'] = 'Zakázané dny';
$_lang['disabled_days_desc'] = 'Čárkou oddělený seznam dnů, které mají být zakázané, počítáno od 0 (výchozí hodnota je prázdné pole). Například:<br />
- Zakázaná neděle a sobota: 0,6<br />
- Zakázané pracovní dny: 1,2,3,4,5';
$_lang['dropdown'] = 'Rozbalovací seznam';
$_lang['earliest_date'] = 'Nejstarší možné datum';
$_lang['earliest_date_desc'] = 'Nejstarší datum, který může být zvoleno.';
$_lang['earliest_time'] = 'Nejstarší možný čas';
$_lang['earliest_time_desc'] = 'Nejstarší čas, který může být zvolen.';
$_lang['email'] = 'E-mail';
$_lang['file'] = 'Soubor';
$_lang['height'] = 'Výška';
$_lang['hidden'] = 'Skryté';
$_lang['htmlarea'] = 'HTML Area';
$_lang['htmltag'] = 'HTML tag';
$_lang['image'] = 'Obrázek';
$_lang['image_align'] = 'Zarovnat';
$_lang['image_align_list'] = 'none,baseline,top,middle,bottom,texttop,absmiddle,absbottom,left,right';
$_lang['image_alt'] = 'Alternativní text';
$_lang['image_border_size'] = 'Šířka ohraničení';
$_lang['image_hspace'] = 'H mezera';
$_lang['image_vspace'] = 'V mezera';
$_lang['latest_date'] = 'Nejnovější možné datum';
$_lang['latest_date_desc'] = 'Nejnovější datum, který může být zvoleno.';
$_lang['latest_time'] = 'Nejnovější možný čas';
$_lang['latest_time_desc'] = 'Nejnovější čas, který může být zvolen..';
$_lang['listbox'] = 'Seznam (jeden vybraný)';
$_lang['listbox-multiple'] = 'Seznam (více vybraných)';
$_lang['list-multiple-legacy'] = 'Seznam s více možnostmi';
$_lang['lower_case'] = 'Malá písmena';
$_lang['max_length'] = 'Max. délka';
$_lang['min_length'] = 'Min. délka';
$_lang['name'] = 'Název';
$_lang['number'] = 'Číslo';
$_lang['number_allowdecimals'] = 'Povolit desetinná čísla';
$_lang['number_allownegative'] = 'Povolit zápornou hodnotu';
$_lang['number_decimalprecision'] = 'Počet desetinných míst';
$_lang['number_decimalprecision_desc'] = 'Počet desetinných míst, které chcete zobrazit (výchozí hodnota je 2).';
$_lang['number_decimalseparator'] = 'Oddělovač desetinných míst';
$_lang['number_decimalseparator_desc'] = 'Znak(y), který chcete použít pro oddělení desetinné hodnoty (výchozí hodnota je ".")';
$_lang['number_maxvalue'] = 'Max. hodnota';
$_lang['number_minvalue'] = 'Min. hodnota';
$_lang['option'] = 'Přepínače';
$_lang['parent_resources'] = 'Nadřazený dokument';
$_lang['radio_columns'] = 'Sloupce';
$_lang['radio_columns_desc'] = 'Počet sloupců, vce kterých jsou zobrazeny přepínače.';
$_lang['rawtext'] = 'Surový text (zastaralé)';
$_lang['rawtextarea'] = 'Surové textové pole (zastaralé)';
$_lang['required'] = 'Povolit prázdné';
$_lang['required_desc'] = 'Je-li nastaveno na Ne, MODX nedovolí uživateli uložit dokument dokud nezadá platnou nenulovou hodnotu pro tuto template variable.';
$_lang['resourcelist'] = 'Seznam dokumentů';
$_lang['resourcelist_depth'] = 'Hloubka';
$_lang['resourcelist_depth_desc'] = 'Počet úrovní, které mají být zobrazeny v seznamu dokumentů. Výchozí hodnota je 10.';
$_lang['resourcelist_includeparent'] = 'Zobrazit rodiče';
$_lang['resourcelist_includeparent_desc'] = 'Je-li nastaveno na Ano, budou v seznamu zobrazeny také dokumenty uvedené v nastavení Rodiče.';
$_lang['resourcelist_limitrelatedcontext'] = 'Omezit na související kontexty';
$_lang['resourcelist_limitrelatedcontext_desc'] = 'Je-li nastaveno Ano, budou zahrnuty pouze dokumenty související s kontextem aktuálního dokumentu.';
$_lang['resourcelist_limit'] = 'Limit';
$_lang['resourcelist_limit_desc'] = 'Počet dokumentů, který má být maximálně zobrazen. 0 nebo prázdné pole znamená neomezeně.';
$_lang['resourcelist_parents'] = 'Rodiče';
$_lang['resourcelist_parents_desc'] = 'Seznam ID dokumentů, ze kterých chcete v seznamu zobrazit dokumenty.';
$_lang['resourcelist_where'] = 'Podmínka WHERE';
$_lang['resourcelist_where_desc'] = 'JSON objekt podmínky WHERE pro vyfiltrování záznamů pro seznam dokumentů. (Nepodporuje prohledávání TV.)';
$_lang['richtext'] = 'WYSIWYG';
$_lang['sentence_case'] = 'Věta';
$_lang['shownone'] = 'Povolit prázdnou položku';
$_lang['shownone_desc'] = 'Umožní uživateli vybrat prázdnou položku jejíž hodnota je také prázdná.';
$_lang['start_day'] = 'První den týdne';
$_lang['start_day_desc'] = 'Index dne, kterým chcete, aby začínal týden. Počítáno od nuly, 0 = neděle, 1 = pondělí.';
$_lang['string'] = 'Řetězec';
$_lang['string_format'] = 'Formát řetězce';
$_lang['style'] = 'Styl';
$_lang['tag_id'] = 'ID tagu';
$_lang['tag_name'] = 'Název tagu';
$_lang['target'] = 'Cíl';
$_lang['text'] = 'Text';
$_lang['textarea'] = 'Textové pole';
$_lang['textareamini'] = 'Textové pole (malé)';
$_lang['textbox'] = 'Textové pole';
$_lang['time_increment'] = 'Přírustek času';
$_lang['time_increment_desc'] = 'Počet minut mezi jednotlivými časovými údaji v seznamu (výchozí hodnota je 15).';
$_lang['title'] = 'Název';
$_lang['upper_case'] = 'Velká písmena';
$_lang['url'] = 'URL';
$_lang['url_display_text'] = 'Zobrazený text';
$_lang['width'] = 'Šířka';
|
gpl-2.0
|
gp6shc/SSK
|
wp-content/plugins/responsive-and-swipe-slider/shortcode.php
|
3816
|
<?php
function rsSlider_shortcode($atts) {
extract(shortcode_atts(array(
'id' => 0,
'title' => false,
'text' => false,
'size' => 'full'
), $atts));
// if Post ID isn't set
if($atts['id'] == 0) return '<strong>Please set the post id in short code eg. [rsSlider id="27"].</strong>';
$postid = $atts['id'];
// JAVASCRIPT
$out = "
<script type='text/javascript'>
jQuery(document).ready(function($){
$('.flexslider').flexslider({
animation: 'slide',
slideshowSpeed: 4500,
start: function(slider){
$('#containerFlexDiv').height('auto');
$('.loading_rsSlider').hide();
}
});
";
// End Javascript
$out .= "
});
</script>
";
$metaSliders = get_post_meta($postid, 'rsSlider_repeatable', true);
$meta_thumbnail = get_post_meta($postid, 'meta_box_select_rsthumb', true);
$meta_display = get_post_meta($postid, 'meta_box_check_text', true);
$meta_display_title = get_post_meta($postid, 'meta_box_check_title', true);
$att_size = '';
if(isset($meta_thumbnail))
$att_size = $meta_thumbnail;
else
$att_size = 'full';
$image_size = get_thumb_image_width( $att_size );
if ( !empty( $image_size ) ) {
$width = $image_size['width'];
$height = $image_size['height'];
}
$hide = false;
if(isset($meta_display) && $meta_display == 'on')
$hide = true;
$hide_title = false;
if(isset($meta_display_title) && $meta_display_title == 'on')
$hide_title = true;
//echo $att_size.' width='.$width.' height='.$height;
$custom_style = '';
if($width > 100 && $height > 100)
$custom_style = 'style="height:'.($height+100).'px ; max-width:'.$width.'px"';
if($hide_title == false):
$out .= '<div class="rsTitle"><h3>'.get_the_title($postid).'</h3></div>';
endif;
// slide start
$out .= '
<div id="containerFlexDiv" class="cf" '.$custom_style.'>
<div class="loading_rsSlider"></div>
<section class="slider">
<div class="flexslider">
<ul class="slides">';
if ($metaSliders) {
foreach($metaSliders as $row) {
$exp_data = explode("::::", $row);
$attachment_id = $exp_data[2];
$this_img = wp_get_attachment_image_src( $attachment_id , $att_size );
$imgSrc = $this_img[0];
$title = $exp_data[0];
$description = $exp_data[1];
$href = $exp_data[3];
#echo nl2br($exp_data[1]);
$out .= '<li>';
$out .= '<a href="'.$href.'" ><div class="rsSliderWrap">';
$out .= '<img src='.$imgSrc.' alt="'.$title.'" />';
if($hide == false):
$out .= '<div class="rsSliderContent">';
//$out .= '<div><a href="'.$href.'" >'.$title.'</a></div>';
$out .= '<div>'.$description.'</div>';
$out .= '</div></a>';
endif;
$out .= '</div>';
$out .= '</li>';
}
}
// slide end
$out .= '
</ul>
</div>
</section>
</div>';
return $out;
}
add_shortcode('rsSlider', 'rsSlider_shortcode');
function get_thumb_image_width( $name ) {
global $_wp_additional_image_sizes;
if($name == 'thumbnail'){
$return_dimensions['width'] = get_option( 'thumbnail_size_w');
$return_dimensions['height'] = get_option( 'thumbnail_size_h');
return $return_dimensions;
}
elseif($name == 'medium'){
$return_dimensions['width'] = get_option( 'medium_size_w');
$return_dimensions['height'] = get_option( 'medium_size_h');
return $return_dimensions;
}
elseif($name == 'large'){
$return_dimensions['width'] = get_option( 'large_size_w');
$return_dimensions['height'] = get_option( 'large_size_h');
return $return_dimensions;
}
elseif ( isset( $_wp_additional_image_sizes[$name] ) ){
return $_wp_additional_image_sizes[$name];
}
return false;
}
|
gpl-2.0
|
micke2k/cacti
|
lib/reports.php
|
50005
|
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2016 The Cacti Group |
| |
| 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. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDTool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
/** duplicate_reports duplicates a report and all items
* @param int $_id - id of the report
* @param string $_title - title of the new report
*/
function duplicate_reports($_id, $_title) {
global $fields_reports_edit, $current_user;
reports_log(__FUNCTION__ . ', id: ' . $_id, false, 'REPORTS TRACE', POLLER_VERBOSITY_MEDIUM);
$report = db_fetch_row_prepared('SELECT * FROM reports WHERE id = ?', array($_id));
$reports_items = db_fetch_assoc_prepared('SELECT * FROM reports_items WHERE report_id = ?', array($_id));
$save = array();
reset($fields_reports_edit);
while (list($field, $array) = each($fields_reports_edit)) {
if (!preg_match('/^hidden/', $array['method']) &&
!preg_match('/^spacer/', $array['method'])) {
$save[$field] = $report[$field];
}
}
/* duplicate to your id */
$save['user_id'] = $_SESSION['sess_user_id'];
/* substitute the title variable */
$save['name'] = str_replace('<name>', $report['name'], $_title);
/* create new rule */
$save['enabled'] = '';
$save['id'] = 0;
$reports_id = sql_save($save, 'reports');
/* create new rule items */
if (sizeof($reports_items) > 0) {
foreach ($reports_items as $reports_item) {
$save = $reports_item;
$save['id'] = 0;
$save['report_id'] = $reports_id;
$reports_item_id = sql_save($save, 'reports_items');
}
}
}
/** reports_date_time_format fetches the date/time formatting information for current user
* @return string - string defining the datetime format specific to this user
*/
function reports_date_time_format() {
global $config;
$graph_date = '';
/* setup date format */
$date_fmt = read_user_setting('default_date_format');
$datechar = read_user_setting('default_datechar');
switch ($datechar) {
case GDC_HYPHEN: $datechar = '-'; break;
case GDC_SLASH: $datechar = '/'; break;
case GDC_DOT: $datechar = '.'; break;
}
switch ($date_fmt) {
case GD_MO_D_Y:
$graph_date = 'm' . $datechar . 'd' . $datechar . 'Y H:i:s';
break;
case GD_MN_D_Y:
$graph_date = 'M' . $datechar . 'd' . $datechar . 'Y H:i:s';
break;
case GD_D_MO_Y:
$graph_date = 'd' . $datechar . 'm' . $datechar . 'Y H:i:s';
break;
case GD_D_MN_Y:
$graph_date = 'd' . $datechar . 'M' . $datechar . 'Y H:i:s';
break;
case GD_Y_MO_D:
$graph_date = 'Y' . $datechar . 'm' . $datechar . 'd H:i:s';
break;
case GD_Y_MN_D:
$graph_date = 'Y' . $datechar . 'M' . $datechar . 'd H:i:s';
break;
}
reports_log(__FUNCTION__ . ', datefmt: ' . $graph_date, false, 'REPORTS TRACE', POLLER_VERBOSITY_MEDIUM);
return $graph_date;
}
/** reports_interval_start computes the next start time for the given set of parameters
* @param int $interval - given interval
* @param int $count - given repeat count
* @param int $offset - offset in seconds to be added to the new start time
* @param int $timestamp - current start time for report
* @return - new timestamp
*/
function reports_interval_start($interval, $count, $offset, $timestamp) {
global $reports_interval;
reports_log(__FUNCTION__ . ', interval: ' . $reports_interval[$interval] . ' count: ' . $count . ' offset: ' . $offset . ' timestamp: ' . date('Y/m/d H:i:s', $timestamp), false, 'REPORTS TRACE', POLLER_VERBOSITY_MEDIUM);
switch ($interval) {
case REPORTS_SCHED_INTVL_MINUTE:
# add $count minutes to current mailtime
$ts = utime_add($timestamp,0,0,0,0,$count,$offset);
break;
case REPORTS_SCHED_INTVL_HOUR:
# add $count hours to current mailtime
$ts = utime_add($timestamp,0,0,0,$count,0,$offset);
break;
case REPORTS_SCHED_INTVL_DAY:
# add $count days to current mailtime
$ts = utime_add($timestamp,0,0,$count,0,0,$offset);
break;
case REPORTS_SCHED_INTVL_WEEK:
# add $count weeks = 7*$count days to current mailtime
$ts = utime_add($timestamp,0,0,7*$count,0,0,$offset);
break;
case REPORTS_SCHED_INTVL_MONTH_DAY:
# add $count months to current mailtime
$ts = utime_add($timestamp,0,$count,0,0,0,$offset);
break;
case REPORTS_SCHED_INTVL_MONTH_WEEKDAY:
# add $count months to current mailtime, but if this is the nth weekday, it must be the same nth weekday in the new month
# e.g. if this is currently the 3rd Monday of current month
# ist must be the 3rd Monday of the new month as well
$weekday = date('l', $timestamp);
$day_of_month = date('j', $timestamp);
$nth_weekday = ceil($day_of_month/7);
$date_str = '+' . $count . ' months';
$month_base = strtotime($date_str, $timestamp);
$new_month = mktime(date('H', $month_base), date('i', $month_base), date('s', $month_base), date('m', $month_base), 1, date('Y', $month_base));
$date_str = '+' . ($nth_weekday -1) . ' week ' . $weekday;
$base = strtotime($date_str, $new_month);
$ts = mktime(date('H', $month_base), date('i', $month_base), date('s', $month_base), date('m', $base), date('d', $base), date('Y', $base));
break;
case REPORTS_SCHED_INTVL_YEAR:
# add $count years to current mailtime
$ts = utime_add($timestamp,$count,0,0,0,0,$offset);
break;
default:
$ts = 0;
break;
}
$now = time();
if ($ts < $now) {
$ts = reports_interval_start($interval, $count, $offset, $now);
}
return $ts;
}
/** utime_add add offsets to given timestamp
* @param int $timestamp- base timestamp
* @param int $yr - offset in years
* @param int $mon - offset in months
* @param int $day - offset in days
* @param int $hr - offset in hours
* @param int $min - offset in minutes
* @param int $sec - offset in seconds
* @return - unix time
*/
function utime_add($timestamp, $yr=0, $mon=0, $day=0, $hr=0, $min=0, $sec=0) {
$dt = localtime($timestamp, true);
$unixnewtime = mktime(
$dt['tm_hour']+$hr, $dt['tm_min']+$min, $dt['tm_sec']+$sec,
$dt['tm_mon']+1+$mon, $dt['tm_mday']+$day, $dt['tm_year']+1900+$yr);
return $unixnewtime;
}
/** reports_log - logs a string to Cacti's log file or optionally to the browser
@param string $string - the string to append to the log file
@param bool $output - whether to output the log line to the browser using pring() or not
@param string $environ - tell's from where the script was called from */
function reports_log($string, $output = false, $environ='REPORTS', $level=POLLER_VERBOSITY_NONE) {
# if current verbosity >= level of current message, print it
if (strstr($string, 'STATS')) {
cacti_log($string, $output, 'SYSTEM');
} elseif (REPORTS_DEBUG >= $level) {
cacti_log($string, $output, $environ);
}
}
/** generate_report create the complete mail for a single report and send it
* @param array $report - complete row of reports table for the report to work upon
* @param bool $force - when forced, lastsent time will not be entered (e.g. Send Now)
*/
function generate_report($report, $force = false) {
global $config, $alignment;
include_once($config['base_path'] . '/lib/time.php');
include_once($config['base_path'] . '/lib/rrd.php');
reports_log(__FUNCTION__ . ', report_id: ' . $report['id'], false, 'REPORTS TRACE', POLLER_VERBOSITY_MEDIUM);
$theme = 'classic';
$body = reports_generate_html($report['id'], REPORTS_OUTPUT_EMAIL, $theme);
$time = time();
# get config option for first-day-of-the-week
$first_weekdayid = read_user_setting('first_weekdayid');
$offset = 0;
$graphids = array();
$attachments = array();
while ( true ) {
$pos = strpos($body, '<GRAPH:', $offset);
if ($pos) {
$offset = $pos+7;
$graph = substr($body, $pos+7, 10);
$arr = explode(':', $graph);
$arr1 = explode('>', $arr[1]);
$graphid = $arr[0];
$timespan = $arr1[0];
$graphids[$graphid . ':' . $timespan] = $graphid;
} else {
break;
}
}
$user = $report['user_id'];
$xport_meta = array();
if (sizeof($graphids)) {
foreach($graphids as $key => $graphid) {
$arr = explode(':', $key);
$timesp = $arr[1];
$timespan = array();
# get start/end time-since-epoch for actual time (now()) and given current-session-timespan
get_timespan($timespan, $time, $timesp, $first_weekdayid);
# provide parameters for rrdtool graph
$graph_data_array = array(
'graph_start' => $timespan['begin_now'],
'graph_end' => $timespan['end_now'],
'graph_width' => $report['graph_width'],
'graph_height' => $report['graph_height'],
'image_format' => 'png',
'graph_theme' => $theme,
'output_flag' => RRDTOOL_OUTPUT_STDOUT,
'disable_cache' => true
);
if ($report['thumbnails'] == 'on') {
$graph_data_array['graph_nolegend'] = true;
}
switch($report['attachment_type']) {
case REPORTS_TYPE_INLINE_PNG:
$attachments[] = array(
'attachment' => @rrdtool_function_graph($graphid, '', $graph_data_array, '', $xport_meta, $user),
'filename' => 'graph_' . $graphid . '.png',
'mime_type' => 'image/png',
'graphid' => $graphid,
'timespan' => $timesp,
'inline' => 'inline'
);
break;
case REPORTS_TYPE_INLINE_JPG:
$attachments[] = array(
'attachment' => png2jpeg(@rrdtool_function_graph($graphid, '', $graph_data_array, '', $xport_meta, $user)),
'filename' => 'graph_' . $graphid . '.jpg',
'mime_type' => 'image/jpg',
'graphid' => $graphid,
'timespan' => $timesp,
'inline' => 'inline'
);
break;
case REPORTS_TYPE_INLINE_GIF:
$attachments[] = array(
'attachment' => png2gif(@rrdtool_function_graph($graphid, '', $graph_data_array, '', $xport_meta, $user)),
'filename' => 'graph_' . $graphid . '.gif',
'mime_type' => 'image/gif',
'graphid' => $graphid,
'timespan' => $timesp,
'inline' => 'inline'
);
break;
case REPORTS_TYPE_ATTACH_PNG:
$attachments[] = array(
'attachment' => @rrdtool_function_graph($graphid, '', $graph_data_array, '', $xport_meta, $user),
'filename' => 'graph_' . $graphid . '.png',
'mime_type' => 'image/png',
'graphid' => $graphid,
'timespan' => $timesp,
'inline' => 'attachment'
);
break;
case REPORTS_TYPE_ATTACH_JPG:
$attachments[] = array(
'attachment' => png2jpeg(@rrdtool_function_graph($graphid, '', $graph_data_array, '', $xport_meta, $user)),
'filename' => 'graph_' . $graphid . '.jpg',
'mime_type' => 'image/jpg',
'graphid' => $graphid,
'timespan' => $timesp,
'inline' => 'attachment'
);
break;
case REPORTS_TYPE_ATTACH_GIF:
$attachments[] = array(
'attachment' => png2gif(@rrdtool_function_graph($graphid, '', $graph_data_array, '', $xport_meta, $user)),
'filename' => 'graph_' . $graphid . '.gif',
'mime_type' => 'image/gif',
'graphid' => $graphid,
'timespan' => $timesp,
'inline' => 'attachment'
);
break;
case REPORTS_TYPE_INLINE_PNG_LN:
$attachments[] = array(
'attachment' => @rrdtool_function_graph($graphid, '', $graph_data_array, '', $xport_meta, $user),
'filename' => '', # LN does not accept filenames for inline attachments
'mime_type' => 'image/png',
'graphid' => $graphid,
'timespan' => $timesp,
'inline' => 'inline'
);
break;
case REPORTS_TYPE_INLINE_JPG_LN:
$attachments[] = array(
'attachment' => png2jpeg(@rrdtool_function_graph($graphid, '', $graph_data_array, '', $xport_meta, $user)),
'filename' => '', # LN does not accept filenames for inline attachments
'mime_type' => 'image/jpg',
'graphid' => $graphid,
'timespan' => $timesp,
'inline' => 'inline'
);
break;
case REPORTS_TYPE_INLINE_GIF_LN:
$attachments[] = array(
'attachment' => png2gif(@rrdtool_function_graph($graphid, '', $graph_data_array, '', $xport_meta, $user)),
'filename' => '', # LN does not accept filenames for inline attachments
'mime_type' => 'image/gif',
'graphid' => $graphid,
'timespan' => $timesp,
'inline' => 'inline'
);
break;
case REPORTS_TYPE_ATTACH_PDF:
# $attachments[] = array(
# 'attachment' => png2gif(@rrdtool_function_graph($graphid, '', $graph_data_array, '', $xport_meta, $user)),
# 'filename' => 'graph_' . $graphid . '.gif',
# 'mime_type' => 'image/gif',
# 'graphid' => $graphid,
# 'timespan' => $timesp,
# 'inline' => 'attachment'
# );
break;
}
}
}
if ($report['subject'] != '') {
$subject = $report['subject'];
} else {
$subject = $report['name'];
}
if(!isset($report['bcc'])) {
$report['bcc'] = '';
}
$v = db_fetch_cell('SELECT cacti FROM version');
$headers['User-Agent'] = 'Cacti-Reports-v' . $v;
$error = mailer(
array($report['from_email'], $report['from_name']),
$report['email'],
'',
$report['bcc'],
'',
$subject,
$body,
'Cacti Reporting Requires and HTML Email Client',
$attachments,
$headers
);
session_start();
if (strlen($error)) {
if (isset_request_var('id')) {
$_SESSION['reports_error'] = "Problems sending Report '" . $report['name'] . "'. Problem with e-mail Subsystem Error is '$error'";
if (!isset_request_var('selected_items')) {
raise_message('reports_error');
}
} else {
reports_log(__FUNCTION__ . ", Problems sending Report '" . $report['name'] . "'. Problem with e-mail Subsystem Error is '$error'", false, 'REPORTS', POLLER_VERBOSITY_LOW);
}
} elseif (isset($_REQUEST)) {
$_SESSION['reports_message'] = "Report '" . $report['name'] . "' Sent Successfully";
if (!isset_request_var('selected_items')) {
raise_message('reports_message');
}
}
if (!isset_request_var('id') && !$force) {
$int = read_config_option('poller_interval');
if ($int == '') $int = 300;
$next = reports_interval_start($report['intrvl'], $report['count'], $report['offset'], $report['mailtime']);
$next = floor($next / $int) * $int;
$sql = "UPDATE reports SET mailtime=$next, lastsent=" . time() . " WHERE id = " . $report['id'];
reports_log(__FUNCTION__ . ', update sql: ' . $sql, false, 'REPORTS TRACE', POLLER_VERBOSITY_MEDIUM);
db_execute($sql);
}
}
/** reports_load_format_file read the format file from disk and determines it's formating
* @param string $format_file - the file to read from the formats directory
* @param string $output - the html and css output from that file
* @param bool $report_tag_included - a boolean that informs the caller if the report tag is present
* @return bool - wether or not the format file was processed correctly
*/
function reports_load_format_file($format_file, &$output, &$report_tag_included, &$theme) {
global $config;
$contents = array();
if (file_exists($config['base_path'] . '/formats/' . $format_file)) {
$contents = file($config['base_path'] . '/formats/' . $format_file);
}
$output = '';
$report_tag_included = false;
if (sizeof($contents)) {
foreach($contents as $line) {
$line = trim($line);
if (substr_count($line, '<REPORT>')) {
$report_tag_included = true;
}
if (substr($line, 0, 1) != '#') {
$output .= $line . "\n";
}elseif (strstr($line, 'Theme:') !== false) {
$tparts = explode(':', $line);
$theme = trim($tparts[1]);
}
}
} else {
return false;
}
return true;
}
/**
* determine, if the given tree has graphs; taking permissions into account
* @param int $tree_id - tree id
* @param int $branch_id - branch id
* @param int $effective_user - user id
* @param string $search_key - search key
*/
function reports_tree_has_graphs($tree_id, $branch_id, $effective_user, $search_key) {
global $config;
include_once($config['library_path'] . '/html_tree.php');
$sql_where = '';
$sql_swhere = '';
$graphs = array();
$new_graphs = array();
if (strlen($search_key)) {
$sql_swhere = " AND gtg.title_cache REGEXP '" . $search_key . "'";
}
if ($branch_id>0) {
$sql_where .= ' AND gti.parent=' . $branch_id;
} else {
$sql_where .= ' AND parent=0';
}
$graphs = array_rekey(db_fetch_assoc("SELECT gl.id
FROM graph_local AS gl
INNER JOIN graph_tree_items AS gti
ON gti.local_graph_id=gl.id
INNER JOIN graph_templates_graph AS gtg
ON gtg.local_graph_id=gti.local_graph_id
WHERE gti.local_graph_id>0
AND graph_tree_id=$tree_id
$sql_where
$sql_swhere"), 'id', 'id');
/* get host graphs first */
$graphs = array_merge($graphs, array_rekey(db_fetch_assoc("SELECT gl.id
FROM graph_local AS gl
INNER JOIN graph_tree_items AS gti
ON gl.host_id=gti.host_id
INNER JOIN graph_templates_graph AS gtg
ON gtg.local_graph_id=gl.id
WHERE gti.graph_tree_id=$tree_id
AND gti.host_id>0
$sql_where
$sql_swhere"), 'id', 'id'));
/* verify permissions */
if (sizeof($graphs)) {
foreach($graphs as $key => $id) {
if (!is_graph_allowed($id, $effective_user)) {
unset($graphs[$key]);
}
}
}
return sizeof($graphs);
}
/** reports_generate_html print report to html for online verification
* @param int $reports_id - id of report report
* @param int $output - type of output
* @return string - generated html output
*/
function reports_generate_html ($reports_id, $output = REPORTS_OUTPUT_STDOUT, &$theme = '') {
global $config, $colors;
global $alignment;
include_once($config['base_path'] . '/lib/time.php');
$outstr = '';
$report = db_fetch_row_prepared('SELECT * FROM reports WHERE id = ?', array($reports_id));
$reports_items = db_fetch_assoc_prepared('SELECT * FROM reports_items WHERE report_id = ? ORDER BY sequence', array($report['id']));
$format_data = '';
$report_tag = false;
$format_ok = false;
if ($theme == '') {
$theme = 'classic';
}
$time = time();
# get config option for first-day-of-the-week
$first_weekdayid = read_user_setting('first_weekdayid');
/* process the format file as applicable */
if ($report['cformat'] == 'on') {
$format_ok = reports_load_format_file($report['format_file'], $format_data, $report_tag, $theme);
}
if ($output == REPORTS_OUTPUT_STDOUT) {
$format_data = str_replace('<html>', '', $format_data);
$format_data = str_replace('</html>', '', $format_data);
$format_data = str_replace('<body>', '', $format_data);
$format_data = str_replace('</body>', '', $format_data);
$format_data = preg_replace('#(<head>).*?(</head>)#si', '', $format_data);
$format_data = str_replace('<head>', '', $format_data);
$format_data = str_replace('</head>', '', $format_data);
}
if ($format_ok && $report_tag) {
$include_body = false;
} else {
$include_body = true;
}
reports_log(__FUNCTION__ . ', items found: ' . sizeof($reports_items), false, 'REPORTS TRACE', POLLER_VERBOSITY_MEDIUM);
if (sizeof($reports_items)) {
if ($output == REPORTS_OUTPUT_EMAIL && $include_body) {
$outstr .= "<body>\n";
}
if ($format_ok) {
$outstr .= "\t<table class='report_table'>\n";
} else {
$outstr .= "\t<table class='report_table' " . ($output == REPORTS_OUTPUT_STDOUT ? "style='background-color:#F9F9F9;'":'') . ">\n";
}
$outstr .= "\t\t<tr class='title_row'>\n";
if ($format_ok) {
$outstr .= "\t\t\t<td class='title' style='text-align:" . $alignment[$report['alignment']] . ";'>\n";
} else {
$outstr .= "\t\t\t<td class='title' style='text-align:" . $alignment[$report['alignment']] . ";font-size:" . $report['font_size'] . "pt;'>\n";
}
$outstr .= "\t\t\t\t" . $report['name'] . "\n";
$outstr .= "\t\t\t</td>\n";
$outstr .= "\t\t</tr>\n";
# this function should be called only at the appropriate targeted time when in batch mode
# but for preview mode we can't use the targeted time
# so let's use time()
$time = time();
# get config option for first-day-of-the-week
$first_weekdayid = read_user_setting('first_weekdayid');
/* don't cache previews */
$_SESSION['custom'] = 'true';
$column = 0;
foreach($reports_items as $item) {
reports_log(__FUNCTION__ . ', item_id: ' . $item['id'] . ' local_graph_id: ' . $item['local_graph_id'], false, 'REPORTS TRACE', POLLER_VERBOSITY_MEDIUM);
if ($item['item_type'] == REPORTS_ITEM_GRAPH) {
$timespan = array();
# get start/end time-since-epoch for actual time (now()) and given current-session-timespan
get_timespan($timespan, $time, $item['timespan'], $first_weekdayid);
if ($column == 0) {
$outstr .= "\t\t<tr class='image_row'>\n";
$outstr .= "\t\t\t<td style='text-align:" . $alignment{$item['align']} . ";'>\n";
if ($format_ok) {
$outstr .= "\t\t\t\t<table class='image_table'>\n";
} else {
$outstr .= "\t\t\t\t<table>\n";
}
$outstr .= "\t\t\t\t\t<tr>\n";
}
if ($format_ok) {
$outstr .= "\t\t\t\t\t\t<td class='image_column' style='text-align:" . $alignment[$item['align']] . ";'>\n";
} else {
$outstr .= "\t\t\t\t\t\t<td style='padding:5px;text-align:" . $alignment[$item['align']] . ";'>\n";
}
$outstr .= "\t\t\t\t\t\t\t" . reports_graph_image($report, $item, $timespan, $output, $theme) . "\n";
$outstr .= "\t\t\t\t\t\t</td>\n";
if ($report['graph_columns'] > 1) {
$column = ($column + 1) % ($report['graph_columns']);
}
if ($column == 0) {
$outstr .= "\t\t\t\t\t</tr>\n";
$outstr .= "\t\t\t\t</table>\n";
$outstr .= "\t\t\t</td>\n";
$outstr .= "\t\t</tr>\n";
}
} elseif ($item['item_type'] == REPORTS_ITEM_TEXT) {
$outstr .= "\t\t<tr class='text_row'>\n";
if ($format_ok) {
$outstr .= "\t\t\t<td style='text-align:" . $alignment[$item['align']] . ";' class='text'>\n";
} else {
$outstr .= "\t\t\t<td style='text-align:" . $alignment[$item['align']] . ";font-size: " . $item['font_size'] . "pt;' class='text'>\n";
}
$outstr .= "\t\t\t\t" . $item['item_text'] . "\n";
$outstr .= "\t\t\t</td>\n";
$outstr .= "\t\t</tr>\n";
/* start a new section */
$column = 0;
} elseif ($item['item_type'] == REPORTS_ITEM_TREE) {
if ($item['tree_cascade'] == 'on') {
$outstr .= expand_branch($report, $item, $item['branch_id'], $output, $format_ok, $theme);
} elseif (reports_tree_has_graphs($item['tree_id'], $item['branch_id'], $report['user_id'], $item['graph_name_regexp'])) {
$outstr .= reports_expand_tree($report, $item, $item['branch_id'], $output, $format_ok, $theme, false);
}
} else {
$outstr .= '<tr><td><br><hr><br></td></tr>';
}
}
$outstr .= "\t</table>\n";
if ($output == REPORTS_OUTPUT_EMAIL && $include_body) {
$outstr .= '</body>';
}
}
if ($format_ok) {
if ($report_tag) {
return str_replace('<REPORT>', $outstr, $format_data);
} else {
return $format_data . "\n" . $outstr;
}
} else {
return $outstr;
}
}
function expand_branch(&$report, &$item, $branch_id, $output, $format_ok, $theme = 'classic') {
$outstr = '';
if (reports_tree_has_graphs($item['tree_id'], $branch_id, $report['user_id'], $item['graph_name_regexp'])) {
$outstr .= reports_expand_tree($report, $item, $branch_id, $output, $format_ok, $theme, true);
}
$tree_branches = db_fetch_assoc_prepared('SELECT id
FROM graph_tree_items
WHERE parent = ?
AND host_id = 0 AND local_graph_id = 0
AND graph_tree_id = ?
ORDER BY position', array($branch_id, $item['tree_id']));
if (sizeof($tree_branches)) {
foreach ($tree_branches as $branch) {
$outstr .= expand_branch($report, $item, $branch['id'], $output, $format_ok, $theme);
}
}
return $outstr;
}
/**
* return html code for an embetted image
* @param array $report - parameters for this report mail report
* @param $item - current graph item
* @param $timespan - timespan
* @param $output - type of output
* @return string - generated html
*/
function reports_graph_image($report, $item, $timespan, $output, $theme = 'classic') {
global $config;
$out = '';
if ($output == REPORTS_OUTPUT_STDOUT) {
$out = "<img class='image' alt='' src='" . htmlspecialchars($config['url_path'] . 'graph_image.php' .
'?graph_width=' . $report['graph_width'] .
'&graph_height=' . $report['graph_height'] .
'&graph_nolegend=' . ($report['thumbnails'] == 'on' ? 'true':'') .
'&local_graph_id=' . $item['local_graph_id'] .
'&graph_start=' . $timespan['begin_now'] .
'&graph_end=' . $timespan['end_now'] .
'&graph_theme=' . $theme .
'&image_format=png' .
'&rra_id=0') . "'>";
} else {
$out = '<GRAPH:' . $item['local_graph_id'] . ':' . $item['timespan'] . '>';
}
if ($report['graph_linked'] == 'on' ) {
$out = "<a href='" . htmlspecialchars(read_config_option('base_url') . $config['url_path'] . 'graph.php?action=view&local_graph_id='.$item['local_graph_id']."&rra_id=0") . "'>" . $out . '</a>';
}
return $out . "\n";
}
/**
* expand a tree for including into report
* @param array $report - parameters for this report mail report
* @param int $item - current graph item
* @param int $output - type of output
* @param bool $format_ok - use css styling
* @param bool $nested - nested tree?
* @return string - html
*/
function reports_expand_tree($report, $item, $parent, $output, $format_ok, $theme = 'classic', $nested = false) {
global $colors, $config, $alignment;
include($config['include_path'] . '/global_arrays.php');
include_once($config['library_path'] . '/data_query.php');
include_once($config['library_path'] . '/html_tree.php');
include_once($config['library_path'] . '/html_utility.php');
$tree_id = $item['tree_id'];
$leaf_id = $item['branch_id'];
$time = time();
# get config option for first-day-of-the-week
$first_weekdayid = read_user_setting('first_weekdayid');
/* check if we have enough data */
if (isset($_SESSION['sess_current_user'])) {
$user = db_fetch_cell_prepared('SELECT id FROM user_auth WHERE id = ?', array($_SESSION['sess_user_id']));
} else {
$user = db_fetch_cell_prepared('SELECT id FROM user_auth WHERE id = ?', array($report['user_id']));
}
$timespan = array();
# get start/end time-since-epoch for actual time (now()) and given current-session-timespan
get_timespan($timespan, $time, $item['timespan'], $first_weekdayid);
if (empty($tree_id)) {
return;
}
$outstr = '';
$leaves = db_fetch_assoc_prepared("SELECT * FROM graph_tree_items WHERE parent = ?", array($parent));
if (sizeof($leaves)) {
foreach ($leaves as $leaf) {
$sql_where = '';
$title = '';
$title_delimeter = '';
$search_key = '';
$host_name = '';
$graph_name = '';
$leaf_id = $leaf['id'];
if (!empty($leaf_id)) {
if ($leaf['local_graph_id'] == 0 && $leaf['host_id'] == 0) {
$leaf_type = 'header';
} elseif ($leaf['host_id'] > 0) {
$leaf_type = 'host';
} else {
$leaf_type = 'graph';
}
} else {
$leaf_type = 'header';
}
/* get information for the headers */
if (!empty($tree_id)) {
$tree_name = db_fetch_cell_prepared('SELECT name FROM graph_tree WHERE id = ?', array($tree_id));
}
if (!empty($parent)) {
$leaf_name = db_fetch_cell_prepared('SELECT title FROM graph_tree_items WHERE id = ?', array($parent));
}
if (!empty($leaf_id)) {
$host_name = db_fetch_cell_prepared('SELECT h.description
FROM graph_tree_items AS gti
INNER JOIN host AS h
ON h.id = gti.host_id
WHERE gti.id = ?', array($leaf_id));
}
if ($leaf_type == 'graph') {
$graph_name = db_fetch_cell_prepared("SELECT
gtg.title_cache AS title
FROM graph_templates_graph AS gtg
WHERE gtg.local_graph_id = ?", array($leaf['local_graph_id']));
}
//if (!empty($tree_name) && empty($leaf_name) && empty($host_name) && !$nested) {
if (!empty($tree_name) && empty($leaf_name) && empty($host_name)) {
$title = $title_delimeter . "<strong>Tree:</strong> $tree_name";
$title_delimeter = '-> ';
}
if (!empty($leaf_name)) {
$title .= $title_delimeter . "<strong>Leaf:</strong> $leaf_name";
$title_delimeter = '-> ';
}
if (!empty($host_name)) {
$title .= $title_delimeter . "<strong>Host:</strong> $host_name";
$title_delimeter = '-> ';
}
if (!empty($graph_name)) {
$title .= $title_delimeter . "<strong>Graph:</strong> $graph_name";
$title_delimeter = '-> ';
}
if (strlen($item['graph_name_regexp'])) {
$sql_where .= " AND title_cache REGEXP '" . $item['graph_name_regexp'] . "'";
}
if (($leaf_type == 'header') && $nested) {
$mygraphs = array();
$graphs = db_fetch_assoc("SELECT DISTINCT
gti.local_graph_id, gtg.title_cache
FROM graph_tree_items AS gti
INNER JOIN graph_local AS gl
ON gl.id=gti.local_graph_id
INNER JOIN graph_templates_graph AS gtg
ON gtg.local_graph_id=gl.id
WHERE gti.graph_tree_id=$tree_id
AND gti.parent=$parent
AND gti.local_graph_id>0
$sql_where
ORDER BY gti.position");
foreach($graphs as $key => $graph) {
if (is_graph_allowed($graph['local_graph_id'], $user)) {
$mygraphs[$graph['local_graph_id']] = $graph;
}
}
if (sizeof($mygraphs)) {
/* start graph display */
if (strlen($title)) {
$outstr .= "\t\t<tr class='text_row'>\n";
if ($format_ok) {
$outstr .= "\t\t\t<td class='text' style='text-align:" . $alignment[$item['align']] . "'>\n";
} else {
$outstr .= "\t\t\t<td class='text' style='text-align:" . $alignment[$item['align']] . ";font-size: " . $item['font_size'] . "pt;'>\n";
}
$outstr .= "\t\t\t\t$title\n";
$outstr .= "\t\t\t</td>\n";
$outstr .= "\t\t</tr>\n";
}
$outstr .= reports_graph_area($mygraphs, $report, $item, $timespan, $output, $format_ok, $theme);
}
} elseif ($leaf_type == 'graph') {
$gr_where = '';
if (strlen($item['graph_name_regexp'])) {
$gr_where .= " AND title_cache REGEXP '" . $item['graph_name_regexp'] . "'";
}
$graph = db_fetch_cell("SELECT count(*)
FROM graph_templates_graph
WHERE local_graph_id=" . $leaf['local_graph_id'] . $gr_where);
/* start graph display */
if ($graph > 0) {
if (strlen($title)) {
$outstr .= "\t\t<tr class='text_row'>\n";
if ($format_ok) {
$outstr .= "\t\t\t<td class='text' style='text-align:" . $alignment[$item['align']] . ";'>\n";
} else {
$outstr .= "\t\t\t<td class='text' style='text-align:" . $alignment[$item['align']] . ";font-size: " . $item['font_size'] . "pt;'>\n";
}
$outstr .= "\t\t\t\t$title\n";
$outstr .= "\t\t\t</td>\n";
$outstr .= "\t\t</tr>\n";
}
$graph_list = array(array('local_graph_id' => $leaf['local_graph_id'], 'title_cache' => $graph_name));
$outstr .= reports_graph_area($graph_list, $report, $item, $timespan, $output, $format_ok, $theme);
}
} elseif ($leaf_type == 'host' && $nested) {
/* graph template grouping */
if ($leaf['host_grouping_type'] == HOST_GROUPING_GRAPH_TEMPLATE) {
$graph_templates = array_rekey(db_fetch_assoc('SELECT DISTINCT
gt.id, gt.name
FROM graph_local AS gl
INNER JOIN graph_templates AS gt
ON gt.id=gl.graph_template_id
INNER JOIN graph_templates_graph AS gtg
ON gtg.local_graph_id=gl.id
WHERE gl.host_id=' . $leaf['host_id'] . '
ORDER BY gt.name'), 'id', 'name');
if (sizeof($graph_templates)) {
foreach($graph_templates AS $id => $name) {
if (!is_graph_template_allowed($id)) {
unset($graph_templates[$id]);
}
}
}
/* for graphs without a template */
array_push($graph_templates, array(
'id' => '0',
'name' => '(No Graph Template)'
));
$outgraphs = array();
if (sizeof($graph_templates) > 0) {
foreach ($graph_templates as $id => $name) {
$graphs = db_fetch_assoc('SELECT
gtg.local_graph_id, gtg.title_cache
FROM graph_local AS gl
INNER JOIN graph_templates_graph AS gtg
ON gtg.local_graph_id=gl.id
WHERE gl.graph_template_id=' . $id . '
AND gl.host_id=' . $leaf['host_id'] . "
$sql_where
ORDER BY gtg.title_cache");
if (sizeof($graphs)) {
foreach($graphs as $key => $graph) {
if (!is_graph_allowed($graph['local_graph_id'], $user)) {
unset($graphs[$key]);
}
}
}
$outgraphs = array_merge($outgraphs, $graphs);
}
if (sizeof($outgraphs) > 0) {
/* let's sort the graphs naturally */
usort($outgraphs, 'necturally_sort_graphs');
/* start graph display */
if (strlen($title)) {
$outstr .= "\t\t<tr class='text_row'>\n";
if ($format_ok) {
$outstr .= "\t\t\t<td class='text' style='text-align:" . $alignment[$item['align']] . "';>\n";
} else {
$outstr .= "\t\t\t<td class='text' style='text-align:" . $alignment[$item['align']] . ";font-size: " . $item['font_size'] . "pt;'>\n";
}
$outstr .= "\t\t\t\t$title\n";
$outstr .= "\t\t\t</td>\n";
$outstr .= "\t\t</tr>\n";
}
$outstr .= reports_graph_area($outgraphs, $report, $item, $timespan, $output, $format_ok, $theme);
}
}
/* data query index grouping */
} elseif ($leaf['host_grouping_type'] == HOST_GROUPING_DATA_QUERY_INDEX) {
$data_queries = db_fetch_assoc('SELECT DISTINCT
sq.id, sq.name
FROM graph_local AS gl
INNER JOIN snmp_query AS sq
ON gl.snmp_query_id=sq.id
WHERE gl.host_id=' . $leaf['host_id'] . '
ORDER BY sq.name');
/* for graphs without a data query */
if (empty($data_query_id)) {
array_push($data_queries, array(
'id' => '0',
'name' => 'Non Query Based'
));
}
$i = 0;
if (sizeof($data_queries)) {
foreach ($data_queries as $data_query) {
/* fetch a list of field names that are sorted by the preferred sort field */
$sort_field_data = get_formatted_data_query_indexes($leaf['host_id'], $data_query['id']);
/* grab a list of all graphs for this host/data query combination */
$graphs = db_fetch_assoc('SELECT
gtg.title_cache, gtg.local_graph_id, gl.snmp_index
FROM graph_local AS gl
INNER JOIN graph_templates_graph AS gtg
ON gl.id=gtg.local_graph_id
WHERE gl.snmp_query_id=' . $data_query['id'] . '
AND gl.host_id=' . $leaf['host_id'] . "
$sql_where
ORDER BY gtg.title_cache");
if (sizeof($graphs)) {
foreach($graphs as $key => $graph) {
if (!is_graph_allowed($graph['local_graph_id'], $user)) {
unset($graphs[$key]);
}
}
}
/* re-key the results on data query index */
if (sizeof($graphs)) {
if ($i == 0) {
/* start graph display */
if (strlen($title)) {
$outstr .= "\t\t<tr class='text_row'>\n";
if ($format_ok) {
$outstr .= "\t\t\t<td class='text' style='text-align:" . $alignment[$item['align']] . ";'>\n";
} else {
$outstr .= "\t\t\t<td class='text' style='text-align:" . $alignment[$item['align']] . ";font-size: " . $item['font_size'] . "pt;'>\n";
}
$outstr .= "\t\t\t\t$title\n";
$outstr .= "\t\t\t</td>\n";
$outstr .= "\t\t</tr>\n";
}
}
$i++;
$outstr .= "\t\t<tr class='text_row'>\n";
if ($format_ok) {
$outstr .= "\t\t\t<td class='text' style='text-align:" . $alignment[$item['align']] . ";'><strong>Data Query:</strong> " . $data_query['name'] . "\n";
$outstr .= "\t\t\t</td>\n";
$outstr .= "\t\t</tr>\n";
} else {
$outstr .= "\t\t\t<td class='text' style='text-align:" . $alignment[$item['align']] . ";font-size: " . $item['font_size'] . "pt;'><strong>Data Query:</strong> " . $data_query['name'] . "\n";
$outstr .= "\t\t\t</td>\n";
$outstr .= "\t\t</tr>\n";
}
/* let's sort the graphs naturally */
usort($graphs, 'necturally_sort_graphs');
foreach ($graphs as $graph) {
$snmp_index_to_graph{$graph['snmp_index']}{$graph['local_graph_id']} = $graph['title_cache'];
}
}
/* using the sorted data as they key; grab each snmp index from the master list */
$graph_list = array();
while (list($snmp_index, $sort_field_value) = each($sort_field_data)) {
/* render each graph for the current data query index */
if (isset($snmp_index_to_graph[$snmp_index])) {
while (list($local_graph_id, $graph_title) = each($snmp_index_to_graph[$snmp_index])) {
/* reformat the array so it's compatable with the html_graph* area functions */
array_push($graph_list, array('local_graph_id' => $local_graph_id, 'title_cache' => $graph_title));
}
}
}
if (sizeof($graph_list)) {
$outstr .= reports_graph_area($graph_list, $report, $item, $timespan, $output, $format_ok, $theme);
}
}
}
}
}
}
}
return $outstr;
}
/**
* natural sort function
* @param $a
* @param $b
*/
function necturally_sort_graphs($a, $b) {
return strnatcasecmp($a['title_cache'], $b['title_cache']);
}
/**
* draw graph area
* @param array $graphs - array of graphs
* @param array $report - report parameters
* @param int $item - current item
* @param int $timespan - requested timespan
* @param int $output - type of output
* @param bool $format_ok - use css styling
*/
function reports_graph_area($graphs, $report, $item, $timespan, $output, $format_ok, $theme = 'classic') {
global $alignment;
$column = 0;
$outstr = '';
if (sizeof($graphs)) {
foreach($graphs as $graph) {
$item['local_graph_id'] = $graph['local_graph_id'];
if ($column == 0) {
$outstr .= "\t\t<tr class='image_row'>\n";
$outstr .= "\t\t\t<td style='text-align:" . $alignment{$item['align']} . ";'>\n";
$outstr .= "\t\t\t\t<table style='width:100%;'>\n";
$outstr .= "\t\t\t\t\t<tr>\n";
}
if ($format_ok) {
$outstr .= "\t\t\t\t\t\t<td class='image_column' style='text-align:" . $alignment{$item['align']} . ";'>\n";
} else {
$outstr .= "\t\t\t\t\t\t<td style='padding:5px;text-align='" . $alignment{$item['align']} . ";'>\n";
}
$outstr .= "\t\t\t\t\t\t\t" . reports_graph_image($report, $item, $timespan, $output, $theme) . "\n";
$outstr .= "\t\t\t\t\t\t</td>\n";
if ($report['graph_columns'] > 1) {
$column = ($column + 1) % ($report['graph_columns']);
}
if ($column == 0) {
$outstr .= "\t\t\t\t\t</tr>\n";
$outstr .= "\t\t\t\t</table>\n";
$outstr .= "\t\t\t</td>\n";
$outstr .= "\t\t</tr>\n";
}
}
}
if ($column > 0) {
$outstr .= "\t\t\t\t\t</tr>\n";
$outstr .= "\t\t\t\t</table>\n";
$outstr .= "\t\t\t</td>\n";
$outstr .= "\t\t</tr>\n";
}
return $outstr;
}
/**
* convert png images stream to jpeg using php-gd
*
* @param string $png_data - the png image as a stream
* @return string - the jpeg image as a stream
*/
function png2jpeg ($png_data) {
global $config;
if ($png_data != '') {
$fn = '/tmp/' . time() . '.png';
/* write rrdtool's png file to scratch dir */
$f = fopen($fn, 'wb');
fwrite($f, $png_data);
fclose($f);
/* create php-gd image object from file */
$im = imagecreatefrompng($fn);
if (!$im) { /* check for errors */
$im = ImageCreate (150, 30); /* create an empty image */
$bgc = ImageColorAllocate ($im, 255, 255, 255);
$tc = ImageColorAllocate ($im, 0, 0, 0);
ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc);
/* print error message */
ImageString($im, 1, 5, 5, "Error while opening: $imgname", $tc);
}
ob_start(); // start a new output buffer to capture jpeg image stream
imagejpeg($im); // output to buffer
$ImageData = ob_get_contents(); // fetch image from buffer
$ImageDataLength = ob_get_length();
ob_end_clean(); // stop this output buffer
imagedestroy($im); //clean up
unlink($fn); // delete scratch file
}
return $ImageData;
}
/**
* convert png images stream to gif using php-gd
*
* @param string $png_data - the png image as a stream
* @return string - the gif image as a stream
*/
function png2gif ($png_data) {
global $config;
if ($png_data != '') {
$fn = '/tmp/' . time() . '.png';
/* write rrdtool's png file to scratch dir */
$f = fopen($fn, 'wb');
fwrite($f, $png_data);
fclose($f);
/* create php-gd image object from file */
$im = imagecreatefrompng($fn);
if (!$im) { /* check for errors */
$im = ImageCreate (150, 30); /* create an empty image */
$bgc = ImageColorAllocate ($im, 255, 255, 255);
$tc = ImageColorAllocate ($im, 0, 0, 0);
ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc);
/* print error message */
ImageString($im, 1, 5, 5, "Error while opening: $imgname", $tc);
}
ob_start(); // start a new output buffer to capture gif image stream
imagegif($im); // output to buffer
$ImageData = ob_get_contents(); // fetch image from buffer
$ImageDataLength = ob_get_length();
ob_end_clean(); // stop this output buffer
imagedestroy($im); //clean up
unlink($fn); // delete scratch file
}
return $ImageData;
}
/**
* get available format files for cacti reporting
* @return array - available format files
*/
function reports_get_format_files() {
global $config;
$formats = array();
$dir = $config['base_path'] . '/formats';
if (is_dir($dir)) {
if (function_exists('scandir')) {
$files = scandir($dir);
} elseif ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
$files[] = $file;
}
closedir($dh);
}
if (sizeof($files)) {
foreach($files as $file) {
if (substr_count($file, '.format')) {
$contents = file($dir . '/' . $file);
if (sizeof($contents)) {
foreach($contents as $line) {
$line = trim($line);
if (substr_count($line, 'Description:') && substr($line, 0, 1) == '#') {
$arr = explode(':', $line);
$formats[$file] = trim($arr[1]) . ' (' . $file . ')';
}
}
}
}
}
}
}
return $formats;
}
/**
* define the reports code that will be processed at the end of each polling event
*/
function reports_poller_bottom () {
global $config;
include_once($config['base_path'] . '/lib/poller.php');
$command_string = read_config_option('path_php_binary');
$extra_args = '-q ' . $config['base_path'] . '/poller_reports.php';
exec_background($command_string, $extra_args);
}
/**
* PHP error handler
* @arg $errno
* @arg $errmsg
* @arg $filename
* @arg $linenum
* @arg $vars
*/
function reports_error_handler($errno, $errmsg, $filename, $linenum, $vars) {
$errno = $errno & error_reporting();
# return if error handling disabled by @
if ($errno == 0) return;
# define constants not available with PHP 4
if(!defined('E_STRICT')) define('E_STRICT', 2048);
if(!defined('E_RECOVERABLE_ERROR')) define('E_RECOVERABLE_ERROR', 4096);
if (read_config_option('log_verbosity') >= POLLER_VERBOSITY_HIGH) {
/* define all error types */
$errortype = array(
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parsing Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
E_STRICT => 'Runtime Notice',
E_RECOVERABLE_ERROR => 'Catchable Fatal Error'
);
/* create an error string for the log */
$err = "ERRNO:'" . $errno . "' TYPE:'" . $errortype[$errno] .
"' MESSAGE:'" . $errmsg . "' IN FILE:'" . $filename .
"' LINE NO:'" . $linenum . "'";
/* let's ignore some lesser issues */
if (substr_count($errmsg, 'date_default_timezone')) return;
if (substr_count($errmsg, 'Only variables')) return;
/* log the error to the Cacti log */
print('PROGERR: ' . $err . '<br><pre>');
# backtrace, if available
cacti_debug_backtrace('REPORTS', true);
if (isset($GLOBALS['error_fatal'])) {
if($GLOBALS['error_fatal'] & $errno) die('fatal');
}
}
return;
}
/**
* Setup the new dropdown action for Graph Management
* @arg $action actions to be performed from dropdown
*/
function reports_graphs_action_array($action) {
$action['reports'] = 'Add to Report';
return $action;
}
/**
* reports_graphs_action_prepare - perform reports_graph prepare action
* @param array $save - drp_action: selected action from dropdown
* graph_array: graphs titles selected from graph management's list
* graph_list: graphs selected from graph management's list
* returns array $save -
* */
function reports_graphs_action_prepare($save) {
global $colors, $config, $graph_timespans, $alignment;
if ($save['drp_action'] == 'reports') { /* report */
print " <tr>
<td class='textArea'>
<p>Choose the Report to associate these graphs with. The defaults for alignment will be used
for each graph in the list below.</p>
<p>" . $save['graph_list'] . "</p>
<p><strong>Report:</strong><br>";
form_dropdown('reports_id', db_fetch_assoc_prepared('SELECT reports.id, reports.name
FROM reports
WHERE user_id = ?
ORDER by name', array($_SESSION['sess_user_id'])),'name','id','','','0');
echo '<br><p><strong>Graph Timespan:</strong><br>';
form_dropdown('timespan', $graph_timespans, '', '', '0', '', '', '');
echo '<br><p><strong>Graph Alignment:</strong><br>';
form_dropdown('alignment', $alignment, '', '', '0', '', '', '');
print "</p>
</td>
</tr>\n
";
} else {
return $save;
}
}
/**
* reports_graphs_action_execute - perform reports_graph execute action
* @param string $action - action to be performed
* return -
* */
function reports_graphs_action_execute($action) {
global $config;
if ($action == 'reports') { /* report */
$message = '';
/* loop through each of the graph_items selected on the previous page for skipped items */
if (isset_request_var('selected_items')) {
$selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items'));
if ($selected_items != false) {
$reports_id = get_filter_request_var('reports_id');
input_validate_input_number($reports_id);
get_filter_request_var('timespan');
get_filter_request_var('alignment');
$report = db_fetch_row_prepared('SELECT * FROM reports WHERE id = ?', array($reports_id));
foreach($selected_items as $local_graph_id) {
/* see if the graph is already added */
$existing = db_fetch_cell_prepared('SELECT id
FROM reports_items
WHERE local_graph_id = ?
AND report_id = ?
AND timespan = ?', array($local_graph_id, $reports_id, get_nfilter_request_var('timespan')));
if (!$existing) {
$sequence = db_fetch_cell_prepared('SELECT max(sequence)
FROM reports_items
WHERE report_id = ?', array($reports_id));
$sequence++;
$graph_data = db_fetch_row_prepared('SELECT *
FROM graph_local
WHERE id = ?', array($local_graph_id));
if ($graph_data['host_id']) {
$host_template = db_fetch_cell_prepared('SELECT host_template_id
FROM host
WHERE id = ?', array($graph_data['host_id']));
} else {
$host_template = 0;
}
$save['id'] = 0;
$save['report_id'] = $reports_id;
$save['item_type'] = REPORTS_ITEM_GRAPH;
$save['tree_id'] = 0;
$save['branch_id'] = 0;
$save['tree_cascade'] = '';
$save['graph_name_regexp'] = '';
$save['host_template_id'] = $host_template;
$save['host_id'] = $graph_data['host_id'];
$save['graph_template_id'] = $graph_data['graph_template_id'];
$save['local_graph_id'] = $local_graph_id;
$save['timespan'] = get_nfilter_request_var('timespan');
$save['align'] = get_nfilter_request_var('alignment');
$save['item_text'] = '';
$save['font_size'] = $report['font_size'];
$save['sequence'] = $sequence;
$id = sql_save($save, 'reports_items');
if ($id) {
$message .= "Created Report Graph Item '<i>" . get_graph_title($local_graph_id) . "</i>'<br>";
} else {
$message .= "Failed Adding Report Graph Item '<i>" . get_graph_title($local_graph_id) . "</i>' Already Exists<br>";
}
} else {
$message .= "Skipped Report Graph Item '<i>" . get_graph_title($local_graph_id) . "</i>' Already Exists<br>";
}
}
}
}
if (strlen($message)) {
$_SESSION['reports_message'] = $message;
}
raise_message('reports_message');
} else {
return $action;
}
}
|
gpl-2.0
|
biblelamp/JavaExercises
|
Java 2/hw1/Course.java
|
505
|
/**
* Java. Level 2. Lesson 1. Example of homework
* Class Course:
* contains array of obstacles
*/
package hw1;
import hw1.obstacles.*;
import java.util.*;
public class Course {
Doable[] obstacles;
public Course(Doable[] obstacles) {
this.obstacles = obstacles;
}
public void doIt(Team team) {
for (Doable obstacle : obstacles)
team.doIt(obstacle);
}
@Override
public String toString() {
return Arrays.toString(obstacles);
}
}
|
gpl-2.0
|
mnjsngh/Magento-Extensions
|
Magento Product Questions/app/code/local/Manojsingh/Productquestions/Block/Summary.php
|
2523
|
<?php
class Manojsingh_Productquestions_Block_Summary extends Mage_Core_Block_Template {
public function __construct() {
parent::__construct();
$this->setTemplate('productquestions/summary.phtml');
}
protected function _toHtml() {
if (Manojsingh_Productquestions_Helper_Data::isModuleOutputDisabled())
return '';
$product = Mage::helper('productquestions')->getCurrentProduct(true);
if (!($product instanceof Mage_Catalog_Model_Product))
return '';
$productId = $product->getId();
$category = Mage::registry('current_category');
if ($category instanceof Mage_Catalog_Model_Category)
$categoryId = $category->getId();
else
$categoryId = false;
$questionCount = Mage::getResourceModel('productquestions/productquestions_collection')
->addProductFilter($productId)
->addVisibilityFilter()
->addAnsweredFilter()
->addStoreFilter()
->getSize();
$params = array('id' => $productId);
if ($categoryId)
$params['category'] = $categoryId;
$suffix = Mage::getStoreConfig('catalog/seo/product_url_suffix');
/* if($urlKey = $product->getUrlKey())
{
$requestString = ltrim(Mage::app()->getFrontController()->getRequest()->getRequestString(), '/');
$pqSuffix = $urlKey.$suffix;
if($pqSuffix == substr($requestString, strlen($requestString)-strlen($pqSuffix)))
{
$requestString = substr($requestString, 0, strlen($requestString)-strlen($suffix));
$this->setQuestionsPageUrl($this->getBaseUrl().$requestString.Manojsingh_Productquestions_Model_Urlrewrite::SEO_SUFFIX.$suffix);
}
} */
if (Mage::getStoreConfig('productquestions/seo/enable_url_rewrites') && Mage::getModel('core/url_rewrite')->load($product->getId(), 'product_id')->getId()) {
$productUrl = $product->getProductUrl();
$fileExtentionPos = ($suffix == '') ? strlen($productUrl) : strrpos($productUrl, $suffix);
$this->setQuestionsPageUrl(substr($productUrl, 0, $fileExtentionPos) . Manojsingh_Productquestions_Model_Urlrewrite::SEO_SUFFIX . $suffix);
} else {
$this->setQuestionsPageUrl(Mage::getUrl('productquestions/index/index/', $params));
}
$this->setQuestionCount($questionCount);
return parent::_toHtml();
}
}
|
gpl-2.0
|
Baahoot/wars
|
remove_image.php
|
779
|
<?php session_start() ?>
<?php require 'connect.php' ?>
<?php
$image_id = mysql_real_escape_string($_GET['id']);
$select_image = mysql_query("SELECT * FROM images WHERE owner_id=".$id." AND id=".$image_id."");
$image_info = mysql_fetch_array($select_image);
if(mysql_num_rows($select_image) == 0) {
$message = die('<span class="Fail">Error: Image Doesn\'t Excist!</span>');
}
if($image == $image_info['url']) {
$message = die('<span class="Fail">Error: This Is Your Current Image!</span>');
}
else {
$message = '<span class="Success">Success: This Image Removed!</span><br /><center><img src="'.$image_info['url'].'" width="60" height="60" /></center>';
$update = mysql_query("DELETE FROM images WHERE owner_id=".$id." AND url='".$image_info['url']."'");
}
echo $message;
?>
|
gpl-2.0
|
Megacrafter127/MSBE
|
src/m127/smd2e/backend/grid/spi/AbstractBlockGrid.java
|
1173
|
package m127.smd2e.backend.grid.spi;
import m127.smd2e.backend.Block;
import m127.smd2e.backend.util.Point3D;
/**
* @author Megacrafter127
* An implementation of all the convenience methods of {@link BlockGrid}.
*/
public abstract class AbstractBlockGrid implements BlockGrid {
@Override
public byte[] getBytes(Point3D p) {
return getBytes(p.x,p.y,p.z);
}
@Override
public void setBytes(Point3D p, byte b1, byte b2, byte b3) {
setBytes(p.x,p.y,p.z,b1,b2,b3);
}
@Override
public Block getBlock(Point3D p) {
return getBlock(p.x,p.y,p.z);
}
@Override
public void setBlock(Point3D p, Block b) {
setBlock(p.x,p.y,p.z,b);
}
@Override
public byte getOrient(Point3D p) {
return getOrient(p.x,p.y,p.z);
}
@Override
public void setOrient(Point3D p, byte orient) {
setOrient(p.x,p.y,p.z,orient);
}
@Override
public byte getHP(Point3D p) {
return getHP(p.x,p.y,p.z);
}
@Override
public void setHP(Point3D p, byte hp) {
setHP(p.x,p.y,p.z,hp);
}
@Override
public boolean isActive(Point3D p) {
return isActive(p.x,p.y,p.z);
}
@Override
public void setActive(Point3D p, boolean active) {
setActive(p.x,p.y,p.z,active);
}
}
|
gpl-2.0
|
NiHab/py-jr
|
src/dictionaries/freq.py
|
972
|
'''
Created on Oct 23, 2015
@author: anon
'''
import collections
class Freq:
"""
Acts as R/O dictionary containing the frequency of expressions
Higher = More Common
Key is the expression
"""
__freqs = collections.defaultdict(int)
__raw = []
def load(self, fp):
print("Loading Frequencies")
f = open(fp, encoding = 'utf-8')
Freq.__raw = f.readlines()
f.close()
self.__parse()
Freq.__raw = None
def __parse(self):
for line in Freq.__raw:
expression = line.split()[0].strip()
freq = line.split('/')[-2].strip()
freq = int(freq.replace('#', ""))
if expression in Freq.__freqs:
if Freq.__freqs[expression] < freq:
Freq.__freqs[expression] = freq
else:
Freq.__freqs[expression] = freq
def __getitem__(self, key):
return Freq.__freqs[key]
|
gpl-2.0
|
Daniel-Dos/Estrutura-de-Dados---Java
|
src/br/com/caelum/ed/Mapas/Associacao.java
|
539
|
package br.com.caelum.ed.Mapas;
import br.com.caelum.ed.Carro;
/**
* @author Daniel Dias
*
*/
public class Associacao {
private String placa;
private Carro carro;
public Associacao(String placa, Carro carro) {
super();
this.placa = placa;
this.carro = carro;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public Carro getCarro() {
return carro;
}
public void setCarro(Carro carro) {
this.carro = carro;
}
}
|
gpl-2.0
|
iut-ibk/DynaMind-ToolBox
|
DynaMind-GDALModules/scripts/GDALModules/dm_sftp_hotstart.py
|
5591
|
from pydynamind import *
import paramiko
import time
from osgeo import ogr
import uuid
import os
class DM_Hoststart_SFTP(Module):
display_name = "Hotstart Simulation from SFTP"
group_name = "Data Import and Export"
def __init__(self):
Module.__init__(self)
self.setIsGDALModule(True)
self.createParameter("username", STRING)
self.username = ""
self.createParameter("password", STRING)
self.password = ""
self.createParameter("port", INT)
self.port = 22
self.createParameter("host", STRING)
self.host = ""
# self.createParameter("folder_name", STRING)
# self.folder_name = ""
self.createParameter("file_name", STRING)
self.file_name = ""
self.createParameter("step", INT)
self.step = 1 #export every x step
self.transport = None
self.sftp = None
self.downloaded_file = ""
self.real_file_name = ""
def generate_downloaded_file_name(self):
return self.file_name + self.username + self.password+self.host
def init(self):
if not self.file_name or not self.host or not self.username or not self.password:
self.dummy = ViewContainer("dummy", SUBSYSTEM, WRITE)
self.registerViewContainers([self.dummy])
return
if self.downloaded_file == self.generate_downloaded_file_name():
return
if not self.connect():
self.dummy = ViewContainer("dummy", SUBSYSTEM, WRITE)
self.registerViewContainers([self.dummy])
return
if not self.get_file(self.file_name):
self.dummy = ViewContainer("dummy", SUBSYSTEM, WRITE)
self.registerViewContainers([self.dummy])
self.close()
return
self.close()
ds = ogr.Open(self.real_file_name)
if ds is None:
print "Open failed.\n"
return
lyr = ds.GetLayerByName("dynamind_table_definitions")
lyr.ResetReading()
views = {}
view_type = {}
for feat in lyr:
view_name = feat.GetFieldAsString("view_name")
attribute_name = feat.GetFieldAsString("attribute_name")
datatype = feat.GetFieldAsString("data_type")
if attribute_name == "DEFINITION":
view_type[view_name] = datatype
continue
if view_name not in views.keys():
views[view_name] = {}
views[view_name][attribute_name] = datatype
self.view_containers = []
for view in view_type.keys():
v = ViewContainer(view, self.StringToDMDataType(view_type[view]), WRITE)
self.view_containers.append(v)
if view not in views.keys():
continue
for attribute in views[view].keys():
v.addAttribute(attribute, self.StringToDMDataType(views[view][attribute]), WRITE )
ds = None
self.registerViewContainers(self.view_containers)
def StringToDMDataType(self, type):
if type == "COMPONENT":
return COMPONENT
if type == "NODE":
return NODE
if type == "EDGE":
return EDGE
if type == "FACE":
return FACE
if type == "SUBSYSTEM":
return SUBSYSTEM
if type == "INTEGER":
return Attribute.INT
if type == "DOUBLE":
return Attribute.DOUBLE
if type == "DOUBLEVECTOR":
return Attribute.DOUBLEVECTOR
if type == "STRING":
return Attribute.STRING
if type == "DATE":
return Attribute.DATE
if type == "LINK":
return Attribute.LINK
def connect(self):
established = False
try:
log(str(self.host) + " " + str(self.port) + " " + str(self.username) + " " + str(self.password), Standard)
self.transport = paramiko.Transport((self.host, self.port))
self.transport.connect(username=self.username, password=self.password)
established = True
except:
return False
log("connected", Standard)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
return True
def close(self):
log("close connection", Standard)
self.sftp.close()
self.transport.close()
self.sftp = None
self.transport = None
def get_file(self, file_name):
if self.real_file_name:
os.remove(self.real_file_name)
self.real_file_name = "/tmp/" + str(uuid.uuid4())+".sqlite"
try:
self.sftp.get(file_name, self.real_file_name)
except:
self.real_file_name = ""
return False
self.downloaded_file = self.generate_downloaded_file_name()
return True
def run(self):
db = self.getGDALData("city")
db.setGDALDatabase(self.real_file_name)
os.remove(self.real_file_name)
|
gpl-2.0
|
SUPLA/supla-cloud
|
src/SuplaBundle/Repository/UserRepository.php
|
1797
|
<?php
namespace SuplaBundle\Repository;
use Doctrine\ORM\QueryBuilder;
use SuplaBundle\Entity\AccessID;
use SuplaBundle\Entity\ClientApp;
use SuplaBundle\Entity\DirectLink;
use SuplaBundle\Entity\IODevice;
use SuplaBundle\Entity\IODeviceChannel;
use SuplaBundle\Entity\IODeviceChannelGroup;
use SuplaBundle\Entity\Location;
use SuplaBundle\Entity\OAuth\ApiClient;
use SuplaBundle\Entity\Schedule;
use SuplaBundle\Entity\User;
/**
* @method User|null findOneByEmail(string $email)
*/
class UserRepository extends EntityWithRelationsRepository {
protected $alias = 'u';
protected function getEntityWithRelationsCountQuery(): QueryBuilder {
return $this->_em->createQueryBuilder()
->addSelect('u entity')
->addSelect(sprintf('(SELECT COUNT(1) FROM %s cg WHERE cg.user = u) channelGroups', IODeviceChannelGroup::class))
->addSelect(sprintf('(SELECT COUNT(1) FROM %s aid WHERE aid.user = u) accessIds', AccessID::class))
->addSelect(sprintf('(SELECT COUNT(1) FROM %s l WHERE l.user = u) locations', Location::class))
->addSelect(sprintf('(SELECT COUNT(1) FROM %s s WHERE s.user = u) schedules', Schedule::class))
->addSelect(sprintf('(SELECT COUNT(1) FROM %s dl WHERE dl.user = u) directLinks', DirectLink::class))
->addSelect(sprintf('(SELECT COUNT(1) FROM %s ac WHERE ac.user = u) apiClients', ApiClient::class))
->addSelect(sprintf('(SELECT COUNT(1) FROM %s io WHERE io.user = u) ioDevices', IODevice::class))
->addSelect(sprintf('(SELECT COUNT(1) FROM %s cl WHERE cl.user = u) clientApps', ClientApp::class))
->addSelect(sprintf('(SELECT COUNT(1) FROM %s c WHERE c.user = u) channels', IODeviceChannel::class))
->from(User::class, 'u');
}
}
|
gpl-2.0
|
bazooka07/PluXml
|
core/admin/statique.php
|
6495
|
<?php
/**
* Edition du code source d'une page statique
*
* @package PLX
* @author Stephane F. et Florent MONTHEL
**/
include __DIR__ .'/prepend.php';
# Hook Plugins
eval($plxAdmin->plxPlugins->callHook('AdminStaticPrepend'));
# Control du token du formulaire
plxToken::validateFormToken($_POST);
# Control de l'accès à la page en fonction du profil de l'utilisateur connecté
$plxAdmin->checkProfil(PROFIL_ADMIN, PROFIL_MANAGER);
# On édite la page statique
if(!empty($_POST) AND isset($plxAdmin->aStats[$_POST['id']])) {
$valid=true;
# Vérification de la validité de la date de création
if(!plxDate::checkDate($_POST['date_creation_day'],$_POST['date_creation_month'],$_POST['date_creation_year'],$_POST['date_creation_time'])) {
$valid = plxMsg::Error(L_ERR_INVALID_DATE_CREATION) AND $valid;
}
# Vérification de la validité de la date de mise à jour
if(!plxDate::checkDate($_POST['date_update_day'],$_POST['date_update_month'],$_POST['date_update_year'],$_POST['date_update_time'])) {
$valid = plxMsg::Error(L_ERR_INVALID_DATE_UPDATE) AND $valid;
}
if($valid) $plxAdmin->editStatique($_POST);
header('Location: statique.php?p='.$_POST['id']);
exit;
} elseif(!empty($_GET['p'])) { # On affiche le contenu de la page
$id = plxUtils::strCheck(plxUtils::nullbyteRemove($_GET['p']));
if(!isset($plxAdmin->aStats[ $id ])) {
plxMsg::Error(L_STATIC_UNKNOWN_PAGE);
header('Location: statiques.php');
exit;
}
# On récupère le contenu
$content = trim($plxAdmin->getFileStatique($id));
$title = $plxAdmin->aStats[$id]['name'];
$url = $plxAdmin->urlRewrite("?static".intval($id)."/".$plxAdmin->aStats[$id]['url']);
$active = $plxAdmin->aStats[$id]['active'];
$title_htmltag = $plxAdmin->aStats[$id]['title_htmltag'];
$meta_description = $plxAdmin->aStats[$id]['meta_description'];
$meta_keywords = $plxAdmin->aStats[$id]['meta_keywords'];
$template = $plxAdmin->aStats[$id]['template'];
$date_creation = plxDate::date2Array($plxAdmin->aStats[$id]['date_creation']);
$date_update = plxDate::date2Array($plxAdmin->aStats[$id]['date_update']);
} else { # Sinon, on redirige
header('Location: statiques.php');
exit;
}
# On récupère les templates des pages statiques
$aTemplates = array();
$files = plxGlob::getInstance(PLX_ROOT.$plxAdmin->aConf['racine_themes'].$plxAdmin->aConf['style']);
if ($array = $files->query('/^static(-[a-z0-9-_]+)?.php$/')) {
foreach($array as $k=>$v)
$aTemplates[$v] = $v;
}
if(empty($aTemplates)) $aTemplates[''] = L_NONE1;
# On inclut le header
include __DIR__ .'/top.php';
?>
<form action="statique.php" method="post" id="form_static">
<div class="inline-form action-bar">
<h2><?php echo L_STATIC_TITLE ?> "<?php echo plxUtils::strCheck($title); ?>"</h2>
<p><a class="back" href="statiques.php"><?php echo L_STATIC_BACK_TO_PAGE ?></a></p>
<input type="submit" value="<?php echo L_STATIC_UPDATE ?>"/>
<a href="<?php echo $url ?>"><?php echo L_STATIC_VIEW_PAGE ?> <?php echo plxUtils::strCheck($title); ?> <?php echo L_STATIC_ON_SITE ?></a>
<?php plxUtils::printInput('id', $id, 'hidden');?>
</div>
<?php eval($plxAdmin->plxPlugins->callHook('AdminStaticTop')) # Hook Plugins ?>
<fieldset>
<div class="grid">
<div class="col sml-12">
<label for="id_content"><?php echo L_CONTENT_FIELD ?> :</label>
<?php plxUtils::printArea('content', plxUtils::strCheck($content),140,30,false,'full-width') ?>
</div>
</div>
<div class="grid">
<div class="col sml-12">
<label for="id_template"><?php echo L_STATICS_TEMPLATE_FIELD ?> :</label>
<?php plxUtils::printSelect('template', $aTemplates, $template) ?>
</div>
</div>
<div class="grid">
<div class="col sml-12">
<label for="id_title_htmltag"><?php echo L_STATIC_TITLE_HTMLTAG ?> :</label>
<?php plxUtils::printInput('title_htmltag',plxUtils::strCheck($title_htmltag),'text','50-255'); ?>
</div>
</div>
<div class="grid">
<div class="col sml-12">
<label for="id_meta_description"><?php echo L_STATIC_META_DESCRIPTION ?> :</label>
<?php plxUtils::printInput('meta_description',plxUtils::strCheck($meta_description),'text','50-255'); ?>
</div>
</div>
<div class="grid">
<div class="col sml-12">
<label for="id_meta_keywords"><?php echo L_STATIC_META_KEYWORDS ?> :</label>
<?php plxUtils::printInput('meta_keywords',plxUtils::strCheck($meta_keywords),'text','50-255'); ?>
</div>
</div>
<div class="grid">
<div class="col sml-12">
<label><?php echo L_DATE_CREATION ?> :</label>
<div class="inline-form creation">
<?php plxUtils::printInput('date_creation_day',$date_creation['day'],'text','2-2',false,'day'); ?>
<?php plxUtils::printInput('date_creation_month',$date_creation['month'],'text','2-2',false,'month'); ?>
<?php plxUtils::printInput('date_creation_year',$date_creation['year'],'text','2-4',false,'year'); ?>
<?php plxUtils::printInput('date_creation_time',$date_creation['time'],'text','2-5',false,'time'); ?>
<a class="ico_cal" href="javascript:void(0)" onclick="dateNow('date_creation', <?php echo date('Z') ?>); return false;" title="<?php L_NOW; ?>">
<img src="theme/images/date.png" alt="calendar" />
</a>
</div>
</div>
</div>
<div class="grid">
<div class="col sml-12">
<?php plxUtils::printInput('date_update', $plxAdmin->aStats[$id]['date_update'], 'hidden');?>
<label><?php echo L_DATE_UPDATE ?> :</label>
<div class="inline-form update">
<?php plxUtils::printInput('date_update_day',$date_update['day'],'text','2-2',false,'day'); ?>
<?php plxUtils::printInput('date_update_month',$date_update['month'],'text','2-2',false,'month'); ?>
<?php plxUtils::printInput('date_update_year',$date_update['year'],'text','2-4',false,'year'); ?>
<?php plxUtils::printInput('date_update_time',$date_update['time'],'text','2-5',false,'time'); ?>
<a class="ico_cal" href="javascript:void(0)" onclick="dateNow('date_update', <?php echo date('Z') ?>); return false;" title="<?php L_NOW; ?>">
<img src="theme/images/date.png" alt="calendar" />
</a>
</div>
</div>
</div>
</fieldset>
<?php eval($plxAdmin->plxPlugins->callHook('AdminStatic')) # Hook Plugins ?>
<?php echo plxToken::getTokenPostMethod() ?>
</form>
<?php
# Hook Plugins
eval($plxAdmin->plxPlugins->callHook('AdminStaticFoot'));
# On inclut le footer
include __DIR__ .'/foot.php';
?>
|
gpl-2.0
|
rwmcoder/Vanilla
|
plugins/recaptcha/class.recaptcha.plugin.php
|
6825
|
<?php
/**
* @copyright 2009-2017 Vanilla Forums Inc
* @license Proprietary
*/
$PluginInfo['recaptcha'] = array(
'Name' => 'reCAPTCHA Support',
'Description' => "Add recaptcha validation to signups.",
'Version' => '0.1',
'MobileFriendly' => true,
'Icon' => 'recaptcha_support.png',
'Author' => "Tim Gunter",
'AuthorEmail' => 'tim@vanillaforums.com',
'AuthorUrl' => 'http://www.vanillaforums.com'
);
/**
* Recaptcha Validation
*
* This plugin adds recaptcha validation to signups.
*
* Changes:
* 0.1 Development
*
* @author Tim Gunter <tim@vanillaforums.com>
* @package vanilla
*/
class RecaptchaPlugin extends Gdn_Plugin {
/**
* reCAPTCHA private key
* @var string
*/
protected $privateKey;
/**
* reCAPTCHA public key
* @var string
*/
protected $publicKey;
/**
* Plugin initialization.
*
*/
public function __construct() {
parent::__construct();
// Get keys from config
$this->privateKey = c('Recaptcha.PrivateKey');
$this->publicKey = c('Recaptcha.PublicKey');
}
/**
* Override private key in memory.
*
* @param string $key
*/
public function setPrivateKey($key) {
$this->privateKey = $key;
}
/**
* Get private key from memory.
*
* @return string
*/
public function getPrivateKey() {
return $this->privateKey;
}
/**
* Override public key in memory.
*
* @param string $key
*/
public function setPublicKey($key) {
$this->publicKey = $key;
}
/**
* Get public key from memory.
*
* @return string
*/
public function getPublicKey() {
return $this->publicKey;
}
/**
* Validate a reCAPTCHA submission.
*
* @param string $captchaText
* @return boolean
* @throws Exception
*/
public function validateCaptcha($captchaText) {
$api = new Garden\Http\HttpClient('https://www.google.com/recaptcha/api');
$data = array(
'secret' => $this->getPrivateKey(),
'response' => $captchaText
);
$response = $api->get('/siteverify', $data);
if ($response->isSuccessful()) {
$result = $response->getBody();
$errorCodes = val('error_codes', $result);
if ($result && val('success', $result)) {
return true;
} else if (!empty($errorCodes) && $errorCodes != array('invalid-input-response')) {
throw new Exception(formatString(t('No response from reCAPTCHA.').' {ErrorCodes}', array('ErrorCodes' => join(', ', $errorCodes))));
}
} else {
throw new Exception(t('No response from reCAPTCHA.'));
}
return false;
}
/**
* Hook (controller) to manage captcha config.
*
* @param SettingsController $sender
*/
public function settingsController_registration_handler($sender) {
$configurationModel = $sender->EventArguments['Configuration'];
$manageCaptcha = c('Garden.Registration.ManageCaptcha', true);
$sender->setData('_ManageCaptcha', $manageCaptcha);
if ($manageCaptcha) {
$configurationModel->setField('Recaptcha.PrivateKey');
$configurationModel->setField('Recaptcha.PublicKey');
}
}
/**
* Hook to indicate a captcha service is available.
*
* @param Gdn_PluginManager $sender
* @param array $args
*/
public function captcha_isEnabled_handler($sender, $args) {
$args['Enabled'] = true;
}
/**
* Hook (view) to manage captcha config.
*
* THIS METHOD ECHOS DATA
*
* @param SettingsController $sender
*/
public function captcha_settings_handler($sender) {
echo $sender->fetchView('registration', 'settings', 'plugins/recaptcha');
}
/**
* Hook (view) to render a captcha.
*
* THIS METHOD ECHOS DATA
*
* @param Gdn_Controller $sender
*/
public function captcha_render_handler($sender) {
echo $sender->fetchView('captcha', 'display', 'plugins/recaptcha');
}
/**
* Hook to validate captchas.
*
* @param Gdn_PluginManager $sender
* @return boolean
* @throws Exception
*/
public function captcha_validate_handler($sender) {
$valid = &$sender->EventArguments['captchavalid'];
$recaptchaResponse = Gdn::request()->post('g-recaptcha-response');
if (!$recaptchaResponse) {
return $valid = false;
}
return $valid = $this->validateCaptcha($recaptchaResponse);
}
/**
* Hook to return captcha submission data.
*
* @param Gdn_PluginManager $sender
*/
public function captcha_get_handler($sender) {
$recaptchaResponse = Gdn::request()->post('g-recaptcha-response');
if ($recaptchaResponse) {
$sender->EventArguments['captchatext'] = $recaptchaResponse;
}
}
/**
* Display reCAPTCHA entry field.
*
* THIS METHOD ECHOS DATA
*
* @param Gdn_Form $sender
* @return string
*/
public function gdn_form_captcha_handler($sender) {
if (!$this->getPrivateKey() || !$this->getPublicKey()) {
echo '<div class="Warning">' . t('reCAPTCHA has not been set up by the site administrator in registration settings. This is required to register.') . '</div>';
}
// Google whitelist https://developers.google.com/recaptcha/docs/language
$whitelist = ['ar', 'bg', 'ca', 'zh-CN', 'zh-TW', 'hr', 'cs', 'da', 'nl', 'en-GB', 'en', 'fil', 'fi', 'fr', 'fr-CA', 'de', 'de-AT', 'de-CH', 'el', 'iw', 'hi', 'hu', 'id', 'it', 'ja', 'ko', 'lv', 'lt', 'no', 'fa', 'pl', 'pt', 'pt-BR', 'pt-PT', 'ro', 'ru', 'sr', 'sk', 'sl', 'es', 'es-419', 'sv', 'th', 'tr', 'uk', 'vi'];
// Use our current locale against the whitelist.
$language = Gdn::locale()->language();
if (!in_array($language, $whitelist)) {
$language = (in_array(Gdn::locale()->Locale, $whitelist)) ? Gdn::locale()->Locale : false;
}
$scriptSrc = 'https://www.google.com/recaptcha/api.js?hl='.$language;
$attributes = array('class' => 'g-recaptcha', 'data-sitekey' => $this->getPublicKey(), 'data-theme' => c('Recaptcha.Theme', 'light'));
// see https://developers.google.com/recaptcha/docs/display for details
$this->EventArguments['Attributes'] = &$attributes;
$this->fireEvent('BeforeCaptcha');
echo '<div '. attribute($attributes) . '></div>';
echo '<script src="'.$scriptSrc.'"></script>';
}
/**
* On plugin enable.
*
*/
public function setup() {}
}
|
gpl-2.0
|
FrodeSolheim/fs-uae-launcher
|
launcher/ui/config/HardDriveGroup.py
|
5056
|
import os
import fsui
from fsgamesys.amiga import whdload
from fsgamesys.checksumtool import ChecksumTool
from fsgamesys.FSGSDirectories import FSGSDirectories
from launcher.context import get_config
from launcher.i18n import gettext
from launcher.ui.behaviors.platformbehavior import AmigaEnableBehavior
from launcher.ui.IconButton import IconButton
from launcher.ui.LauncherFilePicker import LauncherFilePicker
class HardDriveGroup(fsui.Panel):
def __init__(self, parent, index):
fsui.Panel.__init__(self, parent)
AmigaEnableBehavior(self)
self.layout = fsui.VerticalLayout()
self.index = index
self.config_key = "hard_drive_{0}".format(index)
self.config_key_sha1 = "x_hard_drive_{0}_sha1".format(index)
# if index == 0:
# # heading_label = fsui.HeadingLabel(self,
# # _("Hard Drive {0}").format(index + 1))
# heading_label = fsui.HeadingLabel(self, gettext("Hard Drives"))
# self.layout.add(heading_label, margin_bottom=20)
# self.layout.add_spacer(0)
hori_layout = fsui.HorizontalLayout()
self.layout.add(hori_layout, fill=True)
self.eject_button = IconButton(self, "eject_button.png")
self.eject_button.set_tooltip(gettext("Eject"))
self.eject_button.activated.connect(self.on_eject_button)
hori_layout.add(self.eject_button)
self.text_field = fsui.TextField(self, "", read_only=True)
hori_layout.add(self.text_field, expand=True, margin_left=10)
self.browse_button = IconButton(self, "browse_folder_16.png")
self.browse_button.set_tooltip(gettext("Browse for Folder"))
self.browse_button.activated.connect(self.on_browse_folder_button)
hori_layout.add(self.browse_button, margin_left=10)
self.browse_button = IconButton(self, "browse_file_16.png")
self.browse_button.set_tooltip(gettext("Browse for File"))
self.browse_button.activated.connect(self.on_browse_file_button)
hori_layout.add(self.browse_button, margin_left=10)
self.initialize_from_config()
self.set_config_handlers()
def initialize_from_config(self):
self.on_config(self.config_key, get_config(self).get(self.config_key))
def set_config_handlers(self):
get_config(self).add_listener(self)
def onDestroy(self):
get_config(self).remove_listener(self)
super().onDestroy()
def on_config(self, key, value):
if key != self.config_key:
return
dir_path, name = os.path.split(value)
if dir_path:
path = "{0} ({1})".format(name, dir_path)
else:
path = name
self.text_field.set_text(path)
self.text_field.set_cursor_position(0)
self.eject_button.set_enabled(bool(value))
def on_eject_button(self):
get_config(self).set_multiple(
[(self.config_key, ""), (self.config_key_sha1, "")]
)
def on_browse_folder_button(self):
self.browse(dir_mode=True)
def on_browse_file_button(self):
self.browse(dir_mode=False)
def browse(self, dir_mode):
default_dir = FSGSDirectories.get_hard_drives_dir()
dialog = LauncherFilePicker(
self.get_window(),
gettext("Choose Hard Drive"),
"hd",
get_config(self).get(self.config_key),
dir_mode=dir_mode,
)
if not dialog.show_modal():
dialog.destroy()
return
path = dialog.get_path()
dialog.destroy()
checksum_tool = ChecksumTool(self.get_window())
sha1 = ""
if dir_mode:
print("not calculating HD checksums for directories")
else:
size = os.path.getsize(path)
if size < 64 * 1024 * 1024:
sha1 = checksum_tool.checksum(path)
else:
print("not calculating HD checksums HD files > 64MB")
full_path = path
# FIXME: use contract function
dir_path, file = os.path.split(path)
self.text_field.set_text(file)
if os.path.normcase(os.path.normpath(dir_path)) == os.path.normcase(
os.path.normpath(default_dir)
):
path = file
self.text_field.set_text(path)
values = [(self.config_key, path), (self.config_key_sha1, sha1)]
if self.index == 0:
# whdload_args = ""
# dummy, ext = os.path.splitext(path)
# if not dir_mode and ext.lower() in Archive.extensions:
# try:
# whdload_args = self.calculate_whdload_args(full_path)
# except Exception:
# traceback.print_exc()
# values.append(("x_whdload_args", whdload_args))
values.extend(
whdload.generate_config_for_archive(
full_path, model_config=False
).items()
)
get_config(self).set_multiple(values)
|
gpl-2.0
|
Argamore/BILD-IT-Advanced
|
src/zadaca_15_02_2016/Zadatak4.java
|
1227
|
package zadaca_15_02_2016;
import java.io.File;
public class Zadatak4 {
public static void main(String[] args) {
try (java.util.Scanner unos = new java.util.Scanner(System.in)) {
System.out.println("Datoteka mora biti u istoj direktoriji.\nUnesite ime datoteke: ");
String imeFajla = unos.nextLine();
// nakon unosa od korisnika, prosljedjujemo fajl metodi
counter(imeFajla);
} catch (Exception e){
System.err.println("Greka!\nProvjeri ime fajla i da li je gdje treba da bude.");
}
}
public static void counter(String imeFajla) {
int brLinija = 0, brRijeci = 0, brKaraktera = 0;
File file = new File(imeFajla);
try(java.util.Scanner unos = new java.util.Scanner(file)){
while (unos.hasNextLine()) {
String linija = unos.nextLine();
// brojac linija se povecava
brLinija++;
// te i brojac rijeci
brRijeci += linija.split(" ").length;
// na kraju i brojac karaktera, na osnovu broja slova / duzine linije
brKaraktera += linija.length();
}
System.out.println(
"U tekstu ima " + brLinija + " linija, " + brRijeci + " rijeci i " + brKaraktera + " karaktera.");
} catch(Exception e){
System.err.println("Greka!");
}
}
}
|
gpl-2.0
|
Khanos/HardCode
|
OpenEMR/src/library/js/jquery-calendar.js
|
33174
|
/* jQuery Calendar v2.7
Written by Marc Grabanski (m@marcgrabanski.com) and enhanced by Keith Wood (kbwood@iprimus.com.au).
Copyright (c) 2007 Marc Grabanski (http://marcgrabanski.com/code/jquery-calendar)
Dual licensed under the GPL (http://www.gnu.org/licenses/gpl-3.0.txt) and
CC (http://creativecommons.org/licenses/by/3.0/) licenses. "Share or Remix it but please Attribute the authors."
Date: 09-03-2007 */
/* PopUp Calendar manager.
Use the singleton instance of this class, popUpCal, to interact with the calendar.
Settings for (groups of) calendars are maintained in an instance object
(PopUpCalInstance), allowing multiple different settings on the same page. */
function PopUpCal() {
this._nextId = 0; // Next ID for a calendar instance
this._inst = []; // List of instances indexed by ID
this._curInst = null; // The current instance in use
this._disabledInputs = []; // List of calendar inputs that have been disabled
this._popUpShowing = false; // True if the popup calendar is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this.regional = []; // Available regional settings, indexed by language code
this.regional[''] = { // Default regional settings
clearText: 'Clear', // Display text for clear link
closeText: 'Close', // Display text for close link
prevText: '<Prev', // Display text for previous month link
nextText: 'Next>', // Display text for next month link
currentText: 'Today', // Display text for current month link
dayNames: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Names of days starting at Sunday
monthNames: ['January','February','March','April','May','June',
'July','August','September','October','November','December'], // Names of months
dateFormat: 'DMY/' // First three are day, month, year in the required order,
// fourth (optional) is the separator, e.g. US would be 'MDY/', ISO would be 'YMD-'
};
this._defaults = { // Global defaults for all the calendar instances
autoPopUp: 'focus', // 'focus' for popup on focus,
// 'button' for trigger button, or 'both' for either
appendText: '', // Display text following the input box, e.g. showing the format
buttonText: '...', // Text for trigger button
buttonImage: '', // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
closeAtTop: true, // True to have the clear/close at the top,
// false to have them at the bottom
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
changeMonth: true, // True if month can be selected directly, false if only prev/next
changeYear: true, // True if year can be selected directly, false if only prev/next
yearRange: '-10:+10', // Range of years to display in drop-down,
// either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
changeFirstDay: true, // True to click on day name to change, false to remain as set
showOtherMonths: false, // True to show dates in other months, false to leave blank
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
speed: 'medium', // Speed of display/closure
customDate: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not,
// [1] = custom CSS class name(s) or '', e.g. popUpCal.noWeekends
fieldSettings: null, // Function that takes an input field and
// returns a set of custom settings for the calendar
onSelect: null // Define a callback function when a date is selected
};
$.extend(this._defaults, this.regional['']);
this._calendarDiv = $('<div id="calendar_div"></div>');
$(document.body).append(this._calendarDiv);
$(document.body).mousedown(this._checkExternalClick);
}
$.extend(PopUpCal.prototype, {
/* Register a new calendar instance - with custom settings. */
_register: function(inst) {
var id = this._nextId++;
this._inst[id] = inst;
return id;
},
/* Retrieve a particular calendar instance based on its ID. */
_getInst: function(id) {
return this._inst[id] || id;
},
/* Override the default settings for all instances of the calendar.
@param settings object - the new settings to use as defaults (anonymous object)
@return void */
setDefaults: function(settings) {
$.extend(this._defaults, settings || {});
},
/* Handle keystrokes. */
_doKeyDown: function(e) {
var inst = popUpCal._getInst(this._calId);
if (popUpCal._popUpShowing) {
switch (e.keyCode) {
case 9: popUpCal.hideCalendar(inst, '');
break; // hide on tab out
case 13: popUpCal._selectDate(inst);
break; // select the value on enter
case 27: popUpCal.hideCalendar(inst, inst._get('speed'));
break; // hide on escape
case 33: popUpCal._adjustDate(inst, -1, (e.ctrlKey ? 'Y' : 'M'));
break; // previous month/year on page up/+ ctrl
case 34: popUpCal._adjustDate(inst, +1, (e.ctrlKey ? 'Y' : 'M'));
break; // next month/year on page down/+ ctrl
case 35: if (e.ctrlKey) popUpCal._clearDate(inst);
break; // clear on ctrl+end
case 36: if (e.ctrlKey) popUpCal._gotoToday(inst);
break; // current on ctrl+home
case 37: if (e.ctrlKey) popUpCal._adjustDate(inst, -1, 'D');
break; // -1 day on ctrl+left
case 38: if (e.ctrlKey) popUpCal._adjustDate(inst, -7, 'D');
break; // -1 week on ctrl+up
case 39: if (e.ctrlKey) popUpCal._adjustDate(inst, +1, 'D');
break; // +1 day on ctrl+right
case 40: if (e.ctrlKey) popUpCal._adjustDate(inst, +7, 'D');
break; // +1 week on ctrl+down
}
}
else if (e.keyCode == 36 && e.ctrlKey) { // display the calendar on ctrl+home
popUpCal.showFor(this);
}
},
/* Filter entered characters. */
_doKeyPress: function(e) {
var inst = popUpCal._getInst(this._calId);
var chr = String.fromCharCode(e.charCode == undefined ? e.keyCode : e.charCode);
return (chr < ' ' || chr == inst._get('dateFormat').charAt(3) ||
(chr >= '0' && chr <= '9')); // only allow numbers and separator
},
/* Attach the calendar to an input field. */
_connectCalendar: function(target, inst) {
var $input = $(target);
var appendText = inst._get('appendText');
if (appendText) {
$input.after('<span class="calendar_append">' + appendText + '</span>');
}
var autoPopUp = inst._get('autoPopUp');
if (autoPopUp == 'focus' || autoPopUp == 'both') { // pop-up calendar when in the marked field
$input.focus(this.showFor);
}
if (autoPopUp == 'button' || autoPopUp == 'both') { // pop-up calendar when button clicked
var buttonText = inst._get('buttonText');
var buttonImage = inst._get('buttonImage');
var buttonImageOnly = inst._get('buttonImageOnly');
var trigger = $(buttonImageOnly ? '<img class="calendar_trigger" src="' +
buttonImage + '" alt="' + buttonText + '" title="' + buttonText + '"/>' :
'<button type="button" class="calendar_trigger">' + (buttonImage != '' ?
'<img src="' + buttonImage + '" alt="' + buttonText + '" title="' + buttonText + '"/>' :
buttonText) + '</button>');
$input.wrap('<span class="calendar_wrap"></span>').after(trigger);
trigger.click(this.showFor);
}
$input.keydown(this._doKeyDown).keypress(this._doKeyPress);
$input[0]._calId = inst._id;
},
/* Attach an inline calendar to a div. */
_inlineCalendar: function(target, inst) {
$(target).append(inst._calendarDiv);
target._calId = inst._id;
var date = new Date();
inst._selectedDay = date.getDate();
inst._selectedMonth = date.getMonth();
inst._selectedYear = date.getFullYear();
popUpCal._adjustDate(inst);
},
/* Pop-up the calendar in a "dialog" box.
@param dateText string - the initial date to display (in the current format)
@param onSelect function - the function(dateText) to call when a date is selected
@param settings object - update the dialog calendar instance's settings (anonymous object)
@param pos int[2] - coordinates for the dialog's position within the screen
leave empty for default (screen centre)
@return void */
dialogCalendar: function(dateText, onSelect, settings, pos) {
var inst = this._dialogInst; // internal instance
if (!inst) {
inst = this._dialogInst = new PopUpCalInstance({}, false);
this._dialogInput = $('<input type="text" size="1" style="position: absolute; top: -100px;"/>');
this._dialogInput.keydown(this._doKeyDown);
$('body').append(this._dialogInput);
this._dialogInput[0]._calId = inst._id;
}
$.extend(inst._settings, settings || {});
this._dialogInput.val(dateText);
/* Cross Browser Positioning */
if (self.innerHeight) { // all except Explorer
windowWidth = self.innerWidth;
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
this._pos = pos || // should use actual width/height below
[(windowWidth / 2) - 100, (windowHeight / 2) - 100];
// move input on screen for focus, but hidden behind dialog
this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px');
inst._settings.onSelect = onSelect;
this._inDialog = true;
this._calendarDiv.addClass('calendar_dialog');
this.showFor(this._dialogInput[0]);
if ($.blockUI) {
$.blockUI(this._calendarDiv);
}
},
/* Enable the input field(s) for entry.
@param inputs element/object - single input field or jQuery collection of input fields
@return void */
enableFor: function(inputs) {
inputs = (inputs.jquery ? inputs : $(inputs));
inputs.each(function() {
this.disabled = false;
$('../button.calendar_trigger', this).each(function() { this.disabled = false; });
$('../img.calendar_trigger',
this).css({opacity:'1.0',cursor:''});
var $this = this;
popUpCal._disabledInputs = $.map(popUpCal._disabledInputs,
function(value) { return (value == $this ? null : value); }); // delete entry
});
},
/* Disable the input field(s) from entry.
@param inputs element/object - single input field or jQuery collection of input fields
@return void */
disableFor: function(inputs) {
inputs = (inputs.jquery ? inputs : $(inputs));
inputs.each(function() {
this.disabled = true;
$('../button.calendar_trigger', this).each(function() { this.disabled = true; });
$('../img.calendar_trigger', this).css({opacity:'0.5',cursor:'default'});
var $this = this;
popUpCal._disabledInputs = $.map(popUpCal._disabledInputs,
function(value) { return (value == $this ? null : value); }); // delete entry
popUpCal._disabledInputs[popUpCal._disabledInputs.length] = this;
});
},
/* Update the settings for a calendar attached to an input field or division.
@param control element - the input field or div/span attached to the calendar
@param settings object - the new settings to update
@return void */
reconfigureFor: function(control, settings) {
var inst = this._getInst(control._calId);
if (inst) {
$.extend(inst._settings, settings || {});
this._updateCalendar(inst);
}
},
/* Set the date for a calendar attached to an input field or division.
@param control element - the input field or div/span attached to the calendar
@param date Date - the new date
@return void */
setDateFor: function(control, date) {
var inst = this._getInst(control._calId);
if (inst) {
inst._setDate(date);
}
},
/* Retrieve the date for a calendar attached to an input field or division.
@param control element - the input field or div/span attached to the calendar
@return Date - the current date */
getDateFor: function(control) {
var inst = this._getInst(control._calId);
return (inst ? inst._getDate() : null);
},
/* Pop-up the calendar for a given input field.
@param target element - the input field attached to the calendar
@return void */
showFor: function(target) {
var input = (target.nodeName && target.nodeName.toLowerCase() == 'input' ? target : this);
if (input.nodeName.toLowerCase() != 'input') { // find from button/image trigger
input = $('input', input.parentNode)[0];
}
if (popUpCal._lastInput == input) { // already here
return;
}
for (var i = 0; i < popUpCal._disabledInputs.length; i++) { // check not disabled
if (popUpCal._disabledInputs[i] == input) {
return;
}
}
var inst = popUpCal._getInst(input._calId);
popUpCal.hideCalendar(inst, '');
popUpCal._lastInput = input;
inst._setDateFromField(input);
if (popUpCal._inDialog) { // hide cursor
input.value = '';
}
if (!popUpCal._pos) { // position below input
popUpCal._pos = popUpCal._findPos(input);
popUpCal._pos[1] += input.offsetHeight;
}
inst._calendarDiv.css('position', (popUpCal._inDialog && $.blockUI ? 'static' : 'absolute')).
css('left', popUpCal._pos[0] + 'px').css('top', popUpCal._pos[1] + 'px');
popUpCal._pos = null;
var fieldSettings = inst._get('fieldSettings');
$.extend(inst._settings, (fieldSettings ? fieldSettings(input) : {}));
popUpCal._showCalendar(inst);
},
/* Construct and display the calendar. */
_showCalendar: function(id) {
var inst = this._getInst(id);
popUpCal._updateCalendar(inst);
if (!inst._inline) {
var speed = inst._get('speed');
inst._calendarDiv.show(speed, function() {
popUpCal._popUpShowing = true;
popUpCal._afterShow(inst);
});
if (speed == '') {
popUpCal._popUpShowing = true;
popUpCal._afterShow(inst);
}
if (inst._input[0].type != 'hidden') {
inst._input[0].focus();
}
this._curInst = inst;
}
},
/* Generate the calendar content. */
_updateCalendar: function(inst) {
inst._calendarDiv.empty().append(inst._generateCalendar());
if (inst._input && inst._input != 'hidden') {
inst._input[0].focus();
}
},
/* Tidy up after displaying the calendar. */
_afterShow: function(inst) {
if ($.browser.msie) { // fix IE < 7 select problems
$('#calendar_cover').css({width: inst._calendarDiv[0].offsetWidth + 4,
height: inst._calendarDiv[0].offsetHeight + 4});
}
/*// re-position on screen if necessary
var calDiv = inst._calendarDiv[0];
var pos = popUpCal._findPos(inst._input[0]);
if ((calDiv.offsetLeft + calDiv.offsetWidth) >
(document.body.clientWidth + document.body.scrollLeft)) {
inst._calendarDiv.css('left', (pos[0] + inst._input[0].offsetWidth - calDiv.offsetWidth) + 'px');
}
if ((calDiv.offsetTop + calDiv.offsetHeight) >
(document.body.clientHeight + document.body.scrollTop)) {
inst._calendarDiv.css('top', (pos[1] - calDiv.offsetHeight) + 'px');
}*/
},
/* Hide the calendar from view.
@param id string/object - the ID of the current calendar instance,
or the instance itself
@param speed string - the speed at which to close the calendar
@return void */
hideCalendar: function(id, speed) {
var inst = this._getInst(id);
if (popUpCal._popUpShowing) {
speed = (speed != null ? speed : inst._get('speed'));
inst._calendarDiv.hide(speed, function() {
popUpCal._tidyDialog(inst);
});
if (speed == '') {
popUpCal._tidyDialog(inst);
}
popUpCal._popUpShowing = false;
popUpCal._lastInput = null;
inst._settings.prompt = null;
if (popUpCal._inDialog) {
popUpCal._dialogInput.css('position', 'absolute').
css('left', '0px').css('top', '-100px');
if ($.blockUI) {
$.unblockUI();
$('body').append(this._calendarDiv);
}
}
popUpCal._inDialog = false;
}
popUpCal._curInst = null;
},
/* Tidy up after a dialog display. */
_tidyDialog: function(inst) {
inst._calendarDiv.removeClass('calendar_dialog');
$('.calendar_prompt', inst._calendarDiv).remove();
},
/* Close calendar if clicked elsewhere. */
_checkExternalClick: function(event) {
if (!popUpCal._curInst) {
return;
}
var target = $(event.target);
if( (target.parents("#calendar_div").length == 0)
&& (target.attr('class') != 'calendar_trigger')
&& popUpCal._popUpShowing
&& !(popUpCal._inDialog && $.blockUI) )
{
popUpCal.hideCalendar(popUpCal._curInst, '');
}
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(id, offset, period) {
var inst = this._getInst(id);
inst._adjustDate(offset, period);
this._updateCalendar(inst);
},
/* Action for current link. */
_gotoToday: function(id) {
var date = new Date();
var inst = this._getInst(id);
inst._selectedDay = date.getDate();
inst._selectedMonth = date.getMonth();
inst._selectedYear = date.getFullYear();
this._adjustDate(inst);
},
/* Action for selecting a new month/year. */
_selectMonthYear: function(id, select, period) {
var inst = this._getInst(id);
inst._selectingMonthYear = false;
inst[period == 'M' ? '_selectedMonth' : '_selectedYear'] =
select.options[select.selectedIndex].value - 0;
this._adjustDate(inst);
},
/* Restore input focus after not changing month/year. */
_clickMonthYear: function(id) {
var inst = this._getInst(id);
if (inst._input && inst._selectingMonthYear && !$.browser.msie) {
inst._input[0].focus();
}
inst._selectingMonthYear = !inst._selectingMonthYear;
},
/* Action for changing the first week day. */
_changeFirstDay: function(id, a) {
var inst = this._getInst(id);
var dayNames = inst._get('dayNames');
var value = a.firstChild.nodeValue;
for (var i = 0; i < 7; i++) {
if (dayNames[i] == value) {
inst._settings.firstDay = i;
break;
}
}
this._updateCalendar(inst);
},
/* Action for selecting a day. */
_selectDay: function(id, td) {
var inst = this._getInst(id);
inst._selectedDay = $("a", td).html();
this._selectDate(id);
},
/* Erase the input field and hide the calendar. */
_clearDate: function(id) {
this._selectDate(id, '');
},
/* Update the input field with the selected date. */
_selectDate: function(id, dateStr) {
var inst = this._getInst(id);
dateStr = (dateStr != null ? dateStr : inst._formatDate());
if (inst._input) {
inst._input.val(dateStr);
}
var onSelect = inst._get('onSelect');
if (onSelect) {
onSelect(dateStr); // trigger custom callback
}
else {
inst._input.trigger('change'); // fire the change event
}
if (inst._inline) {
this._updateCalendar(inst);
}
else {
this.hideCalendar(inst, inst._get('speed'));
}
},
/* Set as customDate function to prevent selection of weekends.
@param date Date - the date to customise
@return [boolean, string] - is this date selectable?, what is its CSS class? */
noWeekends: function(date) {
var day = date.getDay();
return [(day > 0 && day < 6), ''];
},
/* Find an object's position on the screen. */
_findPos: function(obj) {
if (obj.type == 'hidden') {
obj = obj.nextSibling;
}
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
while (obj = obj.offsetParent) {
var origcurleft = curleft;
curleft += obj.offsetLeft;
if (curleft < 0) {
curleft = origcurleft;
}
curtop += obj.offsetTop;
}
}
return [curleft,curtop];
}
});
/* Individualised settings for calendars applied to one or more related inputs.
Instances are managed and manipulated through the PopUpCal manager. */
function PopUpCalInstance(settings, inline) {
this._id = popUpCal._register(this);
this._selectedDay = 0;
this._selectedMonth = 0; // 0-11
this._selectedYear = 0; // 4-digit year
this._input = null; // The attached input field
this._inline = inline; // True if showing inline, false if used in a popup
this._calendarDiv = (!inline ? popUpCal._calendarDiv :
$('<div id="calendar_div_' + this._id + '" class="calendar_inline"></div>'));
if (inline) {
var date = new Date();
this._currentDay = date.getDate();
this._currentMonth = date.getMonth();
this._currentYear = date.getFullYear();
}
// customise the calendar object - uses manager defaults if not overridden
this._settings = $.extend({}, settings || {}); // clone
}
$.extend(PopUpCalInstance.prototype, {
/* Get a setting value, defaulting if necessary. */
_get: function(name) {
return (this._settings[name] != null ? this._settings[name] : popUpCal._defaults[name]);
},
/* Parse existing date and initialise calendar. */
_setDateFromField: function(input) {
this._input = $(input);
var dateFormat = this._get('dateFormat');
var currentDate = this._input.val().split(dateFormat.charAt(3));
if (currentDate.length == 3) {
this._currentDay = parseInt(currentDate[dateFormat.indexOf('D')], 10);
this._currentMonth = parseInt(currentDate[dateFormat.indexOf('M')], 10) - 1;
this._currentYear = parseInt(currentDate[dateFormat.indexOf('Y')], 10);
}
else {
var date = new Date();
this._currentDay = date.getDate();
this._currentMonth = date.getMonth();
this._currentYear = date.getFullYear();
}
this._selectedDay = this._currentDay;
this._selectedMonth = this._currentMonth;
this._selectedYear = this._currentYear;
this._adjustDate();
},
/* Set the date directly. */
_setDate: function(date) {
this._selectedDay = this._currentDay = date.getDate();
this._selectedMonth = this._currentMonth = date.getMonth();
this._selectedYear = this._currentYear = date.getFullYear();
this._adjustDate();
},
/* Retrieve the date directly. */
_getDate: function() {
return new Date(this._currentYear, this._currentMonth, this._currentDay);
},
/* Generate the HTML for the current state of the calendar. */
_generateCalendar: function() {
var today = new Date();
today = new Date(today.getFullYear(), today.getMonth(), today.getDate()); // clear time
// build the calendar HTML
var controls = '<div class="calendar_control">' +
'<a class="calendar_clear" onclick="popUpCal._clearDate(' + this._id + ');">' +
this._get('clearText') + '</a>' +
'<a class="calendar_close" onclick="popUpCal.hideCalendar(' + this._id + ');">' +
this._get('closeText') + '</a></div>';
var prompt = this._get('prompt');
var closeAtTop = this._get('closeAtTop');
var hideIfNoPrevNext = this._get('hideIfNoPrevNext');
// controls and links
var html = (prompt ? '<div class="calendar_prompt">' + prompt + '</div>' : '') +
(closeAtTop && !this._inline ? controls : '') + '<div class="calendar_links">' +
(this._canAdjustMonth(-1) ? '<a class="calendar_prev" ' +
'onclick="popUpCal._adjustDate(' + this._id + ', -1, \'M\');">' + this._get('prevText') + '</a>' :
(hideIfNoPrevNext ? '' : '<label class="calendar_prev">' + this._get('prevText') + '</label>')) +
(this._isInRange(today) ? '<a class="calendar_current" ' +
'onclick="popUpCal._gotoToday(' + this._id + ');">' + this._get('currentText') + '</a>' : '') +
(this._canAdjustMonth(+1) ? '<a class="calendar_next" ' +
'onclick="popUpCal._adjustDate(' + this._id + ', +1, \'M\');">' + this._get('nextText') + '</a>' :
(hideIfNoPrevNext ? '' : '<label class="calendar_next">' + this._get('nextText') + '</label>')) +
'</div><div class="calendar_header">';
var minDate = this._get('minDate');
var maxDate = this._get('maxDate');
// month selection
var monthNames = this._get('monthNames');
if (!this._get('changeMonth')) {
html += monthNames[this._selectedMonth] + ' ';
}
else {
var inMinYear = (minDate && minDate.getFullYear() == this._selectedYear);
var inMaxYear = (maxDate && maxDate.getFullYear() == this._selectedYear);
html += '<select class="calendar_newMonth" ' +
'onchange="popUpCal._selectMonthYear(' + this._id + ', this, \'M\');" ' +
'onclick="popUpCal._clickMonthYear(' + this._id + ');">';
for (var month = 0; month < 12; month++) {
if ((!inMinYear || month >= minDate.getMonth()) &&
(!inMaxYear || month <= maxDate.getMonth())) {
html += '<option value="' + month + '"' +
(month == this._selectedMonth ? ' selected="selected"' : '') +
'>' + monthNames[month] + '</option>';
}
}
html += '</select>';
}
// year selection
if (!this._get('changeYear')) {
html += this._selectedYear;
}
else {
// determine range of years to display
var years = this._get('yearRange').split(':');
var year = 0;
var endYear = 0;
if (years.length != 2) {
year = this._selectedYear - 10;
endYear = this._selectedYear + 10;
}
else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
year = this._selectedYear + parseInt(years[0], 10);
endYear = this._selectedYear + parseInt(years[1], 10);
}
else {
year = parseInt(years[0], 10);
endYear = parseInt(years[1], 10);
}
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
html += '<select class="calendar_newYear" onchange="popUpCal._selectMonthYear(' +
this._id + ', this, \'Y\');" ' + 'onclick="popUpCal._clickMonthYear(' +
this._id + ');">';
for (; year <= endYear; year++) {
html += '<option value="' + year + '"' +
(year == this._selectedYear ? ' selected="selected"' : '') +
'>' + year + '</option>';
}
html += '</select>';
}
html += '</div><table class="calendar" cellpadding="0" cellspacing="0"><thead>' +
'<tr class="calendar_titleRow">';
var firstDay = this._get('firstDay');
var changeFirstDay = this._get('changeFirstDay');
var dayNames = this._get('dayNames');
for (var dow = 0; dow < 7; dow++) { // days of the week
html += '<td>' + (!changeFirstDay ? '' : '<a onclick="popUpCal._changeFirstDay(' +
this._id + ', this);">') + dayNames[(dow + firstDay) % 7] +
(changeFirstDay ? '</a>' : '') + '</td>';
}
html += '</tr></thead><tbody>';
var daysInMonth = this._getDaysInMonth(this._selectedYear, this._selectedMonth);
this._selectedDay = Math.min(this._selectedDay, daysInMonth);
var leadDays = (this._getFirstDayOfMonth(this._selectedYear, this._selectedMonth) - firstDay + 7) % 7;
var currentDate = new Date(this._currentYear, this._currentMonth, this._currentDay);
var selectedDate = new Date(this._selectedYear, this._selectedMonth, this._selectedDay);
var printDate = new Date(this._selectedYear, this._selectedMonth, 1 - leadDays);
var numRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
var customDate = this._get('customDate');
var showOtherMonths = this._get('showOtherMonths');
for (var row = 0; row < numRows; row++) { // create calendar rows
html += '<tr class="calendar_daysRow">';
for (var dow = 0; dow < 7; dow++) { // create calendar days
var customSettings = (customDate ? customDate(printDate) : [true, '']);
var otherMonth = (printDate.getMonth() != this._selectedMonth);
var unselectable = otherMonth || !customSettings[0] ||
(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
html += '<td class="calendar_daysCell' +
((dow + firstDay + 6) % 7 >= 5 ? ' calendar_weekEndCell' : '') + // highlight weekends
(otherMonth ? ' calendar_otherMonth' : '') + // highlight days from other months
(printDate.getTime() == selectedDate.getTime() ? ' calendar_daysCellOver' : '') + // highlight selected day
(unselectable ? ' calendar_unselectable' : '') + // highlight unselectable days
(!otherMonth || showOtherMonths ? ' ' + customSettings[1] : '') + // highlight custom dates
(printDate.getTime() == currentDate.getTime() ? ' calendar_currentDay' : // highlight current day
(printDate.getTime() == today.getTime() ? ' calendar_today' : '')) + '"' + // highlight today (if different)
(unselectable ? '' : ' onmouseover="$(this).addClass(\'calendar_daysCellOver\');"' +
' onmouseout="$(this).removeClass(\'calendar_daysCellOver\');"' +
' onclick="popUpCal._selectDay(' + this._id + ', this);"') + '>' + // actions
(otherMonth ? (showOtherMonths ? printDate.getDate() : ' ') : // display for other months
(unselectable ? printDate.getDate() : '<a>' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
printDate.setDate(printDate.getDate() + 1);
}
html += '</tr>';
}
html += '</tbody></table>' + (!closeAtTop && !this._inline ? controls : '') +
'<div style="clear: both;"></div>' + (!$.browser.msie ? '' :
'<!--[if lte IE 6.5]><iframe src="javascript:false;" class="calendar_cover"></iframe><![endif]-->');
return html;
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(offset, period) {
var date = new Date(this._selectedYear + (period == 'Y' ? offset : 0),
this._selectedMonth + (period == 'M' ? offset : 0),
this._selectedDay + (period == 'D' ? offset : 0));
// ensure it is within the bounds set
var minDate = this._get('minDate');
var maxDate = this._get('maxDate');
date = (minDate && date < minDate ? minDate : date);
date = (maxDate && date > maxDate ? maxDate : date);
this._selectedDay = date.getDate();
this._selectedMonth = date.getMonth();
this._selectedYear = date.getFullYear();
},
/* Find the number of days in a given month. */
_getDaysInMonth: function(year, month) {
return 32 - new Date(year, month, 32).getDate();
},
/* Find the day of the week of the first of a month. */
_getFirstDayOfMonth: function(year, month) {
return new Date(year, month, 1).getDay();
},
/* Determines if we should allow a "next/prev" month display change. */
_canAdjustMonth: function(offset) {
var date = new Date(this._selectedYear, this._selectedMonth + offset, 1);
if (offset < 0) {
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
}
return this._isInRange(date);
},
/* Is the given date in the accepted range? */
_isInRange: function(date) {
var minDate = this._get('minDate');
var maxDate = this._get('maxDate');
return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
},
/* Format the given date for display. */
_formatDate: function() {
var day = this._currentDay = this._selectedDay;
var month = this._currentMonth = this._selectedMonth;
var year = this._currentYear = this._selectedYear;
month++; // adjust javascript month
var dateFormat = this._get('dateFormat');
var dateString = '';
for (var i = 0; i < 3; i++) {
dateString += dateFormat.charAt(3) +
(dateFormat.charAt(i) == 'D' ? (day < 10 ? '0' : '') + day :
(dateFormat.charAt(i) == 'M' ? (month < 10 ? '0' : '') + month :
(dateFormat.charAt(i) == 'Y' ? year : '?')));
}
return dateString.substring(dateFormat.charAt(3) ? 1 : 0);
}
});
/* Attach the calendar to a jQuery selection.
@param settings object - the new settings to use for this calendar instance (anonymous)
@return jQuery object - for chaining further calls */
$.fn.calendar = function(settings) {
return this.each(function() {
// check for settings on the control itself - in namespace 'cal:'
var inlineSettings = null;
for (attrName in popUpCal._defaults) {
var attrValue = this.getAttribute('cal:' + attrName);
if (attrValue) {
inlineSettings = inlineSettings || {};
try {
inlineSettings[attrName] = eval(attrValue);
}
catch (err) {
inlineSettings[attrName] = attrValue;
}
}
}
var nodeName = this.nodeName.toLowerCase();
if (nodeName == 'input') {
var instSettings = (inlineSettings ? $.extend($.extend({}, settings || {}),
inlineSettings || {}) : settings); // clone and customise
var inst = (inst && !inlineSettings ? inst :
new PopUpCalInstance(instSettings, false));
popUpCal._connectCalendar(this, inst);
}
else if (nodeName == 'div' || nodeName == 'span') {
var instSettings = $.extend($.extend({}, settings || {}),
inlineSettings || {}); // clone and customise
var inst = new PopUpCalInstance(instSettings, true);
popUpCal._inlineCalendar(this, inst);
}
});
};
/* Initialise the calendar. */
$(document).ready(function() {
popUpCal = new PopUpCal(); // singleton instance
});
|
gpl-2.0
|
Fluorohydride/ygopro-scripts
|
c612115.lua
|
2625
|
--剣闘獣レティアリィ
function c612115.initial_effect(c)
--remove
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(612115,0))
e1:SetCategory(CATEGORY_REMOVE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(aux.gbspcon)
e1:SetTarget(c612115.rmtg)
e1:SetOperation(c612115.rmop)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(612115,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_PHASE+PHASE_BATTLE)
e2:SetRange(LOCATION_MZONE)
e2:SetCondition(c612115.spcon)
e2:SetCost(c612115.spcost)
e2:SetTarget(c612115.sptg)
e2:SetOperation(c612115.spop)
c:RegisterEffect(e2)
end
function c612115.rmtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(1-tp) and chkc:IsAbleToRemove() end
if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,g:GetCount(),1-tp,LOCATION_GRAVE)
end
function c612115.rmop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
end
end
function c612115.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetBattledGroupCount()>0
end
function c612115.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsAbleToDeckAsCost() end
Duel.SendtoDeck(c,nil,SEQ_DECKSHUFFLE,REASON_COST)
end
function c612115.filter(c,e,tp)
return not c:IsCode(612115) and c:IsSetCard(0x19) and c:IsCanBeSpecialSummoned(e,SUMMON_VALUE_GLADIATOR,tp,false,false)
end
function c612115.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and Duel.IsExistingMatchingCard(c612115.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c612115.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c612115.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
local tc=g:GetFirst()
if tc then
Duel.SpecialSummon(tc,SUMMON_VALUE_GLADIATOR,tp,tp,false,false,POS_FACEUP)
tc:RegisterFlagEffect(tc:GetOriginalCode(),RESET_EVENT+RESETS_STANDARD+RESET_DISABLE,0,0)
end
end
|
gpl-2.0
|
ndubey/mysql-php-song-database
|
deleteSong.php
|
313
|
<?php
include 'library/dbconnect.php';
if($_GET["cmd"]=="delete")
{
$id=$_GET['id'];
if (empty($id)) {
Header("Location: listSong.php");
exit;
}
$query = "DELETE FROM Songs WHERE SongId=$id";
$result = mysql_query($query);
Header("Location: listSong.php");
exit;
}
?>
|
gpl-2.0
|
saravanaizeno/skizwordpress
|
wp-content/cache/config/master.php
|
21039
|
<?php
return array(
'version' => '0.9.3',
'cluster.messagebus.debug' => false,
'cluster.messagebus.enabled' => false,
'cluster.messagebus.sns.region' => '',
'cluster.messagebus.sns.api_key' => '',
'cluster.messagebus.sns.api_secret' => '',
'cluster.messagebus.sns.topic_arn' => '',
'dbcache.debug' => false,
'dbcache.enabled' => false,
'dbcache.engine' => 'file',
'dbcache.file.gc' => 3600,
'dbcache.file.locking' => false,
'dbcache.lifetime' => 180,
'dbcache.memcached.persistant' => true,
'dbcache.memcached.servers' => array(
0 => '127.0.0.1:11211',
),
'dbcache.reject.cookie' => array(
),
'dbcache.reject.logged' => true,
'dbcache.reject.sql' => array(
0 => 'gdsr_',
1 => 'wp_rg_',
),
'dbcache.reject.uri' => array(
),
'dbcache.reject.words' => array(
0 => '^\\s*insert\\b',
1 => '^\\s*delete\\b',
2 => '^\\s*update\\b',
3 => '^\\s*replace\\b',
4 => '^\\s*create\\b',
5 => '^\\s*alter\\b',
6 => '^\\s*show\\b',
7 => '^\\s*set\\b',
8 => '\\bautoload\\s+=\\s+\'yes\'',
9 => '\\bsql_calc_found_rows\\b',
10 => '\\bfound_rows\\(\\)',
11 => '\\bw3tc_request_data\\b',
),
'objectcache.enabled' => false,
'objectcache.debug' => false,
'objectcache.engine' => 'file',
'objectcache.file.gc' => 3600,
'objectcache.file.locking' => false,
'objectcache.memcached.servers' => array(
0 => '127.0.0.1:11211',
),
'objectcache.memcached.persistant' => true,
'objectcache.groups.global' => array(
0 => 'users',
1 => 'userlogins',
2 => 'usermeta',
3 => 'user_meta',
4 => 'site-transient',
5 => 'site-options',
6 => 'site-lookup',
7 => 'blog-lookup',
8 => 'blog-details',
9 => 'rss',
10 => 'global-posts',
),
'objectcache.groups.nonpersistent' => array(
0 => 'comment',
1 => 'counts',
2 => 'plugins',
),
'objectcache.lifetime' => 180,
'objectcache.purge.all' => false,
'fragmentcache.enabled' => false,
'fragmentcache.debug' => false,
'fragmentcache.engine' => 'file',
'fragmentcache.file.gc' => 3600,
'fragmentcache.file.locking' => false,
'fragmentcache.memcached.servers' => array(
0 => '127.0.0.1:11211',
),
'fragmentcache.memcached.persistant' => true,
'fragmentcache.lifetime' => 180,
'fragmentcache.groups' => array(
),
'pgcache.enabled' => false,
'pgcache.comment_cookie_ttl' => 1800,
'pgcache.debug' => false,
'pgcache.engine' => 'file_generic',
'pgcache.file.gc' => 3600,
'pgcache.file.nfs' => false,
'pgcache.file.locking' => false,
'pgcache.lifetime' => 3600,
'pgcache.memcached.servers' => array(
0 => '127.0.0.1:11211',
),
'pgcache.memcached.persistant' => true,
'pgcache.check.domain' => false,
'pgcache.cache.query' => false,
'pgcache.cache.home' => true,
'pgcache.cache.feed' => false,
'pgcache.cache.nginx_handle_xml' => false,
'pgcache.cache.ssl' => false,
'pgcache.cache.404' => false,
'pgcache.cache.flush' => false,
'pgcache.cache.headers' => array(
0 => 'Last-Modified',
1 => 'Content-Type',
2 => 'X-Pingback',
3 => 'P3P',
),
'pgcache.compatibility' => false,
'pgcache.remove_charset' => false,
'pgcache.accept.uri' => array(
0 => 'sitemap(_index)?\\.xml(\\.gz)?',
1 => '[a-z0-9_\\-]+-sitemap([0-9]+)?\\.xml(\\.gz)?',
),
'pgcache.accept.files' => array(
0 => 'wp-comments-popup.php',
1 => 'wp-links-opml.php',
2 => 'wp-locations.php',
),
'pgcache.accept.qs' => array(
),
'pgcache.reject.front_page' => false,
'pgcache.reject.logged' => true,
'pgcache.reject.logged_roles' => false,
'pgcache.reject.roles' => array(
),
'pgcache.reject.uri' => array(
0 => 'wp-.*\\.php',
1 => 'index\\.php',
),
'pgcache.reject.ua' => array(
),
'pgcache.reject.cookie' => array(
0 => 'wptouch_switch_toggle',
),
'pgcache.reject.request_head' => false,
'pgcache.purge.front_page' => false,
'pgcache.purge.home' => true,
'pgcache.purge.post' => true,
'pgcache.purge.comments' => false,
'pgcache.purge.author' => false,
'pgcache.purge.terms' => false,
'pgcache.purge.archive.daily' => false,
'pgcache.purge.archive.monthly' => false,
'pgcache.purge.archive.yearly' => false,
'pgcache.purge.feed.blog' => true,
'pgcache.purge.feed.comments' => false,
'pgcache.purge.feed.author' => false,
'pgcache.purge.feed.terms' => false,
'pgcache.purge.feed.types' => array(
0 => 'rss2',
),
'pgcache.purge.postpages_limit' => 10,
'pgcache.purge.pages' => array(
),
'pgcache.purge.sitemap_regex' => '([a-z0-9_\\-]*?)sitemap([a-z0-9_\\-]*)?\\.xml',
'pgcache.prime.enabled' => false,
'pgcache.prime.interval' => 900,
'pgcache.prime.limit' => 10,
'pgcache.prime.sitemap' => '',
'pgcache.prime.post.enabled' => false,
'minify.enabled' => false,
'minify.auto' => true,
'minify.debug' => false,
'minify.engine' => 'file',
'minify.file.gc' => 86400,
'minify.file.nfs' => false,
'minify.file.locking' => false,
'minify.memcached.servers' => array(
0 => '127.0.0.1:11211',
),
'minify.memcached.persistant' => true,
'minify.rewrite' => true,
'minify.options' => array(
),
'minify.symlinks' => array(
),
'minify.lifetime' => 86400,
'minify.upload' => true,
'minify.html.enable' => false,
'minify.html.engine' => 'html',
'minify.html.reject.feed' => false,
'minify.html.inline.css' => false,
'minify.html.inline.js' => false,
'minify.html.strip.crlf' => false,
'minify.html.comments.ignore' => array(
0 => 'google_ad_',
1 => 'RSPEAK_',
),
'minify.css.enable' => true,
'minify.css.engine' => 'css',
'minify.css.combine' => false,
'minify.css.strip.comments' => false,
'minify.css.strip.crlf' => false,
'minify.css.imports' => '',
'minify.css.groups' => array(
),
'minify.js.enable' => true,
'minify.js.engine' => 'js',
'minify.js.combine.header' => false,
'minify.js.header.embed_type' => 'blocking',
'minify.js.combine.body' => false,
'minify.js.body.embed_type' => 'blocking',
'minify.js.combine.footer' => false,
'minify.js.footer.embed_type' => 'blocking',
'minify.js.strip.comments' => false,
'minify.js.strip.crlf' => false,
'minify.js.groups' => array(
),
'minify.yuijs.path.java' => 'java',
'minify.yuijs.path.jar' => 'yuicompressor.jar',
'minify.yuijs.options.line-break' => 5000,
'minify.yuijs.options.nomunge' => false,
'minify.yuijs.options.preserve-semi' => false,
'minify.yuijs.options.disable-optimizations' => false,
'minify.yuicss.path.java' => 'java',
'minify.yuicss.path.jar' => 'yuicompressor.jar',
'minify.yuicss.options.line-break' => 5000,
'minify.ccjs.path.java' => 'java',
'minify.ccjs.path.jar' => 'compiler.jar',
'minify.ccjs.options.compilation_level' => 'SIMPLE_OPTIMIZATIONS',
'minify.ccjs.options.formatting' => '',
'minify.csstidy.options.remove_bslash' => true,
'minify.csstidy.options.compress_colors' => true,
'minify.csstidy.options.compress_font-weight' => true,
'minify.csstidy.options.lowercase_s' => false,
'minify.csstidy.options.optimise_shorthands' => 1,
'minify.csstidy.options.remove_last_;' => false,
'minify.csstidy.options.case_properties' => 1,
'minify.csstidy.options.sort_properties' => false,
'minify.csstidy.options.sort_selectors' => false,
'minify.csstidy.options.merge_selectors' => 2,
'minify.csstidy.options.discard_invalid_properties' => false,
'minify.csstidy.options.css_level' => 'CSS2.1',
'minify.csstidy.options.preserve_css' => false,
'minify.csstidy.options.timestamp' => false,
'minify.csstidy.options.template' => 'default',
'minify.htmltidy.options.clean' => false,
'minify.htmltidy.options.hide-comments' => true,
'minify.htmltidy.options.wrap' => 0,
'minify.reject.logged' => false,
'minify.reject.ua' => array(
),
'minify.reject.uri' => array(
),
'minify.reject.files.js' => array(
),
'minify.reject.files.css' => array(
),
'minify.cache.files' => array(
0 => 'https://ajax.googleapis.com',
),
'cdn.enabled' => false,
'cdn.debug' => false,
'cdn.engine' => 'maxcdn',
'cdn.uploads.enable' => true,
'cdn.includes.enable' => true,
'cdn.includes.files' => '*.css;*.js;*.gif;*.png;*.jpg;*.xml',
'cdn.theme.enable' => true,
'cdn.theme.files' => '*.css;*.js;*.gif;*.png;*.jpg;*.ico;*.ttf;*.otf,*.woff',
'cdn.minify.enable' => true,
'cdn.custom.enable' => true,
'cdn.custom.files' => array(
0 => 'favicon.ico',
1 => '{wp_content_dir}/gallery/*',
2 => '{wp_content_dir}/uploads/avatars/*',
3 => '{plugins_dir}/wordpress-seo/css/xml-sitemap.xsl',
4 => '{plugins_dir}/wp-minify/min*',
5 => '{plugins_dir}/*.js',
6 => '{plugins_dir}/*.css',
7 => '{plugins_dir}/*.gif',
8 => '{plugins_dir}/*.jpg',
9 => '{plugins_dir}/*.png',
),
'cdn.import.external' => false,
'cdn.import.files' => '',
'cdn.queue.interval' => 900,
'cdn.queue.limit' => 25,
'cdn.force.rewrite' => false,
'cdn.autoupload.enabled' => false,
'cdn.autoupload.interval' => 3600,
'cdn.canonical_header' => false,
'cdn.ftp.host' => '',
'cdn.ftp.user' => '',
'cdn.ftp.pass' => '',
'cdn.ftp.path' => '',
'cdn.ftp.pasv' => false,
'cdn.ftp.domain' => array(
),
'cdn.ftp.ssl' => 'auto',
'cdn.s3.key' => '',
'cdn.s3.secret' => '',
'cdn.s3.bucket' => '',
'cdn.s3.cname' => array(
),
'cdn.s3.ssl' => 'auto',
'cdn.cf.key' => '',
'cdn.cf.secret' => '',
'cdn.cf.bucket' => '',
'cdn.cf.id' => '',
'cdn.cf.cname' => array(
),
'cdn.cf.ssl' => 'auto',
'cdn.cf2.key' => '',
'cdn.cf2.secret' => '',
'cdn.cf2.id' => '',
'cdn.cf2.cname' => array(
),
'cdn.cf2.ssl' => '',
'cdn.rscf.user' => '',
'cdn.rscf.key' => '',
'cdn.rscf.location' => 'us',
'cdn.rscf.container' => '',
'cdn.rscf.cname' => array(
),
'cdn.rscf.ssl' => 'auto',
'cdn.azure.user' => '',
'cdn.azure.key' => '',
'cdn.azure.container' => '',
'cdn.azure.cname' => array(
),
'cdn.azure.ssl' => 'auto',
'cdn.mirror.domain' => array(
),
'cdn.mirror.ssl' => 'auto',
'cdn.netdna.alias' => '',
'cdn.netdna.consumerkey' => '',
'cdn.netdna.consumersecret' => '',
'cdn.netdna.authorization_key' => '',
'cdn.netdna.domain' => array(
),
'cdn.netdna.ssl' => 'auto',
'cdn.netdna.zone_id' => 0,
'cdn.maxcdn.authorization_key' => '',
'cdn.maxcdn.domain' => array(
),
'cdn.maxcdn.ssl' => 'auto',
'cdn.maxcdn.zone_id' => 0,
'cdn.cotendo.username' => '',
'cdn.cotendo.password' => '',
'cdn.cotendo.zones' => array(
),
'cdn.cotendo.domain' => array(
),
'cdn.cotendo.ssl' => 'auto',
'cdn.akamai.username' => '',
'cdn.akamai.password' => '',
'cdn.akamai.email_notification' => array(
),
'cdn.akamai.action' => 'invalidate',
'cdn.akamai.zone' => 'production',
'cdn.akamai.domain' => array(
),
'cdn.akamai.ssl' => 'auto',
'cdn.edgecast.account' => '',
'cdn.edgecast.token' => '',
'cdn.edgecast.domain' => array(
),
'cdn.edgecast.ssl' => 'auto',
'cdn.att.account' => '',
'cdn.att.token' => '',
'cdn.att.domain' => array(
),
'cdn.att.ssl' => 'auto',
'cdn.reject.admins' => false,
'cdn.reject.logged_roles' => false,
'cdn.reject.roles' => array(
),
'cdn.reject.ua' => array(
),
'cdn.reject.uri' => array(
),
'cdn.reject.files' => array(
0 => '{uploads_dir}/wpcf7_captcha/*',
1 => '{uploads_dir}/imagerotator.swf',
2 => '{plugins_dir}/wp-fb-autoconnect/facebook-platform/channel.html',
),
'cdn.reject.ssl' => false,
'cdncache.enabled' => false,
'cloudflare.enabled' => false,
'cloudflare.email' => '',
'cloudflare.key' => '',
'cloudflare.zone' => '',
'cloudflare.ips.ip4' => array(
0 => '204.93.240.0/24',
1 => '204.93.177.0/24',
2 => '199.27.128.0/21',
3 => '173.245.48.0/20',
4 => '103.22.200.0/22',
5 => '141.101.64.0/18',
6 => '108.162.192.0/18',
7 => '190.93.240.1/20',
8 => '188.114.96.0/20',
9 => '198.41.128.0/17',
),
'cloudflare.ips.ip6' => array(
0 => '2400:cb00::/32',
1 => '2606:4700::/32',
2 => '2803:f800::/32',
),
'varnish.enabled' => false,
'varnish.debug' => false,
'varnish.servers' => array(
),
'browsercache.enabled' => true,
'browsercache.no404wp' => false,
'browsercache.no404wp.exceptions' => array(
0 => 'robots\\.txt',
1 => 'sitemap(_index)?\\.xml(\\.gz)?',
2 => '[a-z0-9_\\-]+-sitemap([0-9]+)?\\.xml(\\.gz)?',
),
'browsercache.cssjs.last_modified' => true,
'browsercache.cssjs.compression' => true,
'browsercache.cssjs.expires' => false,
'browsercache.cssjs.lifetime' => 31536000,
'browsercache.cssjs.nocookies' => false,
'browsercache.cssjs.cache.control' => false,
'browsercache.cssjs.cache.policy' => 'cache_public_maxage',
'browsercache.cssjs.etag' => false,
'browsercache.cssjs.w3tc' => false,
'browsercache.cssjs.replace' => false,
'browsercache.html.compression' => true,
'browsercache.html.last_modified' => true,
'browsercache.html.expires' => false,
'browsercache.html.lifetime' => 3600,
'browsercache.html.cache.control' => false,
'browsercache.html.cache.policy' => 'cache_public_maxage',
'browsercache.html.etag' => false,
'browsercache.html.w3tc' => false,
'browsercache.html.replace' => false,
'browsercache.other.last_modified' => true,
'browsercache.other.compression' => true,
'browsercache.other.expires' => false,
'browsercache.other.lifetime' => 31536000,
'browsercache.other.nocookies' => false,
'browsercache.other.cache.control' => false,
'browsercache.other.cache.policy' => 'cache_public_maxage',
'browsercache.other.etag' => false,
'browsercache.other.w3tc' => false,
'browsercache.other.replace' => false,
'browsercache.timestamp' => '',
'browsercache.replace.exceptions' => array(
),
'mobile.enabled' => false,
'mobile.rgroups' => array(
'high' => array(
'theme' => '',
'enabled' => false,
'redirect' => '',
'agents' => array(
0 => 'acer\\ s100',
1 => 'android',
2 => 'archos5',
3 => 'bada',
4 => 'bb10',
5 => 'blackberry9500',
6 => 'blackberry9530',
7 => 'blackberry9550',
8 => 'blackberry\\ 9800',
9 => 'cupcake',
10 => 'docomo\\ ht\\-03a',
11 => 'dream',
12 => 'froyo',
13 => 'googlebot-mobile',
14 => 'htc\\ hero',
15 => 'htc\\ magic',
16 => 'htc_dream',
17 => 'htc_magic',
18 => 'iemobile/7.0',
19 => 'incognito',
20 => 'ipad',
21 => 'iphone',
22 => 'ipod',
23 => 'kindle',
24 => 'lg\\-gw620',
25 => 'liquid\\ build',
26 => 'maemo',
27 => 'mot\\-mb200',
28 => 'mot\\-mb300',
29 => 'nexus\\ one',
30 => 'nexus\\ 7',
31 => 'opera\\ mini',
32 => 's8000',
33 => 'samsung\\-s8000',
34 => 'series60.*webkit',
35 => 'series60/5\\.0',
36 => 'sonyericssone10',
37 => 'sonyericssonu20',
38 => 'sonyericssonx10',
39 => 't\\-mobile\\ mytouch\\ 3g',
40 => 't\\-mobile\\ opal',
41 => 'tattoo',
42 => 'touch',
43 => 'webmate',
44 => 'webos',
),
),
'low' => array(
'theme' => '',
'enabled' => false,
'redirect' => '',
'agents' => array(
0 => '2\\.0\\ mmp',
1 => '240x320',
2 => 'alcatel',
3 => 'amoi',
4 => 'asus',
5 => 'au\\-mic',
6 => 'audiovox',
7 => 'avantgo',
8 => 'bb10',
9 => 'benq',
10 => 'bird',
11 => 'blackberry',
12 => 'blazer',
13 => 'cdm',
14 => 'cellphone',
15 => 'danger',
16 => 'ddipocket',
17 => 'docomo',
18 => 'dopod',
19 => 'elaine/3\\.0',
20 => 'ericsson',
21 => 'eudoraweb',
22 => 'fly',
23 => 'haier',
24 => 'hiptop',
25 => 'hp\\.ipaq',
26 => 'htc',
27 => 'huawei',
28 => 'i\\-mobile',
29 => 'iemobile',
30 => 'iemobile/7',
31 => 'iemobile/9',
32 => 'j\\-phone',
33 => 'kddi',
34 => 'konka',
35 => 'kwc',
36 => 'kyocera/wx310k',
37 => 'lenovo',
38 => 'lg',
39 => 'lg/u990',
40 => 'lge\\ vx',
41 => 'midp',
42 => 'midp\\-2\\.0',
43 => 'mmef20',
44 => 'mmp',
45 => 'mobilephone',
46 => 'mot\\-v',
47 => 'motorola',
48 => 'msie\\ 10\\.0',
49 => 'netfront',
50 => 'newgen',
51 => 'newt',
52 => 'nintendo\\ ds',
53 => 'nintendo\\ wii',
54 => 'nitro',
55 => 'nokia',
56 => 'novarra',
57 => 'o2',
58 => 'openweb',
59 => 'opera\\ mobi',
60 => 'opera\\.mobi',
61 => 'p160u',
62 => 'palm',
63 => 'panasonic',
64 => 'pantech',
65 => 'pdxgw',
66 => 'pg',
67 => 'philips',
68 => 'phone',
69 => 'playbook',
70 => 'playstation\\ portable',
71 => 'portalmmm',
72 => '\\bppc\\b',
73 => 'proxinet',
74 => 'psp',
75 => 'qtek',
76 => 'sagem',
77 => 'samsung',
78 => 'sanyo',
79 => 'sch',
80 => 'sch\\-i800',
81 => 'sec',
82 => 'sendo',
83 => 'sgh',
84 => 'sharp',
85 => 'sharp\\-tq\\-gx10',
86 => 'small',
87 => 'smartphone',
88 => 'softbank',
89 => 'sonyericsson',
90 => 'sph',
91 => 'symbian',
92 => 'symbian\\ os',
93 => 'symbianos',
94 => 'toshiba',
95 => 'treo',
96 => 'ts21i\\-10',
97 => 'up\\.browser',
98 => 'up\\.link',
99 => 'uts',
100 => 'vertu',
101 => 'vodafone',
102 => 'wap',
103 => 'willcome',
104 => 'windows\\ ce',
105 => 'windows\\.ce',
106 => 'winwap',
107 => 'xda',
108 => 'xoom',
109 => 'zte',
),
),
),
'referrer.enabled' => false,
'referrer.rgroups' => array(
'search_engines' => array(
'theme' => '',
'enabled' => false,
'redirect' => '',
'referrers' => array(
0 => 'google\\.com',
1 => 'yahoo\\.com',
2 => 'bing\\.com',
3 => 'ask\\.com',
4 => 'msn\\.com',
),
),
),
'common.support' => '',
'common.install' => 0,
'common.tweeted' => false,
'config.check' => true,
'config.path' => '',
'widget.latest.items' => 3,
'widget.latest_news.items' => 5,
'widget.pagespeed.enabled' => true,
'widget.pagespeed.key' => '',
'notes.wp_content_changed_perms' => true,
'notes.wp_content_perms' => true,
'notes.theme_changed' => false,
'notes.wp_upgraded' => false,
'notes.plugins_updated' => false,
'notes.cdn_upload' => false,
'notes.cdn_reupload' => false,
'notes.need_empty_pgcache' => false,
'notes.need_empty_minify' => false,
'notes.need_empty_objectcache' => false,
'notes.root_rules' => true,
'notes.rules' => true,
'notes.pgcache_rules_wpsc' => true,
'notes.support_us' => true,
'notes.no_curl' => true,
'notes.no_zlib' => true,
'notes.zlib_output_compression' => true,
'notes.no_permalink_rules' => true,
'notes.browsercache_rules_no404wp' => true,
'notes.cloudflare_plugin' => true,
'timelimit.email_send' => 180,
'timelimit.varnish_purge' => 300,
'timelimit.cache_flush' => 600,
'timelimit.cache_gc' => 600,
'timelimit.cdn_upload' => 600,
'timelimit.cdn_delete' => 300,
'timelimit.cdn_purge' => 300,
'timelimit.cdn_import' => 600,
'timelimit.cdn_test' => 300,
'timelimit.cdn_container_create' => 300,
'timelimit.cloudflare_api_request' => 180,
'timelimit.domain_rename' => 120,
'timelimit.minify_recommendations' => 600,
'minify.auto.filename_length' => 150,
'minify.auto.disable_filename_length_test' => false,
'common.instance_id' => 434477010,
'common.force_master' => true,
'newrelic.enabled' => false,
'newrelic.api_key' => '',
'newrelic.account_id' => '',
'newrelic.application_id' => 0,
'newrelic.appname' => '',
'newrelic.accept.logged_roles' => true,
'newrelic.accept.roles' => array(
0 => 'contributor',
),
'newrelic.use_php_function' => true,
'notes.new_relic_page_load_notification' => true,
'newrelic.appname_prefix' => 'Child Site - ',
'newrelic.merge_with_network' => true,
'newrelic.cache_time' => 5,
'newrelic.enable_xmit' => false,
'newrelic.use_network_wide_id' => false,
'pgcache.late_init' => false,
'newrelic.include_rum' => true,
'extensions.settings' => array(
'genesis.theme' => array(
'wp_head' => '0',
'genesis_header' => '1',
'genesis_do_nav' => '1',
'genesis_do_subnav' => '1',
'loop_front_page' => '1',
'loop_single' => '1',
'loop_single_excluded' => '',
'loop_single_genesis_comments' => '0',
'loop_single_genesis_pings' => '0',
'sidebar' => '0',
'sidebar_excluded' => '',
'genesis_footer' => '1',
'wp_footer' => '0',
'fragment_reject_logged_roles' => '1',
'fragment_reject_logged_roles_on_actions' => array(
0 => 'genesis_loop',
1 => 'wp_head',
2 => 'wp_footer',
),
'fragment_reject_roles' => array(
0 => 'administrator',
),
),
),
'extensions.active' => array(
),
'plugin.license_key' => '',
'plugin.type' => '',
'wordpress.home' => 'http://ec2-54-251-196-138.ap-southeast-1.compute.amazonaws.com/izwordpress',
'pgcache.bad_behavior_path' => '',
);
|
gpl-2.0
|
srcman/blackhawk
|
utils/ethrecv.py
|
1355
|
#!/usr/local/bin/python2.6
#
# Copyright (C) 2009-2010, Oy L M Ericsson Ab, NomadicLab.
# All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version
# 2 as published by the Free Software Foundation.
#
# Alternatively, this software may be distributed under the terms of
# the BSD license.
#
# See LICENSE and COPYING for more details.
#
# Packet receiver utility
# -----------------------
#
# Do note that this is a FreeBSD version that requires that the
# libpsirp API for Python is compiled with socket support enabled and
# that the psfs kernel module is loaded.
from psirp.libpsirp_py import *
import time
iface = "em1"
n = 10
verbose=False
def main():
sockdata = psirp_py_sock_create(iface)
sock = sockdata.sock
try:
print("Receiving (n = %d, iface=%s)..." % (n, iface))
while True:
t1 = time.time()
for i in xrange(n):
data = psirp_py_sock_recv(sockdata, 1500)
if (verbose):
print("Received %d bytes" % data[0])
t2 = time.time()
print("Received: %f bytes/s" % ((n*1500)/(t2-t1)))
except (KeyboardInterrupt, SystemExit):
pass
psirp_py_sock_close(sockdata)
if __name__ == "__main__":
main()
|
gpl-2.0
|
withlovee/Sport-Complex-Reservation-System
|
ui-admin/system-success.php
|
2018
|
<?php include('header.php'); ?>
<h2>ตั้งค่าระบบ</h2>
<div class="row">
<div class="col-md-9" id="content-view">
<div class="alert alert-success"><strong>ปรับปรุงการตั้งค่าเสร็จสมบูรณ์แล้ว</strong></div>
<div class="thread">
<div class="context">
<form class="form-horizontal" role="form" action="system-success.php">
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label">สถานะระบบ</label>
<div class="col-sm-8">
<select name="" id="" class="form-control">
<option value="">เปิด</option>
<option value="">ปิด</option>
</select>
</div>
</div><!--form-group-->
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label">ระงับผู้ใช้อัตโนมัติเมื่อไม่ได้เข้าใช้เกิน (ครั้ง/เดือน)</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="inputEmail3" placeholder="5" value="5">
</div>
</div><!--form-group-->
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label">ระงับผู้ใช้อัตโนมัติเป็นเวลา (วัน)</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="inputEmail3" placeholder="5" value="5">
</div>
</div><!--form-group-->
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" class="btn btn-primary">ปรับปรุงการตั้งค่า</button>
</div>
</div>
</form>
</div><!--context-->
</div><!--thread-->
</div><!--content-->
<?php include('sidebar.php'); ?>
</div><!--row-->
<?php include('footer.php'); ?>
|
gpl-2.0
|
mschnitzer/open-build-service
|
src/api/spec/controllers/webui/cloud/ec2/upload_jobs_controller_spec.rb
|
4982
|
require 'rails_helper'
require 'webmock/rspec'
RSpec.describe Webui::Cloud::Ec2::UploadJobsController, type: :controller, vcr: true do
let!(:ec2_configuration) { create(:ec2_configuration) }
let!(:user_with_ec2_configuration) { create(:confirmed_user, login: 'tom', ec2_configuration: ec2_configuration) }
let(:project) { create(:project, name: 'EC2Images') }
let!(:package) { create(:package, name: 'MyEC2Image', project: project) }
let(:upload_job) { create(:upload_job, user: user_with_ec2_configuration) }
let(:xml_response) do
<<-HEREDOC
<clouduploadjob name="6">
<state>created</state>
<details>waiting to receive image</details>
<created>1513604055</created>
<user>mlschroe</user>
<target>ec2</target>
<project>Base:System</project>
<repository>openSUSE_Factory</repository>
<package>rpm</package>
<arch>x86_64</arch>
<filename>rpm-4.14.0-504.2.x86_64.rpm</filename>
<size>1690860</size>
</clouduploadjob>
HEREDOC
end
before do
login(user_with_ec2_configuration)
end
describe 'GET #new' do
context 'with valid parameters' do
before do
Feature.run_with_activated(:cloud_upload) do
get :new, params: { project: 'EC2Images', package: 'MyEC2Image', repository: 'standard', arch: 'x86_64', filename: 'appliance.raw.xz' }
end
end
it { expect(response).to be_success }
it {
expect(assigns(:upload_job)).
to have_attributes(project: 'EC2Images', package: 'MyEC2Image', repository: 'standard', arch: 'x86_64', filename: 'appliance.raw.xz')
}
end
context 'with invalid parameters' do
shared_context 'it redirects and assigns flash error' do
before do
Feature.run_with_activated(:cloud_upload) do
get :new, params: params
end
end
it { expect(flash[:error]).not_to be_nil }
it { expect(response).to be_redirect }
end
context 'with a not existing package' do
let(:params) { { project: 'EC2Images', package: 'not-existent', repository: 'standard', arch: 'x86_64', filename: 'appliance.raw.xz' } }
include_context 'it redirects and assigns flash error'
end
context 'with an invalid filename' do
let(:params) { { project: 'EC2Images', package: 'MyEC2Image', repository: 'standard', arch: 'x86_64', filename: 'appliance.rpm' } }
include_context 'it redirects and assigns flash error'
end
context 'with an invalid architecture' do
let(:params) { { project: 'EC2Images', package: 'MyEC2Image', repository: 'standard', arch: 'i386', filename: 'appliance.raw.xz' } }
include_context 'it redirects and assigns flash error'
end
end
end
describe 'POST #create' do
let(:params) do
{
project: 'Cloud',
package: 'aws',
repository: 'standard',
arch: 'x86_64',
filename: 'appliance.raw.xz',
region: 'us-east-1',
ami_name: 'my-image',
target: 'ec2'
}
end
shared_context 'it redirects and assigns flash error' do
before do
Feature.run_with_activated(:cloud_upload) do
post :create, params: { cloud_backend_upload_job: params }
end
end
it { expect(flash[:error]).to match(/#{subject}/) }
it { expect(response).to be_redirect }
end
context 'without backend configured' do
subject { 'no cloud upload server configured.' }
include_context 'it redirects and assigns flash error'
end
context 'with an invalid filename' do
subject { 'MyEC2Image.rpm' }
before do
params[:filename] = subject
end
include_context 'it redirects and assigns flash error'
end
context 'with a backend response' do
let(:path) { "#{CONFIG['source_url']}/cloudupload?#{backend_params.to_param}" }
let(:backend_params) do
params.merge(target: 'ec2', user: user_with_ec2_configuration.login).except(:region, :ami_name)
end
let(:additional_data) do
{
region: 'us-east-1',
ami_name: 'my-image'
}
end
let(:post_body) do
user_with_ec2_configuration.ec2_configuration.attributes.except('id', 'created_at', 'updated_at').merge(additional_data).to_json
end
before do
stub_request(:post, path).with(body: post_body).and_return(body: xml_response)
Feature.run_with_activated(:cloud_upload) do
post :create, params: { cloud_backend_upload_job: params }
end
end
it { expect(flash[:success]).not_to be_nil }
it { expect(Cloud::User::UploadJob.last.job_id).to eq(6) }
it { expect(Cloud::User::UploadJob.last.user).to eq(user_with_ec2_configuration) }
it { expect(response).to redirect_to(cloud_upload_index_path) }
it { expect(response).to be_redirect }
end
end
end
|
gpl-2.0
|
Romenig/iVProg_2
|
src/usp/ime/line/ivprog/interpreter/execution/expressions/arithmetic/Subtraction.java
|
1820
|
/**
* Instituto de Matemática e Estatística da Universidade de São Paulo (IME-USP)
* iVProg is a open source and free software of Laboratório de Informática na
* Educação (LInE) licensed under GNU GPL2.0 license.
* Prof. Dr. Leônidas de Oliveira Brandão - leo@ime.usp.br
* Romenig da Silva Ribeiro - romenig@ime.usp.br | romenig@gmail.com
* @author Romenig
*/
package usp.ime.line.ivprog.interpreter.execution.expressions.arithmetic;
import ilm.framework.assignment.model.DomainObject;
import java.util.HashMap;
import usp.ime.line.ivprog.interpreter.DataFactory;
import usp.ime.line.ivprog.interpreter.DataObject;
import usp.ime.line.ivprog.interpreter.execution.Context;
import usp.ime.line.ivprog.interpreter.execution.expressions.Expression;
import usp.ime.line.ivprog.interpreter.execution.expressions.Operation;
import usp.ime.line.ivprog.interpreter.execution.expressions.value.IVPNumber;
import usp.ime.line.ivprog.interpreter.execution.expressions.value.IVPValue;
public class Subtraction extends Operation {
/**
* @param name
* @param description
*/
public Subtraction() {
super("Subtraction", "Subtraction object.");
}
public Object evaluate(Context c, HashMap map, DataFactory factory) {
IVPNumber v1 = (IVPNumber) ((DataObject) map.get(expressionAID)).evaluate(c, map, factory);
IVPNumber v2 = (IVPNumber) ((DataObject) map.get(expressionBID)).evaluate(c, map, factory);
IVPNumber result = v1.subtract(operationResultID, v2, c, factory, map);
return result;
}
/*
* (non-Javadoc)
*
* @see
* ilm.framework.assignment.model.DomainObject#equals(ilm.framework.assignment
* .model.DomainObject)
*/
@Override
public boolean equals(DomainObject o) {
// TODO Auto-generated method stub
return false;
}
}
|
gpl-2.0
|
supahseppe/path-of-gaming
|
wp-content/themes/flatbase/engine/admin/options.php
|
21841
|
<?php
/**
* Table of Contents (options.php)
*
* - nice_formbuilder()
* - nice_option_get_text()
* - nice_option_get_select()
* - nice_option_get_textarea()
* - nice_option_get_file()
* - nice_option_get_checkbox()
* - nice_option_get_radio()
* - nice_option_get_color()
* - nice_option_get_date()
* - nice_option_get_select_multiple()
* - nice_option_get_typography()
* - nice_option_get_info()
* - nice_option_get_password()
*
*/
/**
* nice_formbuilder()
*
* retrieve the options array, creating the html structure for the
* options menu.
*
* @since 1.0.0
*
* @param array $nice_options. Theme Options.
* @return object with menu and content.
*/
if ( ! function_exists( 'nice_formbuilder' ) ) :
function nice_formbuilder( $nice_options ){
$interface = new stdClass();
$interface->menu = '';
$interface->content = '';
foreach ( $nice_options as $key => $option ) :
if ( $option['type'] != 'heading' ) {
$class = '';
if ( isset( $option['class'] ) ) $class = $option['class'];
$interface->content .= '<div class="section section-' . $option['type'] . ' ' . $class . '">' . "\n";
if ( ( $option['type'] != 'upload' ) && ( $option['type'] != 'color' ) && ( $option['type'] != 'heading' ) ){
$interface->content .= '<h3 class="heading"><label for="' . esc_attr( $option['id'] ) . '">' . esc_html( $option['name'] ) . '</label></h3>' . "\n";
} else {
$interface->content .= '<h3 class="heading">' . esc_html( $option['name'] ) . '</h3>' . "\n";
}
if ( $option['type'] != 'checkbox' && ( $option['type'] != 'info' ) && $option['desc'] != '' ) {
$interface->content .= '<a id="btn-help-' . $option['id'] . '" class="nice-help-button">' . __( 'Help', 'nicethemes' ) . '</a>' . "\n";
}
$interface->content .= '<div class="option">' . "\n" . '<div class="controls">' . "\n";
}
$select_value = '';
switch ( $option['type'] ) {
case 'text':
$interface->content .= nice_option_get_text( $option );
break;
case 'password':
$interface->content .= nice_option_get_password( $option );
break;
case 'select':
$interface->content .= nice_option_get_select( $option );
break;
case 'textarea':
$interface->content .= nice_option_get_textarea( $option );
break;
case 'upload':
$interface->content .= nice_option_get_file( $option );
break;
case 'checkbox':
$interface->content .= nice_option_get_checkbox( $option );
break;
case 'radio':
$interface->content .= nice_option_get_radio( $option );
break;
case 'color':
$interface->content .= nice_option_get_color( $option );
break;
case 'date':
$interface->content .= nice_option_get_date( $option );
break;
case 'select_multiple':
$interface->content .= nice_option_get_select_multiple( $option );
break;
case 'info':
$interface->content .= nice_option_get_info( $option );
break;
case 'slider':
$interface->content .= nice_option_get_slider( $option );
break;
case 'heading' :
if ( $key >= 2 ) $interface->content .= '</div>' . "\n";
$jquery_click_hook = preg_replace( '/[^a-zA-Z0-9\s]/', '', strtolower( $option['name'] ) );
$jquery_click_hook = str_replace( ' ', '-', $jquery_click_hook );
$jquery_click_hook = 'nice-option-' . $jquery_click_hook;
$interface->menu .= '<li><a title="' . esc_attr( $option['name'] ) . '" href="#' . $jquery_click_hook . '">' . esc_html( $option['name'] ) . '</a><div></div></li>' . "\n";
$interface->content .= '<div class="group" id="' . $jquery_click_hook . '"><h2>' . esc_html( $option['name'] ). '</h2>' . "\n";
break;
case 'typography':
$interface->content .= nice_option_get_typography( $option );
break;
}
$explain_class = 'explain';
if ( $option['type'] != 'heading' ) {
if ( $option['type'] != 'checkbox' ) $interface->content .= '<br />';
else $explain_class = 'explain-checkbox';
if ( ! isset( $option['desc'] ) ) {
$explain_value = '';
} else {
$explain_value = $option['desc'];
}
$interface->content .= '</div><div id="nice-help-' . $option['id'] . '" class="' . $explain_class . '">';
if ( $option['type'] == 'checkbox' )
$interface->content .= '<label for="' . $option['id'] . '">' . $explain_value . '</label>';
else
$interface->content .= $explain_value;
$interface->content .= '</div>' . "\n";
$interface->content .= '<div class="clear"></div></div></div>' . "\n";
}
endforeach;
$interface->content .= '</div>';
return $interface;
}
endif;
/**
* nice_option_get_text()
*
* Retrieve option info in order to return the field in html code.
*
* @since 1.0.0
*
* @param array item $option. Option info in order return the html code.
* @return string with the text input.
*/
if ( ! function_exists( 'nice_option_get_text' ) ) :
function nice_option_get_text( $option ){
$val = $option['std'];
$tip = $option['tip'];
$std = get_option( $option['id'] );
if ( $std != '' ) $val = $std;
return '<input class="nice-input" name="' . $option['id'] . '" id="' . $option['id'] . '" type="' . $option['type'] . '" value="' . esc_attr( $val ) . '" />';
}
endif;
/**
* nice_option_get_select()
*
* Retrieve option info in order to return the field in html code.
*
* @since 1.0.0
*
* @param array item $option. Option info in order return the html code.
* @return string with the select input.
*/
if ( ! function_exists( 'nice_option_get_select' ) ) :
function nice_option_get_select( $option ){
$html = '<select class="nice-input" name="' . $option['id'] . '" id="' . $option['id'] . '">' . "\n";
$select_value = get_option( $option['id'] );
foreach ( $option['options'] as $o => $n ) {
$selected = '';
if ( $select_value != '' ) {
$selected = selected( $select_value, $o, false );
} else {
if ( isset( $option['std'] ) )
$selected = selected( $option['std'], $o, false);
}
$html .= '<option value="' . esc_attr( $o ) . '" ' . $selected . '>';
$html .= esc_html( $n );
$html .= '</option>' . "\n";
}
$html .= '</select>' . "\n";
return $html;
}
endif;
/**
* nice_option_get_textarea()
*
* Retrieve option info in order to return the field in html code.
*
* @since 1.0.0
*
* @param array item $option. Option info in order return the html code.
* @return string with the textarea input.
*/
if ( ! function_exists( 'nice_option_get_textarea' ) ) :
function nice_option_get_textarea( $option ){
$cols = '8';
$ta_value = '';
if ( isset ( $option['std'] ) ) :
$ta_value = $option['std'];
if ( isset ( $option['options'] ) ) {
$ta_options = $option['options'];
if ( isset ( $ta_options['cols'] ) )
$cols = $ta_options['cols'];
else
$cols = '8';
}
endif;
$std = get_option( $option['id'] );
if ( $std != "" ) $ta_value = stripslashes( $std );
return '<textarea class="nice-input" name="' . $option['id'] . '" id="' . $option['id'] . '" cols="' . $cols . '" rows="8">' . esc_textarea( $ta_value ) . '</textarea>' . "\n";
}
endif;
/**
* nice_option_get_file()
*
* Retrieve option info in order to return the field in html code. Works
* with wordpress mediauploader.
* If there's an image, it shows it with a "remove" button
* Check medialibrary.php
*
* @since 1.0.0
*
* @param array item $option. Option info in order return the html code.
* @return string with the file input.
*/
if ( ! function_exists( 'nice_option_get_file' ) ) :
function nice_option_get_file( $option ){
$post_id = houdini_get_post ( $option['id'] );
$src = get_option( $option['id'] );
if ( $src == '' ) $src = $option['std'];
$html = '<input id="' . $option['id'] . '" class="nice-upload" type="text" size="36" name="' . $option['id'] . '" value="' . esc_attr( $src ) . '" autocomplete="off" /><input id="upload_image_button" class="upload_button nice-input" type="button" value="' . __( 'Upload Image', 'nicethemes' ) . '" rel="' . $post_id . '" />';
$html .= '<div class="screenshot" id="' . '_image">' . "\n";
if ( $src != '' ){
$html .= '<img src="' . $src . '" alt="" />' . '';
$html .= '<a href="#" class="mlu_remove">' . __( 'Remove Image', 'nicethemes') . '</a>' . "\n";
}
$html .= '</div>' . "\n";
return $html;
}
endif;
/**
* nice_option_get_checkbox()
*
* Retrieve option info in order to return the field in html code.
*
* @since 1.0.0
*
* @param array item $option. Option info in order return the html code.
* @return string with the checkbox input.
*/
if ( ! function_exists( 'nice_option_get_checkbox' ) ) :
function nice_option_get_checkbox( $option ){
$checked = '';
$option_std = get_option( $option['id'] );
if ( ! empty( $option_std ) ) {
$checked = checked( $option_std, 'true', false );
} else{
$checked = checked( $option['std'], 'true', false );
}
return '<input type="checkbox" class="checkbox nice-input" name="' . $option['id'] . '" id="' . $option['id'] . '" value="true" ' . $checked . ' />';
}
endif;
/**
* nice_option_get_radio()
*
* Retrieve option info in order to return the field in html code.
*
* @since 1.0.0
*
* @param array item $option. Option info in order return the html code.
* @return string with the radio input.
*/
if ( ! function_exists( 'nice_option_get_radio' ) ) :
function nice_option_get_radio( $option ){
$html = '';
$select_value = get_option( $option['id'] );
foreach ( $option['options'] as $o => $n )
{
$checked = '';
if ( $select_value != '' ) {
$checked = checked( $select_value, $o, false );
} else {
$checked = checked( $option['std'], $o, false );
}
$html .= '<input class="nice-input nice-radio" type="radio" name="' . $option['id'] . '" value="' . $o . '" ' . $checked . ' />' . esc_html( $n ) . '<br />';
}
return $html;
}
endif;
/**
* nice_option_get_color()
*
* Retrieve option info in order to return the field in html code.
*
* @since 1.0.0
*
* @param array item $option. Option info in order return the html code.
* @return string with the color input.
*/
if ( ! function_exists( 'nice_option_get_color' ) ) :
function nice_option_get_color( $option ){
$std = $option['std'];
$db = get_option( $option['id'] );
if ( $db != "" ) { $std = $db; }
$html = '<div id="' . $option['id'] . '_picker" class="colorSelector"><div></div></div>';
$html .= '<input class="nice-color" name="' . $option['id'] . '" id="' . $option['id'] . '" type="text" value="' . esc_attr( $std ) . '" />';
return $html;
}
endif;
/**
* nice_option_get_date()
*
* Retrieve option info in order to return the field in html code + js date picker.
*
* @since 1.0.1
*
* @param array item $option. Option info in order return the html code.
* @return string with the date input.
*/
if ( ! function_exists( 'nice_option_get_date' ) ) :
function nice_option_get_date( $option ){
$std = $option['std'];
$db = get_option( $option['id'] );
if ( $db != "" ) { $std = $db; }
$html = '<input class="nice-date" name="' . $option['id'] . '" id="' . $option['id'] . '" type="text" value="' . esc_attr( $std ) . '" />';
$html .= '<input type="hidden" name="datepicker-image" value="' . get_template_directory_uri() . '/engine/admin/images/calendar.png" />';
return $html;
}
endif;
/**
* nice_option_get_select_multiple()
*
* Retrieve option info in order to return the field in html code + js date picker.
*
* @since 1.0.12
*
* @param array item $option. Option info in order return the html code.
* @return string with the date input.
*/
if ( ! function_exists( 'nice_option_get_select_multiple' ) ) :
function nice_option_get_select_multiple( $option ){
$html = '<select class="nice-input" style="height:auto;" name="' . $option['id'] . '[]" id="' . $option['id'] . '[]" multiple="multiple" >' . "\n";
$select_value = get_option( $option['id'] );
foreach ( $option['options'] as $o => $n ) {
$selected = '';
if ( $select_value != '' ) {
if ( is_array( $select_value) ){
if ( ( $key = array_search( $n, $select_value ) ) !== FALSE ) { $selected = ' selected="selected"'; }
}
} else {
if ( isset( $option['std'] ) )
$selected = selected( $option['std'], $o, false );
}
$html .= '<option value="' . esc_attr( $o ) . '"' . $selected . '>';
$html .= esc_html( $n );
$html .= '</option>' . "\n";
}
$html .= '</select>' . "\n";
return $html;
}
endif;
/**
* nice_option_get_typography()
*
* Retrieve option info in order to return the field in html code + js date picker.
*
* @since 1.0.12
*
* @param array item $option. Option info in order return the html code.
* @return string with the date input.
*/
if ( ! function_exists( 'nice_option_get_typography' ) ) :
function nice_option_get_typography( $option ){
$db = get_option( $option['id'] );
$std = $option['std'];
if ( ! is_array( $db ) || empty( $db ) ) {
$std = $option['std'];
}
// ----------
// font family
$font_family = $std['family'];
if ( $db['family'] != "" ) { $font_family = $db['family']; }
$font01 = '';
$font02 = '';
$font03 = '';
$font04 = '';
$font05 = '';
$font06 = '';
$font07 = '';
$font08 = '';
$font09 = '';
$font10 = '';
$font11 = '';
$font12 = '';
$font13 = '';
$font14 = '';
$font15 = '';
$font16 = '';
$font17 = '';
if ( strpos( $font_family, 'Arial, sans-serif' ) !== false ) { $font01 = 'selected="selected"'; }
if ( strpos( $font_family, 'Verdana, Geneva' ) !== false ) { $font02 = 'selected="selected"'; }
if ( strpos( $font_family, 'Trebuchet' ) !== false ) { $font03 = 'selected="selected"'; }
if ( strpos( $font_family, 'Georgia' ) !== false ) { $font04 = 'selected="selected"'; }
if ( strpos( $font_family, 'Times New Roman' ) !== false ) { $font05 = 'selected="selected"'; }
if ( strpos( $font_family, 'Tahoma, Geneva' ) !== false ) { $font06 = 'selected="selected"'; }
if ( strpos( $font_family, 'Palatino' ) !== false ) { $font07 = 'selected="selected"'; }
if ( strpos( $font_family, 'Helvetica' ) !== false ) { $font08 = 'selected="selected"'; }
if ( strpos( $font_family, 'Calibri' ) !== false ) { $font09 = 'selected="selected"'; }
if ( strpos( $font_family, 'Myriad' ) !== false ) { $font10 = 'selected="selected"'; }
if ( strpos( $font_family, 'Lucida' ) !== false ) { $font11 = 'selected="selected"'; }
if ( strpos( $font_family, 'Arial Black' ) !== false ) { $font12 = 'selected="selected"'; }
if ( strpos( $font_family, 'Gill' ) !== false ) { $font13 = 'selected="selected"'; }
if ( strpos( $font_family, 'Geneva, Tahoma' ) !== false ) { $font14 = 'selected="selected"'; }
if ( strpos( $font_family, 'Impact' ) !== false ) { $font15 = 'selected="selected"'; }
if ( strpos( $font_family, 'Courier' ) !== false ) { $font16 = 'selected="selected"'; }
if ( strpos( $font_family, 'Century Gothic' ) !== false ) { $font17 = 'selected="selected"'; }
$html = '<select class="nice-typography nice-typography-family" name="'. esc_attr( $option['id'].'_family' ) . '" id="'. esc_attr( $option['id'].'_family') . '">' . "\n";
$html .= '<option value="Arial, sans-serif" '. $font01 .'>Arial</option>' . "\n";
$html .= '<option value="Verdana, Geneva, sans-serif" '. $font02 .'>Verdana</option>' . "\n";
$html .= '<option value=""Trebuchet MS", Tahoma, sans-serif"'. $font03 .'>Trebuchet</option>' . "\n";
$html .= '<option value="Georgia, serif" '. $font04 .'>Georgia</option>' . "\n";
$html .= '<option value=""Times New Roman", serif"'. $font05 .'>Times New Roman</option>' . "\n";
$html .= '<option value="Tahoma, Geneva, Verdana, sans-serif"'. $font06 .'>Tahoma</option>' . "\n";
$html .= '<option value="Palatino, "Palatino Linotype", serif"'. $font07 .'>Palatino</option>' . "\n";
$html .= '<option value=""Helvetica Neue", Helvetica, sans-serif" '. $font08 .'>Helvetica</option>' . "\n";
$html .= '<option value="Calibri, Candara, Segoe, Optima, sans-serif"'. $font09 .'>Calibri</option>' . "\n";
$html .= '<option value=""Myriad Pro", Myriad, sans-serif"'. $font10 .'>Myriad Pro</option>' . "\n";
$html .= '<option value=""Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", sans-serif"'. $font11 .'>Lucida</option>' . "\n";
$html .= '<option value=""Arial Black", sans-serif" '. $font12 .'>Arial Black</option>' . "\n";
$html .= '<option value=""Gill Sans", "Gill Sans MT", Calibri, sans-serif" '. $font13 .'>Gill Sans</option>' . "\n";
$html .= '<option value="Geneva, Tahoma, Verdana, sans-serif" '. $font14 .'>Geneva</option>' . "\n";
$html .= '<option value="Impact, Charcoal, sans-serif" '. $font15 .'>Impact</option>' . "\n";
$html .= '<option value="Courier, "Courier New", monospace" '. $font16 .'>Courier</option>' . "\n";
$html .= '<option value=""Century Gothic", sans-serif" '. $font17 .'>Century Gothic</option>' . "\n";
// Google webfonts
global $google_fonts;
sort( $google_fonts );
$html .= '<option value="">———— ' . __( 'Google Fonts', 'nicethemes' ) .' ————</option>' . "\n";
foreach ( $google_fonts as $key => $google_font ) :
$font[$key] = '';
$font[$key] = selected( $font_family, $google_font['name'], false );
$name = $google_font['name'];
$html .= '<option value="' . esc_attr( $name ) . '" '. $font[$key] .'>' . esc_html( $name ) . '</option>' . "\n";
endforeach;
$html .= '</select>' . "\n\n";
// ----------
// font weight
$font_weight = $std['style'];
if ( $db['style'] != "" ) { $font_weight = $db['style']; }
$thin = ''; $thinitalic = ''; $normal = ''; $italic = ''; $bold = ''; $bolditalic = '';
$thin = selected( $font_weight, '300', false );
$thinitalic = selected( $font_weight, '300 italic', false );
$normal = selected( $font_weight, 'normal', false );
$italic = selected( $font_weight, 'italic', false );
$bold = selected( $font_weight, 'bold', false );
$bolditalic = selected( $font_weight, 'bold italic', false );
if ( ( $thin == '' ) && ( $thinitalic == '' ) && ( $normal == '') && ( $italic == '' ) && ( $bold == '' ) && ( $bolditalic == '' ) ){
$normal = 'selected="selected"';
}
$html .= '<select class="nice-typography nice-typography-style" name="'. esc_attr( $option['id'] . '_style' ) . '" id="' . esc_attr( $option['id'] . '_style' ) . '">';
$html .= '<option value="300" '. $thin .'>Thin</option>';
$html .= '<option value="300 italic" '. $thinitalic .'>Thin/Italic</option>';
$html .= '<option value="normal" '. $normal .'>Normal</option>';
$html .= '<option value="italic" '. $italic .'>Italic</option>';
$html .= '<option value="bold" '. $bold .'>Bold</option>';
$html .= '<option value="bold italic" '. $bolditalic .'>Bold/Italic</option>';
$html .= '</select>';
// --------
// font size
if ( isset( $std['size'] ) ) {
$font_size = $std['size'];
if ( $db['size'] != '' ) { $font_size = $db['size']; }
$html .= '<select class="nice-typography nice-typography-size" name="'. esc_attr( $option['id'] . '_size' ) . '" id="'. esc_attr( $option['id'].'_size') . '" >' . "\n";
for ( $i = 9; $i < 71; $i++ ) {
$active = selected( $font_size, strval( $i ), false );
$html .= '<option value="' . esc_attr( $i ) .'" ' . $active . '>' . esc_html( $i . ' px' ) .'</option>' . "\n";
}
$html .= '</select>' . "\n\n";
}
// ----------
// font color
if ( isset( $std['color'] ) ){
$font_color = $std['color'];
if ( $db['color'] != "" ) { $font_color = $db['color']; }
$html .= '<div id="' . esc_attr( $option['id'] . '_color_picker' ) . '" class="colorSelector"><div></div></div>' . "\n";
$html .= '<input class="nice-color nice-typography-color" name="' . esc_attr( $option['id'] . '_color' ) . '" id="' . esc_attr( $option['id'] . '_color' ) . '" type="text" value="' . esc_attr( $font_color ) . '" />' . "\n\n";
}
$html .= '<input type="hidden" class="nice-typography-last" />';
return $html;
}
endif;
/**
* nice_option_get_info()
*
* Display an information field.
*
* @since 1.0.5
*
* @param array item $option. Option info in order return the html code.
* @return string with the text input.
*/
if ( ! function_exists( 'nice_option_get_info' ) ) :
function nice_option_get_info( $option ){
return $option['desc'];
}
endif;
/**
* nice_option_get_password()
*
* Retrieve option info in order to return the field in html code.
*
* @since 1.0.6
*
* @param array item $option. Option info in order return the html code.
* @return string with the text input.
*/
if ( ! function_exists( 'nice_option_get_password' ) ) :
function nice_option_get_password( $option ){
$val = $option['std'];
$tip = $option['tip'];
$std = get_option( $option['id'] );
if ( $std != "" ) $val = $std;
return '<input class="nice-input" name="' . $option['id'] . '" id="' . $option['id'] . '" type="' . $option['type'] . '" value="' . esc_attr( $val ) . '" />';
}
endif;
/**
* nice_option_get_slider()
*
* Retrieve option info in order to return the field in html code.
*
* @since 1.0.6
*
* @param array item $option. Option info in order return the html code.
* @return string with the text input.
*/
if ( ! function_exists( 'nice_option_get_slider' ) ) :
function nice_option_get_slider( $option ){
$db = get_option( $option['id'] );
$std = $option['std'];
if ( ! is_array( $db ) || empty( $db ) ) {
$std = $option['std'];
}
$output = '<div id="' . $option['id'] . '_slider" ></div>';
$output .= '<input type="text" name="' . $option['id'] . '" id="' . $option['id'] . '" />';
return $output;
}
endif;
?>
|
gpl-2.0
|
imeuro/boldbodies
|
wp-content/themes/sean-lite/core/main.php
|
17506
|
<?php
/**
* Wp in Progress
*
* @package Wordpress
* @theme Sean
*
* This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 3.0)
* It is also available at this URL: http://www.gnu.org/licenses/gpl-3.0.txt
*/
/*-----------------------------------------------------------------------------------*/
/* TAG TITLE */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( '_wp_render_title_tag' ) ) {
function seanlite_title( $title, $sep ) {
global $paged, $page;
if ( is_feed() )
return $title;
$title .= get_bloginfo( 'name' );
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
$title = "$title $sep $site_description";
if ( $paged >= 2 || $page >= 2 )
$title = "$title $sep " . sprintf( __( 'Page %s', 'sean-lite' ), max( $paged, $page ) );
return $title;
}
add_filter( 'wp_title', 'seanlite_title', 10, 2 );
function seanlite_addtitle() {
?>
<title><?php wp_title( '|', true, 'right' ); ?></title>
<?php
}
add_action( 'wp_head', 'seanlite_addtitle' );
}
/*-----------------------------------------------------------------------------------*/
/* POST CLASS */
/*-----------------------------------------------------------------------------------*/
if (!function_exists('seanlite_post_class')) {
function seanlite_post_class($classes) {
$classes[] = 'post-container col-md-12';
return $classes;
}
add_filter('post_class', 'seanlite_post_class');
}
/*-----------------------------------------------------------------------------------*/
/* REQUIRE FUNCTION */
/*-----------------------------------------------------------------------------------*/
if (!function_exists('seanlite_require')) {
function seanlite_require($folder) {
if (isset($folder)) :
if ( ( !seanlite_setting('wip_loadsystem') ) || ( seanlite_setting('wip_loadsystem') == "mode_a" ) ) {
$folder = dirname(dirname(__FILE__)) . $folder ;
$files = scandir($folder);
foreach ($files as $key => $name) {
if (!is_dir( $name )) {
require_once $folder . $name;
}
}
} else if ( seanlite_setting('wip_loadsystem') == "mode_b" ) {
$dh = opendir(get_template_directory().$folder);
while (false !== ($filename = readdir($dh))) {
if ( strlen($filename) > 2 ) {
require_once get_template_directory()."/".$folder.$filename;
}
}
}
endif;
}
}
/*-----------------------------------------------------------------------------------*/
/* SCRIPTS FUNCTION */
/*-----------------------------------------------------------------------------------*/
if (!function_exists('seanlite_enqueue_script')) {
function seanlite_enqueue_script($folder) {
if (isset($folder)) :
if ( ( !seanlite_setting('wip_loadsystem') ) || ( seanlite_setting('wip_loadsystem') == "mode_a" ) ) {
$dir = dirname(dirname(__FILE__)) . $folder ;
$files = scandir($dir);
foreach ($files as $key => $name) {
if (!is_dir( $name )) {
wp_enqueue_script( 'seanlite_'. str_replace('.js','',$name), get_template_directory_uri() . $folder . "/" . $name , array('jquery'), FALSE, TRUE );
}
}
} else if ( seanlite_setting('wip_loadsystem') == "mode_b" ) {
$dh = opendir(get_template_directory().$folder);
while (false !== ($filename = readdir($dh))) {
if ( strlen($filename) > 2 ) {
wp_enqueue_script( 'seanlite_'. str_replace('.js','',$filename), get_template_directory_uri() . $folder . "/" . $filename , array('jquery'), FALSE, TRUE );
}
}
}
endif;
}
}
/*-----------------------------------------------------------------------------------*/
/* STYLES FUNCTION */
/*-----------------------------------------------------------------------------------*/
if (!function_exists('seanlite_enqueue_style')) {
function seanlite_enqueue_style($folder) {
if (isset($folder)) :
if ( ( !seanlite_setting('wip_loadsystem') ) || ( seanlite_setting('wip_loadsystem') == "mode_a" ) ) {
$dir = dirname(dirname(__FILE__)) . $folder ;
$files = scandir($dir);
foreach ($files as $key => $name) {
if (!is_dir( $name )) {
wp_enqueue_style( 'seanlite_'. str_replace('.css','',$name), get_template_directory_uri() . $folder . "/" . $name );
}
}
} else if ( seanlite_setting('wip_loadsystem') == "mode_b" ) {
$dh = opendir(get_template_directory().$folder);
while (false !== ($filename = readdir($dh))) {
if ( strlen($filename) > 2 ) {
wp_enqueue_style( 'seanlite_'. str_replace('.css','',$filename), get_template_directory_uri() . $folder . "/" . $filename );
}
}
}
endif;
}
}
/*-----------------------------------------------------------------------------------*/
/* REQUEST FUNCTION */
/*-----------------------------------------------------------------------------------*/
if (!function_exists('seanlite_request')) {
function seanlite_request($id) {
if ( isset ( $_REQUEST[$id]))
return $_REQUEST[$id];
}
}
/*-----------------------------------------------------------------------------------*/
/* THEME PATH */
/*-----------------------------------------------------------------------------------*/
if (!function_exists('seanlite_theme_data')) {
function seanlite_theme_data($id) {
$themedata = wp_get_theme();
return $themedata->get($id);
}
}
/*-----------------------------------------------------------------------------------*/
/* THEME SETTINGS */
/*-----------------------------------------------------------------------------------*/
if (!function_exists('seanlite_setting')) {
function seanlite_setting($id) {
$seanlite_setting = get_theme_mod($id);
if(isset($seanlite_setting))
return $seanlite_setting;
}
}
/*-----------------------------------------------------------------------------------*/
/* POST META */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_postmeta' ) ) {
function seanlite_postmeta($id) {
global $post;
if (!is_404()) {
$val = get_post_meta( $post->ID , $id, TRUE);
if(isset($val))
return $val;
} else {
return null;
}
}
}
/*-----------------------------------------------------------------------------------*/
/* POST ICON */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_posticon' ) ) {
function seanlite_posticon() {
$icons = array (
"video" => "genericon-video" ,
"gallery" => "genericon-image" ,
"audio" => "genericon-audio" ,
"chat" => "genericon-chat",
"status" => "genericon-status",
"image" => "genericon-picture",
"quote" => "genericon-quote" ,
"link" => "genericon-external",
"aside" => "genericon-aside"
);
if (get_post_format()) {
$icon = '<span class="genericon '.$icons[get_post_format()].'"></span> '.ucfirst(get_post_format());
} else {
$icon = '<span class="genericon genericon-standard"></span> Standard';
}
return $icon;
}
}
/*-----------------------------------------------------------------------------------*/
/* Preload system */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_jpreloader_class' ) ) {
function seanlite_jpreloader_class($classes) {
if ( seanlite_setting('wip_preload_system') == "on" ) :
if ( seanlite_setting('wip_preload_layout') == "dark" ) {
$classes[] = 'jpreloader dark';
} else {
$classes[] = 'jpreloader';
}
endif;
return $classes;
}
add_filter('body_class','seanlite_jpreloader_class');
}
/*-----------------------------------------------------------------------------------*/
/* Infinitescroll system */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_infinitescroll_class' ) ) {
function seanlite_infinitescroll_class($classes) {
if ( seanlite_setting('wip_infinitescroll_system') == "on" ) :
$classes[] = 'infinitescroll';
endif;
return $classes;
}
add_filter('body_class','seanlite_infinitescroll_class');
}
/*-----------------------------------------------------------------------------------*/
/* Body class */
/*-----------------------------------------------------------------------------------*/
function seanlite_body_class($classes) {
$classes[] = 'custombody';
return $classes;
}
add_filter('body_class', 'seanlite_body_class');
/*-----------------------------------------------------------------------------------*/
/* LOGIN AREA */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_custom_login_logo' ) ) {
function seanlite_custom_login_logo() {
if ( seanlite_setting('wip_login_logo') ) : ?>
<style type="text/css">
body.login div#login h1 a {
background-image: url('<?php echo esc_url(seanlite_setting('wip_login_logo')); ?>');
-webkit-background-size: inherit;
background-size: inherit ;
width:100%;
height:<?php echo seanlite_setting('wip_login_logo_height'); ?>px;
}
</style>
<?php
endif;
}
add_action( 'login_enqueue_scripts', 'seanlite_custom_login_logo' );
}
/*-----------------------------------------------------------------------------------*/
/* Content template */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_template' ) ) {
function seanlite_template($id) {
$template = array ("full" => "col-md-12" , "left-sidebar" => "col-md-8" , "right-sidebar" => "col-md-8" );
$span = $template["right-sidebar"];
$sidebar = "right-sidebar";
if ( ( (is_category()) || (is_tag()) || (is_tax()) || (is_month() ) ) && (seanlite_setting('wip_category_layout')) ) {
$span = $template[seanlite_setting('wip_category_layout')];
$sidebar = seanlite_setting('wip_category_layout');
} else if ( (is_home()) && (seanlite_setting('wip_home')) ) {
$span = $template[seanlite_setting('wip_home')];
$sidebar = seanlite_setting('wip_home');
} else if ( (is_search()) && (seanlite_setting('wip_search_layout')) ) {
$span = $template[seanlite_setting('wip_search_layout')];
$sidebar = seanlite_setting('wip_search_layout');
} else if ( ( (is_single()) || (is_page()) ) && (seanlite_postmeta('wip_template')) ) {
$span = $template[seanlite_postmeta('wip_template')];
$sidebar = seanlite_postmeta('wip_template');
}
return ${$id};
}
}
/*-----------------------------------------------------------------------------------*/
/* THUMBNAILS */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_get_thumbs' ) ) {
function seanlite_get_thumbs($type) {
if (seanlite_setting('wip_'.$type.'_thumbinal')):
return seanlite_setting('wip_'.$type.'_thumbinal');
else:
return "550";
endif;
}
}
/*-----------------------------------------------------------------------------------*/
/* GET PAGED */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_paged' ) ) {
function seanlite_paged() {
if ( get_query_var('paged') ) {
$paged = get_query_var('paged');
} elseif ( get_query_var('page') ) {
$paged = get_query_var('page');
} else {
$paged = 1;
}
return $paged;
}
}
/*-----------------------------------------------------------------------------------*/
/* PRETTYPHOTO */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_prettyPhoto' ) ) {
function seanlite_prettyPhoto( $html, $id, $size, $permalink, $icon, $text ) {
if ( ! $permalink )
return str_replace( '<a', '<a rel="prettyPhoto" ', $html );
else
return $html;
}
add_filter( 'wp_get_attachment_link', 'seanlite_prettyPhoto', 10, 6);
}
/*-----------------------------------------------------------------------------------*/
/* Excerpt more */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_hide_excerpt_more' ) ) {
function seanlite_hide_excerpt_more() {
return '';
}
add_filter('the_content_more_link', 'seanlite_hide_excerpt_more');
add_filter('excerpt_more', 'seanlite_hide_excerpt_more');
}
if ( ! function_exists( 'seanlite_excerpt' ) ) {
function seanlite_excerpt() {
global $post,$more;
$more = 0;
$class = 'more';
$button = ' [...] ';
if ( seanlite_setting('wip_readmore_button') == "on" ):
$class = 'button';
$button = __('Read more','sean-lite');
endif;
if ($pos=strpos($post->post_content, '<!--more-->')):
$content = substr(apply_filters( 'the_content', get_the_content()), 0, -5);
else:
$content = substr(apply_filters( 'the_excerpt', get_the_excerpt()), 0, -5);
endif;
echo $content. '<a class="'.$class.'" href="'.get_permalink($post->ID).'" title="More">'.$button.'</a></p>';
}
}
/*-----------------------------------------------------------------------------------*/
/* REMOVE CATEGORY LIST REL */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_remove_cat_rel' ) ) {
function seanlite_remove_cat_rel($output) {
$output = str_replace('rel="category"', '', $output);
return $output;
}
add_filter('wp_list_categories', 'seanlite_remove_cat_rel');
add_filter('the_category', 'seanlite_remove_cat_rel');
}
/*-----------------------------------------------------------------------------------*/
/* REMOVE THUMBNAIL DIMENSION */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_thumbs_size' ) ) {
function seanlite_thumbs_size( $html, $post_id, $post_image_id ) {
$html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
return $html;
}
add_filter( 'post_thumbnail_html', 'seanlite_thumbs_size', 10, 3 );
}
/*-----------------------------------------------------------------------------------*/
/* REMOVE CSS GALLERY */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_gallery_style' ) ) {
function seanlite_gallery_style() {
return "<div class='gallery'>";
}
add_filter( 'gallery_style', 'seanlite_gallery_style', 99 );
}
/*-----------------------------------------------------------------------------------*/
/* STYLES AND SCRIPTS */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_includes' ) ) {
function seanlite_includes() {
wp_enqueue_style( 'seanlite-style', get_stylesheet_uri(), array() );
seanlite_enqueue_style('/includes/css');
if ( is_singular() ) wp_enqueue_script( 'comment-reply' );
wp_enqueue_script( "jquery-ui-core", array('jquery'));
wp_enqueue_script( "jquery-ui-tabs", array('jquery'));
seanlite_enqueue_script('/includes/js');
if ( ( get_theme_mod('wip_skin') ) && ( get_theme_mod('wip_skin') <> "turquoise" ) ):
wp_enqueue_style( 'sean-lite' . get_theme_mod('wip_skin') , get_template_directory_uri() . '/includes/skins/' . get_theme_mod('wip_skin') . '.css' );
endif;
wp_enqueue_style( 'google-fonts', '//fonts.googleapis.com/css?family=Dr+Sugiyama|Roboto+Slab|Droid+Serif:400,300,100,700' );
}
add_action( 'wp_enqueue_scripts', 'seanlite_includes' );
}
/*-----------------------------------------------------------------------------------*/
/* THEME SETUP */
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'seanlite_setup' ) ) {
function seanlite_setup() {
add_theme_support( 'post-formats', array( 'aside','gallery','quote','video','audio','link','status','chat','image' ) );
add_theme_support( 'automatic-feed-links' );
add_theme_support( 'post-thumbnails' );
add_theme_support( 'title-tag' );
add_image_size( 'blog', 940,seanlite_get_thumbs('blog'), TRUE );
add_image_size( 'portfolio', 940,seanlite_get_thumbs('portfolio'), TRUE );
add_image_size( 'large', 449,304, TRUE );
add_image_size( 'medium', 290,220, TRUE );
add_image_size( 'small', 211,150, TRUE );
register_nav_menu( 'main-menu', 'Main menu' );
load_theme_textdomain('sean-lite', get_template_directory() . '/languages');
if ( ! isset( $content_width ) )
$content_width = 940;
add_theme_support( 'custom-background', array(
'default-color' => 'f3f3f3',
) );
seanlite_require('/core/classes/');
seanlite_require('/core/admin/customize/');
seanlite_require('/core/templates/');
seanlite_require('/core/scripts/');
seanlite_require('/core/functions/');
seanlite_require('/core/metaboxes/');
}
add_action( 'after_setup_theme', 'seanlite_setup' );
}
?>
|
gpl-2.0
|
Himatekinfo/KP-Sistem-Pengelolaan-SPP-Madrasah-Mu-aliemien
|
protected/models/TransaksiPengeluaran.php
|
3270
|
<?php
/**
* This is the model class for table "tbl_transaksi_pengeluaran".
*
* The followings are the available columns in table 'tbl_transaksi_pengeluaran':
* @property string $Id
* @property string $UserId
* @property string $Deskripsi
* @property string $Tanggal
* @property string $Ket
* @property string $JumlahBenda
* @property string $HargaSatuan
* @property string $SatuanId
*
* The followings are the available model relations:
* @property Satuan $satuan
* @property User $user
*/
class TransaksiPengeluaran extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return TransaksiPengeluaran 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 'tbl_transaksi_pengeluaran';
}
/**
* @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('UserId, Deskripsi, Tanggal, Ket, JumlahBenda, HargaSatuan, SatuanId', 'required'),
array('UserId', 'length', 'max'=>5),
array('Deskripsi, Ket', 'length', 'max'=>200),
array('JumlahBenda, SatuanId', 'length', 'max'=>10),
array('HargaSatuan', 'length', 'max'=>20),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('Id, UserId, Deskripsi, Tanggal, Ket, JumlahBenda, HargaSatuan, SatuanId', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'satuan' => array(self::BELONGS_TO, 'Satuan', 'SatuanId'),
'user' => array(self::BELONGS_TO, 'User', 'UserId'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'Id' => 'ID',
'UserId' => 'User',
'Deskripsi' => 'Deskripsi',
'Tanggal' => 'Tanggal',
'Ket' => 'Ket',
'JumlahBenda' => 'Jumlah Benda',
'HargaSatuan' => 'Harga Satuan',
'SatuanId' => 'Satuan',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('Id',$this->Id,true);
$criteria->compare('UserId',$this->UserId,true);
$criteria->compare('Deskripsi',$this->Deskripsi,true);
$criteria->compare('Tanggal',$this->Tanggal,true);
$criteria->compare('Ket',$this->Ket,true);
$criteria->compare('JumlahBenda',$this->JumlahBenda,true);
$criteria->compare('HargaSatuan',$this->HargaSatuan,true);
$criteria->compare('SatuanId',$this->SatuanId,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
|
gpl-2.0
|
Fluorohydride/ygopro-scripts
|
c14088859.lua
|
4038
|
--ネオス・フュージョン
function c14088859.initial_effect(c)
aux.AddCodeList(c,89943723)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(14088859,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_DECKDES)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c14088859.target)
e1:SetOperation(c14088859.activate)
c:RegisterEffect(e1)
--destroy replace
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EFFECT_DESTROY_REPLACE)
e2:SetRange(LOCATION_GRAVE)
e2:SetTarget(c14088859.reptg)
e2:SetValue(c14088859.repval)
e2:SetOperation(c14088859.repop)
c:RegisterEffect(e2)
--return replace
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EFFECT_SEND_REPLACE)
e3:SetRange(LOCATION_GRAVE)
e3:SetTarget(c14088859.reptg2)
e3:SetOperation(c14088859.repop2)
e3:SetValue(c14088859.repval2)
c:RegisterEffect(e3)
end
function c14088859.filter1(c,e)
return c:IsAbleToGrave() and not c:IsImmuneToEffect(e)
end
function c14088859.filter2(c,e,tp,m,chkf)
return c.neos_fusion and aux.IsMaterialListCode(c,89943723)
and c:IsCanBeSpecialSummoned(e,0,tp,true,false) and c:CheckFusionMaterial(m,nil,chkf,true)
end
function c14088859.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local chkf=tp|0x200
local mg=Duel.GetMatchingGroup(c14088859.filter1,tp,LOCATION_HAND+LOCATION_MZONE+LOCATION_DECK,0,nil,e)
return Duel.IsExistingMatchingCard(c14088859.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg,chkf)
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c14088859.activate(e,tp,eg,ep,ev,re,r,rp)
local chkf=tp|0x200
local mg=Duel.GetMatchingGroup(c14088859.filter1,tp,LOCATION_HAND+LOCATION_MZONE+LOCATION_DECK,0,nil,e)
local sg=Duel.GetMatchingGroup(c14088859.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg,chkf)
if sg:GetCount()>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local tg=sg:Select(tp,1,1,nil)
local tc=tg:GetFirst()
local mat=Duel.SelectFusionMaterial(tp,tc,mg,nil,chkf,true)
Duel.SendtoGrave(mat,REASON_EFFECT)
Duel.BreakEffect()
Duel.SpecialSummon(tc,0,tp,tp,true,false,POS_FACEUP)
end
if e:IsHasType(EFFECT_TYPE_ACTIVATE) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetTargetRange(1,0)
Duel.RegisterEffect(e1,tp)
end
end
function c14088859.repfilter(c,tp)
return c:IsFaceup() and c:IsControler(tp) and c:IsLocation(LOCATION_MZONE) and c:IsType(TYPE_FUSION)
and aux.IsMaterialListCode(c,89943723) and c:IsReason(REASON_EFFECT+REASON_BATTLE) and not c:IsReason(REASON_REPLACE)
end
function c14088859.reptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemove() and eg:IsExists(c14088859.repfilter,1,nil,tp) end
return Duel.SelectEffectYesNo(tp,e:GetHandler(),96)
end
function c14088859.repval(e,c)
return c14088859.repfilter(c,e:GetHandlerPlayer())
end
function c14088859.repop(e,tp,eg,ep,ev,re,r,rp)
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_EFFECT)
end
function c14088859.repfilter2(c,tp,re)
return c:IsControler(tp) and c:IsLocation(LOCATION_MZONE) and aux.IsMaterialListCode(c,89943723) and c:IsType(TYPE_FUSION)
and c:GetDestination()==LOCATION_DECK and re:GetOwner()==c
end
function c14088859.reptg2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return bit.band(r,REASON_EFFECT)~=0 and re
and e:GetHandler():IsAbleToRemove() and eg:IsExists(c14088859.repfilter2,1,nil,tp,re) end
if Duel.SelectEffectYesNo(tp,e:GetHandler(),aux.Stringid(14088859,1)) then
return true
else return false end
end
function c14088859.repop2(e,tp,eg,ep,ev,re,r,rp)
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_EFFECT)
end
function c14088859.repval2(e,c)
return c:IsControler(e:GetHandlerPlayer()) and c:IsLocation(LOCATION_MZONE) and aux.IsMaterialListCode(c,89943723) and c:IsType(TYPE_FUSION)
end
|
gpl-2.0
|
ps-intelegencia-analytics/testRepo
|
sites/all/modules/openlayers/src/Plugin/Interaction/InlineJS/InlineJS.php
|
2215
|
<?php
/**
* @file
* Interaction: JS.
*/
namespace Drupal\openlayers\Plugin\Interaction\InlineJS;
use Drupal\openlayers\Component\Annotation\OpenlayersPlugin;
use Drupal\openlayers\Types\Interaction;
use Drupal\service_container\Messenger\MessengerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\service_container\Legacy\Drupal7;
/**
* Class InlineJS.
*
* @OpenlayersPlugin(
* id = "InlineJS",
* arguments = {
* "@module_handler",
* "@messenger",
* "@drupal7"
* }
* )
*
*/
class InlineJS extends Interaction {
/**
* Constructs an InlineJS plugin.
*
* @param @todo
* @param @todo
* @param @todo
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, ModuleHandlerInterface $module_handler, MessengerInterface $messenger, Drupal7 $drupal7) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->moduleHandler = $module_handler;
$this->messenger = $messenger;
$this->drupal7 = $drupal7;
}
/**
* {@inheritdoc}
*/
public function optionsForm(&$form, &$form_state) {
$attached = array();
if ($this->moduleHandler->moduleExists('ace_editor')) {
$attached = array(
'library' => array(
array('ace_editor', 'ace-editor'),
),
'js' => array(
$this->drupal7->drupal_get_path('module', 'openlayers') . '/js/openlayers.editor.js',
),
);
}
else {
$this->messenger->addMessage(t('To get syntax highlighting, you should install the module <a href="@url1">ace_editor</a> and its <a href="@url2">library</a>.', array('@url1' => 'http://drupal.org/project/ace_editor', '@url2' => 'http://ace.c9.io/')), 'warning');
}
$form['options']['javascript'] = array(
'#type' => 'textarea',
'#title' => t('Javascript'),
'#description' => t('Javascript to evaluate. The available variable is: <em>data</em>. You must create the openlayers variable <em>interaction</em>.'),
'#rows' => 15,
'#default_value' => $this->getOption('javascript'),
'#attributes' => array(
'data-editor' => 'javascript',
),
'#attached' => $attached,
);
}
}
|
gpl-2.0
|
jblanford/Uber-Web-Site
|
sites/all/modules/civicrm/extern/soap.php
|
2429
|
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.1 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2011 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
// patch for CRM-3154
if ( phpversion( ) == "5.2.2" &&
! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents('php://input');
}
session_start( );
require_once '../civicrm.config.php';
require_once 'CRM/Core/Config.php';
$server = new SoapServer(null,
array('uri' => 'urn:civicrm',
'soap_version' => SOAP_1_2 ) );
require_once 'CRM/Utils/SoapServer.php';
$crm_soap = new CRM_Utils_SoapServer();
/* Cache the real UF, override it with the SOAP environment */
$config = CRM_Core_Config::singleton();
$server->setClass('CRM_Utils_SoapServer', $config->userFrameworkClass);
$server->setPersistence(SOAP_PERSISTENCE_SESSION);
$server->handle();
|
gpl-2.0
|
arkev/UM-Virtual
|
wp-content/plugins/advanced-iframe/includes/advanced-iframe-admin-faq.php
|
649
|
<?php if ($devOptions['accordeon_menu'] == 'false') { ?>
<div class="ai-anchor" id="vi"></div>
<?php } ?>
<h1><?php _e('FAQ', 'advanced-iframe'); ?></h1>
<div>
<div id="icon-options-general" class="icon_ai">
<br />
</div> <h2>
<?php _e('FAQ', 'advanced-iframe'); ?> </h2>
<p>
<?php _e('The FAQ is not included in the plugin directly as it is updated frequently on the website.' , 'advanced-iframe'); ?></p><p>
<a href="http://www.tinywebgallery.com/blog/advanced-iframe/advanced-iframe-faq" target="_blank" id="faq" class="button-primary"><?php _e('Go to the FAQ' , 'advanced-iframe'); ?></a>
</p>
</div>
|
gpl-2.0
|
kkkyyy03/coffeemix
|
common/js/common.js
|
28866
|
/**
* @file common.js
* @author NAVER (developers@xpressengine.com)
* @brief 몇가지 유용한 & 기본적으로 자주 사용되는 자바스크립트 함수들 모음
**/
(function($) {
/* OS check */
var UA = navigator.userAgent.toLowerCase();
$.os = {
Linux: /linux/.test(UA),
Unix: /x11/.test(UA),
Mac: /mac/.test(UA),
Windows: /win/.test(UA)
};
$.os.name = ($.os.Windows) ? 'Windows' :
($.os.Linux) ? 'Linux' :
($.os.Unix) ? 'Unix' :
($.os.Mac) ? 'Mac' : '';
/* Intercept getScript error due to broken minified script URL */
$(document).ajaxError(function(event, jqxhr, settings, thrownError) {
if(settings.dataType === "script" && (jqxhr.status >= 400 || (jqxhr.responseText && jqxhr.responseText.length < 32))) {
var match = /^(.+)\.min\.(css|js)($|\?)/.exec(settings.url);
if(match) {
$.getScript(match[1] + "." + match[2], settings.success);
}
}
});
/**
* @brief XE 공용 유틸리티 함수
* @namespace XE
*/
window.XE = {
loaded_popup_menus : [],
addedDocument : [],
/**
* @brief 특정 name을 가진 체크박스들의 checked 속성 변경
* @param [itemName='cart',][options={}]
*/
checkboxToggleAll : function(itemName) {
if(!is_def(itemName)) itemName='cart';
var obj;
var options = {
wrap : null,
checked : 'toggle',
doClick : false
};
switch(arguments.length) {
case 1:
if(typeof(arguments[0]) == "string") {
itemName = arguments[0];
} else {
$.extend(options, arguments[0] || {});
itemName = 'cart';
}
break;
case 2:
itemName = arguments[0];
$.extend(options, arguments[1] || {});
}
if(options.doClick === true) options.checked = null;
if(typeof(options.wrap) == "string") options.wrap ='#'+options.wrap;
if(options.wrap) {
obj = $(options.wrap).find('input[name="'+itemName+'"]:checkbox');
} else {
obj = $('input[name="'+itemName+'"]:checkbox');
}
if(options.checked == 'toggle') {
obj.each(function() {
$(this).attr('checked', ($(this).attr('checked')) ? false : true);
});
} else {
if(options.doClick === true) {
obj.click();
} else {
obj.attr('checked', options.checked);
}
}
},
/**
* @brief 문서/회원 등 팝업 메뉴 출력
*/
displayPopupMenu : function(ret_obj, response_tags, params) {
var target_srl = params.target_srl;
var menu_id = params.menu_id;
var menus = ret_obj.menus;
var html = "";
if(this.loaded_popup_menus[menu_id]) {
html = this.loaded_popup_menus[menu_id];
} else {
if(menus) {
var item = menus.item;
if(typeof(item.length)=='undefined' || item.length<1) item = new Array(item);
if(item.length) {
for(var i=0;i<item.length;i++) {
var url = item[i].url;
var str = item[i].str;
var icon = item[i].icon;
var target = item[i].target;
var styleText = "";
var click_str = "";
/* if(icon) styleText = " style=\"background-image:url('"+icon+"')\" "; */
switch(target) {
case "popup" :
click_str = 'onclick="popopen(this.href, \''+target+'\'); return false;"';
break;
case "javascript" :
click_str = 'onclick="'+url+'; return false; "';
url='#';
break;
default :
click_str = 'target="_blank"';
break;
}
html += '<li '+styleText+'><a href="'+url+'" '+click_str+'>'+str+'</a></li> ';
}
}
}
this.loaded_popup_menus[menu_id] = html;
}
/* 레이어 출력 */
if(html) {
var area = $('#popup_menu_area').html('<ul>'+html+'</ul>');
var areaOffset = {top:params.page_y, left:params.page_x};
if(area.outerHeight()+areaOffset.top > $(window).height()+$(window).scrollTop())
areaOffset.top = $(window).height() - area.outerHeight() + $(window).scrollTop();
if(area.outerWidth()+areaOffset.left > $(window).width()+$(window).scrollLeft())
areaOffset.left = $(window).width() - area.outerWidth() + $(window).scrollLeft();
area.css({ top:areaOffset.top, left:areaOffset.left }).show().focus();
}
}
};
}) (jQuery);
/* jQuery(document).ready() */
jQuery(function($) {
/* select - option의 disabled=disabled 속성을 IE에서도 체크하기 위한 함수 */
if($.browser.msie) {
$('select').each(function(i, sels) {
var disabled_exists = false;
var first_enable = [];
for(var j=0; j < sels.options.length; j++) {
if(sels.options[j].disabled) {
sels.options[j].style.color = '#CCCCCC';
disabled_exists = true;
}else{
first_enable[i] = (first_enable[i] > -1) ? first_enable[i] : j;
}
}
if(!disabled_exists) return;
sels.oldonchange = sels.onchange;
sels.onchange = function() {
if(this.options[this.selectedIndex].disabled) {
this.selectedIndex = first_enable[i];
/*
if(this.options.length<=1) this.selectedIndex = -1;
else if(this.selectedIndex < this.options.length - 1) this.selectedIndex++;
else this.selectedIndex--;
*/
} else {
if(this.oldonchange) this.oldonchange();
}
};
if(sels.selectedIndex >= 0 && sels.options[ sels.selectedIndex ].disabled) sels.onchange();
});
}
/* 단락에디터 fold 컴포넌트 펼치기/접기 */
var drEditorFold = $('.xe_content .fold_button');
if(drEditorFold.size()) {
var fold_container = $('div.fold_container', drEditorFold);
$('button.more', drEditorFold).click(function() {
$(this).hide().next('button').show().parent().next(fold_container).show();
});
$('button.less', drEditorFold).click(function() {
$(this).hide().prev('button').show().parent().next(fold_container).hide();
});
}
jQuery('input[type="submit"],button[type="submit"]').click(function(ev){
var $el = jQuery(ev.currentTarget);
setTimeout(function(){
return function(){
$el.attr('disabled', 'disabled');
};
}(), 0);
setTimeout(function(){
return function(){
$el.removeAttr('disabled');
};
}(), 3000);
});
});
(function(){ // String extension methods
function isSameUrl(a,b) {
return (a.replace(/#.*$/, '') === b.replace(/#.*$/, ''));
}
var isArray = Array.isArray || function(obj){ return Object.prototype.toString.call(obj)=='[object Array]'; };
/**
* @brief location.href에서 특정 key의 값을 return
**/
String.prototype.getQuery = function(key) {
var loc = isSameUrl(this, window.location.href) ? current_url : this;
var idx = loc.indexOf('?');
if(idx == -1) return null;
var query_string = loc.substr(idx+1, this.length), args = {};
query_string.replace(/([^=]+)=([^&]*)(&|$)/g, function() { args[arguments[1]] = arguments[2]; });
var q = args[key];
if(typeof(q)=='undefined') q = '';
return q;
};
/**
* @brief location.href에서 특정 key의 값을 return
**/
String.prototype.setQuery = function(key, val) {
var loc = isSameUrl(this, window.location.href) ? current_url : this;
var idx = loc.indexOf('?');
var uri = loc.replace(/#$/, '');
var act, re, v, toReplace, query_string;
if (typeof(val)=='undefined') val = '';
if (idx != -1) {
var args = {}, q_list = [];
query_string = uri.substr(idx + 1, loc.length);
uri = loc.substr(0, idx);
query_string.replace(/([^=]+)=([^&]*)(&|$)/g, function(all,key,val) { args[key] = val; });
args[key] = val;
for (var prop in args) {
if (!args.hasOwnProperty(prop)) continue;
if (!(v = String(args[prop]).trim())) continue;
q_list.push(prop+'='+decodeURI(v));
}
query_string = q_list.join('&');
uri = uri + (query_string ? '?' + encodeURI(query_string) : '');
} else {
if (String(val).trim()) {
query_string = '?' + key + '=' + val;
uri = uri + encodeURI(query_string);
}
}
re = /^https:\/\/([^:\/]+)(:\d+|)/i;
if (re.test(uri)) {
toReplace = 'http://'+RegExp.$1;
if (window.http_port && http_port != 80) toReplace += ':' + http_port;
uri = uri.replace(re, toReplace);
}
var bUseSSL = !!window.enforce_ssl;
if (!bUseSSL && isArray(window.ssl_actions) && (act=uri.getQuery('act'))) {
for (var i=0,c=ssl_actions.length; i < c; i++) {
if (ssl_actions[i] === act) {
bUseSSL = true;
break;
}
}
}
re = /http:\/\/([^:\/]+)(:\d+|)/i;
if (bUseSSL && re.test(uri)) {
toReplace = 'https://'+RegExp.$1;
if (window.https_port && https_port != 443) toReplace += ':' + https_port;
uri = uri.replace(re, toReplace);
}
// insert index.php if it isn't included
uri = uri.replace(/\/(index\.php)?\?/, '/index.php?');
return uri;
};
/**
* @brief string prototype으로 trim 함수 추가
**/
String.prototype.trim = function() {
return this.replace(/(^\s*)|(\s*$)/g, "");
};
})();
/**
* @brief xSleep(micro time)
**/
function xSleep(sec) {
sec = sec / 1000;
var now = new Date();
var sleep = new Date();
while( sleep.getTime() - now.getTime() < sec) {
sleep = new Date();
}
}
/**
* @brief 주어진 인자가 하나라도 defined되어 있지 않으면 false return
**/
function isDef() {
for(var i=0; i < arguments.length; ++i) {
if(typeof(arguments[i]) == "undefined") return false;
}
return true;
}
/**
* @brief 윈도우 오픈
* 열려진 윈도우의 관리를 통해 window.focus()등을 FF에서도 비슷하게 구현함
**/
var winopen_list = [];
function winopen(url, target, attribute) {
if(typeof(xeVid)!='undefined' && url.indexOf(request_uri)>-1 && !url.getQuery('vid')) url = url.setQuery('vid',xeVid);
try {
if(target != "_blank" && winopen_list[target]) {
winopen_list[target].close();
winopen_list[target] = null;
}
} catch(e) {
}
if(typeof(target) == 'undefined') target = '_blank';
if(typeof(attribute) == 'undefined') attribute = '';
var win = window.open(url, target, attribute);
win.focus();
if(target != "_blank") winopen_list[target] = win;
}
/**
* @brief 팝업으로만 띄우기
* common/tpl/popup_layout.html이 요청되는 XE내의 팝업일 경우에 사용
**/
function popopen(url, target) {
if(typeof(target) == "undefined") target = "_blank";
if(typeof(xeVid)!='undefined' && url.indexOf(request_uri)>-1 && !url.getQuery('vid')) url = url.setQuery('vid',xeVid);
winopen(url, target, "width=800,height=600,scrollbars=yes,resizable=yes,toolbars=no");
}
/**
* @brief 메일 보내기용
**/
function sendMailTo(to) {
location.href="mailto:"+to;
}
/**
* @brief url이동 (open_window 값이 N 가 아니면 새창으로 띄움)
**/
function move_url(url, open_window) {
if(!url) return false;
if(typeof(open_window) == 'undefined') open_window = 'N';
if(open_window=='N') {
open_window = false;
} else {
open_window = true;
}
if(/^\./.test(url)) url = request_uri+url;
if(open_window) {
winopen(url);
} else {
location.href=url;
}
return false;
}
/**
* @brief 멀티미디어 출력용 (IE에서 플래쉬/동영상 주변에 점선 생김 방지용)
**/
function displayMultimedia(src, width, height, options) {
/*jslint evil: true */
var html = _displayMultimedia(src, width, height, options);
if(html) document.writeln(html);
}
function _displayMultimedia(src, width, height, options) {
if(src.indexOf('files') === 0) src = request_uri + src;
var defaults = {
wmode : 'transparent',
allowScriptAccess : 'never',
quality : 'high',
flashvars : '',
autostart : false
};
var params = jQuery.extend(defaults, options || {});
var autostart = (params.autostart && params.autostart != 'false') ? 'true' : 'false';
delete(params.autostart);
var clsid = "";
var codebase = "";
var html = "";
if(/\.(gif|jpg|jpeg|bmp|png)$/i.test(src)){
html = '<img src="'+src+'" width="'+width+'" height="'+height+'" />';
} else if(/\.flv$/i.test(src) || /\.mov$/i.test(src) || /\.moov$/i.test(src) || /\.m4v$/i.test(src)) {
html = '<embed src="'+request_uri+'common/img/flvplayer.swf" allowfullscreen="true" allowscriptaccess="never" autostart="'+autostart+'" width="'+width+'" height="'+height+'" flashvars="&file='+src+'&width='+width+'&height='+height+'&autostart='+autostart+'" wmode="'+params.wmode+'" />';
} else if(/\.swf/i.test(src)) {
clsid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
if(typeof(enforce_ssl)!='undefined' && enforce_ssl){ codebase = "https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0"; }
else { codebase = "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0"; }
html = '<object classid="'+clsid+'" codebase="'+codebase+'" width="'+width+'" height="'+height+'" flashvars="'+params.flashvars+'">';
html += '<param name="movie" value="'+src+'" />';
for(var name in params) {
if(params[name] != 'undefined' && params[name] !== '') {
html += '<param name="'+name+'" value="'+params[name]+'" />';
}
}
html += '' + '<embed src="'+src+'" allowscriptaccess="never" autostart="'+autostart+'" width="'+width+'" height="'+height+'" flashvars="'+params.flashvars+'" wmode="'+params.wmode+'"></embed>' + '</object>';
} else {
if (navigator.userAgent.match(/(firefox|opera)/i)) {
// firefox and opera uses 0 or 1 for autostart parameter.
autostart = (params.autostart && params.autostart != 'false') ? '1' : '0';
}
html = '<embed src="'+src+'" allowscriptaccess="never" autostart="'+autostart+'" width="'+width+'" height="'+height+'"';
if(params.wmode == 'transparent') {
html += ' windowlessvideo="1"';
}
html += '></embed>';
}
return html;
}
/**
* @brief 에디터에서 사용되는 내용 여닫는 코드 (고정, zbxe용)
**/
function zbxe_folder_open(id) {
jQuery("#folder_open_"+id).hide();
jQuery("#folder_close_"+id).show();
jQuery("#folder_"+id).show();
}
function zbxe_folder_close(id) {
jQuery("#folder_open_"+id).show();
jQuery("#folder_close_"+id).hide();
jQuery("#folder_"+id).hide();
}
/**
* @brief 팝업의 경우 내용에 맞춰 현 윈도우의 크기를 조절해줌
* 팝업의 내용에 맞게 크기를 늘리는 것은... 쉽게 되지는 않음.. ㅡ.ㅜ
* popup_layout 에서 window.onload 시 자동 요청됨.
**/
function setFixedPopupSize() {
var $ = jQuery, $win = $(window), $pc = $('body>.popup'), w, h, dw, dh, offset, scbw;
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
scbw = 100 - widthWithScroll;
offset = $pc.css({overflow:'scroll'}).offset();
w = $pc.width(10).height(10000).get(0).scrollWidth + offset.left*2;
h = $pc.height(10).width(10000).get(0).scrollHeight + offset.top*2;
if(w < 800) w = 800 + offset.left*2;
dw = $win.width();
dh = $win.height();
// Window 의 너비나 높이는 스크린의 너비나 높이보다 클 수 없다. 스크린의 너비나 높이와 내용의 너비나 높이를 비교해서 최소값을 이용한다.
if(Math.min(w, window.screen.availWidth) != dw) window.resizeBy(Math.min(w, window.screen.availWidth) - dw, 0);
if(Math.min(h, window.screen.availHeight-100) != dh) window.resizeBy(0, Math.min(h, window.screen.availHeight-100) - dh);
$pc.width(Math.min(w, window.screen.availWidth)-offset.left*2).css({overflow:'',height:''});
if(Math.min(h, window.screen.availHeight-100) === window.screen.availHeight-100) {
$pc.width(Math.min(w, window.screen.availWidth)-offset.left*2-scbw).css({overflow:'',height:''});
}
}
/**
* @brief 추천/비추천,스크랩,신고기능등 특정 srl에 대한 특정 module/action을 호출하는 함수
**/
function doCallModuleAction(module, action, target_srl) {
var params = {
target_srl : target_srl,
cur_mid : current_mid,
mid : current_mid
};
exec_xml(module, action, params, completeCallModuleAction);
}
function completeCallModuleAction(ret_obj, response_tags) {
if(ret_obj.message!='success') alert(ret_obj.message);
location.reload();
}
function completeMessage(ret_obj) {
alert(ret_obj.message);
location.reload();
}
/* 언어코드 (lang_type) 쿠키값 변경 */
function doChangeLangType(obj) {
if(typeof(obj) == "string") {
setLangType(obj);
} else {
var val = obj.options[obj.selectedIndex].value;
setLangType(val);
}
location.href = location.href.setQuery('l', '');
}
function setLangType(lang_type) {
var expire = new Date();
expire.setTime(expire.getTime()+ (7000 * 24 * 3600000));
setCookie('lang_type', lang_type, expire, '/');
}
/* 미리보기 */
function doDocumentPreview(obj) {
var fo_obj = obj;
while(fo_obj.nodeName != "FORM") {
fo_obj = fo_obj.parentNode;
}
if(fo_obj.nodeName != "FORM") return;
var editor_sequence = fo_obj.getAttribute('editor_sequence');
var content = editorGetContent(editor_sequence);
var win = window.open("", "previewDocument","toolbars=no,width=700px;height=800px,scrollbars=yes,resizable=yes");
var dummy_obj = jQuery("#previewDocument");
if(!dummy_obj.length) {
jQuery(
'<form id="previewDocument" target="previewDocument" method="post" action="'+request_uri+'">'+
'<input type="hidden" name="module" value="document" />'+
'<input type="hidden" name="act" value="dispDocumentPreview" />'+
'<input type="hidden" name="content" />'+
'</form>'
).appendTo(document.body);
dummy_obj = jQuery("#previewDocument")[0];
} else {
dummy_obj = dummy_obj[0];
}
if(dummy_obj) {
dummy_obj.content.value = content;
dummy_obj.submit();
}
}
/* 게시글 저장 */
function doDocumentSave(obj) {
var editor_sequence = obj.form.getAttribute('editor_sequence');
var prev_content = editorRelKeys[editor_sequence].content.value;
if(typeof(editor_sequence)!='undefined' && editor_sequence && typeof(editorRelKeys)!='undefined' && typeof(editorGetContent)=='function') {
var content = editorGetContent(editor_sequence);
editorRelKeys[editor_sequence].content.value = content;
}
var params={}, responses=['error','message','document_srl'], elms=obj.form.elements, data=jQuery(obj.form).serializeArray();
jQuery.each(data, function(i, field){
var val = jQuery.trim(field.value);
if(!val) return true;
if(/\[\]$/.test(field.name)) field.name = field.name.replace(/\[\]$/, '');
if(params[field.name]) params[field.name] += '|@|'+val;
else params[field.name] = field.value;
});
exec_xml('document','procDocumentTempSave', params, completeDocumentSave, responses, params, obj.form);
editorRelKeys[editor_sequence].content.value = prev_content;
return false;
}
function completeDocumentSave(ret_obj) {
jQuery('input[name=document_srl]').eq(0).val(ret_obj.document_srl);
alert(ret_obj.message);
}
/* 저장된 게시글 불러오기 */
var objForSavedDoc = null;
function doDocumentLoad(obj) {
// 저장된 게시글 목록 불러오기
objForSavedDoc = obj.form;
popopen(request_uri.setQuery('module','document').setQuery('act','dispTempSavedList'));
}
/* 저장된 게시글의 선택 */
function doDocumentSelect(document_srl, module) {
if(!opener || !opener.objForSavedDoc) {
window.close();
return;
}
if(module===undefined) {
module = 'document';
}
// 게시글을 가져와서 등록하기
switch(module) {
case 'page' :
var url = opener.current_url;
url = url.setQuery('document_srl', document_srl);
if(url.getQuery('act') === 'dispPageAdminMobileContentModify')
{
url = url.setQuery('act', 'dispPageAdminMobileContentModify');
}
else
{
url = url.setQuery('act', 'dispPageAdminContentModify');
}
opener.location.href = url;
break;
default :
opener.location.href = opener.current_url.setQuery('document_srl', document_srl).setQuery('act', 'dispBoardWrite');
break;
}
window.close();
}
/* 스킨 정보 */
function viewSkinInfo(module, skin) {
popopen("./?module=module&act=dispModuleSkinInfo&selected_module="+module+"&skin="+skin, 'SkinInfo');
}
/* 관리자가 문서를 관리하기 위해서 선택시 세션에 넣음 */
var addedDocument = [];
function doAddDocumentCart(obj) {
var srl = obj.value;
addedDocument[addedDocument.length] = srl;
setTimeout(function() { callAddDocumentCart(addedDocument.length); }, 100);
}
function callAddDocumentCart(document_length) {
if(addedDocument.length<1 || document_length != addedDocument.length) return;
var params = [];
params.srls = addedDocument.join(",");
exec_xml("document","procDocumentAddCart", params, null);
addedDocument = [];
}
/* ff의 rgb(a,b,c)를 #... 로 변경 */
function transRGB2Hex(value) {
if(!value) return value;
if(value.indexOf('#') > -1) return value.replace(/^#/, '');
if(value.toLowerCase().indexOf('rgb') < 0) return value;
value = value.replace(/^rgb\(/i, '').replace(/\)$/, '');
value_list = value.split(',');
var hex = '';
for(var i = 0; i < value_list.length; i++) {
var color = parseInt(value_list[i], 10).toString(16);
if(color.length == 1) color = '0'+color;
hex += color;
}
return hex;
}
/* 보안 로그인 모드로 전환 */
function toggleSecuritySignIn() {
var href = location.href;
if(/https:\/\//i.test(href)) location.href = href.replace(/^https/i,'http');
else location.href = href.replace(/^http/i,'https');
}
function reloadDocument() {
location.reload();
}
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
**/
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = 0, c1 = 0, c2 = 0, c3 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
};
/* ----------------------------------------------
* DEPRECATED
* 하위호환용으로 남겨 놓음
* ------------------------------------------- */
if(typeof(resizeImageContents) == 'undefined') {
window.resizeImageContents = function() {};
}
if(typeof(activateOptionDisabled) == 'undefined') {
window.activateOptionDisabled = function() {};
}
objectExtend = jQuery.extend;
/**
* @brief 특정 Element의 display 옵션 토글
**/
function toggleDisplay(objId) {
jQuery('#'+objId).toggle();
}
/**
* @brief 에디터에서 사용하되 내용 여닫는 코드 (zb5beta beta 호환용으로 남겨 놓음)
**/
function svc_folder_open(id) {
jQuery("#_folder_open_"+id).hide();
jQuery("#_folder_close_"+id).show();
jQuery("#_folder_"+id).show();
}
function svc_folder_close(id) {
jQuery("#_folder_open_"+id).show();
jQuery("#_folder_close_"+id).hide();
jQuery("#_folder_"+id).hide();
}
/**
* @brief 날짜 선택 (달력 열기)
**/
function open_calendar(fo_id, day_str, callback_func) {
if(typeof(day_str)=="undefined") day_str = "";
var url = "./common/tpl/calendar.php?";
if(fo_id) url+="fo_id="+fo_id;
if(day_str) url+="&day_str="+day_str;
if(callback_func) url+="&callback_func="+callback_func;
popopen(url, 'Calendar');
}
var loaded_popup_menus = XE.loaded_popup_menus;
function createPopupMenu() {}
function chkPopupMenu() {}
function displayPopupMenu(ret_obj, response_tags, params) {
XE.displayPopupMenu(ret_obj, response_tags, params);
}
function GetObjLeft(obj) {
return jQuery(obj).offset().left;
}
function GetObjTop(obj) {
return jQuery(obj).offset().top;
}
function replaceOuterHTML(obj, html) {
jQuery(obj).replaceWith(html);
}
function getOuterHTML(obj) {
return jQuery(obj).html().trim();
}
function setCookie(name, value, expire, path) {
var s_cookie = name + "=" + escape(value) +
((!expire) ? "" : ("; expires=" + expire.toGMTString())) +
"; path=" + ((!path) ? "/" : path);
document.cookie = s_cookie;
}
function getCookie(name) {
var match = document.cookie.match(new RegExp(name+'=(.*?)(?:;|$)'));
if(match) return unescape(match[1]);
}
function is_def(v) {
return (typeof(v)!='undefined');
}
function ucfirst(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function get_by_id(id) {
return document.getElementById(id);
}
jQuery(function($){
// display popup menu that contains member actions and document actions
$(document).on('click', function(evt) {
var $area = $('#popup_menu_area');
if(!$area.length) $area = $('<div id="popup_menu_area" tabindex="0" style="display:none;" />').appendTo(document.body);
// 이전에 호출되었을지 모르는 팝업메뉴 숨김
$area.hide();
var $target = $(evt.target).filter('a,div,span');
if(!$target.length) $target = $(evt.target).closest('a,div,span');
if(!$target.length) return;
// 객체의 className값을 구함
var cls = $target.attr('class'), match;
if(cls) match = cls.match(new RegExp('(?:^| )((document|comment|member)_([1-9]\\d*))(?: |$)',''));
if(!match) return;
// mobile에서 touchstart에 의한 동작 시 pageX, pageY 위치를 구함
if(evt.pageX===undefined || evt.pageY===undefined)
{
var touch = evt.originalEvent.touches[0];
if(touch!==undefined || !touch)
{
touch = evt.originalEvent.changedTouches[0];
}
evt.pageX = touch.pageX;
evt.pageY = touch.pageY;
}
var action = 'get'+ucfirst(match[2])+'Menu';
var params = {
mid : current_mid,
cur_mid : current_mid,
menu_id : match[1],
target_srl : match[3],
cur_act : current_url.getQuery('act'),
page_x : evt.pageX,
page_y : evt.pageY
};
var response_tags = 'error message menus'.split(' ');
// prevent default action
evt.preventDefault();
evt.stopPropagation();
if(is_def(window.xeVid)) params.vid = xeVid;
if(is_def(XE.loaded_popup_menus[params.menu_id])) return XE.displayPopupMenu(params, response_tags, params);
show_waiting_message = false;
exec_xml('member', action, params, XE.displayPopupMenu, response_tags, params);
show_waiting_message = true;
});
/**
* Create popup windows automatically.
* Find anchors that have the '_xe_popup' class, then add popup script to them.
*/
$('a._xe_popup').click(function(){
var $this = $(this), name = $this.attr('name'), href = $this.attr('href'), win;
if(!name) name = '_xe_popup_'+Math.floor(Math.random()*1000);
win = window.open(href, name, 'left=10,top=10,width=10,height=10,resizable=no,scrollbars=no,toolbars=no');
if(win) win.focus();
// cancel default action
return false;
});
// date picker default settings
if($.datepicker) {
$.datepicker.setDefaults({
dateFormat : 'yy-mm-dd'
});
}
});
|
gpl-2.0
|
risingsunm/Contacts_4.0
|
src/com/android/contacts/list/PhoneFavoriteFragment.java
|
25923
|
/*
* Copyright (C) 2011 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.android.contacts.list;
import com.android.contacts.ContactPhotoManager;
import com.android.contacts.ContactTileLoaderFactory;
import com.android.contacts.R;
import com.android.contacts.list.ContactTileAdapter.ContactEntry;
import com.android.contacts.list.PhoneNumberListAdapter.PhoneQuery;
import com.android.contacts.preference.ContactsPreferences;
import com.android.contacts.util.AccountFilterUtil;
import com.android.contacts.widget.TouchListView;
import com.android.contacts.widget.TouchListView.TriggerListener;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Directory;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.provider.Settings;
import com.android.internal.telephony.SubscriptionManager;
import android.provider.Settings.SettingNotFoundException;
import android.telephony.TelephonyManager;
/**
* Fragment for Phone UI's favorite screen.
*
* This fragment contains three kinds of contacts in one screen: "starred", "frequent", and "all"
* contacts. To show them at once, this merges results from {@link ContactTileAdapter} and
* {@link PhoneNumberListAdapter} into one unified list using {@link PhoneFavoriteMergedAdapter}.
* A contact filter header is also inserted between those adapters' results.
*/
public class PhoneFavoriteFragment extends Fragment implements OnItemClickListener {
private static final String TAG = PhoneFavoriteFragment.class.getSimpleName();
private static final boolean DEBUG = false;
/**
* Used with LoaderManager.
*/
private static int LOADER_ID_CONTACT_TILE = 1;
private static int LOADER_ID_ALL_CONTACTS = 2;
private static final String KEY_FILTER = "filter";
private static final int REQUEST_CODE_ACCOUNT_FILTER = 1;
public interface Listener {
public void onContactSelected(Uri contactUri);
}
private class ContactTileLoaderListener implements LoaderManager.LoaderCallbacks<Cursor> {
@Override
public CursorLoader onCreateLoader(int id, Bundle args) {
if (DEBUG) Log.d(TAG, "ContactTileLoaderListener#onCreateLoader.");
return ContactTileLoaderFactory.createStrequentPhoneOnlyLoader(getActivity());
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (DEBUG) Log.d(TAG, "ContactTileLoaderListener#onLoadFinished");
mContactTileAdapter.setContactCursor(data);
if (mAllContactsForceReload) {
mAllContactsAdapter.onDataReload();
// Use restartLoader() to make LoaderManager to load the section again.
getLoaderManager().restartLoader(
LOADER_ID_ALL_CONTACTS, null, mAllContactsLoaderListener);
} else if (!mAllContactsLoaderStarted) {
// Load "all" contacts if not loaded yet.
getLoaderManager().initLoader(
LOADER_ID_ALL_CONTACTS, null, mAllContactsLoaderListener);
}
mAllContactsForceReload = false;
mAllContactsLoaderStarted = true;
// Show the filter header with "loading" state.
updateFilterHeaderView();
mAccountFilterHeader.setVisibility(View.VISIBLE);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
if (DEBUG) Log.d(TAG, "ContactTileLoaderListener#onLoaderReset. ");
}
}
private class AllContactsLoaderListener implements LoaderManager.LoaderCallbacks<Cursor> {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (DEBUG) Log.d(TAG, "AllContactsLoaderListener#onCreateLoader");
CursorLoader loader = new CursorLoader(getActivity(), null, null, null, null, null);
mAllContactsAdapter.configureLoader(loader, Directory.DEFAULT);
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (DEBUG) Log.d(TAG, "AllContactsLoaderListener#onLoadFinished");
mAllContactsAdapter.changeCursor(0, data);
updateFilterHeaderView();
mAccountFilterHeaderContainer.setVisibility(View.VISIBLE);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
if (DEBUG) Log.d(TAG, "AllContactsLoaderListener#onLoaderReset. ");
}
}
private class ContactTileAdapterListener implements
ContactTileAdapter.Listener {
@Override
public void onContactSelected(Uri contactUri, Rect targetRect) {
if (mListener != null) {
/*
* Begin: Modified by wqiang for ClickFavorite_to_Contact
* 2012/08/03
*/
mListener.onContactSelected(contactUri);
// startActivity(new Intent(Intent.ACTION_VIEW, contactUri));
/*
* End: Modified by wqiang for ClickFavorite_to_Contact
* 2012/08/03
*/
}
}
}
private class FilterHeaderClickListener implements OnClickListener {
@Override
public void onClick(View view) {
AccountFilterUtil.startAccountFilterActivityForResult(
PhoneFavoriteFragment.this, REQUEST_CODE_ACCOUNT_FILTER);
}
}
private class ContactsPreferenceChangeListener implements
ContactsPreferences.ChangeListener {
@Override
public void onChange() {
if (loadContactsPreferences()) {
requestReloadAllContacts();
}
}
}
/* Begin: Modified by wqiang for ClickFavorite_to_Contact 2012/08/03 */
private class ScrollListener implements ListView.OnScrollListener {
private boolean mShouldShowFastScroller;
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// FastScroller should be visible only when the user is seeing "all"
// contacts section.
final boolean shouldShow = mAdapter
.shouldShowFirstScroller(firstVisibleItem);
if (shouldShow != mShouldShowFastScroller) {
mListView.setVerticalScrollBarEnabled(shouldShow);
mListView.setFastScrollEnabled(shouldShow);
mListView.setFastScrollAlwaysVisible(shouldShow);
mShouldShowFastScroller = shouldShow;
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
/* End: Modified by wqiang for ClickFavorite_to_Contact 2012/08/03 */
private Listener mListener;
/* Begin: Modified by wqiang for ClickFavorite_to_Contact 2012/08/03 */
private PhoneFavoriteMergedAdapter mAdapter;
// private ContactTileAdapter mAdapter;
/* End: Modified by wqiang for ClickFavorite_to_Contact 2012/08/03 */
private ContactTileAdapter mContactTileAdapter;
private PhoneNumberListAdapter mAllContactsAdapter;
/**
* true when the loader for {@link PhoneNumberListAdapter} has started already.
*/
private boolean mAllContactsLoaderStarted;
/**
* true when the loader for {@link PhoneNumberListAdapter} must reload "all" contacts again.
* It typically happens when {@link ContactsPreferences} has changed its settings
* (display order and sort order)
*/
private boolean mAllContactsForceReload;
private ContactsPreferences mContactsPrefs;
private ContactListFilter mFilter;
private TextView mEmptyView;
private ListView mListView;
/**
* Layout containing {@link #mAccountFilterHeader}. Used to limit area being "pressed".
*/
private FrameLayout mAccountFilterHeaderContainer;
private View mAccountFilterHeader;
private final ContactTileAdapter.Listener mContactTileAdapterListener =
new ContactTileAdapterListener();
private final LoaderManager.LoaderCallbacks<Cursor> mContactTileLoaderListener =
new ContactTileLoaderListener();
private final LoaderManager.LoaderCallbacks<Cursor> mAllContactsLoaderListener =
new AllContactsLoaderListener();
private final OnClickListener mFilterHeaderClickListener = new FilterHeaderClickListener();
private final ContactsPreferenceChangeListener mContactsPreferenceChangeListener =
new ContactsPreferenceChangeListener();
/* Begin: Modified by sunrise for scroll bar unique 2012-7-30 */
//private final ScrollListener mScrollListener = new ScrollListener();
/*Begin: Modified by wqiang for ClickFavorite_to_Contact 2012/08/03*/
private final ScrollListener mScrollListener = null;
/*End: Modified by wqiang for ClickFavorite_to_Contact 2012/08/03*/
/* End: Modified by sunrise for scroll bar unique 2012-7-30 */
@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
if (savedState != null) {
mFilter = savedState.getParcelable(KEY_FILTER);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_FILTER, mFilter);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContactsPrefs = new ContactsPreferences(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View listLayout = inflater.inflate(
R.layout.phone_contact_tile_list, container, false);
mListView = (ListView) listLayout.findViewById(R.id.contact_tile_list);
mListView.setItemsCanFocus(true);
mListView.setOnItemClickListener(this);
/* Begin: Modified by sunrise for scroll bar unique 2012-7-30 */
//mListView.setVerticalScrollBarEnabled(false);
//mListView.setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_RIGHT);
//mListView.setScrollBarStyle(ListView.SCROLLBARS_OUTSIDE_OVERLAY);
/* End: Modified by sunrise for scroll bar unique 2012-7-30 */
initAdapters(getActivity(), inflater);
mListView.setAdapter(mAdapter);
/* Begin: Modified by sunrise for scroll bar unique 2012-7-30 */
mListView.setVerticalScrollBarEnabled(false);
mListView.setHorizontalScrollBarEnabled(false);
//mListView.setOnScrollListener(mScrollListener);
//mListView.setFastScrollEnabled(false);
//mListView.setFastScrollAlwaysVisible(false);
/* End: Modified by sunrise for scroll bar unique 2012-7-30 */
mEmptyView = (TextView) listLayout.findViewById(R.id.contact_tile_list_empty);
mEmptyView.setText(getString(R.string.listTotalAllContactsZero));
mListView.setEmptyView(mEmptyView);
updateFilterHeaderView();
/*Begin: Modified by bxinchun, add touch view style listview 2012/07/31*/
if (mListView instanceof TouchListView) {
((TouchListView) mListView).setTouchMode(true);
((TouchListView) mListView).setTriggerListener(mTriggerListener);
}
/*End: Modified by bxinchun, add touch view style listview 2012/07/31*/
return listLayout;
}
/*Begin: Added by bxinchun, add touch view style listview 2012/07/31*/
private TriggerListener mTriggerListener = new TriggerListener() {
public boolean isTriggable(int position) {
return mAdapter.isTouchViewItem(position);
}
public void onTrigger(int position, int actionType) {
String number = null;
try {
Object obj = mAdapter.getItem(position);
if (obj == null) { return; }
final int contactTileAdapterCount = mContactTileAdapter.getCount();
if (position < contactTileAdapterCount) {
final int frequentHeaderPosition = mContactTileAdapter.getFrequentHeaderPosition();
if (position > frequentHeaderPosition && obj instanceof ArrayList<?>) {
ArrayList<?> entries = (ArrayList<?>)obj;
if (entries.size() > 0) {
ContactEntry entry = (ContactEntry) entries.get(0);
number = entry == null ? null : entry.phoneNumber;
}
}
} else if (position == contactTileAdapterCount) {
return;
} else {
if (obj instanceof Cursor) {
Cursor cur = (Cursor) obj;
if (cur != null && !cur.isNull(PhoneQuery.PHONE_NUMBER)) {
number = cur.getString(PhoneQuery.PHONE_NUMBER);
}
}
}
/*final int localPosition = position - mContactTileAdapter.getCount() - 1;
number = ((Cursor) mAllContactsAdapter.getItem(localPosition)).getString(PhoneQuery.PHONE_NUMBER);*/
} catch (Exception e) {
System.out.println(e.getMessage());
}
if (TextUtils.isEmpty(number)) return;
//System.out.println("number is:"+number + ", actionTyp :" + actionType);
switch (actionType) {
case LEFT: //sms
Intent smsIntent = new Intent(
Intent.ACTION_SENDTO, Uri.fromParts("sms", number, null));
startActivity(smsIntent);
break;
case RIGHT: //call
Intent phoneIntent = new Intent(
Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", number, null));
/*Begin: Modified by sliangqi for main_call 2012-8-25*/
int subscription = 0;
if (isMultiSimAvailable()) {
try {
subscription = Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.MULTI_SIM_VOICE_CALL_SUBSCRIPTION);
} catch (SettingNotFoundException snfe) {
Log.e(TAG, "Settings Exception Reading Dual Sim Voice Call Values");
}
} else {
subscription = getDefaultSubscription();
}
phoneIntent.putExtra("subscription", subscription);
phoneIntent.putExtra("directDial", true);
/*End: Modified by sliangqi for main_call 2012-8-25*/
startActivity(phoneIntent);
break;
default:
break;
}
}
};
/*Begin: Modified by sliangqi for main_call 2012-8-25*/
public int getDefaultSubscription() {
int subscription = 0;
try {
subscription = Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.DEFAULT_SUBSCRIPTION);
} catch (SettingNotFoundException snfe) {
Log.e(TAG, "Settings Exception Reading Default Subscription");
}
return subscription;
}
private boolean isMultiSimAvailable() {
return TelephonyManager.getTelephonyProperty("gsm.sim.state",0,"").equals("READY")&&TelephonyManager.getTelephonyProperty("gsm.sim.state",1,"").equals("READY");
}
/*End: Modified by sliangqi for main_call 2012-8-25*/
/*End: Added by bxinchun, add touch view style listview 2012/07/31*/
/**
* Constructs and initializes {@link #mContactTileAdapter}, {@link #mAllContactsAdapter}, and
* {@link #mAllContactsAdapter}.
*
* TODO: Move all the code here to {@link PhoneFavoriteMergedAdapter} if possible.
* There are two problems: account header (whose content changes depending on filter settings)
* and OnClickListener (which initiates {@link Activity#startActivityForResult(Intent, int)}).
* See also issue 5429203, 5269692, and 5432286. If we are able to have a singleton for filter,
* this work will become easier.
*/
private void initAdapters(Context context, LayoutInflater inflater) {
mContactTileAdapter = new ContactTileAdapter(context, mContactTileAdapterListener,
getResources().getInteger(R.integer.contact_tile_column_count),
ContactTileAdapter.DisplayType.STREQUENT_PHONE_ONLY);
mContactTileAdapter.setPhotoLoader(ContactPhotoManager.getInstance(context));
// Setup the "all" adapter manually. See also the setup logic in ContactEntryListFragment.
mAllContactsAdapter = new PhoneNumberListAdapter(context);
mAllContactsAdapter.setDisplayPhotos(true);
mAllContactsAdapter.setQuickContactEnabled(true);
mAllContactsAdapter.setSearchMode(false);
mAllContactsAdapter.setIncludeProfile(false);
mAllContactsAdapter.setSelectionVisible(false);
mAllContactsAdapter.setDarkTheme(true);
mAllContactsAdapter.setPhotoLoader(ContactPhotoManager.getInstance(context));
// Disable directory header.
mAllContactsAdapter.setHasHeader(0, false);
// Show A-Z section index.
mAllContactsAdapter.setSectionHeaderDisplayEnabled(true);
// Disable pinned header. It doesn't work with this fragment.
mAllContactsAdapter.setPinnedPartitionHeadersEnabled(false);
// Put photos on left for consistency with "frequent" contacts section.
mAllContactsAdapter.setPhotoPosition(ContactListItemView.PhotoPosition.LEFT);
if (mFilter != null) {
mAllContactsAdapter.setFilter(mFilter);
}
// Create the account filter header but keep it hidden until "all" contacts are loaded.
mAccountFilterHeaderContainer = new FrameLayout(context, null);
mAccountFilterHeader = inflater.inflate(R.layout.account_filter_header_for_phone_favorite,
mListView, false);
mAccountFilterHeader.setOnClickListener(mFilterHeaderClickListener);
mAccountFilterHeaderContainer.addView(mAccountFilterHeader);
mAccountFilterHeaderContainer.setVisibility(View.GONE);
/* Begin: Modified by wqiang for ClickFavorite_to_Contact 2012/08/03 */
mAdapter = new PhoneFavoriteMergedAdapter(context, mContactTileAdapter,
mAccountFilterHeaderContainer, mAllContactsAdapter);
// mAdapter = mContactTileAdapter;
/* End: Modified by wqiang for ClickFavorite_to_Contact 2012/08/03 */
}
@Override
public void onStart() {
super.onStart();
mContactsPrefs.registerChangeListener(mContactsPreferenceChangeListener);
// If ContactsPreferences has changed, we need to reload "all" contacts with the new
// settings. If mAllContactsFoarceReload is already true, it should be kept.
if (loadContactsPreferences()) {
mAllContactsForceReload = true;
}
// Use initLoader() instead of reloadLoader() to refraing unnecessary reload.
// This method call implicitly assures ContactTileLoaderListener's onLoadFinished() will
// be called, on which we'll check if "all" contacts should be reloaded again or not.
getLoaderManager().initLoader(LOADER_ID_CONTACT_TILE, null, mContactTileLoaderListener);
}
@Override
public void onStop() {
super.onStop();
mContactsPrefs.unregisterChangeListener();
}
/**
* {@inheritDoc}
*
* This is only effective for elements provided by {@link #mContactTileAdapter}.
* {@link #mContactTileAdapter} has its own logic for click events.
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final int contactTileAdapterCount = mContactTileAdapter.getCount();
if (position <= contactTileAdapterCount) {
Log.e(TAG, "onItemClick() event for unexpected position. "
+ "The position " + position + " is before \"all\" section. Ignored.");
} else {
final int localPosition = position - mContactTileAdapter.getCount() - 1;
if (mListener != null) {
mListener.onContactSelected(mAllContactsAdapter.getDataUri(localPosition));
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_ACCOUNT_FILTER) {
if (getActivity() != null) {
AccountFilterUtil.handleAccountFilterResult(
ContactListFilterController.getInstance(getActivity()), resultCode, data);
} else {
Log.e(TAG, "getActivity() returns null during Fragment#onActivityResult()");
}
}
}
private boolean loadContactsPreferences() {
if (mContactsPrefs == null || mAllContactsAdapter == null) {
return false;
}
boolean changed = false;
if (mAllContactsAdapter.getContactNameDisplayOrder() != mContactsPrefs.getDisplayOrder()) {
mAllContactsAdapter.setContactNameDisplayOrder(mContactsPrefs.getDisplayOrder());
changed = true;
}
if (mAllContactsAdapter.getSortOrder() != mContactsPrefs.getSortOrder()) {
mAllContactsAdapter.setSortOrder(mContactsPrefs.getSortOrder());
changed = true;
}
return changed;
}
/**
* Requests to reload "all" contacts. If the section is already loaded, this method will
* force reloading it now. If the section isn't loaded yet, the actual load may be done later
* (on {@link #onStart()}.
*/
private void requestReloadAllContacts() {
if (DEBUG) {
Log.d(TAG, "requestReloadAllContacts()"
+ " mAllContactsAdapter: " + mAllContactsAdapter
+ ", mAllContactsLoaderStarted: " + mAllContactsLoaderStarted);
}
if (mAllContactsAdapter == null || !mAllContactsLoaderStarted) {
// Remember this request until next load on onStart().
mAllContactsForceReload = true;
return;
}
if (DEBUG) Log.d(TAG, "Reload \"all\" contacts now.");
mAllContactsAdapter.onDataReload();
// Use restartLoader() to make LoaderManager to load the section again.
getLoaderManager().restartLoader(LOADER_ID_ALL_CONTACTS, null, mAllContactsLoaderListener);
}
private void updateFilterHeaderView() {
final ContactListFilter filter = getFilter();
if (mAccountFilterHeader == null || mAllContactsAdapter == null || filter == null) {
return;
}
AccountFilterUtil.updateAccountFilterTitleForPhone(
mAccountFilterHeader, filter, mAllContactsAdapter.isLoading(), true);
}
public ContactListFilter getFilter() {
return mFilter;
}
public void setFilter(ContactListFilter filter) {
if ((mFilter == null && filter == null) || (mFilter != null && mFilter.equals(filter))) {
return;
}
if (DEBUG) {
Log.d(TAG, "setFilter(). old filter (" + mFilter
+ ") will be replaced with new filter (" + filter + ")");
}
mFilter = filter;
if (mAllContactsAdapter != null) {
mAllContactsAdapter.setFilter(mFilter);
requestReloadAllContacts();
updateFilterHeaderView();
}
}
public void setListener(Listener listener) {
mListener = listener;
}
}
|
gpl-2.0
|
fonea/spot-light
|
web/modules/custom/velon_alter_fields/tests/src/Functional/LoadTest.php
|
903
|
<?php
namespace Drupal\Tests\velon_alter_fields\Functional;
use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;
/**
* Simple test to ensure that main page loads with module enabled.
*
* @group velon_alter_fields
*/
class LoadTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['velon_alter_fields'];
/**
* A user with permission to administer site configuration.
*
* @var \Drupal\user\UserInterface
*/
protected $user;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->user = $this->drupalCreateUser(['administer site configuration']);
$this->drupalLogin($this->user);
}
/**
* Tests that the home page loads with a 200 response.
*/
public function testLoad() {
$this->drupalGet(Url::fromRoute('<front>'));
$this->assertResponse(200);
}
}
|
gpl-2.0
|
bergvogel/stayuplate
|
wp-content/themes/snapshopWP/woocommerce/single-product/up-sells.php
|
1450
|
<?php
/**
* Single Product Up-Sells
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $product, $woocommerce, $woocommerce_loop, $snpshpwp_data;
$upsells = $product->get_upsells();
if ( sizeof( $upsells ) == 0 ) return;
$meta_query = $woocommerce->query->get_meta_query();
$args = array(
'post_type' => 'product',
'ignore_sticky_posts' => 1,
'no_found_rows' => 1,
'posts_per_page' => $snpshpwp_data['woo-columns-rel'],
'orderby' => $orderby,
'post__in' => $upsells,
'post__not_in' => array( $product->id ),
'meta_query' => $meta_query
);
$products = new WP_Query( $args );
$woocommerce_loop['columns'] = apply_filters( 'loop_shop_columns', $snpshpwp_data['woo-columns-rel'] );
if ( $products->have_posts() ) : ?>
<div class="upsells products">
<h3 class="uppercase text-center margin-bottom48"><?php echo __( 'These products are usually ordered with', 'snpshpwp' ) .' '. get_the_title() . ' ' . __('by our customers', 'snpshpwp'); ?></h3>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php woocommerce_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
</div>
<?php endif;
wp_reset_postdata();
|
gpl-2.0
|
rex-xxx/mt6572_x201
|
hardware/libhardware_legacy/audio/A2dpAudioInterface.cpp
|
13930
|
/*
* Copyright (C) 2008 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.
*/
#include <math.h>
//#define LOG_NDEBUG 0
#define LOG_TAG "A2dpAudioInterface"
#include <utils/Log.h>
#include <utils/String8.h>
#include "A2dpAudioInterface.h"
#include "audio/liba2dp.h"
#include <hardware_legacy/power.h>
namespace android_audio_legacy {
static const char *sA2dpWakeLock = "A2dpOutputStream";
#define MAX_WRITE_RETRIES 5
// ----------------------------------------------------------------------------
//AudioHardwareInterface* A2dpAudioInterface::createA2dpInterface()
//{
// AudioHardwareInterface* hw = 0;
//
// hw = AudioHardwareInterface::create();
// ALOGD("new A2dpAudioInterface(hw: %p)", hw);
// hw = new A2dpAudioInterface(hw);
// return hw;
//}
A2dpAudioInterface::A2dpAudioInterface(AudioHardwareInterface* hw) :
mOutput(0), mHardwareInterface(hw), mBluetoothEnabled(true), mSuspended(false)
{
}
A2dpAudioInterface::~A2dpAudioInterface()
{
closeOutputStream((AudioStreamOut *)mOutput);
delete mHardwareInterface;
}
status_t A2dpAudioInterface::initCheck()
{
if (mHardwareInterface == 0) return NO_INIT;
return mHardwareInterface->initCheck();
}
AudioStreamOut* A2dpAudioInterface::openOutputStream(
uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status)
{
if (!audio_is_a2dp_device(devices)) {
ALOGV("A2dpAudioInterface::openOutputStream() open HW device: %x", devices);
return mHardwareInterface->openOutputStream(devices, format, channels, sampleRate, status);
}
status_t err = 0;
// only one output stream allowed
if (mOutput) {
if (status)
*status = -1;
return NULL;
}
// create new output stream
A2dpAudioStreamOut* out = new A2dpAudioStreamOut();
if ((err = out->set(devices, format, channels, sampleRate)) == NO_ERROR) {
mOutput = out;
mOutput->setBluetoothEnabled(mBluetoothEnabled);
mOutput->setSuspended(mSuspended);
} else {
delete out;
}
if (status)
*status = err;
return mOutput;
}
void A2dpAudioInterface::closeOutputStream(AudioStreamOut* out) {
if (mOutput == 0 || mOutput != out) {
mHardwareInterface->closeOutputStream(out);
}
else {
delete mOutput;
mOutput = 0;
}
}
AudioStreamIn* A2dpAudioInterface::openInputStream(
uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status,
AudioSystem::audio_in_acoustics acoustics)
{
return mHardwareInterface->openInputStream(devices, format, channels, sampleRate, status, acoustics);
}
void A2dpAudioInterface::closeInputStream(AudioStreamIn* in)
{
return mHardwareInterface->closeInputStream(in);
}
status_t A2dpAudioInterface::setMode(int mode)
{
return mHardwareInterface->setMode(mode);
}
status_t A2dpAudioInterface::setMicMute(bool state)
{
return mHardwareInterface->setMicMute(state);
}
status_t A2dpAudioInterface::getMicMute(bool* state)
{
return mHardwareInterface->getMicMute(state);
}
status_t A2dpAudioInterface::setParameters(const String8& keyValuePairs)
{
AudioParameter param = AudioParameter(keyValuePairs);
String8 value;
String8 key;
status_t status = NO_ERROR;
ALOGV("setParameters() %s", keyValuePairs.string());
key = "bluetooth_enabled";
if (param.get(key, value) == NO_ERROR) {
mBluetoothEnabled = (value == "true");
if (mOutput) {
mOutput->setBluetoothEnabled(mBluetoothEnabled);
}
param.remove(key);
}
key = String8("A2dpSuspended");
if (param.get(key, value) == NO_ERROR) {
mSuspended = (value == "true");
if (mOutput) {
mOutput->setSuspended(mSuspended);
}
param.remove(key);
}
if (param.size()) {
status_t hwStatus = mHardwareInterface->setParameters(param.toString());
if (status == NO_ERROR) {
status = hwStatus;
}
}
return status;
}
String8 A2dpAudioInterface::getParameters(const String8& keys)
{
AudioParameter param = AudioParameter(keys);
AudioParameter a2dpParam = AudioParameter();
String8 value;
String8 key;
key = "bluetooth_enabled";
if (param.get(key, value) == NO_ERROR) {
value = mBluetoothEnabled ? "true" : "false";
a2dpParam.add(key, value);
param.remove(key);
}
key = "A2dpSuspended";
if (param.get(key, value) == NO_ERROR) {
value = mSuspended ? "true" : "false";
a2dpParam.add(key, value);
param.remove(key);
}
String8 keyValuePairs = a2dpParam.toString();
if (param.size()) {
if (keyValuePairs != "") {
keyValuePairs += ";";
}
keyValuePairs += mHardwareInterface->getParameters(param.toString());
}
ALOGV("getParameters() %s", keyValuePairs.string());
return keyValuePairs;
}
size_t A2dpAudioInterface::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
{
return mHardwareInterface->getInputBufferSize(sampleRate, format, channelCount);
}
status_t A2dpAudioInterface::setVoiceVolume(float v)
{
return mHardwareInterface->setVoiceVolume(v);
}
status_t A2dpAudioInterface::setMasterVolume(float v)
{
return mHardwareInterface->setMasterVolume(v);
}
status_t A2dpAudioInterface::dump(int fd, const Vector<String16>& args)
{
return mHardwareInterface->dumpState(fd, args);
}
// ----------------------------------------------------------------------------
A2dpAudioInterface::A2dpAudioStreamOut::A2dpAudioStreamOut() :
mFd(-1), mStandby(true), mStartCount(0), mRetryCount(0), mData(NULL),
// assume BT enabled to start, this is safe because its only the
// enabled->disabled transition we are worried about
mBluetoothEnabled(true), mDevice(0), mClosing(false), mSuspended(false)
{
// use any address by default
strcpy(mA2dpAddress, "00:00:00:00:00:00");
init();
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::set(
uint32_t device, int *pFormat, uint32_t *pChannels, uint32_t *pRate)
{
int lFormat = pFormat ? *pFormat : 0;
uint32_t lChannels = pChannels ? *pChannels : 0;
uint32_t lRate = pRate ? *pRate : 0;
ALOGD("A2dpAudioStreamOut::set %x, %d, %d, %d\n", device, lFormat, lChannels, lRate);
// fix up defaults
if (lFormat == 0) lFormat = format();
if (lChannels == 0) lChannels = channels();
if (lRate == 0) lRate = sampleRate();
// check values
if ((lFormat != format()) ||
(lChannels != channels()) ||
(lRate != sampleRate())){
if (pFormat) *pFormat = format();
if (pChannels) *pChannels = channels();
if (pRate) *pRate = sampleRate();
return BAD_VALUE;
}
if (pFormat) *pFormat = lFormat;
if (pChannels) *pChannels = lChannels;
if (pRate) *pRate = lRate;
mDevice = device;
mBufferDurationUs = ((bufferSize() * 1000 )/ frameSize() / sampleRate()) * 1000;
return NO_ERROR;
}
A2dpAudioInterface::A2dpAudioStreamOut::~A2dpAudioStreamOut()
{
ALOGV("A2dpAudioStreamOut destructor");
close();
ALOGV("A2dpAudioStreamOut destructor returning from close()");
}
ssize_t A2dpAudioInterface::A2dpAudioStreamOut::write(const void* buffer, size_t bytes)
{
status_t status = -1;
{
Mutex::Autolock lock(mLock);
size_t remaining = bytes;
if (!mBluetoothEnabled || mClosing || mSuspended) {
ALOGV("A2dpAudioStreamOut::write(), but bluetooth disabled \
mBluetoothEnabled %d, mClosing %d, mSuspended %d",
mBluetoothEnabled, mClosing, mSuspended);
goto Error;
}
if (mStandby) {
acquire_wake_lock (PARTIAL_WAKE_LOCK, sA2dpWakeLock);
mStandby = false;
mLastWriteTime = systemTime();
}
status = init();
if (status < 0)
goto Error;
int retries = MAX_WRITE_RETRIES;
while (remaining > 0 && retries) {
status = a2dp_write(mData, buffer, remaining);
if (status < 0) {
ALOGE("a2dp_write failed err: %d\n", status);
goto Error;
}
if (status == 0) {
retries--;
}
remaining -= status;
buffer = (char *)buffer + status;
}
// if A2DP sink runs abnormally fast, sleep a little so that audioflinger mixer thread
// does no spin and starve other threads.
// NOTE: It is likely that the A2DP headset is being disconnected
nsecs_t now = systemTime();
if ((uint32_t)ns2us(now - mLastWriteTime) < (mBufferDurationUs >> 2)) {
ALOGV("A2DP sink runs too fast");
usleep(mBufferDurationUs - (uint32_t)ns2us(now - mLastWriteTime));
}
mLastWriteTime = now;
return bytes;
}
Error:
standby();
// Simulate audio output timing in case of error
usleep(mBufferDurationUs);
return status;
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::init()
{
if (!mData) {
status_t status = a2dp_init(44100, 2, &mData);
if (status < 0) {
ALOGE("a2dp_init failed err: %d\n", status);
mData = NULL;
return status;
}
a2dp_set_sink(mData, mA2dpAddress);
}
return 0;
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::setMuteModeNormal(int Mutecount)
{
WriteMuteCounter = Mutecount;
return NO_ERROR;
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::standby()
{
Mutex::Autolock lock(mLock);
return standby_l();
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::standby_l()
{
int result = NO_ERROR;
if (!mStandby) {
ALOGV_IF(mClosing || !mBluetoothEnabled, "Standby skip stop: closing %d enabled %d",
mClosing, mBluetoothEnabled);
if (!mClosing && mBluetoothEnabled) {
result = a2dp_stop(mData);
}
release_wake_lock(sA2dpWakeLock);
mStandby = true;
}
return result;
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::setParameters(const String8& keyValuePairs)
{
AudioParameter param = AudioParameter(keyValuePairs);
String8 value;
String8 key = String8("a2dp_sink_address");
status_t status = NO_ERROR;
int device;
ALOGV("A2dpAudioStreamOut::setParameters() %s", keyValuePairs.string());
if (param.get(key, value) == NO_ERROR) {
if (value.length() != strlen("00:00:00:00:00:00")) {
status = BAD_VALUE;
} else {
setAddress(value.string());
}
param.remove(key);
}
key = String8("closing");
if (param.get(key, value) == NO_ERROR) {
mClosing = (value == "true");
if (mClosing) {
standby();
}
param.remove(key);
}
key = AudioParameter::keyRouting;
if (param.getInt(key, device) == NO_ERROR) {
if (audio_is_a2dp_device(device)) {
mDevice = device;
status = NO_ERROR;
} else {
status = BAD_VALUE;
}
param.remove(key);
}
if (param.size()) {
status = BAD_VALUE;
}
return status;
}
String8 A2dpAudioInterface::A2dpAudioStreamOut::getParameters(const String8& keys)
{
AudioParameter param = AudioParameter(keys);
String8 value;
String8 key = String8("a2dp_sink_address");
if (param.get(key, value) == NO_ERROR) {
value = mA2dpAddress;
param.add(key, value);
}
key = AudioParameter::keyRouting;
if (param.get(key, value) == NO_ERROR) {
param.addInt(key, (int)mDevice);
}
ALOGV("A2dpAudioStreamOut::getParameters() %s", param.toString().string());
return param.toString();
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::setAddress(const char* address)
{
Mutex::Autolock lock(mLock);
if (strlen(address) != strlen("00:00:00:00:00:00"))
return -EINVAL;
strcpy(mA2dpAddress, address);
if (mData)
a2dp_set_sink(mData, mA2dpAddress);
return NO_ERROR;
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::setBluetoothEnabled(bool enabled)
{
ALOGD("setBluetoothEnabled %d", enabled);
Mutex::Autolock lock(mLock);
mBluetoothEnabled = enabled;
if (!enabled) {
return close_l();
}
return NO_ERROR;
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::setSuspended(bool onOff)
{
ALOGV("setSuspended %d", onOff);
mSuspended = onOff;
standby();
return NO_ERROR;
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::close()
{
Mutex::Autolock lock(mLock);
ALOGV("A2dpAudioStreamOut::close() calling close_l()");
return close_l();
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::close_l()
{
standby_l();
if (mData) {
ALOGV("A2dpAudioStreamOut::close_l() calling a2dp_cleanup(mData)");
a2dp_cleanup(mData);
mData = NULL;
}
return NO_ERROR;
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::dump(int fd, const Vector<String16>& args)
{
return NO_ERROR;
}
status_t A2dpAudioInterface::A2dpAudioStreamOut::getRenderPosition(uint32_t *driverFrames)
{
//TODO: enable when supported by driver
return INVALID_OPERATION;
}
}; // namespace android
|
gpl-2.0
|
dusik/realejuventudfan
|
core/lib/Drupal/Core/TypedData/ListInterface.php
|
736
|
<?php
/**
* @file
* Definition of Drupal\Core\TypedData\ListInterface.
*/
namespace Drupal\Core\TypedData;
use ArrayAccess;
use Countable;
use Traversable;
/**
* Interface for a list of typed data.
*
* A list of typed data contains only items of the same type, is ordered and may
* contain duplicates.
*
* When implementing this interface which extends Traversable, make sure to list
* IteratorAggregate or Iterator before this interface in the implements clause.
*/
interface ListInterface extends ArrayAccess, Countable, Traversable {
/**
* Determines whether the list contains any non-empty items.
*
* @return boolean
* TRUE if the list is empty, FALSE otherwise.
*/
public function isEmpty();
}
|
gpl-2.0
|
jeffgdotorg/opennms
|
features/flows/api/src/main/java/org/opennms/netmgt/flows/api/EnrichedFlowForwarder.java
|
1330
|
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2020 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2020 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 Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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.netmgt.flows.api;
public interface EnrichedFlowForwarder {
void forward(EnrichedFlow enrichedFlow);
}
|
gpl-2.0
|
thereelists/scs
|
wp-content/plugins/plainview-activity-monitor/vendor/plainview/sdk/wordpress/table/table.php
|
1858
|
<?php
namespace plainview\sdk\wordpress\table;
/**
@brief Extends the table class by using the Wordpress base class to translate table object names and titles.
@par Changelog
- 20131019 top() added.
- 20131015 Added bulk_actions();
- 20130509 Complete rework moving all of the translation to the parent table class. Only _() is overridden.
- 20130507 Code: td() and th() can return existing cells.
- 20130506 New: trait has title_().
Code: Renamed wordpress_table_object to wordpress_table_element.
@author Edward Plainview edward@plainview.se
@copyright GPL v3
@since 20130430
@version 20131019
**/
class table
extends \plainview\sdk\table\table
{
use \plainview\sdk\traits\method_chaining;
/**
@brief The \\plainview\\sdk\\table\\wordpress\\base object that created this class.
**/
public $base;
public function __construct( $base )
{
parent::__construct();
$this->base = $base;
}
/**
@brief Use the base's _() method to translate this string. sprintf aware.
@param string $string String to translate.
@return string Translated string.
**/
public function _( $string )
{
return call_user_func_array( array( $this->base, '_' ), func_get_args() );
}
public function __toString()
{
$r = '';
if ( isset( $this->top ) )
$r .= $this->top;
$r .= parent::__toString();
return $r;
}
/**
@brief Create the top tablenav row.
@since 20131019
**/
public function top()
{
if ( ! isset( $this->top ) )
$this->top = new top\top;
return $this->top;
}
/**
@brief Create the bulk actions in the top of the table.
@since 20131015
**/
public function bulk_actions()
{
$top = $this->top();
if ( ! $top->left->has( 'bulk_actions' ) )
$top->left->put( 'bulk_actions', new top\bulkactions( $this ) );
return $top->left->get( 'bulk_actions' );
}
}
|
gpl-2.0
|
gakuba/mtdruittsdachurch
|
wp-content/themes/resurrect/includes/body.php
|
1861
|
<?php
/**
* <body> Functions
*
* @package Resurrect
* @subpackage Functions
* @copyright Copyright (c) 2013, churchthemes.com
* @link http://churchthemes.com/themes/resurrect
* @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* @since 1.0
*/
// No direct access
if ( ! defined( 'ABSPATH' ) ) exit;
/*******************************************
* BODY CLASSES
*******************************************/
/**
* Add helper classes to <body>
*
* @since 1.0
* @param array $classes Classes currently being added to body tag
* @return array Modified classes
*/
function resurrect_add_body_classes( $classes ) {
// Fonts
$fonts_areas = array( 'logo_font', 'heading_font', 'menu_font', 'body_font' );
foreach ( $fonts_areas as $font_area ) {
$font_name = ctfw_customization( $font_area );
$font_name = sanitize_title( $font_name );
$font_area = str_replace( '_', '-', $font_area );
$classes[] = 'resurrect-' . $font_area . '-' . $font_name;
}
// No logo
if ( ! ctfw_customization( 'logo_image' ) ) {
$classes[] = 'resurrect-no-logo';
}
// Fullscreen background image
if ( ctfw_customization( 'background_image_fullscreen' ) ) {
$classes[] = 'resurrect-background-image-fullscreen';
}
// Background image name
// Handy for setting specific background color to match
$background_image = get_background_image();
if ( $background_image ) {
$background_image_info = pathinfo( basename( $background_image ) );
$classes[] = 'resurrect-background-image-file-' . sanitize_title( $background_image_info['filename'] ); // extension removed
}
// "View Full Site" cookie set is set in main.js -- client-side to avoid issues w/caching plugins
return $classes;
}
add_filter( 'body_class', 'resurrect_add_body_classes' );
|
gpl-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.