code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*
*
*
* Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This 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 version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
# include "incls/_precompiled.incl"
# include "incls/_CompiledMethod_i386.cpp.incl"
#if ENABLE_COMPILER
#if !defined(PRODUCT) || ENABLE_TTY_TRACE
int DisassemblerEnv::code_offset(address target) {
int result = target - _code->entry();
if (result < 0 || result > _code->size()) {
return -1;
}
return result;
}
void DisassemblerEnv::comment_on_immediate(unsigned char* pc, int value) {
static char temp[30];
int code_offset = pc - _code->entry();
RelocationReader stream(_code);
switch (stream.kind_at(code_offset)) {
case Relocation::oop_type:
case Relocation::rom_oop_type:
_oop = (OopDesc*)value;
break;
case Relocation::compiler_stub_type:
_comment = " {Compiler stub}";
break;
}
}
void DisassemblerEnv::print_comment(Stream* st) {
if (_comment != NULL) {
st->print(_comment);
} else {
_oop.print_value_on(st);
}
}
void CompiledMethod::print_code_on(Stream* st, jint start, jint end) {
// Warning this is not safe for garbage collection
address pc = entry() + start;
while (*pc != 0x00 && pc < entry() + end) {
DisassemblerEnv env(this);
address instruction_start = pc;
st->print(" %4d: ", instruction_start - entry());
pc = disasm(instruction_start, &env);
st->print("%s", env.buffer());
if (env.has_comment()) {
st->print(" // ");
env.print_comment(st);
}
st->cr();
}
}
void CompiledMethod::print_code_on(Stream* st) {
// Warning this is not safe for garbage collection
address pc = entry();
while (*pc != 0x00) {
DisassemblerEnv env(this);
address instruction_start = pc;
print_comment_for(instruction_start - entry(), st);
st->print(" %4d: ", instruction_start - entry());
pc = disasm(instruction_start, &env);
st->print("%s", env.buffer());
if (env.has_comment()) {
st->print(" // ");
env.print_comment(st);
}
st->cr();
}
}
#endif // !PRODUCT
#endif // COMPILER
#if ENABLE_ROM_GENERATOR
// generate a map of all the field types in this object
int CompiledMethod::generate_fieldmap(TypeArray* field_map) {
SHOULD_NOT_REACH_HERE();
return 0;
}
#endif /* #if ENABLE_ROM_GENERATOR*/
| tommythorn/yari | shared/cacao-related/phoneme_feature/cldc/src/vm/cpu/i386/CompiledMethod_i386.cpp | C++ | gpl-2.0 | 3,246 |
<?php
/* phpMyProfiler
* Copyright (C) 2005-2014 The phpMyProfiler project
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
define('_PMP_REL_PATH', '..');
$pmp_module = 'statistic';
if ( !isset($_SERVER['HTTP_REFERER']) || stristr($_SERVER['HTTP_REFERER'], $_SERVER['SERVER_NAME']) === false ) {
echo "Not allowed! Possible hacking attempt detected!";
exit();
}
require_once('../config.inc.php');
require_once('../include/functions.php');
DEFINE("TTF_DIR", '../include/font/');
DEFINE("CACHE_DIR", '../cache/');
DEFINE("USE_CACHE", $pmp_thumbnail_cache);
require_once('../include/jpgraph/jpgraph.php');
require_once('../include/jpgraph/jpgraph_bar.php');
if ( $pmp_thumbnail_cache && is_file('../cache/graph_productiondecade_'.$_SESSION['lang_id'].'.png') ) {
$filename = '../cache/graph_productiondecade_'.$_SESSION['lang_id'].'.png';
header('Content-Type: image/png');
header("Cache-Control: must-revalidate");
header($ExpStr);
header('Content-Disposition: inline; filename=' . $filename . ';');
@readfile($filename);
}
else {
dbconnect();
$query = 'SELECT name AS year, data AS count FROM pmp_statistics WHERE type = \'decade\' GROUP BY year';
$result = dbexec($query);
$rows = mysql_num_rows($result);
if( $rows == 0 ) {
header('Content-Type: image/gif');
header("Cache-Control: must-revalidate");
header($ExpStr);
header('Content-Disposition: inline; filename=empty.gif; ');
@readfile('../themes/default/images/empty.gif');
}
else {
while ( $row = mysql_fetch_object($result) ) {
$Decade[] = $row->count;
$Legend[] = substr($row->year, 0, 4) . ' - ' . (substr($row->year, 0, 4)+9);
}
if ( $pmp_stat_use_ttf == true ) {
$fontbig = FF_ARIAL;
$fontmedium = FF_ARIAL;
$fontsmall = FF_ARIAL;
}
else {
$fontbig = FF_FONT2;
$fontmedium = FF_FONT1;
$fontsmall = FF_FONT0;
}
// Setup the graph
$graph = new Graph(550, (12*$rows+40), 'graph_productiondecade_'.$_SESSION['lang_id'].'.png');
$graph->SetScale('textlin');
$theme_class = new pmpTheme;
$graph->SetTheme($theme_class);
$graph->Set90AndMargin(150, 20, 20, 20);
// Setup color for axis and labels
$graph->xaxis->SetColor('black', 'black');
$graph->yaxis->SetColor('black', 'black');
// Setup font for axis
$graph->xaxis->SetFont($fontmedium, FS_NORMAL, 8);
$graph->yaxis->SetFont($fontmedium, FS_NORMAL, 10);
// Setup X-axis title (color & font)
$graph->xaxis->title->SetColor('white');
$graph->xaxis->title->SetFont($fontmedium, FS_NORMAL, 10);
// Setup the grid
$graph->xgrid->SetColor('#2a2a2a');
$graph->xgrid->SetLineStyle('dashed');
// Create the bar pot
$bplot = new BarPlot($Decade);
$bplot->SetWidth(.5);
// Setup X-axis labels
$graph->xaxis->SetTickLabels($Legend);
// Setup color for gradient fill style
$tcol = array(255, 204, 00);
$fcol = array(255, 100, 100);
$bplot->SetFillGradient($fcol, $tcol, GRAD_HOR);
$graph->Add($bplot);
// Finally send the graph to the browser and our own header
header('Content-Type: image/png');
header("Cache-Control: must-revalidate");
header($ExpStr);
$graph->img->SetExpired(false);
$graph->Stroke();
}
dbclose();
}
?> | hase77/phpmyprofiler | statistic/graph_productiondecade.php | PHP | gpl-2.0 | 3,852 |
/*
Kvalobs - Free Quality Control Software for Meteorological Observations
$Id: kvdatatest.cc,v 1.1.6.2 2007/09/27 09:02:31 paule Exp $
Copyright (C) 2007 met.no
Contact information:
Norwegian Meteorological Institute
Box 43 Blindern
0313 OSLO
NORWAY
email: kvalobs-dev@met.no
This file is part of KVALOBS
KVALOBS 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.
KVALOBS 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 KVALOBS; if not, write to the Free Software Foundation Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <iostream>
#include "kvalobs/kvData.h"
using namespace kvalobs;
using namespace std;
using namespace miutil;
int main(int argn, char **argv) {
kvData d;
miTime tbtime(miTime::nowTime());
miTime obstime(2002, 4, 8, 12);
string stmt;
d = kvData(1024, obstime, 12.33f, 1023, tbtime, 23, 2, 100, 12.40f,
kvControlInfo(), kvUseInfo(), "");
cerr << d << endl << endl;
cerr << d.toSend() << endl;
cerr << "\n\n";
try {
cerr << "stationid: " << d.stationID() << endl;
cerr << "obstime: " << d.obstime() << endl;
cerr << "original: " << d.original() << endl;
cerr << "paramid: " << d.paramID() << endl;
cerr << "tbtime: " << d.tbtime() << endl;
cerr << "typeid: " << d.typeID() << endl;
cerr << "sensor: " << d.sensor() << endl;
cerr << "level: " << d.level() << endl;
cerr << "corrected: " << d.corrected() << endl;
cerr << "controlinfo: " << d.controlinfo() << endl;
cerr << "useinfo: " << d.useinfo() << endl;
} catch (std::exception &ex) {
cerr << "EXCEPTION: " << ex.what() << endl;
return 1;
}
return 0;
}
| metno/kvalobs | src/lib/kvalobs/test/kvdatatest.cc | C++ | gpl-2.0 | 2,208 |
from ftw.upgrade import UpgradeStep
from plone import api
class AddLanguageIndex(UpgradeStep):
"""Add Language index."""
def __call__(self):
self.install_upgrade_profile()
ct = api.portal.get_tool("portal_catalog")
survey_results = ct(portal_type="euphorie.survey")
for brain in survey_results:
survey = brain.getObject()
survey.reindexObject(idxs=["Language"])
| euphorie/Euphorie | src/euphorie/upgrade/deployment/v1/20210720143221_add_language_index/upgrade.py | Python | gpl-2.0 | 429 |
<?php
//author kwesidev
//gets customer profile as object
class Profile {
private $firstname;
private $lastname;
private $idnumber;
private $dob;
private $address;
private $mobilenumber;
private $email;
private $accnumber;
private $balance = 0;
private $acctype = "";
private $username = "";
private $password = "";
private $admin = 0;
private $block;
public function __construct($idnumber = NULL, $acc = NULL) {
$sql = "SELECT * from customer,account,login WHERE customer.idnumber=login.idnumber AND ";
$sql.="customer.idnumber=account.idnumber AND customer.idnumber=:idnumber OR account.accnumber=:acc";
$rows = getData($sql, array("idnumber" => $idnumber, "acc" => $acc));
if (count($rows) >= 1) {
$this->firstname = $rows[0]['firstname'];
$this->lastname = $rows[0]['lastname'];
$this->idnumber = $rows[0]['idnumber'];
$this->dob = $rows[0]['dob'];
$this->address = $rows[0]['address'];
$this->mobilenumber = $rows[0]['mobilenumber'];
$this->email = $rows[0]['email'];
$this->accnumber = $rows[0]['accnumber'];
$this->balance = $rows[0]['balance'];
$this->username = $rows[0]['username'];
$this->password = $rows[0]['password'];
$this->admin = (int) $rows[0]['level'];
$this->block = (int) $rows[0]['access'];
}
$query = NULL;
}
public function getUsername() {
return($this->username);
}
public function getPassword() {
return($this->password);
}
public function getIdnumber() {
return($this->idnumber);
}
public function getFirstname() {
return($this->firstname);
}
public function getLastname() {
return($this->lastname);
}
public function getAddress() {
return($this->address);
}
public function getMobilenumber() {
return($this->mobilenumber);
}
public function getEmail() {
return($this->email);
}
public function getDob() {
return($this->dob);
}
public function getAccNumber() {
return($this->accnumber);
}
public function getBalance() {
return($this->balance);
}
public function isAdmin() {
if ($this->admin == 1)
return true;
else
return false;
}
public function isBlock() {
if ($this->block == 1)
return true;
else
return false;
}
}
| kwesidev/ibanksys | src/utils/Profile.php | PHP | gpl-2.0 | 2,609 |
/*
* Copyright 2006-2016 The MZmine 3 Development Team
*
* This file is part of MZmine 3.
*
* MZmine 3 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 3 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 3; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.github.mzmine.modules.featuretable.renderers;
import java.text.NumberFormat;
import io.github.msdk.datamodel.featuretables.FeatureTableRow;
import io.github.mzmine.main.MZmineCore;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
public class RtRenderer implements
Callback<TreeTableColumn<FeatureTableRow, Object>, TreeTableCell<FeatureTableRow, Object>> {
@Override
public TreeTableCell<FeatureTableRow, Object> call(TreeTableColumn<FeatureTableRow, Object> p) {
return new TreeTableCell<FeatureTableRow, Object>() {
@Override
public void updateItem(Object object, boolean empty) {
super.updateItem(object, empty);
setStyle("-fx-alignment: CENTER;"
+ "-fx-border-color: transparent -fx-table-cell-border-color -fx-table-cell-border-color transparent;");
if (object == null) {
setText(null);
} else {
NumberFormat formatter = MZmineCore.getConfiguration().getRTFormat();
Float floatValue = Float.parseFloat(object.toString());
setText(formatter.format(floatValue));
}
}
};
}
}
| DrewG/mzmine3 | src/main/java/io/github/mzmine/modules/featuretable/renderers/RtRenderer.java | Java | gpl-2.0 | 1,988 |
<?php
/*
Plugin Name: Gleam Shortcodes
Plugin URI: http://gleamfuture.com/gleam-shortcodes
Description: View the user information and logged-in users meta information
Author: Gleamfuture IT Services
Version: 1.0
License: GPL version 2 or any later version
Author URI: http://www.gleamfuture.com
Text Domain: gleam-shortcodes
*/
/* Copyright 2017 Gleamfuture IT Services (email : gleamfutureservices@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
require_once(dirname(__FILE__) . '/core/plugin_information.php');
require_once(dirname(__FILE__) . '/core/shortcodes.php');
$gleamShortcodes = new gleamShortcodes();
?> | Jaswinder/gleam-shortcodes | user-shortcodes.php | PHP | gpl-2.0 | 1,253 |
Encoding.default_external = "utf-8"
preferred_syntax = :scss
http_path = '/'
css_dir = '/css/'
sass_dir = '/sass'
images_dir = '/images'
javascripts_dir = '/js'
line_comments = false
output_style = :compressed
require 'autoprefixer-rails'
on_stylesheet_saved do |file|
css = File.read(file)
map = file + '.map'
if File.exists? map
result = AutoprefixerRails.process(css,
from: file,
to: file,
map: { prev: File.read(map), inline: false })
File.open(file, 'w') { |io| io << result.css }
File.open(map, 'w') { |io| io << result.map }
else
File.open(file, 'w') { |io| io << AutoprefixerRails.process(css) }
end
end | DjKarui/speed-force | public/config.rb | Ruby | gpl-2.0 | 662 |
/*
* main.cpp
*
* Created on: 25 mar 2014
* Author: Mike
*/
// Inclusions
#include "main.h"
// Functions
void welcome(){
std::cout << "Project Euler v" << GLOBAL_CONST_VERSION;
}
// Main function
int main(int argc, char *argv[]){
if(argc <= 1){
if(argc == 1){
welcome();
}
// prototype
else if(argc < 1){ // -arguments
std::string str = argv[1];
if(str.at(0) == '-'){
if(strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)
{
welcome();
std::cout << "\nAuthor: Mikael Andersson <anhility@gmail.com>\nGithub: <http://github.com/anhility/project-euler.git>\n\nExample of use: \"euler 24\" -> Calculates problem #24.";
std::cout << "Arguments:\n-i";
return 0;
}
else{
welcome();
std::cout << "Unrecognized argument. Type -h for help.";
return 0;
}
}
}
// end prototype
}
CTimer MainTimer;
std::cout << "\n\033[1;4mHello World\033[0m";
MainTimer.getElapsedSecs();
return 0;
}
| anhility/project-euler | src/main.cpp | C++ | gpl-2.0 | 1,037 |
/**
* @file
* Provides functions that enable the selection of elements on a webpage, which can then be manipulated.
*
* HTML elements on the webpage that have a class containing '.selectable'
*/
// JavaScript should be made compatible with libraries other than jQuery by
// wrapping it with an "anonymous closure". See:
// - https://drupal.org/node/1446420
// - http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
(function ($, Drupal, window, document, undefined) {
/**
* CONTENTS
- variable declarations -
Drupal.behaviors.selection.attach()
Drupal.edit_selected
.find_selectables()
.get_selecteds_indexes()
.are_selecteds()
.set_selecteds_indexes()
.selecteds_indexes_push()
.selecteds_indexes_remove()
.add_selection_listeners()
.get_selected_selectables() // Simplest get function.
.get_selected_nids()
.get_selectable()
.get_index()
.deselect_all()
disable_image_drag()
set_up_page()
register_selection()
register_focus()
toggle_selected_element()
adjust_buttons()
set_up_keypress_mgmt()
handle_keypress_see_shortcuts()
handle_keypress_select()
handle_keypress_prev()
get_focussed_prev()
handle_keypress_next()
get_focussed_next()
handle_keypress_group()
*/
/*
* @todo Change primary storage array `selecteds_indexes`
* to store the jQ elements rather than their 'indexes' (unreliable!).
*/
var page_is_setup = false;
var selectables; // View row numbers of the
// The selecteds array temporarily stores the 'pictures' that are currently selected
// The indexes refer to the 'result numbers' of the elements within the view content (for easy JQuery retrieval)
var selecteds_indexes = []; // View row numbers of the
var selecteds = []; // View row numbers of the
var mouseIsDown = false; // Tracks status of mouse button
var shift_key_down = false;
// To understand behaviors, see https://drupal.org/node/756722#behaviors
Drupal.behaviors.selection = {
attach: function(context, settings) {
// console.log('context: ', context);
// console.log('context: ', $(context));
// console.log('selectables: ', selectables);
if (! page_is_setup) {
// disable_image_drag(); // Not needed anymore.
Drupal.selection.find_selectables();
register_focus( selectables.eq(0) );
set_up_keypress_mgmt(context);
set_up_page(context);
$(document).mousedown(function(event) {
// event.preventDefault();
mouseIsDown = true; // When mouse goes down, set mouseIsDown to true
// return false;
})
.mouseup(function() {
mouseIsDown = false; // When mouse goes up, set mouseIsDown to false
});
selectables.each(function() {
Drupal.selection.add_selection_listeners($(this));
});
$( '#deselect_all', context ).click( function() {
Drupal.selection.deselect_all();
});
page_is_setup = true;
}
},
weight: 3
};
Drupal.selection = {
find_selectables: function(context) {
if (typeof context === 'undefined') {
context = document;
}
selectables = $('.selectable', context);
},
get_selecteds_indexes: function() {
return selecteds_indexes;
},
/**
* Determines if there are any selectables currently selected.
*/
are_selecteds: function() {
// var num_selected = Drupal.selection.get_selecteds_indexes().length;
var are_selecteds = selectables.filter('.selected').length > 0 ? true : false;
// console.log('are_selecteds: ', are_selecteds);
return are_selecteds;
},
set_selecteds_indexes: function( array ) {
selecteds_indexes = array;
},
selecteds_indexes_push: function( index ) {
selecteds_indexes.push(index);
},
selecteds_indexes_remove: function( index ) {
selecteds_indexes.splice( $.inArray( index, selecteds_indexes), 1 );
},
/**
* The first element could after the last element (if select was made in reverse).
*/
select_multiple: function( first_element, last_element ) {
// console.log('first_element: ', first_element);
// console.log('last_element: ', last_element);
var settings = {
cleanup: false,
push_index: false
};
var select_on = false;
selectables.each(function(key, element) {
var selectable = $(element);
if (selectable.is(first_element) || selectable.is(last_element)) {
if (! select_on) {
select_on = true;
}
else {
register_selection( selectable, settings ); // For the last one.
select_on = false;
}
}
if (select_on && (! selectable.hasClass('selected'))) {
register_selection( selectable, settings );
}
});
selectables.each(function() {
selecteds_indexes.push($(this).index());
});
// console.log('selecteds_indexes: ', selecteds_indexes);
adjust_buttons();
adjust_toolbar();
$(document).trigger( "selection:select_all" );
},
add_selection_listeners: function(selectable) {
selectable.find('.selectable-target').mousedown( function(event) {
event.preventDefault(); // Prevents browser's "text selection"
var settings = {
cleanup: true
};
var selectable = $(this).parents('.selectable');
if (shift_key_down) {
Drupal.selection.select_multiple(
selectables.filter('.focussed'),
selectable
);
}
else {
register_selection( selectable, settings );
}
register_focus( selectable );
});
selectable.find('.selectable-target').mouseenter( function(event) {
var settings = {
cleanup: true
};
var selectable = $(this).parents('.selectable');
if (mouseIsDown) {
register_selection( selectable, settings );
}
});
},
/**
* @return a list of Jquery elements
*/
get_selected_selectables: function(id) {
// var selecteds_indexes = Drupal.selection.get_selecteds_indexes();
// console.log('selecteds_indexes received: ', selecteds_indexes);
// selecteds = [];
// $.each( selecteds_indexes, function( key, index ) {
// // selecteds.push(selectables.filter('.views-row-' + index ));
// selecteds.push(selectables.filter('.selected'));
// // console.log('elements: ', element.length);
// });
// return selecteds;
return selectables.filter('.selected');
},
/**
* Gets the array of selectable indexes, and creates an array of the nids from it.
*/
get_selected_nids: function() {
// var selecteds_indexes = Drupal.selection.get_selecteds_indexes();
// console.log('selecteds_indexes received: ', selecteds_indexes);
selecteds_nids = [];
selectables.filter('.selected').each(function( key, index ) {
// var selectable = selectables.filter('.views-row-' + (index - 1) );
// console.log('selectable: ', $(this));
var nid = $(this).find( ".property-nid" ).html().trim();
// console.log('nid: ', nid);
selecteds_nids.push( nid );
});
// console.log('selecteds_nids: ', selecteds_nids);
return selecteds_nids;
},
/**
* @return a Jquery element, regardless of whether it's in a group
*/
get_selectable: function(id) {
return selectables.filter('.views-row-' + id );
},
/**
* Determines the position that a result is in within view results.
*/
get_index: function(target) {
var index;
var classes = target.attr( "class" ).split( " " );
// console.log('classes: ', classes);
if(classes) {
// Determine the picture's result number (within view)
$.each( classes, function( key, value ) {
// We use "views-row-#" because it's reliable, and doesn't change (as long as the layout is 'list')
if ( value.substr( 0, 10 ) == "views-row-" ) {
// console.log('substr: ', value.substr( 10, value.length));
index = parseInt( value.substr( 10, value.length ), 10 );
}
else return;
});
}
return index;
},
/**
* Deselects all selected elements.
*/
deselect_all: function() {
// console.log('call: Drupal.selection.deselect_all()');
selectables.filter('.selected').removeClass( "selected" );
adjust_buttons();
adjust_toolbar();
$(window).trigger( "selection:deselect_all" );
}
}
function disable_image_drag() {
// Disable firefox's 'image drag' feature, which messes with our ‘drag-select’
$(document).on("dragstart", function(event) {
event.preventDefault();
// console.log('On: dragstart');
return false;
});
}
function set_up_page(context) {
var toolbar = $('[role="toolbar"][aria-label="primary toolbar"]', context);
$( '.page__title', context )
.after('<div class="action_buttons"></div>');
toolbar
.append("<button id='deselect_all' type='button' disabled>Un-select all</button>");
toolbar.find('#deselect_all').prepend("<span class='icon-select_all'></span> ");
}
/**
* Adds or removes the result number from the selected array.
*
* @param target
* JQuery object that was selected or unselected.
*
* @param checked
* Boolean indicating if the target's checked attribute should be set to true.
*/
function register_selection(target, settings) {
// console.log('Call: register_selection');
var checked = toggle_selected_element( target );
// console.log('checked: ', checked);
var index = Drupal.selection.get_index(target);
// console.log('index: ', index);
if (typeof settings.push_index == 'undefined') {
settings.push_index = true;
}
if (checked && settings.push_index) {
// Add the picture to the 'selecteds' arrays
selecteds_indexes.push( index );
}
else if (settings.push_index) {
// Remove the picture from the 'selecteds' arrays
selecteds_indexes.splice( $.inArray( index, selecteds_indexes), 1 );
}
// console.log("selecteds_indexes: ", selecteds_indexes);
settings = (typeof settings !== 'undefined') ? settings : {
cleanup: false
};
if (settings.cleanup) {
// console.log('cleanup');
adjust_buttons();
adjust_toolbar();
target.trigger( "selection:select" );
}
}
/**
* Adds or removes the result number from the selected array.
*/
function register_focus(target) {
selectables.removeClass('focussed');
target.toggleClass('focussed');
}
/**
* Toggles the selected state of the selected element.
*
* @return boolean
* Returns true if the selected element is now 'selected', or false otherwise.
*/
function toggle_selected_element(target) {
target.toggleClass( "selected" );
var checked = target.hasClass( "selected" );
return checked;
}
/**
* Enables and disables the buttons according to selections.
*/
function adjust_buttons() {
// console.log('adjust_buttons()');
// if( selecteds_indexes.length ) {
// $( '#deselect_all' ).attr('disabled', false);
// } else {
// $( '#deselect_all' ).attr('disabled', true);
// }
$( '#deselect_all' ).attr('disabled', ! Drupal.selection.are_selecteds());
}
/**
* Shows or hides the toolbar according to selections.
*/
function adjust_toolbar() {
var toolbar = $('[role="toolbar"][aria-label*="primary"]');
toolbar.attr('aria-expanded', Drupal.selection.are_selecteds());
var selection_count = selectables.filter('.selected').length;
toolbar.find('.selection-count .count').html(selection_count);
}
function set_up_keypress_mgmt(context) {
Drupal.casabio.add_keypress_info(
"<tr><td><strong>shift</strong> <small>+</small> <strong>/</strong> : </td><td>Show shortcuts</td></tr>"
);
// Further keypress info will be customised by page and added by edit_selected.js.
// Drupal.casabio.add_keypress_info();
// console.log('document, context: ', $(context).find(document));
$('body', context).bind('keydown', 'shift+/', handle_keypress_see_shortcuts);
$('body', context).bind('keydown', 'x', handle_keypress_select);
$('body', context).bind('keydown', 'c', handle_keypress_unselect_all);
$('body', context).bind('keydown', 'left', handle_keypress_prev, context);
$('body', context).bind('keydown', 'right', handle_keypress_next, context);
$('body', context).bind('keydown', 'ctrl+a', handle_keypress_select_all, context);
$('body', context).bind('keydown', 'shift', handle_keypress_shift_down);
$('body', context).bind('keyup', 'shift', handle_keypress_shift_up);
}
function handle_keypress_see_shortcuts() {
// console.log('handle_keypress_see_shortcuts');
var is_open = $( '#display-shortcuts[style*="display: block"]' ).length > 0;
if (is_open) {
$( '#display-shortcuts' ).dialog('close');
}
else {
$( '#display-shortcuts' ).dialog('open');
}
}
function handle_keypress_select() {
var settings = {
cleanup: true,
push_index: false
};
var focussed = selectables.filter('.focussed');
register_selection(focussed, settings);
}
function handle_keypress_unselect_all() {
Drupal.selection.deselect_all();
}
function handle_keypress_prev() {
var selectable = selectables.filter('.focussed');
prev = get_focussed_prev(selectable);
if (prev !== null) {
register_focus(prev);
}
$(window).trigger( "selection:prev", prev );
}
/**
* Gets the previous selectable before an element (which can be a selectable or a group).
*/
function get_focussed_prev(element) {
var prev;
// If in a group and is the last in the group
if ((element.parent('.group').length > 0) && (element.prev().length == 0)) {
// console.log('is in group')
prev = get_focussed_prev(element.parent());
}
// If the previous li or ul is a group
else if (element.prevAll('li, ul').eq(0).hasClass('group')) {
// console.log('next is group')
prev = element.prevAll('li, ul').eq(0).children('.selectable').eq(-1);
}
// If this is the first selectable
else if (element.prevAll('.selectable').length == 0) {
prev = null;
}
else {
prev = element.prevAll('.selectable').eq(0);
}
return prev;
}
function handle_keypress_next(context) {
// console.log('called: handle_keypress_next()');
var selectable = selectables.filter('.focussed');
next = get_focussed_next(selectable);
if (next !== null) {
register_focus(next);
}
$(window).trigger( "selection:next", next );
}
function handle_keypress_select_all(context) {
// Drupal.casa_utilities.start_timer('select_all');
Drupal.selection.select_multiple(selectables.first(), selectables.last());
// Drupal.casa_utilities.end_timer('select_all');
return false;
}
/**
* Gets the next selectable following an element (which can be a selectable or a group).
*/
function get_focussed_next(element) {
// console.log('element class: ', element.attr('class'));
var next;
// If in a group and is the last in the group
if ((element.parent('.group').length > 0) && (element.nextAll('li, ul').eq(0).length == 0)) {
// console.log('is in group')
next = get_focussed_next(element.parent());
}
// If the next li or ul is a group
else if (element.nextAll('li, ul').eq(0).hasClass('group')) {
// console.log('next is group')
next = element.nextAll('li, ul').eq(0).children('.selectable').eq(0);
}
// If this is the last selectable
else if (element.nextAll('.selectable').length == 0) {
next = null;
}
else {
next = element.nextAll('.selectable').eq(0);
// console.log('next class: ', next.attr('class'));
}
return next;
}
function handle_keypress_group() {
group();
}
function handle_keypress_ungroup() {
ungroup_all();
}
function handle_keypress_shift_down() {
shift_key_down = true;
}
function handle_keypress_shift_up() {
shift_key_down = false;
}
})(jQuery, Drupal, this, this.document);
| Droces/casabio | sites/all/modules/custom/selection/scripts/selection.js | JavaScript | gpl-2.0 | 15,835 |
<?php namespace buildr\ServiceProvider;
use buildr\Application\Application;
/**
* Service Provider. This class can handle all sort of service registration.
* This class job is to register services and handle loading of optional services.
*
* BuildR PHP Framework
*
* @author Zoltán Borsos <zolli07@gmail.com>
* @package buildr
* @subpackage ServiceProvider
*
* @copyright Copyright 2015, Zoltán Borsos.
* @license https://github.com/Zolli/BuildR/blob/master/LICENSE.md
* @link https://github.com/Zolli/BuildR
*/
class ServiceProvider {
/**
* @type array
*/
private static $optionalServices = [];
/**
* @type array
*/
private static $loadedOptionalServices = [];
/**
* Register forced service providers by an array.
*
* @param array $providersArray An array that contains service providers FQCN as key
*
* @throw \InvalidArgumentException
*/
public static function registerProvidersByArray($providersArray) {
if(!is_array($providersArray)) {
throw new \InvalidArgumentException("This method must take an array as argument!");
}
//@codeCoverageIgnoreStart
foreach ($providersArray as $providerClassName) {
self::registerByName($providerClassName);
}
//@codeCoverageIgnoreEnd
}
/**
* Register optional service providers by array
*
* @param array $optionalProviders
*
* @throw \InvalidArgumentException
*/
public static function addOptionalsByArray($optionalProviders) {
if(!is_array($optionalProviders)) {
throw new \InvalidArgumentException('This method must take an array as argument!');
}
//@codeCoverageIgnoreStart
foreach($optionalProviders as $bindingName => $providerClass) {
self::addOptionalProvider($bindingName, $providerClass);
}
//@codeCoverageIgnoreEnd
}
/**
* Register an optional service provider.
*
* @param string $serviceName The service short name (eg. binding name)
* @param string $serviceClassName The service provider fully qualified class name
*
* @return bool
*/
public static function addOptionalProvider($serviceName, $serviceClassName) {
if(!isset(self::$optionalServices[$serviceName])) {
self::$optionalServices[$serviceName] = $serviceClassName;
self::registerOptionalProviderBindings($serviceClassName);
return TRUE;
}
$msg = 'The service name (' . $serviceName . ') is already taken by ' . self::$optionalServices[$serviceName];
throw new \LogicException($msg);
}
public static function registerOptionalProviderBindings($serviceClassName) {
$serviceClass = new $serviceClassName;
$container = Application::getContainer();
if(($providedInterfaces = $serviceClass->provides()) !== NULL) {
foreach($providedInterfaces as $interfaceClass) {
$container->alias($interfaceClass, $serviceClass->getBindingName());
}
}
}
/**
* Checks that the given service name is a service name, that an
* optional provider can provide.
*
* @param string $serviceName The service short name (eg. binding name)
*
* @return bool
*/
public static function isOptionalService($serviceName) {
return isset(self::$optionalServices[$serviceName]);
}
/**
* Determines that the given optional provider is already
* loaded or not.
*
* @param string $serviceName The service short name (eg. binding name)
*
* @return bool
*/
public static function isOptionalServiceLoaded($serviceName) {
return isset(self::$loadedOptionalServices[$serviceName]);
}
/**
* Initialize the loading of an optional service.
* It uses the same registration process that the forced providers use.
*
* @param string $serviceName The service short name (eg. binding name)
*/
public static function loadOptionalService($serviceName) {
$providerClassName = self::$optionalServices[$serviceName];
self::registerByName($providerClassName);
self::$loadedOptionalServices[$serviceName] = TRUE;
}
/**
* Invoke the registration process of the given service provider class.
*
* @param string $providerName The provider fully qualified class name
*/
public static function registerByName($providerName) {
/** * @param \buildr\Container\Container $constainer */
$container = Application::getContainer();
$provider = new $providerName;
$container->register($provider);
}
}
| Zolli/BuildR | src/ServiceProvider/ServiceProvider.php | PHP | gpl-2.0 | 4,775 |
'use strict';
import BaseContentService from './BaseContentService.js';
import {Question} from 'common/models.js';
import {Injector} from 'kusema.js';
var I = new Injector('$http', '$q');
var QuestionService = function() {
BaseContentService.call(this, true);
I.init();
this.urlStem = 'api/questions';
}
QuestionService.prototype = Object.create(BaseContentService.prototype, {
model: {writable: false, enumerable: false, value: Question}
});
QuestionService.prototype.getNextTenQuestions = function (requestNumber, group) {
var groupURL = (group) ? ('/'+group) : '';
return I.$http.get(this.urlBase + '/tenMore' + groupURL + '/' + requestNumber)
.then(function(response) {
return this.createClientModels(response.data);
}.bind(this));
};
QuestionService.prototype.getFeed = function(requestNumber, group) {
var groupURL = (group) ? (group+'/') : '';
return I.$http.get(this.urlBase+'/feed/'+groupURL+requestNumber)
.then( (response) => {
if (response.status == 204) {
return I.$q.reject(new Error('No more questions'));
}
return this.createClientModels(response.data)
} );
}
import kusema from 'kusema.js';
kusema.service('questionService', QuestionService); | akdor1154/kusema | Client/lib/common/services/QuestionService.js | JavaScript | gpl-2.0 | 1,296 |
// **********************************************************************
//
// Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
package IceInternal;
public final class OutgoingConnectionFactory
{
//
// Helper class to to multi hash map.
//
private static class MultiHashMap<K, V> extends java.util.HashMap<K, java.util.List<V>>
{
public void
put(K key, V value)
{
java.util.List<V> list = this.get(key);
if(list == null)
{
list = new java.util.LinkedList<V>();
this.put(key, list);
}
list.add(value);
}
public void
remove(K key, V value)
{
java.util.List<V> list = this.get(key);
assert(list != null);
list.remove(value);
if(list.isEmpty())
{
this.remove(key);
}
}
};
interface CreateConnectionCallback
{
void setConnection(Ice.ConnectionI connection, boolean compress);
void setException(Ice.LocalException ex);
}
public synchronized void
destroy()
{
if(_destroyed)
{
return;
}
for(java.util.List<Ice.ConnectionI> connectionList : _connections.values())
{
for(Ice.ConnectionI connection : connectionList)
{
connection.destroy(Ice.ConnectionI.CommunicatorDestroyed);
}
}
_destroyed = true;
notifyAll();
}
public void
waitUntilFinished()
{
java.util.Map<Connector, java.util.List<Ice.ConnectionI> > connections = null;
synchronized(this)
{
//
// First we wait until the factory is destroyed. We also
// wait until there are no pending connections
// anymore. Only then we can be sure the _connections
// contains all connections.
//
while(!_destroyed || !_pending.isEmpty() || _pendingConnectCount > 0)
{
try
{
wait();
}
catch(InterruptedException ex)
{
}
}
//
// We want to wait until all connections are finished outside the
// thread synchronization.
//
connections = new java.util.HashMap<Connector, java.util.List<Ice.ConnectionI> >(_connections);
}
//
// Now we wait until the destruction of each connection is finished.
//
for(java.util.List<Ice.ConnectionI> connectionList : connections.values())
{
for(Ice.ConnectionI connection : connectionList)
{
connection.waitUntilFinished();
}
}
synchronized(this)
{
// Ensure all the connections are finished and reapable at this point.
java.util.List<Ice.ConnectionI> cons = _reaper.swapConnections();
if(cons != null)
{
int size = 0;
for(java.util.List<Ice.ConnectionI> connectionList : _connections.values())
{
size += connectionList.size();
}
assert(cons.size() == size);
_connections.clear();
_connectionsByEndpoint.clear();
}
else
{
assert(_connections.isEmpty());
assert(_connectionsByEndpoint.isEmpty());
}
}
}
public Ice.ConnectionI
create(EndpointI[] endpts, boolean hasMore, Ice.EndpointSelectionType selType, Ice.BooleanHolder compress)
{
assert(endpts.length > 0);
//
// Apply the overrides.
//
java.util.List<EndpointI> endpoints = applyOverrides(endpts);
//
// Try to find a connection to one of the given endpoints.
//
Ice.ConnectionI connection = findConnectionByEndpoint(endpoints, compress);
if(connection != null)
{
return connection;
}
Ice.LocalException exception = null;
//
// If we didn't find a connection with the endpoints, we create the connectors
// for the endpoints.
//
java.util.List<ConnectorInfo> connectors = new java.util.ArrayList<ConnectorInfo>();
java.util.Iterator<EndpointI> p = endpoints.iterator();
while(p.hasNext())
{
EndpointI endpoint = p.next();
//
// Create connectors for the endpoint.
//
try
{
java.util.List<Connector> cons = endpoint.connectors();
assert(cons.size() > 0);
//
// Shuffle connectors if endpoint selection type is Random.
//
if(selType == Ice.EndpointSelectionType.Random)
{
java.util.Collections.shuffle(cons);
}
for(Connector c : cons)
{
connectors.add(new ConnectorInfo(c, endpoint));
}
}
catch(Ice.LocalException ex)
{
exception = ex;
handleException(exception, hasMore || p.hasNext());
}
}
if(connectors.isEmpty())
{
assert(exception != null);
throw exception;
}
//
// Try to get a connection to one of the connectors. A null result indicates that no
// connection was found and that we should try to establish the connection (and that
// the connectors were added to _pending to prevent other threads from establishing
// the connection).
//
connection = getConnection(connectors, null, compress);
if(connection != null)
{
return connection;
}
//
// Try to establish the connection to the connectors.
//
DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides();
java.util.Iterator<ConnectorInfo> q = connectors.iterator();
ConnectorInfo ci = null;
while(q.hasNext())
{
ci = q.next();
try
{
connection = createConnection(ci.connector.connect(), ci);
connection.start(null);
if(defaultsAndOverrides.overrideCompress)
{
compress.value = defaultsAndOverrides.overrideCompressValue;
}
else
{
compress.value = ci.endpoint.compress();
}
connection.activate();
break;
}
catch(Ice.CommunicatorDestroyedException ex)
{
exception = ex;
handleConnectionException(exception, hasMore || p.hasNext());
connection = null;
break; // No need to continue
}
catch(Ice.LocalException ex)
{
exception = ex;
handleConnectionException(exception, hasMore || p.hasNext());
connection = null;
}
}
//
// Finish creating the connection (this removes the connectors from the _pending
// list and notifies any waiting threads).
//
if(connection != null)
{
finishGetConnection(connectors, ci, connection, null);
}
else
{
finishGetConnection(connectors, exception, null);
}
if(connection == null)
{
assert(exception != null);
throw exception;
}
return connection;
}
public void
create(EndpointI[] endpts, boolean hasMore, Ice.EndpointSelectionType selType,
CreateConnectionCallback callback)
{
assert(endpts.length > 0);
//
// Apply the overrides.
//
java.util.List<EndpointI> endpoints = applyOverrides(endpts);
//
// Try to find a connection to one of the given endpoints.
//
try
{
Ice.BooleanHolder compress = new Ice.BooleanHolder();
Ice.ConnectionI connection = findConnectionByEndpoint(endpoints, compress);
if(connection != null)
{
callback.setConnection(connection, compress.value);
return;
}
}
catch(Ice.LocalException ex)
{
callback.setException(ex);
return;
}
ConnectCallback cb = new ConnectCallback(this, endpoints, hasMore, callback, selType);
cb.getConnectors();
}
public synchronized void
setRouterInfo(IceInternal.RouterInfo routerInfo)
{
if(_destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
assert(routerInfo != null);
//
// Search for connections to the router's client proxy
// endpoints, and update the object adapter for such
// connections, so that callbacks from the router can be
// received over such connections.
//
Ice.ObjectAdapter adapter = routerInfo.getAdapter();
DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides();
for(EndpointI endpoint : routerInfo.getClientEndpoints())
{
//
// Modify endpoints with overrides.
//
if(defaultsAndOverrides.overrideTimeout)
{
endpoint = endpoint.timeout(defaultsAndOverrides.overrideTimeoutValue);
}
//
// The Connection object does not take the compression flag of
// endpoints into account, but instead gets the information
// about whether messages should be compressed or not from
// other sources. In order to allow connection sharing for
// endpoints that differ in the value of the compression flag
// only, we always set the compression flag to false here in
// this connection factory.
//
endpoint = endpoint.compress(false);
for(java.util.List<Ice.ConnectionI> connectionList : _connections.values())
{
for(Ice.ConnectionI connection : connectionList)
{
if(connection.endpoint() == endpoint)
{
connection.setAdapter(adapter);
}
}
}
}
}
public synchronized void
removeAdapter(Ice.ObjectAdapter adapter)
{
if(_destroyed)
{
return;
}
for(java.util.List<Ice.ConnectionI> connectionList : _connections.values())
{
for(Ice.ConnectionI connection : connectionList)
{
if(connection.getAdapter() == adapter)
{
connection.setAdapter(null);
}
}
}
}
public void
flushAsyncBatchRequests(CommunicatorBatchOutgoingAsync outAsync)
{
java.util.List<Ice.ConnectionI> c = new java.util.LinkedList<Ice.ConnectionI>();
synchronized(this)
{
if(!_destroyed)
{
for(java.util.List<Ice.ConnectionI> connectionList : _connections.values())
{
for(Ice.ConnectionI connection : connectionList)
{
if(connection.isActiveOrHolding())
{
c.add(connection);
}
}
}
}
}
for(Ice.ConnectionI conn : c)
{
try
{
outAsync.flushConnection(conn);
}
catch(Ice.LocalException ex)
{
// Ignore.
}
}
}
//
// Only for use by Instance.
//
OutgoingConnectionFactory(Instance instance)
{
_instance = instance;
_destroyed = false;
}
protected synchronized void
finalize()
throws Throwable
{
IceUtilInternal.Assert.FinalizerAssert(_destroyed);
//IceUtilInternal.Assert.FinalizerAssert(_connections.isEmpty());
//IceUtilInternal.Assert.FinalizerAssert(_connectionsByEndpoint.isEmpty());
IceUtilInternal.Assert.FinalizerAssert(_pendingConnectCount == 0);
IceUtilInternal.Assert.FinalizerAssert(_pending.isEmpty());
super.finalize();
}
private java.util.List<EndpointI>
applyOverrides(EndpointI[] endpts)
{
DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides();
java.util.List<EndpointI> endpoints = new java.util.ArrayList<EndpointI>();
for(EndpointI endpoint : endpts)
{
//
// Modify endpoints with overrides.
//
if(defaultsAndOverrides.overrideTimeout)
{
endpoints.add(endpoint.timeout(defaultsAndOverrides.overrideTimeoutValue));
}
else
{
endpoints.add(endpoint);
}
}
return endpoints;
}
synchronized private Ice.ConnectionI
findConnectionByEndpoint(java.util.List<EndpointI> endpoints, Ice.BooleanHolder compress)
{
if(_destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides();
assert(!endpoints.isEmpty());
for(EndpointI endpoint : endpoints)
{
java.util.List<Ice.ConnectionI> connectionList = _connectionsByEndpoint.get(endpoint);
if(connectionList == null)
{
continue;
}
for(Ice.ConnectionI connection : connectionList)
{
if(connection.isActiveOrHolding()) // Don't return destroyed or un-validated connections
{
if(defaultsAndOverrides.overrideCompress)
{
compress.value = defaultsAndOverrides.overrideCompressValue;
}
else
{
compress.value = endpoint.compress();
}
return connection;
}
}
}
return null;
}
//
// Must be called while synchronized.
//
private Ice.ConnectionI
findConnection(java.util.List<ConnectorInfo> connectors, Ice.BooleanHolder compress)
{
DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides();
for(ConnectorInfo ci : connectors)
{
if(_pending.containsKey(ci.connector))
{
continue;
}
java.util.List<Ice.ConnectionI> connectionList = _connections.get(ci.connector);
if(connectionList == null)
{
continue;
}
for(Ice.ConnectionI connection : connectionList)
{
if(connection.isActiveOrHolding()) // Don't return destroyed or un-validated connections
{
if(defaultsAndOverrides.overrideCompress)
{
compress.value = defaultsAndOverrides.overrideCompressValue;
}
else
{
compress.value = ci.endpoint.compress();
}
return connection;
}
}
}
return null;
}
synchronized private void
incPendingConnectCount()
{
//
// Keep track of the number of pending connects. The outgoing connection factory
// waitUntilFinished() method waits for all the pending connects to terminate before
// to return. This ensures that the communicator client thread pool isn't destroyed
// too soon and will still be available to execute the ice_exception() callbacks for
// the asynchronous requests waiting on a connection to be established.
//
if(_destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
++_pendingConnectCount;
}
synchronized private void
decPendingConnectCount()
{
--_pendingConnectCount;
assert(_pendingConnectCount >= 0);
if(_destroyed && _pendingConnectCount == 0)
{
notifyAll();
}
}
private Ice.ConnectionI
getConnection(java.util.List<ConnectorInfo> connectors, ConnectCallback cb, Ice.BooleanHolder compress)
{
synchronized(this)
{
if(_destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
//
// Reap closed connections
//
java.util.List<Ice.ConnectionI> cons = _reaper.swapConnections();
if(cons != null)
{
for(Ice.ConnectionI c : cons)
{
_connections.remove(c.connector(), c);
_connectionsByEndpoint.remove(c.endpoint(), c);
_connectionsByEndpoint.remove(c.endpoint().compress(true), c);
}
}
//
// Try to get the connection. We may need to wait for other threads to
// finish if one of them is currently establishing a connection to one
// of our connectors.
//
while(true)
{
if(_destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
//
// Search for a matching connection. If we find one, we're done.
//
Ice.ConnectionI connection = findConnection(connectors, compress);
if(connection != null)
{
return connection;
}
if(addToPending(cb, connectors))
{
//
// If a callback is not specified we wait until another thread notifies us about a
// change to the pending list. Otherwise, if a callback is provided we're done:
// when the pending list changes the callback will be notified and will try to
// get the connection again.
//
if(cb == null)
{
try
{
wait();
}
catch(InterruptedException ex)
{
}
}
else
{
return null;
}
}
else
{
//
// If no thread is currently establishing a connection to one of our connectors,
// we get out of this loop and start the connection establishment to one of the
// given connectors.
//
break;
}
}
}
//
// At this point, we're responsible for establishing the connection to one of
// the given connectors. If it's a non-blocking connect, calling nextConnector
// will start the connection establishment. Otherwise, we return null to get
// the caller to establish the connection.
//
if(cb != null)
{
cb.nextConnector();
}
return null;
}
private synchronized Ice.ConnectionI
createConnection(Transceiver transceiver, ConnectorInfo ci)
{
assert(_pending.containsKey(ci.connector) && transceiver != null);
//
// Create and add the connection to the connection map. Adding the connection to the map
// is necessary to support the interruption of the connection initialization and validation
// in case the communicator is destroyed.
//
Ice.ConnectionI connection = null;
try
{
if(_destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
connection = new Ice.ConnectionI(_instance, _reaper, transceiver, ci.connector,
ci.endpoint.compress(false), null);
}
catch(Ice.LocalException ex)
{
try
{
transceiver.close();
}
catch(Ice.LocalException exc)
{
// Ignore
}
throw ex;
}
_connections.put(ci.connector, connection);
_connectionsByEndpoint.put(connection.endpoint(), connection);
_connectionsByEndpoint.put(connection.endpoint().compress(true), connection);
return connection;
}
private void
finishGetConnection(java.util.List<ConnectorInfo> connectors,
ConnectorInfo ci,
Ice.ConnectionI connection,
ConnectCallback cb)
{
java.util.Set<ConnectCallback> connectionCallbacks = new java.util.HashSet<ConnectCallback>();
if(cb != null)
{
connectionCallbacks.add(cb);
}
java.util.Set<ConnectCallback> callbacks = new java.util.HashSet<ConnectCallback>();
synchronized(this)
{
for(ConnectorInfo c : connectors)
{
java.util.Set<ConnectCallback> cbs = _pending.remove(c.connector);
if(cbs != null)
{
for(ConnectCallback cc : cbs)
{
if(cc.hasConnector(ci))
{
connectionCallbacks.add(cc);
}
else
{
callbacks.add(cc);
}
}
}
}
for(ConnectCallback cc : connectionCallbacks)
{
cc.removeFromPending();
callbacks.remove(cc);
}
for(ConnectCallback cc : callbacks)
{
cc.removeFromPending();
}
notifyAll();
}
boolean compress;
DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides();
if(defaultsAndOverrides.overrideCompress)
{
compress = defaultsAndOverrides.overrideCompressValue;
}
else
{
compress = ci.endpoint.compress();
}
for(ConnectCallback cc : callbacks)
{
cc.getConnection();
}
for(ConnectCallback cc : connectionCallbacks)
{
cc.setConnection(connection, compress);
}
}
private void
finishGetConnection(java.util.List<ConnectorInfo> connectors, Ice.LocalException ex, ConnectCallback cb)
{
java.util.Set<ConnectCallback> failedCallbacks = new java.util.HashSet<ConnectCallback>();
if(cb != null)
{
failedCallbacks.add(cb);
}
java.util.Set<ConnectCallback> callbacks = new java.util.HashSet<ConnectCallback>();
synchronized(this)
{
for(ConnectorInfo c : connectors)
{
java.util.Set<ConnectCallback> cbs = _pending.remove(c.connector);
if(cbs != null)
{
for(ConnectCallback cc : cbs)
{
if(cc.removeConnectors(connectors))
{
failedCallbacks.add(cc);
}
else
{
callbacks.add(cc);
}
}
}
}
for(ConnectCallback cc : callbacks)
{
assert(!failedCallbacks.contains(cc));
cc.removeFromPending();
}
notifyAll();
}
for(ConnectCallback cc : callbacks)
{
cc.getConnection();
}
for(ConnectCallback cc : failedCallbacks)
{
cc.setException(ex);
}
}
private boolean
addToPending(ConnectCallback cb, java.util.List<ConnectorInfo> connectors)
{
//
// Add the callback to each connector pending list.
//
boolean found = false;
for(ConnectorInfo p : connectors)
{
java.util.Set<ConnectCallback> cbs = _pending.get(p.connector);
if(cbs != null)
{
found = true;
if(cb != null)
{
cbs.add(cb); // Add the callback to each pending connector.
}
}
}
if(found)
{
return true;
}
//
// If there's no pending connection for the given connectors, we're
// responsible for its establishment. We add empty pending lists,
// other callbacks to the same connectors will be queued.
//
for(ConnectorInfo p : connectors)
{
if(!_pending.containsKey(p.connector))
{
_pending.put(p.connector, new java.util.HashSet<ConnectCallback>());
}
}
return false;
}
private void
removeFromPending(ConnectCallback cb, java.util.List<ConnectorInfo> connectors)
{
for(ConnectorInfo p : connectors)
{
java.util.Set<ConnectCallback> cbs = _pending.get(p.connector);
if(cbs != null)
{
cbs.remove(cb);
}
}
}
private void
handleConnectionException(Ice.LocalException ex, boolean hasMore)
{
TraceLevels traceLevels = _instance.traceLevels();
if(traceLevels.retry >= 2)
{
StringBuilder s = new StringBuilder(128);
s.append("connection to endpoint failed");
if(ex instanceof Ice.CommunicatorDestroyedException)
{
s.append("\n");
}
else
{
if(hasMore)
{
s.append(", trying next endpoint\n");
}
else
{
s.append(" and no more endpoints to try\n");
}
}
s.append(ex.toString());
_instance.initializationData().logger.trace(traceLevels.retryCat, s.toString());
}
}
private void
handleException(Ice.LocalException ex, boolean hasMore)
{
TraceLevels traceLevels = _instance.traceLevels();
if(traceLevels.retry >= 2)
{
StringBuilder s = new StringBuilder(128);
s.append("couldn't resolve endpoint host");
if(ex instanceof Ice.CommunicatorDestroyedException)
{
s.append("\n");
}
else
{
if(hasMore)
{
s.append(", trying next endpoint\n");
}
else
{
s.append(" and no more endpoints to try\n");
}
}
s.append(ex.toString());
_instance.initializationData().logger.trace(traceLevels.retryCat, s.toString());
}
}
private static class ConnectorInfo
{
public ConnectorInfo(Connector c, EndpointI e)
{
connector = c;
endpoint = e;
}
public boolean
equals(Object obj)
{
ConnectorInfo r = (ConnectorInfo)obj;
return connector.equals(r.connector);
}
public int
hashCode()
{
return connector.hashCode();
}
public Connector connector;
public EndpointI endpoint;
}
private static class ConnectCallback implements Ice.ConnectionI.StartCallback, EndpointI_connectors
{
ConnectCallback(OutgoingConnectionFactory f, java.util.List<EndpointI> endpoints, boolean more,
CreateConnectionCallback cb, Ice.EndpointSelectionType selType)
{
_factory = f;
_endpoints = endpoints;
_hasMore = more;
_callback = cb;
_selType = selType;
_endpointsIter = _endpoints.iterator();
}
//
// Methods from ConnectionI.StartCallback
//
public void
connectionStartCompleted(Ice.ConnectionI connection)
{
connection.activate();
_factory.finishGetConnection(_connectors, _current, connection, this);
}
public void
connectionStartFailed(Ice.ConnectionI connection, Ice.LocalException ex)
{
assert(_current != null);
_factory.handleConnectionException(ex, _hasMore || _iter.hasNext());
if(ex instanceof Ice.CommunicatorDestroyedException) // No need to continue.
{
_factory.finishGetConnection(_connectors, ex, this);
}
else if(_iter.hasNext()) // Try the next connector.
{
nextConnector();
}
else
{
_factory.finishGetConnection(_connectors, ex, this);
}
}
//
// Methods from EndpointI_connectors
//
public void
connectors(java.util.List<Connector> cons)
{
//
// Shuffle connectors if endpoint selection type is Random.
//
if(_selType == Ice.EndpointSelectionType.Random)
{
java.util.Collections.shuffle(cons);
}
for(Connector p : cons)
{
_connectors.add(new ConnectorInfo(p, _currentEndpoint));
}
if(_endpointsIter.hasNext())
{
nextEndpoint();
}
else
{
assert(!_connectors.isEmpty());
//
// We now have all the connectors for the given endpoints. We can try to obtain the
// connection.
//
_iter = _connectors.iterator();
getConnection();
}
}
public void
exception(Ice.LocalException ex)
{
_factory.handleException(ex, _hasMore || _endpointsIter.hasNext());
if(_endpointsIter.hasNext())
{
nextEndpoint();
}
else if(!_connectors.isEmpty())
{
//
// We now have all the connectors for the given endpoints. We can try to obtain the
// connection.
//
_iter = _connectors.iterator();
getConnection();
}
else
{
_callback.setException(ex);
_factory.decPendingConnectCount(); // Must be called last.
}
}
public void
setConnection(Ice.ConnectionI connection, boolean compress)
{
//
// Callback from the factory: the connection to one of the callback
// connectors has been established.
//
_callback.setConnection(connection, compress);
_factory.decPendingConnectCount(); // Must be called last.
}
public void
setException(Ice.LocalException ex)
{
//
// Callback from the factory: connection establishment failed.
//
_callback.setException(ex);
_factory.decPendingConnectCount(); // Must be called last.
}
public boolean
hasConnector(ConnectorInfo ci)
{
return _connectors.contains(ci);
}
public boolean
removeConnectors(java.util.List<ConnectorInfo> connectors)
{
_connectors.removeAll(connectors);
_iter = _connectors.iterator();
return _connectors.isEmpty();
}
public void
removeFromPending()
{
_factory.removeFromPending(this, _connectors);
}
void
getConnectors()
{
try
{
//
// Notify the factory that there's an async connect pending. This is necessary
// to prevent the outgoing connection factory to be destroyed before all the
// pending asynchronous connects are finished.
//
_factory.incPendingConnectCount();
}
catch(Ice.LocalException ex)
{
_callback.setException(ex);
return;
}
nextEndpoint();
}
void
nextEndpoint()
{
try
{
assert(_endpointsIter.hasNext());
_currentEndpoint = _endpointsIter.next();
_currentEndpoint.connectors_async(this);
}
catch(Ice.LocalException ex)
{
exception(ex);
}
}
void
getConnection()
{
try
{
//
// If all the connectors have been created, we ask the factory to get a
// connection.
//
Ice.BooleanHolder compress = new Ice.BooleanHolder();
Ice.ConnectionI connection = _factory.getConnection(_connectors, this, compress);
if(connection == null)
{
//
// A null return value from getConnection indicates that the connection
// is being established and that everthing has been done to ensure that
// the callback will be notified when the connection establishment is
// done.
//
return;
}
_callback.setConnection(connection, compress.value);
_factory.decPendingConnectCount(); // Must be called last.
}
catch(Ice.LocalException ex)
{
_callback.setException(ex);
_factory.decPendingConnectCount(); // Must be called last.
}
}
void
nextConnector()
{
Ice.ConnectionI connection = null;
try
{
assert(_iter.hasNext());
_current = _iter.next();
connection = _factory.createConnection(_current.connector.connect(), _current);
connection.start(this);
}
catch(Ice.LocalException ex)
{
connectionStartFailed(connection, ex);
}
}
private final OutgoingConnectionFactory _factory;
private final boolean _hasMore;
private final CreateConnectionCallback _callback;
private final java.util.List<EndpointI> _endpoints;
private final Ice.EndpointSelectionType _selType;
private java.util.Iterator<EndpointI> _endpointsIter;
private EndpointI _currentEndpoint;
private java.util.List<ConnectorInfo> _connectors = new java.util.ArrayList<ConnectorInfo>();
private java.util.Iterator<ConnectorInfo> _iter;
private ConnectorInfo _current;
}
private final Instance _instance;
private final ConnectionReaper _reaper = new ConnectionReaper();
private boolean _destroyed;
private MultiHashMap<Connector, Ice.ConnectionI> _connections = new MultiHashMap<Connector, Ice.ConnectionI>();
private MultiHashMap<EndpointI, Ice.ConnectionI> _connectionsByEndpoint =
new MultiHashMap<EndpointI, Ice.ConnectionI>();
private java.util.Map<Connector, java.util.HashSet<ConnectCallback> > _pending =
new java.util.HashMap<Connector, java.util.HashSet<ConnectCallback> >();
private int _pendingConnectCount = 0;
}
| joshmoore/zeroc-ice | java/src/IceInternal/OutgoingConnectionFactory.java | Java | gpl-2.0 | 37,163 |
/**
* Exception class for illegal phone number format strings.
* @author Jonathan Hinkle
*/
package net.sf.memoranda;
/**
* This class is thrown when a string is not a valid phone number format.
*
* @author Jonathan Hinkle
*
*/
@SuppressWarnings("serial")
public class IllegalPhoneNumberException extends IllegalArgumentException {
/**
* IllegalPhoneNumberException constructor.
*/
public IllegalPhoneNumberException() {}
/**
* IllegalPhoneNumberException constructor.
*
* @param message A message String
*/
public IllegalPhoneNumberException(String message) {
super(message);
}
}
| cst316/spring16project-Team-Chicago | src/net/sf/memoranda/IllegalPhoneNumberException.java | Java | gpl-2.0 | 614 |
<?php
declare(strict_types=1);
namespace PoPCMSSchema\Users\ConditionalOnComponent\CustomPosts\ConditionalOnComponent\API\ModuleProcessors;
use PoP\Root\App;
use PoPAPI\API\ModuleProcessors\AbstractRelationalFieldDataloadModuleProcessor;
use PoP\ComponentModel\QueryInputOutputHandlers\ListQueryInputOutputHandler;
use PoP\ComponentModel\QueryInputOutputHandlers\QueryInputOutputHandlerInterface;
use PoP\ComponentModel\TypeResolvers\RelationalTypeResolverInterface;
use PoPCMSSchema\CustomPosts\TypeResolvers\ObjectType\CustomPostObjectTypeResolver;
use PoPCMSSchema\Posts\ModuleProcessors\PostFilterInputContainerModuleProcessor;
class FieldDataloadModuleProcessor extends AbstractRelationalFieldDataloadModuleProcessor
{
public const MODULE_DATALOAD_RELATIONALFIELDS_AUTHORCUSTOMPOSTLIST = 'dataload-relationalfields-authorcustompostlist';
private ?CustomPostObjectTypeResolver $customPostObjectTypeResolver = null;
private ?ListQueryInputOutputHandler $listQueryInputOutputHandler = null;
final public function setCustomPostObjectTypeResolver(CustomPostObjectTypeResolver $customPostObjectTypeResolver): void
{
$this->customPostObjectTypeResolver = $customPostObjectTypeResolver;
}
final protected function getCustomPostObjectTypeResolver(): CustomPostObjectTypeResolver
{
return $this->customPostObjectTypeResolver ??= $this->instanceManager->getInstance(CustomPostObjectTypeResolver::class);
}
final public function setListQueryInputOutputHandler(ListQueryInputOutputHandler $listQueryInputOutputHandler): void
{
$this->listQueryInputOutputHandler = $listQueryInputOutputHandler;
}
final protected function getListQueryInputOutputHandler(): ListQueryInputOutputHandler
{
return $this->listQueryInputOutputHandler ??= $this->instanceManager->getInstance(ListQueryInputOutputHandler::class);
}
public function getModulesToProcess(): array
{
return array(
[self::class, self::MODULE_DATALOAD_RELATIONALFIELDS_AUTHORCUSTOMPOSTLIST],
);
}
public function getRelationalTypeResolver(array $module): ?RelationalTypeResolverInterface
{
switch ($module[1]) {
case self::MODULE_DATALOAD_RELATIONALFIELDS_AUTHORCUSTOMPOSTLIST:
return $this->getCustomPostObjectTypeResolver();
}
return parent::getRelationalTypeResolver($module);
}
public function getQueryInputOutputHandler(array $module): ?QueryInputOutputHandlerInterface
{
switch ($module[1]) {
case self::MODULE_DATALOAD_RELATIONALFIELDS_AUTHORCUSTOMPOSTLIST:
return $this->getListQueryInputOutputHandler();
}
return parent::getQueryInputOutputHandler($module);
}
protected function getMutableonrequestDataloadQueryArgs(array $module, array &$props): array
{
$ret = parent::getMutableonrequestDataloadQueryArgs($module, $props);
switch ($module[1]) {
case self::MODULE_DATALOAD_RELATIONALFIELDS_AUTHORCUSTOMPOSTLIST:
$ret['authors'] = [
App::getState(['routing', 'queried-object-id']),
];
break;
}
return $ret;
}
public function getFilterSubmodule(array $module): ?array
{
switch ($module[1]) {
case self::MODULE_DATALOAD_RELATIONALFIELDS_AUTHORCUSTOMPOSTLIST:
return [PostFilterInputContainerModuleProcessor::class, PostFilterInputContainerModuleProcessor::MODULE_FILTERINPUTCONTAINER_POSTS];
}
return parent::getFilterSubmodule($module);
}
}
| leoloso/PoP | layers/CMSSchema/packages/users/src/ConditionalOnComponent/CustomPosts/ConditionalOnComponent/API/ModuleProcessors/FieldDataloadModuleProcessor.php | PHP | gpl-2.0 | 3,656 |
# -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo 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.
#
# Zenodo 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 Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Test API for Zenodo and GitHub integration."""
from __future__ import absolute_import, print_function
from contextlib import contextmanager
from copy import deepcopy
import pytest
from flask import current_app
from invenio_accounts.models import User
from invenio_github.models import Release, ReleaseStatus, Repository
from invenio_pidrelations.contrib.versioning import PIDVersioning
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
from invenio_sipstore.models import SIP
from mock import MagicMock, Mock, patch
from six import BytesIO
from zenodo.modules.deposit.tasks import datacite_register
from zenodo.modules.github.api import ZenodoGitHubRelease
from zenodo.modules.github.utils import is_github_owner, is_github_versioned
from zenodo.modules.records.api import ZenodoRecord
from zenodo.modules.records.minters import zenodo_record_minter
from zenodo.modules.records.permissions import has_newversion_permission, \
has_update_permission
creators_params = (
(dict(),
[dict(name='Contributor', affiliation='X'), ],
[dict(name='Owner', affiliation='Y'), ],
[dict(name='Contributor', affiliation='X'), ]),
(dict(creators=[]), # List of creators provided as empty
[dict(name='Contributor', affiliation='X'), ],
[dict(name='Owner', affiliation='Y'), ],
[dict(name='Owner', affiliation='Y'), ]),
(dict(creators=None),
[dict(name='Contributor', affiliation='X'), ],
None, # Failed to get GH owner
[dict(name='Unknown', affiliation=''), ]),
)
@pytest.mark.parametrize('defaults,contribs,owner,output', creators_params)
@patch('zenodo.modules.github.api.get_owner')
@patch('zenodo.modules.github.api.get_contributors')
@patch('zenodo.modules.github.api.legacyjson_v1_translator')
def test_github_creators_metadata(m_ljv1t, m_get_contributors, m_get_owner,
defaults, contribs, owner, output):
"""Test 'creators' metadata fetching from GitHub."""
m_get_contributors.return_value = contribs
m_get_owner.return_value = owner
release = MagicMock()
release.event.user_id = 1
release.event.payload['repository']['id'] = 1
zgh = ZenodoGitHubRelease(release)
zgh.defaults = defaults
zgh.gh.api = None
zgh.extra_metadata = {}
zgh.metadata
m_ljv1t.assert_called_with({'metadata': {'creators': output}})
@patch('zenodo.modules.github.api.ZenodoGitHubRelease.metadata')
@patch('invenio_pidstore.providers.datacite.DataCiteMDSClient')
def test_github_publish(datacite_mock, zgh_meta, db, users, location,
deposit_metadata):
"""Test basic GitHub payload."""
data = b'foobar'
resp = Mock()
resp.headers = {'Content-Length': len(data)}
resp.raw = BytesIO(b'foobar')
resp.status_code = 200
gh3mock = MagicMock()
gh3mock.api.session.get = Mock(return_value=resp)
gh3mock.account.user.email = 'foo@baz.bar'
release = MagicMock()
release.event.user_id = 1
release.event.payload['release']['author']['id'] = 1
release.event.payload['foo']['bar']['baz'] = 1
release.event.payload['repository']['id'] = 1
zgh = ZenodoGitHubRelease(release)
zgh.gh = gh3mock
zgh.release = dict(author=dict(id=1))
zgh.metadata = deposit_metadata
zgh.files = (('foobar.txt', None), )
zgh.model.repository.releases.filter_by().count.return_value = 0
datacite_task_mock = MagicMock()
# We have to make the call to the task synchronous
datacite_task_mock.delay = datacite_register.apply
with patch('zenodo.modules.deposit.tasks.datacite_register',
new=datacite_task_mock):
zgh.publish()
# datacite should be called twice - for regular DOI and Concept DOI
assert datacite_mock().metadata_post.call_count == 2
datacite_mock().doi_post.assert_any_call(
'10.5072/zenodo.1', 'https://zenodo.org/record/1')
datacite_mock().doi_post.assert_any_call(
'10.5072/zenodo.2', 'https://zenodo.org/record/2')
expected_sip_agent = {
'email': 'foo@baz.bar',
'$schema': 'http://zenodo.org/schemas/sipstore/'
'agent-githubclient-v1.0.0.json',
'user_id': 1,
'github_id': 1,
}
gh_sip = SIP.query.one()
assert gh_sip.agent == expected_sip_agent
@patch('invenio_github.api.GitHubAPI.check_sync', new=lambda *_, **__: False)
def test_github_newversion_permissions(app, db, minimal_record, users, g_users,
g_remoteaccounts):
"""Test new version creation permissions for GitHub records."""
old_owner, new_owner = [User.query.get(u['id']) for u in g_users]
# Create repository, and set owner to `old_owner`
repo = Repository.create(
name='foo/bar', github_id=8000, user_id=old_owner.id, hook=1234)
# Create concpetrecid for the GitHub records
conceptrecid = PersistentIdentifier.create(
'recid', '100', status=PIDStatus.RESERVED)
def create_deposit_and_record(pid_value, owner):
"""Utility function for creating records and deposits."""
recid = PersistentIdentifier.create(
'recid', pid_value, status=PIDStatus.RESERVED)
pv = PIDVersioning(parent=conceptrecid)
pv.insert_draft_child(recid)
depid = PersistentIdentifier.create(
'depid', pid_value, status=PIDStatus.REGISTERED)
deposit = ZenodoRecord.create({'_deposit': {'id': depid.pid_value},
'conceptrecid': conceptrecid.pid_value,
'recid': recid.pid_value})
deposit.commit()
depid.assign('rec', deposit.id)
record_metadata = deepcopy(minimal_record)
record_metadata['_deposit'] = {'id': depid.pid_value}
record_metadata['conceptrecid'] = conceptrecid.pid_value
record_metadata['recid'] = int(recid.pid_value)
record_metadata['owners'] = [owner.id]
record = ZenodoRecord.create(record_metadata)
zenodo_record_minter(record.id, record)
record.commit()
return (depid, deposit, recid, record)
# Create first GitHub record (by `old_owner`)
depid1, d1, recid1, r1 = create_deposit_and_record('101', old_owner)
rel1 = Release(release_id=111, repository_id=repo.id, record_id=d1.id,
status=ReleaseStatus.PUBLISHED)
db.session.add(rel1)
db.session.commit()
assert is_github_versioned(recid1)
@contextmanager
def set_identity(user):
from flask_principal import AnonymousIdentity, Identity
principal = current_app.extensions['security'].principal
principal.set_identity(Identity(user))
yield
principal.set_identity(AnonymousIdentity())
with app.test_request_context():
with set_identity(old_owner):
assert is_github_owner(old_owner, recid1)
assert has_update_permission(old_owner, r1)
assert has_newversion_permission(old_owner, r1)
with set_identity(new_owner):
assert not is_github_owner(new_owner, recid1)
assert not has_update_permission(new_owner, r1)
assert not has_newversion_permission(new_owner, r1)
# Change the repository owner
repo.user_id = new_owner.id
db.session.add(repo)
db.session.commit()
with app.test_request_context():
with set_identity(old_owner):
assert not is_github_owner(old_owner, recid1)
# `old_owner` can edit his record of course
assert has_update_permission(old_owner, r1)
assert has_newversion_permission(old_owner, r1)
with set_identity(new_owner):
assert is_github_owner(new_owner, recid1)
# `new_owner` can't edit the `old_owner`'s record
assert not has_update_permission(new_owner, r1)
assert not has_newversion_permission(new_owner, r1)
# Create second GitHub record (by `new_owner`)
depid2, d2, recid2, r2 = create_deposit_and_record('102', new_owner)
rel2 = Release(release_id=222, repository_id=repo.id, record_id=d2.id,
status=ReleaseStatus.PUBLISHED)
db.session.add(rel2)
db.session.commit()
with app.test_request_context():
with set_identity(old_owner):
assert not is_github_owner(old_owner, recid1)
assert not is_github_owner(old_owner, recid2)
assert has_update_permission(old_owner, r1)
# `old_owner` can't edit the `new_owner`'s record
assert not has_update_permission(old_owner, r2)
assert not has_newversion_permission(old_owner, r1)
assert not has_newversion_permission(old_owner, r2)
with set_identity(new_owner):
assert is_github_owner(new_owner, recid1)
assert is_github_owner(new_owner, recid2)
assert not has_update_permission(new_owner, r1)
# `new_owner` can edit his newly released record
assert has_update_permission(new_owner, r2)
assert has_newversion_permission(new_owner, r1)
assert has_newversion_permission(new_owner, r2)
# Create a manual record (by `new_owner`)
depid3, d3, recid3, r3 = create_deposit_and_record('103', new_owner)
db.session.commit()
with app.test_request_context():
with set_identity(old_owner):
assert not is_github_owner(old_owner, recid3)
assert not has_update_permission(old_owner, r3)
assert not has_newversion_permission(old_owner, r3)
with set_identity(new_owner):
assert is_github_owner(new_owner, recid3)
assert has_update_permission(new_owner, r3)
assert has_newversion_permission(new_owner, r3)
| lnielsen/zenodo | tests/unit/github/test_api.py | Python | gpl-2.0 | 10,739 |
/**
A modal view for handling user logins
@class LoginView
@extends Discourse.ModalBodyView
@namespace Discourse
@module Discourse
**/
Discourse.LoginView = Discourse.ModalBodyView.extend({
templateName: 'modal/login',
siteBinding: 'Discourse.site',
title: Em.String.i18n('login.title'),
authenticate: null,
loggingIn: false,
showView: function(view) {
return this.get('controller').show(view);
},
newAccount: function() {
return this.showView(Discourse.CreateAccountView.create());
},
forgotPassword: function() {
return this.showView(Discourse.ForgotPasswordView.create());
},
loginButtonText: (function() {
if (this.get('loggingIn')) {
return Em.String.i18n('login.logging_in');
}
return Em.String.i18n('login.title');
}).property('loggingIn'),
loginDisabled: (function() {
if (this.get('loggingIn')) {
return true;
}
if (this.blank('loginName') || this.blank('loginPassword')) {
return true;
}
return false;
}).property('loginName', 'loginPassword', 'loggingIn'),
login: function() {
var _this = this;
this.set('loggingIn', true);
$.post("/session", {
login: this.get('loginName'),
password: this.get('loginPassword')
}).success(function(result) {
if (result.error) {
_this.set('loggingIn', false);
if( result.reason === 'not_activated' ) {
return _this.showView(Discourse.NotActivatedView.create({username: _this.get('loginName'), sentTo: result.sent_to_email, currentEmail: result.current_email}));
}
_this.flash(result.error, 'error');
} else {
return window.location.reload();
}
}).fail(function(result) {
_this.flash(Em.String.i18n('login.error'), 'error');
return _this.set('loggingIn', false);
});
return false;
},
authMessage: (function() {
if (this.blank('authenticate')) {
return "";
}
return Em.String.i18n("login." + (this.get('authenticate')) + ".message");
}).property('authenticate'),
twitterLogin: function() {
var left, top;
this.set('authenticate', 'twitter');
left = this.get('lastX') - 400;
top = this.get('lastY') - 200;
return window.open("/auth/twitter", "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top);
},
facebookLogin: function() {
var left, top;
this.set('authenticate', 'facebook');
left = this.get('lastX') - 400;
top = this.get('lastY') - 200;
return window.open("/auth/facebook", "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top);
},
openidLogin: function(provider) {
var left, top;
left = this.get('lastX') - 400;
top = this.get('lastY') - 200;
if (provider === "yahoo") {
this.set("authenticate", 'yahoo');
return window.open("/auth/yahoo", "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top);
} else {
window.open("/auth/google", "_blank", "menubar=no,status=no,height=500,width=850,left=" + left + ",top=" + top);
return this.set("authenticate", 'google');
}
},
githubLogin: function() {
var left, top;
this.set('authenticate', 'github');
left = this.get('lastX') - 400;
top = this.get('lastY') - 200;
return window.open("/auth/github", "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top);
},
personaLogin: function() {
navigator.id.request();
},
authenticationComplete: function(options) {
if (options.awaiting_approval) {
this.flash(Em.String.i18n('login.awaiting_approval'), 'success');
this.set('authenticate', null);
return;
}
if (options.awaiting_activation) {
this.flash(Em.String.i18n('login.awaiting_confirmation'), 'success');
this.set('authenticate', null);
return;
}
// Reload the page if we're authenticated
if (options.authenticated) {
window.location.reload();
return;
}
return this.showView(Discourse.CreateAccountView.create({
accountEmail: options.email,
accountUsername: options.username,
accountName: options.name,
authOptions: Em.Object.create(options)
}));
},
mouseMove: function(e) {
this.set('lastX', e.screenX);
return this.set('lastY', e.screenY);
},
didInsertElement: function(e) {
var _this = this;
return Em.run.next(function() {
return $('#login-account-password').keydown(function(e) {
if (e.keyCode === 13) {
return _this.login();
}
});
});
}
});
| SuperSonicDesignINC/FXDD | app/assets/javascripts/discourse/views/modal/login_view.js | JavaScript | gpl-2.0 | 4,631 |
<?php $wl_theme_options = weblizar_get_options(); ?>
<div class="block ui-tabs-panel active" id="option-general" >
<form method="post" id="weblizar_theme_options_general">
<div id="heading">
<table style="width:100%;"><tr>
<td cols=2 ><h2><?php _e('General Settings','weblizar');?></h2></td>
<td style="width:30%;">
<div class="weblizar_settings_loding" id="weblizar_loding_general_image"></div>
<div class="weblizar_settings_massage" id="weblizar_settings_save_general_success" ><?php _e('Options Data updated','weblizar');?></div>
<div class="weblizar_settings_massage" id="weblizar_settings_save_general_reset" ><?php _e('Options data Reset','weblizar');?></div>
</td>
<td style="text-align:right;">
<input class="button" type="button" name="reset" value="Restore Defaults" onclick="weblizar_option_data_reset('general');">
<input class="button button-primary" type="button" value="Save Options" onclick="weblizar_option_data_save('general')" >
</td>
</tr>
</table>
</div>
<div class="section">
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
<?php _e('Theme Color Schemes','weblizar'); ?>
</a>
<a href="http://weblizar.com/themes/weblizar-premium-theme/" target="_blank" class="btn btn-success btn_upsell"><?php _e('GET PREMIUM ','weblizar'); ?></a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in">
<div class="panel-body">
<?php $stylesheet= ' ' ;?>
<select id="style_sheet" name="style_sheet" class="wl_inpute">
<option <?php echo selected($stylesheet, 'light-blue.css' ); ?> value="light-blue.css" ><?php _e('light-blue','weblizar'); ?></option>
<option <?php echo selected($stylesheet, 'green.css' ); ?> value="green.css" ><?php _e('green','weblizar'); ?></option>
<option <?php echo selected($stylesheet, 'red.css' ); ?> value="red.css" ><?php _e('red','weblizar'); ?></option>
<option <?php echo selected($stylesheet, 'pink.css' ); ?> value="pink.css" ><?php _e('pink','weblizar'); ?></option>
<option <?php echo selected($stylesheet, 'light-purple.css' ); ?> value="light-purple.css" ><?php _e('light-purple','weblizar'); ?></option>
<option <?php echo selected($stylesheet, 'orange.css' ); ?> value="orange.css" ><?php _e('orange','weblizar'); ?></option>
<option <?php echo selected($stylesheet, 'bright-green.css' ); ?> value="bright-green.css" ><?php _e('bright-green','weblizar'); ?></option>
<option <?php echo selected($stylesheet, 'dark-blue.css' ); ?> value="dark-blue.css" ><?php _e('dark-blue','weblizar'); ?></option>
<option <?php echo selected($stylesheet, 'oil.css' ); ?> value="oil.css" ><?php _e('oil','weblizar'); ?></option>
<option <?php echo selected($stylesheet, 'black.css' ); ?> value="black.css" ><?php _e('black','weblizar'); ?></option>
<option <?php echo selected($stylesheet, 'light-brown.css' ); ?> value="light-brown.css" ><?php _e('light-brown','weblizar'); ?></option>
<option <?php echo selected($stylesheet, 'coffee.css' ); ?> value="coffee.css" ><?php _e('coffee','weblizar'); ?></option>
<option <?php echo selected($stylesheet, 'flat-blue.css' ); ?> value="flat-blue.css" ><?php _e('flat-blue','weblizar'); ?></option>
</select>
<span class="explain"><?php _e('Select OUT of 10+ Color Schemes','weblizar'); ?></span>
</div>
</div>
</div>
</div>
</div>
<div class="section">
<h3><?php _e('Home-Page or Custom Page','weblizar'); ?></h3>
<input type="checkbox" <?php if($wl_theme_options['_frontpage']=='on') echo "checked='checked'"; ?> id="_frontpage" name="_frontpage" > <span class="explain"><?php _e('Enable Custom Static Front-Page.','weblizar');?> <a href="<?php echo home_url( '/' ); ?>wp-admin/options-reading.php"><?php _e('Click Here','weblizar');?></a>.</span>
</div>
<div class="section">
<h3><?php _e('Add Your Company Logo','weblizar'); ?></h3>
<input class="weblizar_inpute" id="weblizar_inpute4" type="text" value="<?php if($wl_theme_options['upload_image_logo']!='') { echo esc_url($wl_theme_options['upload_image_logo']); } ?>" name="upload_image_logo" size="36" class="upload has-file"/>
<input type="button" id="upload_button4" value="Upload" class="btn btn-primary upload_image_button" onclick="show_re(4)" />
<input type="button" id="preview_image4" value="Preview" class="btn btn-success " onclick="preview_image(4)" />
<input type="button" id="remove_button4" value="Remove" class="btn btn-danger remove_button" style="<?php if($wl_theme_options['upload_image_logo']=='') { ?> display:none<?php } ?>" onclick="remove_image(4);" />
<span class="explain" id="no_slide_media4" style="display:none"><?php _e('No media Selected','weblizar');?> </span>
<span class="explain"><?php _e('Add Company logo from here suggested size is 150X50','weblizar');?></span>
<img class="weblizar-prev-img" id="slide-img4" src="" />
</div>
<div class="section">
<h3><?php _e('Logo Height','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="height" id="height" value="<?php echo esc_html($wl_theme_options['height']); ?>" >
<span class="explain"><?php _e('Default Logo Height : 55px, if you want to increase than specify your value','weblizar'); ?></span>
</div>
<div class="section">
<h3><?php _e('Logo Width','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="width" id="width" value="<?php echo esc_html($wl_theme_options['width']); ?>" >
<span class="explain"><?php _e('Default Logo Width : 150px, if you want to increase than specify your value','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Your Blog Title','weblizar'); ?></h3>
<input type="checkbox" <?php if($wl_theme_options['text_title']=='on') echo "checked='checked'"; ?> id="text_title" name="text_title" > <span class="explain"><?php _e('Enable Blog-Title as a Logo for your . Setup title','weblizar');?> <a href="<?php echo home_url( '/' ); ?>wp-admin/options-general.php"><?php _e('Click Here','weblizar');?></a>.</span>
</div>
<div class="section">
<h3><?php _e('Add Your Company Fevicon','weblizar'); ?></h3>
<input class="weblizar_inpute" id="weblizar_inpute5" type="text" value="<?php if($wl_theme_options['upload_image_favicon']!='') { echo esc_url($wl_theme_options['upload_image_favicon']); } ?>" name="upload_image_favicon" size="36" class="upload has-file"/>
<input type="button" id="upload_button5" value="Upload" class="btn btn-primary upload_image_button" onclick="show_re(5)" />
<input type="button" id="preview_image5" value="Preview" class="btn btn-success " onclick="preview_image(5)" />
<input type="button" id="remove_button5" value="Remove" class="btn btn-danger remove_button" onclick="remove_image(5);" style="<?php if($wl_theme_options['upload_image_favicon']=='') { ?> display:none<?php } ?>" />
<span class="explain" id="no_slide_media5" style="display:none">No media Selected </span>
<span class="explain"><?php _e('Add Company fevicon from here suggested size is 32X32','weblizar');?></span>
<img class="weblizar-prev-img" id="slide-img5" src="" />
</div>
<div class="section">
<h3><?php _e('Custom css','weblizar'); ?></h3>
<textarea rows="8" cols="8" id="custom_css" name="custom_css"><?php if($wl_theme_options['custom_css']!='') { echo esc_attr($wl_theme_options['custom_css']); } ?></textarea>
<div class="explain"><?php _e('This is a powerful feature provided here. No need to use custom css plugin, just paste your css code and see the magic.','weblizar'); ?><br></div>
</div>
<div id="button_section">
<input type="hidden" value="1" id="weblizar_settings_save_general" name="weblizar_settings_save_general" />
<input class="button" type="button" name="reset" value="Restore Defaults" onclick="weblizar_option_data_reset('general');">
<input class="button button-primary" type="button" value="Save Options" onclick="weblizar_option_data_save('general')" >
</div>
</form>
</div>
<!-------- Home slider setting -------->
<div class="block ui-tabs-panel deactive" id="option-home-image" >
<form method="post" id="weblizar_theme_options_home-image">
<div id="heading">
<table style="width:100%;"><tr>
<td cols=2 ><h2><?php _e('Slide show Settings','weblizar');?></h2></td>
<td style="width:30%;">
<div class="weblizar_settings_loding" id="weblizar_loding_home-image_image"></div>
<div class="weblizar_settings_massage" id="weblizar_settings_save_home-image_success" ><?php _e('Options Data updated','weblizar');?></div>
<div class="weblizar_settings_massage" id="weblizar_settings_save_home-image_reset" ><?php _e('Options data Reset','weblizar');?></div>
</td>
<td style="text-align:right;">
<input class="button" type="button" name="reset" value="Restore Defaults" onclick="weblizar_option_data_reset('home-image');">
<input class="button button-primary" type="button" value="Save Options" onclick="weblizar_option_data_save('home-image')" >
</td>
</tr>
</table>
</div>
<div class="panel-group" id="1accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#1accordion" href="#collapse11">
<?php _e('Slide Detail One','weblizar'); ?>
<span class="glyphicon glyphicon-arrow-down btn_upsell_arrow"></span></a>
</h4>
</div>
<div id="collapse11" class="panel-collapse collapse in">
<div class="panel-body">
<div class="section">
<h3><?php _e('Home Feature Image One','weblizar'); ?></h3>
<input class="weblizar_inpute" id="weblizar_inpute1" type="text" value="<?php if($wl_theme_options['slide_image']!='') { echo esc_url($wl_theme_options['slide_image']); } ?>" name="slide_image" size="36" class="upload has-file"/>
<input type="button" id="upload_button1" value="Upload" class="btn btn-primary upload_image_button" onclick="show_re(1)" />
<input type="button" id="preview_image1" value="Preview" class="btn btn-success " onclick="preview_image(1)" />
<input type="button" id="remove_button1" value="Remove" class="btn btn-danger remove_button" style="<?php if($wl_theme_options['slide_image']=='') { ?> display:none<?php } ?>" onclick="remove_image(1);" />
<span class="explain" id="no_slide_media1" style="display:none"><?php _e('No media Selected','weblizar'); ?> </span>
<span class="explain"><?php _e('Add Home Feature image here, size suggestion is 1900X525.','weblizar'); ?></span>
<img class="weblizar-prev-img" id="slide-img1" src="" />
</div>
<div class="section">
<h3><?php _e('Home Feature Image Title One','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="slide_title" id="slide_title" value="<?php if($wl_theme_options['slide_title']!='') { echo esc_html($wl_theme_options['slide_title']); } ?>" >
<span class="explain"><?php _e('Type Home Feature Image Title Here','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Home Feature Image Description One','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="slide_desc" id="slide_desc" value="<?php if($wl_theme_options['slide_desc']!='') { echo esc_attr($wl_theme_options['slide_desc']); } ?>" >
<span class="explain"><?php _e('Type Home Feature Image Description Here','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Home Feature Image Button Text One','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="slide_btn_text" id="slide_btn_text" value="<?php if($wl_theme_options['slide_btn_text']!='') { echo esc_attr($wl_theme_options['slide_btn_text']); } ?>" >
<span class="explain"><?php _e('Type Home Feature Image Button Text Here','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Home Feature Image Button Link One','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="slide_btn_link" id="slide_btn_link" value="<?php if($wl_theme_options['slide_btn_link']!='') { echo esc_url($wl_theme_options['slide_btn_link']); } ?>" >
<span class="explain"><?php _e('Type Home Feature Image Button Link Here','weblizar');?></span>
</div>
</div>
</div>
</div>
</div>
<!-- Home Feature 2 -->
<div class="section"></div>
<div class="panel-group" id="2accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#2accordion" href="#collapse12">
<?php _e('Slide Detail Two','weblizar'); ?><span class="glyphicon glyphicon-arrow-down btn_upsell_arrow"></span>
</a>
</h4>
</div>
<div id="collapse12" class="panel-collapse collapse">
<div class="panel-body">
<div class="section">
<h3><?php _e('Home Feature Image Two','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" id="weblizar_inpute2" value="<?php if($wl_theme_options['slide_image_1']!='') { echo esc_url($wl_theme_options['slide_image_1']); } ?>" name="slide_image_1" size="36" class="upload has-file"/>
<input type="button" id="upload_button2" value="Upload" class="btn btn-primary upload_image_button" onclick="show_re(2)" />
<input type="button" id="preview_image2" value="Preview" class="btn btn-success " onclick="preview_image(2)" />
<input type="button" id="remove_button2" value="Remove" class="btn btn-danger remove_button" style="<?php if($wl_theme_options['slide_image_1']=='') { ?> display:none<?php } ?>" onclick="remove_image(2);" />
<span class="explain" id="no_slide_media2" style="display:none">No media Selected </span>
<span class="explain"><?php _e('Add Home Feature image here, size suggestion is 1900X525.','weblizar');?></span>
<img class="weblizar-prev-img" id="slide-img2" src="" />
</div>
<div class="section">
<h3><?php _e('Home Feature Image Title Two','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="slide_title_1" id="slide_title_1" value="<?php if($wl_theme_options['slide_title_1']!='') { echo esc_html($wl_theme_options['slide_title_1']); } ?>" >
<span class="explain"><?php _e('Type Home Feature Image Title Here','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Home Feature Image Description Two','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="slide_desc_1" id="slide_desc_1" value="<?php if($wl_theme_options['slide_desc_1']!='') { echo esc_attr($wl_theme_options['slide_desc_1']); } ?>" >
<span class="explain"><?php _e('Type Home Feature Image Description Here','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Home Feature Image Button Text Two','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="slide_btn_text_1" id="slide_btn_text_1" value="<?php if($wl_theme_options['slide_btn_text_1']!='') { echo esc_attr($wl_theme_options['slide_btn_text_1']); } ?>" >
<span class="explain"><?php _e('Type Home Feature Image Button Text Here','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Home Feature Image Button Link Two','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="slide_btn_link_1" id="slide_btn_link_1" value="<?php if($wl_theme_options['slide_btn_link_1']!='') { echo esc_url($wl_theme_options['slide_btn_link_1']); } ?>" >
<span class="explain"><?php _e('Type Home Feature Image Button Link Here','weblizar');?></span>
</div>
</div>
</div>
</div>
</div>
<!-- Home Feature 3 -->
<div class="section"></div>
<div class="panel-group" id="3accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#3accordion" href="#collapse13">
</span> <?php _e('Slide Detail Three','weblizar'); ?> <span class="glyphicon glyphicon-arrow-down btn_upsell_arrow"></span>
</a>
</h4>
</div>
<div id="collapse13" class="panel-collapse collapse">
<div class="panel-body">
<div class="section">
<h3><?php _e('Home Feature Image Three','weblizar'); ?></h3>
<input class="weblizar_inpute" id="weblizar_inpute3" type="text" value="<?php if($wl_theme_options['slide_image_2']!='') { echo esc_url($wl_theme_options['slide_image_2']); } ?>" name="slide_image_2" size="36" class="upload has-file"/>
<input type="button" id="upload_button3" value="Upload" class="btn btn-primary upload_image_button" onclick="show_re(3)" />
<input type="button" id="preview_image3" value="Preview" class="btn btn-success " onclick="preview_image(3)" />
<input type="button" id="remove_button3" value="Remove" class="btn btn-danger remove_button" style="<?php if($wl_theme_options['slide_image_2']=='') { ?> display:none<?php } ?>" onclick="remove_image(3);" />
<span class="explain" id="no_slide_media3" style="display:none">No media Selected </span>
<span class="explain"><?php _e('Add Home Feature image here, size suggestion is 1900X525.','weblizar');?></span>
<img class="weblizar-prev-img" id="slide-img3" src="" />
</div>
<div class="section">
<h3><?php _e('Home Feature Image Title Three','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="slide_title_2" id="slide_title_2" value="<?php if($wl_theme_options['slide_title_2']!='') { echo esc_attr($wl_theme_options['slide_title_2']); } ?>" >
<span class="explain"><?php _e('Type Home Feature Image Title Here','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Home Feature Image Description Three','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="slide_desc_2" id="slide_desc_2" value="<?php if($wl_theme_options['slide_desc_2']!='') { echo esc_attr($wl_theme_options['slide_desc_2']); } ?>" >
<span class="explain"><?php _e('Type Home Feature Image Description Here','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Home Feature Image Button Text Three','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="slide_btn_text_2" id="slide_btn_text_2" value="<?php if($wl_theme_options['slide_btn_text_2']!='') { echo esc_attr($wl_theme_options['slide_btn_text_2']); } ?>" >
<span class="explain"><?php _e('Type Home Feature Image Button Text Here','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Home Feature Image Button Link Three','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="slide_btn_link_2" id="slide_btn_link_2" value="<?php if($wl_theme_options['slide_btn_link_2']!='') { echo esc_url($wl_theme_options['slide_btn_link_2']); } ?>" >
<span class="explain"><?php _e('Type Home Feature Image Button Link Here','weblizar');?></span>
</div>
</div>
</div>
</div>
</div>
<div class="section">
<div class="panel-group" id="accordion1">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapsetwo">
<?php _e('More Slides','weblizar'); ?>
</a>
<a href="http://weblizar.com/themes/weblizar-premium-theme/" target="_blank" class="btn btn-success btn_upsell"><?php _e('GET PREMIUM','weblizar'); ?></a>
</h4>
</div>
<div id="collapsetwo" class="panel-collapse collapse in">
<div class="panel-body">
<span class="explain"><?php _e('Add Unlimited slides for your sideshow ','weblizar'); ?></span>
</div>
</div>
</div>
</div>
</div>
<!---Save DATA -->
<div id="button_section">
<input type="hidden" value="1" id="weblizar_settings_save_home-image" name="weblizar_settings_save_home-image" />
<input class="button" type="button" name="reset" value="Restore Defaults" onclick="weblizar_option_data_reset('home-image');">
<input class="button button-primary" type="button" value="Save Options" onclick="weblizar_option_data_save('home-image')" >
</div>
</form>
</div>
<!-------- Home site info and blog setting ------------>
<div class="block ui-tabs-panel deactive" id="option-site-info" >
<form method="post" id="weblizar_theme_options_site-info">
<div id="heading">
<table style="width:100%;"><tr>
<td cols=2 ><h2><?php _e('Site Info Settings','weblizar');?></h2></td>
<td style="width:30%;">
<div class="weblizar_settings_loding" id="weblizar_loding_site-info_image"></div>
<div class="weblizar_settings_massage" id="weblizar_settings_save_site-info_success" ><?php _e('Options Data updated','weblizar');?></div>
<div class="weblizar_settings_massage" id="weblizar_settings_save_site-info_reset" ><?php _e('Options data Reset','weblizar');?></div>
</td>
<td style="text-align:right;">
<input class="button" type="button" name="reset" value="Restore Defaults" onclick="weblizar_option_data_reset('site-info');">
<input class="button button-primary" type="button" value="Save Options" onclick="weblizar_option_data_save('site-info')" >
</td>
</tr>
</table>
</div>
<div class="section">
<h3><?php _e('Site Intro Title','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="site_intro_title" id="site_intro_title" value="<?php if($wl_theme_options['site_intro_title']!='') { echo esc_html($wl_theme_options['site_intro_title']); } ?>" >
<span class="explain"><?php _e('Type here your site information text','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Site Description','weblizar'); ?></h3>
<textarea rows="8" cols="8" id="site_intro_text" name="site_intro_text"><?php if($wl_theme_options['site_intro_text']!='') { echo esc_attr($wl_theme_options['site_intro_text']); } ?></textarea>
<div class="explain"><?php _e('Type here your site description.','weblizar'); ?><br></div>
</div>
<div class="section">
<h3><?php _e('Blog Title','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="blog_title" id="blog_title" value="<?php if($wl_theme_options['blog_title']!='') { echo esc_html($wl_theme_options['blog_title']); } ?>" >
<span class="explain"><?php _e('Type here your blog title','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Blog Description','weblizar'); ?></h3>
<textarea rows="8" cols="8" id="blog_text" name="blog_text"><?php if($wl_theme_options['blog_text']!='') { echo esc_attr($wl_theme_options['blog_text']); } ?></textarea>
<div class="explain"><?php _e('Type here your Blog description.','weblizar'); ?><br></div>
</div>
<div class="section">
<div class="panel-group" id="accordion2">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapsethree">
<?php _e('More Sections','weblizar'); ?>
</a>
<a href="http://weblizar.com/themes/weblizar-premium-theme/" target="_blank" class="btn btn-success btn_upsell"><?php _e('GET PREMIUM','weblizar'); ?></a>
</h4>
</div>
<div id="collapsethree" class="panel-collapse collapse in">
<div class="panel-body">
<span class="explain"><?php _e('Add More Sections and More Features on your website.','weblizar'); ?></span>
</div>
</div>
</div>
</div>
</div>
<div id="button_section">
<input type="hidden" value="1" id="weblizar_settings_save_site-info" name="weblizar_settings_save_site-info" />
<input class="button" type="button" name="reset" value="Restore Defaults" onclick="weblizar_option_data_reset('site-info');">
<input class="button button-primary" type="button" value="Save Options" onclick="weblizar_option_data_save('site-info')" >
</div>
</form>
</div>
<!--------------- service settings ------------>
<div class="block ui-tabs-panel deactive" id="option-home-service" >
<form method="post" id="weblizar_theme_options_home-service">
<div id="heading">
<table style="width:100%;"><tr>
<td cols=2 ><h2><?php _e('Service Settings','weblizar');?></h2></td>
<td style="width:30%;">
<div class="weblizar_settings_loding" id="weblizar_loding_home-service_image"></div>
<div class="weblizar_settings_massage" id="weblizar_settings_save_home-service_success" ><?php _e('Options Data updated','weblizar');?></div>
<div class="weblizar_settings_massage" id="weblizar_settings_save_home-service_reset" ><?php _e('Options data Reset','weblizar');?></div>
</td>
<td style="text-align:right;">
<input class="button" type="button" name="reset" value="Restore Defaults" onclick="weblizar_option_data_reset('home-service');">
<input class="button button-primary" type="button" value="Save Options" onclick="weblizar_option_data_save('home-service')" >
</td>
</tr>
</table>
</div>
<div class="panel-group" id="4accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#4accordion" href="#collapse14">
</span> <?php _e('Service Detail One','weblizar'); ?><span class="glyphicon glyphicon-arrow-down btn_upsell_arrow"></span>
</a>
</h4>
</div>
<div id="collapse14" class="panel-collapse collapse in">
<div class="panel-body">
<div class="section">
<h3><?php _e('Service One','weblizar'); ?></h3>
<hr>
<h3><?php _e('Service Title','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="service_1_title" id="service_1_title" value="<?php if($wl_theme_options['service_1_title']!='') { echo esc_html($wl_theme_options['service_1_title']); } ?>" >
<span class="explain"><?php _e('Type here your service title','weblizar');?></span>
<h3><?php _e('Service Icons','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="service_1_icons" id="service_1_icons" value="<?php if($wl_theme_options['service_1_icons']!='') { echo esc_attr($wl_theme_options['service_1_icons']); } ?>" >
<br>
<span class="explain"><?php _e('Service Icon (Using Font-Awesome icons name) like: fa fa-angellist','weblizar'); ?> <a href="http://fortawesome.github.io/Font-Awesome/icons/" target="_blank"> <?php _e('Get your Font-Awesome icons','weblizar'); ?>.</a> </span>
<h3><?php _e('Service Description','weblizar'); ?></h3>
<?php $settings = array( "media_buttons" => false,"quicktags" => false, "tinymce" => array( "plugins" => "wordpress" ) ); ?>
<?php $content = $wl_theme_options["service_1_text"]!="" ? esc_attr($wl_theme_options["service_1_text"]) : "" ; ?>
<?php $editor_id = "service_1_text"; ?>
<?php wp_editor( $content, $editor_id,$settings ); ?>
<div class="explain"><?php _e('Type here your service description.','weblizar'); ?><br></div>
<h3><?php _e('Service Link','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="service_1_link" id="service_1_link" value="<?php if($wl_theme_options['service_1_link']!='') { echo esc_url($wl_theme_options['service_1_link']); } ?>" >
<span class="explain"><?php _e('Type here your service link','weblizar');?></span>
</div></div></div></div></div>
<div class="section"></div>
<div class="panel-group" id="5accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#5accordion" href="#collapse15">
<?php _e('Service Detail Two','weblizar'); ?><span class="glyphicon glyphicon-arrow-down btn_upsell_arrow"></span>
</a>
</h4>
</div>
<div id="collapse15" class="panel-collapse collapse">
<div class="panel-body">
<div class="section">
<h3><?php _e('Service Two','weblizar'); ?></h3>
<hr>
<h3><?php _e('Service Title','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="service_2_title" id="service_2_title" value="<?php if($wl_theme_options['service_2_title']!='') { echo esc_html($wl_theme_options['service_2_title']); } ?>" >
<span class="explain"><?php _e('Type here your service title','weblizar');?></span>
<h3><?php _e('Service Icons','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="service_2_icons" id="service_2_icons" value="<?php if($wl_theme_options['service_2_icons']!='') { echo esc_attr($wl_theme_options['service_2_icons']); } ?>" >
<br>
<span class="explain"><?php _e('Service Icon (Using Font-Awesome icons name) like: fa fa-angellist','weblizar'); ?> <a href="http://fortawesome.github.io/Font-Awesome/icons/" target="_blank"><?php _e('Get your Font-Awesome icons','weblizar'); ?>.</a> </span>
<h3><?php _e('Service Description','weblizar'); ?></h3>
<?php $settings = array( "media_buttons" => false,"quicktags" => false, "tinymce" => array( "plugins" => "wordpress" ) ); ?>
<?php $content = $wl_theme_options["service_2_text"]!="" ? esc_attr($wl_theme_options["service_2_text"]) : "" ; ?>
<?php $editor_id = "service_2_text"; ?>
<?php wp_editor( $content, $editor_id,$settings ); ?>
<div class="explain"><?php _e('Type here your service description.','weblizar'); ?><br></div>
<h3><?php _e('Service Link','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="service_2_link" id="service_2_link" value="<?php if($wl_theme_options['service_2_link']!='') { echo esc_url($wl_theme_options['service_2_link']); } ?>" >
<span class="explain"><?php _e('Type here your service link','weblizar');?></span>
</div>
</div>
</div>
</div>
</div>
<div class="section"></div>
<div class="panel-group" id="7accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#7accordion" href="#collapse17">
<?php _e('Service Detail Three','weblizar'); ?><span class="glyphicon glyphicon-arrow-down btn_upsell_arrow"></span>
</a>
</h4>
</div>
<div id="collapse17" class="panel-collapse collapse">
<div class="panel-body">
<div class="section">
<h3><?php _e('Service Three','weblizar'); ?></h3>
<hr>
<h3><?php _e('Service Title','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="service_3_title" id="service_3_title" value="<?php if($wl_theme_options['service_3_title']!='') { echo esc_html($wl_theme_options['service_3_title']); } ?>" >
<span class="explain"><?php _e('Type here your service title','weblizar');?></span>
<h3><?php _e('Service Icons','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="service_3_icons" id="service_3_icons" value="<?php if($wl_theme_options['service_3_icons']!='') { echo esc_attr($wl_theme_options['service_3_icons']); } ?>" >
<br>
<span class="explain"><?php _e('Service Icon (Using Font-Awesome icons name) like: fa fa-angellist','weblizar'); ?> <a href="http://fortawesome.github.io/Font-Awesome/icons/" target="_blank"><?php _e('Get your Font-Awesome icons','weblizar'); ?>.</a> </span>
<h3><?php _e('Service Description','weblizar'); ?></h3>
<?php $settings = array( "media_buttons" => false,"quicktags" => false, "tinymce" => array( "plugins" => "wordpress" ) ); ?>
<?php $content = $wl_theme_options["service_3_text"]!="" ? esc_attr($wl_theme_options["service_3_text"]) : "" ; ?>
<?php $editor_id = "service_3_text"; ?>
<?php wp_editor( $content, $editor_id,$settings ); ?>
<div class="explain"><?php _e('Type here your service description.','weblizar'); ?><br></div>
<h3><?php _e('Service Link','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="service_3_link" id="service_3_link" value="<?php if($wl_theme_options['service_3_link']!='') { echo esc_url($wl_theme_options['service_3_link']); } ?>" >
<span class="explain"><?php _e('Type here your service link','weblizar');?></span>
</div>
</div>
</div>
</div>
</div>
<div class="section"></div>
<div class="panel-group" id="8accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#8accordion" href="#collapse18">
<?php _e('Service Detail Four','weblizar'); ?><span class="glyphicon glyphicon-arrow-down btn_upsell_arrow"></span>
</a>
</h4>
</div>
<div id="collapse18" class="panel-collapse collapse">
<div class="panel-body">
<div class="section">
<h3><?php _e('Service Four','weblizar'); ?></h3>
<hr>
<h3><?php _e('Service Title','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="service_4_title" id="service_4_title" value="<?php if($wl_theme_options['service_4_title']!='') { echo esc_html($wl_theme_options['service_4_title']); } ?>" >
<span class="explain"><?php _e('Type here your service title','weblizar');?></span>
<h3><?php _e('Service Icons','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="service_4_icons" id="service_4_icons" value="<?php if($wl_theme_options['service_4_icons']!='') { echo esc_attr($wl_theme_options['service_4_icons']); } ?>" >
<br>
<span class="explain"><?php _e('Service Icon (Using Font-Awesome icons name) like: fa fa-angellist','weblizar'); ?> <a href="http://fortawesome.github.io/Font-Awesome/icons/" target="_blank"><?php _e('Get your Font-Awesome icons','weblizar'); ?>.</a> </span>
<h3><?php _e('Service Description','weblizar'); ?></h3>
<?php $settings = array( "media_buttons" => false,"quicktags" => false, "tinymce" => array( "plugins" => "wordpress" ) ); ?>
<?php $content = $wl_theme_options["service_4_text"]!="" ? esc_attr($wl_theme_options["service_4_text"]) : "" ; ?>
<?php $editor_id = "service_4_text"; ?>
<?php wp_editor( $content, $editor_id,$settings ); ?>
<div class="explain"><?php _e('Type here your service description.','weblizar'); ?><br></div>
<h3><?php _e('Service Link','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="service_4_link" id="service_4_link" value="<?php if($wl_theme_options['service_4_link']!='') { echo esc_url($wl_theme_options['service_4_link']); } ?>" >
<span class="explain"><?php _e('Type here your service link','weblizar');?></span>
</div>
</div>
</div>
</div>
</div>
<div class="section">
<div class="panel-group" id="accordion3">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapsefour">
<?php _e('More Services','weblizar'); ?>
</a>
<a href="http://weblizar.com/themes/weblizar-premium-theme/" target="_blank" class="btn btn-success btn_upsell"><?php _e('GET PREMIUM','weblizar'); ?></a>
</h4>
</div>
<div id="collapsefour" class="panel-collapse collapse in">
<div class="panel-body">
<span class="explain"><?php _e('Add More Services on your Home Page.','weblizar'); ?></span>
</div>
</div>
</div>
</div>
</div>
<div id="button_section">
<input type="hidden" value="1" id="weblizar_settings_save_home-service" name="weblizar_settings_save_home-service" />
<input class="button" type="button" name="reset" value="Restore Defaults" onclick="weblizar_option_data_reset('home-service');">
<input class="button button-primary" type="button" value="Save Options" onclick="weblizar_option_data_save('home-service')" >
<!-- alert massage when data saved and reset -->
</div>
</form>
</div>
<!-------- Social media link settings ----------->
<div class="block ui-tabs-panel deactive" id="option-social" >
<form method="post" id="weblizar_theme_options_social">
<div id="heading">
<table style="width:100%;"><tr>
<td><h2><?php _e('Social media','weblizar');?></h2></td>
<td style="width:30%;">
<div class="weblizar_settings_loding" id="weblizar_loding_social_image"></div>
<div class="weblizar_settings_massage" id="weblizar_settings_save_social_success" ><?php _e('Options Data updated','weblizar');?></div>
<div class="weblizar_settings_massage" id="weblizar_settings_save_social_reset" ><?php _e('Options data Reset','weblizar');?></div>
</td>
<td style="text-align:right;">
<input class="button" type="button" name="reset" value="Restore Defaults" onclick="weblizar_option_data_reset('social');">
<input class="button button-primary" type="button" value="Save Options" onclick="weblizar_option_data_save('social')" >
</td>
</tr>
</table>
</div>
<div class="section">
<h3><?php _e('Enable Social media:','weblizar'); ?> </h3>
<input type="checkbox" <?php if($wl_theme_options['footer_section_social_media_enbled']=='on') echo "checked='checked'"; ?> id="footer_section_social_media_enbled" name="footer_section_social_media_enbled" > <span class="explain"><?php _e('Enable Social media in footer section.','weblizar'); ?></span>
</div>
<div class="section">
<h3><?php _e('Twitter Link:','weblizar');?></h3>
<input class="weblizar_inpute" type="text" name="social_media_twitter_link" id="social_media_twitter_link" value="<?php if($wl_theme_options['social_media_twitter_link']!='') { echo esc_url($wl_theme_options['social_media_twitter_link']); } ?>" >
<span class="explain"><?php _e('Enter twitter link.','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Linkedin Links:','weblizar');?></h3>
<input class="weblizar_inpute" type="text" name="social_media_linkedin_link" id="social_media_linkedin_link" value="<?php if($wl_theme_options['social_media_linkedin_link']!='') { echo esc_url($wl_theme_options['social_media_linkedin_link']); } ?>" >
<span class="explain"><?php _e('Enter linkedin link.','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Facebook Links:','weblizar');?></h3>
<input class="weblizar_inpute" type="text" name="social_media_facebook_link" id="social_media_facebook_link" value="<?php if($wl_theme_options['social_media_facebook_link']!='') { echo esc_url($wl_theme_options['social_media_facebook_link']); } ?>" >
<span class="explain"><?php _e('Enter facebook link.','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Google Plus Links:','weblizar');?></h3>
<input class="weblizar_inpute" type="text" name="social_media_google_plus" id="social_media_google_plus" value="<?php if($wl_theme_options['social_media_google_plus']!='') { echo esc_url($wl_theme_options['social_media_google_plus']); } ?>" >
<span class="explain"><?php _e('Enter google plus link.','weblizar');?></span>
</div>
<div id="button_section">
<input type="hidden" value="1" id="weblizar_settings_save_social" name="weblizar_settings_save_social" />
<input class="button" type="button" name="reset" value="Restore Defaults" onclick="weblizar_option_data_reset('social');">
<input class="button button-primary" type="button" value="Save Options" onclick="weblizar_option_data_save('social')" >
</div>
</form>
</div>
<!---------------- footer customization Settings form ------------------------>
<div class="block ui-tabs-panel deactive" id="option-footer" >
<form method="post" id="weblizar_theme_options_footer">
<div id="heading">
<table style="width:100%;"><tr>
<td cols=2 ><h2><?php _e('Footer Customization','weblizar');?></h2></td>
<td style="width:30%;">
<div class="weblizar_settings_loding" id="weblizar_loding_footer_image"></div>
<div class="weblizar_settings_massage" id="weblizar_settings_save_footer_success" ><?php _e('Options Data updated','weblizar');?></div>
<div class="weblizar_settings_massage" id="weblizar_settings_save_footer_reset" ><?php _e('Options data Reset','weblizar');?></div>
</td>
<td style="text-align:right;">
<input class="button" type="button" name="reset" value="Restore Defaults" onclick="weblizar_option_data_reset('footer');">
<input class="button button-primary" type="button" value="Save Options" onclick="weblizar_option_data_save('footer')" >
</td>
</tr>
</table>
</div>
<div class="section">
<h3><?php _e('Footer customization','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="footer_customizations" id="footer_customizations" value="<?php if($wl_theme_options['footer_customizations']!='') { echo esc_attr($wl_theme_options['footer_customizations']); } ?>" >
<span class="explain"><?php _e('Enter your footer customization text ','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Developed by text','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="developed_by_text" id="developed_by_text" value="<?php if($wl_theme_options['developed_by_text']!='') { echo esc_html($wl_theme_options['developed_by_text']); } ?>" >
<span class="explain"><?php _e('Enter developed by text','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Developed by link text','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="developed_by_weblizar_text" id="developed_by_weblizar_text" value="<?php if($wl_theme_options['developed_by_weblizar_text']!='') { echo esc_attr($wl_theme_options['developed_by_weblizar_text']); } ?>" >
<span class="explain"><?php _e('Enter developed by link text ','weblizar');?></span>
</div>
<div class="section">
<h3><?php _e('Developed by link','weblizar'); ?></h3>
<input class="weblizar_inpute" type="text" name="developed_by_link" id="developed_by_link" value="<?php if($wl_theme_options['developed_by_link']!='') { echo esc_url($wl_theme_options['developed_by_link']); } ?>" >
<span class="explain"><?php _e('Enter developed by link','weblizar');?></span>
</div>
<div id="button_section">
<input type="hidden" value="1" id="weblizar_settings_save_footer" name="weblizar_settings_save_footer" />
<input class="button" type="button" name="reset" value="Restore Defaults" onclick="weblizar_option_data_reset('footer');">
<input class="button button-primary" type="button" value="Save Options" onclick="weblizar_option_data_save('footer')" >
</div>
</form>
</div>
<!---------------- footer customization Settings form ------------------------>
<div class="block ui-tabs-panel deactive" id="option-getpro" >
<div class="plan-name">
<h2><?php _e('Weblizar Pro Responsive Wordpress Theme','weblizar'); ?></h2>
<h6><?php _e('Get The Premium Weblizar in Just $29','weblizar'); ?> </h6>
</div>
<div class="row-fluid pricing-table pricing-three-column">
<div class="col-md-4">
<div class=" plan ap">
<div class="plan-name">
<h2><?php _e('Weblizar Feature','weblizar'); ?></h2>
</div>
<ul>
<li class="plan-feature"><?php _e('Easy to customize','weblizar'); ?> </li>
<li class="plan-feature"><?php _e('Awesome Slider','weblizar'); ?></li>
<li class="plan-feature"><?php _e('Multi Color','weblizar'); ?></li>
<li class="plan-feature"><?php _e('Boxed & Wide','weblizar'); ?></li>
<li class="plan-feature"><?php _e('Widgetized Footer','weblizar'); ?></li>
<li class="plan-feature"><?php _e('Custom Widgets','weblizar'); ?></li>
<li class="plan-feature"><?php _e('Shortcode','weblizar'); ?></li>
<li class="plan-feature"><?php _e('Page Templates','weblizar'); ?></li>
<li class="plan-feature"><?php _e('Quick Support','weblizar'); ?></li>
<li class="plan-feature"><?php _e('Custom CSS','weblizar'); ?></li>
<li class="plan-feature"><?php _e('Custom Background','weblizar'); ?></li>
<li class="plan-feature"><?php _e('Logo & Header text','weblizar'); ?></li>
<li class="plan-feature"><?php _e('Portfolio Template','weblizar'); ?></li>
<li class="plan-feature"><?php _e('Photobox and Lightbox enable Tamplates','weblizar'); ?> </li>
<li class="plan-feature"><?php _e('Special Gallery Template','weblizar'); ?></li>
</ul>
</div>
</div>
<div class="col-md-4">
<div class=" plan bp">
<div class="plan-name">
<h2><?php _e('Free','weblizar'); ?></h2>
</div>
<ul>
<li class="plan-feature"><i class="fa fa-times fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-times fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-times fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-times fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-times fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-times fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-times fa-1x"></i></li>
<li class="plan-feature">1</li>
<li class="plan-feature"><?php _e('WPORG Support','weblizar'); ?></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-times fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-times fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-times fa-1x"></i></li>
<li class="plan-feature">
<a href="#" class="button button-primary button-hero" style="font-size: large; font-weight: bolder;"><i class="fa fa-thumbs-up"></i> <?php _e('Enjoy Theme','weblizar'); ?></a>
</li>
</ul>
</div>
</div>
<div class="col-md-4">
<div class=" plan cp">
<div class="plan-name">
<h2><?php _e('Pro','weblizar'); ?> - ( $29 )</h2>
</div>
<ul>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature">15+</li>
<li class="plan-feature">15+</li>
<li class="plan-feature"><?php _e('Private Support Forum','weblizar'); ?></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature"><i class="fa fa-check fa-1x"></i></li>
<li class="plan-feature">
<a class="btn btn-primary btn-lg" href="http://www.weblizar.com/themes/weblizar-premium-theme/" target="_new" style="font-size: large; font-weight: bolder;"><i class="fa fa-check-circle"></i> <?php _e('Demo','weblizar'); ?></a>
<a class="btn btn-danger btn-lg" href="http://www.weblizar.com/themes/weblizar-premium-theme/" target="_new" style="font-size: large; font-weight: bolder;"><i class="fa fa-shopping-cart"></i><?php _e(' Buy','weblizar'); ?></a>
</li>
</ul>
</div>
</div>
</div>
<style>
.pricing-table .plan ul li.plan-feature {
padding: 8px !important;
}
.ap .plan-name {
background-color: #1E8CBE !important;
}
.bp .plan-name {
background-color: #1E8CBE !important;
}
.cp .plan-name {
background-color: #1E8CBE !important;
}
li {
font-size: larger !important;
}
.row-fluid .span4 {
width: 30.624% !important;
}
ul li img {
}
</style>
</div>
<div class="block ui-tabs-panel deactive" id="option-ourproduct" >
<div class="row-fluid pricing-table pricing-three-column">
<div class="plan-name centre">
<a style="margin-bottom:10px;textt-align:center" target="_new" href="http://weblizar.com"><img src="http://weblizar.com/wp-content/themes/home-theme/images/weblizar2.png" /></a>
<div class="purchase_btn_div">
<a href="http://www.weblizar.com" target="_new" class="btn btn-primary btn-lg dmobtn">View Site</a>
</div>
</div>
<div class="plan-name">
<h2>Weblizar's Responsive Wordpress Theme</h2>
<h6>Get The Premium, And Create your website Beautifully. </h6>
</div>
<div class="col-md-4 demoftr ">
<h2>Enigma-Pro</h2>
<div class="img-wrapper">
<div class="enigma_home_portfolio_showcase">
<img class="enigma_img_responsive ftr_img" src="<?php echo WL_TEMPLATE_DIR_URI.'/core/theme-options/images/enigma.png' ;?>">
<div class="enigma_home_portfolio_showcase_overlay">
<div class="enigma_home_portfolio_showcase_overlay_inner ">
<div class="enigma_home_portfolio_showcase_icons">
<a title="Link" data-toggle="modal" data-target="#myModal" href="View Detail#">View Detail</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal " id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content ">
<div class="modal-header ">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel"> <a class="pro-dir-button" data-toggle="modal" data-target="#myModalGreen" data-dismiss="modal" href="View Detail#" class="pro-dir-button"><i style="color:#000;line-height:1.5" class="fa fa-angle-right fa-2x"></i></a>
</h4>
</div>
<div class="modal-body">
<div class="col-md-6">
<img class="enigma_img_responsive ftr_img" src="<?php echo WL_TEMPLATE_DIR_URI.'/core/theme-options/images/enigma.png' ;?>">
</div>
<div class="col-md-6">
<div class="theme-info">
<h3 class="theme-name">Enigma Pro Theme</h3>
<h4 class="theme-author">By <a href="http://weblizar.com/" title="Visit author homepage">weblizar</a></h4>
<p class="theme-description">Enigma is HTML5 & CSS3 Responsive WordPress Business theme with business style , 7 blog templates , 6 portfolio templates and many more</p>
<h4 style="margin-top:20px;">Features</h4>
<div class="col-md-6">
<div class="enigma_sidebar_link">
<p>
<i class="fa fa-angle-right"></i>Responsive Design
</p>
<p>
<i class="fa fa-angle-right"></i>Retina Ready
</p>
<p>
<i class="fa fa-angle-right"></i>Html5 & Css3
</p>
<p>
<i class="fa fa-angle-right"></i>Multi-purpose Theme
</p>
<p>
<i class="fa fa-angle-right"></i>Unlimited Color Schemes
</p>
<p>
<i class="fa fa-angle-right"></i>Multiple Templates
</p>
</div>
</div>
<div class="col-md-6">
<div class="enigma_sidebar_link">
<p>
<i class="fa fa-angle-right"></i>All Browser Support
</p>
<p>
<i class="fa fa-angle-right"></i>Powerful Option Panel
</p>
<p>
<i class="fa fa-angle-right"></i>Coming Soon Mode
</p>
<p>
<i class="fa fa-angle-right"></i>Custom Shortcode
</p>
<p>
<i class="fa fa-angle-right"></i>Isotope Effects and lightbox
</p>
<p>
<i class="fa fa-angle-right"></i>Fast & Friendly Support
</p>
</div>
</div>
<div class="col-md-12" style="margin-top:20px;">
<a class="btn btn-success btn-lg" target="_new" href="http://weblizar.com/themes/enigma-premium/">View Demo</a>
<a class="btn btn-danger btn-lg" target="_new" href="http://weblizar.com/themes/enigma-premium/">Purchase Now</a>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="col-md-4 demoftr ">
<h2>Green Lantern Pro</h2>
<div class="img-wrapper">
<div class="enigma_home_portfolio_showcase">
<img class="enigma_img_responsive ftr_img" src="http://weblizar.com/wp-content/themes/home-theme/images/green-lantern-premium-images/glp-slide-1.jpg">
<div class="enigma_home_portfolio_showcase_overlay">
<div class="enigma_home_portfolio_showcase_overlay_inner ">
<div class="enigma_home_portfolio_showcase_icons">
<a title="Link" data-toggle="modal" data-target="#myModalGreen" href="View Detail#">View Detail</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal" id="myModalGreen" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content ">
<div class="modal-header ">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel"><a data-toggle="modal" data-target="#myModal" data-dismiss="modal" href="View Detail#" class="pro-dir-button"><i style="color:#000;line-height:1.5" class="fa fa-angle-left fa-2x"></i></a> <a data-toggle="modal" data-target="#myModalweblizar" data-dismiss="modal" href="View Detail#" class="pro-dir-button"><i style="color:#000;line-height:1.5" class="fa fa-angle-right fa-2x"></i></a>
</h4>
</div>
<div class="modal-body">
<div class="col-md-6">
<img class="enigma_img_responsive ftr_img" src="http://weblizar.com/wp-content/themes/home-theme/images/green-lantern-premium-images/glp-slide-1.jpg">
</div>
<div class="col-md-6">
<div class="theme-info">
<h3 class="theme-name">Green Lantern Pro Theme</h3>
<h4 class="theme-author">By <a href="http://weblizar.com/" title="Visit author homepage">weblizar</a></h4>
<p class="theme-description">Green Lantern is a Full Responsive Multi-Purpose Theme suitable for Business , corporate office amd others .Cool Blog Layout and full width page also present</p>
<h4 style="margin-top:20px;">Features</h4>
<div class="col-md-6">
<div class="enigma_sidebar_link">
<p>
<i class="fa fa-angle-right"></i>Responsive Design
</p>
<p>
<i class="fa fa-angle-right"></i>Retina Ready
</p>
<p>
<i class="fa fa-angle-right"></i>Html5 & Css3
</p>
<p>
<i class="fa fa-angle-right"></i>Multi-purpose Theme
</p>
<p>
<i class="fa fa-angle-right"></i>Unlimited Color Schemes
</p>
<p>
<i class="fa fa-angle-right"></i>Multiple Templates
</p>
</div>
</div>
<div class="col-md-6">
<div class="enigma_sidebar_link">
<p>
<i class="fa fa-angle-right"></i>All Browser Support
</p>
<p>
<i class="fa fa-angle-right"></i>Powerful Option Panel
</p>
<p>
<i class="fa fa-angle-right"></i>Coming Soon Mode
</p>
<p>
<i class="fa fa-angle-right"></i>Custom Shortcode
</p>
<p>
<i class="fa fa-angle-right"></i>Isotope Effects and lightbox
</p>
<p>
<i class="fa fa-angle-right"></i>Fast & Friendly Support
</p>
</div>
</div>
<p></p>
<div class="col-md-12" style="margin-top:20px;">
<a class="btn btn-success btn-lg" target="_new" href="http://weblizar.com/themes/green-lantern-premium-theme/">View Demo</a>
<a class="btn btn-danger btn-lg" target="_new" href="http://weblizar.com/themes/green-lantern-premium-theme/">Purchase Now</a>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="col-md-4 demoftr ">
<h2>Weblizar Pro</h2>
<div class="img-wrapper">
<div class="enigma_home_portfolio_showcase">
<img class="enigma_img_responsive ftr_img" src="http://weblizar.com/wp-content/uploads/2014/06/screenshot1.jpg">
<div class="enigma_home_portfolio_showcase_overlay">
<div class="enigma_home_portfolio_showcase_overlay_inner ">
<div class="enigma_home_portfolio_showcase_icons">
<a title="Link" data-toggle="modal" data-target="#myModalweblizar" href="View Detail#">View Detail</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal" id="myModalweblizar" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content ">
<div class="modal-header ">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel"><a data-toggle="modal" data-target="#myModalGreen" data-dismiss="modal" href="View Detail#" class="pro-dir-button"><i style="color:#000;line-height:1.5" class="fa fa-angle-left fa-2x"></i></a> <a data-toggle="modal" data-target="#myModallightbox" data-dismiss="modal" href="View Detail#" class="pro-dir-button"><i style="color:#000;line-height:1.5" class="fa fa-angle-right fa-2x"></i></a>
</h4>
</div>
<div class="modal-body">
<div class="col-md-6">
<img class="enigma_img_responsive ftr_img" src="http://weblizar.com/wp-content/uploads/2014/06/screenshot1.jpg">
</div>
<div class="col-md-6">
<div class="theme-info">
<h3 class="theme-name">Weblizar Pro Theme</h3>
<h4 class="theme-author">By <a href="http://weblizar.com/" title="Visit author homepage">weblizar</a></h4>
<p class="theme-description">Responsive Multi-Purpose Theme suitable for Business , corporate office and others .Cool Blog Layout and full width page.You can also use it for portfolio, blogging or any type of site. Built with Twitter bootstrap</p>
<h4 style="margin-top:20px;">Features</h4>
<div class="col-md-6">
<div class="enigma_sidebar_link">
<p>
<i class="fa fa-angle-right"></i>Responsive Design
</p>
<p>
<i class="fa fa-angle-right"></i>Retina Ready
</p>
<p>
<i class="fa fa-angle-right"></i>Html5 & Css3
</p>
<p>
<i class="fa fa-angle-right"></i>Multi-purpose Theme
</p>
<p>
<i class="fa fa-angle-right"></i>Unlimited Color Schemes
</p>
<p>
<i class="fa fa-angle-right"></i>Multiple Templates
</p>
</div>
</div>
<div class="col-md-6">
<div class="enigma_sidebar_link">
<p>
<i class="fa fa-angle-right"></i>All Browser Support
</p>
<p>
<i class="fa fa-angle-right"></i>Powerful Option Panel
</p>
<p>
<i class="fa fa-angle-right"></i>Coming Soon Mode
</p>
<p>
<i class="fa fa-angle-right"></i>Custom Shortcode
</p>
<p>
<i class="fa fa-angle-right"></i>Isotope Effects and lightbox
</p>
<p>
<i class="fa fa-angle-right"></i>Fast & Friendly Support
</p>
</div>
</div>
<p></p>
<div class="col-md-12" style="margin-top:20px;">
<a class="btn btn-success btn-lg" target="_new" href="http://weblizar.com/themes/weblizar-premium-theme/">View Demo</a>
<a class="btn btn-danger btn-lg" target="_new" href="http://weblizar.com/themes/weblizar-premium-theme/">Purchase Now</a>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<div class="row-fluid pricing-table pricing-three-column">
<div class="plan-name">
<h2>Weblizar's Responsive Wordpress Plugins</h2>
<h6>Get the Plugin and create beautiful Galleries and Slideshow.</h6>
</div>
<div class="col-md-6 demoftr">
<h2>Lightbox Slider Pro</h2>
<div class="img-wrapper">
<div class="enigma_home_portfolio_showcase">
<img class="enigma_img_responsive ftr_img" src="http://weblizar.com/wp-content/themes/home-theme/images/lightbox/fancy.jpg">
<div class="enigma_home_portfolio_showcase_overlay">
<div class="enigma_home_portfolio_showcase_overlay_inner ">
<div class="enigma_home_portfolio_showcase_icons">
<a title="Link" data-toggle="modal" data-target="#myModallightbox" href="View Detail#">View Detail</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal " id="myModallightbox" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content ">
<div class="modal-header ">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel"> <a class="pro-dir-button" data-toggle="modal" data-target="#myModalweblizar" data-dismiss="modal" href="View Detail#" class="pro-dir-button"><i style="color:#000;line-height:1.5" class="fa fa-angle-left fa-2x"></i></a> <a class="pro-dir-button" data-toggle="modal" data-target="#myModalresponsive" data-dismiss="modal" href="View Detail#" class="pro-dir-button"><i style="color:#000;line-height:1.5" class="fa fa-angle-right fa-2x"></i></a>
</h4>
</div>
<div class="modal-body">
<div class="col-md-6">
<img class="enigma_img_responsive ftr_img" src="http://weblizar.com/wp-content/themes/home-theme/images/lightbox/fancy.jpg">
</div>
<div class="col-md-6">
<div class="theme-info">
<h3 class="theme-name">LightBox Slider Pro</h3>
<h4 class="theme-author">By <a href="http://weblizar.com/" title="Visit author homepage">weblizar</a></h4>
<p class="theme-description">Lightbox Slider is premium wordpress plugin to create gallery with lightbox slide</p>
<h4 style="margin-top:20px;">Features</h4>
<div class="col-md-6">
<div class="enigma_sidebar_link">
<p>
<i class="fa fa-angle-right"></i>Responsive Design
</p>
<p>
<i class="fa fa-angle-right"></i>Ultimate Lightbox
</p>
<p>
<i class="fa fa-angle-right"></i>5 Gallery Layout
</p>
<p>
<i class="fa fa-angle-right"></i>500+ Fonts Styles
</p>
<p>
<i class="fa fa-angle-right"></i>10 Color Opacity
</p>
<p>
<i class="fa fa-angle-right"></i>8 Lightbox
</p>
</div>
</div>
<div class="col-md-6">
<div class="enigma_sidebar_link">
<p>
<i class="fa fa-angle-right"></i>Gallery Shortcode
</p>
<p>
<i class="fa fa-angle-right"></i>Unlimited Color Schemes
</p>
<p>
<i class="fa fa-angle-right"></i>Retina Ready
</p>
<p>
<i class="fa fa-angle-right"></i>Isotope Effects
</p>
<p>
<i class="fa fa-angle-right"></i>All Browser Support
</p>
<p>
<i class="fa fa-angle-right"></i>Fast & Friendly Support
</p>
</div>
</div>
<div class="col-md-12" style="margin-top:20px;">
<a class="btn btn-success btn-lg" target="_new" href="http://weblizar.com/lightbox-slider-pro/">View Demo</a>
<a class="btn btn-danger btn-lg" target="_new" href="http://weblizar.com/lightbox-slider-pro/">Purchase Now</a>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="col-md-6 demoftr">
<h2>Reponsive Photo Gallery</h2>
<div class="img-wrapper">
<div class="enigma_home_portfolio_showcase">
<img class="enigma_img_responsive ftr_img" src="http://weblizar.com/wp-content/themes/home-theme/images/gallery-pro.png">
<div class="enigma_home_portfolio_showcase_overlay">
<div class="enigma_home_portfolio_showcase_overlay_inner ">
<div class="enigma_home_portfolio_showcase_icons">
<a title="Link" data-toggle="modal" data-target="#myModalresponsive" href="View Detail#">View Detail</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal " id="myModalresponsive" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content ">
<div class="modal-header ">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel"> <a class="pro-dir-button" data-toggle="modal" data-target="#myModallightbox" data-dismiss="modal" href="View Detail#" class="pro-dir-button"><i style="color:#000;line-height:1.5" class="fa fa-angle-left fa-2x"></i></a>
</h4>
</div>
<div class="modal-body">
<div class="col-md-6">
<img class="enigma_img_responsive ftr_img" src="http://weblizar.com/wp-content/themes/home-theme/images/gallery-pro.png">
</div>
<div class="col-md-6">
<div class="theme-info">
<h3 class="theme-name">Responsive Photo Gallery</h3>
<h4 class="theme-author">By <a href="http://weblizar.com/" title="Visit author homepage">weblizar</a></h4>
<p class="theme-description">A Highly Animated Image Gallery Plugin For WordPress</p>
<h4 style="margin-top:20px;">Features</h4>
<div class="col-md-6">
<div class="enigma_sidebar_link">
<p>
<i class="fa fa-angle-right"></i>Responsive Design
</p>
<p>
<i class="fa fa-angle-right"></i>8 Animation Effect
</p>
<p>
<i class="fa fa-angle-right"></i>5 Gallery Layout
</p>
<p>
<i class="fa fa-angle-right"></i>500+ Fonts Styles
</p>
<p>
<i class="fa fa-angle-right"></i>10 Color Opacity
</p>
<p>
<i class="fa fa-angle-right"></i>2 Lightbox
</p>
</div>
</div>
<div class="col-md-6">
<div class="enigma_sidebar_link">
<p>
<i class="fa fa-angle-right"></i>Gallery Shortcode
</p>
<p>
<i class="fa fa-angle-right"></i>Unlimited Color Schemes
</p>
<p>
<i class="fa fa-angle-right"></i>Retina Ready
</p>
<p>
<i class="fa fa-angle-right"></i>Isotope Effects
</p>
<p>
<i class="fa fa-angle-right"></i>All Browser Support
</p>
<p>
<i class="fa fa-angle-right"></i>Fast & Friendly Support
</p>
</div>
</div>
<div class="col-md-12" style="margin-top:20px;">
<a class="btn btn-success btn-lg" target="_new" href="http://weblizar.com/plugins/responsive-photo-gallery-pro/">View Demo</a>
<a class="btn btn-danger btn-lg" target="_new" href="http://weblizar.com/plugins/responsive-photo-gallery-pro/">Purchase Now</a>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<div class="plan-name centre">
<div class="purchase_btn_div">
<a href="http://www.weblizar.com" target="_new" class="btn btn-primary btn-lg dmobtn">View Site</a>
</div>
</div>
</div> | eq0rip/Hamroreview.com | wp-content/themes/weblizar/core/theme-options/option-settings.php | PHP | gpl-2.0 | 68,175 |
/* global Package, Npm */
Package.describe({
name: 'procempa:keycloak-auth',
version: '1.0.0',
summary: 'Meteor Keycloak Handshake flow',
git: 'https://github.com/Procempa/meteor-keycloak-auth.git',
documentation: 'README.md'
});
Package.onUse(function(api) {
api.use('ecmascript@0.1.4');
api.use('service-configuration@1.0.1');
api.export('KeycloakServer', 'server');
api.export('KeycloakClient', 'client');
api.mainModule('client-main.js', 'client');
api.mainModule('server-main.js', 'server');
});
Npm.depends({
'lodash': '4.16.1',
'fallbackjs': '1.1.8',
'localforage': '1.4.2',
'keycloak-auth-utils': '2.2.1',
'babel-plugin-transform-decorators-legacy': '1.3.4',
'babel-plugin-transform-class-properties': '6.11.5',
'babel-plugin-transform-strict-mode': '6.11.3',
'q': '1.4.1'
});
| Procempa/meteor-keycloak-auth | package.js | JavaScript | gpl-2.0 | 808 |
/**
* XTemplate 所有的扩展函数集合,用于处理html中常见的格式转换,默认值等处理。
* 如果需要自行扩展,请使用window.Render的addFunc函数
*
* @class Render.funcs
*/
(function (r, undefined) {
'use strict';
/**
* 指定输出的默认值,如果有值就原样输出,如果空或是null,就输出默认值。
*
* 示例:
*
* {name|default,'小明'}
*
* @method default
* @param val {string} 变量名
* @param defaultVal 默认值
* @returns {object}
*/
r.addFunc('default', function (val, defaultVal) {
if (val === undefined || typeof(val) == 'undefined' || val === '' || val === 'null') {
return defaultVal;
}
return val;
});
/**
* 判断变量是否为空。
*
* 示例:
*
* {name|empty,'空','不空'}
*
* @method default
* @param val {string} 变量名
* @param emptyValue 为空时显示值
* @param notEmptyValue 不为空时显示的值
* @returns {object}
*/
r.addFunc('empty', function (val, emptyValue, notEmptyValue) {
if (val === undefined || typeof(val) == 'undefined' || val === '' || val === 'null') {
return emptyValue;
} else {
return notEmptyValue;
}
});
/**
* 根据设定值返回指定内容
*
* 示例:
*
* {status|case,-1,'审核不通过',1,'审核通过','待审核'}
* {status|case,-1,'审核不通过',1,'审核通过',2,'VIP','待审核'}
*
* 参数说明:参数成对出现,第一个是设定值,第二是要返回的值;后续可以增加多个成队的参数;最后一个参数为默认值,所有设定值都不满足时输出
* @method case
* @param val {string} 变量名
* @returns {object}
*/
r.addFunc('case', function (val) {
for (var i = 1; i < arguments.length; i += 2) {
if (val == arguments[i] && i < arguments.length - 1) {
return arguments[i + 1];
}
}
return arguments[arguments.length - 1];
});
/**
* 格式化货币,最少小数显示,
* 示例:
*
* {price|format_money}
* 如果price为10.0100,显示10.01
* 如果price为10.000,显示10
*
* @method format_money
* @param val {string} 变量名
* @returns {number}
*/
r.addFunc('format_money', function (val) {
return parseFloat(val);
});
/**
* 将 Date 转化为指定格式的String
* 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
* 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
* 示例:
*
* {date|format_date,"yyyy-MM-dd hh:mm:ss.S"} 输出 2006-07-02 08:09:04.423
* {date|format_date,"yyyy-M-d h:m:s.S"} 输出 2006-7-2 8:9:4.18
* {date|format_date,"yyyy-M-d h:m:s"} 输出 2006-7-2 8:9:4
*
* @method format_date
* @param val {string} 变量名
* @param fmt {string} 格式串
* @returns {string} 格式化后的日期串
*/
r.addFunc('format_date', function (val, fmt) {
if (typeof(val) != 'object') {
val = new Date(parseInt(val));
}
if (!fmt) {
fmt = 'yyyy-MM-dd hh:mm:ss';
}
var format_data_o = {
"M+": val.getMonth() + 1, //月份
"d+": val.getDate(), //日
"h+": val.getHours(), //小时
"m+": val.getMinutes(), //分
"s+": val.getSeconds(), //秒
"q+": Math.floor((val.getMonth() + 3) / 3), //季度
"S": val.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (val.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in format_data_o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (format_data_o[k]) : (("00" + format_data_o[k]).substr(("" + format_data_o[k]).length)));
return fmt;
});
/**
* 数字保留小数位数
* 示例:
*
* {float_num|fixed,2}
*
* @method fixed
* @param val {string} 要格式的变量名
* @param c {number} 保留的小数位置,默认为0
* @returns {number}
*/
r.addFunc('fixed', function (val, c) {
if (typeof c == 'undefined') {
c = 0;
}
if (typeof(val) == 'number') {
return val.toFixed(c);
} else {
return val;
}
});
/**
* 没有正确的函数处理时,用此函数处理,直接输出变量值
* 外部不要使用
* @param val {string} 变量名
* @returns {string}
*/
r.addFunc('noFunc', function (val) {
return '没有找到正确的处理函数';
});
/**
* 重复输出num次val
*
* 示例:
*
* {num|repeat,'*'},当num=4时,输出****
*
* @method repeat
* @param val {string} 重复次数
* @param res {string}要重复的内容
* @returns {string}
*/
r.addFunc('repeat', function (val, res) {
var result = '';
for (var i = 0; i < val; i++) {
result += res;
}
return result;
});
/**
* 内部实现简单的循环,注意,内部模板和普通模板有区别,需要使用小括号代替大扩号。
* 常用于嵌套循环显示。
*
* 示例:
*
* {array|range,'(id),'},如果array=[{id:0},{id:1}],会输出0,1,
*
* @method range
* @param list {string} 要循环的数组变量名
* @param tmpl {string} 模板
* @returns {string} 输出的html
*/
r.addFunc('range', function (list, tmpl) {
var html = '';
if (tmpl) {
tmpl = tmpl.replace(/\(/g, '{').replace(/\)/g, '}');
var func = r.syntax.buildFunc('range', tmpl);
if (func) {
for (var i = 0; i < list.length; i++) {
html += func(r, list[i]);
}
}
}
return html;
});
/**
* 过滤html字符,因为系统默认已过滤html,所以此函数一般外部不使用
*
* 示例:
*
* {code|filter_html}
*
* @method filter_html
* @param html {string} 待过滤的html代码
* @returns {string}
*/
r.addFunc('filter_html', function (html) {
return r.util.html(html);
});
/**
* 从左侧按指定长度截断字串,注意一个汉字按2个字符计算,这样可以准确的控制格式
*
* 示例:
*
* {str|left,20,'...'}
* {str|left,20}
*
* @method left
* @param str {string} 要截断的字串变量名
* @param len {number} 截断后的字串长度,一个汉字按2个字符计算
* @param dot {string} [可选] 截断后补充的串,示例:"..."
* @returns {string}
*/
r.addFunc('left', function (str, len, dot) {
var newLength = 0;
var newStr = "";
var chineseRegex = /[^\x00-\xff]/g;
var singleChar = "";
var dotLen = 0;
if (dot) {
dotLen = dot.length;
}
var strLength = str.replace(chineseRegex, "**").length;
for (var i = 0; i < strLength; i++) {
singleChar = str.charAt(i).toString();
if (singleChar.match(chineseRegex) !== null) {
newLength += 2;
} else {
newLength++;
}
if (newLength + dotLen > len) {
if (dotLen > 0) {
newStr += dot;
}
break;
}
newStr += singleChar;
}
return newStr;
});
})(window.Render); | seefan/xtemplate | src/funcs.js | JavaScript | gpl-2.0 | 8,148 |
import org.checkerframework.checker.nullness.qual.*;
import org.checkerframework.dataflow.qual.Pure;
class Node {
int id;
@Nullable Node next;
Node(int id, @Nullable Node next) {
this.id = id;
this.next = next;
}
}
class SubEnumerate {
protected @Nullable Node current;
public SubEnumerate(Node node) {
this.current = node;
}
@EnsuresNonNullIf(expression = "current", result = true)
public boolean hasMoreElements() {
return (current != null);
}
}
class Enumerate extends SubEnumerate {
public Enumerate(Node node) {
super(node);
}
public boolean hasMoreElements() {
return (current != null);
}
}
class Main {
public static final void main(String args[]) {
Node n2 = new Node(2, null);
Node n1 = new Node(1, n2);
Enumerate e = new Enumerate(n1);
while (e.hasMoreElements()) {}
}
}
| Jianchu/checker-framework | checker/tests/nullness/EnsuresNonNullIfInheritedTest.java | Java | gpl-2.0 | 934 |
<?php
/**
* File containing the eZURLAlias class.
*
* @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version 2012.2
* @package kernel
*/
/*!
\class eZURLAliasML ezurlaliasml.php
\brief Handles URL aliases in eZ Publish
URL aliases are different names for existing URLs in eZ Publish.
Using URL aliases allows for having better looking urls on the webpage
as well as having fixed URLs pointing to various locations.
This class handles storing, fetching, moving and subtree updates on
eZ Publish URL aliases, this performed using methods from eZPersistentObject.
The table used to store path information is designed to keep each element in
the path (separated by /) in one row, ie. not the entire path.
Each row uses the *parent* field to say which element is the parent of the current one,
a value of 0 means a top-level path element.
The system also supports path elemens in multiple languages, each language
is stored in separate rows but with the same path element ID, the exception is
when the text of multiple languages are the same then they will simply share the
same row.
Instead of manipulating path elements directly it is recommended to use one
the higher level methods for fetching or storing a path.
For objects the methods getChildren() and getPath() can be used to fetch the child elements and path string.
Typically you will not have a path element object and should use on of these static functions:
- storePath() - Stores a given path with specified action, all parent are created if they don't exist.
- fetchByPath() - Fetch path elements by path string, some wildcard support is also available.
- translate() - Translate requested path string into the internal path.
For more detailed path element handling these static methods are available:
- fetchByAction() - Fetch a path element based on the action.
- fetchByParentID() - Fetch path elements based on parent ID.
- fetchPathByActionList() - Fetch path string based on action values, this is more optimized than getPath().
- setLangMaskAlwaysAvailable() - Updates language mask for path elements based on actions.
Most of these methods have some common arguments, they can be:
- $maskLanguages - If true then only elements which matches the currently prioritized languaes is processed.
- $onlyPrioritized - If true then only the top prioritized language of the elements is considered. Requires $maskLanguages to be set to true.
- $includeRedirections - If true then elements which redirects to this is also processed.
*/
class eZURLAliasML extends eZPersistentObject
{
// Return values from storePath()
const LINK_ID_NOT_FOUND = 1;
const LINK_ID_WRONG_ACTION = 2;
const LINK_ALREADY_TAKEN = 3;
const ACTION_INVALID = 51;
const DB_ERROR = 101;
/*!
Optionally computed path string for this element, used for caching purposes.
*/
public $Path;
private static $charset = null;
/*!
Initializes a new URL alias from database row.
\note If 'path' is set it will be cached in $Path.
*/
function eZURLAliasML( $row )
{
$this->eZPersistentObject( $row );
$this->Path = null;
if ( isset( $row['path'] ) )
{
$this->Path = $row['path'];
}
}
static public function definition()
{
static $definition = array( "fields" => array( "id" => array( 'name' => 'ID',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
"parent" => array( 'name' => 'Parent',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
"lang_mask" => array( 'name' => 'LangMask',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
"text" => array( 'name' => 'Text',
'datatype' => 'string',
'default' => '',
'required' => true ),
"text_md5" => array( 'name' => 'TextMD5',
'datatype' => 'string',
'default' => '',
'required' => true ),
"action" => array( 'name' => 'Action',
'datatype' => 'string',
'default' => '',
'required' => true ),
"action_type" => array( 'name' => 'ActionType',
'datatype' => 'string',
'default' => '',
'required' => true ),
"link" => array( 'name' => 'Link',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
"is_alias" => array( 'name' => 'IsAlias',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
"is_original" => array( 'name' => 'IsOriginal',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
"alias_redirects" => array( 'name' => 'AliasRedirects',
'datatype' => 'integer',
'default' => 1,
'required' => true ) ),
"keys" => array( "parent", "text_md5" ),
"function_attributes" => array( "children" => "getChildren",
"path" => "getPath" ),
"class_name" => "eZURLAliasML",
"name" => "ezurlalias_ml" );
return $definition;
}
/*!
Unicode-aware strtolower, performs the conversion by using eZCharTransform
*/
static function strtolower( $text )
{
//We need to detect our internal charset
if ( self::$charset === null )
{
self::$charset = eZTextCodec::internalCharset();
}
//First try to use mbstring
if ( extension_loaded( 'mbstring' ) )
{
return mb_strtolower( $text, self::$charset );
}
else
{
// Fall back if mbstring is not available
$char = eZCharTransform::instance();
return $char->transformByGroup( $text, 'lowercase' );
}
}
/*!
Converts the action property into a real url which responds to the
module/view on the site.
*/
function actionURL()
{
return eZURLAliasML::actionToUrl( $this->Action );
}
/*!
Creates a new path element with given arguments, MD5 sum is automatically created.
\param $element The text string for the path element.
\param $action Action string.
\param $parentID ID of parent path element.
\param $language ID or mask of languages
\param $languageName Name of language(s), comma separated
*/
static function create( $element, $action, $parentID, $language )
{
$row = array( 'text' => $element,
'text_md5' => md5( eZURLAliasML::strtolower( $element ) ),
'parent' => $parentID,
'lang_mask' => $language,
'action' => $action );
return new eZURLAliasML( $row );
}
/*!
Overrides the default behaviour to automatically update TextMD5.
*/
function setAttribute( $name, $value )
{
eZPersistentObject::setAttribute( $name, $value );
if ( $name == 'text' )
{
$this->TextMD5 = md5( eZURLAliasML::strtolower( $value ) );
}
else if ( $name == 'action' )
{
$this->ActionType = null;
}
}
/*!
Generates the md5 for the alias and stores the values.
\note Transaction unsafe. If you call several transaction unsafe methods you must enclose
the calls within a db transaction; thus within db->begin and db->commit.
*/
function store( $fieldFilters = null )
{
if ( $this->ID === null )
{
$this->ID = self::getNewID();
}
if ( $this->Link === null )
{
$this->Link = $this->ID;
}
if ( $this->TextMD5 === null )
{
$this->TextMD5 = md5( eZURLAliasML::strtolower( $this->Text ) );
}
$this->IsOriginal = ($this->ID == $this->Link) ? 1 : 0;
if ( $this->IsAlias )
$this->IsOriginal = true;
if ( $this->Action == "nop:" ) // nop entries can always be replaced
$this->IsOriginal = false;
if ( strlen( $this->ActionType ) == 0 )
{
if ( preg_match( "#^(.+):#", $this->Action, $matches ) )
$this->ActionType = $matches[1];
else
$this->ActionType = 'nop';
}
eZPersistentObject::store( $fieldFilters );
}
/*!
\static
Removes all path elements which matches the action name $actionName and value $actionValue.
*/
static public function removeByAction( $actionName, $actionValue )
{
// If this is an original element we must get rid of all elements which points to it.
$db = eZDB::instance();
$actionStr = $db->escapeString( $actionName . ':' . $actionValue );
$query = "DELETE FROM ezurlalias_ml WHERE action = '{$actionStr}'";
$db->query( $query );
}
/*!
\static
Removes a URL-Alias which has parent $parentID, MD5 text $textMD5 and language $language.
If the entry has only the specified language and there are existing children the entry will be disabled instead of removed.
If the entry has other languages other than the one which was specified the language bit is removed.
\param $parentID ID of the parent element
\param $textMD5 MD5 of the lowercase version of the text, see eZURLAliasML::strtolower().
\param $language The language entry to remove, can be a string with the locale or a language object (eZContentLanguage).
*/
public static function removeSingleEntry( $parentID, $textMD5, $language )
{
$parentID = (int)$parentID;
if ( !is_object( $language ) )
$language = eZContentLanguage::fetchByLocale( $language );
$languageID = (int)$language->attribute( 'id' );
$db = eZDB::instance();
$bitDel = $db->bitAnd( 'lang_mask' , (~$languageID) );
$bitMatch = $db->bitAnd( 'lang_mask', $languageID ) . ' > 0';
$bitMask = $db->bitAnd( 'lang_mask', ~1 );
// Fetch data for the given entry
$rows = $db->arrayQuery( "SELECT * FROM ezurlalias_ml WHERE parent = {$parentID} AND text_md5 = '" . $db->escapeString( $textMD5 ) . "' AND $bitMatch" );
if ( count( $rows ) == 0 )
return false;
$id = (int)$rows[0]['id'];
$mask = (int)$rows[0]['lang_mask'];
if ( ($mask & ~($languageID | 1)) == 0 )
{
// No more languages for this entry so we need to check for children
$childRows = $db->arrayQuery( "SELECT * FROM ezurlalias_ml WHERE parent = {$id}" );
if ( count( $childRows ) > 0 )
{
// Turn entry into a nop: to disable it
$element = new eZURLAliasML( $rows[0] );
$element->LangMask = 1;
$element->Action = "nop:";
$element->ActionType = "nop";
$element->IsAlias = 0;
$element->store();
return;
}
}
// Remove language bit from selected entries and remove entries which have no languages.
$db->query( "UPDATE ezurlalias_ml SET lang_mask = $bitDel WHERE parent = {$parentID} AND text_md5 = '" . $db->escapeString( $textMD5 ) . "' AND $bitMatch" );
$db->query( "DELETE FROM ezurlalias_ml WHERE parent = {$parentID} AND text_md5 = '" . $db->escapeString( $textMD5 ) . "' AND $bitMask = 0" );
}
/*!
Finds all the children of the current element.
For more control over the list use fetchByParentID().
*/
function getChildren()
{
return eZURLAliasML::fetchByParentID( $this->ID, true, true, false );
}
/*!
Calculates the full path for the current item and returns it.
\param $locale The locale for which a path should be calculated.
\param $incomingLanguageList Array of locale codes representing the prioritized site language list.
\note If you know the action values of the path use fetchPathByActionList() instead, it is more optimized.
\note The calculated path is cached in $Path.
*/
function getPath( $locale = null, $incomingLanguageList = null )
{
if ( $this->Path !== null )
return $this->Path;
// Fetch path 'text' elements of correct parent path
$path = array( $this->Text );
$id = (int)$this->Parent;
$db = eZDB::instance();
while ( $id != 0 )
{
$query = "SELECT parent, lang_mask, text FROM ezurlalias_ml WHERE id={$id}";
if ( $locale !== null && is_string( $locale ) )
{
// We also want to consider the prioritized language list for the
// destination siteaccess, so that untranslated objects, are not
// disregarded from the URL.
if ( $incomingLanguageList !== null )
{
eZContentLanguage::setPrioritizedLanguages( $incomingLanguageList );
}
$langMask = trim( eZContentLanguage::languagesSQLFilter( 'ezurlalias_ml', 'lang_mask' ) );
$query .= " AND ({$langMask})";
}
$rows = $db->arrayQuery( $query );
if ( count( $rows ) == 0 )
{
break;
}
$result = eZURLAliasML::choosePrioritizedRow( $rows );
if ( $incomingLanguageList !== null )
{
eZContentLanguage::clearPrioritizedLanguages();
}
if ( !$result )
{
$result = $rows[0];
}
$id = (int)$result['parent'];
array_unshift( $path, $result['text'] );
}
$this->Path = implode( '/', $path );
return $this->Path;
}
/*!
\static
Stores the full path $path to point to action $action, any missing parents are created as placeholders (ie. nop:).
Returns an array containing the entry 'status' which is the status code, is \c true if all went well, a number otherwise (see class constants).
Will contain 'path' for succesful creation or if the path already exists.
\param $path String containing full path, leading and trailing slashes are stripped.
\param $action Action string for entry.
\param $languageName The language to use for entry, can be a string (locale code, e.g. 'nor-NO') an eZContentLanguage object or false for the top prioritized language.
\param $linkID Numeric ID for link field, if it is set to false the entry will point to itself. Use this for redirections. Use \c true if you want to create an link/alias which points to a module (ie. no entry in urlalias table).
\param $alwaysAvailable If true the entry will be available in any language.
\param $rootID ID of the parent element to start at, use 0/false for the very top.
\param $cleanupElements If true each element in the path will be cleaned up according to the current URL transformation rules.
\param $autoAdjustName If true it will adjust the name until it is unique in the path. Used together with $linkID.
\param $reportErrors If true it will report found errors using eZDebug, if \c false errors are only return in 'status'.
\param $aliasRedirects If true and an alias is being stored it will redirect (using HTTP 301) to it's destination.
*/
static function storePath( $path, $action,
$languageName = false, $linkID = false, $alwaysAvailable = false, $rootID = false,
$cleanupElements = true, $autoAdjustName = false, $reportErrors = true, $aliasRedirects = true )
{
$path = eZURLAliasML::cleanURL( $path );
if ( $languageName === false )
{
$languageName = eZContentLanguage::topPriorityLanguage();
}
if ( is_object( $languageName ) )
{
$languageObj = $languageName;
$languageID = (int)$languageName->attribute( 'id' );
$languageName = $languageName->attribute( 'locale' );
}
else
{
$languageObj = eZContentLanguage::fetchByLocale( $languageName );
$languageID = (int)$languageObj->attribute( 'id' );
}
$languageMask = $languageID;
if ( $alwaysAvailable )
$languageMask |= 1;
$path = eZURLAliasML::cleanURL( $path );
$elements = explode( '/', $path );
$db = eZDB::instance();
$parentID = 0;
// If the root ID is specified we will start the parent search from that
if ( $rootID !== false )
{
$parentID = $rootID;
}
$i = 0;
// Top element is handled separately.
$topElement = array_pop( $elements );
// Find correct parent, and create missing ones if necessary
$createdPath = array();
foreach ( $elements as $element )
{
$actionStr = $db->escapeString( $action );
if ( $cleanupElements )
$element = eZURLAliasML::convertToAlias( $element, 'noname' . (count($createdPath)+1) );
$elementStr = $db->escapeString( eZURLAliasML::strtolower( $element ) );
$query = "SELECT * FROM ezurlalias_ml WHERE text_md5 = " . eZURLAliasML::md5( $db, $elementStr, false ) . " AND parent = {$parentID}";
$rows = $db->arrayQuery( $query );
if ( count( $rows ) == 0 )
{
// Create a fake element to ensure we have a parent
$elementObj = eZURLAliasML::create( $element, "nop:", $parentID, 1 );
$elementObj->store();
$parentID = (int)$elementObj->attribute( 'id' );
}
else
{
$parentID = (int)$rows[0]['link'];
}
$createdPath[] = $element;
++$i;
}
if ( $parentID != 0 )
{
$sql = "SELECT text, parent FROM ezurlalias_ml WHERE id = {$parentID}";
$rows = $db->arrayQuery( $sql );
if ( count( $rows ) > 0 )
{
// A special case. If the special entry with empty text is used as parent
// the parent must be adjust to 0 (ie. real top level).
if ( strlen( $rows[0]['text'] ) == 0 && $rows[0]['parent'] == 0 )
{
$createdPath = array();
$parentID = 0;
}
}
}
if ( !preg_match( "#^(.+):(.+)$#", $action, $matches ) )
{
return array( 'status' => self::ACTION_INVALID,
'error_message' => "The action value " . var_export( $action, true ) . " is invalid",
'error_number' => self::ACTION_INVALID,
'path' => null,
'element' => null );
}
$actionName = $matches[1];
$actionValue = $matches[2];
$existingElementID = null;
$alwaysMask = $alwaysAvailable ? 1 : 0;
$actionStr = $db->escapeString( $action );
$actionTypeStr = $db->escapeString( $actionName );
$createdElement = null;
if ( $linkID === false )
{
if ( $cleanupElements )
$topElement = eZURLAliasML::convertToAlias( $topElement, 'noname' . (count($createdPath)+1) );
$adjustName = false;
$curElementID = null;
$newElementID = null;
$newText = $topElement;
$uniqueCounter = 0;
// Loop until we a valid entry point, which means:
// 1. The entry does not exist yet, so create a new one
// 2. The entry exists but is re-usable (e.g. nop or same action)
// 3. The entry exists and cannot be re-used, instead the name is adjusted to be unique.
while ( true )
{
$newText = $topElement;
if ( $uniqueCounter > 0 )
$newText .= ($uniqueCounter + 1);
$textMD5 = eZURLAliasML::md5( $db, $newText );
$query = "SELECT * FROM ezurlalias_ml WHERE parent = $parentID AND text_md5 = {$textMD5}";
$rows = $db->arrayQuery( $query );
if ( count( $rows ) == 0 )
{
// No such entry, create a new one
break;
}
$row = $rows[0];
$curID = (int)$row['id'];
$curAction = $row['action'];
if ( $curAction == 'nop:' || $curAction == $action || $row['is_original'] == 0 )
{
// We can reuse the element so record the ID
$curElementID = $curID;
$newElementID = $curID;
break;
}
if ( !$autoAdjustName )
{
if ( $reportErrors )
eZDebug::writeError( "Tried to store path '{$path}' but the path already exists (ID: {$curID}) but with action '{$curAction}', the new action was '{$action}'" );
return array( 'status' => self::LINK_ALREADY_TAKEN,
'path' => $path,
'element' => null );
}
// Need to adjust name, re-iterate
++$uniqueCounter;
}
$textEsc = $db->escapeString( $newText );
// See if there is already a node in the same level with the same action
if ( $newElementID === null )
{
$query = "SELECT * FROM ezurlalias_ml " .
"WHERE parent = $parentID AND action = '{$actionStr}' AND is_original = 1 AND is_alias = 0";
$rows = $db->arrayQuery( $query );
if ( count( $rows ) > 0 )
{
$newElementID = (int)$rows[0]['id'];
}
}
// Create or update the element
if ( $curElementID !== null )
{
// Check if an already existing entry at the same level exists, with a different id
// if so the id must be updated.
$query = "SELECT * FROM ezurlalias_ml " .
"WHERE parent = $parentID AND action = '{$actionStr}' AND is_original = 1 AND is_alias = 0";
$rows = $db->arrayQuery( $query );
if ( count( $rows ) > 0 )
{
$existingEntryId = (int)$rows[0]['id'];
if ( $existingEntryId != $curElementID )
{
// move history entry to the same id
$query = "UPDATE ezurlalias_ml SET id = {$existingEntryId} " .
"WHERE parent = $parentID AND text_md5 = {$textMD5}";
$res = $db->query( $query );
if ( !$res ) return eZURLAliasML::dbError( $db );
$curElementID = $existingEntryId;
}
}
$bitOr = $db->bitOr( $db->bitAnd( 'lang_mask', ~1 ), $languageMask );
// Note: The `text` field is updated too, this ensures case-changes are stored.
$query = "UPDATE ezurlalias_ml SET link = id, lang_mask = {$bitOr}, text = '{$textEsc}', action = '{$actionStr}', action_type = '{$actionTypeStr}', is_alias = 0, is_original = 1 " .
"WHERE parent = $parentID AND text_md5 = {$textMD5}";
$res = $db->query( $query );
if ( !$res ) return eZURLAliasML::dbError( $db );
$newElementID = $curElementID;
}
else
{
$element = new eZURLAliasML( array( 'id'=> $newElementID,
'link' => null,
'parent' => $parentID,
'text' => $newText,
'lang_mask' => $languageID | $alwaysMask,
'action' => $action ) );
$element->store();
$newElementID = (int)$element->attribute( 'id' );
$createdElement = $element;
}
$createdPath[] = $newText;
// OMS-urlalias-fix: We want to retain the lang_mask of url entries, but mark others as history elements is_original = 0
// Furthermore this change is not performed on custom alias entries.
$bitAnd = $db->bitAnd( 'lang_mask', $languageID );
// First we look at the entries to mark as history entries, if an entry comprise more languages, it must not be set as history element.
$query = "SELECT * FROM ezurlalias_ml " .
"WHERE action = '{$actionStr}' AND (${bitAnd} > 0) AND is_original = 1 AND is_alias = 0 AND (parent != $parentID OR text_md5 != {$textMD5})";
$toBeUpdated = $db->arrayQuery( $query );
// 0. Check if the entry to be updated represents multiple languages:
// IF YES:
// 1. "Downgrade" existing entry, by removing the active translation's language id from the language_mask.
// IF NO:
// 1. Mark entry as a history entry
if ( count( $toBeUpdated ) > 0 )
{
$languageMask = $toBeUpdated[0]['lang_mask'];
if ( ( $languageMask & ~( $languageID | 1 ) ) != 0 )
{
// "Composite entry", downgrade current entry
$currentEntry = new eZURLAliasML( $toBeUpdated[0] );
$currentEntry->LangMask = (int)$currentEntry->LangMask & ~$languageID;
$currentEntry->store();
}
else
{
// Mark as history element.
$query = "UPDATE ezurlalias_ml SET is_original = 0 " .
"WHERE action = '{$actionStr}' AND (${bitAnd} > 0) AND is_original = 1 AND is_alias = 0 AND (parent != $parentID OR text_md5 != {$textMD5})";
$res = $db->query( $query );
if ( !$res ) return eZURLAliasML::dbError( $db );
}
}
// OMS-urlalias-fix: instead entries without language we look at history elements with same action (and language)
// Look for other nodes with the same action and language
// if found make then link to the new entry
$bitAnd = $db->bitAnd( 'lang_mask', $languageID );
$query = "SELECT * FROM ezurlalias_ml " .
"WHERE action = '{$actionStr}' AND (${bitAnd} > 0) AND is_original = 0 AND (parent != $parentID OR text_md5 != {$textMD5})";
$rows = $db->arrayQuery( $query );
foreach ( $rows as $row )
{
$idtmp = (int)$row['id'];
if ( $idtmp == $newElementID )
{
$idtmp = self::getNewID();
}
$parentIDTmp = (int)$row['parent'];
$textMD5Tmp = eZURLAliasML::md5( $db, $row['text'] );
// OMS-urlalias-fix: We do not touch the lang_mask here
$res = $db->query( "UPDATE ezurlalias_ml SET id = {$idtmp}, link = {$newElementID}, is_alias = 0, is_original = 0 " .
"WHERE parent = {$parentIDTmp} AND text_md5 = {$textMD5Tmp}" );
if ( !$res ) return eZURLAliasML::dbError( $db );
}
$res = $db->query( $query );
if ( !$res ) return eZURLAliasML::dbError( $db );
// Look for other nodes which is a link for the current action
// if found make then link to the new entry
// OMS-urlalias-fix: We only want to update the links of entries within the same language.
// Also, only to be applied on normal entries, not custom aliases
$bitAnd = $db->bitAnd( 'lang_mask', $languageID );
$query = "UPDATE ezurlalias_ml SET link = {$newElementID}, is_alias = 0, is_original = 0 " .
"WHERE action = '{$actionStr}' AND is_original = 0 AND is_alias = 0 AND (${bitAnd} > 0) AND (parent != $parentID OR text_md5 != {$textMD5})";
$res = $db->query( $query );
if ( !$res ) return eZURLAliasML::dbError( $db );
// Move children from old node to the new node
// Conflicts:
// New | Old | Action
// -------------------------------
// Element | Link | Delete old
// Element | Element | Will not happen, if so delete old
// Element | Other | Reparent with new name
// Element | nop | Delete old
// Link | Link | Delete old
// Link | Element | Delete new, reparent
// Link | Other | Delete new, reparent
// Link | nop | Delete old
// nop | Link | Delete new, reparent
// nop | Element | Delete new, reparent
// nop | nop | Delete old
// TODO: Handle all conflict cases, for now only the `Delete old, reparent` action is done
// OMS-urlalias-fix: We are only updating child nodes within the same language,
// and only for real system-generated url aliases. Custom aliases are left alone.
$bitAnd = $db->bitAnd( 'lang_mask', $languageID );
$query = "SELECT id FROM ezurlalias_ml " .
"WHERE action = '{$actionStr}' AND is_alias = 0 AND (parent != $parentID OR text_md5 != {$textMD5})";
$rows = $db->arrayQuery( $query );
foreach ( $rows as $row )
{
$oldParentID = (int)$row['id'];
$query = "UPDATE ezurlalias_ml SET parent = {$newElementID} " .
"WHERE parent = {$oldParentID} AND (${bitAnd} > 0)";
$res = $db->query( $query );
if ( !$res ) return eZURLAliasML::dbError( $db );
}
}
else
{
// Check the link ID
if ( $linkID !== true )
{
$linkID = (int)$linkID;
// Step 1, find existing ID
$query = "SELECT * FROM ezurlalias_ml WHERE id = '{$linkID}'";
$rows = $db->arrayQuery( $query );
// Some sanity checking
if ( count( $rows ) == 0 )
{
if ( $reportErrors )
eZDebug::writeError( "The link ID $linkID does not exist, cannot create the link", __METHOD__ );
return array( 'status' => eZURLAliasML::LINK_ID_NOT_FOUND );
}
if ( $rows[0]['action'] != $action )
{
if ( $reportErrors )
eZDebug::writeError( "The link ID $linkID uses a different action ({$rows[0]['action']}) than the requested action ({$action}) for the link, cannot create the link", __METHOD__ );
return array( 'status' => eZURLAliasML::LINK_ID_WRONG_ACTION );
}
// If the element which is pointed to is a link, then grab the link id from that instead
if ( $rows[0]['link'] != $rows[0]['id'] )
{
$linkID = (int)$rows[0]['link'];
}
}
else
{
$linkID = null;
}
if ( $cleanupElements )
$topElement = eZURLAliasML::convertToAlias( $topElement, 'noname' . (count($createdPath)+1) );
$adjustName = false;
$curElementID = null;
$newText = $topElement;
$uniqueCounter = 0;
$rows = null; // Will be filled in by the while loop
// Loop until we a valid entry point, which means:
// 1. The entry does not exist yet, so create a new one
// 2. The entry exists but is re-usable (e.g. nop or same action)
// 3. The entry exists and cannot be re-used, instead the name is adjusted to be unique.
while ( true )
{
$newText = $topElement;
if ( $uniqueCounter > 0 )
$newText .= ($uniqueCounter + 1);
$textMD5 = eZURLAliasML::md5( $db, $newText );
$query = "SELECT * FROM ezurlalias_ml WHERE parent = $parentID AND text_md5 = {$textMD5}";
$rows = $db->arrayQuery( $query );
if ( count( $rows ) == 0 )
{
// No such entry, create a new one
break;
}
$row = $rows[0];
$curID = (int)$row['id'];
$curLink = (int)$row['link'];
$curAction = $row['action'];
if ( $curAction == $action )
{
// If the current node is the same action and is not a link we
// cannot replace it with a link node.
if ( $curID != $curLink )
{
// We can reuse the element so record the ID
$curElementID = $curID;
break;
}
}
else if ( $curAction == 'nop:' || $row['is_original'] == 0 )
{
// We can reuse the element so record the ID
$curElementID = $curID;
break;
}
if ( !$autoAdjustName )
{
if ( $reportErrors )
eZDebug::writeError( "Tried to store path '{$path}' but the path already exists (ID: {$curID}) but with action '{$curAction}', the new action was '{$action}'" );
return array( 'status' => self::LINK_ALREADY_TAKEN,
'path' => $path,
'element' => null );
}
// Need to adjust name, re-iterate
++$uniqueCounter;
}
$textEsc = $db->escapeString( $newText );
// Create or update the element
if ( $curElementID !== null )
{
$element = new eZURLAliasML( $rows[0] ); // $rows is from the while loop
$element->LangMask |= $languageID | $alwaysMask;
$element->IsAlias = 1;
$element->Action = $action;
// Note: The `text` field is updated too, this ensures case-changes are stored.
$element->Text = $newText;
$element->TextMD5 = null;
$element->ActionType = null;
$element->Link = null;
}
else
{
$element = new eZURLAliasML( array( 'id'=> null,
'link' => null,
'parent' => $parentID,
'text' => $newText,
'lang_mask' => $languageID | $alwaysMask,
'action' => $action,
'is_alias' => 1 ) );
}
$element->AliasRedirects = $aliasRedirects ? 1 : 0;
$element->store();
$createdPath[] = $topElement;
$createdElement = $element;
}
return array( 'status' => true,
'path' => join( "/", $createdPath ),
'element' => $createdElement );
}
/*!
\static
\private
Returns a structure with the current database error.
\note This is used by storePath().
*/
static private function dbError( $db )
{
return array( 'status' => self::DB_ERROR,
'error_message' => $db->errorMessage(),
'error_number' => $db->errorNumber(),
'path' => null,
'element' => null );
}
/*!
\static
Fetches real path element(s) which matches the action name $actionName and value $actionValue.
Lets say we have the following elements:
\code
=== ==== ====== =========== ==========
id link parent text action
=== ==== ====== =========== ==========
1 1 0 'ham' 'eznode:4'
2 6 0 'spam' 'eznode:55'
3 3 0 'bicycle' 'eznode:5'
4 4 0 'superman' 'nop:'
5 5 3 'repairman' 'eznode:42'
6 6 3 'repoman' 'eznode:55'
=== ==== ====== =========== ==========
\endcode
then we try to fetch a specific action:
\code
$elements = eZURLAliasML::fetchByAction( 'eznode', 5 );
\endcode
it would return:
\code
=== ==== ====== =========== ==========
id link parent text action
=== ==== ====== =========== ==========
3 3 0 'bicycle' 'eznode:5'
=== ==== ====== =========== ==========
\endcode
Now let's try with an element which is redirecting:
\code
$elements = eZURLAliasML::fetchByAction( 'eznode', 10 );
\endcode
it would return:
\code
=== ==== ====== =========== ==========
id link parent text action
=== ==== ====== =========== ==========
2 6 0 'spam' 'eznode:55'
=== ==== ====== =========== ==========
\endcode
*/
static public function fetchByAction( $actionName, $actionValue, $maskLanguages = false, $onlyPrioritized = false, $includeRedirections = false )
{
$action = $actionName . ":" . $actionValue;
$db = eZDB::instance();
$actionStr = $db->escapeString( $action );
$langMask = '';
if ( $maskLanguages === true )
{
$langMask = "(" . trim( eZContentLanguage::languagesSQLFilter( 'ezurlalias_ml', 'lang_mask' ) ) . ") AND ";
}
else if ( is_string( $maskLanguages ) )
{
// maskByLocale can support array input, here we only want one item.
$mask = eZContentLanguage::maskByLocale( $maskLanguages );
$langFilter = $db->bitAnd( 'lang_mask', $mask );
$langMask = "({$langFilter} > 0) AND";
}
$query = "SELECT * FROM ezurlalias_ml WHERE $langMask action = '$actionStr'";
if ( !$includeRedirections )
{
$query .= " AND is_original = 1 AND is_alias = 0";
}
$rows = $db->arrayQuery( $query );
if ( count( $rows ) == 0 )
return array();
$rows = eZURLAliasML::filterRows( $rows, $onlyPrioritized );
$objectList = eZPersistentObject::handleRows( $rows, 'eZURLAliasML', true );
return $objectList;
}
/*!
\static
Fetches path element(s) which matches the parent ID $id.
Lets say we have the following elements:
=== ==== ====== =========== ==========
id link parent text action
=== ==== ====== =========== ==========
1 1 0 'ham' 'eznode:4'
2 6 0 'spam' 'eznode:55'
3 3 0 'bicycle' 'eznode:5'
4 4 0 'superman' 'nop:'
5 5 3 'repairman' 'eznode:42'
6 6 3 'repoman' 'eznode:55'
=== ==== ====== =========== ==========
then we try to fetch a specific ID:
\code
eZURLAliasML::fetchByParentID( 0 );
\endcode
it would return (ie. no redirections):
\code
=== ==== ====== =========== ==========
id link parent text action
=== ==== ====== =========== ==========
1 1 0 'ham' 'eznode:4'
3 3 0 'bicycle' 'eznode:5'
4 4 0 'superman' 'nop:'
=== ==== ====== =========== ==========
\endcode
Now let's try with an element which is redirecting:
\code
$includeRedirections = true;
eZURLAliasML::fetchByParentID( 0, false, false, $includeRedirections );
\endcode
it would return:
\code
=== ==== ====== =========== ==========
id link parent text action
=== ==== ====== =========== ==========
1 1 0 'ham' 'eznode:4'
2 6 0 'spam' 'eznode:55'
3 3 0 'bicycle' 'eznode:5'
4 4 0 'superman' 'nop:'
=== ==== ====== =========== ==========
\endcode
*/
static public function fetchByParentID( $id, $maskLanguages = false, $onlyPrioritized = false, $includeRedirections = true )
{
$db = eZDB::instance();
$id = (int)$id;
$langMask = trim( eZContentLanguage::languagesSQLFilter( 'ezurlalias_ml', 'lang_mask' ) );
$redirSQL = '';
if ( !$includeRedirections )
{
$redirSQL = " AND is_original = 1";
}
$langMask = '';
if ( $maskLanguages )
{
$langMask = "(" . trim( eZContentLanguage::languagesSQLFilter( 'ezurlalias_ml', 'lang_mask' ) ) . ") AND ";
}
$query = "SELECT * FROM ezurlalias_ml WHERE $langMask parent = {$id} $redirSQL";
$rows = $db->arrayQuery( $query );
$rows = eZURLAliasML::filterRows( $rows, $onlyPrioritized );
return eZPersistentObject::handleRows( $rows, 'eZURLAliasML', true );
}
/*!
\static
Fetches the path string based on the action $actionName and the values $actionValues.
The first entry in $actionValues would be the top-most path element in the path
the second entry the child of the first path element and so on.
Lets say we have the following elements:
\code
=== ==== ====== =========== ==========
id link parent text action
=== ==== ====== =========== ==========
1 1 0 'ham' 'eznode:4'
2 6 0 'spam' 'eznode:55'
3 3 0 'bicycle' 'eznode:5'
4 4 0 'superman' 'nop:'
5 5 3 'repairman' 'eznode:42'
6 6 3 'repoman' 'eznode:55'
=== ==== ====== =========== ==========
\endcode
then we try to fetch a specific ID:
\code
$path = eZURLAliasML::fetchPathByActionList( 'eznode', array( 3, 5 ) );
\endcode
it would return:
\code
'bicycle/repairman'
\endcode
\note This function is faster than getPath() since it can fetch all elements in one SQL.
\note If the fetched elements does not point to each other (parent/id) then null is returned.
*/
static public function fetchPathByActionList( $actionName, $actionValues, $locale = null )
{
if ( !is_array( $actionValues ) || count( $actionValues ) == 0 )
{
eZDebug::writeError( "Action values array must not be empty", __METHOD__ );
return null;
}
$db = eZDB::instance();
$actionList = array();
foreach ( $actionValues as $i => $value )
{
$actionList[] = "'" . $db->escapeString( $actionName . ":" . $value ) . "'";
}
$actionStr = join( ", ", $actionList );
$filterSQL = trim( eZContentLanguage::languagesSQLFilter( 'ezurlalias_ml', 'lang_mask' ) );
$query = "SELECT id, parent, lang_mask, text, action FROM ezurlalias_ml WHERE ( {$filterSQL} ) AND action in ( {$actionStr} ) AND is_original = 1 AND is_alias=0";
$rows = $db->arrayQuery( $query );
$actionMap = array();
foreach ( $rows as $row )
{
$action = $row['action'];
if ( !isset( $actionMap[$action] ) )
$actionMap[$action] = array();
$actionMap[$action][] = $row;
}
if ( $locale !== null && is_string( $locale ) && !empty( $locale ) )
{
$selectedLanguage = eZContentLanguage::fetchByLocale( $locale );
$prioritizedLanguages = eZContentLanguage::prioritizedLanguages();
// Add $selectedLanguage on top of $prioritizedLanguages to take it into account with the highest priority
if ( $selectedLanguage instanceof eZContentLanguage )
array_unshift( $prioritizedLanguages, $selectedLanguage );
}
else
{
$prioritizedLanguages = eZContentLanguage::prioritizedLanguages();
}
$path = array();
$lastID = false;
foreach ( $actionValues as $actionValue )
{
$action = $actionName . ":" . $actionValue;
if ( !isset( $actionMap[$action] ) )
{
// eZDebug::writeError( "The action '{$action}' was not found in the database for the current language language filter, cannot calculate path." );
return null;
}
$actionRows = $actionMap[$action];
$defaultRow = null;
foreach( $prioritizedLanguages as $language )
{
foreach ( $actionRows as $row )
{
$langMask = (int)$row['lang_mask'];
$wantedMask = (int)$language->attribute( 'id' );
if ( ( $wantedMask & $langMask ) > 0 )
{
$defaultRow = $row;
break 2;
}
// If the 'always available' bit is set then choose it as the default
if ( ($langMask & 1) > 0 )
{
$defaultRow = $row;
}
}
}
if ( $defaultRow )
{
$id = (int)$defaultRow['id'];
$paren = (int)$defaultRow['parent'];
// If the parent is 0 it means the element is at the top, ie. reset the path and lastID
if ( $paren == 0 )
{
$lastID = false;
$path = array();
}
$path[] = $defaultRow['text'];
// Check for a valid path
if ( $lastID !== false && $lastID != $paren )
{
eZDebug::writeError( "The parent ID $paren of element with ID $id does not point to the last entry which had ID $lastID, incorrect path would be calculated, aborting" );
return null;
}
$lastID = $id;
}
else
{
// No row was found
eZDebug::writeError( "Fatal error, no row was chosen for action " . $actionName . ":" . $actionValue );
return null;
}
}
return join( "/", $path );
}
/*!
\static
Fetches the path element(s) which has the path $uriString.
If $glob is set it will use $uriString as the folder to search in and $glob as
the starting text to match against.
Lets say we have the following elements:
\code
=== ==== ====== =========== ==========
id link parent text action
=== ==== ====== =========== ==========
1 1 0 'ham' 'eznode:4'
2 6 0 'spam' 'eznode:55'
3 3 0 'bicycle' 'eznode:5'
4 4 0 'superman' 'nop:'
5 5 3 'repairman' 'eznode:42'
6 6 3 'repoman' 'eznode:55'
=== ==== ====== =========== ==========
\endcode
Then we try to fetch a specific path:
\code
$elements = eZURLAliasML::fetchByPath( "bicycle/repairman" );
\endcode
we would get:
\code
=== ==== ====== =========== ==========
id link parent text action
=== ==== ====== =========== ==========
5 5 3 'repairman' 'eznode:42'
=== ==== ====== =========== ==========
\endcode
\code
$elements = eZURLAliasML::fetchByPath( "bicycle", "rep" ); // bicycle/rep*
\endcode
we would get:
\code
=== ==== ====== =========== ==========
id link parent text action
=== ==== ====== =========== ==========
5 5 3 'repairman' 'eznode:42'
6 6 3 'repoman' 'eznode:55'
=== ==== ====== =========== ==========
\endcode
*/
static public function fetchByPath( $uriString, $glob = false )
{
$uriString = eZURLAliasML::cleanURL( $uriString );
$db = eZDB::instance();
if ( $uriString == '' && $glob !== false )
$elements = array();
else
$elements = explode( '/', $uriString );
$len = count( $elements );
$i = 0;
$selects = array();
$tables = array();
$conds = array();
$prevTable = false;
foreach ( $elements as $element )
{
$table = "e" . $i;
$langMask = trim( eZContentLanguage::languagesSQLFilter( $table, 'lang_mask' ) );
if ( $glob === false && ($i == $len - 1) )
$selects[] = eZURLAliasML::generateFullSelect( $table );
else
$selects[] = eZURLAliasML::generateSelect( $table, $i, $len );
$tables[] = "ezurlalias_ml " . $table;
$conds[] = eZURLAliasML::generateCond( $table, $prevTable, $i, $langMask, $element );
$prevTable = $table;
++$i;
}
if ( $glob !== false )
{
++$len;
$table = "e" . $i;
$langMask = trim( eZContentLanguage::languagesSQLFilter( $table, 'lang_mask' ) );
$selects[] = eZURLAliasML::generateFullSelect( $table );
$tables[] = "ezurlalias_ml " . $table;
$conds[] = eZURLAliasML::generateGlobCond( $table, $prevTable, $i, $langMask, $glob );
$prevTable = $table;
++$i;
}
$elementOffset = $i - 1;
$query = "SELECT DISTINCT " . join( ", ", $selects ) . " FROM " . join( ", ", $tables ) . " WHERE " . join( " AND ", $conds );
$pathRows = $db->arrayQuery( $query );
$elements = array();
if ( count( $pathRows ) > 0 )
{
foreach ( $pathRows as $pathRow )
{
$redirectLink = false;
$table = "e" . $elementOffset;
$element = array( 'id' => $pathRow[$table . "_id"],
'parent' => $pathRow[$table . "_parent"],
'lang_mask' => $pathRow[$table . "_lang_mask"],
'text' => $pathRow[$table . "_text"],
'action' => $pathRow[$table . "_action"],
'link' => $pathRow[$table . "_link"] );
$path = array();
$lastID = false;
for ( $i = 0; $i < $len; ++$i )
{
$table = "e" . $i;
$id = $pathRow[$table . "_id"];
$link = $pathRow[$table . "_link"];
$path[] = $pathRow[$table . "_text"];
if ( $link != $id )
{
// Mark the redirect link
$redirectLink = $link;
$redirectOffset = $i;
}
$lastID = $link;
}
if ( $redirectLink )
{
$newLinkID = $redirectLink;
// Resolve new links until a real element is found.
// TODO: Add max redirection count?
while ( $newLinkID )
{
$query = "SELECT id, parent, lang_mask, text, link FROM ezurlalias_ml WHERE id={$newLinkID}";
$rows = $db->arrayQuery( $query );
if ( count( $rows ) == 0 )
{
return false;
}
$newLinkID = false;
if ( $rows[0]['id'] != $rows[0]['link'] )
$newLinkID = (int)$rows[0]['link'];
}
$id = (int)$newLinkID;
$path = array();
// Fetch path 'text' elements of correct parent path
while ( $id != 0 )
{
$query = "SELECT parent, lang_mask, text FROM ezurlalias_ml WHERE id={$id}";
$rows = $db->arrayQuery( $query );
if ( count( $rows ) == 0 )
{
break;
}
$result = eZURLAliasML::choosePrioritizedRow( $rows );
if ( !$result )
{
$result = $rows[0];
}
$id = (int)$result['parent'];
array_unshift( $path, $result['text'] );
}
// Fill in end of path elements
for ( $i = $redirectOffset; $i < $len; ++$i )
{
$table = "e" . $i;
$path[] = $pathRow[$table . "_text"];
}
}
$element['path'] = implode( '/', $path );
$elements[] = $element;
}
}
$rows = array();
$ids = array();
// Discard duplicates
foreach ( $elements as $element )
{
$id = (int)$element['id'];
if ( isset( $ids[$id] ) )
continue;
$ids[$id] = true;
$rows[] = $element;
}
$objectList = eZPersistentObject::handleRows( $rows, 'eZURLAliasML', true );
return $objectList;
}
/*!
\static
The same as 'fetchByPath' but extracting nodeID from action.
Only first entry will be processed if 'fetchByPath' returns multiple result(e.g. $glob is wildcard).
\return nodeID on success or \c false otherwise.
*/
static public function fetchNodeIDByPath( $uriString, $glob = false )
{
$nodeID = false;
$urlAliasMLList = eZURLAliasML::fetchByPath( $uriString, $glob );
if ( is_array( $urlAliasMLList ) && count( $urlAliasMLList ) > 0 )
$nodeID = eZURLAliasML::nodeIDFromAction( $urlAliasMLList[0]->Action );
return $nodeID;
}
/*!
\static
Transforms the URI if there exists an alias for it, the new URI is replaced in $uri.
\return \c true is if successful, \c false otherwise
\return The string with new url is returned if the translation was found, but the resource has moved.
Lets say we have the following elements:
\code
=== ==== ====== =========== ==========
id link parent text action
=== ==== ====== =========== ==========
1 1 0 'ham' 'eznode:4'
2 6 0 'spam' 'eznode:55'
3 3 0 'bicycle' 'eznode:5'
4 4 0 'superman' 'nop:'
5 5 3 'repairman' 'eznode:42'
6 6 3 'repoman' 'eznode:55'
=== ==== ====== =========== ==========
\endcode
then we try to translate a path:
\code
$uri = "bicycle/repairman";
$result = eZURLAliasML::translate( $uri );
if ( $result )
{
echo $result, "\n";
echo $uri, "\n";
}
\endcode
we would get:
\code
'1'
'content/view/full/42'
\endcode
If we then were to try:
\code
$uri = "spam";
$result = eZURLAliasML::translate( $uri );
if ( $result )
{
echo $result, "\n";
echo $uri, "\n";
}
\endcode
we would get:
\code
'bicycle/repoman'
'error/301'
\endcode
Trying a non-existing path:
\code
$uri = "spam/a-lot";
$result = eZURLAliasML::translate( $uri );
if ( $result )
{
echo $result, "\n";
echo $uri, "\n";
}
\endcode
then $result would be empty:
Alterntively we can also do a reverse lookup:
\code
$uri = "content/view/full/55";
$result = eZURLAliasML::translate( $uri, true );
if ( $result )
{
echo $result, "\n";
echo $uri, "\n";
}
\endcode
we would get:
\code
'1'
'bicycle/repoman'
\endcode
*/
static public function translate( &$uri, $reverse = false )
{
if ( $uri instanceof eZURI )
{
$uriString = $uri->elements();
}
else
{
$uriString = $uri;
}
$uriString = eZURLAliasML::cleanURL( $uriString );
$internalURIString = $uriString;
$originalURIString = $uriString;
$ini = eZINI::instance();
$prefixAdded = false;
$prefix = $ini->hasVariable( 'SiteAccessSettings', 'PathPrefix' ) &&
$ini->variable( 'SiteAccessSettings', 'PathPrefix' ) != '' ? eZURLAliasML::cleanURL( $ini->variable( 'SiteAccessSettings', 'PathPrefix' ) ) : false;
if ( $prefix )
{
$escapedPrefix = preg_quote( $prefix, '#' );
// Only prepend the path prefix if it's not already the first element of the url.
if ( !preg_match( "#^$escapedPrefix(/.*)?$#i", $uriString ) )
{
$exclude = $ini->hasVariable( 'SiteAccessSettings', 'PathPrefixExclude' )
? $ini->variable( 'SiteAccessSettings', 'PathPrefixExclude' )
: false;
$breakInternalURI = false;
foreach ( $exclude as $item )
{
$escapedItem = preg_quote( $item, '#' );
if ( preg_match( "#^$escapedItem(/.*)?$#i", $uriString ) )
{
$breakInternalURI = true;
break;
}
}
if ( !$breakInternalURI )
{
$internalURIString = $prefix . '/' . $uriString;
$prefixAdded = true;
}
}
}
$db = eZDB::instance();
$elements = explode( '/', $internalURIString );
$len = count( $elements );
if ( $reverse )
{
return eZURLAliasML::reverseTranslate( $uri, $uriString, $internalURIString );
}
$i = 0;
$selects = array();
$tables = array();
$conds = array();
foreach ( $elements as $element )
{
$table = "e" . $i;
$selectString = "{$table}.id AS {$table}_id, ";
$selectString .= "{$table}.link AS {$table}_link, ";
$selectString .= "{$table}.text AS {$table}_text, ";
$selectString .= "{$table}.text_md5 AS {$table}_text_md5, ";
$selectString .= "{$table}.is_alias AS {$table}_is_alias, ";
if ( $i == $len - 1 )
$selectString .= "{$table}.action AS {$table}_action, ";
$selectString .= "{$table}.alias_redirects AS {$table}_alias_redirects";
$selects[] = $selectString;
$tables[] = "ezurlalias_ml " . $table;
$langMask = trim( eZContentLanguage::languagesSQLFilter( $table, 'lang_mask' ) );
if ( $i == 0 )
{
$conds[] = "{$table}.parent = 0 AND ({$langMask}) AND {$table}.text_md5 = " . eZURLAliasML::md5( $db, $element );
}
else
{
$conds[] = "{$table}.parent = {$prevTable}.link AND ({$langMask}) AND {$table}.text_md5 = " . eZURLAliasML::md5( $db, $element );
}
$prevTable = $table;
++$i;
}
$query = "SELECT " . join( ", ", $selects ) . " FROM " . join( ", ", $tables ) . " WHERE " . join( " AND ", $conds );
$return = false;
$urlAliasArray = $db->arrayQuery( $query, array( 'limit' => 1 ) );
if ( count( $urlAliasArray ) > 0 )
{
$pathRow = $urlAliasArray[0];
$l = count( $pathRow );
$redirectLink = false;
$redirectAction = false;
$lastID = false;
$action = false;
$verifiedPath = array();
$doRedirect = false;
for ( $i = 0; $i < $len; ++$i )
{
$table = "e" . $i;
$id = $pathRow[$table . "_id"];
$link = $pathRow[$table . "_link"];
$text = $pathRow[$table . "_text"];
$isAlias = $pathRow[$table . '_is_alias'];
$aliasRedirects = $pathRow[$table . '_alias_redirects'];
$verifiedPath[] = $text;
if ( $i == $len - 1 )
{
$action = $pathRow[$table . "_action"];
}
if ( $link != $id )
{
$doRedirect = true;
}
else if ( $isAlias && $action !== false )
{
if ( $aliasRedirects )
{
// If the entry is an alias and we have an action we redirect to the original
// url of that action.
$redirectAction = $action;
$doRedirect = true;
}
}
$lastID = $link;
}
if ( !$doRedirect )
{
$verifiedPathString = implode( '/', $verifiedPath );
// Check for case difference
if ( $prefixAdded )
{
if ( strcmp( $originalURIString, substr( $verifiedPathString, strlen( $prefix ) + 1 ) ) != 0 )
{
$doRedirect = true;
}
}
else if ( strcmp( $verifiedPathString, $internalURIString ) != 0 )
{
$doRedirect = true;
}
}
if ( preg_match( "#^module:(.+)$#", $action, $matches ) and $doRedirect )
{
$uriString = 'error/301';
$return = $matches[1];
}
else if ( $doRedirect )
{
if ( $redirectAction !== false )
{
$query = "SELECT id FROM ezurlalias_ml WHERE action = '" . $db->escapeString( $action ) . "' AND is_original = 1 AND is_alias = 0";
$rows = $db->arrayQuery( $query );
if ( count( $rows ) > 0 )
{
$id = (int)$rows[0]['id'];
}
else
{
$id = false;
$uriString = 'error/301';
$return = join( "/", $pathData );
}
}
else
{
$id = (int)$lastID;
}
if ( $id !== false )
{
$pathData = array();
// Figure out the correct path by iterating down the parents until we have all
// elements figured out.
while ( $id != 0 )
{
$query = "SELECT parent, lang_mask, text FROM ezurlalias_ml WHERE id={$id}";
$rows = $db->arrayQuery( $query );
if ( count( $rows ) == 0 )
{
break;
}
$result = eZURLAliasML::choosePrioritizedRow( $rows );
if ( !$result )
{
$result = $rows[0];
}
$id = (int)$result['parent'];
array_unshift( $pathData, $result['text'] );
}
$uriString = 'error/301';
$return = join( "/", $pathData );
}
// Remove prefix of redirect uri if needed
if ( $prefix && is_string( $return ) )
{
if ( strncasecmp( $return, $prefix . '/', strlen( $prefix ) + 1 ) == 0 )
{
$return = substr( $return, strlen( $prefix ) + 1 );
}
}
}
else
{
// See http://issues.ez.no/19062
// If $uriString matches a nop action, we need to check if we also match a wildcard
// since we might want to translate it.
// Default action for nop actions is to display the root node "/" (see eZURLAliasML::actionToURL())
if ( strpos( $action, 'nop') !== false && eZURLWildcard::wildcardExists( $uriString ) )
{
$return = false;
}
else
{
$uriString = eZURLAliasML::actionToUrl( $action );
$return = true;
}
}
if ( $uri instanceof eZURI )
{
$uri->setURIString( $uriString, false );
}
else
{
$uri = $uriString;
}
}
return $return;
}
/*!
\private
\static
Perform reverse translation of uri, that is from system-url to url alias.
*/
static public function reverseTranslate( &$uri, $uriString, $internalURIString )
{
$db = eZDB::instance();
$action = eZURLAliasML::urlToAction( $internalURIString );
if ( $action !== false )
{
$langMask = trim( eZContentLanguage::languagesSQLFilter( 'ezurlalias_ml', 'lang_mask' ) );
$actionStr = $db->escapeString( $action );
$query = "SELECT id, parent, lang_mask, text, action FROM ezurlalias_ml WHERE ($langMask) AND action='{$actionStr}' AND is_original = 1 AND is_alias = 0";
$rows = $db->arrayQuery( $query );
$path = array();
$count = count( $rows );
if ( $count != 0 )
{
$row = eZURLAliasML::choosePrioritizedRow( $rows );
if ( $row === false )
{
$row = $rows[0];
}
$paren = (int)$row['parent'];
$path[] = $row['text'];
// We have the parent so now do an iterative lookup until we have the top element
while ( $paren != 0 )
{
$query = "SELECT id, parent, lang_mask, text FROM ezurlalias_ml WHERE ($langMask) AND id=$paren AND is_original = 1 AND is_alias = 0";
$rows = $db->arrayQuery( $query );
$count = count( $rows );
if ( $count != 0 )
{
$row = eZURLAliasML::choosePrioritizedRow( $rows );
if ( $row === false )
{
$row = $rows[0];
}
$paren = (int)$row['parent'];
array_unshift( $path, $row['text'] );
}
else
{
eZDebug::writeError( "Lookup of parent ID $paren failed, cannot perform reverse lookup of alias." );
return false;
}
}
$uriString = join( '/', $path );
if ( $uri instanceof eZURI )
{
$uri->setURIString( $uriString, false );
}
else
{
$uri = $uriString;
}
return true;
}
else
{
return false;
}
}
return false;
}
/*!
\static
Checks if url translation should be used on the current url.
\param $uri The current eZUri object
*/
static public function urlTranslationEnabledByUri( eZURI $uri )
{
if ( $uri->isEmpty() )
return false;
$ini = eZINI::instance();
if ( $ini->variable( 'URLTranslator', 'Translation' ) === 'enabled' )
{
if ( $ini->variable( 'URLTranslator', 'TranslatableSystemUrls' ) === 'disabled' )
{
$moduleName = $uri->element( 0 );
$moduleINI = eZINI::instance( 'module.ini' );
$moduleList = $moduleINI->variable( 'ModuleSettings', 'ModuleList' );
if ( in_array( $moduleName, $moduleList, true ) )
return false;
}
return true;
}
return false;
}
/*!
\static
Checks if the text entry $text is unique on the current level in the URL path.
If not the name is adjusted with a number at the end until it becomes unique.
The unique text string is returned.
\param $text The text element which is to be checked
\param $action The action string which is to be excluded from the check. Set to empty string to disable the exclusion.
\param $linkCheck If true then it will see all existing entries as taken.
*/
static public function findUniqueText( $parentElementID, $text, $action, $linkCheck = false, $languageID = false )
{
$db = eZDB::instance();
$uniqueNumber = 0;
// If there is no parent we need to check against reserved words
if ( $parentElementID == 0 )
{
$moduleINI = eZINI::instance( 'module.ini' );
$reserved = $moduleINI->variable( 'ModuleSettings', 'ModuleList' );
foreach ( $reserved as $res )
{
if ( strcasecmp( $text, $res ) == 0 )
{
// The name is a reserved word so it needs to be changed
++$uniqueNumber;
break;
}
}
}
$suffix = '';
if ( $uniqueNumber )
$suffix = $uniqueNumber + 1;
$actionSQL = '';
if ( strlen( $action ) > 0 )
{
$actionEsc = $db->escapeString( $action );
$actionSQL = "AND action != '$actionEsc'";
}
$languageSQL = "";
if ( $languageID !== false )
{
$languageSQL = "AND " . $db->bitAnd( 'lang_mask', $languageID ) . ' > 0';
}
// Loop until we find a unique name
while ( true )
{
$textEsc = eZURLAliasML::md5( $db, $text . $suffix );
$query = "SELECT * FROM ezurlalias_ml WHERE parent = $parentElementID $actionSQL $languageSQL AND text_md5 = $textEsc";
if ( !$linkCheck )
{
$query .= " AND is_original = 1";
}
if ( $db->databaseName() === 'mysql' )
{
$query .= ' LOCK IN SHARE MODE';
}
$rows = $db->arrayQuery( $query );
if ( count( $rows ) == 0 )
{
return $text . $suffix;
}
++$uniqueNumber;
$suffix = $uniqueNumber + 1;
}
}
/*!
\static
Updates the lang_mask field for path elements which matches action $actionName and value $actionValue.
If $langID is false then bit 0 (the *always available* bit) will be removed, otherwise it will set bit 0 for the chosen language and remove it for other languages.
*/
static public function setLangMaskAlwaysAvailable( $langID, $actionName, $actionValue )
{
if ( !$actionName )
{
eZDebug::writeError( "ActionName value must not be empty", __METHOD__ );
return null;
}
$db = eZDB::instance();
if ( is_array( $actionName ) )
{
$actions = array();
foreach ( $actionName as $actionItem )
{
$action = $actionItem[0] . ":" . $actionItem[1];
$actions[] = "'" . $db->escapeString( $action ) . "'";
}
$actionSql = "action in (" . implode( ', ', $actions ) . ")";
}
else
{
$action = $actionName . ":" . $actionValue;
$actionSql = "action = '" . $db->escapeString( $action ) . "'";
}
if ( $langID !== false )
{
// Set the 0 bit for chosen language
$bitOp = $db->bitOr( 'lang_mask', 1 );
$langWhere = ' AND ' . $db->bitAnd( 'lang_mask' , (int)$langID ) . ' > 0';
$query = "UPDATE ezurlalias_ml SET lang_mask = $bitOp WHERE $actionSql $langWhere";
$db->query( $query );
// Clear the 0 bit for all other languages
$bitOp = $db->bitAnd( 'lang_mask', ~1 );
$langWhere = ' AND ' . $db->bitAnd( 'lang_mask' , (int)$langID ) . ' = 0';
$query = "UPDATE ezurlalias_ml SET lang_mask = $bitOp WHERE $actionSql $langWhere";
$db->query( $query );
}
else
{
$bitOp = $db->bitAnd( 'lang_mask', ~1 );
$query = "UPDATE ezurlalias_ml SET lang_mask = $bitOp WHERE $actionSql";
$db->query( $query );
}
}
/**
* Chooses the most prioritized row (based on language) of $rows and returns it.
* @param array $rows
* @return array|false The most prioritized row, or false if no match was found
*/
static public function choosePrioritizedRow( $rows )
{
$result = false;
$score = 0;
foreach ( $rows as $row )
{
if ( $result )
{
$newScore = eZURLAliasML::languageScore( $row['lang_mask'] );
if ( $newScore > $score )
{
$result = $row;
$score = $newScore;
}
}
else
{
$result = $row;
$score = eZURLAliasML::languageScore( $row['lang_mask'] );
}
}
// If score is still 0, this means that the objects languages don't
// match the INI settings, and these should be fix according to the doc.
if ( $score == 0 )
{
eZDebug::writeWarning(
"None of the available languages are prioritized in the SiteLanguageList setting. An arbitrary language will be used.",
__METHOD__ );
}
return $result;
}
/*!
\static
\private
Filters the DB rows $rows by selecting the most prioritized row per
path element and returns the new row list.
\param $onlyPrioritized If false all rows are returned, if true filtering is performed.
*/
static private function filterRows( $rows, $onlyPrioritized )
{
if ( !$onlyPrioritized )
{
return $rows;
}
$idMap = array();
foreach ( $rows as $row )
{
if ( !isset( $idMap[$row['id']] ) )
{
$idMap[$row['id']] = array();
}
$idMap[$row['id']][] = $row;
}
$rows = array();
foreach ( $idMap as $id => $langRows )
{
$rows[] = eZURLAliasML::choosePrioritizedRow( $langRows );
}
return $rows;
}
/*!
\static
\private
Calculates the score of the language mask $mask based upon the currently
prioritized languages and returns it.
\note The higher the value the more the language is prioritized.
*/
static private function languageScore( $mask )
{
$prioritizedLanguages = eZContentLanguage::prioritizedLanguages();
$scores = array();
$score = 1;
$mask = (int)$mask;
krsort( $prioritizedLanguages );
foreach ( $prioritizedLanguages as $prioritizedLanguage )
{
$id = (int)$prioritizedLanguage->attribute( 'id' );
if ( $id & $mask )
{
$scores[] = $score;
}
++$score;
}
if ( count( $scores ) > 0 )
{
return max( $scores );
}
else
{
return 0;
}
}
/*!
\static
Decodes the action string $action into an internal path string and returns it.
The following actions are supported:
- eznode - argument is node ID, path is 'content/view/full/<nodeID>'
- module - argument is module/view/args, path is the arguments
- nop - a no-op, path is '/'
*/
static public function actionToUrl( $action )
{
if ( !preg_match( "#^([a-zA-Z0-9_]+):(.+)?$#", $action, $matches ) )
{
eZDebug::writeError( "Action is not of valid syntax '{$action}'" );
return false;
}
$type = $matches[1];
$args = '';
if ( isset( $matches[2] ) )
$args = $matches[2];
switch ( $type )
{
case 'eznode':
if ( !is_numeric( $args ) )
{
eZDebug::writeError( "Arguments to eznode action must be an integer, got '{$args}'" );
return false;
}
$url = 'content/view/full/' . $args;
break;
case 'module':
$url = $args;
break;
case 'nop':
$url = '/';
break;
default:
eZDebug::writeError( "Unknown action type '{$type}', cannot handle it" );
return false;
}
return $url;
}
/*!
\static
Takes the url string $url and returns the action string for it.
The following path are supported:
- content/view/full/<nodeID> => eznode:<nodeID>
If the url points to an existing module it will return module:<url>
\return false if the action could not be figured out.
*/
static public function urlToAction( $url )
{
if ( preg_match( "#^content/view/full/([0-9]+)$#", $url, $matches ) )
{
return "eznode:" . $matches[1];
}
if ( preg_match( "#^([a-zA-Z0-9]+)/#", $url, $matches ) )
{
$name = $matches[1];
$module = eZModule::exists( $name );
if ( $module !== null )
return 'module:' . $url;
}
return false;
}
/*!
\static
Makes sure the URL \a $url does not contain leading and trailing slashes (/).
\return the clean URL
*/
static public function cleanURL( $url )
{
return trim( $url, '/ ' );
}
/*!
\static
Transform a semi-valid url into one that can be stored in the url-alias system.
Removes leading/trailing slashes and repeated slashes.
\code
echo eZURLAliasML::sanitizeURL( "" ); // Result ""
echo eZURLAliasML::sanitizeURL( "users//the_dude" ); // Result "users/the_dude"
echo eZURLAliasML::sanitizeURL( "archive/products/" ); // Result "archive/products"
\endcode
\return the sanitized URL
*/
static public function sanitizeURL( $url )
{
$url = preg_replace( "#//+#", "/", trim( $url, '/' ) );
return $url;
}
/*!
\private
\static
Generates partial SELECT part of SQL based on table $table, counter $i and total length $len.
*/
static private function generateSelect( $table, $i, $len )
{
if ( $i == $len - 1 )
{
$select = "{$table}.id AS {$table}_id, {$table}.link AS {$table}_link, {$table}.text AS {$table}_text, {$table}.text_md5 AS {$table}_text_md5, {$table}.action AS {$table}_action";
}
else
{
$select = "{$table}.id AS {$table}_id, {$table}.link AS {$table}_link, {$table}.text AS {$table}_text, {$table}.text_md5 AS {$table}_text_md5";
}
return $select;
}
/*!
\private
\static
Generates full SELECT part of SQL based on table $table.
*/
static private function generateFullSelect( $table )
{
$select = "{$table}.id AS {$table}_id, {$table}.parent AS {$table}_parent, {$table}.lang_mask AS {$table}_lang_mask, {$table}.text AS {$table}_text, {$table}.text_md5 AS {$table}_text_md5, {$table}.action AS {$table}_action, {$table}.link AS {$table}_link";
return $select;
}
/*!
\private
\static
Generates WHERE part of SQL based on table $table, previous table $prevTable, counter $i, language mask $langMask and text $element.
*/
static private function generateCond( $table, $prevTable, $i, $langMask, $element )
{
$db = eZDB::instance();
if ( $i == 0 )
{
$cond = "{$table}.parent = 0 AND ({$langMask}) AND {$table}.text_md5 = " . eZURLAliasML::md5( $db, $element );
}
else
{
$cond = "{$table}.parent = {$prevTable}.link AND ({$langMask}) AND {$table}.text_md5 = " . eZURLAliasML::md5( $db, $element );
}
return $cond;
}
/*!
\private
\static
Generates WHERE part of SQL for a wildcard match based on table $table, previous table $prevTable, counter $i, language mask $langMask and wildcard text $glob.
\note $glob does not contain the wildcard character * but only the beginning of the matching text.
*/
static private function generateGlobCond( $table, $prevTable, $i, $langMask, $glob )
{
$db = eZDB::instance();
if ( $i == 0 )
{
$cond = "{$table}.parent = 0 AND ({$langMask}) AND {$table}.text LIKE '" . $db->escapeString( $glob ) . "%'";
}
else
{
$cond = "{$table}.parent = {$prevTable}.link AND ({$langMask}) AND {$table}.text LIKE '" . $db->escapeString( $glob ) . "%'";
}
return $cond;
}
/*!
\static
Converts the path \a $urlElement into a new alias url which only conists of valid characters
in the URL.
For non-Unicode setups this means character in the range a-z, numbers and _, for Unicode
setups it means all characters except space, &, ;, /, :, =, ?, [, ], (, ), -
Invalid characters are converted to -.
\return the converted element
Example with a non-Unicode setup
\example
'My car' => 'My-car'
'What is this?' => 'What-is-this'
'This & that' => 'This-that'
'myfile.tpl' => 'Myfile-tpl',
'øæå' => 'oeaeaa'
\endexample
*/
static public function convertToAlias( $urlElement, $defaultValue = false )
{
$trans = eZCharTransform::instance();
$ini = eZINI::instance();
$group = $ini->variable( 'URLTranslator', 'TransformationGroup' );
$urlElement = $trans->transformByGroup( $urlElement, $group );
if ( strlen( $urlElement ) == 0 )
{
if ( $defaultValue === false )
$urlElement = '_1';
else
{
$urlElement = $defaultValue;
$urlElement = $trans->transformByGroup( $urlElement, $group );
}
}
return $urlElement;
}
/*!
\static
Converts the path \a $urlElement into a new alias url which only conists of valid characters
in the URL.
This means character in the range a-z, numbers and _.
Invalid characters are converted to -.
\return the converted element
\example
'My car' => 'My-car'
'What is this?' => 'What-is-this'
'This & that' => 'This-that'
'myfile.tpl' => 'Myfile-tpl',
'øæå' => 'oeaeaa'
\endexample
\note Provided for creating url alias as they were before 3.10. Also used to make path_identification_string.
*/
static public function convertToAliasCompat( $urlElement, $defaultValue = false )
{
$trans = eZCharTransform::instance();
$urlElement = $trans->transformByGroup( $urlElement, "urlalias_compat" );
if ( strlen( $urlElement ) == 0 )
{
if ( $defaultValue === false )
$urlElement = '_1';
else
{
$urlElement = $defaultValue;
$urlElement = $trans->transformByGroup( $urlElement, "urlalias_compat" );
}
}
return $urlElement;
}
/*!
\static
Converts the path \a $pathURL into a new alias path with limited characters.
For more information on the conversion see convertToAlias().
\note each element in the path (separated by / (slash) ) is converted separately.
\return the converted path
*/
static public function convertPathToAlias( $pathURL )
{
$result = array();
$elements = explode( '/', $pathURL );
foreach ( $elements as $element )
{
$element = eZURLAliasML::convertToAlias( $element );
$result[] = $element;
}
return implode( '/', $result );
}
/*!
\static
Grabs nodeID from action string.
\return nodeID on success, \c false otherwise.
*/
static public function nodeIDFromAction( $action )
{
$nodeID = false;
$pos = strpos( $action, 'eznode:' );
if ( $pos === 0 ) // make sure $action starts from 'eznode:'
$nodeID = substr( $action, strlen( 'eznode:' ) );
return $nodeID;
}
/*!
\static
Wraps a database md5 call around the string $text and returns the new SQL for it.
\param $escape If true it will lowercase the text and escape it.
\note If the database is Oracle and the text is empty the MD5 is computed by PHP
and returned.
*/
static private function md5( $db, $text, $escape = true )
{
// Special case for Oracle since it cannot calculate MD5 for empty strings
if ( strlen( $text ) == 0 && $db->databaseName() == 'oracle' )
return "'" . $db->escapeString( md5( $text ) ) . "'";
if ( $escape )
$text = $db->escapeString( eZURLAliasML::strtolower( $text ) );
return $db->md5( "'" . $text . "'" );
}
static function getNewID()
{
$db = eZDB::instance();
if ( $db->supportsDefaultValuesInsertion() )
{
$db->query( 'INSERT INTO ezurlalias_ml_incr DEFAULT VALUES' );
}
else
{
// can not use VALUES(DEFAULT), because of http://bugs.mysql.com/bug.php?id=42270
$db->query( 'INSERT INTO ezurlalias_ml_incr(id) VALUES(NULL)' );
}
return $db->lastSerialID( 'ezurlalias_ml_incr', 'id' );
}
}
?>
| jim835/qscene_ez | kernel/classes/ezurlaliasml.php | PHP | gpl-2.0 | 89,926 |
/* Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */
#include "my_global.h"
#include "my_pthread.h"
#include "table_threads.h"
#include "sql_parse.h"
#include "pfs_instr_class.h"
#include "pfs_instr.h"
THR_LOCK table_threads::m_table_lock;
static const TABLE_FIELD_TYPE field_types[]=
{
{
{ C_STRING_WITH_LEN("THREAD_ID") },
{ C_STRING_WITH_LEN("bigint(20)") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("NAME") },
{ C_STRING_WITH_LEN("varchar(128)") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("TYPE") },
{ C_STRING_WITH_LEN("varchar(10)") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("PROCESSLIST_ID") },
{ C_STRING_WITH_LEN("bigint(20)") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("PROCESSLIST_USER") },
{ C_STRING_WITH_LEN("varchar(16)") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("PROCESSLIST_HOST") },
{ C_STRING_WITH_LEN("varchar(60)") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("PROCESSLIST_DB") },
{ C_STRING_WITH_LEN("varchar(64)") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("PROCESSLIST_COMMAND") },
{ C_STRING_WITH_LEN("varchar(16)") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("PROCESSLIST_TIME") },
{ C_STRING_WITH_LEN("bigint(20)") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("PROCESSLIST_STATE") },
{ C_STRING_WITH_LEN("varchar(64)") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("PROCESSLIST_INFO") },
{ C_STRING_WITH_LEN("longtext") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("PARENT_THREAD_ID") },
{ C_STRING_WITH_LEN("bigint(20)") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("ROLE") },
{ C_STRING_WITH_LEN("varchar(64)") },
{ NULL, 0}
},
{
{ C_STRING_WITH_LEN("INSTRUMENTED") },
{ C_STRING_WITH_LEN("enum(\'YES\',\'NO\')") },
{ NULL, 0}
}
};
TABLE_FIELD_DEF
table_threads::m_field_def=
{ 14, field_types };
PFS_engine_table_share
table_threads::m_share=
{
{ C_STRING_WITH_LEN("threads") },
&pfs_updatable_acl,
&table_threads::create,
NULL, /* write_row */
NULL, /* delete_all_rows */
NULL, /* get_row_count */
1000, /* records */
sizeof(PFS_simple_index), /* ref length */
&m_table_lock,
&m_field_def,
false /* checked */
};
PFS_engine_table* table_threads::create()
{
return new table_threads();
}
table_threads::table_threads()
: cursor_by_thread(& m_share),
m_row_exists(false)
{}
void table_threads::make_row(PFS_thread *pfs)
{
pfs_lock lock;
PFS_stage_class *stage_class;
pfs_lock processlist_info_lock;
PFS_thread_class *safe_class;
m_row_exists= false;
/* Protect this reader against thread termination */
pfs->m_lock.begin_optimistic_lock(&lock);
safe_class= sanitize_thread_class(pfs->m_class);
if (unlikely(safe_class == NULL))
return;
m_row.m_thread_internal_id= pfs->m_thread_internal_id;
m_row.m_parent_thread_internal_id= pfs->m_parent_thread_internal_id;
m_row.m_processlist_id= pfs->m_processlist_id;
m_row.m_name= safe_class->m_name;
m_row.m_name_length= safe_class->m_name_length;
m_row.m_username_length= pfs->m_username_length;
if (unlikely(m_row.m_username_length > sizeof(m_row.m_username)))
return;
if (m_row.m_username_length != 0)
memcpy(m_row.m_username, pfs->m_username, m_row.m_username_length);
m_row.m_hostname_length= pfs->m_hostname_length;
if (unlikely(m_row.m_hostname_length > sizeof(m_row.m_hostname)))
return;
if (m_row.m_hostname_length != 0)
memcpy(m_row.m_hostname, pfs->m_hostname, m_row.m_hostname_length);
m_row.m_dbname_length= pfs->m_dbname_length;
if (unlikely(m_row.m_dbname_length > sizeof(m_row.m_dbname)))
return;
if (m_row.m_dbname_length != 0)
memcpy(m_row.m_dbname, pfs->m_dbname, m_row.m_dbname_length);
m_row.m_command= pfs->m_command;
m_row.m_start_time= pfs->m_start_time;
stage_class= find_stage_class(pfs->m_stage);
if (stage_class != NULL)
{
m_row.m_processlist_state_ptr= stage_class->m_name + stage_class->m_prefix_length;
m_row.m_processlist_state_length= stage_class->m_name_length - stage_class->m_prefix_length;
}
else
{
m_row.m_processlist_state_length= 0;
}
/* Protect this reader against info attribute changes. */
pfs->m_processlist_info_lock.begin_optimistic_lock(&processlist_info_lock);
m_row.m_processlist_info_ptr= & pfs->m_processlist_info[0];
m_row.m_processlist_info_length= pfs->m_processlist_info_length;
if (! pfs->m_processlist_info_lock.end_optimistic_lock(& processlist_info_lock))
{
/*
Column PROCESSLIST_INFO is being updated.
Do not discard the entire row.
Do not loop waiting for a stable value.
Just return NULL values for this column.
*/
m_row.m_processlist_info_length= 0;
}
m_row.m_enabled_ptr= &pfs->m_enabled;
if (pfs->m_lock.end_optimistic_lock(& lock))
m_row_exists= true;
}
int table_threads::read_row_values(TABLE *table,
unsigned char *buf,
Field **fields,
bool read_all)
{
Field *f;
if (unlikely(! m_row_exists))
return HA_ERR_RECORD_DELETED;
/* Set the null bits */
DBUG_ASSERT(table->s->null_bytes == 2);
buf[0]= 0;
buf[1]= 0;
for (; (f= *fields) ; fields++)
{
if (read_all || bitmap_is_set(table->read_set, f->field_index))
{
switch(f->field_index)
{
case 0: /* THREAD_ID */
set_field_ulonglong(f, m_row.m_thread_internal_id);
break;
case 1: /* NAME */
set_field_varchar_utf8(f, m_row.m_name, m_row.m_name_length);
break;
case 2: /* TYPE */
if (m_row.m_processlist_id != 0)
set_field_varchar_utf8(f, "FOREGROUND", 10);
else
set_field_varchar_utf8(f, "BACKGROUND", 10);
break;
case 3: /* PROCESSLIST_ID */
if (m_row.m_processlist_id != 0)
set_field_ulonglong(f, m_row.m_processlist_id);
else
f->set_null();
break;
case 4: /* PROCESSLIST_USER */
if (m_row.m_username_length > 0)
set_field_varchar_utf8(f, m_row.m_username,
m_row.m_username_length);
else
f->set_null();
break;
case 5: /* PROCESSLIST_HOST */
if (m_row.m_hostname_length > 0)
set_field_varchar_utf8(f, m_row.m_hostname,
m_row.m_hostname_length);
else
f->set_null();
break;
case 6: /* PROCESSLIST_DB */
if (m_row.m_dbname_length > 0)
set_field_varchar_utf8(f, m_row.m_dbname,
m_row.m_dbname_length);
else
f->set_null();
break;
case 7: /* PROCESSLIST_COMMAND */
if (m_row.m_processlist_id != 0)
set_field_varchar_utf8(f, command_name[m_row.m_command].str,
command_name[m_row.m_command].length);
else
f->set_null();
break;
case 8: /* PROCESSLIST_TIME */
if (m_row.m_start_time)
{
time_t now= my_time(0);
ulonglong elapsed= (now > m_row.m_start_time ? now - m_row.m_start_time : 0);
set_field_ulonglong(f, elapsed);
}
else
f->set_null();
break;
case 9: /* PROCESSLIST_STATE */
if (m_row.m_processlist_state_length > 0)
set_field_varchar_utf8(f, m_row.m_processlist_state_ptr,
m_row.m_processlist_state_length);
else
f->set_null();
break;
case 10: /* PROCESSLIST_INFO */
if (m_row.m_processlist_info_length > 0)
set_field_longtext_utf8(f, m_row.m_processlist_info_ptr,
m_row.m_processlist_info_length);
else
f->set_null();
break;
case 11: /* PARENT_THREAD_ID */
if (m_row.m_parent_thread_internal_id != 0)
set_field_ulonglong(f, m_row.m_parent_thread_internal_id);
else
f->set_null();
break;
case 12: /* ROLE */
f->set_null();
break;
case 13: /* INSTRUMENTED */
set_field_enum(f, (*m_row.m_enabled_ptr) ? ENUM_YES : ENUM_NO);
break;
default:
DBUG_ASSERT(false);
}
}
}
return 0;
}
int table_threads::update_row_values(TABLE *table,
const unsigned char *old_buf,
unsigned char *new_buf,
Field **fields)
{
Field *f;
enum_yes_no value;
for (; (f= *fields) ; fields++)
{
if (bitmap_is_set(table->write_set, f->field_index))
{
switch(f->field_index)
{
case 0: /* THREAD_ID */
case 1: /* NAME */
case 2: /* TYPE */
case 3: /* PROCESSLIST_ID */
case 4: /* PROCESSLIST_USER */
case 5: /* PROCESSLIST_HOST */
case 6: /* PROCESSLIST_DB */
case 7: /* PROCESSLIST_COMMAND */
case 8: /* PROCESSLIST_TIME */
case 9: /* PROCESSLIST_STATE */
case 10: /* PROCESSLIST_INFO */
case 11: /* PARENT_THREAD_ID */
case 12: /* ROLE */
return HA_ERR_WRONG_COMMAND;
case 13: /* INSTRUMENTED */
value= (enum_yes_no) get_field_enum(f);
*m_row.m_enabled_ptr= (value == ENUM_YES) ? true : false;
break;
default:
DBUG_ASSERT(false);
}
}
}
return 0;
}
| mmplayer/MySQL | storage/perfschema/table_threads.cc | C++ | gpl-2.0 | 10,137 |
/*
* Copyright (C) 2013-2016 Parallel and Reconfigurable Computing Group, University of Auckland.
*
* Authors: <http://homepages.engineering.auckland.ac.nz/~parallel/ParallelIT/People.html>
*
* This file is part of Pyjama, a Java implementation of OpenMP-like directive-based
* parallelisation compiler and its runtime routines.
*
* Pyjama is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pyjama is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Pyjama. If not, see <http://www.gnu.org/licenses/>.
*/
package pj.pr.task;
public abstract class VirtualTarget {
protected String targetName;
public abstract void submit(TargetTask<?> task);
public String targetName() {
return this.targetName;
}
}
| ParallelAndReconfigurableComputing/Pyjama | src/pj/pr/task/VirtualTarget.java | Java | gpl-2.0 | 1,193 |
/*
* Modern effects for a modern Streamer
* Copyright (C) 2017 Michael Fabian Dirks
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "gs-indexbuffer.hpp"
#include <stdexcept>
#include "gs-limits.hpp"
#include "obs/gs/gs-helper.hpp"
streamfx::obs::gs::index_buffer::index_buffer(uint32_t maximumVertices)
{
this->reserve(maximumVertices);
auto gctx = streamfx::obs::gs::context();
_index_buffer = gs_indexbuffer_create(gs_index_type::GS_UNSIGNED_LONG, this->data(), maximumVertices, GS_DYNAMIC);
}
streamfx::obs::gs::index_buffer::index_buffer() : index_buffer(MAXIMUM_VERTICES) {}
streamfx::obs::gs::index_buffer::index_buffer(index_buffer& other) : index_buffer(static_cast<uint32_t>(other.size()))
{
std::copy(other.begin(), other.end(), this->end());
}
streamfx::obs::gs::index_buffer::index_buffer(std::vector<uint32_t>& other)
: index_buffer(static_cast<uint32_t>(other.size()))
{
std::copy(other.begin(), other.end(), this->end());
}
streamfx::obs::gs::index_buffer::~index_buffer()
{
auto gctx = streamfx::obs::gs::context();
gs_indexbuffer_destroy(_index_buffer);
}
gs_indexbuffer_t* streamfx::obs::gs::index_buffer::get()
{
return get(true);
}
gs_indexbuffer_t* streamfx::obs::gs::index_buffer::get(bool refreshGPU)
{
if (refreshGPU) {
auto gctx = streamfx::obs::gs::context();
gs_indexbuffer_flush(_index_buffer);
}
return _index_buffer;
}
| Xaymar/obs-stream-effects | source/obs/gs/gs-indexbuffer.cpp | C++ | gpl-2.0 | 2,065 |
/*
* ----------------------------------------------------------------------------
* Copyright (c) 2012-2013, xSky <guozhw at gmail dot com>
* All rights reserved.
* Distributed under GPL license.
* ----------------------------------------------------------------------------
*/
#include <event.h>
#include "xBlog.h"
#include "xMysqlPool.h"
#include "xConfig.h"
#include "xBlogCache.h"
xBlog::xBlog()
{
memset(szDir, 0, sizeof(szDir));
#ifdef WIN32
WSADATA WSAData;
WSAStartup(0x101, &WSAData);
#else
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
{
log_error("void xBlog::xBlog() SIGPIPE error\n");;
}
#endif
}
xBlog::~xBlog()
{
}
bool xBlog::Init()
{
StartTime = time(NULL);
xBlogPageTemplate::GetInstance()->Init();
strncpy(szDir, Config::GetInstance()->strRootFullPath.c_str(),
Config::GetInstance()->strRootFullPath.length());
return true;
}
void xBlog::OnTimer()
{
//log_debug("void xBlog::OnTimer()\n");
xBlogCache::GetInstance()->OnTimer();
}
void xBlog::DebugHttpHeader(struct evhttp_request *req)
{
struct evkeyval *header;
struct evkeyvalq *headers;
headers = evhttp_request_get_input_headers(req);
for (header = headers->tqh_first; header; header = header->next.tqe_next)
{
log_debug("%s: %s\n", header->key, header->value);
}
}
const char *xBlog::DebugHttpGetCommand(struct evhttp_request *req)
{
const char *cmdtype;
switch (evhttp_request_get_command(req))
{
case EVHTTP_REQ_GET:
cmdtype = "GET";
break;
case EVHTTP_REQ_POST:
cmdtype = "POST";
break;
case EVHTTP_REQ_HEAD:
cmdtype = "HEAD";
break;
case EVHTTP_REQ_PUT:
cmdtype = "PUT";
break;
case EVHTTP_REQ_DELETE:
cmdtype = "DELETE";
break;
case EVHTTP_REQ_OPTIONS:
cmdtype = "OPTIONS";
break;
case EVHTTP_REQ_TRACE:
cmdtype = "TRACE";
break;
case EVHTTP_REQ_CONNECT:
cmdtype = "CONNECT";
break;
case EVHTTP_REQ_PATCH:
cmdtype = "PATCH";
break;
default:
cmdtype = "unknown";
break;
}
log_debug("Received a %s request for %s \n", cmdtype, evhttp_request_get_uri(req));
return cmdtype;
}
void xBlog::HttpParseURL(struct evhttp_request *req, struct evkeyvalq *evMyheader)
{
const char *xBlog_query;
xBlog_query = evhttp_uri_get_query(evhttp_request_get_evhttp_uri(req));
evhttp_parse_query_str(xBlog_query, evMyheader);
}
void xBlog::GetHttpPostData(struct evhttp_request *req, struct evkeyvalq *evdata)
{
evbuffer *pevBuf = evhttp_request_get_input_buffer(req);
int data_len = evbuffer_get_length(pevBuf);
char *pbuffer = (char *) malloc(data_len + 1);
memset(pbuffer, 0, data_len + 1);
evbuffer_copyout(pevBuf, pbuffer, data_len);
log_debug("%s\r\n", pbuffer);
evhttp_parse_query_str(pbuffer, evdata);
free(pbuffer);
}
void xBlog::SendHttpResphone(struct evhttp_request *req, const string & strData)
{
struct evbuffer *buf = evbuffer_new();
if (NULL==buf)
{
log_error("failed to create response buffer\r\n");
return;
}
evbuffer_add_printf(buf, "%s", strData.c_str());
evhttp_add_header(evhttp_request_get_output_headers(req),
"Content-Type", "text/html; charset=utf-8");
evhttp_send_reply(req, 200, "OK", buf);
evbuffer_free(buf);
}
int xBlog::BindSocket(const char *ip, uint16 port)
{
int skt;
skt = socket(AF_INET, SOCK_STREAM, 0);
if (skt < 0)
{
log_error("socket error, nfd=%d \r\n", skt);
return -1;
}
#ifdef _WIN32
int flag = 1;
ioctlsocket(skt, FIONBIO, (unsigned long *) &flag);
#else
/* set socket nonblocking */
int flags;
if ((flags = fcntl(skt, F_GETFL, NULL)) < 0 || fcntl(skt, F_SETFL, flags | O_NONBLOCK) == -1)
{
log_error("O_NONBLOCK error, skt=%d \r\n", skt);
return -1;
}
/* set socket closeonexec */
if ((flags = fcntl(skt, F_GETFD, NULL)) < 0 || fcntl(skt, F_SETFD, flags | FD_CLOEXEC) == -1)
{
log_error("FD_CLOEXEC error, skt=%d \r\n", skt);
return -1;
}
#endif
int on = 1;
setsockopt(skt, SOL_SOCKET, SO_KEEPALIVE, (const char *) &on, sizeof(on));
setsockopt(skt, SOL_SOCKET, SO_REUSEADDR, (const char *) &on, sizeof(on));
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ip);
addr.sin_port = htons(port);
if (bind(skt, (struct sockaddr *) &addr, sizeof(addr)) < 0)
{
log_error("bind %s %d error\r\n", ip, port);
return -1;
}
if (listen(skt, 128) < 0)
{
log_error("listen %s %d error\r\n", ip, port);
return -1;
}
return skt;
}
bool xBlog::Run(const char *ip, uint16 port, uint32 timeout_secs, uint32 nthreads)
{
int ret = -1;
int skt = BindSocket(ip, port);
if (skt < 0)
{
log_error("BindSocket %s %d error\r\n", ip, port);
return false;
}
#ifdef _WIN32
HANDLE ths[128];
for (uint32 i = 0; i < nthreads; i++)
{
struct event_base *base = event_base_new();
if (base == NULL)
{
return false;
}
struct evhttp *httpd = evhttp_new(base);
if (httpd == NULL)
{
return false;
}
ret = evhttp_accept_socket(httpd, skt);
if (r != 0)
{
return false;
}
SetRouteTable(httpd);
ths[i] = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE) xBlog::Dispatch, base, NULL, NULL);
log_info("%d %d \r\n", i, ths[i]);
if (ret != 0)
{
return false;
}
}
#else
pthread_t ths[128];
for (uint32 i = 0; i < nthreads; i++)
{
struct event_base *base = event_base_new();
if (base == NULL)
{
return false;
}
struct evhttp *httpd = evhttp_new(base);
if (httpd == NULL)
{
return false;
}
ret = evhttp_accept_socket(httpd, skt);
if (ret != 0)
{
return false;
}
SetRouteTable(httpd);
ret = pthread_create(&ths[i], NULL, xBlog::Dispatch, base);
log_info("%d %d \r\n", i, ths[i]);
if (ret != 0)
{
return false;
}
}
/*
for (int i = 0; i < nthreads; i++)
{
pthread_join(ths[i], NULL);
}
*/
#endif
return true;
}
void *xBlog::Dispatch(void *arg)
{
if (NULL==arg)
{
log_error("error arg is null\n");
return NULL;
}
event_base_dispatch((struct event_base *) arg);
return NULL;
}
void xBlog::SetRouteTable(evhttp * http)
{
evhttp_set_cb(http, "/download", xBlogPage::DownloadCallback, this); // 测试
evhttp_set_cb(http, "/post", xBlogPage::PostRequestCallback, this); // 请求文章
evhttp_set_cb(http, "/guestbook", xBlogPage::GuestbookCallback, this); // 查看-留言
evhttp_set_cb(http, "/postmessage", xBlogPage::GuestPostCallback, this); // 添加-评论留言
evhttp_set_cb(http, "/catalog", xBlogPage::CatalogRequestCallback, this); // 分类
evhttp_set_cb(http, "/", xBlogPage::IndexRequestCallback, this); // 首页
evhttp_set_cb(http, "/page", xBlogPage::PageRequestCallback, this); // 页面
// 管理后台功能
evhttp_set_cb(http, "/admin", xBlogPage::AdminCallback, this); // 管理后台
evhttp_set_cb(http, "/checklogin", xBlogPage::AdminCheckLoginCallback, this); // 权限验证
evhttp_set_cb(http, "/shell", xBlogPage::AdminShellCallback, this); // 测试
evhttp_set_cb(http, "/status", xBlogPage::AdminStatusCallback, this); // 测试
evhttp_set_cb(http, "/postmanager", xBlogPage::AdminPostManagerCallback, this); // 文章管理
evhttp_set_cb(http, "/siteconfig", xBlogPage::AdminSiteConfigCallback, this); // 网站配置参数管理
evhttp_set_cb(http, "/links", xBlogPage::AdminLinksCallback, this); // 链接管理
evhttp_set_cb(http, "/catalogset", xBlogPage::AdminCatalogCallback, this); // 链接管理
evhttp_set_cb(http, "/comments", xBlogPage::AdminCommentsCallback, this); // 留言评论管理
evhttp_set_cb(http, "/system", xBlogPage::AdminSystemCallback, this); // 系统配置
evhttp_set_cb(http, "/user", xBlogPage::AdminUserCallback, this); // 系统配置
evhttp_set_timeout(http, Config::GetInstance()->xBlogAppConfig.HttpdTimeOut);
evhttp_set_gencb(http, xBlogPage::SendDocumentCallback, this);
}
void xBlog::StartMysqlPool()
{
xBlogData::GetInstance()->pMysqlPool = MysqlPool::GetInstance();
xBlogData::GetInstance()->pMysqlPool->Init(Config::GetInstance()->xBlogMysqlcfg.ipaddr.c_str(),
Config::GetInstance()->xBlogMysqlcfg.username.c_str(),
Config::GetInstance()->xBlogMysqlcfg.passwd.c_str(),
Config::GetInstance()->xBlogMysqlcfg.dbname.c_str());
xBlogData::GetInstance()->pMysqlPool->ConnectDB(Config::GetInstance()->xBlogMysqlcfg.poolsize);
bool bRet = Config::GetInstance()->LoadxBlogSiteConfig();
if (!bRet)
{
log_error("xBlog::StartMysqlPool() site config error, exit\r\n");
exit(0);
}
}
| caibaibai/xblog | xBlog.cpp | C++ | gpl-2.0 | 10,012 |
/**
* <p>Title: ClipboardListener.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: NASA Ames Research Center</p>
* @author Ronald Mak & Luca Severini <lucaseverini@mac.com>
* @version 2.0
*/
package rope1401;
import java.awt.*;
import java.awt.datatransfer.*;
public class ClipboardListener extends Thread implements ClipboardOwner
{
private final Clipboard sysClip;
RopeFrame mainFrame;
public boolean hasValidContent;
ClipboardListener (RopeFrame parent)
{
mainFrame = parent;
// This is ugly but necessary because mainFrame.clipboardListener is used in canPaste() below
mainFrame.clipboardListener = this;
sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
hasValidContent = checkContent(sysClip.getContents(this));
start();
}
@Override
public void run()
{
try
{
regainOwnership(sysClip.getContents(this));
}
catch(Exception ex) {}
while(true)
{
try
{
Thread.sleep(100);
}
catch(InterruptedException ex) {}
}
}
@Override
public void lostOwnership(Clipboard c, Transferable t)
{
// Sleeps a little bit to let the clipboard be ready and avoid exceptions...
try
{
sleep(100);
}
catch(InterruptedException ex)
{
System.out.println("Exception: " + ex);
}
Transferable contents = sysClip.getContents(this);
hasValidContent = checkContent(contents);
regainOwnership(contents);
}
void regainOwnership(Transferable t)
{
sysClip.setContents(t, this);
}
boolean checkContent(Transferable content)
{
return ((content != null) && content.isDataFlavorSupported(DataFlavor.stringFlavor));
}
}
| lucaseverini/ROPE | src/rope1401/ClipboardListener.java | Java | gpl-2.0 | 1,713 |
<?php
namespace Solution\MongoAggregation\Pipeline\Operators\Date;
use Solution\MongoAggregation\Pipeline\Operators\Operator;
class Minute extends Operator
{
function getName()
{
return 'minute';
}
} | f1nder/SolutionPipelineBuilder | src/Solution/MongoAggregation/Pipeline/Operators/Date/Minute.php | PHP | gpl-2.0 | 223 |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery-ui-1.9.2.js
//= require jquery_ujs
//= require jquery_mods
//= require jquery.mobile.custom.js
//= require jquery.waypoints.js
//= require bootstrap
//= require bootstrap-notify.js
//= require notify.js
//= require intro.js
//= require modern-business/modern-business.js
//= require cocoon
//= require smart_listing
//= require highcharts/highcharts.js
//= require highcharts/highcharts-more.js
//= require highcharts/highcharts-3d.js
//= require startup.js
//= require scrollspy.js
//= require typeahead.bundle.js
//= require charts.js
//= require reports.js
//= require stats.js
//= require users.js
//= require dashboard.js
//= require ls_reports.js
//= require ls_reports_filter.js
//= require ls_reports_graph.js
//= require ls_reports_spreadsheet.js
//= require_tree ./assignments
//= require sync_triggers.js
//= require dataTables/dataTables.js
//= require dataTables/extensions/TableTools/js/dataTables.tableTools.js
//= require sessions.js
//= require animations.js
//= require form-utils.js
//= require select2
//= require simplemde/simplemde.min.js
| PatrickVChung/reindeer | app/assets/javascripts/application.js | JavaScript | gpl-2.0 | 1,679 |
package com.lgvalle.beaufitulphotos.fivehundredpxs.model;
import com.lgvalle.beaufitulphotos.R;
/**
* Created by luis.gonzalez on 23/07/14.
* Enum to represent service features
*/
public enum Feature {
Popular("popular", R.string.feature_popular),
HighestRated("highest_rated", R.string.feature_highest_rated);
private final String param;
private final int title;
Feature(String param, int title) {
this.param = param;
this.title = title;
}
public String getParam() {
return param;
}
public int getTitle() {
return title;
}
}
| lgvalle/Beautiful-Photos | app/src/main/java/com/lgvalle/beaufitulphotos/fivehundredpxs/model/Feature.java | Java | gpl-2.0 | 553 |
/**
* Copyright (C) 2007-2016 52North Initiative for Geospatial Open Source
* Software GmbH
*
* 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.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0.
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public License
* version 2 and the aforementioned licenses.
*
* 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.
*
* Contact: Benno Schmidt and Martin May, 52North Initiative for Geospatial
* Open Source Software GmbH, Martin-Luther-King-Weg 24, 48155 Muenster,
* Germany, info@52north.org
*/
package org.n52.v3d.triturus.gisimplm;
import org.n52.v3d.triturus.vgis.*;
import org.n52.v3d.triturus.core.T3dException;
import java.util.ArrayList;
/**
* Class to manage a grid holding elevation values. The grid is assumed
* to be parallel in line with the <i>x</i>- and <i>y</i>-axis. It might be specified
* as vertex-based (so-called <i>"Lattice"</i>) or cell-based
* (<i>"Grid"</i>;, often reffered to as "Raster").
* Note that grid's values may left unset, since for all grid elements
* (vertices or cells) a "no data"-flag can be set.<br/>
* <br/>
* Note: Within this framework, elevation-grids should be used to hold
* georeferenced <i>z</i>-value only, e.g terrain elevation values, groundwater
* levels, geologic depth data, height values inside the atmosphere etc.
* To hold thematic ("non-georeferenced") floating-point data such as
* temperatures, humidities, wind speeds, air pressure values etc. the
* class <tt>{@link GmSimpleFloatGrid}</tt> shall be preferred.
*
* @author Benno Schmidt
*/
public class GmSimpleElevationGrid extends VgElevationGrid
{
private GmSimple2dGridGeometry mGeom;
private double[][] mVal;
private boolean[][] mIsSetFl;
private boolean mLatticeMode = false;
private String mTheme = "Elevation";
/**
* Constructor. This will generate a grid will all elements unset.
*
* @param nCols Number of grid cells in <i>x</i>-direction (columns)
* @param nRows Number of grid cells in <i>y</i>-direction (rows)
* @param origin Origin point
* @param deltaX Cell-size in <i>x</i>-direction
* @param deltaY Cell-size in <i>y</i>-direction
*/
public GmSimpleElevationGrid(
int nCols, int nRows,
VgPoint origin,
double deltaX, double deltaY)
{
// TODO: Im Folgenden besser die static-Methoden aus GmSimpleFloatGrid
// nutzen, um Redundanzen zu vermeiden. (-> nächstes Refactoring)
mGeom = new GmSimple2dGridGeometry(
nCols, nRows,
origin,
deltaX, deltaY);
mVal = new double[nRows][nCols];
mIsSetFl = new boolean[nRows][nCols];
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nCols; j++) {
mIsSetFl[i][j] = false;
}
}
this.setName("unnamed elevation grid");
}
/**
* Constructor. This will generate a grid will all elements unset.
*
* @param geom Existing grid geometry
*/
public GmSimpleElevationGrid(GmSimple2dGridGeometry geom)
{
mGeom = geom;
int nRows = mGeom.numberOfRows();
int nCols = mGeom.numberOfColumns();
mVal = new double[nRows][nCols];
mIsSetFl = new boolean[nRows][nCols];
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nCols; j++) {
mIsSetFl[i][j] = false;
}
}
this.setName("unnamed elevation grid");
}
/**
* provides thematic meta-information.
*
* @return List of strings
*/
public ArrayList<String> getThematicAttributes()
{
ArrayList<String> list = new ArrayList<String>();
list.add(mTheme);
return list;
}
/**
* returns the object geometry.
*
* @return {@link GmSimple2dGridGeometry}-object
*/
public VgGeomObject getGeometry() {
return mGeom;
}
/**
* always returns <i>false</i>, since a {@link GmSimpleElevationGrid}
* consists of one and only geo-object.
*
* @return <i>false</i>
*/
public boolean isCollection() {
return false;
}
/**
* always returns this {@link GmSimpleElevationGrid} itself.
*
* @param i (here always 0)
* @return Elevation-grid itself
* @throws T3dException
*/
public VgFeature getFeature(int i) throws T3dException
{
if (i != 0)
throw new T3dException("Index out of bounds." );
// else:
return this;
}
public int numberOfFeatures() {
return 1;
}
public int numberOfSubFeatures() {
return numberOfFeatures();
}
public int numberOfColumns() {
return mGeom.numberOfColumns();
}
public int numberOfRows() {
return mGeom.numberOfRows();
}
/**
* returns the grid's cell-size in <i>x</i>-direction.
*/
public double getDeltaX() {
return mGeom.getDeltaX();
}
/**
* returns the grid's cell-size in <i>y</i>-direction.
*/
public double getDeltaY() {
return mGeom.getDeltaY();
}
/**
* sets vertex-based interpretation mode. It always holds that either
* vertex-based or cell-based interpretation mode is set.
*/
public void setLatticeInterpretation() {
mLatticeMode = true;
}
/**
* sets cell-based interpretation mode.
*
* @see this{@link #setLatticeInterpretation()}
*/
public void setGridInterpretation() {
mLatticeMode = false;
}
/**
* returns the information, whether vertex-based interpretation mode is
* set.
*
* @return <i>true</i> for vertex-based, <i>false</i> for cell-based interpretation
* @see this{@link #setLatticeInterpretation()}
*/
public boolean isLatticeInterpretion() {
return mLatticeMode;
}
/**
* sets vertex-based interpretation mode to the given value.
*
* @param latticeMode <i>true</i> for vertex-based, <i>false</i> for cell-based interpretation
* @see this{@link #setLatticeInterpretation()}
*/
public void setLatticeInterpretation(boolean latticeMode) {
mLatticeMode = latticeMode;
}
/**
* sets the elevation value <tt>z</tt> for the row index <tt>row</tt> and
* the column index <tt>col</tt>. If one of the assertions
* <i>0 <= row < this.numberOfRows(),
* 0 <= col < this.numberOfColumns()</i>
* is violated, a <tt>T3dException</tt> will be thrown. Post-condition:
* <tt>this.isSet(row, col) = true</tt>
*
* @param row Row-index
* @param col Column-index
* @param z Elevation-value
*/
public void setValue(int row, int col, double z) throws T3dException
{
try {
double zOld = mVal[row][col];
mVal[row][col] = z;
mIsSetFl[row][col] = true;
this.updateZBounds(zOld, z);
}
catch (Exception e) {
throw new T3dException(
"Could not set grid value (" + row + ", " + col + ").");
}
}
/**
* returns <i>true</i>, if an elevation-value is assigned to a given
* grid element. If one of the assertions
* <i>0 <= row < this.numberOfRows(),
* 0 <= col < this.numberOfColumns()</i>
* is violated, a <tt>T3dException</tt> will be thrown.
*
* @param row Row index
* @param col Column index
* @throws T3dException
*/
public boolean isSet(int row, int col) throws T3dException
{
try {
return mIsSetFl[row][col];
}
catch (Exception e) {
throw new T3dException(e.getMessage());
}
}
/**
* returns <i>true</i>, if all <i>z</i>-values are assigned to all grid elements.
*/
public boolean isSet()
{
for (int i = 0; i < this.numberOfRows(); i++) {
for (int j = 0; j < this.numberOfColumns(); j++) {
if (!mIsSetFl[i][j]) return false;
}
}
return true;
}
/**
* defines a grid element (vertex or cell) as unset ("nodata").
* If one of the assertions
* <i>0 <= row < this.numberOfRows(),
* 0 <= col < this.numberOfColumns()</i>
* is violated, a <tt>T3dException</tt> will be thrown. Post-condition:
* <tt>this.isIsSet(row, col) = false</tt><p>
*
* @param row Row index
* @param col Column index
* @throws T3dException
*/
public void unset(int row, int col) throws T3dException
{
try {
mIsSetFl[row][col] = false;
}
catch (Exception e) {
throw new T3dException(e.getMessage());
}
}
/**
* gets the elevation-value for the row-index <tt>row</tt> and the
* column-index <tt>col</tt>.
* If one of the assertions
* <i>0 <= row < this.numberOfRows(),
* 0 <= col < this.numberOfColumns()</i>
* is violated, or if the queried element is unset, a
* <tt>T3dException</tt> will be thrown. Post-condition:
* <tt>this.isIsSet(row, col) = false</tt><p>
*
* @param row Row index
* @param col Column index
* @throws T3dException
*/
public double getValue(int row, int col) throws T3dException
{
try {
if (mIsSetFl[row][col]) {
return mVal[row][col];
} else {
throw new T3dException("Tried to access unset grid element.");
}
}
catch (Exception e) {
throw new T3dException(
"Illegal grid element access. " + e.getMessage());
}
}
/**
* gets the elevation-value for the georeferenced position <tt>pPos</tt>.
* Note that the method performs a <i>bilinear</i> interpolation. If the
* given position is outside the elevation grid's extent, the method will
* return <i>null</i>. If the position-points coordinate reference system
* is not compatible to the elevation-grids reference system, a
* {@link T3dSRSException} will be thrown.
*
* @param pos Position (x, y)
* @return Elevation (z) as {@link Double}-object or <i>null</i>
*/
public Double getValue(VgPoint pos) throws T3dSRSException
{
if (pos == null) {
return null;
}
if (!(pos.getSRS() == null && mGeom.getSRS() == null)) {
if (!(pos.getSRS().equalsIgnoreCase(mGeom.getSRS()))) {
throw new T3dSRSException();
}
}
float[] idx = mGeom.getIndicesAsFloat(pos);
if (idx == null) {
return null;
}
float is = idx[0], js = idx[1];
int row = (int) idx[0], col = (int) idx[1];
if (
mIsSetFl[row][col] &&
mIsSetFl[row + 1][col] &&
mIsSetFl[row][col + 1] &&
mIsSetFl[row + 1][col + 1])
{
double lambda = js - ((float) col), my = is - ((float) row);
return
mVal[row][col] * (1.f - my) * (1.f - lambda) +
mVal[row + 1][col] * my * (1.f - lambda) +
mVal[row][col + 1] * (1.f - my) * lambda +
mVal[row + 1][col + 1] * my * lambda;
}
// else:
return null;
}
/**
* returns the elevation grid's bounding-box. Note that this extent
* depends on the grid-type (vertex-based "lattice" mode or
* cell-based "grid" mode)!
*
* @return 3D-bounding-box, or <i>null</i> if an error occurs
* @see GmSimpleElevationGrid#setLatticeInterpretation
* @see GmSimpleElevationGrid#setGridInterpretation
*/
public VgEnvelope envelope()
{
VgEnvelope env = this.getGeometry().envelope();
double xMin = env.getXMin();
double xMax = env.getXMax();
double yMin = env.getYMin();
double yMax = env.getYMax();
if (!mLatticeMode) {
double dx = 0.5 * this.getDeltaX();
xMin -= dx;
xMax += dx;
double dy = 0.5 * this.getDeltaY();
yMin -= dy;
yMax += dy;
}
double zMin, zMax;
try {
zMin = this.minimalElevation();
zMax = this.maximalElevation();
}
catch (T3dException e) {
return null;
}
return new GmEnvelope(xMin, xMax, yMin, yMax, zMin, zMax);
}
public double minimalElevation() throws T3dException
{
try {
this.calculateZBounds();
}
catch (T3dException e) {
throw e;
}
return mZMin;
}
public double maximalElevation() throws T3dException
{
try {
this.calculateZBounds();
}
catch (T3dException e) {
throw e;
}
return mZMax;
}
/**
* deactivates lazy evaluation mode for minimal/maximal <i>z</i>-value
* computation. For performance reasons, it might be necessary to
* deactivate this mode explicitly before starting multiple
* <tt>setValue()</tt>-calls.
*/
public void setZBoundsInvalid() {
mCalculated = false;
}
// Private helpers to compute z-bounds ("lazy evaluation"!):
private boolean mCalculated = false;
private double mZMin, mZMax;
private void calculateZBounds() throws T3dException
{
if (!mCalculated) {
try {
mZMin = this.getFirstSetZValue();
}
catch (T3dException e) {
throw e;
}
mZMax = mZMin;
double z;
for (int i = 0; i < this.numberOfRows(); i++) {
for (int j = 0; j < this.numberOfColumns(); j++) {
if (this.isSet(i, j)) {
z = this.getValue(i, j);
if (z < mZMin) mZMin = z; else {
if (z > mZMax) mZMax = z; }
}
}
}
mCalculated = true;
}
}
private void updateZBounds(double zOld, double zNew)
{
final double eps = 0.000001; // Epsilon for =-operation
if (mCalculated) {
if (zNew <= mZMin) { mZMin = zNew; return; }
// assert: pZMin < pZNew
if (zNew >= mZMax) { mZMax = zNew; return; }
// assert: pZMin < pZNew < mZMax
if (Math.abs(zOld - mZMin) < eps || Math.abs(zOld - mZMax) < eps)
mCalculated = false; // re-computation will be necessary later
} // else:
; // skip
}
// Get z-value of some set grid element:
private double getFirstSetZValue() throws T3dException
{
for (int i = 0; i < this.numberOfRows(); i++) {
for (int j = 0; j < this.numberOfColumns(); j++) {
if (this.isSet(i, j))
return this.getValue(i, j);
}
}
// else:
throw new T3dException("Tried to access empty elevation grid.");
}
/**
* returns the coordinates of a point that is part of the elevation-grid.
* If there is no <i>z</i>-value assigned to the grid point, the return-value
* will be <i>null</i>.
*
* @param row Row-index
* @param col Column-index
* @return Elevation-Point
*/
public VgPoint getPoint(int row, int col)
{
double
x = mGeom.getOrigin().getX() + col * this.getDeltaX(),
y = mGeom.getOrigin().getY() + row * this.getDeltaY(),
z;
if (!this.isSet(row, col))
return null;
z = this.getValue(row, col);
return new GmPoint(x, y, z);
}
/**
* returns the corresponding footprint geometry.
*
* @return Footprint as {@link GmSimple2dGridGeometry}-object
*/
public VgGeomObject footprint() {
return mGeom.footprint();
}
public String getTheme() {
return mTheme;
}
public void setTheme(String theme) {
mTheme = theme;
}
public String toString() {
String strGeom = "<empty geometry>";
if (mGeom != null)
strGeom = mGeom.toString();
return "[" + mTheme + ", \"" + strGeom + "\"]";
}
}
| 52North/triturus | src/main/java/org/n52/v3d/triturus/gisimplm/GmSimpleElevationGrid.java | Java | gpl-2.0 | 17,502 |
/* WZPlayer, GUI front-end for mplayer and MPV.
Parts copyright (C) 2006-2015 Ricardo Villalba <rvm@users.sourceforge.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "settings/filesettingsbase.h"
namespace Settings {
TFileSettingsBase::TFileSettingsBase(const QString& filename) :
QSettings(filename, QSettings::IniFormat) {
}
TFileSettingsBase::~TFileSettingsBase() {
}
} // namespace Settings
| wilbert2000/smplayer | src/settings/filesettingsbase.cpp | C++ | gpl-2.0 | 1,100 |
<?php
/**
* @file
* Default simple view template to display a list of rows.
*
* @ingroup views_templates
*/
?>
<?php if (!empty($title)): ?>
<h3><?php print $title; ?></h3>
<?php endif; ?>
<div class="our-works-slider"><?php foreach ($rows as $id => $row): ?>
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"'; } ?>>
<?php print $row; ?>
</div>
<?php endforeach; ?></div>
| farruhmirisoev/mir | sites/all/themes/mytheme/templates/views-view-unformatted--view-our-work--block.tpl.php | PHP | gpl-2.0 | 439 |
class CreateSellers < ActiveRecord::Migration
def change
create_table :sellers do |t|
t.integer :personId, null:false
t.integer :document, null:false
t.string :username, null:false, :limit =>50
t.string :userLastName, null:false, :limit =>50
t.string :email, null:false, :limit =>50
t.string :password, null:false
t.string :password_confirmation, null:false
t.string :telephone, null:false, :limit =>20
t.string :userType, null:false, :limit=>10
t.boolean :status, null:false
end
end
end
| dialpapu/bikesis | project/db/migrate/20141016223008_create_sellers.rb | Ruby | gpl-2.0 | 567 |
using System;
using System.Windows.Threading;
using PowerPointLabs.PictureSlidesLab.Thread.Interface;
namespace PowerPointLabs.PictureSlidesLab.Thread
{
class ThreadContext : IThreadContext
{
private readonly Dispatcher _dispatcher;
public ThreadContext(Dispatcher dispatcher)
{
_dispatcher = dispatcher;
}
public void Invoke(Action action)
{
_dispatcher.Invoke(action);
}
public void BeginInvoke(Action action)
{
_dispatcher.BeginInvoke(action);
}
}
}
| PowerPointLabs/PowerPointLabs | PowerPointLabs/PowerPointLabs/PictureSlidesLab/Thread/ThreadContext.cs | C# | gpl-2.0 | 589 |
package spiridon.carorder.caritems;
public class AlloyRimsCarItem extends CarItem {
@Override
public double getPrice() {
return 100;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "Jante Aliaj";
}
}
| sorelmitra/edu | carorder/src/spiridon/carorder/caritems/AlloyRimsCarItem.java | Java | gpl-2.0 | 248 |
/**
*
*/
package edu.ku.brc.specify.tools.export;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Vector;
import edu.ku.brc.af.auth.SecurityMgr;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Element;
import edu.ku.brc.af.auth.JaasContext;
import edu.ku.brc.af.auth.UserAndMasterPasswordMgr;
import edu.ku.brc.af.core.AppContextMgr;
import edu.ku.brc.af.prefs.AppPreferences;
import edu.ku.brc.dbsupport.DatabaseDriverInfo;
import edu.ku.brc.helpers.XMLHelper;
import edu.ku.brc.specify.Specify;
import edu.ku.brc.specify.config.SpecifyAppContextMgr;
import edu.ku.brc.specify.config.SpecifyAppPrefs;
import edu.ku.brc.specify.conversion.BasicSQLUtils;
import edu.ku.brc.specify.datamodel.Discipline;
import edu.ku.brc.specify.tools.ireportspecify.MainFrameSpecify;
import edu.ku.brc.ui.UIHelper;
import edu.ku.brc.ui.UIRegistry;
import edu.ku.brc.util.Pair;
/**
* @author timo
*
*/
public class CmdAppBase {
protected static final String SCHEMA_VERSION_FILENAME = "schema_version.xml";
private static String[] argkeys = {"-u", "-p", "-d", "-m", "-l", "-h", "-o", "-w", "-U", "-P"};
protected List<Pair<String, String>> argList;
protected String userName;
protected String password;
protected String dbName;
protected String outputName;
protected String hostName;
protected String workingPath = ".";
protected Pair<String, String> master;
protected FileWriter out;
boolean success = false;
protected Vector<DatabaseDriverInfo> dbDrivers = new Vector<DatabaseDriverInfo>();
protected int dbDriverIdx;
protected String collectionName;
protected JaasContext jaasContext;
/**
* @param argkeys
*/
public CmdAppBase(String[] akeys) {
String[] as = new String[argkeys.length + akeys.length];
for (int ak=0; ak < argkeys.length; ak++) {
as[ak] = argkeys[ak];
}
for (int ak=0; ak < akeys.length; ak++) {
as[ak + argkeys.length] = akeys[ak];
}
argList = buildArgList(as);
dbDriverIdx = 0;
hostName = "localhost";
}
/**
* @param keys
* @return
*/
protected List<Pair<String, String>> buildArgList(String[] keys) {
List<Pair<String, String>> result = new ArrayList<Pair<String,String>>();
for (String key : keys) {
result.add(new Pair<String, String>(key, null));
}
return result;
}
/**
* @return
*/
public String getDBSchemaVersionFromXML()
{
String dbVersion = null;
Element root;
try
{
root = XMLHelper.readFileToDOM4J(new FileInputStream(XMLHelper.getConfigDirPath(SCHEMA_VERSION_FILENAME)));//$NON-NLS-1$
if (root != null)
{
dbVersion = ((Element)root).getTextTrim();
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
return dbVersion;
}
/**
* @return
*/
protected boolean checkVersion() {
String schemaVersion = getDBSchemaVersionFromXML();
String appVersion = UIRegistry.getAppVersion();
String schemaVersionFromDb = BasicSQLUtils.querySingleObj("select SchemaVersion from spversion");
String appVersionFromDb = BasicSQLUtils.querySingleObj("select AppVersion from spversion");
return (schemaVersion.equals(schemaVersionFromDb) && appVersion.equals(appVersionFromDb));
}
/**
* @param args
*/
protected void readArgs(String[] args) {
for (Pair<String, String> argPair : argList) {
argPair.setSecond(readArg(argPair.getFirst(), args));
}
}
/**
* @param argKey
* @param args
* @return
*/
protected String readArg(String argKey, String[] args) {
for (int k = 0; k < args.length - 1; k+=2) {
if (args[k].equals(argKey)) {
return args[k+1];
}
}
return null;
}
/**
* @return
*/
protected String checkArgs() {
String result = "";
for (Pair<String, String> arg : argList) {
String err = checkArg(arg);
if (StringUtils.isNotBlank(err)) {
if (result.length() > 0) {
result += "; ";
}
result += err;
}
}
return result;
}
/**
* @param arg
* @return "" if arg checks out, else err msg
*/
protected String checkArg(Pair<String, String> arg) {
return "";
}
/**
*
*/
protected void adjustLocaleFromPrefs()
{
String language = AppPreferences.getLocalPrefs().get("locale.lang", null); //$NON-NLS-1$
if (language != null)
{
String country = AppPreferences.getLocalPrefs().get("locale.country", null); //$NON-NLS-1$
String variant = AppPreferences.getLocalPrefs().get("locale.var", null); //$NON-NLS-1$
Locale prefLocale = new Locale(language, country, variant);
Locale.setDefault(prefLocale);
UIRegistry.setResourceLocale(prefLocale);
}
try
{
ResourceBundle.getBundle("resources", Locale.getDefault()); //$NON-NLS-1$
} catch (MissingResourceException ex)
{
edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(MainFrameSpecify.class, ex);
Locale.setDefault(Locale.ENGLISH);
UIRegistry.setResourceLocale(Locale.ENGLISH);
}
}
/**
* @throws Exception
*/
protected void setupPrefs() throws Exception {
//Apparently this is correct...
System.setProperty(SecurityMgr.factoryName, "edu.ku.brc.af.auth.specify.SpecifySecurityMgr");
UIRegistry.setAppName("Specify"); //$NON-NLS-1$
UIRegistry.setDefaultWorkingPath(this.workingPath);
final AppPreferences localPrefs = AppPreferences.getLocalPrefs();
localPrefs.setDirPath(UIRegistry.getAppDataDir());
adjustLocaleFromPrefs();
final String iRepPrefDir = localPrefs.getDirPath();
int mark = iRepPrefDir.lastIndexOf(UIRegistry.getAppName(), iRepPrefDir.length());
final String SpPrefDir = iRepPrefDir.substring(0, mark) + "Specify";
AppPreferences.getLocalPrefs().flush();
AppPreferences.getLocalPrefs().setDirPath(SpPrefDir);
AppPreferences.getLocalPrefs().setProperties(null);
}
/**
* @return
* @throws Exception
*/
protected boolean hasMasterKey() throws Exception {
UserAndMasterPasswordMgr.getInstance().set(userName, password, dbName);
return UserAndMasterPasswordMgr.getInstance().hasMasterUsernameAndPassword();
}
protected boolean needsMasterKey() {
return !(master != null && master.getFirst() != null && master.getSecond()!= null);
}
/**
* @return
* @throws Exception
*/
protected boolean getMaster() throws Exception {
UserAndMasterPasswordMgr.getInstance().set(userName, password, dbName);
if (!needsMasterKey()) {
UserAndMasterPasswordMgr.getInstance().setUserNamePasswordForDB(master.first, master.second);
return true;
}
Pair<String, String> userpw = UserAndMasterPasswordMgr.getInstance().getUserNamePasswordForDB();
if (userpw != null) {
if (StringUtils.isNotBlank(userpw.getFirst()) && StringUtils.isNotBlank(userpw.getSecond())) {
if (master == null) {
master = new Pair<String, String>(null, null);
}
master.setFirst(userpw.getFirst());
master.setSecond(userpw.getSecond());
return true;
}
}
return false;
}
/**
* @return
*/
protected boolean goodUser() {
String userType = BasicSQLUtils.querySingleObj("select UserType from specifyuser where `name` = '" + userName + "'");
return "manager".equalsIgnoreCase(userType);
}
/**
* @param argKey
* @return
*/
protected String getArg(String argKey) {
for (Pair<String, String> arg : argList) {
if (arg.getFirst().equals(argKey)) {
return arg.getSecond();
}
}
return null;
}
/**
* @param success
*/
protected void setSuccess(boolean success) {
this.success = success;
}
public boolean isSuccess() {
return success;
}
protected DatabaseDriverInfo buildDefaultDriverInfo() {
DatabaseDriverInfo result = new DatabaseDriverInfo("MySQL", "com.mysql.jdbc.Driver", "org.hibernate.dialect.MySQL5InnoDBDialect", false, "3306");
result.addFormat(DatabaseDriverInfo.ConnectionType.Opensys, "jdbc:mysql://SERVER:PORT/");
result.addFormat(DatabaseDriverInfo.ConnectionType.Open, "jdbc:mysql://SERVER:PORT/DATABASE?characterEncoding=UTF-8&autoReconnect=true");
return result;
}
/**
*
*/
public void loadDrivers() {
dbDrivers = DatabaseDriverInfo.getDriversList();
}
/**
* @return
*/
protected String getConnectionStr() {
return dbDrivers.get(dbDriverIdx).getConnectionStr(DatabaseDriverInfo.ConnectionType.Open,
hostName, dbName);
}
/**
* @param fileName
* @throws Exception
*/
protected void openLog(String fileName) throws Exception {
FileWriter testOut = new FileWriter(new File(fileName), true);
out = testOut;
}
/**
* @return
*/
protected String getTimestamp() {
return new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
}
/**
* @return
*/
protected String getLogInitText(String[] args) {
String argStr = "";
boolean isPw = false;
for (String arg : args) {
argStr += " " + (isPw ? "********" : arg);
if (isPw) {
isPw = false;
} else if ("-p".equals(arg)) {
isPw = true;
}
}
return String.format(UIRegistry.getResourceString("ExportCmdLine.LogInitTxt"), argStr);
}
/**
* @return
*/
protected String getLogExitText() {
return String.format(UIRegistry.getResourceString("ExportCmdLine.LogExitTxt"), (success ? "" : "UN-") + "successfully.");
}
/**
* @throws IOException
*/
protected void initLog(String[] args) throws IOException {
out(getLogInitText(args));
}
/**
* @throws IOException
*/
protected void flushLog() throws IOException {
if (out != null) {
out.flush();
}
}
/**
* @throws IOException
*/
protected void exitLog() throws IOException {
out(getLogExitText());
if (out != null) {
out.close();
}
}
/**
* @param line
* @throws IOException
*/
protected void out(String line) throws IOException {
if (out != null) {
out.append(getTimestamp() + ": " + line + "\n");
out.flush();
} else {
System.out.println(getTimestamp() + ": " + line);
}
}
/**
* @return
*/
protected boolean login() {
boolean result = UIHelper.tryLogin(dbDrivers.get(dbDriverIdx).getDriverClassName(),
dbDrivers.get(dbDriverIdx).getDialectClassName(),
dbName,
getConnectionStr(),
master.getFirst(),
master.getSecond());
if (result) {
this.jaasContext = new JaasContext();
jaasLogin();
}
return result;
}
/**
* @return true if ContextManager initializes successfully for collection.
*/
protected boolean setContext() {
Specify.setUpSystemProperties();
System.setProperty(AppContextMgr.factoryName, "edu.ku.brc.specify.tools.export.SpecifyExpCmdAppContextMgr"); // Needed by AppContextMgr //$NON-NLS-1$
AppPreferences.shutdownRemotePrefs();
AppContextMgr.CONTEXT_STATUS status = ((SpecifyAppContextMgr)AppContextMgr.getInstance()).
setContext(dbName, userName, false, false, true, collectionName, false);
// AppContextMgr.getInstance().
SpecifyAppPrefs.initialPrefs();
if (status == AppContextMgr.CONTEXT_STATUS.OK) {
if (AppContextMgr.getInstance().getClassObject(Discipline.class) == null) {
return false;
}
} else if (status == AppContextMgr.CONTEXT_STATUS.Error) {
return false;
}
// ...end specify.restartApp snatch
return true;
}
/**
* @return
*/
protected boolean retrieveCollectionName() {
return false;
}
/**
* @return
*/
public boolean jaasLogin()
{
if (jaasContext != null)
{
return jaasContext.jaasLogin(
userName,
password,
getConnectionStr(),
dbDrivers.get(dbDriverIdx).getDriverClassName(),
master.first,
master.second
);
}
return false;
}
/**
* @throws Exception
*/
protected void setMembers() throws Exception {
userName = getArg("-u");
password = getArg("-p");
if (password == null) password = "";
dbName = getArg("-d");
outputName = getArg("-o");
workingPath = getArg("-w");
String logFile = getArg("-l");
if (logFile != null) {
openLog(logFile);
}
String host = getArg("-h");
if (host != null) {
hostName = host;
}
master = new Pair<>(getArg("-U"), getArg("-P"));
}
}
| specify/specify6 | src/edu/ku/brc/specify/tools/export/CmdAppBase.java | Java | gpl-2.0 | 13,017 |
/*
ZynAddSubFX - a software synthesizer
Alienwah.C - "AlienWah" effect
Copyright (C) 2002-2005 Nasca Octavian Paul
Author: Nasca Octavian Paul
Modified for rakarrack by Josep Andreu
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License (version 2) for more details.
You should have received a copy of the GNU General Public License (version 2)
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <math.h>
#include "Alienwah.h"
#include <stdio.h>
Alienwah::Alienwah(double sample_rate, uint32_t intermediate_bufsize)
{
lfo = new EffectLFO(sample_rate);
Ppreset = 0;
PERIOD = intermediate_bufsize; // correct for rakarrak, may be adjusted for lv2
fPERIOD = intermediate_bufsize; // correct for rakarrak, may be adjusted for lv2
panning = fb = depth = lrcross = phase = 0.0f;
outvolume = 0.5f;
oldk = 0;
oldpdelay = 0;
setpreset(Ppreset);
cleanup();
oldclfol.a = fb;
oldclfol.b = 0.0;
oldclfor.a = fb;
oldclfor.b = 0.0;
};
Alienwah::~Alienwah()
{
delete lfo;
};
/*
* Apply the effect
*/
void
Alienwah::out(float * efxoutl, float * efxoutr)
{
unsigned int i;
float lfol, lfor;
COMPLEXTYPE clfol, clfor, out, tmp;
lfo->effectlfoout(&lfol, &lfor);
lfol *= depth * D_PI;
lfor *= depth * D_PI;
clfol.a = cosf(lfol + phase) * fb;
clfol.b = sinf(lfol + phase) * fb;
clfor.a = cosf(lfor + phase) * fb;
clfor.b = sinf(lfor + phase) * fb;
for (i = 0; i < PERIOD; i++)
{
float x = (float) i / fPERIOD;
float x1 = 1.0f - x;
//left
tmp.a = clfol.a * x + oldclfol.a * x1;
tmp.b = clfol.b * x + oldclfol.b * x1;
out.a = tmp.a * oldl[oldk].a - tmp.b * oldl[oldk].b
+ (1.0f - fabsf(fb)) * efxoutl[i] * (1.0f - panning);
out.b = tmp.a * oldl[oldk].b + tmp.b * oldl[oldk].a;
oldl[oldk].a = out.a;
oldl[oldk].b = out.b;
float l = out.a * 10.0f * (fb + 0.1f);
//right
tmp.a = clfor.a * x + oldclfor.a * x1;
tmp.b = clfor.b * x + oldclfor.b * x1;
out.a = tmp.a * oldr[oldk].a - tmp.b * oldr[oldk].b
+ (1.0f - fabsf(fb)) * efxoutr[i] * panning;
out.b = tmp.a * oldr[oldk].b + tmp.b * oldr[oldk].a;
oldr[oldk].a = out.a;
oldr[oldk].b = out.b;
float r = out.a * 10.0f * (fb + 0.1f);
if (++oldk >= Pdelay)
oldk = 0;
//LRcross
efxoutl[i] = l * (1.0f - lrcross) + r * lrcross;
efxoutr[i] = r * (1.0f - lrcross) + l * lrcross;
};
oldclfol.a = clfol.a;
oldclfol.b = clfol.b;
oldclfor.a = clfor.a;
oldclfor.b = clfor.b;
}
/*
* Cleanup the effect
*/
void
Alienwah::cleanup()
{
for (int i = oldpdelay; i < MAX_ALIENWAH_DELAY; i++)
{
oldl[i].a = 0.0f;
oldl[i].b = 0.0f;
oldr[i].a = 0.0f;
oldr[i].b = 0.0f;
};
oldk = 0;
}
void
Alienwah::lv2_update_params(uint32_t period)
{
PERIOD = period;
fPERIOD = period;
lfo->updateparams(period);
}
/*
* Parameter control
*/
void
Alienwah::setdepth(int Pdepth)
{
this->Pdepth = Pdepth;
depth = ((float) Pdepth / 127.0f);
}
void
Alienwah::setfb(int Pfb)
{
this->Pfb = Pfb;
fb = fabsf(((float) Pfb - 64.0f) / 64.1f);
fb = sqrtf(fb);
if (fb < 0.4f)
fb = 0.4f;
if (Pfb < 64)
fb = -fb;
}
void
Alienwah::setvolume(int Pvolume)
{
this->Pvolume = Pvolume;
outvolume = (float) Pvolume / 127.0f;
}
void
Alienwah::setpanning(int Ppanning)
{
this->Ppanning = Ppanning;
panning = ((float) Ppanning + .5f) / 127.0f;
}
void
Alienwah::setlrcross(int Plrcross)
{
this->Plrcross = Plrcross;
lrcross = (float) Plrcross / 127.0f;
}
void
Alienwah::setphase(int Pphase)
{
this->Pphase = Pphase;
phase = ((float) Pphase - 64.0f) / 64.0f * PI;
}
void
Alienwah::setdelay(int Pdelay)
{
if (Pdelay > MAX_ALIENWAH_DELAY)
Pdelay = MAX_ALIENWAH_DELAY;
this->Pdelay = Pdelay;
if (Pdelay > oldpdelay) cleanup();
oldpdelay = Pdelay;
}
void
Alienwah::setpreset(int npreset)
{
const int PRESET_SIZE = 11;
const int NUM_PRESETS = 4;
int pdata[MAX_PDATA_SIZE];
int presets[NUM_PRESETS][PRESET_SIZE] = {
//AlienWah1
{64, 64, 80, 0, 0, 62, 60, 105, 25, 0, 64},
//AlienWah2
{64, 64, 95, 106, 0, 101, 60, 105, 17, 0, 64},
//AlienWah3
{64, 64, 55, 0, 1, 100, 112, 105, 31, 0, 42},
//AlienWah4
{64, 64, 1, 0, 1, 66, 101, 11, 47, 0, 86}
};
if (npreset > NUM_PRESETS - 1)
{
Fpre->ReadPreset(11, npreset - NUM_PRESETS + 1, pdata);
for (int n = 0; n < PRESET_SIZE; n++)
changepar(n, pdata[n]);
}
else
{
for (int n = 0; n < PRESET_SIZE; n++)
changepar(n, presets[npreset][n]);
}
Ppreset = npreset;
}
void
Alienwah::changepar(int npar, int value)
{
switch (npar)
{
case 0:
setvolume(value);
break;
case 1:
setpanning(value);
break;
case 2:
lfo->Pfreq = value;
lfo->updateparams(PERIOD);
break;
case 3:
lfo->Prandomness = value;
lfo->updateparams(PERIOD);
break;
case 4:
lfo->PLFOtype = value;
lfo->updateparams(PERIOD);
break;
case 5:
lfo->Pstereo = value;
lfo->updateparams(PERIOD);
break;
case 6:
setdepth(value);
break;
case 7:
setfb(value);
break;
case 8:
setdelay(value);
break;
case 9:
setlrcross(value);
break;
case 10:
setphase(value);
break;
}
}
int
Alienwah::getpar(int npar)
{
switch (npar)
{
case 0:
return (Pvolume);
break;
case 1:
return (Ppanning);
break;
case 2:
return (lfo->Pfreq);
break;
case 3:
return (lfo->Prandomness);
break;
case 4:
return (lfo->PLFOtype);
break;
case 5:
return (lfo->Pstereo);
break;
case 6:
return (Pdepth);
break;
case 7:
return (Pfb);
break;
case 8:
return (Pdelay);
break;
case 9:
return (Plrcross);
break;
case 10:
return (Pphase);
break;
default:
return (0);
}
}
| Stazed/rakarrack | src/Alienwah.C | C++ | gpl-2.0 | 6,852 |
/* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define DBACC_C
#include "Dbacc.hpp"
#include <AttributeHeader.hpp>
#include <Bitmask.hpp>
#include <signaldata/AccFrag.hpp>
#include <signaldata/AccScan.hpp>
#include <signaldata/NextScan.hpp>
#include <signaldata/AccLock.hpp>
#include <signaldata/EventReport.hpp>
#include <signaldata/FsConf.hpp>
#include <signaldata/FsRef.hpp>
#include <signaldata/FsRemoveReq.hpp>
#include <signaldata/DropTab.hpp>
#include <signaldata/DumpStateOrd.hpp>
#include <signaldata/TuxMaint.hpp>
#include <signaldata/DbinfoScan.hpp>
#include <signaldata/TransIdAI.hpp>
#include <KeyDescriptor.hpp>
#include <signaldata/NodeStateSignalData.hpp>
#include <md5_hash.hpp>
#ifdef VM_TRACE
#define DEBUG(x) ndbout << "DBACC: "<< x << endl;
#else
#define DEBUG(x)
#endif
#ifdef ACC_SAFE_QUEUE
#define vlqrequire(x) do { if (unlikely(!(x))) {\
dump_lock_queue(loPtr); \
ndbrequire(false); } } while(0)
#else
#define vlqrequire(x) ndbrequire(x)
#define dump_lock_queue(x)
#endif
// primary key is stored in TUP
#include "../dbtup/Dbtup.hpp"
#include "../dblqh/Dblqh.hpp"
#define JAM_FILE_ID 345
// Index pages used by ACC instances, used by CMVMI to report index memory usage
extern Uint32 g_acc_pages_used[MAX_NDBMT_LQH_WORKERS];
// Signal entries and statement blocks
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* COMMON SIGNAL RECEPTION MODULE */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* ******************--------------------------------------------------------------- */
/* CONTINUEB CONTINUE SIGNAL */
/* ******************------------------------------+ */
/* SENDER: ACC, LEVEL B */
void Dbacc::execCONTINUEB(Signal* signal)
{
Uint32 tcase;
jamEntry();
tcase = signal->theData[0];
tdata0 = signal->theData[1];
tresult = 0;
switch (tcase) {
case ZINITIALISE_RECORDS:
jam();
initialiseRecordsLab(signal, signal->theData[3], signal->theData[4]);
return;
break;
case ZREL_ROOT_FRAG:
{
jam();
Uint32 tableId = signal->theData[1];
releaseRootFragResources(signal, tableId);
break;
}
case ZREL_FRAG:
{
jam();
Uint32 fragIndex = signal->theData[1];
releaseFragResources(signal, fragIndex);
break;
}
case ZREL_DIR:
{
jam();
releaseDirResources(signal);
break;
}
default:
ndbrequire(false);
break;
}//switch
return;
}//Dbacc::execCONTINUEB()
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* */
/* END OF COMMON SIGNAL RECEPTION MODULE */
/* */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* */
/* SYSTEM RESTART MODULE */
/* */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
void Dbacc::execNDB_STTOR(Signal* signal)
{
Uint32 tstartphase;
Uint32 tStartType;
jamEntry();
cndbcntrRef = signal->theData[0];
cmynodeid = signal->theData[1];
tstartphase = signal->theData[2];
tStartType = signal->theData[3];
switch (tstartphase) {
case ZSPH1:
jam();
ndbsttorryLab(signal);
return;
break;
case ZSPH2:
ndbsttorryLab(signal);
return;
break;
case ZSPH3:
break;
case ZSPH6:
jam();
break;
default:
jam();
/*empty*/;
break;
}//switch
ndbsttorryLab(signal);
return;
}//Dbacc::execNDB_STTOR()
/* ******************--------------------------------------------------------------- */
/* STTOR START / RESTART */
/* ******************------------------------------+ */
/* SENDER: ANY, LEVEL B */
void Dbacc::execSTTOR(Signal* signal)
{
jamEntry();
Uint32 tstartphase = signal->theData[1];
switch (tstartphase) {
case 1:
jam();
ndbrequire((c_tup = (Dbtup*)globalData.getBlock(DBTUP, instance())) != 0);
ndbrequire((c_lqh = (Dblqh*)globalData.getBlock(DBLQH, instance())) != 0);
break;
}
tuserblockref = signal->theData[3];
csignalkey = signal->theData[6];
sttorrysignalLab(signal);
return;
}//Dbacc::execSTTOR()
/* --------------------------------------------------------------------------------- */
/* ZSPH1 */
/* --------------------------------------------------------------------------------- */
void Dbacc::ndbrestart1Lab()
{
cmynodeid = globalData.ownId;
cownBlockref = calcInstanceBlockRef(DBACC);
czero = 0;
cminusOne = czero - 1;
return;
}//Dbacc::ndbrestart1Lab()
void Dbacc::initialiseRecordsLab(Signal* signal, Uint32 ref, Uint32 data)
{
switch (tdata0) {
case 0:
jam();
initialiseTableRec();
break;
case 1:
case 2:
break;
case 3:
jam();
break;
case 4:
jam();
break;
case 5:
jam();
break;
case 6:
jam();
initialiseFragRec();
break;
case 7:
jam();
break;
case 8:
jam();
initialiseOperationRec();
break;
case 9:
jam();
initialisePageRec();
break;
case 10:
jam();
break;
case 11:
jam();
initialiseScanRec();
break;
case 12:
jam();
{
ReadConfigConf * conf = (ReadConfigConf*)signal->getDataPtrSend();
conf->senderRef = reference();
conf->senderData = data;
sendSignal(ref, GSN_READ_CONFIG_CONF, signal,
ReadConfigConf::SignalLength, JBB);
}
return;
break;
default:
ndbrequire(false);
break;
}//switch
signal->theData[0] = ZINITIALISE_RECORDS;
signal->theData[1] = tdata0 + 1;
signal->theData[2] = 0;
signal->theData[3] = ref;
signal->theData[4] = data;
sendSignal(reference(), GSN_CONTINUEB, signal, 5, JBB);
return;
}//Dbacc::initialiseRecordsLab()
/* *********************************<< */
/* NDB_STTORRY */
/* *********************************<< */
void Dbacc::ndbsttorryLab(Signal* signal) const
{
signal->theData[0] = cownBlockref;
sendSignal(cndbcntrRef, GSN_NDB_STTORRY, signal, 1, JBB);
return;
}//Dbacc::ndbsttorryLab()
/* *********************************<< */
/* SIZEALT_REP SIZE ALTERATION */
/* *********************************<< */
void Dbacc::execREAD_CONFIG_REQ(Signal* signal)
{
const ReadConfigReq * req = (ReadConfigReq*)signal->getDataPtr();
Uint32 ref = req->senderRef;
Uint32 senderData = req->senderData;
ndbrequire(req->noOfParameters == 0);
jamEntry();
const ndb_mgm_configuration_iterator * p =
m_ctx.m_config.getOwnConfigIterator();
ndbrequire(p != 0);
ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_ACC_FRAGMENT, &cfragmentsize));
ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_ACC_OP_RECS, &coprecsize));
ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_ACC_PAGE8, &cpagesize));
ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_ACC_TABLE, &ctablesize));
ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_ACC_SCAN, &cscanRecSize));
initRecords();
ndbrestart1Lab();
c_memusage_report_frequency = 0;
ndb_mgm_get_int_parameter(p, CFG_DB_MEMREPORT_FREQUENCY,
&c_memusage_report_frequency);
tdata0 = 0;
initialiseRecordsLab(signal, ref, senderData);
return;
}//Dbacc::execSIZEALT_REP()
/* *********************************<< */
/* STTORRY */
/* *********************************<< */
void Dbacc::sttorrysignalLab(Signal* signal) const
{
signal->theData[0] = csignalkey;
signal->theData[1] = 3;
/* BLOCK CATEGORY */
signal->theData[2] = 2;
/* SIGNAL VERSION NUMBER */
signal->theData[3] = ZSPH1;
signal->theData[4] = 255;
BlockReference cntrRef = !isNdbMtLqh() ? NDBCNTR_REF : DBACC_REF;
sendSignal(cntrRef, GSN_STTORRY, signal, 5, JBB);
/* END OF START PHASES */
return;
}//Dbacc::sttorrysignalLab()
/* --------------------------------------------------------------------------------- */
/* INITIALISE_FRAG_REC */
/* INITIALATES THE FRAGMENT RECORDS. */
/* --------------------------------------------------------------------------------- */
void Dbacc::initialiseFragRec()
{
FragmentrecPtr regFragPtr;
ndbrequire(cfragmentsize > 0);
for (regFragPtr.i = 0; regFragPtr.i < cfragmentsize; regFragPtr.i++) {
jam();
refresh_watch_dog();
ptrAss(regFragPtr, fragmentrec);
initFragGeneral(regFragPtr);
regFragPtr.p->nextfreefrag = regFragPtr.i + 1;
}//for
regFragPtr.i = cfragmentsize - 1;
ptrAss(regFragPtr, fragmentrec);
regFragPtr.p->nextfreefrag = RNIL;
cfirstfreefrag = 0;
}//Dbacc::initialiseFragRec()
/* --------------------------------------------------------------------------------- */
/* INITIALISE_OPERATION_REC */
/* INITIALATES THE OPERATION RECORDS. */
/* --------------------------------------------------------------------------------- */
void Dbacc::initialiseOperationRec()
{
ndbrequire(coprecsize > 0);
for (operationRecPtr.i = 0; operationRecPtr.i < coprecsize; operationRecPtr.i++) {
refresh_watch_dog();
ptrAss(operationRecPtr, operationrec);
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
operationRecPtr.p->nextOp = operationRecPtr.i + 1;
}//for
operationRecPtr.i = coprecsize - 1;
ptrAss(operationRecPtr, operationrec);
operationRecPtr.p->nextOp = RNIL;
cfreeopRec = 0;
}//Dbacc::initialiseOperationRec()
/* --------------------------------------------------------------------------------- */
/* INITIALISE_PAGE_REC */
/* INITIALATES THE PAGE RECORDS. */
/* --------------------------------------------------------------------------------- */
void Dbacc::initialisePageRec()
{
ndbrequire(cpagesize > 0);
cnoOfAllocatedPages = 0;
cnoOfAllocatedPagesMax = 0;
}//Dbacc::initialisePageRec()
/* --------------------------------------------------------------------------------- */
/* INITIALISE_ROOTFRAG_REC */
/* INITIALATES THE ROOTFRAG RECORDS. */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* INITIALISE_SCAN_REC */
/* INITIALATES THE QUE_SCAN RECORDS. */
/* --------------------------------------------------------------------------------- */
void Dbacc::initialiseScanRec()
{
ndbrequire(cscanRecSize > 0);
for (scanPtr.i = 0; scanPtr.i < cscanRecSize; scanPtr.i++) {
ptrAss(scanPtr, scanRec);
scanPtr.p->scanNextfreerec = scanPtr.i + 1;
scanPtr.p->scanState = ScanRec::SCAN_DISCONNECT;
scanPtr.p->activeLocalFrag = RNIL;
scanPtr.p->initContainer();
}//for
scanPtr.i = cscanRecSize - 1;
ptrAss(scanPtr, scanRec);
scanPtr.p->scanNextfreerec = RNIL;
cfirstFreeScanRec = 0;
}//Dbacc::initialiseScanRec()
/* --------------------------------------------------------------------------------- */
/* INITIALISE_TABLE_REC */
/* INITIALATES THE TABLE RECORDS. */
/* --------------------------------------------------------------------------------- */
void Dbacc::initialiseTableRec()
{
ndbrequire(ctablesize > 0);
for (tabptr.i = 0; tabptr.i < ctablesize; tabptr.i++) {
refresh_watch_dog();
ptrAss(tabptr, tabrec);
for (Uint32 i = 0; i < NDB_ARRAY_SIZE(tabptr.p->fragholder); i++) {
tabptr.p->fragholder[i] = RNIL;
tabptr.p->fragptrholder[i] = RNIL;
}//for
}//for
}//Dbacc::initialiseTableRec()
void Dbacc::set_tup_fragptr(Uint32 fragptr, Uint32 tup_fragptr)
{
fragrecptr.i = fragptr;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
fragrecptr.p->tupFragptr = tup_fragptr;
}
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* END OF SYSTEM RESTART MODULE */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* ADD/DELETE FRAGMENT MODULE */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
// JONAS This methods "aer ett saall"
void Dbacc::execACCFRAGREQ(Signal* signal)
{
const AccFragReq * const req = (AccFragReq*)&signal->theData[0];
jamEntry();
if (ERROR_INSERTED(3001)) {
jam();
addFragRefuse(signal, 1);
CLEAR_ERROR_INSERT_VALUE;
return;
}
tabptr.i = req->tableId;
#ifndef VM_TRACE
// config mismatch - do not crash if release compiled
if (tabptr.i >= ctablesize) {
jam();
addFragRefuse(signal, 640);
return;
}
#endif
ptrCheckGuard(tabptr, ctablesize, tabrec);
ndbrequire((req->reqInfo & 0xF) == ZADDFRAG);
ndbrequire(!getfragmentrec(fragrecptr, req->fragId));
if (cfirstfreefrag == RNIL) {
jam();
addFragRefuse(signal, ZFULL_FRAGRECORD_ERROR);
return;
}//if
ndbassert(req->localKeyLen == 1);
if (req->localKeyLen != 1)
{
jam();
addFragRefuse(signal, ZLOCAL_KEY_LENGTH_ERROR);
return;
}
seizeFragrec();
initFragGeneral(fragrecptr);
initFragAdd(signal, fragrecptr);
if (!addfragtotab(fragrecptr.i, req->fragId)) {
jam();
releaseFragRecord(fragrecptr);
addFragRefuse(signal, ZFULL_FRAGRECORD_ERROR);
return;
}//if
Page8Ptr spPageptr;
seizePage(spPageptr);
if (tresult > ZLIMIT_OF_ERROR) {
jam();
addFragRefuse(signal, tresult);
return;
}//if
if (!setPagePtr(fragrecptr.p->directory, 0, spPageptr.i))
{
jam();
addFragRefuse(signal, ZDIR_RANGE_FULL_ERROR);
return;
}
tipPageId = 0;
initPage(spPageptr);
Uint32 userPtr = req->userPtr;
BlockReference retRef = req->userRef;
fragrecptr.p->rootState = ACTIVEROOT;
AccFragConf * const conf = (AccFragConf*)&signal->theData[0];
conf->userPtr = userPtr;
conf->rootFragPtr = RNIL;
conf->fragId[0] = fragrecptr.p->fragmentid;
conf->fragId[1] = RNIL;
conf->fragPtr[0] = fragrecptr.i;
conf->fragPtr[1] = RNIL;
conf->rootHashCheck = fragrecptr.p->roothashcheck;
sendSignal(retRef, GSN_ACCFRAGCONF, signal, AccFragConf::SignalLength, JBB);
}//Dbacc::execACCFRAGREQ()
void Dbacc::addFragRefuse(Signal* signal, Uint32 errorCode) const
{
const AccFragReq * const req = (AccFragReq*)&signal->theData[0];
AccFragRef * const ref = (AccFragRef*)&signal->theData[0];
Uint32 userPtr = req->userPtr;
BlockReference retRef = req->userRef;
ref->userPtr = userPtr;
ref->errorCode = errorCode;
sendSignal(retRef, GSN_ACCFRAGREF, signal, AccFragRef::SignalLength, JBB);
return;
}//Dbacc::addFragRefuseEarly()
void
Dbacc::execDROP_TAB_REQ(Signal* signal){
jamEntry();
DropTabReq* req = (DropTabReq*)signal->getDataPtr();
TabrecPtr tabPtr;
tabPtr.i = req->tableId;
ptrCheckGuard(tabPtr, ctablesize, tabrec);
tabPtr.p->tabUserRef = req->senderRef;
tabPtr.p->tabUserPtr = req->senderData;
tabPtr.p->tabUserGsn = GSN_DROP_TAB_REQ;
signal->theData[0] = ZREL_ROOT_FRAG;
signal->theData[1] = tabPtr.i;
sendSignal(cownBlockref, GSN_CONTINUEB, signal, 2, JBB);
}
void
Dbacc::execDROP_FRAG_REQ(Signal* signal){
jamEntry();
DropFragReq* req = (DropFragReq*)signal->getDataPtr();
TabrecPtr tabPtr;
tabPtr.i = req->tableId;
ptrCheckGuard(tabPtr, ctablesize, tabrec);
tabPtr.p->tabUserRef = req->senderRef;
tabPtr.p->tabUserPtr = req->senderData;
tabPtr.p->tabUserGsn = GSN_DROP_FRAG_REQ;
for (Uint32 i = 0; i < NDB_ARRAY_SIZE(tabPtr.p->fragholder); i++)
{
jam();
if (tabPtr.p->fragholder[i] == req->fragId)
{
jam();
tabPtr.p->fragholder[i] = RNIL;
releaseFragResources(signal, tabPtr.p->fragptrholder[i]);
return;
}//if
}//for
releaseRootFragResources(signal, req->tableId);
}
void Dbacc::releaseRootFragResources(Signal* signal, Uint32 tableId)
{
TabrecPtr tabPtr;
tabPtr.i = tableId;
ptrCheckGuard(tabPtr, ctablesize, tabrec);
if (tabPtr.p->tabUserGsn == GSN_DROP_TAB_REQ)
{
jam();
for (Uint32 i = 0; i < NDB_ARRAY_SIZE(tabPtr.p->fragholder); i++)
{
jam();
if (tabPtr.p->fragholder[i] != RNIL)
{
jam();
tabPtr.p->fragholder[i] = RNIL;
releaseFragResources(signal, tabPtr.p->fragptrholder[i]);
return;
}
}
/**
* Finished...
*/
DropTabConf * const dropConf = (DropTabConf *)signal->getDataPtrSend();
dropConf->senderRef = reference();
dropConf->senderData = tabPtr.p->tabUserPtr;
dropConf->tableId = tabPtr.i;
sendSignal(tabPtr.p->tabUserRef, GSN_DROP_TAB_CONF,
signal, DropTabConf::SignalLength, JBB);
}
else
{
ndbrequire(tabPtr.p->tabUserGsn == GSN_DROP_FRAG_REQ);
DropFragConf * conf = (DropFragConf *)signal->getDataPtrSend();
conf->senderRef = reference();
conf->senderData = tabPtr.p->tabUserPtr;
conf->tableId = tabPtr.i;
sendSignal(tabPtr.p->tabUserRef, GSN_DROP_FRAG_CONF,
signal, DropFragConf::SignalLength, JBB);
}
tabPtr.p->tabUserPtr = RNIL;
tabPtr.p->tabUserRef = 0;
tabPtr.p->tabUserGsn = 0;
}//Dbacc::releaseRootFragResources()
void Dbacc::releaseFragResources(Signal* signal, Uint32 fragIndex)
{
jam();
ndbassert(g_acc_pages_used[instance()] == cnoOfAllocatedPages);
FragmentrecPtr regFragPtr;
regFragPtr.i = fragIndex;
ptrCheckGuard(regFragPtr, cfragmentsize, fragmentrec);
verifyFragCorrect(regFragPtr);
if (!regFragPtr.p->directory.isEmpty()) {
jam();
DynArr256::ReleaseIterator iter;
DynArr256 dir(directoryPool, regFragPtr.p->directory);
dir.init(iter);
signal->theData[0] = ZREL_DIR;
signal->theData[1] = regFragPtr.i;
memcpy(&signal->theData[2], &iter, sizeof(iter));
sendSignal(cownBlockref, GSN_CONTINUEB, signal, 2 + sizeof(iter) / 4, JBB);
} else {
jam();
{
ndbassert(static_cast<Uint32>(regFragPtr.p->m_noOfAllocatedPages) ==
regFragPtr.p->sparsepages.getCount() +
regFragPtr.p->fullpages.getCount());
regFragPtr.p->m_noOfAllocatedPages = 0;
LocalPage8List freelist(*this, cfreepages);
cnoOfAllocatedPages -= regFragPtr.p->sparsepages.getCount();
freelist.appendList(regFragPtr.p->sparsepages);
cnoOfAllocatedPages -= regFragPtr.p->fullpages.getCount();
freelist.appendList(regFragPtr.p->fullpages);
ndbassert(freelist.getCount() + cnoOfAllocatedPages == cpageCount);
g_acc_pages_used[instance()] = cnoOfAllocatedPages;
if (cnoOfAllocatedPages < m_maxAllocPages)
m_oom = false;
}
jam();
Uint32 tab = regFragPtr.p->mytabptr;
releaseFragRecord(regFragPtr);
signal->theData[0] = ZREL_ROOT_FRAG;
signal->theData[1] = tab;
sendSignal(cownBlockref, GSN_CONTINUEB, signal, 2, JBB);
}//if
ndbassert(validatePageCount());
}//Dbacc::releaseFragResources()
void Dbacc::verifyFragCorrect(FragmentrecPtr regFragPtr)const
{
ndbrequire(regFragPtr.p->lockOwnersList == RNIL);
}//Dbacc::verifyFragCorrect()
void Dbacc::releaseDirResources(Signal* signal)
{
jam();
Uint32 fragIndex = signal->theData[1];
DynArr256::ReleaseIterator iter;
memcpy(&iter, &signal->theData[2], sizeof(iter));
FragmentrecPtr regFragPtr;
regFragPtr.i = fragIndex;
ptrCheckGuard(regFragPtr, cfragmentsize, fragmentrec);
verifyFragCorrect(regFragPtr);
DynArr256::Head* directory;
ndbrequire(signal->theData[0] == ZREL_DIR);
directory = ®FragPtr.p->directory;
DynArr256 dir(directoryPool, *directory);
Uint32 ret;
Uint32 pagei;
/* TODO: find a good value for count
* bigger value means quicker release of big index,
* but longer time slice so less concurrent
*/
int count = 10;
while (count > 0 &&
(ret = dir.release(iter, &pagei)) != 0)
{
jam();
count--;
if (ret == 1 && pagei != RNIL)
{
jam();
Page8Ptr rpPageptr;
rpPageptr.i = pagei;
ptrCheckGuard(rpPageptr, cpagesize, page8);
fragrecptr = regFragPtr;
releasePage(rpPageptr);
}
}
if (ret != 0)
{
jam();
memcpy(&signal->theData[2], &iter, sizeof(iter));
sendSignal(cownBlockref, GSN_CONTINUEB, signal, 2 + sizeof(iter) / 4, JBB);
}
else
{
jam();
signal->theData[0] = ZREL_FRAG;
sendSignal(cownBlockref, GSN_CONTINUEB, signal, 2, JBB);
}
}//Dbacc::releaseDirResources()
void Dbacc::releaseFragRecord(FragmentrecPtr regFragPtr)
{
regFragPtr.p->nextfreefrag = cfirstfreefrag;
cfirstfreefrag = regFragPtr.i;
initFragGeneral(regFragPtr);
RSS_OP_FREE(cnoOfFreeFragrec);
}//Dbacc::releaseFragRecord()
/* -------------------------------------------------------------------------- */
/* ADDFRAGTOTAB */
/* DESCRIPTION: PUTS A FRAGMENT ID AND A POINTER TO ITS RECORD INTO */
/* TABLE ARRRAY OF THE TABLE RECORD. */
/* -------------------------------------------------------------------------- */
bool Dbacc::addfragtotab(Uint32 rootIndex, Uint32 fid) const
{
for (Uint32 i = 0; i < NDB_ARRAY_SIZE(tabptr.p->fragholder); i++) {
jam();
if (tabptr.p->fragholder[i] == RNIL) {
jam();
tabptr.p->fragholder[i] = fid;
tabptr.p->fragptrholder[i] = rootIndex;
return true;
}//if
}//for
return false;
}//Dbacc::addfragtotab()
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* END OF ADD/DELETE FRAGMENT MODULE */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* CONNECTION MODULE */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* ******************--------------------------------------------------------------- */
/* ACCSEIZEREQ SEIZE REQ */
/* SENDER: LQH, LEVEL B */
/* ENTER ACCSEIZEREQ WITH */
/* TUSERPTR , CONECTION PTR OF LQH */
/* TUSERBLOCKREF BLOCK REFERENCE OF LQH */
/* ******************--------------------------------------------------------------- */
/* ******************--------------------------------------------------------------- */
/* ACCSEIZEREQ SEIZE REQ */
/* ******************------------------------------+ */
/* SENDER: LQH, LEVEL B */
void Dbacc::execACCSEIZEREQ(Signal* signal)
{
jamEntry();
tuserptr = signal->theData[0];
/* CONECTION PTR OF LQH */
tuserblockref = signal->theData[1];
/* BLOCK REFERENCE OF LQH */
tresult = 0;
if (cfreeopRec == RNIL) {
jam();
refaccConnectLab(signal);
return;
}//if
seizeOpRec();
ptrGuard(operationRecPtr);
operationRecPtr.p->userptr = tuserptr;
operationRecPtr.p->userblockref = tuserblockref;
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
/* ******************************< */
/* ACCSEIZECONF */
/* ******************************< */
signal->theData[0] = tuserptr;
signal->theData[1] = operationRecPtr.i;
sendSignal(tuserblockref, GSN_ACCSEIZECONF, signal, 2, JBB);
return;
}//Dbacc::execACCSEIZEREQ()
void Dbacc::refaccConnectLab(Signal* signal)
{
tresult = ZCONNECT_SIZE_ERROR;
/* ******************************< */
/* ACCSEIZEREF */
/* ******************************< */
signal->theData[0] = tuserptr;
signal->theData[1] = tresult;
sendSignal(tuserblockref, GSN_ACCSEIZEREF, signal, 2, JBB);
return;
}//Dbacc::refaccConnectLab()
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* END OF CONNECTION MODULE */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* EXECUTE OPERATION MODULE */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* INIT_OP_REC */
/* INFORMATION WHICH IS RECIEVED BY ACCKEYREQ WILL BE SAVED */
/* IN THE OPERATION RECORD. */
/* --------------------------------------------------------------------------------- */
void Dbacc::initOpRec(const AccKeyReq* signal, Uint32 siglen) const
{
register Uint32 Treqinfo;
Treqinfo = signal->requestInfo;
operationRecPtr.p->hashValue = LHBits32(signal->hashValue);
operationRecPtr.p->tupkeylen = signal->keyLen;
operationRecPtr.p->xfrmtupkeylen = signal->keyLen;
operationRecPtr.p->transId1 = signal->transId1;
operationRecPtr.p->transId2 = signal->transId2;
const bool readOp = AccKeyReq::getLockType(Treqinfo) == ZREAD;
const bool dirtyOp = AccKeyReq::getDirtyOp(Treqinfo);
const bool dirtyReadOp = readOp & dirtyOp;
Uint32 operation = AccKeyReq::getOperation(Treqinfo);
if (operation == ZREFRESH)
operation = ZWRITE; /* Insert if !exist, otherwise lock */
Uint32 opbits = 0;
opbits |= operation;
opbits |= readOp ? 0 : (Uint32) Operationrec::OP_LOCK_MODE;
opbits |= readOp ? 0 : (Uint32) Operationrec::OP_ACC_LOCK_MODE;
opbits |= dirtyReadOp ? (Uint32) Operationrec::OP_DIRTY_READ : 0;
if (AccKeyReq::getLockReq(Treqinfo))
{
opbits |= Operationrec::OP_LOCK_REQ; // TUX LOCK_REQ
/**
* A lock req has SCAN_OP, it can't delete a row,
* so OP_COMMIT_DELETE_CHECK is set like for SCAN
* see initScanOpRec
*/
opbits |= Operationrec::OP_COMMIT_DELETE_CHECK;
/**
* TODO: Looking at it now, I think it would be more natural
* to treat it as a ZREAD...
*/
}
//operationRecPtr.p->nodeType = AccKeyReq::getReplicaType(Treqinfo);
operationRecPtr.p->fid = fragrecptr.p->myfid;
operationRecPtr.p->fragptr = fragrecptr.i;
operationRecPtr.p->nextParallelQue = RNIL;
operationRecPtr.p->prevParallelQue = RNIL;
operationRecPtr.p->nextSerialQue = RNIL;
operationRecPtr.p->prevSerialQue = RNIL;
operationRecPtr.p->elementPage = RNIL;
operationRecPtr.p->scanRecPtr = RNIL;
operationRecPtr.p->m_op_bits = opbits;
NdbTick_Invalidate(&operationRecPtr.p->m_lockTime);
// bit to mark lock operation
// undo log is not run via ACCKEYREQ
if (operationRecPtr.p->tupkeylen == 0)
{
NDB_STATIC_ASSERT(AccKeyReq::SignalLength_localKey == 10);
ndbassert(siglen == AccKeyReq::SignalLength_localKey);
}
else
{
NDB_STATIC_ASSERT(AccKeyReq::SignalLength_keyInfo == 8);
ndbassert(siglen == AccKeyReq::SignalLength_keyInfo + operationRecPtr.p->tupkeylen);
}
}//Dbacc::initOpRec()
/* --------------------------------------------------------------------------------- */
/* SEND_ACCKEYCONF */
/* --------------------------------------------------------------------------------- */
void Dbacc::sendAcckeyconf(Signal* signal) const
{
signal->theData[0] = operationRecPtr.p->userptr;
signal->theData[1] = operationRecPtr.p->m_op_bits & Operationrec::OP_MASK;
signal->theData[2] = operationRecPtr.p->fid;
signal->theData[3] = operationRecPtr.p->localdata.m_page_no;
signal->theData[4] = operationRecPtr.p->localdata.m_page_idx;
}//Dbacc::sendAcckeyconf()
/* ******************--------------------------------------------------------------- */
/* ACCKEYREQ REQUEST FOR INSERT, DELETE, */
/* RERAD AND UPDATE, A TUPLE. */
/* SENDER: LQH, LEVEL B */
/* SIGNAL DATA: OPERATION_REC_PTR, CONNECTION PTR */
/* TABPTR, TABLE ID = TABLE RECORD POINTER */
/* TREQINFO, */
/* THASHVALUE, HASH VALUE OF THE TUP */
/* TKEYLEN, LENGTH OF THE PRIMARY KEYS */
/* TKEY1, PRIMARY KEY 1 */
/* TKEY2, PRIMARY KEY 2 */
/* TKEY3, PRIMARY KEY 3 */
/* TKEY4, PRIMARY KEY 4 */
/* ******************--------------------------------------------------------------- */
void Dbacc::execACCKEYREQ(Signal* signal)
{
jamEntry();
AccKeyReq* const req = reinterpret_cast<AccKeyReq*>(&signal->theData[0]);
operationRecPtr.i = req->connectPtr; /* CONNECTION PTR */
fragrecptr.i = req->fragmentPtr; /* FRAGMENT RECORD POINTER */
ndbrequire((operationRecPtr.i < coprecsize) ||
(fragrecptr.i < cfragmentsize));
ptrAss(operationRecPtr, operationrec);
ptrAss(fragrecptr, fragmentrec);
ndbrequire(operationRecPtr.p->m_op_bits == Operationrec::OP_INITIAL);
initOpRec(req, signal->getLength());
// normalize key if any char attr
if (operationRecPtr.p->tupkeylen && fragrecptr.p->hasCharAttr)
xfrmKeyData(req);
/*---------------------------------------------------------------*/
/* */
/* WE WILL USE THE HASH VALUE TO LOOK UP THE PROPER MEMORY */
/* PAGE AND MEMORY PAGE INDEX TO START THE SEARCH WITHIN. */
/* WE REMEMBER THESE ADDRESS IF WE LATER NEED TO INSERT */
/* THE ITEM AFTER NOT FINDING THE ITEM. */
/*---------------------------------------------------------------*/
OperationrecPtr lockOwnerPtr;
Page8Ptr bucketPageptr;
Uint32 bucketConidx;
Page8Ptr elemPageptr;
Uint32 elemConptr;
Uint32 elemptr;
const Uint32 found = getElement(req,
lockOwnerPtr,
bucketPageptr,
bucketConidx,
elemPageptr,
elemConptr,
elemptr);
Uint32 opbits = operationRecPtr.p->m_op_bits;
if (AccKeyReq::getTakeOver(req->requestInfo))
{
/* Verify that lock taken over and operation are on same
* element by checking that lockOwner match.
*/
OperationrecPtr lockOpPtr;
lockOpPtr.i = req->lockConnectPtr;
ptrAss(lockOpPtr, operationrec);
if (lockOwnerPtr.i == RNIL ||
!(lockOwnerPtr.i == lockOpPtr.i ||
lockOwnerPtr.i == lockOpPtr.p->m_lock_owner_ptr_i))
{
signal->theData[0] = cminusOne;
signal->theData[1] = ZTO_OP_STATE_ERROR;
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
return; /* Take over failed */
}
signal->theData[1] = req->lockConnectPtr;
signal->theData[2] = operationRecPtr.p->transId1;
signal->theData[3] = operationRecPtr.p->transId2;
execACC_TO_REQ(signal);
if (signal->theData[0] == cminusOne)
{
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
ndbassert(signal->theData[1] == ZTO_OP_STATE_ERROR);
return; /* Take over failed */
}
}
Uint32 op = opbits & Operationrec::OP_MASK;
if (found == ZTRUE)
{
switch (op) {
case ZREAD:
case ZUPDATE:
case ZDELETE:
case ZWRITE:
case ZSCAN_OP:
if (!lockOwnerPtr.p)
{
if(op == ZWRITE)
{
jam();
opbits &= ~(Uint32)Operationrec::OP_MASK;
opbits |= (op = ZUPDATE);
operationRecPtr.p->m_op_bits = opbits; // store to get correct ACCKEYCONF
}
opbits |= Operationrec::OP_STATE_RUNNING;
opbits |= Operationrec::OP_RUN_QUEUE;
c_tup->prepareTUPKEYREQ(operationRecPtr.p->localdata.m_page_no,
operationRecPtr.p->localdata.m_page_idx,
fragrecptr.p->tupFragptr);
sendAcckeyconf(signal);
if (! (opbits & Operationrec::OP_DIRTY_READ)) {
/*---------------------------------------------------------------*/
// It is not a dirty read. We proceed by locking and continue with
// the operation.
/*---------------------------------------------------------------*/
Uint32 eh = elemPageptr.p->word32[elemptr];
operationRecPtr.p->reducedHashValue = ElementHeader::getReducedHashValue(eh);
operationRecPtr.p->elementPage = elemPageptr.i;
operationRecPtr.p->elementContainer = elemConptr;
operationRecPtr.p->elementPointer = elemptr;
eh = ElementHeader::setLocked(operationRecPtr.i);
dbgWord32(elemPageptr, elemptr, eh);
elemPageptr.p->word32[elemptr] = eh;
opbits |= Operationrec::OP_LOCK_OWNER;
insertLockOwnersList(operationRecPtr);
fragrecptr.p->
m_lockStats.req_start_imm_ok((opbits &
Operationrec::OP_LOCK_MODE)
!= ZREADLOCK,
operationRecPtr.p->m_lockTime,
getHighResTimer());
} else {
jam();
/*---------------------------------------------------------------*/
// It is a dirty read. We do not lock anything. Set state to
// IDLE since no COMMIT call will come.
/*---------------------------------------------------------------*/
opbits = Operationrec::OP_EXECUTED_DIRTY_READ;
}//if
operationRecPtr.p->m_op_bits = opbits;
return;
} else {
jam();
accIsLockedLab(signal, lockOwnerPtr);
return;
}//if
break;
case ZINSERT:
jam();
insertExistElemLab(signal, lockOwnerPtr);
return;
break;
default:
ndbrequire(false);
break;
}//switch
} else if (found == ZFALSE) {
switch (op){
case ZWRITE:
opbits &= ~(Uint32)Operationrec::OP_MASK;
opbits |= (op = ZINSERT);
case ZINSERT:
jam();
opbits |= Operationrec::OP_INSERT_IS_DONE;
opbits |= Operationrec::OP_STATE_RUNNING;
opbits |= Operationrec::OP_RUN_QUEUE;
operationRecPtr.p->m_op_bits = opbits;
insertelementLab(signal, bucketPageptr, bucketConidx);
return;
break;
case ZREAD:
case ZUPDATE:
case ZDELETE:
case ZSCAN_OP:
jam();
acckeyref1Lab(signal, ZREAD_ERROR);
return;
break;
default:
ndbrequire(false);
break;
}//switch
} else {
jam();
acckeyref1Lab(signal, found);
return;
}//if
return;
}//Dbacc::execACCKEYREQ()
void
Dbacc::execACCKEY_ORD(Signal* signal, Uint32 opPtrI)
{
jamEntry();
OperationrecPtr lastOp;
lastOp.i = opPtrI;
ptrCheckGuard(lastOp, coprecsize, operationrec);
Uint32 opbits = lastOp.p->m_op_bits;
Uint32 opstate = opbits & Operationrec::OP_STATE_MASK;
if (likely(opbits == Operationrec::OP_EXECUTED_DIRTY_READ))
{
jam();
lastOp.p->m_op_bits = Operationrec::OP_INITIAL;
return;
}
else if (likely(opstate == Operationrec::OP_STATE_RUNNING))
{
opbits |= Operationrec::OP_STATE_EXECUTED;
lastOp.p->m_op_bits = opbits;
startNext(signal, lastOp);
return;
}
else
{
}
ndbout_c("bits: %.8x state: %.8x", opbits, opstate);
ndbrequire(false);
}
void
Dbacc::startNext(Signal* signal, OperationrecPtr lastOp)
{
jam();
OperationrecPtr nextOp;
OperationrecPtr loPtr;
OperationrecPtr tmp;
nextOp.i = lastOp.p->nextParallelQue;
loPtr.i = lastOp.p->m_lock_owner_ptr_i;
Uint32 opbits = lastOp.p->m_op_bits;
if ((opbits & Operationrec::OP_STATE_MASK)!= Operationrec::OP_STATE_EXECUTED)
{
jam();
return;
}
Uint32 nextbits;
if (nextOp.i != RNIL)
{
jam();
ptrCheckGuard(nextOp, coprecsize, operationrec);
nextbits = nextOp.p->m_op_bits;
goto checkop;
}
if ((opbits & Operationrec::OP_LOCK_OWNER) == 0)
{
jam();
ptrCheckGuard(loPtr, coprecsize, operationrec);
}
else
{
jam();
loPtr = lastOp;
}
nextOp.i = loPtr.p->nextSerialQue;
ndbassert(loPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER);
if (nextOp.i == RNIL)
{
jam();
return;
}
/**
* There is an op in serie queue...
* Check if it can run
*/
ptrCheckGuard(nextOp, coprecsize, operationrec);
nextbits = nextOp.p->m_op_bits;
{
const bool same = nextOp.p->is_same_trans(lastOp.p);
if (!same && ((opbits & Operationrec::OP_ACC_LOCK_MODE) ||
(nextbits & Operationrec::OP_LOCK_MODE)))
{
jam();
/**
* Not same transaction
* and either last had exclusive lock
* or next had exclusive lock
*/
return;
}
/**
* same trans and X-lock
*/
if (same && (opbits & Operationrec::OP_ACC_LOCK_MODE))
{
jam();
goto upgrade;
}
}
/**
* all shared lock...
*/
if ((opbits & Operationrec::OP_ACC_LOCK_MODE) == 0 &&
(nextbits & Operationrec::OP_LOCK_MODE) == 0)
{
jam();
goto upgrade;
}
/**
* There is a shared parallell queue & and exclusive op is first in queue
*/
ndbassert((opbits & Operationrec::OP_ACC_LOCK_MODE) == 0 &&
(nextbits & Operationrec::OP_LOCK_MODE));
/**
* We must check if there are many transactions in parallel queue...
*/
tmp= loPtr;
while (tmp.i != RNIL)
{
ptrCheckGuard(tmp, coprecsize, operationrec);
if (!nextOp.p->is_same_trans(tmp.p))
{
jam();
/**
* parallel queue contained another transaction, dont let it run
*/
return;
}
tmp.i = tmp.p->nextParallelQue;
}
upgrade:
/**
* Move first op in serie queue to end of parallell queue
*/
tmp.i = loPtr.p->nextSerialQue = nextOp.p->nextSerialQue;
loPtr.p->m_lo_last_parallel_op_ptr_i = nextOp.i;
nextOp.p->nextSerialQue = RNIL;
nextOp.p->prevSerialQue = RNIL;
nextOp.p->m_lock_owner_ptr_i = loPtr.i;
nextOp.p->prevParallelQue = lastOp.i;
lastOp.p->nextParallelQue = nextOp.i;
if (tmp.i != RNIL)
{
jam();
ptrCheckGuard(tmp, coprecsize, operationrec);
tmp.p->prevSerialQue = loPtr.i;
}
else
{
jam();
loPtr.p->m_lo_last_serial_op_ptr_i = RNIL;
}
nextbits |= Operationrec::OP_RUN_QUEUE;
/**
* Currently no grouping of ops in serie queue
*/
ndbrequire(nextOp.p->nextParallelQue == RNIL);
/**
* Track end-of-wait
*/
{
FragmentrecPtr frp;
frp.i = nextOp.p->fragptr;
ptrCheckGuard(frp, cfragmentsize, fragmentrec);
frp.p->m_lockStats.wait_ok(((nextbits &
Operationrec::OP_LOCK_MODE)
!= ZREADLOCK),
nextOp.p->m_lockTime,
getHighResTimer());
}
checkop:
Uint32 errCode = 0;
OperationrecPtr save = operationRecPtr;
operationRecPtr = nextOp;
Uint32 lastop = opbits & Operationrec::OP_MASK;
Uint32 nextop = nextbits & Operationrec::OP_MASK;
nextbits &= nextbits & ~(Uint32)Operationrec::OP_STATE_MASK;
nextbits |= Operationrec::OP_STATE_RUNNING;
/*
* bug#19031389
* Consider transactions such as read-0,read-1,read-2,delete-3.
* Read-N commits come from TC while delete-3 commit comes from
* backup replica. In MT kernel delete-3 commit can come first.
* Then at read-0 commit there is no ZDELETE left. But all
* ops in parallel queue have been marked OP_ELEMENT_DISAPPEARED.
* So also check for that bit.
*/
if (lastop == ZDELETE ||
(lastOp.p->m_op_bits & Operationrec::OP_ELEMENT_DISAPPEARED))
{
jam();
if (nextop != ZINSERT && nextop != ZWRITE)
{
errCode = ZREAD_ERROR;
goto ref;
}
nextbits &= ~(Uint32)Operationrec::OP_MASK;
nextbits &= ~(Uint32)Operationrec::OP_ELEMENT_DISAPPEARED;
nextbits |= (nextop = ZINSERT);
goto conf;
}
else if (nextop == ZINSERT)
{
jam();
errCode = ZWRITE_ERROR;
goto ref;
}
else if (nextop == ZWRITE)
{
jam();
nextbits &= ~(Uint32)Operationrec::OP_MASK;
nextbits |= (nextop = ZUPDATE);
goto conf;
}
else
{
jam();
}
conf:
nextOp.p->m_op_bits = nextbits;
nextOp.p->localdata = lastOp.p->localdata;
if (nextop == ZSCAN_OP && (nextbits & Operationrec::OP_LOCK_REQ) == 0)
{
jam();
takeOutScanLockQueue(nextOp.p->scanRecPtr);
putReadyScanQueue(nextOp.p->scanRecPtr);
}
else
{
jam();
fragrecptr.i = nextOp.p->fragptr;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
sendAcckeyconf(signal);
sendSignal(nextOp.p->userblockref, GSN_ACCKEYCONF,
signal, 6, JBB);
}
operationRecPtr = save;
return;
ref:
nextOp.p->m_op_bits = nextbits;
if (nextop == ZSCAN_OP && (nextbits & Operationrec::OP_LOCK_REQ) == 0)
{
jam();
nextOp.p->m_op_bits |= Operationrec::OP_ELEMENT_DISAPPEARED;
takeOutScanLockQueue(nextOp.p->scanRecPtr);
putReadyScanQueue(nextOp.p->scanRecPtr);
}
else
{
jam();
signal->theData[0] = nextOp.p->userptr;
signal->theData[1] = errCode;
sendSignal(nextOp.p->userblockref, GSN_ACCKEYREF, signal,
2, JBB);
}
operationRecPtr = save;
return;
}
void
Dbacc::xfrmKeyData(AccKeyReq* signal)const
{
Uint32 table = fragrecptr.p->myTableId;
Uint32 dst[MAX_KEY_SIZE_IN_WORDS * MAX_XFRM_MULTIPLY];
Uint32 keyPartLen[MAX_ATTRIBUTES_IN_INDEX];
Uint32* const src = signal->keyInfo;
Uint32 len = xfrm_key(table, src, dst, sizeof(dst) >> 2, keyPartLen);
ndbrequire(len); // 0 means error
memcpy(src, dst, len << 2);
operationRecPtr.p->xfrmtupkeylen = len;
}
void
Dbacc::accIsLockedLab(Signal* signal, OperationrecPtr lockOwnerPtr) const
{
Uint32 bits = operationRecPtr.p->m_op_bits;
validate_lock_queue(lockOwnerPtr);
if ((bits & Operationrec::OP_DIRTY_READ) == 0){
Uint32 return_result;
if ((bits & Operationrec::OP_LOCK_MODE) == ZREADLOCK) {
jam();
return_result = placeReadInLockQueue(lockOwnerPtr);
} else {
jam();
return_result = placeWriteInLockQueue(lockOwnerPtr);
}//if
if (return_result == ZPARALLEL_QUEUE) {
jam();
c_tup->prepareTUPKEYREQ(operationRecPtr.p->localdata.m_page_no,
operationRecPtr.p->localdata.m_page_idx,
fragrecptr.p->tupFragptr);
fragrecptr.p->m_lockStats.req_start_imm_ok((bits &
Operationrec::OP_LOCK_MODE)
!= ZREADLOCK,
operationRecPtr.p->m_lockTime,
getHighResTimer());
sendAcckeyconf(signal);
return;
} else if (return_result == ZSERIAL_QUEUE) {
jam();
fragrecptr.p->m_lockStats.req_start((bits &
Operationrec::OP_LOCK_MODE)
!= ZREADLOCK,
operationRecPtr.p->m_lockTime,
getHighResTimer());
signal->theData[0] = RNIL;
return;
} else {
jam();
acckeyref1Lab(signal, return_result);
return;
}//if
ndbrequire(false);
}
else
{
if (! (lockOwnerPtr.p->m_op_bits & Operationrec::OP_ELEMENT_DISAPPEARED) &&
! lockOwnerPtr.p->localdata.isInvalid())
{
jam();
/* ---------------------------------------------------------------
* It is a dirty read. We do not lock anything. Set state to
*IDLE since no COMMIT call will arrive.
* ---------------------------------------------------------------*/
c_tup->prepareTUPKEYREQ(operationRecPtr.p->localdata.m_page_no,
operationRecPtr.p->localdata.m_page_idx,
fragrecptr.p->tupFragptr);
sendAcckeyconf(signal);
operationRecPtr.p->m_op_bits = Operationrec::OP_EXECUTED_DIRTY_READ;
return;
}
else
{
jam();
/*---------------------------------------------------------------*/
// The tuple does not exist in the committed world currently.
// Report read error.
/*---------------------------------------------------------------*/
acckeyref1Lab(signal, ZREAD_ERROR);
return;
}//if
}//if
}//Dbacc::accIsLockedLab()
/* ------------------------------------------------------------------------ */
/* I N S E R T E X I S T E L E M E N T */
/* ------------------------------------------------------------------------ */
void Dbacc::insertExistElemLab(Signal* signal,
OperationrecPtr lockOwnerPtr) const
{
if (!lockOwnerPtr.p)
{
jam();
acckeyref1Lab(signal, ZWRITE_ERROR);/* THE ELEMENT ALREADY EXIST */
return;
}//if
accIsLockedLab(signal, lockOwnerPtr);
}//Dbacc::insertExistElemLab()
/* --------------------------------------------------------------------------------- */
/* INSERTELEMENT */
/* --------------------------------------------------------------------------------- */
void Dbacc::insertelementLab(Signal* signal,
Page8Ptr bucketPageptr,
Uint32 bucketConidx)
{
if (unlikely(m_oom))
{
jam();
acckeyref1Lab(signal, ZPAGESIZE_ERROR);
return;
}
if (unlikely(fragrecptr.p->dirRangeFull))
{
jam();
acckeyref1Lab(signal, ZDIR_RANGE_FULL_ERROR);
return;
}
if (fragrecptr.p->sparsepages.isEmpty())
{
jam();
allocOverflowPage();
if (tresult > ZLIMIT_OF_ERROR) {
jam();
acckeyref1Lab(signal, tresult);
return;
}//if
}//if
ndbrequire(operationRecPtr.p->tupkeylen <= fragrecptr.p->keyLength);
ndbassert(!(operationRecPtr.p->m_op_bits & Operationrec::OP_LOCK_REQ));
insertLockOwnersList(operationRecPtr);
operationRecPtr.p->reducedHashValue = fragrecptr.p->level.reduce(operationRecPtr.p->hashValue);
const Uint32 tidrElemhead = ElementHeader::setLocked(operationRecPtr.i);
Page8Ptr idrPageptr;
idrPageptr = bucketPageptr;
Uint32 tidrPageindex = bucketConidx;
bool isforward = true;
ndbrequire(fragrecptr.p->localkeylen == 1);
/* ----------------------------------------------------------------------- */
/* WE SET THE LOCAL KEY TO MINUS ONE TO INDICATE IT IS NOT YET VALID. */
/* ----------------------------------------------------------------------- */
Local_key localKey;
localKey.setInvalid();
operationRecPtr.p->localdata = localKey;
Uint32 conptr;
insertElement(Element(tidrElemhead, localKey.m_page_no),
operationRecPtr,
idrPageptr,
tidrPageindex,
isforward,
conptr,
Operationrec::ANY_SCANBITS,
false);
fragrecptr.p->m_lockStats.req_start_imm_ok(true /* Exclusive */,
operationRecPtr.p->m_lockTime,
getHighResTimer());
c_tup->prepareTUPKEYREQ(localKey.m_page_no, localKey.m_page_idx, fragrecptr.p->tupFragptr);
sendAcckeyconf(signal);
return;
}//Dbacc::insertelementLab()
/* ------------------------------------------------------------------------ */
/* GET_NO_PARALLEL_TRANSACTION */
/* ------------------------------------------------------------------------ */
Uint32
Dbacc::getNoParallelTransaction(const Operationrec * op) const
{
OperationrecPtr tmp;
tmp.i= op->nextParallelQue;
Uint32 transId[2] = { op->transId1, op->transId2 };
while (tmp.i != RNIL)
{
jam();
ptrCheckGuard(tmp, coprecsize, operationrec);
if (tmp.p->transId1 == transId[0] && tmp.p->transId2 == transId[1])
tmp.i = tmp.p->nextParallelQue;
else
return 2;
}
return 1;
}//Dbacc::getNoParallelTransaction()
#ifdef VM_TRACE
Uint32
Dbacc::getNoParallelTransactionFull(const Operationrec * op) const
{
ConstPtr<Operationrec> tmp;
tmp.p = op;
while ((tmp.p->m_op_bits & Operationrec::OP_LOCK_OWNER) == 0)
{
tmp.i = tmp.p->prevParallelQue;
if (tmp.i != RNIL)
{
ptrCheckGuard(tmp, coprecsize, operationrec);
}
else
{
break;
}
}
return getNoParallelTransaction(tmp.p);
}
#endif
#ifdef ACC_SAFE_QUEUE
Uint32
Dbacc::get_parallel_head(OperationrecPtr opPtr) const
{
while ((opPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER) == 0 &&
opPtr.p->prevParallelQue != RNIL)
{
opPtr.i = opPtr.p->prevParallelQue;
ptrCheckGuard(opPtr, coprecsize, operationrec);
}
return opPtr.i;
}
bool
Dbacc::validate_lock_queue(OperationrecPtr opPtr)const
{
OperationrecPtr loPtr;
loPtr.i = get_parallel_head(opPtr);
ptrCheckGuard(loPtr, coprecsize, operationrec);
while((loPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER) == 0 &&
loPtr.p->prevSerialQue != RNIL)
{
loPtr.i = loPtr.p->prevSerialQue;
ptrCheckGuard(loPtr, coprecsize, operationrec);
}
// Now we have lock owner...
vlqrequire(loPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER);
vlqrequire(loPtr.p->m_op_bits & Operationrec::OP_RUN_QUEUE);
// 1 Validate page pointer
{
Page8Ptr pagePtr;
pagePtr.i = loPtr.p->elementPage;
ptrCheckGuard(pagePtr, cpagesize, page8);
arrGuard(loPtr.p->elementPointer, 2048);
Uint32 eh = pagePtr.p->word32[loPtr.p->elementPointer];
vlqrequire(ElementHeader::getLocked(eh));
vlqrequire(ElementHeader::getOpPtrI(eh) == loPtr.i);
}
// 2 Lock owner should always have same LOCK_MODE and ACC_LOCK_MODE
if (loPtr.p->m_op_bits & Operationrec::OP_LOCK_MODE)
{
vlqrequire(loPtr.p->m_op_bits & Operationrec::OP_ACC_LOCK_MODE);
}
else
{
vlqrequire((loPtr.p->m_op_bits & Operationrec::OP_ACC_LOCK_MODE) == 0);
}
// 3 Lock owner should never be waiting...
bool running = false;
{
Uint32 opstate = loPtr.p->m_op_bits & Operationrec::OP_STATE_MASK;
if (opstate == Operationrec::OP_STATE_RUNNING)
running = true;
else
{
vlqrequire(opstate == Operationrec::OP_STATE_EXECUTED);
}
}
// Validate parallel queue
{
bool many = false;
bool orlockmode = loPtr.p->m_op_bits & Operationrec::OP_LOCK_MODE;
OperationrecPtr lastP = loPtr;
while (lastP.p->nextParallelQue != RNIL)
{
Uint32 prev = lastP.i;
lastP.i = lastP.p->nextParallelQue;
ptrCheckGuard(lastP, coprecsize, operationrec);
vlqrequire(lastP.p->prevParallelQue == prev);
Uint32 opbits = lastP.p->m_op_bits;
many |= loPtr.p->is_same_trans(lastP.p) ? 0 : 1;
orlockmode |= !!(opbits & Operationrec::OP_LOCK_MODE);
vlqrequire(opbits & Operationrec::OP_RUN_QUEUE);
vlqrequire((opbits & Operationrec::OP_LOCK_OWNER) == 0);
Uint32 opstate = opbits & Operationrec::OP_STATE_MASK;
if (running)
{
// If I found a running operation,
// all following should be waiting
vlqrequire(opstate == Operationrec::OP_STATE_WAITING);
}
else
{
if (opstate == Operationrec::OP_STATE_RUNNING)
running = true;
else
vlqrequire(opstate == Operationrec::OP_STATE_EXECUTED);
}
if (lastP.p->m_op_bits & Operationrec::OP_LOCK_MODE)
{
vlqrequire(lastP.p->m_op_bits & Operationrec::OP_ACC_LOCK_MODE);
}
else
{
vlqrequire((lastP.p->m_op_bits && orlockmode) == orlockmode);
vlqrequire((lastP.p->m_op_bits & Operationrec::OP_MASK) == ZREAD ||
(lastP.p->m_op_bits & Operationrec::OP_MASK) == ZSCAN_OP);
}
if (many)
{
vlqrequire(orlockmode == 0);
}
}
if (lastP.i != loPtr.i)
{
vlqrequire(loPtr.p->m_lo_last_parallel_op_ptr_i == lastP.i);
vlqrequire(lastP.p->m_lock_owner_ptr_i == loPtr.i);
}
else
{
vlqrequire(loPtr.p->m_lo_last_parallel_op_ptr_i == RNIL);
}
}
// Validate serie queue
if (loPtr.p->nextSerialQue != RNIL)
{
Uint32 prev = loPtr.i;
OperationrecPtr lastS;
lastS.i = loPtr.p->nextSerialQue;
while (true)
{
ptrCheckGuard(lastS, coprecsize, operationrec);
vlqrequire(lastS.p->prevSerialQue == prev);
vlqrequire(getNoParallelTransaction(lastS.p) == 1);
vlqrequire((lastS.p->m_op_bits & Operationrec::OP_LOCK_OWNER) == 0);
vlqrequire((lastS.p->m_op_bits & Operationrec::OP_RUN_QUEUE) == 0);
vlqrequire((lastS.p->m_op_bits & Operationrec::OP_STATE_MASK) == Operationrec::OP_STATE_WAITING);
if (lastS.p->nextSerialQue == RNIL)
break;
prev = lastS.i;
lastS.i = lastS.p->nextSerialQue;
}
vlqrequire(loPtr.p->m_lo_last_serial_op_ptr_i == lastS.i);
}
else
{
vlqrequire(loPtr.p->m_lo_last_serial_op_ptr_i == RNIL);
}
return true;
}
NdbOut&
operator<<(NdbOut & out, Dbacc::OperationrecPtr ptr)
{
Uint32 opbits = ptr.p->m_op_bits;
out << "[ " << dec << ptr.i
<< " [ " << hex << ptr.p->transId1
<< " " << hex << ptr.p->transId2 << "] "
<< " bits: H'" << hex << opbits << " ";
bool read = false;
switch(opbits & Dbacc::Operationrec::OP_MASK){
case ZREAD: out << "READ "; read = true; break;
case ZINSERT: out << "INSERT "; break;
case ZUPDATE: out << "UPDATE "; break;
case ZDELETE: out << "DELETE "; break;
case ZWRITE: out << "WRITE "; break;
case ZSCAN_OP: out << "SCAN "; read = true; break;
default:
out << "<Unknown: H'"
<< hex << (opbits & Dbacc::Operationrec::OP_MASK)
<< "> ";
}
if (read)
{
if (opbits & Dbacc::Operationrec::OP_LOCK_MODE)
out << "(X)";
else
out << "(S)";
if (opbits & Dbacc::Operationrec::OP_ACC_LOCK_MODE)
out << "(X)";
else
out << "(S)";
}
if (opbits)
{
out << "(RQ)";
}
switch(opbits & Dbacc::Operationrec::OP_STATE_MASK){
case Dbacc::Operationrec::OP_STATE_WAITING:
out << " WAITING "; break;
case Dbacc::Operationrec::OP_STATE_RUNNING:
out << " RUNNING "; break;
case Dbacc::Operationrec::OP_STATE_EXECUTED:
out << " EXECUTED "; break;
case Dbacc::Operationrec::OP_STATE_IDLE:
out << " IDLE "; break;
default:
out << " <Unknown: H'"
<< hex << (opbits & Dbacc::Operationrec::OP_STATE_MASK)
<< "> ";
}
/*
OP_MASK = 0x000F // 4 bits for operation type
,OP_LOCK_MODE = 0x0010 // 0 - shared lock, 1 = exclusive lock
,OP_ACC_LOCK_MODE = 0x0020 // Or:de lock mode of all operation
// before me
,OP_LOCK_OWNER = 0x0040
,OP_DIRTY_READ = 0x0080
,OP_LOCK_REQ = 0x0100 // isAccLockReq
,OP_COMMIT_DELETE_CHECK = 0x0200
,OP_INSERT_IS_DONE = 0x0400
,OP_ELEMENT_DISAPPEARED = 0x0800
,OP_STATE_MASK = 0xF000
,OP_STATE_IDLE = 0xF000
,OP_STATE_WAITING = 0x0000
,OP_STATE_RUNNING = 0x1000
,OP_STATE_EXECUTED = 0x3000
};
*/
if (opbits & Dbacc::Operationrec::OP_LOCK_OWNER)
out << "LO ";
if (opbits & Dbacc::Operationrec::OP_DIRTY_READ)
out << "DR ";
if (opbits & Dbacc::Operationrec::OP_LOCK_REQ)
out << "LOCK_REQ ";
if (opbits & Dbacc::Operationrec::OP_COMMIT_DELETE_CHECK)
out << "COMMIT_DELETE_CHECK ";
if (opbits & Dbacc::Operationrec::OP_INSERT_IS_DONE)
out << "INSERT_IS_DONE ";
if (opbits & Dbacc::Operationrec::OP_ELEMENT_DISAPPEARED)
out << "ELEMENT_DISAPPEARED ";
if (opbits & Dbacc::Operationrec::OP_LOCK_OWNER)
{
out << "last_parallel: " << dec << ptr.p->m_lo_last_parallel_op_ptr_i << " ";
out << "last_serial: " << dec << ptr.p->m_lo_last_serial_op_ptr_i << " ";
}
out << "]";
return out;
}
void
Dbacc::dump_lock_queue(OperationrecPtr loPtr)const
{
if ((loPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER) == 0)
{
while ((loPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER) == 0 &&
loPtr.p->prevParallelQue != RNIL)
{
loPtr.i = loPtr.p->prevParallelQue;
ptrCheckGuard(loPtr, coprecsize, operationrec);
}
while ((loPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER) == 0 &&
loPtr.p->prevSerialQue != RNIL)
{
loPtr.i = loPtr.p->prevSerialQue;
ptrCheckGuard(loPtr, coprecsize, operationrec);
}
ndbassert(loPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER);
}
ndbout << "-- HEAD --" << endl;
OperationrecPtr tmp = loPtr;
while (tmp.i != RNIL)
{
ptrCheckGuard(tmp, coprecsize, operationrec);
ndbout << tmp << " ";
tmp.i = tmp.p->nextParallelQue;
if (tmp.i == loPtr.i)
{
ndbout << " <LOOP>";
break;
}
}
ndbout << endl;
tmp.i = loPtr.p->nextSerialQue;
while (tmp.i != RNIL)
{
ptrCheckGuard(tmp, coprecsize, operationrec);
OperationrecPtr tmp2 = tmp;
if (tmp.i == loPtr.i)
{
ndbout << "<LOOP S>" << endl;
break;
}
while (tmp2.i != RNIL)
{
ptrCheckGuard(tmp2, coprecsize, operationrec);
ndbout << tmp2 << " ";
tmp2.i = tmp2.p->nextParallelQue;
if (tmp2.i == tmp.i)
{
ndbout << "<LOOP 3>";
break;
}
}
ndbout << endl;
tmp.i = tmp.p->nextSerialQue;
}
}
#endif
/* -------------------------------------------------------------------------
* PLACE_WRITE_IN_LOCK_QUEUE
* INPUT: OPERATION_REC_PTR OUR OPERATION POINTER
* QUE_OPER_PTR LOCK QUEUE OWNER OPERATION POINTER
* PWI_PAGEPTR PAGE POINTER OF ELEMENT
* TPWI_ELEMENTPTR ELEMENT POINTER OF ELEMENT
* OUTPUT TRESULT =
* ZPARALLEL_QUEUE OPERATION PLACED IN PARALLEL QUEUE
* OPERATION CAN PROCEED NOW.
* ZSERIAL_QUEUE OPERATION PLACED IN SERIAL QUEUE
* ERROR CODE OPERATION NEEDS ABORTING
* ------------------------------------------------------------------------- */
Uint32
Dbacc::placeWriteInLockQueue(OperationrecPtr lockOwnerPtr) const
{
OperationrecPtr lastOpPtr;
lastOpPtr.i = lockOwnerPtr.p->m_lo_last_parallel_op_ptr_i;
Uint32 opbits = operationRecPtr.p->m_op_bits;
if (lastOpPtr.i == RNIL)
{
lastOpPtr = lockOwnerPtr;
}
else
{
ptrCheckGuard(lastOpPtr, coprecsize, operationrec);
}
ndbassert(get_parallel_head(lastOpPtr) == lockOwnerPtr.i);
Uint32 lastbits = lastOpPtr.p->m_op_bits;
if (lastbits & Operationrec::OP_ACC_LOCK_MODE)
{
if(operationRecPtr.p->is_same_trans(lastOpPtr.p))
{
goto checkop;
}
}
else
{
/**
* We dont have an exclusive lock on operation and
*
*/
jam();
/**
* Scan parallell queue to see if we are the only one
*/
OperationrecPtr loopPtr = lockOwnerPtr;
do
{
ptrCheckGuard(loopPtr, coprecsize, operationrec);
if (!loopPtr.p->is_same_trans(operationRecPtr.p))
{
goto serial;
}
loopPtr.i = loopPtr.p->nextParallelQue;
} while (loopPtr.i != RNIL);
goto checkop;
}
serial:
jam();
placeSerialQueue(lockOwnerPtr, operationRecPtr);
validate_lock_queue(lockOwnerPtr);
return ZSERIAL_QUEUE;
checkop:
/*
WE ARE PERFORMING AN READ EXCLUSIVE, INSERT, UPDATE OR DELETE IN THE SAME
TRANSACTION WHERE WE PREVIOUSLY HAVE EXECUTED AN OPERATION.
Read-All, Update-All, Insert-All and Delete-Insert are allowed
combinations.
Delete-Read, Delete-Update and Delete-Delete are not an allowed
combination and will result in tuple not found error.
*/
const Uint32 lstate = lastbits & Operationrec::OP_STATE_MASK;
Uint32 retValue = ZSERIAL_QUEUE; // So that it gets blocked...
if (lstate == Operationrec::OP_STATE_EXECUTED)
{
jam();
/**
* Since last operation has executed...we can now check operation types
* if not, we have to wait until it has executed
*/
const Uint32 op = opbits & Operationrec::OP_MASK;
const Uint32 lop = lastbits & Operationrec::OP_MASK;
if (op == ZINSERT && lop != ZDELETE)
{
jam();
return ZWRITE_ERROR;
}//if
/**
* NOTE. No checking op operation types, as one can read different save
* points...
*/
if(op == ZWRITE)
{
opbits &= ~(Uint32)Operationrec::OP_MASK;
opbits |= (lop == ZDELETE) ? ZINSERT : ZUPDATE;
}
opbits |= Operationrec::OP_STATE_RUNNING;
operationRecPtr.p->localdata = lastOpPtr.p->localdata;
retValue = ZPARALLEL_QUEUE;
}
opbits |= Operationrec::OP_RUN_QUEUE;
operationRecPtr.p->m_op_bits = opbits;
operationRecPtr.p->prevParallelQue = lastOpPtr.i;
operationRecPtr.p->m_lock_owner_ptr_i = lockOwnerPtr.i;
lastOpPtr.p->nextParallelQue = operationRecPtr.i;
lockOwnerPtr.p->m_lo_last_parallel_op_ptr_i = operationRecPtr.i;
validate_lock_queue(lockOwnerPtr);
return retValue;
}//Dbacc::placeWriteInLockQueue()
Uint32
Dbacc::placeReadInLockQueue(OperationrecPtr lockOwnerPtr) const
{
OperationrecPtr lastOpPtr;
OperationrecPtr loopPtr = lockOwnerPtr;
lastOpPtr.i = lockOwnerPtr.p->m_lo_last_parallel_op_ptr_i;
Uint32 opbits = operationRecPtr.p->m_op_bits;
if (lastOpPtr.i == RNIL)
{
lastOpPtr = lockOwnerPtr;
}
else
{
ptrCheckGuard(lastOpPtr, coprecsize, operationrec);
}
ndbassert(get_parallel_head(lastOpPtr) == lockOwnerPtr.i);
/**
* Last operation in parallell queue of lock owner is same trans
* and ACC_LOCK_MODE is exlusive, then we can proceed
*/
Uint32 lastbits = lastOpPtr.p->m_op_bits;
bool same = operationRecPtr.p->is_same_trans(lastOpPtr.p);
if (same && (lastbits & Operationrec::OP_ACC_LOCK_MODE))
{
jam();
opbits |= Operationrec::OP_LOCK_MODE; // Upgrade to X-lock
goto checkop;
}
if ((lastbits & Operationrec::OP_ACC_LOCK_MODE) && !same)
{
jam();
/**
* Last op in serial queue had X-lock and was not our transaction...
*/
goto serial;
}
if (lockOwnerPtr.p->nextSerialQue == RNIL)
{
jam();
goto checkop;
}
/**
* Scan parallell queue to see if we are already there...
*/
do
{
ptrCheckGuard(loopPtr, coprecsize, operationrec);
if (loopPtr.p->is_same_trans(operationRecPtr.p))
goto checkop;
loopPtr.i = loopPtr.p->nextParallelQue;
} while (loopPtr.i != RNIL);
serial:
placeSerialQueue(lockOwnerPtr, operationRecPtr);
validate_lock_queue(lockOwnerPtr);
return ZSERIAL_QUEUE;
checkop:
Uint32 lstate = lastbits & Operationrec::OP_STATE_MASK;
Uint32 retValue = ZSERIAL_QUEUE; // So that it gets blocked...
if (lstate == Operationrec::OP_STATE_EXECUTED)
{
jam();
/**
* NOTE. No checking op operation types, as one can read different save
* points...
*/
#if 0
/**
* Since last operation has executed...we can now check operation types
* if not, we have to wait until it has executed
*/
if (lop == ZDELETE)
{
jam();
return ZREAD_ERROR;
}
#endif
opbits |= Operationrec::OP_STATE_RUNNING;
operationRecPtr.p->localdata = lastOpPtr.p->localdata;
retValue = ZPARALLEL_QUEUE;
}
opbits |= (lastbits & Operationrec::OP_ACC_LOCK_MODE);
opbits |= Operationrec::OP_RUN_QUEUE;
operationRecPtr.p->m_op_bits = opbits;
operationRecPtr.p->prevParallelQue = lastOpPtr.i;
operationRecPtr.p->m_lock_owner_ptr_i = lockOwnerPtr.i;
lastOpPtr.p->nextParallelQue = operationRecPtr.i;
lockOwnerPtr.p->m_lo_last_parallel_op_ptr_i = operationRecPtr.i;
validate_lock_queue(lockOwnerPtr);
return retValue;
}//Dbacc::placeReadInLockQueue
void Dbacc::placeSerialQueue(OperationrecPtr lockOwnerPtr,
OperationrecPtr opPtr)const
{
OperationrecPtr lastOpPtr;
lastOpPtr.i = lockOwnerPtr.p->m_lo_last_serial_op_ptr_i;
if (lastOpPtr.i == RNIL)
{
// Lock owner is last...
ndbrequire(lockOwnerPtr.p->nextSerialQue == RNIL);
lastOpPtr = lockOwnerPtr;
}
else
{
ptrCheckGuard(lastOpPtr, coprecsize, operationrec);
}
operationRecPtr.p->prevSerialQue = lastOpPtr.i;
lastOpPtr.p->nextSerialQue = opPtr.i;
lockOwnerPtr.p->m_lo_last_serial_op_ptr_i = opPtr.i;
}
/* ------------------------------------------------------------------------- */
/* ACC KEYREQ END */
/* ------------------------------------------------------------------------- */
void Dbacc::acckeyref1Lab(Signal* signal, Uint32 result_code) const
{
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
/* ************************<< */
/* ACCKEYREF */
/* ************************<< */
signal->theData[0] = cminusOne;
signal->theData[1] = result_code;
return;
}//Dbacc::acckeyref1Lab()
/* ******************----------------------------------------------------- */
/* ACCMINUPDATE UPDATE LOCAL KEY REQ */
/* DESCRIPTION: UPDATES LOCAL KEY OF AN ELEMENTS IN THE HASH TABLE */
/* THIS SIGNAL IS WAITED AFTER ANY INSERT REQ */
/* ENTER ACCMINUPDATE WITH SENDER: LQH, LEVEL B */
/* OPERATION_REC_PTR, OPERATION RECORD PTR */
/* CLOCALKEY(0), LOCAL KEY 1 */
/* CLOCALKEY(1) LOCAL KEY 2 */
/* ******************----------------------------------------------------- */
void Dbacc::execACCMINUPDATE(Signal* signal)
{
Page8Ptr ulkPageidptr;
Uint32 tulkLocalPtr;
Local_key localkey;
jamEntry();
operationRecPtr.i = signal->theData[0];
localkey.m_page_no = signal->theData[1];
localkey.m_page_idx = signal->theData[2];
ptrCheckGuard(operationRecPtr, coprecsize, operationrec);
Uint32 opbits = operationRecPtr.p->m_op_bits;
fragrecptr.i = operationRecPtr.p->fragptr;
ulkPageidptr.i = operationRecPtr.p->elementPage;
tulkLocalPtr = operationRecPtr.p->elementPointer + 1;
if ((opbits & Operationrec::OP_STATE_MASK) == Operationrec::OP_STATE_RUNNING)
{
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
ptrCheckGuard(ulkPageidptr, cpagesize, page8);
dbgWord32(ulkPageidptr, tulkLocalPtr, tlocalkey1);
arrGuard(tulkLocalPtr, 2048);
operationRecPtr.p->localdata = localkey;
ndbrequire(fragrecptr.p->localkeylen == 1);
ulkPageidptr.p->word32[tulkLocalPtr] = localkey.m_page_no;
return;
}//if
ndbrequire(false);
}//Dbacc::execACCMINUPDATE()
void
Dbacc::removerow(Uint32 opPtrI, const Local_key* key)
{
jamEntry();
operationRecPtr.i = opPtrI;
ptrCheckGuard(operationRecPtr, coprecsize, operationrec);
Uint32 opbits = operationRecPtr.p->m_op_bits;
fragrecptr.i = operationRecPtr.p->fragptr;
/* Mark element disappeared */
opbits |= Operationrec::OP_ELEMENT_DISAPPEARED;
opbits &= ~Uint32(Operationrec::OP_COMMIT_DELETE_CHECK);
/**
* This function is (currently?) only used when refreshTuple()
* inserts a record...and later wants to remove it
*
* Since this should not affect row-count...we change the optype to UPDATE
* execACC_COMMITREQ will be called in same timeslice as this change...
*/
opbits &= ~Uint32(Operationrec::OP_MASK);
opbits |= ZUPDATE;
operationRecPtr.p->m_op_bits = opbits;
#ifdef VM_TRACE
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
ndbrequire(operationRecPtr.p->localdata.m_page_no == key->m_page_no);
ndbrequire(operationRecPtr.p->localdata.m_page_idx == key->m_page_idx);
#endif
}//Dbacc::execACCMINUPDATE()
/* ******************--------------------------------------------------------------- */
/* ACC_COMMITREQ COMMIT TRANSACTION */
/* SENDER: LQH, LEVEL B */
/* INPUT: OPERATION_REC_PTR , */
/* ******************--------------------------------------------------------------- */
void Dbacc::execACC_COMMITREQ(Signal* signal)
{
Uint8 Toperation;
jamEntry();
operationRecPtr.i = signal->theData[0];
ptrCheckGuard(operationRecPtr, coprecsize, operationrec);
#ifdef VM_TRACE
Uint32 tmp = operationRecPtr.i;
void* ptr = operationRecPtr.p;
#endif
Uint32 opbits = operationRecPtr.p->m_op_bits;
fragrecptr.i = operationRecPtr.p->fragptr;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
Toperation = opbits & Operationrec::OP_MASK;
commitOperation(signal);
ndbassert(operationRecPtr.i == tmp);
ndbassert(operationRecPtr.p == ptr);
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
if((Toperation != ZREAD) &&
(Toperation != ZSCAN_OP))
{
fragrecptr.p->m_commit_count++;
#ifdef ERROR_INSERT
bool force_expand_shrink = false;
if (ERROR_INSERTED(3004) &&
fragrecptr.p->fragmentid == 0 &&
fragrecptr.p->level.getSize() != ERROR_INSERT_EXTRA)
{
force_expand_shrink = true;
}
#endif
if (Toperation != ZINSERT) {
if (Toperation != ZDELETE) {
return;
} else {
jam();
#ifdef ERROR_INSERT
ndbrequire(fragrecptr.p->noOfElements > 0);
#else
ndbassert(fragrecptr.p->noOfElements > 0);
#endif
fragrecptr.p->noOfElements--;
fragrecptr.p->slack += fragrecptr.p->elementLength;
#ifdef ERROR_INSERT
if (force_expand_shrink || fragrecptr.p->slack > fragrecptr.p->slackCheck)
#else
if (fragrecptr.p->slack > fragrecptr.p->slackCheck)
#endif
{
/* TIME FOR JOIN BUCKETS PROCESS */
if (fragrecptr.p->expandCounter > 0) {
if (!fragrecptr.p->expandOrShrinkQueued)
{
jam();
signal->theData[0] = fragrecptr.i;
fragrecptr.p->expandOrShrinkQueued = true;
sendSignal(cownBlockref, GSN_SHRINKCHECK2, signal, 1, JBB);
}//if
}//if
}//if
}//if
} else {
jam(); /* EXPAND PROCESS HANDLING */
fragrecptr.p->noOfElements++;
fragrecptr.p->slack -= fragrecptr.p->elementLength;
#ifdef ERROR_INSERT
if ((force_expand_shrink || fragrecptr.p->slack < 0) &&
!fragrecptr.p->level.isFull())
#else
if (fragrecptr.p->slack < 0 && !fragrecptr.p->level.isFull())
#endif
{
/* IT MEANS THAT IF SLACK < ZERO */
if (!fragrecptr.p->expandOrShrinkQueued)
{
jam();
signal->theData[0] = fragrecptr.i;
fragrecptr.p->expandOrShrinkQueued = true;
sendSignal(cownBlockref, GSN_EXPANDCHECK2, signal, 1, JBB);
}//if
}//if
}
}
return;
}//Dbacc::execACC_COMMITREQ()
/* ******************------------------------------------------------------- */
/* ACC ABORT REQ ABORT ALL OPERATION OF THE TRANSACTION */
/* ******************------------------------------+ */
/* SENDER: LQH, LEVEL B */
/* ******************------------------------------------------------------- */
/* ACC ABORT REQ ABORT TRANSACTION */
/* ******************------------------------------+ */
/* SENDER: LQH, LEVEL B */
void Dbacc::execACC_ABORTREQ(Signal* signal)
{
jamEntry();
operationRecPtr.i = signal->theData[0];
Uint32 sendConf = signal->theData[1];
ptrCheckGuard(operationRecPtr, coprecsize, operationrec);
fragrecptr.i = operationRecPtr.p->fragptr;
Uint32 opbits = operationRecPtr.p->m_op_bits;
Uint32 opstate = opbits & Operationrec::OP_STATE_MASK;
tresult = 0; /* ZFALSE */
if (opbits == Operationrec::OP_EXECUTED_DIRTY_READ)
{
jam();
}
else if (opstate == Operationrec::OP_STATE_EXECUTED ||
opstate == Operationrec::OP_STATE_WAITING ||
opstate == Operationrec::OP_STATE_RUNNING)
{
jam();
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
abortOperation(signal);
}
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
signal->theData[0] = operationRecPtr.p->userptr;
signal->theData[1] = 0;
switch(sendConf){
case 0:
return;
case 2:
if (opstate != Operationrec::OP_STATE_RUNNING)
{
return;
}
case 1:
sendSignal(operationRecPtr.p->userblockref, GSN_ACC_ABORTCONF,
signal, 1, JBB);
}
signal->theData[1] = RNIL;
}
/*
* Lock or unlock tuple.
*/
void Dbacc::execACC_LOCKREQ(Signal* signal)
{
jamEntry();
AccLockReq* sig = (AccLockReq*)signal->getDataPtrSend();
AccLockReq reqCopy = *sig;
AccLockReq* const req = &reqCopy;
Uint32 lockOp = (req->requestInfo & 0xFF);
if (lockOp == AccLockReq::LockShared ||
lockOp == AccLockReq::LockExclusive) {
jam();
// find table
tabptr.i = req->tableId;
ptrCheckGuard(tabptr, ctablesize, tabrec);
// find fragment (TUX will know it)
if (req->fragPtrI == RNIL) {
for (Uint32 i = 0; i < NDB_ARRAY_SIZE(tabptr.p->fragholder); i++) {
jam();
if (tabptr.p->fragholder[i] == req->fragId){
jam();
req->fragPtrI = tabptr.p->fragptrholder[i];
break;
}
}
}
fragrecptr.i = req->fragPtrI;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
ndbrequire(req->fragId == fragrecptr.p->myfid);
// caller must be explicit here
ndbrequire(req->accOpPtr == RNIL);
// seize operation to hold the lock
if (cfreeopRec != RNIL) {
jam();
seizeOpRec();
// init as in ACCSEIZEREQ
operationRecPtr.p->userptr = req->userPtr;
operationRecPtr.p->userblockref = req->userRef;
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
operationRecPtr.p->scanRecPtr = RNIL;
// do read with lock via ACCKEYREQ
Uint32 lockMode = (lockOp == AccLockReq::LockShared) ? 0 : 1;
Uint32 opCode = ZSCAN_OP;
{
Uint32 accreq = 0;
accreq = AccKeyReq::setOperation(accreq, opCode);
accreq = AccKeyReq::setLockType(accreq, lockMode);
accreq = AccKeyReq::setDirtyOp(accreq, false);
accreq = AccKeyReq::setReplicaType(accreq, 0); // ?
accreq = AccKeyReq::setTakeOver(accreq, false);
accreq = AccKeyReq::setLockReq(accreq, true);
AccKeyReq* keyreq = reinterpret_cast<AccKeyReq*>(&signal->theData[0]);
keyreq->connectPtr = operationRecPtr.i;
keyreq->fragmentPtr = fragrecptr.i;
keyreq->requestInfo = accreq;
keyreq->hashValue = req->hashValue;
keyreq->keyLen = 0; // search local key
keyreq->transId1 = req->transId1;
keyreq->transId2 = req->transId2;
keyreq->lockConnectPtr = RNIL;
// enter local key in place of PK
keyreq->localKey[0] = req->page_id;
keyreq->localKey[1] = req->page_idx;
NDB_STATIC_ASSERT(AccKeyReq::SignalLength_localKey == 10);
}
EXECUTE_DIRECT(DBACC, GSN_ACCKEYREQ, signal, AccKeyReq::SignalLength_localKey);
/* keyreq invalid, signal now contains return value */
// translate the result
if (signal->theData[0] < RNIL) {
jam();
req->returnCode = AccLockReq::Success;
req->accOpPtr = operationRecPtr.i;
} else if (signal->theData[0] == RNIL) {
jam();
req->returnCode = AccLockReq::IsBlocked;
req->accOpPtr = operationRecPtr.i;
} else {
ndbrequire(signal->theData[0] == (UintR)-1);
releaseOpRec();
req->returnCode = AccLockReq::Refused;
req->accOpPtr = RNIL;
}
} else {
jam();
req->returnCode = AccLockReq::NoFreeOp;
}
*sig = *req;
return;
}
if (lockOp == AccLockReq::Unlock) {
jam();
// do unlock via ACC_COMMITREQ (immediate)
signal->theData[0] = req->accOpPtr;
EXECUTE_DIRECT(DBACC, GSN_ACC_COMMITREQ, signal, 1);
releaseOpRec();
req->returnCode = AccLockReq::Success;
*sig = *req;
return;
}
if (lockOp == AccLockReq::Abort) {
jam();
// do abort via ACC_ABORTREQ (immediate)
signal->theData[0] = req->accOpPtr;
signal->theData[1] = 0; // Dont send abort
execACC_ABORTREQ(signal);
releaseOpRec();
req->returnCode = AccLockReq::Success;
*sig = *req;
return;
}
if (lockOp == AccLockReq::AbortWithConf) {
jam();
// do abort via ACC_ABORTREQ (with conf signal)
signal->theData[0] = req->accOpPtr;
signal->theData[1] = 1; // send abort
execACC_ABORTREQ(signal);
releaseOpRec();
req->returnCode = AccLockReq::Success;
*sig = *req;
return;
}
ndbrequire(false);
}
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* END OF EXECUTE OPERATION MODULE */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/**
* HASH TABLE MODULE
*
* Each partition (fragment) consist of a linear hash table in Dbacc.
* The linear hash table can expand and shrink by one bucket at a time,
* moving data from only one bucket.
*
* The operations supported are:
*
* [] insert one new element
* [] delete one element
* [] lookup one element
* [] expand by splitting one bucket creating a new top bucket
* [] shrink by merge top bucket data into a merge bucket
* [] scan
*
* SCANS INTERACTION WITH EXPAND AND SHRINK
*
* Since expanding and shrinking can occur during the scan, and elements
* move around one need to take extra care so that elements are scanned
* exactly once. Elements deleted or inserted during scan should be
* scanned at most once, there reinserted data always counts as a different
* element.
*
* Scans are done in one or two laps. The first lap scans buckets from
* bottom (bucket 0) to top. During this lap expanding and shrinking may
* occur. In the second lap one rescan buckets that got merged after they
* was scanned in lap one, and now expanding and shrinking are not allowed.
*
* Neither is a expand or shrink involving the currently scanned bucket
* allowed.
*
* During lap one the table can be seen consisting of five kinds of buckets:
*
* [] unscanned, note that these have no defined scan bits, since the scan
* bits are left overs from earlier scans.
* [] current, exactly one bucket
* [] scanned, all buckets below current
* [] expanded, these buckets have not been scanned in lap one, but may
* contain scanned elements. Anyway they always have well defined scan
* bits also for unscanned elements.
* [] merged and scanned, these are buckets scanned in lap one but have
* been merged after they got scanned, and may contain unscanned
* elements. These buckets must be rescanned during lap two of scan.
* Note that we only keep track of a first and last bucket to rescan
* even if there are some buckets in between that have not been merged.
*
* The diagram below show the possible regions of buckets. The names to
* the right are the data members that describes the limits of the regions.
*
* +--------------------------+
* | Expanded buckets. May | Fragmentrec::level.getTop()
* | contain both scanned and |
* | unscanned data. |
* | |
* +--------------------------+
* | Unscanned data with | ScanRec::startNoOfBuckets
* | undefined scan bits. |
* | | ScanRec::nextBucketIndex + 1
* +--------------------------+
* | Currently scanned data. | ScanRec::nextBucketIndex
* +--------------------------+
* | Scanned buckets. |
* | |
* +--------------------------+
* | Merged buckets after | ScanRec::maxBucketIndexToRescan
* | scan start - need rescan.|
* | | ScanRec::minBucketIndexToRescan
* +--------------------------+
* | |
* | Scanned buckets. | 0
* +--------------------------+
*
* When scan starts, all buckets are unscanned and have undefined scan bits.
* On start scanning of an unscanned bucket with undefined scan bits all
* scan bits for the bucket are cleared. ScanRec::startNoOfBuckets keeps
* track of the last bucket with undefined scan bits, note that
* startNoOfBuckets may decrease if table shrinks below it.
*
* During the second lap the buckets from minBucketIndexToRescan to
* maxBucketIndexToRescan inclusive, are scanned, and no bucket need to have
* its scan bits cleared prior to scan.
*
* SCAN AND EXPAND
*
* After expand, the new top bucket will always have defined scan bits.
*
* If the split bucket have undefined scan bits the buckets scan bits are
* cleared before split.
*
* The expanded bucket may only contain scanned elements if the split
* bucket was a scanned bucket below the current bucket. This fact comes
* from noting that once the split bucket are below current bucket, the
* following expand can not have a split bucket above current bucket, since
* next split bucket is either the next bucket, or the bottom bucket due to
* how the linear hash table grow. And since expand are not allowed when
* split bucket would be the current bucket all expand bucket with scanned
* elements must come from buckets below current bucket.
*
* SCAN AND SHRINK
*
* Shrink merge back the top bucket into the bucket it was split from in
* the corresponding expand. This implies that we will never merge back a
* bucket with scanned elements into an unscanned bucket, with or without
* defined scan bits.
*
* If the top bucket have undefined scan bits they are cleared before merge,
* even if it is into another bucket with undefined scan bits. This is to
* ensure that an element is not inserted in a bucket that have scan bits
* set that are not allowed in bucket, for details why see under BUCKET
* INVARIANTS.
*
* Whenever top bucket have undefined scan bits one need to decrease
* startNoOfBuckets that indicates the last bucket with undefined scan
* bits. If the top bucket reappear by expand it will have defined
* scan bits which possibly indicate scan elements, these must not be
* cleared prior scan.
*
* If merge destination are below current bucket, it must be added for
* rescan. Note that we only keep track of lowest and highest bucket
* number to rescan even if some buckets in between are not merged and do
* not need rescan.
*
* CONTAINERS
*
* Each bucket is a linked list of containers. Only the first head
* container may be empty.
*
* Containers are located in 8KiB pages. Each page have 72 buffers with
* 28 words. Each buffer may host up to two containers. One headed at
* buffers lowest address, called left end, and one headed at buffers high
* words, the right end. The left end container grows forward towards
* higher addresses, and the right end container grows backwards.
*
* Each bucket has its first container at a unique logical address, the
* logical page number is bucket number divided by 64 with the remainder
* index one of the first 64 left end containers on page. A dynamic array
* are used to map the logical page number to physical page number.
*
* The pages which host the head containers of buckets are called normal
* pages. When a container is full a new container is allocated, first it
* looks for one of the eight left end containers that are on same page.
* If no one is free, one look for a free right end container on same page.
* Otherwise one look for an overflow container on an overflow page. New
* overflow pages are allocated if needed.
*
* SCAN BITS
*
* To keep track of which elements have been scanned several means are used.
* Every container header have scan bits, if a scan bit is set it means that
* all elements in that container have been scanned by the corresponding
* scan.
*
* If a container is currently scanned, that is some elements are scanned
* and some not, each element in the container have a scan bit in the scan
* record (ScanRec::elemScanned). The next scanned element is looked for
* in the current container, if none found, the next container is used, and
* then the next bucket.
*
* A scan may only scan one container at a time.
*
* BUCKETS INVARIANTS
*
* To be able to guarantee that only one container at a time are currently
* scanned, there is an important invariant:
*
* [] No container may have a scan bit set that preceding container have
* not set. That is, container are scanned in order within bucket, and
* no inserted element may be put in such that the invariant breaks.
*
* Also a condition that all operations on buckets must satisfy is:
*
* [] It is not allowed to insert an element with more scan bits set than
* the buckets head container have (unless it is for a new top bucket).
*
* This is too avoid extra complexity that would arise if such an
* element was inserted. A new container can not be inserted preceding
* the bucket head container since it has an fixed logical address. The
* alternative would be to create a new bucket after the bucket head
* container and move every element from head container to the new
* container.
*
* How the condition is fulfilled are:
*
* [] Shrink, where top bucket have undefined scan bits.
*
* Top buckets scan bits are first cleared prior to merge.
*
* [] Shrink, where destination bucket have undefined scan bits.
*
* In this case top bucket must also have undefined scan bits (see SCAN
* AND SHRINK above) and both top and destination bucket have their scan
* bits cleared before merge.
*
* [] Shrink, where destination bucket is scanned, below current.
*
* The only way the top bucket can have scanned elements is that it is
* expanded from a scanned bucket, below current. Since that must be the
* shrink destination bucket, no element can have more scan bits set than
* the destination buckets head container.
*
* [] Expand.
*
* The new top bucket is always a new bucket and head containers scan bits
* are taken from split source bucket.
*
* [] Insert.
*
* A new element may be inserted in any container with free space, and it
* inherits the containers scan bits. If a new container is needed it is
* put last with container scan bits copied from preceding container.
*
* [] Delete.
*
* Deleting an element, replaces the deleted element with the last
* element with same scan bits as the deleted element. If a container
* becomes empty it is unlinked, unless it is the head container which
* always must remain.
*
* Since the first containers in a bucket are more likely to be on the
* same (normal) page, it is better to unlink a container towards the
* end of bucket. If the deleted element is the last one in its
* container, but not the head container, and there are no other element
* in bucket with same scan bits that can replace the deleted element.
* It is allowed to use another element with fewer bits as replacement
* and clear scan bits of the container accordingly.
*
* The reason the bucket head container may not have some of its scan
* bits cleared, is that it could later result in a need to insert back
* an element with more scan bits set. The scenario for that is:
*
* 1) Split a merged bucket, A, into a new bucket B, moving some
* elements with some scan bits set.
*
* 2) Delete some elements in bucket A, leaving only elements with no
* scan bits set.
*
* 3) Shrink table and merge back bucket B into bucket A, if we have
* cleared the head container of bucket A, this would result in
* inserting elements with more scan bits set then bucket A head
* container.
*
*/
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* MODULE: INSERT */
/* THE FOLLOWING SUBROUTINES ARE ONLY USED BY INSERT_ELEMENT. THIS */
/* ROUTINE IS THE SOLE INTERFACE TO INSERT ELEMENTS INTO THE INDEX. */
/* CURRENT USERS ARE INSERT REQUESTS, EXPAND CONTAINER AND SHRINK */
/* CONTAINER. */
/* */
/* THE FOLLOWING SUBROUTINES ARE INCLUDED IN THIS MODULE: */
/* INSERT_ELEMENT */
/* INSERT_CONTAINER */
/* ADDNEWCONTAINER */
/* GETFREELIST */
/* INCREASELISTCONT */
/* SEIZE_LEFTLIST */
/* SEIZE_RIGHTLIST */
/* */
/* THESE ROUTINES ARE ONLY USED BY THIS MODULE AND BY NO ONE ELSE. */
/* ALSO THE ROUTINES MAKE NO USE OF ROUTINES IN OTHER MODULES. */
/* TAKE_REC_OUT_OF_FREE_OVERPAGE AND RELEASE_OVERFLOW_REC ARE */
/* EXCEPTIONS TO THIS RULE. */
/* */
/* THE ONLY SHORT-LIVED VARIABLES USED IN OTHER PARTS OF THE BLOCK ARE */
/* THOSE DEFINED AS INPUT AND OUTPUT IN INSERT_ELEMENT */
/* SHORT-LIVED VARIABLES INCLUDE TEMPORARY VARIABLES, COMMON VARIABLES */
/* AND POINTER VARIABLES. */
/* THE ONLY EXCEPTION TO THIS RULE IS FRAGRECPTR WHICH POINTS TO THE */
/* FRAGMENT RECORD. THIS IS MORE LESS STATIC ALWAYS DURING A SIGNAL */
/* EXECUTION. */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* INSERT_ELEMENT */
/* INPUT: */
/* IDR_PAGEPTR (POINTER TO THE ACTIVE PAGE REC) */
/* TIDR_PAGEINDEX (INDEX OF THE CONTAINER) */
/* TIDR_FORWARD (DIRECTION FORWARD OR BACKWARD) */
/* TIDR_ELEMHEAD (HEADER OF ELEMENT TO BE INSERTED */
/* CIDR_KEYS(ARRAY OF TUPLE KEYS) */
/* CLOCALKEY(ARRAY OF LOCAL KEYS). */
/* FRAGRECPTR */
/* IDR_OPERATION_REC_PTR */
/* TIDR_KEY_LEN */
/* conScanMask - ANY_SCANBITS or scan bits container must */
/* have. Note elements inserted are never more scanned than */
/* container. */
/* */
/* OUTPUT: */
/* TIDR_PAGEINDEX (PAGE INDEX OF INSERTED ELEMENT) */
/* IDR_PAGEPTR (PAGE POINTER OF INSERTED ELEMENT) */
/* TIDR_FORWARD (CONTAINER DIRECTION OF INSERTED ELEMENT) */
/* NONE */
/* --------------------------------------------------------------------------------- */
void Dbacc::insertElement(const Element elem,
OperationrecPtr oprecptr,
Page8Ptr& pageptr,
Uint32& conidx,
bool& isforward,
Uint32& conptr,
Uint16 conScanMask,
const bool newBucket)
{
Page8Ptr inrNewPageptr;
Uint32 tidrResult;
Uint16 scanmask;
bool newContainer = newBucket;
ContainerHeader containerhead;
do {
insertContainer(elem,
oprecptr,
pageptr,
conidx,
isforward,
conptr,
containerhead,
conScanMask,
newContainer,
tidrResult);
if (tidrResult != ZFALSE)
{
jam();
return;
/* INSERTION IS DONE, OR */
/* AN ERROR IS DETECTED */
}//if
if (containerhead.getNextEnd() != 0) {
/* THE NEXT CONTAINER IS IN THE SAME PAGE */
conidx = containerhead.getNextIndexNumber();
if (containerhead.getNextEnd() == ZLEFT) {
jam();
isforward = true;
} else if (containerhead.getNextEnd() == ZRIGHT) {
jam();
isforward = false;
} else {
ndbrequire(false);
return;
}//if
if (!containerhead.isNextOnSamePage()) {
jam(); /* NEXT CONTAINER IS IN AN OVERFLOW PAGE */
pageptr.i = pageptr.p->word32[conptr + 1];
ptrCheckGuard(pageptr, cpagesize, page8);
}//if
ndbrequire(conidx <= Container::MAX_CONTAINER_INDEX);
} else {
scanmask = containerhead.getScanBits();
break;
}//if
// Only first container can be a new container
newContainer = false;
} while (1);
Uint32 newPageindex;;
Uint32 newBuftype;
getfreelist(pageptr, newPageindex, newBuftype);
bool nextOnSamePage;
if (newPageindex == Container::NO_CONTAINER_INDEX) {
jam();
/* NO FREE BUFFER IS FOUND */
if (fragrecptr.p->sparsepages.isEmpty())
{
jam();
allocOverflowPage();
ndbrequire(tresult <= ZLIMIT_OF_ERROR);
}//if
{
LocalContainerPageList sparselist(*this, fragrecptr.p->sparsepages);
sparselist.first(inrNewPageptr);
}
getfreelist(inrNewPageptr, newPageindex, newBuftype);
ndbrequire(newPageindex != Container::NO_CONTAINER_INDEX);
nextOnSamePage = false;
} else {
jam();
inrNewPageptr = pageptr;
nextOnSamePage = true;
}//if
if (newBuftype == ZLEFT)
{
seizeLeftlist(inrNewPageptr, newPageindex);
isforward = true;
}
else if (newBuftype == ZRIGHT)
{
seizeRightlist(inrNewPageptr, newPageindex);
isforward = false;
}
else
{
ndbrequire(newBuftype == ZLEFT || newBuftype == ZRIGHT);
}
Uint32 containerptr = getContainerPtr(newPageindex, isforward);
ContainerHeader newcontainerhead;
newcontainerhead.initInUse();
Uint32 nextPtrI;
if (containerhead.haveNext())
{
nextPtrI = pageptr.p->word32[conptr+1];
newcontainerhead.setNext(containerhead.getNextEnd(),
containerhead.getNextIndexNumber(),
inrNewPageptr.i == nextPtrI);
}
else
{
nextPtrI = RNIL;
newcontainerhead.clearNext();
}
inrNewPageptr.p->word32[containerptr] = newcontainerhead;
inrNewPageptr.p->word32[containerptr + 1] = nextPtrI;
addnewcontainer(pageptr, conptr, newPageindex,
newBuftype, nextOnSamePage, inrNewPageptr.i);
pageptr = inrNewPageptr;
conidx = newPageindex;
if (conScanMask == Operationrec::ANY_SCANBITS)
{
/**
* ANY_SCANBITS indicates that this is an insert of a new element, not
* an insert from expand or shrink. In that case the inserted element
* and the new container will inherit scan bits from previous container.
* This makes the element look as scanned as possible still preserving
* the invariant that containers and element towards the end of bucket
* has less scan bits set than those towards the beginning.
*/
conScanMask = scanmask;
}
insertContainer(elem,
oprecptr,
pageptr,
conidx,
isforward,
conptr,
containerhead,
conScanMask,
true,
tidrResult);
ndbrequire(tidrResult == ZTRUE);
}//Dbacc::insertElement()
/**
* insertContainer puts an element into a container if it has free space and
* the requested scan bits match.
*
* If it is a new element inserted the requested scan bits given by
* conScanMask can be ANY_SCANBITS or a valid set of bits. If it is
* ANY_SCANBITS the containers scan bits are not checked. If it is set to
* valid scan bits the container is a newly created empty container.
*
* The buckets header container may never be removed. Nor should any scan
* bit of it be cleared, unless for expand there the first inserted element
* determines the bucket header containers scan bits. newContainer indicates
* that that current insert is part of populating a new bucket with expand.
*
* In case the container is empty it is either the bucket header container
* or a new container created by caller (insertElement).
*
* @param[in] elem
* @param[in] oprecptr
* @param[in] pageptr
* @param[in] conidx
* @param[in] isforward
* @param[out] conptr
* @param[out] containerhead
* @param[in] conScanMask
* @param[in] newContainer
* @param[out] result
*/
void Dbacc::insertContainer(const Element elem,
const OperationrecPtr oprecptr,
const Page8Ptr pageptr,
const Uint32 conidx,
const bool isforward,
Uint32& conptr,
ContainerHeader& containerhead,
Uint16 conScanMask,
const bool newContainer,
Uint32& result)
{
Uint32 tidrContainerlen;
Uint32 tidrConfreelen;
Uint32 tidrNextSide;
Uint32 tidrNextConLen;
Uint32 tidrIndex;
result = ZFALSE;
/* --------------------------------------------------------------------------------- */
/* CALCULATE THE POINTER TO THE ELEMENT TO BE INSERTED AND THE POINTER TO THE */
/* CONTAINER HEADER OF THE OTHER SIDE OF THE BUFFER. */
/* --------------------------------------------------------------------------------- */
conptr = getForwardContainerPtr(conidx);
if (isforward) {
jam();
tidrNextSide = conptr + (ZBUF_SIZE - Container::HEADER_SIZE);
arrGuard(tidrNextSide + 1, 2048);
containerhead = pageptr.p->word32[conptr];
tidrContainerlen = containerhead.getLength();
tidrIndex = conptr + tidrContainerlen;
} else {
jam();
tidrNextSide = conptr;
conptr = conptr + (ZBUF_SIZE - Container::HEADER_SIZE);
arrGuard(conptr + 1, 2048);
containerhead = pageptr.p->word32[conptr];
tidrContainerlen = containerhead.getLength();
tidrIndex = (conptr - tidrContainerlen) +
(Container::HEADER_SIZE - fragrecptr.p->elementLength);
}//if
const Uint16 activeScanMask = fragrecptr.p->activeScanMask;
const Uint16 conscanmask = containerhead.getScanBits();
if(tidrContainerlen > Container::HEADER_SIZE || !newContainer)
{
if (conScanMask != Operationrec::ANY_SCANBITS &&
((conscanmask & ~conScanMask) & activeScanMask) != 0)
{
/* Container have more scan bits set than requested */
/* Continue to next container. */
return;
}
}
if (tidrContainerlen == Container::HEADER_SIZE && newContainer)
{
/**
* Only the first header container in a bucket or a newly created bucket
* in insertElement can be empty.
*
* Set container scan bits as requested.
*/
ndbrequire(conScanMask != Operationrec::ANY_SCANBITS);
containerhead.copyScanBits(conScanMask & activeScanMask);
pageptr.p->word32[conptr] = containerhead;
}
if (tidrContainerlen >= (ZBUF_SIZE - fragrecptr.p->elementLength))
{
return;
}//if
tidrConfreelen = ZBUF_SIZE - tidrContainerlen;
/* --------------------------------------------------------------------------------- */
/* WE CALCULATE THE TOTAL LENGTH THE CONTAINER CAN EXPAND TO */
/* THIS INCLUDES THE OTHER SIDE OF THE BUFFER IF POSSIBLE TO EXPAND THERE. */
/* --------------------------------------------------------------------------------- */
if (!containerhead.isUsingBothEnds()) {
jam();
/* --------------------------------------------------------------------------------- */
/* WE HAVE NOT EXPANDED TO THE ENTIRE BUFFER YET. WE CAN THUS READ THE OTHER */
/* SIDE'S CONTAINER HEADER TO READ HIS LENGTH. */
/* --------------------------------------------------------------------------------- */
ContainerHeader conhead(pageptr.p->word32[tidrNextSide]);
tidrNextConLen = conhead.getLength();
tidrConfreelen = tidrConfreelen - tidrNextConLen;
if (tidrConfreelen > ZBUF_SIZE) {
ndbrequire(false);
/* --------------------------------------------------------------------------------- */
/* THE BUFFERS ARE PLACED ON TOP OF EACH OTHER. THIS SHOULD NEVER OCCUR. */
/* --------------------------------------------------------------------------------- */
return;
}//if
} else {
jam();
tidrNextConLen = 1; /* INDICATE OTHER SIDE IS NOT PART OF FREE LIST */
}//if
if (tidrConfreelen < fragrecptr.p->elementLength) {
jam();
/* --------------------------------------------------------------------------------- */
/* THE CONTAINER COULD NOT BE EXPANDED TO FIT THE NEW ELEMENT. WE HAVE TO */
/* RETURN AND FIND A NEW CONTAINER TO INSERT IT INTO. */
/* --------------------------------------------------------------------------------- */
return;
}//if
tidrContainerlen = tidrContainerlen + fragrecptr.p->elementLength;
if (tidrNextConLen == 0) {
/* EACH SIDE OF THE BUFFER WHICH BELONG TO A FREE */
/* LIST, HAS ZERO AS LENGTH. */
if (tidrContainerlen > Container::UP_LIMIT) {
ContainerHeader conthead = pageptr.p->word32[conptr];
conthead.setUsingBothEnds();
dbgWord32(pageptr, conptr, conthead);
pageptr.p->word32[conptr] = conthead;
if (isforward) {
jam();
/* REMOVE THE RIGHT SIDE OF THE BUFFER FROM THE FREE LIST */
seizeRightlist(pageptr, conidx);
} else {
jam();
/* REMOVE THE LEFT SIDE OF THE BUFFER FROM THE FREE LIST */
seizeLeftlist(pageptr, conidx);
}//if
}//if
}//if
/* OF THE FREE CONTAINERS */
/* --------------------------------------------------------------------------------- */
/* WE HAVE NOW FOUND A FREE SPOT IN THE CURRENT CONTAINER. WE INSERT THE */
/* ELEMENT HERE. THE ELEMENT CONTAINS A HEADER, A LOCAL KEY AND A TUPLE KEY. */
/* BEFORE INSERTING THE ELEMENT WE WILL UPDATE THE OPERATION RECORD WITH THE */
/* DATA CONCERNING WHERE WE INSERTED THE ELEMENT. THIS MAKES IT EASY TO FIND */
/* THIS INFORMATION WHEN WE RETURN TO UPDATE THE LOCAL KEY OR RETURN TO COMMIT */
/* OR ABORT THE INSERT. IF NO OPERATION RECORD EXIST IT MEANS THAT WE ARE */
/* PERFORMING THIS AS A PART OF THE EXPAND OR SHRINK PROCESS. */
/* --------------------------------------------------------------------------------- */
const Uint32 elemhead = elem.getHeader();
ContainerHeader conthead = pageptr.p->word32[conptr];
if (oprecptr.i != RNIL)
{
jam();
ndbrequire(ElementHeader::getLocked(elemhead));
oprecptr.p->elementPage = pageptr.i;
oprecptr.p->elementContainer = conptr;
oprecptr.p->elementPointer = tidrIndex;
}
else
{
ndbassert(!ElementHeader::getLocked(elemhead));
}
/* --------------------------------------------------------------------------------- */
/* WE CHOOSE TO UNDO LOG INSERTS BY WRITING THE BEFORE VALUE TO THE UNDO LOG. */
/* WE COULD ALSO HAVE DONE THIS BY WRITING THIS BEFORE VALUE WHEN DELETING */
/* ELEMENTS. WE CHOOSE TO PUT IT HERE SINCE WE THEREBY ENSURE THAT WE ALWAYS */
/* UNDO LOG ALL WRITES TO PAGE MEMORY. IT SHOULD BE EASIER TO MAINTAIN SUCH A */
/* STRUCTURE. IT IS RATHER DIFFICULT TO MAINTAIN A LOGICAL STRUCTURE WHERE */
/* DELETES ARE INSERTS AND INSERTS ARE PURELY DELETES. */
/* --------------------------------------------------------------------------------- */
ndbrequire(fragrecptr.p->localkeylen == 1);
arrGuard(tidrIndex + 1, 2048);
pageptr.p->word32[tidrIndex] = elem.getHeader();
pageptr.p->word32[tidrIndex + 1] = elem.getData(); /* INSERTS LOCALKEY */
conthead.setLength(tidrContainerlen);
dbgWord32(pageptr, conptr, conthead);
pageptr.p->word32[conptr] = conthead;
result = ZTRUE;
}//Dbacc::insertContainer()
/** ---------------------------------------------------------------------------
* Set next link of a container to reference to next container.
*
* @param[in] pageptr Pointer to page of container to modify.
* @param[in] conptr Pointer within page of container to modify.
* @param[in] nextConidx Index within page of next container.
* @param[in] nextContype Type of next container, left or right end.
* @param[in] nextSamepage True if next container is on same page as modified
* container
* @param[in] nextPagei Overflow page number of next container.
* ------------------------------------------------------------------------- */
void Dbacc::addnewcontainer(Page8Ptr pageptr,
Uint32 conptr,
Uint32 nextConidx,
Uint32 nextContype,
bool nextSamepage,
Uint32 nextPagei) const
{
ContainerHeader containerhead(pageptr.p->word32[conptr]);
containerhead.setNext(nextContype, nextConidx, nextSamepage);
dbgWord32(pageptr, conptr, containerhead);
pageptr.p->word32[conptr] = containerhead;
dbgWord32(pageptr, conptr + 1, nextPagei);
pageptr.p->word32[conptr + 1] = nextPagei;
}//Dbacc::addnewcontainer()
/* --------------------------------------------------------------------------------- */
/* GETFREELIST */
/* INPUT: */
/* GFL_PAGEPTR (POINTER TO A PAGE RECORD). */
/* OUTPUT: */
/* TGFL_PAGEINDEX(POINTER TO A FREE BUFFER IN THE FREEPAGE), AND */
/* TGFL_BUF_TYPE( TYPE OF THE FREE BUFFER). */
/* DESCRIPTION: SEARCHS IN THE FREE LIST OF THE FREE BUFFER IN THE PAGE HEAD */
/* (WORD32(1)),AND RETURN ADDRESS OF A FREE BUFFER OR NIL. */
/* THE FREE BUFFER CAN BE A RIGHT CONTAINER OR A LEFT ONE */
/* THE KIND OF THE CONTAINER IS NOTED BY TGFL_BUF_TYPE. */
/* --------------------------------------------------------------------------------- */
void Dbacc::getfreelist(Page8Ptr pageptr, Uint32& pageindex, Uint32& buftype)
{
const Uint32 emptylist = pageptr.p->word32[ZPOS_EMPTY_LIST];
pageindex = (emptylist >> 7) & 0x7f; /* LEFT FREE LIST */
buftype = ZLEFT;
if (pageindex == Container::NO_CONTAINER_INDEX) {
jam();
pageindex = emptylist & 0x7f; /* RIGHT FREE LIST */
buftype = ZRIGHT;
}//if
ndbrequire((pageindex <= Container::MAX_CONTAINER_INDEX) ||
(pageindex == Container::NO_CONTAINER_INDEX));
}//Dbacc::getfreelist()
/* --------------------------------------------------------------------------------- */
/* INCREASELISTCONT */
/* INPUT: */
/* ILC_PAGEPTR PAGE POINTER TO INCREASE NUMBER OF CONTAINERS IN */
/* A CONTAINER OF AN OVERFLOW PAGE (FREEPAGEPTR) IS ALLOCATED, NR OF */
/* ALLOCATED CONTAINER HAVE TO BE INCRESE BY ONE . */
/* IF THE NUMBER OF ALLOCATED CONTAINERS IS ABOVE THE FREE LIMIT WE WILL */
/* REMOVE THE PAGE FROM THE FREE LIST. */
/* --------------------------------------------------------------------------------- */
void Dbacc::increaselistcont(Page8Ptr ilcPageptr)
{
dbgWord32(ilcPageptr, ZPOS_ALLOC_CONTAINERS, ilcPageptr.p->word32[ZPOS_ALLOC_CONTAINERS] + 1);
ilcPageptr.p->word32[ZPOS_ALLOC_CONTAINERS] = ilcPageptr.p->word32[ZPOS_ALLOC_CONTAINERS] + 1;
// A sparse page just got full
if (ilcPageptr.p->word32[ZPOS_ALLOC_CONTAINERS] == ZFREE_LIMIT + 1) {
// Check that it is an overflow page
if (((ilcPageptr.p->word32[ZPOS_EMPTY_LIST] >> ZPOS_PAGE_TYPE_BIT) & 3) == 1)
{
jam();
LocalContainerPageList sparselist(*this, fragrecptr.p->sparsepages);
LocalContainerPageList fulllist(*this, fragrecptr.p->fullpages);
sparselist.remove(ilcPageptr);
fulllist.addLast(ilcPageptr);
}//if
}//if
}//Dbacc::increaselistcont()
/* --------------------------------------------------------------------------------- */
/* SEIZE_LEFTLIST */
/* INPUT: */
/* TSL_PAGEINDEX PAGE INDEX OF CONTAINER TO SEIZE */
/* SL_PAGEPTR PAGE POINTER OF CONTAINER TO SEIZE */
/* TSL_UPDATE_HEADER SHOULD WE UPDATE THE CONTAINER HEADER */
/* */
/* OUTPUT: */
/* NONE */
/* DESCRIPTION: THE BUFFER NOTED BY TSL_PAGEINDEX WILL BE REMOVED FROM THE */
/* LIST OF LEFT FREE CONTAINER, IN THE HEADER OF THE PAGE */
/* (FREEPAGEPTR). PREVIOUS AND NEXT BUFFER OF REMOVED BUFFER */
/* WILL BE UPDATED. */
/* --------------------------------------------------------------------------------- */
void Dbacc::seizeLeftlist(Page8Ptr slPageptr, Uint32 tslPageindex)
{
Uint32 tsllTmp1;
Uint32 tsllHeadIndex;
Uint32 tsllTmp;
tsllHeadIndex = getForwardContainerPtr(tslPageindex);
arrGuard(tsllHeadIndex + 1, 2048);
Uint32 tslNextfree = slPageptr.p->word32[tsllHeadIndex];
Uint32 tslPrevfree = slPageptr.p->word32[tsllHeadIndex + 1];
if (tslPrevfree == Container::NO_CONTAINER_INDEX) {
jam();
/* UPDATE FREE LIST OF LEFT CONTAINER IN PAGE HEAD */
tsllTmp1 = slPageptr.p->word32[ZPOS_EMPTY_LIST];
tsllTmp = tsllTmp1 & 0x7f;
tsllTmp1 = (tsllTmp1 >> 14) << 14;
tsllTmp1 = (tsllTmp1 | (tslNextfree << 7)) | tsllTmp;
dbgWord32(slPageptr, ZPOS_EMPTY_LIST, tsllTmp1);
slPageptr.p->word32[ZPOS_EMPTY_LIST] = tsllTmp1;
} else {
ndbrequire(tslPrevfree <= Container::MAX_CONTAINER_INDEX);
jam();
tsllTmp = getForwardContainerPtr(tslPrevfree);
dbgWord32(slPageptr, tsllTmp, tslNextfree);
slPageptr.p->word32[tsllTmp] = tslNextfree;
}//if
if (tslNextfree <= Container::MAX_CONTAINER_INDEX) {
jam();
tsllTmp = getForwardContainerPtr(tslNextfree) + 1;
dbgWord32(slPageptr, tsllTmp, tslPrevfree);
slPageptr.p->word32[tsllTmp] = tslPrevfree;
} else {
ndbrequire(tslNextfree == Container::NO_CONTAINER_INDEX);
jam();
}//if
increaselistcont(slPageptr);
}//Dbacc::seizeLeftlist()
/* --------------------------------------------------------------------------------- */
/* SEIZE_RIGHTLIST */
/* DESCRIPTION: THE BUFFER NOTED BY TSL_PAGEINDEX WILL BE REMOVED FROM THE */
/* LIST OF RIGHT FREE CONTAINER, IN THE HEADER OF THE PAGE */
/* (SL_PAGEPTR). PREVIOUS AND NEXT BUFFER OF REMOVED BUFFER */
/* WILL BE UPDATED. */
/* --------------------------------------------------------------------------------- */
void Dbacc::seizeRightlist(Page8Ptr slPageptr, Uint32 tslPageindex)
{
Uint32 tsrlHeadIndex;
Uint32 tsrlTmp;
tsrlHeadIndex = getBackwardContainerPtr(tslPageindex);
arrGuard(tsrlHeadIndex + 1, 2048);
Uint32 tslNextfree = slPageptr.p->word32[tsrlHeadIndex];
Uint32 tslPrevfree = slPageptr.p->word32[tsrlHeadIndex + 1];
if (tslPrevfree == Container::NO_CONTAINER_INDEX) {
jam();
tsrlTmp = slPageptr.p->word32[ZPOS_EMPTY_LIST];
dbgWord32(slPageptr, ZPOS_EMPTY_LIST, ((tsrlTmp >> 7) << 7) | tslNextfree);
slPageptr.p->word32[ZPOS_EMPTY_LIST] = ((tsrlTmp >> 7) << 7) | tslNextfree;
} else {
ndbrequire(tslPrevfree <= Container::MAX_CONTAINER_INDEX);
jam();
tsrlTmp = getBackwardContainerPtr(tslPrevfree);
dbgWord32(slPageptr, tsrlTmp, tslNextfree);
slPageptr.p->word32[tsrlTmp] = tslNextfree;
}//if
if (tslNextfree <= Container::MAX_CONTAINER_INDEX) {
jam();
tsrlTmp = getBackwardContainerPtr(tslNextfree) + 1;
dbgWord32(slPageptr, tsrlTmp, tslPrevfree);
slPageptr.p->word32[tsrlTmp] = tslPrevfree;
} else {
ndbrequire(tslNextfree == Container::NO_CONTAINER_INDEX);
jam();
}//if
increaselistcont(slPageptr);
}//Dbacc::seizeRightlist()
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* END OF INSERT_ELEMENT MODULE */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* MODULE: GET_ELEMENT */
/* THE FOLLOWING SUBROUTINES ARE ONLY USED BY GET_ELEMENT AND */
/* GETDIRINDEX. THIS ROUTINE IS THE SOLE INTERFACE TO GET ELEMENTS */
/* FROM THE INDEX. CURRENT USERS ARE ALL REQUESTS AND EXECUTE UNDO LOG */
/* */
/* THE FOLLOWING SUBROUTINES ARE INCLUDED IN THIS MODULE: */
/* GET_ELEMENT */
/* GET_DIRINDEX */
/* SEARCH_LONG_KEY */
/* */
/* THESE ROUTINES ARE ONLY USED BY THIS MODULE AND BY NO ONE ELSE. */
/* ALSO THE ROUTINES MAKE NO USE OF ROUTINES IN OTHER MODULES. */
/* THE ONLY SHORT-LIVED VARIABLES USED IN OTHER PARTS OF THE BLOCK ARE */
/* THOSE DEFINED AS INPUT AND OUTPUT IN GET_ELEMENT AND GETDIRINDEX */
/* SHORT-LIVED VARIABLES INCLUDE TEMPORARY VARIABLES, COMMON VARIABLES */
/* AND POINTER VARIABLES. */
/* THE ONLY EXCEPTION TO THIS RULE IS FRAGRECPTR WHICH POINTS TO THE */
/* FRAGMENT RECORD. THIS IS MORE LESS STATIC ALWAYS DURING A SIGNAL */
/* EXECUTION. */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* GETDIRINDEX */
/* SUPPORT ROUTINE FOR INSERT ELEMENT, GET ELEMENT AND COMMITDELETE */
/* INPUT:FRAGRECPTR ( POINTER TO THE ACTIVE FRAGMENT REC) */
/* OPERATION_REC_PTR (POINTER TO THE OPERATION REC). */
/* */
/* OUTPUT:GDI_PAGEPTR ( POINTER TO THE PAGE OF THE ELEMENT) */
/* TGDI_PAGEINDEX ( INDEX OF THE ELEMENT IN THE PAGE). */
/* */
/* DESCRIPTION: CHECK THE HASH VALUE OF THE OPERATION REC AND CALCULATE THE */
/* THE ADDRESS OF THE ELEMENT IN THE HASH TABLE,(GDI_PAGEPTR, */
/* TGDI_PAGEINDEX) ACCORDING TO LH3. */
/* --------------------------------------------------------------------------------- */
Uint32 Dbacc::getPagePtr(DynArr256::Head& directory, Uint32 index)
{
DynArr256 dir(directoryPool, directory);
Uint32* ptr = dir.get(index);
return *ptr;
}
bool Dbacc::setPagePtr(DynArr256::Head& directory, Uint32 index, Uint32 ptri)
{
DynArr256 dir(directoryPool, directory);
Uint32* ptr = dir.set(index);
if (ptr == NULL) return false;
*ptr = ptri;
return true;
}
Uint32 Dbacc::unsetPagePtr(DynArr256::Head& directory, Uint32 index)
{
DynArr256 dir(directoryPool, directory);
Uint32* ptr = dir.get(index);
Uint32 ptri = *ptr;
*ptr = RNIL;
return ptri;
}
void Dbacc::getdirindex(Page8Ptr& pageptr, Uint32& conidx)
{
const LHBits32 hashValue = operationRecPtr.p->hashValue;
const Uint32 address = fragrecptr.p->level.getBucketNumber(hashValue);
conidx = fragrecptr.p->getPageIndex(address);
pageptr.i = getPagePtr(fragrecptr.p->directory,
fragrecptr.p->getPageNumber(address));
ptrCheckGuard(pageptr, cpagesize, page8);
}//Dbacc::getdirindex()
Uint32
Dbacc::readTablePk(Uint32 localkey1, Uint32 localkey2,
Uint32 eh, Ptr<Operationrec> opPtr)
{
int ret;
Uint32 tableId = fragrecptr.p->myTableId;
Uint32 fragId = fragrecptr.p->myfid;
bool xfrm = fragrecptr.p->hasCharAttr;
#ifdef VM_TRACE
memset(ckeys, 0x1f, (fragrecptr.p->keyLength * MAX_XFRM_MULTIPLY) << 2);
#endif
if (likely(! Local_key::isInvalid(localkey1, localkey2)))
{
ret = c_tup->accReadPk(tableId, fragId, localkey1, localkey2,
ckeys, true);
}
else
{
ndbrequire(ElementHeader::getLocked(eh));
if (unlikely((opPtr.p->m_op_bits & Operationrec::OP_MASK) == ZSCAN_OP))
{
dump_lock_queue(opPtr);
ndbrequire(opPtr.p->nextParallelQue == RNIL);
ndbrequire(opPtr.p->m_op_bits & Operationrec::OP_ELEMENT_DISAPPEARED);
ndbrequire(opPtr.p->m_op_bits & Operationrec::OP_COMMIT_DELETE_CHECK);
ndbrequire((opPtr.p->m_op_bits & Operationrec::OP_STATE_MASK) == Operationrec::OP_STATE_RUNNING);
return 0;
}
ret = c_lqh->readPrimaryKeys(opPtr.p->userptr, ckeys, xfrm);
}
jamEntry();
ndbrequire(ret >= 0);
return ret;
}
/** ---------------------------------------------------------------------------
* Find element.
*
* Method scan the bucket given by hashValue from operationRecPtr and look for
* the element with primary key given in signal. If element found return
* pointer to element, if not found return only bucket information.
*
* @param[in] signal Signal containing primary key to look for.
* @param[out] lockOwnerPtr Lock owner if any of found element.
* @param[out] bucketPageptr Page of first container of bucket there element
should be.
* @param[out] bucketConidx Index within page of first container of bucket
there element should be.
* @param[out] elemPageptr Page of found element.
* @param[out] elemConptr Pointer within page to container of found
element.
* @param[out] elemptr Pointer within page to found element.
* @return Returns ZTRUE if element was found.
* ------------------------------------------------------------------------- */
Uint32
Dbacc::getElement(const AccKeyReq* signal,
OperationrecPtr& lockOwnerPtr,
Page8Ptr& bucketPageptr,
Uint32& bucketConidx,
Page8Ptr& elemPageptr,
Uint32& elemConptr,
Uint32& elemptr)
{
Uint32 tgeElementHeader;
Uint32 tgeElemStep;
Uint32 tgePageindex;
Uint32 tgeNextptrtype;
register Uint32 tgeRemLen;
const Uint32 TelemLen = fragrecptr.p->elementLength;
register const Uint32* Tkeydata = signal->keyInfo; /* or localKey if keyLen == 0 */
const Uint32 localkeylen = fragrecptr.p->localkeylen;
Uint32 bucket_number = fragrecptr.p->level.getBucketNumber(operationRecPtr.p->hashValue);
getdirindex(bucketPageptr, bucketConidx);
elemPageptr = bucketPageptr;
tgePageindex = bucketConidx;
/*
* The value seached is
* - table key for ACCKEYREQ, stored in TUP
* - local key (1 word) for ACC_LOCKREQ and UNDO, stored in ACC
*/
const bool searchLocalKey = operationRecPtr.p->tupkeylen == 0;
ndbrequire(TelemLen == ZELEM_HEAD_SIZE + localkeylen);
tgeNextptrtype = ZLEFT;
do {
if (tgeNextptrtype == ZLEFT) {
jam();
elemConptr = getForwardContainerPtr(tgePageindex);
elemptr = elemConptr + Container::HEADER_SIZE;
tgeElemStep = TelemLen;
ndbrequire(elemConptr < 2048);
ContainerHeader conhead(elemPageptr.p->word32[elemConptr]);
tgeRemLen = conhead.getLength();
ndbrequire((elemConptr + tgeRemLen - 1) < 2048);
} else if (tgeNextptrtype == ZRIGHT) {
jam();
elemConptr = getBackwardContainerPtr(tgePageindex);
tgeElemStep = 0 - TelemLen;
elemptr = elemConptr - TelemLen;
ndbrequire(elemConptr < 2048);
ContainerHeader conhead(elemPageptr.p->word32[elemConptr]);
tgeRemLen = conhead.getLength();
ndbrequire((elemConptr - tgeRemLen) < 2048);
} else {
ndbrequire((tgeNextptrtype == ZLEFT) || (tgeNextptrtype == ZRIGHT));
}//if
if (tgeRemLen >= Container::HEADER_SIZE + TelemLen) {
ndbrequire(tgeRemLen <= ZBUF_SIZE);
/* ------------------------------------------------------------------- */
// There is at least one element in this container.
// Check if it is the element searched for.
/* ------------------------------------------------------------------- */
do {
bool possible_match;
tgeElementHeader = elemPageptr.p->word32[elemptr];
tgeRemLen = tgeRemLen - TelemLen;
Local_key localkey;
lockOwnerPtr.i = RNIL;
lockOwnerPtr.p = NULL;
LHBits16 reducedHashValue;
if (ElementHeader::getLocked(tgeElementHeader)) {
jam();
lockOwnerPtr.i = ElementHeader::getOpPtrI(tgeElementHeader);
ptrCheckGuard(lockOwnerPtr, coprecsize, operationrec);
possible_match = lockOwnerPtr.p->hashValue.match(operationRecPtr.p->hashValue);
reducedHashValue = lockOwnerPtr.p->reducedHashValue;
localkey = lockOwnerPtr.p->localdata;
} else {
jam();
reducedHashValue = ElementHeader::getReducedHashValue(tgeElementHeader);
const Uint32 pos = elemptr + 1;
ndbrequire(localkeylen == 1);
localkey.m_page_no = elemPageptr.p->word32[pos];
localkey.m_page_idx = ElementHeader::getPageIdx(tgeElementHeader);
possible_match = true;
}
if (possible_match &&
operationRecPtr.p->hashValue.match(fragrecptr.p->level.enlarge(reducedHashValue, bucket_number)))
{
jam();
bool found;
if (! searchLocalKey)
{
Uint32 len = readTablePk(localkey.m_page_no, localkey.m_page_idx, tgeElementHeader,
lockOwnerPtr);
found = (len == operationRecPtr.p->xfrmtupkeylen) &&
(memcmp(Tkeydata, ckeys, len << 2) == 0);
} else {
jam();
found = (localkey.m_page_no == Tkeydata[0] && Uint32(localkey.m_page_idx) == Tkeydata[1]);
}
if (found)
{
jam();
operationRecPtr.p->localdata = localkey;
return ZTRUE;
}
}
if (tgeRemLen <= Container::HEADER_SIZE) {
break;
}
elemptr = elemptr + tgeElemStep;
} while (true);
}//if
ndbrequire(tgeRemLen == Container::HEADER_SIZE);
ContainerHeader containerhead = elemPageptr.p->word32[elemConptr];
tgeNextptrtype = containerhead.getNextEnd();
if (tgeNextptrtype == 0) {
jam();
return ZFALSE; /* NO MORE CONTAINER */
}//if
tgePageindex = containerhead.getNextIndexNumber(); /* NEXT CONTAINER PAGE INDEX 7 BITS */
ndbrequire(tgePageindex <= Container::NO_CONTAINER_INDEX);
if (!containerhead.isNextOnSamePage()) {
jam();
elemPageptr.i = elemPageptr.p->word32[elemConptr + 1]; /* NEXT PAGE ID */
ptrCheckGuard(elemPageptr, cpagesize, page8);
}//if
} while (1);
return ZFALSE;
}//Dbacc::getElement()
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* */
/* END OF GET_ELEMENT MODULE */
/* */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* */
/* MODULE: DELETE */
/* */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* COMMITDELETE */
/* INPUT: OPERATION_REC_PTR, PTR TO AN OPERATION RECORD. */
/* FRAGRECPTR, PTR TO A FRAGMENT RECORD */
/* */
/* OUTPUT: */
/* NONE */
/* DESCRIPTION: DELETE OPERATIONS WILL BE COMPLETED AT THE
* COMMIT OF TRANSACTION. THIS SUBROUTINE SEARCHS FOR ELEMENT AND
* DELETES IT. IT DOES SO BY REPLACING IT WITH THE LAST
* ELEMENT IN THE BUCKET. IF THE DELETED ELEMENT IS ALSO THE LAST
* ELEMENT THEN IT IS ONLY NECESSARY TO REMOVE THE ELEMENT
* ------------------------------------------------------------------------- */
void
Dbacc::report_dealloc(Signal* signal, const Operationrec* opPtrP)
{
Local_key localKey = opPtrP->localdata;
Uint32 opbits = opPtrP->m_op_bits;
Uint32 userptr= opPtrP->userptr;
Uint32 scanInd =
((opbits & Operationrec::OP_MASK) == ZSCAN_OP) ||
(opbits & Operationrec::OP_LOCK_REQ);
if (! localKey.isInvalid())
{
signal->theData[0] = fragrecptr.p->myfid;
signal->theData[1] = fragrecptr.p->myTableId;
signal->theData[2] = localKey.m_page_no;
signal->theData[3] = localKey.m_page_idx;
signal->theData[4] = userptr;
signal->theData[5] = scanInd;
EXECUTE_DIRECT(DBLQH, GSN_TUP_DEALLOCREQ, signal, 6);
jamEntry();
}
}
void Dbacc::commitdelete(Signal* signal)
{
Page8Ptr lastPageptr;
Page8Ptr lastPrevpageptr;
bool lastIsforward;
Uint32 tlastPageindex;
Uint32 tlastElementptr;
Uint32 tlastContainerptr;
Uint32 tlastPrevconptr;
Page8Ptr lastBucketPageptr;
Uint32 lastBucketConidx;
jam();
report_dealloc(signal, operationRecPtr.p);
getdirindex(lastBucketPageptr, lastBucketConidx);
lastPageptr = lastBucketPageptr;
tlastPageindex = lastBucketConidx;
lastIsforward = true;
tlastContainerptr = getForwardContainerPtr(tlastPageindex);
arrGuard(tlastContainerptr, 2048);
lastPrevpageptr.i = RNIL;
ptrNull(lastPrevpageptr);
tlastPrevconptr = 0;
/**
* Position last on delete container before call to getLastAndRemove.
*/
Page8Ptr delPageptr;
delPageptr.i = operationRecPtr.p->elementPage;
ptrCheckGuard(delPageptr, cpagesize, page8);
const Uint32 delConptr = operationRecPtr.p->elementContainer;
while (lastPageptr.i != delPageptr.i ||
tlastContainerptr != delConptr)
{
lastPrevpageptr = lastPageptr;
tlastPrevconptr = tlastContainerptr;
ContainerHeader lasthead(lastPageptr.p->word32[tlastContainerptr]);
ndbrequire(lasthead.haveNext());
if (!lasthead.isNextOnSamePage())
{
lastPageptr.i = lastPageptr.p->word32[tlastContainerptr + 1];
ptrCheckGuard(lastPageptr, cpagesize, page8);
}
tlastPageindex = lasthead.getNextIndexNumber();
lastIsforward = lasthead.getNextEnd() == ZLEFT;
tlastContainerptr = getContainerPtr(tlastPageindex, lastIsforward);
}
getLastAndRemove(lastPrevpageptr,
tlastPrevconptr,
lastPageptr,
tlastPageindex,
tlastContainerptr,
lastIsforward,
tlastElementptr);
const Uint32 delElemptr = operationRecPtr.p->elementPointer;
/*
* If last element is in same container as delete element, and that container
* have scans in progress, one must make sure the last element still have the
* same scan state, or clear if it is the one deleted.
* If last element is not in same container as delete element, that element
* can not have any scans in progress, in that case the container scanbits
* should have been fewer than delete containers which is not allowed for last.
*/
if ((lastPageptr.i == delPageptr.i) &&
(tlastContainerptr == delConptr))
{
ContainerHeader conhead(delPageptr.p->word32[delConptr]);
/**
* If the deleted element was the only element in container
* getLastAndRemove may have released the container already.
* In that case header is still valid to read but it will
* not be in use, but free.
*/
if (conhead.isInUse() && conhead.isScanInProgress())
{
/**
* Initialize scanInProgress with the active scans which have not
* completly scanned the container. Then check which scan actually
* currently scan the container.
*/
Uint16 scansInProgress =
fragrecptr.p->activeScanMask & ~conhead.getScanBits();
scansInProgress = delPageptr.p->checkScans(scansInProgress, delConptr);
for(int i = 0; scansInProgress != 0; i++, scansInProgress >>= 1)
{
/**
* For each scan in progress in container, move the scan bit for
* last element to the delete elements place. If it is the last
* element that is deleted, the scan bit will be cleared by
* moveScanBit.
*/
if ((scansInProgress & 1) != 0)
{
ScanRecPtr scanPtr;
scanPtr.i = fragrecptr.p->scan[i];
ptrCheckGuard(scanPtr, cscanRecSize, scanRec);
scanPtr.p->moveScanBit(delElemptr, tlastElementptr);
}
}
}
}
else
{
/**
* The last element which is to be moved into deleted elements place
* are in different containers.
*
* Since both containers have the same scan bits that implies that there
* are no scans in progress in the last elements container, otherwise
* the delete container should have an extra scan bit set.
*/
#ifdef VM_TRACE
ContainerHeader conhead(lastPageptr.p->word32[tlastContainerptr]);
ndbassert(!conhead.isInUse() || !conhead.isScanInProgress());
conhead = ContainerHeader(delPageptr.p->word32[delConptr]);
#else
ContainerHeader conhead(delPageptr.p->word32[delConptr]);
#endif
if (conhead.isScanInProgress())
{
/**
* Initialize scanInProgress with the active scans which have not
* completly scanned the container. Then check which scan actually
* currently scan the container.
*/
Uint16 scansInProgress = fragrecptr.p->activeScanMask & ~conhead.getScanBits();
scansInProgress = delPageptr.p->checkScans(scansInProgress, delConptr);
for(int i = 0; scansInProgress != 0; i++, scansInProgress >>= 1)
{
if ((scansInProgress & 1) != 0)
{
ScanRecPtr scanPtr;
scanPtr.i = fragrecptr.p->scan[i];
ptrCheckGuard(scanPtr, cscanRecSize, scanRec);
if(scanPtr.p->isScanned(delElemptr))
{
scanPtr.p->clearScanned(delElemptr);
}
}
}
}
}
if (operationRecPtr.p->elementPage == lastPageptr.i) {
if (operationRecPtr.p->elementPointer == tlastElementptr) {
jam();
/* --------------------------------------------------------------------------------- */
/* THE LAST ELEMENT WAS THE ELEMENT TO BE DELETED. WE NEED NOT COPY IT. */
/* Setting it to an invalid value only for sanity, the value should never be read. */
/* --------------------------------------------------------------------------------- */
delPageptr.p->word32[delElemptr] = ElementHeader::setInvalid();
return;
}//if
}//if
/* --------------------------------------------------------------------------------- */
/* THE DELETED ELEMENT IS NOT THE LAST. WE READ THE LAST ELEMENT AND OVERWRITE THE */
/* DELETED ELEMENT. */
/* --------------------------------------------------------------------------------- */
#if defined(VM_TRACE) || !defined(NDEBUG)
delPageptr.p->word32[delElemptr] = ElementHeader::setInvalid();
#endif
deleteElement(delPageptr,
delConptr,
delElemptr,
lastPageptr,
tlastElementptr);
}//Dbacc::commitdelete()
/** --------------------------------------------------------------------------
* Move last element over deleted element.
*
* And if moved element has an operation record update that with new element
* location.
*
* @param[in] delPageptr Pointer to page of deleted element.
* @param[in] delConptr Pointer within page to container of deleted element
* @param[in] delElemptr Pointer within page to deleted element.
* @param[in] lastPageptr Pointer to page of last element.
* @param[in] lastElemptr Pointer within page to last element.
* ------------------------------------------------------------------------- */
void Dbacc::deleteElement(Page8Ptr delPageptr,
Uint32 delConptr,
Uint32 delElemptr,
Page8Ptr lastPageptr,
Uint32 lastElemptr) const
{
OperationrecPtr deOperationRecPtr;
if (lastElemptr >= 2048)
goto deleteElement_index_error1;
{
const Uint32 tdeElemhead = lastPageptr.p->word32[lastElemptr];
ndbrequire(fragrecptr.p->elementLength == 2);
ndbassert(!ElementHeader::isValid(delPageptr.p->word32[delElemptr]));
delPageptr.p->word32[delElemptr] = lastPageptr.p->word32[lastElemptr];
delPageptr.p->word32[delElemptr + 1] =
lastPageptr.p->word32[lastElemptr + 1];
if (ElementHeader::getLocked(tdeElemhead))
{
/* --------------------------------------------------------------------------------- */
/* THE LAST ELEMENT IS LOCKED AND IS THUS REFERENCED BY AN OPERATION RECORD. WE NEED */
/* TO UPDATE THE OPERATION RECORD WITH THE NEW REFERENCE TO THE ELEMENT. */
/* --------------------------------------------------------------------------------- */
deOperationRecPtr.i = ElementHeader::getOpPtrI(tdeElemhead);
ptrCheckGuard(deOperationRecPtr, coprecsize, operationrec);
deOperationRecPtr.p->elementPage = delPageptr.i;
deOperationRecPtr.p->elementContainer = delConptr;
deOperationRecPtr.p->elementPointer = delElemptr;
/* Writing an invalid value only for sanity, the value should never be read. */
lastPageptr.p->word32[lastElemptr] = ElementHeader::setInvalid();
}//if
return;
}
deleteElement_index_error1:
arrGuard(lastElemptr, 2048);
return;
}//Dbacc::deleteElement()
/** ---------------------------------------------------------------------------
* Find last element in bucket.
*
* Shrink container of last element, but keep element words intact. If
* container became empty and is not the first container in bucket, unlink it
* from previous container.
*
* @param[in] lastPrevpageptr Page of previous container, if any.
* @param[in] tlastPrevconptr Pointer within page of previous container
* @param[in,out] lastPageptr Page of first container to search, and on
* return the last container.
* @param[in,out] tlastPageindex Index of container within first page to
* search, and on return the last container.
* @param[in,out] tlastContainerptr Pointer within page to first container to
* search, and on return the last container.
* @param[in,out] lastIsforward Direction of first container to search,
* and on return the last container.
* @param[out] tlastElementptr On return the pointer within page to last
* element.
* ------------------------------------------------------------------------ */
void Dbacc::getLastAndRemove(Page8Ptr lastPrevpageptr,
Uint32 tlastPrevconptr,
Page8Ptr& lastPageptr,
Uint32& tlastPageindex,
Uint32& tlastContainerptr,
bool& lastIsforward,
Uint32& tlastElementptr)
{
/**
* Should find the last container with same scanbits as the first.
*/
ContainerHeader containerhead(lastPageptr.p->word32[tlastContainerptr]);
Uint32 tlastContainerlen = containerhead.getLength();
/**
* getLastAndRemove are always called prior delete of element in first
* container, and that can not be empty.
*/
ndbassert(tlastContainerlen != Container::HEADER_SIZE);
const Uint16 activeScanMask = fragrecptr.p->activeScanMask;
const Uint16 conScanMask = containerhead.getScanBits();
while (containerhead.getNextEnd() != 0)
{
jam();
Uint32 nextIndex = containerhead.getNextIndexNumber();
Uint32 nextEnd = containerhead.getNextEnd();
bool nextOnSamePage = containerhead.isNextOnSamePage();
Page8Ptr nextPage;
if (nextOnSamePage)
{
nextPage = lastPageptr;
}
else
{
jam();
nextPage.i = lastPageptr.p->word32[tlastContainerptr + 1];
ptrCheckGuard(nextPage, cpagesize, page8);
}
const bool nextIsforward = nextEnd == ZLEFT;
const Uint32 nextConptr = getContainerPtr(nextIndex, nextIsforward);
const ContainerHeader nextHead(nextPage.p->word32[nextConptr]);
const Uint16 nextScanMask = nextHead.getScanBits();
if (((conScanMask ^ nextScanMask) & activeScanMask) != 0)
{
/**
* Next container have different active scan bits,
* current container is the last one with wanted scan bits.
* Stop searching!
*/
ndbassert(((nextScanMask & ~conScanMask) & activeScanMask) == 0);
break;
}
lastPrevpageptr.i = lastPageptr.i;
lastPrevpageptr.p = lastPageptr.p;
tlastPrevconptr = tlastContainerptr;
tlastPageindex = nextIndex;
if (!nextOnSamePage)
{
lastPageptr = nextPage;
}
lastIsforward = nextIsforward;
tlastContainerptr = nextConptr;
containerhead = lastPageptr.p->word32[tlastContainerptr];
tlastContainerlen = containerhead.getLength();
ndbassert(tlastContainerlen >= ((Uint32)Container::HEADER_SIZE + fragrecptr.p->elementLength));
}
/**
* Last container found.
*/
tlastContainerlen = tlastContainerlen - fragrecptr.p->elementLength;
if (lastIsforward)
{
jam();
tlastElementptr = tlastContainerptr + tlastContainerlen;
}
else
{
jam();
tlastElementptr = (tlastContainerptr + (Container::HEADER_SIZE -
fragrecptr.p->elementLength)) -
tlastContainerlen;
}//if
if (containerhead.isUsingBothEnds()) {
/* --------------------------------------------------------------------------------- */
/* WE HAVE OWNERSHIP OF BOTH PARTS OF THE CONTAINER ENDS. */
/* --------------------------------------------------------------------------------- */
if (tlastContainerlen < Container::DOWN_LIMIT) {
/* --------------------------------------------------------------------------------- */
/* WE HAVE DECREASED THE SIZE BELOW THE DOWN LIMIT, WE MUST GIVE UP THE OTHER */
/* SIDE OF THE BUFFER. */
/* --------------------------------------------------------------------------------- */
containerhead.clearUsingBothEnds();
if (lastIsforward)
{
jam();
Uint32 relconptr = tlastContainerptr +
(ZBUF_SIZE - Container::HEADER_SIZE);
releaseRightlist(lastPageptr, tlastPageindex, relconptr);
} else {
jam();
Uint32 relconptr = tlastContainerptr -
(ZBUF_SIZE - Container::HEADER_SIZE);
releaseLeftlist(lastPageptr, tlastPageindex, relconptr);
}//if
}//if
}//if
if (tlastContainerlen <= Container::HEADER_SIZE)
{
ndbrequire(tlastContainerlen == Container::HEADER_SIZE);
if (lastPrevpageptr.i != RNIL)
{
jam();
/* --------------------------------------------------------------------------------- */
/* THE LAST CONTAINER IS EMPTY AND IS NOT THE FIRST CONTAINER WHICH IS NOT REMOVED. */
/* DELETE THE LAST CONTAINER AND UPDATE THE PREVIOUS CONTAINER. ALSO PUT THIS */
/* CONTAINER IN FREE CONTAINER LIST OF THE PAGE. */
/* --------------------------------------------------------------------------------- */
ndbrequire(tlastPrevconptr < 2048);
ContainerHeader prevConhead(lastPrevpageptr.p->word32[tlastPrevconptr]);
ndbrequire(containerhead.isInUse());
if (!containerhead.haveNext())
{
Uint32 tglrTmp = prevConhead.clearNext();
dbgWord32(lastPrevpageptr, tlastPrevconptr, tglrTmp);
lastPrevpageptr.p->word32[tlastPrevconptr] = tglrTmp;
}
else
{
Uint32 nextPagei = (containerhead.isNextOnSamePage()
? lastPageptr.i
: lastPageptr.p->word32[tlastContainerptr+1]);
Uint32 tglrTmp = prevConhead.setNext(containerhead.getNextEnd(),
containerhead.getNextIndexNumber(),
(nextPagei == lastPrevpageptr.i));
dbgWord32(lastPrevpageptr, tlastPrevconptr, tglrTmp);
lastPrevpageptr.p->word32[tlastPrevconptr] = tglrTmp;
lastPrevpageptr.p->word32[tlastPrevconptr+1] = nextPagei;
}
/**
* Any scans currently scanning the last container must be evicted from
* container since it is about to be deleted. Scans will look for next
* unscanned container at next call to getScanElement.
*/
if (containerhead.isScanInProgress())
{
Uint16 scansInProgress =
fragrecptr.p->activeScanMask & ~containerhead.getScanBits();
scansInProgress = lastPageptr.p->checkScans(scansInProgress,
tlastContainerptr);
Uint16 scanbit = 1;
for(int i = 0 ;
scansInProgress != 0 ;
i++, scansInProgress>>=1, scanbit<<=1)
{
if ((scansInProgress & 1) != 0)
{
ScanRecPtr scanPtr;
scanPtr.i = fragrecptr.p->scan[i];
ptrCheckGuard(scanPtr, cscanRecSize, scanRec);
scanPtr.p->leaveContainer(lastPageptr.i, tlastContainerptr);
lastPageptr.p->clearScanContainer(scanbit, tlastContainerptr);
}
}
/**
* All scans in progress for container are now canceled.
* No need to call clearScanInProgress for container header since
* container is about to be released anyway.
*/
}
if (lastIsforward)
{
jam();
releaseLeftlist(lastPageptr, tlastPageindex, tlastContainerptr);
}
else
{
jam();
releaseRightlist(lastPageptr, tlastPageindex, tlastContainerptr);
}//if
return;
}//if
}//if
containerhead.setLength(tlastContainerlen);
dbgWord32(lastPageptr, tlastContainerptr, containerhead);
arrGuard(tlastContainerptr, 2048);
lastPageptr.p->word32[tlastContainerptr] = containerhead;
}//Dbacc::getLastAndRemove()
/* --------------------------------------------------------------------------------- */
/* RELEASE_LEFTLIST */
/* INPUT: */
/* RL_PAGEPTR PAGE POINTER OF CONTAINER TO BE RELEASED */
/* TRL_PAGEINDEX PAGE INDEX OF CONTAINER TO BE RELEASED */
/* TURL_INDEX INDEX OF CONTAINER TO BE RELEASED */
/* TRL_REL_CON TRUE IF CONTAINER RELEASED OTHERWISE ONLY */
/* A PART IS RELEASED. */
/* */
/* OUTPUT: */
/* NONE */
/* */
/* THE FREE LIST OF LEFT FREE BUFFER IN THE PAGE WILL BE UPDATE */
/* TULL_INDEX IS INDEX TO THE FIRST WORD IN THE LEFT SIDE OF THE BUFFER */
/* --------------------------------------------------------------------------------- */
void Dbacc::releaseLeftlist(Page8Ptr pageptr, Uint32 conidx, Uint32 conptr)
{
Uint32 tullTmp;
Uint32 tullTmp1;
dbgWord32(pageptr, conptr + 1, Container::NO_CONTAINER_INDEX);
arrGuard(conptr + 1, 2048);
pageptr.p->word32[conptr + 1] = Container::NO_CONTAINER_INDEX;
tullTmp1 = (pageptr.p->word32[ZPOS_EMPTY_LIST] >> 7) & 0x7f;
dbgWord32(pageptr, conptr, tullTmp1);
arrGuard(conptr, 2048);
pageptr.p->word32[conptr] = tullTmp1;
if (tullTmp1 <= Container::MAX_CONTAINER_INDEX) {
jam();
tullTmp1 = getForwardContainerPtr(tullTmp1) + 1;
dbgWord32(pageptr, tullTmp1, conidx);
/* UPDATES PREV POINTER IN THE NEXT FREE */
pageptr.p->word32[tullTmp1] = conidx;
} else {
ndbrequire(tullTmp1 == Container::NO_CONTAINER_INDEX);
}//if
tullTmp = pageptr.p->word32[ZPOS_EMPTY_LIST];
tullTmp = (((tullTmp >> 14) << 14) | (conidx << 7)) | (tullTmp & 0x7f);
dbgWord32(pageptr, ZPOS_EMPTY_LIST, tullTmp);
pageptr.p->word32[ZPOS_EMPTY_LIST] = tullTmp;
dbgWord32(pageptr,
ZPOS_ALLOC_CONTAINERS,
pageptr.p->word32[ZPOS_ALLOC_CONTAINERS] - 1);
pageptr.p->word32[ZPOS_ALLOC_CONTAINERS] =
pageptr.p->word32[ZPOS_ALLOC_CONTAINERS] - 1;
ndbrequire(pageptr.p->word32[ZPOS_ALLOC_CONTAINERS] <= ZNIL);
if (((pageptr.p->word32[ZPOS_EMPTY_LIST] >> ZPOS_PAGE_TYPE_BIT) & 3) == 1) {
jam();
ptrCheck(pageptr, cpagesize, page8);
checkoverfreelist(pageptr);
}//if
}//Dbacc::releaseLeftlist()
/* --------------------------------------------------------------------------------- */
/* RELEASE_RIGHTLIST */
/* INPUT: */
/* RL_PAGEPTR PAGE POINTER OF CONTAINER TO BE RELEASED */
/* TRL_PAGEINDEX PAGE INDEX OF CONTAINER TO BE RELEASED */
/* TURL_INDEX INDEX OF CONTAINER TO BE RELEASED */
/* TRL_REL_CON TRUE IF CONTAINER RELEASED OTHERWISE ONLY */
/* A PART IS RELEASED. */
/* */
/* OUTPUT: */
/* NONE */
/* */
/* THE FREE LIST OF RIGHT FREE BUFFER IN THE PAGE WILL BE UPDATE. */
/* TURL_INDEX IS INDEX TO THE FIRST WORD IN THE RIGHT SIDE OF */
/* THE BUFFER, WHICH IS THE LAST WORD IN THE BUFFER. */
/* --------------------------------------------------------------------------------- */
void Dbacc::releaseRightlist(Page8Ptr pageptr, Uint32 conidx, Uint32 conptr)
{
Uint32 turlTmp1;
Uint32 turlTmp;
dbgWord32(pageptr, conptr + 1, Container::NO_CONTAINER_INDEX);
arrGuard(conptr + 1, 2048);
pageptr.p->word32[conptr + 1] = Container::NO_CONTAINER_INDEX;
turlTmp1 = pageptr.p->word32[ZPOS_EMPTY_LIST] & 0x7f;
dbgWord32(pageptr, conptr, turlTmp1);
arrGuard(conptr, 2048);
pageptr.p->word32[conptr] = turlTmp1;
if (turlTmp1 <= Container::MAX_CONTAINER_INDEX) {
jam();
turlTmp = getBackwardContainerPtr(turlTmp1) + 1;
dbgWord32(pageptr, turlTmp, conidx);
/* UPDATES PREV POINTER IN THE NEXT FREE */
pageptr.p->word32[turlTmp] = conidx;
} else {
ndbrequire(turlTmp1 == Container::NO_CONTAINER_INDEX);
}//if
turlTmp = pageptr.p->word32[ZPOS_EMPTY_LIST];
dbgWord32(pageptr, ZPOS_EMPTY_LIST, ((turlTmp >> 7) << 7) | conidx);
pageptr.p->word32[ZPOS_EMPTY_LIST] = ((turlTmp >> 7) << 7) | conidx;
dbgWord32(pageptr,
ZPOS_ALLOC_CONTAINERS,
pageptr.p->word32[ZPOS_ALLOC_CONTAINERS] - 1);
pageptr.p->word32[ZPOS_ALLOC_CONTAINERS] =
pageptr.p->word32[ZPOS_ALLOC_CONTAINERS] - 1;
ndbrequire(pageptr.p->word32[ZPOS_ALLOC_CONTAINERS] <= ZNIL);
if (((pageptr.p->word32[ZPOS_EMPTY_LIST] >> ZPOS_PAGE_TYPE_BIT) & 3) == 1) {
jam();
checkoverfreelist(pageptr);
}//if
}//Dbacc::releaseRightlist()
/* --------------------------------------------------------------------------------- */
/* CHECKOVERFREELIST */
/* INPUT: COL_PAGEPTR, POINTER OF AN OVERFLOW PAGE RECORD. */
/* DESCRIPTION: CHECKS IF THE PAGE HAVE TO PUT IN FREE LIST OF OVER FLOW */
/* PAGES. WHEN IT HAVE TO, AN OVERFLOW REC PTR WILL BE ALLOCATED */
/* TO KEEP NFORMATION ABOUT THE PAGE. */
/* --------------------------------------------------------------------------------- */
void Dbacc::checkoverfreelist(Page8Ptr colPageptr)
{
Uint32 tcolTmp;
// always an overflow page
tcolTmp = colPageptr.p->word32[ZPOS_ALLOC_CONTAINERS];
if (tcolTmp == 0) // Just got empty
{
jam();
releaseOverpage(colPageptr);
}
else if (tcolTmp == ZFREE_LIMIT) // Just got sparse
{
jam();
LocalContainerPageList fulllist(*this, fragrecptr.p->fullpages);
LocalContainerPageList sparselist(*this, fragrecptr.p->sparsepages);
fulllist.remove(colPageptr);
sparselist.addFirst(colPageptr);
}//if
}//Dbacc::checkoverfreelist()
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* */
/* END OF DELETE MODULE */
/* */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* */
/* COMMIT AND ABORT MODULE */
/* */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ABORT_OPERATION */
/*DESCRIPTION: AN OPERATION RECORD CAN BE IN A LOCK QUEUE OF AN ELEMENT OR */
/*OWNS THE LOCK. BY THIS SUBROUTINE THE LOCK STATE OF THE OPERATION WILL */
/*BE CHECKED. THE OPERATION RECORD WILL BE REMOVED FROM THE QUEUE IF IT */
/*BELONGED TO ANY ONE, OTHERWISE THE ELEMENT HEAD WILL BE UPDATED. */
/* ------------------------------------------------------------------------- */
/**
*
* P0 - P1 - P2 - P3
* S0
* S1
* S2
*/
void
Dbacc::abortParallelQueueOperation(Signal* signal, OperationrecPtr opPtr)
{
jam();
OperationrecPtr nextP;
OperationrecPtr prevP;
OperationrecPtr loPtr;
Uint32 opbits = opPtr.p->m_op_bits;
Uint32 opstate = opbits & Operationrec::OP_STATE_MASK;
nextP.i = opPtr.p->nextParallelQue;
prevP.i = opPtr.p->prevParallelQue;
loPtr.i = opPtr.p->m_lock_owner_ptr_i;
ndbassert(! (opbits & Operationrec::OP_LOCK_OWNER));
ndbassert(opbits & Operationrec::OP_RUN_QUEUE);
ptrCheckGuard(prevP, coprecsize, operationrec);
ndbassert(prevP.p->nextParallelQue == opPtr.i);
prevP.p->nextParallelQue = nextP.i;
if (nextP.i != RNIL)
{
ptrCheckGuard(nextP, coprecsize, operationrec);
ndbassert(nextP.p->prevParallelQue == opPtr.i);
nextP.p->prevParallelQue = prevP.i;
}
else if (prevP.i != loPtr.i)
{
jam();
ptrCheckGuard(loPtr, coprecsize, operationrec);
ndbassert(loPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER);
ndbassert(loPtr.p->m_lo_last_parallel_op_ptr_i == opPtr.i);
loPtr.p->m_lo_last_parallel_op_ptr_i = prevP.i;
prevP.p->m_lock_owner_ptr_i = loPtr.i;
/**
* Abort P3...check start next
*/
startNext(signal, prevP);
validate_lock_queue(prevP);
return;
}
else
{
jam();
/**
* P0 - P1
*
* Abort P1, check start next
*/
ndbassert(prevP.p->m_op_bits & Operationrec::OP_LOCK_OWNER);
prevP.p->m_lo_last_parallel_op_ptr_i = RNIL;
startNext(signal, prevP);
validate_lock_queue(prevP);
return;
}
/**
* Abort P1/P2
*/
if (opbits & Operationrec::OP_LOCK_MODE)
{
Uint32 nextbits = nextP.p->m_op_bits;
while ((nextbits & Operationrec::OP_LOCK_MODE) == 0)
{
ndbassert(nextbits & Operationrec::OP_ACC_LOCK_MODE);
nextbits &= ~(Uint32)Operationrec::OP_ACC_LOCK_MODE;
nextP.p->m_op_bits = nextbits;
if (nextP.p->nextParallelQue != RNIL)
{
nextP.i = nextP.p->nextParallelQue;
ptrCheckGuard(nextP, coprecsize, operationrec);
nextbits = nextP.p->m_op_bits;
}
else
{
break;
}
}
}
/**
* Abort P1, P2
*/
if (opstate == Operationrec::OP_STATE_RUNNING)
{
jam();
startNext(signal, prevP);
validate_lock_queue(prevP);
return;
}
ndbassert(opstate == Operationrec::OP_STATE_EXECUTED ||
opstate == Operationrec::OP_STATE_WAITING);
/**
* Scan to last of run queue
*/
while (nextP.p->nextParallelQue != RNIL)
{
jam();
nextP.i = nextP.p->nextParallelQue;
ptrCheckGuard(nextP, coprecsize, operationrec);
}
#ifdef VM_TRACE
loPtr.i = nextP.p->m_lock_owner_ptr_i;
ptrCheckGuard(loPtr, coprecsize, operationrec);
ndbassert(loPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER);
ndbassert(loPtr.p->m_lo_last_parallel_op_ptr_i == nextP.i);
#endif
startNext(signal, nextP);
validate_lock_queue(nextP);
return;
}
void
Dbacc::abortSerieQueueOperation(Signal* signal, OperationrecPtr opPtr)
{
jam();
OperationrecPtr prevS, nextS;
OperationrecPtr prevP, nextP;
OperationrecPtr loPtr;
Uint32 opbits = opPtr.p->m_op_bits;
prevS.i = opPtr.p->prevSerialQue;
nextS.i = opPtr.p->nextSerialQue;
prevP.i = opPtr.p->prevParallelQue;
nextP.i = opPtr.p->nextParallelQue;
ndbassert((opbits & Operationrec::OP_LOCK_OWNER) == 0);
ndbassert((opbits & Operationrec::OP_RUN_QUEUE) == 0);
{
FragmentrecPtr frp;
frp.i = opPtr.p->fragptr;
ptrCheckGuard(frp, cfragmentsize, fragmentrec);
frp.p->m_lockStats.wait_fail((opbits &
Operationrec::OP_LOCK_MODE)
!= ZREADLOCK,
opPtr.p->m_lockTime,
getHighResTimer());
}
if (prevP.i != RNIL)
{
/**
* We're not list head...
*/
ptrCheckGuard(prevP, coprecsize, operationrec);
ndbassert(prevP.p->nextParallelQue == opPtr.i);
prevP.p->nextParallelQue = nextP.i;
if (nextP.i != RNIL)
{
ptrCheckGuard(nextP, coprecsize, operationrec);
ndbassert(nextP.p->prevParallelQue == opPtr.i);
ndbassert((nextP.p->m_op_bits & Operationrec::OP_STATE_MASK) ==
Operationrec::OP_STATE_WAITING);
nextP.p->prevParallelQue = prevP.i;
if ((prevP.p->m_op_bits & Operationrec::OP_ACC_LOCK_MODE) == 0 &&
opbits & Operationrec::OP_LOCK_MODE)
{
/**
* Scan right in parallel queue to fix OP_ACC_LOCK_MODE
*/
while ((nextP.p->m_op_bits & Operationrec::OP_LOCK_MODE) == 0)
{
ndbassert(nextP.p->m_op_bits & Operationrec::OP_ACC_LOCK_MODE);
nextP.p->m_op_bits &= ~(Uint32)Operationrec::OP_ACC_LOCK_MODE;
nextP.i = nextP.p->nextParallelQue;
if (nextP.i == RNIL)
break;
ptrCheckGuard(nextP, coprecsize, operationrec);
}
}
}
validate_lock_queue(prevP);
return;
}
else
{
/**
* We're a list head
*/
ptrCheckGuard(prevS, coprecsize, operationrec);
ndbassert(prevS.p->nextSerialQue == opPtr.i);
if (nextP.i != RNIL)
{
/**
* Promote nextP to list head
*/
ptrCheckGuard(nextP, coprecsize, operationrec);
ndbassert(nextP.p->prevParallelQue == opPtr.i);
prevS.p->nextSerialQue = nextP.i;
nextP.p->prevParallelQue = RNIL;
nextP.p->nextSerialQue = nextS.i;
if (nextS.i != RNIL)
{
jam();
ptrCheckGuard(nextS, coprecsize, operationrec);
ndbassert(nextS.p->prevSerialQue == opPtr.i);
nextS.p->prevSerialQue = nextP.i;
validate_lock_queue(prevS);
return;
}
else
{
// nextS is RNIL, i.e we're last in serie queue...
// we must update lockOwner.m_lo_last_serial_op_ptr_i
loPtr = prevS;
while ((loPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER) == 0)
{
loPtr.i = loPtr.p->prevSerialQue;
ptrCheckGuard(loPtr, coprecsize, operationrec);
}
ndbassert(loPtr.p->m_lo_last_serial_op_ptr_i == opPtr.i);
loPtr.p->m_lo_last_serial_op_ptr_i = nextP.i;
validate_lock_queue(loPtr);
return;
}
}
if (nextS.i == RNIL)
{
/**
* Abort S2
*/
// nextS is RNIL, i.e we're last in serie queue...
// and we have no parallel queue,
// we must update lockOwner.m_lo_last_serial_op_ptr_i
prevS.p->nextSerialQue = RNIL;
loPtr = prevS;
while ((loPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER) == 0)
{
loPtr.i = loPtr.p->prevSerialQue;
ptrCheckGuard(loPtr, coprecsize, operationrec);
}
ndbassert(loPtr.p->m_lo_last_serial_op_ptr_i == opPtr.i);
if (prevS.i != loPtr.i)
{
jam();
loPtr.p->m_lo_last_serial_op_ptr_i = prevS.i;
}
else
{
loPtr.p->m_lo_last_serial_op_ptr_i = RNIL;
}
validate_lock_queue(loPtr);
}
else if (nextP.i == RNIL)
{
ptrCheckGuard(nextS, coprecsize, operationrec);
ndbassert(nextS.p->prevSerialQue == opPtr.i);
prevS.p->nextSerialQue = nextS.i;
nextS.p->prevSerialQue = prevS.i;
if (prevS.p->m_op_bits & Operationrec::OP_LOCK_OWNER)
{
/**
* Abort S0
*/
OperationrecPtr lastOp;
lastOp.i = prevS.p->m_lo_last_parallel_op_ptr_i;
if (lastOp.i != RNIL)
{
jam();
ptrCheckGuard(lastOp, coprecsize, operationrec);
ndbassert(lastOp.p->m_lock_owner_ptr_i == prevS.i);
}
else
{
jam();
lastOp = prevS;
}
startNext(signal, lastOp);
validate_lock_queue(lastOp);
}
else
{
validate_lock_queue(prevS);
}
}
}
}
void Dbacc::abortOperation(Signal* signal)
{
Uint32 opbits = operationRecPtr.p->m_op_bits;
validate_lock_queue(operationRecPtr);
if (opbits & Operationrec::OP_LOCK_OWNER)
{
takeOutLockOwnersList(operationRecPtr);
opbits &= ~(Uint32)Operationrec::OP_LOCK_OWNER;
if (opbits & Operationrec::OP_INSERT_IS_DONE)
{
jam();
opbits |= Operationrec::OP_ELEMENT_DISAPPEARED;
}//if
operationRecPtr.p->m_op_bits = opbits;
const bool queue = (operationRecPtr.p->nextParallelQue != RNIL ||
operationRecPtr.p->nextSerialQue != RNIL);
if (queue)
{
jam();
release_lockowner(signal, operationRecPtr, false);
}
else
{
/* -------------------------------------------------------------------
* WE ARE OWNER OF THE LOCK AND NO OTHER OPERATIONS ARE QUEUED.
* IF INSERT OR STANDBY WE DELETE THE ELEMENT OTHERWISE WE REMOVE
* THE LOCK FROM THE ELEMENT.
* ------------------------------------------------------------------ */
if ((opbits & Operationrec::OP_ELEMENT_DISAPPEARED) == 0)
{
jam();
Page8Ptr aboPageidptr;
Uint32 taboElementptr;
Uint32 tmp2Olq;
taboElementptr = operationRecPtr.p->elementPointer;
aboPageidptr.i = operationRecPtr.p->elementPage;
ndbassert(!operationRecPtr.p->localdata.isInvalid());
tmp2Olq = ElementHeader::setUnlocked(
operationRecPtr.p->localdata.m_page_idx,
operationRecPtr.p->reducedHashValue);
ptrCheckGuard(aboPageidptr, cpagesize, page8);
dbgWord32(aboPageidptr, taboElementptr, tmp2Olq);
arrGuard(taboElementptr, 2048);
aboPageidptr.p->word32[taboElementptr] = tmp2Olq;
return;
}
else
{
jam();
commitdelete(signal);
}//if
}//if
}
else if (opbits & Operationrec::OP_RUN_QUEUE)
{
abortParallelQueueOperation(signal, operationRecPtr);
}
else
{
abortSerieQueueOperation(signal, operationRecPtr);
}
}
void
Dbacc::commitDeleteCheck()const
{
OperationrecPtr opPtr;
OperationrecPtr lastOpPtr;
OperationrecPtr deleteOpPtr;
Uint32 elementDeleted = 0;
bool deleteCheckOngoing = true;
LHBits32 hashValue;
lastOpPtr = operationRecPtr;
opPtr.i = operationRecPtr.p->nextParallelQue;
while (opPtr.i != RNIL) {
jam();
ptrCheckGuard(opPtr, coprecsize, operationrec);
lastOpPtr = opPtr;
opPtr.i = opPtr.p->nextParallelQue;
}//while
deleteOpPtr = lastOpPtr;
do {
Uint32 opbits = deleteOpPtr.p->m_op_bits;
Uint32 op = opbits & Operationrec::OP_MASK;
if (op == ZDELETE) {
jam();
/* -------------------------------------------------------------------
* IF THE CURRENT OPERATION TO BE COMMITTED IS A DELETE OPERATION DUE TO
* A SCAN-TAKEOVER THE ACTUAL DELETE WILL BE PERFORMED BY THE PREVIOUS
* OPERATION (SCAN) IN THE PARALLEL QUEUE WHICH OWNS THE LOCK.
* THE PROBLEM IS THAT THE SCAN OPERATION DOES NOT HAVE A HASH VALUE
* ASSIGNED TO IT SO WE COPY IT FROM THIS OPERATION.
*
* WE ASSUME THAT THIS SOLUTION WILL WORK BECAUSE THE ONLY WAY A
* SCAN CAN PERFORM A DELETE IS BY BEING FOLLOWED BY A NORMAL
* DELETE-OPERATION THAT HAS A HASH VALUE.
* ----------------------------------------------------------------- */
hashValue = deleteOpPtr.p->hashValue;
elementDeleted = Operationrec::OP_ELEMENT_DISAPPEARED;
deleteCheckOngoing = false;
} else if (op == ZREAD || op == ZSCAN_OP) {
/* -------------------------------------------------------------------
* We are trying to find out whether the commit will in the end delete
* the tuple. Normally the delete will be the last operation in the
* list of operations on this. It is however possible to issue reads
* and scans in the same savepoint as the delete operation was issued
* and these can end up after the delete in the list of operations
* in the parallel queue. Thus if we discover a read or a scan
* we have to continue scanning the list looking for a delete operation.
*/
deleteOpPtr.i = deleteOpPtr.p->prevParallelQue;
if (opbits & Operationrec::OP_LOCK_OWNER) {
jam();
deleteCheckOngoing = false;
} else {
jam();
ptrCheckGuard(deleteOpPtr, coprecsize, operationrec);
}//if
} else {
jam();
/* ------------------------------------------------------------------ */
/* Finding an UPDATE or INSERT before finding a DELETE
* means we cannot be deleting as the end result of this transaction.
*/
deleteCheckOngoing = false;
}//if
} while (deleteCheckOngoing);
opPtr = lastOpPtr;
do {
jam();
opPtr.p->m_op_bits |= Operationrec::OP_COMMIT_DELETE_CHECK;
if (elementDeleted) {
jam();
opPtr.p->m_op_bits |= elementDeleted;
opPtr.p->hashValue = hashValue;
}//if
opPtr.i = opPtr.p->prevParallelQue;
if (opPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER) {
jam();
break;
}//if
ptrCheckGuard(opPtr, coprecsize, operationrec);
} while (true);
}//Dbacc::commitDeleteCheck()
/* ------------------------------------------------------------------------- */
/* COMMIT_OPERATION */
/* INPUT: OPERATION_REC_PTR, POINTER TO AN OPERATION RECORD */
/* DESCRIPTION: THE OPERATION RECORD WILL BE TAKE OUT OF ANY LOCK QUEUE. */
/* IF IT OWNS THE ELEMENT LOCK. HEAD OF THE ELEMENT WILL BE UPDATED. */
/* ------------------------------------------------------------------------- */
void Dbacc::commitOperation(Signal* signal)
{
validate_lock_queue(operationRecPtr);
Uint32 opbits = operationRecPtr.p->m_op_bits;
Uint32 op = opbits & Operationrec::OP_MASK;
ndbrequire((opbits & Operationrec::OP_STATE_MASK) == Operationrec::OP_STATE_EXECUTED);
if ((opbits & Operationrec::OP_COMMIT_DELETE_CHECK) == 0 &&
(op != ZREAD && op != ZSCAN_OP))
{
jam();
/* This method is used to check whether the end result of the transaction
will be to delete the tuple. In this case all operation will be marked
with elementIsDisappeared = true to ensure that the last operation
committed will remove the tuple. We only run this once per transaction
(commitDeleteCheckFlag = true if performed earlier) and we don't
execute this code when committing a scan operation since committing
a scan operation only means that the scan is continuing and the scan
lock is released.
*/
commitDeleteCheck();
opbits = operationRecPtr.p->m_op_bits;
}//if
ndbassert(opbits & Operationrec::OP_RUN_QUEUE);
if (opbits & Operationrec::OP_LOCK_OWNER)
{
takeOutLockOwnersList(operationRecPtr);
opbits &= ~(Uint32)Operationrec::OP_LOCK_OWNER;
operationRecPtr.p->m_op_bits = opbits;
const bool queue = (operationRecPtr.p->nextParallelQue != RNIL ||
operationRecPtr.p->nextSerialQue != RNIL);
if (!queue && (opbits & Operationrec::OP_ELEMENT_DISAPPEARED) == 0)
{
/*
* This is the normal path through the commit for operations owning the
* lock without any queues and not a delete operation.
*/
Page8Ptr coPageidptr;
Uint32 tcoElementptr;
Uint32 tmp2Olq;
coPageidptr.i = operationRecPtr.p->elementPage;
tcoElementptr = operationRecPtr.p->elementPointer;
ndbassert(!operationRecPtr.p->localdata.isInvalid());
tmp2Olq = ElementHeader::setUnlocked(
operationRecPtr.p->localdata.m_page_idx,
operationRecPtr.p->reducedHashValue);
ptrCheckGuard(coPageidptr, cpagesize, page8);
dbgWord32(coPageidptr, tcoElementptr, tmp2Olq);
arrGuard(tcoElementptr, 2048);
coPageidptr.p->word32[tcoElementptr] = tmp2Olq;
return;
}
else if (queue)
{
jam();
/*
* The case when there is a queue lined up.
* Release the lock and pass it to the next operation lined up.
*/
release_lockowner(signal, operationRecPtr, true);
return;
}
else
{
jam();
/*
* No queue and elementIsDisappeared is true.
* We perform the actual delete operation.
*/
commitdelete(signal);
return;
}//if
}
else
{
/**
* THE OPERATION DOES NOT OWN THE LOCK. IT MUST BE IN A LOCK QUEUE OF THE
* ELEMENT.
*/
jam();
OperationrecPtr prev, next, lockOwner;
prev.i = operationRecPtr.p->prevParallelQue;
next.i = operationRecPtr.p->nextParallelQue;
lockOwner.i = operationRecPtr.p->m_lock_owner_ptr_i;
ptrCheckGuard(prev, coprecsize, operationrec);
prev.p->nextParallelQue = next.i;
if (next.i != RNIL)
{
jam();
ptrCheckGuard(next, coprecsize, operationrec);
next.p->prevParallelQue = prev.i;
}
else if (prev.p->m_op_bits & Operationrec::OP_LOCK_OWNER)
{
jam();
ndbassert(lockOwner.i == prev.i);
prev.p->m_lo_last_parallel_op_ptr_i = RNIL;
next = prev;
}
else
{
jam();
/**
* Last operation in parallell queue
*/
ndbassert(prev.i != lockOwner.i);
ptrCheckGuard(lockOwner, coprecsize, operationrec);
ndbassert(lockOwner.p->m_op_bits & Operationrec::OP_LOCK_OWNER);
lockOwner.p->m_lo_last_parallel_op_ptr_i = prev.i;
prev.p->m_lock_owner_ptr_i = lockOwner.i;
next = prev;
}
/**
* Check possible lock upgrade
*/
if(opbits & Operationrec::OP_ACC_LOCK_MODE)
{
jam();
/**
* Not lock owner...committing a exclusive operation...
*
* e.g
* T1(R) T1(X)
* T2(R/X)
*
* If T1(X) commits T2(R/X) is not supposed to run
* as T1(R) should also commit
*
* e.g
* T1(R) T1(X) T1*(R)
* T2(R/X)
*
* If T1*(R) commits T2(R/X) is not supposed to run
* as T1(R),T2(x) should also commit
*/
validate_lock_queue(prev);
return;
}
/**
* We committed a shared lock
* Check if we can start next...
*/
while(next.p->nextParallelQue != RNIL)
{
jam();
next.i = next.p->nextParallelQue;
ptrCheckGuard(next, coprecsize, operationrec);
if ((next.p->m_op_bits & Operationrec::OP_STATE_MASK) !=
Operationrec::OP_STATE_EXECUTED)
{
jam();
return;
}
}
startNext(signal, next);
validate_lock_queue(prev);
}
}//Dbacc::commitOperation()
void
Dbacc::release_lockowner(Signal* signal, OperationrecPtr opPtr, bool commit)
{
OperationrecPtr nextP;
OperationrecPtr nextS;
OperationrecPtr newOwner;
OperationrecPtr lastP;
Uint32 opbits = opPtr.p->m_op_bits;
nextP.i = opPtr.p->nextParallelQue;
nextS.i = opPtr.p->nextSerialQue;
lastP.i = opPtr.p->m_lo_last_parallel_op_ptr_i;
Uint32 lastS = opPtr.p->m_lo_last_serial_op_ptr_i;
ndbassert(lastP.i != RNIL || lastS != RNIL);
ndbassert(nextP.i != RNIL || nextS.i != RNIL);
enum {
NOTHING,
CHECK_LOCK_UPGRADE,
START_NEW
} action = NOTHING;
if (nextP.i != RNIL)
{
jam();
ptrCheckGuard(nextP, coprecsize, operationrec);
newOwner = nextP;
if (lastP.i == newOwner.i)
{
newOwner.p->m_lo_last_parallel_op_ptr_i = RNIL;
lastP = nextP;
}
else
{
ptrCheckGuard(lastP, coprecsize, operationrec);
newOwner.p->m_lo_last_parallel_op_ptr_i = lastP.i;
lastP.p->m_lock_owner_ptr_i = newOwner.i;
}
newOwner.p->m_lo_last_serial_op_ptr_i = lastS;
newOwner.p->nextSerialQue = nextS.i;
if (nextS.i != RNIL)
{
jam();
ptrCheckGuard(nextS, coprecsize, operationrec);
ndbassert(nextS.p->prevSerialQue == opPtr.i);
nextS.p->prevSerialQue = newOwner.i;
}
if (commit)
{
if ((opbits & Operationrec::OP_ACC_LOCK_MODE) == ZREADLOCK)
{
jam();
/**
* Lock owner...committing a shared operation...
* this can be a lock upgrade
*
* e.g
* T1(R) T2(R)
* T2(X)
*
* If T1(R) commits T2(X) is supposed to run
*
* e.g
* T1(X) T1(R)
* T2(R)
*
* If T1(X) commits, then T1(R) _should_ commit before T2(R) is
* allowed to proceed
*/
action = CHECK_LOCK_UPGRADE;
}
else
{
jam();
newOwner.p->m_op_bits |= Operationrec::OP_LOCK_MODE;
}
}
else
{
/**
* Aborting an operation can *always* lead to lock upgrade
*/
action = CHECK_LOCK_UPGRADE;
Uint32 opstate = opbits & Operationrec::OP_STATE_MASK;
if (opstate != Operationrec::OP_STATE_EXECUTED)
{
ndbassert(opstate == Operationrec::OP_STATE_RUNNING);
if (opbits & Operationrec::OP_ELEMENT_DISAPPEARED)
{
jam();
report_dealloc(signal, opPtr.p);
newOwner.p->localdata.setInvalid();
}
else
{
jam();
newOwner.p->localdata = opPtr.p->localdata;
}
action = START_NEW;
}
/**
* Update ACC_LOCK_MODE
*/
if (opbits & Operationrec::OP_LOCK_MODE)
{
Uint32 nextbits = nextP.p->m_op_bits;
while ((nextbits & Operationrec::OP_LOCK_MODE) == 0)
{
ndbassert(nextbits & Operationrec::OP_ACC_LOCK_MODE);
nextbits &= ~(Uint32)Operationrec::OP_ACC_LOCK_MODE;
nextP.p->m_op_bits = nextbits;
if (nextP.p->nextParallelQue != RNIL)
{
nextP.i = nextP.p->nextParallelQue;
ptrCheckGuard(nextP, coprecsize, operationrec);
nextbits = nextP.p->m_op_bits;
}
else
{
break;
}
}
}
}
}
else
{
jam();
ptrCheckGuard(nextS, coprecsize, operationrec);
newOwner = nextS;
newOwner.p->m_op_bits |= Operationrec::OP_RUN_QUEUE;
if (opbits & Operationrec::OP_ELEMENT_DISAPPEARED)
{
report_dealloc(signal, opPtr.p);
newOwner.p->localdata.setInvalid();
}
else
{
jam();
newOwner.p->localdata = opPtr.p->localdata;
}
lastP = newOwner;
while (lastP.p->nextParallelQue != RNIL)
{
lastP.i = lastP.p->nextParallelQue;
ptrCheckGuard(lastP, coprecsize, operationrec);
lastP.p->m_op_bits |= Operationrec::OP_RUN_QUEUE;
}
if (newOwner.i != lastP.i)
{
jam();
newOwner.p->m_lo_last_parallel_op_ptr_i = lastP.i;
}
else
{
jam();
newOwner.p->m_lo_last_parallel_op_ptr_i = RNIL;
}
if (newOwner.i != lastS)
{
jam();
newOwner.p->m_lo_last_serial_op_ptr_i = lastS;
}
else
{
jam();
newOwner.p->m_lo_last_serial_op_ptr_i = RNIL;
}
action = START_NEW;
}
insertLockOwnersList(newOwner);
/**
* Copy op info, and store op in element
*
*/
{
newOwner.p->elementPage = opPtr.p->elementPage;
newOwner.p->elementPointer = opPtr.p->elementPointer;
newOwner.p->elementContainer = opPtr.p->elementContainer;
newOwner.p->reducedHashValue = opPtr.p->reducedHashValue;
newOwner.p->m_op_bits |= (opbits & Operationrec::OP_ELEMENT_DISAPPEARED);
if (opbits & Operationrec::OP_ELEMENT_DISAPPEARED)
{
/* ------------------------------------------------------------------- */
// If the elementIsDisappeared is set then we know that the
// hashValue is also set since it always originates from a
// committing abort or a aborting insert.
// Scans do not initialise the hashValue and must have this
// value initialised if they are
// to successfully commit the delete.
/* ------------------------------------------------------------------- */
jam();
newOwner.p->hashValue = opPtr.p->hashValue;
}//if
Page8Ptr pagePtr;
pagePtr.i = newOwner.p->elementPage;
ptrCheckGuard(pagePtr, cpagesize, page8);
const Uint32 tmp = ElementHeader::setLocked(newOwner.i);
arrGuard(newOwner.p->elementPointer, 2048);
pagePtr.p->word32[newOwner.p->elementPointer] = tmp;
#if defined(VM_TRACE) || defined(ERROR_INSERT)
/**
* Invalidate page number in elements second word for test in initScanOp
*/
if (newOwner.p->localdata.isInvalid())
{
pagePtr.p->word32[newOwner.p->elementPointer + 1] =
newOwner.p->localdata.m_page_no;
}
else
{
ndbrequire(newOwner.p->localdata.m_page_no ==
pagePtr.p->word32[newOwner.p->elementPointer+1]);
}
#endif
}
switch(action){
case NOTHING:
validate_lock_queue(newOwner);
return;
case START_NEW:
startNew(signal, newOwner);
validate_lock_queue(newOwner);
return;
case CHECK_LOCK_UPGRADE:
startNext(signal, lastP);
validate_lock_queue(lastP);
break;
}
}
void
Dbacc::startNew(Signal* signal, OperationrecPtr newOwner)
{
OperationrecPtr save = operationRecPtr;
operationRecPtr = newOwner;
Uint32 opbits = newOwner.p->m_op_bits;
Uint32 op = opbits & Operationrec::OP_MASK;
ndbassert((opbits & Operationrec::OP_STATE_MASK) ==
Operationrec::OP_STATE_WAITING);
ndbassert(opbits & Operationrec::OP_LOCK_OWNER);
const bool deleted = opbits & Operationrec::OP_ELEMENT_DISAPPEARED;
Uint32 errCode = 0;
opbits &= opbits & ~(Uint32)Operationrec::OP_STATE_MASK;
opbits |= Operationrec::OP_STATE_RUNNING;
if (op == ZSCAN_OP && (opbits & Operationrec::OP_LOCK_REQ) == 0)
goto scan;
/* Waiting op now runnable... */
{
FragmentrecPtr frp;
frp.i = newOwner.p->fragptr;
ptrCheckGuard(frp, cfragmentsize, fragmentrec);
frp.p->m_lockStats.wait_ok((opbits & Operationrec::OP_LOCK_MODE)
!= ZREADLOCK,
operationRecPtr.p->m_lockTime,
getHighResTimer());
}
if (deleted)
{
jam();
if (op != ZINSERT && op != ZWRITE)
{
errCode = ZREAD_ERROR;
goto ref;
}
opbits &= ~(Uint32)Operationrec::OP_MASK;
opbits &= ~(Uint32)Operationrec::OP_ELEMENT_DISAPPEARED;
opbits |= (op = ZINSERT);
opbits |= Operationrec::OP_INSERT_IS_DONE;
goto conf;
}
else if (op == ZINSERT)
{
jam();
errCode = ZWRITE_ERROR;
goto ref;
}
else if (op == ZWRITE)
{
jam();
opbits &= ~(Uint32)Operationrec::OP_MASK;
opbits |= (op = ZUPDATE);
goto conf;
}
conf:
newOwner.p->m_op_bits = opbits;
sendAcckeyconf(signal);
sendSignal(newOwner.p->userblockref, GSN_ACCKEYCONF,
signal, 6, JBB);
operationRecPtr = save;
return;
scan:
jam();
newOwner.p->m_op_bits = opbits;
takeOutScanLockQueue(newOwner.p->scanRecPtr);
putReadyScanQueue(newOwner.p->scanRecPtr);
operationRecPtr = save;
return;
ref:
newOwner.p->m_op_bits = opbits;
signal->theData[0] = newOwner.p->userptr;
signal->theData[1] = errCode;
sendSignal(newOwner.p->userblockref, GSN_ACCKEYREF, signal,
2, JBB);
operationRecPtr = save;
return;
}
/**
* takeOutLockOwnersList
*
* Description: Take out an operation from the doubly linked
* lock owners list on the fragment.
*
*/
void Dbacc::takeOutLockOwnersList(const OperationrecPtr& outOperPtr) const
{
const Uint32 Tprev = outOperPtr.p->prevLockOwnerOp;
const Uint32 Tnext = outOperPtr.p->nextLockOwnerOp;
#ifdef VM_TRACE
// Check that operation is already in the list
OperationrecPtr tmpOperPtr;
bool inList = false;
tmpOperPtr.i = fragrecptr.p->lockOwnersList;
while (tmpOperPtr.i != RNIL){
ptrCheckGuard(tmpOperPtr, coprecsize, operationrec);
if (tmpOperPtr.i == outOperPtr.i)
inList = true;
tmpOperPtr.i = tmpOperPtr.p->nextLockOwnerOp;
}
ndbrequire(inList == true);
#endif
ndbassert(outOperPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER);
// Fast path through the code for the common case.
if ((Tprev == RNIL) && (Tnext == RNIL)) {
ndbrequire(fragrecptr.p->lockOwnersList == outOperPtr.i);
fragrecptr.p->lockOwnersList = RNIL;
return;
}
// Check previous operation
if (Tprev != RNIL) {
jam();
arrGuard(Tprev, coprecsize);
operationrec[Tprev].nextLockOwnerOp = Tnext;
} else {
fragrecptr.p->lockOwnersList = Tnext;
}//if
// Check next operation
if (Tnext == RNIL) {
return;
} else {
jam();
arrGuard(Tnext, coprecsize);
operationrec[Tnext].prevLockOwnerOp = Tprev;
}//if
return;
}//Dbacc::takeOutLockOwnersList()
/**
* insertLockOwnersList
*
* Description: Insert an operation first in the dubly linked lock owners
* list on the fragment.
*
*/
void Dbacc::insertLockOwnersList(const OperationrecPtr& insOperPtr) const
{
OperationrecPtr tmpOperPtr;
#ifdef VM_TRACE
// Check that operation is not already in list
tmpOperPtr.i = fragrecptr.p->lockOwnersList;
while(tmpOperPtr.i != RNIL){
ptrCheckGuard(tmpOperPtr, coprecsize, operationrec);
ndbrequire(tmpOperPtr.i != insOperPtr.i);
tmpOperPtr.i = tmpOperPtr.p->nextLockOwnerOp;
}
#endif
tmpOperPtr.i = fragrecptr.p->lockOwnersList;
ndbrequire(! (insOperPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER));
insOperPtr.p->m_op_bits |= Operationrec::OP_LOCK_OWNER;
insOperPtr.p->prevLockOwnerOp = RNIL;
insOperPtr.p->nextLockOwnerOp = tmpOperPtr.i;
fragrecptr.p->lockOwnersList = insOperPtr.i;
if (tmpOperPtr.i == RNIL) {
return;
} else {
jam();
ptrCheckGuard(tmpOperPtr, coprecsize, operationrec);
tmpOperPtr.p->prevLockOwnerOp = insOperPtr.i;
}//if
}//Dbacc::insertLockOwnersList()
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* END OF COMMIT AND ABORT MODULE */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* ALLOC_OVERFLOW_PAGE */
/* DESCRIPTION: */
/* --------------------------------------------------------------------------------- */
void Dbacc::allocOverflowPage()
{
tresult = 0;
Page8Ptr spPageptr;
seizePage(spPageptr);
if (tresult > ZLIMIT_OF_ERROR)
{
return;
}
{
LocalContainerPageList sparselist(*this, fragrecptr.p->sparsepages);
sparselist.addLast(spPageptr);
}
initOverpage(spPageptr);
}//Dbacc::allocOverflowPage()
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* EXPAND/SHRINK MODULE */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* ******************--------------------------------------------------------------- */
/*EXPANDCHECK EXPAND BUCKET ORD */
/* SENDER: ACC, LEVEL B */
/* INPUT: FRAGRECPTR, POINTS TO A FRAGMENT RECORD. */
/* DESCRIPTION: A BUCKET OF A FRAGMENT PAGE WILL BE EXPAND INTO TWO BUCKETS */
/* ACCORDING TO LH3. */
/* ******************--------------------------------------------------------------- */
/* ******************--------------------------------------------------------------- */
/* EXPANDCHECK EXPAND BUCKET ORD */
/* ******************------------------------------+ */
/* SENDER: ACC, LEVEL B */
/* A BUCKET OF THE FRAGMENT WILL */
/* BE EXPANDED ACORDING TO LH3, */
/* AND COMMIT TRANSACTION PROCESS */
/* WILL BE CONTINUED */
Uint32 Dbacc::checkScanExpand(Uint32 splitBucket)
{
Uint32 Ti;
Uint32 TreturnCode = 0;
Uint32 TPageIndex;
Uint32 TDirInd;
Uint32 TSplit;
Uint32 TreleaseScanBucket;
Page8Ptr TPageptr;
ScanRecPtr TscanPtr;
Uint16 releaseScanMask = 0;
TSplit = splitBucket;
for (Ti = 0; Ti < MAX_PARALLEL_SCANS_PER_FRAG; Ti++)
{
if (fragrecptr.p->scan[Ti] != RNIL)
{
//-------------------------------------------------------------
// A scan is ongoing on this particular local fragment. We have
// to check its current state.
//-------------------------------------------------------------
TscanPtr.i = fragrecptr.p->scan[Ti];
ptrCheckGuard(TscanPtr, cscanRecSize, scanRec);
if (TscanPtr.p->activeLocalFrag == fragrecptr.i) {
if (TscanPtr.p->scanBucketState == ScanRec::FIRST_LAP) {
if (TSplit == TscanPtr.p->nextBucketIndex) {
jam();
//-------------------------------------------------------------
// We are currently scanning this bucket. We cannot split it
// simultaneously with the scan. We have to pass this offer for
// splitting the bucket.
//-------------------------------------------------------------
TreturnCode = 1;
return TreturnCode;
}
else if (TSplit > TscanPtr.p->nextBucketIndex)
{
jam();
ndbassert(TSplit <= TscanPtr.p->startNoOfBuckets);
if (TSplit <= TscanPtr.p->startNoOfBuckets)
{
//-------------------------------------------------------------
// This bucket has not yet been scanned. We must reset the scanned
// bit indicator for this scan on this bucket.
//-------------------------------------------------------------
releaseScanMask |= TscanPtr.p->scanMask;
}
}
else
{
jam();
}//if
} else if (TscanPtr.p->scanBucketState == ScanRec::SECOND_LAP) {
jam();
//-------------------------------------------------------------
// We are performing a second lap to handle buckets that was
// merged during the first lap of scanning. During this second
// lap we do not allow any splits or merges.
//-------------------------------------------------------------
TreturnCode = 1;
return TreturnCode;
} else {
ndbrequire(TscanPtr.p->scanBucketState == ScanRec::SCAN_COMPLETED);
jam();
//-------------------------------------------------------------
// The scan is completed and we can thus go ahead and perform
// the split.
//-------------------------------------------------------------
}//if
}//if
}//if
}//for
TreleaseScanBucket = TSplit;
TPageIndex = fragrecptr.p->getPageIndex(TreleaseScanBucket);
TDirInd = fragrecptr.p->getPageNumber(TreleaseScanBucket);
TPageptr.i = getPagePtr(fragrecptr.p->directory, TDirInd);
ptrCheckGuard(TPageptr, cpagesize, page8);
releaseScanBucket(TPageptr, TPageIndex, releaseScanMask);
return TreturnCode;
}//Dbacc::checkScanExpand()
void Dbacc::execEXPANDCHECK2(Signal* signal)
{
jamEntry();
if(refToBlock(signal->getSendersBlockRef()) == DBLQH)
{
jam();
return;
}
fragrecptr.i = signal->theData[0];
tresult = 0; /* 0= FALSE,1= TRUE,> ZLIMIT_OF_ERROR =ERRORCODE */
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
fragrecptr.p->expandOrShrinkQueued = false;
#ifdef ERROR_INSERT
bool force_expand_shrink = false;
if (ERROR_INSERTED(3004) && fragrecptr.p->fragmentid == 0)
{
if (fragrecptr.p->level.getSize() > ERROR_INSERT_EXTRA)
{
return execSHRINKCHECK2(signal);
}
else if (fragrecptr.p->level.getSize() == ERROR_INSERT_EXTRA)
{
return;
}
force_expand_shrink = true;
}
if (!force_expand_shrink && fragrecptr.p->slack > 0)
#else
if (fragrecptr.p->slack > 0)
#endif
{
jam();
/* IT MEANS THAT IF SLACK > ZERO */
/*--------------------------------------------------------------*/
/* THE SLACK HAS IMPROVED AND IS NOW ACCEPTABLE AND WE */
/* CAN FORGET ABOUT THE EXPAND PROCESS. */
/*--------------------------------------------------------------*/
if (ERROR_INSERTED(3002))
debug_lh_vars("SLK");
if (fragrecptr.p->dirRangeFull == ZTRUE) {
jam();
fragrecptr.p->dirRangeFull = ZFALSE;
}
return;
}//if
if (fragrecptr.p->sparsepages.isEmpty())
{
jam();
allocOverflowPage();
if (tresult > ZLIMIT_OF_ERROR) {
jam();
/*--------------------------------------------------------------*/
/* WE COULD NOT ALLOCATE ANY OVERFLOW PAGE. THUS WE HAVE TO STOP*/
/* THE EXPAND SINCE WE CANNOT GUARANTEE ITS COMPLETION. */
/*--------------------------------------------------------------*/
return;
}//if
}//if
if (cfreepages.isEmpty())
{
jam();
/*--------------------------------------------------------------*/
/* WE HAVE TO STOP THE EXPAND PROCESS SINCE THERE ARE NO FREE */
/* PAGES. THIS MEANS THAT WE COULD BE FORCED TO CRASH SINCE WE */
/* CANNOT COMPLETE THE EXPAND. TO AVOID THE CRASH WE EXIT HERE. */
/*--------------------------------------------------------------*/
return;
}//if
if (fragrecptr.p->level.isFull())
{
jam();
/*
* The level structure does not allow more buckets.
* Do not expand.
*/
return;
}
Uint32 splitBucket;
Uint32 receiveBucket;
bool doSplit = fragrecptr.p->level.getSplitBucket(splitBucket, receiveBucket);
// Check that splitted bucket is not currently scanned
if (doSplit && checkScanExpand(splitBucket) == 1) {
jam();
/*--------------------------------------------------------------*/
// A scan state was inconsistent with performing an expand
// operation.
/*--------------------------------------------------------------*/
return;
}//if
/*--------------------------------------------------------------------------*/
/* WE START BY FINDING THE PAGE, THE PAGE INDEX AND THE PAGE DIRECTORY*/
/* OF THE NEW BUCKET WHICH SHALL RECEIVE THE ELEMENT WHICH HAVE A 1 IN*/
/* THE NEXT HASH BIT. THIS BIT IS USED IN THE SPLIT MECHANISM TO */
/* DECIDE WHICH ELEMENT GOES WHERE. */
/*--------------------------------------------------------------------------*/
texpDirInd = fragrecptr.p->getPageNumber(receiveBucket);
if (fragrecptr.p->getPageIndex(receiveBucket) == 0)
{ // Need new bucket
expPageptr.i = RNIL;
}
else
{
expPageptr.i = getPagePtr(fragrecptr.p->directory, texpDirInd);
#ifdef VM_TRACE
require(expPageptr.i != RNIL);
#endif
}
if (expPageptr.i == RNIL) {
jam();
seizePage(expPageptr);
if (tresult > ZLIMIT_OF_ERROR) {
jam();
return;
}//if
if (!setPagePtr(fragrecptr.p->directory, texpDirInd, expPageptr.i))
{
jam();
// TODO: should release seized page
tresult = ZDIR_RANGE_FULL_ERROR;
return;
}
tipPageId = texpDirInd;
initPage(expPageptr);
} else {
ptrCheckGuard(expPageptr, cpagesize, page8);
}//if
fragrecptr.p->expReceivePageptr = expPageptr.i;
fragrecptr.p->expReceiveIndex = fragrecptr.p->getPageIndex(receiveBucket);
/*--------------------------------------------------------------------------*/
/* THE NEXT ACTION IS TO FIND THE PAGE, THE PAGE INDEX AND THE PAGE */
/* DIRECTORY OF THE BUCKET TO BE SPLIT. */
/*--------------------------------------------------------------------------*/
Page8Ptr pageptr;
Uint32 conidx = fragrecptr.p->getPageIndex(splitBucket);
texpDirInd = fragrecptr.p->getPageNumber(splitBucket);
pageptr.i = getPagePtr(fragrecptr.p->directory, texpDirInd);
#ifdef VM_TRACE
require(pageptr.i != RNIL);
#endif
fragrecptr.p->expSenderIndex = conidx;
fragrecptr.p->expSenderPageptr = pageptr.i;
if (pageptr.i == RNIL) {
jam();
endofexpLab(signal); /* EMPTY BUCKET */
return;
}//if
fragrecptr.p->expReceiveIsforward = true;
ptrCheckGuard(pageptr, cpagesize, page8);
expandcontainer(pageptr, conidx);
endofexpLab(signal);
return;
}//Dbacc::execEXPANDCHECK2()
void Dbacc::endofexpLab(Signal* signal) const
{
fragrecptr.p->slack += fragrecptr.p->maxloadfactor;
fragrecptr.p->expandCounter++;
fragrecptr.p->level.expand();
Uint32 noOfBuckets = fragrecptr.p->level.getSize();
Uint32 Thysteres = fragrecptr.p->maxloadfactor - fragrecptr.p->minloadfactor;
fragrecptr.p->slackCheck = Int64(noOfBuckets) * Thysteres;
#ifdef ERROR_INSERT
bool force_expand_shrink = false;
if (ERROR_INSERTED(3004) &&
fragrecptr.p->fragmentid == 0 &&
fragrecptr.p->level.getSize() != ERROR_INSERT_EXTRA)
{
force_expand_shrink = true;
}
if ((force_expand_shrink || fragrecptr.p->slack < 0) &&
!fragrecptr.p->level.isFull())
#else
if (fragrecptr.p->slack < 0 && !fragrecptr.p->level.isFull())
#endif
{
jam();
/* IT MEANS THAT IF SLACK < ZERO */
/* --------------------------------------------------------------------------------- */
/* IT IS STILL NECESSARY TO EXPAND THE FRAGMENT EVEN MORE. START IT FROM HERE */
/* WITHOUT WAITING FOR NEXT COMMIT ON THE FRAGMENT. */
/* --------------------------------------------------------------------------------- */
signal->theData[0] = fragrecptr.i;
fragrecptr.p->expandOrShrinkQueued = true;
sendSignal(cownBlockref, GSN_EXPANDCHECK2, signal, 1, JBB);
}//if
return;
}//Dbacc::endofexpLab()
void Dbacc::execDEBUG_SIG(Signal* signal)
{
jamEntry();
expPageptr.i = signal->theData[0];
progError(__LINE__, NDBD_EXIT_SR_UNDOLOG);
return;
}//Dbacc::execDEBUG_SIG()
LHBits32 Dbacc::getElementHash(OperationrecPtr& oprec)
{
jam();
ndbassert(!oprec.isNull());
// Only calculate hash value if operation does not already have a complete hash value
if (oprec.p->hashValue.valid_bits() < fragrecptr.p->MAX_HASH_VALUE_BITS)
{
jam();
Local_key localkey;
localkey = oprec.p->localdata;
Uint32 len = readTablePk(localkey.m_page_no, localkey.m_page_idx, ElementHeader::setLocked(oprec.i), oprec);
if (len > 0)
oprec.p->hashValue = LHBits32(md5_hash((Uint64*)ckeys, len));
}
return oprec.p->hashValue;
}
LHBits32 Dbacc::getElementHash(Uint32 const* elemptr)
{
jam();
assert(ElementHeader::getUnlocked(*elemptr));
Uint32 elemhead = *elemptr;
Local_key localkey;
elemptr += 1;
ndbrequire(fragrecptr.p->localkeylen == 1);
localkey.m_page_no = *elemptr;
localkey.m_page_idx = ElementHeader::getPageIdx(elemhead);
OperationrecPtr oprec;
oprec.i = RNIL;
Uint32 len = readTablePk(localkey.m_page_no, localkey.m_page_idx, elemhead, oprec);
if (len > 0)
{
jam();
return LHBits32(md5_hash((Uint64*)ckeys, len));
}
else
{ // Return an invalid hash value if no data
jam();
return LHBits32();
}
}
LHBits32 Dbacc::getElementHash(Uint32 const* elemptr, OperationrecPtr& oprec)
{
jam();
if (!oprec.isNull())
{
jam();
return getElementHash(oprec);
}
Uint32 elemhead = *elemptr;
if (ElementHeader::getUnlocked(elemhead))
{
jam();
return getElementHash(elemptr);
}
else
{
jam();
oprec.i = ElementHeader::getOpPtrI(elemhead);
ptrCheckGuard(oprec, coprecsize, operationrec);
return getElementHash(oprec);
}
}
/* --------------------------------------------------------------------------------- */
/* EXPANDCONTAINER */
/* INPUT: EXC_PAGEPTR (POINTER TO THE ACTIVE PAGE RECORD) */
/* CEXC_PAGEINDEX (INDEX OF THE BUCKET). */
/* */
/* DESCRIPTION: THE HASH VALUE OF ALL ELEMENTS IN THE CONTAINER WILL BE */
/* CHECKED. SOME OF THIS ELEMENTS HAVE TO MOVE TO THE NEW CONTAINER */
/* --------------------------------------------------------------------------------- */
void Dbacc::expandcontainer(Page8Ptr pageptr, Uint32 conidx)
{
ContainerHeader containerhead;
LHBits32 texcHashvalue;
Uint32 tidrContainerptr;
Uint32 tidrElemhead;
Page8Ptr lastPageptr;
Page8Ptr lastPrevpageptr;
bool lastIsforward;
Uint32 tlastPageindex;
Uint32 tlastElementptr;
Uint32 tlastContainerptr;
Uint32 tlastPrevconptr;
Uint32 elemptr;
Uint32 prevPageptr = RNIL;
Uint32 prevConptr = 0;
bool isforward = true;
Uint32 elemStep;
const Uint32 elemLen = fragrecptr.p->elementLength;
OperationrecPtr oprecptr;
bool newBucket = true;
EXP_CONTAINER_LOOP:
Uint32 conptr = getContainerPtr(conidx, isforward);
if (isforward)
{
jam();
elemptr = conptr + Container::HEADER_SIZE;
elemStep = elemLen;
}
else
{
jam();
elemStep = -elemLen;
elemptr = conptr + elemStep;
}
arrGuard(conptr, 2048);
containerhead = pageptr.p->word32[conptr];
const Uint32 conlen = containerhead.getLength();
Uint32 cexcMovedLen = Container::HEADER_SIZE;
if (conlen <= Container::HEADER_SIZE) {
ndbrequire(conlen >= Container::HEADER_SIZE);
jam();
goto NEXT_ELEMENT;
}//if
NEXT_ELEMENT_LOOP:
oprecptr.i = RNIL;
ptrNull(oprecptr);
/* --------------------------------------------------------------------------------- */
/* CEXC_PAGEINDEX PAGE INDEX OF CURRENT CONTAINER BEING EXAMINED. */
/* CEXC_CONTAINERPTR INDEX OF CURRENT CONTAINER BEING EXAMINED. */
/* CEXC_ELEMENTPTR INDEX OF CURRENT ELEMENT BEING EXAMINED. */
/* EXC_PAGEPTR PAGE WHERE CURRENT ELEMENT RESIDES. */
/* CEXC_PREVPAGEPTR PAGE OF PREVIOUS CONTAINER. */
/* CEXC_PREVCONPTR INDEX OF PREVIOUS CONTAINER */
/* CEXC_FORWARD DIRECTION OF CURRENT CONTAINER */
/* --------------------------------------------------------------------------------- */
arrGuard(elemptr, 2048);
tidrElemhead = pageptr.p->word32[elemptr];
bool move;
if (ElementHeader::getLocked(tidrElemhead))
{
jam();
oprecptr.i = ElementHeader::getOpPtrI(tidrElemhead);
ptrCheckGuard(oprecptr, coprecsize, operationrec);
ndbassert(oprecptr.p->reducedHashValue.valid_bits() >= 1);
move = oprecptr.p->reducedHashValue.get_bit(1);
oprecptr.p->reducedHashValue.shift_out();
const LHBits16 reducedHashValue = oprecptr.p->reducedHashValue;
if (!fragrecptr.p->enough_valid_bits(reducedHashValue))
{
jam();
oprecptr.p->reducedHashValue =
fragrecptr.p->level.reduceForSplit(getElementHash(oprecptr));
}
}
else
{
jam();
LHBits16 reducedHashValue = ElementHeader::getReducedHashValue(tidrElemhead);
ndbassert(reducedHashValue.valid_bits() >= 1);
move = reducedHashValue.get_bit(1);
reducedHashValue.shift_out();
if (!fragrecptr.p->enough_valid_bits(reducedHashValue))
{
jam();
const Uint32* elemwordptr = &pageptr.p->word32[elemptr];
const LHBits32 hashValue = getElementHash(elemwordptr);
reducedHashValue =
fragrecptr.p->level.reduceForSplit(hashValue);
}
tidrElemhead = ElementHeader::setReducedHashValue(tidrElemhead, reducedHashValue);
}
if (!move)
{
jam();
if (ElementHeader::getUnlocked(tidrElemhead))
pageptr.p->word32[elemptr] = tidrElemhead;
/* --------------------------------------------------------------------------------- */
/* THIS ELEMENT IS NOT TO BE MOVED. WE CALCULATE THE WHEREABOUTS OF THE NEXT */
/* ELEMENT AND PROCEED WITH THAT OR END THE SEARCH IF THERE ARE NO MORE */
/* ELEMENTS IN THIS CONTAINER. */
/* --------------------------------------------------------------------------------- */
goto NEXT_ELEMENT;
}//if
/* --------------------------------------------------------------------------------- */
/* THE HASH BIT WAS SET AND WE SHALL MOVE THIS ELEMENT TO THE NEW BUCKET. */
/* WE START BY READING THE ELEMENT TO BE ABLE TO INSERT IT INTO THE NEW BUCKET.*/
/* THEN WE INSERT THE ELEMENT INTO THE NEW BUCKET. THE NEXT STEP IS TO DELETE */
/* THE ELEMENT FROM THIS BUCKET. THIS IS PERFORMED BY REPLACING IT WITH THE */
/* LAST ELEMENT IN THE BUCKET. IF THIS ELEMENT IS TO BE MOVED WE MOVE IT AND */
/* GET THE LAST ELEMENT AGAIN UNTIL WE EITHER FIND ONE THAT STAYS OR THIS */
/* ELEMENT IS THE LAST ELEMENT. */
/* --------------------------------------------------------------------------------- */
{
ndbrequire(fragrecptr.p->localkeylen == 1);
const Uint32 localkey = pageptr.p->word32[elemptr + 1];
#if defined(VM_TRACE) || !defined(NDEBUG)
pageptr.p->word32[elemptr] = ElementHeader::setInvalid();
#endif
Uint32 tidrPageindex = fragrecptr.p->expReceiveIndex;
Page8Ptr idrPageptr;
idrPageptr.i = fragrecptr.p->expReceivePageptr;
ptrCheckGuard(idrPageptr, cpagesize, page8);
bool tidrIsforward = fragrecptr.p->expReceiveIsforward;
insertElement(Element(tidrElemhead, localkey),
oprecptr,
idrPageptr,
tidrPageindex,
tidrIsforward,
tidrContainerptr,
containerhead.getScanBits(),
newBucket);
fragrecptr.p->expReceiveIndex = tidrPageindex;
fragrecptr.p->expReceivePageptr = idrPageptr.i;
fragrecptr.p->expReceiveIsforward = tidrIsforward;
newBucket = false;
}
REMOVE_LAST_LOOP:
jam();
lastPageptr.i = pageptr.i;
lastPageptr.p = pageptr.p;
tlastContainerptr = conptr;
lastPrevpageptr.i = prevPageptr;
ptrCheck(lastPrevpageptr, cpagesize, page8);
tlastPrevconptr = prevConptr;
arrGuard(tlastContainerptr, 2048);
lastIsforward = isforward;
tlastPageindex = conidx;
getLastAndRemove(lastPrevpageptr,
tlastPrevconptr,
lastPageptr,
tlastPageindex,
tlastContainerptr,
lastIsforward,
tlastElementptr);
if (pageptr.i == lastPageptr.i)
{
if (elemptr == tlastElementptr)
{
jam();
/* --------------------------------------------------------------------------------- */
/* THE CURRENT ELEMENT WAS ALSO THE LAST ELEMENT. */
/* --------------------------------------------------------------------------------- */
return;
}//if
}//if
/* --------------------------------------------------------------------------------- */
/* THE CURRENT ELEMENT WAS NOT THE LAST ELEMENT. IF THE LAST ELEMENT SHOULD */
/* STAY WE COPY IT TO THE POSITION OF THE CURRENT ELEMENT, OTHERWISE WE INSERT */
/* INTO THE NEW BUCKET, REMOVE IT AND TRY WITH THE NEW LAST ELEMENT. */
/* --------------------------------------------------------------------------------- */
oprecptr.i = RNIL;
ptrNull(oprecptr);
arrGuard(tlastElementptr, 2048);
tidrElemhead = lastPageptr.p->word32[tlastElementptr];
if (ElementHeader::getLocked(tidrElemhead))
{
jam();
oprecptr.i = ElementHeader::getOpPtrI(tidrElemhead);
ptrCheckGuard(oprecptr, coprecsize, operationrec);
ndbassert(oprecptr.p->reducedHashValue.valid_bits() >= 1);
move = oprecptr.p->reducedHashValue.get_bit(1);
oprecptr.p->reducedHashValue.shift_out();
if (!fragrecptr.p->enough_valid_bits(oprecptr.p->reducedHashValue))
{
jam();
oprecptr.p->reducedHashValue =
fragrecptr.p->level.reduceForSplit(getElementHash(oprecptr));
}
}
else
{
jam();
LHBits16 reducedHashValue = ElementHeader::getReducedHashValue(tidrElemhead);
ndbassert(reducedHashValue.valid_bits() > 0);
move = reducedHashValue.get_bit(1);
reducedHashValue.shift_out();
if (!fragrecptr.p->enough_valid_bits(reducedHashValue))
{
jam();
const Uint32* elemwordptr = &lastPageptr.p->word32[tlastElementptr];
const LHBits32 hashValue = getElementHash(elemwordptr);
reducedHashValue =
fragrecptr.p->level.reduceForSplit(hashValue);
}
tidrElemhead = ElementHeader::setReducedHashValue(tidrElemhead, reducedHashValue);
}
if (!move)
{
jam();
if (ElementHeader::getUnlocked(tidrElemhead))
lastPageptr.p->word32[tlastElementptr] = tidrElemhead;
/* --------------------------------------------------------------------------------- */
/* THE LAST ELEMENT IS NOT TO BE MOVED. WE COPY IT TO THE CURRENT ELEMENT. */
/* --------------------------------------------------------------------------------- */
const Page8Ptr delPageptr = pageptr;
const Uint32 delConptr = conptr;
const Uint32 delElemptr = elemptr;
deleteElement(delPageptr,
delConptr,
delElemptr,
lastPageptr,
tlastElementptr);
}
else
{
jam();
/* --------------------------------------------------------------------------------- */
/* THE LAST ELEMENT IS ALSO TO BE MOVED. */
/* --------------------------------------------------------------------------------- */
{
ndbrequire(fragrecptr.p->localkeylen == 1);
const Uint32 localkey = lastPageptr.p->word32[tlastElementptr + 1];
Uint32 tidrPageindex = fragrecptr.p->expReceiveIndex;
Page8Ptr idrPageptr;
idrPageptr.i = fragrecptr.p->expReceivePageptr;
ptrCheckGuard(idrPageptr, cpagesize, page8);
bool tidrIsforward = fragrecptr.p->expReceiveIsforward;
insertElement(Element(tidrElemhead, localkey),
oprecptr,
idrPageptr,
tidrPageindex,
tidrIsforward,
tidrContainerptr,
containerhead.getScanBits(),
newBucket);
fragrecptr.p->expReceiveIndex = tidrPageindex;
fragrecptr.p->expReceivePageptr = idrPageptr.i;
fragrecptr.p->expReceiveIsforward = tidrIsforward;
newBucket = false;
}
goto REMOVE_LAST_LOOP;
}//if
NEXT_ELEMENT:
arrGuard(conptr, 2048);
containerhead = pageptr.p->word32[conptr];
cexcMovedLen = cexcMovedLen + fragrecptr.p->elementLength;
if (containerhead.getLength() > cexcMovedLen) {
jam();
/* --------------------------------------------------------------------------------- */
/* WE HAVE NOT YET MOVED THE COMPLETE CONTAINER. WE PROCEED WITH THE NEXT */
/* ELEMENT IN THE CONTAINER. IT IS IMPORTANT TO READ THE CONTAINER LENGTH */
/* FROM THE CONTAINER HEADER SINCE IT MIGHT CHANGE BY REMOVING THE LAST */
/* ELEMENT IN THE BUCKET. */
/* --------------------------------------------------------------------------------- */
elemptr = elemptr + elemStep;
goto NEXT_ELEMENT_LOOP;
}//if
if (containerhead.getNextEnd() != 0) {
jam();
/* --------------------------------------------------------------------------------- */
/* WE PROCEED TO THE NEXT CONTAINER IN THE BUCKET. */
/* --------------------------------------------------------------------------------- */
prevPageptr = pageptr.i;
prevConptr = conptr;
nextcontainerinfo(pageptr,
conptr,
containerhead,
conidx,
isforward);
goto EXP_CONTAINER_LOOP;
}//if
}//Dbacc::expandcontainer()
/* ******************--------------------------------------------------------------- */
/* SHRINKCHECK JOIN BUCKET ORD */
/* SENDER: ACC, LEVEL B */
/* INPUT: FRAGRECPTR, POINTS TO A FRAGMENT RECORD. */
/* DESCRIPTION: TWO BUCKET OF A FRAGMENT PAGE WILL BE JOINED TOGETHER */
/* ACCORDING TO LH3. */
/* ******************--------------------------------------------------------------- */
/* ******************--------------------------------------------------------------- */
/* SHRINKCHECK JOIN BUCKET ORD */
/* ******************------------------------------+ */
/* SENDER: ACC, LEVEL B */
/* TWO BUCKETS OF THE FRAGMENT */
/* WILL BE JOINED ACORDING TO LH3 */
/* AND COMMIT TRANSACTION PROCESS */
/* WILL BE CONTINUED */
Uint32 Dbacc::checkScanShrink(Uint32 sourceBucket, Uint32 destBucket)
{
Uint32 Ti;
Uint32 TreturnCode = 0;
Uint32 TPageIndex;
Uint32 TDirInd;
Uint32 TmergeDest;
Uint32 TmergeSource;
Uint32 TreleaseScanBucket;
Uint32 TreleaseInd = 0;
enum Actions { ExtendRescan, ReduceUndefined };
Bitmask<1> actions[MAX_PARALLEL_SCANS_PER_FRAG];
Uint16 releaseDestScanMask = 0;
Uint16 releaseSourceScanMask = 0;
Page8Ptr TPageptr;
ScanRecPtr scanPtr;
TmergeDest = destBucket;
TmergeSource = sourceBucket;
for (Ti = 0; Ti < MAX_PARALLEL_SCANS_PER_FRAG; Ti++)
{
actions[Ti].clear();
if (fragrecptr.p->scan[Ti] != RNIL) {
scanPtr.i = fragrecptr.p->scan[Ti];
ptrCheckGuard(scanPtr, cscanRecSize, scanRec);
if (scanPtr.p->activeLocalFrag == fragrecptr.i) {
//-------------------------------------------------------------
// A scan is ongoing on this particular local fragment. We have
// to check its current state.
//-------------------------------------------------------------
if (scanPtr.p->scanBucketState == ScanRec::FIRST_LAP) {
jam();
if ((TmergeDest == scanPtr.p->nextBucketIndex) ||
(TmergeSource == scanPtr.p->nextBucketIndex)) {
jam();
//-------------------------------------------------------------
// We are currently scanning one of the buckets involved in the
// merge. We cannot merge while simultaneously performing a scan.
// We have to pass this offer for merging the buckets.
//-------------------------------------------------------------
TreturnCode = 1;
return TreturnCode;
}
else if (TmergeDest < scanPtr.p->nextBucketIndex)
{
jam();
/**
* Merge bucket into scanned bucket. Mark for rescan.
*/
actions[Ti].set(ExtendRescan);
if (TmergeSource == scanPtr.p->startNoOfBuckets)
{
/**
* Merge unscanned bucket with undefined scan bits into scanned
* bucket. Source buckets scan bits must be cleared.
*/
actions[Ti].set(ReduceUndefined);
releaseSourceScanMask |= scanPtr.p->scanMask;
}
TreleaseInd = 1;
}//if
else
{
/**
* Merge unscanned bucket with undefined scan bits into unscanned
* bucket with undefined scan bits.
*/
if (TmergeSource == scanPtr.p->startNoOfBuckets)
{
actions[Ti].set(ReduceUndefined);
releaseSourceScanMask |= scanPtr.p->scanMask;
TreleaseInd = 1;
}
if (TmergeDest <= scanPtr.p->startNoOfBuckets)
{
jam();
// Destination bucket is not scanned by scan
releaseDestScanMask |= scanPtr.p->scanMask;
}
}
}
else if (scanPtr.p->scanBucketState == ScanRec::SECOND_LAP)
{
jam();
//-------------------------------------------------------------
// We are performing a second lap to handle buckets that was
// merged during the first lap of scanning. During this second
// lap we do not allow any splits or merges.
//-------------------------------------------------------------
TreturnCode = 1;
return TreturnCode;
} else if (scanPtr.p->scanBucketState == ScanRec::SCAN_COMPLETED) {
jam();
//-------------------------------------------------------------
// The scan is completed and we can thus go ahead and perform
// the split.
//-------------------------------------------------------------
releaseDestScanMask |= scanPtr.p->scanMask;
releaseSourceScanMask |= scanPtr.p->scanMask;
} else {
jam();
sendSystemerror(__LINE__);
return TreturnCode;
}//if
}//if
}//if
}//for
TreleaseScanBucket = TmergeSource;
TPageIndex = fragrecptr.p->getPageIndex(TreleaseScanBucket);
TDirInd = fragrecptr.p->getPageNumber(TreleaseScanBucket);
TPageptr.i = getPagePtr(fragrecptr.p->directory, TDirInd);
ptrCheckGuard(TPageptr, cpagesize, page8);
releaseScanBucket(TPageptr, TPageIndex, releaseSourceScanMask);
TreleaseScanBucket = TmergeDest;
TPageIndex = fragrecptr.p->getPageIndex(TreleaseScanBucket);
TDirInd = fragrecptr.p->getPageNumber(TreleaseScanBucket);
TPageptr.i = getPagePtr(fragrecptr.p->directory, TDirInd);
ptrCheckGuard(TPageptr, cpagesize, page8);
releaseScanBucket(TPageptr, TPageIndex, releaseDestScanMask);
if (TreleaseInd == 1) {
jam();
for (Ti = 0; Ti < MAX_PARALLEL_SCANS_PER_FRAG; Ti++) {
if (!actions[Ti].isclear())
{
jam();
scanPtr.i = fragrecptr.p->scan[Ti];
ptrCheckGuard(scanPtr, cscanRecSize, scanRec);
if (actions[Ti].get(ReduceUndefined))
{
scanPtr.p->startNoOfBuckets --;
}
if (actions[Ti].get(ExtendRescan))
{
if (TmergeDest < scanPtr.p->minBucketIndexToRescan)
{
jam();
//-------------------------------------------------------------
// We have to keep track of the starting bucket to Rescan in the
// second lap.
//-------------------------------------------------------------
scanPtr.p->minBucketIndexToRescan = TmergeDest;
}//if
if (TmergeDest > scanPtr.p->maxBucketIndexToRescan)
{
jam();
//-------------------------------------------------------------
// We have to keep track of the ending bucket to Rescan in the
// second lap.
//-------------------------------------------------------------
scanPtr.p->maxBucketIndexToRescan = TmergeDest;
}//if
}
}//if
}//for
}//if
return TreturnCode;
}//Dbacc::checkScanShrink()
void Dbacc::execSHRINKCHECK2(Signal* signal)
{
jamEntry();
fragrecptr.i = signal->theData[0];
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
fragrecptr.p->expandOrShrinkQueued = false;
tresult = 0; /* 0= FALSE,1= TRUE,> ZLIMIT_OF_ERROR =ERRORCODE */
#ifdef ERROR_INSERT
bool force_expand_shrink = false;
if (ERROR_INSERTED(3004) && fragrecptr.p->fragmentid == 0)
{
if (fragrecptr.p->level.getSize() < ERROR_INSERT_EXTRA)
{
return execEXPANDCHECK2(signal);
}
else if (fragrecptr.p->level.getSize() == ERROR_INSERT_EXTRA)
{
return;
}
force_expand_shrink = true;
}
if (!force_expand_shrink &&
fragrecptr.p->slack <= fragrecptr.p->slackCheck)
#else
if (fragrecptr.p->slack <= fragrecptr.p->slackCheck)
#endif
{
jam();
/* TIME FOR JOIN BUCKETS PROCESS */
/*--------------------------------------------------------------*/
/* NO LONGER NECESSARY TO SHRINK THE FRAGMENT. */
/*--------------------------------------------------------------*/
return;
}//if
#ifdef ERROR_INSERT
if (!force_expand_shrink && fragrecptr.p->slack < 0)
#else
if (fragrecptr.p->slack < 0)
#endif
{
jam();
/*--------------------------------------------------------------*/
/* THE SLACK IS NEGATIVE, IN THIS CASE WE WILL NOT NEED ANY */
/* SHRINK. */
/*--------------------------------------------------------------*/
return;
}//if
if (fragrecptr.p->sparsepages.isEmpty())
{
jam();
allocOverflowPage();
if (tresult > ZLIMIT_OF_ERROR) {
jam();
return;
}//if
}//if
if (cfreepages.isEmpty())
{
jam();
/*--------------------------------------------------------------*/
/* WE HAVE TO STOP THE SHRINK PROCESS SINCE THERE ARE NO FREE */
/* PAGES. THIS MEANS THAT WE COULD BE FORCED TO CRASH SINCE WE */
/* CANNOT COMPLETE THE SHRINK. TO AVOID THE CRASH WE EXIT HERE. */
/*--------------------------------------------------------------*/
return;
}//if
if (fragrecptr.p->level.isEmpty())
{
jam();
/* no need to shrink empty hash table */
return;
}
// Since expandCounter guards more shrinks than expands and
// all fragments starts with a full page of buckets
ndbassert(fragrecptr.p->getPageNumber(fragrecptr.p->level.getTop()) > 0);
Uint32 mergeSourceBucket;
Uint32 mergeDestBucket;
bool doMerge = fragrecptr.p->level.getMergeBuckets(mergeSourceBucket, mergeDestBucket);
ndbassert(doMerge); // Merge always needed since we never shrink below one page of buckets
/* check that neither of source or destination bucket are currently scanned */
if (doMerge && checkScanShrink(mergeSourceBucket, mergeDestBucket) == 1) {
jam();
/*--------------------------------------------------------------*/
// A scan state was inconsistent with performing a shrink
// operation.
/*--------------------------------------------------------------*/
return;
}//if
if (ERROR_INSERTED(3002))
debug_lh_vars("SHR");
if (fragrecptr.p->dirRangeFull == ZTRUE) {
jam();
fragrecptr.p->dirRangeFull = ZFALSE;
}
shrink_adjust_reduced_hash_value(mergeDestBucket);
/*--------------------------------------------------------------------------*/
/* WE START BY FINDING THE NECESSARY INFORMATION OF THE BUCKET TO BE */
/* REMOVED WHICH WILL SEND ITS ELEMENTS TO THE RECEIVING BUCKET. */
/*--------------------------------------------------------------------------*/
Uint32 cexcPageindex = fragrecptr.p->getPageIndex(mergeSourceBucket);
texpDirInd = fragrecptr.p->getPageNumber(mergeSourceBucket);
Page8Ptr pageptr;
pageptr.i = getPagePtr(fragrecptr.p->directory, texpDirInd);
fragrecptr.p->expSenderIndex = cexcPageindex;
fragrecptr.p->expSenderPageptr = pageptr.i;
fragrecptr.p->expSenderDirIndex = texpDirInd;
/*--------------------------------------------------------------------------*/
/* WE NOW PROCEED BY FINDING THE NECESSARY INFORMATION ABOUT THE */
/* RECEIVING BUCKET. */
/*--------------------------------------------------------------------------*/
texpDirInd = fragrecptr.p->getPageNumber(mergeDestBucket);
fragrecptr.p->expReceivePageptr = getPagePtr(fragrecptr.p->directory, texpDirInd);
fragrecptr.p->expReceiveIndex = fragrecptr.p->getPageIndex(mergeDestBucket);
fragrecptr.p->expReceiveIsforward = true;
if (pageptr.i == RNIL)
{
jam();
endofshrinkbucketLab(signal); /* EMPTY BUCKET */
return;
}//if
/*--------------------------------------------------------------------------*/
/* INITIALISE THE VARIABLES FOR THE SHRINK PROCESS. */
/*--------------------------------------------------------------------------*/
ptrCheckGuard(pageptr, cpagesize, page8);
bool isforward = true;
Uint32 conptr = getForwardContainerPtr(cexcPageindex);
arrGuard(conptr, 2048);
ContainerHeader containerhead = pageptr.p->word32[conptr];
Uint32 conlen = containerhead.getLength();
if (conlen <= Container::HEADER_SIZE) {
ndbrequire(conlen == Container::HEADER_SIZE);
} else {
jam();
shrinkcontainer(pageptr, conptr, isforward, conlen);
}//if
/*--------------------------------------------------------------------------*/
/* THIS CONTAINER IS NOT YET EMPTY AND WE REMOVE ALL THE ELEMENTS. */
/*--------------------------------------------------------------------------*/
if (containerhead.isUsingBothEnds()) {
jam();
Uint32 relconptr = conptr + (ZBUF_SIZE - Container::HEADER_SIZE);
releaseRightlist(pageptr, cexcPageindex, relconptr);
}//if
ContainerHeader conthead;
conthead.initInUse();
dbgWord32(pageptr, conptr, conthead);
arrGuard(conptr, 2048);
pageptr.p->word32[conptr] = conthead;
if (containerhead.getNextEnd() == 0) {
jam();
endofshrinkbucketLab(signal);
return;
}//if
nextcontainerinfo(pageptr,
conptr,
containerhead,
cexcPageindex,
isforward);
do {
conptr = getContainerPtr(cexcPageindex, isforward);
arrGuard(conptr, 2048);
containerhead = pageptr.p->word32[conptr];
conlen = containerhead.getLength();
ndbrequire(conlen > Container::HEADER_SIZE);
/*--------------------------------------------------------------------------*/
/* THIS CONTAINER IS NOT YET EMPTY AND WE REMOVE ALL THE ELEMENTS. */
/*--------------------------------------------------------------------------*/
shrinkcontainer(pageptr, conptr, isforward, conlen);
const Uint32 prevPageptr = pageptr.i;
const Uint32 cexcPrevpageindex = cexcPageindex;
const Uint32 cexcPrevisforward = isforward;
if (containerhead.getNextEnd() != 0) {
jam();
/*--------------------------------------------------------------------------*/
/* WE MUST CALL THE NEXT CONTAINER INFO ROUTINE BEFORE WE RELEASE THE */
/* CONTAINER SINCE THE RELEASE WILL OVERWRITE THE NEXT POINTER. */
/*--------------------------------------------------------------------------*/
nextcontainerinfo(pageptr,
conptr,
containerhead,
cexcPageindex,
isforward);
}//if
Page8Ptr rlPageptr;
rlPageptr.i = prevPageptr;
ptrCheckGuard(rlPageptr, cpagesize, page8);
ndbassert(!containerhead.isScanInProgress());
if (cexcPrevisforward)
{
jam();
if (containerhead.isUsingBothEnds()) {
jam();
Uint32 relconptr = conptr + (ZBUF_SIZE - Container::HEADER_SIZE);
releaseRightlist(rlPageptr, cexcPrevpageindex, relconptr);
}//if
ndbrequire(ContainerHeader(rlPageptr.p->word32[conptr]).isInUse());
releaseLeftlist(rlPageptr, cexcPrevpageindex, conptr);
}
else
{
jam();
if (containerhead.isUsingBothEnds()) {
jam();
Uint32 relconptr = conptr - (ZBUF_SIZE - Container::HEADER_SIZE);
releaseLeftlist(rlPageptr, cexcPrevpageindex, relconptr);
}//if
ndbrequire(ContainerHeader(rlPageptr.p->word32[conptr]).isInUse());
releaseRightlist(rlPageptr, cexcPrevpageindex, conptr);
}//if
} while (containerhead.getNextEnd() != 0);
endofshrinkbucketLab(signal);
return;
}//Dbacc::execSHRINKCHECK2()
void Dbacc::endofshrinkbucketLab(Signal* signal)
{
fragrecptr.p->level.shrink();
fragrecptr.p->expandCounter--;
fragrecptr.p->slack -= fragrecptr.p->maxloadfactor;
if (fragrecptr.p->expSenderIndex == 0) {
jam();
if (fragrecptr.p->expSenderPageptr != RNIL) {
jam();
Page8Ptr rpPageptr;
rpPageptr.i = fragrecptr.p->expSenderPageptr;
ptrCheckGuard(rpPageptr, cpagesize, page8);
releasePage(rpPageptr);
unsetPagePtr(fragrecptr.p->directory, fragrecptr.p->expSenderDirIndex);
}//if
if ((fragrecptr.p->getPageNumber(fragrecptr.p->level.getSize()) & 0xff) == 0) {
jam();
DynArr256 dir(directoryPool, fragrecptr.p->directory);
DynArr256::ReleaseIterator iter;
Uint32 relcode;
#ifdef VM_TRACE
Uint32 count = 0;
#endif
dir.init(iter);
while ((relcode = dir.trim(fragrecptr.p->expSenderDirIndex, iter)) != 0)
{
#ifdef VM_TRACE
count++;
ndbrequire(count <= 256);
#endif
}
}//if
}//if
#ifdef ERROR_INSERT
bool force_expand_shrink = false;
if (ERROR_INSERTED(3004) &&
fragrecptr.p->fragmentid == 0 &&
fragrecptr.p->level.getSize() != ERROR_INSERT_EXTRA)
{
force_expand_shrink = true;
}
if (force_expand_shrink || fragrecptr.p->slack > 0)
#else
if (fragrecptr.p->slack > 0)
#endif
{
jam();
/*--------------------------------------------------------------*/
/* THE SLACK IS POSITIVE, IN THIS CASE WE WILL CHECK WHETHER */
/* WE WILL CONTINUE PERFORM ANOTHER SHRINK. */
/*--------------------------------------------------------------*/
Uint32 noOfBuckets = fragrecptr.p->level.getSize();
Uint32 Thysteresis = fragrecptr.p->maxloadfactor - fragrecptr.p->minloadfactor;
fragrecptr.p->slackCheck = Int64(noOfBuckets) * Thysteresis;
#ifdef ERROR_INSERT
if (force_expand_shrink || fragrecptr.p->slack > Thysteresis)
#else
if (fragrecptr.p->slack > Thysteresis)
#endif
{
/*--------------------------------------------------------------*/
/* IT IS STILL NECESSARY TO SHRINK THE FRAGMENT MORE. THIS*/
/* CAN HAPPEN WHEN A NUMBER OF SHRINKS GET REJECTED */
/* DURING A LOCAL CHECKPOINT. WE START A NEW SHRINK */
/* IMMEDIATELY FROM HERE WITHOUT WAITING FOR A COMMIT TO */
/* START IT. */
/*--------------------------------------------------------------*/
if (fragrecptr.p->expandCounter > 0) {
jam();
/*--------------------------------------------------------------*/
/* IT IS VERY IMPORTANT TO NOT TRY TO SHRINK MORE THAN */
/* WAS EXPANDED. IF MAXP IS SET TO A VALUE BELOW 63 THEN */
/* WE WILL LOSE RECORDS SINCE GETDIRINDEX CANNOT HANDLE */
/* SHRINKING BELOW 2^K - 1 (NOW 63). THIS WAS A BUG THAT */
/* WAS REMOVED 2000-05-12. */
/*--------------------------------------------------------------*/
signal->theData[0] = fragrecptr.i;
ndbrequire(!fragrecptr.p->expandOrShrinkQueued);
fragrecptr.p->expandOrShrinkQueued = true;
sendSignal(cownBlockref, GSN_SHRINKCHECK2, signal, 1, JBB);
}//if
}//if
}//if
ndbrequire(fragrecptr.p->getPageNumber(fragrecptr.p->level.getSize()) > 0);
return;
}//Dbacc::endofshrinkbucketLab()
/* --------------------------------------------------------------------------------- */
/* SHRINKCONTAINER */
/* INPUT: EXC_PAGEPTR (POINTER TO THE ACTIVE PAGE RECORD) */
/* CEXC_CONTAINERLEN (LENGTH OF THE CONTAINER). */
/* CEXC_CONTAINERPTR (ARRAY INDEX OF THE CONTAINER). */
/* CEXC_FORWARD (CONTAINER FORWARD (+1) OR BACKWARD (-1)) */
/* */
/* DESCRIPTION: SCAN ALL ELEMENTS IN DESTINATION BUCKET BEFORE MERGE */
/* AND ADJUST THE STORED REDUCED HASH VALUE (SHIFT IN ZERO). */
/* --------------------------------------------------------------------------------- */
void
Dbacc::shrink_adjust_reduced_hash_value(Uint32 bucket_number)
{
/*
* Note: function are a copy paste from getElement() with modified inner loop
* instead of finding a specific element, scan through all and modify.
*/
Uint32 tgeElementHeader;
Uint32 tgeElemStep;
Uint32 tgePageindex;
Uint32 tgeNextptrtype;
Uint32 tgeContainerptr;
Uint32 tgeElementptr;
register Uint32 tgeRemLen;
const Uint32 TelemLen = fragrecptr.p->elementLength;
const Uint32 localkeylen = fragrecptr.p->localkeylen;
tgePageindex = fragrecptr.p->getPageIndex(bucket_number);
Page8Ptr gePageptr;
gePageptr.i = getPagePtr(fragrecptr.p->directory, fragrecptr.p->getPageNumber(bucket_number));
ptrCheckGuard(gePageptr, cpagesize, page8);
ndbrequire(TelemLen == ZELEM_HEAD_SIZE + localkeylen);
tgeNextptrtype = ZLEFT;
/* Loop through all containers in a bucket */
do {
if (tgeNextptrtype == ZLEFT)
{
jam();
tgeContainerptr = getForwardContainerPtr(tgePageindex);
tgeElementptr = tgeContainerptr + Container::HEADER_SIZE;
tgeElemStep = TelemLen;
ndbrequire(tgeContainerptr < 2048);
tgeRemLen = ContainerHeader(gePageptr.p->word32[tgeContainerptr]).getLength();
ndbrequire((tgeContainerptr + tgeRemLen - 1) < 2048);
}
else if (tgeNextptrtype == ZRIGHT)
{
jam();
tgeContainerptr = getBackwardContainerPtr(tgePageindex);
tgeElementptr = tgeContainerptr - TelemLen;
tgeElemStep = 0 - TelemLen;
ndbrequire(tgeContainerptr < 2048);
tgeRemLen = ContainerHeader(gePageptr.p->word32[tgeContainerptr]).getLength();
ndbrequire((tgeContainerptr - tgeRemLen) < 2048);
}
else
{
jam();
jamLine(tgeNextptrtype);
ndbrequire(false);
}//if
if (tgeRemLen >= Container::HEADER_SIZE + TelemLen)
{
ndbrequire(tgeRemLen <= ZBUF_SIZE);
/* ------------------------------------------------------------------- */
/* Loop through all elements in a container */
do
{
tgeElementHeader = gePageptr.p->word32[tgeElementptr];
tgeRemLen = tgeRemLen - TelemLen;
/*
* Adjust the stored reduced hash value for element, shifting in a zero
*/
if (ElementHeader::getLocked(tgeElementHeader))
{
jam();
OperationrecPtr oprec;
oprec.i = ElementHeader::getOpPtrI(tgeElementHeader);
ptrCheckGuard(oprec, coprecsize, operationrec);
oprec.p->reducedHashValue.shift_in(false);
}
else
{
jam();
LHBits16 reducedHashValue = ElementHeader::getReducedHashValue(tgeElementHeader);
reducedHashValue.shift_in(false);
tgeElementHeader = ElementHeader::setReducedHashValue(tgeElementHeader, reducedHashValue);
gePageptr.p->word32[tgeElementptr] = tgeElementHeader;
}
if (tgeRemLen <= Container::HEADER_SIZE)
{
break;
}
tgeElementptr = tgeElementptr + tgeElemStep;
} while (true);
}//if
ndbrequire(tgeRemLen == Container::HEADER_SIZE);
ContainerHeader containerhead = gePageptr.p->word32[tgeContainerptr];
ndbassert((containerhead.getScanBits() & ~fragrecptr.p->activeScanMask) == 0);
tgeNextptrtype = containerhead.getNextEnd();
if (tgeNextptrtype == 0)
{
jam();
return; /* NO MORE CONTAINER */
}//if
tgePageindex = containerhead.getNextIndexNumber(); /* NEXT CONTAINER PAGE INDEX 7 BITS */
ndbrequire((tgePageindex <= Container::MAX_CONTAINER_INDEX) || (tgePageindex == Container::NO_CONTAINER_INDEX));
if (!containerhead.isNextOnSamePage())
{
jam();
gePageptr.i = gePageptr.p->word32[tgeContainerptr + 1]; /* NEXT PAGE I */
ptrCheckGuard(gePageptr, cpagesize, page8);
}//if
} while (1);
return;
}//Dbacc::shrink_adjust_reduced_hash_value()
void Dbacc::shrinkcontainer(Page8Ptr pageptr,
Uint32 conptr,
bool isforward,
Uint32 conlen)
{
Uint32 tshrElementptr;
Uint32 tshrRemLen;
Uint32 tidrContainerptr;
Uint32 tidrElemhead;
const Uint32 elemLen = fragrecptr.p->elementLength;
Uint32 elemStep;
OperationrecPtr oprecptr;
tshrRemLen = conlen - Container::HEADER_SIZE;
if (isforward)
{
jam();
tshrElementptr = conptr + Container::HEADER_SIZE;
elemStep = elemLen;
}
else
{
jam();
elemStep = -elemLen;
tshrElementptr = conptr + elemStep;
}//if
SHR_LOOP:
oprecptr.i = RNIL;
ptrNull(oprecptr);
/* --------------------------------------------------------------------------------- */
/* THE CODE BELOW IS ALL USED TO PREPARE FOR THE CALL TO INSERT_ELEMENT AND */
/* HANDLE THE RESULT FROM INSERT_ELEMENT. INSERT_ELEMENT INSERTS THE ELEMENT */
/* INTO ANOTHER BUCKET. */
/* --------------------------------------------------------------------------------- */
arrGuard(tshrElementptr, 2048);
tidrElemhead = pageptr.p->word32[tshrElementptr];
if (ElementHeader::getLocked(tidrElemhead)) {
jam();
/* --------------------------------------------------------------------------------- */
/* IF THE ELEMENT IS LOCKED WE MUST UPDATE THE ELEMENT INFO IN THE OPERATION */
/* RECORD OWNING THE LOCK. WE DO THIS BY READING THE OPERATION RECORD POINTER */
/* FROM THE ELEMENT HEADER. */
/* --------------------------------------------------------------------------------- */
oprecptr.i = ElementHeader::getOpPtrI(tidrElemhead);
ptrCheckGuard(oprecptr, coprecsize, operationrec);
oprecptr.p->reducedHashValue.shift_in(true);
}//if
else
{
LHBits16 reducedHashValue = ElementHeader::getReducedHashValue(tidrElemhead);
reducedHashValue.shift_in(true);
tidrElemhead = ElementHeader::setReducedHashValue(tidrElemhead, reducedHashValue);
}
{
ndbrequire(fragrecptr.p->localkeylen == 1);
const Uint32 localkey = pageptr.p->word32[tshrElementptr + 1];
Uint32 tidrPageindex = fragrecptr.p->expReceiveIndex;
Page8Ptr idrPageptr;
idrPageptr.i = fragrecptr.p->expReceivePageptr;
ptrCheckGuard(idrPageptr, cpagesize, page8);
bool tidrIsforward = fragrecptr.p->expReceiveIsforward;
insertElement(Element(tidrElemhead, localkey),
oprecptr,
idrPageptr,
tidrPageindex,
tidrIsforward,
tidrContainerptr,
ContainerHeader(pageptr.p->word32[conptr]).getScanBits(),
false);
/* --------------------------------------------------------------- */
/* TAKE CARE OF RESULT FROM INSERT_ELEMENT. */
/* --------------------------------------------------------------- */
fragrecptr.p->expReceiveIndex = tidrPageindex;
fragrecptr.p->expReceivePageptr = idrPageptr.i;
fragrecptr.p->expReceiveIsforward = tidrIsforward;
}
if (tshrRemLen < elemLen) {
jam();
sendSystemerror(__LINE__);
}//if
tshrRemLen = tshrRemLen - elemLen;
if (tshrRemLen != 0) {
jam();
tshrElementptr += elemStep;
goto SHR_LOOP;
}//if
}//Dbacc::shrinkcontainer()
void Dbacc::initFragAdd(Signal* signal,
FragmentrecPtr regFragPtr) const
{
const AccFragReq * const req = (AccFragReq*)&signal->theData[0];
Uint32 minLoadFactor = (req->minLoadFactor * ZBUF_SIZE) / 100;
Uint32 maxLoadFactor = (req->maxLoadFactor * ZBUF_SIZE) / 100;
if (ERROR_INSERTED(3003)) // use small LoadFactors to force sparse hash table
{
jam();
minLoadFactor = 1;
maxLoadFactor = 2;
}
if (minLoadFactor >= maxLoadFactor) {
jam();
minLoadFactor = maxLoadFactor - 1;
}//if
regFragPtr.p->fragState = ACTIVEFRAG;
// NOTE: next line must match calculation in Dblqh::execLQHFRAGREQ
regFragPtr.p->myfid = req->fragId;
regFragPtr.p->myTableId = req->tableId;
ndbrequire(req->kValue == 6);
ndbrequire(req->kValue == regFragPtr.p->k);
regFragPtr.p->expandCounter = 0;
/**
* Only allow shrink during SR
* - to make sure we don't run out of pages during REDO log execution
*
* Is later restored to 0 by LQH at end of REDO log execution
*/
regFragPtr.p->expandOrShrinkQueued = false;
regFragPtr.p->level.setSize(1 << req->kValue);
regFragPtr.p->minloadfactor = minLoadFactor;
regFragPtr.p->maxloadfactor = maxLoadFactor;
regFragPtr.p->slack = Int64(regFragPtr.p->level.getSize()) * maxLoadFactor;
regFragPtr.p->localkeylen = req->localKeyLen;
regFragPtr.p->nodetype = (req->reqInfo >> 4) & 0x3;
regFragPtr.p->keyLength = req->keyLength;
ndbrequire(req->keyLength != 0);
ndbrequire(regFragPtr.p->elementLength ==
ZELEM_HEAD_SIZE + regFragPtr.p->localkeylen);
Uint32 Tmp1 = regFragPtr.p->level.getSize();
Uint32 Tmp2 = regFragPtr.p->maxloadfactor - regFragPtr.p->minloadfactor;
regFragPtr.p->slackCheck = Int64(Tmp1) * Tmp2;
regFragPtr.p->mytabptr = req->tableId;
regFragPtr.p->roothashcheck = req->kValue + req->lhFragBits;
regFragPtr.p->noOfElements = 0;
regFragPtr.p->m_commit_count = 0; // stable results
for (Uint32 i = 0; i < MAX_PARALLEL_SCANS_PER_FRAG; i++) {
regFragPtr.p->scan[i] = RNIL;
}//for
Uint32 hasCharAttr = g_key_descriptor_pool.getPtr(req->tableId)->hasCharAttr;
regFragPtr.p->hasCharAttr = hasCharAttr;
}//Dbacc::initFragAdd()
void Dbacc::initFragGeneral(FragmentrecPtr regFragPtr)const
{
new (®FragPtr.p->directory) DynArr256::Head();
regFragPtr.p->lockOwnersList = RNIL;
regFragPtr.p->hasCharAttr = ZFALSE;
regFragPtr.p->dirRangeFull = ZFALSE;
regFragPtr.p->fragState = FREEFRAG;
regFragPtr.p->sparsepages.init();
regFragPtr.p->fullpages.init();
regFragPtr.p->m_noOfAllocatedPages = 0;
regFragPtr.p->activeScanMask = 0;
regFragPtr.p->m_lockStats.init();
}//Dbacc::initFragGeneral()
void Dbacc::execACC_SCANREQ(Signal* signal) //Direct Executed
{
jamEntry();
AccScanReq * req = (AccScanReq*)&signal->theData[0];
tuserptr = req->senderData;
tuserblockref = req->senderRef;
tabptr.i = req->tableId;
tfid = req->fragmentNo;
tscanFlag = req->requestInfo;
tscanTrid1 = req->transId1;
tscanTrid2 = req->transId2;
tresult = 0;
ptrCheckGuard(tabptr, ctablesize, tabrec);
ndbrequire(getfragmentrec(fragrecptr, tfid));
Uint32 i;
for (i = 0; i < MAX_PARALLEL_SCANS_PER_FRAG; i++) {
jam();
if (fragrecptr.p->scan[i] == RNIL) {
jam();
break;
}
}
ndbrequire(i != MAX_PARALLEL_SCANS_PER_FRAG);
ndbrequire(cfirstFreeScanRec != RNIL);
seizeScanRec();
fragrecptr.p->scan[i] = scanPtr.i;
scanPtr.p->scanBucketState = ScanRec::FIRST_LAP;
scanPtr.p->scanLockMode = AccScanReq::getLockMode(tscanFlag);
scanPtr.p->scanReadCommittedFlag = AccScanReq::getReadCommittedFlag(tscanFlag);
/* TWELVE BITS OF THE ELEMENT HEAD ARE SCAN */
/* CHECK BITS. THE MASK NOTES WHICH BIT IS */
/* ALLOCATED FOR THE ACTIVE SCAN */
scanPtr.p->scanMask = 1 << i;
scanPtr.p->scanUserptr = tuserptr;
scanPtr.p->scanUserblockref = tuserblockref;
scanPtr.p->scanTrid1 = tscanTrid1;
scanPtr.p->scanTrid2 = tscanTrid2;
scanPtr.p->scanLockHeld = 0;
scanPtr.p->scanOpsAllocated = 0;
scanPtr.p->scanFirstActiveOp = RNIL;
scanPtr.p->scanFirstQueuedOp = RNIL;
scanPtr.p->scanLastQueuedOp = RNIL;
scanPtr.p->scanFirstLockedOp = RNIL;
scanPtr.p->scanLastLockedOp = RNIL;
scanPtr.p->scanState = ScanRec::WAIT_NEXT;
initScanFragmentPart();
/* ************************ */
/* ACC_SCANCONF */
/* ************************ */
signal->theData[0] = scanPtr.p->scanUserptr;
signal->theData[1] = scanPtr.i;
signal->theData[2] = 1; /* NR OF LOCAL FRAGMENT */
signal->theData[3] = fragrecptr.p->fragmentid;
signal->theData[4] = RNIL;
signal->theData[7] = AccScanConf::ZNOT_EMPTY_FRAGMENT;
signal->theData[8] = 0; /* Success */
/**
* Return with signal->theData[8] == 0 indicates ACC_SCANCONF
* return signal.
*/
return;
}//Dbacc::execACC_SCANREQ()
/* ******************--------------------------------------------------------------- */
/* NEXT_SCANREQ REQUEST FOR NEXT ELEMENT OF */
/* ******************------------------------------+ A FRAGMENT. */
/* SENDER: LQH, LEVEL B */
void Dbacc::execNEXT_SCANREQ(Signal* signal)
{
Uint32 tscanNextFlag;
jamEntry();
scanPtr.i = signal->theData[0];
operationRecPtr.i = signal->theData[1];
tscanNextFlag = signal->theData[2];
/* ------------------------------------------ */
/* 1 = ZCOPY_NEXT GET NEXT ELEMENT */
/* 2 = ZCOPY_NEXT_COMMIT COMMIT THE */
/* ACTIVE ELEMENT AND GET THE NEXT ONE */
/* 3 = ZCOPY_COMMIT COMMIT THE ACTIVE ELEMENT */
/* 4 = ZCOPY_REPEAT GET THE ACTIVE ELEMENT */
/* 5 = ZCOPY_ABORT RELOCK THE ACTIVE ELEMENT */
/* 6 = ZCOPY_CLOSE THE SCAN PROCESS IS READY */
/* ------------------------------------------ */
tresult = 0;
ptrCheckGuard(scanPtr, cscanRecSize, scanRec);
ndbrequire(scanPtr.p->scanState == ScanRec::WAIT_NEXT);
switch (tscanNextFlag) {
case NextScanReq::ZSCAN_NEXT:
jam();
/*empty*/;
break;
case NextScanReq::ZSCAN_NEXT_COMMIT:
case NextScanReq::ZSCAN_COMMIT:
jam();
/* --------------------------------------------------------------------- */
/* COMMIT ACTIVE OPERATION.
* SEND NEXT SCAN ELEMENT IF IT IS ZCOPY_NEXT_COMMIT.
* --------------------------------------------------------------------- */
ptrCheckGuard(operationRecPtr, coprecsize, operationrec);
fragrecptr.i = operationRecPtr.p->fragptr;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
if (!scanPtr.p->scanReadCommittedFlag) {
commitOperation(signal);
}//if
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
takeOutActiveScanOp();
releaseOpRec();
scanPtr.p->scanOpsAllocated--;
if (tscanNextFlag == NextScanReq::ZSCAN_COMMIT) {
jam();
signal->theData[0] = 0; /* Success */
/**
* signal->theData[0] = 0 indicates NEXT_SCANCONF return
* signal for NextScanReq::ZSCAN_COMMIT
*/
return;
}//if
break;
case NextScanReq::ZSCAN_CLOSE:
jam();
fragrecptr.i = scanPtr.p->activeLocalFrag;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
ndbassert(fragrecptr.p->activeScanMask & scanPtr.p->scanMask);
/* ---------------------------------------------------------------------
* THE SCAN PROCESS IS FINISHED. RELOCK ALL LOCKED EL.
* RELESE ALL INVOLVED REC.
* ------------------------------------------------------------------- */
releaseScanLab(signal);
return;
break;
default:
ndbrequire(false);
break;
}//switch
signal->theData[0] = scanPtr.i;
signal->theData[1] = AccCheckScan::ZNOT_CHECK_LCP_STOP;
execACC_CHECK_SCAN(signal);
return;
}//Dbacc::execNEXT_SCANREQ()
void Dbacc::checkNextBucketLab(Signal* signal)
{
Page8Ptr nsPageptr;
Page8Ptr gnsPageidptr;
Page8Ptr tnsPageidptr;
Uint32 tnsElementptr;
Uint32 tnsContainerptr;
Uint32 tnsIsLocked;
Uint32 tnsCopyDir;
tnsCopyDir = fragrecptr.p->getPageNumber(scanPtr.p->nextBucketIndex);
tnsPageidptr.i = getPagePtr(fragrecptr.p->directory, tnsCopyDir);
ptrCheckGuard(tnsPageidptr, cpagesize, page8);
gnsPageidptr.i = tnsPageidptr.i;
gnsPageidptr.p = tnsPageidptr.p;
Uint32 conidx = fragrecptr.p->getPageIndex(scanPtr.p->nextBucketIndex);
Page8Ptr pageptr;
pageptr.i = gnsPageidptr.i;
pageptr.p = gnsPageidptr.p;
Uint32 conptr;
bool isforward;
Uint32 elemptr;
Uint32 islocked;
if (!getScanElement(pageptr, conidx, conptr, isforward, elemptr, islocked))
{
scanPtr.p->nextBucketIndex++;
if (scanPtr.p->scanBucketState == ScanRec::SECOND_LAP) {
if (scanPtr.p->nextBucketIndex > scanPtr.p->maxBucketIndexToRescan) {
/* ---------------------------------------------------------------- */
// We have finished the rescan phase.
// We are ready to proceed with the next fragment part.
/* ---------------------------------------------------------------- */
jam();
checkNextFragmentLab(signal);
return;
}//if
} else if (scanPtr.p->scanBucketState == ScanRec::FIRST_LAP) {
if (fragrecptr.p->level.getTop() < scanPtr.p->nextBucketIndex) {
/* ---------------------------------------------------------------- */
// All buckets have been scanned a first time.
/* ---------------------------------------------------------------- */
if (scanPtr.p->minBucketIndexToRescan == 0xFFFFFFFF) {
jam();
/* -------------------------------------------------------------- */
// We have not had any merges behind the scan.
// Thus it is not necessary to perform any rescan any buckets
// and we can proceed immediately with the next fragment part.
/* --------------------------------------------------------------- */
checkNextFragmentLab(signal);
return;
} else {
jam();
/* --------------------------------------------------------------------------------- */
// Some buckets are in the need of rescanning due to merges that have moved records
// from in front of the scan to behind the scan. During the merges we kept track of
// which buckets that need a rescan. We start with the minimum and end with maximum.
/* --------------------------------------------------------------------------------- */
scanPtr.p->nextBucketIndex = scanPtr.p->minBucketIndexToRescan;
scanPtr.p->scanBucketState = ScanRec::SECOND_LAP;
if (scanPtr.p->maxBucketIndexToRescan > fragrecptr.p->level.getTop()) {
jam();
/* --------------------------------------------------------------------------------- */
// If we have had so many merges that the maximum is bigger than the number of buckets
// then we will simply satisfy ourselves with scanning to the end. This can only happen
// after bringing down the total of buckets to less than half and the minimum should
// be 0 otherwise there is some problem.
/* --------------------------------------------------------------------------------- */
if (scanPtr.p->minBucketIndexToRescan != 0) {
jam();
sendSystemerror(__LINE__);
return;
}//if
scanPtr.p->maxBucketIndexToRescan = fragrecptr.p->level.getTop();
}//if
}//if
}//if
}//if
if ((scanPtr.p->scanBucketState == ScanRec::FIRST_LAP) &&
(scanPtr.p->nextBucketIndex <= scanPtr.p->startNoOfBuckets)) {
/* --------------------------------------------------------------------------------- */
// We will only reset the scan indicator on the buckets that existed at the start of the
// scan. The others will be handled by the split and merge code.
/* --------------------------------------------------------------------------------- */
Uint32 conidx = fragrecptr.p->getPageIndex(scanPtr.p->nextBucketIndex);
if (conidx == 0) {
jam();
Uint32 pagei = fragrecptr.p->getPageNumber(scanPtr.p->nextBucketIndex);
gnsPageidptr.i = getPagePtr(fragrecptr.p->directory, pagei);
ptrCheckGuard(gnsPageidptr, cpagesize, page8);
}//if
ndbassert(!scanPtr.p->isInContainer());
releaseScanBucket(gnsPageidptr, conidx, scanPtr.p->scanMask);
}//if
signal->theData[0] = scanPtr.i;
signal->theData[1] = AccCheckScan::ZCHECK_LCP_STOP;
sendSignal(cownBlockref, GSN_ACC_CHECK_SCAN, signal, 2, JBB);
return;
}//if
/* ----------------------------------------------------------------------- */
/* AN ELEMENT WHICH HAVE NOT BEEN SCANNED WAS FOUND. WE WILL PREPARE IT */
/* TO BE SENT TO THE LQH BLOCK FOR FURTHER PROCESSING. */
/* WE ASSUME THERE ARE OPERATION RECORDS AVAILABLE SINCE LQH SHOULD HAVE*/
/* GUARANTEED THAT THROUGH EARLY BOOKING. */
/* ----------------------------------------------------------------------- */
tnsIsLocked = islocked;
tnsElementptr = elemptr;
tnsContainerptr = conptr;
nsPageptr.i = pageptr.i;
nsPageptr.p = pageptr.p;
seizeOpRec();
initScanOpRec(nsPageptr, tnsContainerptr, tnsElementptr);
if (!tnsIsLocked){
if (!scanPtr.p->scanReadCommittedFlag) {
jam();
/* Immediate lock grant as element unlocked */
fragrecptr.p->m_lockStats.
req_start_imm_ok(scanPtr.p->scanLockMode != ZREADLOCK,
operationRecPtr.p->m_lockTime,
getHighResTimer());
setlock(nsPageptr, tnsElementptr);
insertLockOwnersList(operationRecPtr);
operationRecPtr.p->m_op_bits |=
Operationrec::OP_STATE_RUNNING | Operationrec::OP_RUN_QUEUE;
}//if
} else {
arrGuard(tnsElementptr, 2048);
queOperPtr.i =
ElementHeader::getOpPtrI(nsPageptr.p->word32[tnsElementptr]);
ptrCheckGuard(queOperPtr, coprecsize, operationrec);
if (queOperPtr.p->m_op_bits & Operationrec::OP_ELEMENT_DISAPPEARED ||
queOperPtr.p->localdata.isInvalid())
{
jam();
/* ------------------------------------------------------------------ */
// If the lock owner indicates the element is disappeared then
// we will not report this tuple. We will continue with the next tuple.
/* ------------------------------------------------------------------ */
/* FC : Is this correct, shouldn't we wait for lock holder commit? */
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
releaseOpRec();
scanPtr.p->scanOpsAllocated--;
signal->theData[0] = scanPtr.i;
signal->theData[1] = AccCheckScan::ZCHECK_LCP_STOP;
sendSignal(cownBlockref, GSN_ACC_CHECK_SCAN, signal, 2, JBB);
return;
}//if
if (!scanPtr.p->scanReadCommittedFlag) {
Uint32 return_result;
if (scanPtr.p->scanLockMode == ZREADLOCK) {
jam();
return_result = placeReadInLockQueue(queOperPtr);
} else {
jam();
return_result = placeWriteInLockQueue(queOperPtr);
}//if
if (return_result == ZSERIAL_QUEUE) {
/* -----------------------------------------------------------------
* WE PLACED THE OPERATION INTO A SERIAL QUEUE AND THUS WE HAVE TO
* WAIT FOR THE LOCK TO BE RELEASED. WE CONTINUE WITH THE NEXT ELEMENT
* ----------------------------------------------------------------- */
fragrecptr.p->
m_lockStats.req_start(scanPtr.p->scanLockMode != ZREADLOCK,
operationRecPtr.p->m_lockTime,
getHighResTimer());
putOpScanLockQue(); /* PUT THE OP IN A QUE IN THE SCAN REC */
signal->theData[0] = scanPtr.i;
signal->theData[1] = AccCheckScan::ZCHECK_LCP_STOP;
sendSignal(cownBlockref, GSN_ACC_CHECK_SCAN, signal, 2, JBB);
return;
} else if (return_result != ZPARALLEL_QUEUE) {
jam();
/* ----------------------------------------------------------------- */
// The tuple is either not committed yet or a delete in
// the same transaction (not possible here since we are a scan).
// Thus we simply continue with the next tuple.
/* ----------------------------------------------------------------- */
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
releaseOpRec();
scanPtr.p->scanOpsAllocated--;
signal->theData[0] = scanPtr.i;
signal->theData[1] = AccCheckScan::ZCHECK_LCP_STOP;
sendSignal(cownBlockref, GSN_ACC_CHECK_SCAN, signal, 2, JBB);
return;
}//if
ndbassert(return_result == ZPARALLEL_QUEUE);
/* We got into the parallel queue - immediate grant */
fragrecptr.p->m_lockStats.
req_start_imm_ok(scanPtr.p->scanLockMode != ZREADLOCK,
operationRecPtr.p->m_lockTime,
getHighResTimer());
}//if
}//if
/* ----------------------------------------------------------------------- */
// Committed read proceed without caring for locks immediately
// down here except when the tuple was deleted permanently
// and no new operation has inserted it again.
/* ----------------------------------------------------------------------- */
putActiveScanOp();
sendNextScanConf(signal);
return;
}//Dbacc::checkNextBucketLab()
void Dbacc::checkNextFragmentLab(Signal* signal)
{
scanPtr.p->scanBucketState = ScanRec::SCAN_COMPLETED;
// The scan is completed. ACC_CHECK_SCAN will perform all the necessary
// checks to see
// what the next step is.
signal->theData[0] = scanPtr.i;
signal->theData[1] = AccCheckScan::ZCHECK_LCP_STOP;
execACC_CHECK_SCAN(signal);
return;
}//Dbacc::checkNextFragmentLab()
void Dbacc::initScanFragmentPart()
{
Page8Ptr cnfPageidptr;
/* ----------------------------------------------------------------------- */
// Set the active fragment part.
// Set the current bucket scanned to the first.
// Start with the first lap.
// Remember the number of buckets at start of the scan.
// Set the minimum and maximum to values that will always be smaller and
// larger than.
// Reset the scan indicator on the first bucket.
/* ----------------------------------------------------------------------- */
ndbassert(scanPtr.p->activeLocalFrag == RNIL);
scanPtr.p->activeLocalFrag = fragrecptr.i;
scanPtr.p->nextBucketIndex = 0; /* INDEX OF SCAN BUCKET */
ndbassert(!scanPtr.p->isInContainer());
scanPtr.p->scanBucketState = ScanRec::FIRST_LAP;
scanPtr.p->startNoOfBuckets = fragrecptr.p->level.getTop();
scanPtr.p->minBucketIndexToRescan = 0xFFFFFFFF;
scanPtr.p->maxBucketIndexToRescan = 0;
cnfPageidptr.i = getPagePtr(fragrecptr.p->directory, 0);
ptrCheckGuard(cnfPageidptr, cpagesize, page8);
const Uint32 conidx = fragrecptr.p->getPageIndex(scanPtr.p->nextBucketIndex);
ndbassert(!(fragrecptr.p->activeScanMask & scanPtr.p->scanMask));
ndbassert(!scanPtr.p->isInContainer());
releaseScanBucket(cnfPageidptr, conidx, scanPtr.p->scanMask);
fragrecptr.p->activeScanMask |= scanPtr.p->scanMask;
}//Dbacc::initScanFragmentPart()
/* -------------------------------------------------------------------------
* FLAG = 6 = ZCOPY_CLOSE THE SCAN PROCESS IS READY OR ABORTED.
* ALL OPERATION IN THE ACTIVE OR WAIT QUEUE ARE RELEASED,
* SCAN FLAG OF ROOT FRAG IS RESET AND THE SCAN RECORD IS RELEASED.
* ------------------------------------------------------------------------ */
void Dbacc::releaseScanLab(Signal* signal)
{
releaseAndCommitActiveOps(signal);
releaseAndCommitQueuedOps(signal);
releaseAndAbortLockedOps(signal);
fragrecptr.i = scanPtr.p->activeLocalFrag;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
ndbassert(fragrecptr.p->activeScanMask & scanPtr.p->scanMask);
/**
* Dont leave partial scanned bucket as partial scanned.
* Elements scanbits must match containers scanbits.
*/
if ((scanPtr.p->scanBucketState == ScanRec::FIRST_LAP &&
scanPtr.p->nextBucketIndex <= fragrecptr.p->level.getTop()) ||
(scanPtr.p->scanBucketState == ScanRec::SECOND_LAP &&
scanPtr.p->nextBucketIndex <= scanPtr.p->maxBucketIndexToRescan))
{
jam();
Uint32 conidx = fragrecptr.p->getPageIndex(scanPtr.p->nextBucketIndex);
Uint32 pagei = fragrecptr.p->getPageNumber(scanPtr.p->nextBucketIndex);
Page8Ptr pageptr;
pageptr.i = getPagePtr(fragrecptr.p->directory, pagei);
ptrCheckGuard(pageptr, cpagesize, page8);
Uint32 inPageI;
Uint32 inConptr;
if(scanPtr.p->getContainer(inPageI, inConptr))
{
Page8Ptr page;
page.i = inPageI;
ptrCheckGuard(page, cpagesize, page8);
ContainerHeader conhead(page.p->word32[inConptr]);
scanPtr.p->leaveContainer(inPageI, inConptr);
page.p->clearScanContainer(scanPtr.p->scanMask, inConptr);
if (!page.p->checkScanContainer(inConptr))
{
conhead.clearScanInProgress();
page.p->word32[inConptr] = Uint32(conhead);
}
}
releaseScanBucket(pageptr, conidx, scanPtr.p->scanMask);
}
for (tmp = 0; tmp < MAX_PARALLEL_SCANS_PER_FRAG; tmp++) {
jam();
if (fragrecptr.p->scan[tmp] == scanPtr.i) {
jam();
fragrecptr.p->scan[tmp] = RNIL;
}//if
}//for
// Stops the heartbeat
Uint32 blockNo = refToMain(scanPtr.p->scanUserblockref);
signal->theData[0] = scanPtr.p->scanUserptr;
signal->theData[1] = RNIL;
signal->theData[2] = RNIL;
fragrecptr.p->activeScanMask &= ~scanPtr.p->scanMask;
scanPtr.p->activeLocalFrag = RNIL;
releaseScanRec();
EXECUTE_DIRECT(blockNo,
GSN_NEXT_SCANCONF,
signal,
3);
return;
}//Dbacc::releaseScanLab()
void Dbacc::releaseAndCommitActiveOps(Signal* signal)
{
OperationrecPtr trsoOperPtr;
operationRecPtr.i = scanPtr.p->scanFirstActiveOp;
while (operationRecPtr.i != RNIL) {
jam();
ptrCheckGuard(operationRecPtr, coprecsize, operationrec);
trsoOperPtr.i = operationRecPtr.p->nextOp;
fragrecptr.i = operationRecPtr.p->fragptr;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
if (!scanPtr.p->scanReadCommittedFlag) {
jam();
if ((operationRecPtr.p->m_op_bits & Operationrec::OP_STATE_MASK) ==
Operationrec::OP_STATE_EXECUTED)
{
commitOperation(signal);
}
else
{
abortOperation(signal);
}
}//if
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
takeOutActiveScanOp();
releaseOpRec();
scanPtr.p->scanOpsAllocated--;
operationRecPtr.i = trsoOperPtr.i;
}//if
}//Dbacc::releaseAndCommitActiveOps()
void Dbacc::releaseAndCommitQueuedOps(Signal* signal)
{
OperationrecPtr trsoOperPtr;
operationRecPtr.i = scanPtr.p->scanFirstQueuedOp;
while (operationRecPtr.i != RNIL) {
jam();
ptrCheckGuard(operationRecPtr, coprecsize, operationrec);
trsoOperPtr.i = operationRecPtr.p->nextOp;
fragrecptr.i = operationRecPtr.p->fragptr;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
if (!scanPtr.p->scanReadCommittedFlag) {
jam();
if ((operationRecPtr.p->m_op_bits & Operationrec::OP_STATE_MASK) ==
Operationrec::OP_STATE_EXECUTED)
{
commitOperation(signal);
}
else
{
abortOperation(signal);
}
}//if
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
takeOutReadyScanQueue();
releaseOpRec();
scanPtr.p->scanOpsAllocated--;
operationRecPtr.i = trsoOperPtr.i;
}//if
}//Dbacc::releaseAndCommitQueuedOps()
void Dbacc::releaseAndAbortLockedOps(Signal* signal) {
OperationrecPtr trsoOperPtr;
operationRecPtr.i = scanPtr.p->scanFirstLockedOp;
while (operationRecPtr.i != RNIL) {
jam();
ptrCheckGuard(operationRecPtr, coprecsize, operationrec);
trsoOperPtr.i = operationRecPtr.p->nextOp;
fragrecptr.i = operationRecPtr.p->fragptr;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
if (!scanPtr.p->scanReadCommittedFlag) {
jam();
abortOperation(signal);
}//if
takeOutScanLockQueue(scanPtr.i);
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
releaseOpRec();
scanPtr.p->scanOpsAllocated--;
operationRecPtr.i = trsoOperPtr.i;
}//if
}//Dbacc::releaseAndAbortLockedOps()
/* 3.18.3 ACC_CHECK_SCAN */
/* ******************--------------------------------------------------------------- */
/* ACC_CHECK_SCAN */
/* ENTER ACC_CHECK_SCAN WITH */
/* SCAN_PTR */
/* ******************--------------------------------------------------------------- */
/* ******************--------------------------------------------------------------- */
/* ACC_CHECK_SCAN */
/* ******************------------------------------+ */
void Dbacc::execACC_CHECK_SCAN(Signal* signal)
{
Uint32 TcheckLcpStop;
jamEntry();
scanPtr.i = signal->theData[0];
TcheckLcpStop = signal->theData[1];
ptrCheckGuard(scanPtr, cscanRecSize, scanRec);
while (scanPtr.p->scanFirstQueuedOp != RNIL) {
jam();
//---------------------------------------------------------------------
// An operation has been released from the lock queue.
// We are in the parallel queue of this tuple. We are
// ready to report the tuple now.
//------------------------------------------------------------------------
operationRecPtr.i = scanPtr.p->scanFirstQueuedOp;
ptrCheckGuard(operationRecPtr, coprecsize, operationrec);
takeOutReadyScanQueue();
fragrecptr.i = operationRecPtr.p->fragptr;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
/* Scan op that had to wait for a lock is now runnable */
fragrecptr.p->m_lockStats.wait_ok(scanPtr.p->scanLockMode != ZREADLOCK,
operationRecPtr.p->m_lockTime,
getHighResTimer());
if (operationRecPtr.p->m_op_bits & Operationrec::OP_ELEMENT_DISAPPEARED)
{
jam();
/**
* Despite aborting, this is an 'ok' wait.
* This op is waking up to find the entity it locked has gone.
* As a 'QueuedOp', we are in the parallel queue of the element, so
* at the abort below we don't double-count abort as a failure.
*/
abortOperation(signal);
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
releaseOpRec();
scanPtr.p->scanOpsAllocated--;
continue;
}//if
putActiveScanOp();
sendNextScanConf(signal);
return;
}//while
if ((scanPtr.p->scanBucketState == ScanRec::SCAN_COMPLETED) &&
(scanPtr.p->scanLockHeld == 0)) {
jam();
//----------------------------------------------------------------------------
// The scan is now completed and there are no more locks outstanding. Thus we
// we will report the scan as completed to LQH.
//----------------------------------------------------------------------------
signal->theData[0] = scanPtr.p->scanUserptr;
signal->theData[1] = RNIL;
signal->theData[2] = RNIL;
EXECUTE_DIRECT(refToMain(scanPtr.p->scanUserblockref),
GSN_NEXT_SCANCONF,
signal,
3);
return;
}//if
if (TcheckLcpStop == AccCheckScan::ZCHECK_LCP_STOP) {
//---------------------------------------------------------------------------
// To ensure that the block of the fragment occurring at the start of a local
// checkpoint is not held for too long we insert a release and reacquiring of
// that lock here. This is performed in LQH. If we are blocked or if we have
// requested a sleep then we will receive RNIL in the returning signal word.
//---------------------------------------------------------------------------
signal->theData[0] = scanPtr.p->scanUserptr;
signal->theData[1] =
((scanPtr.p->scanLockHeld >= ZSCAN_MAX_LOCK) ||
(scanPtr.p->scanBucketState == ScanRec::SCAN_COMPLETED));
EXECUTE_DIRECT(DBLQH, GSN_CHECK_LCP_STOP, signal, 2);
jamEntry();
if (signal->theData[0] == RNIL) {
jam();
return;
}//if
}//if
/**
* If we have more than max locks held OR
* scan is completed AND at least one lock held
* - Inform LQH about this condition
*/
if ((scanPtr.p->scanLockHeld >= ZSCAN_MAX_LOCK) ||
(cfreeopRec == RNIL) ||
((scanPtr.p->scanBucketState == ScanRec::SCAN_COMPLETED) &&
(scanPtr.p->scanLockHeld > 0))) {
jam();
signal->theData[0] = scanPtr.p->scanUserptr;
signal->theData[1] = RNIL; // No operation is returned
signal->theData[2] = 512; // MASV
sendSignal(scanPtr.p->scanUserblockref, GSN_NEXT_SCANCONF, signal, 3, JBB);
return;
}
if (scanPtr.p->scanBucketState == ScanRec::SCAN_COMPLETED) {
jam();
signal->theData[0] = scanPtr.i;
signal->theData[1] = AccCheckScan::ZCHECK_LCP_STOP;
execACC_CHECK_SCAN(signal);
return;
}//if
fragrecptr.i = scanPtr.p->activeLocalFrag;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
ndbassert(fragrecptr.p->activeScanMask & scanPtr.p->scanMask);
checkNextBucketLab(signal);
return;
}//Dbacc::execACC_CHECK_SCAN()
/* ******************---------------------------------------------------- */
/* ACC_TO_REQ PERFORM A TAKE OVER */
/* ******************-------------------+ */
/* SENDER: LQH, LEVEL B */
void Dbacc::execACC_TO_REQ(Signal* signal)
{
OperationrecPtr tatrOpPtr;
jamEntry();
tatrOpPtr.i = signal->theData[1]; /* OPER PTR OF ACC */
ptrCheckGuard(tatrOpPtr, coprecsize, operationrec);
/* Only scan locks can be taken over */
if ((tatrOpPtr.p->m_op_bits & Operationrec::OP_MASK) == ZSCAN_OP)
{
if (signal->theData[2] == tatrOpPtr.p->transId1 &&
signal->theData[3] == tatrOpPtr.p->transId2)
{
/* If lock is from same transaction as take over, lock can
* be taken over several times.
*
* This occurs for example in this scenario:
*
* create table t (x int primary key, y int);
* insert into t (x, y) values (1, 0);
* begin;
* # Scan and lock rows in t, update using take over operation.
* update t set y = 1;
* # The second update on same row, will take over the same lock as previous update
* update t set y = 2;
* commit;
*/
return;
}
else if (tatrOpPtr.p->m_op_bits & Operationrec::OP_LOCK_OWNER &&
tatrOpPtr.p->nextParallelQue == RNIL)
{
/* If lock is taken over from other transaction it must be
* the only one in the parallel queue. Otherwise one could
* end up with mixing operations from different transaction
* in a parallel queue.
*/
tatrOpPtr.p->transId1 = signal->theData[2];
tatrOpPtr.p->transId2 = signal->theData[3];
validate_lock_queue(tatrOpPtr);
return;
}
}
jam();
signal->theData[0] = cminusOne;
signal->theData[1] = ZTO_OP_STATE_ERROR;
return;
}//Dbacc::execACC_TO_REQ()
/** ---------------------------------------------------------------------------
* Get next unscanned element in fragment.
*
* @param[in,out] pageptr Page of first container to scan, on return
* container for found element.
* @param[in,out] conidx Index within page for first container to scan, on
* return container for found element.
* @param[out] conptr Pointer withing page of first container to scan,
* on return container for found element.
* @param[in,out] isforward Direction of first container to scan, on return
* the direction of container for found element.
* @param[out] elemptr Pointer within page of next element in scan.
* @param[out] islocked Indicates if element is locked.
* @return Return true if an unscanned element was found.
* ------------------------------------------------------------------------- */
bool Dbacc::getScanElement(Page8Ptr& pageptr,
Uint32& conidx,
Uint32& conptr,
bool& isforward,
Uint32& elemptr,
Uint32& islocked) const
{
/* Input is always the bucket header container */
isforward = true;
/* Check if scan is already active in a container */
Uint32 inPageI;
Uint32 inConptr;
if (scanPtr.p->getContainer(inPageI, inConptr))
{
// TODO: in VM_TRACE double check container is in bucket!
pageptr.i = inPageI;
ptrCheckGuard(pageptr, cpagesize, page8);
conptr = inConptr;
ContainerHeader conhead(pageptr.p->word32[conptr]);
ndbassert(conhead.isScanInProgress());
ndbassert((conhead.getScanBits() & scanPtr.p->scanMask)==0);
getContainerIndex(conptr, conidx, isforward);
}
else // if first bucket is not in scan nor scanned , start it
{
Uint32 conptr = getContainerPtr(conidx, isforward);
ContainerHeader containerhead(pageptr.p->word32[conptr]);
if (!(containerhead.getScanBits() & scanPtr.p->scanMask))
{
if(!containerhead.isScanInProgress())
{
containerhead.setScanInProgress();
pageptr.p->word32[conptr] = containerhead;
}
scanPtr.p->enterContainer(pageptr.i, conptr);
pageptr.p->setScanContainer(scanPtr.p->scanMask, conptr);
}
}
NEXTSEARCH_SCAN_LOOP:
conptr = getContainerPtr(conidx, isforward);
ContainerHeader containerhead(pageptr.p->word32[conptr]);
Uint32 conlen = containerhead.getLength();
if (containerhead.getScanBits() & scanPtr.p->scanMask)
{ // Already scanned, go to next.
ndbassert(!pageptr.p->checkScans(scanPtr.p->scanMask, conptr));
}
else
{
ndbassert(containerhead.isScanInProgress());
if (searchScanContainer(pageptr,
conptr,
isforward,
conlen,
elemptr,
islocked))
{
jam();
return true;
}//if
}
if ((containerhead.getScanBits() & scanPtr.p->scanMask) == 0)
{
containerhead.setScanBits(scanPtr.p->scanMask);
scanPtr.p->leaveContainer(pageptr.i, conptr);
pageptr.p->clearScanContainer(scanPtr.p->scanMask, conptr);
if (!pageptr.p->checkScanContainer(conptr))
{
containerhead.clearScanInProgress();
}
pageptr.p->word32[conptr] = Uint32(containerhead);
}
if (containerhead.haveNext())
{
jam();
nextcontainerinfo(pageptr, conptr, containerhead, conidx, isforward);
conptr=getContainerPtr(conidx,isforward);
containerhead=pageptr.p->word32[conptr];
if ((containerhead.getScanBits() & scanPtr.p->scanMask) == 0)
{
if(!containerhead.isScanInProgress())
{
containerhead.setScanInProgress();
}
pageptr.p->word32[conptr] = Uint32(containerhead);
scanPtr.p->enterContainer(pageptr.i, conptr);
pageptr.p->setScanContainer(scanPtr.p->scanMask, conptr);
} // else already scanned, get next
goto NEXTSEARCH_SCAN_LOOP;
}//if
pageptr.p->word32[conptr] = Uint32(containerhead);
return false;
}//Dbacc::getScanElement()
/* --------------------------------------------------------------------------------- */
/* INIT_SCAN_OP_REC */
/* --------------------------------------------------------------------------------- */
void Dbacc::initScanOpRec(Page8Ptr pageptr,
Uint32 conptr,
Uint32 elemptr) const
{
Uint32 tisoLocalPtr;
Uint32 localkeylen = fragrecptr.p->localkeylen;
scanPtr.p->scanOpsAllocated++;
Uint32 opbits = 0;
opbits |= ZSCAN_OP;
opbits |= scanPtr.p->scanLockMode ? (Uint32) Operationrec::OP_LOCK_MODE : 0;
opbits |= scanPtr.p->scanLockMode ? (Uint32) Operationrec::OP_ACC_LOCK_MODE : 0;
opbits |= (scanPtr.p->scanReadCommittedFlag ?
(Uint32) Operationrec::OP_EXECUTED_DIRTY_READ : 0);
opbits |= Operationrec::OP_COMMIT_DELETE_CHECK;
operationRecPtr.p->userptr = RNIL;
operationRecPtr.p->scanRecPtr = scanPtr.i;
operationRecPtr.p->fid = fragrecptr.p->myfid;
operationRecPtr.p->fragptr = fragrecptr.i;
operationRecPtr.p->nextParallelQue = RNIL;
operationRecPtr.p->prevParallelQue = RNIL;
operationRecPtr.p->nextSerialQue = RNIL;
operationRecPtr.p->prevSerialQue = RNIL;
operationRecPtr.p->transId1 = scanPtr.p->scanTrid1;
operationRecPtr.p->transId2 = scanPtr.p->scanTrid2;
operationRecPtr.p->elementContainer = conptr;
operationRecPtr.p->elementPointer = elemptr;
operationRecPtr.p->elementPage = pageptr.i;
operationRecPtr.p->m_op_bits = opbits;
tisoLocalPtr = elemptr + 1;
arrGuard(tisoLocalPtr, 2048);
if(ElementHeader::getUnlocked(pageptr.p->word32[elemptr]))
{
Local_key key;
key.m_page_no = pageptr.p->word32[tisoLocalPtr];
key.m_page_idx = ElementHeader::getPageIdx(pageptr.p->word32[elemptr]);
operationRecPtr.p->localdata = key;
}
else
{
OperationrecPtr oprec;
oprec.i = ElementHeader::getOpPtrI(pageptr.p->word32[elemptr]);
ptrCheckGuard(oprec, coprecsize, operationrec);
#if defined(VM_TRACE) || defined(ERROR_INSERT)
ndbrequire(oprec.p->localdata.m_page_no == pageptr.p->word32[tisoLocalPtr]);
#endif
operationRecPtr.p->localdata = oprec.p->localdata;
}
tisoLocalPtr = tisoLocalPtr + 1;
ndbrequire(localkeylen == 1)
operationRecPtr.p->hashValue.clear();
operationRecPtr.p->tupkeylen = fragrecptr.p->keyLength;
operationRecPtr.p->xfrmtupkeylen = 0; // not used
NdbTick_Invalidate(&operationRecPtr.p->m_lockTime);
}//Dbacc::initScanOpRec()
/* ----------------------------------------------------------------------------
* Get information of next container.
*
* @param[in,out] pageptr Page of current container, and on return to
* next container.
* @param[in] conptr Pointer within page to current container.
* @param[in] containerheader Header of current container.
* @param[out] nextConidx Index within page to next container.
* @param[out] nextIsforward Direction of next container.
* ------------------------------------------------------------------------- */
void Dbacc::nextcontainerinfo(Page8Ptr& pageptr,
Uint32 conptr,
ContainerHeader containerhead,
Uint32& nextConidx,
bool& nextIsforward) const
{
/* THE NEXT CONTAINER IS IN THE SAME PAGE */
nextConidx = containerhead.getNextIndexNumber();
if (containerhead.getNextEnd() == ZLEFT)
{
jam();
nextIsforward = true;
}
else if (containerhead.getNextEnd() == ZRIGHT)
{
jam();
nextIsforward = false;
}
else
{
ndbrequire(containerhead.getNextEnd() == ZLEFT ||
containerhead.getNextEnd() == ZRIGHT);
}
if (!containerhead.isNextOnSamePage())
{
jam();
/* NEXT CONTAINER IS IN AN OVERFLOW PAGE */
arrGuard(conptr + 1, 2048);
pageptr.i = pageptr.p->word32[conptr + 1];
ptrCheckGuard(pageptr, cpagesize, page8);
}//if
}//Dbacc::nextcontainerinfo()
/* --------------------------------------------------------------------------------- */
/* PUT_ACTIVE_SCAN_OP */
/* --------------------------------------------------------------------------------- */
void Dbacc::putActiveScanOp() const
{
OperationrecPtr pasOperationRecPtr;
pasOperationRecPtr.i = scanPtr.p->scanFirstActiveOp;
if (pasOperationRecPtr.i != RNIL) {
jam();
ptrCheckGuard(pasOperationRecPtr, coprecsize, operationrec);
pasOperationRecPtr.p->prevOp = operationRecPtr.i;
}//if
operationRecPtr.p->nextOp = pasOperationRecPtr.i;
operationRecPtr.p->prevOp = RNIL;
scanPtr.p->scanFirstActiveOp = operationRecPtr.i;
}//Dbacc::putActiveScanOp()
/**
* putOpScanLockQueue
*
* Description: Put an operation in the doubly linked
* lock list on a scan record. The list is used to
* keep track of which operations belonging
* to the scan are put in serial lock list of another
* operation
*
* @note Use takeOutScanLockQueue to remove an operation
* from the list
*
*/
void Dbacc::putOpScanLockQue() const
{
#ifdef VM_TRACE
// DEBUG CODE
// Check that there are as many operations in the lockqueue as
// scanLockHeld indicates
OperationrecPtr tmpOp;
int numLockedOpsBefore = 0;
tmpOp.i = scanPtr.p->scanFirstLockedOp;
while(tmpOp.i != RNIL){
numLockedOpsBefore++;
ptrCheckGuard(tmpOp, coprecsize, operationrec);
if (tmpOp.p->nextOp == RNIL)
{
ndbrequire(tmpOp.i == scanPtr.p->scanLastLockedOp);
}
tmpOp.i = tmpOp.p->nextOp;
}
ndbrequire(numLockedOpsBefore==scanPtr.p->scanLockHeld);
#endif
OperationrecPtr pslOperationRecPtr;
ScanRec theScanRec;
theScanRec = *scanPtr.p;
pslOperationRecPtr.i = scanPtr.p->scanLastLockedOp;
operationRecPtr.p->prevOp = pslOperationRecPtr.i;
operationRecPtr.p->nextOp = RNIL;
if (pslOperationRecPtr.i != RNIL) {
jam();
ptrCheckGuard(pslOperationRecPtr, coprecsize, operationrec);
pslOperationRecPtr.p->nextOp = operationRecPtr.i;
} else {
jam();
scanPtr.p->scanFirstLockedOp = operationRecPtr.i;
}//if
scanPtr.p->scanLastLockedOp = operationRecPtr.i;
scanPtr.p->scanLockHeld++;
}//Dbacc::putOpScanLockQue()
/* --------------------------------------------------------------------------------- */
/* PUT_READY_SCAN_QUEUE */
/* --------------------------------------------------------------------------------- */
void Dbacc::putReadyScanQueue(Uint32 scanRecIndex) const
{
OperationrecPtr prsOperationRecPtr;
ScanRecPtr TscanPtr;
TscanPtr.i = scanRecIndex;
ptrCheckGuard(TscanPtr, cscanRecSize, scanRec);
prsOperationRecPtr.i = TscanPtr.p->scanLastQueuedOp;
operationRecPtr.p->prevOp = prsOperationRecPtr.i;
operationRecPtr.p->nextOp = RNIL;
TscanPtr.p->scanLastQueuedOp = operationRecPtr.i;
if (prsOperationRecPtr.i != RNIL) {
jam();
ptrCheckGuard(prsOperationRecPtr, coprecsize, operationrec);
prsOperationRecPtr.p->nextOp = operationRecPtr.i;
} else {
jam();
TscanPtr.p->scanFirstQueuedOp = operationRecPtr.i;
}//if
}//Dbacc::putReadyScanQueue()
/** ---------------------------------------------------------------------------
* Reset scan bit for all elements within a bucket.
*
* Which scan bit are determined by scanPtr.
*
* @param[in] pageptr Page of first container of bucket
* @param[in] conidx Index within page to first container of bucket
* @param[in] scanMask Scan bit mask for scan bits that should be cleared
* ------------------------------------------------------------------------- */
void Dbacc::releaseScanBucket(Page8Ptr pageptr,
Uint32 conidx,
Uint16 scanMask) const
{
scanMask |= (~fragrecptr.p->activeScanMask &
((1 << MAX_PARALLEL_SCANS_PER_FRAG) - 1));
bool isforward = true;
NEXTRELEASESCANLOOP:
Uint32 conptr = getContainerPtr(conidx, isforward);
ContainerHeader containerhead(pageptr.p->word32[conptr]);
Uint32 conlen = containerhead.getLength();
const Uint16 isScanned = containerhead.getScanBits() & scanMask;
releaseScanContainer(pageptr, conptr, isforward, conlen, scanMask, isScanned);
if (isScanned)
{
containerhead.clearScanBits(isScanned);
pageptr.p->word32[conptr] = Uint32(containerhead);
}
if (containerhead.getNextEnd() != 0) {
jam();
nextcontainerinfo(pageptr, conptr, containerhead, conidx, isforward);
goto NEXTRELEASESCANLOOP;
}//if
}//Dbacc::releaseScanBucket()
/** --------------------------------------------------------------------------
* Reset scan bit of the element for each element in a container.
* Which scan bit are determined by scanPtr.
*
* @param[in] pageptr Pointer to page holding container.
* @param[in] conptr Pointer within page to container.
* @param[in] forward Container growing direction.
* @param[in] conlen Containers current size.
* @param[in] scanMask Scan bits that should be cleared if set
* @param[in] allScanned All elements should have this bits set (debug)
* ------------------------------------------------------------------------- */
void Dbacc::releaseScanContainer(const Page8Ptr pageptr,
const Uint32 conptr,
const bool isforward,
const Uint32 conlen,
const Uint16 scanMask,
const Uint16 allScanned) const
{
OperationrecPtr rscOperPtr;
Uint32 trscElemStep;
Uint32 trscElementptr;
Uint32 trscElemlens;
Uint32 trscElemlen;
if (conlen < 4) {
if (conlen != Container::HEADER_SIZE) {
jam();
sendSystemerror(__LINE__);
}//if
return; /* 2 IS THE MINIMUM SIZE OF THE ELEMENT */
}//if
trscElemlens = conlen - Container::HEADER_SIZE;
trscElemlen = fragrecptr.p->elementLength;
if (isforward)
{
jam();
trscElementptr = conptr + Container::HEADER_SIZE;
trscElemStep = trscElemlen;
}
else
{
jam();
trscElementptr = conptr - trscElemlen;
trscElemStep = 0 - trscElemlen;
}//if
if (trscElemlens % trscElemlen != 0)
{
jam();
sendSystemerror(__LINE__);
}//if
}//Dbacc::releaseScanContainer()
/* --------------------------------------------------------------------------------- */
/* RELEASE_SCAN_REC */
/* --------------------------------------------------------------------------------- */
void Dbacc::releaseScanRec()
{
// Check that all ops this scan has allocated have been
// released
ndbrequire(scanPtr.p->scanOpsAllocated==0);
// Check that all locks this scan might have aquired
// have been properly released
ndbrequire(scanPtr.p->scanLockHeld == 0);
ndbrequire(scanPtr.p->scanFirstLockedOp == RNIL);
ndbrequire(scanPtr.p->scanLastLockedOp == RNIL);
// Check that all active operations have been
// properly released
ndbrequire(scanPtr.p->scanFirstActiveOp == RNIL);
// Check that all queued operations have been
// properly released
ndbrequire(scanPtr.p->scanFirstQueuedOp == RNIL);
ndbrequire(scanPtr.p->scanLastQueuedOp == RNIL);
// Put scan record in free list
scanPtr.p->scanNextfreerec = cfirstFreeScanRec;
scanPtr.p->scanState = ScanRec::SCAN_DISCONNECT;
cfirstFreeScanRec = scanPtr.i;
}//Dbacc::releaseScanRec()
/* --------------------------------------------------------------------------------- */
/* SEARCH_SCAN_CONTAINER */
/* INPUT: TSSC_CONTAINERLEN */
/* TSSC_CONTAINERPTR */
/* TSSC_ISFORWARD */
/* SSC_PAGEIDPTR */
/* SCAN_PTR */
/* OUTPUT: TSSC_IS_LOCKED */
/* */
/* DESCRIPTION: SEARCH IN A CONTAINER TO FIND THE NEXT SCAN ELEMENT. */
/* TO DO THIS THE SCAN BIT OF THE ELEMENT HEADER IS CHECKED. IF */
/* THIS BIT IS ZERO, IT IS SET TO ONE AND THE ELEMENT IS RETURNED.*/
/* --------------------------------------------------------------------------------- */
bool Dbacc::searchScanContainer(Page8Ptr pageptr,
Uint32 conptr,
bool isforward,
Uint32 conlen,
Uint32& elemptr,
Uint32& islocked) const
{
OperationrecPtr operPtr;
Uint32 elemlens;
Uint32 elemlen;
Uint32 elemStep;
Uint32 Telemptr;
Uint32 Tislocked;
#ifdef VM_TRACE
ContainerHeader chead(pageptr.p->word32[conptr]);
ndbassert((chead.getScanBits()&scanPtr.p->scanMask)==0);
ndbassert(chead.isScanInProgress());
ndbassert(scanPtr.p->isInContainer());
{
Uint32 pagei; Uint32 cptr;
ndbassert(scanPtr.p->getContainer(pagei, cptr));
ndbassert(pageptr.i==pagei);
ndbassert(conptr==cptr);
}
#endif
if (conlen < 4) {
jam();
return false; /* 2 IS THE MINIMUM SIZE OF THE ELEMENT */
}//if
elemlens = conlen - Container::HEADER_SIZE;
elemlen = fragrecptr.p->elementLength;
/* LENGTH OF THE ELEMENT */
if (isforward)
{
jam();
Telemptr = conptr + Container::HEADER_SIZE;
elemStep = elemlen;
}
else
{
jam();
Telemptr = conptr - elemlen;
elemStep = 0 - elemlen;
}//if
SCANELEMENTLOOP001:
arrGuard(Telemptr, 2048);
const Uint32 eh = pageptr.p->word32[Telemptr];
bool found=false;
if (!scanPtr.p->isScanned(Telemptr))
{
found=true;
scanPtr.p->setScanned(Telemptr);
}
Tislocked = ElementHeader::getLocked(eh);
if (found)
{
elemptr = Telemptr;
islocked = Tislocked;
return true;
}
ndbassert(!found);
/* THE ELEMENT IS ALREADY SENT. */
/* SEARCH FOR NEXT ONE */
elemlens = elemlens - elemlen;
if (elemlens > 1) {
jam();
Telemptr = Telemptr + elemStep;
goto SCANELEMENTLOOP001;
}//if
return false;
}//Dbacc::searchScanContainer()
/* --------------------------------------------------------------------------------- */
/* SEND THE RESPONSE NEXT_SCANCONF AND POSSIBLE KEYINFO SIGNALS AS WELL. */
/* --------------------------------------------------------------------------------- */
void Dbacc::sendNextScanConf(Signal* signal)
{
const Local_key localKey = operationRecPtr.p->localdata;
c_tup->prepareTUPKEYREQ(localKey.m_page_no, localKey.m_page_idx, fragrecptr.p->tupFragptr);
const Uint32 scanUserPtr = scanPtr.p->scanUserptr;
const Uint32 opPtrI = operationRecPtr.i;
const Uint32 fid = operationRecPtr.p->fid;
BlockReference blockRef = scanPtr.p->scanUserblockref;
jam();
/** ---------------------------------------------------------------------
* LQH WILL NOT HAVE ANY USE OF THE TUPLE KEY LENGTH IN THIS CASE AND
* SO WE DO NOT PROVIDE IT. IN THIS CASE THESE VALUES ARE UNDEFINED.
* ---------------------------------------------------------------------- */
signal->theData[0] = scanUserPtr;
signal->theData[1] = opPtrI;
signal->theData[2] = fid;
signal->theData[3] = localKey.m_page_no;
signal->theData[4] = localKey.m_page_idx;
EXECUTE_DIRECT(refToMain(blockRef), GSN_NEXT_SCANCONF, signal, 5);
return;
}//Dbacc::sendNextScanConf()
/** ---------------------------------------------------------------------------
* Sets lock on an element.
*
* Information about the element is copied from element head into operation
* record. A pointer to operation record are inserted in element header
* instead.
*
* @param[in] pageptr Pointer to page holding element.
* @param[in] elemptr Pointer within page to element.
* ------------------------------------------------------------------------- */
void Dbacc::setlock(Page8Ptr pageptr, Uint32 elemptr) const
{
Uint32 tselTmp1;
arrGuard(elemptr, 2048);
tselTmp1 = pageptr.p->word32[elemptr];
operationRecPtr.p->reducedHashValue = ElementHeader::getReducedHashValue(tselTmp1);
tselTmp1 = ElementHeader::setLocked(operationRecPtr.i);
dbgWord32(pageptr, elemptr, tselTmp1);
pageptr.p->word32[elemptr] = tselTmp1;
}//Dbacc::setlock()
/* --------------------------------------------------------------------------------- */
/* TAKE_OUT_ACTIVE_SCAN_OP */
/* DESCRIPTION: AN ACTIVE SCAN OPERATION IS BELOGED TO AN ACTIVE LIST OF THE */
/* SCAN RECORD. BY THIS SUBRUTIN THE LIST IS UPDATED. */
/* --------------------------------------------------------------------------------- */
void Dbacc::takeOutActiveScanOp() const
{
OperationrecPtr tasOperationRecPtr;
if (operationRecPtr.p->prevOp != RNIL) {
jam();
tasOperationRecPtr.i = operationRecPtr.p->prevOp;
ptrCheckGuard(tasOperationRecPtr, coprecsize, operationrec);
tasOperationRecPtr.p->nextOp = operationRecPtr.p->nextOp;
} else {
jam();
scanPtr.p->scanFirstActiveOp = operationRecPtr.p->nextOp;
}//if
if (operationRecPtr.p->nextOp != RNIL) {
jam();
tasOperationRecPtr.i = operationRecPtr.p->nextOp;
ptrCheckGuard(tasOperationRecPtr, coprecsize, operationrec);
tasOperationRecPtr.p->prevOp = operationRecPtr.p->prevOp;
}//if
}//Dbacc::takeOutActiveScanOp()
/**
* takeOutScanLockQueue
*
* Description: Take out an operation from the doubly linked
* lock list on a scan record.
*
* @note Use putOpScanLockQue to insert a operation in
* the list
*
*/
void Dbacc::takeOutScanLockQueue(Uint32 scanRecIndex) const
{
OperationrecPtr tslOperationRecPtr;
ScanRecPtr TscanPtr;
TscanPtr.i = scanRecIndex;
ptrCheckGuard(TscanPtr, cscanRecSize, scanRec);
if (operationRecPtr.p->prevOp != RNIL) {
jam();
tslOperationRecPtr.i = operationRecPtr.p->prevOp;
ptrCheckGuard(tslOperationRecPtr, coprecsize, operationrec);
tslOperationRecPtr.p->nextOp = operationRecPtr.p->nextOp;
} else {
jam();
// Check that first are pointing at operation to take out
ndbrequire(TscanPtr.p->scanFirstLockedOp==operationRecPtr.i);
TscanPtr.p->scanFirstLockedOp = operationRecPtr.p->nextOp;
}//if
if (operationRecPtr.p->nextOp != RNIL) {
jam();
tslOperationRecPtr.i = operationRecPtr.p->nextOp;
ptrCheckGuard(tslOperationRecPtr, coprecsize, operationrec);
tslOperationRecPtr.p->prevOp = operationRecPtr.p->prevOp;
} else {
jam();
// Check that last are pointing at operation to take out
ndbrequire(TscanPtr.p->scanLastLockedOp==operationRecPtr.i);
TscanPtr.p->scanLastLockedOp = operationRecPtr.p->prevOp;
}//if
TscanPtr.p->scanLockHeld--;
#ifdef VM_TRACE
// DEBUG CODE
// Check that there are as many operations in the lockqueue as
// scanLockHeld indicates
OperationrecPtr tmpOp;
int numLockedOps = 0;
tmpOp.i = TscanPtr.p->scanFirstLockedOp;
while(tmpOp.i != RNIL){
numLockedOps++;
ptrCheckGuard(tmpOp, coprecsize, operationrec);
if (tmpOp.p->nextOp == RNIL)
{
ndbrequire(tmpOp.i == TscanPtr.p->scanLastLockedOp);
}
tmpOp.i = tmpOp.p->nextOp;
}
ndbrequire(numLockedOps==TscanPtr.p->scanLockHeld);
#endif
}//Dbacc::takeOutScanLockQueue()
/* --------------------------------------------------------------------------------- */
/* TAKE_OUT_READY_SCAN_QUEUE */
/* --------------------------------------------------------------------------------- */
void Dbacc::takeOutReadyScanQueue() const
{
OperationrecPtr trsOperationRecPtr;
if (operationRecPtr.p->prevOp != RNIL) {
jam();
trsOperationRecPtr.i = operationRecPtr.p->prevOp;
ptrCheckGuard(trsOperationRecPtr, coprecsize, operationrec);
trsOperationRecPtr.p->nextOp = operationRecPtr.p->nextOp;
} else {
jam();
scanPtr.p->scanFirstQueuedOp = operationRecPtr.p->nextOp;
}//if
if (operationRecPtr.p->nextOp != RNIL) {
jam();
trsOperationRecPtr.i = operationRecPtr.p->nextOp;
ptrCheckGuard(trsOperationRecPtr, coprecsize, operationrec);
trsOperationRecPtr.p->prevOp = operationRecPtr.p->prevOp;
} else {
jam();
scanPtr.p->scanLastQueuedOp = operationRecPtr.p->nextOp;
}//if
}//Dbacc::takeOutReadyScanQueue()
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* */
/* END OF SCAN MODULE */
/* */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
bool Dbacc::getfragmentrec(FragmentrecPtr& rootPtr, Uint32 fid)
{
for (Uint32 i = 0; i < NDB_ARRAY_SIZE(tabptr.p->fragholder); i++) {
jam();
if (tabptr.p->fragholder[i] == fid) {
jam();
fragrecptr.i = tabptr.p->fragptrholder[i];
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
return true;
}//if
}//for
return false;
}//Dbacc::getrootfragmentrec()
/* --------------------------------------------------------------------------------- */
/* INIT_OVERPAGE */
/* INPUT. IOP_PAGEPTR, POINTER TO AN OVERFLOW PAGE RECORD */
/* DESCRIPTION: CONTAINERS AND FREE LISTS OF THE PAGE, GET INITIALE VALUE */
/* ACCORDING TO LH3 AND PAGE STRUCTOR DESCRIPTION OF NDBACC BLOCK */
/* --------------------------------------------------------------------------------- */
void Dbacc::initOverpage(Page8Ptr iopPageptr)
{
Uint32 tiopPrevFree;
Uint32 tiopNextFree;
// Clear page, but keep page list entries
// Setting word32[ALLOC_CONTAINERS] and word32[CHECK_SUM] to zero is essential
Uint32 nextPage = iopPageptr.p->word32[Page8::NEXT_PAGE];
Uint32 prevPage = iopPageptr.p->word32[Page8::PREV_PAGE];
bzero(iopPageptr.p->word32, sizeof(iopPageptr.p->word32));
iopPageptr.p->word32[Page8::NEXT_PAGE] = nextPage;
iopPageptr.p->word32[Page8::PREV_PAGE] = prevPage;
iopPageptr.p->word32[Page8::EMPTY_LIST] = (1 << ZPOS_PAGE_TYPE_BIT);
/* --------------------------------------------------------------------------------- */
/* INITIALISE PREVIOUS PART OF DOUBLY LINKED LIST FOR LEFT CONTAINERS. */
/* --------------------------------------------------------------------------------- */
tiopIndex = ZHEAD_SIZE + 1;
iopPageptr.p->word32[tiopIndex] = Container::NO_CONTAINER_INDEX;
for (tiopPrevFree = 0; tiopPrevFree <= Container::MAX_CONTAINER_INDEX - 1; tiopPrevFree++) {
tiopIndex = tiopIndex + ZBUF_SIZE;
iopPageptr.p->word32[tiopIndex] = tiopPrevFree;
}//for
/* --------------------------------------------------------------------------------- */
/* INITIALISE NEXT PART OF DOUBLY LINKED LIST FOR LEFT CONTAINERS. */
/* --------------------------------------------------------------------------------- */
tiopIndex = ZHEAD_SIZE;
for (tiopNextFree = 1; tiopNextFree <= Container::MAX_CONTAINER_INDEX; tiopNextFree++) {
iopPageptr.p->word32[tiopIndex] = tiopNextFree;
tiopIndex = tiopIndex + ZBUF_SIZE;
}//for
iopPageptr.p->word32[tiopIndex] = Container::NO_CONTAINER_INDEX; /* LEFT_LIST IS UPDATED */
/* --------------------------------------------------------------------------------- */
/* INITIALISE PREVIOUS PART OF DOUBLY LINKED LIST FOR RIGHT CONTAINERS. */
/* --------------------------------------------------------------------------------- */
tiopIndex = (ZBUF_SIZE + ZHEAD_SIZE) - 1;
iopPageptr.p->word32[tiopIndex] = Container::NO_CONTAINER_INDEX;
for (tiopPrevFree = 0; tiopPrevFree <= Container::MAX_CONTAINER_INDEX - 1; tiopPrevFree++) {
tiopIndex = tiopIndex + ZBUF_SIZE;
iopPageptr.p->word32[tiopIndex] = tiopPrevFree;
}//for
/* --------------------------------------------------------------------------------- */
/* INITIALISE NEXT PART OF DOUBLY LINKED LIST FOR RIGHT CONTAINERS. */
/* --------------------------------------------------------------------------------- */
tiopIndex = (ZBUF_SIZE + ZHEAD_SIZE) - 2;
for (tiopNextFree = 1; tiopNextFree <= Container::MAX_CONTAINER_INDEX; tiopNextFree++) {
iopPageptr.p->word32[tiopIndex] = tiopNextFree;
tiopIndex = tiopIndex + ZBUF_SIZE;
}//for
iopPageptr.p->word32[tiopIndex] = Container::NO_CONTAINER_INDEX; /* RIGHT_LIST IS UPDATED */
}//Dbacc::initOverpage()
/* --------------------------------------------------------------------------------- */
/* INIT_PAGE */
/* INPUT. INP_PAGEPTR, POINTER TO A PAGE RECORD */
/* DESCRIPTION: CONTAINERS AND FREE LISTS OF THE PAGE, GET INITIALE VALUE */
/* ACCORDING TO LH3 AND PAGE STRUCTOR DISACRIPTION OF NDBACC BLOCK */
/* --------------------------------------------------------------------------------- */
void Dbacc::initPage(Page8Ptr inpPageptr)
{
Uint32 tinpIndex;
Uint32 tinpTmp;
Uint32 tinpPrevFree;
Uint32 tinpNextFree;
for (tiopIndex = 0; tiopIndex <= 2047; tiopIndex++) {
// Do not clear page list
if (tiopIndex == Page8::NEXT_PAGE) continue;
if (tiopIndex == Page8::PREV_PAGE) continue;
inpPageptr.p->word32[tiopIndex] = 0;
}//for
/* --------------------------------------------------------------------------------- */
/* SET PAGE ID FOR USE OF CHECKPOINTER. */
/* PREPARE CONTAINER HEADERS INDICATING EMPTY CONTAINERS WITHOUT NEXT. */
/* --------------------------------------------------------------------------------- */
inpPageptr.p->word32[ZPOS_PAGE_ID] = tipPageId;
ContainerHeader tinpTmp1;
tinpTmp1.initInUse();
/* --------------------------------------------------------------------------------- */
/* INITIALISE ZNO_CONTAINERS PREDEFINED HEADERS ON LEFT SIZE. */
/* --------------------------------------------------------------------------------- */
tinpIndex = ZHEAD_SIZE;
for (tinpTmp = 0; tinpTmp <= ZNO_CONTAINERS - 1; tinpTmp++) {
inpPageptr.p->word32[tinpIndex] = tinpTmp1;
tinpIndex = tinpIndex + ZBUF_SIZE;
}//for
/* WORD32(ZPOS_EMPTY_LIST) DATA STRUCTURE:*/
/*--------------------------------------- */
/*| PAGE TYPE|LEFT FREE|RIGHT FREE */
/*| 1 | LIST | LIST */
/*| BIT | 7 BITS | 7 BITS */
/*--------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* INITIALISE FIRST POINTER TO DOUBLY LINKED LIST OF FREE CONTAINERS. */
/* INITIALISE LEFT FREE LIST TO 64 AND RIGHT FREE LIST TO ZERO. */
/* ALSO INITIALISE PAGE TYPE TO NOT OVERFLOW PAGE. */
/* --------------------------------------------------------------------------------- */
tinpTmp = (ZNO_CONTAINERS << 7);
inpPageptr.p->word32[ZPOS_EMPTY_LIST] = tinpTmp;
/* --------------------------------------------------------------------------------- */
/* INITIALISE PREVIOUS PART OF DOUBLY LINKED LIST FOR RIGHT CONTAINERS. */
/* --------------------------------------------------------------------------------- */
tinpIndex = (ZHEAD_SIZE + ZBUF_SIZE) - 1;
inpPageptr.p->word32[tinpIndex] = Container::NO_CONTAINER_INDEX;
for (tinpPrevFree = 0; tinpPrevFree <= Container::MAX_CONTAINER_INDEX - 1; tinpPrevFree++) {
tinpIndex = tinpIndex + ZBUF_SIZE;
inpPageptr.p->word32[tinpIndex] = tinpPrevFree;
}//for
/* --------------------------------------------------------------------------------- */
/* INITIALISE NEXT PART OF DOUBLY LINKED LIST FOR RIGHT CONTAINERS. */
/* --------------------------------------------------------------------------------- */
tinpIndex = (ZHEAD_SIZE + ZBUF_SIZE) - 2;
for (tinpNextFree = 1; tinpNextFree <= Container::MAX_CONTAINER_INDEX; tinpNextFree++) {
inpPageptr.p->word32[tinpIndex] = tinpNextFree;
tinpIndex = tinpIndex + ZBUF_SIZE;
}//for
inpPageptr.p->word32[tinpIndex] = Container::NO_CONTAINER_INDEX;
/* --------------------------------------------------------------------------------- */
/* INITIALISE PREVIOUS PART OF DOUBLY LINKED LIST FOR LEFT CONTAINERS. */
/* THE FIRST ZNO_CONTAINERS ARE NOT PUT INTO FREE LIST SINCE THEY ARE */
/* PREDEFINED AS OCCUPIED. */
/* --------------------------------------------------------------------------------- */
tinpIndex = (ZNO_CONTAINERS * ZBUF_SIZE) + ZHEAD_SIZE;
for (tinpNextFree = ZNO_CONTAINERS + 1; tinpNextFree <= Container::MAX_CONTAINER_INDEX; tinpNextFree++) {
inpPageptr.p->word32[tinpIndex] = tinpNextFree;
tinpIndex = tinpIndex + ZBUF_SIZE;
}//for
inpPageptr.p->word32[tinpIndex] = Container::NO_CONTAINER_INDEX;
/* --------------------------------------------------------------------------------- */
/* INITIALISE NEXT PART OF DOUBLY LINKED LIST FOR LEFT CONTAINERS. */
/* THE FIRST ZNO_CONTAINERS ARE NOT PUT INTO FREE LIST SINCE THEY ARE */
/* PREDEFINED AS OCCUPIED. */
/* --------------------------------------------------------------------------------- */
tinpIndex = ((ZNO_CONTAINERS * ZBUF_SIZE) + ZHEAD_SIZE) + 1;
inpPageptr.p->word32[tinpIndex] = Container::NO_CONTAINER_INDEX;
for (tinpPrevFree = ZNO_CONTAINERS; tinpPrevFree <= Container::MAX_CONTAINER_INDEX - 1; tinpPrevFree++) {
tinpIndex = tinpIndex + ZBUF_SIZE;
inpPageptr.p->word32[tinpIndex] = tinpPrevFree;
}//for
/* --------------------------------------------------------------------------------- */
/* INITIALISE HEADER POSITIONS NOT CURRENTLY USED AND ENSURE USE OF OVERFLOW */
/* RECORD POINTER ON THIS PAGE LEADS TO ERROR. */
/* --------------------------------------------------------------------------------- */
inpPageptr.p->word32[ZPOS_CHECKSUM] = 0;
inpPageptr.p->word32[ZPOS_ALLOC_CONTAINERS] = 0;
}//Dbacc::initPage()
/* --------------------------------------------------------------------------------- */
/* RELEASE OP RECORD */
/* PUT A FREE OPERATION IN A FREE LIST OF THE OPERATIONS */
/* --------------------------------------------------------------------------------- */
void Dbacc::releaseOpRec()
{
#if 0
// DEBUG CODE
// Check that the operation to be released isn't
// already in the list of free operations
// Since this code loops through the entire list of free operations
// it's only enabled in VM_TRACE mode
OperationrecPtr opRecPtr;
bool opInList = false;
opRecPtr.i = cfreeopRec;
while (opRecPtr.i != RNIL){
if (opRecPtr.i == operationRecPtr.i){
opInList = true;
break;
}
ptrCheckGuard(opRecPtr, coprecsize, operationrec);
opRecPtr.i = opRecPtr.p->nextOp;
}
ndbrequire(opInList == false);
#endif
ndbrequire(operationRecPtr.p->m_op_bits == Operationrec::OP_INITIAL);
operationRecPtr.p->nextOp = cfreeopRec;
cfreeopRec = operationRecPtr.i; /* UPDATE FREE LIST OF OP RECORDS */
operationRecPtr.p->prevOp = RNIL;
operationRecPtr.p->m_op_bits = Operationrec::OP_INITIAL;
}//Dbacc::releaseOpRec()
/* --------------------------------------------------------------------------------- */
/* RELEASE_OVERPAGE */
/* --------------------------------------------------------------------------------- */
void Dbacc::releaseOverpage(Page8Ptr ropPageptr)
{
jam();
{
LocalContainerPageList sparselist(*this, fragrecptr.p->sparsepages);
sparselist.remove(ropPageptr);
}
jam();
releasePage(ropPageptr);
}//Dbacc::releaseOverpage()
/* ------------------------------------------------------------------------- */
/* RELEASE_PAGE */
/* ------------------------------------------------------------------------- */
void Dbacc::releasePage(Page8Ptr rpPageptr)
{
jam();
ndbassert(g_acc_pages_used[instance()] == cnoOfAllocatedPages);
LocalPage8List freelist(*this, cfreepages);
#ifdef VM_TRACE
// ndbrequire(!freelist.find(rpPageptr));
#endif
freelist.addFirst(rpPageptr);
cnoOfAllocatedPages--;
ndbassert(freelist.getCount() + cnoOfAllocatedPages == cpageCount);
fragrecptr.p->m_noOfAllocatedPages--;
g_acc_pages_used[instance()] = cnoOfAllocatedPages;
if (cnoOfAllocatedPages < m_maxAllocPages)
m_oom = false;
}//Dbacc::releasePage()
bool Dbacc::validatePageCount() const
{
jam();
FragmentrecPtr regFragPtr;
Uint32 pageCount = 0;
for (regFragPtr.i = 0; regFragPtr.i < cfragmentsize; regFragPtr.i++)
{
ptrAss(regFragPtr, fragmentrec);
pageCount += regFragPtr.p->m_noOfAllocatedPages;
}
return pageCount==cnoOfAllocatedPages;
}//Dbacc::validatePageCount()
Uint64 Dbacc::getLinHashByteSize(Uint32 fragId) const
{
ndbassert(validatePageCount());
FragmentrecPtr fragPtr(NULL, fragId);
ptrCheck(fragPtr, cfragmentsize, fragmentrec);
if (unlikely(fragPtr.p == NULL))
{
jam();
ndbassert(false);
return 0;
}
else
{
jam();
ndbassert(fragPtr.p->fragState == ACTIVEFRAG);
return fragPtr.p->m_noOfAllocatedPages * static_cast<Uint64>(sizeof(Page8));
}
}
/* --------------------------------------------------------------------------------- */
/* SEIZE FRAGREC */
/* --------------------------------------------------------------------------------- */
void Dbacc::seizeFragrec()
{
RSS_OP_ALLOC(cnoOfFreeFragrec);
fragrecptr.i = cfirstfreefrag;
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
cfirstfreefrag = fragrecptr.p->nextfreefrag;
fragrecptr.p->nextfreefrag = RNIL;
}//Dbacc::seizeFragrec()
/* --------------------------------------------------------------------------------- */
/* SEIZE_OP_REC */
/* --------------------------------------------------------------------------------- */
void Dbacc::seizeOpRec()
{
operationRecPtr.i = cfreeopRec;
ptrCheckGuard(operationRecPtr, coprecsize, operationrec);
cfreeopRec = operationRecPtr.p->nextOp; /* UPDATE FREE LIST OF OP RECORDS */
/* PUTS OPERTION RECORD PTR IN THE LIST */
/* OF OPERATION IN CONNECTION RECORD */
operationRecPtr.p->nextOp = RNIL;
}//Dbacc::seizeOpRec()
/**
* A ZPAGESIZE_ERROR has occured, out of index pages
* Print some debug info if debug compiled
*/
void Dbacc::zpagesize_error(const char* where){
DEBUG(where << endl
<< " ZPAGESIZE_ERROR" << endl
<< " cfreepages.getCount()=" << cfreepages.getCount() << endl
<< " cpagesize=" <<cpagesize<<endl
<< " cnoOfAllocatedPages="<<cnoOfAllocatedPages);
}
/* --------------------------------------------------------------------------------- */
/* SEIZE_PAGE */
/* --------------------------------------------------------------------------------- */
void Dbacc::seizePage(Page8Ptr& spPageptr)
{
jam();
ndbassert(g_acc_pages_used[instance()] == cnoOfAllocatedPages);
tresult = 0;
if (cfreepages.isEmpty() || m_oom)
{
jam();
zpagesize_error("Dbacc::seizePage");
tresult = ZPAGESIZE_ERROR;
}
else
{
jam();
LocalPage8List freelist(*this, cfreepages);
freelist.removeFirst(spPageptr);
cnoOfAllocatedPages++;
ndbassert(freelist.getCount() + cnoOfAllocatedPages == cpageCount);
fragrecptr.p->m_noOfAllocatedPages++;
if (cnoOfAllocatedPages >= m_maxAllocPages)
m_oom = true;
if (cnoOfAllocatedPages > cnoOfAllocatedPagesMax)
cnoOfAllocatedPagesMax = cnoOfAllocatedPages;
g_acc_pages_used[instance()] = cnoOfAllocatedPages;
}
}//Dbacc::seizePage()
/* --------------------------------------------------------------------------------- */
/* SEIZE_ROOTFRAGREC */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* SEIZE_SCAN_REC */
/* --------------------------------------------------------------------------------- */
void Dbacc::seizeScanRec()
{
scanPtr.i = cfirstFreeScanRec;
ptrCheckGuard(scanPtr, cscanRecSize, scanRec);
ndbrequire(scanPtr.p->scanState == ScanRec::SCAN_DISCONNECT);
cfirstFreeScanRec = scanPtr.p->scanNextfreerec;
}//Dbacc::seizeScanRec()
/* --------------------------------------------------------------------------------- */
/* SEIZE_SR_VERSION_REC */
/* --------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------- */
/* SEND_SYSTEMERROR */
/* --------------------------------------------------------------------------------- */
void Dbacc::sendSystemerror(int line)const
{
progError(line, NDBD_EXIT_PRGERR);
}//Dbacc::sendSystemerror()
void Dbacc::execDBINFO_SCANREQ(Signal *signal)
{
jamEntry();
DbinfoScanReq req= *(DbinfoScanReq*)signal->theData;
const Ndbinfo::ScanCursor* cursor =
CAST_CONSTPTR(Ndbinfo::ScanCursor, DbinfoScan::getCursorPtr(&req));
Ndbinfo::Ratelimit rl;
switch(req.tableId){
case Ndbinfo::POOLS_TABLEID:
{
jam();
const DynArr256Pool::Info pmpInfo = directoryPool.getInfo();
Ndbinfo::pool_entry pools[] =
{
{ "Index memory",
cnoOfAllocatedPages,
cpageCount,
sizeof(Page8),
cnoOfAllocatedPagesMax,
{ CFG_DB_INDEX_MEM,0,0,0 }},
{ "L2PMap pages",
pmpInfo.pg_count,
0, /* No real limit */
pmpInfo.pg_byte_sz,
/*
No HWM for this row as it would be a fixed fraction of "Data memory"
and therefore of limited interest.
*/
0,
{ 0, 0, 0}},
{ "L2PMap nodes",
pmpInfo.inuse_nodes,
pmpInfo.pg_count * pmpInfo.nodes_per_page, // Max within current pages.
pmpInfo.node_byte_sz,
/*
No HWM for this row as it would be a fixed fraction of "Data memory"
and therefore of limited interest.
*/
0,
{ 0, 0, 0 }},
{ NULL, 0,0,0,0,{ 0,0,0,0 }}
};
static const size_t num_config_params =
sizeof(pools[0].config_params)/sizeof(pools[0].config_params[0]);
Uint32 pool = cursor->data[0];
BlockNumber bn = blockToMain(number());
while(pools[pool].poolname)
{
jam();
Ndbinfo::Row row(signal, req);
row.write_uint32(getOwnNodeId());
row.write_uint32(bn); // block number
row.write_uint32(instance()); // block instance
row.write_string(pools[pool].poolname);
row.write_uint64(pools[pool].used);
row.write_uint64(pools[pool].total);
row.write_uint64(pools[pool].used_hi);
row.write_uint64(pools[pool].entry_size);
for (size_t i = 0; i < num_config_params; i++)
row.write_uint32(pools[pool].config_params[i]);
ndbinfo_send_row(signal, req, row, rl);
pool++;
if (rl.need_break(req))
{
jam();
ndbinfo_send_scan_break(signal, req, rl, pool);
return;
}
}
break;
}
case Ndbinfo::FRAG_LOCKS_TABLEID:
{
Uint32 tableid = cursor->data[0];
for (;tableid < ctablesize; tableid++)
{
TabrecPtr tabPtr;
tabPtr.i = tableid;
ptrAss(tabPtr, tabrec);
if (tabPtr.p->fragholder[0] != RNIL)
{
jam();
// Loop over all fragments for this table.
for (Uint32 f = 0; f < NDB_ARRAY_SIZE(tabPtr.p->fragholder); f++)
{
if (tabPtr.p->fragholder[f] != RNIL)
{
jam();
FragmentrecPtr frp;
frp.i = tabPtr.p->fragptrholder[f];
ptrCheckGuard(frp, cfragmentsize, fragmentrec);
const Fragmentrec::LockStats& ls = frp.p->m_lockStats;
Ndbinfo::Row row(signal, req);
row.write_uint32(getOwnNodeId());
row.write_uint32(instance());
row.write_uint32(tableid);
row.write_uint32(tabPtr.p->fragholder[f]);
row.write_uint64(ls.m_ex_req_count);
row.write_uint64(ls.m_ex_imm_ok_count);
row.write_uint64(ls.m_ex_wait_ok_count);
row.write_uint64(ls.m_ex_wait_fail_count);
row.write_uint64(ls.m_sh_req_count);
row.write_uint64(ls.m_sh_imm_ok_count);
row.write_uint64(ls.m_sh_wait_ok_count);
row.write_uint64(ls.m_sh_wait_fail_count);
row.write_uint64(ls.m_wait_ok_millis);
row.write_uint64(ls.m_wait_fail_millis);
ndbinfo_send_row(signal, req, row, rl);
}
}
}
/*
If a break is needed, break on a table boundary,
as we use the table id as a cursor.
*/
if (rl.need_break(req))
{
jam();
ndbinfo_send_scan_break(signal, req, rl, tableid + 1);
return;
}
}
break;
}
case Ndbinfo::ACC_OPERATIONS_TABLEID:
{
jam();
/* Take a break periodically when scanning records */
Uint32 maxToCheck = 1024;
NDB_TICKS now = getHighResTimer();
OperationrecPtr opRecPtr;
opRecPtr.i = cursor->data[0];
while (opRecPtr.i < coprecsize)
{
ptrCheckGuard(opRecPtr, coprecsize, operationrec);
/**
* ACC holds lock requests/operations in a 2D queue
* structure.
* The lock owning operation is directly linked from the
* PK hash element. Only one operation is the 'owner'
* at any one time.
*
* The lock owning operation may have other operations
* concurrently holding the lock, for example other
* operations in the same transaction, or, for shared
* reads, in other transactions.
* These operations are in the 'parallel' queue of the
* lock owning operation, linked from its
* nextParallelQue member.
*
* Non-compatible lock requests must wait until some/
* all of the current lock holder(s) have released the
* lock before they can run. They are held in the
* 'serial' queue, lined from the lockOwner's
* nextSerialQue member.
*
* Note also : Only one operation per row can 'run'
* in LDM at any one time, but this serialisation
* is not considered as locking overhead.
*
* Note also : These queue members are part of overlays
* and are not always guaranteed to be valid, m_op_bits
* often must be consulted too.
*/
if (opRecPtr.p->m_op_bits != Operationrec::OP_INITIAL)
{
jam();
FragmentrecPtr fp;
fp.i = opRecPtr.p->fragptr;
ptrCheckGuard(fp, cfragmentsize, fragmentrec);
const Uint32 tableId = fp.p->myTableId;
const Uint32 fragId = fp.p->myfid;
const Uint64 rowId =
Uint64(opRecPtr.p->localdata.m_page_no) << 32 |
Uint64(opRecPtr.p->localdata.m_page_idx);
/* Send as separate attrs, as in cluster_operations */
const Uint32 transId0 = opRecPtr.p->transId1;
const Uint32 transId1 = opRecPtr.p->transId2;
const Uint32 prevSerialQue = opRecPtr.p->prevSerialQue;
const Uint32 nextSerialQue = opRecPtr.p->nextSerialQue;
const Uint32 prevParallelQue = opRecPtr.p->prevParallelQue;
const Uint32 nextParallelQue = opRecPtr.p->nextParallelQue;
const Uint32 flags = opRecPtr.p->m_op_bits;
/* Ignore Uint32 overflow at ~ 50 days */
const Uint32 durationMillis =
(Uint32) NdbTick_Elapsed(opRecPtr.p->m_lockTime,
now).milliSec();
const Uint32 userPtr = opRecPtr.p->userptr;
/* Live operation */
Ndbinfo::Row row(signal, req);
row.write_uint32(getOwnNodeId());
row.write_uint32(instance());
row.write_uint32(tableId);
row.write_uint32(fragId);
row.write_uint64(rowId);
row.write_uint32(transId0);
row.write_uint32(transId1);
row.write_uint32(opRecPtr.i);
row.write_uint32(flags);
row.write_uint32(prevSerialQue);
row.write_uint32(nextSerialQue);
row.write_uint32(prevParallelQue);
row.write_uint32(nextParallelQue);
row.write_uint32(durationMillis);
row.write_uint32(userPtr);
ndbinfo_send_row(signal, req, row, rl);
}
maxToCheck--;
opRecPtr.i++;
if (rl.need_break(req) || maxToCheck == 0)
{
jam();
ndbinfo_send_scan_break(signal, req, rl, opRecPtr.i);
return;
}
}
break;
}
default:
break;
}
ndbinfo_send_scan_conf(signal, req, rl);
}
void
Dbacc::execDUMP_STATE_ORD(Signal* signal)
{
DumpStateOrd * const dumpState = (DumpStateOrd *)&signal->theData[0];
if (dumpState->args[0] == DumpStateOrd::AccDumpOneScanRec){
Uint32 recordNo = RNIL;
if (signal->length() == 2)
recordNo = dumpState->args[1];
else
return;
if (recordNo >= cscanRecSize)
return;
scanPtr.i = recordNo;
ptrAss(scanPtr, scanRec);
infoEvent("Dbacc::ScanRec[%d]: state=%d, transid(0x%x, 0x%x)",
scanPtr.i, scanPtr.p->scanState,scanPtr.p->scanTrid1,
scanPtr.p->scanTrid2);
infoEvent(" activeLocalFrag=%d, nextBucketIndex=%d",
scanPtr.p->activeLocalFrag,
scanPtr.p->nextBucketIndex);
infoEvent(" scanNextfreerec=%d firstActOp=%d firstLockedOp=%d, "
"scanLastLockedOp=%d firstQOp=%d lastQOp=%d",
scanPtr.p->scanNextfreerec,
scanPtr.p->scanFirstActiveOp,
scanPtr.p->scanFirstLockedOp,
scanPtr.p->scanLastLockedOp,
scanPtr.p->scanFirstQueuedOp,
scanPtr.p->scanLastQueuedOp);
infoEvent(" scanUserP=%d, startNoBuck=%d, minBucketIndexToRescan=%d, "
"maxBucketIndexToRescan=%d",
scanPtr.p->scanUserptr,
scanPtr.p->startNoOfBuckets,
scanPtr.p->minBucketIndexToRescan,
scanPtr.p->maxBucketIndexToRescan);
infoEvent(" scanBucketState=%d, scanLockHeld=%d, userBlockRef=%d, "
"scanMask=%d scanLockMode=%d",
scanPtr.p->scanBucketState,
scanPtr.p->scanLockHeld,
scanPtr.p->scanUserblockref,
scanPtr.p->scanMask,
scanPtr.p->scanLockMode);
return;
}
// Dump all ScanRec(ords)
if (dumpState->args[0] == DumpStateOrd::AccDumpAllScanRec){
Uint32 recordNo = 0;
if (signal->length() == 1)
infoEvent("ACC: Dump all ScanRec - size: %d",
cscanRecSize);
else if (signal->length() == 2)
recordNo = dumpState->args[1];
else
return;
dumpState->args[0] = DumpStateOrd::AccDumpOneScanRec;
dumpState->args[1] = recordNo;
execDUMP_STATE_ORD(signal);
if (recordNo < cscanRecSize-1){
dumpState->args[0] = DumpStateOrd::AccDumpAllScanRec;
dumpState->args[1] = recordNo+1;
sendSignal(reference(), GSN_DUMP_STATE_ORD, signal, 2, JBB);
}
return;
}
// Dump all active ScanRec(ords)
if (dumpState->args[0] == DumpStateOrd::AccDumpAllActiveScanRec){
Uint32 recordNo = 0;
if (signal->length() == 1)
infoEvent("ACC: Dump active ScanRec - size: %d",
cscanRecSize);
else if (signal->length() == 2)
recordNo = dumpState->args[1];
else
return;
ScanRecPtr sp;
sp.i = recordNo;
ptrAss(sp, scanRec);
if (sp.p->scanState != ScanRec::SCAN_DISCONNECT){
dumpState->args[0] = DumpStateOrd::AccDumpOneScanRec;
dumpState->args[1] = recordNo;
execDUMP_STATE_ORD(signal);
}
if (recordNo < cscanRecSize-1){
dumpState->args[0] = DumpStateOrd::AccDumpAllActiveScanRec;
dumpState->args[1] = recordNo+1;
sendSignal(reference(), GSN_DUMP_STATE_ORD, signal, 2, JBB);
}
return;
}
if(dumpState->args[0] == DumpStateOrd::EnableUndoDelayDataWrite){
ndbout << "Dbacc:: delay write of datapages for table = "
<< dumpState->args[1]<< endl;
c_errorInsert3000_TableId = dumpState->args[1];
SET_ERROR_INSERT_VALUE(3000);
return;
}
if(dumpState->args[0] == DumpStateOrd::AccDumpOneOperationRec){
Uint32 recordNo = RNIL;
if (signal->length() == 2)
recordNo = dumpState->args[1];
else
return;
if (recordNo >= coprecsize)
return;
OperationrecPtr tmpOpPtr;
tmpOpPtr.i = recordNo;
ptrAss(tmpOpPtr, operationrec);
infoEvent("Dbacc::operationrec[%d]: transid(0x%x, 0x%x)",
tmpOpPtr.i, tmpOpPtr.p->transId1,
tmpOpPtr.p->transId2);
infoEvent("elementPage=%d, elementPointer=%d ",
tmpOpPtr.p->elementPage,
tmpOpPtr.p->elementPointer);
infoEvent("fid=%d, fragptr=%d ",
tmpOpPtr.p->fid, tmpOpPtr.p->fragptr);
infoEvent("hashValue=%d", tmpOpPtr.p->hashValue.pack());
infoEvent("nextLockOwnerOp=%d, nextOp=%d, nextParallelQue=%d ",
tmpOpPtr.p->nextLockOwnerOp, tmpOpPtr.p->nextOp,
tmpOpPtr.p->nextParallelQue);
infoEvent("nextSerialQue=%d, prevOp=%d ",
tmpOpPtr.p->nextSerialQue,
tmpOpPtr.p->prevOp);
infoEvent("prevLockOwnerOp=%d, prevParallelQue=%d",
tmpOpPtr.p->prevLockOwnerOp, tmpOpPtr.p->nextParallelQue);
infoEvent("prevSerialQue=%d, scanRecPtr=%d",
tmpOpPtr.p->prevSerialQue, tmpOpPtr.p->scanRecPtr);
infoEvent("m_op_bits=0x%x, reducedHashValue=%x ",
tmpOpPtr.p->m_op_bits, tmpOpPtr.p->reducedHashValue.pack());
return;
}
if(dumpState->args[0] == DumpStateOrd::AccDumpNumOpRecs){
Uint32 freeOpRecs = 0;
OperationrecPtr opRecPtr;
opRecPtr.i = cfreeopRec;
while (opRecPtr.i != RNIL){
freeOpRecs++;
ptrCheckGuard(opRecPtr, coprecsize, operationrec);
opRecPtr.i = opRecPtr.p->nextOp;
}
infoEvent("Dbacc::OperationRecords: num=%d, free=%d",
coprecsize, freeOpRecs);
return;
}
if(dumpState->args[0] == DumpStateOrd::AccDumpFreeOpRecs){
OperationrecPtr opRecPtr;
opRecPtr.i = cfreeopRec;
while (opRecPtr.i != RNIL){
dumpState->args[0] = DumpStateOrd::AccDumpOneOperationRec;
dumpState->args[1] = opRecPtr.i;
execDUMP_STATE_ORD(signal);
ptrCheckGuard(opRecPtr, coprecsize, operationrec);
opRecPtr.i = opRecPtr.p->nextOp;
}
return;
}
if(dumpState->args[0] == DumpStateOrd::AccDumpNotFreeOpRecs){
Uint32 recordStart = RNIL;
if (signal->length() == 2)
recordStart = dumpState->args[1];
else
return;
if (recordStart >= coprecsize)
return;
for (Uint32 i = recordStart; i < coprecsize; i++){
bool inFreeList = false;
OperationrecPtr opRecPtr;
opRecPtr.i = cfreeopRec;
while (opRecPtr.i != RNIL){
if (opRecPtr.i == i){
inFreeList = true;
break;
}
ptrCheckGuard(opRecPtr, coprecsize, operationrec);
opRecPtr.i = opRecPtr.p->nextOp;
}
if (inFreeList == false){
dumpState->args[0] = DumpStateOrd::AccDumpOneOperationRec;
dumpState->args[1] = i;
execDUMP_STATE_ORD(signal);
}
}
return;
}
#if 0
if (type == 100) {
RelTabMemReq * const req = (RelTabMemReq *)signal->getDataPtrSend();
req->primaryTableId = 2;
req->secondaryTableId = RNIL;
req->userPtr = 2;
req->userRef = DBDICT_REF;
sendSignal(cownBlockref, GSN_REL_TABMEMREQ, signal,
RelTabMemReq::SignalLength, JBB);
return;
}//if
if (type == 101) {
RelTabMemReq * const req = (RelTabMemReq *)signal->getDataPtrSend();
req->primaryTableId = 4;
req->secondaryTableId = 5;
req->userPtr = 4;
req->userRef = DBDICT_REF;
sendSignal(cownBlockref, GSN_REL_TABMEMREQ, signal,
RelTabMemReq::SignalLength, JBB);
return;
}//if
if (type == 102) {
RelTabMemReq * const req = (RelTabMemReq *)signal->getDataPtrSend();
req->primaryTableId = 6;
req->secondaryTableId = 8;
req->userPtr = 6;
req->userRef = DBDICT_REF;
sendSignal(cownBlockref, GSN_REL_TABMEMREQ, signal,
RelTabMemReq::SignalLength, JBB);
return;
}//if
if (type == 103) {
DropTabFileReq * const req = (DropTabFileReq *)signal->getDataPtrSend();
req->primaryTableId = 2;
req->secondaryTableId = RNIL;
req->userPtr = 2;
req->userRef = DBDICT_REF;
sendSignal(cownBlockref, GSN_DROP_TABFILEREQ, signal,
DropTabFileReq::SignalLength, JBB);
return;
}//if
if (type == 104) {
DropTabFileReq * const req = (DropTabFileReq *)signal->getDataPtrSend();
req->primaryTableId = 4;
req->secondaryTableId = 5;
req->userPtr = 4;
req->userRef = DBDICT_REF;
sendSignal(cownBlockref, GSN_DROP_TABFILEREQ, signal,
DropTabFileReq::SignalLength, JBB);
return;
}//if
if (type == 105) {
DropTabFileReq * const req = (DropTabFileReq *)signal->getDataPtrSend();
req->primaryTableId = 6;
req->secondaryTableId = 8;
req->userPtr = 6;
req->userRef = DBDICT_REF;
sendSignal(cownBlockref, GSN_DROP_TABFILEREQ, signal,
DropTabFileReq::SignalLength, JBB);
return;
}//if
#endif
if (signal->theData[0] == DumpStateOrd::SchemaResourceSnapshot)
{
RSS_OP_SNAPSHOT_SAVE(cnoOfFreeFragrec);
return;
}
if (signal->theData[0] == DumpStateOrd::SchemaResourceCheckLeak)
{
RSS_OP_SNAPSHOT_CHECK(cnoOfFreeFragrec);
return;
}
}//Dbacc::execDUMP_STATE_ORD()
Uint32
Dbacc::getL2PMapAllocBytes(Uint32 fragId) const
{
jam();
FragmentrecPtr fragPtr(NULL, fragId);
ptrCheckGuard(fragPtr, cfragmentsize, fragmentrec);
return fragPtr.p->directory.getByteSize();
}
void
Dbacc::execREAD_PSEUDO_REQ(Signal* signal){
jamEntry();
fragrecptr.i = signal->theData[0];
Uint32 attrId = signal->theData[1];
ptrCheckGuard(fragrecptr, cfragmentsize, fragmentrec);
Uint64 tmp;
switch(attrId){
case AttributeHeader::ROW_COUNT:
tmp = fragrecptr.p->noOfElements;
break;
case AttributeHeader::COMMIT_COUNT:
tmp = fragrecptr.p->m_commit_count;
break;
default:
tmp = 0;
}
memcpy(signal->theData, &tmp, 8); /* must be memcpy, gives strange results on
* ithanium gcc (GCC) 3.4.1 smp linux 2.4
* otherwise
*/
// Uint32 * src = (Uint32*)&tmp;
// signal->theData[0] = src[0];
// signal->theData[1] = src[1];
}
void
Dbacc::execNODE_STATE_REP(Signal* signal)
{
jamEntry();
const NodeStateRep* rep = CAST_CONSTPTR(NodeStateRep,
signal->getDataPtr());
if (rep->nodeState.startLevel == NodeState::SL_STARTED)
{
jam();
const ndb_mgm_configuration_iterator * p =
m_ctx.m_config.getOwnConfigIterator();
ndbrequire(p != 0);
Uint32 free_pct = 5;
ndb_mgm_get_int_parameter(p, CFG_DB_FREE_PCT, &free_pct);
m_free_pct = free_pct;
m_maxAllocPages = (cpagesize * (100 - free_pct)) / 100;
if (cnoOfAllocatedPages >= m_maxAllocPages)
m_oom = true;
}
SimulatedBlock::execNODE_STATE_REP(signal);
}
#ifdef VM_TRACE
void
Dbacc::debug_lh_vars(const char* where)const
{
Uint32 b = fragrecptr.p->level.getTop();
Uint32 di = fragrecptr.p->getPageNumber(b);
Uint32 ri = di >> 8;
ndbout
<< "DBACC: " << where << ":"
<< " frag:" << fragrecptr.p->myTableId
<< "/" << fragrecptr.p->myfid
<< " slack:" << fragrecptr.p->slack
<< "/" << fragrecptr.p->slackCheck
<< " top:" << fragrecptr.p->level.getTop()
<< " di:" << di
<< " ri:" << ri
<< " full:" << fragrecptr.p->dirRangeFull
<< "\n";
}
#endif
| gunnarku/mysql-8.0 | storage/ndb/src/kernel/blocks/dbacc/DbaccMain.cpp | C++ | gpl-2.0 | 339,088 |
<?php
/**
*
* Types Marketing Class
*
* $HeadURL: https://www.onthegosystems.com/misc_svn/cck/tags/1.6.6.5/classes/class.wpcf-marketing-messages.php $
* $LastChangedDate: 2015-03-19 17:22:58 +0000 (Thu, 19 Mar 2015) $
* $LastChangedRevision: 32503 $
* $LastChangedBy: juan $
*
*/
include_once dirname(__FILE__).'/class.wpcf-marketing.php';
/**
* Types Marketing Class
*
* @since Types 1.6.5
* @package Types
* @subpackage Classes
* @version 0.1
* @category Help
* @author marcin <marcin.p@icanlocalize.com>
*/
class WPCF_Types_Marketing_Messages extends WPCF_Types_Marketing
{
private $state;
public function __construct()
{
parent::__construct();
add_action('admin_enqueue_scripts', array($this, 'register_scripts'), 1);
add_action('wp_ajax_toolset_messages', array( $this, 'update_toolset_messages' ));
add_action('admin_notices', array($this, 'add_message_after_activate'));
$this->set_state();
}
private function set_state()
{
$this->state = '0' == get_option($this->option_disable, '0')? 'endabled':'disabled';
if ('disabled' == $this->state) {
return;
}
if ( self::check_register() ) {
$this->state = 'disabled';
}
}
public static function check_register()
{
if(!function_exists('WP_Installer')){
return false;
}
$repos = array(
'toolset'
);
foreach( $repos as $repository_id ) {
$key = WP_Installer()->repository_has_subscription($repository_id);
if ( empty($key) ) {
continue;
}
return true;
}
return false;
}
private function get_data()
{
/**
* check kind
*/
$kind = $this->get_kind();
/**
* get default
*/
if ( empty($kind) ) {
$kind = $this->get_default_kind();
}
/**
* check exists?
*/
if ( empty($kind) || !array_key_exists($kind, $this->adverts ) ) {
return;
}
/**
* check type
*/
$type = $this->get_page_type();
if ( empty($type) || !array_key_exists($type, $this->adverts[$kind]) ) {
return;
}
if ( !is_array($this->adverts[$kind][$type]) ) {
return;
}
/**
* get number
*/
$number = intval(get_user_option('types-modal'));
if ( !isset($this->adverts[$kind][$type][$number]) ) {
if ( empty($this->adverts[$kind][$type]) ) {
return;
}
$number = 0;
}
$data = $this->adverts[$kind][$type][$number];
$data['number'] = $number;
$data['count'] = count($this->adverts[$kind][$type]);
return $data;
}
private function replace_placeholders($text)
{
$type = $this->get_page_type();
switch($type) {
case 'cpt':
if (
is_array($_GET)
&& array_key_exists('wpcf-post-type', $_GET)
) {
$types = get_option('wpcf-custom-types', array());
$candidate_key = sanitize_text_field( $_GET['wpcf-post-type'] );
if ( array_key_exists($candidate_key, $types ) ) {
$text = preg_replace( '/PPP/', $types[$candidate_key]['labels']['name'], $text);
}
}
break;
case 'taxonomy':
if (
is_array($_GET)
&& array_key_exists('wpcf-tax', $_GET)
) {
$taxonomies = get_option('wpcf-custom-taxonomies', array());
$candidate_key = sanitize_text_field( $_GET['wpcf-tax'] );
if ( array_key_exists($candidate_key, $taxonomies) ) {
$text = preg_replace( '/TTT/', $taxonomies[$candidate_key]['labels']['name'], $text);
if ( array_key_exists('supports', $taxonomies[$candidate_key]) ) {
$types = get_option('wpcf-custom-types', array());
$post_type = array_keys($taxonomies[$candidate_key]['supports']);
if ( !empty($post_type) ) {
$post_type = $post_type[array_rand($post_type)];
$post_type = get_post_type_object($post_type);
if ( $post_type ) {
$text = preg_replace( '/PPP/', $post_type->labels->name, $text);
}
}
}
}
}
break;
}
/**
* defaults
*/
$text = preg_replace( '/PPP/', __('Posts'), $text);
$text = preg_replace( '/TTT/', __('Tags'), $text);
return $text;
}
public function register_scripts()
{
$data = $this->get_data();
if ( empty($data) ) {
return;
}
/**
* common question
*/
$data['message'] = __('Saving your changes', 'wpcf');
$data['spinner'] = apply_filters('wpcf_marketing_message', admin_url('/images/spinner.gif'), $data, 'spinner');
$data['question'] = apply_filters('wpcf_marketing_message', __('Did you know?', 'wcpf'), $data, 'question');
/**
* random image & class
*/
$image = isset($data['image'])? $data['image']:'views';
$src = sprintf(
'%s/marketing/assets/images/%s.png',
WPCF_RELPATH,
$image
);
$data['image'] = apply_filters('wpcf_marketing_message', $src, $data, 'image');
$data['class'] = apply_filters('wpcf_marketing_message', $image, $data, 'class');
/**
* values depend on type
*/
foreach ( array('header', 'description') as $key ) {
$value = '';
if ( isset($data[$key]) && $data[$key] ) {
$value = $this->replace_placeholders($data[$key]);
}
$data[$key] = apply_filters('wpcf_marketing_message', $value, $data, $key );
$data['state'] = $this->state;
}
wp_register_script( 'types-modal', WPCF_EMBEDDED_RES_RELPATH.'/js/modal.js', array('jquery'), WPCF_VERSION, true);
wp_localize_script( 'types-modal', 'types_modal', $data);
wp_enqueue_script('types-modal');
}
public function update_message($message = false)
{
if (empty($message)) {
return;
}
echo '<div class="updated"><p>', $message, '</p></div>';
}
public function update_options()
{
if(!isset($_POST['marketing'])) {
return;
}
if ( !wp_verify_nonce($_POST['marketing'], 'update')) {
return;
}
if (
array_key_exists($this->option_name, $_POST)
&& array_key_exists($_POST[$this->option_name], $this->options)
) {
// @todo we need to sanitize $_POST[$this->option_name]: is it a string, an array or what?
if ( !add_option($this->option_name, $_POST[$this->option_name], '', 'no') ) {
update_option($this->option_name, $_POST[$this->option_name]);
}
}
$this->set_state();
}
public function delete_option_kind()
{
delete_option($this->option_name);
}
public function get_kind_list()
{
$type = get_option($this->option_name);
$content = '<ul class="marketing-kind-list">';
foreach( $this->options as $key => $one ) {
$content .= '<li>';
$content .= sprintf(
'<input type="radio" name="%s" value="%s" id="getting_started_%s" %s/>',
$this->get_option_name(),
$key,
$key,
$type == $key? ' checked="checked" ':''
);
$content .= sprintf(
'<label for="getting_started_%s"> <strong>%s</strong>%s%s</label>',
$key,
$one['title'],
array_key_exists('description', $one)? ' | ':'',
array_key_exists('description', $one)? $one['description']:''
);
$content .= '</li>';
}
$content .= '</ul>';
return $content;
}
public function kind_list()
{
echo $this->get_kind_list();
}
public function show_top($update = true)
{
$data = $this->get_data();
if ( empty($data) ) {
return false;
}
$content = '<div class="icon-toolset-logo icon-toolset">';
$content .= sprintf('<p class="wpcf-notif-header">%s</p>', $update? __('Updated!', 'wpcf'):__('Created!', 'wpcf') );
if ( 'endabled' == $this->state) {
$content .= '<p class="wpcf-notif-description">';
if ( isset($data['link']) ) {
$content .= sprintf(
'<a href="%s">%s</a>',
$this->add_ga_campain($data['link'], 'save-updated'),
$data['description']
);
} else {
$content .= $data['description'];
}
$content .= '</p>';
}
$content .= '</div>';
$content = $this->replace_placeholders($content);
/**
* after all set up types-modal for next time
*/
$key = rand( 0, $data['count']-1 );
$user_id = get_current_user_id();
update_user_option($user_id, 'types-modal', $key);
return $content;
}
public function get_content()
{
if ( $url = $this->get_kind_url() ) {
include_once dirname(__FILE__).'/class.wpcf-marketing-tutorial.php';
$tutorial = new WPCF_Types_Marketing_Tutorial();
return $tutorial->get_content('kind');
}
return;
}
// @todo nonce ?
// @todo auth ?
public function update_toolset_messages()
{
$settings = wpcf_get_settings();
if (
array_key_exists('value', $_POST)
&& 'checked' == $_POST['value']
) {
if ( !add_option($this->option_disable, '1', '', 'no') ) {
update_option($this->option_disable, '1');
}
$settings['toolset_messages'] = true;
} else {
delete_option($this->option_disable);
$settings['toolset_messages'] = false;
}
update_option('wpcf_settings', $settings);
echo '<div class="updated"><p>';
_e('Toolset Messages state saved!', 'wpcf');
echo '</p></div>';
die;
}
public function add_message_after_activate()
{
if ( !isset($_GET['activate']) ) {
return;
}
if ( is_multisite() ) {
return;
}
if ( 'show' != get_option('types_show_on_activate') ) {
return;
}
wp_enqueue_style('onthego-admin-styles');
wp_enqueue_style('wpcf-css-embedded');
$data = array(
'header' => __('Need help with <em>Types</em>?', 'wpcf'),
'text' => __('Types plugin includes a lot of options. Tell us what kind of site you are building and we\'ll show you how to use Types in the best way.', 'wpcf'),
'button_primary_url' => add_query_arg( 'page', basename(dirname(dirname(__FILE__))).'/marketing/getting-started/index.php', admin_url('admin.php') ),
'button_primary_text' => __('Get Started', 'wpcf'),
'button_dismiss_url' => '',
'button_dismiss_text' => __('Dismiss', 'wpcf'),
);
wp_localize_script('marketing-getting-started', 'types_activate', $data);
wp_enqueue_script('marketing-getting-started');
update_option('types_show_on_activate', 'hide');
}
}
| juliusmiranda/wordpress | wp-content/plugins/types/classes/class.wpcf-marketing-messages.php | PHP | gpl-2.0 | 11,944 |
/**************************************************************************\
*
* FILE: Int16Record.cpp
*
* This source file is part of DIME.
* Copyright (C) 1998-1999 by Systems In Motion. All rights reserved.
*
* This library 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 library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License (the accompanying file named COPYING) for more
* details.
*
**************************************************************************
*
* If you need DIME for a non-GPL project, contact Systems In Motion
* to acquire a Professional Edition License:
*
* Systems In Motion http://www.sim.no/
* Prof. Brochs gate 6 sales@sim.no
* N-7030 Trondheim Voice: +47 22114160
* NORWAY Fax: +47 67172912
*
\**************************************************************************/
/*!
\class dimeInt16Record dime/records/Int16Record.h
\brief The dimeInt16Record class is a container class for 16-bit integer records.
*/
#include <dime/records/Int16Record.h>
#include <dime/Input.h>
#include <dime/Output.h>
#include <dime/util/MemHandler.h>
/*!
Constructor
*/
dimeInt16Record::dimeInt16Record(const int group_code, const int16 val)
:dimeRecord(group_code)
{
this->setValue(val);
}
//!
dimeRecord *
dimeInt16Record::copy(dimeMemHandler * const mh) const
{
return new(mh) dimeInt16Record(this->groupCode, this->value);
}
/*!
Sets the int16 value.
*/
void
dimeInt16Record::setValue(const int16 val)
{
this->value = val;
}
/*!
Returns the int16 value.
*/
int16
dimeInt16Record::getValue() const
{
return this->value;
}
//!
int
dimeInt16Record::typeId() const
{
return dimeBase::dimeInt16RecordType;
}
//!
bool
dimeInt16Record::read(dimeInput * const in)
{
return in->readInt16(this->value);
}
//!
bool
dimeInt16Record::write(dimeOutput * const out)
{
if (dimeRecord::write(out)) {
return out->writeInt16(this->value);
}
return false;
}
//!
void
dimeInt16Record::setValue(const dimeParam ¶m, dimeMemHandler * const )
{
this->value = param.int16_data;
}
//!
void
dimeInt16Record::getValue(dimeParam ¶m) const
{
param.int16_data = this->value;
}
| h4ck3rm1k3/TwoNickels | src/records/Int16Record.cpp | C++ | gpl-2.0 | 2,623 |
/*
* Copyright (C) 2008-2019 TrinityCore <https://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 "Guild.h"
#include "AccountMgr.h"
#include "Bag.h"
#include "CalendarMgr.h"
#include "CharacterCache.h"
#include "Chat.h"
#include "Config.h"
#include "DatabaseEnv.h"
#include "GameTime.h"
#include "GuildMgr.h"
#include "Language.h"
#include "Log.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Opcodes.h"
#include "Player.h"
#include "ScriptMgr.h"
#include "SocialMgr.h"
#include "World.h"
#include "WorldSession.h"
size_t const MAX_GUILD_BANK_TAB_TEXT_LEN = 500;
uint32 const EMBLEM_PRICE = 10 * GOLD;
// only used in logs
char const* GetGuildEventString(GuildEvents event)
{
switch (event)
{
case GE_PROMOTION:
return "Member promotion";
case GE_DEMOTION:
return "Member demotion";
case GE_MOTD:
return "Guild MOTD";
case GE_JOINED:
return "Member joined";
case GE_LEFT:
return "Member left";
case GE_REMOVED:
return "Member removed";
case GE_LEADER_IS:
return "Leader is";
case GE_LEADER_CHANGED:
return "Leader changed";
case GE_DISBANDED:
return "Guild disbanded";
case GE_TABARDCHANGE:
return "Tabard change";
case GE_RANK_UPDATED:
return "Rank updated";
case GE_RANK_DELETED:
return "Rank deleted";
case GE_SIGNED_ON:
return "Member signed on";
case GE_SIGNED_OFF:
return "Member signed off";
case GE_GUILDBANKBAGSLOTS_CHANGED:
return "Bank bag slots changed";
case GE_BANK_TAB_PURCHASED:
return "Bank tab purchased";
case GE_BANK_TAB_UPDATED:
return "Bank tab updated";
case GE_BANK_MONEY_SET:
return "Bank money set";
case GE_BANK_TAB_AND_MONEY_UPDATED:
return "Bank and money updated";
case GE_BANK_TEXT_CHANGED:
return "Bank tab text changed";
default:
break;
}
return "<None>";
}
inline uint32 GetGuildBankTabPrice(uint8 tabId)
{
// these prices are in gold units, not copper
static uint32 const tabPrices[GUILD_BANK_MAX_TABS] = { 100, 250, 500, 1000, 2500, 5000 };
ASSERT(tabId < GUILD_BANK_MAX_TABS);
return tabPrices[tabId];
}
void Guild::SendCommandResult(WorldSession* session, GuildCommandType type, GuildCommandError errCode, std::string const& param)
{
WorldPacket data(SMSG_GUILD_COMMAND_RESULT, 8 + param.size() + 1);
data << uint32(type);
data << param;
data << uint32(errCode);
session->SendPacket(&data);
TC_LOG_DEBUG("guild", "SMSG_GUILD_COMMAND_RESULT [%s]: Type: %u, code: %u, param: %s"
, session->GetPlayerInfo().c_str(), type, errCode, param.c_str());
}
void Guild::SendSaveEmblemResult(WorldSession* session, GuildEmblemError errCode)
{
WorldPacket data(MSG_SAVE_GUILD_EMBLEM, 4);
data << uint32(errCode);
session->SendPacket(&data);
TC_LOG_DEBUG("guild", "MSG_SAVE_GUILD_EMBLEM [%s] Code: %u", session->GetPlayerInfo().c_str(), errCode);
}
// LogHolder
Guild::LogHolder::~LogHolder()
{
// Cleanup
for (auto itr = m_log.begin(); itr != m_log.end(); ++itr)
delete (*itr);
}
// Adds event loaded from database to collection
inline void Guild::LogHolder::LoadEvent(LogEntry* entry)
{
if (m_nextGUID == uint32(GUILD_EVENT_LOG_GUID_UNDEFINED))
m_nextGUID = entry->GetGUID();
m_log.push_front(entry);
}
// Adds new event happened in game.
// If maximum number of events is reached, oldest event is removed from collection.
inline void Guild::LogHolder::AddEvent(SQLTransaction& trans, LogEntry* entry)
{
// Check max records limit
if (m_log.size() >= m_maxRecords)
{
LogEntry* oldEntry = m_log.front();
delete oldEntry;
m_log.pop_front();
}
// Add event to list
m_log.push_back(entry);
// Save to DB
entry->SaveToDB(trans);
}
// Writes information about all events into packet.
inline void Guild::LogHolder::WritePacket(WorldPacket& data) const
{
data << uint8(m_log.size());
for (auto itr = m_log.begin(); itr != m_log.end(); ++itr)
(*itr)->WritePacket(data);
}
inline uint32 Guild::LogHolder::GetNextGUID()
{
// Next guid was not initialized. It means there are no records for this holder in DB yet.
// Start from the beginning.
if (m_nextGUID == uint32(GUILD_EVENT_LOG_GUID_UNDEFINED))
m_nextGUID = 0;
else
m_nextGUID = (m_nextGUID + 1) % m_maxRecords;
return m_nextGUID;
}
Guild::LogEntry::LogEntry(ObjectGuid::LowType guildId, uint32 guid) : m_guildId(guildId), m_guid(guid), m_timestamp(GameTime::GetGameTime()) { }
// EventLogEntry
void Guild::EventLogEntry::SaveToDB(SQLTransaction& trans) const
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_EVENTLOG);
stmt->setUInt32(0, m_guildId);
stmt->setUInt32(1, m_guid);
trans->Append(stmt);
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_EVENTLOG);
stmt->setUInt32( index, m_guildId);
stmt->setUInt32(++index, m_guid);
stmt->setUInt8 (++index, uint8(m_eventType));
stmt->setUInt32(++index, m_playerGuid1);
stmt->setUInt32(++index, m_playerGuid2);
stmt->setUInt8 (++index, m_newRank);
stmt->setUInt64(++index, m_timestamp);
trans->Append(stmt);
}
void Guild::EventLogEntry::WritePacket(WorldPacket& data) const
{
// Event type
data << uint8(m_eventType);
// Player 1
data << ObjectGuid(HighGuid::Player, m_playerGuid1);
// Player 2 not for left/join guild events
if (m_eventType != GUILD_EVENT_LOG_JOIN_GUILD && m_eventType != GUILD_EVENT_LOG_LEAVE_GUILD)
data << ObjectGuid(HighGuid::Player, m_playerGuid2);
// New Rank - only for promote/demote guild events
if (m_eventType == GUILD_EVENT_LOG_PROMOTE_PLAYER || m_eventType == GUILD_EVENT_LOG_DEMOTE_PLAYER)
data << uint8(m_newRank);
// Event timestamp
data << uint32(GameTime::GetGameTime() - m_timestamp);
}
// BankEventLogEntry
void Guild::BankEventLogEntry::SaveToDB(SQLTransaction& trans) const
{
uint8 index = 0;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_EVENTLOG);
stmt->setUInt32( index, m_guildId);
stmt->setUInt32(++index, m_guid);
stmt->setUInt8 (++index, m_bankTabId);
trans->Append(stmt);
index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_EVENTLOG);
stmt->setUInt32( index, m_guildId);
stmt->setUInt32(++index, m_guid);
stmt->setUInt8 (++index, m_bankTabId);
stmt->setUInt8 (++index, uint8(m_eventType));
stmt->setUInt32(++index, m_playerGuid);
stmt->setUInt32(++index, m_itemOrMoney);
stmt->setUInt16(++index, m_itemStackCount);
stmt->setUInt8 (++index, m_destTabId);
stmt->setUInt64(++index, m_timestamp);
trans->Append(stmt);
}
void Guild::BankEventLogEntry::WritePacket(WorldPacket& data) const
{
data << uint8(m_eventType);
data << ObjectGuid(HighGuid::Player, m_playerGuid);
switch (m_eventType)
{
case GUILD_BANK_LOG_DEPOSIT_ITEM:
case GUILD_BANK_LOG_WITHDRAW_ITEM:
data << uint32(m_itemOrMoney);
data << uint32(m_itemStackCount);
break;
case GUILD_BANK_LOG_MOVE_ITEM:
case GUILD_BANK_LOG_MOVE_ITEM2:
data << uint32(m_itemOrMoney);
data << uint32(m_itemStackCount);
data << uint8(m_destTabId);
break;
default:
data << uint32(m_itemOrMoney);
}
data << uint32(GameTime::GetGameTime() - m_timestamp);
}
// RankInfo
void Guild::RankInfo::LoadFromDB(Field* fields)
{
m_rankId = fields[1].GetUInt8();
m_name = fields[2].GetString();
m_rights = fields[3].GetUInt32();
m_bankMoneyPerDay = fields[4].GetUInt32();
if (m_rankId == GR_GUILDMASTER) // Prevent loss of leader rights
m_rights |= GR_RIGHT_ALL;
}
void Guild::RankInfo::SaveToDB(SQLTransaction& trans) const
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_RANK);
stmt->setUInt32(0, m_guildId);
stmt->setUInt8 (1, m_rankId);
stmt->setString(2, m_name);
stmt->setUInt32(3, m_rights);
stmt->setUInt32(4, m_bankMoneyPerDay);
CharacterDatabase.ExecuteOrAppend(trans, stmt);
}
void Guild::RankInfo::CreateMissingTabsIfNeeded(uint8 tabs, SQLTransaction& trans, bool logOnCreate /* = false */)
{
for (uint8 i = 0; i < tabs; ++i)
{
GuildBankRightsAndSlots& rightsAndSlots = m_bankTabRightsAndSlots[i];
if (rightsAndSlots.GetTabId() == i)
continue;
rightsAndSlots.SetTabId(i);
if (m_rankId == GR_GUILDMASTER)
rightsAndSlots.SetGuildMasterValues();
if (logOnCreate)
TC_LOG_ERROR("guild", "Guild %u has broken Tab %u for rank %u. Created default tab.", m_guildId, i, m_rankId);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_RIGHT);
stmt->setUInt32(0, m_guildId);
stmt->setUInt8(1, i);
stmt->setUInt8(2, m_rankId);
stmt->setUInt8(3, rightsAndSlots.GetRights());
stmt->setUInt32(4, rightsAndSlots.GetSlots());
trans->Append(stmt);
}
}
void Guild::RankInfo::WritePacket(WorldPacket& data) const
{
data << uint32(m_rights);
if (m_bankMoneyPerDay == GUILD_WITHDRAW_MONEY_UNLIMITED)
data << uint32(GUILD_WITHDRAW_MONEY_UNLIMITED);
else
data << uint32(m_bankMoneyPerDay);
for (uint8 i = 0; i < GUILD_BANK_MAX_TABS; ++i)
{
data << uint32(m_bankTabRightsAndSlots[i].GetRights());
data << uint32(m_bankTabRightsAndSlots[i].GetSlots());
}
}
void Guild::RankInfo::SetName(std::string const& name)
{
if (m_name == name)
return;
m_name = name;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_RANK_NAME);
stmt->setString(0, m_name);
stmt->setUInt8 (1, m_rankId);
stmt->setUInt32(2, m_guildId);
CharacterDatabase.Execute(stmt);
}
void Guild::RankInfo::SetRights(uint32 rights)
{
if (m_rankId == GR_GUILDMASTER) // Prevent loss of leader rights
rights = GR_RIGHT_ALL;
if (m_rights == rights)
return;
m_rights = rights;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_RANK_RIGHTS);
stmt->setUInt32(0, m_rights);
stmt->setUInt8 (1, m_rankId);
stmt->setUInt32(2, m_guildId);
CharacterDatabase.Execute(stmt);
}
void Guild::RankInfo::SetBankMoneyPerDay(uint32 money)
{
if (m_rankId == GR_GUILDMASTER) // Prevent loss of leader rights
money = uint32(GUILD_WITHDRAW_MONEY_UNLIMITED);
if (m_bankMoneyPerDay == money)
return;
m_bankMoneyPerDay = money;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_RANK_BANK_MONEY);
stmt->setUInt32(0, money);
stmt->setUInt8 (1, m_rankId);
stmt->setUInt32(2, m_guildId);
CharacterDatabase.Execute(stmt);
}
void Guild::RankInfo::SetBankTabSlotsAndRights(GuildBankRightsAndSlots rightsAndSlots, bool saveToDB)
{
if (m_rankId == GR_GUILDMASTER) // Prevent loss of leader rights
rightsAndSlots.SetGuildMasterValues();
GuildBankRightsAndSlots& guildBR = m_bankTabRightsAndSlots[rightsAndSlots.GetTabId()];
guildBR = rightsAndSlots;
if (saveToDB)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_RIGHT);
stmt->setUInt32(0, m_guildId);
stmt->setUInt8 (1, guildBR.GetTabId());
stmt->setUInt8 (2, m_rankId);
stmt->setUInt8 (3, guildBR.GetRights());
stmt->setUInt32(4, guildBR.GetSlots());
CharacterDatabase.Execute(stmt);
}
}
// BankTab
Guild::BankTab::BankTab(ObjectGuid::LowType guildId, uint8 tabId) : m_guildId(guildId), m_tabId(tabId)
{
memset(m_items, 0, GUILD_BANK_MAX_SLOTS * sizeof(Item*));
}
void Guild::BankTab::LoadFromDB(Field* fields)
{
m_name = fields[2].GetString();
m_icon = fields[3].GetString();
m_text = fields[4].GetString();
}
bool Guild::BankTab::LoadItemFromDB(Field* fields)
{
uint8 slotId = fields[13].GetUInt8();
ObjectGuid::LowType itemGuid = fields[14].GetUInt32();
uint32 itemEntry = fields[15].GetUInt32();
if (slotId >= GUILD_BANK_MAX_SLOTS)
{
TC_LOG_ERROR("guild", "Invalid slot for item (GUID: %u, id: %u) in guild bank, skipped.", itemGuid, itemEntry);
return false;
}
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemEntry);
if (!proto)
{
TC_LOG_ERROR("guild", "Unknown item (GUID: %u, id: %u) in guild bank, skipped.", itemGuid, itemEntry);
return false;
}
Item* pItem = NewItemOrBag(proto);
if (!pItem->LoadFromDB(itemGuid, ObjectGuid::Empty, fields, itemEntry))
{
TC_LOG_ERROR("guild", "Item (GUID %u, id: %u) not found in item_instance, deleting from guild bank!", itemGuid, itemEntry);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_NONEXISTENT_GUILD_BANK_ITEM);
stmt->setUInt32(0, m_guildId);
stmt->setUInt8 (1, m_tabId);
stmt->setUInt8 (2, slotId);
CharacterDatabase.Execute(stmt);
delete pItem;
return false;
}
pItem->AddToWorld();
m_items[slotId] = pItem;
return true;
}
// Deletes contents of the tab from the world (and from DB if necessary)
void Guild::BankTab::Delete(SQLTransaction& trans, bool removeItemsFromDB)
{
for (uint8 slotId = 0; slotId < GUILD_BANK_MAX_SLOTS; ++slotId)
{
if (Item* pItem = m_items[slotId])
{
pItem->RemoveFromWorld();
if (removeItemsFromDB)
pItem->DeleteFromDB(trans);
delete pItem;
pItem = nullptr;
}
}
}
inline void Guild::BankTab::WritePacket(WorldPacket& data) const
{
uint8 count = 0;
size_t pos = data.wpos();
data << uint8(0);
for (uint8 slotId = 0; slotId < GUILD_BANK_MAX_SLOTS; ++slotId)
if (WriteSlotPacket(data, slotId))
++count;
data.put<uint8>(pos, count);
}
// Writes information about contents of specified slot into packet.
bool Guild::BankTab::WriteSlotPacket(WorldPacket& data, uint8 slotId, bool ignoreEmpty /* = true */) const
{
Item* pItem = GetItem(slotId);
uint32 itemEntry = pItem ? pItem->GetEntry() : 0;
if (!itemEntry && ignoreEmpty)
return false;
data << uint8(slotId);
data << uint32(itemEntry);
if (itemEntry)
{
data << uint32(0); // 3.3.0 (0x00018020, 0x00018000)
if (uint32 random = pItem->GetItemRandomPropertyId())
{
data << uint32(random); // Random item property id
data << uint32(pItem->GetItemSuffixFactor()); // SuffixFactor
}
else
data << uint32(0);
data << uint32(pItem->GetCount()); // ITEM_FIELD_STACK_COUNT
data << uint32(pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT)); // Permanent enchantment
data << uint8(abs(pItem->GetSpellCharges())); // Spell charges
uint8 enchCount = 0;
size_t enchCountPos = data.wpos();
data << uint8(enchCount); // Number of enchantments
for (uint32 socketSlot = SOCK_ENCHANTMENT_SLOT; socketSlot < SOCK_ENCHANTMENT_SLOT + MAX_GEM_SOCKETS; ++socketSlot)
{
if (uint32 enchId = pItem->GetEnchantmentId(EnchantmentSlot(socketSlot)))
{
data << uint8(socketSlot - SOCK_ENCHANTMENT_SLOT);
data << uint32(enchId);
++enchCount;
}
}
data.put<uint8>(enchCountPos, enchCount);
}
return true;
}
void Guild::BankTab::WriteInfoPacket(WorldPacket& data) const
{
data << m_name;
data << m_icon;
}
void Guild::BankTab::SetInfo(std::string const& name, std::string const& icon)
{
if (m_name == name && m_icon == icon)
return;
m_name = name;
m_icon = icon;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_BANK_TAB_INFO);
stmt->setString(0, m_name);
stmt->setString(1, m_icon);
stmt->setUInt32(2, m_guildId);
stmt->setUInt8 (3, m_tabId);
CharacterDatabase.Execute(stmt);
}
void Guild::BankTab::SetText(std::string const& text)
{
if (m_text == text)
return;
m_text = text;
utf8truncate(m_text, MAX_GUILD_BANK_TAB_TEXT_LEN); // DB and client size limitation
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_BANK_TAB_TEXT);
stmt->setString(0, m_text);
stmt->setUInt32(1, m_guildId);
stmt->setUInt8 (2, m_tabId);
CharacterDatabase.Execute(stmt);
}
// Sets/removes contents of specified slot.
// If pItem == nullptr contents are removed.
bool Guild::BankTab::SetItem(SQLTransaction& trans, uint8 slotId, Item* item)
{
if (slotId >= GUILD_BANK_MAX_SLOTS)
return false;
m_items[slotId] = item;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_ITEM);
stmt->setUInt32(0, m_guildId);
stmt->setUInt8 (1, m_tabId);
stmt->setUInt8 (2, slotId);
trans->Append(stmt);
if (item)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_ITEM);
stmt->setUInt32(0, m_guildId);
stmt->setUInt8 (1, m_tabId);
stmt->setUInt8 (2, slotId);
stmt->setUInt32(3, item->GetGUID().GetCounter());
trans->Append(stmt);
item->SetGuidValue(ITEM_FIELD_CONTAINED, ObjectGuid::Empty);
item->SetGuidValue(ITEM_FIELD_OWNER, ObjectGuid::Empty);
item->FSetState(ITEM_NEW);
item->SaveToDB(trans); // Not in inventory and can be saved standalone
}
return true;
}
void Guild::BankTab::SendText(Guild const* guild, WorldSession* session) const
{
WorldPacket data(MSG_QUERY_GUILD_BANK_TEXT, 1 + m_text.size() + 1);
data << uint8(m_tabId);
data << m_text;
if (session)
{
TC_LOG_DEBUG("guild", "MSG_QUERY_GUILD_BANK_TEXT [%s]: Tabid: %u, Text: %s"
, session->GetPlayerInfo().c_str(), m_tabId, m_text.c_str());
session->SendPacket(&data);
}
else
{
TC_LOG_DEBUG("guild", "MSG_QUERY_GUILD_BANK_TEXT [Broadcast]: Tabid: %u, Text: %s", m_tabId, m_text.c_str());
guild->BroadcastPacket(&data);
}
}
// Member
Guild::Member::Member(ObjectGuid::LowType guildId, ObjectGuid guid, uint8 rankId) :
m_guildId(guildId),
m_guid(guid),
m_zoneId(0),
m_level(0),
m_class(0),
m_gender(0),
m_flags(GUILDMEMBER_STATUS_NONE),
m_logoutTime(GameTime::GetGameTime()),
m_accountId(0),
m_rankId(rankId)
{
memset(m_bankWithdraw, 0, (GUILD_BANK_MAX_TABS + 1) * sizeof(int32));
}
void Guild::Member::SetStats(Player* player)
{
m_name = player->GetName();
m_level = player->GetLevel();
m_class = player->GetClass();
m_gender = player->GetNativeGender();
m_zoneId = player->GetZoneId();
m_accountId = player->GetSession()->GetAccountId();
}
void Guild::Member::SetStats(std::string const& name, uint8 level, uint8 _class, uint8 gender, uint32 zoneId, uint32 accountId)
{
m_name = name;
m_level = level;
m_class = _class;
m_gender = gender;
m_zoneId = zoneId;
m_accountId = accountId;
}
void Guild::Member::SetPublicNote(std::string const& publicNote)
{
if (m_publicNote == publicNote)
return;
m_publicNote = publicNote;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MEMBER_PNOTE);
stmt->setString(0, publicNote);
stmt->setUInt32(1, m_guid.GetCounter());
CharacterDatabase.Execute(stmt);
}
void Guild::Member::SetOfficerNote(std::string const& officerNote)
{
if (m_officerNote == officerNote)
return;
m_officerNote = officerNote;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MEMBER_OFFNOTE);
stmt->setString(0, officerNote);
stmt->setUInt32(1, m_guid.GetCounter());
CharacterDatabase.Execute(stmt);
}
void Guild::Member::ChangeRank(SQLTransaction& trans, uint8 newRank)
{
m_rankId = newRank;
// Update rank information in player's field, if he is online.
if (Player* player = FindPlayer())
player->SetRank(newRank);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MEMBER_RANK);
stmt->setUInt8 (0, newRank);
stmt->setUInt32(1, m_guid.GetCounter());
CharacterDatabase.ExecuteOrAppend(trans, stmt);
}
void Guild::Member::UpdateLogoutTime()
{
m_logoutTime = GameTime::GetGameTime();
}
void Guild::Member::SaveToDB(SQLTransaction& trans) const
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_MEMBER);
stmt->setUInt32(0, m_guildId);
stmt->setUInt32(1, m_guid.GetCounter());
stmt->setUInt8 (2, m_rankId);
stmt->setString(3, m_publicNote);
stmt->setString(4, m_officerNote);
CharacterDatabase.ExecuteOrAppend(trans, stmt);
}
// Loads member's data from database.
// If member has broken fields (level, class) returns false.
// In this case member has to be removed from guild.
bool Guild::Member::LoadFromDB(Field* fields)
{
m_publicNote = fields[3].GetString();
m_officerNote = fields[4].GetString();
for (uint8 i = 0; i <= GUILD_BANK_MAX_TABS; ++i)
m_bankWithdraw[i] = fields[5 + i].GetUInt32();
SetStats(fields[12].GetString(),
fields[13].GetUInt8(), // characters.level
fields[14].GetUInt8(), // characters.class
fields[15].GetUInt8(), // characters.gender
fields[16].GetUInt16(), // characters.zone
fields[17].GetUInt32()); // characters.account
m_logoutTime = fields[18].GetUInt32(); // characters.logout_time
if (!CheckStats())
return false;
if (!m_zoneId)
{
TC_LOG_DEBUG("guild", "%s has broken zone-data", m_guid.ToString().c_str());
m_zoneId = Player::GetZoneIdFromDB(m_guid);
}
ResetFlags();
return true;
}
// Validate player fields. Returns false if corrupted fields are found.
bool Guild::Member::CheckStats() const
{
if (m_level < 1)
{
TC_LOG_ERROR("guild", "%s has a broken data in field `characters`.`level`, deleting him from guild!", m_guid.ToString().c_str());
return false;
}
if (m_class < CLASS_WARRIOR || m_class >= MAX_CLASSES)
{
TC_LOG_ERROR("guild", "%s has a broken data in field `characters`.`class`, deleting him from guild!", m_guid.ToString().c_str());
return false;
}
return true;
}
void Guild::Member::WritePacket(WorldPacket& data, bool sendOfficerNote) const
{
data << uint64(m_guid)
<< uint8(m_flags)
<< m_name
<< uint32(m_rankId)
<< uint8(m_level)
<< uint8(m_class)
<< uint8(m_gender)
<< uint32(m_zoneId);
if (!m_flags)
data << float(float(GameTime::GetGameTime() - m_logoutTime) / DAY);
data << m_publicNote;
if (sendOfficerNote)
data << m_officerNote;
else
data << "";
}
Player* Guild::Member::FindPlayer() const
{
return ObjectAccessor::FindPlayer(m_guid);
}
Player* Guild::Member::FindConnectedPlayer() const
{
return ObjectAccessor::FindConnectedPlayer(m_guid);
}
// Decreases amount of money/slots left for today.
// If (tabId == GUILD_BANK_MAX_TABS) decrease money amount.
// Otherwise decrease remaining items amount for specified tab.
void Guild::Member::UpdateBankWithdrawValue(SQLTransaction& trans, uint8 tabId, uint32 amount)
{
m_bankWithdraw[tabId] += amount;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_MEMBER_WITHDRAW);
stmt->setUInt32(0, m_guid.GetCounter());
for (uint8 i = 0; i <= GUILD_BANK_MAX_TABS;)
{
uint32 withdraw = m_bankWithdraw[i++];
stmt->setUInt32(i, withdraw);
}
CharacterDatabase.ExecuteOrAppend(trans, stmt);
}
void Guild::Member::ResetValues()
{
for (uint8 tabId = 0; tabId <= GUILD_BANK_MAX_TABS; ++tabId)
m_bankWithdraw[tabId] = 0;
}
// Get amount of money/slots left for today.
// If (tabId == GUILD_BANK_MAX_TABS) return money amount.
// Otherwise return remaining items amount for specified tab.
int32 Guild::Member::GetBankWithdrawValue(uint8 tabId) const
{
// Guild master has unlimited amount.
if (IsRank(GR_GUILDMASTER))
return static_cast<int32>(tabId == GUILD_BANK_MAX_TABS ? GUILD_WITHDRAW_MONEY_UNLIMITED : GUILD_WITHDRAW_SLOT_UNLIMITED);
return m_bankWithdraw[tabId];
}
// EmblemInfo
void EmblemInfo::ReadPacket(WorldPacket& recv)
{
recv >> m_style >> m_color >> m_borderStyle >> m_borderColor >> m_backgroundColor;
}
void EmblemInfo::LoadFromDB(Field* fields)
{
m_style = fields[3].GetUInt8();
m_color = fields[4].GetUInt8();
m_borderStyle = fields[5].GetUInt8();
m_borderColor = fields[6].GetUInt8();
m_backgroundColor = fields[7].GetUInt8();
}
void EmblemInfo::WritePacket(WorldPacket& data) const
{
data << uint32(m_style);
data << uint32(m_color);
data << uint32(m_borderStyle);
data << uint32(m_borderColor);
data << uint32(m_backgroundColor);
}
void EmblemInfo::SaveToDB(ObjectGuid::LowType guildId) const
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_EMBLEM_INFO);
stmt->setUInt32(0, m_style);
stmt->setUInt32(1, m_color);
stmt->setUInt32(2, m_borderStyle);
stmt->setUInt32(3, m_borderColor);
stmt->setUInt32(4, m_backgroundColor);
stmt->setUInt32(5, guildId);
CharacterDatabase.Execute(stmt);
}
// MoveItemData
Guild::MoveItemData::MoveItemData(Guild* guild, Player* player, uint8 container, uint8 slotId) : m_pGuild(guild), m_pPlayer(player),
m_container(container), m_slotId(slotId), m_pItem(nullptr), m_pClonedItem(nullptr)
{
}
Guild::MoveItemData::~MoveItemData()
{
}
bool Guild::MoveItemData::CheckItem(uint32& splitedAmount)
{
ASSERT(m_pItem);
if (splitedAmount > m_pItem->GetCount())
return false;
if (splitedAmount == m_pItem->GetCount())
splitedAmount = 0;
return true;
}
bool Guild::MoveItemData::CanStore(Item* pItem, bool swap, bool sendError)
{
m_vec.clear();
InventoryResult msg = CanStore(pItem, swap);
if (sendError && msg != EQUIP_ERR_OK)
m_pPlayer->SendEquipError(msg, pItem);
return (msg == EQUIP_ERR_OK);
}
bool Guild::MoveItemData::CloneItem(uint32 count)
{
ASSERT(m_pItem);
m_pClonedItem = m_pItem->CloneItem(count);
if (!m_pClonedItem)
{
m_pPlayer->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, m_pItem);
return false;
}
return true;
}
void Guild::MoveItemData::LogAction(MoveItemData* pFrom) const
{
ASSERT(pFrom->GetItem());
sScriptMgr->OnGuildItemMove(m_pGuild, m_pPlayer, pFrom->GetItem(),
pFrom->IsBank(), pFrom->GetContainer(), pFrom->GetSlotId(),
IsBank(), GetContainer(), GetSlotId());
}
inline void Guild::MoveItemData::CopySlots(SlotIds& ids) const
{
for (auto itr = m_vec.begin(); itr != m_vec.end(); ++itr)
ids.insert(uint8(itr->pos));
}
// PlayerMoveItemData
bool Guild::PlayerMoveItemData::InitItem()
{
m_pItem = m_pPlayer->GetItemByPos(m_container, m_slotId);
if (m_pItem)
{
// Anti-WPE protection. Do not move non-empty bags to bank.
if (m_pItem->IsNotEmptyBag())
{
m_pPlayer->SendEquipError(EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS, m_pItem);
m_pItem = nullptr;
}
// Bound items cannot be put into bank.
else if (!m_pItem->CanBeTraded())
{
m_pPlayer->SendEquipError(EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, m_pItem);
m_pItem = nullptr;
}
}
return (m_pItem != nullptr);
}
void Guild::PlayerMoveItemData::RemoveItem(SQLTransaction& trans, MoveItemData* /*pOther*/, uint32 splitedAmount)
{
if (splitedAmount)
{
m_pItem->SetCount(m_pItem->GetCount() - splitedAmount);
m_pItem->SetState(ITEM_CHANGED, m_pPlayer);
m_pPlayer->SaveInventoryAndGoldToDB(trans);
}
else
{
m_pPlayer->MoveItemFromInventory(m_container, m_slotId, true);
m_pItem->DeleteFromInventoryDB(trans);
m_pItem = nullptr;
}
}
Item* Guild::PlayerMoveItemData::StoreItem(SQLTransaction& trans, Item* pItem)
{
ASSERT(pItem);
m_pPlayer->MoveItemToInventory(m_vec, pItem, true);
m_pPlayer->SaveInventoryAndGoldToDB(trans);
return pItem;
}
void Guild::PlayerMoveItemData::LogBankEvent(SQLTransaction& trans, MoveItemData* pFrom, uint32 count) const
{
ASSERT(pFrom);
// Bank -> Char
m_pGuild->_LogBankEvent(trans, GUILD_BANK_LOG_WITHDRAW_ITEM, pFrom->GetContainer(), m_pPlayer->GetGUID().GetCounter(),
pFrom->GetItem()->GetEntry(), count);
}
inline InventoryResult Guild::PlayerMoveItemData::CanStore(Item* pItem, bool swap)
{
return m_pPlayer->CanStoreItem(m_container, m_slotId, m_vec, pItem, swap);
}
// BankMoveItemData
bool Guild::BankMoveItemData::InitItem()
{
m_pItem = m_pGuild->_GetItem(m_container, m_slotId);
return (m_pItem != nullptr);
}
bool Guild::BankMoveItemData::HasStoreRights(MoveItemData* pOther) const
{
ASSERT(pOther);
// Do not check rights if item is being swapped within the same bank tab
if (pOther->IsBank() && pOther->GetContainer() == m_container)
return true;
return m_pGuild->_MemberHasTabRights(m_pPlayer->GetGUID(), m_container, GUILD_BANK_RIGHT_DEPOSIT_ITEM);
}
bool Guild::BankMoveItemData::HasWithdrawRights(MoveItemData* pOther) const
{
ASSERT(pOther);
// Do not check rights if item is being swapped within the same bank tab
if (pOther->IsBank() && pOther->GetContainer() == m_container)
return true;
int32 slots = 0;
if (Member const* member = m_pGuild->GetMember(m_pPlayer->GetGUID()))
slots = m_pGuild->_GetMemberRemainingSlots(member, m_container);
return slots != 0;
}
void Guild::BankMoveItemData::RemoveItem(SQLTransaction& trans, MoveItemData* pOther, uint32 splitedAmount)
{
ASSERT(m_pItem);
if (splitedAmount)
{
m_pItem->SetCount(m_pItem->GetCount() - splitedAmount);
m_pItem->FSetState(ITEM_CHANGED);
m_pItem->SaveToDB(trans);
}
else
{
m_pGuild->_RemoveItem(trans, m_container, m_slotId);
m_pItem = nullptr;
}
// Decrease amount of player's remaining items (if item is moved to different tab or to player)
if (!pOther->IsBank() || pOther->GetContainer() != m_container)
m_pGuild->_UpdateMemberWithdrawSlots(trans, m_pPlayer->GetGUID(), m_container);
}
Item* Guild::BankMoveItemData::StoreItem(SQLTransaction& trans, Item* pItem)
{
if (!pItem)
return nullptr;
BankTab* pTab = m_pGuild->GetBankTab(m_container);
if (!pTab)
return nullptr;
Item* pLastItem = pItem;
for (auto itr = m_vec.begin(); itr != m_vec.end(); )
{
ItemPosCount pos(*itr);
++itr;
ASSERT(pItem);
TC_LOG_DEBUG("guild", "GUILD STORAGE: StoreItem tab = %u, slot = %u, item = %u, count = %u",
m_container, m_slotId, pItem->GetEntry(), pItem->GetCount());
pLastItem = _StoreItem(trans, pTab, pItem, pos, itr != m_vec.end());
}
return pLastItem;
}
void Guild::BankMoveItemData::LogBankEvent(SQLTransaction& trans, MoveItemData* pFrom, uint32 count) const
{
ASSERT(pFrom->GetItem());
if (pFrom->IsBank())
// Bank -> Bank
m_pGuild->_LogBankEvent(trans, GUILD_BANK_LOG_MOVE_ITEM, pFrom->GetContainer(), m_pPlayer->GetGUID().GetCounter(),
pFrom->GetItem()->GetEntry(), count, m_container);
else
// Char -> Bank
m_pGuild->_LogBankEvent(trans, GUILD_BANK_LOG_DEPOSIT_ITEM, m_container, m_pPlayer->GetGUID().GetCounter(),
pFrom->GetItem()->GetEntry(), count);
}
void Guild::BankMoveItemData::LogAction(MoveItemData* pFrom) const
{
MoveItemData::LogAction(pFrom);
if (!pFrom->IsBank() && m_pPlayer->GetSession()->HasPermission(rbac::RBAC_PERM_LOG_GM_TRADE)) /// @todo Move this to scripts
{
sLog->outCommand(m_pPlayer->GetSession()->GetAccountId(),
"GM %s (Guid: %u) (Account: %u) deposit item: %s (Entry: %d Count: %u) to guild bank named: %s (Guild ID: %u)",
m_pPlayer->GetName().c_str(), m_pPlayer->GetGUID().GetCounter(), m_pPlayer->GetSession()->GetAccountId(),
pFrom->GetItem()->GetTemplate()->Name1.c_str(), pFrom->GetItem()->GetEntry(), pFrom->GetItem()->GetCount(),
m_pGuild->GetName().c_str(), m_pGuild->GetId());
}
}
Item* Guild::BankMoveItemData::_StoreItem(SQLTransaction& trans, BankTab* pTab, Item* pItem, ItemPosCount& pos, bool clone) const
{
uint8 slotId = uint8(pos.pos);
uint32 count = pos.count;
if (Item* pItemDest = pTab->GetItem(slotId))
{
pItemDest->SetCount(pItemDest->GetCount() + count);
pItemDest->FSetState(ITEM_CHANGED);
pItemDest->SaveToDB(trans);
if (!clone)
{
pItem->RemoveFromWorld();
pItem->DeleteFromDB(trans);
delete pItem;
}
return pItemDest;
}
if (clone)
pItem = pItem->CloneItem(count);
else
pItem->SetCount(count);
if (pItem && pTab->SetItem(trans, slotId, pItem))
return pItem;
return nullptr;
}
// Tries to reserve space for source item.
// If item in destination slot exists it must be the item of the same entry
// and stack must have enough space to take at least one item.
// Returns false if destination item specified and it cannot be used to reserve space.
bool Guild::BankMoveItemData::_ReserveSpace(uint8 slotId, Item* pItem, Item* pItemDest, uint32& count)
{
uint32 requiredSpace = pItem->GetMaxStackCount();
if (pItemDest)
{
// Make sure source and destination items match and destination item has space for more stacks.
if (pItemDest->GetEntry() != pItem->GetEntry() || pItemDest->GetCount() >= pItem->GetMaxStackCount())
return false;
requiredSpace -= pItemDest->GetCount();
}
// Let's not be greedy, reserve only required space
requiredSpace = std::min(requiredSpace, count);
// Reserve space
ItemPosCount pos(slotId, requiredSpace);
if (!pos.isContainedIn(m_vec))
{
m_vec.push_back(pos);
count -= requiredSpace;
}
return true;
}
void Guild::BankMoveItemData::CanStoreItemInTab(Item* pItem, uint8 skipSlotId, bool merge, uint32& count)
{
for (uint8 slotId = 0; (slotId < GUILD_BANK_MAX_SLOTS) && (count > 0); ++slotId)
{
// Skip slot already processed in CanStore (when destination slot was specified)
if (slotId == skipSlotId)
continue;
Item* pItemDest = m_pGuild->_GetItem(m_container, slotId);
if (pItemDest == pItem)
pItemDest = nullptr;
// If merge skip empty, if not merge skip non-empty
if ((pItemDest != nullptr) != merge)
continue;
_ReserveSpace(slotId, pItem, pItemDest, count);
}
}
InventoryResult Guild::BankMoveItemData::CanStore(Item* pItem, bool swap)
{
TC_LOG_DEBUG("guild", "GUILD STORAGE: CanStore() tab = %u, slot = %u, item = %u, count = %u",
m_container, m_slotId, pItem->GetEntry(), pItem->GetCount());
uint32 count = pItem->GetCount();
// Soulbound items cannot be moved
if (pItem->IsSoulBound())
return EQUIP_ERR_CANT_DROP_SOULBOUND;
// Make sure destination bank tab exists
if (m_container >= m_pGuild->_GetPurchasedTabsSize())
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
// Slot explicitely specified. Check it.
if (m_slotId != NULL_SLOT)
{
Item* pItemDest = m_pGuild->_GetItem(m_container, m_slotId);
// Ignore swapped item (this slot will be empty after move)
if ((pItemDest == pItem) || swap)
pItemDest = nullptr;
if (!_ReserveSpace(m_slotId, pItem, pItemDest, count))
return EQUIP_ERR_ITEM_CANT_STACK;
if (count == 0)
return EQUIP_ERR_OK;
}
// Slot was not specified or it has not enough space for all the items in stack
// Search for stacks to merge with
if (pItem->GetMaxStackCount() > 1)
{
CanStoreItemInTab(pItem, m_slotId, true, count);
if (count == 0)
return EQUIP_ERR_OK;
}
// Search free slot for item
CanStoreItemInTab(pItem, m_slotId, false, count);
if (count == 0)
return EQUIP_ERR_OK;
return EQUIP_ERR_BANK_FULL;
}
// Guild
Guild::Guild():
m_id(0),
m_leaderGuid(),
m_createdDate(0),
m_accountsNumber(0),
m_bankMoney(0),
m_eventLog(nullptr)
{
memset(&m_bankEventLog, 0, (GUILD_BANK_MAX_TABS + 1) * sizeof(LogHolder*));
}
Guild::~Guild()
{
SQLTransaction temp(nullptr);
_DeleteBankItems(temp);
// Cleanup
delete m_eventLog;
m_eventLog = nullptr;
for (uint8 tabId = 0; tabId <= GUILD_BANK_MAX_TABS; ++tabId)
{
delete m_bankEventLog[tabId];
m_bankEventLog[tabId] = nullptr;
}
for (auto itr = m_members.begin(); itr != m_members.end(); ++itr)
{
delete itr->second;
itr->second = nullptr;
}
}
// Creates new guild with default data and saves it to database.
bool Guild::Create(Player* pLeader, std::string const& name)
{
// Check if guild with such name already exists
if (sGuildMgr->GetGuildByName(name))
return false;
WorldSession* pLeaderSession = pLeader->GetSession();
if (!pLeaderSession)
return false;
m_id = sGuildMgr->GenerateGuildId();
m_leaderGuid = pLeader->GetGUID();
m_name = name;
m_info = "";
m_motd = "No message set.";
m_bankMoney = 0;
m_createdDate = GameTime::GetGameTime();
_CreateLogHolders();
TC_LOG_DEBUG("guild", "GUILD: creating guild [%s] for leader %s (%u)",
name.c_str(), pLeader->GetName().c_str(), m_leaderGuid.GetCounter());
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBERS);
stmt->setUInt32(0, m_id);
trans->Append(stmt);
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD);
stmt->setUInt32( index, m_id);
stmt->setString(++index, name);
stmt->setUInt32(++index, m_leaderGuid.GetCounter());
stmt->setString(++index, m_info);
stmt->setString(++index, m_motd);
stmt->setUInt64(++index, uint32(m_createdDate));
stmt->setUInt32(++index, m_emblemInfo.GetStyle());
stmt->setUInt32(++index, m_emblemInfo.GetColor());
stmt->setUInt32(++index, m_emblemInfo.GetBorderStyle());
stmt->setUInt32(++index, m_emblemInfo.GetBorderColor());
stmt->setUInt32(++index, m_emblemInfo.GetBackgroundColor());
stmt->setUInt64(++index, m_bankMoney);
trans->Append(stmt);
_CreateDefaultGuildRanks(trans, pLeaderSession->GetSessionDbLocaleIndex()); // Create default ranks
bool ret = AddMember(trans, m_leaderGuid, GR_GUILDMASTER); // Add guildmaster
CharacterDatabase.CommitTransaction(trans);
if (ret)
sScriptMgr->OnGuildCreate(this, pLeader, name);
return ret;
}
// Disbands guild and deletes all related data from database
void Guild::Disband()
{
// Call scripts before guild data removed from database
sScriptMgr->OnGuildDisband(this);
_BroadcastEvent(GE_DISBANDED, ObjectGuid::Empty);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
// Remove all members
while (!m_members.empty())
{
auto itr = m_members.begin();
DeleteMember(trans, itr->second->GetGUID(), true);
}
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD);
stmt->setUInt32(0, m_id);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_RANKS);
stmt->setUInt32(0, m_id);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_TABS);
stmt->setUInt32(0, m_id);
trans->Append(stmt);
// Free bank tab used memory and delete items stored in them
_DeleteBankItems(trans, true);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_ITEMS);
stmt->setUInt32(0, m_id);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_RIGHTS);
stmt->setUInt32(0, m_id);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_EVENTLOGS);
stmt->setUInt32(0, m_id);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_EVENTLOGS);
stmt->setUInt32(0, m_id);
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
sGuildMgr->RemoveGuild(m_id);
}
void Guild::UpdateMemberData(Player* player, uint8 dataid, uint32 value)
{
if (Member* member = GetMember(player->GetGUID()))
{
switch (dataid)
{
case GUILD_MEMBER_DATA_ZONEID:
member->SetZoneID(value);
break;
case GUILD_MEMBER_DATA_LEVEL:
member->SetLevel(value);
break;
default:
TC_LOG_ERROR("guild", "Guild::UpdateMemberData: Called with incorrect DATAID %u (value %u)", dataid, value);
return;
}
//HandleRoster();
}
}
void Guild::OnPlayerStatusChange(Player* player, uint32 flag, bool state)
{
if (Member* member = GetMember(player->GetGUID()))
{
if (state)
member->AddFlag(flag);
else member->RemFlag(flag);
}
}
bool Guild::SetName(std::string const& name)
{
if (m_name == name || name.empty() || name.length() > 24 || sObjectMgr->IsReservedName(name) || !ObjectMgr::IsValidCharterName(name))
return false;
m_name = name;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_NAME);
stmt->setString(0, m_name);
stmt->setUInt32(1, GetId());
CharacterDatabase.Execute(stmt);
return true;
}
void Guild::HandleRoster(WorldSession* session)
{
// Guess size
WorldPacket data(SMSG_GUILD_ROSTER, (4 + m_motd.length() + 1 + m_info.length() + 1 + 4 + _GetRanksSize() * (4 + 4 + GUILD_BANK_MAX_TABS * (4 + 4)) + m_members.size() * 50));
data << uint32(m_members.size());
data << m_motd;
data << m_info;
data << uint32(_GetRanksSize());
for (auto ritr = m_ranks.begin(); ritr != m_ranks.end(); ++ritr)
ritr->WritePacket(data);
for (auto itr = m_members.begin(); itr != m_members.end(); ++itr)
itr->second->WritePacket(data, _HasRankRight(session->GetPlayer(), GR_RIGHT_VIEWOFFNOTE));
TC_LOG_DEBUG("guild", "SMSG_GUILD_ROSTER [%s]", session->GetPlayerInfo().c_str());
session->SendPacket(&data);
}
void Guild::HandleQuery(WorldSession* session)
{
WorldPacket data(SMSG_GUILD_QUERY_RESPONSE, 8 * 32 + 200); // Guess size
data << uint32(m_id);
data << m_name;
// Rank name
for (uint8 i = 0; i < GUILD_RANKS_MAX_COUNT; ++i) // Always show 10 ranks
{
if (i < _GetRanksSize())
data << m_ranks[i].GetName();
else
data << uint8(0); // Empty string
}
m_emblemInfo.WritePacket(data);
data << uint32(_GetRanksSize()); // Number of ranks used
session->SendPacket(&data);
TC_LOG_DEBUG("guild", "SMSG_GUILD_QUERY_RESPONSE [%s]", session->GetPlayerInfo().c_str());
}
void Guild::HandleSetMOTD(WorldSession* session, std::string const& motd)
{
if (m_motd == motd)
return;
// Player must have rights to set MOTD
if (!_HasRankRight(session->GetPlayer(), GR_RIGHT_SETMOTD))
SendCommandResult(session, GUILD_COMMAND_EDIT_MOTD, ERR_GUILD_PERMISSIONS);
else
{
m_motd = motd;
sScriptMgr->OnGuildMOTDChanged(this, motd);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MOTD);
stmt->setString(0, motd);
stmt->setUInt32(1, m_id);
CharacterDatabase.Execute(stmt);
_BroadcastEvent(GE_MOTD, ObjectGuid::Empty, motd.c_str());
}
}
void Guild::HandleSetInfo(WorldSession* session, std::string const& info)
{
if (m_info == info)
return;
// Player must have rights to set guild's info
if (_HasRankRight(session->GetPlayer(), GR_RIGHT_MODIFY_GUILD_INFO))
{
m_info = info;
sScriptMgr->OnGuildInfoChanged(this, info);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_INFO);
stmt->setString(0, info);
stmt->setUInt32(1, m_id);
CharacterDatabase.Execute(stmt);
}
}
void Guild::HandleSetEmblem(WorldSession* session, EmblemInfo const& emblemInfo)
{
Player* player = session->GetPlayer();
if (!_IsLeader(player))
SendSaveEmblemResult(session, ERR_GUILDEMBLEM_NOTGUILDMASTER); // "Only guild leaders can create emblems."
else if (!player->HasEnoughMoney(EMBLEM_PRICE))
SendSaveEmblemResult(session, ERR_GUILDEMBLEM_NOTENOUGHMONEY); // "You can't afford to do that."
else
{
player->ModifyMoney(-int32(EMBLEM_PRICE));
m_emblemInfo = emblemInfo;
m_emblemInfo.SaveToDB(m_id);
SendSaveEmblemResult(session, ERR_GUILDEMBLEM_SUCCESS); // "Guild Emblem saved."
HandleQuery(session);
}
}
void Guild::HandleSetLeader(WorldSession* session, std::string const& name)
{
Player* player = session->GetPlayer();
// Only leader can assign new leader
if (!_IsLeader(player))
SendCommandResult(session, GUILD_COMMAND_CHANGE_LEADER, ERR_GUILD_PERMISSIONS);
// Old leader must be a member of guild
else if (Member* pOldLeader = GetMember(player->GetGUID()))
{
// New leader must be a member of guild
if (Member* pNewLeader = GetMember(name))
{
_SetLeaderGUID(pNewLeader);
SQLTransaction trans(nullptr);
pOldLeader->ChangeRank(trans, GR_OFFICER);
_BroadcastEvent(GE_LEADER_CHANGED, ObjectGuid::Empty, player->GetName().c_str(), name.c_str());
}
}
}
void Guild::HandleSetBankTabInfo(WorldSession* session, uint8 tabId, std::string const& name, std::string const& icon)
{
BankTab* tab = GetBankTab(tabId);
if (!tab)
{
TC_LOG_ERROR("guild", "Guild::HandleSetBankTabInfo: Player %s trying to change bank tab info from unexisting tab %d.",
session->GetPlayerInfo().c_str(), tabId);
return;
}
tab->SetInfo(name, icon);
_BroadcastEvent(GE_BANK_TAB_UPDATED, ObjectGuid::Empty, std::to_string(tabId).c_str(), name.c_str(), icon.c_str());
}
void Guild::HandleSetMemberNote(WorldSession* session, std::string const& name, std::string const& note, bool officer)
{
// Player must have rights to set public/officer note
if (!_HasRankRight(session->GetPlayer(), officer ? GR_RIGHT_EOFFNOTE : GR_RIGHT_EPNOTE))
SendCommandResult(session, GUILD_COMMAND_PUBLIC_NOTE, ERR_GUILD_PERMISSIONS);
else if (Member* member = GetMember(name))
{
if (officer)
member->SetOfficerNote(note);
else
member->SetPublicNote(note);
HandleRoster(session);
}
}
void Guild::HandleSetRankInfo(WorldSession* session, uint8 rankId, std::string const& name, uint32 rights, uint32 moneyPerDay, GuildBankRightsAndSlotsVec const& rightsAndSlots)
{
// Only leader can modify ranks
if (!_IsLeader(session->GetPlayer()))
SendCommandResult(session, GUILD_COMMAND_CHANGE_RANK, ERR_GUILD_PERMISSIONS);
else if (RankInfo* rankInfo = GetRankInfo(rankId))
{
TC_LOG_DEBUG("guild", "Changed RankName to '%s', rights to 0x%08X", name.c_str(), rights);
rankInfo->SetName(name);
rankInfo->SetRights(rights);
_SetRankBankMoneyPerDay(rankId, moneyPerDay);
for (auto itr = rightsAndSlots.begin(); itr != rightsAndSlots.end(); ++itr)
_SetRankBankTabRightsAndSlots(rankId, *itr);
_BroadcastEvent(GE_RANK_UPDATED, ObjectGuid::Empty, std::to_string(rankId).c_str(), name.c_str());
}
}
void Guild::HandleBuyBankTab(WorldSession* session, uint8 tabId)
{
Player* player = session->GetPlayer();
if (!player)
return;
Member const* member = GetMember(player->GetGUID());
if (!member)
return;
if (_GetPurchasedTabsSize() >= GUILD_BANK_MAX_TABS)
return;
if (tabId != _GetPurchasedTabsSize())
return;
if (tabId >= GUILD_BANK_MAX_TABS)
return;
uint32 tabCost = GetGuildBankTabPrice(tabId) * GOLD;
if (!player->HasEnoughMoney(tabCost)) // Should not happen, this is checked by client
return;
player->ModifyMoney(-int32(tabCost));
_CreateNewBankTab();
_BroadcastEvent(GE_BANK_TAB_PURCHASED, ObjectGuid::Empty);
SendPermissions(session); /// Hack to force client to update permissions
}
void Guild::HandleInviteMember(WorldSession* session, std::string const& name)
{
Player* pInvitee = ObjectAccessor::FindPlayerByName(name);
if (!pInvitee)
{
SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_GUILD_PLAYER_NOT_FOUND_S, name);
return;
}
Player* player = session->GetPlayer();
// Do not show invitations from ignored players
if (pInvitee->GetSocial()->HasIgnore(player->GetGUID()))
return;
if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD) && pInvitee->GetTeam() != player->GetTeam())
{
SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_GUILD_NOT_ALLIED, name);
return;
}
// Invited player cannot be in another guild
if (pInvitee->GetGuildId())
{
SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_ALREADY_IN_GUILD_S, name);
return;
}
// Invited player cannot be invited
if (pInvitee->GetGuildIdInvited())
{
SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_ALREADY_INVITED_TO_GUILD_S, name);
return;
}
// Inviting player must have rights to invite
if (!_HasRankRight(player, GR_RIGHT_INVITE))
{
SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_GUILD_PERMISSIONS);
return;
}
SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_GUILD_COMMAND_SUCCESS, name);
TC_LOG_DEBUG("guild", "Player %s invited %s to join his Guild", player->GetName().c_str(), name.c_str());
pInvitee->SetGuildIdInvited(m_id);
_LogEvent(GUILD_EVENT_LOG_INVITE_PLAYER, player->GetGUID().GetCounter(), pInvitee->GetGUID().GetCounter());
WorldPacket data(SMSG_GUILD_INVITE, 8 + 10); // Guess size
data << player->GetName();
data << m_name;
pInvitee->SendDirectMessage(&data);
TC_LOG_DEBUG("guild", "SMSG_GUILD_INVITE [%s]", pInvitee->GetName().c_str());
}
void Guild::HandleAcceptMember(WorldSession* session)
{
Player* player = session->GetPlayer();
if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD) &&
player->GetTeam() != sCharacterCache->GetCharacterTeamByGuid(GetLeaderGUID()))
return;
SQLTransaction trans(nullptr);
AddMember(trans, player->GetGUID());
}
void Guild::HandleLeaveMember(WorldSession* session)
{
Player* player = session->GetPlayer();
bool disband = false;
// If leader is leaving
if (_IsLeader(player))
{
if (m_members.size() > 1)
// Leader cannot leave if he is not the last member
SendCommandResult(session, GUILD_COMMAND_QUIT, ERR_GUILD_LEADER_LEAVE);
else
{
// Guild is disbanded if leader leaves.
Disband();
disband = true;
}
}
else
{
SQLTransaction trans(nullptr);
DeleteMember(trans, player->GetGUID(), false, false);
_LogEvent(GUILD_EVENT_LOG_LEAVE_GUILD, player->GetGUID().GetCounter());
_BroadcastEvent(GE_LEFT, player->GetGUID(), player->GetName().c_str());
SendCommandResult(session, GUILD_COMMAND_QUIT, ERR_GUILD_COMMAND_SUCCESS, m_name);
}
sCalendarMgr->RemovePlayerGuildEventsAndSignups(player->GetGUID(), GetId());
if (disband)
delete this;
}
void Guild::HandleRemoveMember(WorldSession* session, std::string const& name)
{
Player* player = session->GetPlayer();
// Player must have rights to remove members
if (!_HasRankRight(player, GR_RIGHT_REMOVE))
SendCommandResult(session, GUILD_COMMAND_REMOVE, ERR_GUILD_PERMISSIONS);
else if (Member* member = GetMember(name))
{
// Guild masters cannot be removed
if (member->IsRank(GR_GUILDMASTER))
SendCommandResult(session, GUILD_COMMAND_REMOVE, ERR_GUILD_LEADER_LEAVE);
// Do not allow to remove player with the same rank or higher
else
{
Member const* memberMe = GetMember(player->GetGUID());
if (!memberMe || member->IsRankNotLower(memberMe->GetRankId()))
SendCommandResult(session, GUILD_COMMAND_REMOVE, ERR_GUILD_RANK_TOO_HIGH_S, name);
else
{
ObjectGuid guid = member->GetGUID();
// After call to DeleteMember pointer to member becomes invalid
SQLTransaction trans(nullptr);
DeleteMember(trans, guid, false, true);
_LogEvent(GUILD_EVENT_LOG_UNINVITE_PLAYER, player->GetGUID().GetCounter(), guid.GetCounter());
_BroadcastEvent(GE_REMOVED, ObjectGuid::Empty, name.c_str(), player->GetName().c_str());
}
}
}
}
void Guild::HandleUpdateMemberRank(WorldSession* session, std::string const& name, bool demote)
{
Player* player = session->GetPlayer();
GuildCommandType type = demote ? GUILD_COMMAND_DEMOTE : GUILD_COMMAND_PROMOTE;
// Player must have rights to promote
if (!_HasRankRight(player, demote ? GR_RIGHT_DEMOTE : GR_RIGHT_PROMOTE))
SendCommandResult(session, type, ERR_GUILD_PERMISSIONS);
// Promoted player must be a member of guild
else if (Member* member = GetMember(name))
{
// Player cannot promote himself
if (member->IsSamePlayer(player->GetGUID()))
{
SendCommandResult(session, type, ERR_GUILD_NAME_INVALID);
return;
}
Member const* memberMe = GetMember(player->GetGUID());
ASSERT(memberMe);
uint8 rankId = memberMe->GetRankId();
if (demote)
{
// Player can demote only lower rank members
if (member->IsRankNotLower(rankId))
{
SendCommandResult(session, type, ERR_GUILD_RANK_TOO_HIGH_S, name);
return;
}
// Lowest rank cannot be demoted
if (member->GetRankId() >= _GetLowestRankId())
{
SendCommandResult(session, type, ERR_GUILD_RANK_TOO_LOW_S, name);
return;
}
}
else
{
// Allow to promote only to lower rank than member's rank
// member->GetRankId() + 1 is the highest rank that current player can promote to
if (member->IsRankNotLower(rankId + 1))
{
SendCommandResult(session, type, ERR_GUILD_RANK_TOO_HIGH_S, name);
return;
}
}
uint32 newRankId = member->GetRankId() + (demote ? 1 : -1);
SQLTransaction trans(nullptr);
member->ChangeRank(trans, newRankId);
_LogEvent(demote ? GUILD_EVENT_LOG_DEMOTE_PLAYER : GUILD_EVENT_LOG_PROMOTE_PLAYER, player->GetGUID().GetCounter(), member->GetGUID().GetCounter(), newRankId);
_BroadcastEvent(demote ? GE_DEMOTION : GE_PROMOTION, ObjectGuid::Empty, player->GetName().c_str(), name.c_str(), _GetRankName(newRankId).c_str());
}
}
void Guild::HandleAddNewRank(WorldSession* session, std::string const& name)
{
uint8 size = _GetRanksSize();
if (size >= GUILD_RANKS_MAX_COUNT)
return;
// Only leader can add new rank
if (_IsLeader(session->GetPlayer()))
{
SQLTransaction trans(nullptr);
if (_CreateRank(trans, name, GR_RIGHT_GCHATLISTEN | GR_RIGHT_GCHATSPEAK))
_BroadcastEvent(GE_RANK_UPDATED, ObjectGuid::Empty, std::to_string(size).c_str(), name.c_str());
}
}
void Guild::HandleRemoveLowestRank(WorldSession* session)
{
HandleRemoveRank(session, _GetLowestRankId());
}
void Guild::HandleRemoveRank(WorldSession* session, uint8 rankId)
{
// Cannot remove rank if total count is minimum allowed by the client or is not leader
if (_GetRanksSize() <= GUILD_RANKS_MIN_COUNT || rankId >= _GetRanksSize() || !_IsLeader(session->GetPlayer()))
return;
// Delete bank rights for rank
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_RIGHTS_FOR_RANK);
stmt->setUInt32(0, m_id);
stmt->setUInt8(1, rankId);
CharacterDatabase.Execute(stmt);
// Delete rank
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_LOWEST_RANK);
stmt->setUInt32(0, m_id);
stmt->setUInt8(1, rankId);
CharacterDatabase.Execute(stmt);
m_ranks.pop_back();
_BroadcastEvent(GE_RANK_DELETED, ObjectGuid::Empty, std::to_string(rankId).c_str());
}
void Guild::HandleMemberDepositMoney(WorldSession* session, uint32 amount)
{
Player* player = session->GetPlayer();
// Call script after validation and before money transfer.
sScriptMgr->OnGuildMemberDepositMoney(this, player, amount);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
_ModifyBankMoney(trans, amount, true);
player->ModifyMoney(-int32(amount));
player->SaveGoldToDB(trans);
_LogBankEvent(trans, GUILD_BANK_LOG_DEPOSIT_MONEY, uint8(0), player->GetGUID().GetCounter(), amount);
CharacterDatabase.CommitTransaction(trans);
std::string aux = ByteArrayToHexStr(reinterpret_cast<uint8*>(&m_bankMoney), 8, true);
_BroadcastEvent(GE_BANK_MONEY_SET, ObjectGuid::Empty, aux.c_str());
if (player->GetSession()->HasPermission(rbac::RBAC_PERM_LOG_GM_TRADE))
{
sLog->outCommand(player->GetSession()->GetAccountId(),
"GM %s (Account: %u) deposit money (Amount: %u) to guild bank (Guild ID %u)",
player->GetName().c_str(), player->GetSession()->GetAccountId(), amount, m_id);
}
}
bool Guild::HandleMemberWithdrawMoney(WorldSession* session, uint32 amount, bool repair)
{
//clamp amount to MAX_MONEY_AMOUNT, Players can't hold more than that anyway
amount = std::min(amount, MAX_MONEY_AMOUNT);
if (m_bankMoney < amount) // Not enough money in bank
return false;
Player* player = session->GetPlayer();
Member* member = GetMember(player->GetGUID());
if (!member)
return false;
if (uint32(_GetMemberRemainingMoney(member)) < amount) // Check if we have enough slot/money today
return false;
// Call script after validation and before money transfer.
sScriptMgr->OnGuildMemberWitdrawMoney(this, player, amount, repair);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
// Add money to player (if required)
if (!repair)
{
if (!player->ModifyMoney(amount))
return false;
player->SaveGoldToDB(trans);
}
// Update remaining money amount
member->UpdateBankWithdrawValue(trans, GUILD_BANK_MAX_TABS, amount);
// Remove money from bank
_ModifyBankMoney(trans, amount, false);
// Log guild bank event
_LogBankEvent(trans, repair ? GUILD_BANK_LOG_REPAIR_MONEY : GUILD_BANK_LOG_WITHDRAW_MONEY, uint8(0), player->GetGUID().GetCounter(), amount);
CharacterDatabase.CommitTransaction(trans);
std::string aux = ByteArrayToHexStr(reinterpret_cast<uint8*>(&m_bankMoney), 8, true);
_BroadcastEvent(GE_BANK_MONEY_SET, ObjectGuid::Empty, aux.c_str());
return true;
}
void Guild::HandleMemberLogout(WorldSession* session)
{
Player* player = session->GetPlayer();
if (Member* member = GetMember(player->GetGUID()))
{
member->SetStats(player);
member->UpdateLogoutTime();
member->ResetFlags();
}
_BroadcastEvent(GE_SIGNED_OFF, player->GetGUID(), player->GetName().c_str());
}
void Guild::HandleDisband(WorldSession* session)
{
// Only leader can disband guild
if (_IsLeader(session->GetPlayer()))
{
Disband();
TC_LOG_DEBUG("guild", "Guild Successfully Disbanded");
delete this;
}
}
// Send data to client
void Guild::SendInfo(WorldSession* session) const
{
WorldPacket data(SMSG_GUILD_INFO, m_name.size() + 4 + 4 + 4);
data << m_name;
data.AppendPackedTime(m_createdDate); // 3.x (prev. year + month + day)
data << uint32(m_members.size()); // Number of members
data << m_accountsNumber; // Number of accounts
session->SendPacket(&data);
TC_LOG_DEBUG("guild", "SMSG_GUILD_INFO [%s]", session->GetPlayerInfo().c_str());
}
void Guild::SendEventLog(WorldSession* session) const
{
WorldPacket data(MSG_GUILD_EVENT_LOG_QUERY, 1 + m_eventLog->GetSize() * (1 + 8 + 4));
m_eventLog->WritePacket(data);
session->SendPacket(&data);
TC_LOG_DEBUG("guild", "MSG_GUILD_EVENT_LOG_QUERY [%s]", session->GetPlayerInfo().c_str());
}
void Guild::SendBankLog(WorldSession* session, uint8 tabId) const
{
// GUILD_BANK_MAX_TABS send by client for money log
if (tabId < _GetPurchasedTabsSize() || tabId == GUILD_BANK_MAX_TABS)
{
LogHolder const* pLog = m_bankEventLog[tabId];
WorldPacket data(MSG_GUILD_BANK_LOG_QUERY, pLog->GetSize() * (4 * 4 + 1) + 1 + 1);
data << uint8(tabId);
pLog->WritePacket(data);
session->SendPacket(&data);
TC_LOG_DEBUG("guild", "MSG_GUILD_BANK_LOG_QUERY [%s]", session->GetPlayerInfo().c_str());
}
}
void Guild::SendBankTabData(WorldSession* session, uint8 tabId) const
{
if (tabId < _GetPurchasedTabsSize())
_SendBankContent(session, tabId);
}
void Guild::SendBankTabsInfo(WorldSession* session, bool sendAllSlots /*= false*/) const
{
_SendBankList(session, 0, sendAllSlots);
}
void Guild::SendBankTabText(WorldSession* session, uint8 tabId) const
{
if (BankTab const* tab = GetBankTab(tabId))
tab->SendText(this, session);
}
void Guild::SendPermissions(WorldSession* session) const
{
Member const* member = GetMember(session->GetPlayer()->GetGUID());
if (!member)
return;
uint8 rankId = member->GetRankId();
WorldPacket data(MSG_GUILD_PERMISSIONS, 4 * 15 + 1);
data << uint32(rankId);
data << uint32(_GetRankRights(rankId));
data << uint32(_GetMemberRemainingMoney(member));
data << uint8(_GetPurchasedTabsSize());
for (uint8 tabId = 0; tabId < GUILD_BANK_MAX_TABS; ++tabId)
{
data << uint32(_GetRankBankTabRights(rankId, tabId));
data << uint32(_GetMemberRemainingSlots(member, tabId));
}
session->SendPacket(&data);
TC_LOG_DEBUG("guild", "MSG_GUILD_PERMISSIONS [%s] Rank: %u", session->GetPlayerInfo().c_str(), rankId);
}
void Guild::SendMoneyInfo(WorldSession* session) const
{
Member const* member = GetMember(session->GetPlayer()->GetGUID());
if (!member)
return;
int32 amount = _GetMemberRemainingMoney(member);
WorldPacket data(MSG_GUILD_BANK_MONEY_WITHDRAWN, 4);
data << int32(amount);
session->SendPacket(&data);
TC_LOG_DEBUG("guild", "MSG_GUILD_BANK_MONEY_WITHDRAWN [%s] Money: %u", session->GetPlayerInfo().c_str(), amount);
}
void Guild::SendLoginInfo(WorldSession* session)
{
WorldPacket data(SMSG_GUILD_EVENT, 1 + 1 + m_motd.size() + 1);
data << uint8(GE_MOTD);
data << uint8(1);
data << m_motd;
session->SendPacket(&data);
TC_LOG_DEBUG("guild", "SMSG_GUILD_EVENT [%s] MOTD", session->GetPlayerInfo().c_str());
SendBankTabsInfo(session);
Player* player = session->GetPlayer();
HandleRoster(session);
_BroadcastEvent(GE_SIGNED_ON, player->GetGUID(), player->GetName().c_str());
if (Member* member = GetMember(player->GetGUID()))
{
member->SetStats(player);
member->AddFlag(GUILDMEMBER_STATUS_ONLINE);
}
}
// Loading methods
bool Guild::LoadFromDB(Field* fields)
{
m_id = fields[0].GetUInt32();
m_name = fields[1].GetString();
m_leaderGuid = ObjectGuid(HighGuid::Player, fields[2].GetUInt32());
m_emblemInfo.LoadFromDB(fields);
m_info = fields[8].GetString();
m_motd = fields[9].GetString();
m_createdDate = time_t(fields[10].GetUInt32());
m_bankMoney = fields[11].GetUInt64();
uint8 purchasedTabs = uint8(fields[12].GetUInt64());
if (purchasedTabs > GUILD_BANK_MAX_TABS)
purchasedTabs = GUILD_BANK_MAX_TABS;
m_bankTabs.resize(purchasedTabs);
for (uint8 i = 0; i < purchasedTabs; ++i)
m_bankTabs[i] = new BankTab(m_id, i);
_CreateLogHolders();
return true;
}
void Guild::LoadRankFromDB(Field* fields)
{
RankInfo rankInfo(m_id);
rankInfo.LoadFromDB(fields);
m_ranks.push_back(rankInfo);
}
bool Guild::LoadMemberFromDB(Field* fields)
{
ObjectGuid::LowType lowguid = fields[1].GetUInt32();
ObjectGuid playerGuid(HighGuid::Player, lowguid);
Member* member = new Member(m_id, playerGuid, fields[2].GetUInt8());
if (!member->LoadFromDB(fields))
{
SQLTransaction trans(nullptr);
_DeleteMemberFromDB(trans, lowguid);
delete member;
return false;
}
sCharacterCache->UpdateCharacterGuildId(playerGuid, GetId());
m_members[lowguid] = member;
return true;
}
void Guild::LoadBankRightFromDB(Field* fields)
{
// tabId rights slots
GuildBankRightsAndSlots rightsAndSlots(fields[1].GetUInt8(), fields[3].GetUInt8(), fields[4].GetUInt32());
// rankId
_SetRankBankTabRightsAndSlots(fields[2].GetUInt8(), rightsAndSlots, false);
}
bool Guild::LoadEventLogFromDB(Field* fields)
{
if (m_eventLog->CanInsert())
{
m_eventLog->LoadEvent(new EventLogEntry(
m_id, // guild id
fields[1].GetUInt32(), // guid
time_t(fields[6].GetUInt32()), // timestamp
GuildEventLogTypes(fields[2].GetUInt8()), // event type
fields[3].GetUInt32(), // player guid 1
fields[4].GetUInt32(), // player guid 2
fields[5].GetUInt8())); // rank
return true;
}
return false;
}
bool Guild::LoadBankEventLogFromDB(Field* fields)
{
uint8 dbTabId = fields[1].GetUInt8();
bool isMoneyTab = (dbTabId == GUILD_BANK_MONEY_LOGS_TAB);
if (dbTabId < _GetPurchasedTabsSize() || isMoneyTab)
{
uint8 tabId = isMoneyTab ? uint8(GUILD_BANK_MAX_TABS) : dbTabId;
LogHolder* pLog = m_bankEventLog[tabId];
if (pLog->CanInsert())
{
ObjectGuid::LowType guid = fields[2].GetUInt32();
GuildBankEventLogTypes eventType = GuildBankEventLogTypes(fields[3].GetUInt8());
if (BankEventLogEntry::IsMoneyEvent(eventType))
{
if (!isMoneyTab)
{
TC_LOG_ERROR("guild", "GuildBankEventLog ERROR: MoneyEvent(LogGuid: %u, Guild: %u) does not belong to money tab (%u), ignoring...", guid, m_id, dbTabId);
return false;
}
}
else if (isMoneyTab)
{
TC_LOG_ERROR("guild", "GuildBankEventLog ERROR: non-money event (LogGuid: %u, Guild: %u) belongs to money tab, ignoring...", guid, m_id);
return false;
}
pLog->LoadEvent(new BankEventLogEntry(
m_id, // guild id
guid, // guid
time_t(fields[8].GetUInt32()), // timestamp
dbTabId, // tab id
eventType, // event type
fields[4].GetUInt32(), // player guid
fields[5].GetUInt32(), // item or money
fields[6].GetUInt16(), // itam stack count
fields[7].GetUInt8())); // dest tab id
}
}
return true;
}
void Guild::LoadBankTabFromDB(Field* fields)
{
uint8 tabId = fields[1].GetUInt8();
if (tabId >= _GetPurchasedTabsSize())
TC_LOG_ERROR("guild", "Invalid tab (tabId: %u) in guild bank, skipped.", tabId);
else
m_bankTabs[tabId]->LoadFromDB(fields);
}
bool Guild::LoadBankItemFromDB(Field* fields)
{
uint8 tabId = fields[12].GetUInt8();
if (tabId >= _GetPurchasedTabsSize())
{
TC_LOG_ERROR("guild", "Invalid tab for item (GUID: %u, id: #%u) in guild bank, skipped.",
fields[14].GetUInt32(), fields[15].GetUInt32());
return false;
}
return m_bankTabs[tabId]->LoadItemFromDB(fields);
}
// Validates guild data loaded from database. Returns false if guild should be deleted.
bool Guild::Validate()
{
// Validate ranks data
// GUILD RANKS represent a sequence starting from 0 = GUILD_MASTER (ALL PRIVILEGES) to max 9 (lowest privileges).
// The lower rank id is considered higher rank - so promotion does rank-- and demotion does rank++
// Between ranks in sequence cannot be gaps - so 0, 1, 2, 4 is impossible
// Min ranks count is 5 and max is 10.
bool broken_ranks = false;
uint8 ranks = _GetRanksSize();
SQLTransaction trans = CharacterDatabase.BeginTransaction();
if (ranks < GUILD_RANKS_MIN_COUNT || ranks > GUILD_RANKS_MAX_COUNT)
{
TC_LOG_ERROR("guild", "Guild %u has invalid number of ranks, creating new...", m_id);
broken_ranks = true;
}
else
{
for (uint8 rankId = 0; rankId < ranks; ++rankId)
{
RankInfo* rankInfo = GetRankInfo(rankId);
if (rankInfo->GetId() != rankId)
{
TC_LOG_ERROR("guild", "Guild %u has broken rank id %u, creating default set of ranks...", m_id, rankId);
broken_ranks = true;
}
else
rankInfo->CreateMissingTabsIfNeeded(_GetPurchasedTabsSize(), trans, true);
}
}
if (broken_ranks)
{
m_ranks.clear();
_CreateDefaultGuildRanks(trans, DEFAULT_LOCALE);
}
// Validate members' data
for (auto itr = m_members.begin(); itr != m_members.end(); ++itr)
if (itr->second->GetRankId() > _GetRanksSize())
itr->second->ChangeRank(trans, _GetLowestRankId());
// Repair the structure of the guild.
// If the guildmaster doesn't exist or isn't member of the guild
// attempt to promote another member.
Member* pLeader = GetMember(m_leaderGuid);
if (!pLeader)
{
SQLTransaction dummy(nullptr);
DeleteMember(dummy, m_leaderGuid);
// If no more members left, disband guild
if (m_members.empty())
{
Disband();
return false;
}
}
else if (!pLeader->IsRank(GR_GUILDMASTER))
_SetLeaderGUID(pLeader);
// Check config if multiple guildmasters are allowed
if (!sConfigMgr->GetBoolDefault("Guild.AllowMultipleGuildMaster", 0))
for (auto itr = m_members.begin(); itr != m_members.end(); ++itr)
if (itr->second->GetRankId() == GR_GUILDMASTER && !itr->second->IsSamePlayer(m_leaderGuid))
itr->second->ChangeRank(trans, GR_OFFICER);
if (trans->GetSize() > 0)
CharacterDatabase.CommitTransaction(trans);
_UpdateAccountsNumber();
return true;
}
// Broadcasts
void Guild::BroadcastToGuild(WorldSession* session, bool officerOnly, std::string const& msg, uint32 language) const
{
if (session && session->GetPlayer() && _HasRankRight(session->GetPlayer(), officerOnly ? GR_RIGHT_OFFCHATSPEAK : GR_RIGHT_GCHATSPEAK))
{
WorldPacket data;
ChatHandler::BuildChatPacket(data, officerOnly ? CHAT_MSG_OFFICER : CHAT_MSG_GUILD, Language(language), session->GetPlayer(), nullptr, msg);
for (auto itr = m_members.begin(); itr != m_members.end(); ++itr)
if (Player* player = itr->second->FindConnectedPlayer())
if (player->GetSession() && _HasRankRight(player, officerOnly ? GR_RIGHT_OFFCHATLISTEN : GR_RIGHT_GCHATLISTEN) &&
!player->GetSocial()->HasIgnore(session->GetPlayer()->GetGUID()))
player->SendDirectMessage(&data);
}
}
void Guild::BroadcastPacketToRank(WorldPacket* packet, uint8 rankId) const
{
for (auto itr = m_members.begin(); itr != m_members.end(); ++itr)
if (itr->second->IsRank(rankId))
if (Player* player = itr->second->FindConnectedPlayer())
player->SendDirectMessage(packet);
}
void Guild::BroadcastPacket(WorldPacket* packet) const
{
for (auto itr = m_members.begin(); itr != m_members.end(); ++itr)
if (Player* player = itr->second->FindPlayer())
player->SendDirectMessage(packet);
}
void Guild::MassInviteToEvent(WorldSession* session, uint32 minLevel, uint32 maxLevel, uint32 minRank)
{
uint32 count = 0;
WorldPacket data(SMSG_CALENDAR_FILTER_GUILD);
data << uint32(count); // count placeholder
for (auto itr = m_members.begin(); itr != m_members.end(); ++itr)
{
// not sure if needed, maybe client checks it as well
if (count >= CALENDAR_MAX_INVITES)
{
if (Player* player = session->GetPlayer())
sCalendarMgr->SendCalendarCommandResult(player->GetGUID(), CALENDAR_ERROR_INVITES_EXCEEDED);
return;
}
Member* member = itr->second;
uint32 level = sCharacterCache->GetCharacterLevelByGuid(member->GetGUID());
if (member->GetGUID() != session->GetPlayer()->GetGUID() && level >= minLevel && level <= maxLevel && member->IsRankNotLower(minRank))
{
data.appendPackGUID(member->GetGUID().GetRawValue());
data << uint8(0); // unk
++count;
}
}
data.put<uint32>(0, count);
session->SendPacket(&data);
}
// Members handling
bool Guild::AddMember(SQLTransaction& trans, ObjectGuid guid, uint8 rankId)
{
Player* player = ObjectAccessor::FindConnectedPlayer(guid);
// Player cannot be in guild
if (player)
{
if (player->GetGuildId() != 0)
return false;
}
else if (sCharacterCache->GetCharacterGuildIdByGuid(guid) != 0)
return false;
// Remove all player signs from another petitions
// This will be prevent attempt to join many guilds and corrupt guild data integrity
Player::RemovePetitionsAndSigns(guid, GUILD_CHARTER_TYPE);
ObjectGuid::LowType lowguid = guid.GetCounter();
// If rank was not passed, assign lowest possible rank
if (rankId == GUILD_RANK_NONE)
rankId = _GetLowestRankId();
Member* member = new Member(m_id, guid, rankId);
std::string name;
if (player)
{
m_members[lowguid] = member;
player->SetInGuild(m_id);
player->SetGuildIdInvited(0);
player->SetRank(rankId);
member->SetStats(player);
SendLoginInfo(player->GetSession());
name = player->GetName();
}
else
{
member->ResetFlags();
bool ok = false;
// Player must exist
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_DATA_FOR_GUILD);
stmt->setUInt32(0, lowguid);
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
{
Field* fields = result->Fetch();
name = fields[0].GetString();
member->SetStats(
name,
fields[1].GetUInt8(),
fields[2].GetUInt8(),
fields[3].GetUInt8(),
fields[4].GetUInt16(),
fields[5].GetUInt32());
ok = member->CheckStats();
}
if (!ok)
{
delete member;
return false;
}
m_members[lowguid] = member;
sCharacterCache->UpdateCharacterGuildId(guid, GetId());
}
member->SaveToDB(trans);
_UpdateAccountsNumber();
_LogEvent(GUILD_EVENT_LOG_JOIN_GUILD, lowguid);
_BroadcastEvent(GE_JOINED, guid, name.c_str());
// Call scripts if member was succesfully added (and stored to database)
sScriptMgr->OnGuildAddMember(this, player, rankId);
return true;
}
void Guild::DeleteMember(SQLTransaction& trans, ObjectGuid guid, bool isDisbanding, bool isKicked, bool canDeleteGuild)
{
ObjectGuid::LowType lowguid = guid.GetCounter();
Player* player = ObjectAccessor::FindConnectedPlayer(guid);
// Guild master can be deleted when loading guild and guid doesn't exist in characters table
// or when he is removed from guild by gm command
if (m_leaderGuid == guid && !isDisbanding)
{
Member* oldLeader = nullptr;
Member* newLeader = nullptr;
for (auto i = m_members.begin(); i != m_members.end(); ++i)
{
if (i->first == lowguid)
oldLeader = i->second;
else if (!newLeader || newLeader->GetRankId() > i->second->GetRankId())
newLeader = i->second;
}
if (!newLeader)
{
Disband();
if (canDeleteGuild)
delete this;
return;
}
_SetLeaderGUID(newLeader);
// If player not online data in data field will be loaded from guild tabs no need to update it !!
if (Player* newLeaderPlayer = newLeader->FindPlayer())
newLeaderPlayer->SetRank(GR_GUILDMASTER);
// If leader does not exist (at guild loading with deleted leader) do not send broadcasts
if (oldLeader)
{
_BroadcastEvent(GE_LEADER_CHANGED, ObjectGuid::Empty, oldLeader->GetName().c_str(), newLeader->GetName().c_str());
_BroadcastEvent(GE_LEFT, guid, oldLeader->GetName().c_str());
}
}
// Call script on remove before member is actually removed from guild (and database)
sScriptMgr->OnGuildRemoveMember(this, player, isDisbanding, isKicked);
if (Member* member = GetMember(guid))
delete member;
m_members.erase(lowguid);
// If player not online data in data field will be loaded from guild tabs no need to update it !!
if (player)
{
player->SetInGuild(0);
player->SetRank(0);
}
else
sCharacterCache->UpdateCharacterGuildId(guid, 0);
_DeleteMemberFromDB(trans, lowguid);
if (!isDisbanding)
_UpdateAccountsNumber();
}
bool Guild::ChangeMemberRank(SQLTransaction& trans, ObjectGuid guid, uint8 newRank)
{
if (newRank <= _GetLowestRankId()) // Validate rank (allow only existing ranks)
{
if (Member* member = GetMember(guid))
{
member->ChangeRank(trans, newRank);
return true;
}
}
return false;
}
// Bank (items move)
void Guild::SwapItems(Player* player, uint8 tabId, uint8 slotId, uint8 destTabId, uint8 destSlotId, uint32 splitedAmount)
{
if (tabId >= _GetPurchasedTabsSize() || slotId >= GUILD_BANK_MAX_SLOTS ||
destTabId >= _GetPurchasedTabsSize() || destSlotId >= GUILD_BANK_MAX_SLOTS)
return;
if (tabId == destTabId && slotId == destSlotId)
return;
BankMoveItemData from(this, player, tabId, slotId);
BankMoveItemData to(this, player, destTabId, destSlotId);
_MoveItems(&from, &to, splitedAmount);
}
void Guild::SwapItemsWithInventory(Player* player, bool toChar, uint8 tabId, uint8 slotId, uint8 playerBag, uint8 playerSlotId, uint32 splitedAmount)
{
if ((slotId >= GUILD_BANK_MAX_SLOTS && slotId != NULL_SLOT) || tabId >= _GetPurchasedTabsSize())
return;
BankMoveItemData bankData(this, player, tabId, slotId);
PlayerMoveItemData charData(this, player, playerBag, playerSlotId);
if (toChar)
_MoveItems(&bankData, &charData, splitedAmount);
else
_MoveItems(&charData, &bankData, splitedAmount);
}
// Bank tabs
void Guild::SetBankTabText(uint8 tabId, std::string const& text)
{
if (BankTab* pTab = GetBankTab(tabId))
{
pTab->SetText(text);
pTab->SendText(this, nullptr);
}
}
bool Guild::_HasRankRight(Player* player, uint32 right) const
{
if (player)
if (Member const* member = GetMember(player->GetGUID()))
return (_GetRankRights(member->GetRankId()) & right) != GR_RIGHT_EMPTY;
return false;
}
void Guild::_DeleteMemberFromDB(SQLTransaction& trans, ObjectGuid::LowType lowguid)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBER);
stmt->setUInt32(0, lowguid);
CharacterDatabase.ExecuteOrAppend(trans, stmt);
}
// Private methods
void Guild::_CreateLogHolders()
{
m_eventLog = new LogHolder(sWorld->getIntConfig(CONFIG_GUILD_EVENT_LOG_COUNT));
for (uint8 tabId = 0; tabId <= GUILD_BANK_MAX_TABS; ++tabId)
m_bankEventLog[tabId] = new LogHolder(sWorld->getIntConfig(CONFIG_GUILD_BANK_EVENT_LOG_COUNT));
}
void Guild::_CreateNewBankTab()
{
uint8 tabId = _GetPurchasedTabsSize(); // Next free id
m_bankTabs.push_back(new BankTab(m_id, tabId));
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_TAB);
stmt->setUInt32(0, m_id);
stmt->setUInt8 (1, tabId);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_TAB);
stmt->setUInt32(0, m_id);
stmt->setUInt8 (1, tabId);
trans->Append(stmt);
++tabId;
for (auto itr = m_ranks.begin(); itr != m_ranks.end(); ++itr)
(*itr).CreateMissingTabsIfNeeded(tabId, trans, false);
CharacterDatabase.CommitTransaction(trans);
}
void Guild::_CreateDefaultGuildRanks(SQLTransaction& trans, LocaleConstant loc)
{
ASSERT(trans);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_RANKS);
stmt->setUInt32(0, m_id);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_RIGHTS);
stmt->setUInt32(0, m_id);
trans->Append(stmt);
_CreateRank(trans, sObjectMgr->GetTrinityString(LANG_GUILD_MASTER, loc), GR_RIGHT_ALL);
_CreateRank(trans, sObjectMgr->GetTrinityString(LANG_GUILD_OFFICER, loc), GR_RIGHT_ALL);
_CreateRank(trans, sObjectMgr->GetTrinityString(LANG_GUILD_VETERAN, loc), GR_RIGHT_GCHATLISTEN | GR_RIGHT_GCHATSPEAK);
_CreateRank(trans, sObjectMgr->GetTrinityString(LANG_GUILD_MEMBER, loc), GR_RIGHT_GCHATLISTEN | GR_RIGHT_GCHATSPEAK);
_CreateRank(trans, sObjectMgr->GetTrinityString(LANG_GUILD_INITIATE, loc), GR_RIGHT_GCHATLISTEN | GR_RIGHT_GCHATSPEAK);
}
bool Guild::_CreateRank(SQLTransaction& trans, std::string const& name, uint32 rights)
{
uint8 newRankId = _GetRanksSize();
if (newRankId >= GUILD_RANKS_MAX_COUNT)
return false;
// Ranks represent sequence 0, 1, 2, ... where 0 means guildmaster
RankInfo info(m_id, newRankId, name, rights, 0);
m_ranks.push_back(info);
bool const isInTransaction = bool(trans);
if (!isInTransaction)
trans = CharacterDatabase.BeginTransaction();
info.CreateMissingTabsIfNeeded(_GetPurchasedTabsSize(), trans);
info.SaveToDB(trans);
if (!isInTransaction)
CharacterDatabase.CommitTransaction(trans);
return true;
}
// Updates the number of accounts that are in the guild
// Player may have many characters in the guild, but with the same account
void Guild::_UpdateAccountsNumber()
{
// We use a set to be sure each element will be unique
std::set<uint32> accountsIdSet;
for (auto itr = m_members.begin(); itr != m_members.end(); ++itr)
accountsIdSet.insert(itr->second->GetAccountId());
m_accountsNumber = accountsIdSet.size();
}
// Detects if player is the guild master.
// Check both leader guid and player's rank (otherwise multiple feature with
// multiple guild masters won't work)
bool Guild::_IsLeader(Player* player) const
{
if (player->GetGUID() == m_leaderGuid)
return true;
if (Member const* member = GetMember(player->GetGUID()))
return member->IsRank(GR_GUILDMASTER);
return false;
}
void Guild::_DeleteBankItems(SQLTransaction& trans, bool removeItemsFromDB)
{
for (uint8 tabId = 0; tabId < _GetPurchasedTabsSize(); ++tabId)
{
m_bankTabs[tabId]->Delete(trans, removeItemsFromDB);
delete m_bankTabs[tabId];
m_bankTabs[tabId] = nullptr;
}
m_bankTabs.clear();
}
bool Guild::_ModifyBankMoney(SQLTransaction& trans, uint64 amount, bool add)
{
if (add)
m_bankMoney += amount;
else
{
// Check if there is enough money in bank.
if (m_bankMoney < amount)
return false;
m_bankMoney -= amount;
}
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_BANK_MONEY);
stmt->setUInt64(0, m_bankMoney);
stmt->setUInt32(1, m_id);
trans->Append(stmt);
return true;
}
void Guild::_SetLeaderGUID(Member* pLeader)
{
if (!pLeader)
return;
SQLTransaction trans = CharacterDatabase.BeginTransaction();
m_leaderGuid = pLeader->GetGUID();
pLeader->ChangeRank(trans, GR_GUILDMASTER);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_LEADER);
stmt->setUInt32(0, m_leaderGuid.GetCounter());
stmt->setUInt32(1, m_id);
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
}
void Guild::_SetRankBankMoneyPerDay(uint8 rankId, uint32 moneyPerDay)
{
if (RankInfo* rankInfo = GetRankInfo(rankId))
rankInfo->SetBankMoneyPerDay(moneyPerDay);
}
void Guild::_SetRankBankTabRightsAndSlots(uint8 rankId, GuildBankRightsAndSlots rightsAndSlots, bool saveToDB)
{
if (rightsAndSlots.GetTabId() >= _GetPurchasedTabsSize())
return;
if (RankInfo* rankInfo = GetRankInfo(rankId))
rankInfo->SetBankTabSlotsAndRights(rightsAndSlots, saveToDB);
}
inline std::string Guild::_GetRankName(uint8 rankId) const
{
if (RankInfo const* rankInfo = GetRankInfo(rankId))
return rankInfo->GetName();
return "<unknown>";
}
inline uint32 Guild::_GetRankRights(uint8 rankId) const
{
if (RankInfo const* rankInfo = GetRankInfo(rankId))
return rankInfo->GetRights();
return 0;
}
inline int32 Guild::_GetRankBankMoneyPerDay(uint8 rankId) const
{
if (RankInfo const* rankInfo = GetRankInfo(rankId))
return rankInfo->GetBankMoneyPerDay();
return 0;
}
inline int32 Guild::_GetRankBankTabSlotsPerDay(uint8 rankId, uint8 tabId) const
{
if (tabId < _GetPurchasedTabsSize())
if (RankInfo const* rankInfo = GetRankInfo(rankId))
return rankInfo->GetBankTabSlotsPerDay(tabId);
return 0;
}
inline int8 Guild::_GetRankBankTabRights(uint8 rankId, uint8 tabId) const
{
if (RankInfo const* rankInfo = GetRankInfo(rankId))
return rankInfo->GetBankTabRights(tabId);
return 0;
}
inline int32 Guild::_GetMemberRemainingSlots(Member const* member, uint8 tabId) const
{
if (member)
{
uint8 rankId = member->GetRankId();
if (rankId == GR_GUILDMASTER)
return static_cast<int32>(GUILD_WITHDRAW_SLOT_UNLIMITED);
if ((_GetRankBankTabRights(rankId, tabId) & GUILD_BANK_RIGHT_VIEW_TAB) != 0)
{
int32 remaining = _GetRankBankTabSlotsPerDay(rankId, tabId) - member->GetBankWithdrawValue(tabId);
if (remaining > 0)
return remaining;
}
}
return 0;
}
inline int32 Guild::_GetMemberRemainingMoney(Member const* member) const
{
if (member)
{
uint8 rankId = member->GetRankId();
if (rankId == GR_GUILDMASTER)
return static_cast<int32>(GUILD_WITHDRAW_MONEY_UNLIMITED);
if ((_GetRankRights(rankId) & (GR_RIGHT_WITHDRAW_REPAIR | GR_RIGHT_WITHDRAW_GOLD)) != 0)
{
int32 remaining = _GetRankBankMoneyPerDay(rankId) - member->GetBankWithdrawValue(GUILD_BANK_MAX_TABS);
if (remaining > 0)
return remaining;
}
}
return 0;
}
inline void Guild::_UpdateMemberWithdrawSlots(SQLTransaction& trans, ObjectGuid guid, uint8 tabId)
{
if (Member* member = GetMember(guid))
{
uint8 rankId = member->GetRankId();
if (rankId != GR_GUILDMASTER
&& member->GetBankWithdrawValue(tabId) < _GetRankBankTabSlotsPerDay(rankId, tabId))
member->UpdateBankWithdrawValue(trans, tabId, 1);
}
}
inline bool Guild::_MemberHasTabRights(ObjectGuid guid, uint8 tabId, uint32 rights) const
{
if (Member const* member = GetMember(guid))
{
// Leader always has full rights
if (member->IsRank(GR_GUILDMASTER) || m_leaderGuid == guid)
return true;
return (_GetRankBankTabRights(member->GetRankId(), tabId) & rights) == rights;
}
return false;
}
// Add new event log record
inline void Guild::_LogEvent(GuildEventLogTypes eventType, ObjectGuid::LowType playerGuid1, ObjectGuid::LowType playerGuid2, uint8 newRank)
{
SQLTransaction trans = CharacterDatabase.BeginTransaction();
m_eventLog->AddEvent(trans, new EventLogEntry(m_id, m_eventLog->GetNextGUID(), eventType, playerGuid1, playerGuid2, newRank));
CharacterDatabase.CommitTransaction(trans);
sScriptMgr->OnGuildEvent(this, uint8(eventType), playerGuid1, playerGuid2, newRank);
}
// Add new bank event log record
void Guild::_LogBankEvent(SQLTransaction& trans, GuildBankEventLogTypes eventType, uint8 tabId, ObjectGuid::LowType lowguid, uint32 itemOrMoney, uint16 itemStackCount, uint8 destTabId)
{
if (tabId > GUILD_BANK_MAX_TABS)
return;
// not logging moves within the same tab
if (eventType == GUILD_BANK_LOG_MOVE_ITEM && tabId == destTabId)
return;
uint8 dbTabId = tabId;
if (BankEventLogEntry::IsMoneyEvent(eventType))
{
tabId = GUILD_BANK_MAX_TABS;
dbTabId = GUILD_BANK_MONEY_LOGS_TAB;
}
LogHolder* pLog = m_bankEventLog[tabId];
pLog->AddEvent(trans, new BankEventLogEntry(m_id, pLog->GetNextGUID(), eventType, dbTabId, lowguid, itemOrMoney, itemStackCount, destTabId));
sScriptMgr->OnGuildBankEvent(this, uint8(eventType), tabId, lowguid, itemOrMoney, itemStackCount, destTabId);
}
inline Item* Guild::_GetItem(uint8 tabId, uint8 slotId) const
{
if (BankTab const* tab = GetBankTab(tabId))
return tab->GetItem(slotId);
return nullptr;
}
inline void Guild::_RemoveItem(SQLTransaction& trans, uint8 tabId, uint8 slotId)
{
if (BankTab* pTab = GetBankTab(tabId))
pTab->SetItem(trans, slotId, nullptr);
}
void Guild::_MoveItems(MoveItemData* pSrc, MoveItemData* pDest, uint32 splitedAmount)
{
// 1. Initialize source item
if (!pSrc->InitItem())
return; // No source item
// 2. Check source item
if (!pSrc->CheckItem(splitedAmount))
return; // Source item or splited amount is invalid
/*
if (pItemSrc->GetCount() == 0)
{
TC_LOG_FATAL("guild", "Guild::SwapItems: Player %s(GUIDLow: %u) tried to move item %u from tab %u slot %u to tab %u slot %u, but item %u has a stack of zero!",
player->GetName(), player->GetGUID().GetCounter(), pItemSrc->GetEntry(), tabId, slotId, destTabId, destSlotId, pItemSrc->GetEntry());
//return; // Commented out for now, uncomment when it's verified that this causes a crash!!
}
// */
// 3. Check destination rights
if (!pDest->HasStoreRights(pSrc))
return; // Player has no rights to store item in destination
// 4. Check source withdraw rights
if (!pSrc->HasWithdrawRights(pDest))
return; // Player has no rights to withdraw items from source
// 5. Check split
if (splitedAmount)
{
// 5.1. Clone source item
if (!pSrc->CloneItem(splitedAmount))
return; // Item could not be cloned
// 5.2. Move splited item to destination
_DoItemsMove(pSrc, pDest, true, splitedAmount);
}
else // 6. No split
{
// 6.1. Try to merge items in destination (pDest->GetItem() == nullptr)
if (!_DoItemsMove(pSrc, pDest, false)) // Item could not be merged
{
// 6.2. Try to swap items
// 6.2.1. Initialize destination item
if (!pDest->InitItem())
return;
// 6.2.2. Check rights to store item in source (opposite direction)
if (!pSrc->HasStoreRights(pDest))
return; // Player has no rights to store item in source (opposite direction)
if (!pDest->HasWithdrawRights(pSrc))
return; // Player has no rights to withdraw item from destination (opposite direction)
// 6.2.3. Swap items (pDest->GetItem() != nullptr)
_DoItemsMove(pSrc, pDest, true);
}
}
// 7. Send changes
_SendBankContentUpdate(pSrc, pDest);
}
bool Guild::_DoItemsMove(MoveItemData* pSrc, MoveItemData* pDest, bool sendError, uint32 splitedAmount)
{
Item* pDestItem = pDest->GetItem();
bool swap = (pDestItem != nullptr);
Item* pSrcItem = pSrc->GetItem(splitedAmount != 0);
// 1. Can store source item in destination
if (!pDest->CanStore(pSrcItem, swap, sendError))
return false;
// 2. Can store destination item in source
if (swap)
if (!pSrc->CanStore(pDestItem, true, true))
return false;
// GM LOG (@todo move to scripts)
pDest->LogAction(pSrc);
if (swap)
pSrc->LogAction(pDest);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
// 3. Log bank events
pDest->LogBankEvent(trans, pSrc, pSrcItem->GetCount());
if (swap)
pSrc->LogBankEvent(trans, pDest, pDestItem->GetCount());
// 4. Remove item from source
pSrc->RemoveItem(trans, pDest, splitedAmount);
// 5. Remove item from destination
if (swap)
pDest->RemoveItem(trans, pSrc);
// 6. Store item in destination
pDest->StoreItem(trans, pSrcItem);
// 7. Store item in source
if (swap)
pSrc->StoreItem(trans, pDestItem);
CharacterDatabase.CommitTransaction(trans);
return true;
}
void Guild::_SendBankContent(WorldSession* session, uint8 tabId) const
{
ObjectGuid guid = session->GetPlayer()->GetGUID();
if (!_MemberHasTabRights(guid, tabId, GUILD_BANK_RIGHT_VIEW_TAB))
return;
_SendBankList(session, tabId, true);
}
void Guild::_SendBankMoneyUpdate(WorldSession* session) const
{
_SendBankList(session);
}
void Guild::_SendBankContentUpdate(MoveItemData* pSrc, MoveItemData* pDest) const
{
ASSERT(pSrc->IsBank() || pDest->IsBank());
uint8 tabId = 0;
SlotIds slots;
if (pSrc->IsBank()) // B ->
{
tabId = pSrc->GetContainer();
slots.insert(pSrc->GetSlotId());
if (pDest->IsBank()) // B -> B
{
// Same tab - add destination slots to collection
if (pDest->GetContainer() == pSrc->GetContainer())
pDest->CopySlots(slots);
else // Different tabs - send second message
{
SlotIds destSlots;
pDest->CopySlots(destSlots);
_SendBankContentUpdate(pDest->GetContainer(), destSlots);
}
}
}
else if (pDest->IsBank()) // C -> B
{
tabId = pDest->GetContainer();
pDest->CopySlots(slots);
}
_SendBankContentUpdate(tabId, slots);
}
void Guild::_SendBankContentUpdate(uint8 tabId, SlotIds slots) const
{
_SendBankList(nullptr, tabId, false, &slots);
}
void Guild::_BroadcastEvent(GuildEvents guildEvent, ObjectGuid guid, char const* param1, char const* param2, char const* param3) const
{
uint8 count = !param3 ? (!param2 ? (!param1 ? 0 : 1) : 2) : 3;
WorldPacket data(SMSG_GUILD_EVENT, 1 + 1 + count + (8));
data << uint8(guildEvent);
data << uint8(count);
if (param3)
data << param1 << param2 << param3;
else if (param2)
data << param1 << param2;
else if (param1)
data << param1;
if (guid)
data << uint64(guid);
BroadcastPacket(&data);
TC_LOG_DEBUG("guild", "SMSG_GUILD_EVENT [Broadcast] Event: %s (%u)", GetGuildEventString(guildEvent), guildEvent);
}
void Guild::_SendBankList(WorldSession* session /* = nullptr*/, uint8 tabId /*= 0*/, bool sendAllSlots /*= false*/, SlotIds *slots /*= nullptr*/) const
{
WorldPacket data(SMSG_GUILD_BANK_LIST, 500);
data << uint64(m_bankMoney);
data << uint8(tabId);
size_t rempos = data.wpos();
data << uint32(0);
data << uint8(sendAllSlots);
if (sendAllSlots && !tabId)
{
data << uint8(_GetPurchasedTabsSize()); // Number of tabs
for (uint8 i = 0; i < _GetPurchasedTabsSize(); ++i)
m_bankTabs[i]->WriteInfoPacket(data);
}
BankTab const* tab = GetBankTab(tabId);
if (!tab)
data << uint8(0);
else if (sendAllSlots)
tab->WritePacket(data);
else if (slots && !slots->empty())
{
data << uint8(slots->size());
for (auto itr = slots->begin(); itr != slots->end(); ++itr)
tab->WriteSlotPacket(data, *itr, false);
}
else
data << uint8(0);
if (session)
{
int32 numSlots = 0;
if (Member const* member = GetMember(session->GetPlayer()->GetGUID()))
numSlots = _GetMemberRemainingSlots(member, tabId);
data.put<uint32>(rempos, numSlots);
session->SendPacket(&data);
TC_LOG_DEBUG("guild", "SMSG_GUILD_BANK_LIST [%s]: TabId: %u, FullSlots: %u, slots: %d",
session->GetPlayerInfo().c_str(), tabId, sendAllSlots, numSlots);
}
else /// @todo - Probably this is just sent to session + those that have sent CMSG_GUILD_BANKER_ACTIVATE
{
for (auto itr = m_members.begin(); itr != m_members.end(); ++itr)
{
if (!_MemberHasTabRights(itr->second->GetGUID(), tabId, GUILD_BANK_RIGHT_VIEW_TAB))
continue;
Player* player = itr->second->FindPlayer();
if (!player)
continue;
uint32 numSlots = _GetMemberRemainingSlots(itr->second, tabId);
data.put<uint32>(rempos, numSlots);
player->SendDirectMessage(&data);
TC_LOG_DEBUG("guild", "SMSG_GUILD_BANK_LIST [%s]: TabId: %u, FullSlots: %u, slots: %u"
, player->GetName().c_str(), tabId, sendAllSlots, numSlots);
}
}
}
void Guild::ResetTimes()
{
for (auto itr = m_members.begin(); itr != m_members.end(); ++itr)
itr->second->ResetValues();
_BroadcastEvent(GE_BANK_TAB_AND_MONEY_UPDATED, ObjectGuid::Empty);
}
| 123xlex/TrinityCore | src/server/game/Guilds/Guild.cpp | C++ | gpl-2.0 | 100,940 |
<?php
namespace Album\Model;
/**
*
* @author Rogerio Lamarques
*
*/
use Zend\Db\TableGateway\TableGateway;
class AlbumTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getAlbum($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array(
'id' => $id
));
$row = $rowset->current();
if (! $row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function saveAlbum(Album $album)
{
$data = array(
'artist' => $album->artist,
'title' => $album->title
);
$id = (int) $album->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getAlbum($id)) {
$this->tableGateway->update($data, array(
'id' => $id
));
} else {
throw new \Exception('Album id does not exist');
}
}
}
public function deleteAlbum($id)
{
$this->tableGateway->delete(array(
'id' => (int) $id
));
}
}
?> | lamarques/Zend-studies | module/Album/src/Album/Model/AlbumTable.php | PHP | gpl-2.0 | 1,418 |
<?php
/**
* This file has been @generated by a phing task by {@link BuildMetadataPHPFromXml}.
* See [README.md](README.md#generating-data) for more information.
*
* Pull requests changing data in these files will not be accepted. See the
* [FAQ in the README](README.md#problems-with-invalid-numbers] on how to make
* metadata changes.
*
* Do not modify this file directly!
*/
return array (
'generalDesc' =>
array (
'NationalNumberPattern' => '[14-9]\\d{7,8}',
'PossibleNumberPattern' => '\\d{6,9}',
'PossibleLength' =>
array (
0 => 8,
1 => 9,
),
'PossibleLengthLocalOnly' =>
array (
0 => 6,
1 => 7,
),
),
'fixedLine' =>
array (
'NationalNumberPattern' => '(?:1\\d|4[1-4]|5[1-46]|6[1-7]|7[2-46]|8[2-4])\\d{6}',
'PossibleNumberPattern' => '\\d{6,8}',
'ExampleNumber' => '11234567',
'PossibleLength' =>
array (
0 => 8,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'mobile' =>
array (
'NationalNumberPattern' => '9\\d{8}',
'PossibleNumberPattern' => '\\d{9}',
'ExampleNumber' => '912345678',
'PossibleLength' =>
array (
0 => 9,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'tollFree' =>
array (
'NationalNumberPattern' => '800\\d{5}',
'PossibleNumberPattern' => '\\d{8}',
'ExampleNumber' => '80012345',
'PossibleLength' =>
array (
0 => 8,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'premiumRate' =>
array (
'NationalNumberPattern' => '805\\d{5}',
'PossibleNumberPattern' => '\\d{8}',
'ExampleNumber' => '80512345',
'PossibleLength' =>
array (
0 => 8,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'sharedCost' =>
array (
'NationalNumberPattern' => '801\\d{5}',
'PossibleNumberPattern' => '\\d{8}',
'ExampleNumber' => '80112345',
'PossibleLength' =>
array (
0 => 8,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'personalNumber' =>
array (
'NationalNumberPattern' => '80[24]\\d{5}',
'PossibleNumberPattern' => '\\d{8}',
'ExampleNumber' => '80212345',
'PossibleLength' =>
array (
0 => 8,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'voip' =>
array (
'NationalNumberPattern' => 'NA',
'PossibleNumberPattern' => 'NA',
'PossibleLength' =>
array (
0 => -1,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'pager' =>
array (
'NationalNumberPattern' => 'NA',
'PossibleNumberPattern' => 'NA',
'PossibleLength' =>
array (
0 => -1,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'uan' =>
array (
'NationalNumberPattern' => 'NA',
'PossibleNumberPattern' => 'NA',
'PossibleLength' =>
array (
0 => -1,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'voicemail' =>
array (
'NationalNumberPattern' => 'NA',
'PossibleNumberPattern' => 'NA',
'PossibleLength' =>
array (
0 => -1,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'noInternationalDialling' =>
array (
'NationalNumberPattern' => 'NA',
'PossibleNumberPattern' => 'NA',
'PossibleLength' =>
array (
0 => -1,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'id' => 'PE',
'countryCode' => 51,
'internationalPrefix' => '19(?:1[124]|77|90)00',
'nationalPrefix' => '0',
'preferredExtnPrefix' => ' Anexo ',
'nationalPrefixForParsing' => '0',
'sameMobileAndFixedLinePattern' => false,
'numberFormat' =>
array (
0 =>
array (
'pattern' => '(1)(\\d{7})',
'format' => '$1 $2',
'leadingDigitsPatterns' =>
array (
0 => '1',
),
'nationalPrefixFormattingRule' => '(0$1)',
'domesticCarrierCodeFormattingRule' => '',
'nationalPrefixOptionalWhenFormatting' => false,
),
1 =>
array (
'pattern' => '([4-8]\\d)(\\d{6})',
'format' => '$1 $2',
'leadingDigitsPatterns' =>
array (
0 => '[4-7]|8[2-4]',
),
'nationalPrefixFormattingRule' => '(0$1)',
'domesticCarrierCodeFormattingRule' => '',
'nationalPrefixOptionalWhenFormatting' => false,
),
2 =>
array (
'pattern' => '(\\d{3})(\\d{5})',
'format' => '$1 $2',
'leadingDigitsPatterns' =>
array (
0 => '80',
),
'nationalPrefixFormattingRule' => '(0$1)',
'domesticCarrierCodeFormattingRule' => '',
'nationalPrefixOptionalWhenFormatting' => false,
),
3 =>
array (
'pattern' => '(9\\d{2})(\\d{3})(\\d{3})',
'format' => '$1 $2 $3',
'leadingDigitsPatterns' =>
array (
0 => '9',
),
'nationalPrefixFormattingRule' => '$1',
'domesticCarrierCodeFormattingRule' => '',
'nationalPrefixOptionalWhenFormatting' => false,
),
),
'intlNumberFormat' =>
array (
),
'mainCountryForCode' => false,
'leadingZeroPossible' => false,
'mobileNumberPortableRegion' => true,
);
| THECALLR/callr-woocommerce | admin/vendor/giggsey/libphonenumber-for-php/src/libphonenumber/data/PhoneNumberMetadata_PE.php | PHP | gpl-2.0 | 5,143 |
class RenameOrdeLineToOrderDetail < ActiveRecord::Migration
def change
rename_table :order_lines, :order_details
end
end
| carojasq/miscelanea | db/migrate/20141104132104_rename_orde_line_to_order_detail.rb | Ruby | gpl-2.0 | 128 |
<?php
/* core/themes/classy/templates/navigation/breadcrumb.html.twig */
class __TwigTemplate_409f5f562164b0f9049b70e0b01c2edc7c70d123e0f9fa1f2378198c8de96bdf extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array("if" => 10, "for" => 14);
$filters = array("t" => 12);
$functions = array();
try {
$this->env->getExtension('Twig_Extension_Sandbox')->checkSecurity(
array('if', 'for'),
array('t'),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setSourceContext($this->getSourceContext());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 10
if ((isset($context["breadcrumb"]) ? $context["breadcrumb"] : null)) {
// line 11
echo " <nav class=\"breadcrumb\" role=\"navigation\" aria-labelledby=\"system-breadcrumb\">
<h2 id=\"system-breadcrumb\" class=\"visually-hidden\">";
// line 12
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->renderVar(t("Breadcrumb")));
echo "</h2>
<ol>
";
// line 14
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["breadcrumb"]) ? $context["breadcrumb"] : null));
foreach ($context['_seq'] as $context["_key"] => $context["item"]) {
// line 15
echo " <li>
";
// line 16
if ($this->getAttribute($context["item"], "url", array())) {
// line 17
echo " <a href=\"";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["item"], "url", array()), "html", null, true));
echo "\">";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["item"], "text", array()), "html", null, true));
echo "</a>
";
} else {
// line 19
echo " ";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["item"], "text", array()), "html", null, true));
echo "
";
}
// line 21
echo " </li>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['item'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 23
echo " </ol>
</nav>
";
}
}
public function getTemplateName()
{
return "core/themes/classy/templates/navigation/breadcrumb.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 83 => 23, 76 => 21, 70 => 19, 62 => 17, 60 => 16, 57 => 15, 53 => 14, 48 => 12, 45 => 11, 43 => 10,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("", "core/themes/classy/templates/navigation/breadcrumb.html.twig", "D:\\Sachin\\work\\XAMPP\\htdocs\\sachlife\\core\\themes\\classy\\templates\\navigation\\breadcrumb.html.twig");
}
}
| sachinsuryavanshi/sachlife-xampp | sites/default/files/php/twig/5b08fe9a00394_breadcrumb.html.twig_bpT9qXxQz_4B9K3QemSggcJmT/IVc0q79j4Y19Uv2OOMsPaLuNWKUUGGyreYxX9ChfHYA.php | PHP | gpl-2.0 | 4,970 |
/*******************************************************************************
JimmLangFileTool - Simple Java GUI for editing/comparing Jimm language files
Copyright (C) 2005 Jimm Project
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
********************************************************************************
File: src/jimmLangFileTool/LGFileSubset.java
Version: ###VERSION### Date: ###DATE###
Author(s): Andreas Rossbacher
*******************************************************************************/
package jimmLangFileTool;
import java.util.Vector;
public class LGFileSubset extends Vector
{
private static final long serialVersionUID = 1L;
String id;
boolean removed;
public LGFileSubset(String _id)
{
super();
id = _id;
removed = false;
}
public LGFileSubset()
{
super();
}
public LGFileSubset getClone()
{
return this;
}
public LGString containsKey(String key)
{
for(int i=0;i<super.size();i++)
{
if(super.get(i) instanceof LGString)
if(((LGString)super.get(i)).getKey().equals(key))
return (LGString) super.get(i);
}
return null;
}
/**
* @return Returns the id.
*/
public String getId()
{
return id;
}
public String toString()
{
return id;
}
/**
* @param id The id to set.
*/
public void setId(String id)
{
this.id = id;
}
/**
* @return Returns the removed.
*/
public boolean isRemoved()
{
return removed;
}
/**
* @param removed The removed to set.
*/
public void setRemoved(boolean removed)
{
this.removed = removed;
}
}
| fin-nick/fj | util/jlft2/src/jimmLangFileTool/LGFileSubset.java | Java | gpl-2.0 | 2,216 |
//
// Created by 孙启龙 on 2017/8/18.
//
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define maxn 1111
char c[] = {'A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y'}, s[maxn];
int T, k, n, a[111];
void solve()
{
ll temp = 0;
int flag = 0;
for (int i = n - 1; i >= 0; i--)
{
temp = 11ll * temp + 10 - a[s[i]];
if (temp >= k) {
flag = 1;
break;
}
}
if (!flag)
{
k -= temp + 1;
n++;
for (int i = 0; i < n; i++)
s[i] = 'A';
solve();
}
else
{
int up = 0;
for (int i = 0; i < n; i++)
{
up += a[s[i]] + k % 11;
s[i] = c[up % 11];
up /= 11, k /= 11;
}
for (int i = n - 1; i >= 0; i--)
printf("%c", s[i]);
printf("\n");
}
}
int main()
{
for (int i = 0; i < 11; i++)
a[c[i]] = i;
scanf("%d", &T);
while (T--)
{
scanf("%d %s", &k, s);
n = strlen(s);
for (int i = 0, j = n - 1; i < j; i++, j--)
swap(s[i], s[j]);
solve();
}
return 0;
}
| sunmoyi/ACM | acm clion/Secure but True 2/Secure but True .cpp | C++ | gpl-2.0 | 1,332 |
/*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program 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 version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package server.expeditions;
/**
*
* @author SharpAceX(Alan)
*/
public enum MapleExpeditionType {
BALROG_EASY(3, 30, 50, 255, 5),
BALROG_NORMAL(6, 30, 50, 255, 5),
SCARGA(6, 30, 100, 255, 5),
SHOWA(3, 30, 100, 255, 5),
ZAKUM(6, 30, 50, 255, 5),
HORNTAIL(6, 30, 100, 255, 5),
CHAOS_ZAKUM(6, 30, 120, 255, 5),
CHAOS_HORNTAIL(6, 30, 120, 255, 5),
PINKBEAN(6, 30, 120, 255, 5),
CWKPQ(6, 30, 100, 255, 5);
private int minSize;
private int maxSize;
private int minLevel;
private int maxLevel;
private int registrationTime;
private MapleExpeditionType(int minSize, int maxSize, int minLevel, int maxLevel, int minutes) {
this.minSize = minSize;
this.maxSize = maxSize;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
this.registrationTime = minutes;
}
public int getMinSize() {
return minSize;
}
public int getMaxSize() {
return maxSize;
}
public int getMinLevel() {
return minLevel;
}
public int getMaxLevel() {
return maxLevel;
}
public int getRegistrationTime(){
return registrationTime;
}
}
| xstory61/server | src/server/expeditions/MapleExpeditionType.java | Java | gpl-2.0 | 2,190 |
package com.byhealth.wechat.mysdk.process.in.executor;
import com.byhealth.wechat.base.admin.entity.RespMsgActionEntity;
import com.byhealth.wechat.config.MsgTemplateConstants;
import com.byhealth.wechat.mysdk.constants.WechatReqMsgtypeConstants;
import com.byhealth.wechat.mysdk.context.WechatContext;
import com.byhealth.wechat.mysdk.process.ext.TextExtService;
import com.byhealth.wechat.mysdk.tools.NameTool;
import com.byhealth.wechat.mysdk.beans.req.ReqTextMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
/**
* 文本消息处理器
* @author fengjx xd-fjx@qq.com
* @date 2014年9月11日
*/
public class InWechatTextMsgExecutor extends InServiceExecutor {
@Autowired
private TextExtService textExtService;
@Override
public String execute() throws Exception {
ReqTextMessage textMessage = new ReqTextMessage(WechatContext.getWechatPostMap());
logger.info("进入文本消息处理器fromUserName="+textMessage.getFromUserName());
RespMsgActionEntity actionEntity = msgActionService.loadMsgAction(null,WechatReqMsgtypeConstants.REQ_MSG_TYPE_TEXT, null,textMessage.getContent(), WechatContext.getPublicAccount().getSysUser());
//没有找到匹配规则
if(null == actionEntity){
String res = textExtService.execute();
if(StringUtils.isNotBlank(res)){ //如果有数据则直接返回
return res;
}
//返回默认回复消息
actionEntity = msgActionService.loadMsgAction(MsgTemplateConstants.WECHAT_DEFAULT_MSG, null, null, null, WechatContext.getPublicAccount().getSysUser());
}
return doAction(actionEntity);
}
@Override
public String getExecutorName() {
return NameTool.buildInServiceName(WechatReqMsgtypeConstants.REQ_MSG_TYPE_TEXT, null);
}
}
| huangyaoming/wxtest | src/com/byhealth/wechat/mysdk/process/in/executor/InWechatTextMsgExecutor.java | Java | gpl-2.0 | 1,776 |
/*
* MultiSelect v0.9.8
* Copyright (c) 2012 Louis Cuny
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*/
!function ($) {
"use strict";
/* MULTISELECT CLASS DEFINITION
* ====================== */
var MultiSelect = function (element, options) {
this.options = options;
this.$element = $(element);
this.$container = $('<div/>', { 'class': "ms-container" });
this.$selectableContainer = $('<div/>', { 'class': 'ms-selectable' });
this.$selectionContainer = $('<div/>', { 'class': 'ms-selection' });
this.$selectableUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' });
this.$selectionUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' });
this.scrollTo = 0;
this.sanitizeRegexp = new RegExp("\\W+", 'gi');
this.elemsSelector = 'li:visible:not(.ms-optgroup-label,.ms-optgroup-container,.'+options.disabledClass+')';
};
MultiSelect.prototype = {
constructor: MultiSelect,
init: function(){
var that = this,
ms = this.$element;
if (ms.next('.ms-container').length === 0){
ms.css({ position: 'absolute', left: '-9999px' });
ms.attr('id', ms.attr('id') ? ms.attr('id') : Math.ceil(Math.random()*1000)+'multiselect');
this.$container.attr('id', 'ms-'+ms.attr('id'));
ms.find('option').each(function(){
that.generateLisFromOption(this);
});
this.$selectionUl.find('.ms-optgroup-label').hide();
if (that.options.selectableHeader){
that.$selectableContainer.append(that.options.selectableHeader);
}
that.$selectableContainer.append(that.$selectableUl);
if (that.options.selectableFooter){
that.$selectableContainer.append(that.options.selectableFooter);
}
if (that.options.selectionHeader){
that.$selectionContainer.append(that.options.selectionHeader);
}
that.$selectionContainer.append(that.$selectionUl);
if (that.options.selectionFooter){
that.$selectionContainer.append(that.options.selectionFooter);
}
that.$container.append(that.$selectableContainer);
that.$container.append(that.$selectionContainer);
ms.after(that.$container);
that.activeMouse(that.$selectableUl);
that.activeKeyboard(that.$selectableUl);
var action = that.options.dblClick ? 'dblclick' : 'click';
that.$selectableUl.on(action, '.ms-elem-selectable', function(){
that.select($(this).data('ms-value'));
});
that.$selectionUl.on(action, '.ms-elem-selection', function(){
that.deselect($(this).data('ms-value'));
});
that.activeMouse(that.$selectionUl);
that.activeKeyboard(that.$selectionUl);
ms.on('focus', function(){
that.$selectableUl.focus();
})
}
var selectedValues = ms.find('option:selected').map(function(){ return $(this).val(); }).get();
that.select(selectedValues, 'init');
if (typeof that.options.afterInit === 'function') {
that.options.afterInit.call(this, this.$container);
}
},
'generateLisFromOption' : function(option){
var that = this,
ms = that.$element,
attributes = "",
$option = $(option);
for (var cpt = 0; cpt < option.attributes.length; cpt++){
var attr = option.attributes[cpt];
if(attr.name !== 'value' && attr.name !== 'disabled'){
attributes += attr.name+'="'+attr.value+'" ';
}
}
var selectableLi = $('<li '+attributes+'><span>'+$option.text()+'</span></li>'),
selectedLi = selectableLi.clone(),
value = $option.val(),
elementId = that.sanitize(value, that.sanitizeRegexp);
selectableLi
.data('ms-value', value)
.addClass('ms-elem-selectable')
.attr('id', elementId+'-selectable');
selectedLi
.data('ms-value', value)
.addClass('ms-elem-selection')
.attr('id', elementId+'-selection')
.hide();
if ($option.prop('disabled') || ms.prop('disabled')){
selectedLi.addClass(that.options.disabledClass);
selectableLi.addClass(that.options.disabledClass);
}
var $optgroup = $option.parent('optgroup');
if ($optgroup.length > 0){
var optgroupLabel = $optgroup.attr('label'),
optgroupId = that.sanitize(optgroupLabel, that.sanitizeRegexp),
$selectableOptgroup = that.$selectableUl.find('#optgroup-selectable-'+optgroupId),
$selectionOptgroup = that.$selectionUl.find('#optgroup-selection-'+optgroupId);
if ($selectableOptgroup.length === 0){
var optgroupContainerTpl = '<li class="ms-optgroup-container"></li>',
optgroupTpl = '<ul class="ms-optgroup"><li class="ms-optgroup-label"><span>'+optgroupLabel+'</span></li></ul>';
$selectableOptgroup = $(optgroupContainerTpl);
$selectionOptgroup = $(optgroupContainerTpl);
$selectableOptgroup.attr('id', 'optgroup-selectable-'+optgroupId);
$selectionOptgroup.attr('id', 'optgroup-selection-'+optgroupId);
$selectableOptgroup.append($(optgroupTpl));
$selectionOptgroup.append($(optgroupTpl));
if (that.options.selectableOptgroup){
$selectableOptgroup.find('.ms-optgroup-label').on('click', function(){
var values = $optgroup.children(':not(:selected)').map(function(){ return $(this).val() }).get();
that.select(values);
});
$selectionOptgroup.find('.ms-optgroup-label').on('click', function(){
var values = $optgroup.children(':selected').map(function(){ return $(this).val() }).get();
that.deselect(values);
});
}
that.$selectableUl.append($selectableOptgroup);
that.$selectionUl.append($selectionOptgroup);
}
$selectableOptgroup.children().append(selectableLi);
$selectionOptgroup.children().append(selectedLi);
} else {
that.$selectableUl.append(selectableLi);
that.$selectionUl.append(selectedLi);
}
},
'activeKeyboard' : function($list){
var that = this;
$list.on('focus', function(){
$(this).addClass('ms-focus');
})
.on('blur', function(){
$(this).removeClass('ms-focus');
})
.on('keydown', function(e){
switch (e.which) {
case 40:
case 38:
e.preventDefault();
e.stopPropagation();
that.moveHighlight($(this), (e.which === 38) ? -1 : 1);
return;
case 37:
case 39:
e.preventDefault();
e.stopPropagation();
that.switchList($list);
return;
case 9:
if(that.$element.is('[tabindex]')){
e.preventDefault();
var tabindex = parseInt(that.$element.attr('tabindex'), 10);
tabindex = (e.shiftKey) ? tabindex-1 : tabindex+1;
$('[tabindex="'+(tabindex)+'"]').focus();
return;
}else{
if(e.shiftKey){
that.$element.trigger('focus');
}
}
}
if($.inArray(e.which, that.options.keySelect) > -1){
e.preventDefault();
e.stopPropagation();
that.selectHighlighted($list);
return;
}
});
},
'moveHighlight': function($list, direction){
var $elems = $list.find(this.elemsSelector),
$currElem = $elems.filter('.ms-hover'),
$nextElem = null,
elemHeight = $elems.first().outerHeight(),
containerHeight = $list.height(),
containerSelector = '#'+this.$container.prop('id');
// Deactive mouseenter event when move is active
// It fixes a bug when mouse is over the list
$elems.off('mouseenter');
$elems.removeClass('ms-hover');
if (direction === 1){ // DOWN
$nextElem = $currElem.nextAll(this.elemsSelector).first();
if ($nextElem.length === 0){
var $optgroupUl = $currElem.parent();
if ($optgroupUl.hasClass('ms-optgroup')){
var $optgroupLi = $optgroupUl.parent(),
$nextOptgroupLi = $optgroupLi.next(':visible');
if ($nextOptgroupLi.length > 0){
$nextElem = $nextOptgroupLi.find(this.elemsSelector).first();
} else {
$nextElem = $elems.first();
}
} else {
$nextElem = $elems.first();
}
}
} else if (direction === -1){ // UP
$nextElem = $currElem.prevAll(this.elemsSelector).first();
if ($nextElem.length === 0){
var $optgroupUl = $currElem.parent();
if ($optgroupUl.hasClass('ms-optgroup')){
var $optgroupLi = $optgroupUl.parent(),
$prevOptgroupLi = $optgroupLi.prev(':visible');
if ($prevOptgroupLi.length > 0){
$nextElem = $prevOptgroupLi.find(this.elemsSelector).last();
} else {
$nextElem = $elems.last();
}
} else {
$nextElem = $elems.last();
}
}
}
if ($nextElem.length > 0){
$nextElem.addClass('ms-hover');
var scrollTo = $list.scrollTop() + $nextElem.position().top -
containerHeight / 2 + elemHeight / 2;
$list.scrollTop(scrollTo);
}
},
'selectHighlighted' : function($list){
var $elems = $list.find(this.elemsSelector),
$highlightedElem = $elems.filter('.ms-hover').first();
if ($highlightedElem.length > 0){
if ($list.parent().hasClass('ms-selectable')){
this.select($highlightedElem.data('ms-value'));
} else {
this.deselect($highlightedElem.data('ms-value'));
}
$elems.removeClass('ms-hover');
}
},
'switchList' : function($list){
$list.blur();
if ($list.parent().hasClass('ms-selectable')){
this.$selectionUl.focus();
} else {
this.$selectableUl.focus();
}
},
'activeMouse' : function($list){
var that = this;
var lastMovedDom = false;
$list.on('mousemove', function(){
if (lastMovedDom === this) return;
lastMovedDom = this;
var elems = $list.find(that.elemsSelector);
elems.on('mouseenter', function(){
elems.removeClass('ms-hover');
$(this).addClass('ms-hover');
});
});
},
'refresh' : function() {
this.destroy();
this.$element.multiSelect(this.options);
},
'destroy' : function(){
$("#ms-"+this.$element.attr("id")).remove();
this.$element.removeData('multiselect');
},
'select' : function(value, method){
if (typeof value === 'string'){ value = [value]; }
var that = this,
ms = this.$element,
msIds = $.map(value, function(val){ return(that.sanitize(val, that.sanitizeRegexp)); }),
selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'),
selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection').filter(':not(.'+that.options.disabledClass+')'),
options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); });
if (selectables.length > 0){
selectables.addClass('ms-selected').hide();
selections.addClass('ms-selected').show();
options.prop('selected', true);
var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
if (selectableOptgroups.length > 0){
selectableOptgroups.each(function(){
var selectablesLi = $(this).find('.ms-elem-selectable');
if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){
$(this).find('.ms-optgroup-label').hide();
}
});
var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');
selectionOptgroups.each(function(){
var selectionsLi = $(this).find('.ms-elem-selection');
if (selectionsLi.filter('.ms-selected').length > 0){
$(this).find('.ms-optgroup-label').show();
}
});
} else {
if (that.options.keepOrder){
var selectionLiLast = that.$selectionUl.find('.ms-selected');
if((selectionLiLast.length > 1) && (selectionLiLast.last().get(0) != selections.get(0))) {
selections.insertAfter(selectionLiLast.last());
}
}
}
if (method !== 'init'){
ms.trigger('change');
if (typeof that.options.afterSelect === 'function') {
that.options.afterSelect.call(this, value);
}
}
}
},
'deselect' : function(value){
if (typeof value === 'string'){ value = [value]; }
var that = this,
ms = this.$element,
msIds = $.map(value, function(val){ return(that.sanitize(val, that.sanitizeRegexp)); }),
selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),
selections = this.$selectionUl.find('#' + msIds.join('-selection, #')+'-selection').filter('.ms-selected'),
options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); });
if (selections.length > 0){
selectables.removeClass('ms-selected').show();
selections.removeClass('ms-selected').hide();
options.prop('selected', false);
var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
if (selectableOptgroups.length > 0){
selectableOptgroups.each(function(){
var selectablesLi = $(this).find('.ms-elem-selectable');
if (selectablesLi.filter(':not(.ms-selected)').length > 0){
$(this).find('.ms-optgroup-label').show();
}
});
var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');
selectionOptgroups.each(function(){
var selectionsLi = $(this).find('.ms-elem-selection');
if (selectionsLi.filter('.ms-selected').length === 0){
$(this).find('.ms-optgroup-label').hide();
}
});
}
ms.trigger('change');
if (typeof that.options.afterDeselect === 'function') {
that.options.afterDeselect.call(this, value);
}
}
},
'select_all' : function(){
var ms = this.$element,
values = ms.val();
ms.find('option:not(":disabled")').prop('selected', true);
this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').hide();
this.$selectionUl.find('.ms-optgroup-label').show();
this.$selectableUl.find('.ms-optgroup-label').hide();
this.$selectionUl.find('.ms-elem-selection').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').show();
this.$selectionUl.focus();
ms.trigger('change');
if (typeof this.options.afterSelect === 'function') {
var selectedValues = $.grep(ms.val(), function(item){
return $.inArray(item, values) < 0;
});
this.options.afterSelect.call(this, selectedValues);
}
},
'deselect_all' : function(){
var ms = this.$element,
values = ms.val();
ms.find('option').prop('selected', false);
this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').show();
this.$selectionUl.find('.ms-optgroup-label').hide();
this.$selectableUl.find('.ms-optgroup-label').show();
this.$selectionUl.find('.ms-elem-selection').removeClass('ms-selected').hide();
this.$selectableUl.focus();
ms.trigger('change');
if (typeof this.options.afterDeselect === 'function') {
this.options.afterDeselect.call(this, values);
}
},
sanitize: function(value, reg){
return(value.replace(reg, '_'));
}
};
/* MULTISELECT PLUGIN DEFINITION
* ======================= */
$.fn.multiSelect = function () {
var option = arguments[0],
args = arguments;
return this.each(function () {
var $this = $(this),
data = $this.data('multiselect'),
options = $.extend({}, $.fn.multiSelect.defaults, $this.data(), typeof option === 'object' && option);
if (!data){ $this.data('multiselect', (data = new MultiSelect(this, options))); }
if (typeof option === 'string'){
data[option](args[1]);
} else {
data.init();
}
});
};
$.fn.multiSelect.defaults = {
keySelect: [32],
selectableOptgroup: false,
disabledClass : 'disabled',
dblClick : false,
keepOrder: false
};
$.fn.multiSelect.Constructor = MultiSelect;
}(window.jQuery); | jvvlimme/www.zenstore.dev | wp-content/plugins/codespacing-progress-map/js/jquery.multi-select.js | JavaScript | gpl-2.0 | 17,428 |
#include "person.h"
Person::Person()
{
hunger=0;
toilet=0;
WaitForDo=0;
}
void Person::AddToDo(Deal todo, float time)
{
ToDoList.append(qMakePair(todo,time));
if (WaitForDo==0) WaitForDo=time;
}
void Person::CheckDeal()
{
WaitForDo-=1;
if (WaitForDo<0)
{
if (!ToDoList.isEmpty())
{
ToDoList.removeFirst();
while(true)
{
if((WaitForDo+ToDoList.at(0).second)>0) break;
if (!ToDoList.isEmpty()) ToDoList.removeFirst();
}
}
else WaitForDo=0;
}
}
Deal::Deal()
{
name="noname";
timeToDeal=0;
}
Deal::Deal(int time, QString n)
{
name=n;
timeToDeal=time;
}
bool Deal::Execution()
{
return true;
}
Deal Person::Eat(float NutritionalValue, float timeToEat)
{
hunger-=NutritionalValue;
Deal noname(1,"n");
return noname;
}
| SteeveRan/town | town/person.cpp | C++ | gpl-2.0 | 895 |
<?php
// We are adding thumbnail support for forums
add_action('init', 'firmasite_social_bbpress_init');
function firmasite_social_bbpress_init() {
add_post_type_support( 'forum', 'thumbnail' );
}
// We are adding bbpress support for theme special systems
add_action('firmasite_pre_get_posts_ekle', 'firmasite_bbpress_pre_get_posts_ekle');
function firmasite_bbpress_pre_get_posts_ekle($array) {
$array[] = "forum";
$array[] = "topic";
return $array;
}
// http://bbpress.org/forums/topic/make-notification-of-new-replies-auto-checked/
add_filter( 'bbp_get_form_topic_subscribed', 'firmasite_auto_check_subscribe', 10, 2 );
function firmasite_auto_check_subscribe( $checked, $topic_subscribed ) {
if( $topic_subscribed == 0 )
$topic_subscribed = true;
return checked( $topic_subscribed, true, false );
}
// removing default plugin css.. bootstrap is enough :)
add_action( 'bbp_theme_compat_actions', 'firmasite_social_remove_default_style' );
function firmasite_social_remove_default_style( $BBP_Default ) {
remove_action( 'bbp_enqueue_scripts', array( $BBP_Default, 'enqueue_styles' ) );
}
// bootstrapped bbPress breadcrumbs
add_filter( 'bbp_before_get_breadcrumb_parse_args', "firmasite_bbp_get_breadcrumb", 10, 1);
function firmasite_bbp_get_breadcrumb($r){
// HTML
$r['before'] = '<ul class="bbp-breadcrumb breadcrumb">';
$r['after' ] = '</ul>';
// Separator
$r['sep_before'] = '<span class="hide">';
$r['sep_after'] = '</span>';
// Crumbs
$r['crumb_before'] = '<li>';
$r['crumb_after'] = '</li>';
// Current
$r['current_before'] = '<span class="bbp-breadcrumb-current text-muted">';
$r['current_after'] = '</span>';
return $r;
}
add_filter ( 'bbp_get_topic_class', 'firmasite_social_bbp_get_topic_class', 10, 2);
function firmasite_social_bbp_get_topic_class ($classes, $topic_id) {
$bbp = bbpress();
$count = isset( $bbp->topic_query->current_post ) ? $bbp->topic_query->current_post : 1;
if(bbp_is_topic_sticky( $topic_id, false )) {
$classes[] = 'alert alert-warning panel-body';
} else if(bbp_is_topic_super_sticky( $topic_id )) {
$classes[] = 'alert alert-danger panel-body';
} else {
$classes[] = ( (int) $count % 2 ) ? 'panel-footer' : 'panel-body';
}
$classes[] = "clearfix";
return $classes;
}
add_filter( 'bbp_get_forum_class', "firmasite_social_bbp_get_forum_class" );
function firmasite_social_bbp_get_forum_class ($classes) {
$classes[] = " well well-sm";
return $classes;
}
add_filter( 'bbp_replies_pagination', "firmasite_social_bbp_replies_pagination");
add_filter( 'bbp_topic_pagination', "firmasite_social_bbp_replies_pagination");
function firmasite_social_bbp_replies_pagination($array){
$array['type'] = 'list';
return $array;
}
function firmasite_social_bbp_get_reply_class_modal($reply_id = 0) {
/* $bbp = bbpress();
$reply_id = bbp_get_reply_id( $reply_id );
$count = isset( $bbp->reply_query->current_post ) ? $bbp->reply_query->current_post : 1;*/
global $firmasite_bbpress_count;
$firmasite_bbpress_count++;
$class = ( (int) $firmasite_bbpress_count % 2 ) ? 'panel-footer' : 'panel-body';
return $class;
}
// we re-created function for adding bootstrap tooltip. re-creating function was better solution then others
function firmasite_social_bbp_get_topic_freshness_link( $topic_id = 0 ) {
$topic_id = bbp_get_topic_id( $topic_id );
$link_url = bbp_get_topic_last_reply_url( $topic_id );
$title = bbp_get_topic_last_reply_title( $topic_id );
$time_since = bbp_get_topic_last_active_time( $topic_id );
if ( !empty( $time_since ) )
$anchor = '<a href="' . $link_url . '" data-toggle="popover" data-rel="popover" data-placement="left" data-trigger="hover" data-html="true" data-original-title="'. __( 'Freshness', 'firmasite' ) . '" data-content="' . esc_attr( $time_since ) . '"><i class="icon-time"></i></a>';
else
$anchor = __( 'No Replies', 'firmasite' );
return apply_filters( 'bbp_get_topic_freshness_link', $anchor, $topic_id );
}
// we re-created function for adding bootstrap tooltip. re-creating function was better solution then others
function firmasite_social_bbp_get_forum_freshness_link( $forum_id = 0 ) {
$forum_id = bbp_get_forum_id( $forum_id );
$active_id = bbp_get_forum_last_active_id( $forum_id );
if ( empty( $active_id ) )
$active_id = bbp_get_forum_last_reply_id( $forum_id );
if ( empty( $active_id ) )
$active_id = bbp_get_forum_last_topic_id( $forum_id );
if ( bbp_is_topic( $active_id ) ) {
$link_url = bbp_get_forum_last_topic_permalink( $forum_id );
$title = bbp_get_forum_last_topic_title( $forum_id );
} elseif ( bbp_is_reply( $active_id ) ) {
$link_url = bbp_get_forum_last_reply_url( $forum_id );
$title = bbp_get_forum_last_reply_title( $forum_id );
}
$time_since = bbp_get_forum_last_active_time( $forum_id );
if ( !empty( $time_since ) && !empty( $link_url ) )
$anchor = '<a href="' . $link_url . '" data-toggle="popover" data-rel="popover" data-placement="left" data-trigger="hover" data-html="true" data-original-title="'. __( 'Freshness', 'firmasite' ) .'" data-content="' . esc_attr( $time_since ) . '"><i class="icon-time"></i></a> '. __( 'Freshness', 'firmasite' ) . ':';
else
$anchor = __( 'No Topics', 'firmasite' );
return apply_filters( 'bbp_get_forum_freshness_link', $anchor, $forum_id );
}
// Sadly we needed to re-create bbp_get_topic_pagination just because to add 'type' => 'list' to $pagination args -.-'
function firmasite_social_bbp_get_topic_pagination( $args = '' ) {
global $wp_rewrite;
$defaults = array(
'topic_id' => bbp_get_topic_id(),
'before' => '<div class="makeit-pag-small">',
'after' => '</div>',
);
$r = bbp_parse_args( $args, $defaults, 'get_topic_pagination' );
extract( $r );
// If pretty permalinks are enabled, make our pagination pretty
if ( $wp_rewrite->using_permalinks() )
$base = trailingslashit( get_permalink( $topic_id ) ) . user_trailingslashit( $wp_rewrite->pagination_base . '/%#%/' );
else
$base = add_query_arg( 'paged', '%#%', get_permalink( $topic_id ) );
// Get total and add 1 if topic is included in the reply loop
$total = bbp_get_topic_reply_count( $topic_id, true );
// Bump if topic is in loop
if ( !bbp_show_lead_topic() )
$total++;
// Pagination settings
$pagination = array(
'type' => 'list', // yes.. this little bastard is reason to re-create that function
'base' => $base,
'format' => '',
'total' => ceil( (int) $total / (int) bbp_get_replies_per_page() ),
'current' => 0,
'prev_next' => false,
'mid_size' => 2,
'end_size' => 3,
'add_args' => ( bbp_get_view_all() ) ? array( 'view' => 'all' ) : false
);
// Add pagination to query object
$pagination_links = paginate_links( $pagination );
if ( !empty( $pagination_links ) ) {
// Remove first page from pagination
if ( $wp_rewrite->using_permalinks() ) {
$pagination_links = str_replace( $wp_rewrite->pagination_base . '/1/', '', $pagination_links );
} else {
$pagination_links = str_replace( '&paged=1', '', $pagination_links );
}
// Add before and after to pagination links
$pagination_links = $before . $pagination_links . $after;
}
return apply_filters( 'bbp_get_topic_pagination', $pagination_links, $args );
}
add_action('wp_enqueue_scripts', "firmasite_bbpress_enqueue_script" );
function firmasite_bbpress_enqueue_script() {
// Deregister WordPress comment-reply script
wp_deregister_script('bbpress-reply');
// Register our own comment-reply script for wysiwyg support
wp_register_script('bbpress-reply', get_template_directory_uri() .'/assets/js/bbpress-reply.js');
}
/**
* List replies
*
* @since bbPress (r4944)
*/
function firmasite_bbp_list_replies( $args = array() ) {
// Reset the reply depth
bbpress()->reply_query->reply_depth = 0;
// In reply loop
bbpress()->reply_query->in_the_loop = true;
$r = bbp_parse_args( $args, array(
'walker' => null,
'max_depth' => bbp_thread_replies_depth(),
'style' => 'ul',
'callback' => null,
'end_callback' => null,
'page' => 1,
'per_page' => -1
), 'list_replies' );
// Get replies to loop through in $_replies
$walker = new FirmaSite_BBP_Walker_Reply;
$walker->paged_walk( bbpress()->reply_query->posts, $r['max_depth'], $r['page'], $r['per_page'], $r );
bbpress()->max_num_pages = $walker->max_pages;
bbpress()->reply_query->in_the_loop = false;
}
/**
* Create hierarchical list of bbPress replies.
*
* @package bbPress
* @subpackage Classes
*
* @since bbPress (r4944)
*/
if ( class_exists( 'BBP_Walker_Reply' ) ) {
class FirmaSite_BBP_Walker_Reply extends BBP_Walker_Reply {
/**
* @see Walker:start_el()
*
* @since bbPress (r4944)
*/
public function start_el( &$output, $object, $depth = 0, $args = array(), $current_object_id = 0 ) {
// Set up reply
$depth++;
bbpress()->reply_query->reply_depth = $depth;
bbpress()->reply_query->post = $object;
bbpress()->current_reply_id = $object->ID;
// Check for a callback and use it if specified
if ( !empty( $args['callback'] ) ) {
call_user_func( $args['callback'], $object, $args, $depth );
return;
}
// Style for div or list element
if ( 'div' === $args['style'] ) {
$tag = 'div';
} else if ($depth>1) {
$tag = 'li class="list-unstyled panel panel-default"';
} else {
$tag = 'li class="list-unstyled"';
}?>
<<?php echo $tag ?>>
<?php if ($depth>1) { ?>
<?php bbp_get_template_part( 'loop', 'single-reply-threaded' ); ?>
<?php } else { ?>
<?php bbp_get_template_part( 'loop', 'single-reply' ); ?>
<?php } ?>
</<?php echo $tag ?>>
<?php
}
}
}
| simonkim/wp-weirdmeetup | wp-content/themes/firmasite/functions/bbpress.php | PHP | gpl-2.0 | 10,073 |
<?php
return array(
'auth_url' => 'https://auth.selcdn.ru',
'auth_user' => '20531_test0',
'auth_key' => 'RP0crKEwNw',
'container_name' => 'test0',
'container_url' => 'https://71015.selcdn.ru/test0',
'container_secret_key' => 'sjdahsasajkslamdakdjh',
);
| fhteam/selectel-storage-api | tests/data/config.php | PHP | gpl-2.0 | 278 |
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
require_once( JPATH_COMPONENT.DS.'controller.php' );
// Require specific controller if requested
if($controller = JRequest::getWord('controller')) {
$path = JPATH_COMPONENT.DS.'controllers'.DS.$controller.'.php';
if (file_exists($path)) {
require_once $path;
} else {
$controller = '';
}
}
// Create the controller
$classname = 'GplabController'.$controller;
$controller = new $classname( );
// Perform the Request task
$controller->execute( JRequest::getVar( 'task' ) );
// Redirect if set by the controller
$controller->redirect(); | grlf/eyedock | administrator/components/com_gplab/gplab.php | PHP | gpl-2.0 | 639 |
<iframe id="change_password_frame" name="change_password_frame" style="border: 0; width: 100%;height: 40px;overflow: auto">
</iframe>
<form class="normosa-ui-form" target="change_password_frame" method="post" action="<?php echo CONTEXT_PATH ?>/backend/plantation-city/users?action=update-password">
<div class="row">
<label class="label" for="password">Password</label>
<input inputtype="textbox" type="password" id="password" name="password" class="textbox w200" validation="String" min="3" maxlength="20"/>
<input inputtype="_default" type="hidden" id="id" name="id" class="textbox w200" value="<?php echo $_GET['id']?>"/>
<span class="error" style="display: block;padding-left: 210px; color: #c02;font-size: 11px; line-height: 20px; height: 20px"></span>
</div>
<div class="row">
<center><button>Update</button></center>
</div>
</form>
| anytimestream/genesisville | views/backend/pc/user-change-password-form.php | PHP | gpl-2.0 | 908 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DSIViewerPoC")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DSIViewerPoC")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bfe31832-fce5-4858-b6fe-9c442df61b3c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| sdl/Sdl-Community | Code samples/DSIViewerPoC/DSIViewerPoC/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,400 |
<?php
/**
* Elgg users
* Functions to manage multiple or single users in an Elgg install
*
* @package Elgg.Core
* @subpackage DataModel.User
*/
/// Map a username to a cached GUID
global $USERNAME_TO_GUID_MAP_CACHE;
$USERNAME_TO_GUID_MAP_CACHE = array();
/// Map a user code to a cached GUID
global $CODE_TO_GUID_MAP_CACHE;
$CODE_TO_GUID_MAP_CACHE = array();
/**
* Return the user specific details of a user by a row.
*
* @param int $guid The ElggUser guid
*
* @return mixed
* @access private
*/
function get_user_entity_as_row($guid) {
global $CONFIG;
$guid = (int)$guid;
return get_data_row("SELECT * from {$CONFIG->dbprefix}users_entity where guid=$guid");
}
/**
* Create or update the entities table for a given user.
* Call create_entity first.
*
* @param int $guid The user's GUID
* @param string $name The user's display name
* @param string $username The username
* @param string $password The password
* @param string $salt A salt for the password
* @param string $email The user's email address
* @param string $language The user's default language
* @param string $code A code
*
* @return bool
* @access private
*/
function create_user_entity($guid, $name, $username, $password, $salt, $email, $language, $code) {
global $CONFIG;
$guid = (int)$guid;
$name = sanitise_string($name);
$username = sanitise_string($username);
$password = sanitise_string($password);
$salt = sanitise_string($salt);
$email = sanitise_string($email);
$language = sanitise_string($language);
$code = sanitise_string($code);
$row = get_entity_as_row($guid);
if ($row) {
// Exists and you have access to it
$query = "SELECT guid from {$CONFIG->dbprefix}users_entity where guid = {$guid}";
if ($exists = get_data_row($query)) {
$query = "UPDATE {$CONFIG->dbprefix}users_entity
SET name='$name', username='$username', password='$password', salt='$salt',
email='$email', language='$language', code='$code'
WHERE guid = $guid";
$result = update_data($query);
if ($result != false) {
// Update succeeded, continue
$entity = get_entity($guid);
if (elgg_trigger_event('update', $entity->type, $entity)) {
return $guid;
} else {
$entity->delete();
}
}
} else {
// Exists query failed, attempt an insert.
$query = "INSERT into {$CONFIG->dbprefix}users_entity
(guid, name, username, password, salt, email, language, code)
values ($guid, '$name', '$username', '$password', '$salt', '$email', '$language', '$code')";
$result = insert_data($query);
if ($result !== false) {
$entity = get_entity($guid);
if (elgg_trigger_event('create', $entity->type, $entity)) {
return $guid;
} else {
$entity->delete();
}
}
}
}
return false;
}
/**
* Disables all of a user's entities
*
* @param int $owner_guid The owner GUID
*
* @return bool Depending on success
*/
function disable_user_entities($owner_guid) {
global $CONFIG;
$owner_guid = (int) $owner_guid;
if ($entity = get_entity($owner_guid)) {
if (elgg_trigger_event('disable', $entity->type, $entity)) {
if ($entity->canEdit()) {
$query = "UPDATE {$CONFIG->dbprefix}entities
set enabled='no' where owner_guid={$owner_guid}
or container_guid = {$owner_guid}";
$res = update_data($query);
return $res;
}
}
}
return false;
}
/**
* Ban a user
*
* @param int $user_guid The user guid
* @param string $reason A reason
*
* @return bool
*/
function ban_user($user_guid, $reason = "") {
global $CONFIG;
$user_guid = (int)$user_guid;
$user = get_entity($user_guid);
if (($user) && ($user->canEdit()) && ($user instanceof ElggUser)) {
if (elgg_trigger_event('ban', 'user', $user)) {
// Add reason
if ($reason) {
create_metadata($user_guid, 'ban_reason', $reason, '', 0, ACCESS_PUBLIC);
}
// clear "remember me" cookie code so user cannot login in using it
$user->code = "";
$user->save();
// invalidate memcache for this user
static $newentity_cache;
if ((!$newentity_cache) && (is_memcache_available())) {
$newentity_cache = new ElggMemcache('new_entity_cache');
}
if ($newentity_cache) {
$newentity_cache->delete($user_guid);
}
// Set ban flag
$query = "UPDATE {$CONFIG->dbprefix}users_entity set banned='yes' where guid=$user_guid";
return update_data($query);
}
return FALSE;
}
return FALSE;
}
/**
* Unban a user.
*
* @param int $user_guid Unban a user.
*
* @return bool
*/
function unban_user($user_guid) {
global $CONFIG;
$user_guid = (int)$user_guid;
$user = get_entity($user_guid);
if (($user) && ($user->canEdit()) && ($user instanceof ElggUser)) {
if (elgg_trigger_event('unban', 'user', $user)) {
create_metadata($user_guid, 'ban_reason', '', '', 0, ACCESS_PUBLIC);
// invalidate memcache for this user
static $newentity_cache;
if ((!$newentity_cache) && (is_memcache_available())) {
$newentity_cache = new ElggMemcache('new_entity_cache');
}
if ($newentity_cache) {
$newentity_cache->delete($user_guid);
}
$query = "UPDATE {$CONFIG->dbprefix}users_entity set banned='no' where guid=$user_guid";
return update_data($query);
}
return FALSE;
}
return FALSE;
}
/**
* Makes user $guid an admin.
*
* @param int $user_guid User guid
*
* @return bool
*/
function make_user_admin($user_guid) {
global $CONFIG;
$user = get_entity((int)$user_guid);
if (($user) && ($user instanceof ElggUser) && ($user->canEdit())) {
if (elgg_trigger_event('make_admin', 'user', $user)) {
// invalidate memcache for this user
static $newentity_cache;
if ((!$newentity_cache) && (is_memcache_available())) {
$newentity_cache = new ElggMemcache('new_entity_cache');
}
if ($newentity_cache) {
$newentity_cache->delete($user_guid);
}
$r = update_data("UPDATE {$CONFIG->dbprefix}users_entity set admin='yes' where guid=$user_guid");
_elgg_invalidate_cache_for_entity($user_guid);
return $r;
}
return FALSE;
}
return FALSE;
}
/**
* Removes user $guid's admin flag.
*
* @param int $user_guid User GUID
*
* @return bool
*/
function remove_user_admin($user_guid) {
global $CONFIG;
$user = get_entity((int)$user_guid);
if (($user) && ($user instanceof ElggUser) && ($user->canEdit())) {
if (elgg_trigger_event('remove_admin', 'user', $user)) {
// invalidate memcache for this user
static $newentity_cache;
if ((!$newentity_cache) && (is_memcache_available())) {
$newentity_cache = new ElggMemcache('new_entity_cache');
}
if ($newentity_cache) {
$newentity_cache->delete($user_guid);
}
$r = update_data("UPDATE {$CONFIG->dbprefix}users_entity set admin='no' where guid=$user_guid");
_elgg_invalidate_cache_for_entity($user_guid);
return $r;
}
return FALSE;
}
return FALSE;
}
/**
* Get the sites this user is part of
*
* @param int $user_guid The user's GUID
* @param int $limit Number of results to return
* @param int $offset Any indexing offset
*
* @return ElggSite[]|false On success, an array of ElggSites
*/
function get_user_sites($user_guid, $limit = 10, $offset = 0) {
$user_guid = (int)$user_guid;
$limit = (int)$limit;
$offset = (int)$offset;
return elgg_get_entities_from_relationship(array(
'site_guids' => ELGG_ENTITIES_ANY_VALUE,
'relationship' => 'member_of_site',
'relationship_guid' => $user_guid,
'inverse_relationship' => FALSE,
'type' => 'site',
'limit' => $limit,
'offset' => $offset,
));
}
/**
* Adds a user to another user's friends list.
*
* @param int $user_guid The GUID of the friending user
* @param int $friend_guid The GUID of the user to friend
*
* @return bool Depending on success
*/
function user_add_friend($user_guid, $friend_guid) {
$user_guid = (int) $user_guid;
$friend_guid = (int) $friend_guid;
if ($user_guid == $friend_guid) {
return false;
}
if (!$friend = get_entity($friend_guid)) {
return false;
}
if (!$user = get_entity($user_guid)) {
return false;
}
if ((!($user instanceof ElggUser)) || (!($friend instanceof ElggUser))) {
return false;
}
return add_entity_relationship($user_guid, "friend", $friend_guid);
}
/**
* Removes a user from another user's friends list.
*
* @param int $user_guid The GUID of the friending user
* @param int $friend_guid The GUID of the user on the friends list
*
* @return bool Depending on success
*/
function user_remove_friend($user_guid, $friend_guid) {
$user_guid = (int) $user_guid;
$friend_guid = (int) $friend_guid;
// perform cleanup for access lists.
$collections = get_user_access_collections($user_guid);
if ($collections) {
foreach ($collections as $collection) {
remove_user_from_access_collection($friend_guid, $collection->id);
}
}
return remove_entity_relationship($user_guid, "friend", $friend_guid);
}
/**
* Determines whether or not a user is another user's friend.
*
* @param int $user_guid The GUID of the user
* @param int $friend_guid The GUID of the friend
*
* @return bool
*/
function user_is_friend($user_guid, $friend_guid) {
return check_entity_relationship($user_guid, "friend", $friend_guid) !== false;
}
/**
* Obtains a given user's friends
*
* @param int $user_guid The user's GUID
* @param string $subtype The subtype of users, if any
* @param int $limit Number of results to return (default 10)
* @param int $offset Indexing offset, if any
*
* @return ElggUser[]|false Either an array of ElggUsers or false, depending on success
*/
function get_user_friends($user_guid, $subtype = ELGG_ENTITIES_ANY_VALUE, $limit = 10,
$offset = 0) {
return elgg_get_entities_from_relationship(array(
'relationship' => 'friend',
'relationship_guid' => $user_guid,
'type' => 'user',
'subtype' => $subtype,
'limit' => $limit,
'offset' => $offset
));
}
/**
* Obtains the people who have made a given user a friend
*
* @param int $user_guid The user's GUID
* @param string $subtype The subtype of users, if any
* @param int $limit Number of results to return (default 10)
* @param int $offset Indexing offset, if any
*
* @return ElggUser[]|false Either an array of ElggUsers or false, depending on success
*/
function get_user_friends_of($user_guid, $subtype = ELGG_ENTITIES_ANY_VALUE, $limit = 10,
$offset = 0) {
return elgg_get_entities_from_relationship(array(
'relationship' => 'friend',
'relationship_guid' => $user_guid,
'inverse_relationship' => TRUE,
'type' => 'user',
'subtype' => $subtype,
'limit' => $limit,
'offset' => $offset
));
}
/**
* Obtains a list of objects owned by a user's friends
*
* @param int $user_guid The GUID of the user to get the friends of
* @param string $subtype Optionally, the subtype of objects
* @param int $limit The number of results to return (default 10)
* @param int $offset Indexing offset, if any
* @param int $timelower The earliest time the entity can have been created. Default: all
* @param int $timeupper The latest time the entity can have been created. Default: all
*
* @return ElggObject[]|false An array of ElggObjects or false, depending on success
*/
function get_user_friends_objects($user_guid, $subtype = ELGG_ENTITIES_ANY_VALUE, $limit = 10,
$offset = 0, $timelower = 0, $timeupper = 0) {
if ($friends = get_user_friends($user_guid, "", 999999, 0)) {
$friendguids = array();
foreach ($friends as $friend) {
$friendguids[] = $friend->getGUID();
}
return elgg_get_entities(array(
'type' => 'object',
'subtype' => $subtype,
'owner_guids' => $friendguids,
'limit' => $limit,
'offset' => $offset,
'container_guids' => $friendguids,
'created_time_lower' => $timelower,
'created_time_upper' => $timeupper
));
}
return FALSE;
}
/**
* Counts the number of objects owned by a user's friends
*
* @param int $user_guid The GUID of the user to get the friends of
* @param string $subtype Optionally, the subtype of objects
* @param int $timelower The earliest time the entity can have been created. Default: all
* @param int $timeupper The latest time the entity can have been created. Default: all
*
* @return int The number of objects
*/
function count_user_friends_objects($user_guid, $subtype = ELGG_ENTITIES_ANY_VALUE,
$timelower = 0, $timeupper = 0) {
if ($friends = get_user_friends($user_guid, "", 999999, 0)) {
$friendguids = array();
foreach ($friends as $friend) {
$friendguids[] = $friend->getGUID();
}
return elgg_get_entities(array(
'type' => 'object',
'subtype' => $subtype,
'owner_guids' => $friendguids,
'count' => TRUE,
'container_guids' => $friendguids,
'created_time_lower' => $timelower,
'created_time_upper' => $timeupper
));
}
return 0;
}
/**
* Displays a list of a user's friends' objects of a particular subtype, with navigation.
*
* @see elgg_view_entity_list
*
* @param int $user_guid The GUID of the user
* @param string $subtype The object subtype
* @param int $limit The number of entities to display on a page
* @param bool $full_view Whether or not to display the full view (default: true)
* @param bool $listtypetoggle Whether or not to allow you to flip to gallery mode (default: true)
* @param bool $pagination Whether to display pagination (default: true)
* @param int $timelower The earliest time the entity can have been created. Default: all
* @param int $timeupper The latest time the entity can have been created. Default: all
*
* @return string
*/
function list_user_friends_objects($user_guid, $subtype = "", $limit = 10, $full_view = true,
$listtypetoggle = true, $pagination = true, $timelower = 0, $timeupper = 0) {
$offset = (int)get_input('offset');
$limit = (int)$limit;
$count = (int)count_user_friends_objects($user_guid, $subtype, $timelower, $timeupper);
$entities = get_user_friends_objects($user_guid, $subtype, $limit, $offset,
$timelower, $timeupper);
return elgg_view_entity_list($entities, array(
'count' => $count,
'offset' => $offset,
'limit' => $limit,
'full_view' => $full_view,
'list_type_toggle' => $listtypetoggle,
'pagination' => $pagination,
));
}
/**
* Get a user object from a GUID.
*
* This function returns an ElggUser from a given GUID.
*
* @param int $guid The GUID
*
* @return ElggUser|false
*/
function get_user($guid) {
// Fixes "Exception thrown without stack frame" when db_select fails
if (!empty($guid)) {
$result = get_entity($guid);
}
if ((!empty($result)) && (!($result instanceof ElggUser))) {
return false;
}
if (!empty($result)) {
return $result;
}
return false;
}
/**
* Get user by username
*
* @param string $username The user's username
*
* @return ElggUser|false Depending on success
*/
function get_user_by_username($username) {
global $CONFIG, $USERNAME_TO_GUID_MAP_CACHE;
// Fixes #6052. Username is frequently sniffed from the path info, which,
// unlike $_GET, is not URL decoded. If the username was not URL encoded,
// this is harmless.
$username = rawurldecode($username);
$username = sanitise_string($username);
$access = get_access_sql_suffix('e');
// Caching
if ((isset($USERNAME_TO_GUID_MAP_CACHE[$username]))
&& (_elgg_retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username]))) {
return _elgg_retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username]);
}
$query = "SELECT e.* from {$CONFIG->dbprefix}users_entity u
join {$CONFIG->dbprefix}entities e on e.guid=u.guid
where u.username='$username' and $access ";
$entity = get_data_row($query, 'entity_row_to_elggstar');
if ($entity) {
$USERNAME_TO_GUID_MAP_CACHE[$username] = $entity->guid;
} else {
$entity = false;
}
return $entity;
}
/**
* Get user by session code
*
* @param string $code The session code
*
* @return ElggUser|false Depending on success
*/
function get_user_by_code($code) {
global $CONFIG, $CODE_TO_GUID_MAP_CACHE;
$code = sanitise_string($code);
$access = get_access_sql_suffix('e');
// Caching
if ((isset($CODE_TO_GUID_MAP_CACHE[$code]))
&& (_elgg_retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code]))) {
return _elgg_retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code]);
}
$query = "SELECT e.* from {$CONFIG->dbprefix}users_entity u
join {$CONFIG->dbprefix}entities e on e.guid=u.guid
where u.code='$code' and $access";
$entity = get_data_row($query, 'entity_row_to_elggstar');
if ($entity) {
$CODE_TO_GUID_MAP_CACHE[$code] = $entity->guid;
}
return $entity;
}
/**
* Get an array of users from an email address
*
* @param string $email Email address.
*
* @return array
*/
function get_user_by_email($email) {
global $CONFIG;
$email = sanitise_string($email);
$access = get_access_sql_suffix('e');
$query = "SELECT e.* from {$CONFIG->dbprefix}entities e
join {$CONFIG->dbprefix}users_entity u on e.guid=u.guid
where email='$email' and $access";
return get_data($query, 'entity_row_to_elggstar');
}
/**
* A function that returns a maximum of $limit users who have done something within the last
* $seconds seconds or the total count of active users.
*
* @param int $seconds Number of seconds (default 600 = 10min)
* @param int $limit Limit, default 10.
* @param int $offset Offset, default 0.
* @param bool $count Count, default false.
*
* @return mixed
*/
function find_active_users($seconds = 600, $limit = 10, $offset = 0, $count = false) {
$seconds = (int)$seconds;
$limit = (int)$limit;
$offset = (int)$offset;
$params = array('seconds' => $seconds, 'limit' => $limit, 'offset' => $offset, 'count' => $count);
$data = elgg_trigger_plugin_hook('find_active_users', 'system', $params, NULL);
if (!$data) {
global $CONFIG;
$time = time() - $seconds;
$data = elgg_get_entities(array(
'type' => 'user',
'limit' => $limit,
'offset' => $offset,
'count' => $count,
'joins' => array("join {$CONFIG->dbprefix}users_entity u on e.guid = u.guid"),
'wheres' => array("u.last_action >= {$time}"),
'order_by' => "u.last_action desc"
));
}
return $data;
}
/**
* Generate and send a password request email to a given user's registered email address.
*
* @param int $user_guid User GUID
*
* @return bool
*/
function send_new_password_request($user_guid) {
$user_guid = (int)$user_guid;
$user = get_entity($user_guid);
if ($user instanceof ElggUser) {
// generate code
$code = generate_random_cleartext_password();
$user->setPrivateSetting('passwd_conf_code', $code);
// generate link
$link = elgg_get_site_url() . "resetpassword?u=$user_guid&c=$code";
// generate email
$email = '<div style="color:#333;font-size:16px;">'
.elgg_echo('email:resetreq:body', array($user->name, $link)).'</div>';
//return notify_user($user->guid, elgg_get_site_entity()->guid,
// elgg_echo('email:resetreq:subject'), $email, array(), 'email');
$site_name = elgg_get_site_entity()->name;
return zhgroups_send_email($site_name, $user->email,
elgg_echo('email:resetreq:subject', array($site_name)), $email);
}
return false;
}
/**
* Low level function to reset a given user's password.
*
* This can only be called from execute_new_password_request().
*
* @param int $user_guid The user.
* @param string $password Text (which will then be converted into a hash and stored)
*
* @return bool
*/
function force_user_password_reset($user_guid, $password) {
$user = get_entity($user_guid);
if ($user instanceof ElggUser) {
$ia = elgg_set_ignore_access();
$user->salt = _elgg_generate_password_salt();
$hash = generate_user_password($user, $password);
$user->password = $hash;
$result = (bool)$user->save();
elgg_set_ignore_access($ia);
return $result;
}
return false;
}
/**
* Validate and execute a password reset for a user.
*
* @param int $user_guid The user id
* @param string $conf_code Confirmation code as sent in the request email.
*
* @return mixed
*/
function execute_new_password_request($user_guid, $conf_code) {
global $CONFIG;
$user_guid = (int)$user_guid;
$user = get_entity($user_guid);
if ($user instanceof ElggUser) {
$saved_code = $user->getPrivateSetting('passwd_conf_code');
if ($saved_code && $saved_code == $conf_code) {
$password = generate_random_cleartext_password();
if (force_user_password_reset($user_guid, $password)) {
remove_private_setting($user_guid, 'passwd_conf_code');
// clean the logins failures
reset_login_failure_count($user_guid);
$email = '<div style="color:#333;font-size:16px;">'
.elgg_echo('email:resetpassword:body', array($user->name, $password)).'</div>';
//return notify_user($user->guid, $CONFIG->site->guid,
// elgg_echo('email:resetpassword:subject'), $email, array(), 'email');
$site_name = elgg_get_site_entity()->name;
return zhgroups_send_email($site_name, $user->email,
elgg_echo('email:resetpassword:subject', array($site_name)), $email);
}
}
}
return FALSE;
}
/**
* Generate a random 12 character clear text password.
*
* @return string
*/
function generate_random_cleartext_password() {
return ElggCrypto::getRandomString(12, ElggCrypto::CHARS_PASSWORD);
}
/**
* Generate an 8 character Base64 URL salt for the password
*
* @return string
* @access private
*/
function _elgg_generate_password_salt() {
return ElggCrypto::getRandomString(8);
}
/**
* Hash a password for storage. Currently salted MD5.
*
* @param ElggUser $user The user this is being generated for.
* @param string $password Password in clear text
*
* @return string
*/
function generate_user_password(ElggUser $user, $password) {
return md5($password . $user->salt);
}
/**
* Simple function which ensures that a username contains only valid characters.
*
* This should only permit chars that are valid on the file system as well.
*
* @param string $username Username
*
* @return bool
* @throws RegistrationException on invalid
*/
function validate_username($username) {
global $CONFIG;
// Basic, check length
if (!isset($CONFIG->minusername)) {
$CONFIG->minusername = 4;
}
if (strlen($username) < $CONFIG->minusername) {
$msg = elgg_echo('registration:usernametooshort', array($CONFIG->minusername));
throw new RegistrationException($msg);
}
// username in the database has a limit of 60 characters
if (strlen($username) > 60) {
$msg = elgg_echo('registration:usernametoolong').elgg_echo('input:max', array(20, 60));
throw new RegistrationException($msg);
}
// Blacklist for bad characters (partially nicked from mediawiki)
$blacklist = '/[' .
'\x{0080}-\x{009f}' . // iso-8859-1 control chars
'\x{00a0}' . // non-breaking space
'\x{2000}-\x{200f}' . // various whitespace
'\x{2028}-\x{202f}' . // breaks and control chars
'\x{3000}' . // ideographic space
'\x{e000}-\x{f8ff}' . // private use
']/u';
if (
preg_match($blacklist, $username)
) {
// @todo error message needs work
throw new RegistrationException(elgg_echo('registration:invalidchars'));
}
// Belts and braces
// @todo Tidy into main unicode
$blacklist2 = '\'/\\"*& ?#%^(){}[]~?<>;|¬`@-+=';
for ($n = 0; $n < strlen($blacklist2); $n++) {
if (strpos($username, $blacklist2[$n]) !== false) {
$msg = elgg_echo('registration:invalidchars', array($blacklist2[$n], $blacklist2));
$msg = htmlspecialchars($msg, ENT_QUOTES, 'UTF-8');
throw new RegistrationException($msg);
}
}
$result = true;
return elgg_trigger_plugin_hook('registeruser:validate:username', 'all',
array('username' => $username), $result);
}
/**
* Simple validation of a password.
*
* @param string $password Clear text password
*
* @return bool
* @throws RegistrationException on invalid
*/
function validate_password($password) {
global $CONFIG;
if (!isset($CONFIG->min_password_length)) {
$CONFIG->min_password_length = 6;
}
if (strlen($password) < $CONFIG->min_password_length) {
$msg = elgg_echo('registration:passwordtooshort', array($CONFIG->min_password_length));
throw new RegistrationException($msg);
}
$result = true;
return elgg_trigger_plugin_hook('registeruser:validate:password', 'all',
array('password' => $password), $result);
}
/**
* Simple validation of a email.
*
* @param string $address Email address
*
* @throws RegistrationException on invalid
* @return bool
*/
function validate_email_address($address) {
if (!is_email_address($address)) {
throw new RegistrationException(elgg_echo('registration:notemail'));
}
// Got here, so lets try a hook (defaulting to ok)
$result = true;
return elgg_trigger_plugin_hook('registeruser:validate:email', 'all',
array('email' => $address), $result);
}
/**
* Registers a user, returning false if the username already exists
*
* @param string $username The username of the new user
* @param string $password The password
* @param string $name The user's display name
* @param string $email Their email address
* @param bool $allow_multiple_emails Allow the same email address to be
* registered multiple times?
* @param int $friend_guid GUID of a user to friend once fully registered
* @param string $invitecode An invite code from a friend
*
* @return int|false The new user's GUID; false on failure
* @throws RegistrationException
*/
function register_user($username, $password, $name, $email,
$allow_multiple_emails = false, $friend_guid = 0, $invitecode = '') {
// no need to trim password.
$username = trim($username);
$name = trim(strip_tags($name));
$email = trim($email);
// A little sanity checking
if (empty($username)
|| empty($password)
|| empty($name)
|| empty($email)) {
return false;
}
// Make sure a user with conflicting details hasn't registered and been disabled
$access_status = access_get_show_hidden_status();
access_show_hidden_entities(true);
if (strlen($name) > 60) {
$msg = elgg_echo('registration:nametoolong').elgg_echo('input:max', array(20, 60));
throw new RegistrationException($msg);
}
if (strlen($email) > 60) {
$msg = elgg_echo('registration:emailtoolong', array(60));
throw new RegistrationException($msg);
}
if (strlen($password) > 60) {
$msg = elgg_echo('registration:passwordtoolong', array(60));
throw new RegistrationException($msg);
}
if (!validate_email_address($email)) {
throw new RegistrationException(elgg_echo('registration:emailnotvalid'));
}
if (!validate_password($password)) {
throw new RegistrationException(elgg_echo('registration:passwordnotvalid'));
}
if (!validate_username($username)) {
throw new RegistrationException(elgg_echo('registration:usernamenotvalid'));
}
if ($user = get_user_by_username($username)) {
throw new RegistrationException(elgg_echo('registration:userexists'));
}
if ((!$allow_multiple_emails) && (get_user_by_email($email))) {
throw new RegistrationException(elgg_echo('registration:dupeemail'));
}
access_show_hidden_entities($access_status);
// Create user
$user = new ElggUser();
$user->username = $username;
$user->email = $email;
$user->name = $name;
$user->access_id = ACCESS_PUBLIC;
$user->salt = _elgg_generate_password_salt();
$user->password = generate_user_password($user, $password);
$user->owner_guid = 0; // Users aren't owned by anyone, even if they are admin created.
$user->container_guid = 0; // Users aren't contained by anyone, even if they are admin created.
$user->language = get_current_language();
$user->save();
// If $friend_guid has been set, make mutual friends
if ($friend_guid) {
if ($friend_user = get_user($friend_guid)) {
if ($invitecode == generate_invite_code($friend_user->username)) {
$user->addFriend($friend_guid);
$friend_user->addFriend($user->guid);
// @todo Should this be in addFriend?
add_to_river('river/relationship/friend/create', 'friend', $user->getGUID(), $friend_guid);
add_to_river('river/relationship/friend/create', 'friend', $friend_guid, $user->getGUID());
}
}
}
// Turn on email notifications by default
set_user_notification_setting($user->getGUID(), 'email', true);
set_user_notification_setting($user->getGUID(), 'site', true);
return $user->getGUID();
}
/**
* Generates a unique invite code for a user
*
* @param string $username The username of the user sending the invitation
*
* @return string Invite code
*/
function generate_invite_code($username) {
$secret = datalist_get('__site_secret__');
return md5($username . $secret);
}
/**
* Set the validation status for a user.
*
* @param int $user_guid The user's GUID
* @param bool $status Validated (true) or unvalidated (false)
* @param string $method Optional method to say how a user was validated
* @return bool
* @since 1.8.0
*/
function elgg_set_user_validation_status($user_guid, $status, $method = '') {
$result1 = create_metadata($user_guid, 'validated', $status, '', 0, ACCESS_PUBLIC, false);
$result2 = create_metadata($user_guid, 'validated_method', $method, '', 0, ACCESS_PUBLIC, false);
if ($result1 && $result2) {
return true;
} else {
return false;
}
}
/**
* Gets the validation status of a user.
*
* @param int $user_guid The user's GUID
* @return bool|null Null means status was not set for this user.
* @since 1.8.0
*/
function elgg_get_user_validation_status($user_guid) {
$md = elgg_get_metadata(array(
'guid' => $user_guid,
'metadata_name' => 'validated'
));
if ($md == false) {
return null;
}
if ($md[0]->value) {
return true;
}
return false;
}
/**
* Adds collection submenu items
*
* @return void
* @access private
*/
function collections_submenu_items() {
$user = elgg_get_logged_in_user_entity();
elgg_register_menu_item('page', array(
'name' => 'friends:view:collections',
'text' => elgg_echo('friends:collections'),
'href' => "collections/$user->username",
));
}
/**
* Page handler for friends-related pages
*
* @param array $segments URL segments
* @param string $handler The first segment in URL used for routing
*
* @return bool
* @access private
*/
function friends_page_handler($segments, $handler) {
elgg_set_context('friends');
if (isset($segments[0]) && $user = get_user_by_username($segments[0])) {
elgg_set_page_owner_guid($user->getGUID());
}
if (elgg_get_logged_in_user_guid() == elgg_get_page_owner_guid()) {
collections_submenu_items();
}
switch ($handler) {
case 'friends':
require_once(dirname(dirname(dirname(__FILE__))) . "/pages/friends/index.php");
break;
case 'friendsof':
require_once(dirname(dirname(dirname(__FILE__))) . "/pages/friends/of.php");
break;
default:
return false;
}
return true;
}
/**
* Page handler for friends collections
*
* @param array $page_elements Page elements
*
* @return bool
* @access private
*/
function collections_page_handler($page_elements) {
gatekeeper();
elgg_set_context('friends');
$base = elgg_get_config('path');
if (isset($page_elements[0])) {
if ($page_elements[0] == "add") {
elgg_set_page_owner_guid(elgg_get_logged_in_user_guid());
collections_submenu_items();
require_once "{$base}pages/friends/collections/add.php";
return true;
} else {
$user = get_user_by_username($page_elements[0]);
if ($user) {
elgg_set_page_owner_guid($user->getGUID());
if (elgg_get_logged_in_user_guid() == elgg_get_page_owner_guid()) {
collections_submenu_items();
}
require_once "{$base}pages/friends/collections/view.php";
return true;
}
}
}
return false;
}
/**
* Page handler for account related pages
*
* @param array $page_elements Page elements
* @param string $handler The handler string
*
* @return bool
* @access private
*/
function elgg_user_account_page_handler($page_elements, $handler) {
$base_dir = elgg_get_root_path() . 'pages/account';
switch ($handler) {
case 'login':
require_once("$base_dir/login.php");
break;
case 'forgotpassword':
require_once("$base_dir/forgotten_password.php");
break;
case 'resetpassword':
require_once("$base_dir/reset_password.php");
break;
case 'register':
require_once("$base_dir/register.php");
break;
default:
return false;
}
return true;
}
/**
* Sets the last action time of the given user to right now.
*
* @param int $user_guid The user GUID
*
* @return void
*/
function set_last_action($user_guid) {
$user_guid = (int) $user_guid;
global $CONFIG;
$time = time();
$query = "UPDATE {$CONFIG->dbprefix}users_entity
set prev_last_action = last_action,
last_action = {$time} where guid = {$user_guid}";
execute_delayed_write_query($query);
}
/**
* Sets the last logon time of the given user to right now.
*
* @param int $user_guid The user GUID
*
* @return void
*/
function set_last_login($user_guid) {
$user_guid = (int) $user_guid;
global $CONFIG;
$time = time();
$query = "UPDATE {$CONFIG->dbprefix}users_entity
set prev_last_login = last_login, last_login = {$time} where guid = {$user_guid}";
execute_delayed_write_query($query);
}
/**
* Creates a relationship between this site and the user.
*
* @param string $event create
* @param string $object_type user
* @param ElggUser $object User object
*
* @return void
* @access private
*/
function user_create_hook_add_site_relationship($event, $object_type, $object) {
add_entity_relationship($object->getGUID(), 'member_of_site', elgg_get_site_entity()->guid);
}
/**
* Serves the user's avatar
*
* @param string $hook
* @param string $entity_type
* @param string $returnvalue
* @param array $params
* @return string
* @access private
*/
function user_avatar_hook($hook, $entity_type, $returnvalue, $params) {
$user = $params['entity'];
$size = $params['size'];
if (isset($user->icontime)) {
return "avatar/view/$user->username/$size/$user->icontime";
} else {
return "_graphics/icons/user/default{$size}.gif";
}
}
/**
* Setup the default user hover menu
* @access private
*/
function elgg_user_hover_menu($hook, $type, $return, $params) {
$user = $params['entity'];
/* @var ElggUser $user */
if (elgg_is_logged_in()) {
// remove add friend from profile page
// if (elgg_get_logged_in_user_guid() != $user->guid) {
// if ($user->isFriend()) {
// $url = "action/friends/remove?friend={$user->guid}";
// $text = elgg_echo('friend:remove');
// $name = 'remove_friend';
// } else {
// $url = "action/friends/add?friend={$user->guid}";
// $text = elgg_echo('friend:add');
// $name = 'add_friend';
// }
// $url = elgg_add_action_tokens_to_url($url);
// $item = new ElggMenuItem($name, $text, $url);
// $item->setSection('action');
// $return[] = $item;
// }
if (elgg_get_logged_in_user_guid() == $user->guid) {
$url = "profile/$user->username/edit";
$item = new ElggMenuItem('profile:edit', elgg_echo('profile:edit'), $url);
$item->setSection('action');
$return[] = $item;
$url = "avatar/edit/$user->username";
$item = new ElggMenuItem('avatar:edit', elgg_echo('avatar:edit'), $url);
$item->setSection('action');
$return[] = $item;
if(elgg_get_viewtype() == 'mobile'){
$url = "profile/$user->username/view";
$itemText = 'profile:view';
}
else{
$url = "profile/$user->username";
$itemText = 'profile:home_page';
}
$item = new ElggMenuItem('profile:home_page', elgg_echo($itemText), $url);
$item->setSection('action');
$return[] = $item;
if(elgg_get_viewtype() == 'mobile'){
$url = "action/logout";
$item = new ElggMenuItem('profile:logout', elgg_echo('logout'), $url);
$item->setSection('action');
$item->setPriority(1);
$return[] = $item;
}
}
}
// prevent admins from banning or deleting themselves
if (elgg_get_logged_in_user_guid() == $user->guid) {
return $return;
}
if (elgg_is_admin_logged_in()) {
$actions = array();
if (!$user->isBanned()) {
$actions[] = 'ban';
} else {
$actions[] = 'unban';
}
$actions[] = 'delete';
$actions[] = 'resetpassword';
if (!$user->isAdmin()) {
$actions[] = 'makeadmin';
} else {
$actions[] = 'removeadmin';
}
foreach ($actions as $action) {
$url = "action/admin/user/$action?guid={$user->guid}";
$url = elgg_add_action_tokens_to_url($url);
$item = new ElggMenuItem($action, elgg_echo($action), $url);
$item->setSection('admin');
$item->setLinkClass('elgg-requires-confirmation');
$return[] = $item;
}
$url = "profile/$user->username/edit";
$item = new ElggMenuItem('profile:edit', elgg_echo('profile:edit'), $url);
$item->setSection('admin');
$return[] = $item;
$url = "settings/user/$user->username";
$item = new ElggMenuItem('settings:edit', elgg_echo('settings:edit'), $url);
$item->setSection('admin');
$return[] = $item;
}
return $return;
}
/**
* Setup the menu shown with an entity
*
* @param string $hook
* @param string $type
* @param array $return
* @param array $params
* @return array
*
* @access private
*/
function elgg_users_setup_entity_menu($hook, $type, $return, $params) {
if (elgg_in_context('widgets')) {
return $return;
}
$entity = $params['entity'];
if (!elgg_instanceof($entity, 'user')) {
return $return;
}
/* @var ElggUser $entity */
if ($entity->isBanned()) {
$banned = elgg_echo('banned');
$options = array(
'name' => 'banned',
'text' => "<span>$banned</span>",
'href' => false,
'priority' => 0,
);
$return = array(ElggMenuItem::factory($options));
} else {
$return = array();
if (isset($entity->location)) {
$location = htmlspecialchars($entity->location, ENT_QUOTES, 'UTF-8', false);
$options = array(
'name' => 'location',
'text' => "<span>$location</span>",
'href' => false,
'priority' => 150,
);
$return[] = ElggMenuItem::factory($options);
}
}
return $return;
}
/**
* This function loads a set of default fields into the profile, then triggers a hook letting other plugins to edit
* add and delete fields.
*
* Note: This is a secondary system:init call and is run at a super low priority to guarantee that it is called after all
* other plugins have initialised.
* @access private
*/
function elgg_profile_fields_setup() {
global $CONFIG;
$profile_defaults = array (
'description' => 'longtext',
'briefdescription' => 'text',
'location' => 'location',
'interests' => 'tags',
'skills' => 'tags',
'contactemail' => 'email',
'phone' => 'text',
'mobile' => 'text',
'website' => 'url',
'twitter' => 'text'
);
$loaded_defaults = array();
if ($fieldlist = elgg_get_config('profile_custom_fields')) {
if (!empty($fieldlist)) {
$fieldlistarray = explode(',', $fieldlist);
foreach ($fieldlistarray as $listitem) {
if ($translation = elgg_get_config("admin_defined_profile_{$listitem}")) {
$type = elgg_get_config("admin_defined_profile_type_{$listitem}");
$loaded_defaults["admin_defined_profile_{$listitem}"] = $type;
add_translation(get_current_language(), array("profile:admin_defined_profile_{$listitem}" => $translation));
}
}
}
}
if (count($loaded_defaults)) {
$CONFIG->profile_using_custom = true;
$profile_defaults = $loaded_defaults;
}
$CONFIG->profile_fields = elgg_trigger_plugin_hook('profile:fields', 'profile', NULL, $profile_defaults);
// register any tag metadata names
foreach ($CONFIG->profile_fields as $name => $type) {
if ($type == 'tags' || $type == 'location' || $type == 'tag') {
elgg_register_tag_metadata_name($name);
// register a tag name translation
add_translation(get_current_language(), array("tag_names:$name" => elgg_echo("profile:$name")));
}
}
}
/**
* Avatar page handler
*
* /avatar/edit/<username>
* /avatar/view/<username>/<size>/<icontime>
*
* @param array $page
* @return bool
* @access private
*/
function elgg_avatar_page_handler($page) {
global $CONFIG;
$user = get_user_by_username($page[1]);
if ($user) {
elgg_set_page_owner_guid($user->getGUID());
}
if ($page[0] == 'edit') {
require_once("{$CONFIG->path}pages/avatar/edit.php");
return true;
} else {
set_input('size', $page[2]);
require_once("{$CONFIG->path}pages/avatar/view.php");
return true;
}
return false;
}
/**
* Profile page handler
*
* @param array $page
* @return bool
* @access private
*/
function elgg_profile_page_handler($page) {
global $CONFIG;
$user = get_user_by_username($page[0]);
elgg_set_page_owner_guid($user->guid);
if ($page[1] == 'edit') {
require_once("{$CONFIG->path}pages/profile/edit.php");
return true;
}
return false;
}
/**
* Sets up user-related menu items
*
* @return void
* @access private
*/
function users_pagesetup() {
$owner = elgg_get_page_owner_entity();
$viewer = elgg_get_logged_in_user_entity();
if ($owner) {
$params = array(
'name' => 'friends',
'text' => elgg_echo('friends'),
'href' => 'friends/' . $owner->username,
'contexts' => array('friends')
);
elgg_register_menu_item('page', $params);
$params = array(
'name' => 'friends:of',
'text' => elgg_echo('friends:of'),
'href' => 'friendsof/' . $owner->username,
'contexts' => array('friends')
);
elgg_register_menu_item('page', $params);
elgg_register_menu_item('page', array(
'name' => 'edit_avatar',
'href' => "avatar/edit/{$owner->username}",
'text' => elgg_echo('avatar:edit'),
'contexts' => array('profile_edit'),
));
elgg_register_menu_item('page', array(
'name' => 'edit_profile',
'href' => "profile/{$owner->username}/edit",
'text' => elgg_echo('profile:edit'),
'contexts' => array('profile_edit'),
));
}
// topbar
if ($viewer) {
elgg_register_menu_item('topbar', array(
'name' => 'profile',
'href' => $viewer->getURL(),
'text' => elgg_view('output/img', array(
'src' => $viewer->getIconURL('topbar'),
'alt' => $viewer->name,
'title' => elgg_echo('profile'),
'class' => 'elgg-border-plain elgg-transition',
)),
'priority' => 100,
'link_class' => 'elgg-topbar-avatar',
));
elgg_register_menu_item('topbar', array(
'name' => 'friends',
'href' => "friends/{$viewer->username}",
'text' => elgg_view_icon('users'),
'title' => elgg_echo('friends'),
'priority' => 300,
));
elgg_register_menu_item('topbar', array(
'name' => 'usersettings',
'href' => "settings/user/{$viewer->username}",
'text' => elgg_view_icon('settings') . elgg_echo('settings'),
'priority' => 500,
'section' => 'alt',
));
elgg_register_menu_item('topbar', array(
'name' => 'logout',
'href' => "action/logout",
'text' => elgg_echo('logout'),
'is_action' => TRUE,
'priority' => 1000,
'section' => 'alt',
));
}
}
/**
* Users initialisation function, which establishes the page handler
*
* @return void
* @access private
*/
function users_init() {
elgg_register_page_handler('friends', 'friends_page_handler');
elgg_register_page_handler('friendsof', 'friends_page_handler');
elgg_register_page_handler('register', 'elgg_user_account_page_handler');
elgg_register_page_handler('forgotpassword', 'elgg_user_account_page_handler');
elgg_register_page_handler('resetpassword', 'elgg_user_account_page_handler');
elgg_register_page_handler('login', 'elgg_user_account_page_handler');
elgg_register_page_handler('avatar', 'elgg_avatar_page_handler');
elgg_register_page_handler('profile', 'elgg_profile_page_handler');
elgg_register_page_handler('collections', 'collections_page_handler');
elgg_register_plugin_hook_handler('register', 'menu:user_hover', 'elgg_user_hover_menu');
elgg_register_action('register', '', 'public');
elgg_register_action('useradd', '', 'admin');
elgg_register_action('friends/add');
elgg_register_action('friends/remove');
elgg_register_action('avatar/upload');
elgg_register_action('avatar/crop');
elgg_register_action('avatar/remove');
elgg_register_action('profile/edit');
elgg_register_action('friends/collections/add');
elgg_register_action('friends/collections/delete');
elgg_register_action('friends/collections/edit');
elgg_register_plugin_hook_handler('entity:icon:url', 'user', 'user_avatar_hook');
elgg_register_action('user/passwordreset', '', 'public');
elgg_register_action('user/requestnewpassword', '', 'public');
elgg_register_widget_type('friends', elgg_echo('friends'), elgg_echo('friends:widget:description'));
// Register the user type
elgg_register_entity_type('user', '');
elgg_register_plugin_hook_handler('register', 'menu:entity', 'elgg_users_setup_entity_menu', 501);
elgg_register_event_handler('create', 'user', 'user_create_hook_add_site_relationship');
}
/**
* Runs unit tests for ElggObject
*
* @param string $hook unit_test
* @param string $type system
* @param mixed $value Array of tests
* @param mixed $params Params
*
* @return array
* @access private
*/
function users_test($hook, $type, $value, $params) {
global $CONFIG;
$value[] = "{$CONFIG->path}engine/tests/objects/users.php";
return $value;
}
elgg_register_event_handler('init', 'system', 'users_init', 0);
elgg_register_event_handler('init', 'system', 'elgg_profile_fields_setup', 10000); // Ensure this runs after other plugins
elgg_register_event_handler('pagesetup', 'system', 'users_pagesetup', 0);
elgg_register_plugin_hook_handler('unit_test', 'system', 'users_test');
| pingwangcs/51zhaohu | engine/lib/users.php | PHP | gpl-2.0 | 45,519 |
/**********************************************************************
Audacity: A Digital Audio Editor
Envelope.cpp
Dominic Mazzoni (original author)
Dr William Bland (integration - the Calculus kind)
Monty (xiphmont) (important bug fixes)
*******************************************************************//**
\class Envelope
\brief Draggable curve used in TrackPanel for varying amplification.
This class manages an envelope - i.e. a piecewise linear funtion
that the user can edit by dragging control points around. The
envelope is most commonly used to control the amplitude of a
waveform, but it is also used to shape the Equalization curve.
*//****************************************************************//**
\class EnvPoint
\brief EnvPoint, derived from XMLTagHandler, provides Envelope with
a draggable point type.
*//*******************************************************************/
#include "Envelope.h"
#include "ViewInfo.h"
#include <math.h>
#include <wx/dc.h>
#include <wx/brush.h>
#include <wx/event.h>
#include <wx/pen.h>
#include <wx/textfile.h>
#include <wx/log.h>
#include "AColor.h"
#include "DirManager.h"
#include "TrackArtist.h"
Envelope::Envelope()
{
mOffset = 0.0;
mTrackLen = 0.0;
// Anything with a sample rate of no more than 200 KHz
// will have samples spaced apart by at least this amount,
// "epsilon". We use this to enforce that there aren't
// allowed to be multiple control points at the same t
// value.
mTrackEpsilon = 1.0 / 200000.0;
mDB = true;
mDefaultValue = 1.0;
mDragPoint = -1;
mDirty = false;
mIsDeleting = false;
mMirror = true;
mMinValue = 1.0e-7;
mMaxValue = 2.0;
mButton = wxMOUSE_BTN_NONE;
mSearchGuess = -1;
}
Envelope::~Envelope()
{
}
void Envelope::Mirror(bool mirror)
{
mMirror = mirror;
}
/// Rescale function for time tracks (could also be used for other tracks though).
/// This is used to load old time track project files where the envelope used a 0 to 1
/// range instead of storing the actual time track values. This function will change the range of the envelope
/// and rescale all envelope points accordingly (unlike SetRange, which clamps the envelope points to the NEW range).
/// @minValue - the NEW minimum value
/// @maxValue - the NEW maximum value
void Envelope::Rescale(double minValue, double maxValue)
{
double oldMinValue = mMinValue;
double oldMaxValue = mMaxValue;
mMinValue = minValue;
mMaxValue = maxValue;
// rescale the default value
double factor = (mDefaultValue - oldMinValue) / (oldMaxValue - oldMinValue);
mDefaultValue = ClampValue(mMinValue + (mMaxValue - mMinValue) * factor);
// rescale all points
for( unsigned int i = 0; i < mEnv.size(); i++ ) {
factor = (mEnv[i].GetVal() - oldMinValue) / (oldMaxValue - oldMinValue);
mEnv[i].SetVal(mMinValue + (mMaxValue - mMinValue) * factor);
}
}
/// Flatten removes all points from the envelope to
/// make it horizontal at a chosen y-value.
/// @value - the y-value for the flat envelope.
void Envelope::Flatten(double value)
{
mEnv.clear();
mDefaultValue = ClampValue(value);
}
void Envelope::SetRange(double minValue, double maxValue) {
mMinValue = minValue;
mMaxValue = maxValue;
mDefaultValue = ClampValue(mDefaultValue);
for( unsigned int i = 0; i < mEnv.size(); i++ )
mEnv[i].SetVal(mEnv[i].GetVal()); // this clamps the value to the NEW range
}
EnvPoint *Envelope::AddPointAtEnd( double t, double val )
{
mEnv.push_back(EnvPoint(this, t, val));
return &mEnv.back();
}
void Envelope::CopyFrom(const Envelope *e, double t0, double t1)
{
wxASSERT( t0 < t1 );
mOffset = wxMax(t0, e->mOffset);
mTrackLen = wxMin(t1, e->mOffset + e->mTrackLen) - mOffset;
mEnv.clear();
int len = e->mEnv.size();
int i = 0;
// Skip the points that come before the copied region
while ((i < len) && e->mOffset + e->mEnv[i].GetT() <= t0)
i++;
// Create the point at 0 if it needs interpolated representation
if (i>0)
AddPointAtEnd( 0, e->GetValue(mOffset) );
// Copy points from inside the copied region
while (i < len) {
const EnvPoint &point = e->mEnv[i];
const double when = e->mOffset + point.GetT() - mOffset;
if (when < mTrackLen) {
AddPointAtEnd(when, point.GetVal());
i++;
}
else
break;
}
// Create the final point if it needs interpolated representation
// If the last point of e was exatly at t1, this effectively copies it too.
if (mTrackLen > 0 && i < len)
AddPointAtEnd( mTrackLen, e->GetValue(mOffset + mTrackLen));
}
/// Limit() limits a double value to a range.
/// TODO: Move to a general utilities source file.
static double Limit( double Lo, double Value, double Hi )
{
if( Value < Lo )
return Lo;
if( Value > Hi )
return Hi;
return Value;
}
/// TODO: This should probably move to track artist.
static void DrawPoint(wxDC & dc, const wxRect & r, int x, int y, bool top)
{
if (y >= 0 && y <= r.height) {
wxRect circle(r.x + x, r.y + (top ? y - 1: y - 2), 4, 4);
dc.DrawEllipse(circle);
}
}
/// TODO: This should probably move to track artist.
void Envelope::DrawPoints(wxDC & dc, const wxRect & r, const ZoomInfo &zoomInfo,
bool dB, double dBRange,
float zoomMin, float zoomMax) const
{
dc.SetPen(AColor::envelopePen);
dc.SetBrush(*wxWHITE_BRUSH);
for (int i = 0; i < (int)mEnv.size(); i++) {
const double time = mEnv[i].GetT() + mOffset;
const wxInt64 position = zoomInfo.TimeToPosition(time);
if (position >= 0 && position < r.width) {
// Change colour if this is the draggable point...
if (i == mDragPoint) {
dc.SetPen(AColor::envelopePen);
dc.SetBrush(AColor::envelopeBrush);
}
double v = mEnv[i].GetVal();
int x = (int)(position);
int y, y2;
y = GetWaveYPos(v, zoomMin, zoomMax, r.height, dB,
true, dBRange, false);
if (!mMirror) {
DrawPoint(dc, r, x, y, true);
}
else {
y2 = GetWaveYPos(-v-.000000001, zoomMin, zoomMax, r.height, dB,
true, dBRange, false);
// This follows the same logic as the envelop drawing in
// TrackArtist::DrawEnvelope().
// TODO: make this calculation into a reusable function.
if (y2 - y < 9) {
int value = (int)((zoomMax / (zoomMax - zoomMin)) * r.height);
y = value - 4;
y2 = value + 4;
}
DrawPoint(dc, r, x, y, true);
DrawPoint(dc, r, x, y2, false);
// Contour
y = GetWaveYPos(v, zoomMin, zoomMax, r.height, dB,
false, dBRange, false);
y2 = GetWaveYPos(-v-.000000001, zoomMin, zoomMax, r.height, dB,
false, dBRange, false);
if (y <= y2) {
DrawPoint(dc, r, x, y, true);
DrawPoint(dc, r, x, y2, false);
}
}
// Change colour back again if was the draggable point.
if (i == mDragPoint) {
dc.SetPen(AColor::envelopePen);
dc.SetBrush(*wxWHITE_BRUSH);
}
}
}
}
bool Envelope::HandleXMLTag(const wxChar *tag, const wxChar **attrs)
{
// Return unless it's the envelope tag.
if (wxStrcmp(tag, wxT("envelope")))
return false;
int numPoints = 0;
long nValue = -1;
while (*attrs) {
const wxChar *attr = *attrs++;
const wxChar *value = *attrs++;
if (!value)
break;
const wxString strValue = value;
if( !wxStrcmp(attr, wxT("numpoints")) &&
XMLValueChecker::IsGoodInt(strValue) && strValue.ToLong(&nValue))
numPoints = nValue;
}
if (numPoints < 0)
return false;
mEnv.clear();
mEnv.reserve(numPoints);
return true;
}
XMLTagHandler *Envelope::HandleXMLChild(const wxChar *tag)
{
if (wxStrcmp(tag, wxT("controlpoint")))
return NULL;
return AddPointAtEnd(0,0);
}
void Envelope::WriteXML(XMLWriter &xmlFile) const
{
unsigned int ctrlPt;
xmlFile.StartTag(wxT("envelope"));
xmlFile.WriteAttr(wxT("numpoints"), mEnv.size());
for (ctrlPt = 0; ctrlPt < mEnv.size(); ctrlPt++) {
const EnvPoint &point = mEnv[ctrlPt];
xmlFile.StartTag(wxT("controlpoint"));
xmlFile.WriteAttr(wxT("t"), point.GetT(), 12);
xmlFile.WriteAttr(wxT("val"), point.GetVal(), 12);
xmlFile.EndTag(wxT("controlpoint"));
}
xmlFile.EndTag(wxT("envelope"));
}
namespace
{
inline int SQR(int x) { return x * x; }
}
/// ValueOfPixel() converts a y position on screen to an envelope value.
/// @param y - y position, usually of the mouse.relative to the clip.
/// @param height - height of the rectangle we are in.
/// @upper - true if we are on the upper line, false if on lower.
/// @dB - display mode either linear or log.
/// @zoomMin - vertical scale, typically -1.0
/// @zoomMax - vertical scale, typically +1.0
float Envelope::ValueOfPixel( int y, int height, bool upper,
bool dB, double dBRange,
float zoomMin, float zoomMax)
{
float v = ::ValueOfPixel(y, height, 0 != mContourOffset, dB, dBRange, zoomMin, zoomMax);
// MB: this is mostly equivalent to what the old code did, I'm not sure
// if anything special is needed for asymmetric ranges
if(upper)
return ClampValue(v);
else
return ClampValue(-v);
}
/// HandleMouseButtonDown either finds an existing control point or adds a NEW one
/// which is then recorded as the point to drag.
/// This is slightly complicated by there possibly being four control points for
/// a given time value:
/// We have an upper and lower envelope line.
/// Also we may be showing an inner envelope (at 0.5 the range).
bool Envelope::HandleMouseButtonDown(wxMouseEvent & event, wxRect & r,
const ZoomInfo &zoomInfo,
bool dB, double dBRange,
float zoomMin, float zoomMax)
{
int ctr = (int)(r.height * zoomMax / (zoomMax - zoomMin));
bool upper = !mMirror || (zoomMin >= 0.0) || (event.m_y - r.y < ctr);
int clip_y = event.m_y - r.y;
if(clip_y < 0) clip_y = 0; //keeps point in rect r, even if mouse isn't
if(clip_y > r.GetBottom()) clip_y = r.GetBottom();
int bestNum = -1;
int bestDistSqr = 100; // Must be within 10 pixel radius.
// Member variables hold state that will be needed in dragging.
mButton = event.GetButton();
mIsDeleting = false;
mContourOffset = false;
// wxLogDebug(wxT("Y:%i Height:%i Offset:%i"), y, height, mContourOffset );
int len = mEnv.size();
// TODO: extract this into a function FindNearestControlPoint()
// TODO: also fix it so that we can drag the last point on an envelope.
for (int i = 0; i < len; i++) { //search for control point nearest click
const double time = mEnv[i].GetT() + mOffset;
const wxInt64 position = zoomInfo.TimeToPosition(time);
if (position >= 0 && position < r.width) {
int x = (int)(position);
int y[4];
int numControlPoints;
// Outer control points
double value = mEnv[i].GetVal();
y[0] = GetWaveYPos(value, zoomMin, zoomMax, r.height,
dB, true, dBRange, false);
y[1] = GetWaveYPos(-value, zoomMin, zoomMax, r.height,
dB, true, dBRange, false);
// Inner control points(contour)
y[2] = GetWaveYPos(value, zoomMin, zoomMax, r.height,
dB, false, dBRange, false);
y[3] = GetWaveYPos(-value -.00000001, zoomMin, zoomMax,
r.height, dB, false, dBRange, false);
numControlPoints = 4;
if (y[2] > y[3])
numControlPoints = 2;
if (!mMirror)
numControlPoints = 1;
const int deltaXSquared = SQR(x - (event.m_x - r.x));
for(int j=0; j<numControlPoints; j++){
const int dSqr = deltaXSquared + SQR(y[j] - (event.m_y - r.y));
if (dSqr < bestDistSqr) {
bestNum = i;
bestDistSqr = dSqr;
mContourOffset = (bool)(j > 1);
}
}
}
}
if (bestNum >= 0) {
mDragPoint = bestNum;
}
else {
// TODO: Extract this into a function CreateNewPoint
const double when = zoomInfo.PositionToTime(event.m_x, r.x);
// if (when <= 0 || when >= mTrackLen)
// return false;
const double v = GetValue( when );
int ct = GetWaveYPos( v, zoomMin, zoomMax, r.height, dB,
false, dBRange, false) ;
int cb = GetWaveYPos( -v-.000000001, zoomMin, zoomMax, r.height, dB,
false, dBRange, false) ;
if( ct <= cb || !mMirror ){
int t = GetWaveYPos( v, zoomMin, zoomMax, r.height, dB,
true, dBRange, false) ;
int b = GetWaveYPos( -v, zoomMin, zoomMax, r.height, dB,
true, dBRange, false) ;
ct = (t + ct) / 2;
cb = (b + cb) / 2;
if(mMirror &&
(event.m_y - r.y) > ct &&
((event.m_y - r.y) < cb))
mContourOffset = true;
else
mContourOffset = false;
}
double newVal = ValueOfPixel(clip_y, r.height, upper, dB, dBRange,
zoomMin, zoomMax);
mDragPoint = Insert(when - mOffset, newVal);
mDirty = true;
}
mUpper = upper;
mInitialVal = mEnv[mDragPoint].GetVal();
mInitialY = event.m_y+mContourOffset;
return true;
}
/// Mark dragged point for deletion.
/// It will be deleted on mouse button up.
void Envelope::MarkDragPointForDeletion()
{
mIsDeleting = true;
// We're going to be deleting the point; On
// screen we show this by having the envelope move to
// the position it will have after deletion of the point.
// Without delting the point we move it left or right
// to the same position as the previous or next point.
if( mEnv.size() <= 1)
{
// There is only one point - just move it
// off screen and at default height.
// temporary state when dragging only!
mEnv[mDragPoint].SetT(-1000000.0);
mEnv[mDragPoint].SetVal(mDefaultValue);
return;
}
// Place it exactly on one of its neighbours.
int iNeighbourPoint = mDragPoint + ((mDragPoint > 0) ? -1:+1);
mEnv[mDragPoint].SetT(mEnv[iNeighbourPoint].GetT());
mEnv[mDragPoint].SetVal(mEnv[iNeighbourPoint].GetVal());
}
void Envelope::MoveDraggedPoint( wxMouseEvent & event, wxRect & r,
const ZoomInfo &zoomInfo, bool dB, double dBRange,
float zoomMin, float zoomMax)
{
int clip_y = event.m_y - r.y;
if(clip_y < 0) clip_y = 0;
if(clip_y > r.height) clip_y = r.height;
double newVal = ValueOfPixel(clip_y, r.height, mUpper, dB, dBRange,
zoomMin, zoomMax);
// We no longer tolerate multiple envelope points at the same t.
// epsilon is less than the time offset of a single sample
// TODO: However because mTrackEpsilon assumes 200KHz this use
// of epsilon is a tad bogus. What we need to do instead is DELETE
// a duplicated point on a mouse up.
double newWhen = zoomInfo.PositionToTime(event.m_x, r.x) - mOffset;
// We'll limit the drag point time to be between those of the preceding
// and next envelope point.
double limitLo = 0.0;
double limitHi = mTrackLen;
if (mDragPoint > 0)
limitLo = mEnv[mDragPoint - 1].GetT() + mTrackEpsilon;
if (mDragPoint < (int)mEnv.size() - 1 )
limitHi = mEnv[mDragPoint + 1].GetT() - mTrackEpsilon;
newWhen = Limit( limitLo, newWhen, limitHi );
newWhen = Limit( mTrackEpsilon, newWhen, mTrackLen - mTrackEpsilon);
mEnv[mDragPoint].SetT(newWhen);
mEnv[mDragPoint].SetVal(newVal);
}
bool Envelope::HandleDragging( wxMouseEvent & event, wxRect & r,
const ZoomInfo &zoomInfo, bool dB, double dBRange,
float zoomMin, float zoomMax)
{
mDirty = true;
wxRect larger = r;
larger.Inflate(10, 10);
if (larger.Contains(event.m_x, event.m_y))
{
// IF we're in the rect THEN we're not deleting this point (anymore).
mIsDeleting = false;
// ...we're dragging it.
MoveDraggedPoint( event, r, zoomInfo, dB, dBRange, zoomMin, zoomMax);
return true;
}
if(mIsDeleting )
// IF we already know we're deleting THEN no envelope point to update.
return false;
MarkDragPointForDeletion();
return true;
}
// Exit dragging mode and deletes dragged point if neccessary.
bool Envelope::HandleMouseButtonUp()
{
if (mIsDeleting) {
Delete(mDragPoint);
}
mDragPoint = -1;
mButton = wxMOUSE_BTN_NONE;
return true;
}
void Envelope::Delete( int point )
{
mEnv.erase(mEnv.begin() + point);
}
void Envelope::Insert(int point, const EnvPoint &p)
{
mEnv.insert(mEnv.begin() + point, p);
}
// Returns true if parent needs to be redrawn
bool Envelope::MouseEvent(wxMouseEvent & event, wxRect & r,
const ZoomInfo &zoomInfo, bool dB, double dBRange,
float zoomMin, float zoomMax)
{
if (event.ButtonDown() && mButton == wxMOUSE_BTN_NONE)
return HandleMouseButtonDown( event, r, zoomInfo, dB, dBRange,
zoomMin, zoomMax);
if (event.Dragging() && mDragPoint >= 0)
return HandleDragging( event, r, zoomInfo, dB, dBRange,
zoomMin, zoomMax);
if (event.ButtonUp() && event.GetButton() == mButton)
return HandleMouseButtonUp();
return false;
}
void Envelope::CollapseRegion(double t0, double t1)
{
// This gets called when somebody clears samples. All of the
// control points within the region disappear and the points
// to the right get shifted over.
t0 -= mOffset;
t1 -= mOffset;
t0 = std::max(0.0, std::min(mTrackLen, t0));
t1 = std::max(0.0, std::min(mTrackLen, t1));
int len = mEnv.size();
int i;
// Remove points in deleted region.
for (i = 0; i < len - 0; i++)
if (mEnv[i].GetT() >= t0 && mEnv[i].GetT() < t1) {
Delete(i);
len--;
i--;
}
// Shift points left after deleted region.
for (i = 0; i < len; i++)
if (mEnv[i].GetT() >= t1)
mEnv[i].SetT(mEnv[i].GetT() - (t1 - t0));
mTrackLen -= (t1-t0);
}
// This operation is trickier than it looks; the basic rub is that
// a track's envelope runs the range from t=0 to t=tracklen; the t=0
// envelope point applies to the first sample, but the t=tracklen
// envelope point applies one-past the last actual sample.
// Rather than going to a .5-offset-index, we special case the framing.
void Envelope::Paste(double t0, const Envelope *e)
{
const bool wasEmpty = (this->mEnv.size() == 0);
// JC: The old analysis of cases and the resulting code here is way more complex than needed.
// TODO: simplify the analysis and simplify the code.
if (e->mEnv.size() == 0 && wasEmpty && e->mDefaultValue == this->mDefaultValue)
{
// msmeyer: The envelope is empty and has the same default value, so
// there is nothing that must be inserted, just return. This avoids
// the creation of unnecessary duplicate control points
// MJS: but the envelope does get longer
mTrackLen += e->mTrackLen;
return;
}
t0 = wxMin(t0 - mOffset, mTrackLen); // t0 now has origin of zero
double deltat = e->mTrackLen;
unsigned int i;
unsigned int pos = 0;
bool someToShift = false;
bool atStart = false;
bool beforeStart = false;
bool atEnd = false;
bool afterEnd = false;
bool onPoint = false;
unsigned int len = mEnv.size();
// get values to perform framing of the insertion
double splitval = GetValue(t0 + mOffset);
if(len != 0) { // Not case 10: there are point/s in the envelope
/*
Old analysis of cases:
(see discussions on audacity-devel around 19/8/7 - 23/8/7 and beyond, "Envelopes and 'Join'")
1 9 11 2 3 5 7 8 6 4 13 12
0-----0--0---0 -----0---0------ --(0)----
1 The insert point is at the beginning of the current env, and it is a control point.
2 The insert point is at the end of the current env, and it is a control point.
3 The insert point is at the beginning of the current env, and it is not a control point.
4 The insert point is at the end of the current env, and it is not a control point.
5 The insert point is not at a control point, and there is space either side.
6 As 5.
7 The insert point is at a control point, and there is space either side.
8 Same as 7.
9 Same as 5.
10 There are no points in the current envelope (commonly called by the 'undo' stuff, and not in the diagrams).
11 As 7.
12 Insert beyond the RH end of the current envelope (should not happen, at the moment)
13 Insert beyond the LH end of the current envelope (should not happen, at the moment)
*/
// JC: Simplified Analysis:
// In pasting in a clip we choose to preserve the envelope so that the loudness of the
// parts is unchanged.
//
// 1) This may introduce a discontnuity in the envelope at a boundary between the
// old and NEW clips. In that case we must ensure there are envelope points
// at sample positions immediately before and immediately after the boundary.
// 2) If the points have the same value we only need one of them.
// 3) If the points have the same value AND it is the same as the value interpolated
// from the rest of the envelope then we don't need it at all.
//
// We do the same for the left and right edge of the NEW clip.
//
// Even simpler: we could always add two points at a boundary and then call
// RemoveUnneededPoints() (provided that function behaves correctly).
// See if existing points need shifting to the right, and what Case we are in
for (i = 0; i < len; i++) {
if (mEnv[i].GetT() > t0)
someToShift = true;
else {
pos = i; // last point not moved
if ( fabs(mEnv[i].GetT() - t0) - 1/500000.0 < 0.0 ) // close enough to a point
onPoint = true;
}
}
// In these statements, remember we subtracted mOffset from t0
if( t0 < mTrackEpsilon )
atStart = true;
if( (mTrackLen - t0) < mTrackEpsilon )
atEnd = true;
if(0 > t0)
beforeStart = true; // Case 13
if(mTrackLen < t0)
afterEnd = true; // Case 12
// Now test for the various Cases, and try to do the right thing
if(atStart) { // insertion at the beginning
if(onPoint) { // first env point is at LH end
mEnv[0].SetT(mEnv[0].GetT() + mTrackEpsilon); // Case 1: move it R slightly to avoid duplicate point
someToShift = true; // there is now, even if there wasn't before
//wxLogDebug(wxT("Case 1"));
}
else {
Insert(t0 + mTrackEpsilon, splitval); // Case 3: insert a point to maintain the envelope
someToShift = true;
//wxLogDebug(wxT("Case 3"));
}
}
else {
if(atEnd) { // insertion at the end
if(onPoint) { // last env point is at RH end, Case 2:
mEnv[0].SetT(mEnv[0].GetT() - mTrackEpsilon); // move it L slightly to avoid duplicate point
//wxLogDebug(wxT("Case 2"));
}
else { // Case 4:
Insert(t0 - mTrackEpsilon, splitval); // insert a point to maintain the envelope
//wxLogDebug(wxT("Case 4"));
}
}
else {
if(onPoint) { // Case 7: move the point L and insert a NEW one to the R
mEnv[pos].SetT(mEnv[pos].GetT() - mTrackEpsilon);
Insert(t0 + mTrackEpsilon, splitval);
someToShift = true;
//wxLogDebug(wxT("Case 7"));
}
else {
if( !beforeStart && !afterEnd ) {// Case 5: Insert points to L and R
Insert(t0 - mTrackEpsilon, splitval);
Insert(t0 + mTrackEpsilon, splitval);
someToShift = true;
//wxLogDebug(wxT("Case 5"));
}
else {
if( beforeStart ) { // Case 13:
//wxLogDebug(wxT("Case 13"));
}
else { // Case 12:
//wxLogDebug(wxT("Case 12"));
}
}
}
}
}
// Now shift existing points to the right, if required
if(someToShift) {
len = mEnv.size(); // it may well have changed
for (i = 0; i < len; i++)
if (mEnv[i].GetT() > t0)
mEnv[i].SetT(mEnv[i].GetT() + deltat);
}
mTrackLen += deltat;
}
else { // Case 10:
if( mTrackLen == 0 ) // creating a NEW envelope
{
mTrackLen = e->mTrackLen;
mOffset = e->mOffset;
//wxLogDebug(wxT("Case 10, NEW env/clip: mTrackLen %f mOffset %f t0 %f"), mTrackLen, mOffset, t0);
}
else
{
mTrackLen += e->mTrackLen;
//wxLogDebug(wxT("Case 10, paste into current env: mTrackLen %f mOffset %f t0 %f"), mTrackLen, mOffset, t0);
}
}
// Copy points from inside the selection
if (!wasEmpty) {
// Add end points in case they are not not in e.
// If they are in e, no harm, because the repeated Insert
// calls for the start and end times will have no effect.
const double leftval = e->GetValue(0 + e->mOffset);
const double rightval = e->GetValue(e->mTrackLen + e->mOffset);
Insert(t0, leftval);
Insert(t0 + e->mTrackLen, rightval);
}
len = e->mEnv.size();
for (i = 0; i < len; i++)
Insert(t0 + e->mEnv[i].GetT(), e->mEnv[i].GetVal());
/* if(len != 0)
for (i = 0; i < mEnv.size(); i++)
wxLogDebug(wxT("Fixed i %d when %.18f val %f"),i,mEnv[i].GetT(),mEnv[i].GetVal()); */
}
// Deletes 'unneeded' points, starting from the left.
// If 'time' is set and positive, just deletes points in a small region
// around that value.
// 'Unneeded' means that the envelope doesn't change by more than
// 'tolerence' without the point being there.
void Envelope::RemoveUnneededPoints(double time, double tolerence)
{
unsigned int len = mEnv.size();
unsigned int i;
double when, val, val1;
if(mEnv.size() == 0)
return;
for (i = 0; i < len; i++) {
when = mEnv[i].GetT();
if(time >= 0)
{
if(fabs(when + mOffset - time) > 0.00025) // 2 samples at 8kHz, 11 at 44.1kHz
continue;
}
val = mEnv[i].GetVal();
Delete(i); // try it to see if it's doing anything
val1 = GetValue(when + mOffset);
bool bExcludePoint = true;
if( fabs(val -val1) > tolerence )
{
Insert(when, val); // put it back, we needed it
//Insert may have modified instead of inserting, if two points were at the same time.
// in which case len needs to shrink i and len, because the array size decreased.
bExcludePoint = (mEnv.size() < len);
}
if( bExcludePoint ) { // it made no difference so leave it out
len--;
i--;
}
}
}
void Envelope::InsertSpace(double t0, double tlen)
{
unsigned int len = mEnv.size();
unsigned int i;
for (i = 0; i < len; i++)
if (mEnv[i].GetT() > t0)
mEnv[i].SetT(mEnv[i].GetT() + tlen);
mTrackLen += tlen;
}
int Envelope::Move(double when, double value)
{
int len = mEnv.size();
if (len == 0)
return -1;
int i = 0;
while (i < len && when > mEnv[i].GetT())
i++;
if (i >= len || when < mEnv[i].GetT())
return -1;
mEnv[i].SetVal(value);
return 0;
}
int Envelope::GetNumberOfPoints() const
{
return mEnv.size();
}
void Envelope::GetPoints(double *bufferWhen,
double *bufferValue,
int bufferLen) const
{
int n = mEnv.size();
if (n > bufferLen)
n = bufferLen;
int i;
for (i = 0; i < n; i++) {
bufferWhen[i] = mEnv[i].GetT();
bufferValue[i] = mEnv[i].GetVal();
}
}
// Private methods
// We no longer tolerate multiple envelope control points at the exact
// same t; the behavior can be well-defined, but it is still incorrect
// in that it vastly complicates paste operations behaving as a user
// reasonably expects. The most common problem occurs pasting an
// envelope into another track; the boundary behavior causes the
// t=insert_point envelope level of the insertee to apply to sample 0
// of the inserted sample, causing a pop. This most visibly manifests
// itself in undo and mixing when a v=1.0 sample magically shows
// up at boundaries causing a pop.
// Although this renders the name a slight misnomer, a duplicate
// 'replaces' the current control point.
/** @brief Add a control point to the envelope
*
* Control point positions start at zero and are measured in seconds from the
* start of the envelope. The position of the envelope on the project-wide
* time scale is store in seconds in Envelope::mOffset.
* This is worth remembering.
* If you call Envelope::Insert() from WaveClip, or anywhere else outside the
* Envelope class that is using project timing, subtract the envelope's mOffset
* from the time.
* If you call Envelope::Insert() from within Envelope, don't subtract mOffset
* because you are working in relative time inside the envelope
* @param when the time in seconds when the envelope point should be created.
* @param value the envelope value to use at the given point.
* @return the index of the NEW envelope point within array of envelope points.
*/
int Envelope::Insert(double when, double value)
{
#if defined(__WXDEBUG__)
// in debug builds, do a spot of argument checking
if(when > mTrackLen + 0.0000001)
{
wxString msg;
msg = wxString::Format(wxT("when %.20f mTrackLen %.20f diff %.20f"), when, mTrackLen, when-mTrackLen);
wxASSERT_MSG(when <= (mTrackLen), msg);
}
if(when < 0)
{
wxString msg;
msg = wxString::Format(wxT("when %.20f mTrackLen %.20f"), when, mTrackLen);
wxASSERT_MSG(when >= 0, msg);
}
#endif
int len = mEnv.size();
if (len && when < 0.0)
return 0;
if ((len > 1) && when > mTrackLen)
return len - 1;
if (when < 0.0)
when = 0.0;
if ((len>1) && when > mTrackLen)
when = mTrackLen;
int i = 0;
while (i < len && when > mEnv[i].GetT())
i++;
if(i < len && when == mEnv[i].GetT()) {
// modify existing
mEnv[i].SetVal(value);
}
else {
// Add NEW
EnvPoint e(this, when, value);
if (i < len) {
Insert(i, e);
} else {
mEnv.push_back(e);
}
}
return i;
}
// Control
void Envelope::SetOffset(double newOffset)
{
mOffset = newOffset;
}
void Envelope::SetTrackLen(double trackLen)
{
mTrackLen = trackLen;
int len = mEnv.size();
for (int i = 0; i < len; i++)
if (mEnv[i].GetT() > mTrackLen) {
Delete(i);
len--;
i--;
}
}
// Accessors
double Envelope::GetValue(double t) const
{
// t is absolute time
double temp;
GetValues(&temp, 1, t, 1.0);
return temp;
}
/// @param Lo returns last index at or before this time.
/// @param Hi returns first index after this time.
void Envelope::BinarySearchForTime( int &Lo, int &Hi, double t ) const
{
Lo = 0;
Hi = mEnv.size() - 1;
// JC: Do we have a problem if the envelope only has one point??
wxASSERT(Hi > Lo);
// Optimizations for the usual pattern of repeated calls with
// small increases of t.
{
if (mSearchGuess >= 0 && mSearchGuess < (int)(mEnv.size()) - 1) {
if (t >= mEnv[mSearchGuess].GetT() &&
t < mEnv[1 + mSearchGuess].GetT()) {
Lo = mSearchGuess;
Hi = 1 + mSearchGuess;
return;
}
}
++mSearchGuess;
if (mSearchGuess >= 0 && mSearchGuess < (int)(mEnv.size()) - 1) {
if (t >= mEnv[mSearchGuess].GetT() &&
t < mEnv[1 + mSearchGuess].GetT()) {
Lo = mSearchGuess;
Hi = 1 + mSearchGuess;
return;
}
}
}
while (Hi > (Lo + 1)) {
int mid = (Lo + Hi) / 2;
if (t < mEnv[mid].GetT())
Hi = mid;
else
Lo = mid;
}
wxASSERT( Hi == ( Lo+1 ));
mSearchGuess = Lo;
}
/// GetInterpolationStartValueAtPoint() is used to select either the
/// envelope value or its log depending on whether we are doing linear
/// or log interpolation.
/// @param iPoint index in env array to look at.
/// @return value there, or its (safe) log10.
double Envelope::GetInterpolationStartValueAtPoint( int iPoint ) const
{
double v = mEnv[ iPoint ].GetVal();
if( !mDB )
return v;
else
return log10(v);
}
void Envelope::GetValues(double *buffer, int bufferLen,
double t0, double tstep) const
{
// Convert t0 from absolute to clip-relative time
t0 -= mOffset;
// JC: If bufferLen ==0 we have probably just allocated a zero sized buffer.
// wxASSERT( bufferLen > 0 );
int len = mEnv.size();
double t = t0;
double tprev, vprev, tnext = 0, vnext, vstep = 0;
for (int b = 0; b < bufferLen; b++) {
// Get easiest cases out the way first...
// IF empty envelope THEN default value
if (len <= 0) {
buffer[b] = mDefaultValue;
t += tstep;
continue;
}
// IF before envelope THEN first value
if (t <= mEnv[0].GetT()) {
buffer[b] = mEnv[0].GetVal();
t += tstep;
continue;
}
// IF after envelope THEN last value
if (t >= mEnv[len - 1].GetT()) {
buffer[b] = mEnv[len - 1].GetVal();
t += tstep;
continue;
}
if (b == 0 || t > tnext) {
// We're beyond our tnext, so find the next one.
// Don't just increment lo or hi because we might
// be zoomed far out and that could be a large number of
// points to move over. That's why we binary search.
int lo,hi;
BinarySearchForTime( lo, hi, t );
tprev = mEnv[lo].GetT();
tnext = mEnv[hi].GetT();
vprev = GetInterpolationStartValueAtPoint( lo );
vnext = GetInterpolationStartValueAtPoint( hi );
// Interpolate, either linear or log depending on mDB.
double dt = (tnext - tprev);
double to = t - tprev;
double v;
if (dt > 0.0)
{
v = (vprev * (dt - to) + vnext * to) / dt;
vstep = (vnext - vprev) * tstep / dt;
}
else
{
v = vnext;
vstep = 0.0;
}
// An adjustment if logarithmic scale.
if( mDB )
{
v = pow(10.0, v);
vstep = pow( 10.0, vstep );
}
buffer[b] = v;
} else {
if (mDB){
buffer[b] = buffer[b - 1] * vstep;
}else{
buffer[b] = buffer[b - 1] + vstep;
}
}
t += tstep;
}
}
void Envelope::GetValues
(double *buffer, int bufferLen, int leftOffset, const ZoomInfo &zoomInfo) const
{
for (int xx = 0; xx < bufferLen; ++xx)
buffer[xx] = GetValue(zoomInfo.PositionToTime(xx, -leftOffset));
}
int Envelope::NumberOfPointsAfter(double t) const
{
if( t >= mEnv[mEnv.size()-1].GetT() )
return 0;
else if( t < mEnv[0].GetT() )
return mEnv.size();
else
{
int lo,hi;
BinarySearchForTime( lo, hi, t );
if( mEnv[hi].GetT() == t )
return mEnv.size() - (hi+1);
else
return mEnv.size() - hi;
}
}
double Envelope::NextPointAfter(double t) const
{
if( mEnv[mEnv.size()-1].GetT() < t )
return t;
else if( t < mEnv[0].GetT() )
return mEnv[0].GetT();
else
{
int lo,hi;
BinarySearchForTime( lo, hi, t );
if( mEnv[hi].GetT() == t )
return mEnv[hi+1].GetT();
else
return mEnv[hi].GetT();
}
}
double Envelope::Average( double t0, double t1 ) const
{
if( t0 == t1 )
return GetValue( t0 );
else
return Integral( t0, t1 ) / (t1 - t0);
}
double Envelope::AverageOfInverse( double t0, double t1 ) const
{
if( t0 == t1 )
return 1.0 / GetValue( t0 );
else
return IntegralOfInverse( t0, t1 ) / (t1 - t0);
}
//
// Integration and debugging functions
//
// The functions below are used by the TimeTrack and possibly for
// other debugging. They do not affect normal amplitude envelopes
// for waveforms, nor frequency envelopes for equalization.
// The 'Average' function also uses 'Integral'.
//
// A few helper functions to make the code below more readable.
static double InterpolatePoints(double y1, double y2, double factor, bool logarithmic)
{
if(logarithmic)
// you can use any base you want, it doesn't change the result
return exp(log(y1) * (1.0 - factor) + log(y2) * factor);
else
return y1 * (1.0 - factor) + y2 * factor;
}
static double IntegrateInterpolated(double y1, double y2, double time, bool logarithmic)
{
// Calculates: integral(interpolate(y1, y2, x), x = 0 .. time)
// Integrating logarithmic interpolated segments is surprisingly simple. You can check this formula here:
// http://www.wolframalpha.com/input/?i=integrate+10%5E%28log10%28y1%29*%28T-x%29%2FT%2Blog10%28y2%29*x%2FT%29+from+0+to+T
// Again, the base you use for interpolation is irrelevant, the formula below should always use the natural
// logarithm (i.e. 'log' in C/C++). If the denominator is too small, it's better to use linear interpolation
// because the rounding errors would otherwise get too large. The threshold value is 1.0e-5 because at that
// point the rounding errors become larger than the difference between linear and logarithmic (I tested this in Octave).
if(logarithmic)
{
double l = log(y1 / y2);
if(fabs(l) < 1.0e-5) // fall back to linear interpolation
return (y1 + y2) * 0.5 * time;
return (y1 - y2) / l * time;
}
else
{
return (y1 + y2) * 0.5 * time;
}
}
static double IntegrateInverseInterpolated(double y1, double y2, double time, bool logarithmic)
{
// Calculates: integral(1 / interpolate(y1, y2, x), x = 0 .. time)
// This one is a bit harder. Linear:
// http://www.wolframalpha.com/input/?i=integrate+1%2F%28y1*%28T-x%29%2FT%2By2*x%2FT%29+from+0+to+T
// Logarithmic:
// http://www.wolframalpha.com/input/?i=integrate+1%2F%2810%5E%28log10%28y1%29*%28T-x%29%2FT%2Blog10%28y2%29*x%2FT%29%29+from+0+to+T
// Here both cases need a special case for y1 == y2. The threshold is 1.0e5 again, this is still the
// best value in both cases.
double l = log(y1 / y2);
if(fabs(l) < 1.0e-5) // fall back to average
return 2.0 / (y1 + y2) * time;
if(logarithmic)
return (y1 - y2) / (l * y1 * y2) * time;
else
return l / (y1 - y2) * time;
}
static double SolveIntegrateInverseInterpolated(double y1, double y2, double time, double area, bool logarithmic)
{
// Calculates: solve (integral(1 / interpolate(y1, y2, x), x = 0 .. res) = area) for res
// Don't try to derive these formulas by hand :). The threshold is 1.0e5 again.
double a = area / time, res;
if(logarithmic)
{
double l = log(y1 / y2);
if(fabs(l) < 1.0e-5) // fall back to average
res = a * (y1 + y2) * 0.5;
else if(1.0 + a * y1 * l <= 0.0)
res = 1.0;
else
res = log1p(a * y1 * l) / l;
}
else
{
if(fabs(y2 - y1) < 1.0e-5) // fall back to average
res = a * (y1 + y2) * 0.5;
else
res = y1 * expm1(a * (y2 - y1)) / (y2 - y1);
}
return std::max(0.0, std::min(1.0, res)) * time;
}
// We should be able to write a very efficient memoizer for this
// but make sure it gets reset when the envelope is changed.
double Envelope::Integral( double t0, double t1 ) const
{
if(t0 == t1)
return 0.0;
if(t0 > t1)
{
return -Integral(t1, t0); // this makes more sense than returning the default value
}
unsigned int count = mEnv.size();
if(count == 0) // 'empty' envelope
return (t1 - t0) * mDefaultValue;
double total = 0.0, lastT, lastVal;
unsigned int i; // this is the next point to check
if(t0 < mEnv[0].GetT()) // t0 preceding the first point
{
if(t1 <= mEnv[0].GetT())
return (t1 - t0) * mEnv[0].GetVal();
i = 1;
lastT = mEnv[0].GetT();
lastVal = mEnv[0].GetVal();
total += (lastT - t0) * lastVal;
}
else if(t0 >= mEnv[count - 1].GetT()) // t0 following the last point
{
return (t1 - t0) * mEnv[count - 1].GetVal();
}
else // t0 enclosed by points
{
// Skip any points that come before t0 using binary search
int lo, hi;
BinarySearchForTime(lo, hi, t0);
lastVal = InterpolatePoints(mEnv[lo].GetVal(), mEnv[hi].GetVal(), (t0 - mEnv[lo].GetT()) / (mEnv[hi].GetT() - mEnv[lo].GetT()), mDB);
lastT = t0;
i = hi; // the point immediately after t0.
}
// loop through the rest of the envelope points until we get to t1
while (1)
{
if(i >= count) // the requested range extends beyond the last point
{
return total + (t1 - lastT) * lastVal;
}
else if(mEnv[i].GetT() >= t1) // this point follows the end of the range
{
double thisVal = InterpolatePoints(mEnv[i - 1].GetVal(), mEnv[i].GetVal(), (t1 - mEnv[i - 1].GetT()) / (mEnv[i].GetT() - mEnv[i - 1].GetT()), mDB);
return total + IntegrateInterpolated(lastVal, thisVal, t1 - lastT, mDB);
}
else // this point preceeds the end of the range
{
total += IntegrateInterpolated(lastVal, mEnv[i].GetVal(), mEnv[i].GetT() - lastT, mDB);
lastT = mEnv[i].GetT();
lastVal = mEnv[i].GetVal();
i++;
}
}
}
double Envelope::IntegralOfInverse( double t0, double t1 ) const
{
if(t0 == t1)
return 0.0;
if(t0 > t1)
{
return -IntegralOfInverse(t1, t0); // this makes more sense than returning the default value
}
unsigned int count = mEnv.size();
if(count == 0) // 'empty' envelope
return (t1 - t0) / mDefaultValue;
double total = 0.0, lastT, lastVal;
unsigned int i; // this is the next point to check
if(t0 < mEnv[0].GetT()) // t0 preceding the first point
{
if(t1 <= mEnv[0].GetT())
return (t1 - t0) / mEnv[0].GetVal();
i = 1;
lastT = mEnv[0].GetT();
lastVal = mEnv[0].GetVal();
total += (lastT - t0) / lastVal;
}
else if(t0 >= mEnv[count - 1].GetT()) // t0 following the last point
{
return (t1 - t0) / mEnv[count - 1].GetVal();
}
else // t0 enclosed by points
{
// Skip any points that come before t0 using binary search
int lo, hi;
BinarySearchForTime(lo, hi, t0);
lastVal = InterpolatePoints(mEnv[lo].GetVal(), mEnv[hi].GetVal(), (t0 - mEnv[lo].GetT()) / (mEnv[hi].GetT() - mEnv[lo].GetT()), mDB);
lastT = t0;
i = hi; // the point immediately after t0.
}
// loop through the rest of the envelope points until we get to t1
while (1)
{
if(i >= count) // the requested range extends beyond the last point
{
return total + (t1 - lastT) / lastVal;
}
else if(mEnv[i].GetT() >= t1) // this point follows the end of the range
{
double thisVal = InterpolatePoints(mEnv[i - 1].GetVal(), mEnv[i].GetVal(), (t1 - mEnv[i - 1].GetT()) / (mEnv[i].GetT() - mEnv[i - 1].GetT()), mDB);
return total + IntegrateInverseInterpolated(lastVal, thisVal, t1 - lastT, mDB);
}
else // this point preceeds the end of the range
{
total += IntegrateInverseInterpolated(lastVal, mEnv[i].GetVal(), mEnv[i].GetT() - lastT, mDB);
lastT = mEnv[i].GetT();
lastVal = mEnv[i].GetVal();
i++;
}
}
}
double Envelope::SolveIntegralOfInverse( double t0, double area ) const
{
if(area == 0.0)
return t0;
unsigned int count = mEnv.size();
if(count == 0) // 'empty' envelope
return t0 + area * mDefaultValue;
double lastT, lastVal;
int i; // this is the next point to check
if(t0 < mEnv[0].GetT()) // t0 preceding the first point
{
if (area < 0) {
return t0 + area * mEnv[0].GetVal();
}
else {
i = 1;
lastT = mEnv[0].GetT();
lastVal = mEnv[0].GetVal();
double added = (lastT - t0) / lastVal;
if(added >= area)
return t0 + area * mEnv[0].GetVal();
area -= added;
}
}
else if(t0 >= mEnv[count - 1].GetT()) // t0 following the last point
{
if (area < 0) {
i = count - 2;
lastT = mEnv[count - 1].GetT();
lastVal = mEnv[count - 1].GetVal();
double added = (lastT - t0) / lastVal; // negative
if(added <= area)
return t0 + area * mEnv[count - 1].GetVal();
area -= added;
}
else {
return t0 + area * mEnv[count - 1].GetVal();
}
}
else // t0 enclosed by points
{
// Skip any points that come before t0 using binary search
int lo, hi;
BinarySearchForTime(lo, hi, t0);
lastVal = InterpolatePoints(mEnv[lo].GetVal(), mEnv[hi].GetVal(), (t0 - mEnv[lo].GetT()) / (mEnv[hi].GetT() - mEnv[lo].GetT()), mDB);
lastT = t0;
if (area < 0)
i = lo;
else
i = hi; // the point immediately after t0.
}
if (area < 0) {
// loop BACKWARDS through the rest of the envelope points until we get to t1
// (which is less than t0)
while (1)
{
if(i < 0) // the requested range extends beyond the leftmost point
{
return lastT + area * lastVal;
}
else
{
double added =
-IntegrateInverseInterpolated(mEnv[i].GetVal(), lastVal, lastT - mEnv[i].GetT(), mDB);
if(added <= area)
return lastT - SolveIntegrateInverseInterpolated(lastVal, mEnv[i].GetVal(), lastT - mEnv[i].GetT(), -area, mDB);
area -= added;
lastT = mEnv[i].GetT();
lastVal = mEnv[i].GetVal();
--i;
}
}
}
else {
// loop through the rest of the envelope points until we get to t1
while (1)
{
if(i >= count) // the requested range extends beyond the last point
{
return lastT + area * lastVal;
}
else
{
double added = IntegrateInverseInterpolated(lastVal, mEnv[i].GetVal(), mEnv[i].GetT() - lastT, mDB);
if(added >= area)
return lastT + SolveIntegrateInverseInterpolated(lastVal, mEnv[i].GetVal(), mEnv[i].GetT() - lastT, area, mDB);
area -= added;
lastT = mEnv[i].GetT();
lastVal = mEnv[i].GetVal();
i++;
}
}
}
}
void Envelope::print() const
{
for( unsigned int i = 0; i < mEnv.size(); i++ )
printf( "(%.2f, %.2f)\n", mEnv[i].GetT(), mEnv[i].GetVal() );
}
static void checkResult( int n, double a, double b )
{
if( (a-b > 0 ? a-b : b-a) > 0.0000001 )
{
printf( "Envelope: Result #%d is: %f, should be %f\n", n, a, b );
//exit( -1 );
}
}
void Envelope::testMe()
{
double t0=0, t1=0;
SetInterpolateDB(false);
Mirror(false);
Flatten(0.5);
checkResult( 1, Integral(0.0,100.0), 50);
checkResult( 2, Integral(-10.0,10.0), 10);
Flatten(0.5);
checkResult( 3, Integral(0.0,100.0), 50);
checkResult( 4, Integral(-10.0,10.0), 10);
checkResult( 5, Integral(-20.0,-10.0), 5);
Flatten(0.5);
Insert( 5.0, 0.5 );
checkResult( 6, Integral(0.0,100.0), 50);
checkResult( 7, Integral(-10.0,10.0), 10);
Flatten(0.0);
Insert( 0.0, 0.0 );
Insert( 5.0, 1.0 );
Insert( 10.0, 0.0 );
t0 = 10.0 - .1;
t1 = 10.0 + .1;
double result = Integral(0.0,t1);
double resulta = Integral(0.0,t0);
double resultb = Integral(t0,t1);
// Integrals should be additive
checkResult( 8, result - resulta - resultb, 0);
Flatten(0.0);
Insert( 0.0, 0.0 );
Insert( 5.0, 1.0 );
Insert( 10.0, 0.0 );
t0 = 10.0 - .1;
t1 = 10.0 + .1;
checkResult( 9, Integral(0.0,t1), 5);
checkResult( 10, Integral(0.0,t0), 4.999);
checkResult( 11, Integral(t0,t1), .001);
mEnv.clear();
Insert( 0.0, 0.0 );
Insert( 5.0, 1.0 );
Insert( 10.0, 0.0 );
checkResult( 12, NumberOfPointsAfter( -1 ), 3 );
checkResult( 13, NumberOfPointsAfter( 0 ), 2 );
checkResult( 14, NumberOfPointsAfter( 1 ), 2 );
checkResult( 15, NumberOfPointsAfter( 5 ), 1 );
checkResult( 16, NumberOfPointsAfter( 7 ), 1 );
checkResult( 17, NumberOfPointsAfter( 10 ), 0 );
checkResult( 18, NextPointAfter( 0 ), 5 );
checkResult( 19, NextPointAfter( 5 ), 10 );
}
| ThomasFeher/audacity | src/Envelope.cpp | C++ | gpl-2.0 | 49,441 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body{
font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
background-color: #EEE;
}
#wide{
border-top: 15px solid #853B45;
padding: 15px;
padding-top: 10px;
max-width: 600px;
width: 85%;
background-color: #FFF;
margin-left: auto;
margin-right: auto;
}
a{
color: #853B45;
text-decoration: none;
font-weight: bold;
}
a:hover{
color: #b94a48;
text-decoration: none;
font-weight: bold;
}
</style>
</head>
<body>
<div id="wide">
<p>Hello {{htmlspecialchars($fullName)}}</p>
<p><strong>Either you or someone else tried to request a password change at OpenShowcase.</strong></p>
<p>You (or someone else) requested a new password. You can ignore this message, or <a href="{{$domain}}/user/{{$id}}/resetpassword/{{$code}}">change your password to your account by visiting this link</a>.</p>
<p>If you have any additional questions, do not hesitate to send us a message.</p>
<p>Sincerely</p>
<p>Nico Verbruggen<br/>
<i>Project Lead</i><br/>
<a href="mailto:nico@openshowcase.net">nico@openshowcase.net</a></p>
</div>
</body>
</html> | nicoverbruggen/openshowcase | app/views/emails/resetpassword.blade.php | PHP | gpl-2.0 | 1,412 |
<?php
/**
* @package Joomla.Plugin
* @subpackage Editors-xtd.fields
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Object\CMSObject;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Session\Session;
use Joomla\Component\Fields\Administrator\Helper\FieldsHelper;
/**
* Editor Fields button
*
* @since 3.7.0
*/
class PlgButtonFields extends CMSPlugin
{
/**
* Load the language file on instantiation.
*
* @var boolean
* @since 3.7.0
*/
protected $autoloadLanguage = true;
/**
* Display the button
*
* @param string $name The name of the button to add
*
* @return CMSObject The button options as JObject
*
* @since 3.7.0
*/
public function onDisplay($name)
{
// Check if com_fields is enabled
if (!ComponentHelper::isEnabled('com_fields'))
{
return;
}
// Guess the field context based on view.
$jinput = Factory::getApplication()->input;
$context = $jinput->get('option') . '.' . $jinput->get('view');
// Validate context.
$context = implode('.', FieldsHelper::extract($context));
if (!FieldsHelper::getFields($context))
{
return;
}
$link = 'index.php?option=com_fields&view=fields&layout=modal&tmpl=component&context='
. $context . '&editor=' . $name . '&' . Session::getFormToken() . '=1';
$button = new CMSObject;
$button->modal = true;
$button->link = $link;
$button->text = Text::_('PLG_EDITORS-XTD_FIELDS_BUTTON_FIELD');
$button->name = 'puzzle';
$button->iconSVG = '<svg viewBox="0 0 32 32" width="24" height="24"><path d="M29.948 8.008h-5.264c-1.357-0.002-2.709-0.094-1.391-2.421 1'
. '.321-2.331 2.254-5.595-3.050-5.595s-4.371 3.264-3.050 5.595c1.319 2.327-0.034 2.418-1.391 2.421h-5.746c-1.129 0-2'
. '.052 0.924-2.052 2.052v6.387c0 1.36 0.369 2.72-1.962 1.399s-6.042-2.254-6.042 3.050c0 5.303 3.711 4.371 6.042 3.0'
. '50s1.962 0.039 1.962 1.399v4.611c0 1.129 0.924 2.052 2.052 2.052h5.738c1.36 0 2.72-0.544 1.399-2.875s-2.254-5.595'
. ' 3.050-5.595 4.371 3.264 3.050 5.595c-1.321 2.331 0.039 2.875 1.399 2.875h5.256c1.129 0 2.052-0.924 2.052-2.052v-'
. '19.896c0-1.129-0.923-2.052-2.052-2.052z"></path></svg>';
$button->options = [
'height' => '300px',
'width' => '800px',
'bodyHeight' => '70',
'modalWidth' => '80',
];
return $button;
}
}
| twister65/joomla-cms | plugins/editors-xtd/fields/fields.php | PHP | gpl-2.0 | 2,629 |
<?php
/* --------------------------------------------------------------
protected_shops_handlungsanleitung.php 2014-02-28_1207 mabr
Gambio GmbH
http://www.gambio.de
Copyright (c) 2014 Gambio GmbH
Released under the GNU General Public License (Version 2)
[http://www.gnu.org/licenses/gpl-2.0.html]
--------------------------------------------------------------
based on:
(c) 2000-2001 The Exchange Project (earlier name of osCommerce)
(c) 2002-2003 osCommerce(ot_cod_fee.php,v 1.02 2003/02/24); www.oscommerce.com
(C) 2001 - 2003 TheMedia, Dipl.-Ing Thomas Plänkers ; http://www.themedia.at & http://www.oscommerce.at
(c) 2003 XT-Commerce - community made shopping http://www.xt-commerce.com ($Id: ot_cod_fee.php 1003 2005-07-10 18:58:52Z mz $)
Released under the GNU General Public License
---------------------------------------------------------------------------------------*/
$t_document_file = dirname(__FILE__).'/ps_handlungsanleitung.html';
if(defined('DIR_FS_CATALOG'))
{
include $t_document_file;
}
else
{
?>
<!DOCTYPE html>
<html>
<head>
<title>Protected Shops</title>
<style>
body { font: 0.8em sans-serif; }
</style>
</head>
<body>
<?php include $t_document_file; ?>
</body>
</html>
<?php
}
| khadim-raath/gambioTest | media/content/protected_shops_handlungsanleitung.php | PHP | gpl-2.0 | 1,273 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace YouWalk.Portal.Controllers
{
public class IndexController : Controller
{
public ActionResult Index()
{
return View();
}
}
} | rakhmanoff/YouWalk | YouWalk/Controllers/IndexController.cs | C# | gpl-2.0 | 292 |
#include "renderer.h"
#include "controller.h"
#include "renderableobject.h"
#include <QtQuick/qquickwindow.h>
#include <QtGui/QOpenGLShaderProgram>
#include <QtGui/QOpenGLContext>
#include <QGLFormat>
#include <QOpenGLContext>
#include <iostream>
#include <cmath>
#include <QOpenGLFramebufferObjectFormat>
using namespace std;
namespace CompPhys {
void Renderer::synchronize(QQuickFramebufferObject* item)
{
m_syncCount++;
Controller *controller = (Controller*)item; // TODO: Use correct casting method
if(!controller) {
return;
}
if(controller->simulatorOutputDirty()) {
controller->m_simulatorOutputMutex.lock();
const vector<RenderableObject *> &renderableObjects = controller->renderableObjects();
m_renderableObjects = renderableObjects;
for(RenderableObject *obj : m_renderableObjects) {
if(!obj->isInitialized()) {
obj->initializeSuper();
}
obj->uploadVBOs();
}
controller->setSimulatorOutputDirty(false);
controller->m_simulatorOutputMutex.unlock();
m_dirtyCount++;
}
}
void Renderer::render()
{
m_renderCount++;
glDepthMask(true);
glClearColor(1.0, 1.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
QMatrix4x4 modelViewMatrix;
QMatrix4x4 projectionMatrix;
// Render data
for(RenderableObject *obj : m_renderableObjects) {
if(obj->isInitialized()) {
obj->render(modelViewMatrix, projectionMatrix);
}
}
}
Renderer::Renderer() :
m_skipNextFrame(false),
m_syncCount(0),
m_renderCount(0),
m_dirtyCount(0)
{
}
Renderer::~Renderer()
{
}
QOpenGLFramebufferObject *Renderer::createFramebufferObject(const QSize &size) {
QOpenGLFramebufferObjectFormat format;
format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
format.setSamples(4);
return new QOpenGLFramebufferObject(size, format);
}
}
| andeplane/SimpleVisualizer | renderer.cpp | C++ | gpl-2.0 | 2,012 |
/*
* #%L
* VisBio application for visualization of multidimensional biological
* image data.
* %%
* Copyright (C) 2002 - 2014 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* 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/gpl-2.0.html>.
* #L%
*/
package loci.visbio;
import java.awt.Color;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import loci.visbio.util.InstanceServer;
import loci.visbio.util.SplashScreen;
/**
* VisBio is a biological visualization tool designed for easy visualization and
* analysis of multidimensional image data. This class is the main gateway into
* the application. It creates and displays a VisBioFrame via reflection, so
* that the splash screen appears as quickly as possible, before the class
* loader gets too far along.
*/
public final class VisBio extends Thread {
// -- Constants --
/** Application title. */
public static final String TITLE = "VisBio";
/** Application version (of the form "###"). */
private static final String V = "@visbio.version@";
/** Application version (of the form "#.##"). */
public static final String VERSION = V.equals("@visbio" + ".version@")
? "(internal build)" : (V.substring(0, 1) + "." + V.substring(1));
/** Application authors. */
public static final String AUTHOR = "Curtis Rueden and Abraham Sorber, LOCI";
/** Application build date. */
public static final String DATE = "@date@";
/** Port to use for communicating between application instances. */
public static final int INSTANCE_PORT = 0xabcd;
// -- Constructor --
/** Ensure this class can't be externally instantiated. */
private VisBio() {}
// -- VisBio API methods --
/** Launches the VisBio GUI with no arguments, in a separate thread. */
public static void startProgram() {
new VisBio().start();
}
/** Launches VisBio, returning the newly constructed VisBioFrame object. */
public static Object launch(final String[] args)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException, InvocationTargetException, NoSuchMethodException
{
// check whether VisBio is already running
boolean isRunning = true;
try {
InstanceServer.sendArguments(args, INSTANCE_PORT);
}
catch (final IOException exc) {
isRunning = false;
}
if (isRunning) return null;
// display splash screen
final String[] msg =
{ TITLE + " " + VERSION + " - " + AUTHOR, "VisBio is starting up..." };
final SplashScreen ss =
new SplashScreen(VisBio.class.getResource("visbio-logo.png"), msg,
new Color(255, 255, 220), new Color(255, 50, 50));
ss.setVisible(true);
// toggle window decoration mode via reflection
final boolean b =
"true".equals(System.getProperty("visbio.decorateWindows"));
final Class<?> jf = Class.forName("javax.swing.JFrame");
final Method m =
jf.getMethod("setDefaultLookAndFeelDecorated",
new Class<?>[] { boolean.class });
m.invoke(null, new Object[] { new Boolean(b) });
// construct VisBio interface via reflection
final Class<?> vb = Class.forName("loci.visbio.VisBioFrame");
final Constructor<?> con =
vb.getConstructor(new Class[] { ss.getClass(), String[].class });
return con.newInstance(new Object[] { ss, args });
}
// -- Thread API methods --
/** Launches the VisBio GUI with no arguments. */
@Override
public void run() {
try {
launch(new String[0]);
}
catch (final Exception exc) {
exc.printStackTrace();
}
}
// -- Main --
/** Launches the VisBio GUI. */
public static void main(final String[] args) throws ClassNotFoundException,
IllegalAccessException, InstantiationException, InvocationTargetException,
NoSuchMethodException
{
System.setProperty("apple.laf.useScreenMenuBar", "true");
final Object o = launch(args);
if (o == null) System.out.println("VisBio is already running.");
}
}
| uw-loci/visbio | src/main/java/loci/visbio/VisBio.java | Java | gpl-2.0 | 4,536 |
<?php
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
/**
* The configuration file for VirtueMart
*
* @package VirtueMart
* @subpackage core
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details.
*
* http://virtuemart.net
*/
global $mosConfig_absolute_path,$mosConfig_live_site;
if( !class_exists( 'jconfig' )) {
$global_lang = $GLOBALS['mosConfig_lang'];
@include( dirname( __FILE__ ).'/../../../configuration.php' );
$GLOBALS['mosConfig_lang'] = $mosConfig_lang = $global_lang;
}
// Check for trailing slash
if( $mosConfig_live_site[strlen( $mosConfig_live_site)-1] == '/' ) {
$app = '';
}
else {
$app = '/';
}
// these path and url definitions here are based on the Joomla! Configuration
define( 'URL', 'http://www.franar.com.ve/' );
define( 'SECUREURL', 'http://www.franar.com.ve/' );
if ( (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == '443' ) {
define( 'IMAGEURL', SECUREURL .'components/com_virtuemart/shop_image/' );
define( 'VM_THEMEURL', SECUREURL.'components/com_virtuemart/themes/ja_larix/' );
} else {
define( 'IMAGEURL', URL .'components/com_virtuemart/shop_image/' );
define( 'VM_THEMEURL', URL.'components/com_virtuemart/themes/ja_larix/' );
}
define( 'VM_THEMEPATH', $mosConfig_absolute_path.'/components/com_virtuemart/themes/ja_larix/' );
define( 'COMPONENTURL', URL .'administrator/components/com_virtuemart/' );
define( 'ADMINPATH', $mosConfig_absolute_path.'/administrator/components/com_virtuemart/' );
define( 'CLASSPATH', ADMINPATH.'classes/' );
define( 'PAGEPATH', ADMINPATH.'html/' );
define( 'IMAGEPATH', $mosConfig_absolute_path.'/components/com_virtuemart/shop_image/' );
define('PSHOP_IS_OFFLINE', '');
define('PSHOP_OFFLINE_MESSAGE', 'La tienda está actualmente en mantenimiento. Por favor vuelva pronto.');
define('USE_AS_CATALOGUE', '1');
define('VM_TABLEPREFIX', 'vm');
define('VM_PRICE_SHOW_PACKAGING_PRICELABEL', '');
define('VM_PRICE_SHOW_INCLUDINGTAX', '');
define('VM_PRICE_ACCESS_LEVEL', 'Public Frontend');
define('VM_REGISTRATION_TYPE', 'NORMAL_REGISTRATION');
define('VM_BROWSE_ORDERBY_FIELD', 'product_sku');
define('VM_GENERALLY_PREVENT_HTTPS', '1');
define('VM_ALLOW_EXTENDED_CLASSES', '');
define('VM_SHOW_REMEMBER_ME_BOX', '');
define('VM_REVIEWS_MINIMUM_COMMENT_LENGTH', '100');
define('VM_REVIEWS_MAXIMUM_COMMENT_LENGTH', '2000');
define('VM_SHOW_PRINTICON', '');
define('VM_SHOW_EMAILFRIEND', '1');
define('PSHOP_PDF_BUTTON_ENABLE', '');
define('VM_REVIEWS_AUTOPUBLISH', '');
define('VM_PROXY_URL', '');
define('VM_PROXY_PORT', '');
define('VM_PROXY_USER', '');
define('VM_PROXY_PASS', '');
define('VM_ONCHECKOUT_SHOW_LEGALINFO', '');
define('VM_ONCHECKOUT_LEGALINFO_SHORTTEXT', 'Returns Policy
You can cancel this order within two weeks after we have received it.
You can return new, unopened items from a cancelled order within 2 weeks after they have been
delivered to you. Items should be returned in their original packaging.
For more information on cancelling orders and returning items, see the Our Returns Policy page.');
define('VM_ONCHECKOUT_LEGALINFO_LINK', '');
define('ENABLE_DOWNLOADS', '1');
define('DOWNLOAD_MAX', '3');
define('DOWNLOAD_EXPIRE', '432000');
define('ENABLE_DOWNLOAD_STATUS', 'C');
define('DISABLE_DOWNLOAD_STATUS', 'X');
define('DOWNLOADROOT', '/home/franarc1/public_html/media/');
define('VM_DOWNLOADABLE_PRODUCTS_KEEP_STOCKLEVEL', '');
define('_SHOW_PRICES', '');
define('ORDER_MAIL_HTML', '1');
define('HOMEPAGE', 'shop.index');
define('CATEGORY_TEMPLATE', 'ja_vm_cat_browse');
define('FLYPAGE', 'flypage_images.tpl');
define('PRODUCTS_PER_ROW', '1');
define('ERRORPAGE', 'shop.error');
define('NO_IMAGE', 'noimage_franar.gif');
define('DEBUG', '');
define('SHOWVERSION', '');
define('TAX_VIRTUAL', '');
define('TAX_MODE', '1');
define('MULTIPLE_TAXRATES_ENABLE', '');
define('PAYMENT_DISCOUNT_BEFORE', '');
define('PAYMENT_DISCOUNT_VAT_ID', '');
define('PSHOP_ALLOW_REVIEWS', '');
define('PSHOP_AGREE_TO_TOS_ONORDER', '');
define('SHOW_CHECKOUT_BAR', '1');
define('CHECK_STOCK', '');
define('ENCODE_KEY', '6eaafec014956e95b28182d1d40120a8');
define('NO_SHIPPING', '');
define('NO_SHIPTO', '');
define('AFFILIATE_ENABLE', '');
define('PSHOP_ALLOW_FRONTENDADMIN_FOR_NOBACKENDERS', '');
define('PSHOP_IMG_RESIZE_ENABLE', '');
define('PSHOP_IMG_WIDTH', '90');
define('PSHOP_IMG_HEIGHT', '90');
define('PSHOP_COUPONS_ENABLE', '');
define('PSHOP_SHOW_PRODUCTS_IN_CATEGORY', '1');
define('PSHOP_SHOW_TOP_PAGENAV', '1');
define('PSHOP_SHOW_OUT_OF_STOCK_PRODUCTS', '1');
define('VM_CURRENCY_CONVERTER_MODULE', 'convertECB');
define('VM_CONTENT_PLUGINS_ENABLE', '');
define('VM_ENABLE_COOKIE_CHECK', '1');
define('VM_FEED_ENABLED', '1');
define('VM_FEED_CACHE', '1');
define('VM_FEED_CACHETIME', '3600');
define('VM_FEED_TITLE', 'Latest Products from {storename}');
define('VM_FEED_TITLE_CATEGORIES', '{storename} - Latest Products from Category: {catname}');
define('VM_FEED_SHOW_IMAGES', '1');
define('VM_FEED_SHOW_PRICES', '1');
define('VM_FEED_SHOW_DESCRIPTION', '1');
define('VM_FEED_DESCRIPTION_TYPE', 'product_s_desc');
define('VM_FEED_LIMITTEXT', '1');
define('VM_FEED_MAX_TEXT_LENGTH', '250');
define('VM_STORE_CREDITCARD_DATA', '1');
define('VM_ENCRYPT_FUNCTION', 'AES_ENCRYPT');
define('VM_COMPONENT_NAME', 'com_virtuemart');
define('VM_LOGFILE_ENABLED', '');
define('VM_LOGFILE_NAME', '');
define('VM_LOGFILE_LEVEL', 'PEAR_LOG_WARNING');
define('VM_DEBUG_IP_ENABLED', '');
define('VM_DEBUG_IP_ADDRESS', '');
define('VM_LOGFILE_FORMAT', '%{timestamp} %{ident} [%{priority}] [%{remoteip}] [%{username}] %{message}');
/* OrderByFields */
global $VM_BROWSE_ORDERBY_FIELDS;
$VM_BROWSE_ORDERBY_FIELDS = array( 'product_name','product_cdate','product_sku' );
/* Shop Modules that run with https only*/
global $VM_MODULES_FORCE_HTTPS;
$VM_MODULES_FORCE_HTTPS = array( 'account','checkout' );
// Checkout Steps and their order
global $VM_CHECKOUT_MODULES;
$VM_CHECKOUT_MODULES = array( 'CHECK_OUT_GET_SHIPPING_ADDR'=>array('order'=>1,'enabled'=>1),
'CHECK_OUT_GET_SHIPPING_METHOD'=>array('order'=>2,'enabled'=>1),
'CHECK_OUT_GET_PAYMENT_METHOD'=>array('order'=>3,'enabled'=>1),
'CHECK_OUT_GET_FINAL_CONFIRMATION'=>array('order'=>4,'enabled'=>1) );
/* Shipping Methods Definition */
global $PSHOP_SHIPPING_MODULES;
$PSHOP_SHIPPING_MODULES[0] = "flex";
$PSHOP_SHIPPING_MODULES[1] = "standard_shipping";
?> | kuwox/wwwfranar | administrator/components/com_virtuemart/virtuemart.cfg.php | PHP | gpl-2.0 | 6,791 |
<?php
defined( 'ABSPATH' ) or die( 'You cannot access this script directly' );
// Hook importer into admin init
add_action( 'admin_init', 'hb_importer' );
function hb_importer() {
global $wpdb;
if ( current_user_can( 'manage_options' ) && isset( $_GET['import_content_data'] ) ) {
if ( !defined('WP_LOAD_IMPORTERS') ) define('WP_LOAD_IMPORTERS', true); // we are loading importers
if ( ! class_exists( 'WP_Importer' ) ) { // if main importer class doesn't exist
$wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
include $wp_importer;
}
if ( ! class_exists('WP_Import') ) { // if WP importer doesn't exist
$wp_import = get_template_directory() . '/includes/plugins/importer/wordpress-importer.php';
include $wp_import;
}
if ( class_exists( 'WP_Importer' ) && class_exists( 'WP_Import' ) ) { // check for main import class and wp import class
$importer = new WP_Import();
$hb_import_attachments = true;
if ( isset($_GET['light_import']) && $_GET['light_import']=='yes' ){
$hb_import_attachments = false;
}
/* Delete menus to prevent menu duplication */
wp_delete_nav_menu('Main Menu');
wp_delete_nav_menu('Footer Menu');
wp_delete_nav_menu('One Page Menu');
wp_delete_nav_menu('Shortcodes Menu');
wp_delete_nav_menu('Sidebar Navigation1');
/* First Import Posts, Pages, Portfolio Content, FAQ, Images, Menus */
$theme_xml = get_template_directory() . '/includes/plugins/importer/data/highend.xml.gz';
$importer->fetch_attachments = $hb_import_attachments;
ob_start();
$importer->import($theme_xml);
ob_end_clean();
/* Import Woocommerce if WooCommerce Exists
if( class_exists('Woocommerce') ) {
$importer = new WP_Import();
$theme_xml = get_template_directory() . '/includes/plugins/importer/data/wooproducts.xml.gz';
$importer->fetch_attachments = true;
ob_start();
$importer->import($theme_xml);
ob_end_clean();
// Set pages
$woopages = array(
'woocommerce_shop_page_id' => 'Shop',
'woocommerce_cart_page_id' => 'Cart',
'woocommerce_checkout_page_id' => 'Checkout',
'woocommerce_pay_page_id' => 'Checkout → Pay',
'woocommerce_thanks_page_id' => 'Order Received',
'woocommerce_myaccount_page_id' => 'My Account',
'woocommerce_edit_address_page_id' => 'Edit My Address',
'woocommerce_view_order_page_id' => 'View Order',
'woocommerce_change_password_page_id' => 'Change Password',
'woocommerce_logout_page_id' => 'Logout',
'woocommerce_lost_password_page_id' => 'Lost Password'
);
foreach($woopages as $woo_page_name => $woo_page_title) {
$woopage = get_page_by_title( $woo_page_title );
if($woopage->ID) {
update_option($woo_page_name, $woopage->ID); // Front Page
}
}
// We no longer need to install pages
delete_option( '_wc_needs_pages' );
delete_transient( '_wc_activation_redirect' );
// Flush rules after install
flush_rewrite_rules();
}
*/
// Set imported menus to registered theme locations
$locations = get_theme_mod( 'nav_menu_locations' ); // registered menu locations in theme
$menus = wp_get_nav_menus(); // registered menus
if($menus) {
foreach($menus as $menu) { // assign menus to theme locations
if( $menu->name == 'Main Menu' ) {
$locations['main-menu'] = $menu->term_id;
$locations['mobile-menu'] = $menu->term_id;
} else if( $menu->name == 'Footer Menu' ) {
$locations['footer-menu'] = $menu->term_id;
} else if( $menu->name == 'One Page Menu' ) {
$locations['one-page-menu'] = $menu->term_id;
}
}
}
set_theme_mod( 'nav_menu_locations', $locations ); // set menus to locations
// Set reading options
$homepage = get_page_by_title( 'Home' );
if($homepage != null && $homepage->ID ) {
update_option('show_on_front', 'page');
update_option('page_on_front', $homepage->ID); // Front Page
}
if( class_exists('Woocommerce') ) {
// Add sidebar widget areas
$sidebars = array(
'ShopWidget1' => 'Show Widget 1',
'ShopWidget2' => 'Show Widget 2',
'ShopWidget3' => 'Show Widget 3',
'ShopWidget4' => 'Show Widget 4',
'DefaultPageSidebar' => 'Default Page Sidebar',
'SidebarNavigation1' => 'Sidebar Navigation 1',
'PortfolioSingleSidebar' => 'Portfolio Single Sidebar',
'ShortcodesSidebar' => 'Shortcodes Sidebar',
'ShopSidebar' => 'Shop Sidebar',
);
} else {
// Add sidebar widget areas
$sidebars = array(
'DefaultPageSidebar' => 'Default Page Sidebar',
'SidebarNavigation1' => 'Sidebar Navigation 1',
'PortfolioSingleSidebar' => 'Portfolio Single Sidebar',
'ShortcodesSidebar' => 'Shortcodes Sidebar',
);
}
update_option( 'sbg_sidebars', $sidebars );
foreach( $sidebars as $sidebar ) {
$sidebar_class = hb_name_to_class( $sidebar );
register_sidebar(array(
'name' => $sidebar,
'id' => 'hb-custom-sidebar-' . strtolower( $sidebar_class ),
'before_widget' => '<div id="%1$s" class="widget-item %2$s">',
'after_widget' => '</div>',
'before_title' => '<h4>',
'after_title' => '</h4>'
));
}
// Add data to widgets
$widgets_json = get_template_directory_uri() . '/includes/plugins/importer/data/widgets.json'; // widgets data file
$widgets_json = wp_remote_get( $widgets_json );
$widget_data = $widgets_json['body'];
$import_widgets = hb_import_widget_data( $widget_data );
/* Import Layerslider
if( function_exists( 'layerslider_import_sample_slider' ) && $hb_import_attachments == true ) { // if layerslider is activated
// Get importUtil
include WP_PLUGIN_DIR . '/LayerSlider/classes/class.ls.importutil.php';
$layer_directory = get_template_directory() . '/includes/plugins/importer/data/layersliders/'; // layerslider data dir
foreach( glob( $layer_directory . '*.zip' ) as $filename ) { // get all files from revsliders data dir
$filename = basename($filename);
$layer_files[] = get_template_directory() . '/includes/plugins/importer/data/layersliders/' . $filename ;
}
foreach( $layer_files as $layer_file ) { // finally import layer slider
$import = new LS_ImportUtil($layer_file);
}
// Get all sliders
// Table name
$table_name = $wpdb->prefix . "layerslider";
// Get sliders
$sliders = $wpdb->get_results( "SELECT * FROM $table_name
WHERE flag_hidden = '0' AND flag_deleted = '0'
ORDER BY date_c ASC" );
if(!empty($sliders)):
foreach($sliders as $key => $item):
$slides[$item->id] = $item->name;
endforeach;
endif;
if($slides){
foreach($slides as $key => $val){
$slides_array[$val] = $key;
}
}
}*/
// Import Revslider
if( class_exists('UniteFunctionsRev') && $hb_import_attachments == true ) { // if revslider is activated
// Download Rev Sliders imports to local
$url = get_template_directory() . '/includes/plugins/importer/data/revsliders/jobs-slider.zip';
if (!file_exists($url)){
$d_url = 'http://hb-themes.com/repository/import/highend/revsliders/jobs-slider.zip';
$src = fopen($d_url, 'r');
$dest = fopen($url, 'w');
stream_copy_to_stream($src, $dest);
fclose($d_url);
fclose($url);
}
$url = get_template_directory() . '/includes/plugins/importer/data/revsliders/boxed-corporate-slider.zip';
if (!file_exists($url)){
$d_url = 'http://hb-themes.com/repository/import/highend/revsliders/boxed-corporate-slider.zip';
$src = fopen($d_url, 'r');
$dest = fopen($url, 'w');
stream_copy_to_stream($src, $dest);
fclose($d_url);
fclose($url);
}
$url = get_template_directory() . '/includes/plugins/importer/data/revsliders/corporate-slider.zip';
if (!file_exists($url)){
$d_url = 'http://hb-themes.com/repository/import/highend/revsliders/corporate-slider.zip';
$src = fopen($d_url, 'r');
$dest = fopen($url, 'w');
stream_copy_to_stream($src, $dest);
fclose($d_url);
fclose($url);
}
$url = get_template_directory() . '/includes/plugins/importer/data/revsliders/home-classic-slider.zip';
if (!file_exists($url)){
$d_url = 'http://hb-themes.com/repository/import/highend/revsliders/home-classic-slider.zip';
$src = fopen($d_url, 'r');
$dest = fopen($url, 'w');
stream_copy_to_stream($src, $dest);
fclose($d_url);
fclose($url);
}
$url = get_template_directory() . '/includes/plugins/importer/data/revsliders/home-default-slider.zip';
if (!file_exists($url)){
$d_url = 'http://hb-themes.com/repository/import/highend/revsliders/home-default-slider.zip';
$src = fopen($d_url, 'r');
$dest = fopen($url, 'w');
stream_copy_to_stream($src, $dest);
fclose($d_url);
fclose($url);
}
$url = get_template_directory() . '/includes/plugins/importer/data/revsliders/home-special-slider.zip';
if (!file_exists($url)){
$d_url = 'http://hb-themes.com/repository/import/highend/revsliders/home-special-slider.zip';
$src = fopen($d_url, 'r');
$dest = fopen($url, 'w');
stream_copy_to_stream($src, $dest);
fclose($d_url);
fclose($url);
}
$url = get_template_directory() . '/includes/plugins/importer/data/revsliders/one-page-slider.zip';
if (!file_exists($url)){
$d_url = 'http://hb-themes.com/repository/import/highend/revsliders/one-page-slider.zip';
$src = fopen($d_url, 'r');
$dest = fopen($url, 'w');
stream_copy_to_stream($src, $dest);
fclose($d_url);
fclose($url);
}
$url = get_template_directory() . '/includes/plugins/importer/data/revsliders/shop-slider.zip';
if (!file_exists($url)){
$d_url = 'http://hb-themes.com/repository/import/highend/revsliders/shop-slider.zip';
$src = fopen($d_url, 'r');
$dest = fopen($url, 'w');
stream_copy_to_stream($src, $dest);
fclose($d_url);
fclose($url);
}
// END REV SLIDER IMPORTS
$rev_directory = get_template_directory() . '/includes/plugins/importer/data/revsliders/'; // layerslider data dir
foreach( glob( $rev_directory . '*.zip' ) as $filename ) { // get all files from revsliders data dir
$filename = basename($filename);
$rev_files[] = get_template_directory() . '/includes/plugins/importer/data/revsliders/' . $filename ;
}
foreach( $rev_files as $rev_file ) { // finally import rev slider data files
$filepath = $rev_file;
//if(file_exists($filepath) == false)
//UniteFunctionsRev::throwError("Import file not found!!!");
//check if zip file or fallback to old, if zip, check if all files exist
$zip = new ZipArchive;
$importZip = $zip->open($filepath, ZIPARCHIVE::CREATE);
if($importZip === true){ //true or integer. If integer, its not a correct zip file
//check if files all exist in zip
$slider_export = $zip->getStream('slider_export.txt');
$custom_animations = $zip->getStream('custom_animations.txt');
$dynamic_captions = $zip->getStream('dynamic-captions.css');
$static_captions = $zip->getStream('static-captions.css');
//if(!$slider_export) UniteFunctionsRev::throwError("slider_export.txt does not exist!");
//if(!$custom_animations) UniteFunctionsRev::throwError("custom_animations.txt does not exist!");
//if(!$dynamic_captions) UniteFunctionsRev::throwError("dynamic-captions.css does not exist!");
//if(!$static_captions) UniteFunctionsRev::throwError("static-captions.css does not exist!");
$content = '';
$animations = '';
$dynamic = '';
$static = '';
while (!feof($slider_export)) $content .= fread($slider_export, 1024);
if($custom_animations){ while (!feof($custom_animations)) $animations .= fread($custom_animations, 1024); }
if($dynamic_captions){ while (!feof($dynamic_captions)) $dynamic .= fread($dynamic_captions, 1024); }
if($static_captions){ while (!feof($static_captions)) $static .= fread($static_captions, 1024); }
fclose($slider_export);
if($custom_animations){ fclose($custom_animations); }
if($dynamic_captions){ fclose($dynamic_captions); }
if($static_captions){ fclose($static_captions); }
//check for images!
}else{ //check if fallback
//get content array
$content = @file_get_contents($filepath);
}
if($importZip === true){ //we have a zip
$db = new UniteDBRev();
//update/insert custom animations
$animations = @unserialize($animations);
if(!empty($animations)){
foreach($animations as $key => $animation){ //$animation['id'], $animation['handle'], $animation['params']
$exist = $db->fetch(GlobalsRevSlider::$table_layer_anims, "handle = '".$animation['handle']."'");
if(!empty($exist)){ //update the animation, get the ID
if($updateAnim == "true"){ //overwrite animation if exists
$arrUpdate = array();
$arrUpdate['params'] = stripslashes(json_encode(str_replace("'", '"', $animation['params'])));
$db->update(GlobalsRevSlider::$table_layer_anims, $arrUpdate, array('handle' => $animation['handle']));
$id = $exist['0']['id'];
}else{ //insert with new handle
$arrInsert = array();
$arrInsert["handle"] = 'copy_'.$animation['handle'];
$arrInsert["params"] = stripslashes(json_encode(str_replace("'", '"', $animation['params'])));
$id = $db->insert(GlobalsRevSlider::$table_layer_anims, $arrInsert);
}
}else{ //insert the animation, get the ID
$arrInsert = array();
$arrInsert["handle"] = $animation['handle'];
$arrInsert["params"] = stripslashes(json_encode(str_replace("'", '"', $animation['params'])));
$id = $db->insert(GlobalsRevSlider::$table_layer_anims, $arrInsert);
}
//and set the current customin-oldID and customout-oldID in slider params to new ID from $id
$content = str_replace(array('customin-'.$animation['id'], 'customout-'.$animation['id']), array('customin-'.$id, 'customout-'.$id), $content);
}
//dmp(__("animations imported!",REVSLIDER_TEXTDOMAIN));
}else{
//dmp(__("no custom animations found, if slider uses custom animations, the provided export may be broken...",REVSLIDER_TEXTDOMAIN));
}
//overwrite/append static-captions.css
if(!empty($static)){
if($updateStatic == "true"){ //overwrite file
RevOperations::updateStaticCss($static);
}else{ //append
$static_cur = RevOperations::getStaticCss();
$static = $static_cur."\n".$static;
RevOperations::updateStaticCss($static);
}
}
//overwrite/create dynamic-captions.css
//parse css to classes
$dynamicCss = UniteCssParserRev::parseCssToArray($dynamic);
if(is_array($dynamicCss) && $dynamicCss !== false && count($dynamicCss) > 0){
foreach($dynamicCss as $class => $styles){
//check if static style or dynamic style
$class = trim($class);
if((strpos($class, ':hover') === false && strpos($class, ':') !== false) || //before, after
strpos($class," ") !== false || // .tp-caption.imageclass img or .tp-caption .imageclass or .tp-caption.imageclass .img
strpos($class,".tp-caption") === false || // everything that is not tp-caption
(strpos($class,".") === false || strpos($class,"#") !== false) || // no class -> #ID or img
strpos($class,">") !== false){ //.tp-caption>.imageclass or .tp-caption.imageclass>img or .tp-caption.imageclass .img
continue;
}
//is a dynamic style
if(strpos($class, ':hover') !== false){
$class = trim(str_replace(':hover', '', $class));
$arrInsert = array();
$arrInsert["hover"] = json_encode($styles);
$arrInsert["settings"] = json_encode(array('hover' => 'true'));
}else{
$arrInsert = array();
$arrInsert["params"] = json_encode($styles);
}
//check if class exists
$result = $db->fetch(GlobalsRevSlider::$table_css, "handle = '".$class."'");
if(!empty($result)){ //update
$db->update(GlobalsRevSlider::$table_css, $arrInsert, array('handle' => $class));
}else{ //insert
$arrInsert["handle"] = $class;
$db->insert(GlobalsRevSlider::$table_css, $arrInsert);
}
}
//dmp(__("dynamic styles imported!",REVSLIDER_TEXTDOMAIN));
}else{
//dmp(__("no dynamic styles found, if slider uses dynamic styles, the provided export may be broken...",REVSLIDER_TEXTDOMAIN));
}
}
$content = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $content); //clear errors in string
$arrSlider = @unserialize($content);
$sliderParams = $arrSlider["params"];
if(isset($sliderParams["background_image"]))
$sliderParams["background_image"] = UniteFunctionsWPRev::getImageUrlFromPath($sliderParams["background_image"]);
$json_params = json_encode($sliderParams);
//new slider
$arrInsert = array();
$arrInsert["params"] = $json_params;
$arrInsert["title"] = UniteFunctionsRev::getVal($sliderParams, "title","Slider1");
$arrInsert["alias"] = UniteFunctionsRev::getVal($sliderParams, "alias","slider1");
$sliderID = $wpdb->insert(GlobalsRevSlider::$table_sliders,$arrInsert);
$sliderID = $wpdb->insert_id;
//-------- Slides Handle -----------
//create all slides
$arrSlides = $arrSlider["slides"];
$alreadyImported = array();
foreach($arrSlides as $slide){
$params = $slide["params"];
$layers = $slide["layers"];
//convert params images:
if(isset($params["image"])){
//import if exists in zip folder
if(trim($params["image"]) !== ''){
if($importZip === true){ //we have a zip, check if exists
$image = $zip->getStream('images/'.$params["image"]);
if(!$image){
echo $params["image"].' not found!<br>';
}else{
if(!isset($alreadyImported['zip://'.$filepath."#".'images/'.$params["image"]])){
$importImage = UniteFunctionsWPRev::import_media('zip://'.$filepath."#".'images/'.$params["image"], $sliderParams["alias"].'/');
if($importImage !== false){
$alreadyImported['zip://'.$filepath."#".'images/'.$params["image"]] = $importImage['path'];
$params["image"] = $importImage['path'];
}
}else{
$params["image"] = $alreadyImported['zip://'.$filepath."#".'images/'.$params["image"]];
}
}
}
}
$params["image"] = UniteFunctionsWPRev::getImageUrlFromPath($params["image"]);
}
//convert layers images:
foreach($layers as $key=>$layer){
if(isset($layer["image_url"])){
//import if exists in zip folder
if(trim($layer["image_url"]) !== ''){
if($importZip === true){ //we have a zip, check if exists
$image_url = $zip->getStream('images/'.$layer["image_url"]);
if(!$image_url){
echo $layer["image_url"].' not found!<br>';
}else{
if(!isset($alreadyImported['zip://'.$filepath."#".'images/'.$layer["image_url"]])){
$importImage = UniteFunctionsWPRev::import_media('zip://'.$filepath."#".'images/'.$layer["image_url"], $sliderParams["alias"].'/');
if($importImage !== false){
$alreadyImported['zip://'.$filepath."#".'images/'.$layer["image_url"]] = $importImage['path'];
$layer["image_url"] = $importImage['path'];
}
}else{
$layer["image_url"] = $alreadyImported['zip://'.$filepath."#".'images/'.$layer["image_url"]];
}
}
}
}
$layer["image_url"] = UniteFunctionsWPRev::getImageUrlFromPath($layer["image_url"]);
$layers[$key] = $layer;
}
}
//create new slide
$arrCreate = array();
$arrCreate["slider_id"] = $sliderID;
$arrCreate["slide_order"] = $slide["slide_order"];
$arrCreate["layers"] = json_encode($layers);
$arrCreate["params"] = json_encode($params);
$wpdb->insert(GlobalsRevSlider::$table_slides,$arrCreate);
//}
}
}
}
// finally redirect to success page
wp_redirect( admin_url( 'themes.php?page=highend_options&imported=success#_hb_general_settings' ) );
}
}
}
// Parsing Widgets Function
// Thanks to http://wordpress.org/plugins/widget-settings-importexport/
function hb_import_widget_data( $widget_data ) {
$json_data = $widget_data;
$json_data = json_decode( $json_data, true );
$sidebar_data = $json_data[0];
$widget_data = $json_data[1];
foreach ( $widget_data as $widget_data_title => $widget_data_value ) {
$widgets[ $widget_data_title ] = '';
foreach( $widget_data_value as $widget_data_key => $widget_data_array ) {
if( is_int( $widget_data_key ) ) {
$widgets[$widget_data_title][$widget_data_key] = 'on';
}
}
}
unset($widgets[""]);
foreach ( $sidebar_data as $title => $sidebar ) {
$count = count( $sidebar );
for ( $i = 0; $i < $count; $i++ ) {
$widget = array( );
$widget['type'] = trim( substr( $sidebar[$i], 0, strrpos( $sidebar[$i], '-' ) ) );
$widget['type-index'] = trim( substr( $sidebar[$i], strrpos( $sidebar[$i], '-' ) + 1 ) );
if ( !isset( $widgets[$widget['type']][$widget['type-index']] ) ) {
unset( $sidebar_data[$title][$i] );
}
}
$sidebar_data[$title] = array_values( $sidebar_data[$title] );
}
foreach ( $widgets as $widget_title => $widget_value ) {
foreach ( $widget_value as $widget_key => $widget_value ) {
$widgets[$widget_title][$widget_key] = $widget_data[$widget_title][$widget_key];
}
}
$sidebar_data = array( array_filter( $sidebar_data ), $widgets );
hb_parse_import_data( $sidebar_data );
}
function hb_parse_import_data( $import_array ) {
global $wp_registered_sidebars;
$sidebars_data = $import_array[0];
$widget_data = $import_array[1];
$current_sidebars = get_option( 'sidebars_widgets' );
$new_widgets = array( );
foreach ( $sidebars_data as $import_sidebar => $import_widgets ) :
foreach ( $import_widgets as $import_widget ) :
//if the sidebar exists
if ( isset( $wp_registered_sidebars[$import_sidebar] ) ) :
$title = trim( substr( $import_widget, 0, strrpos( $import_widget, '-' ) ) );
$index = trim( substr( $import_widget, strrpos( $import_widget, '-' ) + 1 ) );
$current_widget_data = get_option( 'widget_' . $title );
$new_widget_name = hb_get_new_widget_name( $title, $index );
$new_index = trim( substr( $new_widget_name, strrpos( $new_widget_name, '-' ) + 1 ) );
if ( !empty( $new_widgets[ $title ] ) && is_array( $new_widgets[$title] ) ) {
while ( array_key_exists( $new_index, $new_widgets[$title] ) ) {
$new_index++;
}
}
$current_sidebars[$import_sidebar][] = $title . '-' . $new_index;
if ( array_key_exists( $title, $new_widgets ) ) {
$new_widgets[$title][$new_index] = $widget_data[$title][$index];
$multiwidget = $new_widgets[$title]['_multiwidget'];
unset( $new_widgets[$title]['_multiwidget'] );
$new_widgets[$title]['_multiwidget'] = $multiwidget;
} else {
$current_widget_data[$new_index] = $widget_data[$title][$index];
$current_multiwidget = $current_widget_data['_multiwidget'];
$new_multiwidget = isset($widget_data[$title]['_multiwidget']) ? $widget_data[$title]['_multiwidget'] : false;
$multiwidget = ($current_multiwidget != $new_multiwidget) ? $current_multiwidget : 1;
unset( $current_widget_data['_multiwidget'] );
$current_widget_data['_multiwidget'] = $multiwidget;
$new_widgets[$title] = $current_widget_data;
}
endif;
endforeach;
endforeach;
if ( isset( $new_widgets ) && isset( $current_sidebars ) ) {
update_option( 'sidebars_widgets', $current_sidebars );
foreach ( $new_widgets as $title => $content )
update_option( 'widget_' . $title, $content );
return true;
}
return false;
}
function hb_get_new_widget_name( $widget_name, $widget_index ) {
$current_sidebars = get_option( 'sidebars_widgets' );
$all_widget_array = array( );
foreach ( $current_sidebars as $sidebar => $widgets ) {
if ( !empty( $widgets ) && is_array( $widgets ) && $sidebar != 'wp_inactive_widgets' ) {
foreach ( $widgets as $widget ) {
$all_widget_array[] = $widget;
}
}
}
while ( in_array( $widget_name . '-' . $widget_index, $all_widget_array ) ) {
$widget_index++;
}
$new_widget_name = $widget_name . '-' . $widget_index;
return $new_widget_name;
}
if( function_exists( 'layerslider_import_sample_slider' ) ) {
function hb_import_sample_slider( $layerslider_data ) {
// Base64 encoded, serialized slider export code
$sample_slider = $layerslider_data;
// Iterate over the sliders
foreach($sample_slider as $sliderkey => $slider) {
// Iterate over the layers
foreach($sample_slider[$sliderkey]['layers'] as $layerkey => $layer) {
// Change background images if any
if(!empty($sample_slider[$sliderkey]['layers'][$layerkey]['properties']['background'])) {
$sample_slider[$sliderkey]['layers'][$layerkey]['properties']['background'] = $GLOBALS['lsPluginPath'].'sampleslider/'.basename($layer['properties']['background']);
}
// Change thumbnail images if any
if(!empty($sample_slider[$sliderkey]['layers'][$layerkey]['properties']['thumbnail'])) {
$sample_slider[$sliderkey]['layers'][$layerkey]['properties']['thumbnail'] = $GLOBALS['lsPluginPath'].'sampleslider/'.basename($layer['properties']['thumbnail']);
}
// Iterate over the sublayers
if(isset($layer['sublayers']) && !empty($layer['sublayers'])) {
foreach($layer['sublayers'] as $sublayerkey => $sublayer) {
// Only IMG sublayers
if($sublayer['type'] == 'img') {
$sample_slider[$sliderkey]['layers'][$layerkey]['sublayers'][$sublayerkey]['image'] = $GLOBALS['lsPluginPath'].'sampleslider/'.basename($sublayer['image']);
}
}
}
}
}
// Get WPDB Object
global $wpdb;
// Table name
$table_name = $wpdb->prefix . "layerslider";
// Append duplicate
foreach($sample_slider as $key => $val) {
// Insert the duplicate
$wpdb->query(
$wpdb->prepare("INSERT INTO $table_name
(name, data, date_c, date_m)
VALUES (%s, %s, %d, %d)",
$val['properties']['title'],
json_encode($val),
time(),
time()
)
);
}
}
}
// Rename sidebar
function hb_name_to_class($name){
$class = str_replace(array(' ',',','.','"',"'",'/',"\\",'+','=',')','(','*','&','^','%','$','#','@','!','~','`','<','>','?','[',']','{','}','|',':',),'',$name);
return $class;
} | czucker/genco | wp-content/themes/HighendWP/includes/plugins/importer/importer.php | PHP | gpl-2.0 | 33,687 |
/******************************************************************************
* Copyright (C) 2011 Kenos Assessoria e Consultoria de Sistemas Ltda *
* Copyright (C) 2011 Ricardo Santana *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*****************************************************************************/
package org.adempierelbr.model;
import java.sql.ResultSet;
import java.util.Properties;
/**
* Model for Tax Configuration Product
*
* @author Ricardo Santana (Kenos, www.kenos.com.br)
* @version $Id: MLBRTaxConfigProduct.java, v2.0 2011/10/13 2:16:18 PM, ralexsander Exp $
*/
public class MLBRTaxConfigProduct extends X_LBR_TaxConfig_Product
{
/**
* Serial Version
*/
private static final long serialVersionUID = 1L;
/**************************************************************************
* Default Constructor
* @param Properties ctx
* @param int ID (0 create new)
* @param String trx
*/
public MLBRTaxConfigProduct (Properties ctx, int ID, String trxName)
{
super (ctx, ID, trxName);
} // MLBRTaxConfigProduct
/**
* Load Constructor
* @param ctx context
* @param rs result set record
* @param trxName transaction
*/
public MLBRTaxConfigProduct (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MLBRTaxConfigProduct
/**
* Before Save
*/
protected boolean beforeSave (boolean newRecord)
{
return super.beforeSave(newRecord);
} // beforeSave
} // MLBRTaxConfigProduct | arthurmelo88/palmetalADP | palmetal_to_lbrk/base/src/org/adempierelbr/model/MLBRTaxConfigProduct.java | Java | gpl-2.0 | 2,274 |
/*
* TODO: license
*/
package ca.mbabic.headphonecontroller.statemachine;
import java.lang.Thread.State;
import java.util.concurrent.Semaphore;
import android.util.Log;
import ca.mbabic.headphonecontroller.services.MediaButtonListenerService;
/**
* State machine keeping track of the state of the button presses.
* Implementation of the State Pattern. See:
* http://sourcemaking.com/design_patterns/state
*
* @author Marko Babic
*/
public class HCStateMachine {
/**
* Reference to MediaButtonListenerService such that after command execution
* we can re-register ourselves as exclusive media button player listener.
*/
private static MediaButtonListenerService listenerService;
/**
* Class specific logging tag.
*/
private static final String TAG = ".statemachine.HCStateMachine";
/**
* Interval to wait between button presses.
*/
// TODO: make configurable
private static final long BTN_PRESS_INTERVAL = 400;
/**
* Instance of HCStateMachine available to the application.
*/
private static volatile HCStateMachine instance = null;
/**
* Reference to the state in which the machine is currently in.
*/
private static HCState currentState;
/**
* The starting state of the machine.
*/
private static HCState startState;
/**
* Time left until count down thread will execute the current state's
* command.
*/
private static long timeToExecution;
/**
* The amount of time the count down thread will sleep between acquiring the
* semaphore and updating timeToExecution.
*/
private static final long SLEEP_INTERVAL = 100;
/**
* Semaphore used to lock access to shared variable timeToExecution.
*/
private static Semaphore countDownSemaphore = new Semaphore(1);
/**
* Thread in which the count down to execution monitoring functionality is
* implemented.
*/
private Thread countDownThread;
static Runnable countDownRunnable = new Runnable() {
public void run() {
timeToExecution = BTN_PRESS_INTERVAL;
while (timeToExecution > 0) {
try {
Thread.sleep(SLEEP_INTERVAL);
countDownSemaphore.acquire();
timeToExecution -= SLEEP_INTERVAL;
} catch (InterruptedException ie) {
Log.e(TAG, "Coundown thread interrupted!");
return;
} finally {
countDownSemaphore.release();
}
}
// Count down expired, execute current state's command.
// TODO: this should be synchronized ... and we should take one
// last check here to make sure timeToExecution <= 0 and if not
// start looping again and not execute anything ...
currentState.executeCommand();
listenerService.registerAsMediaButtonListener();
currentState = startState;
}
};
/**
* Private constructor. Get global application reference to state machine
* via getInstance().
*/
private HCStateMachine() {
startState = new InactiveState();
currentState = startState;
}
public void setService(MediaButtonListenerService mbls) {
listenerService = mbls;
}
/**
* @return Singleton instance of HCStateMachine.
*/
public static HCStateMachine getInstance() {
if (instance == null) {
synchronized (HCStateMachine.class) {
// Double check instance locking
if (instance == null) {
instance = new HCStateMachine();
}
}
}
return instance;
}
/**
* Indicate to state machine that the media button has been pressed on the
* headphones. TODO: keep track of long clicks... should not transition to
* next state at end of such a command.
*/
public void keyUp() {
makeStateTransition();
}
/**
* Transition to next state as appropriate given currentState.
*/
private void makeStateTransition() {
HCState nextState = currentState.getNextState();
if (currentState.isTerminal()) {
stopCountDownToExecution();
currentState.executeCommand();
currentState = startState;
} else {
currentState = nextState;
startCountDownToExecution();
}
}
/**
* Call to start or reset a count down to execution of the current state's
* command.
*/
private void startCountDownToExecution() {
try {
countDownSemaphore.acquire();
if (countDownThread == null
|| countDownThread.getState() == State.TERMINATED) {
countDownThread = new Thread(countDownRunnable);
countDownThread.start();
} else {
timeToExecution = BTN_PRESS_INTERVAL;
}
} catch (Exception e) {
Log.e(TAG, e.toString());
} finally {
countDownSemaphore.release();
}
}
/**
* Called to cancel count down to execution thread.
*/
private void stopCountDownToExecution() {
countDownThread.interrupt();
try {
countDownThread.join();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
}
| mbabic/HeadphoneController | src/ca/mbabic/headphonecontroller/statemachine/HCStateMachine.java | Java | gpl-2.0 | 4,900 |
#!/usr/bin/env python
import os
from setuptools import setup
from subprocess import call
from sys import platform, argv
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
SCRIPTS = ["src/bg_daemon/background_daemon.py"]
# only compile quack when none of these options are chosen
if (all([e not in argv for e in ['egg_info', 'sdist', 'register']]) and
platform == 'darwin'):
try:
call(['make', '-C', 'src/bg_daemon/'])
SCRIPTS.append("src/bg_daemon/quack")
except OSError as e:
print "Can't compile quack, reason {}".format(str(e))
setup(
name="bg_daemon",
version="0.0.1",
author="Santiago Torres",
author_email="torresariass@gmail.com",
description=("An extensible set of classes that can programmatically "
"update the desktop wallpaper"),
license="GPLv2",
keywords="imgur desktop wallpaper background",
url="https://github.com/santiagotorres/bg_daemon",
packages=["bg_daemon", "bg_daemon.fetchers"],
package_dir={"bg_daemon": "src/bg_daemon",
"bg_daemon.fetchers": "src/bg_daemon/fetchers"},
scripts=SCRIPTS,
include_package_data=True,
data_files=[('bg_daemon', ['src/bg_daemon/settings.json',
'src/bg_daemon/mac-update.sh'])],
long_description=read("README.md"),
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Topic :: Utilities",
"License :: ",
"Environment :: No Input/Output (Daemon)",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: GNU General Public License v2 (GPLv2)",
"Operating System :: Unix",
"Topic :: Multimedia",
],
install_requires=[
"imgurpython",
"requests",
"python-crontab",
"mock",
],
)
| echenran/bg_daemon | setup.py | Python | gpl-2.0 | 1,862 |
/*
* Copyright (C) 2014-2017 StormCore
*
* 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 "ObjectMgr.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellScript.h"
#include "Spell.h"
#include "SpellAuraEffects.h"
#include "PassiveAI.h"
//
// Emerald Dragon NPCs and IDs (kept here for reference)
//
enum EmeraldDragonNPC
{
NPC_DREAM_FOG = 15224,
DRAGON_YSONDRE = 14887,
DRAGON_LETHON = 14888,
DRAGON_EMERISS = 14889,
DRAGON_TAERAR = 14890,
};
//
// Emerald Dragon Spells (used for the dragons)
//
enum EmeraldDragonSpells
{
SPELL_TAIL_SWEEP = 15847, // tail sweep - slap everything behind dragon (2 seconds interval)
SPELL_SUMMON_PLAYER = 24776, // teleport highest threat player in front of dragon if wandering off
SPELL_DREAM_FOG = 24777, // auraspell for Dream Fog NPC (15224)
SPELL_SLEEP = 24778, // sleep triggerspell (used for Dream Fog)
SPELL_SEEPING_FOG_LEFT = 24813, // dream fog - summon left
SPELL_SEEPING_FOG_RIGHT = 24814, // dream fog - summon right
SPELL_NOXIOUS_BREATH = 24818,
SPELL_MARK_OF_NATURE = 25040, // Mark of Nature trigger (applied on target death - 15 minutes of being suspectible to Aura Of Nature)
SPELL_MARK_OF_NATURE_AURA = 25041, // Mark of Nature (passive marker-test, ticks every 10 seconds from boss, triggers spellID 25042 (scripted)
SPELL_AURA_OF_NATURE = 25043, // Stun for 2 minutes (used when SPELL_MARK_OF_NATURE exists on the target)
};
//
// Emerald Dragon Eventlists (shared and specials)
//
enum Events
{
// General events for all dragons
EVENT_SEEPING_FOG = 1,
EVENT_NOXIOUS_BREATH,
EVENT_TAIL_SWEEP,
// Ysondre
EVENT_LIGHTNING_WAVE,
EVENT_SUMMON_DRUID_SPIRITS,
// Lethon
EVENT_SHADOW_BOLT_WHIRL,
// Emeriss
EVENT_VOLATILE_INFECTION,
EVENT_CORRUPTION_OF_EARTH,
// Taerar
EVENT_ARCANE_BLAST,
EVENT_BELLOWING_ROAR,
};
/*
* ---
* --- Emerald Dragons : Base AI-structure used for all the Emerald dragons
* ---
*/
struct emerald_dragonAI : public WorldBossAI
{
emerald_dragonAI(Creature* creature) : WorldBossAI(creature)
{
}
void Reset() override
{
WorldBossAI::Reset();
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE);
me->SetReactState(REACT_AGGRESSIVE);
DoCast(me, SPELL_MARK_OF_NATURE_AURA, true);
events.ScheduleEvent(EVENT_TAIL_SWEEP, 4000);
events.ScheduleEvent(EVENT_NOXIOUS_BREATH, urand(7500, 15000));
events.ScheduleEvent(EVENT_SEEPING_FOG, urand(12500, 20000));
}
// Target killed during encounter, mark them as suspectible for Aura Of Nature
void KilledUnit(Unit* who) override
{
if (who->GetTypeId() == TYPEID_PLAYER)
who->CastSpell(who, SPELL_MARK_OF_NATURE, true);
}
// Execute and reschedule base events shared between all Emerald Dragons
void ExecuteEvent(uint32 eventId) override
{
switch (eventId)
{
case EVENT_SEEPING_FOG:
// Seeping Fog appears only as "pairs", and only ONE pair at any given time!
// Despawntime is 2 minutes, so reschedule it for new cast after 2 minutes + a minor "random time" (30 seconds at max)
DoCast(me, SPELL_SEEPING_FOG_LEFT, true);
DoCast(me, SPELL_SEEPING_FOG_RIGHT, true);
events.ScheduleEvent(EVENT_SEEPING_FOG, urand(120000, 150000));
break;
case EVENT_NOXIOUS_BREATH:
// Noxious Breath is cast on random intervals, no less than 7.5 seconds between
DoCast(me, SPELL_NOXIOUS_BREATH);
events.ScheduleEvent(EVENT_NOXIOUS_BREATH, urand(7500, 15000));
break;
case EVENT_TAIL_SWEEP:
// Tail Sweep is cast every two seconds, no matter what goes on in front of the dragon
DoCast(me, SPELL_TAIL_SWEEP);
events.ScheduleEvent(EVENT_TAIL_SWEEP, 2000);
break;
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
ExecuteEvent(eventId);
if (Unit* target = SelectTarget(SELECT_TARGET_TOPAGGRO, 0, -50.0f, true))
DoCast(target, SPELL_SUMMON_PLAYER);
DoMeleeAttackIfReady();
}
};
/*
* --- NPC: Dream Fog
*/
class npc_dream_fog : public CreatureScript
{
public:
npc_dream_fog() : CreatureScript("npc_dream_fog") { }
struct npc_dream_fogAI : public ScriptedAI
{
npc_dream_fogAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
}
void Initialize()
{
_roamTimer = 0;
}
void Reset() override
{
Initialize();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (!_roamTimer)
{
// Chase target, but don't attack - otherwise just roam around
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true))
{
_roamTimer = urand(15000, 30000);
me->GetMotionMaster()->Clear(false);
me->GetMotionMaster()->MoveChase(target, 0.2f);
}
else
{
_roamTimer = 2500;
me->GetMotionMaster()->Clear(false);
me->GetMotionMaster()->MoveRandom(25.0f);
}
// Seeping fog movement is slow enough for a player to be able to walk backwards and still outpace it
me->SetWalk(true);
me->SetSpeedRate(MOVE_WALK, 0.75f);
}
else
_roamTimer -= diff;
}
private:
uint32 _roamTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_dream_fogAI(creature);
}
};
/*
* ---
* --- Dragonspecific scripts and handling: YSONDRE
* ---
*/
enum YsondreNPC
{
NPC_DEMENTED_DRUID = 15260,
};
enum YsondreTexts
{
SAY_YSONDRE_AGGRO = 0,
SAY_YSONDRE_SUMMON_DRUIDS = 1,
};
enum YsondreSpells
{
SPELL_LIGHTNING_WAVE = 24819,
SPELL_SUMMON_DRUID_SPIRITS = 24795,
};
class boss_ysondre : public CreatureScript
{
public:
boss_ysondre() : CreatureScript("boss_ysondre") { }
struct boss_ysondreAI : public emerald_dragonAI
{
boss_ysondreAI(Creature* creature) : emerald_dragonAI(creature)
{
Initialize();
}
void Initialize()
{
_stage = 1;
}
void Reset() override
{
Initialize();
emerald_dragonAI::Reset();
events.ScheduleEvent(EVENT_LIGHTNING_WAVE, 12000);
}
void EnterCombat(Unit* who) override
{
Talk(SAY_YSONDRE_AGGRO);
WorldBossAI::EnterCombat(who);
}
// Summon druid spirits on 75%, 50% and 25% health
void DamageTaken(Unit* /*attacker*/, uint32& /*damage*/) override
{
if (!HealthAbovePct(100 - 25 * _stage))
{
Talk(SAY_YSONDRE_SUMMON_DRUIDS);
for (uint8 i = 0; i < 10; ++i)
DoCast(me, SPELL_SUMMON_DRUID_SPIRITS, true);
++_stage;
}
}
void ExecuteEvent(uint32 eventId) override
{
switch (eventId)
{
case EVENT_LIGHTNING_WAVE:
DoCastVictim(SPELL_LIGHTNING_WAVE);
events.ScheduleEvent(EVENT_LIGHTNING_WAVE, urand(10000, 20000));
break;
default:
emerald_dragonAI::ExecuteEvent(eventId);
break;
}
}
private:
uint8 _stage;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_ysondreAI(creature);
}
};
/*
* ---
* --- Dragonspecific scripts and handling: LETHON
* ---
*
* @todo
* - Spell: Shadow bolt whirl casts needs custom handling (spellscript)
*/
enum LethonTexts
{
SAY_LETHON_AGGRO = 0,
SAY_LETHON_DRAW_SPIRIT = 1,
};
enum LethonSpells
{
SPELL_DRAW_SPIRIT = 24811,
SPELL_SHADOW_BOLT_WHIRL = 24834,
SPELL_DARK_OFFERING = 24804,
};
enum LethonCreatures
{
NPC_SPIRIT_SHADE = 15261,
};
class boss_lethon : public CreatureScript
{
public:
boss_lethon() : CreatureScript("boss_lethon") { }
struct boss_lethonAI : public emerald_dragonAI
{
boss_lethonAI(Creature* creature) : emerald_dragonAI(creature)
{
Initialize();
}
void Initialize()
{
_stage = 1;
}
void Reset() override
{
Initialize();
emerald_dragonAI::Reset();
events.ScheduleEvent(EVENT_SHADOW_BOLT_WHIRL, 10000);
}
void EnterCombat(Unit* who) override
{
Talk(SAY_LETHON_AGGRO);
WorldBossAI::EnterCombat(who);
}
void DamageTaken(Unit* /*attacker*/, uint32& /*damage*/) override
{
if (!HealthAbovePct(100 - 25 * _stage))
{
Talk(SAY_LETHON_DRAW_SPIRIT);
DoCast(me, SPELL_DRAW_SPIRIT);
++_stage;
}
}
void SpellHitTarget(Unit* target, SpellInfo const* spell) override
{
if (spell->Id == SPELL_DRAW_SPIRIT && target->GetTypeId() == TYPEID_PLAYER)
{
Position targetPos = target->GetPosition();
me->SummonCreature(NPC_SPIRIT_SHADE, targetPos, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 50000);
}
}
void ExecuteEvent(uint32 eventId) override
{
switch (eventId)
{
case EVENT_SHADOW_BOLT_WHIRL:
me->CastSpell((Unit*)NULL, SPELL_SHADOW_BOLT_WHIRL, false);
events.ScheduleEvent(EVENT_SHADOW_BOLT_WHIRL, urand(15000, 30000));
break;
default:
emerald_dragonAI::ExecuteEvent(eventId);
break;
}
}
private:
uint8 _stage;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_lethonAI(creature);
}
};
class npc_spirit_shade : public CreatureScript
{
public:
npc_spirit_shade() : CreatureScript("npc_spirit_shade") { }
struct npc_spirit_shadeAI : public PassiveAI
{
npc_spirit_shadeAI(Creature* creature) : PassiveAI(creature), _summonerGuid()
{
}
void IsSummonedBy(Unit* summoner) override
{
_summonerGuid = summoner->GetGUID();
me->GetMotionMaster()->MoveFollow(summoner, 0.0f, 0.0f);
}
void MovementInform(uint32 moveType, uint32 data) override
{
if (moveType == FOLLOW_MOTION_TYPE && data == _summonerGuid.GetCounter())
{
me->CastSpell((Unit*)NULL, SPELL_DARK_OFFERING, false);
me->DespawnOrUnsummon(1000);
}
}
private:
ObjectGuid _summonerGuid;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_spirit_shadeAI(creature);
}
};
/*
* ---
* --- Dragonspecific scripts and handling: EMERISS
* ---
*/
enum EmerissTexts
{
SAY_EMERISS_AGGRO = 0,
SAY_EMERISS_CAST_CORRUPTION = 1,
};
enum EmerissSpells
{
SPELL_PUTRID_MUSHROOM = 24904,
SPELL_CORRUPTION_OF_EARTH = 24910,
SPELL_VOLATILE_INFECTION = 24928,
};
class boss_emeriss : public CreatureScript
{
public:
boss_emeriss() : CreatureScript("boss_emeriss") { }
struct boss_emerissAI : public emerald_dragonAI
{
boss_emerissAI(Creature* creature) : emerald_dragonAI(creature)
{
Initialize();
}
void Initialize()
{
_stage = 1;
}
void Reset() override
{
Initialize();
emerald_dragonAI::Reset();
events.ScheduleEvent(EVENT_VOLATILE_INFECTION, 12000);
}
void KilledUnit(Unit* who) override
{
if (who->GetTypeId() == TYPEID_PLAYER)
DoCast(who, SPELL_PUTRID_MUSHROOM, true);
emerald_dragonAI::KilledUnit(who);
}
void EnterCombat(Unit* who) override
{
Talk(SAY_EMERISS_AGGRO);
WorldBossAI::EnterCombat(who);
}
void DamageTaken(Unit* /*attacker*/, uint32& /*damage*/) override
{
if (!HealthAbovePct(100 - 25 * _stage))
{
Talk(SAY_EMERISS_CAST_CORRUPTION);
DoCast(me, SPELL_CORRUPTION_OF_EARTH, true);
++_stage;
}
}
void ExecuteEvent(uint32 eventId) override
{
switch (eventId)
{
case EVENT_VOLATILE_INFECTION:
DoCastVictim(SPELL_VOLATILE_INFECTION);
events.ScheduleEvent(EVENT_VOLATILE_INFECTION, 120000);
break;
default:
emerald_dragonAI::ExecuteEvent(eventId);
break;
}
}
private:
uint8 _stage;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_emerissAI(creature);
}
};
/*
* ---
* --- Dragonspecific scripts and handling: TAERAR
* ---
*/
enum TaerarTexts
{
SAY_TAERAR_AGGRO = 0,
SAY_TAERAR_SUMMON_SHADES = 1,
};
enum TaerarSpells
{
SPELL_BELLOWING_ROAR = 22686,
SPELL_SHADE = 24313,
SPELL_SUMMON_SHADE_1 = 24841,
SPELL_SUMMON_SHADE_2 = 24842,
SPELL_SUMMON_SHADE_3 = 24843,
SPELL_ARCANE_BLAST = 24857,
};
uint32 const TaerarShadeSpells[] =
{
SPELL_SUMMON_SHADE_1, SPELL_SUMMON_SHADE_2, SPELL_SUMMON_SHADE_3
};
class boss_taerar : public CreatureScript
{
public:
boss_taerar() : CreatureScript("boss_taerar") { }
struct boss_taerarAI : public emerald_dragonAI
{
boss_taerarAI(Creature* creature) : emerald_dragonAI(creature)
{
Initialize();
}
void Initialize()
{
_stage = 1;
_shades = 0;
_banished = false;
_banishedTimer = 0;
}
void Reset() override
{
me->RemoveAurasDueToSpell(SPELL_SHADE);
Initialize();
emerald_dragonAI::Reset();
events.ScheduleEvent(EVENT_ARCANE_BLAST, 12000);
events.ScheduleEvent(EVENT_BELLOWING_ROAR, 30000);
}
void EnterCombat(Unit* who) override
{
Talk(SAY_TAERAR_AGGRO);
emerald_dragonAI::EnterCombat(who);
}
void SummonedCreatureDies(Creature* /*summon*/, Unit* /*killer*/) override
{
--_shades;
}
void DamageTaken(Unit* /*attacker*/, uint32& /*damage*/) override
{
// At 75, 50 or 25 percent health, we need to activate the shades and go "banished"
// Note: _stage holds the amount of times they have been summoned
if (!_banished && !HealthAbovePct(100 - 25 * _stage))
{
_banished = true;
_banishedTimer = 60000;
me->InterruptNonMeleeSpells(false);
DoStopAttack();
Talk(SAY_TAERAR_SUMMON_SHADES);
uint32 count = sizeof(TaerarShadeSpells) / sizeof(uint32);
for (uint32 i = 0; i < count; ++i)
DoCastVictim(TaerarShadeSpells[i], true);
_shades += count;
DoCast(SPELL_SHADE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE);
me->SetReactState(REACT_PASSIVE);
++_stage;
}
}
void ExecuteEvent(uint32 eventId) override
{
switch (eventId)
{
case EVENT_ARCANE_BLAST:
DoCast(SPELL_ARCANE_BLAST);
events.ScheduleEvent(EVENT_ARCANE_BLAST, urand(7000, 12000));
break;
case EVENT_BELLOWING_ROAR:
DoCast(SPELL_BELLOWING_ROAR);
events.ScheduleEvent(EVENT_BELLOWING_ROAR, urand(20000, 30000));
break;
default:
emerald_dragonAI::ExecuteEvent(eventId);
break;
}
}
void UpdateAI(uint32 diff) override
{
if (!me->IsInCombat())
return;
if (_banished)
{
// If all three shades are dead, OR it has taken too long, end the current event and get Taerar back into business
if (_banishedTimer <= diff || !_shades)
{
_banished = false;
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE);
me->RemoveAurasDueToSpell(SPELL_SHADE);
me->SetReactState(REACT_AGGRESSIVE);
}
// _banishtimer has not expired, and we still have active shades:
else
_banishedTimer -= diff;
// Update the events before we return (handled under emerald_dragonAI::UpdateAI(diff); if we're not inside this check)
events.Update(diff);
return;
}
emerald_dragonAI::UpdateAI(diff);
}
private:
bool _banished; // used for shades activation testing
uint32 _banishedTimer; // counter for banishment timeout
uint8 _shades; // keep track of how many shades are dead
uint8 _stage; // check which "shade phase" we're at (75-50-25 percentage counters)
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_taerarAI(creature);
}
};
/*
* --- Spell: Dream Fog
*/
class DreamFogTargetSelector
{
public:
DreamFogTargetSelector() { }
bool operator()(WorldObject* object)
{
if (Unit* unit = object->ToUnit())
return unit->HasAura(SPELL_SLEEP);
return true;
}
};
class spell_dream_fog_sleep : public SpellScriptLoader
{
public:
spell_dream_fog_sleep() : SpellScriptLoader("spell_dream_fog_sleep") { }
class spell_dream_fog_sleep_SpellScript : public SpellScript
{
PrepareSpellScript(spell_dream_fog_sleep_SpellScript);
void FilterTargets(std::list<WorldObject*>& targets)
{
targets.remove_if(DreamFogTargetSelector());
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_dream_fog_sleep_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_DEST_AREA_ENEMY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_dream_fog_sleep_SpellScript();
}
};
/*
* --- Spell: Mark of Nature
*/
class MarkOfNatureTargetSelector
{
public:
MarkOfNatureTargetSelector() { }
bool operator()(WorldObject* object)
{
// return those not tagged or already under the influence of Aura of Nature
if (Unit* unit = object->ToUnit())
return !(unit->HasAura(SPELL_MARK_OF_NATURE) && !unit->HasAura(SPELL_AURA_OF_NATURE));
return true;
}
};
class spell_mark_of_nature : public SpellScriptLoader
{
public:
spell_mark_of_nature() : SpellScriptLoader("spell_mark_of_nature") { }
class spell_mark_of_nature_SpellScript : public SpellScript
{
PrepareSpellScript(spell_mark_of_nature_SpellScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_NATURE))
return false;
if (!sSpellMgr->GetSpellInfo(SPELL_AURA_OF_NATURE))
return false;
return true;
}
void FilterTargets(std::list<WorldObject*>& targets)
{
targets.remove_if(MarkOfNatureTargetSelector());
}
void HandleEffect(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
GetHitUnit()->CastSpell(GetHitUnit(), SPELL_AURA_OF_NATURE, true);
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_mark_of_nature_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
OnEffectHitTarget += SpellEffectFn(spell_mark_of_nature_SpellScript::HandleEffect, EFFECT_0, SPELL_EFFECT_APPLY_AURA);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_mark_of_nature_SpellScript();
}
};
void AddSC_emerald_dragons()
{
// helper NPC scripts
new npc_dream_fog();
new npc_spirit_shade();
// dragons
new boss_ysondre();
new boss_taerar();
new boss_emeriss();
new boss_lethon();
// dragon spellscripts
new spell_dream_fog_sleep();
new spell_mark_of_nature();
}
| Ragebones/StormCore | src/server/scripts/World/boss_emerald_dragons.cpp | C++ | gpl-2.0 | 24,419 |
<?php
/*
------------------
Language: Français (French)
------------------
*/
$LANG['COORD_MAP'] = 'Carte de Coordonnées de Liste';
$LANG['NO_COORDS'] = 'Votre requête ne contient apparemment aucun enregistrement avec des coordonnées pouvant être cartographiées';
$LANG['MAYBE_RARE'] = 'Il se peut que les échantillons aient un statut rare/menacé qui nécessite que les coordonnées de la localité soient cachées';
?> | egbot/Symbiota | content/lang/checklists/checklistmap.fr.php | PHP | gpl-2.0 | 429 |
#region License
/*
* This file is part of uEssentials project.
* https://uessentials.github.io/
*
* Copyright (C) 2015-2018 leonardosnt
*
* 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.
*/
#endregion
using System.Linq;
using Essentials.Api.Command;
using Essentials.Api.Command.Source;
using Essentials.Api.Unturned;
using Essentials.Common;
using Essentials.I18n;
using SDG.Unturned;
namespace Essentials.Commands {
[CommandInfo(
Name = "refuelvehicle",
Aliases = new[] { "refuel" },
Description = "Refuel current/all vehicles",
Usage = "<all>",
MaxArgs = 1
)]
public class CommandRefuelVehicle : EssCommand {
public override CommandResult OnExecute(ICommandSource src, ICommandArgs args) {
if (args.IsEmpty) {
if (src.IsConsole) {
return CommandResult.ShowUsage();
}
var currentVeh = src.ToPlayer().CurrentVehicle;
if (currentVeh != null) {
RefuelVehicle(currentVeh);
EssLang.Send(src, "VEHICLE_REFUELED");
} else {
return CommandResult.LangError("NOT_IN_VEHICLE");
}
} else if (args[0].Equals("all")) {
if (!src.HasPermission($"{Permission}.all")) {
return CommandResult.NoPermission($"{Permission}.all");
}
lock (UWorld.Vehicles) {
UWorld.Vehicles
.Where(veh => !veh.isExploded && !veh.isUnderwater)
.ForEach(RefuelVehicle);
EssLang.Send(src, "VEHICLE_REFUELED_ALL");
}
}
return CommandResult.Success();
}
private void RefuelVehicle(InteractableVehicle veh) {
VehicleManager.instance.channel.send("tellVehicleFuel", ESteamCall.ALL,
ESteamPacket.UPDATE_UNRELIABLE_BUFFER, veh.instanceID, veh.asset.fuel);
}
}
} | uEssentials/uEssentials | src/Commands/CommandRefuelVehicle.cs | C# | gpl-2.0 | 2,730 |
"""
Stateful module base class and interface description.
All stateful Python modules
- Get Skype4Py Skype instance on init - have full control over Skype and
thus are not limited to !command handlers
- Reside in the some modules/ folder as UNIX script modules
- Have .py extension and be valid Python 2.7 modules
- Have #!/sevabot magic string at the head of the file
- Exports Python attribute *sevabot_handler* which is an instance of the class
as described below
Please note that in the future we might have different chat backends (GTalk)
and thus have a same-same-but-different stateful handlers.
"""
class StatefulSkypeHandler:
"""
Base class for stateful handlers.
All exceptions slip through are caught and logged.
"""
def init(self, sevabot):
"""
Set-up our state. This is called every time module is (re)loaded.
You can get Skype4Py instance via ``sevabot.getSkype()``.
:param sevabot: Handle to Sevabot instance
"""
def handle_message(self, msg, status):
"""Override this method to have a customized handler for each Skype message.
:param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409
:param status: -
:return: True if the message was handled and should not be further processed
"""
def shutdown():
""" Called when the module is reloaded.
In ``shutdown()`` you must
* Stop all created threads
* Unregister all event handlers
..note ::
We do *not* guaranteed to be call when Sevabot process shutdowns as
the process may terminate with SIGKILL.
"""
def register_callback(self, skype, event, callback):
"""
Register any callable as a callback for a skype event.
Thin wrapper for RegisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py
:param skype: Skype4Py instance
:param event: Same as Event
:param callback: Same as Target
:return: Same as RegisterEventHandler
"""
return skype.RegisterEventHandler(event, callback)
def unregister_callback(self, skype, event, callback):
"""
Unregister a callback previously registered with register_callback.
Thin wrapper for UnregisterEventHandler https://github.com/awahlig/skype4py/blob/master/Skype4Py/utils.py
:param skype: Skype4Py instance
:param event: Same as Event
:param callback: Same as Target
:return: Same as UnregisterEventHandler
"""
return skype.UnregisterEventHandler(event, callback)
| mikemike/SkypeBot | unused-modules/stateful.py | Python | gpl-2.0 | 2,755 |
<?php
/*
Plugin Name: Allowed posttags
Plugin URI:
Description: 特権管理者じゃなくてもdlとかのclassを消されたり、WordPress Importerで投稿をインポートした時記事内にiframeとかobjectとかあっても消されたりしないようにする。(<a href="http://ja.forums.wordpress.org/topic/6393?replies=4" target="_blank">元ネタはこちら</a>)
Author: Kei Nomura
Version: 1.0
*/
function set_allowedposttags($content){
global $allowedposttags;
$allowedposttags['dl'] = array(
'class' => array(),
'id' => array()
);
$allowedposttags['dt'] = array(
'class' => array(),
'id' => array()
);
$allowedposttags['dd'] = array(
'class' => array(),
'id' => array()
);
$allowedposttags['iframe'] = array(
'class' => array(),
'src' => array(),
'width' => array(),
'height' => array() ,
'frameborder' => array(),
'scrolling' => array(),
'marginheight' => array(),
'marginwidth' => array()
);
$allowedposttags['object'] = array(
'class' => array(),
'data' => array(),
'width' => array(),
'height' => array(),
'type' => array()
);
$allowedposttags['param'] = array(
'class' => array(),
'name' => array(),
'value' => array()
);
return $content;
}
add_filter('content_save_pre', 'set_allowedposttags', 8);
| mypacecreator/my_allowedposttags | allowedposttags.php | PHP | gpl-2.0 | 1,349 |
<?php
/**
* Template Name: WDM Search Page
*/
include(WP_PLUGIN_DIR.'/wdm-search/wdm-query.php');
global $wp_query, $product_page_width, $product_sidebar, $product_sidebar_width;
$product_sidebar = false;
if (prima_get_option('themelayout') == 'boxed') {
$product_page_width = 665;
}
else {
$product_page_width = 720;
}
$img_width = 185;
$img_height = 185;
?>
<?php get_header(); ?>
<div id="header-wrapper">
<?php get_template_part( 'flexi-header' ); ?>
<div id="leader" class="container">
<div class="margin clearfix">
<?php if (class_exists('WP_eCommerce') && prima_get_option('searchformpage')): ?>
<?php prima_product_search(); ?>
<?php endif; ?>
<h1><?php the_title(); ?></h1>
</div>
</div>
</div>
<div id="content-wrapper">
<div id="main-content" class="container">
<?php wdm_search_form(); ?>
<div class="margin">
<div id="main-col">
<?php if ($pageposts->have_posts()): ?>
<?php while ($pageposts->have_posts()): ?>
<?php $pageposts->the_post(); ?>
<div class="blog-post blog-overview">
<div class="post-content clearfix">
<?php $thumbnail = prima_get_image( false, $img_width, $img_height, true ); ?>
<?php if ( $thumbnail ): ?>
<img class="attachment-post-thumbnail alignleft" src="<?php echo $thumbnail; ?>" title="<?php the_title_attribute(); ?>" alt="<?php the_title_attribute(); ?>" width="<?php echo $img_width; ?>" height="<?php echo $img_height; ?>" />
<?php endif; ?>
<div class="overlay">
<div class="price"><?php echo prima_the_product_price( prima_get_option('productsvariationtext'), $pricedecimal, get_the_ID(), $variationprice ); ?></div>
<h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h3>
<div class="excerpt"><?php the_excerpt();?></div>
<a href="<?php the_permalink() ?>" class="read-more"><?php _e('Show') ?></a>
</div>
</div>
</div>
<?php endwhile; ?>
<?php pagination(); ?>
<?php else : ?>
<div id="divNotFound">
<p ><strong><h1><?php _e( 'Not Found', PRIMA_DOMAIN ); ?><br /><br /></h1></strong></p>
<p><?php _e( 'Apologies, but the page you requested could not be found. <br />Perhaps searching will help.', PRIMA_DOMAIN ); ?></p>
</div>
<?php endif; ?>
</div>
<div id="home-sidebar">
<?php if ( is_active_sidebar( 'home-right' ) ) : ?>
<?php dynamic_sidebar( 'home-right' ); ?>
<?php endif; ?>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>
| GiorgioNatili/windmaniacs | wp-content/themes/yourflexishop/b4ksearchpage.php | PHP | gpl-2.0 | 2,699 |
/*
Copyright (C) 2005 Wolfgang Becker <uafr@gmx.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <config.h>
#include "GameView.hpp"
#include "gui/TextureManager.hpp"
#include "gui/Painter.hpp"
#include "gui/Rect2D.hpp"
#include "gui/Color.hpp"
#include "gui/ComponentFactory.hpp"
#include "gui/XmlReader.hpp"
#include "gui/Event.hpp"
#include "PhysfsStream/PhysfsSDL.hpp"
#include "gui/Paragraph.hpp"
#include "gui/Desktop.hpp"
#include "lincity/lin-city.h"
#include "lincity/lctypes.h"
#include "lincity/engglobs.h"
#include "MapEdit.hpp"
#include "MiniMap.hpp"
#include "Dialog.hpp"
#include "Config.hpp"
#include "ScreenInterface.hpp"
#include "Util.hpp"
#include <SDL_keysym.h>
#include <math.h>
#include <sstream>
#include <physfs.h>
#include "gui_interface/shared_globals.h"
#include "tinygettext/gettext.hpp"
#include "gui/callback/Callback.hpp"
#include "gui/Button.hpp"
#include "CheckButton.hpp"
extern int is_allowed_here(int x, int y, short cst_type, short msg);
const float GameView::defaultTileWidth = 128;
const float GameView::defaultTileHeight = 64;
const float GameView::defaultZoom = 0.5;
GameView* gameViewPtr = 0;
GameView* getGameView()
{
return gameViewPtr;
}
GameView::GameView()
{
assert(gameViewPtr == 0);
gameViewPtr = this;
mTextures = SDL_CreateMutex();
mThreadRunning = SDL_CreateMutex();
loaderThread = 0;
keyScrollState = 0;
mouseScrollState = 0;
}
GameView::~GameView()
{
stopThread = true;
SDL_mutexP( mThreadRunning );
//SDL_KillThread( loaderThread );
SDL_WaitThread( loaderThread, NULL );
SDL_DestroyMutex( mThreadRunning );
SDL_DestroyMutex( mTextures );
for(int i = 0; i < NUM_OF_TYPES; ++i) {
delete cityTextures[i];
// in case the image was loaded but no texture created yet we have a
// dangling SDL_Surface here
SDL_FreeSurface(cityImages[i]);
}
if(gameViewPtr == this)
gameViewPtr = 0;
}
//Static function to use with SDL_CreateThread
int GameView::gameViewThread( void* data )
{
GameView* gv = (GameView*) data;
gv->loadTextures();
gv->requestRedraw();
return 0;
}
void GameView::parse(XmlReader& reader)
{
//Read from config
XmlReader::AttributeIterator iter(reader);
while(iter.next()) {
const char* attribute = (const char*) iter.getName();
const char* value = (const char*) iter.getValue();
//check if Attribute handled by parent
if(parseAttribute(attribute, value)) {
continue;
} else {
std::cerr << "GameView::parse# Skipping unknown attribute '" << attribute << "'.\n";
}
}
// no more elements to parse
//Load Textures
blankTexture = readTexture( "blank.png" );
memset( &cityTextures, 0, sizeof( cityTextures ) );
memset( &cityImages, 0, sizeof( cityImages ) );
stopThread = false;
SDL_mutexP( mThreadRunning );
loaderThread = SDL_CreateThread( gameViewThread, this );
SDL_mutexV( mThreadRunning );
//GameView is resizable
setFlags(FLAG_RESIZABLE);
//start at location from savegame
zoom = defaultZoom;
tileWidth = defaultTileWidth * zoom;
tileHeight = defaultTileHeight * zoom;
virtualScreenWidth = tileWidth * WORLD_SIDE_LEN;
virtualScreenHeight = tileHeight * WORLD_SIDE_LEN;
readOrigin( false );
mouseInGameView = false;
dragging = false;
leftButtonDown = false;
roadDragging = false;
startRoad = MapPoint(0, 0);
rightButtonDown = false;
tileUnderMouse = MapPoint(0, 0);
dragStart = Vector2(0, 0);
hideHigh = false;
cursorSize = 0;
mapOverlay = overlayNone;
mapMode = MiniMap::NORMAL;
buttonsConnected = false;
lastStatusMessage = "";
}
/*
* Connect to GUI-Buttons.
*/
void GameView::connectButtons(){
if( buttonsConnected ){
return;
}
buttonsConnected = true;
Component* root = this;
while( root->getParent() ){
root = root->getParent();
}
Button* button = getButton( *root, "hideHighBuildings" );
button->clicked.connect( makeCallback(*this, &GameView::buttonClicked ) );
button = getButton( *root, "mapOverlay" );
button->clicked.connect( makeCallback(*this, &GameView::buttonClicked ) );
}
/*
* Handle Clicks on Button.
*/
void GameView::buttonClicked( Button* button ){
std::string name = button->getName();
if( name == "hideHighBuildings" ){
hideHigh = !hideHigh;
requestRedraw();
return;
}
if( name == "mapOverlay" ){
mapOverlay++;
if( mapOverlay > overlayMAX ) {
mapOverlay = overlayNone;
}
requestRedraw();
return;
}
std::cerr << "GameView::buttonClicked# Unhandled Button '" << name <<"',\n";
}
/*
* size in Tiles of marking under Cursor
* atm 0 is an outlined Version of size 1.
*/
void GameView::setCursorSize( int size )
{
if( size != cursorSize )
{
cursorSize = size;
setDirty();
}
}
/*
* evaluate main_screen_originx and main_screen_originy
*/
void GameView::readOrigin( bool redraw /* = true */ ){
MapPoint newCenter( main_screen_originx, main_screen_originy );
show( newCenter, redraw );
}
/*
* set main_screen_originx and main_screen_originy
*/
void GameView::writeOrigin(){
main_screen_originx = getCenter().x;
main_screen_originy = getCenter().y;
}
/*
* inform GameView about change in Mini Map Mode
*/
void GameView::setMapMode( MiniMap::DisplayMode mMode ) {
switch( mMode ){
case MiniMap::NORMAL:
printStatusMessage( _("Minimap: outline map") );
break;
case MiniMap::UB40:
printStatusMessage( _("Minimap: unemployment") );
break;
case MiniMap::POLLUTION:
printStatusMessage( _("Minimap: pollution") );
break;
case MiniMap::STARVE:
printStatusMessage( _("Minimap: nourishments") );
break;
case MiniMap::POWER:
printStatusMessage( _("Minimap: power supply") );
break;
case MiniMap::FIRE:
printStatusMessage( _("Minimap: firedepartment cover") );
break;
case MiniMap::CRICKET:
printStatusMessage( _("Minimap: sport cover") );
break;
case MiniMap::HEALTH:
printStatusMessage( _("Minimap: medical care") );
break;
case MiniMap::COAL:
printStatusMessage( _("Minimap: coal depots") );
break;
case MiniMap::TRAFFIC:
printStatusMessage( _("Minimap: traffic density") );
break;
default:
std::cerr << "Unknown minimap mode " << mMode<<"\n";
}
if( mapMode == mMode ){
return;
}
mapMode = mMode;
if( mapOverlay != overlayNone ){
requestRedraw();
}
}
/*
* Get Tile in Center of Screen.
*/
MapPoint GameView::getCenter(){
Vector2 center( getWidth() / 2, getHeight() / 2 );
return getTile( center );
}
/*
* Adjust the Zoomlevel.
*/
void GameView::setZoom(float newzoom){
MapPoint centerTile = getCenter();
if ( newzoom < .0625 ) return;
if ( newzoom > 4 ) return;
zoom = newzoom;
// fix rounding errors...
if(fabs(zoom - 1.0) < .01)
zoom = 1;
tileWidth = defaultTileWidth * zoom;
tileHeight = defaultTileHeight * zoom;
//a virtual screen containing the whole city
virtualScreenWidth = tileWidth * WORLD_SIDE_LEN;
virtualScreenHeight = tileHeight * WORLD_SIDE_LEN;
//std::cout << "Zoom " << zoom << "\n";
//Show the Center
show( centerTile );
}
/* set Zoomlevel to 100% */
void GameView::resetZoom(){
setZoom( defaultZoom );
}
/* increase Zoomlevel */
void GameView::zoomIn(){
setZoom( zoom * sqrt( 2.f ) );
}
/** decrease Zoomlevel */
void GameView::zoomOut(){
setZoom( zoom / sqrt( 2.f ) );
}
/**
* Show City Tile(x/y) by centering the screen
* redraw = false is used on initialisation.
*/
void GameView::show( MapPoint map , bool redraw /* = true */ )
{
Vector2 center;
center.x = virtualScreenWidth / 2 + ( map.x - map.y ) * ( tileWidth / 2 );
center.y = ( map.x + map.y ) * ( tileHeight / 2 ) + ( tileHeight / 2 );
if( redraw ){
viewport.x = center.x - ( getWidth() / 2 );
viewport.y = center.y - ( getHeight() / 2 );
requestRedraw();
} else { //on startup getWidth is 0.
viewport.x = center.x - ( getConfig()->videoX / 2 );
viewport.y = center.y - ( getConfig()->videoY / 2 );
}
}
/*
* Loads Texture from filename, Returns Pointer to Texture
* or Null if no file found.
*/
Texture* GameView::readTexture(const std::string& filename)
{
std::string nfilename = std::string("images/tiles/") + filename;
Texture* currentTexture;
try {
currentTexture = texture_manager->load(nfilename);
} catch(std::exception& err) {
std::cerr << nfilename << "GameView::readTexture# missing: " << err.what() << "\n";
return 0;
}
return currentTexture;
}
/*
* Loads Image from filename, Returns Pointer to Image
* or Null if no file found.
*/
SDL_Surface* GameView::readImage(const std::string& filename)
{
std::string nfilename = std::string("images/tiles/") + filename;
SDL_Surface* currentImage;
if( !PHYSFS_exists( nfilename.c_str() ) ){
std::cerr << "GameView::readImage# No image file "<< nfilename << " found.\n";
return 0;
}
currentImage = IMG_Load_RW(getPhysfsSDLRWops( nfilename ), 1);
if( !currentImage ) {
std::cerr << "GameView::readImage# Could not load image "<< nfilename << "\n";
}
return currentImage;
}
/**
* preload a City Texture and fill in X and Y Data.
*
* images/tiles/images.xml contains the x-Coordinate of the
* middle of the Building in Case the Image is asymetric,
* eg. a high tower with a long shadow to the right
*
* Some of the Image to Texture Conversion seems not to be threadsave
* in OpenGL, so load just Images and convert them to Textures on
* demand in the main Tread.
*/
void GameView::preReadCityTexture( int textureType, const std::string& filename )
{
//skip loading if we stop anyway
if(stopThread) {
return;
}
XmlReader reader( "images/tiles/images.xml" );
int xmlX = -1;
int xmlY = -1;
bool hit = false;
SDL_mutexP( mTextures );
cityImages[ textureType ] = readImage( filename );
if( cityImages[ textureType ] )
{
//now we need to find x for our filename in images/tiles/images.xml
while( reader.read() )
{
if( reader.getNodeType() == XML_READER_TYPE_ELEMENT)
{
const std::string& element = (const char*) reader.getName();
if( element == "image" )
{
XmlReader::AttributeIterator iter(reader);
while(iter.next())
{
const char* name = (const char*) iter.getName();
const char* value = (const char*) iter.getValue();
if( strcmp(name, "file" ) == 0 )
{
if( filename.compare( value ) == 0 )
{
hit = true;
}
}
else if( strcmp(name, "x" ) == 0 )
{
if(sscanf(value, "%i", &xmlX) != 1)
{
std::cerr << "GameView::preReadCityTexture# Error parsing integer value '" << value << "' in x attribute.\n";
xmlX = -1;
}
}
else if(strcmp(name, "y") == 0 )
{
if(sscanf(value, "%i", &xmlY) != 1)
{
std::cerr << "GameView::preReadCityTexture# Error parsing integer value '" << value << "' in y attribute.\n";
xmlY = -1;
}
}
}
if( hit )
{
break;
}
}
}
}
if( hit && ( xmlX >= 0 ) )
{
cityTextureX[ textureType ] = xmlX;
}
else
{
cityTextureX[ textureType ] = int( ( cityImages[ textureType ]->w / 2 ) );
}
cityTextureY[ textureType ] = int( cityImages[ textureType ]->h );
}
SDL_mutexV( mTextures );
}
/**
* Preload all required Textures. (his Function is called by loaderThread)
* Some of the Image to Texture Conversion seems not to be threadsave
* in OpenGL, so load just Images and convert them to Textures on
* demand in the main Tread.
*/
void GameView::loadTextures()
{
//We need Textures for all Types from lincity/lctypes.h
//Code Generation:
/*
grep -e LCT src/lincity/lctypes.h | sed \
-e 's/#define LC/ preReadCityTexture( CS/' \
-e 's/_G /, /' \
-e 's/_G\t/, /' \
-e 's/"/.png" );/2'
*/
preReadCityTexture( CST_GREEN, "green.png" );
preReadCityTexture( CST_DESERT_0, "desert_0.png" );
preReadCityTexture( CST_DESERT_1L, "desert_1l.png" );
preReadCityTexture( CST_DESERT_1R, "desert_1r.png" );
preReadCityTexture( CST_DESERT_1U, "desert_1u.png" );
preReadCityTexture( CST_DESERT_1D, "desert_1d.png" );
preReadCityTexture( CST_DESERT_2LR, "desert_2lr.png" );
preReadCityTexture( CST_DESERT_2LU, "desert_2lu.png" );
preReadCityTexture( CST_DESERT_2LD, "desert_2ld.png" );
preReadCityTexture( CST_DESERT_2RU, "desert_2ru.png" );
preReadCityTexture( CST_DESERT_2RD, "desert_2rd.png" );
preReadCityTexture( CST_DESERT_2UD, "desert_2ud.png" );
preReadCityTexture( CST_DESERT_3LRD, "desert_3lrd.png" );
preReadCityTexture( CST_DESERT_3LRU, "desert_3lru.png" );
preReadCityTexture( CST_DESERT_3LUD, "desert_3lud.png" );
preReadCityTexture( CST_DESERT_3RUD, "desert_3rud.png" );
preReadCityTexture( CST_DESERT, "desert.png" );
preReadCityTexture( CST_TREE, "tree.png" );
preReadCityTexture( CST_TREE2, "tree2.png" );
preReadCityTexture( CST_TREE3, "tree3.png" );
preReadCityTexture( CST_POWERL_H_L, "powerlhl.png" );
preReadCityTexture( CST_POWERL_V_L, "powerlvl.png" );
preReadCityTexture( CST_POWERL_LD_L, "powerlldl.png" );
preReadCityTexture( CST_POWERL_RD_L, "powerlrdl.png" );
preReadCityTexture( CST_POWERL_LU_L, "powerllul.png" );
preReadCityTexture( CST_POWERL_RU_L, "powerlrul.png" );
preReadCityTexture( CST_POWERL_LDU_L, "powerlldul.png" );
preReadCityTexture( CST_POWERL_LDR_L, "powerlldrl.png" );
preReadCityTexture( CST_POWERL_LUR_L, "powerllurl.png" );
preReadCityTexture( CST_POWERL_UDR_L, "powerludrl.png" );
preReadCityTexture( CST_POWERL_LUDR_L, "powerlludrl.png" );
preReadCityTexture( CST_POWERL_H_D, "powerlhd.png" );
preReadCityTexture( CST_POWERL_V_D, "powerlvd.png" );
preReadCityTexture( CST_POWERL_LD_D, "powerlldd.png" );
preReadCityTexture( CST_POWERL_RD_D, "powerlrdd.png" );
preReadCityTexture( CST_POWERL_LU_D, "powerllud.png" );
preReadCityTexture( CST_POWERL_RU_D, "powerlrud.png" );
preReadCityTexture( CST_POWERL_LDU_D, "powerlldud.png" );
preReadCityTexture( CST_POWERL_LDR_D, "powerlldrd.png" );
preReadCityTexture( CST_POWERL_LUR_D, "powerllurd.png" );
preReadCityTexture( CST_POWERL_UDR_D, "powerludrd.png" );
preReadCityTexture( CST_POWERL_LUDR_D, "powerlludrd.png" );
preReadCityTexture( CST_SHANTY, "shanty.png" );
preReadCityTexture( CST_POWERS_SOLAR, "powerssolar.png" );
preReadCityTexture( CST_POWERS_COAL_EMPTY, "powerscoal-empty.png" );
preReadCityTexture( CST_POWERS_COAL_LOW, "powerscoal-low.png" );
preReadCityTexture( CST_POWERS_COAL_MED, "powerscoal-med.png" );
preReadCityTexture( CST_POWERS_COAL_FULL, "powerscoal-full.png" );
preReadCityTexture( CST_BURNT, "burnt_land.png" );
preReadCityTexture( CST_SUBSTATION_R, "substation-R.png" );
preReadCityTexture( CST_SUBSTATION_G, "substation-G.png" );
preReadCityTexture( CST_SUBSTATION_RG, "substation-RG.png" );
preReadCityTexture( CST_UNIVERSITY, "university.png" );
preReadCityTexture( CST_RESIDENCE_LL, "reslowlow.png" );
preReadCityTexture( CST_RESIDENCE_ML, "resmedlow.png" );
preReadCityTexture( CST_RESIDENCE_HL, "reshilow.png" );
preReadCityTexture( CST_RESIDENCE_LH, "reslowhi.png" );
preReadCityTexture( CST_RESIDENCE_MH, "resmedhi.png" );
preReadCityTexture( CST_RESIDENCE_HH, "reshihi.png" );
preReadCityTexture( CST_MARKET_EMPTY, "market-empty.png" );
preReadCityTexture( CST_MARKET_LOW, "market-low.png" );
preReadCityTexture( CST_MARKET_MED, "market-med.png" );
preReadCityTexture( CST_MARKET_FULL, "market-full.png" );
preReadCityTexture( CST_RECYCLE, "recycle-centre.png" );
preReadCityTexture( CST_TRACK_LR, "tracklr.png" );
preReadCityTexture( CST_TRACK_LU, "tracklu.png" );
preReadCityTexture( CST_TRACK_LD, "trackld.png" );
preReadCityTexture( CST_TRACK_UD, "trackud.png" );
preReadCityTexture( CST_TRACK_UR, "trackur.png" );
preReadCityTexture( CST_TRACK_DR, "trackdr.png" );
preReadCityTexture( CST_TRACK_LUR, "tracklur.png" );
preReadCityTexture( CST_TRACK_LDR, "trackldr.png" );
preReadCityTexture( CST_TRACK_LUD, "tracklud.png" );
preReadCityTexture( CST_TRACK_UDR, "trackudr.png" );
preReadCityTexture( CST_TRACK_LUDR, "trackludr.png" );
preReadCityTexture( CST_PARKLAND_PLANE, "parkland-plane.png" );
preReadCityTexture( CST_PARKLAND_LAKE, "parkland-lake.png" );
preReadCityTexture( CST_MONUMENT_0, "monument0.png" );
preReadCityTexture( CST_MONUMENT_1, "monument1.png" );
preReadCityTexture( CST_MONUMENT_2, "monument2.png" );
preReadCityTexture( CST_MONUMENT_3, "monument3.png" );
preReadCityTexture( CST_MONUMENT_4, "monument4.png" );
preReadCityTexture( CST_MONUMENT_5, "monument5.png" );
preReadCityTexture( CST_COALMINE_EMPTY, "coalmine-empty.png" );
preReadCityTexture( CST_COALMINE_LOW, "coalmine-low.png" );
preReadCityTexture( CST_COALMINE_MED, "coalmine-med.png" );
preReadCityTexture( CST_COALMINE_FULL, "coalmine-full.png" );
preReadCityTexture( CST_RAIL_LR, "raillr.png" );
preReadCityTexture( CST_RAIL_LU, "raillu.png" );
preReadCityTexture( CST_RAIL_LD, "railld.png" );
preReadCityTexture( CST_RAIL_UD, "railud.png" );
preReadCityTexture( CST_RAIL_UR, "railur.png" );
preReadCityTexture( CST_RAIL_DR, "raildr.png" );
preReadCityTexture( CST_RAIL_LUR, "raillur.png" );
preReadCityTexture( CST_RAIL_LDR, "railldr.png" );
preReadCityTexture( CST_RAIL_LUD, "raillud.png" );
preReadCityTexture( CST_RAIL_UDR, "railudr.png" );
preReadCityTexture( CST_RAIL_LUDR, "railludr.png" );
preReadCityTexture( CST_FIRE_1, "fire1.png" );
preReadCityTexture( CST_FIRE_2, "fire2.png" );
preReadCityTexture( CST_FIRE_3, "fire3.png" );
preReadCityTexture( CST_FIRE_4, "fire4.png" );
preReadCityTexture( CST_FIRE_5, "fire5.png" );
preReadCityTexture( CST_FIRE_DONE1, "firedone1.png" );
preReadCityTexture( CST_FIRE_DONE2, "firedone2.png" );
preReadCityTexture( CST_FIRE_DONE3, "firedone3.png" );
preReadCityTexture( CST_FIRE_DONE4, "firedone4.png" );
preReadCityTexture( CST_ROAD_LR, "roadlr.png" );
preReadCityTexture( CST_ROAD_LU, "roadlu.png" );
preReadCityTexture( CST_ROAD_LD, "roadld.png" );
preReadCityTexture( CST_ROAD_UD, "roadud.png" );
preReadCityTexture( CST_ROAD_UR, "roadur.png" );
preReadCityTexture( CST_ROAD_DR, "roaddr.png" );
preReadCityTexture( CST_ROAD_LUR, "roadlur.png" );
preReadCityTexture( CST_ROAD_LDR, "roadldr.png" );
preReadCityTexture( CST_ROAD_LUD, "roadlud.png" );
preReadCityTexture( CST_ROAD_UDR, "roadudr.png" );
preReadCityTexture( CST_ROAD_LUDR, "roadludr.png" );
preReadCityTexture( CST_OREMINE_5, "oremine5.png" );
preReadCityTexture( CST_OREMINE_6, "oremine6.png" );
preReadCityTexture( CST_OREMINE_7, "oremine7.png" );
preReadCityTexture( CST_OREMINE_8, "oremine8.png" );
preReadCityTexture( CST_OREMINE_1, "oremine1.png" );
preReadCityTexture( CST_OREMINE_2, "oremine2.png" );
preReadCityTexture( CST_OREMINE_3, "oremine3.png" );
preReadCityTexture( CST_OREMINE_4, "oremine4.png" );
preReadCityTexture( CST_HEALTH, "health.png" );
preReadCityTexture( CST_SCHOOL, "school0.png" );
preReadCityTexture( CST_EX_PORT, "ex_port.png" );
preReadCityTexture( CST_MILL_0, "mill0.png" );
preReadCityTexture( CST_MILL_1, "mill1.png" );
preReadCityTexture( CST_MILL_2, "mill2.png" );
preReadCityTexture( CST_MILL_3, "mill3.png" );
preReadCityTexture( CST_MILL_4, "mill4.png" );
preReadCityTexture( CST_MILL_5, "mill5.png" );
preReadCityTexture( CST_MILL_6, "mill6.png" );
preReadCityTexture( CST_ROCKET_1, "rocket1.png" );
preReadCityTexture( CST_ROCKET_2, "rocket2.png" );
preReadCityTexture( CST_ROCKET_3, "rocket3.png" );
preReadCityTexture( CST_ROCKET_4, "rocket4.png" );
preReadCityTexture( CST_ROCKET_5, "rocket5.png" );
preReadCityTexture( CST_ROCKET_6, "rocket6.png" );
preReadCityTexture( CST_ROCKET_7, "rocket7.png" );
preReadCityTexture( CST_ROCKET_FLOWN, "rocketflown.png" );
preReadCityTexture( CST_WINDMILL_1_G, "windmill1g.png" );
preReadCityTexture( CST_WINDMILL_2_G, "windmill2g.png" );
preReadCityTexture( CST_WINDMILL_3_G, "windmill3g.png" );
preReadCityTexture( CST_WINDMILL_1_RG, "windmill1rg.png" );
preReadCityTexture( CST_WINDMILL_2_RG, "windmill2rg.png" );
preReadCityTexture( CST_WINDMILL_3_RG, "windmill3rg.png" );
preReadCityTexture( CST_WINDMILL_1_R, "windmill1r.png" );
preReadCityTexture( CST_WINDMILL_2_R, "windmill2r.png" );
preReadCityTexture( CST_WINDMILL_3_R, "windmill3r.png" );
preReadCityTexture( CST_WINDMILL_1_W, "windmill1w.png" );
preReadCityTexture( CST_WINDMILL_2_W, "windmill2w.png" );
preReadCityTexture( CST_WINDMILL_3_W, "windmill3w.png" );
preReadCityTexture( CST_BLACKSMITH_0, "blacksmith0.png" );
preReadCityTexture( CST_BLACKSMITH_1, "blacksmith1.png" );
preReadCityTexture( CST_BLACKSMITH_2, "blacksmith2.png" );
preReadCityTexture( CST_BLACKSMITH_3, "blacksmith3.png" );
preReadCityTexture( CST_BLACKSMITH_4, "blacksmith4.png" );
preReadCityTexture( CST_BLACKSMITH_5, "blacksmith5.png" );
preReadCityTexture( CST_BLACKSMITH_6, "blacksmith6.png" );
preReadCityTexture( CST_POTTERY_0, "pottery0.png" );
preReadCityTexture( CST_POTTERY_1, "pottery1.png" );
preReadCityTexture( CST_POTTERY_2, "pottery2.png" );
preReadCityTexture( CST_POTTERY_3, "pottery3.png" );
preReadCityTexture( CST_POTTERY_4, "pottery4.png" );
preReadCityTexture( CST_POTTERY_5, "pottery5.png" );
preReadCityTexture( CST_POTTERY_6, "pottery6.png" );
preReadCityTexture( CST_POTTERY_7, "pottery7.png" );
preReadCityTexture( CST_POTTERY_8, "pottery8.png" );
preReadCityTexture( CST_POTTERY_9, "pottery9.png" );
preReadCityTexture( CST_POTTERY_10, "pottery10.png" );
preReadCityTexture( CST_WATER, "water.png" );
preReadCityTexture( CST_WATER_D, "waterd.png" );
preReadCityTexture( CST_WATER_R, "waterr.png" );
preReadCityTexture( CST_WATER_U, "wateru.png" );
preReadCityTexture( CST_WATER_L, "waterl.png" );
preReadCityTexture( CST_WATER_LR, "waterlr.png" );
preReadCityTexture( CST_WATER_UD, "waterud.png" );
preReadCityTexture( CST_WATER_LD, "waterld.png" );
preReadCityTexture( CST_WATER_RD, "waterrd.png" );
preReadCityTexture( CST_WATER_LU, "waterlu.png" );
preReadCityTexture( CST_WATER_UR, "waterur.png" );
preReadCityTexture( CST_WATER_LUD, "waterlud.png" );
preReadCityTexture( CST_WATER_LRD, "waterlrd.png" );
preReadCityTexture( CST_WATER_LUR, "waterlur.png" );
preReadCityTexture( CST_WATER_URD, "waterurd.png" );
preReadCityTexture( CST_WATER_LURD, "waterlurd.png" );
preReadCityTexture( CST_WATERWELL, "waterwell.png" );
preReadCityTexture( CST_CRICKET_1, "cricket1.png" );
preReadCityTexture( CST_CRICKET_2, "cricket2.png" );
preReadCityTexture( CST_CRICKET_3, "cricket3.png" );
preReadCityTexture( CST_CRICKET_4, "cricket4.png" );
preReadCityTexture( CST_CRICKET_5, "cricket5.png" );
preReadCityTexture( CST_CRICKET_6, "cricket6.png" );
preReadCityTexture( CST_CRICKET_7, "cricket7.png" );
preReadCityTexture( CST_FIRESTATION_1, "firestation1.png" );
preReadCityTexture( CST_FIRESTATION_2, "firestation2.png" );
preReadCityTexture( CST_FIRESTATION_3, "firestation3.png" );
preReadCityTexture( CST_FIRESTATION_4, "firestation4.png" );
preReadCityTexture( CST_FIRESTATION_5, "firestation5.png" );
preReadCityTexture( CST_FIRESTATION_6, "firestation6.png" );
preReadCityTexture( CST_FIRESTATION_7, "firestation7.png" );
preReadCityTexture( CST_FIRESTATION_8, "firestation8.png" );
preReadCityTexture( CST_FIRESTATION_9, "firestation9.png" );
preReadCityTexture( CST_FIRESTATION_10, "firestation10.png" );
preReadCityTexture( CST_TIP_0, "tip0.png" );
preReadCityTexture( CST_TIP_1, "tip1.png" );
preReadCityTexture( CST_TIP_2, "tip2.png" );
preReadCityTexture( CST_TIP_3, "tip3.png" );
preReadCityTexture( CST_TIP_4, "tip4.png" );
preReadCityTexture( CST_TIP_5, "tip5.png" );
preReadCityTexture( CST_TIP_6, "tip6.png" );
preReadCityTexture( CST_TIP_7, "tip7.png" );
preReadCityTexture( CST_TIP_8, "tip8.png" );
preReadCityTexture( CST_COMMUNE_1, "commune1.png" );
preReadCityTexture( CST_COMMUNE_2, "commune2.png" );
preReadCityTexture( CST_COMMUNE_3, "commune3.png" );
preReadCityTexture( CST_COMMUNE_4, "commune4.png" );
preReadCityTexture( CST_COMMUNE_5, "commune5.png" );
preReadCityTexture( CST_COMMUNE_6, "commune6.png" );
preReadCityTexture( CST_COMMUNE_7, "commune7.png" );
preReadCityTexture( CST_COMMUNE_8, "commune8.png" );
preReadCityTexture( CST_COMMUNE_9, "commune9.png" );
preReadCityTexture( CST_COMMUNE_10, "commune10.png" );
preReadCityTexture( CST_COMMUNE_11, "commune11.png" );
//preReadCityTexture( CST_COMMUNE_12, "commune12.png" );
//preReadCityTexture( CST_COMMUNE_13, "commune13.png" );
//preReadCityTexture( CST_COMMUNE_14, "commune14.png" );
preReadCityTexture( CST_INDUSTRY_H_C, "industryhc.png" );
preReadCityTexture( CST_INDUSTRY_H_L1, "industryhl1.png" );
preReadCityTexture( CST_INDUSTRY_H_L2, "industryhl2.png" );
preReadCityTexture( CST_INDUSTRY_H_L3, "industryhl3.png" );
preReadCityTexture( CST_INDUSTRY_H_L4, "industryhl4.png" );
preReadCityTexture( CST_INDUSTRY_H_L5, "industryhl5.png" );
preReadCityTexture( CST_INDUSTRY_H_L6, "industryhl6.png" );
preReadCityTexture( CST_INDUSTRY_H_L7, "industryhl7.png" );
preReadCityTexture( CST_INDUSTRY_H_L8, "industryhl8.png" );
preReadCityTexture( CST_INDUSTRY_H_M1, "industryhm1.png" );
preReadCityTexture( CST_INDUSTRY_H_M2, "industryhm2.png" );
preReadCityTexture( CST_INDUSTRY_H_M3, "industryhm3.png" );
preReadCityTexture( CST_INDUSTRY_H_M4, "industryhm4.png" );
preReadCityTexture( CST_INDUSTRY_H_M5, "industryhm5.png" );
preReadCityTexture( CST_INDUSTRY_H_M6, "industryhm6.png" );
preReadCityTexture( CST_INDUSTRY_H_M7, "industryhm7.png" );
preReadCityTexture( CST_INDUSTRY_H_M8, "industryhm8.png" );
preReadCityTexture( CST_INDUSTRY_H_H1, "industryhh1.png" );
preReadCityTexture( CST_INDUSTRY_H_H2, "industryhh2.png" );
preReadCityTexture( CST_INDUSTRY_H_H3, "industryhh3.png" );
preReadCityTexture( CST_INDUSTRY_H_H4, "industryhh4.png" );
preReadCityTexture( CST_INDUSTRY_H_H5, "industryhh5.png" );
preReadCityTexture( CST_INDUSTRY_H_H6, "industryhh6.png" );
preReadCityTexture( CST_INDUSTRY_H_H7, "industryhh7.png" );
preReadCityTexture( CST_INDUSTRY_H_H8, "industryhh8.png" );
preReadCityTexture( CST_INDUSTRY_L_C, "industrylc.png" );
preReadCityTexture( CST_INDUSTRY_L_Q1, "industrylq1.png" );
preReadCityTexture( CST_INDUSTRY_L_Q2, "industrylq2.png" );
preReadCityTexture( CST_INDUSTRY_L_Q3, "industrylq3.png" );
preReadCityTexture( CST_INDUSTRY_L_Q4, "industrylq4.png" );
preReadCityTexture( CST_INDUSTRY_L_L1, "industryll1.png" );
preReadCityTexture( CST_INDUSTRY_L_L2, "industryll2.png" );
preReadCityTexture( CST_INDUSTRY_L_L3, "industryll3.png" );
preReadCityTexture( CST_INDUSTRY_L_L4, "industryll4.png" );
preReadCityTexture( CST_INDUSTRY_L_M1, "industrylm1.png" );
preReadCityTexture( CST_INDUSTRY_L_M2, "industrylm2.png" );
preReadCityTexture( CST_INDUSTRY_L_M3, "industrylm3.png" );
preReadCityTexture( CST_INDUSTRY_L_M4, "industrylm4.png" );
preReadCityTexture( CST_INDUSTRY_L_H1, "industrylh1.png" );
preReadCityTexture( CST_INDUSTRY_L_H2, "industrylh2.png" );
preReadCityTexture( CST_INDUSTRY_L_H3, "industrylh3.png" );
preReadCityTexture( CST_INDUSTRY_L_H4, "industrylh4.png" );
preReadCityTexture( CST_FARM_O0, "farm0.png" );
//preReadCityTexture( CST_FARM_O1, "farm1.png" );
//preReadCityTexture( CST_FARM_O2, "farm2.png" );
preReadCityTexture( CST_FARM_O3, "farm3.png" );
//preReadCityTexture( CST_FARM_O4, "farm4.png" );
//preReadCityTexture( CST_FARM_O5, "farm5.png" );
//preReadCityTexture( CST_FARM_O6, "farm6.png" );
preReadCityTexture( CST_FARM_O7, "farm7.png" );
//preReadCityTexture( CST_FARM_O8, "farm8.png" );
//preReadCityTexture( CST_FARM_O9, "farm9.png" );
//preReadCityTexture( CST_FARM_O10, "farm10.png" );
preReadCityTexture( CST_FARM_O11, "farm11.png" );
//preReadCityTexture( CST_FARM_O12, "farm12.png" );
//preReadCityTexture( CST_FARM_O13, "farm13.png" );
//preReadCityTexture( CST_FARM_O14, "farm14.png" );
preReadCityTexture( CST_FARM_O15, "farm15.png" );
//preReadCityTexture( CST_FARM_O16, "farm16.png" );
preReadCityTexture( CST_TRACK_BRIDGE_LR, "Trackbridge2.png" );
preReadCityTexture( CST_TRACK_BRIDGE_UD, "Trackbridge1.png" );
preReadCityTexture( CST_TRACK_BRIDGE_LRP, "Trackbridge_pg1.png" );
preReadCityTexture( CST_TRACK_BRIDGE_UDP, "Trackbridge_pg2.png" );
preReadCityTexture( CST_TRACK_BRIDGE_ILR, "Trackbridge_entrance_270.png" );
preReadCityTexture( CST_TRACK_BRIDGE_OLR, "Trackbridge_entrance_90.png" );
preReadCityTexture( CST_TRACK_BRIDGE_IUD, "Trackbridge_entrance_00.png" );
preReadCityTexture( CST_TRACK_BRIDGE_OUD, "Trackbridge_entrance_180.png" );
preReadCityTexture( CST_ROAD_BRIDGE_LR, "Roadbridge1.png" );
preReadCityTexture( CST_ROAD_BRIDGE_UD, "Roadbridge2.png" );
preReadCityTexture( CST_ROAD_BRIDGE_LRP, "Roadbridge1s.png" );
preReadCityTexture( CST_ROAD_BRIDGE_UDP, "Roadbridge2s.png" );
preReadCityTexture( CST_ROAD_BRIDGE_LRPG, "Roadbridge_pg1.png" );
preReadCityTexture( CST_ROAD_BRIDGE_UDPG, "Roadbridge_pg2.png" );
preReadCityTexture( CST_ROAD_BRIDGE_I1LR, "Roadbridge_entrance1_270.png" );
preReadCityTexture( CST_ROAD_BRIDGE_O1LR, "Roadbridge_entrance1_90.png" );
preReadCityTexture( CST_ROAD_BRIDGE_I1UD, "Roadbridge_entrance1_00.png" );
preReadCityTexture( CST_ROAD_BRIDGE_O1UD, "Roadbridge_entrance1_180.png" );
preReadCityTexture( CST_ROAD_BRIDGE_I2LR, "Roadbridge_entrance2_270.png" );
preReadCityTexture( CST_ROAD_BRIDGE_O2LR, "Roadbridge_entrance2_90.png" );
preReadCityTexture( CST_ROAD_BRIDGE_I2UD, "Roadbridge_entrance2_00.png" );
preReadCityTexture( CST_ROAD_BRIDGE_O2UD, "Roadbridge_entrance2_180.png" );
preReadCityTexture( CST_RAIL_BRIDGE_LR, "Railbridge1.png" );
preReadCityTexture( CST_RAIL_BRIDGE_UD, "Railbridge2.png" );
preReadCityTexture( CST_RAIL_BRIDGE_LRPG, "Railbridge_pg1.png" );
preReadCityTexture( CST_RAIL_BRIDGE_UDPG, "Railbridge_pg2.png" );
preReadCityTexture( CST_RAIL_BRIDGE_I1LR, "Railbridge_entrance1_270.png" );
preReadCityTexture( CST_RAIL_BRIDGE_O1LR, "Railbridge_entrance1_90.png" );
preReadCityTexture( CST_RAIL_BRIDGE_I1UD, "Railbridge_entrance1_00.png" );
preReadCityTexture( CST_RAIL_BRIDGE_O1UD, "Railbridge_entrance1_180.png" );
preReadCityTexture( CST_RAIL_BRIDGE_I2LR, "Railbridge_entrance2_270.png" );
preReadCityTexture( CST_RAIL_BRIDGE_O2LR, "Railbridge_entrance2_90.png" );
preReadCityTexture( CST_RAIL_BRIDGE_I2UD, "Railbridge_entrance2_00.png" );
preReadCityTexture( CST_RAIL_BRIDGE_O2UD, "Railbridge_entrance2_180.png" );
// End of generated Code.
}
/*
* Scroll the map.
*/
void GameView::scroll( void )
{
static Uint32 oldTime = SDL_GetTicks();
Uint32 now = SDL_GetTicks();
//TODO: scroll speed should be configurable
float stepx = (now - oldTime) * tileWidth / 100;
float stepy = (now - oldTime) * tileHeight / 100;
oldTime = now;
if( keyScrollState == 0 && mouseScrollState == 0 ) {
return;
}
if( keyScrollState & (SCROLL_LSHIFT | SCROLL_RSHIFT) ) {
stepx *= 4;
stepy *= 4;
}
if( (keyScrollState | mouseScrollState) &
(SCROLL_UP | SCROLL_UP_LEFT | SCROLL_UP_RIGHT) ) {
viewport.y -= stepy;
}
if( (keyScrollState | mouseScrollState) &
(SCROLL_DOWN | SCROLL_DOWN_LEFT | SCROLL_DOWN_RIGHT) ) {
viewport.y += stepy;
}
if( (keyScrollState | mouseScrollState) &
(SCROLL_LEFT | SCROLL_UP_LEFT | SCROLL_DOWN_LEFT) ) {
viewport.x -= stepx;
}
if( (keyScrollState | mouseScrollState) &
(SCROLL_RIGHT | SCROLL_UP_RIGHT | SCROLL_DOWN_RIGHT) ) {
viewport.x += stepx;
}
requestRedraw();
}
/*
* Process event
*/
void GameView::event(const Event& event)
{
switch(event.type) {
case Event::MOUSEMOTION: {
mouseScrollState = 0;
if( event.mousepos.x < scrollBorder ) {
mouseScrollState |= SCROLL_LEFT;
} else if( event.mousepos.x > getWidth() - scrollBorder ) {
mouseScrollState |= SCROLL_RIGHT;
}
if( event.mousepos.y < scrollBorder ) {
mouseScrollState |= SCROLL_UP;
} else if( event.mousepos.y > getHeight() - scrollBorder ) {
mouseScrollState |= SCROLL_DOWN;
}
if( dragging ) {
if(fabsf(event.mousemove.x) < 1 && fabsf(event.mousemove.y) < 1)
break;
// this was most probably a SDL_WarpMouse
if(event.mousepos == dragStart)
break;
viewport += event.mousemove;
setDirty();
break;
}
if(!event.inside) {
mouseInGameView = false;
break;
}
mouseInGameView = true;
if( !dragging && rightButtonDown ) {
dragging = true;
dragStart = event.mousepos;
SDL_ShowCursor( SDL_DISABLE );
dragStartTime = SDL_GetTicks();
}
MapPoint tile = getTile(event.mousepos);
if( !roadDragging && leftButtonDown && ( cursorSize == 1 ) ) {
roadDragging = true;
startRoad = tile;
}
if( roadDragging && ( cursorSize != 1 ) ){
roadDragging = false;
}
// bulldoze at once while still dragging
if( roadDragging && (selected_module_type == CST_GREEN) ){
if( tile != startRoad ){
editMap( startRoad, SDL_BUTTON_LEFT);
startRoad = tile;
}
}
if(tileUnderMouse != tile) {
tileUnderMouse = tile;
setDirty();
}
break;
}
case Event::MOUSEBUTTONDOWN: {
if(!event.inside) {
break;
}
if( event.mousebutton == SDL_BUTTON_RIGHT ) {
dragging = false;
rightButtonDown = true;
break;
}
if( event.mousebutton == SDL_BUTTON_LEFT ) {
roadDragging = false;
leftButtonDown = true;
break;
}
if( event.mousebutton == SDL_BUTTON_MIDDLE ) {
if( inCity( getTile( event.mousepos ) ) ) {
getMiniMap()->showMpsEnv( getTile( event.mousepos ) );
}
}
break;
}
case Event::MOUSEBUTTONUP:
if(event.mousebutton == SDL_BUTTON_MIDDLE ){
getMiniMap()->hideMpsEnv();
}
if( event.mousebutton == SDL_BUTTON_RIGHT ){
if ( dragging ) {
dragging = false;
rightButtonDown = false;
SDL_ShowCursor( SDL_ENABLE );
SDL_WarpMouse((Uint16) dragStart.x, (Uint16) dragStart.y);
break;
}
dragging = false;
rightButtonDown = false;
}
if( event.mousebutton == SDL_BUTTON_LEFT ){
resetLastMessage();
if ( roadDragging && event.inside ) {
MapPoint endRoad = getTile( event.mousepos );
roadDragging = false;
leftButtonDown = false;
if( cursorSize != 1 ){//roadDragging was aborted with Escape
break;
}
MapPoint currentTile = startRoad;
//build last tile first to play the sound
if( !blockingDialogIsOpen )
editMap(endRoad, SDL_BUTTON_LEFT);
//turn off effects for the rest of the tiles
bool fx = getConfig()->soundEnabled;
getConfig()->soundEnabled = false;
//use same method to find all Tiles as in void GameView::draw()
int stepx = ( startRoad.x > endRoad.x ) ? -1 : 1;
int stepy = ( startRoad.y > endRoad.y ) ? -1 : 1;
while( currentTile.x != endRoad.x ) {
if( !blockingDialogIsOpen )
editMap(currentTile, SDL_BUTTON_LEFT);
currentTile.x += stepx;
}
while( currentTile.y != endRoad.y ) {
if( !blockingDialogIsOpen )
editMap(currentTile, SDL_BUTTON_LEFT);
currentTile.y += stepy;
}
getConfig()->soundEnabled = fx;
break;
}
roadDragging = false;
leftButtonDown = false;
}
if(!event.inside) {
break;
}
if( event.mousebutton == SDL_BUTTON_LEFT ){ //left
if( !blockingDialogIsOpen )
editMap( getTile( event.mousepos ), SDL_BUTTON_LEFT); //edit tile
}
else if( event.mousebutton == SDL_BUTTON_RIGHT ){ //middle
recenter(event.mousepos); //adjust view
}
else if( event.mousebutton == SDL_BUTTON_WHEELUP ){ //up
zoomIn(); //zoom in
}
else if( event.mousebutton == SDL_BUTTON_WHEELDOWN ){ //down
zoomOut(); //zoom out
}
break;
case Event::KEYDOWN:
if( event.keysym.sym == SDLK_KP8 || event.keysym.sym == SDLK_UP ){
keyScrollState |= SCROLL_UP;
break;
}
if( event.keysym.sym == SDLK_KP2 || event.keysym.sym == SDLK_DOWN ){
keyScrollState |= SCROLL_DOWN;
break;
}
if( event.keysym.sym == SDLK_KP4 || event.keysym.sym == SDLK_LEFT ){
keyScrollState |= SCROLL_LEFT;
break;
}
if( event.keysym.sym == SDLK_KP6 || event.keysym.sym == SDLK_RIGHT ){
keyScrollState |= SCROLL_RIGHT;
break;
}
if( event.keysym.sym == SDLK_KP7 ){
keyScrollState |= SCROLL_UP_LEFT;
break;
}
if( event.keysym.sym == SDLK_KP9 ){
keyScrollState |= SCROLL_UP_RIGHT;
break;
}
if( event.keysym.sym == SDLK_KP1 ){
keyScrollState |= SCROLL_DOWN_LEFT;
break;
}
if( event.keysym.sym == SDLK_KP3 ){
keyScrollState |= SCROLL_DOWN_RIGHT;
break;
}
if( event.keysym.sym == SDLK_LSHIFT ){
keyScrollState |= SCROLL_LSHIFT;
break;
}
if( event.keysym.sym == SDLK_RSHIFT ){
keyScrollState |= SCROLL_RSHIFT;
break;
}
break;
case Event::KEYUP:
//TEst
if( event.keysym.sym == SDLK_x ){
writeOrigin();
readOrigin();
break;
}
//Hide High Buildings
if( event.keysym.sym == SDLK_h ){
if( hideHigh ){
hideHigh = false;
} else {
hideHigh = true;
}
requestRedraw();
break;
}
//overlay MiniMap Information
if( event.keysym.sym == SDLK_v ){
mapOverlay++;
if( mapOverlay > overlayMAX ) {
mapOverlay = overlayNone;
}
requestRedraw();
break;
}
//Zoom
if( event.keysym.sym == SDLK_KP_PLUS ){
zoomIn();
break;
}
if( event.keysym.sym == SDLK_KP_MINUS ){
zoomOut();
break;
}
if( event.keysym.sym == SDLK_KP_ENTER ){
resetZoom();
break;
}
//Scroll
if( event.keysym.sym == SDLK_KP8 || event.keysym.sym == SDLK_UP ){
keyScrollState &= ~SCROLL_UP;
break;
}
if( event.keysym.sym == SDLK_KP2 || event.keysym.sym == SDLK_DOWN ){
keyScrollState &= ~SCROLL_DOWN;
break;
}
if( event.keysym.sym == SDLK_KP4 || event.keysym.sym == SDLK_LEFT ){
keyScrollState &= ~SCROLL_LEFT;
break;
}
if( event.keysym.sym == SDLK_KP6 || event.keysym.sym == SDLK_RIGHT ){
keyScrollState &= ~SCROLL_RIGHT;
break;
}
if( event.keysym.sym == SDLK_KP7 ){
keyScrollState &= ~SCROLL_UP_LEFT;
break;
}
if( event.keysym.sym == SDLK_KP9 ){
keyScrollState &= ~SCROLL_UP_RIGHT;
break;
}
if( event.keysym.sym == SDLK_KP1 ){
keyScrollState &= ~SCROLL_DOWN_LEFT;
break;
}
if( event.keysym.sym == SDLK_KP3 ){
keyScrollState &= ~SCROLL_DOWN_RIGHT;
break;
}
if( event.keysym.sym == SDLK_LSHIFT ){
keyScrollState &= ~SCROLL_LSHIFT;
break;
}
if( event.keysym.sym == SDLK_RSHIFT ){
keyScrollState &= ~SCROLL_RSHIFT;
break;
}
if ( event.keysym.sym == SDLK_KP5 ) {
show(MapPoint(WORLD_SIDE_LEN / 2, WORLD_SIDE_LEN / 2));
setDirty();
break;
}
break;
case Event::UPDATE:
if(dragging)
SDL_WarpMouse((Uint16) dragStart.x, (Uint16) dragStart.y);
break;
default:
break;
}
}
/*
* Parent tells us to change size.
*/
void GameView::resize(float newwidth , float newheight )
{
width = newwidth;
height = newheight;
requestRedraw();
}
/*
* We should draw the whole City again.
*/
void GameView::requestRedraw()
{
if( !getMiniMap() ){ //initialization not completed
return;
}
//TODO: do this only when View changed
//Tell Minimap about new Corners
getMiniMap()->setGameViewCorners( getTile(Vector2(0, 0)),
getTile(Vector2(getWidth(), 0)),
getTile(Vector2(getWidth(), getHeight())),
getTile(Vector2(0, getHeight()) ) );
//request redraw
setDirty();
}
/*
* Pos is new Center of the Screen
*/
void GameView::recenter(const Vector2& pos)
{
Vector2 position = pos + viewport;
viewport.x = floor( position.x - ( getWidth() / 2 ) );
viewport.y = floor( position.y - ( getHeight() / 2 ) );
//request redraw
requestRedraw();
}
/*
* Find point on Screen, where lower right corner of tile
* is placed.
*/
Vector2 GameView::getScreenPoint(MapPoint map)
{
Vector2 point;
point.x = virtualScreenWidth / 2 + (map.x - map.y) * ( tileWidth / 2 );
point.y = (map.x + map.y) * ( tileHeight / 2 );
//we want the lower right corner
point.y += tileHeight;
//on Screen
point -= viewport;
return point;
}
/*
* Find Tile at point on viewport
*/
MapPoint GameView::getTile(const Vector2& p)
{
MapPoint tile;
// Map Point to virtual Screen
Vector2 point = p + viewport;
float x = (point.x - virtualScreenWidth / 2 ) / tileWidth
+ point.y / tileHeight;
tile.x = (int) floorf(x);
tile.y = (int) floorf( 2 * point.y / tileHeight - x );
return tile;
}
/*
* Draw a filled Diamond inside given Rectangle
*/
void GameView::fillDiamond( Painter& painter, const Rect2D& rect )
{
Vector2 points[ 4 ];
points[ 0 ].x = rect.p1.x + ( rect.getWidth() / 2 );
points[ 0 ].y = rect.p1.y;
points[ 1 ].x = rect.p1.x;
points[ 1 ].y = rect.p1.y + ( rect.getHeight() / 2 );
points[ 2 ].x = rect.p1.x + ( rect.getWidth() / 2 );
points[ 2 ].y = rect.p2.y;
points[ 3 ].x = rect.p2.x;
points[ 3 ].y = rect.p1.y + ( rect.getHeight() / 2 );
painter.fillPolygon( 4, points );
}
/*
* Draw a outlined Diamond inside given Rectangle
*/
void GameView::drawDiamond( Painter& painter, const Rect2D& rect )
{
if( !buttonsConnected ) connectButtons();//has to be done here,
// because now everything else is initialized.
Vector2 points[ 4 ];
points[ 0 ].x = rect.p1.x + ( rect.getWidth() / 2 );
points[ 0 ].y = rect.p1.y;
points[ 1 ].x = rect.p1.x;
points[ 1 ].y = rect.p1.y + ( rect.getHeight() / 2 );
points[ 2 ].x = rect.p1.x + ( rect.getWidth() / 2 );
points[ 2 ].y = rect.p2.y;
points[ 3 ].x = rect.p2.x;
points[ 3 ].y = rect.p1.y + ( rect.getHeight() / 2 );
painter.drawPolygon( 4, points );
}
/*
* Check if Tile is in City
* in oldgui you can edit (1,1) to (98,98) with WORLD_SIDE_LEN 100
* i.e. there is a hidden border of green tiles arround the city
*/
bool GameView::inCity( MapPoint tile ){
if( tile.x > gameAreaMax || tile.y > gameAreaMax || tile.x < gameAreaMin || tile.y < gameAreaMin ) {
return false;
}
return true;
}
/*
* Draw MiniMapOverlay for tile.
*/
void GameView::drawOverlay(Painter& painter, MapPoint tile){
Color black;
black.parse("black");
Color miniMapColor;
Vector2 tileOnScreenPoint = getScreenPoint(tile);
Rect2D tilerect( 0, 0, tileWidth, tileHeight );
tileOnScreenPoint.x = tileOnScreenPoint.x - ( tileWidth / 2);
tileOnScreenPoint.y -= tileHeight;
tilerect.move( tileOnScreenPoint );
//Outside of the Map gets Black overlay
if( !inCity( tile ) ) {
painter.setFillColor( black );
} else {
miniMapColor = getMiniMap()->getColor( tile.x, tile.y );
if( mapOverlay == overlayOn ){
miniMapColor.a = 200; //Transparent
}
painter.setFillColor( miniMapColor );
}
fillDiamond( painter, tilerect );
}
/*
* If the current Tile is Part of a Building, return the
* Coordinates of the tile that contains the real informations.
*/
MapPoint GameView::realTile( MapPoint tile ){
MapPoint real = tile;
if( ! inCity( tile ) )
return real;
if ( MP_TYPE( tile.x, tile.y ) == CST_USED )
{
real.x = MP_INFO(tile.x, tile.y).int_1;
real.y = MP_INFO(tile.x, tile.y).int_2;
}
return real;
}
void GameView::drawTile(Painter& painter, MapPoint tile)
{
Rect2D tilerect( 0, 0, tileWidth, tileHeight );
Vector2 tileOnScreenPoint = getScreenPoint( tile );
//is Tile in City? If not draw Blank
if( ! inCity( tile ) )
{
tileOnScreenPoint.x -= (blankTexture->getWidth() / 2) * zoom;
tileOnScreenPoint.y -= blankTexture->getHeight() * zoom;
tilerect.move( tileOnScreenPoint );
tilerect.setSize(blankTexture->getWidth() * zoom,
blankTexture->getHeight() * zoom);
if(zoom == 1.0)
{
painter.drawTexture( blankTexture, tilerect.p1 );
}
else
{
painter.drawStretchTexture( blankTexture, tilerect );
}
return;
}
Texture* texture;
int size;
int upperLeftX = tile.x;
int upperLeftY = tile.y;
if ( MP_TYPE( tile.x, tile.y ) == CST_USED )
{
upperLeftX = MP_INFO(tile.x, tile.y).int_1;
upperLeftY = MP_INFO(tile.x, tile.y).int_2;
}
size = MP_SIZE( upperLeftX, upperLeftY );
//is Tile the lower left corner of the Building?
//dont't draw if not.
if ( ( tile.x != upperLeftX ) || ( tile.y - size +1 != upperLeftY ) )
{
return;
}
//adjust OnScreenPoint of big Tiles
if( size > 1 ) {
MapPoint lowerRightTile( tile.x + size - 1 , tile.y );
tileOnScreenPoint = getScreenPoint( lowerRightTile );
}
int textureType = MP_TYPE( upperLeftX, upperLeftY );
texture = cityTextures[ textureType ];
// Test if we have to convert Preloaded Image to Texture
if( !texture ) {
SDL_mutexP( mTextures );
if( cityImages[ textureType ] ){
cityTextures[ textureType ] = texture_manager->create( cityImages[ textureType ] );
cityImages[ textureType ] = 0; //Image is erased by texture_manager->create.
texture = cityTextures[ textureType ];
}
SDL_mutexV( mTextures );
}
if( texture && ( !hideHigh || size == 1 ) )
{
/* TODO: it seems possible to put green or desert tile first,
* so that buildings without ground will look nice
* especially power lines :) */
tileOnScreenPoint.x -= cityTextureX[textureType] * zoom;
tileOnScreenPoint.y -= cityTextureY[textureType] * zoom;
tilerect.move( tileOnScreenPoint );
tilerect.setSize(texture->getWidth() * zoom, texture->getHeight() * zoom);
if( zoom == 1.0 ) {
painter.drawTexture(texture, tilerect.p1);
}
else
{
painter.drawStretchTexture(texture, tilerect);
}
}
else
{
tileOnScreenPoint.x = tileOnScreenPoint.x - ( tileWidth*size / 2);
tileOnScreenPoint.y -= tileHeight*size;
tilerect.move( tileOnScreenPoint );
tilerect.setSize( size * tileWidth, size * tileHeight );
painter.setFillColor( getMiniMap()->getColorNormal( tile.x, tile.y ) );
fillDiamond( painter, tilerect );
}
}
/*
* Mark a tile with current cursor
*/
void GameView::markTile( Painter& painter, MapPoint tile )
{
Vector2 tileOnScreenPoint = getScreenPoint(tile);
if( cursorSize == 0 ) {
Color alphawhite( 255, 255, 255, 128 );
painter.setLineColor( alphawhite );
Rect2D tilerect( 0, 0, tileWidth, tileHeight );
tileOnScreenPoint.x = tileOnScreenPoint.x - ( tileWidth / 2);
tileOnScreenPoint.y -= tileHeight;
tilerect.move( tileOnScreenPoint );
drawDiamond( painter, tilerect );
} else {
Color alphablue( 0, 0, 255, 128 );
Color alphared( 255, 0, 0, 128 );
painter.setFillColor( alphablue );
//check if building is inside the map, if not use Red Cursor
int x = (int) tile.x;
int y = (int) tile.y;
MapPoint seCorner( x + cursorSize -1, y + cursorSize -1 );
if( !inCity( seCorner ) || !inCity( tile ) ) {
painter.setFillColor( alphared );
} else {
for( y = (int) tile.y; y < tile.y + cursorSize; y++ ){
for( x = (int) tile.x; x < tile.x + cursorSize; x++ ){
if( !GROUP_IS_BARE(MP_GROUP( x, y ))) {
if( !((MP_GROUP( x, y ) == GROUP_WATER) && ( // bridge on water is OK
(selected_module_type == CST_TRACK_LR ) ||
(selected_module_type == CST_ROAD_LR ) ||
(selected_module_type == CST_RAIL_LR ) ))) {
painter.setFillColor( alphared );
y += cursorSize;
break;
}
}
}
}
}
//check if building is allowed here, if not use Red Cursor
// These tests are in engine.cpp with place_item.
if ( !is_allowed_here(tile.x, tile.y, selected_module_type, 0) )
painter.setFillColor( alphared );
Rect2D tilerect( 0, 0, tileWidth * cursorSize, tileHeight * cursorSize );
tileOnScreenPoint.x = tileOnScreenPoint.x - (tileWidth * cursorSize / 2);
tileOnScreenPoint.y -= tileHeight;
tilerect.move( tileOnScreenPoint );
fillDiamond( painter, tilerect );
// Draw range for selected_module_type
int range = 0;
int reduceNW = 0; // substation and market reduce the range to nort west by one.
switch ( selected_module_type ){
//case CST_RESIDENCE_LL: break;
//case CST_RESIDENCE_ML: break;
//case CST_RESIDENCE_HL: break;
//case CST_RESIDENCE_LH: break;
//case CST_RESIDENCE_MH: break;
//case CST_RESIDENCE_HH: break;
//case CST_FARM_O0: break;
//case CST_MILL_0: break;
case CST_HEALTH: range = HEALTH_CENTRE_RANGE; break;
case CST_CRICKET_1: range = CRICKET_RANGE; break;
case CST_FIRESTATION_1: range = FIRESTATION_RANGE; break;
//case CST_SCHOOL: break;
//case CST_UNIVERSITY: break;
//case CST_TRACK_LR: break;
//case CST_ROAD_LR: break;
//case CST_RAIL_LR: break;
//case CST_EX_PORT: break;
//case CST_ROCKET_1: break;
//case CST_POWERL_H_L: break;
//case CST_POWERS_COAL_EMPTY: break;
//case CST_POWERS_SOLAR: break;
case CST_SUBSTATION_R: range = SUBSTATION_RANGE; reduceNW = 1; break;
case CST_WINDMILL_1_R: range = SUBSTATION_RANGE; reduceNW = 1; break; //Windmills are handled like substations
//case CST_COMMUNE_1: break;
case CST_COALMINE_EMPTY: range = COAL_RESERVE_SEARCH_LEN; break;
//case CST_OREMINE_1: break;
//case CST_TIP_0: break;
//case CST_RECYCLE: break;
//case CST_INDUSTRY_L_C: break;
//case CST_INDUSTRY_H_C: break;
case CST_MARKET_EMPTY: range = MARKET_RANGE; reduceNW = 1; break;
//case CST_POTTERY_0: break;
//case CST_BLACKSMITH_0: break;
//case CST_MONUMENT_0: break;
//case CST_PARKLAND_PLANE: break;
//case CST_WATER: break;
case CST_WATERWELL: range = WATERWELL_RANGE; break;
}
if (range > 0 )
{
painter.setFillColor( Color( 0, 0, 128, 64 ) );
Rect2D rangerect( 0,0,
tileWidth * ( 2 * range - reduceNW ) ,
tileHeight * ( 2 * range - reduceNW ) );
Vector2 screenPoint = getScreenPoint(tile);
screenPoint.x -= tileWidth * ( range - 0.5 * reduceNW );
screenPoint.y -= tileHeight * ( range + 1 - reduceNW );
rangerect.move( screenPoint );
fillDiamond( painter, rangerect );
}
}
}
/*
* Paint an isometric View of the City in the component.
*/
void GameView::draw(Painter& painter)
{
//If the centre of the Screen is not Part of the city
//adjust viewport so it is.
MapPoint centerTile = getCenter();
bool outside = false;
if( centerTile.x < gameAreaMin ) {
centerTile.x = gameAreaMin;
outside = true;
}
if( centerTile.x > gameAreaMax ) {
centerTile.x = gameAreaMax;
outside = true;
}
if( centerTile.y < gameAreaMin ) {
centerTile.y = gameAreaMin;
outside = true;
}
if( centerTile.y > gameAreaMax ) {
centerTile.y = gameAreaMax;
outside = true;
}
if( outside ){
mouseScrollState = 0; //Avoid clipping in pause mode
keyScrollState = 0;
show( centerTile );
return;
}
//The Corners of The Screen
//TODO: change here to only draw dirtyRect
// dirtyRectangle is the current Clippingarea (if set)
// so we should get clippingArea (as soon this is implemented)
// and adjust these Vectors:
Vector2 upperLeft( 0, 0);
Vector2 upperRight( getWidth(), 0 );
Vector2 lowerLeft( 0, getHeight() );
//Find visible Tiles
MapPoint upperLeftTile = getTile( upperLeft );
MapPoint upperRightTile = getTile( upperRight );
MapPoint lowerLeftTile = getTile( lowerLeft );
//draw Background
Color green;
Rect2D background( 0, 0, getWidth(), getHeight() );
green.parse( "green" );
painter.setFillColor( green );
painter.fillRectangle( background );
//draw Tiles
MapPoint currentTile;
//Draw some extra tiles depending on the maximal size of a building.
int extratiles = 7;
upperLeftTile.x -= extratiles;
upperRightTile.y -= extratiles;
upperRightTile.x += extratiles;
lowerLeftTile.y += extratiles;
if( mapOverlay != overlayOnly ){
for(int k = 0; k <= 2 * ( lowerLeftTile.y - upperLeftTile.y ); k++ )
{
for(int i = 0; i <= upperRightTile.x - upperLeftTile.x; i++ )
{
currentTile.x = upperLeftTile.x + i + k / 2 + k % 2;
currentTile.y = upperLeftTile.y - i + k / 2;
drawTile( painter, currentTile );
}
}
}
if( mapOverlay != overlayNone ){
for(int k = 0; k <= 2 * ( lowerLeftTile.y - upperLeftTile.y ); k++ )
{
for(int i = 0; i <= upperRightTile.x - upperLeftTile.x; i++ )
{
currentTile.x = upperLeftTile.x + i + k / 2 + k % 2;
currentTile.y = upperLeftTile.y - i + k / 2;
drawOverlay( painter, currentTile );
}
}
}
int cost = 0;
//Mark Tile under Mouse
if( mouseInGameView && !blockingDialogIsOpen ) {
MapPoint lastRazed( -1,-1 );
int tiles = 0;
if( roadDragging && ( cursorSize == 1 ) ){
//use same method to find all Tiles as in GameView::event(const Event& event)
int stepx = ( startRoad.x > tileUnderMouse.x ) ? -1 : 1;
int stepy = ( startRoad.y > tileUnderMouse.y ) ? -1 : 1;
currentTile = startRoad;
while( currentTile.x != tileUnderMouse.x ) {
markTile( painter, currentTile );
//we are speaking of tools, so CST_GREEN == bulldozer
if( (selected_module_type == CST_GREEN) && (realTile( currentTile ) != lastRazed) ){
cost += bulldozeCost( currentTile );
lastRazed = realTile( currentTile );
} else {
cost += buildCost( currentTile );
}
tiles++;
currentTile.x += stepx;
}
while( currentTile.y != tileUnderMouse.y ) {
markTile( painter, currentTile );
if( (selected_module_type == CST_GREEN ) && realTile( currentTile ) != lastRazed ){
cost += bulldozeCost( currentTile );
lastRazed = realTile( currentTile );
} else {
cost += buildCost( currentTile );
}
tiles++;
currentTile.y += stepy;
}
}
markTile( painter, tileUnderMouse );
tiles++;
if( (selected_module_type == CST_GREEN ) && realTile( currentTile ) != lastRazed ) {
cost += bulldozeCost( tileUnderMouse );
} else {
cost += buildCost( tileUnderMouse );
}
std::stringstream prize;
if( selected_module_type == CST_GREEN ){
if( roadDragging ){
prize << _("Estimated Bulldoze Cost: ");
} else {
prize << _("Bulldoze Cost: ");
}
if( cost > 0 ) {
prize << cost << _("$");
} else {
prize << _("n/a");
}
printStatusMessage( prize.str() );
} else if( selected_module_type == CST_TRACK_LR || selected_module_type == CST_ROAD_LR
|| selected_module_type == CST_RAIL_LR )
{
int group = main_types[ selected_module_type ].group;
std::string buildingName = main_groups[ group ].name;
prize << dictionaryManager->get_dictionary().translate( buildingName );
prize << _(": Cost to build ");
if( cost > 0 ) {
prize << cost << _("$");
} else {
prize << _("n/a");
}
printStatusMessage( prize.str() );
} else {
showToolInfo( tiles );
}
}
}
/*
* Show informatiosn about selected Tool
*/
void GameView::showToolInfo( int number /*= 0*/ )
{
std::stringstream infotextstream;
if( selected_module_type == CST_NONE ) //query
{
infotextstream << _("Query Tool: Show information about selected building.");
}
else if( selected_module_type == CST_GREEN ) //bulldoze
{
infotextstream << _("Bulldozer: remove building -price varies-");
}
else
{
int group = main_types[ selected_module_type ].group;
std::string buildingName = main_groups[ group ].name;
infotextstream << dictionaryManager->get_dictionary().translate( buildingName );
infotextstream << _(": Cost to build ") << selected_module_cost <<_("$");
infotextstream << _(", to bulldoze ") << main_groups[ group ].bul_cost <<_("$.");
if( number > 1 ){
infotextstream << _(" To build ") << number << _(" of them ");
infotextstream << _("will cost about ") << number*selected_module_cost << _("$.");
}
}
printStatusMessage( infotextstream.str() );
}
/*
* Print a Message to the StatusBar.
*/
void GameView::printStatusMessage( std::string message ){
if( message == lastStatusMessage ){
return;
}
Component* root = this;
while( root->getParent() )
root = root->getParent();
Desktop* desktop = dynamic_cast<Desktop*> (root);
if(!desktop) {
std::cerr << "Root not a desktop!?!\n";
return;
}
try {
Paragraph* statusParagraph = getParagraph( *root, "statusParagraph");
statusParagraph->setText( message );
} catch(std::exception& e) {
std::cerr << "Couldn't print status message '" << message << "': "
<< e.what() << "\n";
return;
}
lastStatusMessage = message;
}
int GameView::bulldozeCost( MapPoint tile ){
int group;
int prize = 0;
if (MP_TYPE( tile.x, tile.y) == CST_USED)
group = MP_GROUP( MP_INFO(tile.x,tile.y).int_1,
MP_INFO(tile.x,tile.y).int_2 );
else
group = MP_GROUP( tile.x,tile.y );
prize = main_groups[group].bul_cost;
return prize;
}
int GameView::buildCost( MapPoint tile ){
if( selected_module_type == CST_NONE ){
return 0;
}
if (MP_TYPE( tile.x, tile.y ) == CST_USED)
return 0;
if (( selected_module_type == CST_TRACK_LR || selected_module_type == CST_ROAD_LR ||
selected_module_type == CST_RAIL_LR) &&
// Transport on water need a bridge
(MP_GROUP( tile.x, tile.y) == GROUP_WATER ||
// upgrade bridge
((selected_module_type == CST_ROAD_LR && (MP_GROUP( tile.x, tile.y) == GROUP_TRACK_BRIDGE)) ||
(selected_module_type == CST_RAIL_LR && (MP_GROUP( tile.x, tile.y) == GROUP_TRACK_BRIDGE ||
MP_GROUP( tile.x, tile.y) == GROUP_ROAD_BRIDGE))) ) )
{
switch( selected_module_type ) {
case CST_TRACK_LR:
return get_group_cost( GROUP_TRACK_BRIDGE );
case CST_ROAD_LR:
return get_group_cost( GROUP_ROAD_BRIDGE );
case CST_RAIL_LR:
return get_group_cost( GROUP_RAIL_BRIDGE );
}
// Not updgrade a transport
} else if ( !GROUP_IS_BARE(MP_GROUP( tile.x, tile.y )) && (selected_module_type == CST_TRACK_LR
|| (selected_module_type == CST_ROAD_LR && (MP_GROUP( tile.x, tile.y) == GROUP_ROAD ||
MP_GROUP( tile.x, tile.y) == GROUP_RAIL || MP_GROUP( tile.x, tile.y) == GROUP_RAIL_BRIDGE))
|| (selected_module_type == CST_RAIL_LR &&
(MP_GROUP( tile.x, tile.y) == GROUP_RAIL || MP_GROUP( tile.x, tile.y) == GROUP_RAIL_BRIDGE))
|| (selected_module_type == CST_WATER && MP_GROUP( tile.x, tile.y) == GROUP_WATER )) ){
return 0;
}
return get_group_cost( main_types[ selected_module_type ].group );
}
//Register as Component
IMPLEMENT_COMPONENT_FACTORY(GameView);
| javiercantero/lincity-ng | src/lincity-ng/GameView.cpp | C++ | gpl-2.0 | 69,238 |
/***************************************************************************
* Copyright (C) 2010 by Kai Dombrowe <just89@gmx.de> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
// own
#include "videopage.h"
// JoschyCore
#include <joschycore/manager.h>
#include <joschycore/plugininfo.h>
#include <joschycore/abstractprovider.h>
// KDE
#include <kmessagebox.h>
#include <kdebug.h>
// Qt
#include <QtCore/QFile>
VideoPage::VideoPage(QWidget *parent)
: QWizardPage(parent), m_provider(0)
{
setupUi(this);
registerField("Video*", videoRequester, "text", SIGNAL(textChanged(QString)));
registerField("Title*", titleEdit);
registerField("Description*", descriptionEdit, "plainText", SIGNAL(textChanged()));
registerField("Category*", categoryCombo, "currentText", SIGNAL(currentIndexChanged(QString)));
registerField("Tags*", tagBox, "items", SIGNAL(changed()));
connect(descriptionEdit, SIGNAL(textChanged()), this, SLOT(descriptionChanged()));
descriptionEdit->setCheckSpellingEnabled(true);
}
VideoPage::~VideoPage()
{
if (m_provider) {
Joschy::Manager::self()->unloadProvider(m_provider);
}
}
void VideoPage::initializePage()
{
if (m_provider) {
Joschy::Manager::self()->unloadProvider(m_provider);
m_provider = 0;
}
Joschy::AbstractProvider *plugin = Joschy::Manager::self()->createProvider(field("Provider").toString(),
"QNetworkLayer");
if (!plugin) {
KMessageBox::error(this, i18n("Cannot load: %1", field("Provider").toString()));
return;
}
m_provider = plugin;
categorysChanged(plugin->categorys());
connect(m_provider, SIGNAL(categorysChanged(QStringList)), this,
SLOT(categorysChanged(QStringList)));
videoRequester->setText(m_video);
}
void VideoPage::setVideo(const QString &video)
{
m_video = video;
}
void VideoPage::categorysChanged(const QStringList &categorys)
{
categoryCombo->clear();
categoryCombo->addItems(categorys);
}
void VideoPage::descriptionChanged()
{
QString text = descriptionEdit->toPlainText();
if (text.length() > 5000) {
text.resize(5000);
descriptionEdit->setText(text);
}
}
#include "videopage.moc"
| hippich/recorditnow | src/upload/videopage.cpp | C++ | gpl-2.0 | 3,534 |
using System;
using System.Text.RegularExpressions;
using SelfMediaDatabase.Core.Operations.Prune;
using System.Collections.Generic;
namespace SelfMediaDatabase.Core.Operations
{
public static class FileFilterProvider
{
private static readonly Regex _tagFileRegex;
private static readonly Regex _pruneHistoryMatcherRegex;
private static readonly HashSet<string> _managedFileExtensions;
static FileFilterProvider()
{
_managedFileExtensions = GetManagedFileExtensions();
_tagFileRegex = new Regex(@".*\.(" + _managedFileExtensions.Join("|") +")", RegexOptions.IgnoreCase | RegexOptions.Compiled);
_pruneHistoryMatcherRegex = new Regex(@"^.*\" + PruneOperation.PRUNE_INVENTORY_FILE + "$", RegexOptions.Compiled);
}
/// <summary>
/// Gets a regex that match if file could contain media tag values.
/// </summary>
public static Regex TagFileMatcher { get { return _tagFileRegex; } }
/// <summary>
/// Gets a regex that match if file name is a prune inventory text file.
/// </summary>
public static Regex PruneInventoryFileMatcher { get { return _pruneHistoryMatcherRegex; } }
private static HashSet<string> GetManagedFileExtensions()
{
var result = new HashSet<string>();
// Images
result.Add("jpg");
result.Add("jpeg");
result.Add("tiff");
result.Add("png");
// Video
result.Add("avi");
result.Add("mp4");
result.Add("mts");
// Audio
result.Add("ogg");
result.Add("flac");
result.Add("mp3");
result.Add("m4a");
result.Add("wav");
return result;
}
}
}
| crabouif/Self-Media-Database | SelfMediaDatabase.Core/Operations/FileFilterProvider.cs | C# | gpl-2.0 | 1,602 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest12371")
public class BenchmarkTest12371 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] values = request.getParameterValues("foo");
String param;
if (values.length != 0)
param = request.getParameterValues("foo")[0];
else param = null;
String bar = new Test().doSomething(param);
java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir + bar));
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
// Chain a bunch of propagators in sequence
String a13109 = param; //assign
StringBuilder b13109 = new StringBuilder(a13109); // stick in stringbuilder
b13109.append(" SafeStuff"); // append some safe content
b13109.replace(b13109.length()-"Chars".length(),b13109.length(),"Chars"); //replace some of the end content
java.util.HashMap<String,Object> map13109 = new java.util.HashMap<String,Object>();
map13109.put("key13109", b13109.toString()); // put in a collection
String c13109 = (String)map13109.get("key13109"); // get it back out
String d13109 = c13109.substring(0,c13109.length()-1); // extract most of it
String e13109 = new String( new sun.misc.BASE64Decoder().decodeBuffer(
new sun.misc.BASE64Encoder().encode( d13109.getBytes() ) )); // B64 encode and decode it
String f13109 = e13109.split(" ")[0]; // split it on a space
org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing();
String g13109 = "barbarians_at_the_gate"; // This is static so this whole flow is 'safe'
String bar = thing.doSomething(g13109); // reflection
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest12371.java | Java | gpl-2.0 | 3,211 |
using UnityEngine;
public static class AnimationCurveExtensions {
public static AnimationCurve Clamp(this AnimationCurve curve, float minTime, float maxTime, float minValue, float maxValue) {
for (int i = 0; i < curve.keys.Length; i++) {
Keyframe key = curve.keys[i];
if (key.time < minTime || key.time > maxTime || key.value < minValue || key.value > maxValue) {
var newKey = new Keyframe(Mathf.Clamp(key.time, minTime, maxTime), Mathf.Clamp(key.value, minValue, maxValue));
newKey.inTangent = key.inTangent;
newKey.outTangent = key.outTangent;
curve.MoveKey(i, newKey);
}
}
return curve;
}
}
| Magicolo/LibPd4UnityTools | PDPlayerExample/Assets/Other Assets/Magicolo/GeneralTools/Utils/Extensions/AnimationCurveExtensions.cs | C# | gpl-2.0 | 632 |
<?php
//DRY don't repeat yourself
$tipo_usuario = array('Adm','FBA','Lab');
require_once '../validarSesion.php';
require_once '../../model/resultado_interface.php';
require_once '../../model/laboratorio_interface.php';
$parametro_template = 'abm/resultado.html';
$parametro_columnas = Array('ID_RESULTADO','COMENTARIO','FECHA ANALISIS','LABORATORIO','ANALITO');
$parametro_datos = ORM_resultado::buscar_resultado_Twig_Tabla();
$perfil = $_SESSION['usuarioLogeado']['rol'];
if (($perfil != 'Administrador')and($perfil != 'FBA')){
$perfil = str_replace('Laboratorio_','',$perfil);
$laboratorio = ORM_laboratorio:: buscar_laboratorio_Twig($perfil); //es la busqueda por id de lab
$codlab = $laboratorio['cod_lab'];
$parametro_datos = ORM_resultado::buscar_resultado_Twig_Tabla_para_lab($codlab);
}
if (isset($_POST['error'])){
$error = $_POST['error'];
$display = 'block';
$color = "red";
}
else{
$error = '';
$color = "yellow";
$display = 'none';
}
if($error == "1"){
$color = "green";
$error = "Operacion Exitosa!";
}
$parametro_display = array(
'cabecera' => $parametro_columnas,
'filas' => $parametro_datos,
'perfil' => $perfil,
'error' => $error,
'displayerror' => $display,
'messagecolor' => $color
);
require '../controller.generico.php';
?> | ggoral/improved_login | controller/tablas/controller.resultado.php | PHP | gpl-2.0 | 1,303 |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Win32;
using Sdl.Community.XLIFF.Manager.Common;
using Sdl.Community.XLIFF.Manager.Interfaces;
namespace Sdl.Community.XLIFF.Manager.Service
{
public class DialogService : IDialogService
{
public List<string> ShowFileDialog(string filter, string title, string initialDirectory)
{
try
{
var openFileDialog = new OpenFileDialog
{
Filter = filter.ToLower(),
Multiselect = true,
Title = title,
InitialDirectory = initialDirectory
};
return openFileDialog.ShowDialog() != true
? new List<string>()
: openFileDialog.FileNames.ToList();
}
catch
{
return new List<string>();
}
}
public string ShowFolderDialog(string dialogTitle, string initialDirectory)
{
if (string.IsNullOrEmpty(initialDirectory) || !Directory.Exists(initialDirectory))
{
initialDirectory = null;
}
var folderDialog = new FolderSelectDialog
{
Title = dialogTitle,
InitialDirectory = initialDirectory
};
return folderDialog.ShowDialog()
? folderDialog.FileName
: string.Empty;
}
}
}
| sdl/Sdl-Community | XLIFF.Manager/XLIFF.Manager/Service/DialogService.cs | C# | gpl-2.0 | 1,168 |
<?php
/**
* Created by PhpStorm.
* User: Firdavs Murodov
* Date: 4/20/15
* Time: 8:59 AM
*/
require 'config.php';
// $_user_ = 'test';
// $_password_ = 'test';
session_start();
$url_action = (empty($_REQUEST['action'])) ? 'logIn' : $_REQUEST['action'];
$auth_realm = (isset($auth_realm)) ? $auth_realm : '';
if (isset($url_action)) {
if (is_callable($url_action)) {
call_user_func($url_action);
} else {
echo 'Function does not exist, request terminated';
};
};
function logIn() {
global $auth_realm;
if (!isset($_SESSION['username'])) {
if (!isset($_SESSION['login'])) {
$_SESSION['login'] = TRUE;
header('WWW-Authenticate: Basic realm="'.$auth_realm.'"');
header('HTTP/1.0 401 Unauthorized');
echo 'You must enter a valid login and password';
echo '<p><a href="?action=logOut">Try again</a></p>';
exit;
} else {
$user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
$password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
$result = authenticate($user, $password);
if ($result == 0) {
$_SESSION['username'] = $user;
} else {
session_unset($_SESSION['login']);
errMes($result);
echo '<p><a href="">Try again</a></p>';
exit;
};
};
};
}
function authenticate($user, $password) {
global $_user_;
global $_password_;
if (($user == $_user_)&&($password == $_password_)) { return 0; }
else { return 1; };
}
function errMes($errno) {
switch ($errno) {
case 0:
break;
case 1:
echo 'The username or password you entered is incorrect';
break;
default:
echo 'Unknown error';
};
}
function logOut() {
session_destroy();
if (isset($_SESSION['username'])) {
session_unset($_SESSION['username']);
echo "You've successfully logged out<br>";
echo '<p><a href="?action=logIn">LogIn</a></p>';
} else {
header("Location: ?action=logIn", TRUE, 301);
};
if (isset($_SESSION['login'])) { session_unset($_SESSION['login']); };
exit;
}
?> | firdavsich/dashboard | auth.php | PHP | gpl-2.0 | 2,309 |
/***************************************************************************
qgsvertextool.cpp
--------------------------------------
Date : February 2017
Copyright : (C) 2017 by Martin Dobias
Email : wonder dot sk at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsvertextool.h"
#include "qgsadvanceddigitizingdockwidget.h"
#include "qgscurve.h"
#include "qgscurvepolygon.h"
#include "qgsgeometryutils.h"
#include "qgsgeometryvalidator.h"
#include "qgslogger.h"
#include "qgsmapcanvas.h"
#include "qgsmulticurve.h"
#include "qgsmultipoint.h"
#include "qgspointlocator.h"
#include "qgsproject.h"
#include "qgsrubberband.h"
#include "qgssettings.h"
#include "qgssnapindicator.h"
#include "qgssnappingutils.h"
#include "qgsvectorlayer.h"
#include "qgsvertexmarker.h"
#include "qgsstatusbar.h"
#include "qgisapp.h"
#include "qgsselectedfeature.h"
#include "qgsvertexeditor.h"
#include "qgsvertexentry.h"
#include <QMenu>
#include <QRubberBand>
uint qHash( const Vertex &v )
{
return qHash( v.layer ) ^ qHash( v.fid ) ^ qHash( v.vertexId );
}
//
// geomutils - may get moved elsewhere
//
//! Find out whether vertex at the given index is an endpoint (assuming linear geometry)
static bool isEndpointAtVertexIndex( const QgsGeometry &geom, int vertexIndex )
{
const QgsAbstractGeometry *g = geom.constGet();
if ( const QgsCurve *curve = qgsgeometry_cast< const QgsCurve *>( g ) )
{
return vertexIndex == 0 || vertexIndex == curve->numPoints() - 1;
}
else if ( const QgsMultiCurve *multiCurve = qgsgeometry_cast<const QgsMultiCurve *>( g ) )
{
for ( int i = 0; i < multiCurve->numGeometries(); ++i )
{
QgsCurve *part = qgsgeometry_cast<QgsCurve *>( multiCurve->geometryN( i ) );
Q_ASSERT( part );
if ( vertexIndex < part->numPoints() )
return vertexIndex == 0 || vertexIndex == part->numPoints() - 1;
vertexIndex -= part->numPoints();
}
Q_ASSERT( false ); // should not get here
return false;
}
else
{
QgsDebugMsg( "is_endpoint_at_vertex_index: unexpected geometry type!" );
return false;
}
}
//! Returns the index of vertex adjacent to the given endpoint. Assuming linear geometries.
int adjacentVertexIndexToEndpoint( const QgsGeometry &geom, int vertexIndex )
{
const QgsAbstractGeometry *g = geom.constGet();
if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( g ) )
{
return vertexIndex == 0 ? 1 : curve->numPoints() - 2;
}
else if ( const QgsMultiCurve *multiCurve = qgsgeometry_cast<const QgsMultiCurve *>( g ) )
{
int offset = 0;
for ( int i = 0; i < multiCurve->numGeometries(); ++i )
{
const QgsCurve *part = qgsgeometry_cast<const QgsCurve *>( multiCurve->geometryN( i ) );
Q_ASSERT( part );
if ( vertexIndex < part->numPoints() )
return vertexIndex == 0 ? offset + 1 : offset + part->numPoints() - 2;
vertexIndex -= part->numPoints();
offset += part->numPoints();
}
}
else
{
QgsDebugMsg( "adjacent_vertex_index_to_endpoint: unexpected geometry type!" );
}
return -1;
}
/**
* Determine whether a vertex is in the middle of a circular edge or not
* (wrapper for slightly awkward API)
*/
static bool isCircularVertex( const QgsGeometry &geom, int vertexIndex )
{
QgsVertexId vid;
return geom.vertexIdFromVertexNr( vertexIndex, vid ) && vid.type == QgsVertexId::CurveVertex;
}
//! Create a multi-point geometry that can be used to highlight vertices of a feature
static QgsGeometry geometryToMultiPoint( const QgsGeometry &geom )
{
QgsMultiPoint *multiPoint = new QgsMultiPoint();
QgsGeometry outputGeom( multiPoint );
for ( auto pointIt = geom.vertices_begin(); pointIt != geom.vertices_end(); ++pointIt )
multiPoint->addGeometry( ( *pointIt ).clone() );
return outputGeom;
}
//
// snapping match filters
//
//! a filter to allow just one particular feature
class OneFeatureFilter : public QgsPointLocator::MatchFilter
{
public:
OneFeatureFilter( const QgsVectorLayer *layer, QgsFeatureId fid )
: layer( layer )
, fid( fid )
{}
bool acceptMatch( const QgsPointLocator::Match &match ) override
{
return match.layer() == layer && match.featureId() == fid;
}
private:
const QgsVectorLayer *layer = nullptr;
QgsFeatureId fid;
};
//! a filter just to gather all matches at the same place
class MatchCollectingFilter : public QgsPointLocator::MatchFilter
{
public:
QList<QgsPointLocator::Match> matches;
QgsVertexTool *vertextool = nullptr;
MatchCollectingFilter( QgsVertexTool *vertextool )
: vertextool( vertextool ) {}
bool acceptMatch( const QgsPointLocator::Match &match ) override
{
if ( match.distance() > 0 )
return false;
matches.append( match );
// there may be multiple points at the same location, but we get only one
// result... the locator API needs a new method verticesInRect()
QgsGeometry matchGeom = vertextool->cachedGeometry( match.layer(), match.featureId() );
QgsVertexId vid;
QgsPoint pt;
while ( matchGeom.constGet()->nextVertex( vid, pt ) )
{
int vindex = matchGeom.vertexNrFromVertexId( vid );
if ( pt.x() == match.point().x() && pt.y() == match.point().y() && vindex != match.vertexIndex() )
{
QgsPointLocator::Match extra_match( match.type(), match.layer(), match.featureId(),
0, match.point(), vindex );
matches.append( extra_match );
}
}
return true;
}
};
/**
* Keeps the best match from a selected feature so that we can possibly use it with higher priority.
* If we do not encounter any selected feature within tolerance, we use the best match as usual.
*/
class SelectedMatchFilter : public QgsPointLocator::MatchFilter
{
public:
explicit SelectedMatchFilter( double tol )
: mTolerance( tol ) {}
bool acceptMatch( const QgsPointLocator::Match &match ) override
{
if ( match.distance() <= mTolerance && match.layer() && match.layer()->selectedFeatureIds().contains( match.featureId() ) )
{
if ( !mBestSelectedMatch.isValid() || match.distance() < mBestSelectedMatch.distance() )
mBestSelectedMatch = match;
}
return true;
}
bool hasSelectedMatch() const { return mBestSelectedMatch.isValid(); }
QgsPointLocator::Match bestSelectedMatch() const { return mBestSelectedMatch; }
private:
double mTolerance;
QgsPointLocator::Match mBestSelectedMatch;
};
//
//
//
QgsVertexTool::QgsVertexTool( QgsMapCanvas *canvas, QgsAdvancedDigitizingDockWidget *cadDock, VertexToolMode mode )
: QgsMapToolAdvancedDigitizing( canvas, cadDock )
, mMode( mode )
{
setAdvancedDigitizingAllowed( false );
mSnapIndicator.reset( new QgsSnapIndicator( canvas ) );
mEdgeCenterMarker = new QgsVertexMarker( canvas );
mEdgeCenterMarker->setIconType( QgsVertexMarker::ICON_CROSS );
mEdgeCenterMarker->setColor( Qt::red );
mEdgeCenterMarker->setPenWidth( 3 );
mEdgeCenterMarker->setVisible( false );
mFeatureBand = createRubberBand( QgsWkbTypes::LineGeometry );
mFeatureBand->setVisible( false );
QColor color = digitizingStrokeColor();
mFeatureBandMarkers = new QgsRubberBand( canvas );
mFeatureBandMarkers->setIcon( QgsRubberBand::ICON_CIRCLE );
mFeatureBandMarkers->setColor( color );
mFeatureBandMarkers->setIconSize( 8 );
mFeatureBandMarkers->setVisible( false );
mVertexBand = new QgsRubberBand( canvas );
mVertexBand->setIcon( QgsRubberBand::ICON_CIRCLE );
mVertexBand->setColor( color );
mVertexBand->setIconSize( 15 );
mVertexBand->setVisible( false );
QColor color2( color );
color2.setAlpha( color2.alpha() / 3 );
mEdgeBand = new QgsRubberBand( canvas );
mEdgeBand->setColor( color2 );
mEdgeBand->setWidth( 10 );
mEdgeBand->setVisible( false );
mEndpointMarker = new QgsVertexMarker( canvas );
mEndpointMarker->setIconType( QgsVertexMarker::ICON_CROSS );
mEndpointMarker->setColor( Qt::red );
mEndpointMarker->setPenWidth( 3 );
mEndpointMarker->setVisible( false );
}
QgsVertexTool::~QgsVertexTool()
{
delete mEdgeCenterMarker;
delete mFeatureBand;
delete mFeatureBandMarkers;
delete mVertexBand;
delete mEdgeBand;
delete mEndpointMarker;
}
void QgsVertexTool::deactivate()
{
setHighlightedVertices( QList<Vertex>() );
removeTemporaryRubberBands();
cleanupVertexEditor();
mSnapIndicator->setMatch( QgsPointLocator::Match() );
QHash< QPair<QgsVectorLayer *, QgsFeatureId>, GeometryValidation>::iterator it = mValidations.begin();
for ( ; it != mValidations.end(); ++it )
it->cleanup();
mValidations.clear();
QgsMapToolAdvancedDigitizing::deactivate();
}
void QgsVertexTool::addDragBand( const QgsPointXY &v1, const QgsPointXY &v2 )
{
addDragStraightBand( nullptr, v1, v2, false, true, v2 );
}
void QgsVertexTool::addDragStraightBand( QgsVectorLayer *layer, QgsPointXY v0, QgsPointXY v1, bool moving0, bool moving1, const QgsPointXY &mapPoint )
{
// if layer is not null, the input coordinates are coming in the layer's CRS rather than map CRS
if ( layer )
{
v0 = toMapCoordinates( layer, v0 );
v1 = toMapCoordinates( layer, v1 );
}
StraightBand b;
b.band = createRubberBand( QgsWkbTypes::LineGeometry, true );
b.p0 = v0;
b.p1 = v1;
b.moving0 = moving0;
b.moving1 = moving1;
b.offset0 = v0 - mapPoint;
b.offset1 = v1 - mapPoint;
b.band->addPoint( v0 );
b.band->addPoint( v1 );
mDragStraightBands << b;
}
void QgsVertexTool::addDragCircularBand( QgsVectorLayer *layer, QgsPointXY v0, QgsPointXY v1, QgsPointXY v2, bool moving0, bool moving1, bool moving2, const QgsPointXY &mapPoint )
{
// if layer is not null, the input coordinates are coming in the layer's CRS rather than map CRS
if ( layer )
{
v0 = toMapCoordinates( layer, v0 );
v1 = toMapCoordinates( layer, v1 );
v2 = toMapCoordinates( layer, v2 );
}
CircularBand b;
b.band = createRubberBand( QgsWkbTypes::LineGeometry, true );
b.p0 = v0;
b.p1 = v1;
b.p2 = v2;
b.moving0 = moving0;
b.moving1 = moving1;
b.moving2 = moving2;
b.offset0 = v0 - mapPoint;
b.offset1 = v1 - mapPoint;
b.offset2 = v2 - mapPoint;
b.updateRubberBand( mapPoint );
mDragCircularBands << b;
}
void QgsVertexTool::clearDragBands()
{
qDeleteAll( mDragPointMarkers );
mDragPointMarkers.clear();
mDragPointMarkersOffset.clear();
for ( const StraightBand &b : qgis::as_const( mDragStraightBands ) )
delete b.band;
mDragStraightBands.clear();
for ( const CircularBand &b : qgis::as_const( mDragCircularBands ) )
delete b.band;
mDragCircularBands.clear();
}
void QgsVertexTool::cadCanvasPressEvent( QgsMapMouseEvent *e )
{
if ( mSelectionMethod == SelectionRange )
{
rangeMethodPressEvent( e );
return;
}
if ( !mDraggingVertex && !mSelectedVertices.isEmpty() && !( e->modifiers() & Qt::ShiftModifier ) && !( e->modifiers() & Qt::ControlModifier ) )
{
// only remove highlight if not clicked on one of highlighted vertices
bool clickedOnHighlightedVertex = false;
QgsPointLocator::Match m = snapToEditableLayer( e );
if ( m.hasVertex() )
{
for ( const Vertex &selectedVertex : qgis::as_const( mSelectedVertices ) )
{
if ( selectedVertex.layer == m.layer() && selectedVertex.fid == m.featureId() && selectedVertex.vertexId == m.vertexIndex() )
{
clickedOnHighlightedVertex = true;
break;
}
}
}
if ( !clickedOnHighlightedVertex )
setHighlightedVertices( QList<Vertex>() ); // reset selection
}
if ( e->button() == Qt::LeftButton )
{
if ( e->modifiers() & Qt::ControlModifier || e->modifiers() & Qt::ShiftModifier )
{
// shift or ctrl-click vertices to highlight without entering edit mode
QgsPointLocator::Match m = snapToEditableLayer( e );
if ( m.hasVertex() )
{
Vertex vertex( m.layer(), m.featureId(), m.vertexIndex() );
HighlightMode mode = ModeReset;
if ( e->modifiers() & Qt::ShiftModifier )
{
// Shift+Click to add vertex to highlight
mode = ModeAdd;
}
else if ( e->modifiers() & Qt::ControlModifier )
{
// Ctrl+Click to remove vertex
mode = ModeSubtract;
}
setHighlightedVertices( QList<Vertex>() << vertex, mode );
return;
}
}
// the user may have started dragging a rect to select vertices
if ( !mDraggingVertex && !mDraggingEdge )
mSelectionRectStartPos.reset( new QPoint( e->pos() ) );
}
if ( e->button() == Qt::RightButton )
{
if ( !mSelectionRect && !mDraggingVertex && !mDraggingEdge )
{
// show popup menu - if we are on top of a feature
if ( mLastMouseMoveMatch.isValid() && mLastMouseMoveMatch.layer() )
{
QMenu menu;
QAction *actionVertexEditor = menu.addAction( tr( "Vertex Editor" ) );
connect( actionVertexEditor, &QAction::triggered, this, &QgsVertexTool::showVertexEditor ); //#spellok
menu.exec( mCanvas->mapToGlobal( e->pos() ) );
}
}
}
}
void QgsVertexTool::cadCanvasReleaseEvent( QgsMapMouseEvent *e )
{
if ( mSelectionMethod == SelectionRange )
{
rangeMethodReleaseEvent( e );
return;
}
if ( mNewVertexFromDoubleClick )
{
QgsPointLocator::Match m( *mNewVertexFromDoubleClick );
mNewVertexFromDoubleClick.reset();
// dragging of edges and double clicking on edges to add vertex are slightly overlapping
// so we need to cancel edge moving before we start dragging new vertex
stopDragging();
startDraggingAddVertex( m );
}
else if ( mSelectionRect )
{
// only handling of selection rect being dragged
QgsPointXY pt0 = toMapCoordinates( *mSelectionRectStartPos );
QgsPointXY pt1 = toMapCoordinates( e->pos() );
QgsRectangle map_rect( pt0, pt1 );
QList<Vertex> vertices;
QList<Vertex> selectedVertices;
// for each editable layer, select vertices
const auto layers = canvas()->layers();
for ( QgsMapLayer *layer : layers )
{
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
if ( !vlayer || !vlayer->isEditable() || !vlayer->isSpatial() )
continue;
if ( mMode == ActiveLayer && vlayer != currentVectorLayer() )
continue;
QgsRectangle layerRect = toLayerCoordinates( vlayer, map_rect );
QgsFeature f;
QgsFeatureIterator fi = vlayer->getFeatures( QgsFeatureRequest( layerRect ).setSubsetOfAttributes( QgsAttributeList() ) );
while ( fi.nextFeature( f ) )
{
bool isFeatureSelected = vlayer->selectedFeatureIds().contains( f.id() );
QgsGeometry g = f.geometry();
for ( int i = 0; i < g.constGet()->nCoordinates(); ++i )
{
QgsPointXY pt = g.vertexAt( i );
if ( layerRect.contains( pt ) )
{
vertices << Vertex( vlayer, f.id(), i );
if ( isFeatureSelected )
selectedVertices << Vertex( vlayer, f.id(), i );
}
}
}
}
// If there were any vertices that come from selected features, use just vertices from selected features.
// This allows user to select a bunch of features in complex situations to constrain the selection.
if ( !selectedVertices.isEmpty() )
vertices = selectedVertices;
HighlightMode mode = ModeReset;
if ( e->modifiers() & Qt::ShiftModifier )
mode = ModeAdd;
else if ( e->modifiers() & Qt::ControlModifier )
mode = ModeSubtract;
setHighlightedVertices( vertices, mode );
stopSelectionRect();
}
else // selection rect is not being dragged
{
if ( e->button() == Qt::LeftButton && !( e->modifiers() & Qt::ShiftModifier ) && !( e->modifiers() & Qt::ControlModifier ) )
{
// accepting action
if ( mDraggingVertex )
{
QgsPointLocator::Match match = e->mapPointMatch();
moveVertex( e->mapPoint(), &match );
}
else if ( mDraggingEdge )
{
// do not use e.mapPoint() as it may be snapped
moveEdge( toMapCoordinates( e->pos() ) );
}
else
{
startDragging( e );
}
}
else if ( e->button() == Qt::RightButton )
{
// cancel action
stopDragging();
}
}
mSelectionRectStartPos.reset();
}
void QgsVertexTool::cadCanvasMoveEvent( QgsMapMouseEvent *e )
{
if ( mSelectionMethod == SelectionRange )
{
rangeMethodMoveEvent( e );
return;
}
if ( mDraggingVertex )
{
mouseMoveDraggingVertex( e );
}
else if ( mDraggingEdge )
{
mouseMoveDraggingEdge( e );
}
else if ( mSelectionRectStartPos )
{
// the user may be dragging a rect to select vertices
if ( !mSelectionRect && ( e->pos() - *mSelectionRectStartPos ).manhattanLength() >= 10 )
{
startSelectionRect( *mSelectionRectStartPos );
}
if ( mSelectionRect )
{
updateSelectionRect( e->pos() );
}
}
else
{
mouseMoveNotDragging( e );
}
}
void QgsVertexTool::mouseMoveDraggingVertex( QgsMapMouseEvent *e )
{
mSnapIndicator->setMatch( e->mapPointMatch() );
mEdgeCenterMarker->setVisible( false );
moveDragBands( e->mapPoint() );
}
void QgsVertexTool::moveDragBands( const QgsPointXY &mapPoint )
{
for ( int i = 0; i < mDragStraightBands.count(); ++i )
{
StraightBand &b = mDragStraightBands[i];
if ( b.moving0 )
b.band->movePoint( 0, mapPoint + b.offset0 );
if ( b.moving1 )
b.band->movePoint( 1, mapPoint + b.offset1 );
}
for ( int i = 0; i < mDragCircularBands.count(); ++i )
{
CircularBand &b = mDragCircularBands[i];
b.updateRubberBand( mapPoint );
}
// in case of moving of standalone point geometry
for ( int i = 0; i < mDragPointMarkers.count(); ++i )
{
QgsVertexMarker *marker = mDragPointMarkers[i];
QgsVector offset = mDragPointMarkersOffset[i];
marker->setCenter( mapPoint + offset );
}
// make sure the temporary feature rubber band is not visible
removeTemporaryRubberBands();
}
void QgsVertexTool::mouseMoveDraggingEdge( QgsMapMouseEvent *e )
{
mSnapIndicator->setMatch( QgsPointLocator::Match() );
mEdgeCenterMarker->setVisible( false );
QgsPointXY mapPoint = toMapCoordinates( e->pos() ); // do not use e.mapPoint() as it may be snapped
moveDragBands( mapPoint );
}
void QgsVertexTool::canvasDoubleClickEvent( QgsMapMouseEvent *e )
{
QgsPointLocator::Match m = snapToEditableLayer( e );
if ( !m.hasEdge() )
return;
mNewVertexFromDoubleClick.reset( new QgsPointLocator::Match( m ) );
}
void QgsVertexTool::removeTemporaryRubberBands()
{
mFeatureBand->setVisible( false );
mFeatureBandMarkers->setVisible( false );
mFeatureBandLayer = nullptr;
mFeatureBandFid = QgsFeatureId();
mVertexBand->setVisible( false );
mEdgeBand->setVisible( false );
mEndpointMarkerCenter.reset();
mEndpointMarker->setVisible( false );
}
QgsPointLocator::Match QgsVertexTool::snapToEditableLayer( QgsMapMouseEvent *e )
{
QgsSnappingUtils *snapUtils = canvas()->snappingUtils();
QgsSnappingConfig oldConfig = snapUtils->config();
QgsPointLocator::Match m;
QgsPointXY mapPoint = toMapCoordinates( e->pos() );
double tol = QgsTolerance::vertexSearchRadius( canvas()->mapSettings() );
QgsSnappingConfig config( QgsProject::instance() );
config.setEnabled( true );
config.setMode( QgsSnappingConfig::AdvancedConfiguration );
config.setIntersectionSnapping( false ); // only snap to layers
// if there is a current layer, it should have priority over other layers
// because sometimes there may be match from multiple layers at one location
// and selecting current layer is an easy way for the user to prioritize a layer
if ( QgsVectorLayer *currentVlayer = currentVectorLayer() )
{
if ( currentVlayer->isEditable() )
{
const auto layers = canvas()->layers();
for ( QgsMapLayer *layer : layers )
{
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
if ( !vlayer )
continue;
config.setIndividualLayerSettings( vlayer, QgsSnappingConfig::IndividualLayerSettings(
vlayer == currentVlayer, QgsSnappingConfig::VertexAndSegment, tol, QgsTolerance::ProjectUnits ) );
}
snapUtils->setConfig( config );
SelectedMatchFilter filter( tol );
m = snapUtils->snapToMap( mapPoint, &filter );
// we give priority to snap matches that are from selected features
if ( filter.hasSelectedMatch() )
{
m = filter.bestSelectedMatch();
mLastSnap.reset();
}
}
}
// if there is no match from the current layer, try to use any editable vector layer
if ( !m.isValid() && mMode == AllLayers )
{
const auto layers = canvas()->layers();
for ( QgsMapLayer *layer : layers )
{
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
if ( !vlayer )
continue;
config.setIndividualLayerSettings( vlayer, QgsSnappingConfig::IndividualLayerSettings(
vlayer->isEditable(), QgsSnappingConfig::VertexAndSegment, tol, QgsTolerance::ProjectUnits ) );
}
snapUtils->setConfig( config );
SelectedMatchFilter filter( tol );
m = snapUtils->snapToMap( mapPoint, &filter );
// we give priority to snap matches that are from selected features
if ( filter.hasSelectedMatch() )
{
m = filter.bestSelectedMatch();
mLastSnap.reset();
}
}
// try to stay snapped to previously used feature
// so the highlight does not jump around at vertices where features are joined
if ( mLastSnap )
{
OneFeatureFilter filterLast( mLastSnap->layer(), mLastSnap->featureId() );
QgsPointLocator::Match lastMatch = snapUtils->snapToMap( mapPoint, &filterLast );
// but skip the the previously used feature if it would only snap to segment, while now we have snap to vertex
// so that if there is a point on a line, it gets priority (as is usual with combined vertex+segment snapping)
bool matchHasVertexLastHasEdge = m.hasVertex() && lastMatch.hasEdge();
if ( lastMatch.isValid() && lastMatch.distance() <= m.distance() && !matchHasVertexLastHasEdge )
{
m = lastMatch;
}
}
snapUtils->setConfig( oldConfig );
mLastSnap.reset( new QgsPointLocator::Match( m ) );
return m;
}
bool QgsVertexTool::isNearEndpointMarker( const QgsPointXY &mapPoint )
{
if ( !mEndpointMarkerCenter )
return false;
double distMarker = std::sqrt( mEndpointMarkerCenter->sqrDist( mapPoint ) );
double tol = QgsTolerance::vertexSearchRadius( canvas()->mapSettings() );
QgsGeometry geom = cachedGeometryForVertex( *mMouseAtEndpoint );
QgsPointXY vertexPointV2 = geom.vertexAt( mMouseAtEndpoint->vertexId );
QgsPointXY vertexPoint = QgsPointXY( vertexPointV2.x(), vertexPointV2.y() );
double distVertex = std::sqrt( vertexPoint.sqrDist( mapPoint ) );
return distMarker < tol && distMarker < distVertex;
}
bool QgsVertexTool::isMatchAtEndpoint( const QgsPointLocator::Match &match )
{
QgsGeometry geom = cachedGeometry( match.layer(), match.featureId() );
if ( geom.type() != QgsWkbTypes::LineGeometry )
return false;
return isEndpointAtVertexIndex( geom, match.vertexIndex() );
}
QgsPointXY QgsVertexTool::positionForEndpointMarker( const QgsPointLocator::Match &match )
{
QgsGeometry geom = cachedGeometry( match.layer(), match.featureId() );
QgsPointXY pt0 = geom.vertexAt( adjacentVertexIndexToEndpoint( geom, match.vertexIndex() ) );
QgsPointXY pt1 = geom.vertexAt( match.vertexIndex() );
pt0 = toMapCoordinates( match.layer(), pt0 );
pt1 = toMapCoordinates( match.layer(), pt1 );
double dx = pt1.x() - pt0.x();
double dy = pt1.y() - pt0.y();
double dist = 15 * canvas()->mapSettings().mapUnitsPerPixel();
double angle = std::atan2( dy, dx ); // to the top: angle=0, to the right: angle=90, to the left: angle=-90
double x = pt1.x() + std::cos( angle ) * dist;
double y = pt1.y() + std::sin( angle ) * dist;
return QgsPointXY( x, y );
}
void QgsVertexTool::mouseMoveNotDragging( QgsMapMouseEvent *e )
{
if ( mMouseAtEndpoint )
{
// check if we are still at the endpoint, i.e. whether to keep showing
// the endpoint indicator - or go back to snapping to editable layers
QgsPointXY mapPoint = toMapCoordinates( e->pos() );
if ( isNearEndpointMarker( mapPoint ) )
{
mEndpointMarker->setColor( Qt::red );
mEndpointMarker->update();
// make it clear this would add endpoint, not move the vertex
mVertexBand->setVisible( false );
return;
}
}
// do not use snap from mouse event, use our own with any editable layer
QgsPointLocator::Match m = snapToEditableLayer( e );
mLastMouseMoveMatch = m;
// possibility to move a vertex
if ( m.type() == QgsPointLocator::Vertex )
{
updateVertexBand( m );
// if we are at an endpoint, let's show also the endpoint indicator
// so user can possibly add a new vertex at the end
if ( isMatchAtEndpoint( m ) )
{
mMouseAtEndpoint.reset( new Vertex( m.layer(), m.featureId(), m.vertexIndex() ) );
mEndpointMarkerCenter.reset( new QgsPointXY( positionForEndpointMarker( m ) ) );
mEndpointMarker->setCenter( *mEndpointMarkerCenter );
mEndpointMarker->setColor( Qt::gray );
mEndpointMarker->setVisible( true );
mEndpointMarker->update();
}
else
{
mMouseAtEndpoint.reset();
mEndpointMarkerCenter.reset();
mEndpointMarker->setVisible( false );
}
}
else
{
mVertexBand->setVisible( false );
mMouseAtEndpoint.reset();
mEndpointMarkerCenter.reset();
mEndpointMarker->setVisible( false );
}
// possibility to create new vertex here - or to move the edge
if ( m.type() == QgsPointLocator::Edge )
{
QgsPointXY mapPoint = toMapCoordinates( e->pos() );
bool isCircularEdge = false;
QgsPointXY p0, p1;
m.edgePoints( p0, p1 );
QgsGeometry geom = cachedGeometry( m.layer(), m.featureId() );
if ( isCircularVertex( geom, m.vertexIndex() ) )
{
// circular edge at the first vertex
isCircularEdge = true;
QgsPointXY pX = toMapCoordinates( m.layer(), geom.vertexAt( m.vertexIndex() - 1 ) );
QgsPointSequence points;
QgsGeometryUtils::segmentizeArc( QgsPoint( pX ), QgsPoint( p0 ), QgsPoint( p1 ), points );
mEdgeBand->reset();
for ( const QgsPoint &pt : qgis::as_const( points ) )
mEdgeBand->addPoint( pt );
}
else if ( isCircularVertex( geom, m.vertexIndex() + 1 ) )
{
// circular edge at the second vertex
isCircularEdge = true;
QgsPointXY pX = toMapCoordinates( m.layer(), geom.vertexAt( m.vertexIndex() + 2 ) );
QgsPointSequence points;
QgsGeometryUtils::segmentizeArc( QgsPoint( p0 ), QgsPoint( p1 ), QgsPoint( pX ), points );
mEdgeBand->reset();
for ( const QgsPoint &pt : qgis::as_const( points ) )
mEdgeBand->addPoint( pt );
}
else
{
// straight edge
QgsPolylineXY points;
points << p0 << p1;
mEdgeBand->setToGeometry( QgsGeometry::fromPolylineXY( points ), nullptr );
}
QgsPointXY edgeCenter;
bool isNearCenter = matchEdgeCenterTest( m, mapPoint, &edgeCenter );
mEdgeCenterMarker->setCenter( edgeCenter );
mEdgeCenterMarker->setColor( isNearCenter ? Qt::red : Qt::gray );
mEdgeCenterMarker->setVisible( !isCircularEdge ); // currently not supported for circular edges
mEdgeCenterMarker->update();
mEdgeBand->setVisible( !isNearCenter );
}
else
{
mEdgeCenterMarker->setVisible( false );
mEdgeBand->setVisible( false );
}
updateFeatureBand( m );
}
void QgsVertexTool::updateVertexBand( const QgsPointLocator::Match &m )
{
if ( m.hasVertex() && m.layer() )
{
mVertexBand->setToGeometry( QgsGeometry::fromPointXY( m.point() ), nullptr );
mVertexBand->setVisible( true );
bool isCircular = false;
if ( m.layer() )
{
isCircular = isCircularVertex( cachedGeometry( m.layer(), m.featureId() ), m.vertexIndex() );
}
mVertexBand->setIcon( isCircular ? QgsRubberBand::ICON_FULL_DIAMOND : QgsRubberBand::ICON_CIRCLE );
}
else
{
mVertexBand->setVisible( false );
}
}
void QgsVertexTool::updateFeatureBand( const QgsPointLocator::Match &m )
{
// highlight feature
if ( m.isValid() && m.layer() )
{
if ( mFeatureBandLayer == m.layer() && mFeatureBandFid == m.featureId() )
return; // skip regeneration of rubber band if not needed
QgsGeometry geom = cachedGeometry( m.layer(), m.featureId() );
mFeatureBandMarkers->setToGeometry( geometryToMultiPoint( geom ), m.layer() );
mFeatureBandMarkers->setVisible( true );
if ( QgsWkbTypes::isCurvedType( geom.wkbType() ) )
geom = QgsGeometry( geom.constGet()->segmentize() );
mFeatureBand->setToGeometry( geom, m.layer() );
mFeatureBand->setVisible( true );
mFeatureBandLayer = m.layer();
mFeatureBandFid = m.featureId();
}
else
{
mFeatureBand->setVisible( false );
mFeatureBandMarkers->setVisible( false );
mFeatureBandLayer = nullptr;
mFeatureBandFid = QgsFeatureId();
}
}
void QgsVertexTool::keyPressEvent( QKeyEvent *e )
{
if ( !mDraggingVertex && !mDraggingEdge && e->key() == Qt::Key_R && e->modifiers() & Qt::ShiftModifier )
{
startRangeVertexSelection();
return;
}
if ( mSelectionMethod == SelectionRange && e->key() == Qt::Key_Escape )
{
stopRangeVertexSelection();
return;
}
if ( !mDraggingVertex && mSelectedVertices.count() == 0 )
return;
if ( e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace )
{
e->ignore(); // Override default shortcut management
deleteVertex();
}
else if ( e->key() == Qt::Key_Escape )
{
if ( mDraggingVertex )
stopDragging();
}
else if ( e->key() == Qt::Key_Less || e->key() == Qt::Key_Comma )
{
highlightAdjacentVertex( -1 );
}
else if ( e->key() == Qt::Key_Greater || e->key() == Qt::Key_Period )
{
highlightAdjacentVertex( + 1 );
}
}
QgsGeometry QgsVertexTool::cachedGeometry( const QgsVectorLayer *layer, QgsFeatureId fid )
{
if ( !mCache.contains( layer ) )
{
connect( layer, &QgsVectorLayer::geometryChanged, this, &QgsVertexTool::onCachedGeometryChanged );
connect( layer, &QgsVectorLayer::featureDeleted, this, &QgsVertexTool::onCachedGeometryDeleted );
// TODO: also clear cache when layer is deleted
}
QHash<QgsFeatureId, QgsGeometry> &layerCache = mCache[layer];
if ( !layerCache.contains( fid ) )
{
QgsFeature f;
layer->getFeatures( QgsFeatureRequest( fid ).setSubsetOfAttributes( QgsAttributeList() ) ).nextFeature( f );
layerCache[fid] = f.geometry();
}
return layerCache[fid];
}
QgsGeometry QgsVertexTool::cachedGeometryForVertex( const Vertex &vertex )
{
return cachedGeometry( vertex.layer, vertex.fid );
}
void QgsVertexTool::onCachedGeometryChanged( QgsFeatureId fid, const QgsGeometry &geom )
{
QgsVectorLayer *layer = qobject_cast<QgsVectorLayer *>( sender() );
Q_ASSERT( mCache.contains( layer ) );
QHash<QgsFeatureId, QgsGeometry> &layerCache = mCache[layer];
if ( layerCache.contains( fid ) )
layerCache[fid] = geom;
// refresh highlighted vertices - their position may have changed
setHighlightedVertices( mSelectedVertices );
// re-run validation for the feature
validateGeometry( layer, fid );
}
void QgsVertexTool::onCachedGeometryDeleted( QgsFeatureId fid )
{
QgsVectorLayer *layer = qobject_cast<QgsVectorLayer *>( sender() );
Q_ASSERT( mCache.contains( layer ) );
QHash<QgsFeatureId, QgsGeometry> &layerCache = mCache[layer];
if ( layerCache.contains( fid ) )
layerCache.remove( fid );
// refresh highlighted vertices - some may have been deleted
setHighlightedVertices( mSelectedVertices );
}
void QgsVertexTool::showVertexEditor() //#spellok
{
QgsPointLocator::Match m = mLastMouseMoveMatch;
if ( !m.isValid() || !m.layer() )
return;
mSelectedFeature.reset( new QgsSelectedFeature( m.featureId(), m.layer(), mCanvas ) );
for ( int i = 0; i < mSelectedVertices.length(); ++i )
{
if ( mSelectedVertices.at( i ).layer == m.layer() && mSelectedVertices.at( i ).fid == m.featureId() )
{
mSelectedFeature->selectVertex( mSelectedVertices.at( i ).vertexId );
}
}
if ( !mVertexEditor )
{
mVertexEditor.reset( new QgsVertexEditor( m.layer(), mSelectedFeature.get(), mCanvas ) );
QgisApp::instance()->addDockWidget( Qt::LeftDockWidgetArea, mVertexEditor.get() );
connect( mVertexEditor.get(), &QgsVertexEditor::deleteSelectedRequested, this, &QgsVertexTool::deleteVertexEditorSelection );
connect( mVertexEditor.get(), &QgsVertexEditor::editorClosed, this, &QgsVertexTool::cleanupVertexEditor );
}
else
{
mVertexEditor->updateEditor( m.layer(), mSelectedFeature.get() );
}
connect( mSelectedFeature.get()->layer(), &QgsVectorLayer::featureDeleted, this, &QgsVertexTool::cleanEditor );
}
void QgsVertexTool::cleanupVertexEditor()
{
mSelectedFeature.reset();
mVertexEditor.reset();
}
static int _firstSelectedVertex( QgsSelectedFeature &selectedFeature )
{
QList<QgsVertexEntry *> &vertexMap = selectedFeature.vertexMap();
for ( int i = 0, n = vertexMap.size(); i < n; ++i )
{
if ( vertexMap[i]->isSelected() )
{
return i;
}
}
return -1;
}
static void _safeSelectVertex( QgsSelectedFeature &selectedFeature, int vertexNr )
{
int n = selectedFeature.vertexMap().size();
selectedFeature.selectVertex( ( vertexNr + n ) % n );
}
void QgsVertexTool::deleteVertexEditorSelection()
{
if ( !mSelectedFeature )
return;
int firstSelectedIndex = _firstSelectedVertex( *mSelectedFeature );
if ( firstSelectedIndex == -1 )
return;
// make a list of selected vertices
QList<Vertex> vertices;
QList<QgsVertexEntry *> &selFeatureVertices = mSelectedFeature->vertexMap();
QgsVectorLayer *layer = mSelectedFeature->layer();
QgsFeatureId fid = mSelectedFeature->featureId();
QgsGeometry geometry = cachedGeometry( layer, fid );
for ( QgsVertexEntry *vertex : qgis::as_const( selFeatureVertices ) )
{
if ( vertex->isSelected() )
{
int vertexIndex = geometry.vertexNrFromVertexId( vertex->vertexId() );
if ( vertexIndex != -1 )
vertices.append( Vertex( layer, fid, vertexIndex ) );
}
}
// now select the vertices and delete them...
setHighlightedVertices( vertices );
deleteVertex();
if ( !mSelectedFeature->geometry()->isNull() )
{
int nextVertexToSelect = firstSelectedIndex;
if ( mSelectedFeature->geometry()->type() == QgsWkbTypes::LineGeometry )
{
// for lines we don't wrap around vertex selection when deleting vertices from end of line
nextVertexToSelect = std::min( nextVertexToSelect, mSelectedFeature->geometry()->constGet()->nCoordinates() - 1 );
}
_safeSelectVertex( *mSelectedFeature, nextVertexToSelect );
}
mSelectedFeature->layer()->triggerRepaint();
}
void QgsVertexTool::startDragging( QgsMapMouseEvent *e )
{
QgsPointXY mapPoint = toMapCoordinates( e->pos() );
if ( isNearEndpointMarker( mapPoint ) )
{
startDraggingAddVertexAtEndpoint( mapPoint );
return;
}
QgsPointLocator::Match m = snapToEditableLayer( e );
if ( !m.isValid() )
return;
// activate advanced digitizing dock
setAdvancedDigitizingAllowed( true );
// adding a new vertex instead of moving a vertex
if ( m.hasEdge() )
{
// only start dragging if we are near edge center
mapPoint = toMapCoordinates( e->pos() );
bool isNearCenter = matchEdgeCenterTest( m, mapPoint );
if ( isNearCenter )
startDraggingAddVertex( m );
else
startDraggingEdge( m, mapPoint );
}
else // vertex
{
startDraggingMoveVertex( m );
}
}
void QgsVertexTool::startDraggingMoveVertex( const QgsPointLocator::Match &m )
{
Q_ASSERT( m.hasVertex() );
QgsGeometry geom = cachedGeometry( m.layer(), m.featureId() );
// start dragging of snapped point of current layer
mDraggingVertex.reset( new Vertex( m.layer(), m.featureId(), m.vertexIndex() ) );
mDraggingVertexType = MovingVertex;
mDraggingExtraVertices.clear();
mDraggingExtraVerticesOffset.clear();
setHighlightedVerticesVisible( false ); // hide any extra highlight of vertices until we are done with moving
QgsPointXY origDraggingVertexPoint = geom.vertexAt( mDraggingVertex->vertexId );
// if there are other highlighted vertices, they should be dragged as well with their offset
for ( const Vertex &v : qgis::as_const( mSelectedVertices ) )
{
if ( v != *mDraggingVertex )
{
QgsPointXY origPointV = cachedGeometryForVertex( v ).vertexAt( v.vertexId );
QgsPointXY origPointLayer = origDraggingVertexPoint;
if ( v.layer->crs() != mDraggingVertex->layer->crs() ) // reproject if necessary
origPointLayer = toLayerCoordinates( v.layer, toMapCoordinates( m.layer(), origDraggingVertexPoint ) );
QgsVector offset = origPointV - origPointLayer;
mDraggingExtraVertices << v;
mDraggingExtraVerticesOffset << offset;
}
}
cadDockWidget()->setPoints( QList<QgsPointXY>() << m.point() << m.point() );
if ( QgsProject::instance()->topologicalEditing() )
{
// support for topo editing - find extra features
// that have coincident point with the vertex being dragged
const auto layers = canvas()->layers();
for ( QgsMapLayer *layer : layers )
{
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
if ( !vlayer || !vlayer->isEditable() )
continue;
const auto snappedVertices = layerVerticesSnappedToPoint( vlayer, m.point() );
for ( const QgsPointLocator::Match &otherMatch : snappedVertices )
{
if ( otherMatch.layer() == m.layer() &&
otherMatch.featureId() == m.featureId() &&
otherMatch.vertexIndex() == m.vertexIndex() )
continue;
// start dragging of snapped point of current layer
mDraggingExtraVertices << Vertex( otherMatch.layer(), otherMatch.featureId(), otherMatch.vertexIndex() );
mDraggingExtraVerticesOffset << QgsVector(); // topo vertices have the same position
}
}
}
// now build drag rubber bands for extra vertices
QSet<Vertex> movingVertices;
movingVertices << *mDraggingVertex;
for ( const Vertex &v : qgis::as_const( mDraggingExtraVertices ) )
movingVertices << v;
QgsPointXY dragVertexMapPoint = m.point();
buildDragBandsForVertices( movingVertices, dragVertexMapPoint );
}
void QgsVertexTool::buildDragBandsForVertices( const QSet<Vertex> &movingVertices, const QgsPointXY &dragVertexMapPoint )
{
QSet<Vertex> verticesInStraightBands; // always the vertex with lower index
// set of middle vertices that are already in a circular rubber band
// i.e. every circular band is defined by its middle circular vertex
QSet<Vertex> verticesInCircularBands;
for ( const Vertex &v : qgis::as_const( movingVertices ) )
{
int v0idx, v1idx;
QgsGeometry geom = cachedGeometry( v.layer, v.fid );
QgsPointXY pt = geom.vertexAt( v.vertexId );
geom.adjacentVertices( v.vertexId, v0idx, v1idx );
if ( v0idx != -1 && v1idx != -1 && isCircularVertex( geom, v.vertexId ) )
{
// the vertex is in the middle of a curved segment
if ( !verticesInCircularBands.contains( v ) )
{
addDragCircularBand( v.layer,
geom.vertexAt( v0idx ),
pt,
geom.vertexAt( v1idx ),
movingVertices.contains( Vertex( v.layer, v.fid, v0idx ) ),
true,
movingVertices.contains( Vertex( v.layer, v.fid, v1idx ) ),
dragVertexMapPoint );
verticesInCircularBands << v;
}
// skip the rest - no need for further straight of circular bands for this vertex
// because our circular rubber band spans both towards left and right
continue;
}
if ( v0idx != -1 )
{
// there is another vertex to the left - let's build a rubber band for it
Vertex v0( v.layer, v.fid, v0idx );
if ( isCircularVertex( geom, v0idx ) )
{
// circular segment to the left
if ( !verticesInCircularBands.contains( v0 ) )
{
addDragCircularBand( v.layer,
geom.vertexAt( v0idx - 1 ),
geom.vertexAt( v0idx ),
pt,
movingVertices.contains( Vertex( v.layer, v.fid, v0idx - 1 ) ),
movingVertices.contains( Vertex( v.layer, v.fid, v0idx ) ),
true,
dragVertexMapPoint );
verticesInCircularBands << v0;
}
}
else
{
// straight segment to the left
if ( !verticesInStraightBands.contains( v0 ) )
{
addDragStraightBand( v.layer,
geom.vertexAt( v0idx ),
pt,
movingVertices.contains( v0 ),
true,
dragVertexMapPoint );
verticesInStraightBands << v0;
}
}
}
if ( v1idx != -1 )
{
// there is another vertex to the right - let's build a rubber band for it
Vertex v1( v.layer, v.fid, v1idx );
if ( isCircularVertex( geom, v1idx ) )
{
// circular segment to the right
if ( !verticesInCircularBands.contains( v1 ) )
{
addDragCircularBand( v.layer,
pt,
geom.vertexAt( v1idx ),
geom.vertexAt( v1idx + 1 ),
true,
movingVertices.contains( v1 ),
movingVertices.contains( Vertex( v.layer, v.fid, v1idx + 1 ) ),
dragVertexMapPoint );
verticesInCircularBands << v1;
}
}
else
{
// straight segment to the right
if ( !verticesInStraightBands.contains( v ) )
{
addDragStraightBand( v.layer,
pt,
geom.vertexAt( v1idx ),
true,
movingVertices.contains( v1 ),
dragVertexMapPoint );
verticesInStraightBands << v;
}
}
}
if ( v0idx == -1 && v1idx == -1 )
{
// this is a standalone point - we need to use a marker for it
// to give some feedback to the user
QgsPointXY ptMapPoint = toMapCoordinates( v.layer, pt );
QgsVertexMarker *marker = new QgsVertexMarker( mCanvas );
marker->setIconType( QgsVertexMarker::ICON_X );
marker->setColor( Qt::red );
marker->setPenWidth( 3 );
marker->setVisible( true );
marker->setCenter( ptMapPoint );
mDragPointMarkers << marker;
mDragPointMarkersOffset << ( ptMapPoint - dragVertexMapPoint );
}
}
}
QList<QgsPointLocator::Match> QgsVertexTool::layerVerticesSnappedToPoint( QgsVectorLayer *layer, const QgsPointXY &mapPoint )
{
MatchCollectingFilter myfilter( this );
QgsPointLocator *loc = canvas()->snappingUtils()->locatorForLayer( layer );
loc->nearestVertex( mapPoint, 0, &myfilter );
return myfilter.matches;
}
void QgsVertexTool::startDraggingAddVertex( const QgsPointLocator::Match &m )
{
Q_ASSERT( m.hasEdge() );
// activate advanced digitizing dock
setAdvancedDigitizingAllowed( true );
mDraggingVertex.reset( new Vertex( m.layer(), m.featureId(), m.vertexIndex() + 1 ) );
mDraggingVertexType = AddingVertex;
mDraggingExtraVertices.clear();
mDraggingExtraVerticesOffset.clear();
QgsGeometry geom = cachedGeometry( m.layer(), m.featureId() );
// TODO: handles rings correctly?
QgsPointXY v0 = geom.vertexAt( m.vertexIndex() );
QgsPointXY v1 = geom.vertexAt( m.vertexIndex() + 1 );
QgsPointXY map_v0 = toMapCoordinates( m.layer(), v0 );
QgsPointXY map_v1 = toMapCoordinates( m.layer(), v1 );
if ( v0.x() != 0 || v0.y() != 0 )
addDragBand( map_v0, m.point() );
if ( v1.x() != 0 || v1.y() != 0 )
addDragBand( map_v1, m.point() );
cadDockWidget()->setPoints( QList<QgsPointXY>() << m.point() << m.point() );
}
void QgsVertexTool::startDraggingAddVertexAtEndpoint( const QgsPointXY &mapPoint )
{
Q_ASSERT( mMouseAtEndpoint );
// activate advanced digitizing dock
setAdvancedDigitizingAllowed( true );
mDraggingVertex.reset( new Vertex( mMouseAtEndpoint->layer, mMouseAtEndpoint->fid, mMouseAtEndpoint->vertexId ) );
mDraggingVertexType = AddingEndpoint;
mDraggingExtraVertices.clear();
mDraggingExtraVerticesOffset.clear();
QgsGeometry geom = cachedGeometry( mMouseAtEndpoint->layer, mMouseAtEndpoint->fid );
QgsPointXY v0 = geom.vertexAt( mMouseAtEndpoint->vertexId );
QgsPointXY map_v0 = toMapCoordinates( mMouseAtEndpoint->layer, v0 );
addDragBand( map_v0, mapPoint );
// setup CAD dock previous points to endpoint and the previous point
QgsPointXY pt0 = geom.vertexAt( adjacentVertexIndexToEndpoint( geom, mMouseAtEndpoint->vertexId ) );
QgsPointXY pt1 = geom.vertexAt( mMouseAtEndpoint->vertexId );
cadDockWidget()->setPoints( QList<QgsPointXY>() << pt0 << pt1 << pt1 );
}
void QgsVertexTool::startDraggingEdge( const QgsPointLocator::Match &m, const QgsPointXY &mapPoint )
{
Q_ASSERT( m.hasEdge() );
// activate advanced digitizing
setAdvancedDigitizingAllowed( true );
mDraggingEdge = true;
mDraggingExtraVertices.clear();
mDraggingExtraVerticesOffset.clear();
QgsGeometry geom = cachedGeometry( m.layer(), m.featureId() );
QSet<Vertex> movingVertices;
movingVertices << Vertex( m.layer(), m.featureId(), m.vertexIndex() );
movingVertices << Vertex( m.layer(), m.featureId(), m.vertexIndex() + 1 );
// add an extra vertex if it is circular edge - so that we move the whole edge and not just one part of it
if ( isCircularVertex( geom, m.vertexIndex() ) )
{
movingVertices << Vertex( m.layer(), m.featureId(), m.vertexIndex() - 1 );
}
else if ( isCircularVertex( geom, m.vertexIndex() + 1 ) )
{
movingVertices << Vertex( m.layer(), m.featureId(), m.vertexIndex() + 2 );
}
buildDragBandsForVertices( movingVertices, mapPoint );
QgsPointXY layerPoint = toLayerCoordinates( m.layer(), mapPoint );
for ( const Vertex &v : qgis::as_const( movingVertices ) )
{
mDraggingExtraVertices << v;
mDraggingExtraVerticesOffset << ( geom.vertexAt( v.vertexId ) - QgsPoint( layerPoint ) );
}
cadDockWidget()->setPoints( QList<QgsPointXY>() << m.point() << m.point() );
}
void QgsVertexTool::stopDragging()
{
// deactivate advanced digitizing
setAdvancedDigitizingAllowed( false );
cadDockWidget()->clear(); // clear cad points and release locks
mDraggingVertex.reset();
mDraggingVertexType = NotDragging;
mDraggingEdge = false;
clearDragBands();
setHighlightedVerticesVisible( true ); // highlight can be shown again
mSnapIndicator->setMatch( QgsPointLocator::Match() );
}
QgsPointXY QgsVertexTool::matchToLayerPoint( const QgsVectorLayer *destLayer, const QgsPointXY &mapPoint, const QgsPointLocator::Match *match )
{
// try to use point coordinates in the original CRS if it is the same
if ( match && match->hasVertex() && match->layer() && match->layer()->crs() == destLayer->crs() )
{
QgsFeature f;
QgsFeatureIterator fi = match->layer()->getFeatures( QgsFeatureRequest( match->featureId() ).setSubsetOfAttributes( QgsAttributeList() ) );
if ( fi.nextFeature( f ) )
return f.geometry().vertexAt( match->vertexIndex() );
}
// fall back to reprojection of the map point to layer point if they are not the same CRS
return toLayerCoordinates( destLayer, mapPoint );
}
void QgsVertexTool::moveEdge( const QgsPointXY &mapPoint )
{
stopDragging();
VertexEdits edits;
addExtraVerticesToEdits( edits, mapPoint );
applyEditsToLayers( edits );
}
void QgsVertexTool::moveVertex( const QgsPointXY &mapPoint, const QgsPointLocator::Match *mapPointMatch )
{
// deactivate advanced digitizing
setAdvancedDigitizingAllowed( false );
QgsVectorLayer *dragLayer = mDraggingVertex->layer;
QgsFeatureId dragFid = mDraggingVertex->fid;
int dragVertexId = mDraggingVertex->vertexId;
bool addingVertex = mDraggingVertexType == AddingVertex || mDraggingVertexType == AddingEndpoint;
bool addingAtEndpoint = mDraggingVertexType == AddingEndpoint;
QgsGeometry geom = cachedGeometryForVertex( *mDraggingVertex );
stopDragging();
QgsPointXY layerPoint = matchToLayerPoint( dragLayer, mapPoint, mapPointMatch );
QgsVertexId vid;
if ( !geom.vertexIdFromVertexNr( dragVertexId, vid ) )
{
QgsDebugMsg( "invalid vertex index" );
return;
}
QgsAbstractGeometry *geomTmp = geom.constGet()->clone();
// add/move vertex
if ( addingVertex )
{
if ( addingAtEndpoint && vid.vertex != 0 ) // appending?
vid.vertex++;
QgsPoint pt( layerPoint );
if ( QgsWkbTypes::hasZ( dragLayer->wkbType() ) )
pt.addZValue( defaultZValue() );
if ( !geomTmp->insertVertex( vid, pt ) )
{
QgsDebugMsg( "append vertex failed!" );
return;
}
}
else
{
if ( !geomTmp->moveVertex( vid, QgsPoint( layerPoint ) ) )
{
QgsDebugMsg( "move vertex failed!" );
return;
}
}
geom.set( geomTmp );
VertexEdits edits; // dict { layer : { fid : geom } }
edits[dragLayer][dragFid] = geom;
addExtraVerticesToEdits( edits, mapPoint, dragLayer, layerPoint );
applyEditsToLayers( edits );
if ( QgsProject::instance()->topologicalEditing() && mapPointMatch->hasEdge() && mapPointMatch->layer() )
{
// topo editing: add vertex to existing segments when moving/adding a vertex to such segment.
// this requires that the snapping match is to a segment and the segment layer's CRS
// is the same (otherwise we would need to reproject the point and it will not be coincident)
const auto editKeys = edits.keys();
for ( QgsVectorLayer *layer : editKeys )
{
if ( layer->crs() == mapPointMatch->layer()->crs() )
{
layer->addTopologicalPoints( layerPoint );
}
}
}
setHighlightedVertices( mSelectedVertices ); // update positions of existing highlighted vertices
setHighlightedVerticesVisible( true ); // time to show highlighted vertices again
}
void QgsVertexTool::addExtraVerticesToEdits( QgsVertexTool::VertexEdits &edits, const QgsPointXY &mapPoint, QgsVectorLayer *dragLayer, const QgsPointXY &layerPoint )
{
Q_ASSERT( mDraggingExtraVertices.count() == mDraggingExtraVerticesOffset.count() );
// add moved vertices from other layers
for ( int i = 0; i < mDraggingExtraVertices.count(); ++i )
{
const Vertex &topo = mDraggingExtraVertices[i];
const QgsVector &offset = mDraggingExtraVerticesOffset[i];
QHash<QgsFeatureId, QgsGeometry> &layerEdits = edits[topo.layer];
QgsGeometry topoGeom;
if ( layerEdits.contains( topo.fid ) )
topoGeom = QgsGeometry( edits[topo.layer][topo.fid] );
else
topoGeom = QgsGeometry( cachedGeometryForVertex( topo ) );
QgsPointXY point;
if ( dragLayer && topo.layer->crs() == dragLayer->crs() )
point = layerPoint; // this point may come from exact match so it may be more precise
else
point = toLayerCoordinates( topo.layer, mapPoint );
if ( offset.x() || offset.y() )
{
point += offset;
}
if ( !topoGeom.moveVertex( point.x(), point.y(), topo.vertexId ) )
{
QgsDebugMsg( "[topo] move vertex failed!" );
continue;
}
edits[topo.layer][topo.fid] = topoGeom;
}
}
void QgsVertexTool::applyEditsToLayers( QgsVertexTool::VertexEdits &edits )
{
QHash<QgsVectorLayer *, QHash<QgsFeatureId, QgsGeometry> >::iterator it = edits.begin();
for ( ; it != edits.end(); ++it )
{
QgsVectorLayer *layer = it.key();
QHash<QgsFeatureId, QgsGeometry> &layerEdits = it.value();
layer->beginEditCommand( tr( "Moved vertex" ) );
QHash<QgsFeatureId, QgsGeometry>::iterator it2 = layerEdits.begin();
for ( ; it2 != layerEdits.end(); ++it2 )
layer->changeGeometry( it2.key(), it2.value() );
layer->endEditCommand();
layer->triggerRepaint();
}
}
void QgsVertexTool::deleteVertex()
{
QSet<Vertex> toDelete;
if ( !mSelectedVertices.isEmpty() )
{
toDelete = QSet<Vertex>::fromList( mSelectedVertices );
}
else
{
bool addingVertex = mDraggingVertexType == AddingVertex || mDraggingVertexType == AddingEndpoint;
toDelete << *mDraggingVertex;
toDelete += QSet<Vertex>::fromList( mDraggingExtraVertices );
if ( addingVertex )
{
stopDragging();
return; // just cancel the vertex
}
}
stopDragging();
setHighlightedVertices( QList<Vertex>() ); // reset selection
if ( QgsProject::instance()->topologicalEditing() )
{
// if topo editing is enabled, delete all the vertices that are on the same location
QSet<Vertex> topoVerticesToDelete;
for ( const Vertex &vertexToDelete : qgis::as_const( toDelete ) )
{
QgsPointXY layerPt = cachedGeometryForVertex( vertexToDelete ).vertexAt( vertexToDelete.vertexId );
QgsPointXY mapPt = toMapCoordinates( vertexToDelete.layer, layerPt );
const auto snappedVertices = layerVerticesSnappedToPoint( vertexToDelete.layer, mapPt );
for ( const QgsPointLocator::Match &otherMatch : snappedVertices )
{
Vertex otherVertex( otherMatch.layer(), otherMatch.featureId(), otherMatch.vertexIndex() );
if ( toDelete.contains( otherVertex ) || topoVerticesToDelete.contains( otherVertex ) )
continue;
topoVerticesToDelete.insert( otherVertex );
}
}
toDelete.unite( topoVerticesToDelete );
}
// switch from a plain list to dictionary { layer: { fid: [vertexNr1, vertexNr2, ...] } }
QHash<QgsVectorLayer *, QHash<QgsFeatureId, QList<int> > > toDeleteGrouped;
for ( const Vertex &vertex : qgis::as_const( toDelete ) )
{
toDeleteGrouped[vertex.layer][vertex.fid].append( vertex.vertexId );
}
// de-duplicate vertices in linear rings - if there is the first vertex selected,
// then also the last vertex will be selected - but we want just one out of the pair
QHash<QgsVectorLayer *, QHash<QgsFeatureId, QList<int> > >::iterator itX = toDeleteGrouped.begin();
for ( ; itX != toDeleteGrouped.end(); ++itX )
{
QgsVectorLayer *layer = itX.key();
QHash<QgsFeatureId, QList<int> > &featuresDict = itX.value();
QHash<QgsFeatureId, QList<int> >::iterator it2 = featuresDict.begin();
for ( ; it2 != featuresDict.end(); ++it2 )
{
QgsFeatureId fid = it2.key();
QList<int> &vertexIds = it2.value();
if ( vertexIds.count() >= 2 && layer->geometryType() == QgsWkbTypes::PolygonGeometry )
{
QSet<int> duplicateVertexIndices;
QgsGeometry geom = cachedGeometry( layer, fid );
for ( int i = 0; i < vertexIds.count(); ++i )
{
QgsVertexId vid;
if ( geom.vertexIdFromVertexNr( vertexIds[i], vid ) )
{
int ringVertexCount = geom.constGet()->vertexCount( vid.part, vid.ring );
if ( vid.vertex == ringVertexCount - 1 )
{
// this is the last vertex of the ring - remove the first vertex from the list
duplicateVertexIndices << geom.vertexNrFromVertexId( QgsVertexId( vid.part, vid.ring, 0 ) );
}
}
}
// now delete the duplicities
for ( int duplicateVertexIndex : qgis::as_const( duplicateVertexIndices ) )
vertexIds.removeOne( duplicateVertexIndex );
}
}
}
// main for cycle to delete all selected vertices
QHash<QgsVectorLayer *, QHash<QgsFeatureId, QList<int> > >::iterator it = toDeleteGrouped.begin();
for ( ; it != toDeleteGrouped.end(); ++it )
{
QgsVectorLayer *layer = it.key();
QHash<QgsFeatureId, QList<int> > &featuresDict = it.value();
layer->beginEditCommand( tr( "Deleted vertex" ) );
bool success = true;
QHash<QgsFeatureId, QList<int> >::iterator it2 = featuresDict.begin();
for ( ; it2 != featuresDict.end(); ++it2 )
{
QgsFeatureId fid = it2.key();
QList<int> &vertexIds = it2.value();
bool res = QgsVectorLayer::Success;
std::sort( vertexIds.begin(), vertexIds.end(), std::greater<int>() );
for ( int vertexId : vertexIds )
{
if ( res != QgsVectorLayer::EmptyGeometry )
res = layer->deleteVertex( fid, vertexId );
if ( res != QgsVectorLayer::EmptyGeometry && res != QgsVectorLayer::Success )
{
QgsDebugMsg( QString( "failed to delete vertex %1 %2 %3!" ).arg( layer->name() ).arg( fid ).arg( vertexId ) );
success = false;
}
}
if ( res == QgsVectorLayer::EmptyGeometry )
{
emit messageEmitted( tr( "Geometry has been cleared. Use the add part tool to set geometry for this feature." ) );
}
}
if ( success )
{
layer->endEditCommand();
layer->triggerRepaint();
}
else
layer->destroyEditCommand();
}
// make sure the temporary feature rubber band is not visible
removeTemporaryRubberBands();
// pre-select next vertex for deletion if we are deleting just one vertex
if ( toDelete.count() == 1 )
{
const Vertex &vertex = *toDelete.constBegin();
QgsGeometry geom( cachedGeometryForVertex( vertex ) );
int vertexId = vertex.vertexId;
// if next vertex is not available, use the previous one
if ( geom.vertexAt( vertexId ) == QgsPoint() )
vertexId -= 1;
if ( geom.vertexAt( vertexId ) != QgsPoint() )
{
QList<Vertex> vertices_new;
vertices_new << Vertex( vertex.layer, vertex.fid, vertexId );
setHighlightedVertices( vertices_new );
}
}
}
void QgsVertexTool::setHighlightedVertices( const QList<Vertex> &listVertices, HighlightMode mode )
{
if ( mode == ModeReset )
{
qDeleteAll( mSelectedVerticesMarkers );
mSelectedVerticesMarkers.clear();
mSelectedVertices.clear();
}
else if ( mode == ModeSubtract )
{
// need to clear vertex markers, and rebuild later. We have no way to link
// a marker to a vertex in order to remove one-by-one
qDeleteAll( mSelectedVerticesMarkers );
mSelectedVerticesMarkers.clear();
}
auto createMarkerForVertex = [ = ]( const Vertex & vertex )->bool
{
QgsGeometry geom = cachedGeometryForVertex( vertex );
QgsVertexId vid;
if ( !geom.vertexIdFromVertexNr( vertex.vertexId, vid ) )
return false; // vertex may not exist anymore
QgsVertexMarker *marker = new QgsVertexMarker( canvas() );
marker->setIconType( QgsVertexMarker::ICON_CIRCLE );
marker->setPenWidth( 3 );
marker->setColor( Qt::blue );
marker->setFillColor( Qt::blue );
marker->setCenter( toMapCoordinates( vertex.layer, geom.vertexAt( vertex.vertexId ) ) );
mSelectedVerticesMarkers.append( marker );
return true;
};
for ( const Vertex &vertex : listVertices )
{
if ( mode == ModeAdd && mSelectedVertices.contains( vertex ) )
{
continue;
}
else if ( mode == ModeSubtract )
{
mSelectedVertices.removeAll( vertex );
continue;
}
if ( !createMarkerForVertex( vertex ) )
continue; // vertex may not exist anymore
mSelectedVertices.append( vertex );
}
if ( mode == ModeSubtract )
{
// rebuild markers for remaining selection
for ( const Vertex &vertex : qgis::as_const( mSelectedVertices ) )
{
createMarkerForVertex( vertex );
}
}
}
void QgsVertexTool::setHighlightedVerticesVisible( bool visible )
{
for ( QgsVertexMarker *marker : qgis::as_const( mSelectedVerticesMarkers ) )
marker->setVisible( visible );
}
void QgsVertexTool::highlightAdjacentVertex( double offset )
{
if ( mSelectedVertices.isEmpty() )
return;
Vertex vertex = mSelectedVertices[0]; // simply use the first one
QgsGeometry geom = cachedGeometryForVertex( vertex );
// try to wrap around polygon rings
int newVertexId, v0idx, v1idx;
geom.adjacentVertices( vertex.vertexId, v0idx, v1idx );
if ( offset == -1 && v0idx != -1 )
newVertexId = v0idx;
else if ( offset == 1 && v1idx != -1 )
newVertexId = v1idx;
else
newVertexId = vertex.vertexId + offset;
QgsPointXY pt = geom.vertexAt( newVertexId );
if ( pt != QgsPointXY() )
vertex = Vertex( vertex.layer, vertex.fid, newVertexId );
setHighlightedVertices( QList<Vertex>() << vertex );
zoomToVertex( vertex ); // make sure the vertex is visible
}
void QgsVertexTool::startSelectionRect( const QPoint &point0 )
{
Q_ASSERT( !mSelectionRect );
mSelectionRect.reset( new QRect() );
mSelectionRect->setTopLeft( point0 );
mSelectionRectItem = new QRubberBand( QRubberBand::Rectangle, canvas() );
}
void QgsVertexTool::updateSelectionRect( const QPoint &point1 )
{
Q_ASSERT( mSelectionRect );
mSelectionRect->setBottomRight( point1 );
mSelectionRectItem->setGeometry( mSelectionRect->normalized() );
mSelectionRectItem->show();
}
void QgsVertexTool::stopSelectionRect()
{
Q_ASSERT( mSelectionRect );
mSelectionRectItem->deleteLater();
mSelectionRectItem = nullptr;
mSelectionRect.reset();
}
bool QgsVertexTool::matchEdgeCenterTest( const QgsPointLocator::Match &m, const QgsPointXY &mapPoint, QgsPointXY *edgeCenterPtr )
{
QgsPointXY p0, p1;
m.edgePoints( p0, p1 );
QgsGeometry geom = cachedGeometry( m.layer(), m.featureId() );
if ( isCircularVertex( geom, m.vertexIndex() ) || isCircularVertex( geom, m.vertexIndex() + 1 ) )
return false; // currently not supported for circular edges
QgsRectangle visible_extent = canvas()->mapSettings().visibleExtent();
if ( !visible_extent.contains( p0 ) || !visible_extent.contains( p1 ) )
{
// clip line segment to the extent so the mid-point marker is always visible
QgsGeometry extentGeom = QgsGeometry::fromRect( visible_extent );
QgsGeometry lineGeom = QgsGeometry::fromPolylineXY( QgsPolylineXY() << p0 << p1 );
lineGeom = extentGeom.intersection( lineGeom );
QgsPolylineXY polyline = lineGeom.asPolyline();
Q_ASSERT( polyline.count() == 2 );
p0 = polyline[0];
p1 = polyline[1];
}
QgsPointXY edgeCenter( ( p0.x() + p1.x() ) / 2, ( p0.y() + p1.y() ) / 2 );
if ( edgeCenterPtr )
*edgeCenterPtr = edgeCenter;
double distFromEdgeCenter = std::sqrt( mapPoint.sqrDist( edgeCenter ) );
double tol = QgsTolerance::vertexSearchRadius( canvas()->mapSettings() );
bool isNearCenter = distFromEdgeCenter < tol;
return isNearCenter;
}
void QgsVertexTool::CircularBand::updateRubberBand( const QgsPointXY &mapPoint )
{
QgsPointSequence points;
QgsPointXY v0 = moving0 ? mapPoint + offset0 : p0;
QgsPointXY v1 = moving1 ? mapPoint + offset1 : p1;
QgsPointXY v2 = moving2 ? mapPoint + offset2 : p2;
QgsGeometryUtils::segmentizeArc( QgsPoint( v0 ), QgsPoint( v1 ), QgsPoint( v2 ), points );
// it would be useful to have QgsRubberBand::setPoints() call
band->reset();
for ( const QgsPoint &p : qgis::as_const( points ) )
band->addPoint( p );
}
void QgsVertexTool::validationErrorFound( const QgsGeometry::Error &e )
{
QgsGeometryValidator *validator = qobject_cast<QgsGeometryValidator *>( sender() );
if ( !validator )
return;
QHash< QPair<QgsVectorLayer *, QgsFeatureId>, GeometryValidation>::iterator it = mValidations.begin();
for ( ; it != mValidations.end(); ++it )
{
GeometryValidation &validation = *it;
if ( validation.validator == validator )
{
validation.addError( e );
break;
}
}
}
void QgsVertexTool::validationFinished()
{
QgsGeometryValidator *validator = qobject_cast<QgsGeometryValidator *>( sender() );
if ( !validator )
return;
QHash< QPair<QgsVectorLayer *, QgsFeatureId>, GeometryValidation>::iterator it = mValidations.begin();
for ( ; it != mValidations.end(); ++it )
{
GeometryValidation &validation = *it;
if ( validation.validator == validator )
{
QgsStatusBar *sb = QgisApp::instance()->statusBarIface();
sb->showMessage( tr( "Validation finished (%n error(s) found).", "number of geometry errors", validation.errorMarkers.size() ) );
if ( validation.errorMarkers.isEmpty() )
{
// not needed anymore (no markers to keep displayed)
validation.cleanup();
mValidations.remove( it.key() );
}
break;
}
}
}
void QgsVertexTool::GeometryValidation::start( QgsGeometry &geom, QgsVertexTool *t, QgsVectorLayer *l )
{
tool = t;
layer = l;
QgsGeometry::ValidationMethod method = QgsGeometry::ValidatorQgisInternal;
QgsSettings settings;
if ( settings.value( QStringLiteral( "qgis/digitizing/validate_geometries" ), 1 ).toInt() == 2 )
method = QgsGeometry::ValidatorGeos;
validator = new QgsGeometryValidator( geom, nullptr, method );
connect( validator, &QgsGeometryValidator::errorFound, tool, &QgsVertexTool::validationErrorFound );
connect( validator, &QThread::finished, tool, &QgsVertexTool::validationFinished );
validator->start();
}
void QgsVertexTool::GeometryValidation::addError( QgsGeometry::Error e )
{
if ( !errors.isEmpty() )
errors += '\n';
errors += e.what();
if ( e.hasWhere() )
{
QgsVertexMarker *marker = new QgsVertexMarker( tool->canvas() );
marker->setCenter( tool->canvas()->mapSettings().layerToMapCoordinates( layer, e.where() ) );
marker->setIconType( QgsVertexMarker::ICON_X );
marker->setColor( Qt::green );
marker->setZValue( marker->zValue() + 1 );
marker->setPenWidth( 2 );
marker->setToolTip( e.what() );
errorMarkers << marker;
}
QgsStatusBar *sb = QgisApp::instance()->statusBarIface();
sb->showMessage( e.what() );
sb->setToolTip( errors );
}
void QgsVertexTool::GeometryValidation::cleanup()
{
if ( validator )
{
validator->stop();
validator->wait();
validator->deleteLater();
validator = nullptr;
}
qDeleteAll( errorMarkers );
errorMarkers.clear();
}
void QgsVertexTool::validateGeometry( QgsVectorLayer *layer, QgsFeatureId featureId )
{
QgsSettings settings;
if ( settings.value( QStringLiteral( "qgis/digitizing/validate_geometries" ), 1 ).toInt() == 0 )
return;
QPair<QgsVectorLayer *, QgsFeatureId> id( layer, featureId );
if ( mValidations.contains( id ) )
{
mValidations[id].cleanup();
mValidations.remove( id );
}
GeometryValidation validation;
QgsGeometry geom = cachedGeometry( layer, featureId );
validation.start( geom, this, layer );
mValidations.insert( id, validation );
}
void QgsVertexTool::zoomToVertex( const Vertex &vertex )
{
QgsPointXY newCenter = cachedGeometryForVertex( vertex ).vertexAt( vertex.vertexId );
QgsPointXY mapPoint = mCanvas->mapSettings().layerToMapCoordinates( vertex.layer, newCenter );
QPolygonF ext = mCanvas->mapSettings().visiblePolygon();
if ( !ext.containsPoint( mapPoint.toQPointF(), Qt::OddEvenFill ) )
{
mCanvas->setCenter( mapPoint );
mCanvas->refresh();
}
}
QList<Vertex> QgsVertexTool::verticesInRange( QgsVectorLayer *layer, QgsFeatureId fid, int vertexId0, int vertexId1, bool longWay )
{
QgsGeometry geom = cachedGeometry( layer, fid );
if ( vertexId0 > vertexId1 )
std::swap( vertexId0, vertexId1 );
// check it is the same part and ring
QgsVertexId vid0, vid1;
geom.vertexIdFromVertexNr( vertexId0, vid0 );
geom.vertexIdFromVertexNr( vertexId1, vid1 );
if ( vid0.part != vid1.part || vid0.ring != vid1.ring )
return QList<Vertex>();
// check whether we are in a linear ring
int vertexIdTmp = vertexId0 - 1;
QgsVertexId vidTmp;
while ( geom.vertexIdFromVertexNr( vertexIdTmp, vidTmp ) &&
vidTmp.part == vid0.part && vidTmp.ring == vid0.ring )
--vertexIdTmp;
int startVertexIndex = vertexIdTmp + 1;
vertexIdTmp = vertexId1 + 1;
while ( geom.vertexIdFromVertexNr( vertexIdTmp, vidTmp ) &&
vidTmp.part == vid0.part && vidTmp.ring == vid0.ring )
++vertexIdTmp;
int endVertexIndex = vertexIdTmp - 1;
QList<Vertex> lst;
if ( geom.vertexAt( startVertexIndex ) == geom.vertexAt( endVertexIndex ) )
{
// closed curve - we need to find out which way around the curve is shorter
double lengthTotal = 0, length0to1 = 0;
QgsPoint ptOld = geom.vertexAt( startVertexIndex );
for ( int i = startVertexIndex + 1; i <= endVertexIndex; ++i )
{
QgsPoint pt( geom.vertexAt( i ) );
double len = ptOld.distance( pt );
lengthTotal += len;
if ( i > vertexId0 && i <= vertexId1 )
length0to1 += len;
ptOld = pt;
}
bool use0to1 = length0to1 < lengthTotal / 2;
if ( longWay )
use0to1 = !use0to1;
for ( int i = startVertexIndex; i <= endVertexIndex; ++i )
{
bool isPickedVertex = i == vertexId0 || i == vertexId1;
bool is0to1 = i > vertexId0 && i < vertexId1;
if ( isPickedVertex || is0to1 == use0to1 )
lst.append( Vertex( layer, fid, i ) );
}
}
else
{
// curve that is not closed
for ( int i = vertexId0; i <= vertexId1; ++i )
{
lst.append( Vertex( layer, fid, i ) );
}
}
return lst;
}
void QgsVertexTool::rangeMethodPressEvent( QgsMapMouseEvent *e )
{
// nothing to do here for now...
Q_UNUSED( e );
}
void QgsVertexTool::rangeMethodReleaseEvent( QgsMapMouseEvent *e )
{
if ( e->button() == Qt::RightButton )
{
stopRangeVertexSelection();
return;
}
else if ( e->button() == Qt::LeftButton )
{
if ( mRangeSelectionFirstVertex )
{
// pick final vertex, make selection and switch back to normal selection
QgsPointLocator::Match m = snapToEditableLayer( e );
if ( m.hasVertex() )
{
if ( m.layer() == mRangeSelectionFirstVertex->layer && m.featureId() == mRangeSelectionFirstVertex->fid )
{
QList<Vertex> lst = verticesInRange( m.layer(), m.featureId(), mRangeSelectionFirstVertex->vertexId, m.vertexIndex(), e->modifiers() & Qt::ControlModifier );
setHighlightedVertices( lst );
mSelectionMethod = SelectionNormal;
}
}
}
else
{
// pick first vertex
QgsPointLocator::Match m = snapToEditableLayer( e );
if ( m.hasVertex() )
{
mRangeSelectionFirstVertex.reset( new Vertex( m.layer(), m.featureId(), m.vertexIndex() ) );
setHighlightedVertices( QList<Vertex>() << *mRangeSelectionFirstVertex );
}
}
}
}
void QgsVertexTool::rangeMethodMoveEvent( QgsMapMouseEvent *e )
{
if ( e->buttons() )
return; // only with no buttons pressed
QgsPointLocator::Match m = snapToEditableLayer( e );
updateFeatureBand( m );
updateVertexBand( m );
if ( !m.hasVertex() )
{
QList<Vertex> lst;
if ( mRangeSelectionFirstVertex )
lst << *mRangeSelectionFirstVertex;
setHighlightedVertices( lst );
return;
}
if ( mRangeSelectionFirstVertex )
{
// pick temporary final vertex and highlight vertices
if ( m.layer() == mRangeSelectionFirstVertex->layer && m.featureId() == mRangeSelectionFirstVertex->fid )
{
QList<Vertex> lst = verticesInRange( m.layer(), m.featureId(), mRangeSelectionFirstVertex->vertexId, m.vertexIndex(), e->modifiers() & Qt::ControlModifier );
setHighlightedVertices( lst );
}
}
}
void QgsVertexTool::startRangeVertexSelection()
{
mSelectionMethod = SelectionRange;
setHighlightedVertices( QList<Vertex>() );
mRangeSelectionFirstVertex.reset();
}
void QgsVertexTool::stopRangeVertexSelection()
{
mSelectionMethod = SelectionNormal;
setHighlightedVertices( QList<Vertex>() );
}
void QgsVertexTool::cleanEditor( QgsFeatureId id )
{
if ( mSelectedFeature.get() && mSelectedFeature.get()->featureId() == id )
{
cleanupVertexEditor();
};
}
| dgoedkoop/QGIS | src/app/vertextool/qgsvertextool.cpp | C++ | gpl-2.0 | 72,948 |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqlalchemy import ZopeTransactionExtension
import tornado.web
from handlers.index import IndexHandler
from handlers.sensors import SensorsHandler
import logging
logging.getLogger().setLevel(logging.DEBUG)
app = tornado.web.Application([
(r'/', IndexHandler),
(r'/sensors', SensorsHandler)
])
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
| nextgis/entels_front_demo | entels_demo_tornado/__init__.py | Python | gpl-2.0 | 548 |
<?php
namespace VMeC\VmecChurches\Domain\Repository;
/***************************************************************
*
* Copyright notice
*
* (c) 2014 Christoph Fischer <christoph.fischer@volksmission.de>, Volksmission entschiedener Christen e.V.
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* The repository for Addresses
*/
class AddressRepository extends \TYPO3\CMS\Extbase\Persistence\Repository {
} | Volksmission/vmec_churches | Classes/Domain/Repository/AddressRepository.php | PHP | gpl-2.0 | 1,198 |
<?php
/**
* @file
* Default theme implementation to display a printer-friendly version page.
*
* This file is akin to Drupal's page.tpl.php template. The contents being
* displayed are all included in the $content variable, while the rest of the
* template focuses on positioning and theming the other page elements.
*
* All the variables available in the page.tpl.php template should also be
* available in this template. In addition to those, the following variables
* defined by the print module(s) are available:
*
* Arguments to the theme call:
* - $node: The node object. For node content, this is a normal node object.
* For system-generated pages, this contains usually only the title, path
* and content elements.
* - $format: The output format being used ('html' for the Web version, 'mail'
* for the send by email, 'pdf' for the PDF version, etc.).
* - $expand_css: TRUE if the CSS used in the file should be provided as text
* instead of a list of @include directives.
* - $message: The message included in the send by email version with the
* text provided by the sender of the email.
*
* Variables created in the preprocess stage:
* - $print_logo: the image tag with the configured logo image.
* - $content: the rendered HTML of the node content.
* - $scripts: the HTML used to include the JavaScript files in the page head.
* - $footer_scripts: the HTML to include the JavaScript files in the page
* footer.
* - $sourceurl_enabled: TRUE if the source URL infromation should be
* displayed.
* - $url: absolute URL of the original source page.
* - $source_url: absolute URL of the original source page, either as an alias
* or as a system path, as configured by the user.
* - $cid: comment ID of the node being displayed.
* - $print_title: the title of the page.
* - $head: HTML contents of the head tag, provided by drupal_get_html_head().
* - $robots_meta: meta tag with the configured robots directives.
* - $css: the syle tags contaning the list of include directives or the full
* text of the files for inline CSS use.
* - $sendtoprinter: depending on configuration, this is the script tag
* including the JavaScript to send the page to the printer and to close the
* window afterwards.
*
* print[--format][--node--content-type[--nodeid]].tpl.php
*
* The following suggestions can be used:
* 1. print--format--node--content-type--nodeid.tpl.php
* 2. print--format--node--content-type.tpl.php
* 3. print--format.tpl.php
* 4. print--node--content-type--nodeid.tpl.php
* 5. print--node--content-type.tpl.php
* 6. print.tpl.php
*
* Where format is the ouput format being used, content-type is the node's
* content type and nodeid is the node's identifier (nid).
*
* @see print_preprocess_print()
* @see theme_print_published
* @see theme_print_breadcrumb
* @see theme_print_footer
* @see theme_print_sourceurl
* @see theme_print_url_list
* @see page.tpl.php
* @ingroup print
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>">
<head>
<?php print $head; ?>
<base href='<?php print $url ?>' />
<title><?php print $print_title; ?></title>
<?php print $scripts; ?>
<?php if (isset($sendtoprinter)) print $sendtoprinter; ?>
<?php print $robots_meta; ?>
<?php if (theme_get_setting('toggle_favicon')): ?>
<link rel='shortcut icon' href='<?php print theme_get_setting('favicon') ?>' type='image/x-icon' />
<?php endif; ?>
<?php print $css; ?>
</head>
<body>
<?php if (!empty($message)): ?>
<div class="print-message"><?php print $message; ?></div><p />
<?php endif; ?>
<?php if ($print_logo): ?>
<div class="print-logo"><?php print $print_logo; ?></div>
<?php endif; ?>
<div class="print-site_name"><?php print theme('print_published'); ?></div>
<p />
<!--<div class="print-breadcrumb"><?php print theme('print_breadcrumb', array('node' => $node)); ?></div>
<hr class="print-hr" />-->
<?php if (!isset($node->type)): ?>
<h2 class="print-title"><?php print $print_title; ?></h2>
<?php endif; ?>
<div class="print-content"><?php print $content; ?></div>
<div class="print-footer"><?php print theme('print_footer'); ?></div>
<hr class="print-hr" />
<?php if ($sourceurl_enabled): ?>
<div class="print-source_url">
<?php print theme('print_sourceurl', array('url' => $source_url, 'node' => $node, 'cid' => $cid)); ?>
</div>
<?php endif; ?>
<div class="print-links"><?php print theme('print_url_list'); ?></div>
<?php print $footer_scripts; ?>
</body>
</html>
| heliogabal/karus_theme | templates/print.tpl.php | PHP | gpl-2.0 | 4,821 |
/*
* Copyright (C) Johan Engelen 2007-2008 <j.b.c.engelen@utwente.nl>
* Abhishek Sharma
*
* Released under GNU GPL, read the file 'COPYING' for more information
*/
#include "live_effects/lpeobject.h"
#include "live_effects/effect.h"
#include "xml/repr.h"
#include "xml/node-event-vector.h"
#include "sp-object.h"
#include "attributes.h"
#include "document.h"
#include "document-private.h"
#include <glibmm/i18n.h>
//#define LIVEPATHEFFECT_VERBOSE
static void livepatheffect_on_repr_attr_changed (Inkscape::XML::Node * repr, const gchar *key, const gchar *oldval, const gchar *newval, bool is_interactive, void * data);
static Inkscape::XML::NodeEventVector const livepatheffect_repr_events = {
NULL, /* child_added */
NULL, /* child_removed */
livepatheffect_on_repr_attr_changed,
NULL, /* content_changed */
NULL /* order_changed */
};
LivePathEffectObject::LivePathEffectObject()
: SPObject(), effecttype(Inkscape::LivePathEffect::INVALID_LPE), effecttype_set(false),
lpe(NULL)
{
#ifdef LIVEPATHEFFECT_VERBOSE
g_message("Init livepatheffectobject");
#endif
}
LivePathEffectObject::~LivePathEffectObject() {
}
/**
* Virtual build: set livepatheffect attributes from its associated XML node.
*/
void LivePathEffectObject::build(SPDocument *document, Inkscape::XML::Node *repr) {
g_assert(this != NULL);
g_assert(SP_IS_OBJECT(this));
SPObject::build(document, repr);
this->readAttr( "effect" );
if (repr) {
repr->addListener (&livepatheffect_repr_events, this);
}
/* Register ourselves, is this necessary? */
// document->addResource("path-effect", object);
}
/**
* Virtual release of livepatheffect members before destruction.
*/
void LivePathEffectObject::release() {
this->getRepr()->removeListenerByData(this);
/*
if (object->document) {
// Unregister ourselves
sp_document_removeResource(object->document, "livepatheffect", object);
}
if (gradient->ref) {
gradient->modified_connection.disconnect();
gradient->ref->detach();
delete gradient->ref;
gradient->ref = NULL;
}
gradient->modified_connection.~connection();
*/
if (this->lpe) {
delete this->lpe;
this->lpe = NULL;
}
this->effecttype = Inkscape::LivePathEffect::INVALID_LPE;
SPObject::release();
}
/**
* Virtual set: set attribute to value.
*/
void LivePathEffectObject::set(unsigned key, gchar const *value) {
#ifdef LIVEPATHEFFECT_VERBOSE
g_print("Set livepatheffect");
#endif
switch (key) {
case SP_PROP_PATH_EFFECT:
if (this->lpe) {
delete this->lpe;
this->lpe = NULL;
}
if ( value && Inkscape::LivePathEffect::LPETypeConverter.is_valid_key(value) ) {
this->effecttype = Inkscape::LivePathEffect::LPETypeConverter.get_id_from_key(value);
this->lpe = Inkscape::LivePathEffect::Effect::New(this->effecttype, this);
this->effecttype_set = true;
} else {
this->effecttype = Inkscape::LivePathEffect::INVALID_LPE;
this->effecttype_set = false;
}
this->requestModified(SP_OBJECT_MODIFIED_FLAG);
break;
}
SPObject::set(key, value);
}
/**
* Virtual write: write object attributes to repr.
*/
Inkscape::XML::Node* LivePathEffectObject::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) {
if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
repr = xml_doc->createElement("inkscape:path-effect");
}
if ((flags & SP_OBJECT_WRITE_ALL) || this->lpe) {
repr->setAttribute("effect", Inkscape::LivePathEffect::LPETypeConverter.get_key(this->effecttype).c_str());
this->lpe->writeParamsToSVG();
}
SPObject::write(xml_doc, repr, flags);
return repr;
}
static void
livepatheffect_on_repr_attr_changed ( Inkscape::XML::Node * /*repr*/,
const gchar *key,
const gchar */*oldval*/,
const gchar *newval,
bool /*is_interactive*/,
void * data )
{
#ifdef LIVEPATHEFFECT_VERBOSE
g_print("livepatheffect_on_repr_attr_changed");
#endif
if (!data)
return;
LivePathEffectObject *lpeobj = (LivePathEffectObject*) data;
if (!lpeobj->get_lpe())
return;
lpeobj->get_lpe()->setParameter(key, newval);
lpeobj->requestModified(SP_OBJECT_MODIFIED_FLAG);
}
/**
* If this has other users, create a new private duplicate and return it
* returns 'this' when no forking was necessary (and therefore no duplicate was made)
* Check out SPLPEItem::forkPathEffectsIfNecessary !
*/
LivePathEffectObject *LivePathEffectObject::fork_private_if_necessary(unsigned int nr_of_allowed_users)
{
if (hrefcount > nr_of_allowed_users) {
SPDocument *doc = this->document;
Inkscape::XML::Document *xml_doc = doc->getReprDoc();
Inkscape::XML::Node *dup_repr = this->getRepr()->duplicate(xml_doc);
doc->getDefs()->getRepr()->addChild(dup_repr, NULL);
LivePathEffectObject *lpeobj_new = LIVEPATHEFFECT( doc->getObjectByRepr(dup_repr) );
Inkscape::GC::release(dup_repr);
return lpeobj_new;
}
return this;
}
/*
Local Variables:
mode:c++
c-file-style:"stroustrup"
c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
indent-tabs-mode:nil
fill-column:99
End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :
| danieljabailey/inkscape_experiments | src/live_effects/lpeobject.cpp | C++ | gpl-2.0 | 5,686 |
class SectionsController < ApplicationController
authorize_resource
def index
flash.keep
redirect_to courses_path
end
def new
@section = Section.new
@section.course = Course.find(params[:course_id])
end
def create
@section = Section.new(section_params)
@section.course = Course.find(params[:course_id])
if @section.save
redirect_to course_path(@section.course), notice: 'Section saved.'
else
render 'new'
end
end
def show
course = Course.find(params[:course_id])
@section = course.sections.find(params[:id])
authorize! :read, @section
end
def edit
course = Course.find(params[:course_id])
@section = course.sections.find(params[:id])
end
def update
course = Course.find(params[:course_id])
@section = course.sections.find(params[:id])
if @section.update(section_params)
redirect_to course_section_path(@section.course, @section), notice: "Section updated."
else
render 'edit'
end
end
def destroy
course = Course.find(params[:course_id])
@section = course.sections.find(params[:id])
@section.destroy
redirect_to course_path(@section.course), notice: 'Section deleted.'
end
private
def section_params
params.require(:section).permit(:name, :course_id, :public, :week, :layout_file_path)
end
end
| epicodus/textbook | app/controllers/sections_controller.rb | Ruby | gpl-2.0 | 1,356 |
package com.rarnu.tools.neo.activity;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import com.rarnu.tools.neo.R;
import com.rarnu.tools.neo.api.NativeAPI;
import com.rarnu.tools.neo.base.BaseActivity;
import com.rarnu.tools.neo.fragment.MainFragment;
import com.rarnu.tools.neo.utils.UIUtils;
import com.rarnu.tools.neo.xposed.XpStatus;
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
UIUtils.initDisplayMetrics(this, getWindowManager(), false);
super.onCreate(savedInstanceState);
NativeAPI.isRejected = !NativeAPI.mount();
if (!XpStatus.isEnable()) {
new AlertDialog.Builder(this)
.setTitle(R.string.alert_hint)
.setMessage(R.string.alert_xposed)
.setCancelable(false)
.setPositiveButton(R.string.alert_ok, null)
.show();
}
if (Build.VERSION.SDK_INT >= 24) {
new AlertDialog.Builder(this)
.setTitle(R.string.alert_hint)
.setMessage(R.string.alert_androidn_pending)
.setPositiveButton(R.string.alert_ok, null)
.show();
} else {
if (NativeAPI.isRejected) {
new AlertDialog.Builder(this)
.setTitle(R.string.alert_hint)
.setMessage(R.string.alert_root)
.setCancelable(false)
.setPositiveButton(R.string.alert_ok, null)
.show();
}
}
requirePermission();
}
@Override
public int getIcon() {
return R.drawable.ic_launcher;
}
@Override
public Fragment replaceFragment() {
return new MainFragment();
}
@Override
public int customTheme() {
return 0;
}
@Override
public boolean getActionBarCanBack() {
return false;
}
private void requirePermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
} else {
XpStatus.canWriteSdcard = true;
}
} else {
XpStatus.canWriteSdcard = true;
}
}
// No override here for compact with 5.0
// @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int i = 0; i < permissions.length; i++) {
if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
XpStatus.canWriteSdcard = grantResults[i] == PackageManager.PERMISSION_GRANTED;
break;
}
}
}
}
| baijian/root-tools | RootTools2/src/main/java/com/rarnu/tools/neo/activity/MainActivity.java | Java | gpl-2.0 | 3,185 |
package xzd.mobile.android.common;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.DisplayMetrics;
import android.view.View;
public class ImageUtils {
public final static String SDCARD_MNT = "/mnt/sdcard";
public final static String SDCARD = "/sdcard";
/** 请求相册 */
public static final int REQUEST_CODE_GETIMAGE_BYSDCARD = 0;
/** 请求相机 */
public static final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1;
/** 请求裁剪 */
public static final int REQUEST_CODE_GETIMAGE_BYCROP = 2;
private static ImageUtils mImageUtils = null;
public static ImageUtils getInstance() {
if (mImageUtils == null) {
mImageUtils = new ImageUtils();
}
return mImageUtils;
}
public static void releaseMem() {
if (mImageUtils != null) {
mImageUtils = null;
}
}
public Bitmap getBitmapFromView(View view) {
view.destroyDrawingCache();
view.measure(View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache(true);
return bitmap;
}
/**
* 写图片文�? 在Android系统中,文件保存�?/data/data/PACKAGE_NAME/files 目录�?
*
* @throws IOException
*/
public void saveImage(Context context, String fileName, Bitmap bitmap)
throws IOException {
saveImage(context, fileName, bitmap, 100);
}
public void saveImage(Context context, String fileName, Bitmap bitmap,
int quality) throws IOException {
if (bitmap == null || fileName == null || context == null)
return;
FileOutputStream fos = context.openFileOutput(fileName,
Context.MODE_PRIVATE);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, quality, stream);
byte[] bytes = stream.toByteArray();
fos.write(bytes);
fos.close();
}
/**
* 写图片文件到SD�?
*
* @throws IOException
*/
public void saveImageToSD(String filePath, Bitmap bitmap, int quality)
throws IOException {
if (bitmap != null) {
FileOutputStream fos = new FileOutputStream(filePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, quality, stream);
byte[] bytes = stream.toByteArray();
fos.write(bytes);
fos.close();
}
}
/**
* 获取bitmap
*
* @param context
* @param fileName
* @return
*/
public Bitmap getBitmap(Context context, String fileName) {
FileInputStream fis = null;
Bitmap bitmap = null;
try {
fis = context.openFileInput(fileName);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
return bitmap;
}
/**
* 获取bitmap
*
* @param filePath
* @return
*/
public Bitmap getBitmapByPath(String filePath) {
return getBitmapByPath(filePath, null);
}
public Bitmap getBitmapByPath(String filePath, BitmapFactory.Options opts) {
FileInputStream fis = null;
Bitmap bitmap = null;
try {
File file = new File(filePath);
fis = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fis, null, opts);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
return bitmap;
}
/**
* 获取bitmap
*
* @param file
* @return
*/
public Bitmap getBitmapByFile(File file) {
FileInputStream fis = null;
Bitmap bitmap = null;
try {
fis = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
return bitmap;
}
/**
* 使用当前时间戳拼接一个唯�?��文件�?
*
* @param format
* @return
*/
public String getTempFileName() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SS");
String fileName = format.format(new Timestamp(System
.currentTimeMillis()));
return fileName;
}
/**
* 获取照相机使用的目录
*
* @return
*/
public String getCamerPath() {
return Environment.getExternalStorageDirectory() + File.separator
+ "FounderNews" + File.separator;
}
/**
* 判断当前Url是否标准的content://样式,如果不是,则返回绝对路�?
*
* @param uri
* @return
*/
public String getAbsolutePathFromNoStandardUri(Uri mUri) {
String filePath = null;
String mUriString = mUri.toString();
mUriString = Uri.decode(mUriString);
String pre1 = "file://" + SDCARD + File.separator;
String pre2 = "file://" + SDCARD_MNT + File.separator;
if (mUriString.startsWith(pre1)) {
filePath = Environment.getExternalStorageDirectory().getPath()
+ File.separator + mUriString.substring(pre1.length());
} else if (mUriString.startsWith(pre2)) {
filePath = Environment.getExternalStorageDirectory().getPath()
+ File.separator + mUriString.substring(pre2.length());
}
return filePath;
}
/**
* 通过uri获取文件的绝对路�?
*
* @param uri
* @return
*/
public String getAbsoluteImagePath(Activity context, Uri uri) {
String imagePath = "";
String[] proj = { MediaColumns.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = context.managedQuery(uri, proj, // Which columns to
// return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
imagePath = cursor.getString(column_index);
}
}
return imagePath;
}
/**
* 获取图片缩略�? 只有Android2.1以上版本支持
*
* @param imgName
* @param kind
* MediaStore.Images.Thumbnails.MICRO_KIND
* @return
*/
public Bitmap loadImgThumbnail(Activity context, String imgName, int kind) {
Bitmap bitmap = null;
String[] proj = { BaseColumns._ID, MediaColumns.DISPLAY_NAME };
Cursor cursor = context.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
MediaColumns.DISPLAY_NAME + "='" + imgName + "'", null, null);
if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
ContentResolver crThumb = context.getContentResolver();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
bitmap = MethodsCompat.getInstance().getThumbnail(crThumb,
cursor.getInt(0), kind, options);
}
return bitmap;
}
public Bitmap loadImgThumbnail(String filePath, int w, int h) {
Bitmap bitmap = getBitmapByPath(filePath);
return zoomBitmap(bitmap, w, h);
}
/**
* 获取SD卡中�?��图片路径
*
* @return
*/
public String getLatestImage(Activity context) {
String latestImage = null;
String[] items = { BaseColumns._ID, MediaColumns.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = context.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, items, null,
null, BaseColumns._ID + " desc");
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
latestImage = cursor.getString(1);
break;
}
}
return latestImage;
}
/**
* 计算缩放图片的宽�?
*
* @param img_size
* @param square_size
* @return
*/
public int[] scaleImageSize(int[] img_size, int square_size) {
if (img_size[0] <= square_size && img_size[1] <= square_size)
return img_size;
double ratio = square_size
/ (double) Math.max(img_size[0], img_size[1]);
return new int[] { (int) (img_size[0] * ratio),
(int) (img_size[1] * ratio) };
}
/**
* 创建缩略�?
*
* @param context
* @param largeImagePath
* 原始大图路径
* @param thumbfilePath
* 输出缩略图路�?
* @param square_size
* 输出图片宽度
* @param quality
* 输出图片质量
* @throws IOException
*/
public void createImageThumbnail(Context context, String largeImagePath,
String thumbfilePath, int square_size, int quality)
throws IOException {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 1;
// 原始图片bitmap
Bitmap cur_bitmap = getBitmapByPath(largeImagePath, opts);
if (cur_bitmap == null)
return;
// 原始图片的高�?
int[] cur_img_size = new int[] { cur_bitmap.getWidth(),
cur_bitmap.getHeight() };
// 计算原始图片缩放后的宽高
int[] new_img_size = scaleImageSize(cur_img_size, square_size);
// 生成缩放后的bitmap
Bitmap thb_bitmap = zoomBitmap(cur_bitmap, new_img_size[0],
new_img_size[1]);
// 生成缩放后的图片文件
saveImageToSD(thumbfilePath, thb_bitmap, quality);
}
/**
* 放大缩小图片
*
* @param bitmap
* @param w
* @param h
* @return
*/
public Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
Bitmap newbmp = null;
if (bitmap != null) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidht = ((float) w / width);
float scaleHeight = ((float) h / height);
matrix.postScale(scaleWidht, scaleHeight);
newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
true);
}
return newbmp;
}
public Bitmap scaleBitmap(Bitmap bitmap) {
// 获取这个图片的宽和高
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// 定义预转换成的图片的宽度和高�?
int newWidth = 200;
int newHeight = 200;
// 计算缩放率,新尺寸除原始尺寸
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
// 旋转图片 动作
// matrix.postRotate(45);
// 创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
matrix, true);
return resizedBitmap;
}
/**
* (缩放)重绘图片
*
* @param context
* Activity
* @param bitmap
* @return
*/
public Bitmap reDrawBitMap(Activity context, Bitmap bitmap) {
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
int rHeight = dm.heightPixels;
int rWidth = dm.widthPixels;
// float rHeight=dm.heightPixels/dm.density+0.5f;
// float rWidth=dm.widthPixels/dm.density+0.5f;
// int height=bitmap.getScaledHeight(dm);
// int width = bitmap.getScaledWidth(dm);
int height = bitmap.getHeight();
int width = bitmap.getWidth();
float zoomScale;
/** 方式1 **/
// if(rWidth/rHeight>width/height){//以高为准
// zoomScale=((float) rHeight) / height;
// }else{
// //if(rWidth/rHeight<width/height)//以宽为准
// zoomScale=((float) rWidth) / width;
// }
/** 方式2 **/
// if(width*1.5 >= height) {//以宽为准
// if(width >= rWidth)
// zoomScale = ((float) rWidth) / width;
// else
// zoomScale = 1.0f;
// }else {//以高为准
// if(height >= rHeight)
// zoomScale = ((float) rHeight) / height;
// else
// zoomScale = 1.0f;
// }
/** 方式3 **/
if (width >= rWidth)
zoomScale = ((float) rWidth) / width;
else
zoomScale = 1.0f;
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 缩放图片动作
matrix.postScale(zoomScale, zoomScale);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
/**
* 将Drawable转化为Bitmap
*
* @param drawable
* @return
*/
public Bitmap drawableToBitmap(Drawable drawable) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, width, height);
drawable.draw(canvas);
return bitmap;
}
/**
* 获得圆角图片的方�?
*
* @param bitmap
* @param roundPx
* �?��设成14
* @return
*/
public Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
/**
* 获得带�?影的图片方法
*
* @param bitmap
* @return
*/
public Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
final int reflectionGap = 4;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
width, height / 2, matrix, false);
Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
(height + height / 2), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(bitmap, 0, 0, null);
Paint deafalutPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
0x00ffffff, TileMode.CLAMP);
paint.setShader(shader);
// Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
// Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
+ reflectionGap, paint);
return bitmapWithReflection;
}
/**
* 将bitmap转化为drawable
*
* @param bitmap
* @return
*/
public Drawable bitmapToDrawable(Bitmap bitmap) {
Drawable drawable = new BitmapDrawable(bitmap);
return drawable;
}
/**
* 获取图片类型
*
* @param file
* @return
*/
public String getImageType(File file) {
if (file == null || !file.exists()) {
return null;
}
InputStream in = null;
try {
in = new FileInputStream(file);
String type = getImageType(in);
return type;
} catch (IOException e) {
return null;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
}
}
}
/**
* detect bytes's image type by inputstream
*
* @param in
* @return
* @see #getImageType(byte[])
*/
public String getImageType(InputStream in) {
if (in == null) {
return null;
}
try {
byte[] bytes = new byte[8];
in.read(bytes);
return getImageType(bytes);
} catch (IOException e) {
return null;
}
}
/**
* detect bytes's image type
*
* @param bytes
* 2~8 byte at beginning of the image file
* @return image mimetype or null if the file is not image
*/
public String getImageType(byte[] bytes) {
if (isJPEG(bytes)) {
return "image/jpeg";
}
if (isGIF(bytes)) {
return "image/gif";
}
if (isPNG(bytes)) {
return "image/png";
}
if (isBMP(bytes)) {
return "application/x-bmp";
}
return null;
}
private boolean isJPEG(byte[] b) {
if (b.length < 2) {
return false;
}
return (b[0] == (byte) 0xFF) && (b[1] == (byte) 0xD8);
}
private boolean isGIF(byte[] b) {
if (b.length < 6) {
return false;
}
return b[0] == 'G' && b[1] == 'I' && b[2] == 'F' && b[3] == '8'
&& (b[4] == '7' || b[4] == '9') && b[5] == 'a';
}
private boolean isPNG(byte[] b) {
if (b.length < 8) {
return false;
}
return (b[0] == (byte) 137 && b[1] == (byte) 80 && b[2] == (byte) 78
&& b[3] == (byte) 71 && b[4] == (byte) 13 && b[5] == (byte) 10
&& b[6] == (byte) 26 && b[7] == (byte) 10);
}
private boolean isBMP(byte[] b) {
if (b.length < 2) {
return false;
}
return (b[0] == 0x42) && (b[1] == 0x4d);
}
}
| zhanglei920802/ypgl | src/xzd/mobile/android/common/ImageUtils.java | Java | gpl-2.0 | 18,019 |
package org.uppermodel.translog;
import java.util.LinkedList;
import java.util.List;
import org.uppermodel.translog.v0v1v0.Event;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
/**
* Translog document v.0.1.0
*
* @author Daniel Couto-Vale <danielvale@icloud.com>
*/
public class TranslogDocument_0_1_0 implements TranslogDocument {
private static final String VERSION_EXP = "/LogFile/VersionString";
private static final String TRANSLATOR_ID_EXP = "/LogFile/Subject";
private static final String SOURCE_TEXT_EXP = "/LogFile/Project/Interface/Standard/Settings/SourceTextUTF8";
private static final String TARGET_TEXT_EXP = "/LogFile/Project/Interface/Standard/Settings/TargetTextUTF8";
private static final String FINAL_TARGET_TEXT_EXP = "/LogFile/FinalTextChar/CharPos";
private static final String EVENTS_EXP = "/LogFile/Events/*";
/**
* The DOM document
*/
private Document document;
/**
* The xPath object
*/
private final XPath xPath;
private XPathExpression versionExp;
private XPathExpression translatorIdExp;
private XPathExpression sourceTextExp;
private XPathExpression targetTextExp;
private XPathExpression finalTargetTextExp;
private XPathExpression eventsExp;
/**
* Constructor
*
* @param document the DOM document
*/
public TranslogDocument_0_1_0(Document document) {
this.document = document;
this.xPath = XPathFactory.newInstance().newXPath();
try {
this.versionExp = this.xPath.compile(VERSION_EXP);
this.translatorIdExp = this.xPath.compile(TRANSLATOR_ID_EXP);
this.sourceTextExp = this.xPath.compile(SOURCE_TEXT_EXP);
this.targetTextExp = this.xPath.compile(TARGET_TEXT_EXP);
this.finalTargetTextExp = this.xPath.compile(FINAL_TARGET_TEXT_EXP);
this.eventsExp = this.xPath.compile(EVENTS_EXP);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
@Override
public final String getVersion() {
return extractString(versionExp);
}
@Override
public final String getTranslatorId() {
return extractString(translatorIdExp);
}
@Override
public final String getSourceText() {
return extractString(sourceTextExp);
}
@Override
public final String getInitialTargetText() {
return extractString(targetTextExp);
}
@Override
public final String getFinalTargetText() {
try {
return getFinalTargetTextImpl();
} catch (XPathExpressionException e) {
e.printStackTrace();
return "";
}
}
private final String getFinalTargetTextImpl() throws XPathExpressionException {
StringBuffer buffer = new StringBuffer();
NodeList nodeList = (NodeList) finalTargetTextExp.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element)nodeList.item(i);
String value = element.getAttribute("Value");
if (value.equals("\n")) {
value = "";
}
buffer.append(value);
}
return buffer.toString();
}
@Override
public final List<TranslogEvent> getEvents() {
try {
return getEventListImp();
} catch (XPathExpressionException e) {
e.printStackTrace();
return new LinkedList<TranslogEvent>();
}
}
private final List<TranslogEvent> getEventListImp() throws XPathExpressionException {
List<TranslogEvent> events = new LinkedList<TranslogEvent>();
NodeList nodeList = (NodeList) eventsExp.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element)nodeList.item(i);
events.add(Event.makeNode(element, xPath));
}
return events;
}
private final String extractString(XPathExpression exp) {
try {
return extractStringImp(exp);
} catch (XPathExpressionException e) {
e.printStackTrace();
return null;
}
}
private final String extractStringImp(XPathExpression exp) throws XPathExpressionException {
NodeList nodeList = (NodeList) exp.evaluate(document, XPathConstants.NODESET);
Node node = nodeList.item(0).getFirstChild();
return node == null ? "" : node.getNodeValue();
}
@Override
public boolean isCompliant() {
return document.getDocumentElement().getNodeName().equals("LogFile");
}
}
| DanielCoutoVale/TranslogToolset | src/org/uppermodel/translog/TranslogDocument_0_1_0.java | Java | gpl-2.0 | 4,381 |
// Copyright (C) 2012-2016 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
//
// { dg-do run { target c++11 xfail *-*-* } }
// { dg-require-debug-mode "" }
#include <set>
void test01()
{
std::set<int> s1;
auto it1 = s1.begin();
it1 = std::move(it1);
}
int main()
{
test01();
return 0;
}
| paranoiacblack/gcc | libstdc++-v3/testsuite/23_containers/set/debug/iterator_self_move_assign_neg.cc | C++ | gpl-2.0 | 992 |
package com.catglo.dashplaygroundfree;
import java.util.LinkedList;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
interface MenuExecutor {
void execute();
}
class MenuItem extends Object {
Rect area;
private MenuExecutor executor;
boolean inverted=false;
public MenuItem(Rect r,MenuExecutor executor){
area = r;
this.executor = executor;
}
void go(){
executor.execute();
}
public void invert() {
inverted=true;
}
}
| marchold/DashAndDittosPlayground | PlaygroundFree/src/com/catglo/dashplaygroundfree/MenuExecutor.java | Java | gpl-2.0 | 973 |
<?php
/**
* Loads the correct file using the get_template_part function
*
* @package Total
* @author Alexander Clarke
* @copyright Copyright (c) 2014, Symple Workz LLC
* @link http://www.wpexplorer.com
* @since Total 1.40
*/
if ( ! function_exists( 'wpex_get_template_part' ) ) {
function wpex_get_template_part( $template_part = '' ) {
// Get Post Vars
global $post;
$post_id = $post->ID;
$post_type = get_post_type( $post_id );
// Search result
if ( is_search() ) {
$template_part = 'searchresult';
// Standard Posts
} elseif ( 'post' == $post_type ) {
$template_part = get_post_format( $post_id );
// Portfolio
} elseif ( 'portfolio' == $post_type ) {
$template_part = 'portfolio';
// Staff
} elseif ( 'staff' == $post_type ) {
$template_part = 'staff';
// Testimonials
} elseif ( 'testimonials' == $post_type ) {
$template_part = 'staff';
// Other Post Types
} else {
$template_part = 'other';
}
// Apply filter for child editing
apply_filters( 'wpex_get_template_part', $template_part );
// Echo Template Part
ob_start();
get_template_part( 'content', $template_part );
echo ob_get_clean();
}
} | poppalex/VLAA_dev | wp-content/themes/Total/framework/template-parts.php | PHP | gpl-2.0 | 1,184 |
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Spell.h"
#include "AzeriteEmpoweredItem.h"
#include "Battlefield.h"
#include "BattlefieldMgr.h"
#include "Battleground.h"
#include "CellImpl.h"
#include "CombatLogPackets.h"
#include "Common.h"
#include "ConditionMgr.h"
#include "DB2Stores.h"
#include "DatabaseEnv.h"
#include "DisableMgr.h"
#include "DynamicObject.h"
#include "GameObjectAI.h"
#include "GridNotifiersImpl.h"
#include "Guild.h"
#include "Group.h"
#include "InstanceScript.h"
#include "Item.h"
#include "Log.h"
#include "LootMgr.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "PathGenerator.h"
#include "Pet.h"
#include "Player.h"
#include "ScriptMgr.h"
#include "SharedDefines.h"
#include "SpellAuraEffects.h"
#include "SpellHistory.h"
#include "SpellInfo.h"
#include "SpellMgr.h"
#include "SpellPackets.h"
#include "SpellScript.h"
#include "TemporarySummon.h"
#include "TradeData.h"
#include "Util.h"
#include "VMapFactory.h"
#include "Vehicle.h"
#include "World.h"
#include "WorldSession.h"
#include <numeric>
extern NonDefaultConstructible<pEffect> SpellEffects[TOTAL_SPELL_EFFECTS];
SpellDestination::SpellDestination()
{
_position.Relocate(0, 0, 0, 0);
_transportGUID.Clear();
_transportOffset.Relocate(0, 0, 0, 0);
}
SpellDestination::SpellDestination(float x, float y, float z, float orientation, uint32 mapId)
{
_position.Relocate(x, y, z, orientation);
_transportGUID.Clear();
_position.m_mapId = mapId;
_transportOffset.Relocate(0, 0, 0, 0);
}
SpellDestination::SpellDestination(Position const& pos)
{
_position.Relocate(pos);
_transportGUID.Clear();
_transportOffset.Relocate(0, 0, 0, 0);
}
SpellDestination::SpellDestination(WorldObject const& wObj)
{
_transportGUID = wObj.GetTransGUID();
_transportOffset.Relocate(wObj.GetTransOffsetX(), wObj.GetTransOffsetY(), wObj.GetTransOffsetZ(), wObj.GetTransOffsetO());
_position.Relocate(wObj);
}
void SpellDestination::Relocate(Position const& pos)
{
if (!_transportGUID.IsEmpty())
{
Position offset;
_position.GetPositionOffsetTo(pos, offset);
_transportOffset.RelocateOffset(offset);
}
_position.Relocate(pos);
}
void SpellDestination::Relocate(WorldLocation const &loc)
{
_position = loc;
}
void SpellDestination::RelocateOffset(Position const& offset)
{
if (!_transportGUID.IsEmpty())
_transportOffset.RelocateOffset(offset);
_position.RelocateOffset(offset);
}
SpellCastTargets::SpellCastTargets() : m_targetMask(0), m_objectTarget(nullptr), m_itemTarget(nullptr),
m_itemTargetEntry(0), m_pitch(0.0f), m_speed(0.0f)
{
}
SpellCastTargets::SpellCastTargets(Unit* caster, WorldPackets::Spells::SpellCastRequest const& spellCastRequest) :
m_targetMask(spellCastRequest.Target.Flags), m_objectTarget(nullptr), m_itemTarget(nullptr),
m_objectTargetGUID(spellCastRequest.Target.Unit), m_itemTargetGUID(spellCastRequest.Target.Item),
m_itemTargetEntry(0), m_pitch(0.0f), m_speed(0.0f), m_strTarget(spellCastRequest.Target.Name)
{
if (spellCastRequest.Target.SrcLocation)
{
m_src._transportGUID = spellCastRequest.Target.SrcLocation->Transport;
Position* pos;
if (!m_src._transportGUID.IsEmpty())
pos = &m_src._transportOffset;
else
pos = &m_src._position;
pos->Relocate(spellCastRequest.Target.SrcLocation->Location);
if (spellCastRequest.Target.Orientation)
pos->SetOrientation(*spellCastRequest.Target.Orientation);
}
if (spellCastRequest.Target.DstLocation)
{
m_dst._transportGUID = spellCastRequest.Target.DstLocation->Transport;
Position* pos;
if (!m_dst._transportGUID.IsEmpty())
pos = &m_dst._transportOffset;
else
pos = &m_dst._position;
pos->Relocate(spellCastRequest.Target.DstLocation->Location);
if (spellCastRequest.Target.Orientation)
pos->SetOrientation(*spellCastRequest.Target.Orientation);
}
SetPitch(spellCastRequest.MissileTrajectory.Pitch);
SetSpeed(spellCastRequest.MissileTrajectory.Speed);
if (spellCastRequest.SendCastFlags == 8) // Archaeology
{
uint32 kEntry, kCount, fEntry, fCount;
uint8 type;
for (auto const& weight : spellCastRequest.Weight)
{
type = weight.Type;
switch (type)
{
case 1: // Fragments
fEntry = weight.ID; // Currency id
fCount = weight.Quantity; // Currency count
break;
case 2: // Keystones
kEntry = weight.ID; // Item id
kCount = weight.Quantity; // Item count
break;
}
}
if (kCount > 0 && caster->GetTypeId() == TYPEID_PLAYER)
caster->ToPlayer()->DestroyItemCount(kEntry, -(int32(kCount)), true, false);
if (fCount > 0 && caster->GetTypeId() == TYPEID_PLAYER)
caster->ToPlayer()->ModifyCurrency(fEntry, -(int32(fCount)), false);
}
Update(caster);
}
SpellCastTargets::~SpellCastTargets() { }
void SpellCastTargets::Write(WorldPackets::Spells::SpellTargetData& data)
{
data.Flags = m_targetMask;
if (m_targetMask & (TARGET_FLAG_UNIT | TARGET_FLAG_CORPSE_ALLY | TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_CORPSE_ENEMY | TARGET_FLAG_UNIT_MINIPET))
data.Unit = m_objectTargetGUID;
if (m_targetMask & (TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM) && m_itemTarget)
data.Item = m_itemTarget->GetGUID();
if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION)
{
data.SrcLocation = boost::in_place();
data.SrcLocation->Transport = m_src._transportGUID; // relative position guid here - transport for example
if (!m_src._transportGUID.IsEmpty())
data.SrcLocation->Location = m_src._transportOffset;
else
data.SrcLocation->Location = m_src._position;
}
if (m_targetMask & TARGET_FLAG_DEST_LOCATION)
{
data.DstLocation = boost::in_place();
data.DstLocation->Transport = m_dst._transportGUID; // relative position guid here - transport for example
if (!m_dst._transportGUID.IsEmpty())
data.DstLocation->Location = m_dst._transportOffset;
else
data.DstLocation->Location = m_dst._position;
}
if (m_targetMask & TARGET_FLAG_STRING)
data.Name = m_strTarget;
}
ObjectGuid SpellCastTargets::GetOrigUnitTargetGUID() const
{
switch (m_origObjectTargetGUID.GetHigh())
{
case HighGuid::Player:
case HighGuid::Vehicle:
case HighGuid::Creature:
case HighGuid::Pet:
return m_origObjectTargetGUID;
default:
return ObjectGuid();
}
}
void SpellCastTargets::SetOrigUnitTarget(Unit* target)
{
if (!target)
return;
m_origObjectTargetGUID = target->GetGUID();
}
ObjectGuid SpellCastTargets::GetUnitTargetGUID() const
{
if (m_objectTargetGUID.IsUnit())
return m_objectTargetGUID;
return ObjectGuid::Empty;
}
Unit* SpellCastTargets::GetUnitTarget() const
{
if (m_objectTarget)
return m_objectTarget->ToUnit();
return NULL;
}
void SpellCastTargets::SetUnitTarget(Unit* target)
{
if (!target)
return;
m_objectTarget = target;
m_objectTargetGUID = target->GetGUID();
m_targetMask |= TARGET_FLAG_UNIT;
}
ObjectGuid SpellCastTargets::GetGOTargetGUID() const
{
if (m_objectTargetGUID.IsAnyTypeGameObject())
return m_objectTargetGUID;
return ObjectGuid::Empty;
}
GameObject* SpellCastTargets::GetGOTarget() const
{
if (m_objectTarget)
return m_objectTarget->ToGameObject();
return NULL;
}
void SpellCastTargets::SetGOTarget(GameObject* target)
{
if (!target)
return;
m_objectTarget = target;
m_objectTargetGUID = target->GetGUID();
m_targetMask |= TARGET_FLAG_GAMEOBJECT;
}
ObjectGuid SpellCastTargets::GetCorpseTargetGUID() const
{
if (m_objectTargetGUID.IsCorpse())
return m_objectTargetGUID;
return ObjectGuid::Empty;
}
Corpse* SpellCastTargets::GetCorpseTarget() const
{
if (m_objectTarget)
return m_objectTarget->ToCorpse();
return NULL;
}
WorldObject* SpellCastTargets::GetObjectTarget() const
{
return m_objectTarget;
}
ObjectGuid SpellCastTargets::GetObjectTargetGUID() const
{
return m_objectTargetGUID;
}
void SpellCastTargets::RemoveObjectTarget()
{
m_objectTarget = NULL;
m_objectTargetGUID.Clear();
m_targetMask &= ~(TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK | TARGET_FLAG_GAMEOBJECT_MASK);
}
void SpellCastTargets::SetItemTarget(Item* item)
{
if (!item)
return;
m_itemTarget = item;
m_itemTargetGUID = item->GetGUID();
m_itemTargetEntry = item->GetEntry();
m_targetMask |= TARGET_FLAG_ITEM;
}
void SpellCastTargets::SetTradeItemTarget(Player* caster)
{
m_itemTargetGUID = ObjectGuid::TradeItem;
m_itemTargetEntry = 0;
m_targetMask |= TARGET_FLAG_TRADE_ITEM;
Update(caster);
}
void SpellCastTargets::UpdateTradeSlotItem()
{
if (m_itemTarget && (m_targetMask & TARGET_FLAG_TRADE_ITEM))
{
m_itemTargetGUID = m_itemTarget->GetGUID();
m_itemTargetEntry = m_itemTarget->GetEntry();
}
}
SpellDestination const* SpellCastTargets::GetSrc() const
{
return &m_src;
}
Position const* SpellCastTargets::GetSrcPos() const
{
return &m_src._position;
}
void SpellCastTargets::SetSrc(float x, float y, float z)
{
m_src = SpellDestination(x, y, z);
m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
}
void SpellCastTargets::SetSrc(Position const& pos)
{
m_src = SpellDestination(pos);
m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
}
void SpellCastTargets::SetSrc(WorldObject const& wObj)
{
m_src = SpellDestination(wObj);
m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
}
void SpellCastTargets::ModSrc(Position const& pos)
{
ASSERT(m_targetMask & TARGET_FLAG_SOURCE_LOCATION);
m_src.Relocate(pos);
}
void SpellCastTargets::RemoveSrc()
{
m_targetMask &= ~(TARGET_FLAG_SOURCE_LOCATION);
}
SpellDestination const* SpellCastTargets::GetDst() const
{
return &m_dst;
}
WorldLocation const* SpellCastTargets::GetDstPos() const
{
return &m_dst._position;
}
void SpellCastTargets::SetDst(float x, float y, float z, float orientation, uint32 mapId)
{
m_dst = SpellDestination(x, y, z, orientation, mapId);
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
}
void SpellCastTargets::SetDst(Position const& pos)
{
m_dst = SpellDestination(pos);
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
}
void SpellCastTargets::SetDst(WorldObject const& wObj)
{
m_dst = SpellDestination(wObj);
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
}
void SpellCastTargets::SetDst(SpellDestination const& spellDest)
{
m_dst = spellDest;
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
}
void SpellCastTargets::SetDst(SpellCastTargets const& spellTargets)
{
m_dst = spellTargets.m_dst;
m_targetMask |= TARGET_FLAG_DEST_LOCATION;
}
void SpellCastTargets::ModDst(Position const& pos)
{
ASSERT(m_targetMask & TARGET_FLAG_DEST_LOCATION);
m_dst.Relocate(pos);
}
void SpellCastTargets::ModDst(SpellDestination const& spellDest)
{
ASSERT(m_targetMask & TARGET_FLAG_DEST_LOCATION);
m_dst = spellDest;
}
void SpellCastTargets::RemoveDst()
{
m_targetMask &= ~(TARGET_FLAG_DEST_LOCATION);
}
bool SpellCastTargets::HasSrc() const
{
return (GetTargetMask() & TARGET_FLAG_SOURCE_LOCATION) != 0;
}
bool SpellCastTargets::HasDst() const
{
return (GetTargetMask() & TARGET_FLAG_DEST_LOCATION) != 0;
}
void SpellCastTargets::Update(Unit* caster)
{
m_objectTarget = !m_objectTargetGUID.IsEmpty() ? ((m_objectTargetGUID == caster->GetGUID()) ? caster : ObjectAccessor::GetWorldObject(*caster, m_objectTargetGUID)) : NULL;
m_itemTarget = NULL;
if (caster->GetTypeId() == TYPEID_PLAYER)
{
Player* player = caster->ToPlayer();
if (m_targetMask & TARGET_FLAG_ITEM)
m_itemTarget = player->GetItemByGuid(m_itemTargetGUID);
else if (m_targetMask & TARGET_FLAG_TRADE_ITEM)
{
if (m_itemTargetGUID == ObjectGuid::TradeItem)
if (TradeData* pTrade = player->GetTradeData())
m_itemTarget = pTrade->GetTraderData()->GetItem(TRADE_SLOT_NONTRADED);
}
if (m_itemTarget)
m_itemTargetEntry = m_itemTarget->GetEntry();
}
// update positions by transport move
if (HasSrc() && !m_src._transportGUID.IsEmpty())
{
if (WorldObject* transport = ObjectAccessor::GetWorldObject(*caster, m_src._transportGUID))
{
m_src._position.Relocate(transport);
m_src._position.RelocateOffset(m_src._transportOffset);
}
}
if (HasDst() && !m_dst._transportGUID.IsEmpty())
{
if (WorldObject* transport = ObjectAccessor::GetWorldObject(*caster, m_dst._transportGUID))
{
m_dst._position.Relocate(transport);
m_dst._position.RelocateOffset(m_dst._transportOffset);
}
}
}
void SpellCastTargets::OutDebug() const
{
if (!m_targetMask)
TC_LOG_DEBUG("spells", "No targets");
TC_LOG_DEBUG("spells", "target mask: %u", m_targetMask);
if (m_targetMask & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK | TARGET_FLAG_GAMEOBJECT_MASK))
TC_LOG_DEBUG("spells", "Object target: %s", m_objectTargetGUID.ToString().c_str());
if (m_targetMask & TARGET_FLAG_ITEM)
TC_LOG_DEBUG("spells", "Item target: %s", m_itemTargetGUID.ToString().c_str());
if (m_targetMask & TARGET_FLAG_TRADE_ITEM)
TC_LOG_DEBUG("spells", "Trade item target: %s", m_itemTargetGUID.ToString().c_str());
if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION)
TC_LOG_DEBUG("spells", "Source location: transport guid:%s trans offset: %s position: %s", m_src._transportGUID.ToString().c_str(), m_src._transportOffset.ToString().c_str(), m_src._position.ToString().c_str());
if (m_targetMask & TARGET_FLAG_DEST_LOCATION)
TC_LOG_DEBUG("spells", "Destination location: transport guid:%s trans offset: %s position: %s", m_dst._transportGUID.ToString().c_str(), m_dst._transportOffset.ToString().c_str(), m_dst._position.ToString().c_str());
if (m_targetMask & TARGET_FLAG_STRING)
TC_LOG_DEBUG("spells", "String: %s", m_strTarget.c_str());
TC_LOG_DEBUG("spells", "speed: %f", m_speed);
TC_LOG_DEBUG("spells", "pitch: %f", m_pitch);
}
SpellValue::SpellValue(SpellInfo const* proto, Unit const* caster)
{
memset(EffectBasePoints, 0, sizeof(EffectBasePoints));
memset(EffectTriggerSpell, 0, sizeof(EffectTriggerSpell));
for (SpellEffectInfo const* effect : proto->GetEffects())
{
if (effect)
{
EffectBasePoints[effect->EffectIndex] = effect->CalcBaseValue(caster, nullptr, 0, -1);
EffectTriggerSpell[effect->EffectIndex] = effect->TriggerSpell;
}
}
CustomBasePointsMask = 0;
MaxAffectedTargets = proto->MaxAffectedTargets;
RadiusMod = 1.0f;
AuraStackAmount = 1;
Duration = 0;
}
class TC_GAME_API SpellEvent : public BasicEvent
{
public:
SpellEvent(Spell* spell);
virtual ~SpellEvent();
virtual bool Execute(uint64 e_time, uint32 p_time) override;
virtual void Abort(uint64 e_time) override;
virtual bool IsDeletable() const override;
protected:
Spell* m_Spell;
};
Spell::Spell(Unit* caster, SpellInfo const* info, TriggerCastFlags triggerFlags, ObjectGuid originalCasterGUID, bool skipCheck) :
m_spellInfo(info), m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerOrOwner()) ? caster->GetCharmerOrOwner() : caster),
m_spellValue(new SpellValue(m_spellInfo, caster)), _spellEvent(nullptr)
{
m_customError = SPELL_CUSTOM_ERROR_NONE;
m_skipCheck = skipCheck;
m_fromClient = false;
m_selfContainer = NULL;
m_referencedFromCurrentSpell = false;
m_executedCurrently = false;
m_needComboPoints = m_spellInfo->NeedsComboPoints();
m_comboPointGain = 0;
m_delayStart = 0;
m_delayAtDamageCount = 0;
m_applyMultiplierMask = 0;
memset(m_damageMultipliers, 0, sizeof(m_damageMultipliers));
// Get data for type of attack
m_attackType = info->GetAttackType();
m_spellSchoolMask = info->GetSchoolMask(); // Can be override for some spell (wand shoot for example)
if (m_attackType == RANGED_ATTACK)
// wand case
if ((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId() == TYPEID_PLAYER)
if (Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK))
m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetTemplate()->GetDamageType());
if (!originalCasterGUID.IsEmpty())
m_originalCasterGUID = originalCasterGUID;
else
m_originalCasterGUID = m_caster->GetGUID();
if (m_originalCasterGUID == m_caster->GetGUID())
m_originalCaster = m_caster;
else
{
m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID);
if (m_originalCaster && !m_originalCaster->IsInWorld())
m_originalCaster = NULL;
}
m_spellState = SPELL_STATE_NULL;
_triggeredCastFlags = triggerFlags;
if (info->HasAttribute(SPELL_ATTR4_CAN_CAST_WHILE_CASTING))
_triggeredCastFlags = TriggerCastFlags(uint32(_triggeredCastFlags) | TRIGGERED_CAN_CAST_WHILE_CASTING_MASK);
m_CastItem = NULL;
m_castItemGUID.Clear();
m_castItemEntry = 0;
m_castItemLevel = -1;
m_castFlagsEx = 0;
unitTarget = NULL;
itemTarget = NULL;
gameObjTarget = NULL;
destTarget = NULL;
damage = 0;
targetMissInfo = SPELL_MISS_NONE;
variance = 0.0f;
effectHandleMode = SPELL_EFFECT_HANDLE_LAUNCH;
effectInfo = nullptr;
m_damage = 0;
m_healing = 0;
m_procAttacker = 0;
m_procVictim = 0;
m_hitMask = 0;
focusObject = NULL;
m_castId = ObjectGuid::Create<HighGuid::Cast>(SPELL_CAST_SOURCE_NORMAL, m_caster->GetMapId(), m_spellInfo->Id, m_caster->GetMap()->GenerateLowGuid<HighGuid::Cast>());
memset(m_misc.Raw.Data, 0, sizeof(m_misc.Raw.Data));
m_SpellVisual = caster->GetCastSpellXSpellVisualId(m_spellInfo);
m_triggeredByAuraSpell = NULL;
m_spellAura = NULL;
//Auto Shot & Shoot (wand)
m_autoRepeat = m_spellInfo->IsAutoRepeatRangedSpell();
m_runesState = 0;
m_casttime = 0; // setup to correct value in Spell::prepare, must not be used before.
m_timer = 0; // will set to castime in prepare
m_channeledDuration = 0; // will be setup in Spell::handle_immediate
m_launchHandled = false;
m_immediateHandled = false;
m_currentTargetInfo = nullptr;
m_channelTargetEffectMask = 0;
// Determine if spell can be reflected back to the caster
// Patch 1.2 notes: Spell Reflection no longer reflects abilities
m_canReflect = m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !m_spellInfo->HasAttribute(SPELL_ATTR0_ABILITY)
&& !m_spellInfo->HasAttribute(SPELL_ATTR1_CANT_BE_REFLECTED) && !m_spellInfo->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)
&& !m_spellInfo->IsPassive();
CleanupTargetList();
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
m_destTargets[i] = SpellDestination(*m_caster);
dispellSuccess = false;
}
Spell::~Spell()
{
// unload scripts
for (auto itr = m_loadedScripts.begin(); itr != m_loadedScripts.end(); ++itr)
{
(*itr)->_Unload();
delete (*itr);
}
if (m_referencedFromCurrentSpell && m_selfContainer && *m_selfContainer == this)
{
// Clean the reference to avoid later crash.
// If this error is repeating, we may have to add an ASSERT to better track down how we get into this case.
TC_LOG_ERROR("spells", "SPELL: deleting spell for spell ID %u. However, spell still referenced.", m_spellInfo->Id);
*m_selfContainer = NULL;
}
if (m_caster && m_caster->GetTypeId() == TYPEID_PLAYER)
ASSERT(m_caster->ToPlayer()->m_spellModTakingSpell != this);
delete m_spellValue;
}
void Spell::InitExplicitTargets(SpellCastTargets const& targets)
{
m_targets = targets;
m_targets.SetOrigUnitTarget(m_targets.GetUnitTarget());
// this function tries to correct spell explicit targets for spell
// client doesn't send explicit targets correctly sometimes - we need to fix such spells serverside
// this also makes sure that we correctly send explicit targets to client (removes redundant data)
uint32 neededTargets = m_spellInfo->GetExplicitTargetMask();
if (WorldObject* target = m_targets.GetObjectTarget())
{
// check if object target is valid with needed target flags
// for unit case allow corpse target mask because player with not released corpse is a unit target
if ((target->ToUnit() && !(neededTargets & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK)))
|| (target->ToGameObject() && !(neededTargets & TARGET_FLAG_GAMEOBJECT_MASK))
|| (target->ToCorpse() && !(neededTargets & TARGET_FLAG_CORPSE_MASK)))
m_targets.RemoveObjectTarget();
}
else
{
// try to select correct unit target if not provided by client or by serverside cast
if (neededTargets & (TARGET_FLAG_UNIT_MASK))
{
Unit* unit = NULL;
// try to use player selection as a target
if (Player* playerCaster = m_caster->ToPlayer())
{
// selection has to be found and to be valid target for the spell
if (Unit* selectedUnit = ObjectAccessor::GetUnit(*m_caster, playerCaster->GetTarget()))
if (m_spellInfo->CheckExplicitTarget(m_caster, selectedUnit) == SPELL_CAST_OK)
unit = selectedUnit;
}
// try to use attacked unit as a target
else if ((m_caster->GetTypeId() == TYPEID_UNIT) && neededTargets & (TARGET_FLAG_UNIT_ENEMY | TARGET_FLAG_UNIT))
unit = m_caster->GetVictim();
// didn't find anything - let's use self as target
if (!unit && neededTargets & (TARGET_FLAG_UNIT_RAID | TARGET_FLAG_UNIT_PARTY | TARGET_FLAG_UNIT_ALLY))
unit = m_caster;
m_targets.SetUnitTarget(unit);
}
}
// check if spell needs dst target
if (neededTargets & TARGET_FLAG_DEST_LOCATION)
{
// and target isn't set
if (!m_targets.HasDst())
{
// try to use unit target if provided
if (WorldObject* target = targets.GetObjectTarget())
m_targets.SetDst(*target);
// or use self if not available
else
m_targets.SetDst(*m_caster);
}
}
else
m_targets.RemoveDst();
if (neededTargets & TARGET_FLAG_SOURCE_LOCATION)
{
if (!targets.HasSrc())
m_targets.SetSrc(*m_caster);
}
else
m_targets.RemoveSrc();
}
void Spell::SelectExplicitTargets()
{
// here go all explicit target changes made to explicit targets after spell prepare phase is finished
if (Unit* target = m_targets.GetUnitTarget())
{
// check for explicit target redirection, for Grounding Totem for example
if (m_spellInfo->GetExplicitTargetMask() & TARGET_FLAG_UNIT_ENEMY
|| (m_spellInfo->GetExplicitTargetMask() & TARGET_FLAG_UNIT && !m_caster->IsFriendlyTo(target)))
{
Unit* redirect;
switch (m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MAGIC:
redirect = m_caster->GetMagicHitRedirectTarget(target, m_spellInfo);
break;
case SPELL_DAMAGE_CLASS_MELEE:
case SPELL_DAMAGE_CLASS_RANGED:
redirect = m_caster->GetMeleeHitRedirectTarget(target, m_spellInfo);
break;
default:
redirect = NULL;
break;
}
if (redirect && (redirect != target))
m_targets.SetUnitTarget(redirect);
}
}
}
void Spell::SelectSpellTargets()
{
// select targets for cast phase
SelectExplicitTargets();
uint32 processedAreaEffectsMask = 0;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
if (!effect)
continue;
// not call for empty effect.
// Also some spells use not used effect targets for store targets for dummy effect in triggered spells
if (!effect->IsEffect())
continue;
// set expected type of implicit targets to be sent to client
uint32 implicitTargetMask = GetTargetFlagMask(effect->TargetA.GetObjectType()) | GetTargetFlagMask(effect->TargetB.GetObjectType());
if (implicitTargetMask & TARGET_FLAG_UNIT)
m_targets.SetTargetFlag(TARGET_FLAG_UNIT);
if (implicitTargetMask & (TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_GAMEOBJECT_ITEM))
m_targets.SetTargetFlag(TARGET_FLAG_GAMEOBJECT);
SelectEffectImplicitTargets(SpellEffIndex(effect->EffectIndex), effect->TargetA, processedAreaEffectsMask);
SelectEffectImplicitTargets(SpellEffIndex(effect->EffectIndex), effect->TargetB, processedAreaEffectsMask);
// Select targets of effect based on effect type
// those are used when no valid target could be added for spell effect based on spell target type
// some spell effects use explicit target as a default target added to target map (like SPELL_EFFECT_LEARN_SPELL)
// some spell effects add target to target map only when target type specified (like SPELL_EFFECT_WEAPON)
// some spell effects don't add anything to target map (confirmed with sniffs) (like SPELL_EFFECT_DESTROY_ALL_TOTEMS)
SelectEffectTypeImplicitTargets(effect->EffectIndex);
if (m_targets.HasDst())
AddDestTarget(*m_targets.GetDst(), effect->EffectIndex);
if (m_spellInfo->IsChanneled())
{
// maybe do this for all spells?
if (m_UniqueTargetInfo.empty() && m_UniqueGOTargetInfo.empty() && m_UniqueItemInfo.empty() && !m_targets.HasDst())
{
SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS);
finish(false);
return;
}
uint32 mask = (1 << effect->EffectIndex);
for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->effectMask & mask)
{
m_channelTargetEffectMask |= mask;
break;
}
}
}
}
if (uint64 dstDelay = CalculateDelayMomentForDst(m_spellInfo->LaunchDelay))
m_delayMoment = dstDelay;
}
uint64 Spell::CalculateDelayMomentForDst(float launchDelay) const
{
if (m_targets.HasDst())
{
if (m_targets.HasTraj())
{
float speed = m_targets.GetSpeedXY();
if (speed > 0.0f)
return uint64(std::floor((m_targets.GetDist2d() / speed + launchDelay) * 1000.0f));
}
else if (m_spellInfo->HasAttribute(SPELL_ATTR9_SPECIAL_DELAY_CALCULATION))
return uint64(std::floor((m_spellInfo->Speed + launchDelay) * 1000.0f));
else if (m_spellInfo->Speed > 0.0f)
{
// We should not subtract caster size from dist calculation (fixes execution time desync with animation on client, eg. Malleable Goo cast by PP)
float dist = m_caster->GetExactDist(*m_targets.GetDstPos());
return uint64(std::floor((dist / m_spellInfo->Speed + launchDelay) * 1000.0f));
}
return uint64(std::floor(launchDelay * 1000.0f));
}
return 0;
}
void Spell::RecalculateDelayMomentForDst()
{
m_delayMoment = CalculateDelayMomentForDst(0.0f);
m_caster->m_Events.ModifyEventTime(_spellEvent, GetDelayStart() + m_delayMoment);
}
void Spell::SelectEffectImplicitTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32& processedEffectMask)
{
if (!targetType.GetTarget())
return;
uint32 effectMask = 1 << effIndex;
// set the same target list for all effects
// some spells appear to need this, however this requires more research
switch (targetType.GetSelectionCategory())
{
case TARGET_SELECT_CATEGORY_NEARBY:
case TARGET_SELECT_CATEGORY_CONE:
case TARGET_SELECT_CATEGORY_AREA:
//case TARGET_SELECT_CATEGORY_LINE:
// targets for effect already selected
if (effectMask & processedEffectMask)
return;
if (SpellEffectInfo const* _effect = m_spellInfo->GetEffect(effIndex))
{
// choose which targets we can select at once
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
//for (uint32 j = effIndex + 1; j < MAX_SPELL_EFFECTS; ++j)
if (!effect || effect->EffectIndex <= uint32(effIndex))
continue;
if (effect->IsEffect() &&
_effect->TargetA.GetTarget() == effect->TargetA.GetTarget() &&
_effect->TargetB.GetTarget() == effect->TargetB.GetTarget() &&
_effect->ImplicitTargetConditions == effect->ImplicitTargetConditions &&
_effect->CalcRadius(m_caster) == effect->CalcRadius(m_caster) &&
CheckScriptEffectImplicitTargets(effIndex, effect->EffectIndex))
{
effectMask |= 1 << effect->EffectIndex;
}
}
}
processedEffectMask |= effectMask;
break;
default:
break;
}
switch (targetType.GetSelectionCategory())
{
case TARGET_SELECT_CATEGORY_CHANNEL:
SelectImplicitChannelTargets(effIndex, targetType);
break;
case TARGET_SELECT_CATEGORY_NEARBY:
SelectImplicitNearbyTargets(effIndex, targetType, effectMask);
break;
case TARGET_SELECT_CATEGORY_CONE:
SelectImplicitConeTargets(effIndex, targetType, effectMask);
break;
case TARGET_SELECT_CATEGORY_AREA:
SelectImplicitAreaTargets(effIndex, targetType, effectMask);
break;
case TARGET_SELECT_CATEGORY_TRAJ:
// just in case there is no dest, explanation in SelectImplicitDestDestTargets
CheckDst();
SelectImplicitTrajTargets(effIndex, targetType);
break;
case TARGET_SELECT_CATEGORY_DEFAULT:
switch (targetType.GetObjectType())
{
case TARGET_OBJECT_TYPE_SRC:
switch (targetType.GetReferenceType())
{
case TARGET_REFERENCE_TYPE_CASTER:
m_targets.SetSrc(*m_caster);
break;
default:
ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT_SRC");
break;
}
break;
case TARGET_OBJECT_TYPE_DEST:
switch (targetType.GetReferenceType())
{
case TARGET_REFERENCE_TYPE_CASTER:
SelectImplicitCasterDestTargets(effIndex, targetType);
break;
case TARGET_REFERENCE_TYPE_TARGET:
SelectImplicitTargetDestTargets(effIndex, targetType);
break;
case TARGET_REFERENCE_TYPE_DEST:
SelectImplicitDestDestTargets(effIndex, targetType);
break;
default:
ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT_DEST");
break;
}
break;
default:
switch (targetType.GetReferenceType())
{
case TARGET_REFERENCE_TYPE_CASTER:
SelectImplicitCasterObjectTargets(effIndex, targetType);
break;
case TARGET_REFERENCE_TYPE_TARGET:
SelectImplicitTargetObjectTargets(effIndex, targetType);
break;
default:
ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT");
break;
}
break;
}
break;
case TARGET_SELECT_CATEGORY_NYI:
TC_LOG_DEBUG("spells", "SPELL: target type %u, found in spellID %u, effect %u is not implemented yet!", m_spellInfo->Id, effIndex, targetType.GetTarget());
break;
default:
ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target category");
break;
}
}
void Spell::SelectImplicitChannelTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER)
{
ASSERT(false && "Spell::SelectImplicitChannelTargets: received not implemented target reference type");
return;
}
Spell* channeledSpell = m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL);
if (!channeledSpell)
{
TC_LOG_DEBUG("spells", "Spell::SelectImplicitChannelTargets: cannot find channel spell for spell ID %u, effect %u", m_spellInfo->Id, effIndex);
return;
}
switch (targetType.GetTarget())
{
case TARGET_UNIT_CHANNEL_TARGET:
{
for (ObjectGuid const& channelTarget : m_originalCaster->m_unitData->ChannelObjects)
{
WorldObject* target = ObjectAccessor::GetUnit(*m_caster, channelTarget);
CallScriptObjectTargetSelectHandlers(target, effIndex, targetType);
// unit target may be no longer avalible - teleported out of map for example
Unit* unitTarget = target ? target->ToUnit() : nullptr;
if (unitTarget)
AddUnitTarget(unitTarget, 1 << effIndex);
else
TC_LOG_DEBUG("spells", "SPELL: cannot find channel spell target for spell ID %u, effect %u", m_spellInfo->Id, effIndex);
}
break;
}
case TARGET_DEST_CHANNEL_TARGET:
if (channeledSpell->m_targets.HasDst())
m_targets.SetDst(channeledSpell->m_targets);
else
{
auto const& channelObjects = m_originalCaster->m_unitData->ChannelObjects;
WorldObject* target = channelObjects.size() > 0 ? ObjectAccessor::GetWorldObject(*m_caster, *channelObjects.begin()) : nullptr;
if (target)
{
CallScriptObjectTargetSelectHandlers(target, effIndex, targetType);
if (target)
{
SpellDestination dest(*target);
CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType);
m_targets.SetDst(dest);
}
}
else
TC_LOG_DEBUG("spells", "SPELL: cannot find channel spell destination for spell ID %u, effect %u", m_spellInfo->Id, effIndex);
}
break;
case TARGET_DEST_CHANNEL_CASTER:
{
SpellDestination dest(*channeledSpell->GetCaster());
CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType);
m_targets.SetDst(dest);
break;
}
default:
ASSERT(false && "Spell::SelectImplicitChannelTargets: received not implemented target type");
break;
}
}
void Spell::SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask)
{
if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER)
{
ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented target reference type");
return;
}
SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex);
if (!effect)
return;
float range = 0.0f;
switch (targetType.GetCheckType())
{
case TARGET_CHECK_ENEMY:
range = m_spellInfo->GetMaxRange(false, m_caster, this);
break;
case TARGET_CHECK_ALLY:
case TARGET_CHECK_PARTY:
case TARGET_CHECK_RAID:
case TARGET_CHECK_RAID_CLASS:
case TARGET_CHECK_RAID_DEATH:
range = m_spellInfo->GetMaxRange(true, m_caster, this);
break;
case TARGET_CHECK_ENTRY:
case TARGET_CHECK_DEFAULT:
range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive(), m_caster, this);
break;
default:
ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented selection check type");
break;
}
ConditionContainer* condList = effect->ImplicitTargetConditions;
// handle emergency case - try to use other provided targets if no conditions provided
if (targetType.GetCheckType() == TARGET_CHECK_ENTRY && (!condList || condList->empty()))
{
TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: no conditions entry for target with TARGET_CHECK_ENTRY of spell ID %u, effect %u - selecting default targets", m_spellInfo->Id, effIndex);
switch (targetType.GetObjectType())
{
case TARGET_OBJECT_TYPE_GOBJ:
if (m_spellInfo->RequiresSpellFocus)
{
if (focusObject)
AddGOTarget(focusObject, effMask);
else
{
SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS);
finish(false);
}
return;
}
break;
case TARGET_OBJECT_TYPE_DEST:
if (m_spellInfo->RequiresSpellFocus)
{
if (focusObject)
{
SpellDestination dest(*focusObject);
CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType);
m_targets.SetDst(dest);
}
else
{
SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS);
finish(false);
}
return;
}
break;
default:
break;
}
}
WorldObject* target = SearchNearbyTarget(range, targetType.GetObjectType(), targetType.GetCheckType(), condList);
if (!target)
{
TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: cannot find nearby target for spell ID %u, effect %u", m_spellInfo->Id, effIndex);
SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS);
finish(false);
return;
}
CallScriptObjectTargetSelectHandlers(target, effIndex, targetType);
if (!target)
{
TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: OnObjectTargetSelect script hook for spell Id %u set NULL target, effect %u", m_spellInfo->Id, effIndex);
SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS);
finish(false);
return;
}
switch (targetType.GetObjectType())
{
case TARGET_OBJECT_TYPE_UNIT:
if (Unit* unit = target->ToUnit())
AddUnitTarget(unit, effMask, true, false);
else
{
TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: OnObjectTargetSelect script hook for spell Id %u set object of wrong type, expected unit, got %s, effect %u", m_spellInfo->Id, target->GetGUID().GetTypeName(), effMask);
SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS);
finish(false);
return;
}
break;
case TARGET_OBJECT_TYPE_GOBJ:
if (GameObject* gobjTarget = target->ToGameObject())
AddGOTarget(gobjTarget, effMask);
else
{
TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: OnObjectTargetSelect script hook for spell Id %u set object of wrong type, expected gameobject, got %s, effect %u", m_spellInfo->Id, target->GetGUID().GetTypeName(), effMask);
SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS);
finish(false);
return;
}
break;
case TARGET_OBJECT_TYPE_DEST:
{
SpellDestination dest(*target);
CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType);
m_targets.SetDst(dest);
break;
}
default:
ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented target object type");
break;
}
SelectImplicitChainTargets(effIndex, targetType, target, effMask);
}
void Spell::SelectImplicitConeTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask)
{
if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER)
{
ASSERT(false && "Spell::SelectImplicitConeTargets: received not implemented target reference type");
return;
}
std::list<WorldObject*> targets;
SpellTargetObjectTypes objectType = targetType.GetObjectType();
SpellTargetCheckTypes selectionType = targetType.GetCheckType();
SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex);
if (!effect)
return;
ConditionContainer* condList = effect->ImplicitTargetConditions;
float radius = effect->CalcRadius(m_caster) * m_spellValue->RadiusMod;
if (uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList))
{
Trinity::WorldObjectSpellConeTargetCheck check(DegToRad(m_spellInfo->ConeAngle), m_spellInfo->Width ? m_spellInfo->Width : m_caster->GetCombatReach(), radius, m_caster, m_spellInfo, selectionType, condList);
Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellConeTargetCheck> searcher(m_caster, targets, check, containerTypeMask);
SearchTargets<Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellConeTargetCheck> >(searcher, containerTypeMask, m_caster, m_caster, radius);
CallScriptObjectAreaTargetSelectHandlers(targets, effIndex, targetType);
if (!targets.empty())
{
// Other special target selection goes here
if (uint32 maxTargets = m_spellValue->MaxAffectedTargets)
Trinity::Containers::RandomResize(targets, maxTargets);
for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
{
if (Unit* unit = (*itr)->ToUnit())
AddUnitTarget(unit, effMask, false);
else if (GameObject* gObjTarget = (*itr)->ToGameObject())
AddGOTarget(gObjTarget, effMask);
}
}
}
}
void Spell::SelectImplicitLineTargets(SpellEffIndex /*effIndex*/, SpellImplicitTargetInfo const& /*targetType*/, uint32 /*effMask*/)
{
/*if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER)
{
ASSERT(false && "Spell::SelectImplicitLineTargets: received not implemented target reference type");
return;
}
std::list<WorldObject*> targets;
SpellTargetObjectTypes objectType = targetType.GetObjectType();
SpellTargetCheckTypes selectionType = targetType.GetCheckType();
float radius = m_spellInfo->GetEffect(effIndex)->CalcRadius(m_caster, this);
if (uint32 containerTypeMask = GetSearcherTypeMask(objectType, GetEffect(effIndex)->ImplicitTargetConditions))
{
Trinity::WorldObjectSpellLineTargetCheck check(radius, m_caster, m_spellInfo, selectionType, GetEffect(effIndex)->ImplicitTargetConditions);
Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellLineTargetCheck> searcher(m_caster, targets, check, containerTypeMask);
SearchTargets<Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellLineTargetCheck> >(searcher, containerTypeMask, m_caster, m_caster, radius);
CallScriptObjectAreaTargetSelectHandlers(targets, effIndex, targetType);
if (!targets.empty())
{
if (uint32 maxTargets = m_spellValue->MaxAffectedTargets)
Trinity::Containers::RandomResize(targets, maxTargets);
for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
{
if (Unit* unitTarget = (*itr)->ToUnit())
AddUnitTarget(unitTarget, effMask, false);
else if (GameObject* gObjTarget = (*itr)->ToGameObject())
AddGOTarget(gObjTarget, effMask);
}
}
}*/
}
void Spell::SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask)
{
Unit* referer = NULL;
switch (targetType.GetReferenceType())
{
case TARGET_REFERENCE_TYPE_SRC:
case TARGET_REFERENCE_TYPE_DEST:
case TARGET_REFERENCE_TYPE_CASTER:
referer = m_caster;
break;
case TARGET_REFERENCE_TYPE_TARGET:
referer = m_targets.GetUnitTarget();
break;
case TARGET_REFERENCE_TYPE_LAST:
{
// find last added target for this effect
for (std::vector<TargetInfo>::reverse_iterator ihit = m_UniqueTargetInfo.rbegin(); ihit != m_UniqueTargetInfo.rend(); ++ihit)
{
if (ihit->effectMask & (1 << effIndex))
{
referer = ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
break;
}
}
break;
}
default:
ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type");
return;
}
if (!referer)
return;
Position const* center = NULL;
switch (targetType.GetReferenceType())
{
case TARGET_REFERENCE_TYPE_SRC:
center = m_targets.GetSrcPos();
break;
case TARGET_REFERENCE_TYPE_DEST:
center = m_targets.GetDstPos();
break;
case TARGET_REFERENCE_TYPE_CASTER:
case TARGET_REFERENCE_TYPE_TARGET:
case TARGET_REFERENCE_TYPE_LAST:
center = referer;
break;
default:
ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type");
return;
}
std::list<WorldObject*> targets;
SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex);
if (!effect)
return;
switch (targetType.GetTarget())
{
case TARGET_UNIT_TARGET_ALLY_OR_RAID:
if (Unit* targetedUnit = m_targets.GetUnitTarget())
{
if (!m_caster->IsInRaidWith(targetedUnit))
{
targets.push_back(m_targets.GetUnitTarget());
CallScriptObjectAreaTargetSelectHandlers(targets, effIndex, targetType);
if (!targets.empty())
{
// Other special target selection goes here
if (uint32 maxTargets = m_spellValue->MaxAffectedTargets)
Trinity::Containers::RandomResize(targets, maxTargets);
for (WorldObject* target : targets)
{
if (Unit* unit = target->ToUnit())
AddUnitTarget(unit, effMask, false, true, center);
else if (GameObject* gObjTarget = target->ToGameObject())
AddGOTarget(gObjTarget, effMask);
}
}
return;
}
center = targetedUnit;
}
break;
case TARGET_UNIT_CASTER_AND_SUMMONS:
targets.push_back(m_caster);
break;
default:
break;
}
float radius = effect->CalcRadius(m_caster) * m_spellValue->RadiusMod;
if (radius)
SearchAreaTargets(targets, radius, center, referer, targetType.GetObjectType(), targetType.GetCheckType(), effect->ImplicitTargetConditions);
CallScriptObjectAreaTargetSelectHandlers(targets, effIndex, targetType);
if (!targets.empty())
{
// Other special target selection goes here
if (uint32 maxTargets = m_spellValue->MaxAffectedTargets)
Trinity::Containers::RandomResize(targets, maxTargets);
for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
{
if (Unit* unit = (*itr)->ToUnit())
AddUnitTarget(unit, effMask, false, true, center);
else if (GameObject* gObjTarget = (*itr)->ToGameObject())
AddGOTarget(gObjTarget, effMask);
}
}
}
void Spell::SelectImplicitCasterDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
SpellDestination dest(*m_caster);
switch (targetType.GetTarget())
{
case TARGET_DEST_CASTER:
break;
case TARGET_DEST_HOME:
if (Player* playerCaster = m_caster->ToPlayer())
dest = SpellDestination(playerCaster->m_homebindX, playerCaster->m_homebindY, playerCaster->m_homebindZ, playerCaster->GetOrientation(), playerCaster->m_homebindMapId);
break;
case TARGET_DEST_DB:
if (SpellTargetPosition const* st = sSpellMgr->GetSpellTargetPosition(m_spellInfo->Id, effIndex))
{
/// @todo fix this check
if (m_spellInfo->HasEffect(SPELL_EFFECT_TELEPORT_UNITS) || m_spellInfo->HasEffect(SPELL_EFFECT_BIND))
dest = SpellDestination(st->target_X, st->target_Y, st->target_Z, st->target_Orientation, (int32)st->target_mapId);
else if (st->target_mapId == m_caster->GetMapId())
dest = SpellDestination(st->target_X, st->target_Y, st->target_Z, st->target_Orientation);
}
else
{
TC_LOG_DEBUG("spells", "SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id);
if (WorldObject* target = m_targets.GetObjectTarget())
dest = SpellDestination(*target);
}
break;
case TARGET_DEST_CASTER_FISHING:
{
float minDist = m_spellInfo->GetMinRange(true);
float maxDist = m_spellInfo->GetMaxRange(true);
float dist = frand(minDist, maxDist);
float x, y, z;
float angle = float(rand_norm()) * static_cast<float>(M_PI * 35.0f / 180.0f) - static_cast<float>(M_PI * 17.5f / 180.0f);
m_caster->GetClosePoint(x, y, z, DEFAULT_PLAYER_BOUNDING_RADIUS, dist, angle);
float ground = m_caster->GetMap()->GetHeight(m_caster->GetPhaseShift(), x, y, z, true, 50.0f);
float liquidLevel = VMAP_INVALID_HEIGHT_VALUE;
LiquidData liquidData;
if (m_caster->GetMap()->GetLiquidStatus(m_caster->GetPhaseShift(), x, y, z, MAP_ALL_LIQUIDS, &liquidData))
liquidLevel = liquidData.level;
if (liquidLevel <= ground) // When there is no liquid Map::GetWaterOrGroundLevel returns ground level
{
SendCastResult(SPELL_FAILED_NOT_HERE);
SendChannelUpdate(0);
finish(false);
return;
}
if (ground + 0.75 > liquidLevel)
{
SendCastResult(SPELL_FAILED_TOO_SHALLOW);
SendChannelUpdate(0);
finish(false);
return;
}
dest = SpellDestination(x, y, liquidLevel, m_caster->GetOrientation());
break;
}
case TARGET_DEST_CASTER_GROUND:
{
float groundZ = m_caster->GetMap()->GetHeight(m_caster->GetPhaseShift(), m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ(), true, MAX_HEIGHT);
dest = SpellDestination(m_caster->GetPositionX(), m_caster->GetPositionY(), groundZ, m_caster->GetOrientation());
break;
}
case TARGET_DEST_LAST_QUEST_GIVER:
{
if (SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex))
{
float dist = effect->CalcRadius(m_caster);
if (Player* casterPlayer = m_caster->ToPlayer())
if (WorldObject* target = casterPlayer->GetLastQuestGiver())
if (casterPlayer->GetDistance(target) < dist)
dest = SpellDestination(*target);
}
break;
}
case TARGET_DEST_SUMMONER:
if (TempSummon const* casterSummon = m_caster->ToTempSummon())
if (Unit const* summoner = casterSummon->GetSummoner())
dest = SpellDestination(*summoner);
break;
default:
{
if (SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex))
{
float dist = effect->CalcRadius(m_caster);
float angle = targetType.CalcDirectionAngle();
float objSize = m_caster->GetCombatReach();
switch (targetType.GetTarget())
{
case TARGET_DEST_CASTER_SUMMON:
dist = PET_FOLLOW_DIST;
break;
case TARGET_DEST_CASTER_RANDOM:
if (dist > objSize)
dist = objSize + (dist - objSize) * float(rand_norm());
break;
case TARGET_DEST_CASTER_FRONT_LEFT:
case TARGET_DEST_CASTER_BACK_LEFT:
case TARGET_DEST_CASTER_FRONT_RIGHT:
case TARGET_DEST_CASTER_BACK_RIGHT:
{
static float const DefaultTotemDistance = 3.0f;
if (!effect->HasRadius() && !effect->HasMaxRadius())
dist = DefaultTotemDistance;
break;
}
default:
break;
}
if (dist < objSize)
dist = objSize;
Position pos = dest._position;
m_caster->MovePositionToFirstCollision(pos, dist, angle);
dest.Relocate(pos);
}
break;
}
}
CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType);
m_targets.SetDst(dest);
}
void Spell::SelectImplicitTargetDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
ASSERT(m_targets.GetObjectTarget() && "Spell::SelectImplicitTargetDestTargets - no explicit object target available!");
WorldObject* target = m_targets.GetObjectTarget();
SpellDestination dest(*target);
switch (targetType.GetTarget())
{
case TARGET_DEST_TARGET_ENEMY:
case TARGET_DEST_TARGET_ANY:
case TARGET_DEST_TARGET_ALLY:
break;
default:
{
if (SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex))
{
float angle = targetType.CalcDirectionAngle();
float objSize = target->GetCombatReach();
float dist = effect->CalcRadius(m_caster);
if (dist < objSize)
dist = objSize;
else if (targetType.GetTarget() == TARGET_DEST_TARGET_RANDOM)
dist = objSize + (dist - objSize) * float(rand_norm());
Position pos = dest._position;
target->MovePositionToFirstCollision(pos, dist, angle);
dest.Relocate(pos);
}
break;
}
}
CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType);
m_targets.SetDst(dest);
}
void Spell::SelectImplicitDestDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
// set destination to caster if no dest provided
// can only happen if previous destination target could not be set for some reason
// (not found nearby target, or channel target for example
// maybe we should abort the spell in such case?
CheckDst();
SpellDestination dest(*m_targets.GetDst());
switch (targetType.GetTarget())
{
case TARGET_DEST_DYNOBJ_ENEMY:
case TARGET_DEST_DYNOBJ_ALLY:
case TARGET_DEST_DYNOBJ_NONE:
case TARGET_DEST_DEST:
return;
default:
{
if (SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex))
{
float angle = targetType.CalcDirectionAngle();
float dist = effect->CalcRadius(m_caster);
if (targetType.GetTarget() == TARGET_DEST_DEST_RANDOM)
dist *= float(rand_norm());
Position pos = dest._position;
m_caster->MovePositionToFirstCollision(pos, dist, angle);
dest.Relocate(pos);
}
break;
}
}
CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType);
m_targets.ModDst(dest);
}
void Spell::SelectImplicitCasterObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
WorldObject* target = NULL;
bool checkIfValid = true;
switch (targetType.GetTarget())
{
case TARGET_UNIT_CASTER:
target = m_caster;
checkIfValid = false;
break;
case TARGET_UNIT_MASTER:
target = m_caster->GetCharmerOrOwner();
break;
case TARGET_UNIT_PET:
target = m_caster->GetGuardianPet();
break;
case TARGET_UNIT_SUMMONER:
if (m_caster->IsSummon())
target = m_caster->ToTempSummon()->GetSummoner();
break;
case TARGET_UNIT_VEHICLE:
target = m_caster->GetVehicleBase();
break;
case TARGET_UNIT_PASSENGER_0:
case TARGET_UNIT_PASSENGER_1:
case TARGET_UNIT_PASSENGER_2:
case TARGET_UNIT_PASSENGER_3:
case TARGET_UNIT_PASSENGER_4:
case TARGET_UNIT_PASSENGER_5:
case TARGET_UNIT_PASSENGER_6:
case TARGET_UNIT_PASSENGER_7:
if (m_caster->IsVehicle())
target = m_caster->GetVehicleKit()->GetPassenger(targetType.GetTarget() - TARGET_UNIT_PASSENGER_0);
break;
case TARGET_UNIT_OWN_CRITTER:
target = ObjectAccessor::GetCreatureOrPetOrVehicle(*m_caster, m_caster->GetCritterGUID());
break;
default:
break;
}
CallScriptObjectTargetSelectHandlers(target, effIndex, targetType);
if (target && target->ToUnit())
AddUnitTarget(target->ToUnit(), 1 << effIndex, checkIfValid);
}
void Spell::SelectImplicitTargetObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
ASSERT((m_targets.GetObjectTarget() || m_targets.GetItemTarget()) && "Spell::SelectImplicitTargetObjectTargets - no explicit object or item target available!");
WorldObject* target = m_targets.GetObjectTarget();
CallScriptObjectTargetSelectHandlers(target, effIndex, targetType);
if (target)
{
if (Unit* unit = target->ToUnit())
AddUnitTarget(unit, 1 << effIndex, true, false);
else if (GameObject* gobj = target->ToGameObject())
AddGOTarget(gobj, 1 << effIndex);
SelectImplicitChainTargets(effIndex, targetType, target, 1 << effIndex);
}
// Script hook can remove object target and we would wrongly land here
else if (Item* item = m_targets.GetItemTarget())
AddItemTarget(item, 1 << effIndex);
}
void Spell::SelectImplicitChainTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, WorldObject* target, uint32 effMask)
{
SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex);
if (!effect)
return;
uint32 maxTargets = effect->ChainTargets;
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, maxTargets, this);
if (maxTargets > 1)
{
// mark damage multipliers as used
for (SpellEffectInfo const* eff : m_spellInfo->GetEffects())
if (eff && (effMask & (1 << eff->EffectIndex)))
m_damageMultipliers[eff->EffectIndex] = 1.0f;
m_applyMultiplierMask |= effMask;
std::list<WorldObject*> targets;
SearchChainTargets(targets, maxTargets - 1, target, targetType.GetObjectType(), targetType.GetCheckType()
, effect->ImplicitTargetConditions, targetType.GetTarget() == TARGET_UNIT_TARGET_CHAINHEAL_ALLY);
// Chain primary target is added earlier
CallScriptObjectAreaTargetSelectHandlers(targets, effIndex, targetType);
for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
if (Unit* unit = (*itr)->ToUnit())
AddUnitTarget(unit, effMask, false);
}
}
float tangent(float x)
{
x = std::tan(x);
//if (x < std::numeric_limits<float>::max() && x > -std::numeric_limits<float>::max()) return x;
//if (x >= std::numeric_limits<float>::max()) return std::numeric_limits<float>::max();
//if (x <= -std::numeric_limits<float>::max()) return -std::numeric_limits<float>::max();
if (x < 100000.0f && x > -100000.0f) return x;
if (x >= 100000.0f) return 100000.0f;
if (x <= 100000.0f) return -100000.0f;
return 0.0f;
}
void Spell::SelectImplicitTrajTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
if (!m_targets.HasTraj())
return;
float dist2d = m_targets.GetDist2d();
if (!dist2d)
return;
Position srcPos = *m_targets.GetSrcPos();
srcPos.SetOrientation(m_caster->GetOrientation());
float srcToDestDelta = m_targets.GetDstPos()->m_positionZ - srcPos.m_positionZ;
SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex);
std::list<WorldObject*> targets;
Trinity::WorldObjectSpellTrajTargetCheck check(dist2d, &srcPos, m_caster, m_spellInfo, targetType.GetCheckType(), effect->ImplicitTargetConditions);
Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellTrajTargetCheck> searcher(m_caster, targets, check, GRID_MAP_TYPE_MASK_ALL);
SearchTargets<Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellTrajTargetCheck> > (searcher, GRID_MAP_TYPE_MASK_ALL, m_caster, &srcPos, dist2d);
if (targets.empty())
return;
targets.sort(Trinity::ObjectDistanceOrderPred(m_caster));
float b = tangent(m_targets.GetPitch());
float a = (srcToDestDelta - dist2d * b) / (dist2d * dist2d);
if (a > -0.0001f)
a = 0;
// We should check if triggered spell has greater range (which is true in many cases, and initial spell has too short max range)
// limit max range to 300 yards, sometimes triggered spells can have 50000yds
float bestDist = m_spellInfo->GetMaxRange(false);
if (SpellInfo const* triggerSpellInfo = sSpellMgr->GetSpellInfo(effect->TriggerSpell, GetCastDifficulty()))
bestDist = std::min(std::max(bestDist, triggerSpellInfo->GetMaxRange(false)), std::min(dist2d, 300.0f));
std::list<WorldObject*>::const_iterator itr = targets.begin();
for (; itr != targets.end(); ++itr)
{
if (m_spellInfo->CheckTarget(m_caster, *itr, true) != SPELL_CAST_OK)
continue;
if (Unit* unit = (*itr)->ToUnit())
{
if (m_caster == *itr || m_caster->IsOnVehicle(unit) || unit->GetVehicle())
continue;
if (Creature* creatureTarget = unit->ToCreature())
{
if (!(creatureTarget->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_CAN_COLLIDE_WITH_MISSILES))
continue;
}
}
const float size = std::max((*itr)->GetCombatReach(), 1.0f);
const float objDist2d = srcPos.GetExactDist2d(*itr);
const float dz = (*itr)->GetPositionZ() - srcPos.m_positionZ;
const float horizontalDistToTraj = std::fabs(objDist2d * std::sin(srcPos.GetRelativeAngle(*itr)));
const float sizeFactor = std::cos((horizontalDistToTraj / size) * (M_PI / 2.0f));
const float distToHitPoint = std::max(objDist2d * std::cos(srcPos.GetRelativeAngle(*itr)) - size * sizeFactor, 0.0f);
const float height = distToHitPoint * (a * distToHitPoint + b);
if (fabs(dz - height) > size + b / 2.0f + TRAJECTORY_MISSILE_SIZE)
continue;
if (distToHitPoint < bestDist)
{
bestDist = distToHitPoint;
break;
}
}
if (dist2d > bestDist)
{
float x = m_targets.GetSrcPos()->m_positionX + std::cos(m_caster->GetOrientation()) * bestDist;
float y = m_targets.GetSrcPos()->m_positionY + std::sin(m_caster->GetOrientation()) * bestDist;
float z = m_targets.GetSrcPos()->m_positionZ + bestDist * (a * bestDist + b);
SpellDestination dest(x, y, z, m_caster->GetOrientation());
CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType);
m_targets.ModDst(dest);
}
if (Vehicle* veh = m_caster->GetVehicleKit())
veh->SetLastShootPos(*m_targets.GetDstPos());
}
void Spell::SelectEffectTypeImplicitTargets(uint32 effIndex)
{
// special case for SPELL_EFFECT_SUMMON_RAF_FRIEND and SPELL_EFFECT_SUMMON_PLAYER
/// @todo this is a workaround - target shouldn't be stored in target map for those spells
SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex);
if (!effect)
return;
switch (effect->Effect)
{
case SPELL_EFFECT_SUMMON_RAF_FRIEND:
case SPELL_EFFECT_SUMMON_PLAYER:
if (m_caster->GetTypeId() == TYPEID_PLAYER && !m_caster->GetTarget().IsEmpty())
{
WorldObject* target = ObjectAccessor::FindPlayer(m_caster->GetTarget());
CallScriptObjectTargetSelectHandlers(target, SpellEffIndex(effIndex), SpellImplicitTargetInfo());
if (target && target->ToPlayer())
AddUnitTarget(target->ToUnit(), 1 << effIndex, false);
}
return;
default:
break;
}
// select spell implicit targets based on effect type
if (!effect->GetImplicitTargetType())
return;
uint32 targetMask = effect->GetMissingTargetMask();
if (!targetMask)
return;
WorldObject* target = NULL;
switch (effect->GetImplicitTargetType())
{
// add explicit object target or self to the target map
case EFFECT_IMPLICIT_TARGET_EXPLICIT:
// player which not released his spirit is Unit, but target flag for it is TARGET_FLAG_CORPSE_MASK
if (targetMask & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK))
{
if (Unit* unit = m_targets.GetUnitTarget())
target = unit;
else if (targetMask & TARGET_FLAG_CORPSE_MASK)
{
if (Corpse* corpseTarget = m_targets.GetCorpseTarget())
{
/// @todo this is a workaround - corpses should be added to spell target map too, but we can't do that so we add owner instead
if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID()))
target = owner;
}
}
else //if (targetMask & TARGET_FLAG_UNIT_MASK)
target = m_caster;
}
if (targetMask & TARGET_FLAG_ITEM_MASK)
{
if (Item* item = m_targets.GetItemTarget())
AddItemTarget(item, 1 << effIndex);
return;
}
if (targetMask & TARGET_FLAG_GAMEOBJECT_MASK)
target = m_targets.GetGOTarget();
break;
// add self to the target map
case EFFECT_IMPLICIT_TARGET_CASTER:
if (targetMask & TARGET_FLAG_UNIT_MASK)
target = m_caster;
break;
default:
break;
}
CallScriptObjectTargetSelectHandlers(target, SpellEffIndex(effIndex), SpellImplicitTargetInfo());
if (target)
{
if (target->ToUnit())
AddUnitTarget(target->ToUnit(), 1 << effIndex, false);
else if (target->ToGameObject())
AddGOTarget(target->ToGameObject(), 1 << effIndex);
}
}
uint32 Spell::GetSearcherTypeMask(SpellTargetObjectTypes objType, ConditionContainer* condList)
{
// this function selects which containers need to be searched for spell target
uint32 retMask = GRID_MAP_TYPE_MASK_ALL;
// filter searchers based on searched object type
switch (objType)
{
case TARGET_OBJECT_TYPE_UNIT:
case TARGET_OBJECT_TYPE_UNIT_AND_DEST:
case TARGET_OBJECT_TYPE_CORPSE:
case TARGET_OBJECT_TYPE_CORPSE_ENEMY:
case TARGET_OBJECT_TYPE_CORPSE_ALLY:
retMask &= GRID_MAP_TYPE_MASK_PLAYER | GRID_MAP_TYPE_MASK_CORPSE | GRID_MAP_TYPE_MASK_CREATURE;
break;
case TARGET_OBJECT_TYPE_GOBJ:
case TARGET_OBJECT_TYPE_GOBJ_ITEM:
retMask &= GRID_MAP_TYPE_MASK_GAMEOBJECT;
break;
default:
break;
}
if (!m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_DEAD))
retMask &= ~GRID_MAP_TYPE_MASK_CORPSE;
if (m_spellInfo->HasAttribute(SPELL_ATTR3_ONLY_TARGET_PLAYERS))
retMask &= GRID_MAP_TYPE_MASK_CORPSE | GRID_MAP_TYPE_MASK_PLAYER;
if (m_spellInfo->HasAttribute(SPELL_ATTR3_ONLY_TARGET_GHOSTS))
retMask &= GRID_MAP_TYPE_MASK_PLAYER;
if (condList)
retMask &= sConditionMgr->GetSearcherTypeMaskForConditionList(*condList);
return retMask;
}
template<class SEARCHER>
void Spell::SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* referer, Position const* pos, float radius)
{
if (!containerMask)
return;
// search world and grid for possible targets
bool searchInGrid = (containerMask & (GRID_MAP_TYPE_MASK_CREATURE | GRID_MAP_TYPE_MASK_GAMEOBJECT)) != 0;
bool searchInWorld = (containerMask & (GRID_MAP_TYPE_MASK_CREATURE | GRID_MAP_TYPE_MASK_PLAYER | GRID_MAP_TYPE_MASK_CORPSE)) != 0;
if (searchInGrid || searchInWorld)
{
float x, y;
x = pos->GetPositionX();
y = pos->GetPositionY();
CellCoord p(Trinity::ComputeCellCoord(x, y));
Cell cell(p);
cell.SetNoCreate();
Map* map = referer->GetMap();
if (searchInWorld)
Cell::VisitWorldObjects(x, y, map, searcher, radius);
if (searchInGrid)
Cell::VisitGridObjects(x, y, map, searcher, radius);
}
}
WorldObject* Spell::SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionContainer* condList)
{
WorldObject* target = NULL;
uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList);
if (!containerTypeMask)
return NULL;
Trinity::WorldObjectSpellNearbyTargetCheck check(range, m_caster, m_spellInfo, selectionType, condList);
Trinity::WorldObjectLastSearcher<Trinity::WorldObjectSpellNearbyTargetCheck> searcher(m_caster, target, check, containerTypeMask);
SearchTargets<Trinity::WorldObjectLastSearcher<Trinity::WorldObjectSpellNearbyTargetCheck> > (searcher, containerTypeMask, m_caster, m_caster, range);
return target;
}
void Spell::SearchAreaTargets(std::list<WorldObject*>& targets, float range, Position const* position, Unit* referer, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionContainer* condList)
{
uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList);
if (!containerTypeMask)
return;
Trinity::WorldObjectSpellAreaTargetCheck check(range, position, m_caster, referer, m_spellInfo, selectionType, condList);
Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellAreaTargetCheck> searcher(m_caster, targets, check, containerTypeMask);
SearchTargets<Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellAreaTargetCheck> > (searcher, containerTypeMask, m_caster, position, range);
}
void Spell::SearchChainTargets(std::list<WorldObject*>& targets, uint32 chainTargets, WorldObject* target, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectType, ConditionContainer* condList, bool isChainHeal)
{
// max dist for jump target selection
float jumpRadius = 0.0f;
switch (m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_RANGED:
// 7.5y for multi shot
jumpRadius = 7.5f;
break;
case SPELL_DAMAGE_CLASS_MELEE:
// 5y for swipe, cleave and similar
jumpRadius = 5.0f;
break;
case SPELL_DAMAGE_CLASS_NONE:
case SPELL_DAMAGE_CLASS_MAGIC:
// 12.5y for chain heal spell since 3.2 patch
if (isChainHeal)
jumpRadius = 12.5f;
// 10y as default for magic chain spells
else
jumpRadius = 10.0f;
break;
}
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_DISTANCE, jumpRadius, this);
// chain lightning/heal spells and similar - allow to jump at larger distance and go out of los
bool isBouncingFar = (m_spellInfo->HasAttribute(SPELL_ATTR4_AREA_TARGET_CHAIN)
|| m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE
|| m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC);
// max dist which spell can reach
float searchRadius = jumpRadius;
if (isBouncingFar)
searchRadius *= chainTargets;
std::list<WorldObject*> tempTargets;
SearchAreaTargets(tempTargets, searchRadius, target, m_caster, objectType, selectType, condList);
tempTargets.remove(target);
// remove targets which are always invalid for chain spells
// for some spells allow only chain targets in front of caster (swipe for example)
if (!isBouncingFar)
{
for (std::list<WorldObject*>::iterator itr = tempTargets.begin(); itr != tempTargets.end();)
{
std::list<WorldObject*>::iterator checkItr = itr++;
if (!m_caster->HasInArc(static_cast<float>(M_PI), *checkItr))
tempTargets.erase(checkItr);
}
}
while (chainTargets)
{
// try to get unit for next chain jump
std::list<WorldObject*>::iterator foundItr = tempTargets.end();
// get unit with highest hp deficit in dist
if (isChainHeal)
{
uint32 maxHPDeficit = 0;
for (std::list<WorldObject*>::iterator itr = tempTargets.begin(); itr != tempTargets.end(); ++itr)
{
if (Unit* unit = (*itr)->ToUnit())
{
uint32 deficit = unit->GetMaxHealth() - unit->GetHealth();
if ((deficit > maxHPDeficit || foundItr == tempTargets.end()) && target->IsWithinDist(unit, jumpRadius) && target->IsWithinLOSInMap(unit, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2))
{
foundItr = itr;
maxHPDeficit = deficit;
}
}
}
}
// get closest object
else
{
for (std::list<WorldObject*>::iterator itr = tempTargets.begin(); itr != tempTargets.end(); ++itr)
{
if (foundItr == tempTargets.end())
{
if ((!isBouncingFar || target->IsWithinDist(*itr, jumpRadius)) && target->IsWithinLOSInMap(*itr, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2))
foundItr = itr;
}
else if (target->GetDistanceOrder(*itr, *foundItr) && target->IsWithinLOSInMap(*itr, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2))
foundItr = itr;
}
}
// not found any valid target - chain ends
if (foundItr == tempTargets.end())
break;
target = *foundItr;
tempTargets.erase(foundItr);
targets.push_back(target);
--chainTargets;
}
}
GameObject* Spell::SearchSpellFocus()
{
GameObject* focus = NULL;
Trinity::GameObjectFocusCheck check(m_caster, m_spellInfo->RequiresSpellFocus);
Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck> searcher(m_caster, focus, check);
SearchTargets<Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck> > (searcher, GRID_MAP_TYPE_MASK_GAMEOBJECT, m_caster, m_caster, m_caster->GetVisibilityRange());
return focus;
}
void Spell::prepareDataForTriggerSystem()
{
//==========================================================================================
// Now fill data for trigger system, need know:
// Create base triggers flags for Attacker and Victim (m_procAttacker, m_procVictim and m_hitMask)
//==========================================================================================
m_procVictim = m_procAttacker = 0;
// Get data for type of attack and fill base info for trigger
switch (m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MELEE:
m_procAttacker = PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS;
if (m_attackType == OFF_ATTACK)
m_procAttacker |= PROC_FLAG_DONE_OFFHAND_ATTACK;
else
m_procAttacker |= PROC_FLAG_DONE_MAINHAND_ATTACK;
m_procVictim = PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS;
break;
case SPELL_DAMAGE_CLASS_RANGED:
// Auto attack
if (m_spellInfo->HasAttribute(SPELL_ATTR2_AUTOREPEAT_FLAG))
{
m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK;
m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK;
}
else // Ranged spell attack
{
m_procAttacker = PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS;
m_procVictim = PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS;
}
break;
default:
if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON &&
m_spellInfo->EquippedItemSubClassMask & (1 << ITEM_SUBCLASS_WEAPON_WAND)
&& m_spellInfo->HasAttribute(SPELL_ATTR2_AUTOREPEAT_FLAG)) // Wands auto attack
{
m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK;
m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK;
}
// For other spells trigger procflags are set in Spell::DoAllEffectOnTarget
// Because spell positivity is dependant on target
}
// Hunter trap spells - activation proc for Lock and Load, Entrapment and Misdirection
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER &&
(m_spellInfo->SpellFamilyFlags[0] & 0x18 || // Freezing and Frost Trap, Freezing Arrow
m_spellInfo->Id == 57879 || // Snake Trap - done this way to avoid double proc
m_spellInfo->SpellFamilyFlags[2] & 0x00024000)) // Explosive and Immolation Trap
{
m_procAttacker |= PROC_FLAG_DONE_TRAP_ACTIVATION;
// also fill up other flags (DoAllEffectOnTarget only fills up flag if both are not set)
m_procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG;
m_procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG;
}
// Hellfire Effect - trigger as DOT
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[0] & 0x00000040)
{
m_procAttacker = PROC_FLAG_DONE_PERIODIC;
m_procVictim = PROC_FLAG_TAKEN_PERIODIC;
}
}
void Spell::CleanupTargetList()
{
m_UniqueTargetInfo.clear();
m_UniqueGOTargetInfo.clear();
m_UniqueItemInfo.clear();
m_delayMoment = 0;
}
class ProcReflectDelayed : public BasicEvent
{
public:
ProcReflectDelayed(Unit* owner, ObjectGuid casterGuid) : _victim(owner), _casterGuid(casterGuid) { }
bool Execute(uint64 /*e_time*/, uint32 /*p_time*/) override
{
Unit* caster = ObjectAccessor::GetUnit(*_victim, _casterGuid);
if (!caster)
return true;
uint32 const typeMaskActor = PROC_FLAG_NONE;
uint32 const typeMaskActionTarget = PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG | PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG;
uint32 const spellTypeMask = PROC_SPELL_TYPE_DAMAGE | PROC_SPELL_TYPE_NO_DMG_HEAL;
uint32 const spellPhaseMask = PROC_SPELL_PHASE_NONE;
uint32 const hitMask = PROC_HIT_REFLECT;
caster->ProcSkillsAndAuras(_victim, typeMaskActor, typeMaskActionTarget, spellTypeMask, spellPhaseMask, hitMask, nullptr, nullptr, nullptr);
return true;
}
private:
Unit* _victim;
ObjectGuid _casterGuid;
};
void Spell::AddUnitTarget(Unit* target, uint32 effectMask, bool checkIfValid /*= true*/, bool implicit /*= true*/, Position const* losPosition /*= nullptr*/)
{
uint32 validEffectMask = 0;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && (effectMask & (1 << effect->EffectIndex)) != 0 && CheckEffectTarget(target, effect, losPosition))
validEffectMask |= 1 << effect->EffectIndex;
effectMask &= validEffectMask;
// no effects left
if (!effectMask)
return;
if (checkIfValid)
if (m_spellInfo->CheckTarget(m_caster, target, implicit || m_caster->GetEntry() == WORLD_TRIGGER) != SPELL_CAST_OK) // skip stealth checks for GO casts
return;
// Check for effect immune skip if immuned
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && target->IsImmunedToSpellEffect(m_spellInfo, effect->EffectIndex, m_caster))
effectMask &= ~(1 << effect->EffectIndex);
ObjectGuid targetGUID = target->GetGUID();
// Lookup target in already in list
for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (targetGUID == ihit->targetGUID) // Found in list
{
ihit->effectMask |= effectMask; // Immune effects removed from mask
return;
}
}
// This is new target calculate data for him
// Get spell hit result on target
TargetInfo targetInfo;
targetInfo.targetGUID = targetGUID; // Store target GUID
targetInfo.effectMask = effectMask; // Store all effects not immune
targetInfo.processed = false; // Effects not apply on target
targetInfo.alive = target->IsAlive();
targetInfo.damage = 0;
targetInfo.crit = false;
// Calculate hit result
if (m_originalCaster)
{
targetInfo.missCondition = m_originalCaster->SpellHitResult(target, m_spellInfo, m_canReflect && !(m_spellInfo->IsPositive() && m_caster->IsFriendlyTo(target)));
if (m_skipCheck && targetInfo.missCondition != SPELL_MISS_IMMUNE)
targetInfo.missCondition = SPELL_MISS_NONE;
}
else
targetInfo.missCondition = SPELL_MISS_EVADE; //SPELL_MISS_NONE;
// Spell have speed - need calculate incoming time
// Incoming time is zero for self casts. At least I think so.
if (m_caster != target)
{
float hitDelay = m_spellInfo->LaunchDelay;
if (m_spellInfo->HasAttribute(SPELL_ATTR9_SPECIAL_DELAY_CALCULATION))
hitDelay += m_spellInfo->Speed;
else if (m_spellInfo->Speed > 0.0f)
{
// calculate spell incoming interval
/// @todo this is a hack
float dist = std::max(m_caster->GetDistance(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ()), 5.0f);
hitDelay += dist / m_spellInfo->Speed;
}
targetInfo.timeDelay = uint64(std::floor(hitDelay * 1000.0f));
}
else
targetInfo.timeDelay = 0ULL;
// If target reflect spell back to caster
if (targetInfo.missCondition == SPELL_MISS_REFLECT)
{
// Calculate reflected spell result on caster
targetInfo.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, false); // can't reflect twice
// Proc spell reflect aura when missile hits the original target
target->m_Events.AddEvent(new ProcReflectDelayed(target, m_originalCasterGUID), target->m_Events.CalculateTime(targetInfo.timeDelay));
// Increase time interval for reflected spells by 1.5
targetInfo.timeDelay += targetInfo.timeDelay >> 1;
}
else
targetInfo.reflectResult = SPELL_MISS_NONE;
// Calculate minimum incoming time
if (targetInfo.timeDelay && (!m_delayMoment || m_delayMoment > targetInfo.timeDelay))
m_delayMoment = targetInfo.timeDelay;
// Add target to list
m_UniqueTargetInfo.push_back(targetInfo);
}
void Spell::AddGOTarget(GameObject* go, uint32 effectMask)
{
uint32 validEffectMask = 0;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && (effectMask & (1 << effect->EffectIndex)) != 0 && CheckEffectTarget(go, effect))
validEffectMask |= 1 << effect->EffectIndex;
effectMask &= validEffectMask;
// no effects left
if (!effectMask)
return;
ObjectGuid targetGUID = go->GetGUID();
// Lookup target in already in list
for (std::vector<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
{
if (targetGUID == ihit->targetGUID) // Found in list
{
ihit->effectMask |= effectMask; // Add only effect mask
return;
}
}
// This is new target calculate data for him
GOTargetInfo target;
target.targetGUID = targetGUID;
target.effectMask = effectMask;
target.processed = false; // Effects not apply on target
// Spell have speed - need calculate incoming time
if (static_cast<WorldObject*>(m_caster) != go)
{
float hitDelay = m_spellInfo->LaunchDelay;
if (m_spellInfo->HasAttribute(SPELL_ATTR9_SPECIAL_DELAY_CALCULATION))
hitDelay += m_spellInfo->Speed;
else if (m_spellInfo->Speed > 0.0f)
{
// calculate spell incoming interval
float dist = std::max(m_caster->GetDistance(go->GetPositionX(), go->GetPositionY(), go->GetPositionZ()), 5.0f);
hitDelay += dist / m_spellInfo->Speed;
}
target.timeDelay = uint64(std::floor(hitDelay * 1000.0f));
}
else
target.timeDelay = 0ULL;
// Calculate minimum incoming time
if (target.timeDelay && (!m_delayMoment || m_delayMoment > target.timeDelay))
m_delayMoment = target.timeDelay;
// Add target to list
m_UniqueGOTargetInfo.push_back(target);
}
void Spell::AddItemTarget(Item* item, uint32 effectMask)
{
uint32 validEffectMask = 0;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && (effectMask & (1 << effect->EffectIndex)) != 0 && CheckEffectTarget(item, effect))
validEffectMask |= 1 << effect->EffectIndex;
effectMask &= validEffectMask;
// no effects left
if (!effectMask)
return;
// Lookup target in already in list
for (std::vector<ItemTargetInfo>::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit)
{
if (item == ihit->item) // Found in list
{
ihit->effectMask |= effectMask; // Add only effect mask
return;
}
}
// This is new target add data
ItemTargetInfo target;
target.item = item;
target.effectMask = effectMask;
m_UniqueItemInfo.push_back(target);
}
void Spell::AddDestTarget(SpellDestination const& dest, uint32 effIndex)
{
m_destTargets[effIndex] = dest;
}
void Spell::DoAllEffectOnTarget(TargetInfo* target)
{
if (!target || target->processed)
return;
target->processed = true; // Target checked in apply effects procedure
// Get mask of effects for target
uint32 mask = target->effectMask;
Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID);
if (!unit && target->targetGUID.IsPlayer()) // only players may be targeted across maps
{
uint32 farMask = 0;
// create far target mask
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && effect->IsFarUnitTargetEffect())
if ((1 << effect->EffectIndex) & mask)
farMask |= (1 << effect->EffectIndex);
if (!farMask)
return;
// find unit in world
unit = ObjectAccessor::FindPlayer(target->targetGUID);
if (!unit)
return;
// do far effects on the unit
// can't use default call because of threading, do stuff as fast as possible
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && (farMask & (1 << effect->EffectIndex)))
HandleEffects(unit, NULL, NULL, effect->EffectIndex, SPELL_EFFECT_HANDLE_HIT_TARGET);
return;
}
if (!unit)
return;
if (unit->IsAlive() != target->alive)
return;
if (getState() == SPELL_STATE_DELAYED && !m_spellInfo->IsPositive() && (GameTime::GetGameTimeMS() - target->timeDelay) <= unit->m_lastSanctuaryTime)
return; // No missinfo in that case
// Get original caster (if exist) and calculate damage/healing from him data
Unit* caster = m_originalCaster ? m_originalCaster : m_caster;
// Skip if m_originalCaster not avaiable
if (!caster)
return;
SpellMissInfo missInfo = target->missCondition;
// Need init unitTarget by default unit (can changed in code on reflect)
// Or on missInfo != SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem)
unitTarget = unit;
targetMissInfo = missInfo;
// Reset damage/healing counter
m_damage = target->damage;
m_healing = -target->damage;
m_currentTargetInfo = target;
// Fill base trigger info
uint32 procAttacker = m_procAttacker;
uint32 procVictim = m_procVictim;
uint32 hitMask = PROC_HIT_NONE;
m_spellAura = nullptr; // Set aura to null for every target-make sure that pointer is not used for unit without aura applied
// Spells with this flag cannot trigger if effect is cast on self
bool const canEffectTrigger = !m_spellInfo->HasAttribute(SPELL_ATTR3_CANT_TRIGGER_PROC) && unitTarget->CanProc() && (CanExecuteTriggersOnHit(mask) || missInfo == SPELL_MISS_IMMUNE || missInfo == SPELL_MISS_IMMUNE2);
Unit* spellHitTarget = nullptr;
if (missInfo == SPELL_MISS_NONE) // In case spell hit target, do all effect on that target
spellHitTarget = unit;
else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit)
{
if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him
{
spellHitTarget = m_caster;
if (m_caster->GetTypeId() == TYPEID_UNIT)
m_caster->ToCreature()->LowerPlayerDamageReq(target->damage);
}
}
if (missInfo != SPELL_MISS_NONE)
if (m_caster->IsCreature() && m_caster->IsAIEnabled)
m_caster->ToCreature()->AI()->SpellMissTarget(unit, m_spellInfo, missInfo);
PrepareScriptHitHandlers();
CallScriptBeforeHitHandlers(missInfo);
bool enablePvP = false; // need to check PvP state before spell effects, but act on it afterwards
if (spellHitTarget)
{
// if target is flagged for pvp also flag caster if a player
if (unit->IsPvP() && m_caster->GetTypeId() == TYPEID_PLAYER)
enablePvP = true; // Decide on PvP flagging now, but act on it later.
SpellMissInfo missInfo2 = DoSpellHitOnUnit(spellHitTarget, mask);
if (missInfo2 != SPELL_MISS_NONE)
{
if (missInfo2 != SPELL_MISS_MISS)
m_caster->SendSpellMiss(unit, m_spellInfo->Id, missInfo2);
m_damage = 0;
spellHitTarget = nullptr;
}
}
// Do not take combo points on dodge and miss
if (missInfo != SPELL_MISS_NONE && m_needComboPoints && m_targets.GetUnitTargetGUID() == target->targetGUID)
m_needComboPoints = false;
// Trigger info was not filled in Spell::prepareDataForTriggerSystem - we do it now
if (canEffectTrigger && !procAttacker && !procVictim)
{
bool positive = true;
if (m_damage > 0)
positive = false;
else if (!m_healing)
{
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
// in case of immunity, check all effects to choose correct procFlags, as none has technically hit
if (target->effectMask && !(target->effectMask & (1 << i)))
continue;
if (!m_spellInfo->IsPositiveEffect(i))
{
positive = false;
break;
}
}
}
switch (m_spellInfo->DmgClass)
{
case SPELL_DAMAGE_CLASS_MAGIC:
if (positive)
{
procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS;
procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS;
}
else
{
procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG;
procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG;
}
break;
case SPELL_DAMAGE_CLASS_NONE:
if (positive)
{
procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS;
procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS;
}
else
{
procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG;
procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG;
}
break;
}
}
CallScriptOnHitHandlers();
// All calculated do it!
// Do healing and triggers
if (m_healing > 0)
{
bool crit = target->crit;
uint32 addhealth = m_healing;
if (crit)
{
hitMask |= PROC_HIT_CRITICAL;
addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, nullptr);
}
else
hitMask |= PROC_HIT_NORMAL;
HealInfo healInfo(caster, unitTarget, addhealth, m_spellInfo, m_spellInfo->GetSchoolMask());
caster->HealBySpell(healInfo, crit);
unitTarget->getHostileRefManager().threatAssist(caster, float(healInfo.GetEffectiveHeal()) * 0.5f, m_spellInfo);
m_healing = healInfo.GetEffectiveHeal();
// Do triggers for unit
if (canEffectTrigger)
caster->ProcSkillsAndAuras(unitTarget, procAttacker, procVictim, PROC_SPELL_TYPE_HEAL, PROC_SPELL_PHASE_HIT, hitMask, this, nullptr, &healInfo);
}
// Do damage and triggers
else if (m_damage > 0)
{
// Fill base damage struct (unitTarget - is real spell target)
SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo, m_SpellVisual, m_spellSchoolMask, m_castId);
// Check damage immunity
if (unitTarget->IsImmunedToDamage(m_spellInfo))
{
hitMask = PROC_HIT_IMMUNE;
m_damage = 0;
// no packet found in sniffs
}
else
{
// Add bonuses and fill damageInfo struct
caster->CalculateSpellDamageTaken(&damageInfo, m_damage, m_spellInfo, m_attackType, target->crit);
caster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb, SPELL_DIRECT_DAMAGE);
hitMask |= createProcHitMask(&damageInfo, missInfo);
procVictim |= PROC_FLAG_TAKEN_DAMAGE;
m_damage = damageInfo.damage;
caster->DealSpellDamage(&damageInfo, true);
// Send log damage message to client
caster->SendSpellNonMeleeDamageLog(&damageInfo);
}
// Do triggers for unit
if (canEffectTrigger)
{
DamageInfo spellDamageInfo(damageInfo, SPELL_DIRECT_DAMAGE, m_attackType, hitMask);
caster->ProcSkillsAndAuras(unitTarget, procAttacker, procVictim, PROC_SPELL_TYPE_DAMAGE, PROC_SPELL_PHASE_HIT, hitMask, this, &spellDamageInfo, nullptr);
if (caster->GetTypeId() == TYPEID_PLAYER && !m_spellInfo->HasAttribute(SPELL_ATTR0_STOP_ATTACK_TARGET) &&
(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED))
caster->ToPlayer()->CastItemCombatSpell(spellDamageInfo);
}
}
// Passive spell hits/misses or active spells only misses (only triggers)
else
{
// Fill base damage struct (unitTarget - is real spell target)
SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo, m_SpellVisual, m_spellSchoolMask);
hitMask |= createProcHitMask(&damageInfo, missInfo);
// Do triggers for unit
if (canEffectTrigger)
{
DamageInfo spellNoDamageInfo(damageInfo, NODAMAGE, m_attackType, hitMask);
caster->ProcSkillsAndAuras(unitTarget, procAttacker, procVictim, PROC_SPELL_TYPE_NO_DMG_HEAL, PROC_SPELL_PHASE_HIT, hitMask, this, &spellNoDamageInfo, nullptr);
if (caster->GetTypeId() == TYPEID_PLAYER && !m_spellInfo->HasAttribute(SPELL_ATTR0_STOP_ATTACK_TARGET) &&
(m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED))
caster->ToPlayer()->CastItemCombatSpell(spellNoDamageInfo);
}
// Failed Pickpocket, reveal rogue
if (missInfo == SPELL_MISS_RESIST && m_spellInfo->HasAttribute(SPELL_ATTR0_CU_PICKPOCKET) && unitTarget->GetTypeId() == TYPEID_UNIT)
{
m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK);
if (unitTarget->ToCreature()->IsAIEnabled)
unitTarget->ToCreature()->AI()->AttackStart(m_caster);
}
}
// set hitmask for finish procs
m_hitMask |= hitMask;
// spellHitTarget can be null if spell is missed in DoSpellHitOnUnit
if (missInfo != SPELL_MISS_EVADE && spellHitTarget && !m_caster->IsFriendlyTo(unit) && (!m_spellInfo->IsPositive() || m_spellInfo->HasEffect(SPELL_EFFECT_DISPEL)))
{
m_caster->CombatStart(unit, m_spellInfo->HasInitialAggro());
if (!unit->IsStandState())
unit->SetStandState(UNIT_STAND_STATE_STAND);
}
// Check for SPELL_ATTR7_INTERRUPT_ONLY_NONPLAYER
if (missInfo == SPELL_MISS_NONE && m_spellInfo->HasAttribute(SPELL_ATTR7_INTERRUPT_ONLY_NONPLAYER) && unit->GetTypeId() != TYPEID_PLAYER)
caster->CastSpell(unit, SPELL_INTERRUPT_NONPLAYER, true);
if (spellHitTarget)
{
//AI functions
if (spellHitTarget->GetTypeId() == TYPEID_UNIT)
if (spellHitTarget->ToCreature()->IsAIEnabled)
spellHitTarget->ToCreature()->AI()->SpellHit(m_caster, m_spellInfo);
if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsAIEnabled)
m_caster->ToCreature()->AI()->SpellHitTarget(spellHitTarget, m_spellInfo);
// Needs to be called after dealing damage/healing to not remove breaking on damage auras
DoTriggersOnSpellHit(spellHitTarget, mask);
if (enablePvP)
m_caster->ToPlayer()->UpdatePvP(true);
CallScriptAfterHitHandlers();
}
}
SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask)
{
if (!unit || !effectMask)
return SPELL_MISS_EVADE;
// Target may have begun evading between launch and hit phases - re-check now
if (Creature* creatureTarget = unit->ToCreature())
if (creatureTarget->IsEvadingAttacks())
return SPELL_MISS_EVADE;
// For delayed spells immunity may be applied between missile launch and hit - check immunity for that case
if (m_spellInfo->HasHitDelay() && unit->IsImmunedToSpell(m_spellInfo, m_caster))
return SPELL_MISS_IMMUNE;
// disable effects to which unit is immune
SpellMissInfo returnVal = SPELL_MISS_IMMUNE;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && (effectMask & (1 << effect->EffectIndex)))
if (unit->IsImmunedToSpellEffect(m_spellInfo, effect->EffectIndex, m_caster))
effectMask &= ~(1 << effect->EffectIndex);
if (!effectMask)
return returnVal;
if (Player* player = unit->ToPlayer())
{
player->StartCriteriaTimer(CRITERIA_TIMED_TYPE_SPELL_TARGET, m_spellInfo->Id);
player->UpdateCriteria(CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id, 0, 0, m_caster);
player->UpdateCriteria(CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id);
}
if (Player* player = m_caster->ToPlayer())
{
player->StartCriteriaTimer(CRITERIA_TIMED_TYPE_SPELL_CASTER, m_spellInfo->Id);
player->UpdateCriteria(CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, 0, unit);
}
if (m_caster != unit)
{
// Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells
if (m_spellInfo->HasHitDelay() && unit->HasUnitFlag(UNIT_FLAG_NON_ATTACKABLE) && unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID())
return SPELL_MISS_EVADE;
if (m_caster->_IsValidAttackTarget(unit, m_spellInfo))
unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_HITBYSPELL);
else if (m_caster->IsFriendlyTo(unit))
{
// for delayed spells ignore negative spells (after duel end) for friendly targets
/// @todo this cause soul transfer bugged
// 63881 - Malady of the Mind jump spell (Yogg-Saron)
if (m_spellInfo->HasHitDelay() && unit->GetTypeId() == TYPEID_PLAYER && !m_spellInfo->IsPositive() && m_spellInfo->Id != 63881)
return SPELL_MISS_EVADE;
// assisting case, healing and resurrection
if (unit->HasUnitState(UNIT_STATE_ATTACK_PLAYER))
{
m_caster->SetContestedPvP();
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->UpdatePvP(true);
}
if (unit->IsInCombat() && m_spellInfo->HasInitialAggro())
{
m_caster->SetInCombatState(unit->GetCombatTimer() > 0, unit);
unit->getHostileRefManager().threatAssist(m_caster, 0.0f);
}
}
}
uint32 aura_effmask = 0;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && (effectMask & (1 << effect->EffectIndex) && effect->IsUnitOwnedAuraEffect()))
aura_effmask |= 1 << effect->EffectIndex;
// Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add
DiminishingGroup const diminishGroup = m_spellInfo->GetDiminishingReturnsGroupForSpell();
DiminishingLevels diminishLevel = DIMINISHING_LEVEL_1;
if (diminishGroup && aura_effmask)
{
diminishLevel = unit->GetDiminishing(diminishGroup);
DiminishingReturnsType type = m_spellInfo->GetDiminishingReturnsGroupType();
// Increase Diminishing on unit, current informations for actually casts will use values above
if ((type == DRTYPE_PLAYER &&
(unit->GetCharmerOrOwnerPlayerOrPlayerItself() || (unit->GetTypeId() == TYPEID_UNIT && unit->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH))) ||
type == DRTYPE_ALL)
unit->IncrDiminishing(m_spellInfo);
}
if (aura_effmask)
{
if (m_originalCaster)
{
int32 basePoints[MAX_SPELL_EFFECTS];
for (SpellEffectInfo const* auraSpellEffect : m_spellInfo->GetEffects())
if (auraSpellEffect)
basePoints[auraSpellEffect->EffectIndex] = (m_spellValue->CustomBasePointsMask & (1 << auraSpellEffect->EffectIndex)) ?
m_spellValue->EffectBasePoints[auraSpellEffect->EffectIndex] :
auraSpellEffect->CalcBaseValue(m_originalCaster, unit, m_castItemEntry, m_castItemLevel);
bool refresh = false;
bool const resetPeriodicTimer = !(_triggeredCastFlags & TRIGGERED_DONT_RESET_PERIODIC_TIMER);
m_spellAura = Aura::TryRefreshStackOrCreate(m_spellInfo, m_castId, effectMask, unit,
m_originalCaster, GetCastDifficulty(), basePoints,
m_CastItem, ObjectGuid::Empty, &refresh, resetPeriodicTimer, ObjectGuid::Empty, m_castItemEntry, m_castItemLevel);
if (m_spellAura)
{
// Set aura stack amount to desired value
if (m_spellValue->AuraStackAmount > 1)
{
if (!refresh)
m_spellAura->SetStackAmount(m_spellValue->AuraStackAmount);
else
m_spellAura->ModStackAmount(m_spellValue->AuraStackAmount);
}
// Now Reduce spell duration using data received at spell hit
// check whatever effects we're going to apply, diminishing returns only apply to negative aura effects
bool positive = true;
if (m_originalCaster == unit || !m_originalCaster->IsFriendlyTo(unit))
{
for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i)
{
if ((effectMask & (1 << i)) && !m_spellInfo->IsPositiveEffect(i))
{
positive = false;
break;
}
}
}
int32 duration = m_spellAura->GetMaxDuration();
// unit is immune to aura if it was diminished to 0 duration
if (!positive && !unit->ApplyDiminishingToDuration(m_spellInfo, duration, m_originalCaster, diminishLevel))
{
m_spellAura->Remove();
bool found = false;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && (effectMask & (1 << effect->EffectIndex) && effect->Effect != SPELL_EFFECT_APPLY_AURA))
found = true;
if (!found)
return SPELL_MISS_IMMUNE;
}
else
{
static_cast<UnitAura*>(m_spellAura)->SetDiminishGroup(diminishGroup);
duration = m_originalCaster->ModSpellDuration(m_spellInfo, unit, duration, positive, effectMask);
if (duration > 0)
{
// Haste modifies duration of channeled spells
if (m_spellInfo->IsChanneled())
m_originalCaster->ModSpellDurationTime(m_spellInfo, duration, this);
else if (m_spellInfo->HasAttribute(SPELL_ATTR5_HASTE_AFFECT_DURATION))
{
int32 origDuration = duration;
duration = 0;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect)
if (AuraEffect const* eff = m_spellAura->GetEffect(effect->EffectIndex))
if (int32 period = eff->GetPeriod()) // period is hastened by UNIT_MOD_CAST_SPEED
duration = std::max(std::max(origDuration / period, 1) * period, duration);
// if there is no periodic effect
if (!duration)
duration = int32(origDuration * m_originalCaster->m_unitData->ModCastingSpeed);
}
}
// Set duration to desired value
if (m_spellValue->Duration > 0)
duration = m_spellValue->Duration;
if (duration != m_spellAura->GetMaxDuration())
{
m_spellAura->SetMaxDuration(duration);
m_spellAura->SetDuration(duration);
}
m_spellAura->_RegisterForTargets();
}
}
}
}
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && (effectMask & (1 << effect->EffectIndex)))
HandleEffects(unit, NULL, NULL, effect->EffectIndex, SPELL_EFFECT_HANDLE_HIT_TARGET);
return SPELL_MISS_NONE;
}
void Spell::DoTriggersOnSpellHit(Unit* unit, uint32 effMask)
{
// handle SPELL_AURA_ADD_TARGET_TRIGGER auras
// this is executed after spell proc spells on target hit
// spells are triggered for each hit spell target
// info confirmed with retail sniffs of permafrost and shadow weaving
if (!m_hitTriggerSpells.empty())
{
int32 _duration = 0;
for (auto i = m_hitTriggerSpells.begin(); i != m_hitTriggerSpells.end(); ++i)
{
if (CanExecuteTriggersOnHit(effMask, i->triggeredByAura) && roll_chance_i(i->chance))
{
m_caster->CastSpell(unit, i->triggeredSpell, TRIGGERED_FULL_MASK);
TC_LOG_DEBUG("spells", "Spell %d triggered spell %d by SPELL_AURA_ADD_TARGET_TRIGGER aura", m_spellInfo->Id, i->triggeredSpell->Id);
// SPELL_AURA_ADD_TARGET_TRIGGER auras shouldn't trigger auras without duration
// set duration of current aura to the triggered spell
if (i->triggeredSpell->GetDuration() == -1)
{
if (Aura* triggeredAur = unit->GetAura(i->triggeredSpell->Id, m_caster->GetGUID()))
{
// get duration from aura-only once
if (!_duration)
{
Aura* aur = unit->GetAura(m_spellInfo->Id, m_caster->GetGUID());
_duration = aur ? aur->GetDuration() : -1;
}
triggeredAur->SetDuration(_duration);
}
}
}
}
}
// trigger linked auras remove/apply
/// @todo remove/cleanup this, as this table is not documented and people are doing stupid things with it
if (std::vector<int32> const* spellTriggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id + SPELL_LINK_HIT))
{
for (std::vector<int32>::const_iterator i = spellTriggered->begin(); i != spellTriggered->end(); ++i)
{
if (*i < 0)
unit->RemoveAurasDueToSpell(-(*i));
else
unit->CastSpell(unit, *i, true, nullptr, nullptr, m_caster->GetGUID());
}
}
}
void Spell::DoAllEffectOnTarget(GOTargetInfo* target)
{
if (target->processed) // Check target
return;
target->processed = true; // Target checked in apply effects procedure
uint32 effectMask = target->effectMask;
if (!effectMask)
return;
GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID);
if (!go)
return;
PrepareScriptHitHandlers();
CallScriptBeforeHitHandlers(SPELL_MISS_NONE);
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && (effectMask & (1 << effect->EffectIndex)))
HandleEffects(NULL, NULL, go, effect->EffectIndex, SPELL_EFFECT_HANDLE_HIT_TARGET);
if (go->AI())
go->AI()->SpellHit(m_caster, m_spellInfo);
CallScriptOnHitHandlers();
CallScriptAfterHitHandlers();
}
void Spell::DoAllEffectOnTarget(ItemTargetInfo* target)
{
uint32 effectMask = target->effectMask;
if (!target->item || !effectMask)
return;
PrepareScriptHitHandlers();
CallScriptBeforeHitHandlers(SPELL_MISS_NONE);
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && (effectMask & (1 << effect->EffectIndex)))
HandleEffects(NULL, target->item, NULL, effect->EffectIndex, SPELL_EFFECT_HANDLE_HIT_TARGET);
CallScriptOnHitHandlers();
CallScriptAfterHitHandlers();
}
bool Spell::UpdateChanneledTargetList()
{
// Not need check return true
if (m_channelTargetEffectMask == 0)
return true;
uint32 channelTargetEffectMask = m_channelTargetEffectMask;
uint32 channelAuraMask = 0;
float maxRadius = 0;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
if (effect && effect->Effect == SPELL_EFFECT_APPLY_AURA)
{
channelAuraMask |= 1 << effect->EffectIndex;
maxRadius = std::max(effect->CalcRadius(m_caster, this), maxRadius);
}
}
channelAuraMask &= channelTargetEffectMask;
float range = 0;
if (channelAuraMask)
{
range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive());
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this);
if (!range)
range = maxRadius;
// add little tolerance level
range += std::min(MAX_SPELL_RANGE_TOLERANCE, range*0.1f); // 10% but no more than MAX_SPELL_RANGE_TOLERANCE
}
for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->missCondition == SPELL_MISS_NONE && (channelTargetEffectMask & ihit->effectMask))
{
Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
if (!unit)
continue;
if (IsValidDeadOrAliveTarget(unit))
{
if (channelAuraMask & ihit->effectMask)
{
if (AuraApplication * aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID))
{
if (m_caster != unit && !m_caster->IsWithinDistInMap(unit, range))
{
ihit->effectMask &= ~aurApp->GetEffectMask();
unit->RemoveAura(aurApp);
continue;
}
}
else // aura is dispelled
continue;
}
channelTargetEffectMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target
}
}
}
// is all effects from m_needAliveTargetMask have alive targets
return channelTargetEffectMask == 0;
}
bool Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggeredByAura)
{
if (m_CastItem)
{
m_castItemGUID = m_CastItem->GetGUID();
m_castItemEntry = m_CastItem->GetEntry();
if (Player* owner = m_CastItem->GetOwner())
m_castItemLevel = int32(m_CastItem->GetItemLevel(owner));
else if (m_CastItem->GetOwnerGUID() == m_caster->GetGUID())
m_castItemLevel = int32(m_CastItem->GetItemLevel(m_caster->ToPlayer()));
else
{
SendCastResult(SPELL_FAILED_EQUIPPED_ITEM);
finish(false);
return false;
}
}
InitExplicitTargets(*targets);
m_spellState = SPELL_STATE_PREPARING;
if (triggeredByAura)
{
m_triggeredByAuraSpell = triggeredByAura->GetSpellInfo();
m_castItemLevel = triggeredByAura->GetBase()->GetCastItemLevel();
}
// create and add update event for this spell
_spellEvent = new SpellEvent(this);
m_caster->m_Events.AddEvent(_spellEvent, m_caster->m_Events.CalculateTime(1));
//Prevent casting at cast another spell (ServerSide check)
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_IN_PROGRESS) && m_caster->IsNonMeleeSpellCast(false, true, true) && !m_castId.IsEmpty())
{
SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS);
finish(false);
return false;
}
if (DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, m_caster))
{
SendCastResult(SPELL_FAILED_SPELL_UNAVAILABLE);
finish(false);
return false;
}
LoadScripts();
CallScriptOnPrepareHandlers();
// Fill cost data (do not use power for item casts)
if (!m_CastItem)
m_powerCost = m_spellInfo->CalcPowerCost(m_caster, m_spellSchoolMask, this);
// Set combo point requirement
if ((_triggeredCastFlags & TRIGGERED_IGNORE_COMBO_POINTS) || m_CastItem || !m_caster->m_playerMovingMe)
m_needComboPoints = false;
uint32 param1 = 0, param2 = 0;
SpellCastResult result = CheckCast(true, ¶m1, ¶m2);
// target is checked in too many locations and with different results to handle each of them
// handle just the general SPELL_FAILED_BAD_TARGETS result which is the default result for most DBC target checks
if (_triggeredCastFlags & TRIGGERED_IGNORE_TARGET_CHECK && result == SPELL_FAILED_BAD_TARGETS)
result = SPELL_CAST_OK;
if (result != SPELL_CAST_OK && !IsAutoRepeat()) //always cast autorepeat dummy for triggering
{
// Periodic auras should be interrupted when aura triggers a spell which can't be cast
// for example bladestorm aura should be removed on disarm as of patch 3.3.5
// channeled periodic spells should be affected by this (arcane missiles, penance, etc)
// a possible alternative sollution for those would be validating aura target on unit state change
if (triggeredByAura && triggeredByAura->IsPeriodic() && !triggeredByAura->GetBase()->IsPassive())
{
SendChannelUpdate(0);
triggeredByAura->GetBase()->SetDuration(0);
}
if (param1 || param2)
SendCastResult(result, ¶m1, ¶m2);
else
SendCastResult(result);
finish(false);
return false;
}
// Prepare data for triggers
prepareDataForTriggerSystem();
if (Player* player = m_caster->ToPlayer())
{
if (!player->GetCommandStatus(CHEAT_CASTTIME))
{
// calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail)
m_casttime = m_spellInfo->CalcCastTime(player->getLevel(), this);
}
else
m_casttime = 0; // Set cast time to 0 if .cheat casttime is enabled.
}
else
m_casttime = m_spellInfo->CalcCastTime(m_caster->getLevel(), this);
CallScriptOnCalcCastTimeHandlers();
m_casttime *= m_caster->GetTotalAuraMultiplier(SPELL_AURA_MOD_CASTING_SPEED);
// don't allow channeled spells / spells with cast time to be cast while moving
// exception are only channeled spells that have no casttime and SPELL_ATTR5_CAN_CHANNEL_WHEN_MOVING
// (even if they are interrupted on moving, spells with almost immediate effect get to have their effect processed before movement interrupter kicks in)
// don't cancel spells which are affected by a SPELL_AURA_CAST_WHILE_WALKING effect
if (((m_spellInfo->IsChanneled() || m_casttime) && m_caster->GetTypeId() == TYPEID_PLAYER && !(m_caster->IsCharmed() && m_caster->GetCharmerGUID().IsCreature()) && m_caster->isMoving() &&
m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) && !m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_CAST_WHILE_WALKING, m_spellInfo))
{
// 1. Has casttime, 2. Or doesn't have flag to allow movement during channel
if (m_casttime || !m_spellInfo->IsMoveAllowedChannel())
{
SendCastResult(SPELL_FAILED_MOVING);
finish(false);
return false;
}
}
// focus if not controlled creature
if (m_caster->GetTypeId() == TYPEID_UNIT && !m_caster->HasUnitFlag(UNIT_FLAG_PLAYER_CONTROLLED))
{
if (!(m_spellInfo->IsNextMeleeSwingSpell() || IsAutoRepeat() || (_triggeredCastFlags & TRIGGERED_IGNORE_SET_FACING)))
{
if (m_targets.GetObjectTarget() && m_caster != m_targets.GetObjectTarget())
m_caster->ToCreature()->FocusTarget(this, m_targets.GetObjectTarget());
else if (m_spellInfo->HasAttribute(SPELL_ATTR5_DONT_TURN_DURING_CAST))
m_caster->ToCreature()->FocusTarget(this, nullptr);
}
}
// set timer base at cast time
ReSetTimer();
TC_LOG_DEBUG("spells", "Spell::prepare: spell id %u source %u caster %d customCastFlags %u mask %u", m_spellInfo->Id, m_caster->GetEntry(), m_originalCaster ? m_originalCaster->GetEntry() : -1, _triggeredCastFlags, m_targets.GetTargetMask());
//Containers for channeled spells have to be set
/// @todoApply this to all cast spells if needed
// Why check duration? 29350: channelled triggers channelled
if ((_triggeredCastFlags & TRIGGERED_CAST_DIRECTLY) && (!m_spellInfo->IsChanneled() || !m_spellInfo->GetMaxDuration()))
cast(true);
else
{
// stealth must be removed at cast starting (at show channel bar)
// skip triggered spell (item equip spell casting and other not explicit character casts/item uses)
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_AURA_INTERRUPT_FLAGS) && m_spellInfo->IsBreakingStealth())
{
m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CAST);
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && effect->GetUsedTargetObjectType() == TARGET_OBJECT_TYPE_UNIT)
{
m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_SPELL_ATTACK);
break;
}
}
m_caster->SetCurrentCastSpell(this);
SendSpellStart();
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_GCD))
TriggerGlobalCooldown();
//item: first cast may destroy item and second cast causes crash
// commented out !m_spellInfo->StartRecoveryTime, it forces instant spells with global cooldown to be processed in spell::update
// as a result a spell that passed CheckCast and should be processed instantly may suffer from this delayed process
// the easiest bug to observe is LoS check in AddUnitTarget, even if spell passed the CheckCast LoS check the situation can change in spell::update
// because target could be relocated in the meantime, making the spell fly to the air (no targets can be registered, so no effects processed, nothing in combat log)
if (!m_casttime && /*!m_spellInfo->StartRecoveryTime && */!m_castItemGUID && GetCurrentContainer() == CURRENT_GENERIC_SPELL)
cast(true);
}
return true;
}
void Spell::cancel()
{
if (m_spellState == SPELL_STATE_FINISHED)
return;
uint32 oldState = m_spellState;
m_spellState = SPELL_STATE_FINISHED;
m_autoRepeat = false;
switch (oldState)
{
case SPELL_STATE_PREPARING:
CancelGlobalCooldown();
/* fallthrough */
case SPELL_STATE_DELAYED:
SendInterrupted(0);
SendCastResult(SPELL_FAILED_INTERRUPTED);
break;
case SPELL_STATE_CASTING:
for (std::vector<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
if ((*ihit).missCondition == SPELL_MISS_NONE)
if (Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID))
unit->RemoveOwnedAura(m_spellInfo->Id, m_originalCasterGUID, 0, AURA_REMOVE_BY_CANCEL);
SendChannelUpdate(0);
SendInterrupted(0);
SendCastResult(SPELL_FAILED_INTERRUPTED);
m_appliedMods.clear();
break;
default:
break;
}
SetReferencedFromCurrent(false);
if (m_selfContainer && *m_selfContainer == this)
*m_selfContainer = NULL;
m_caster->RemoveDynObject(m_spellInfo->Id);
if (m_spellInfo->IsChanneled()) // if not channeled then the object for the current cast wasn't summoned yet
m_caster->RemoveGameObject(m_spellInfo->Id, true);
//set state back so finish will be processed
m_spellState = oldState;
finish(false);
}
void Spell::cast(bool skipCheck)
{
Player* modOwner = m_caster->GetSpellModOwner();
Spell* lastSpellMod = nullptr;
if (modOwner)
{
lastSpellMod = modOwner->m_spellModTakingSpell;
if (lastSpellMod)
modOwner->SetSpellModTakingSpell(lastSpellMod, false);
}
_cast(skipCheck);
if (lastSpellMod)
modOwner->SetSpellModTakingSpell(lastSpellMod, true);
}
void Spell::_cast(bool skipCheck)
{
// update pointers base at GUIDs to prevent access to non-existed already object
if (!UpdatePointers())
{
// cancel the spell if UpdatePointers() returned false, something wrong happened there
cancel();
return;
}
// cancel at lost explicit target during cast
if (!m_targets.GetObjectTargetGUID().IsEmpty() && !m_targets.GetObjectTarget())
{
cancel();
return;
}
if (Player* playerCaster = m_caster->ToPlayer())
{
// now that we've done the basic check, now run the scripts
// should be done before the spell is actually executed
sScriptMgr->OnPlayerSpellCast(playerCaster, this, skipCheck);
// As of 3.0.2 pets begin attacking their owner's target immediately
// Let any pets know we've attacked something. Check DmgClass for harmful spells only
// This prevents spells such as Hunter's Mark from triggering pet attack
if (this->GetSpellInfo()->DmgClass != SPELL_DAMAGE_CLASS_NONE)
if (Unit* unitTarget = m_targets.GetUnitTarget())
for (Unit* controlled : playerCaster->m_Controlled)
if (Creature* cControlled = controlled->ToCreature())
if (cControlled->IsAIEnabled)
cControlled->AI()->OwnerAttacked(unitTarget);
}
SetExecutedCurrently(true);
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_SET_FACING))
if (m_caster->GetTypeId() == TYPEID_UNIT && m_targets.GetObjectTarget() && m_caster != m_targets.GetObjectTarget())
m_caster->SetInFront(m_targets.GetObjectTarget());
// Should this be done for original caster?
Player* modOwner = m_caster->GetSpellModOwner();
if (modOwner)
{
// Set spell which will drop charges for triggered cast spells
// if not successfully cast, will be remove in finish(false)
modOwner->SetSpellModTakingSpell(this, true);
}
CallScriptBeforeCastHandlers();
// skip check if done already (for instant cast spells for example)
if (!skipCheck)
{
uint32 param1 = 0, param2 = 0;
SpellCastResult castResult = CheckCast(false, ¶m1, ¶m2);
if (castResult != SPELL_CAST_OK)
{
SendCastResult(castResult, ¶m1, ¶m2);
SendInterrupted(0);
if (modOwner)
modOwner->SetSpellModTakingSpell(this, false);
finish(false);
SetExecutedCurrently(false);
return;
}
// additional check after cast bar completes (must not be in CheckCast)
// if trade not complete then remember it in trade data
if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM)
{
if (modOwner)
{
if (TradeData* my_trade = modOwner->GetTradeData())
{
if (!my_trade->IsInAcceptProcess())
{
// Spell will be cast after completing the trade. Silently ignore at this place
my_trade->SetSpell(m_spellInfo->Id, m_CastItem);
SendCastResult(SPELL_FAILED_DONT_REPORT);
SendInterrupted(0);
modOwner->SetSpellModTakingSpell(this, false);
finish(false);
SetExecutedCurrently(false);
return;
}
}
}
}
}
// if the spell allows the creature to turn while casting, then adjust server-side orientation to face the target now
// client-side orientation is handled by the client itself, as the cast target is targeted due to Creature::FocusTarget
if (m_caster->GetTypeId() == TYPEID_UNIT && !m_caster->HasUnitFlag(UNIT_FLAG_PLAYER_CONTROLLED))
if (m_spellInfo->CasterCanTurnDuringCast())
if (WorldObject* objTarget = m_targets.GetObjectTarget())
m_caster->SetInFront(objTarget);
SelectSpellTargets();
// Spell may be finished after target map check
if (m_spellState == SPELL_STATE_FINISHED)
{
SendInterrupted(0);
// cleanup after mod system
// triggered spell pointer can be not removed in some cases
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetSpellModTakingSpell(this, false);
finish(false);
SetExecutedCurrently(false);
return;
}
if (m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET))
if (Creature* pet = ObjectAccessor::GetCreature(*m_caster, m_caster->GetPetGUID()))
pet->DespawnOrUnsummon();
PrepareTriggersExecutedOnHit();
CallScriptOnCastHandlers();
// traded items have trade slot instead of guid in m_itemTargetGUID
// set to real guid to be sent later to the client
m_targets.UpdateTradeSlotItem();
if (Player* player = m_caster->ToPlayer())
{
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_ITEM) && m_CastItem)
{
player->StartCriteriaTimer(CRITERIA_TIMED_TYPE_ITEM, m_CastItem->GetEntry());
player->UpdateCriteria(CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry());
}
player->UpdateCriteria(CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id);
}
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST))
{
// Powers have to be taken before SendSpellGo
TakePower();
TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot
}
else if (Item* targetItem = m_targets.GetItemTarget())
{
/// Not own traded item (in trader trade slot) req. reagents including triggered spell case
if (targetItem->GetOwnerGUID() != m_caster->GetGUID())
TakeReagents();
}
// CAST SPELL
SendSpellCooldown();
PrepareScriptHitHandlers();
if (!m_spellInfo->LaunchDelay)
{
HandleLaunchPhase();
m_launchHandled = true;
}
// we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()...
SendSpellGo();
// Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells
if ((m_spellInfo->HasHitDelay() && !m_spellInfo->IsChanneled()) || m_spellInfo->HasAttribute(SPELL_ATTR4_UNK4))
{
// Remove used for cast item if need (it can be already NULL after TakeReagents call
// in case delayed spell remove item at cast delay start
TakeCastItem();
// Okay, maps created, now prepare flags
m_immediateHandled = false;
m_spellState = SPELL_STATE_DELAYED;
SetDelayStart(0);
if (m_caster->HasUnitState(UNIT_STATE_CASTING) && !m_caster->IsNonMeleeSpellCast(false, false, true))
m_caster->ClearUnitState(UNIT_STATE_CASTING);
}
else
{
// Immediate spell, no big deal
handle_immediate();
}
CallScriptAfterCastHandlers();
if (m_caster->IsCreature() && m_caster->IsAIEnabled)
m_caster->ToCreature()->AI()->OnSpellCasted(m_spellInfo);
if (m_caster->IsPlayer())
sScriptMgr->OnPlayerSuccessfulSpellCast(m_caster->ToPlayer(), this);
if (const std::vector<int32> *spell_triggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id))
{
for (std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i)
if (*i < 0)
m_caster->RemoveAurasDueToSpell(-(*i));
else
m_caster->CastSpell(m_targets.GetUnitTarget() ? m_targets.GetUnitTarget() : m_caster, *i, true);
}
if (modOwner)
{
modOwner->SetSpellModTakingSpell(this, false);
//Clear spell cooldowns after every spell is cast if .cheat cooldown is enabled.
if (modOwner->GetCommandStatus(CHEAT_COOLDOWN))
{
m_caster->GetSpellHistory()->ResetCooldown(m_spellInfo->Id, true);
m_caster->GetSpellHistory()->RestoreCharge(m_spellInfo->ChargeCategoryId);
}
}
SetExecutedCurrently(false);
if (!m_originalCaster)
return;
// Handle procs on cast
uint32 procAttacker = m_procAttacker;
if (!procAttacker)
{
if (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC)
procAttacker = m_spellInfo->IsPositive() ? PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS : PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG;
else
procAttacker = m_spellInfo->IsPositive() ? PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS : PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG;
}
uint32 hitMask = m_hitMask;
if (!(hitMask & PROC_HIT_CRITICAL))
hitMask |= PROC_HIT_NORMAL;
m_originalCaster->ProcSkillsAndAuras(nullptr, procAttacker, PROC_FLAG_NONE, PROC_SPELL_TYPE_MASK_ALL, PROC_SPELL_PHASE_CAST, hitMask, this, nullptr, nullptr);
// Call CreatureAI hook OnSuccessfulSpellCast
if (Creature* caster = m_originalCaster->ToCreature())
if (caster->IsAIEnabled)
caster->AI()->OnSuccessfulSpellCast(GetSpellInfo());
}
void Spell::handle_immediate()
{
// start channeling if applicable
if (m_spellInfo->IsChanneled())
{
int32 duration = m_spellInfo->GetDuration();
if (duration > 0)
{
// First mod_duration then haste - see Missile Barrage
// Apply duration mod
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
// Apply haste mods
m_caster->ModSpellDurationTime(m_spellInfo, duration, this);
m_spellState = SPELL_STATE_CASTING;
m_caster->AddInterruptMask(m_spellInfo->ChannelInterruptFlags);
m_channeledDuration = duration;
SendChannelStart(duration);
}
else if (duration == -1)
{
m_spellState = SPELL_STATE_CASTING;
m_caster->AddInterruptMask(m_spellInfo->ChannelInterruptFlags);
SendChannelStart(duration);
}
}
PrepareTargetProcessing();
// process immediate effects (items, ground, etc.) also initialize some variables
_handle_immediate_phase();
// consider spell hit for some spells without target, so they may proc on finish phase correctly
if (m_UniqueTargetInfo.empty())
m_hitMask = PROC_HIT_NORMAL;
else
{
for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
DoAllEffectOnTarget(&(*ihit));
}
for (std::vector<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit)
DoAllEffectOnTarget(&(*ihit));
FinishTargetProcessing();
// spell is finished, perform some last features of the spell here
_handle_finish_phase();
// Remove used for cast item if need (it can be already NULL after TakeReagents call
TakeCastItem();
if (m_spellState != SPELL_STATE_CASTING)
finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell)
}
uint64 Spell::handle_delayed(uint64 t_offset)
{
if (!UpdatePointers())
{
// finish the spell if UpdatePointers() returned false, something wrong happened there
finish(false);
return 0;
}
bool single_missile = m_targets.HasDst();
uint64 next_time = 0;
if (!m_launchHandled)
{
uint64 launchMoment = uint64(std::floor(m_spellInfo->LaunchDelay * 1000.0f));
if (launchMoment > t_offset)
return launchMoment;
HandleLaunchPhase();
m_launchHandled = true;
if (m_delayMoment > t_offset)
{
if (single_missile)
return m_delayMoment;
next_time = m_delayMoment;
if ((m_UniqueTargetInfo.size() > 2 || (m_UniqueTargetInfo.size() == 1 && m_UniqueTargetInfo.front().targetGUID == m_caster->GetGUID())) || !m_UniqueGOTargetInfo.empty())
{
t_offset = 0; // if LaunchDelay was present then the only target that has timeDelay = 0 is m_caster - and that is the only target we want to process now
}
}
}
if (single_missile && !t_offset)
return m_delayMoment;
Player* modOwner = m_caster->GetSpellModOwner();
if (modOwner)
modOwner->SetSpellModTakingSpell(this, true);
PrepareTargetProcessing();
if (!m_immediateHandled && t_offset)
{
_handle_immediate_phase();
m_immediateHandled = true;
}
// now recheck units targeting correctness (need before any effects apply to prevent adding immunity at first effect not allow apply second spell effect and similar cases)
for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->processed == false)
{
if (single_missile || ihit->timeDelay <= t_offset)
{
ihit->timeDelay = t_offset;
DoAllEffectOnTarget(&(*ihit));
}
else if (next_time == 0 || ihit->timeDelay < next_time)
next_time = ihit->timeDelay;
}
}
m_currentTargetInfo = nullptr;
// now recheck gameobject targeting correctness
for (std::vector<GOTargetInfo>::iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit)
{
if (ighit->processed == false)
{
if (single_missile || ighit->timeDelay <= t_offset)
DoAllEffectOnTarget(&(*ighit));
else if (next_time == 0 || ighit->timeDelay < next_time)
next_time = ighit->timeDelay;
}
}
FinishTargetProcessing();
if (modOwner)
modOwner->SetSpellModTakingSpell(this, false);
// All targets passed - need finish phase
if (next_time == 0)
{
// spell is finished, perform some last features of the spell here
_handle_finish_phase();
finish(true); // successfully finish spell cast
// return zero, spell is finished now
return 0;
}
else
{
// spell is unfinished, return next execution time
return next_time;
}
}
void Spell::_handle_immediate_phase()
{
m_spellAura = NULL;
// handle some immediate features of the spell here
HandleThreatSpells();
PrepareScriptHitHandlers();
// handle effects with SPELL_EFFECT_HANDLE_HIT mode
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
// don't do anything for empty effect
if (!effect || !effect->IsEffect())
continue;
// call effect handlers to handle destination hit
HandleEffects(NULL, NULL, NULL, effect->EffectIndex, SPELL_EFFECT_HANDLE_HIT);
}
// process items
for (std::vector<ItemTargetInfo>::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit)
DoAllEffectOnTarget(&(*ihit));
}
void Spell::_handle_finish_phase()
{
if (m_caster->m_playerMovingMe)
{
// Take for real after all targets are processed
if (m_needComboPoints)
m_caster->m_playerMovingMe->ClearComboPoints();
// Real add combo points from effects
if (m_comboPointGain)
m_caster->m_playerMovingMe->GainSpellComboPoints(m_comboPointGain);
}
if (m_caster->m_extraAttacks && m_spellInfo->HasEffect(SPELL_EFFECT_ADD_EXTRA_ATTACKS))
{
if (Unit* victim = ObjectAccessor::GetUnit(*m_caster, m_targets.GetOrigUnitTargetGUID()))
m_caster->HandleProcExtraAttackFor(victim);
else
m_caster->m_extraAttacks = 0;
}
// Handle procs on finish
if (!m_originalCaster)
return;
uint32 procAttacker = m_procAttacker;
if (!procAttacker)
{
if (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC)
procAttacker = m_spellInfo->IsPositive() ? PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS : PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG;
else
procAttacker = m_spellInfo->IsPositive() ? PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS : PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG;
}
m_originalCaster->ProcSkillsAndAuras(nullptr, procAttacker, PROC_FLAG_NONE, PROC_SPELL_TYPE_MASK_ALL, PROC_SPELL_PHASE_FINISH, m_hitMask, this, nullptr, nullptr);
}
void Spell::SendSpellCooldown()
{
if (m_CastItem)
m_caster->GetSpellHistory()->HandleCooldowns(m_spellInfo, m_CastItem, this);
else
m_caster->GetSpellHistory()->HandleCooldowns(m_spellInfo, m_castItemEntry, this);
}
void Spell::update(uint32 difftime)
{
// update pointers based at it's GUIDs
if (!UpdatePointers())
{
// cancel the spell if UpdatePointers() returned false, something wrong happened there
cancel();
return;
}
if (!m_targets.GetUnitTargetGUID().IsEmpty() && !m_targets.GetUnitTarget())
{
TC_LOG_DEBUG("spells", "Spell %u is cancelled due to removal of target.", m_spellInfo->Id);
cancel();
return;
}
// check if the player caster has moved before the spell finished
// with the exception of spells affected with SPELL_AURA_CAST_WHILE_WALKING effect
SpellEffectInfo const* effect = m_spellInfo->GetEffect(EFFECT_0);
if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) &&
m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) &&
((effect && effect->Effect != SPELL_EFFECT_STUCK) || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING_FAR)) &&
!m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_CAST_WHILE_WALKING, m_spellInfo))
{
// don't cancel for melee, autorepeat, triggered and instant spells
if (!m_spellInfo->IsNextMeleeSwingSpell() && !IsAutoRepeat() && !IsTriggered() && !(IsChannelActive() && m_spellInfo->IsMoveAllowedChannel()))
{
// if charmed by creature, trust the AI not to cheat and allow the cast to proceed
// @todo this is a hack, "creature" movesplines don't differentiate turning/moving right now
// however, checking what type of movement the spline is for every single spline would be really expensive
if (!m_caster->GetCharmerGUID().IsCreature())
cancel();
}
}
switch (m_spellState)
{
case SPELL_STATE_PREPARING:
{
if (m_timer > 0)
{
if (difftime >= (uint32)m_timer)
m_timer = 0;
else
m_timer -= difftime;
}
if (m_timer == 0 && !m_spellInfo->IsNextMeleeSwingSpell() && !IsAutoRepeat())
// don't CheckCast for instant spells - done in spell::prepare, skip duplicate checks, needed for range checks for example
cast(!m_casttime);
break;
}
case SPELL_STATE_CASTING:
{
if (m_timer)
{
// check if there are alive targets left
if (!UpdateChanneledTargetList())
{
TC_LOG_DEBUG("spells", "Channeled spell %d is removed due to lack of targets", m_spellInfo->Id);
m_timer = 0;
// Also remove applied auras
for (TargetInfo const& target : m_UniqueTargetInfo)
if (Unit* unit = m_caster->GetGUID() == target.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target.targetGUID))
unit->RemoveOwnedAura(m_spellInfo->Id, m_originalCasterGUID, 0, AURA_REMOVE_BY_CANCEL);
}
if (m_timer > 0)
{
if (difftime >= (uint32)m_timer)
m_timer = 0;
else
m_timer -= difftime;
}
}
if (m_timer == 0)
{
SendChannelUpdate(0);
finish();
}
break;
}
default:
break;
}
}
void Spell::finish(bool ok)
{
if (!m_caster)
return;
if (m_spellState == SPELL_STATE_FINISHED)
return;
m_spellState = SPELL_STATE_FINISHED;
if (m_caster->IsCreature() && m_caster->IsAIEnabled)
m_caster->ToCreature()->AI()->OnSpellFinished(m_spellInfo);
if (m_spellInfo->IsChanneled())
m_caster->UpdateInterruptMask();
if (m_caster->HasUnitState(UNIT_STATE_CASTING) && !m_caster->IsNonMeleeSpellCast(false, false, true))
m_caster->ClearUnitState(UNIT_STATE_CASTING);
// Unsummon summon as possessed creatures on spell cancel
if (m_spellInfo->IsChanneled() && m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (Unit* charm = m_caster->GetCharm())
if (charm->GetTypeId() == TYPEID_UNIT
&& charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET)
&& charm->m_unitData->CreatedBySpell == int32(m_spellInfo->Id))
((Puppet*)charm)->UnSummon();
}
if (Creature* creatureCaster = m_caster->ToCreature())
creatureCaster->ReleaseFocus(this);
if (!ok)
return;
if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsSummon())
{
// Unsummon statue
uint32 spell = m_caster->m_unitData->CreatedBySpell;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell, GetCastDifficulty());
if (spellInfo && spellInfo->IconFileDataId == 134230)
{
TC_LOG_DEBUG("spells", "Statue %s is unsummoned in spell %d finish", m_caster->GetGUID().ToString().c_str(), m_spellInfo->Id);
m_caster->setDeathState(JUST_DIED);
return;
}
}
if (IsAutoActionResetSpell())
{
bool found = false;
Unit::AuraEffectList const& vIgnoreReset = m_caster->GetAuraEffectsByType(SPELL_AURA_IGNORE_MELEE_RESET);
for (Unit::AuraEffectList::const_iterator i = vIgnoreReset.begin(); i != vIgnoreReset.end(); ++i)
{
if ((*i)->IsAffectingSpell(m_spellInfo))
{
found = true;
break;
}
}
if (!found && !m_spellInfo->HasAttribute(SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS))
{
m_caster->resetAttackTimer(BASE_ATTACK);
if (m_caster->haveOffhandWeapon())
m_caster->resetAttackTimer(OFF_ATTACK);
m_caster->resetAttackTimer(RANGED_ATTACK);
}
}
// potions disabled by client, send event "not in combat" if need
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (!m_triggeredByAuraSpell)
m_caster->ToPlayer()->UpdatePotionCooldown(this);
}
// Stop Attack for some spells
if (m_spellInfo->HasAttribute(SPELL_ATTR0_STOP_ATTACK_TARGET))
m_caster->AttackStop();
}
template<class T>
inline void FillSpellCastFailedArgs(T& packet, ObjectGuid castId, SpellInfo const* spellInfo, SpellCastResult result, SpellCustomErrors customError, uint32* param1 /*= nullptr*/, uint32* param2 /*= nullptr*/, Player* caster)
{
packet.CastID = castId;
packet.SpellID = spellInfo->Id;
packet.Reason = result;
switch (result)
{
case SPELL_FAILED_NOT_READY:
if (param1)
packet.FailedArg1 = *param1;
else
packet.FailedArg1 = 0; // unknown (value 1 update cooldowns on client flag)
break;
case SPELL_FAILED_REQUIRES_SPELL_FOCUS:
if (param1)
packet.FailedArg1 = *param1;
else
packet.FailedArg1 = spellInfo->RequiresSpellFocus; // SpellFocusObject.dbc id
break;
case SPELL_FAILED_REQUIRES_AREA: // AreaTable.dbc id
if (param1)
packet.FailedArg1 = *param1;
else
{
// hardcode areas limitation case
switch (spellInfo->Id)
{
case 41617: // Cenarion Mana Salve
case 41619: // Cenarion Healing Salve
packet.FailedArg1 = 3905;
break;
case 41618: // Bottled Nethergon Energy
case 41620: // Bottled Nethergon Vapor
packet.FailedArg1 = 3842;
break;
case 45373: // Bloodberry Elixir
packet.FailedArg1 = 4075;
break;
default: // default case (don't must be)
packet.FailedArg1 = 0;
break;
}
}
break;
case SPELL_FAILED_TOTEMS:
if (param1)
{
packet.FailedArg1 = *param1;
if (param2)
packet.FailedArg2 = *param2;
}
else
{
if (spellInfo->Totem[0])
packet.FailedArg1 = spellInfo->Totem[0];
if (spellInfo->Totem[1])
packet.FailedArg2 = spellInfo->Totem[1];
}
break;
case SPELL_FAILED_TOTEM_CATEGORY:
if (param1)
{
packet.FailedArg1 = *param1;
if (param2)
packet.FailedArg2 = *param2;
}
else
{
if (spellInfo->TotemCategory[0])
packet.FailedArg1 = spellInfo->TotemCategory[0];
if (spellInfo->TotemCategory[1])
packet.FailedArg2 = spellInfo->TotemCategory[1];
}
break;
case SPELL_FAILED_EQUIPPED_ITEM_CLASS:
case SPELL_FAILED_EQUIPPED_ITEM_CLASS_MAINHAND:
case SPELL_FAILED_EQUIPPED_ITEM_CLASS_OFFHAND:
if (param1 && param2)
{
packet.FailedArg1 = *param1;
packet.FailedArg2 = *param2;
}
else
{
packet.FailedArg1 = spellInfo->EquippedItemClass;
packet.FailedArg2 = spellInfo->EquippedItemSubClassMask;
}
break;
case SPELL_FAILED_TOO_MANY_OF_ITEM:
{
if (param1)
packet.FailedArg1 = *param1;
else
{
uint32 item = 0;
for (SpellEffectInfo const* effect : spellInfo->GetEffects())
if (effect->ItemType)
item = effect->ItemType;
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item);
if (proto && proto->GetItemLimitCategory())
packet.FailedArg1 = proto->GetItemLimitCategory();
}
break;
}
case SPELL_FAILED_PREVENTED_BY_MECHANIC:
if (param1)
packet.FailedArg1 = *param1;
else
packet.FailedArg1 = spellInfo->GetAllEffectsMechanicMask(); // SpellMechanic.dbc id
break;
case SPELL_FAILED_NEED_EXOTIC_AMMO:
if (param1)
packet.FailedArg1 = *param1;
else
packet.FailedArg1 = spellInfo->EquippedItemSubClassMask; // seems correct...
break;
case SPELL_FAILED_NEED_MORE_ITEMS:
if (param1 && param2)
{
packet.FailedArg1 = *param1;
packet.FailedArg2 = *param2;
}
else
{
packet.FailedArg1 = 0; // Item id
packet.FailedArg2 = 0; // Item count?
}
break;
case SPELL_FAILED_MIN_SKILL:
if (param1 && param2)
{
packet.FailedArg1 = *param1;
packet.FailedArg2 = *param2;
}
else
{
packet.FailedArg1 = 0; // SkillLine.dbc id
packet.FailedArg2 = 0; // required skill value
}
break;
case SPELL_FAILED_FISHING_TOO_LOW:
if (param1)
packet.FailedArg1 = *param1;
else
packet.FailedArg1 = 0; // required fishing skill
break;
case SPELL_FAILED_CUSTOM_ERROR:
packet.FailedArg1 = customError;
break;
case SPELL_FAILED_SILENCED:
if (param1)
packet.FailedArg1 = *param1;
else
packet.FailedArg1 = 0; // Unknown
break;
case SPELL_FAILED_REAGENTS:
{
if (param1)
packet.FailedArg1 = *param1;
else
{
uint32 missingItem = 0;
for (uint32 i = 0; i < MAX_SPELL_REAGENTS; i++)
{
if (spellInfo->Reagent[i] <= 0)
continue;
uint32 itemid = spellInfo->Reagent[i];
uint32 itemcount = spellInfo->ReagentCount[i];
if (!caster->HasItemCount(itemid, itemcount))
{
missingItem = itemid;
break;
}
}
packet.FailedArg1 = missingItem; // first missing item
}
break;
}
case SPELL_FAILED_CANT_UNTALENT:
{
ASSERT(param1);
packet.FailedArg1 = *param1;
break;
}
// TODO: SPELL_FAILED_NOT_STANDING
default:
break;
}
}
void Spell::SendCastResult(SpellCastResult result, uint32* param1 /*= nullptr*/, uint32* param2 /*= nullptr*/) const
{
if (result == SPELL_CAST_OK)
return;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
if (m_caster->ToPlayer()->IsLoading()) // don't send cast results at loading time
return;
if (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR)
result = SPELL_FAILED_DONT_REPORT;
WorldPackets::Spells::CastFailed castFailed;
castFailed.SpellXSpellVisualID = m_SpellVisual;
FillSpellCastFailedArgs(castFailed, m_castId, m_spellInfo, result, m_customError, param1, param2, m_caster->ToPlayer());
m_caster->ToPlayer()->SendDirectMessage(castFailed.Write());
}
void Spell::SendPetCastResult(SpellCastResult result, uint32* param1 /*= nullptr*/, uint32* param2 /*= nullptr*/) const
{
if (result == SPELL_CAST_OK)
return;
Unit* owner = m_caster->GetCharmerOrOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return;
if (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR)
result = SPELL_FAILED_DONT_REPORT;
WorldPackets::Spells::PetCastFailed petCastFailed;
FillSpellCastFailedArgs(petCastFailed, m_castId, m_spellInfo, result, SPELL_CUSTOM_ERROR_NONE, param1, param2, owner->ToPlayer());
owner->ToPlayer()->SendDirectMessage(petCastFailed.Write());
}
void Spell::SendCastResult(Player* caster, SpellInfo const* spellInfo, uint32 spellVisual, ObjectGuid cast_count, SpellCastResult result, SpellCustomErrors customError /*= SPELL_CUSTOM_ERROR_NONE*/, uint32* param1 /*= nullptr*/, uint32* param2 /*= nullptr*/)
{
if (result == SPELL_CAST_OK)
return;
WorldPackets::Spells::CastFailed packet;
packet.SpellXSpellVisualID = spellVisual;
FillSpellCastFailedArgs(packet, cast_count, spellInfo, result, customError, param1, param2, caster);
caster->GetSession()->SendPacket(packet.Write());
}
void Spell::SendMountResult(MountResult result)
{
if (result == MountResult::Ok)
return;
if (!m_caster->IsPlayer())
return;
Player* caster = m_caster->ToPlayer();
if (caster->IsLoading()) // don't send mount results at loading time
return;
WorldPackets::Spells::MountResult packet;
packet.Result = AsUnderlyingType(result);
caster->SendDirectMessage(packet.Write());
}
void Spell::SendSpellStart()
{
if (!IsNeedSendToClient())
return;
TC_LOG_DEBUG("spells", "Sending SMSG_SPELL_START id=%u", m_spellInfo->Id);
uint32 castFlags = CAST_FLAG_HAS_TRAJECTORY;
uint32 schoolImmunityMask = m_caster->GetSchoolImmunityMask();
uint32 mechanicImmunityMask = m_caster->GetMechanicImmunityMask();
if (schoolImmunityMask || mechanicImmunityMask)
castFlags |= CAST_FLAG_IMMUNITY;
if (((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell) && !m_fromClient)
castFlags |= CAST_FLAG_PENDING;
if (m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO) || m_spellInfo->HasAttribute(SPELL_ATTR0_CU_NEEDS_AMMO_DATA))
castFlags |= CAST_FLAG_PROJECTILE;
if ((m_caster->GetTypeId() == TYPEID_PLAYER ||
(m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsPet()))
&& std::find_if(m_powerCost.begin(), m_powerCost.end(), [](SpellPowerCost const& cost) { return cost.Power != POWER_HEALTH; }) != m_powerCost.end())
castFlags |= CAST_FLAG_POWER_LEFT_SELF;
if (std::find_if(m_powerCost.begin(), m_powerCost.end(), [](SpellPowerCost const& cost) { return cost.Power == POWER_RUNES; }) != m_powerCost.end())
castFlags |= CAST_FLAG_NO_GCD; // not needed, but Blizzard sends it
WorldPackets::Spells::SpellStart packet;
WorldPackets::Spells::SpellCastData& castData = packet.Cast;
if (m_CastItem)
castData.CasterGUID = m_CastItem->GetGUID();
else
castData.CasterGUID = m_caster->GetGUID();
castData.CasterUnit = m_caster->GetGUID();
castData.CastID = m_castId;
castData.OriginalCastID = m_originalCastId;
castData.SpellID = m_spellInfo->Id;
castData.SpellXSpellVisualID = m_SpellVisual;
castData.CastFlags = castFlags;
castData.CastFlagsEx = m_castFlagsEx;
castData.CastTime = m_casttime;
m_targets.Write(castData.Target);
if (castFlags & CAST_FLAG_POWER_LEFT_SELF)
{
for (SpellPowerCost const& cost : m_powerCost)
{
WorldPackets::Spells::SpellPowerData powerData;
powerData.Type = cost.Power;
powerData.Cost = m_caster->GetPower(cost.Power);
castData.RemainingPower.push_back(powerData);
}
}
if (castFlags & CAST_FLAG_RUNE_LIST) // rune cooldowns list
{
castData.RemainingRunes = boost::in_place();
//TODO: There is a crash caused by a spell with CAST_FLAG_RUNE_LIST casted by a creature
//The creature is the mover of a player, so HandleCastSpellOpcode uses it as the caster
if (Player* player = m_caster->ToPlayer())
{
castData.RemainingRunes->Start = m_runesState; // runes state before
castData.RemainingRunes->Count = player->GetRunesState(); // runes state after
for (uint8 i = 0; i < player->GetMaxPower(POWER_RUNES); ++i)
{
// float casts ensure the division is performed on floats as we need float result
float baseCd = float(player->GetRuneBaseCooldown());
castData.RemainingRunes->Cooldowns.push_back((baseCd - float(player->GetRuneCooldown(i))) / baseCd * 255); // rune cooldown passed
}
}
else
{
castData.RemainingRunes->Start = 0;
castData.RemainingRunes->Count = 0;
for (uint8 i = 0; i < player->GetMaxPower(POWER_RUNES); ++i)
castData.RemainingRunes->Cooldowns.push_back(0);
}
}
if (castFlags & CAST_FLAG_PROJECTILE)
UpdateSpellCastDataAmmo(castData.Ammo);
if (castFlags & CAST_FLAG_IMMUNITY)
{
castData.Immunities.School = schoolImmunityMask;
castData.Immunities.Value = mechanicImmunityMask;
}
/** @todo implement heal prediction packet data
if (castFlags & CAST_FLAG_HEAL_PREDICTION)
{
castData.Predict.BeconGUID = ??
castData.Predict.Points = 0;
castData.Predict.Type = 0;
}**/
m_caster->SendMessageToSet(packet.Write(), true);
}
void Spell::SendSpellGo()
{
// not send invisible spell casting
if (!IsNeedSendToClient())
return;
TC_LOG_DEBUG("spells", "Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id);
uint32 castFlags = CAST_FLAG_UNKNOWN_9;
// triggered spells with spell visual != 0
if (((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell) && !m_fromClient)
castFlags |= CAST_FLAG_PENDING;
if (m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO) || m_spellInfo->HasAttribute(SPELL_ATTR0_CU_NEEDS_AMMO_DATA))
castFlags |= CAST_FLAG_PROJECTILE; // arrows/bullets visual
if ((m_caster->GetTypeId() == TYPEID_PLAYER ||
(m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsPet()))
&& std::find_if(m_powerCost.begin(), m_powerCost.end(), [](SpellPowerCost const& cost) { return cost.Power != POWER_HEALTH; }) != m_powerCost.end())
castFlags |= CAST_FLAG_POWER_LEFT_SELF; // should only be sent to self, but the current messaging doesn't make that possible
if ((m_caster->GetTypeId() == TYPEID_PLAYER)
&& (m_caster->getClass() == CLASS_DEATH_KNIGHT)
&& std::find_if(m_powerCost.begin(), m_powerCost.end(), [](SpellPowerCost const& cost) { return cost.Power == POWER_RUNES; }) != m_powerCost.end()
&& !(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST))
{
castFlags |= CAST_FLAG_NO_GCD; // not needed, but Blizzard sends it
castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list
}
if (m_spellInfo->HasEffect(SPELL_EFFECT_ACTIVATE_RUNE))
castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list
if (m_targets.HasTraj())
castFlags |= CAST_FLAG_ADJUST_MISSILE;
if (!m_spellInfo->StartRecoveryTime)
castFlags |= CAST_FLAG_NO_GCD;
WorldPackets::Spells::SpellGo packet;
WorldPackets::Spells::SpellCastData& castData = packet.Cast;
if (m_CastItem)
castData.CasterGUID = m_CastItem->GetGUID();
else
castData.CasterGUID = m_caster->GetGUID();
castData.CasterUnit = m_caster->GetGUID();
castData.CastID = m_castId;
castData.OriginalCastID = m_originalCastId;
castData.SpellID = m_spellInfo->Id;
castData.SpellXSpellVisualID = m_SpellVisual;
castData.CastFlags = castFlags;
castData.CastFlagsEx = m_castFlagsEx;
castData.CastTime = getMSTime();
UpdateSpellCastDataTargets(castData);
m_targets.Write(castData.Target);
if (castFlags & CAST_FLAG_POWER_LEFT_SELF)
{
for (SpellPowerCost const& cost : m_powerCost)
{
WorldPackets::Spells::SpellPowerData powerData;
powerData.Type = cost.Power;
powerData.Cost = m_caster->GetPower(cost.Power);
castData.RemainingPower.push_back(powerData);
}
}
if (castFlags & CAST_FLAG_RUNE_LIST) // rune cooldowns list
{
castData.RemainingRunes = boost::in_place();
//TODO: There is a crash caused by a spell with CAST_FLAG_RUNE_LIST casted by a creature
//The creature is the mover of a player, so HandleCastSpellOpcode uses it as the caster
if (Player* player = m_caster->ToPlayer())
{
castData.RemainingRunes->Start = m_runesState; // runes state before
castData.RemainingRunes->Count = player->GetRunesState(); // runes state after
for (uint8 i = 0; i < player->GetMaxPower(POWER_RUNES); ++i)
{
// float casts ensure the division is performed on floats as we need float result
float baseCd = float(player->GetRuneBaseCooldown());
castData.RemainingRunes->Cooldowns.push_back((baseCd - float(player->GetRuneCooldown(i))) / baseCd * 255); // rune cooldown passed
}
}
else
{
castData.RemainingRunes->Start = 0;
castData.RemainingRunes->Count = 0;
for (uint8 i = 0; i < player->GetMaxPower(POWER_RUNES); ++i)
castData.RemainingRunes->Cooldowns.push_back(0);
}
}
if (castFlags & CAST_FLAG_ADJUST_MISSILE)
{
castData.MissileTrajectory.TravelTime = m_delayMoment;
castData.MissileTrajectory.Pitch = m_targets.GetPitch();
}
packet.LogData.Initialize(this);
m_caster->SendCombatLogMessage(&packet);
}
/// Writes miss and hit targets for a SMSG_SPELL_GO packet
void Spell::UpdateSpellCastDataTargets(WorldPackets::Spells::SpellCastData& data)
{
// This function also fill data for channeled spells:
// m_needAliveTargetMask req for stop channeling if one target die
for (TargetInfo& targetInfo : m_UniqueTargetInfo)
{
if (targetInfo.effectMask == 0) // No effect apply - all immune add state
// possibly SPELL_MISS_IMMUNE2 for this??
targetInfo.missCondition = SPELL_MISS_IMMUNE2;
if (targetInfo.missCondition == SPELL_MISS_NONE) // hits
{
data.HitTargets.push_back(targetInfo.targetGUID);
data.HitStatus.emplace_back(SPELL_MISS_NONE);
m_channelTargetEffectMask |= targetInfo.effectMask;
}
else // misses
{
data.MissTargets.push_back(targetInfo.targetGUID);
data.MissStatus.emplace_back(targetInfo.missCondition, targetInfo.reflectResult);
}
}
for (GOTargetInfo const& targetInfo : m_UniqueGOTargetInfo)
data.HitTargets.push_back(targetInfo.targetGUID); // Always hits
// Reset m_needAliveTargetMask for non channeled spell
if (!m_spellInfo->IsChanneled())
m_channelTargetEffectMask = 0;
}
void Spell::UpdateSpellCastDataAmmo(WorldPackets::Spells::SpellAmmo& ammo)
{
uint32 ammoInventoryType = 0;
uint32 ammoDisplayID = 0;
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK);
if (pItem)
{
ammoInventoryType = pItem->GetTemplate()->GetInventoryType();
if (ammoInventoryType == INVTYPE_THROWN)
ammoDisplayID = pItem->GetDisplayId(m_caster->ToPlayer());
else if (m_caster->HasAura(46699)) // Requires No Ammo
{
ammoDisplayID = 5996; // normal arrow
ammoInventoryType = INVTYPE_AMMO;
}
}
}
else
{
for (uint8 i = 0; i < 3; ++i)
{
if (uint32 item_id = m_caster->GetVirtualItemId(i))
{
if (ItemEntry const* itemEntry = sItemStore.LookupEntry(item_id))
{
if (itemEntry->ClassID == ITEM_CLASS_WEAPON)
{
switch (itemEntry->SubclassID)
{
case ITEM_SUBCLASS_WEAPON_THROWN:
ammoDisplayID = sDB2Manager.GetItemDisplayId(item_id, m_caster->GetVirtualItemAppearanceMod(i));
ammoInventoryType = itemEntry->InventoryType;
break;
case ITEM_SUBCLASS_WEAPON_BOW:
case ITEM_SUBCLASS_WEAPON_CROSSBOW:
ammoDisplayID = 5996; // is this need fixing?
ammoInventoryType = INVTYPE_AMMO;
break;
case ITEM_SUBCLASS_WEAPON_GUN:
ammoDisplayID = 5998; // is this need fixing?
ammoInventoryType = INVTYPE_AMMO;
break;
}
if (ammoDisplayID)
break;
}
}
}
}
}
ammo.DisplayID = ammoDisplayID;
ammo.InventoryType = ammoInventoryType;
}
void Spell::SendSpellExecuteLog()
{
WorldPackets::CombatLog::SpellExecuteLog spellExecuteLog;
spellExecuteLog.Caster = m_caster->GetGUID();
spellExecuteLog.SpellID = m_spellInfo->Id;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
if (!effect)
continue;
if (_powerDrainTargets[effect->EffectIndex].empty() && _extraAttacksTargets[effect->EffectIndex].empty() &&
_durabilityDamageTargets[effect->EffectIndex].empty() && _genericVictimTargets[effect->EffectIndex].empty() &&
_tradeSkillTargets[effect->EffectIndex].empty() && _feedPetTargets[effect->EffectIndex].empty())
continue;
spellExecuteLog.Effects.emplace_back();
WorldPackets::CombatLog::SpellExecuteLog::SpellLogEffect& spellLogEffect = spellExecuteLog.Effects.back();
spellLogEffect.Effect = effect->Effect;
spellLogEffect.PowerDrainTargets = std::move(_powerDrainTargets[effect->EffectIndex]);
spellLogEffect.ExtraAttacksTargets = std::move(_extraAttacksTargets[effect->EffectIndex]);
spellLogEffect.DurabilityDamageTargets = std::move(_durabilityDamageTargets[effect->EffectIndex]);
spellLogEffect.GenericVictimTargets = std::move(_genericVictimTargets[effect->EffectIndex]);
spellLogEffect.TradeSkillTargets = std::move(_tradeSkillTargets[effect->EffectIndex]);
spellLogEffect.FeedPetTargets = std::move(_feedPetTargets[effect->EffectIndex]);
}
if (!spellExecuteLog.Effects.empty())
m_caster->SendCombatLogMessage(&spellExecuteLog);
}
void Spell::ExecuteLogEffectTakeTargetPower(uint8 effIndex, Unit* target, uint32 powerType, uint32 points, float amplitude)
{
SpellLogEffectPowerDrainParams spellLogEffectPowerDrainParams;
spellLogEffectPowerDrainParams.Victim = target->GetGUID();
spellLogEffectPowerDrainParams.Points = points;
spellLogEffectPowerDrainParams.PowerType = powerType;
spellLogEffectPowerDrainParams.Amplitude = amplitude;
_powerDrainTargets[effIndex].push_back(spellLogEffectPowerDrainParams);
}
void Spell::ExecuteLogEffectExtraAttacks(uint8 effIndex, Unit* victim, uint32 numAttacks)
{
SpellLogEffectExtraAttacksParams spellLogEffectExtraAttacksParams;
spellLogEffectExtraAttacksParams.Victim = victim->GetGUID();
spellLogEffectExtraAttacksParams.NumAttacks = numAttacks;
_extraAttacksTargets[effIndex].push_back(spellLogEffectExtraAttacksParams);
}
void Spell::ExecuteLogEffectInterruptCast(uint8 /*effIndex*/, Unit* victim, uint32 spellId)
{
WorldPackets::CombatLog::SpellInterruptLog data;
data.Caster = m_caster->GetGUID();
data.Victim = victim->GetGUID();
data.InterruptedSpellID = m_spellInfo->Id;
data.SpellID = spellId;
m_caster->SendMessageToSet(data.Write(), true);
}
void Spell::ExecuteLogEffectDurabilityDamage(uint8 effIndex, Unit* victim, int32 itemId, int32 amount)
{
SpellLogEffectDurabilityDamageParams spellLogEffectDurabilityDamageParams;
spellLogEffectDurabilityDamageParams.Victim = victim->GetGUID();
spellLogEffectDurabilityDamageParams.ItemID = itemId;
spellLogEffectDurabilityDamageParams.Amount = amount;
_durabilityDamageTargets[effIndex].push_back(spellLogEffectDurabilityDamageParams);
}
void Spell::ExecuteLogEffectOpenLock(uint8 effIndex, Object* obj)
{
SpellLogEffectGenericVictimParams spellLogEffectGenericVictimParams;
spellLogEffectGenericVictimParams.Victim = obj->GetGUID();
_genericVictimTargets[effIndex].push_back(spellLogEffectGenericVictimParams);
}
void Spell::ExecuteLogEffectCreateItem(uint8 effIndex, uint32 entry)
{
SpellLogEffectTradeSkillItemParams spellLogEffectTradeSkillItemParams;
spellLogEffectTradeSkillItemParams.ItemID = entry;
_tradeSkillTargets[effIndex].push_back(spellLogEffectTradeSkillItemParams);
}
void Spell::ExecuteLogEffectDestroyItem(uint8 effIndex, uint32 entry)
{
SpellLogEffectFeedPetParams spellLogEffectFeedPetParams;
spellLogEffectFeedPetParams.ItemID = entry;
_feedPetTargets[effIndex].push_back(spellLogEffectFeedPetParams);
}
void Spell::ExecuteLogEffectSummonObject(uint8 effIndex, WorldObject* obj)
{
SpellLogEffectGenericVictimParams spellLogEffectGenericVictimParams;
spellLogEffectGenericVictimParams.Victim = obj->GetGUID();
_genericVictimTargets[effIndex].push_back(spellLogEffectGenericVictimParams);
}
void Spell::ExecuteLogEffectUnsummonObject(uint8 effIndex, WorldObject* obj)
{
SpellLogEffectGenericVictimParams spellLogEffectGenericVictimParams;
spellLogEffectGenericVictimParams.Victim = obj->GetGUID();
_genericVictimTargets[effIndex].push_back(spellLogEffectGenericVictimParams);
}
void Spell::ExecuteLogEffectResurrect(uint8 effect, Unit* target)
{
SpellLogEffectGenericVictimParams spellLogEffectGenericVictimParams;
spellLogEffectGenericVictimParams.Victim = target->GetGUID();
_genericVictimTargets[effect].push_back(spellLogEffectGenericVictimParams);
}
void Spell::SendInterrupted(uint8 result)
{
WorldPackets::Spells::SpellFailure failurePacket;
failurePacket.CasterUnit = m_caster->GetGUID();
failurePacket.CastID = m_castId;
failurePacket.SpellID = m_spellInfo->Id;
failurePacket.SpellXSpellVisualID = m_SpellVisual;
failurePacket.Reason = result;
m_caster->SendMessageToSet(failurePacket.Write(), true);
WorldPackets::Spells::SpellFailedOther failedPacket;
failedPacket.CasterUnit = m_caster->GetGUID();
failedPacket.CastID = m_castId;
failedPacket.SpellID = m_spellInfo->Id;
failedPacket.Reason = result;
m_caster->SendMessageToSet(failedPacket.Write(), true);
}
void Spell::SendChannelUpdate(uint32 time)
{
if (time == 0)
{
m_caster->ClearChannelObjects();
m_caster->SetChannelSpellId(0);
m_caster->SetChannelSpellXSpellVisualId(0);
}
WorldPackets::Spells::SpellChannelUpdate spellChannelUpdate;
spellChannelUpdate.CasterGUID = m_caster->GetGUID();
spellChannelUpdate.TimeRemaining = time;
m_caster->SendMessageToSet(spellChannelUpdate.Write(), true);
}
void Spell::SendChannelStart(uint32 duration)
{
WorldPackets::Spells::SpellChannelStart spellChannelStart;
spellChannelStart.CasterGUID = m_caster->GetGUID();
spellChannelStart.SpellID = m_spellInfo->Id;
spellChannelStart.SpellXSpellVisualID = m_SpellVisual;
spellChannelStart.ChannelDuration = duration;
m_caster->SendMessageToSet(spellChannelStart.Write(), true);
uint32 schoolImmunityMask = m_caster->GetSchoolImmunityMask();
uint32 mechanicImmunityMask = m_caster->GetMechanicImmunityMask();
if (schoolImmunityMask || mechanicImmunityMask)
{
spellChannelStart.InterruptImmunities = boost::in_place();
spellChannelStart.InterruptImmunities->SchoolImmunities = schoolImmunityMask;
spellChannelStart.InterruptImmunities->Immunities = mechanicImmunityMask;
}
m_timer = duration;
for (TargetInfo const& target : m_UniqueTargetInfo)
{
m_caster->AddChannelObject(target.targetGUID);
if (m_UniqueTargetInfo.size() == 1 && m_UniqueGOTargetInfo.empty())
if(target.targetGUID != m_caster->GetGUID())
if (Creature* creatureCaster = m_caster->ToCreature())
if (!creatureCaster->IsFocusing(this))
creatureCaster->FocusTarget(this, ObjectAccessor::GetWorldObject(*creatureCaster, target.targetGUID));
}
for (GOTargetInfo const& target : m_UniqueGOTargetInfo)
m_caster->AddChannelObject(target.targetGUID);
m_caster->SetChannelSpellId(m_spellInfo->Id);
m_caster->SetChannelSpellXSpellVisualId(m_SpellVisual);
}
void Spell::SendResurrectRequest(Player* target)
{
// get resurrector name for creature resurrections, otherwise packet will be not accepted
// for player resurrections the name is looked up by guid
std::string const sentName(m_caster->GetTypeId() == TYPEID_PLAYER
? "" : m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex()));
WorldPackets::Spells::ResurrectRequest resurrectRequest;
resurrectRequest.ResurrectOffererGUID = m_caster->GetGUID();
resurrectRequest.ResurrectOffererVirtualRealmAddress = GetVirtualRealmAddress();
if (Pet* pet = target->GetPet())
{
if (CharmInfo* charmInfo = pet->GetCharmInfo())
resurrectRequest.PetNumber = charmInfo->GetPetNumber();
}
resurrectRequest.SpellID = m_spellInfo->Id;
//packet.ReadBit("UseTimer"); /// @todo: 6.x Has to be implemented
resurrectRequest.Sickness = m_caster->GetTypeId() != TYPEID_PLAYER; // "you'll be afflicted with resurrection sickness"
resurrectRequest.Name = sentName;
target->GetSession()->SendPacket(resurrectRequest.Write());
}
void Spell::TakeCastItem()
{
if (!m_CastItem)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
// not remove cast item at triggered spell (equipping, weapon damage, etc)
if (_triggeredCastFlags & TRIGGERED_IGNORE_CAST_ITEM)
return;
ItemTemplate const* proto = m_CastItem->GetTemplate();
if (!proto)
{
// This code is to avoid a crash
// I'm not sure, if this is really an error, but I guess every item needs a prototype
TC_LOG_ERROR("spells", "Cast item has no item prototype %s", m_CastItem->GetGUID().ToString().c_str());
return;
}
bool expendable = false;
bool withoutCharges = false;
for (ItemEffectEntry const* itemEffect : m_CastItem->GetEffects())
{
if (itemEffect->LegacySlotIndex >= m_CastItem->m_itemData->SpellCharges.size())
continue;
// item has limited charges
if (itemEffect->Charges)
{
if (itemEffect->Charges < 0)
expendable = true;
int32 charges = m_CastItem->GetSpellCharges(itemEffect->LegacySlotIndex);
// item has charges left
if (charges)
{
(charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use
if (proto->GetMaxStackSize() == 1)
m_CastItem->SetSpellCharges(itemEffect->LegacySlotIndex, charges);
m_CastItem->SetState(ITEM_CHANGED, player);
}
// all charges used
withoutCharges = (charges == 0);
}
}
if (expendable && withoutCharges)
{
uint32 count = 1;
m_caster->ToPlayer()->DestroyItemCount(m_CastItem, count, true);
// prevent crash at access to deleted m_targets.GetItemTarget
if (m_CastItem == m_targets.GetItemTarget())
m_targets.SetItemTarget(NULL);
m_CastItem = NULL;
m_castItemGUID.Clear();
m_castItemEntry = 0;
}
}
void Spell::TakePower()
{
if (m_CastItem || m_triggeredByAuraSpell)
return;
//Don't take power if the spell is cast while .cheat power is enabled.
if (m_caster->IsPlayer())
if (m_caster->ToPlayer()->GetCommandStatus(CHEAT_POWER))
return;
for (SpellPowerCost& cost : m_powerCost)
{
Powers powerType = Powers(cost.Power);
bool hit = true;
if (m_caster->IsPlayer())
{
if (powerType == POWER_RAGE || powerType == POWER_ENERGY || powerType == POWER_RUNES)
{
ObjectGuid targetGUID = m_targets.GetUnitTargetGUID();
if (!targetGUID.IsEmpty())
{
for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->targetGUID == targetGUID)
{
if (ihit->missCondition != SPELL_MISS_NONE)
{
hit = false;
//lower spell cost on fail (by talent aura)
if (Player* modOwner = m_caster->ToPlayer()->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_SPELL_COST_REFUND_ON_FAIL, cost.Amount);
}
break;
}
}
}
}
}
CallScriptOnTakePowerHandlers(cost);
if (powerType == POWER_RUNES)
{
TakeRunePower(hit);
continue;
}
if (!cost.Amount)
continue;
// health as power used
if (powerType == POWER_HEALTH)
{
m_caster->ModifyHealth(-cost.Amount);
continue;
}
if (powerType >= MAX_POWERS)
{
TC_LOG_ERROR("spells", "Spell::TakePower: Unknown power type '%d'", powerType);
continue;
}
if (hit)
m_caster->ModifyPower(powerType, -cost.Amount);
else if (cost.Amount > 0)
m_caster->ModifyPower(powerType, -irand(0, cost.Amount / 4));
}
}
SpellCastResult Spell::CheckRuneCost() const
{
int32 runeCost = std::accumulate(m_powerCost.begin(), m_powerCost.end(), 0, [](int32 totalCost, SpellPowerCost const& cost)
{
return totalCost + (cost.Power == POWER_RUNES ? cost.Amount : 0);
});
if (!runeCost)
return SPELL_CAST_OK;
Player* player = m_caster->ToPlayer();
if (!player)
return SPELL_CAST_OK;
if (player->getClass() != CLASS_DEATH_KNIGHT)
return SPELL_CAST_OK;
int32 readyRunes = 0;
for (int32 i = 0; i < player->GetMaxPower(POWER_RUNES); ++i)
if (player->GetRuneCooldown(i) == 0)
++readyRunes;
if (readyRunes < runeCost)
return SPELL_FAILED_NO_POWER; // not sure if result code is correct
return SPELL_CAST_OK;
}
void Spell::TakeRunePower(bool didHit)
{
if (m_caster->GetTypeId() != TYPEID_PLAYER || m_caster->getClass() != CLASS_DEATH_KNIGHT)
return;
Player* player = m_caster->ToPlayer();
m_runesState = player->GetRunesState(); // store previous state
int32 runeCost = std::accumulate(m_powerCost.begin(), m_powerCost.end(), 0, [](int32 totalCost, SpellPowerCost const& cost)
{
return totalCost + (cost.Power == POWER_RUNES ? cost.Amount : 0);
});
for (int32 i = 0; i < player->GetMaxPower(POWER_RUNES); ++i)
{
if (!player->GetRuneCooldown(i) && runeCost > 0)
{
player->SetRuneCooldown(i, didHit ? player->GetRuneBaseCooldown() : uint32(RUNE_MISS_COOLDOWN));
--runeCost;
}
sScriptMgr->OnModifyPower(player, POWER_RUNES, 0, runeCost, false, false);
}
}
void Spell::TakeReagents()
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
// do not take reagents for these item casts
if (m_CastItem && m_CastItem->GetTemplate()->GetFlags() & ITEM_FLAG_NO_REAGENT_COST)
return;
Player* p_caster = m_caster->ToPlayer();
if (p_caster->CanNoReagentCast(m_spellInfo))
return;
for (uint32 x = 0; x < MAX_SPELL_REAGENTS; ++x)
{
if (m_spellInfo->Reagent[x] <= 0)
continue;
uint32 itemid = m_spellInfo->Reagent[x];
uint32 itemcount = m_spellInfo->ReagentCount[x];
// if CastItem is also spell reagent
if (m_CastItem && m_CastItem->GetEntry() == itemid)
{
for (ItemEffectEntry const* itemEffect : m_CastItem->GetEffects())
{
if (itemEffect->LegacySlotIndex >= m_CastItem->m_itemData->SpellCharges.size())
continue;
// CastItem will be used up and does not count as reagent
int32 charges = m_CastItem->GetSpellCharges(itemEffect->LegacySlotIndex);
if (itemEffect->Charges < 0 && abs(charges) < 2)
{
++itemcount;
break;
}
}
m_CastItem = NULL;
m_castItemGUID.Clear();
m_castItemEntry = 0;
}
// if GetItemTarget is also spell reagent
if (m_targets.GetItemTargetEntry() == itemid)
m_targets.SetItemTarget(NULL);
p_caster->DestroyItemCount(itemid, itemcount, true);
}
}
void Spell::HandleThreatSpells()
{
if (m_UniqueTargetInfo.empty())
return;
if (!m_spellInfo->HasInitialAggro())
return;
float threat = 0.0f;
if (SpellThreatEntry const* threatEntry = sSpellMgr->GetSpellThreatEntry(m_spellInfo->Id))
{
if (threatEntry->apPctMod != 0.0f)
threat += threatEntry->apPctMod * m_caster->GetTotalAttackPowerValue(BASE_ATTACK);
threat += threatEntry->flatMod;
}
else if (!m_spellInfo->HasAttribute(SPELL_ATTR0_CU_NO_INITIAL_THREAT))
threat += m_spellInfo->SpellLevel;
// past this point only multiplicative effects occur
if (threat == 0.0f)
return;
// since 2.0.1 threat from positive effects also is distributed among all targets, so the overall caused threat is at most the defined bonus
threat /= m_UniqueTargetInfo.size();
for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
float threatToAdd = threat;
if (ihit->missCondition != SPELL_MISS_NONE)
threatToAdd = 0.0f;
Unit* target = ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID);
if (!target)
continue;
// positive spells distribute threat among all units that are in combat with target, like healing
if (m_spellInfo->IsPositive())
target->getHostileRefManager().threatAssist(m_caster, threatToAdd, m_spellInfo);
// for negative spells threat gets distributed among affected targets
else
{
if (!target->CanHaveThreatList())
continue;
target->AddThreat(m_caster, threatToAdd, m_spellInfo->GetSchoolMask(), m_spellInfo);
}
}
TC_LOG_DEBUG("spells", "Spell %u, added an additional %f threat for %s %u target(s)", m_spellInfo->Id, threat, m_spellInfo->IsPositive() ? "assisting" : "harming", uint32(m_UniqueTargetInfo.size()));
}
void Spell::HandleEffects(Unit* pUnitTarget, Item* pItemTarget, GameObject* pGOTarget, uint32 i, SpellEffectHandleMode mode)
{
effectHandleMode = mode;
unitTarget = pUnitTarget;
itemTarget = pItemTarget;
gameObjTarget = pGOTarget;
destTarget = &m_destTargets[i]._position;
effectInfo = m_spellInfo->GetEffect(i);
if (!effectInfo)
{
TC_LOG_ERROR("spells", "Spell: %u HandleEffects at EffectIndex: %u missing effect", m_spellInfo->Id, i);
return;
}
uint32 eff = effectInfo->Effect;
TC_LOG_DEBUG("spells", "Spell: %u Effect: %u", m_spellInfo->Id, eff);
damage = CalculateDamage(i, unitTarget, &variance);
bool preventDefault = CallScriptEffectHandlers((SpellEffIndex)i, mode);
if (!preventDefault && eff < TOTAL_SPELL_EFFECTS)
{
(this->*SpellEffects[eff].Value)((SpellEffIndex)i);
}
}
SpellCastResult Spell::CheckCast(bool strict, uint32* param1 /*= nullptr*/, uint32* param2 /*= nullptr*/)
{
// check death state
if (!m_caster->IsAlive() && !m_spellInfo->IsPassive() && !(m_spellInfo->HasAttribute(SPELL_ATTR0_CASTABLE_WHILE_DEAD) || (IsTriggered() && !m_triggeredByAuraSpell)))
return SPELL_FAILED_CASTER_DEAD;
// check cooldowns to prevent cheating
if (!m_spellInfo->IsPassive())
{
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
//can cast triggered (by aura only?) spells while have this flag
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURASTATE) && m_caster->ToPlayer()->HasPlayerFlag(PLAYER_ALLOW_ONLY_ABILITY))
return SPELL_FAILED_SPELL_IN_PROGRESS;
// check if we are using a potion in combat for the 2nd+ time. Cooldown is added only after caster gets out of combat
if (!IsIgnoringCooldowns() && m_caster->ToPlayer()->GetLastPotionId() && m_CastItem && (m_CastItem->IsPotion() || m_spellInfo->IsCooldownStartedOnEvent()))
return SPELL_FAILED_NOT_READY;
}
if (!m_caster->GetSpellHistory()->IsReady(m_spellInfo, m_castItemEntry, IsIgnoringCooldowns()))
{
if (IsTriggered() || m_triggeredByAuraSpell)
return SPELL_FAILED_DONT_REPORT;
else
return SPELL_FAILED_NOT_READY;
}
}
if (m_spellInfo->HasAttribute(SPELL_ATTR7_IS_CHEAT_SPELL) && !m_caster->HasUnitFlag2(UNIT_FLAG2_ALLOW_CHEAT_SPELLS))
{
m_customError = SPELL_CUSTOM_ERROR_GM_ONLY;
return SPELL_FAILED_CUSTOM_ERROR;
}
// Check global cooldown
if (strict && !(_triggeredCastFlags & TRIGGERED_IGNORE_GCD) && HasGlobalCooldown())
return !m_spellInfo->HasAttribute(SPELL_ATTR0_DISABLED_WHILE_ACTIVE) ? SPELL_FAILED_NOT_READY : SPELL_FAILED_DONT_REPORT;
// only triggered spells can be processed an ended battleground
if (!IsTriggered() && m_caster->GetTypeId() == TYPEID_PLAYER)
if (Battleground* bg = m_caster->ToPlayer()->GetBattleground())
if (bg->GetStatus() == STATUS_WAIT_LEAVE)
return SPELL_FAILED_DONT_REPORT;
if (m_caster->GetTypeId() == TYPEID_PLAYER && VMAP::VMapFactory::createOrGetVMapManager()->isLineOfSightCalcEnabled())
{
if (m_spellInfo->HasAttribute(SPELL_ATTR0_OUTDOORS_ONLY) &&
!m_caster->GetMap()->IsOutdoors(m_caster->GetPhaseShift(), m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ()))
return SPELL_FAILED_ONLY_OUTDOORS;
if (m_spellInfo->HasAttribute(SPELL_ATTR0_INDOORS_ONLY) &&
m_caster->GetMap()->IsOutdoors(m_caster->GetPhaseShift(), m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ()))
return SPELL_FAILED_ONLY_INDOORS;
}
// only check at first call, Stealth auras are already removed at second call
// for now, ignore triggered spells
if (strict && !(_triggeredCastFlags & TRIGGERED_IGNORE_SHAPESHIFT))
{
bool checkForm = true;
// Ignore form req aura
Unit::AuraEffectList const& ignore = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT);
for (AuraEffect const* aurEff : ignore)
{
if (!aurEff->IsAffectingSpell(m_spellInfo))
continue;
checkForm = false;
break;
}
if (checkForm)
{
// Cannot be used in this stance/form
SpellCastResult shapeError = m_spellInfo->CheckShapeshift(m_caster->GetShapeshiftForm());
if (shapeError != SPELL_CAST_OK)
return shapeError;
if ((m_spellInfo->HasAttribute(SPELL_ATTR0_ONLY_STEALTHED)) && !(m_caster->HasStealthAura()))
return SPELL_FAILED_ONLY_STEALTHED;
}
}
if (m_caster->HasAuraTypeWithMiscvalue(SPELL_AURA_BLOCK_SPELL_FAMILY, m_spellInfo->SpellFamilyName))
return SPELL_FAILED_SPELL_UNAVAILABLE;
bool reqCombat = true;
Unit::AuraEffectList const& stateAuras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE);
for (Unit::AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j)
{
if ((*j)->IsAffectingSpell(m_spellInfo))
{
m_needComboPoints = false;
if ((*j)->GetMiscValue() == 1)
{
reqCombat=false;
break;
}
}
}
// caster state requirements
// not for triggered spells (needed by execute)
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURASTATE))
{
if (m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraStateType(m_spellInfo->CasterAuraState), m_spellInfo, m_caster))
return SPELL_FAILED_CASTER_AURASTATE;
if (m_spellInfo->ExcludeCasterAuraState && m_caster->HasAuraState(AuraStateType(m_spellInfo->ExcludeCasterAuraState), m_spellInfo, m_caster))
return SPELL_FAILED_CASTER_AURASTATE;
// Note: spell 62473 requres casterAuraSpell = triggering spell
if (m_spellInfo->CasterAuraSpell && !m_caster->HasAura(m_spellInfo->CasterAuraSpell))
return SPELL_FAILED_CASTER_AURASTATE;
if (m_spellInfo->ExcludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->ExcludeCasterAuraSpell))
return SPELL_FAILED_CASTER_AURASTATE;
if (reqCombat && m_caster->IsInCombat() && !m_spellInfo->CanBeUsedInCombat())
return SPELL_FAILED_AFFECTING_COMBAT;
}
// cancel autorepeat spells if cast start when moving
// (not wand currently autorepeat cast delayed to moving stop anyway in spell update code)
// Do not cancel spells which are affected by a SPELL_AURA_CAST_WHILE_WALKING effect
if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->isMoving() && (!m_caster->IsCharmed() || !m_caster->GetCharmerGUID().IsCreature()) && !m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_CAST_WHILE_WALKING, m_spellInfo))
{
// skip stuck spell to allow use it in falling case and apply spell limitations at movement
SpellEffectInfo const* effect = m_spellInfo->GetEffect(EFFECT_0);
if ((!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING_FAR) || (effect && effect->Effect != SPELL_EFFECT_STUCK)) &&
(IsAutoRepeat() || m_spellInfo->HasAuraInterruptFlag(AURA_INTERRUPT_FLAG_NOT_SEATED)))
return SPELL_FAILED_MOVING;
}
// Check vehicle flags
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE))
{
SpellCastResult vehicleCheck = m_spellInfo->CheckVehicle(m_caster);
if (vehicleCheck != SPELL_CAST_OK)
return vehicleCheck;
}
// check spell cast conditions from database
{
ConditionSourceInfo condInfo = ConditionSourceInfo(m_caster, m_targets.GetObjectTarget());
if (!sConditionMgr->IsObjectMeetingNotGroupedConditions(CONDITION_SOURCE_TYPE_SPELL, m_spellInfo->Id, condInfo))
{
// mLastFailedCondition can be NULL if there was an error processing the condition in Condition::Meets (i.e. wrong data for ConditionTarget or others)
if (condInfo.mLastFailedCondition && condInfo.mLastFailedCondition->ErrorType)
{
if (condInfo.mLastFailedCondition->ErrorType == SPELL_FAILED_CUSTOM_ERROR)
m_customError = SpellCustomErrors(condInfo.mLastFailedCondition->ErrorTextId);
return SpellCastResult(condInfo.mLastFailedCondition->ErrorType);
}
if (!condInfo.mLastFailedCondition || !condInfo.mLastFailedCondition->ConditionTarget)
return SPELL_FAILED_CASTER_AURASTATE;
return SPELL_FAILED_BAD_TARGETS;
}
}
// Don't check explicit target for passive spells (workaround) (check should be skipped only for learn case)
// those spells may have incorrect target entries or not filled at all (for example 15332)
// such spells when learned are not targeting anyone using targeting system, they should apply directly to caster instead
// also, such casts shouldn't be sent to client
if (!(m_spellInfo->IsPassive() && (!m_targets.GetUnitTarget() || m_targets.GetUnitTarget() == m_caster)))
{
// Check explicit target for m_originalCaster - todo: get rid of such workarounds
Unit* caster = m_caster;
if (m_originalCaster && m_caster->GetEntry() != WORLD_TRIGGER) // Do a simplified check for gameobject casts
caster = m_originalCaster;
SpellCastResult castResult = m_spellInfo->CheckExplicitTarget(caster, m_targets.GetObjectTarget(), m_targets.GetItemTarget());
if (castResult != SPELL_CAST_OK)
return castResult;
}
if (Unit* target = m_targets.GetUnitTarget())
{
SpellCastResult castResult = m_spellInfo->CheckTarget(m_caster, target, m_caster->GetEntry() == WORLD_TRIGGER); // skip stealth checks for GO casts
if (castResult != SPELL_CAST_OK)
return castResult;
// If it's not a melee spell, check if vision is obscured by SPELL_AURA_INTERFERE_TARGETTING
if (m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE)
{
for (auto const& itr : m_caster->GetAuraEffectsByType(SPELL_AURA_INTERFERE_TARGETTING))
if (!m_caster->IsFriendlyTo(itr->GetCaster()) && !target->HasAura(itr->GetId(), itr->GetCasterGUID()))
return SPELL_FAILED_VISION_OBSCURED;
for (auto const& itr : target->GetAuraEffectsByType(SPELL_AURA_INTERFERE_TARGETTING))
if (!m_caster->IsFriendlyTo(itr->GetCaster()) && (!target->HasAura(itr->GetId(), itr->GetCasterGUID()) || !m_caster->HasAura(itr->GetId(), itr->GetCasterGUID())))
return SPELL_FAILED_VISION_OBSCURED;
}
if (target != m_caster)
{
// Must be behind the target
if ((m_spellInfo->HasAttribute(SPELL_ATTR0_CU_REQ_CASTER_BEHIND_TARGET)) && target->HasInArc(static_cast<float>(M_PI), m_caster))
return SPELL_FAILED_NOT_BEHIND;
// Target must be facing you
if ((m_spellInfo->HasAttribute(SPELL_ATTR0_CU_REQ_TARGET_FACING_CASTER)) && !target->HasInArc(static_cast<float>(M_PI), m_caster))
return SPELL_FAILED_NOT_INFRONT;
if (m_caster->GetEntry() != WORLD_TRIGGER) // Ignore LOS for gameobjects casts (wrongly cast by a trigger)
{
WorldObject* losTarget = m_caster;
if (IsTriggered() && m_triggeredByAuraSpell)
if (DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell->Id))
losTarget = dynObj;
if (!m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS) && !target->IsWithinLOSInMap(losTarget, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2))
return SPELL_FAILED_LINE_OF_SIGHT;
}
}
}
// Check for line of sight for spells with dest
if (m_targets.HasDst())
{
float x, y, z;
m_targets.GetDstPos()->GetPosition(x, y, z);
if (!m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS) && !m_caster->IsWithinLOS(x, y, z, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2))
return SPELL_FAILED_LINE_OF_SIGHT;
}
// check pet presence
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
if (effect && effect->TargetA.GetTarget() == TARGET_UNIT_PET)
{
if (!m_caster->GetGuardianPet())
{
if (m_triggeredByAuraSpell) // not report pet not existence for triggered spells
return SPELL_FAILED_DONT_REPORT;
else
return SPELL_FAILED_NO_PET;
}
break;
}
}
// Spell cast only in battleground
if ((m_spellInfo->HasAttribute(SPELL_ATTR3_BATTLEGROUND)) && m_caster->GetTypeId() == TYPEID_PLAYER)
if (!m_caster->ToPlayer()->InBattleground())
return SPELL_FAILED_ONLY_BATTLEGROUNDS;
// do not allow spells to be cast in arenas or rated battlegrounds
if (Player* player = m_caster->ToPlayer())
if (player->InArena()/* || player->InRatedBattleGround() NYI*/)
{
SpellCastResult castResult = CheckArenaAndRatedBattlegroundCastRules();
if (castResult != SPELL_CAST_OK)
return castResult;
}
// zone check
if (m_caster->GetTypeId() == TYPEID_UNIT || !m_caster->ToPlayer()->IsGameMaster())
{
uint32 zone, area;
m_caster->GetZoneAndAreaId(zone, area);
SpellCastResult locRes = m_spellInfo->CheckLocation(m_caster->GetMapId(), zone, area, m_caster->ToPlayer());
if (locRes != SPELL_CAST_OK)
return locRes;
}
// not let players cast spells at mount (and let do it to creatures)
if (m_caster->IsMounted() && m_caster->GetTypeId() == TYPEID_PLAYER && !(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE) &&
!m_spellInfo->IsPassive() && !m_spellInfo->HasAttribute(SPELL_ATTR0_CASTABLE_WHILE_MOUNTED))
{
if (m_caster->IsInFlight())
return SPELL_FAILED_NOT_ON_TAXI;
else
return SPELL_FAILED_NOT_MOUNTED;
}
// check spell focus object
if (m_spellInfo->RequiresSpellFocus)
{
focusObject = SearchSpellFocus();
if (!focusObject)
return SPELL_FAILED_REQUIRES_SPELL_FOCUS;
}
SpellCastResult castResult = SPELL_CAST_OK;
// always (except passive spells) check items (only player related checks)
if (!m_spellInfo->IsPassive())
{
castResult = CheckItems(param1, param2);
if (castResult != SPELL_CAST_OK)
return castResult;
}
// Triggered spells also have range check
/// @todo determine if there is some flag to enable/disable the check
castResult = CheckRange(strict);
if (castResult != SPELL_CAST_OK)
return castResult;
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST))
{
castResult = CheckPower();
if (castResult != SPELL_CAST_OK)
return castResult;
}
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURAS))
{
castResult = CheckCasterAuras(param1);
if (castResult != SPELL_CAST_OK)
return castResult;
}
// script hook
castResult = CallScriptCheckCastHandlers();
if (castResult != SPELL_CAST_OK)
return castResult;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
if (!effect)
continue;
// for effects of spells that have only one target
switch (effect->Effect)
{
case SPELL_EFFECT_DUMMY:
{
if (m_spellInfo->Id == 19938) // Awaken Peon
{
Unit* unit = m_targets.GetUnitTarget();
if (!unit || !unit->HasAura(17743))
return SPELL_FAILED_BAD_TARGETS;
}
else if (m_spellInfo->Id == 31789) // Righteous Defense
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_DONT_REPORT;
Unit* target = m_targets.GetUnitTarget();
if (!target || !target->IsFriendlyTo(m_caster) || target->getAttackers().empty())
return SPELL_FAILED_BAD_TARGETS;
}
break;
}
case SPELL_EFFECT_LEARN_SPELL:
{
if (effect->TargetA.GetTarget() != TARGET_UNIT_PET)
break;
Pet* pet = m_caster->ToPlayer()->GetPet();
if (!pet)
return SPELL_FAILED_NO_PET;
SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(effect->TriggerSpell, DIFFICULTY_NONE);
if (!learn_spellproto)
return SPELL_FAILED_NOT_KNOWN;
if (m_spellInfo->SpellLevel > pet->getLevel())
return SPELL_FAILED_LOWLEVEL;
break;
}
case SPELL_EFFECT_UNLOCK_GUILD_VAULT_TAB:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
if (Guild* guild = m_caster->ToPlayer()->GetGuild())
if (guild->GetLeaderGUID() != m_caster->ToPlayer()->GetGUID())
return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW;
break;
}
case SPELL_EFFECT_LEARN_PET_SPELL:
{
// check target only for unit target case
if (Unit* unit = m_targets.GetUnitTarget())
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
Pet* pet = unit->ToPet();
if (!pet || pet->GetOwner() != m_caster)
return SPELL_FAILED_BAD_TARGETS;
SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(effect->TriggerSpell, DIFFICULTY_NONE);
if (!learn_spellproto)
return SPELL_FAILED_NOT_KNOWN;
if (m_spellInfo->SpellLevel > pet->getLevel())
return SPELL_FAILED_LOWLEVEL;
}
break;
}
case SPELL_EFFECT_APPLY_GLYPH:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_GLYPH_NO_SPEC;
Player* caster = m_caster->ToPlayer();
if (!caster->HasSpell(m_misc.SpellId))
return SPELL_FAILED_NOT_KNOWN;
if (uint32 glyphId = effect->MiscValue)
{
GlyphPropertiesEntry const* glyphProperties = sGlyphPropertiesStore.LookupEntry(glyphId);
if (!glyphProperties)
return SPELL_FAILED_INVALID_GLYPH;
std::vector<uint32> const* glyphBindableSpells = sDB2Manager.GetGlyphBindableSpells(glyphId);
if (!glyphBindableSpells)
return SPELL_FAILED_INVALID_GLYPH;
if (std::find(glyphBindableSpells->begin(), glyphBindableSpells->end(), m_misc.SpellId) == glyphBindableSpells->end())
return SPELL_FAILED_INVALID_GLYPH;
if (std::vector<uint32> const* glyphRequiredSpecs = sDB2Manager.GetGlyphRequiredSpecs(glyphId))
{
if (!caster->GetPrimarySpecialization())
return SPELL_FAILED_GLYPH_NO_SPEC;
if (std::find(glyphRequiredSpecs->begin(), glyphRequiredSpecs->end(), caster->GetPrimarySpecialization()) == glyphRequiredSpecs->end())
return SPELL_FAILED_GLYPH_INVALID_SPEC;
}
uint32 replacedGlyph = 0;
for (uint32 activeGlyphId : caster->GetGlyphs(caster->GetActiveTalentGroup()))
{
if (std::vector<uint32> const* activeGlyphBindableSpells = sDB2Manager.GetGlyphBindableSpells(activeGlyphId))
{
if (std::find(activeGlyphBindableSpells->begin(), activeGlyphBindableSpells->end(), m_misc.SpellId) != activeGlyphBindableSpells->end())
{
replacedGlyph = activeGlyphId;
break;
}
}
}
for (uint32 activeGlyphId : caster->GetGlyphs(caster->GetActiveTalentGroup()))
{
if (activeGlyphId == replacedGlyph)
continue;
if (activeGlyphId == glyphId)
return SPELL_FAILED_UNIQUE_GLYPH;
if (sGlyphPropertiesStore.AssertEntry(activeGlyphId)->GlyphExclusiveCategoryID == glyphProperties->GlyphExclusiveCategoryID)
return SPELL_FAILED_GLYPH_EXCLUSIVE_CATEGORY;
}
}
break;
}
case SPELL_EFFECT_FEED_PET:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
Item* foodItem = m_targets.GetItemTarget();
if (!foodItem)
return SPELL_FAILED_BAD_TARGETS;
Pet* pet = m_caster->ToPlayer()->GetPet();
if (!pet)
return SPELL_FAILED_NO_PET;
if (!pet->HaveInDiet(foodItem->GetTemplate()))
return SPELL_FAILED_WRONG_PET_FOOD;
if (!pet->GetCurrentFoodBenefitLevel(foodItem->GetTemplate()->GetBaseItemLevel()))
return SPELL_FAILED_FOOD_LOWLEVEL;
if (m_caster->IsInCombat() || pet->IsInCombat())
return SPELL_FAILED_AFFECTING_COMBAT;
break;
}
case SPELL_EFFECT_POWER_BURN:
case SPELL_EFFECT_POWER_DRAIN:
{
// Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects)
if (m_caster->IsPlayer())
if (effect->TargetA.GetTarget() != TARGET_UNIT_CASTER)
if (Unit* target = m_targets.GetUnitTarget())
if (target != m_caster && target->GetPowerType() != Powers(effect->MiscValue))
return SPELL_FAILED_BAD_TARGETS;
break;
}
case SPELL_EFFECT_CHARGE:
{
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURAS) && m_caster->HasUnitState(UNIT_STATE_ROOT))
return SPELL_FAILED_ROOTED;
if (GetSpellInfo()->NeedsExplicitUnitTarget())
{
Unit* target = m_targets.GetUnitTarget();
if (!target)
return SPELL_FAILED_DONT_REPORT;
// first we must check to see if the target is in LoS. A path can usually be built but LoS matters for charge spells
if (!target->IsWithinLOSInMap(m_caster)) //Do full LoS/Path check. Don't exclude m2
return SPELL_FAILED_LINE_OF_SIGHT;
float objSize = target->GetCombatReach();
float range = m_spellInfo->GetMaxRange(true, m_caster, this) * 1.5f + objSize; // can't be overly strict
m_preGeneratedPath = std::make_unique<PathGenerator>(m_caster);
m_preGeneratedPath->SetPathLengthLimit(range);
// first try with raycast, if it fails fall back to normal path
float targetObjectSize = std::min(target->GetCombatReach(), 4.0f);
bool result = m_preGeneratedPath->CalculatePath(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + targetObjectSize, false, true);
if (m_preGeneratedPath->GetPathType() & PATHFIND_SHORT)
return SPELL_FAILED_OUT_OF_RANGE;
else if (!result || m_preGeneratedPath->GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE))
{
result = m_preGeneratedPath->CalculatePath(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + targetObjectSize, false, false);
if (m_preGeneratedPath->GetPathType() & PATHFIND_SHORT)
return SPELL_FAILED_OUT_OF_RANGE;
else if (!result || m_preGeneratedPath->GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE))
return SPELL_FAILED_NOPATH;
else if (m_preGeneratedPath->IsInvalidDestinationZ(target)) // Check position z, if not in a straight line
return SPELL_FAILED_NOPATH;
}
else if (m_preGeneratedPath->IsInvalidDestinationZ(target)) // Check position z, if in a straight line
return SPELL_FAILED_NOPATH;
m_preGeneratedPath->ReducePathLenghtByDist(objSize); // move back
}
break;
}
case SPELL_EFFECT_SKINNING:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.GetUnitTarget() || m_targets.GetUnitTarget()->GetTypeId() != TYPEID_UNIT)
return SPELL_FAILED_BAD_TARGETS;
if (!m_targets.GetUnitTarget()->HasUnitFlag(UNIT_FLAG_SKINNABLE))
return SPELL_FAILED_TARGET_UNSKINNABLE;
Creature* creature = m_targets.GetUnitTarget()->ToCreature();
if (!creature->IsCritter() && !creature->loot.isLooted())
return SPELL_FAILED_TARGET_NOT_LOOTED;
uint32 skill = creature->GetCreatureTemplate()->GetRequiredLootSkill();
int32 skillValue = m_caster->ToPlayer()->GetSkillValue(skill);
int32 TargetLevel = creature->GetCreatureTemplate()->minlevel;
int32 ReqValue = (skillValue < 100 ? (TargetLevel-10) * 10 : TargetLevel * 5);
if (ReqValue > skillValue)
return SPELL_FAILED_LOW_CASTLEVEL;
// chance for fail at orange skinning attempt
if ((m_selfContainer && (*m_selfContainer) == this) &&
skillValue < sWorld->GetConfigMaxSkillValue() &&
(ReqValue < 0 ? 0 : ReqValue) > irand(skillValue - 25, skillValue + 37))
return SPELL_FAILED_TRY_AGAIN;
break;
}
case SPELL_EFFECT_OPEN_LOCK:
{
if (effect->TargetA.GetTarget() != TARGET_GAMEOBJECT_TARGET &&
effect->TargetA.GetTarget() != TARGET_GAMEOBJECT_ITEM_TARGET)
break;
if (m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc.
// we need a go target in case of TARGET_GAMEOBJECT_TARGET
|| (effect->TargetA.GetTarget() == TARGET_GAMEOBJECT_TARGET && !m_targets.GetGOTarget()))
return SPELL_FAILED_BAD_TARGETS;
Item* pTempItem = NULL;
if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM)
{
if (TradeData* pTrade = m_caster->ToPlayer()->GetTradeData())
pTempItem = pTrade->GetTraderData()->GetItem(TRADE_SLOT_NONTRADED);
}
else if (m_targets.GetTargetMask() & TARGET_FLAG_ITEM)
pTempItem = m_caster->ToPlayer()->GetItemByGuid(m_targets.GetItemTargetGUID());
// we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM_TARGET
if (effect->TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET &&
!m_targets.GetGOTarget() &&
(!pTempItem || !pTempItem->GetTemplate()->GetLockID() || !pTempItem->IsLocked()))
return SPELL_FAILED_BAD_TARGETS;
if (m_spellInfo->Id != 1842 || (m_targets.GetGOTarget() &&
m_targets.GetGOTarget()->GetGOInfo()->type != GAMEOBJECT_TYPE_TRAP))
if (m_caster->ToPlayer()->InBattleground() && // In Battleground players can use only flags and banners
!m_caster->ToPlayer()->CanUseBattlegroundObject(m_targets.GetGOTarget()))
return SPELL_FAILED_TRY_AGAIN;
// get the lock entry
uint32 lockId = 0;
if (GameObject* go = m_targets.GetGOTarget())
{
lockId = go->GetGOInfo()->GetLockId();
if (!lockId)
return SPELL_FAILED_BAD_TARGETS;
}
else if (Item* itm = m_targets.GetItemTarget())
lockId = itm->GetTemplate()->GetLockID();
SkillType skillId = SKILL_NONE;
int32 reqSkillValue = 0;
int32 skillValue = 0;
// check lock compatibility
SpellCastResult res = CanOpenLock(effect->EffectIndex, lockId, skillId, reqSkillValue, skillValue);
if (res != SPELL_CAST_OK)
return res;
break;
}
case SPELL_EFFECT_RESURRECT_PET:
{
Creature* pet = m_caster->GetGuardianPet();
if (pet && pet->IsAlive())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
break;
}
// This is generic summon effect
case SPELL_EFFECT_SUMMON:
{
SummonPropertiesEntry const* SummonProperties = sSummonPropertiesStore.LookupEntry(effect->MiscValueB);
if (!SummonProperties)
break;
switch (SummonProperties->Control)
{
case SUMMON_CATEGORY_PET:
if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET) && !m_caster->GetPetGUID().IsEmpty())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
/* fallthrough */
// intentional, check both GetPetGUID() and GetCharmGUID for SUMMON_CATEGORY_PET
case SUMMON_CATEGORY_PUPPET:
if (!m_caster->GetCharmGUID().IsEmpty())
return SPELL_FAILED_ALREADY_HAVE_CHARM;
break;
}
break;
}
case SPELL_EFFECT_CREATE_TAMED_PET:
{
if (m_targets.GetUnitTarget())
{
if (m_targets.GetUnitTarget()->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET) && !m_targets.GetUnitTarget()->GetPetGUID().IsEmpty())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
}
break;
}
case SPELL_EFFECT_SUMMON_PET:
{
if (!m_caster->GetPetGUID().IsEmpty()) //let warlock do a replacement summon
{
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player)
if (Pet* pet = m_caster->ToPlayer()->GetPet())
pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID());
}
else if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET))
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
}
if (!m_caster->GetCharmGUID().IsEmpty())
return SPELL_FAILED_ALREADY_HAVE_CHARM;
break;
}
case SPELL_EFFECT_SUMMON_PLAYER:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
if (!m_caster->GetTarget())
return SPELL_FAILED_BAD_TARGETS;
Player* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetTarget());
if (!target || m_caster->ToPlayer() == target || (!target->IsInSameRaidWith(m_caster->ToPlayer()) && m_spellInfo->Id != 48955)) // refer-a-friend spell
return SPELL_FAILED_BAD_TARGETS;
if (target->HasSummonPending())
return SPELL_FAILED_SUMMON_PENDING;
// check if our map is dungeon
MapEntry const* map = sMapStore.LookupEntry(m_caster->GetMapId());
if (map->IsDungeon())
{
uint32 mapId = m_caster->GetMap()->GetId();
Difficulty difficulty = m_caster->GetMap()->GetDifficultyID();
if (map->IsRaid())
if (InstancePlayerBind* targetBind = target->GetBoundInstance(mapId, difficulty))
if (InstancePlayerBind* casterBind = m_caster->ToPlayer()->GetBoundInstance(mapId, difficulty))
if (targetBind->perm && targetBind->save != casterBind->save)
return SPELL_FAILED_TARGET_LOCKED_TO_RAID_INSTANCE;
InstanceTemplate const* instance = sObjectMgr->GetInstanceTemplate(mapId);
if (!instance)
return SPELL_FAILED_TARGET_NOT_IN_INSTANCE;
if (!target->Satisfy(sObjectMgr->GetAccessRequirement(mapId, difficulty), mapId))
return SPELL_FAILED_BAD_TARGETS;
}
break;
}
// RETURN HERE
case SPELL_EFFECT_SUMMON_RAF_FRIEND:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
Player* playerCaster = m_caster->ToPlayer();
//
if (!(playerCaster->GetTarget()))
return SPELL_FAILED_BAD_TARGETS;
Player* target = playerCaster->GetSelectedPlayer();
if (!target ||
!(target->GetSession()->GetRecruiterId() == playerCaster->GetSession()->GetAccountId() || target->GetSession()->GetAccountId() == playerCaster->GetSession()->GetRecruiterId()))
return SPELL_FAILED_BAD_TARGETS;
break;
}
case SPELL_EFFECT_LEAP:
case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER:
{
//Do not allow to cast it before BG starts.
if (m_caster->GetTypeId() == TYPEID_PLAYER)
if (Battleground const* bg = m_caster->ToPlayer()->GetBattleground())
if (bg->GetStatus() != STATUS_IN_PROGRESS)
return SPELL_FAILED_TRY_AGAIN;
break;
}
case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF:
{
if (!m_targets.GetUnitTarget() || m_targets.GetUnitTarget() == m_caster)
return SPELL_FAILED_BAD_TARGETS;
break;
}
case SPELL_EFFECT_LEAP_BACK:
{
if (m_caster->HasUnitState(UNIT_STATE_ROOT))
{
if (m_caster->GetTypeId() == TYPEID_PLAYER)
return SPELL_FAILED_ROOTED;
else
return SPELL_FAILED_DONT_REPORT;
}
break;
}
case SPELL_EFFECT_JUMP:
case SPELL_EFFECT_JUMP_DEST:
{
if (m_caster->HasUnitState(UNIT_STATE_ROOT))
return SPELL_FAILED_ROOTED;
break;
}
case SPELL_EFFECT_TALENT_SPEC_SELECT:
{
ChrSpecializationEntry const* spec = sChrSpecializationStore.LookupEntry(m_misc.SpecializationId);
Player* player = m_caster->ToPlayer();
if (!player)
return SPELL_FAILED_TARGET_NOT_PLAYER;
if (!spec || (spec->ClassID != m_caster->getClass() && !spec->IsPetSpecialization()))
return SPELL_FAILED_NO_SPEC;
if (spec->IsPetSpecialization())
{
Pet* pet = player->GetPet();
if (!pet || !pet->IsHunterPet() || !pet->GetCharmInfo())
return SPELL_FAILED_NO_PET;
}
// can't change during already started arena/battleground
if (Battleground const* bg = player->GetBattleground())
if (bg->GetStatus() == STATUS_IN_PROGRESS)
return SPELL_FAILED_NOT_IN_BATTLEGROUND;
break;
}
case SPELL_EFFECT_REMOVE_TALENT:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
TalentEntry const* talent = sTalentStore.LookupEntry(m_misc.TalentId);
if (!talent)
return SPELL_FAILED_DONT_REPORT;
if (m_caster->GetSpellHistory()->HasCooldown(talent->SpellID))
{
if (param1)
*param1 = talent->SpellID;
return SPELL_FAILED_CANT_UNTALENT;
}
break;
}
case SPELL_EFFECT_GIVE_ARTIFACT_POWER:
case SPELL_EFFECT_GIVE_ARTIFACT_POWER_NO_BONUS:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_BAD_TARGETS;
Aura* artifactAura = m_caster->GetAura(ARTIFACTS_ALL_WEAPONS_GENERAL_WEAPON_EQUIPPED_PASSIVE);
if (!artifactAura)
return SPELL_FAILED_NO_ARTIFACT_EQUIPPED;
Item* artifact = m_caster->ToPlayer()->GetItemByGuid(artifactAura->GetCastItemGUID());
if (!artifact)
return SPELL_FAILED_NO_ARTIFACT_EQUIPPED;
if (effect->Effect == SPELL_EFFECT_GIVE_ARTIFACT_POWER)
{
ArtifactEntry const* artifactEntry = sArtifactStore.LookupEntry(artifact->GetTemplate()->GetArtifactID());
if (!artifactEntry || artifactEntry->ArtifactCategoryID != effect->MiscValue)
return SPELL_FAILED_WRONG_ARTIFACT_EQUIPPED;
}
break;
}
default:
break;
}
}
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
if (!effect)
continue;
switch (effect->ApplyAuraName)
{
case SPELL_AURA_MOD_POSSESS_PET:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_NO_PET;
Pet* pet = m_caster->ToPlayer()->GetPet();
if (!pet)
return SPELL_FAILED_NO_PET;
if (!pet->GetCharmerGUID().IsEmpty())
return SPELL_FAILED_CHARMED;
break;
}
case SPELL_AURA_MOD_POSSESS:
case SPELL_AURA_MOD_CHARM:
case SPELL_AURA_AOE_CHARM:
{
if (!m_caster->GetCharmerGUID().IsEmpty())
return SPELL_FAILED_CHARMED;
if (effect->ApplyAuraName == SPELL_AURA_MOD_CHARM
|| effect->ApplyAuraName == SPELL_AURA_MOD_POSSESS)
{
if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET) && !m_caster->GetPetGUID().IsEmpty())
return SPELL_FAILED_ALREADY_HAVE_SUMMON;
if (!m_caster->GetCharmGUID().IsEmpty())
return SPELL_FAILED_ALREADY_HAVE_CHARM;
}
if (Unit* target = m_targets.GetUnitTarget())
{
if (target->GetTypeId() == TYPEID_UNIT && target->IsVehicle())
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
if (target->IsMounted())
return SPELL_FAILED_CANT_BE_CHARMED;
if (!target->GetCharmerGUID().IsEmpty())
return SPELL_FAILED_CHARMED;
if (target->GetOwner() && target->GetOwner()->GetTypeId() == TYPEID_PLAYER)
return SPELL_FAILED_TARGET_IS_PLAYER_CONTROLLED;
int32 value = CalculateDamage(effect->EffectIndex, target);
if (value && int32(target->GetLevelForTarget(m_caster)) > value)
return SPELL_FAILED_HIGHLEVEL;
}
break;
}
case SPELL_AURA_MOUNTED:
{
if (m_caster->IsInWater() && m_spellInfo->HasAura(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED))
return SPELL_FAILED_ONLY_ABOVEWATER;
// Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells
bool allowMount = !m_caster->GetMap()->IsDungeon() || m_caster->GetMap()->IsBattlegroundOrArena();
InstanceTemplate const* it = sObjectMgr->GetInstanceTemplate(m_caster->GetMapId());
if (it)
allowMount = it->AllowMount;
if (m_caster->GetTypeId() == TYPEID_PLAYER && !allowMount && !m_spellInfo->RequiredAreasID)
return SPELL_FAILED_NO_MOUNTS_ALLOWED;
if (m_caster->IsInDisallowedMountForm())
{
SendMountResult(MountResult::Shapeshifted); // mount result gets sent before the cast result
return SPELL_FAILED_DONT_REPORT;
}
break;
}
case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS:
{
if (!m_targets.GetUnitTarget())
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
// can be cast at non-friendly unit or own pet/charm
if (m_caster->IsFriendlyTo(m_targets.GetUnitTarget()))
return SPELL_FAILED_TARGET_FRIENDLY;
break;
}
case SPELL_AURA_FLY:
case SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED:
{
// not allow cast fly spells if not have req. skills (all spells is self target)
// allow always ghost flight spells
if (m_originalCaster && m_originalCaster->GetTypeId() == TYPEID_PLAYER && m_originalCaster->IsAlive())
{
Battlefield* Bf = sBattlefieldMgr->GetBattlefieldToZoneId(m_originalCaster->GetZoneId());
if (AreaTableEntry const* area = sAreaTableStore.LookupEntry(m_originalCaster->GetAreaId()))
if (area->Flags[0] & AREA_FLAG_NO_FLY_ZONE || (Bf && !Bf->CanFlyIn()))
return SPELL_FAILED_NOT_HERE;
}
break;
}
case SPELL_AURA_PERIODIC_MANA_LEECH:
{
if (effect->IsTargetingArea())
break;
if (!m_targets.GetUnitTarget())
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
if (m_caster->GetTypeId() != TYPEID_PLAYER || m_CastItem)
break;
if (m_targets.GetUnitTarget()->GetPowerType() != POWER_MANA)
return SPELL_FAILED_BAD_TARGETS;
break;
}
default:
break;
}
}
// check trade slot case (last, for allow catch any another cast problems)
if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM)
{
if (m_CastItem)
return SPELL_FAILED_ITEM_ENCHANT_TRADE_WINDOW;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_NOT_TRADING;
TradeData* my_trade = m_caster->ToPlayer()->GetTradeData();
if (!my_trade)
return SPELL_FAILED_NOT_TRADING;
if (m_targets.GetItemTargetGUID() != ObjectGuid::TradeItem)
return SPELL_FAILED_BAD_TARGETS;
if (!IsTriggered())
if (my_trade->GetSpell())
return SPELL_FAILED_ITEM_ALREADY_ENCHANTED;
}
// check if caster has at least 1 combo point for spells that require combo points
if (m_needComboPoints)
if (Player* plrCaster = m_caster->ToPlayer())
if (!plrCaster->GetComboPoints())
return SPELL_FAILED_NO_COMBO_POINTS;
// all ok
return SPELL_CAST_OK;
}
SpellCastResult Spell::CheckPetCast(Unit* target)
{
if (m_caster->HasUnitState(UNIT_STATE_CASTING) && !(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_IN_PROGRESS)) //prevent spellcast interruption by another spellcast
return SPELL_FAILED_SPELL_IN_PROGRESS;
// dead owner (pets still alive when owners ressed?)
if (Unit* owner = m_caster->GetCharmerOrOwner())
if (!owner->IsAlive())
return SPELL_FAILED_CASTER_DEAD;
if (!target && m_targets.GetUnitTarget())
target = m_targets.GetUnitTarget();
if (m_spellInfo->NeedsExplicitUnitTarget())
{
if (!target)
return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
m_targets.SetUnitTarget(target);
}
// check cooldown
if (Creature* creatureCaster = m_caster->ToCreature())
if (!creatureCaster->GetSpellHistory()->IsReady(m_spellInfo))
return SPELL_FAILED_NOT_READY;
// Check if spell is affected by GCD
if (m_spellInfo->StartRecoveryCategory > 0)
if (m_caster->GetCharmInfo() && m_caster->GetSpellHistory()->HasGlobalCooldown(m_spellInfo))
return SPELL_FAILED_NOT_READY;
return CheckCast(true);
}
SpellCastResult Spell::CheckCasterAuras(uint32* param1) const
{
// spells totally immuned to caster auras (wsg flag drop, give marks etc)
if (m_spellInfo->HasAttribute(SPELL_ATTR6_IGNORE_CASTER_AURAS))
return SPELL_CAST_OK;
// these attributes only show the spell as usable on the client when it has related aura applied
// still they need to be checked against certain mechanics
// SPELL_ATTR5_USABLE_WHILE_STUNNED by default only MECHANIC_STUN (ie no sleep, knockout, freeze, etc.)
bool usableWhileStunned = m_spellInfo->HasAttribute(SPELL_ATTR5_USABLE_WHILE_STUNNED);
// SPELL_ATTR5_USABLE_WHILE_FEARED by default only fear (ie no horror)
bool usableWhileFeared = m_spellInfo->HasAttribute(SPELL_ATTR5_USABLE_WHILE_FEARED);
// SPELL_ATTR5_USABLE_WHILE_CONFUSED by default only disorient (ie no polymorph)
bool usableWhileConfused = m_spellInfo->HasAttribute(SPELL_ATTR5_USABLE_WHILE_CONFUSED);
// Check whether the cast should be prevented by any state you might have.
SpellCastResult result = SPELL_CAST_OK;
// Get unit state
uint32 const unitflag = m_caster->m_unitData->Flags;
// this check should only be done when player does cast directly
// (ie not when it's called from a script) Breaks for example PlayerAI when charmed
/*
if (!m_caster->GetCharmerGUID().IsEmpty())
{
if (Unit* charmer = m_caster->GetCharmer())
if (charmer->GetUnitBeingMoved() != m_caster && !CheckSpellCancelsCharm(param1))
result = SPELL_FAILED_CHARMED;
}
*/
// spell has attribute usable while having a cc state, check if caster has allowed mechanic auras, another mechanic types must prevent cast spell
auto mechanicCheck = [&](AuraType type) -> SpellCastResult
{
bool foundNotMechanic = false;
Unit::AuraEffectList const& auras = m_caster->GetAuraEffectsByType(type);
for (AuraEffect const* aurEff : auras)
{
uint32 const mechanicMask = aurEff->GetSpellInfo()->GetAllEffectsMechanicMask();
if (mechanicMask && !(mechanicMask & GetSpellInfo()->GetAllowedMechanicMask()))
{
foundNotMechanic = true;
// fill up aura mechanic info to send client proper error message
if (param1)
{
*param1 = aurEff->GetSpellInfo()->GetEffect(aurEff->GetEffIndex())->Mechanic;
if (!*param1)
*param1 = aurEff->GetSpellInfo()->Mechanic;
}
break;
}
}
if (foundNotMechanic)
{
switch (type)
{
case SPELL_AURA_MOD_STUN:
return SPELL_FAILED_STUNNED;
case SPELL_AURA_MOD_FEAR:
return SPELL_FAILED_FLEEING;
case SPELL_AURA_MOD_CONFUSE:
return SPELL_FAILED_CONFUSED;
default:
ABORT();
return SPELL_FAILED_NOT_KNOWN;
}
}
return SPELL_CAST_OK;
};
if (unitflag & UNIT_FLAG_STUNNED)
{
if (usableWhileStunned)
{
SpellCastResult mechanicResult = mechanicCheck(SPELL_AURA_MOD_STUN);
if (mechanicResult != SPELL_CAST_OK)
result = mechanicResult;
}
else if (!CheckSpellCancelsStun(param1))
result = SPELL_FAILED_STUNNED;
}
else if (unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType & SPELL_PREVENTION_TYPE_SILENCE && !CheckSpellCancelsSilence(param1))
result = SPELL_FAILED_SILENCED;
else if (unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType & SPELL_PREVENTION_TYPE_PACIFY && !CheckSpellCancelsPacify(param1))
result = SPELL_FAILED_PACIFIED;
else if (unitflag & UNIT_FLAG_FLEEING)
{
if (usableWhileFeared)
{
SpellCastResult mechanicResult = mechanicCheck(SPELL_AURA_MOD_FEAR);
if (mechanicResult != SPELL_CAST_OK)
result = mechanicResult;
}
else if (!CheckSpellCancelsFear(param1))
result = SPELL_FAILED_FLEEING;
}
else if (unitflag & UNIT_FLAG_CONFUSED)
{
if (usableWhileConfused)
{
SpellCastResult mechanicResult = mechanicCheck(SPELL_AURA_MOD_CONFUSE);
if (mechanicResult != SPELL_CAST_OK)
result = mechanicResult;
}
else if (!CheckSpellCancelsConfuse(param1))
result = SPELL_FAILED_CONFUSED;
}
else if (m_caster->HasUnitFlag2(UNIT_FLAG2_NO_ACTIONS) && m_spellInfo->PreventionType & SPELL_PREVENTION_TYPE_NO_ACTIONS && !CheckSpellCancelsNoActions(param1))
result = SPELL_FAILED_NO_ACTIONS;
// Attr must make flag drop spell totally immune from all effects
if (result != SPELL_CAST_OK)
return (param1 && *param1) ? SPELL_FAILED_PREVENTED_BY_MECHANIC : result;
return SPELL_CAST_OK;
}
bool Spell::CheckSpellCancelsAuraEffect(AuraType auraType, uint32* param1) const
{
// Checking auras is needed now, because you are prevented by some state but the spell grants immunity.
Unit::AuraEffectList const& auraEffects = m_caster->GetAuraEffectsByType(auraType);
if (auraEffects.empty())
return true;
for (AuraEffect const* aurEff : auraEffects)
{
if (m_spellInfo->SpellCancelsAuraEffect(aurEff))
continue;
if (param1)
{
*param1 = aurEff->GetSpellEffectInfo()->Mechanic;
if (!*param1)
*param1 = aurEff->GetSpellInfo()->Mechanic;
}
return false;
}
return true;
}
bool Spell::CheckSpellCancelsCharm(uint32* param1) const
{
return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_CHARM, param1) &&
CheckSpellCancelsAuraEffect(SPELL_AURA_AOE_CHARM, param1) &&
CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_POSSESS, param1);
}
bool Spell::CheckSpellCancelsStun(uint32* param1) const
{
return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_STUN, param1) &&
CheckSpellCancelsAuraEffect(SPELL_AURA_STRANGULATE, param1);
}
bool Spell::CheckSpellCancelsSilence(uint32* param1) const
{
return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_SILENCE, param1) &&
CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_PACIFY_SILENCE, param1);
}
bool Spell::CheckSpellCancelsPacify(uint32* param1) const
{
return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_PACIFY, param1) &&
CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_PACIFY_SILENCE, param1);
}
bool Spell::CheckSpellCancelsFear(uint32* param1) const
{
return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_FEAR, param1) &&
CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_FEAR_2, param1);
}
bool Spell::CheckSpellCancelsConfuse(uint32* param1) const
{
return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_CONFUSE, param1);
}
bool Spell::CheckSpellCancelsNoActions(uint32* param1) const
{
return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_NO_ACTIONS, param1);
}
SpellCastResult Spell::CheckArenaAndRatedBattlegroundCastRules()
{
bool isRatedBattleground = false; // NYI
bool isArena = !isRatedBattleground;
// check USABLE attributes
// USABLE takes precedence over NOT_USABLE
if (isRatedBattleground && m_spellInfo->HasAttribute(SPELL_ATTR9_USABLE_IN_RATED_BATTLEGROUNDS))
return SPELL_CAST_OK;
if (isArena && m_spellInfo->HasAttribute(SPELL_ATTR4_USABLE_IN_ARENA))
return SPELL_CAST_OK;
// check NOT_USABLE attributes
if (m_spellInfo->HasAttribute(SPELL_ATTR4_NOT_USABLE_IN_ARENA_OR_RATED_BG))
return isArena ? SPELL_FAILED_NOT_IN_ARENA : SPELL_FAILED_NOT_IN_RATED_BATTLEGROUND;
if (isArena && m_spellInfo->HasAttribute(SPELL_ATTR9_NOT_USABLE_IN_ARENA))
return SPELL_FAILED_NOT_IN_ARENA;
// check cooldowns
uint32 spellCooldown = m_spellInfo->GetRecoveryTime();
if (isArena && spellCooldown > 10 * MINUTE * IN_MILLISECONDS) // not sure if still needed
return SPELL_FAILED_NOT_IN_ARENA;
if (isRatedBattleground && spellCooldown > 15 * MINUTE * IN_MILLISECONDS)
return SPELL_FAILED_NOT_IN_RATED_BATTLEGROUND;
return SPELL_CAST_OK;
}
int32 Spell::CalculateDamage(uint8 i, Unit const* target, float* var /*= nullptr*/) const
{
bool needRecalculateBasePoints = !(m_spellValue->CustomBasePointsMask & (1 << i));
return m_caster->CalculateSpellDamage(target, m_spellInfo, i, needRecalculateBasePoints ? nullptr : &m_spellValue->EffectBasePoints[i], var, m_castItemEntry, m_castItemLevel);
}
bool Spell::CanAutoCast(Unit* target)
{
if (!target)
return (CheckPetCast(target) == SPELL_CAST_OK);
ObjectGuid targetguid = target->GetGUID();
// check if target already has the same or a more powerful aura
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
if (!effect)
continue;
if (!effect->IsAura())
continue;
AuraType const& auraType = AuraType(effect->ApplyAuraName);
Unit::AuraEffectList const& auras = target->GetAuraEffectsByType(auraType);
for (Unit::AuraEffectList::const_iterator auraIt = auras.begin(); auraIt != auras.end(); ++auraIt)
{
if (GetSpellInfo()->Id == (*auraIt)->GetSpellInfo()->Id)
return false;
switch (sSpellMgr->CheckSpellGroupStackRules(GetSpellInfo(), (*auraIt)->GetSpellInfo()))
{
case SPELL_GROUP_STACK_RULE_EXCLUSIVE:
return false;
case SPELL_GROUP_STACK_RULE_EXCLUSIVE_FROM_SAME_CASTER:
if (GetCaster() == (*auraIt)->GetCaster())
return false;
break;
case SPELL_GROUP_STACK_RULE_EXCLUSIVE_SAME_EFFECT: // this one has further checks, but i don't think they're necessary for autocast logic
case SPELL_GROUP_STACK_RULE_EXCLUSIVE_HIGHEST:
if (abs(effect->BasePoints) <= abs((*auraIt)->GetAmount()))
return false;
break;
case SPELL_GROUP_STACK_RULE_DEFAULT:
default:
break;
}
}
}
SpellCastResult result = CheckPetCast(target);
if (result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT)
{
// do not check targets for ground-targeted spells (we target them on top of the intended target anyway)
if (GetSpellInfo()->ExplicitTargetMask & TARGET_FLAG_DEST_LOCATION)
return true;
SelectSpellTargets();
//check if among target units, our WANTED target is as well (->only self cast spells return false)
for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
if (ihit->targetGUID == targetguid)
return true;
}
// either the cast failed or the intended target wouldn't be hit
return false;
}
void Spell::CheckSrc()
{
if (!m_targets.HasSrc())
m_targets.SetSrc(*m_caster);
}
void Spell::CheckDst()
{
if (!m_targets.HasDst())
m_targets.SetDst(*m_caster);
}
SpellCastResult Spell::CheckRange(bool strict) const
{
// Don't check for instant cast spells
if (!strict && m_casttime == 0)
return SPELL_CAST_OK;
float minRange, maxRange;
std::tie(minRange, maxRange) = GetMinMaxRange(strict);
// dont check max_range to strictly after cast
if (m_spellInfo->RangeEntry && m_spellInfo->RangeEntry->Flags != SPELL_RANGE_MELEE && !strict)
maxRange += std::min(MAX_SPELL_RANGE_TOLERANCE, maxRange*0.1f); // 10% but no more than MAX_SPELL_RANGE_TOLERANCE
// get square values for sqr distance checks
minRange *= minRange;
maxRange *= maxRange;
Unit* target = m_targets.GetUnitTarget();
if (target && target != m_caster)
{
if (m_caster->GetExactDistSq(target) > maxRange)
return SPELL_FAILED_OUT_OF_RANGE;
if (minRange > 0.0f && m_caster->GetExactDistSq(target) < minRange)
return SPELL_FAILED_OUT_OF_RANGE;
if (m_caster->GetTypeId() == TYPEID_PLAYER &&
(((m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc(static_cast<float>(M_PI), target))
&& !m_caster->IsWithinBoundaryRadius(target)))
return SPELL_FAILED_UNIT_NOT_INFRONT;
}
if (m_targets.HasDst() && !m_targets.HasTraj())
{
if (m_caster->GetExactDistSq(m_targets.GetDstPos()) > maxRange)
return SPELL_FAILED_OUT_OF_RANGE;
if (minRange > 0.0f && m_caster->GetExactDistSq(m_targets.GetDstPos()) < minRange)
return SPELL_FAILED_OUT_OF_RANGE;
}
return SPELL_CAST_OK;
}
std::pair<float, float> Spell::GetMinMaxRange(bool strict) const
{
float rangeMod = 0.0f;
float minRange = 0.0f;
float maxRange = 0.0f;
if (strict && m_spellInfo->IsNextMeleeSwingSpell())
{
maxRange = 100.0f;
return std::pair<float, float>(minRange, maxRange);
}
if (m_spellInfo->RangeEntry)
{
Unit* target = m_targets.GetUnitTarget();
if (m_spellInfo->RangeEntry->Flags & SPELL_RANGE_MELEE)
{
rangeMod = m_caster->GetMeleeRange(target ? target : m_caster); // when the target is not a unit, take the caster's combat reach as the target's combat reach.
}
else
{
float meleeRange = 0.0f;
if (m_spellInfo->RangeEntry->Flags & SPELL_RANGE_RANGED)
meleeRange = m_caster->GetMeleeRange(target ? target : m_caster); // when the target is not a unit, take the caster's combat reach as the target's combat reach.
minRange = m_caster->GetSpellMinRangeForTarget(target, m_spellInfo) + meleeRange;
maxRange = m_caster->GetSpellMaxRangeForTarget(target, m_spellInfo);
if (target || m_targets.GetCorpseTarget())
{
rangeMod = m_caster->GetCombatReach() + (target ? target->GetCombatReach() : m_caster->GetCombatReach());
if (minRange > 0.0f && !(m_spellInfo->RangeEntry->Flags & SPELL_RANGE_RANGED))
minRange += rangeMod;
}
}
if (target && m_caster->isMoving() && target->isMoving() && !m_caster->IsWalking() && !target->IsWalking() &&
(m_spellInfo->RangeEntry->Flags & SPELL_RANGE_MELEE || target->GetTypeId() == TYPEID_PLAYER))
rangeMod += 8.0f / 3.0f;
}
if (m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO) && m_caster->GetTypeId() == TYPEID_PLAYER)
if (Item* ranged = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK, true))
maxRange *= ranged->GetTemplate()->GetRangedModRange() * 0.01f;
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, maxRange, const_cast<Spell*>(this));
maxRange += rangeMod;
return std::pair<float, float>(minRange, maxRange);
}
SpellCastResult Spell::CheckPower() const
{
// item cast not used power
if (m_CastItem)
return SPELL_CAST_OK;
for (SpellPowerCost const& cost : m_powerCost)
{
// health as power used - need check health amount
if (cost.Power == POWER_HEALTH)
{
if (int32(m_caster->GetHealth()) <= cost.Amount)
return SPELL_FAILED_CASTER_AURASTATE;
continue;
}
// Check valid power type
if (cost.Power >= MAX_POWERS)
{
TC_LOG_ERROR("spells", "Spell::CheckPower: Unknown power type '%d'", cost.Power);
return SPELL_FAILED_UNKNOWN;
}
//check rune cost only if a spell has PowerType == POWER_RUNES
if (cost.Power == POWER_RUNES)
{
SpellCastResult failReason = CheckRuneCost();
if (failReason != SPELL_CAST_OK)
return failReason;
}
// Check power amount
if (int32(m_caster->GetPower(cost.Power)) < cost.Amount)
return SPELL_FAILED_NO_POWER;
}
return SPELL_CAST_OK;
}
SpellCastResult Spell::CheckItems(uint32* param1 /*= nullptr*/, uint32* param2 /*= nullptr*/) const
{
Player* player = m_caster->ToPlayer();
if (!player)
return SPELL_CAST_OK;
if (m_spellInfo->HasAttribute(SPELL_ATTR2_IGNORE_ITEM_CHECK))
return SPELL_CAST_OK;
if (!m_CastItem)
{
if (!m_castItemGUID.IsEmpty())
return SPELL_FAILED_ITEM_NOT_READY;
}
else
{
uint32 itemid = m_CastItem->GetEntry();
if (!player->HasItemCount(itemid))
return SPELL_FAILED_ITEM_NOT_READY;
ItemTemplate const* proto = m_CastItem->GetTemplate();
if (!proto)
return SPELL_FAILED_ITEM_NOT_READY;
for (ItemEffectEntry const* itemEffect : m_CastItem->GetEffects())
if (itemEffect->LegacySlotIndex < m_CastItem->m_itemData->SpellCharges.size() && itemEffect->Charges)
if (m_CastItem->GetSpellCharges(itemEffect->LegacySlotIndex) == 0)
return SPELL_FAILED_NO_CHARGES_REMAIN;
// consumable cast item checks
if (proto->GetClass() == ITEM_CLASS_CONSUMABLE && m_targets.GetUnitTarget())
{
// such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example
SpellCastResult failReason = SPELL_CAST_OK;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
// skip check, pet not required like checks, and for TARGET_UNIT_PET m_targets.GetUnitTarget() is not the real target but the caster
if (!effect || effect->TargetA.GetTarget() == TARGET_UNIT_PET)
continue;
if (effect->Effect == SPELL_EFFECT_HEAL)
{
if (m_targets.GetUnitTarget()->IsFullHealth())
{
failReason = SPELL_FAILED_ALREADY_AT_FULL_HEALTH;
continue;
}
else
{
failReason = SPELL_CAST_OK;
break;
}
}
// Mana Potion, Rage Potion, Thistle Tea(Rogue), ...
if (effect->Effect == SPELL_EFFECT_ENERGIZE)
{
if (effect->MiscValue < 0 || effect->MiscValue >= int8(MAX_POWERS))
{
failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
continue;
}
Powers power = Powers(effect->MiscValue);
if (m_targets.GetUnitTarget()->GetPower(power) == m_targets.GetUnitTarget()->GetMaxPower(power))
{
failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER;
continue;
}
else
{
failReason = SPELL_CAST_OK;
break;
}
}
}
if (failReason != SPELL_CAST_OK)
return failReason;
}
}
// check target item
if (!m_targets.GetItemTargetGUID().IsEmpty())
{
Item* item = m_targets.GetItemTarget();
if (!item)
return SPELL_FAILED_ITEM_GONE;
if (!item->IsFitToSpellRequirements(m_spellInfo))
return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
}
// if not item target then required item must be equipped
else
{
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_EQUIPPED_ITEM_REQUIREMENT))
if (!player->HasItemFitToSpellRequirements(m_spellInfo))
return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
}
// do not take reagents for these item casts
if (!(m_CastItem && m_CastItem->GetTemplate()->GetFlags() & ITEM_FLAG_NO_REAGENT_COST))
{
bool checkReagents = !(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST) && !player->CanNoReagentCast(m_spellInfo);
// Not own traded item (in trader trade slot) requires reagents even if triggered spell
if (!checkReagents)
if (Item* targetItem = m_targets.GetItemTarget())
if (targetItem->GetOwnerGUID() != m_caster->GetGUID())
checkReagents = true;
// check reagents (ignore triggered spells with reagents processed by original spell) and special reagent ignore case.
if (checkReagents)
{
for (uint32 i = 0; i < MAX_SPELL_REAGENTS; i++)
{
if (m_spellInfo->Reagent[i] <= 0)
continue;
uint32 itemid = m_spellInfo->Reagent[i];
uint32 itemcount = m_spellInfo->ReagentCount[i];
// if CastItem is also spell reagent
if (m_CastItem && m_CastItem->GetEntry() == itemid)
{
ItemTemplate const* proto = m_CastItem->GetTemplate();
if (!proto)
return SPELL_FAILED_ITEM_NOT_READY;
for (ItemEffectEntry const* itemEffect : m_CastItem->GetEffects())
{
if (itemEffect->LegacySlotIndex >= m_CastItem->m_itemData->SpellCharges.size())
continue;
// CastItem will be used up and does not count as reagent
int32 charges = m_CastItem->GetSpellCharges(itemEffect->LegacySlotIndex);
if (itemEffect->Charges < 0 && abs(charges) < 2)
{
++itemcount;
break;
}
}
}
if (!player->HasItemCount(itemid, itemcount))
{
if (param1)
*param1 = itemid;
return SPELL_FAILED_REAGENTS;
}
}
}
// check totem-item requirements (items presence in inventory)
uint32 totems = 2;
for (uint8 i = 0; i < 2; ++i)
{
if (m_spellInfo->Totem[i] != 0)
{
if (player->HasItemCount(m_spellInfo->Totem[i]))
{
totems -= 1;
continue;
}
}
else
totems -= 1;
}
if (totems != 0)
return SPELL_FAILED_TOTEMS;
// Check items for TotemCategory (items presence in inventory)
uint32 totemCategory = 2;
for (uint8 i = 0; i < 2; ++i)
{
if (m_spellInfo->TotemCategory[i] != 0)
{
if (player->HasItemTotemCategory(m_spellInfo->TotemCategory[i]))
{
totemCategory -= 1;
continue;
}
}
else
totemCategory -= 1;
}
if (totemCategory != 0)
return SPELL_FAILED_TOTEM_CATEGORY;
}
// special checks for spell effects
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
if (!effect)
continue;
switch (effect->Effect)
{
case SPELL_EFFECT_CREATE_ITEM:
case SPELL_EFFECT_CREATE_LOOT:
{
// m_targets.GetUnitTarget() means explicit cast, otherwise we dont check for possible equip error
Unit* target = m_targets.GetUnitTarget() ? m_targets.GetUnitTarget() : m_caster;
if (target && target->GetTypeId() == TYPEID_PLAYER && !IsTriggered() && effect->ItemType)
{
ItemPosCountVec dest;
InventoryResult msg = target->ToPlayer()->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, effect->ItemType, 1);
if (msg != EQUIP_ERR_OK)
{
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(effect->ItemType);
/// @todo Needs review
if (pProto && !(pProto->GetItemLimitCategory()))
{
player->SendEquipError(msg, nullptr, nullptr, effect->ItemType);
return SPELL_FAILED_DONT_REPORT;
}
else
{
if (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x40000000)))
return SPELL_FAILED_TOO_MANY_OF_ITEM;
else if (!(target->ToPlayer()->HasItemCount(effect->ItemType)))
{
player->SendEquipError(msg, nullptr, nullptr, effect->ItemType);
return SPELL_FAILED_DONT_REPORT;
}
else if (SpellEffectInfo const* efi = m_spellInfo->GetEffect(EFFECT_1))
player->CastSpell(m_caster, efi->CalcValue(), false); // move this to anywhere
return SPELL_FAILED_DONT_REPORT;
}
}
}
break;
}
case SPELL_EFFECT_ENCHANT_ITEM:
if (effect->ItemType && m_targets.GetItemTarget()
&& (m_targets.GetItemTarget()->IsVellum()))
{
// cannot enchant vellum for other player
if (m_targets.GetItemTarget()->GetOwner() != m_caster)
return SPELL_FAILED_NOT_TRADEABLE;
// do not allow to enchant vellum from scroll made by vellum-prevent exploit
if (m_CastItem && m_CastItem->GetTemplate()->GetFlags() & ITEM_FLAG_NO_REAGENT_COST)
return SPELL_FAILED_TOTEM_CATEGORY;
ItemPosCountVec dest;
InventoryResult msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, effect->ItemType, 1);
if (msg != EQUIP_ERR_OK)
{
player->SendEquipError(msg, nullptr, nullptr, effect->ItemType);
return SPELL_FAILED_DONT_REPORT;
}
}
/* fallthrough */
case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC:
{
Item* targetItem = m_targets.GetItemTarget();
if (!targetItem)
return SPELL_FAILED_ITEM_NOT_FOUND;
// required level has to be checked also! Exploit fix
if (targetItem->GetItemLevel(targetItem->GetOwner()) < m_spellInfo->BaseLevel || (targetItem->GetRequiredLevel() && uint32(targetItem->GetRequiredLevel()) < m_spellInfo->BaseLevel))
return SPELL_FAILED_LOWLEVEL;
bool isItemUsable = false;
for (ItemEffectEntry const* itemEffect : targetItem->GetEffects())
{
if (itemEffect->SpellID && itemEffect->TriggerType == ITEM_SPELLTRIGGER_ON_USE)
{
isItemUsable = true;
break;
}
}
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(effect->MiscValue);
// do not allow adding usable enchantments to items that have use effect already
if (enchantEntry)
{
for (uint8 s = 0; s < MAX_ITEM_ENCHANTMENT_EFFECTS; ++s)
{
switch (enchantEntry->Effect[s])
{
case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
if (isItemUsable)
return SPELL_FAILED_ON_USE_ENCHANT;
break;
case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
{
uint32 numSockets = 0;
for (uint32 socket = 0; socket < MAX_ITEM_PROTO_SOCKETS; ++socket)
if (targetItem->GetSocketColor(socket))
++numSockets;
if (numSockets == MAX_ITEM_PROTO_SOCKETS || targetItem->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT))
return SPELL_FAILED_MAX_SOCKETS;
break;
}
}
}
}
// Not allow enchant in trade slot for some enchant type
if (targetItem->GetOwner() != m_caster)
{
if (!enchantEntry)
return SPELL_FAILED_ERROR;
if (enchantEntry->Flags & ENCHANTMENT_CAN_SOULBOUND)
return SPELL_FAILED_NOT_TRADEABLE;
}
break;
}
case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY:
{
Item* item = m_targets.GetItemTarget();
if (!item)
return SPELL_FAILED_ITEM_NOT_FOUND;
// Not allow enchant in trade slot for some enchant type
if (item->GetOwner() != m_caster)
{
uint32 enchant_id = effect->MiscValue;
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
return SPELL_FAILED_ERROR;
if (pEnchant->Flags & ENCHANTMENT_CAN_SOULBOUND)
return SPELL_FAILED_NOT_TRADEABLE;
}
// Apply item level restriction if the enchanting spell has max level restrition set
if (m_CastItem && m_spellInfo->MaxLevel > 0)
{
if (item->GetTemplate()->GetBaseItemLevel() < (uint32)m_CastItem->GetTemplate()->GetBaseRequiredLevel())
return SPELL_FAILED_LOWLEVEL;
if (item->GetTemplate()->GetBaseItemLevel() > m_spellInfo->MaxLevel)
return SPELL_FAILED_HIGHLEVEL;
}
break;
}
case SPELL_EFFECT_ENCHANT_HELD_ITEM:
// check item existence in effect code (not output errors at offhand hold item effect to main hand for example
break;
case SPELL_EFFECT_DISENCHANT:
{
Item const* item = m_targets.GetItemTarget();
if (!item)
return SPELL_FAILED_CANT_BE_DISENCHANTED;
// prevent disenchanting in trade slot
if (item->GetOwnerGUID() != m_caster->GetGUID())
return SPELL_FAILED_CANT_BE_DISENCHANTED;
ItemTemplate const* itemProto = item->GetTemplate();
if (!itemProto)
return SPELL_FAILED_CANT_BE_DISENCHANTED;
ItemDisenchantLootEntry const* itemDisenchantLoot = item->GetDisenchantLoot(m_caster->ToPlayer());
if (!itemDisenchantLoot)
return SPELL_FAILED_CANT_BE_DISENCHANTED;
if (itemDisenchantLoot->SkillRequired > player->GetSkillValue(SKILL_ENCHANTING))
return SPELL_FAILED_LOW_CASTLEVEL;
break;
}
case SPELL_EFFECT_PROSPECTING:
{
Item* item = m_targets.GetItemTarget();
if (!item)
return SPELL_FAILED_CANT_BE_PROSPECTED;
//ensure item is a prospectable ore
if (!(item->GetTemplate()->GetFlags() & ITEM_FLAG_IS_PROSPECTABLE))
return SPELL_FAILED_CANT_BE_PROSPECTED;
//prevent prospecting in trade slot
if (item->GetOwnerGUID() != m_caster->GetGUID())
return SPELL_FAILED_CANT_BE_PROSPECTED;
//Check for enough skill in jewelcrafting
uint32 item_prospectingskilllevel = item->GetTemplate()->GetRequiredSkillRank();
if (item_prospectingskilllevel > player->GetSkillValue(SKILL_JEWELCRAFTING))
return SPELL_FAILED_LOW_CASTLEVEL;
//make sure the player has the required ores in inventory
if (item->GetCount() < 5)
{
if (param1 && param2)
{
*param1 = item->GetEntry();
*param2 = 5;
}
return SPELL_FAILED_NEED_MORE_ITEMS;
}
if (!LootTemplates_Prospecting.HaveLootFor(m_targets.GetItemTargetEntry()))
return SPELL_FAILED_CANT_BE_PROSPECTED;
break;
}
case SPELL_EFFECT_MILLING:
{
Item* item = m_targets.GetItemTarget();
if (!item)
return SPELL_FAILED_CANT_BE_MILLED;
//ensure item is a millable herb
if (!(item->GetTemplate()->GetFlags() & ITEM_FLAG_IS_MILLABLE))
return SPELL_FAILED_CANT_BE_MILLED;
//prevent milling in trade slot
if (item->GetOwnerGUID() != m_caster->GetGUID())
return SPELL_FAILED_CANT_BE_MILLED;
//Check for enough skill in inscription
uint32 item_millingskilllevel = item->GetTemplate()->GetRequiredSkillRank();
if (item_millingskilllevel > player->GetSkillValue(SKILL_INSCRIPTION))
return SPELL_FAILED_LOW_CASTLEVEL;
//make sure the player has the required herbs in inventory
if (item->GetCount() < 5)
{
if (param1 && param2)
{
*param1 = item->GetEntry();
*param2 = 5;
}
return SPELL_FAILED_NEED_MORE_ITEMS;
}
if (!LootTemplates_Milling.HaveLootFor(m_targets.GetItemTargetEntry()))
return SPELL_FAILED_CANT_BE_MILLED;
break;
}
case SPELL_EFFECT_WEAPON_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
{
if (m_attackType != RANGED_ATTACK)
break;
Item* pItem = player->GetWeaponForAttack(m_attackType);
if (!pItem || pItem->IsBroken())
return SPELL_FAILED_EQUIPPED_ITEM;
switch (pItem->GetTemplate()->GetSubClass())
{
case ITEM_SUBCLASS_WEAPON_THROWN:
{
uint32 ammo = pItem->GetEntry();
if (!player->HasItemCount(ammo))
return SPELL_FAILED_NO_AMMO;
break;
}
case ITEM_SUBCLASS_WEAPON_GUN:
case ITEM_SUBCLASS_WEAPON_BOW:
case ITEM_SUBCLASS_WEAPON_CROSSBOW:
case ITEM_SUBCLASS_WEAPON_WAND:
break;
default:
break;
}
break;
}
case SPELL_EFFECT_RECHARGE_ITEM:
{
uint32 itemId = effect->ItemType;
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemId);
if (!proto)
return SPELL_FAILED_ITEM_AT_MAX_CHARGES;
if (Item* item = player->GetItemByEntry(itemId))
for (ItemEffectEntry const* itemEffect : item->GetEffects())
if (itemEffect->LegacySlotIndex <= item->m_itemData->SpellCharges.size()
&& itemEffect->Charges != 0
&& item->GetSpellCharges(itemEffect->LegacySlotIndex) == itemEffect->Charges)
return SPELL_FAILED_ITEM_AT_MAX_CHARGES;
break;
}
case SPELL_EFFECT_RESPEC_AZERITE_EMPOWERED_ITEM:
{
Item const* item = m_targets.GetItemTarget();
if (!item)
return SPELL_FAILED_AZERITE_EMPOWERED_ONLY;
if (item->GetOwnerGUID() != m_caster->GetGUID())
return SPELL_FAILED_DONT_REPORT;
AzeriteEmpoweredItem const* azeriteEmpoweredItem = item->ToAzeriteEmpoweredItem();
if (!azeriteEmpoweredItem)
return SPELL_FAILED_AZERITE_EMPOWERED_ONLY;
bool hasSelections = false;
for (int32 tier = 0; tier < azeriteEmpoweredItem->GetMaxAzeritePowerTier(); ++tier)
{
if (azeriteEmpoweredItem->GetSelectedAzeritePower(tier))
{
hasSelections = true;
break;
}
}
if (!hasSelections)
return SPELL_FAILED_AZERITE_EMPOWERED_NO_CHOICES_TO_UNDO;
if (!m_caster->ToPlayer()->HasEnoughMoney(azeriteEmpoweredItem->GetRespecCost()))
return SPELL_FAILED_DONT_REPORT;
break;
}
default:
break;
}
}
// check weapon presence in slots for main/offhand weapons
if (!(_triggeredCastFlags & TRIGGERED_IGNORE_EQUIPPED_ITEM_REQUIREMENT) && m_spellInfo->EquippedItemClass >= 0)
{
auto weaponCheck = [this](WeaponAttackType attackType) -> SpellCastResult
{
Item const* item = m_caster->ToPlayer()->GetWeaponForAttack(attackType);
// skip spell if no weapon in slot or broken
if (!item || item->IsBroken())
return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
// skip spell if weapon not fit to triggered spell
if (!item->IsFitToSpellRequirements(m_spellInfo))
return SPELL_FAILED_EQUIPPED_ITEM_CLASS;
return SPELL_CAST_OK;
};
if (m_spellInfo->HasAttribute(SPELL_ATTR3_MAIN_HAND))
{
SpellCastResult mainHandResult = weaponCheck(BASE_ATTACK);
if (mainHandResult != SPELL_CAST_OK)
return mainHandResult;
}
if (m_spellInfo->HasAttribute(SPELL_ATTR3_REQ_OFFHAND))
{
SpellCastResult offHandResult = weaponCheck(OFF_ATTACK);
if (offHandResult != SPELL_CAST_OK)
return offHandResult;
}
}
return SPELL_CAST_OK;
}
void Spell::Delayed() // only called in DealDamage()
{
if (!m_caster)// || m_caster->GetTypeId() != TYPEID_PLAYER)
return;
//if (m_spellState == SPELL_STATE_DELAYED)
// return; // spell is active and can't be time-backed
if (isDelayableNoMore()) // Spells may only be delayed twice
return;
// spells not loosing casting time (slam, dynamites, bombs..)
//if (!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE))
// return;
//check pushback reduce
int32 delaytime = 150; // spellcasting delay is normally 500ms, updated Legion 2x150ms ~
int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
if (delayReduce >= 100)
return;
AddPct(delaytime, -delayReduce);
if (m_timer + delaytime > m_casttime)
{
delaytime = m_casttime - m_timer;
m_timer = m_casttime;
}
else
m_timer += delaytime;
TC_LOG_DEBUG("spells", "Spell %u partially interrupted for (%d) ms at damage", m_spellInfo->Id, delaytime);
WorldPackets::Spells::SpellDelayed spellDelayed;
spellDelayed.Caster = m_caster->GetGUID();
spellDelayed.ActualDelay = delaytime;
m_caster->SendMessageToSet(spellDelayed.Write(), true);
}
void Spell::DelayedChannel()
{
if (!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING)
return;
if (isDelayableNoMore()) // Spells may only be delayed twice
return;
//check pushback reduce
// should be affected by modifiers, not take the dbc duration.
//int32 duration = ((m_channeledDuration > 0) ? m_channeledDuration : m_spellInfo->GetDuration());
// needs some more research, sniff shows anywhere from 130 to 189, it is not a pct of duration
// https://gist.github.com/EPS1L0N/fa8977a74918ba4b9c63
int32 delaytime = 150;
int32 delayReduce = 100; // must be initialized to 100 for percent modifiers
m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this);
delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100;
if (delayReduce >= 100)
return;
AddPct(delaytime, -delayReduce);
if (m_timer <= delaytime)
{
delaytime = m_timer;
m_timer = 0;
}
else
m_timer -= delaytime;
TC_LOG_DEBUG("spells", "Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer);
for (std::vector<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
if ((*ihit).missCondition == SPELL_MISS_NONE)
if (Unit* unit = (m_caster->GetGUID() == ihit->targetGUID) ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID))
unit->DelayOwnedAuras(m_spellInfo->Id, m_originalCasterGUID, delaytime);
// partially interrupt persistent area auras
if (DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id))
dynObj->Delay(delaytime);
SendChannelUpdate(m_timer);
}
bool Spell::UpdatePointers()
{
if (m_originalCasterGUID == m_caster->GetGUID())
m_originalCaster = m_caster;
else
{
m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID);
if (m_originalCaster && !m_originalCaster->IsInWorld())
m_originalCaster = NULL;
}
if (!m_castItemGUID.IsEmpty() && m_caster->GetTypeId() == TYPEID_PLAYER)
{
m_CastItem = m_caster->ToPlayer()->GetItemByGuid(m_castItemGUID);
m_castItemLevel = -1;
// cast item not found, somehow the item is no longer where we expected
if (!m_CastItem)
return false;
// check if the item is really the same, in case it has been wrapped for example
if (m_castItemEntry != m_CastItem->GetEntry())
return false;
m_castItemLevel = int32(m_CastItem->GetItemLevel(m_caster->ToPlayer()));
}
m_targets.Update(m_caster);
// further actions done only for dest targets
if (!m_targets.HasDst())
return true;
// cache last transport
WorldObject* transport = NULL;
// update effect destinations (in case of moved transport dest target)
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
if (!effect)
continue;
SpellDestination& dest = m_destTargets[effect->EffectIndex];
if (!dest._transportGUID)
continue;
if (!transport || transport->GetGUID() != dest._transportGUID)
transport = ObjectAccessor::GetWorldObject(*m_caster, dest._transportGUID);
if (transport)
{
dest._position.Relocate(transport);
dest._position.RelocateOffset(dest._transportOffset);
}
}
return true;
}
SpellPowerCost const* Spell::GetPowerCost(Powers power) const
{
std::vector<SpellPowerCost> const& costs = GetPowerCost();
auto c = std::find_if(costs.begin(), costs.end(), [power](SpellPowerCost const& cost) { return cost.Power == power; });
if (c != costs.end())
return &(*c);
return nullptr;
}
float Spell::GetSpellPowerCostModifier(Powers power) const
{
float maxCost = 0.f;
for (SpellPowerEntry const* powerEntry : GetSpellInfo()->PowerCosts)
if (powerEntry->PowerType == power)
maxCost += powerEntry->ManaCost + powerEntry->OptionalCost;
if (SpellPowerCost const* powerCost = GetPowerCost(power))
return powerCost->Amount / maxCost;
return 0.f;
}
CurrentSpellTypes Spell::GetCurrentContainer() const
{
if (m_spellInfo->IsNextMeleeSwingSpell())
return CURRENT_MELEE_SPELL;
else if (IsAutoRepeat())
return CURRENT_AUTOREPEAT_SPELL;
else if (m_spellInfo->IsChanneled())
return CURRENT_CHANNELED_SPELL;
return CURRENT_GENERIC_SPELL;
}
Difficulty Spell::GetCastDifficulty() const
{
return m_caster->GetMap()->GetDifficultyID();
}
bool Spell::CheckEffectTarget(Unit const* target, SpellEffectInfo const* effect, Position const* losPosition) const
{
if (!effect->IsEffect())
return false;
switch (effect->ApplyAuraName)
{
case SPELL_AURA_MOD_POSSESS:
case SPELL_AURA_MOD_CHARM:
case SPELL_AURA_MOD_POSSESS_PET:
case SPELL_AURA_AOE_CHARM:
if (target->GetTypeId() == TYPEID_UNIT && target->IsVehicle())
return false;
if (target->IsMounted())
return false;
if (!target->GetCharmerGUID().IsEmpty())
return false;
if (int32 value = CalculateDamage(effect->EffectIndex, target))
if ((int32)target->GetLevelForTarget(m_caster) > value)
return false;
break;
default:
break;
}
// check for ignore LOS on the effect itself
if (m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS))
return true;
// if spell is triggered, need to check for LOS disable on the aura triggering it and inherit that behaviour
if (IsTriggered() && m_triggeredByAuraSpell && (m_triggeredByAuraSpell->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_triggeredByAuraSpell->Id, NULL, SPELL_DISABLE_LOS)))
return true;
/// @todo shit below shouldn't be here, but it's temporary
//Check targets for LOS visibility
switch (effect->Effect)
{
case SPELL_EFFECT_SKIN_PLAYER_CORPSE:
{
if (!m_targets.GetCorpseTargetGUID())
{
if (target->IsWithinLOSInMap(m_caster, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2) && target->HasUnitFlag(UNIT_FLAG_SKINNABLE))
return true;
return false;
}
Corpse* corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.GetCorpseTargetGUID());
if (!corpse)
return false;
if (target->GetGUID() != corpse->GetOwnerGUID())
return false;
if (!corpse->HasDynamicFlag(CORPSE_DYNFLAG_LOOTABLE))
return false;
if (!corpse->IsWithinLOSInMap(m_caster, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2))
return false;
break;
}
default:
{
if (losPosition)
return target->IsWithinLOS(losPosition->GetPositionX(), losPosition->GetPositionY(), losPosition->GetPositionZ(), LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2);
else
{
// Get GO cast coordinates if original caster -> GO
WorldObject* caster = NULL;
if (m_originalCasterGUID.IsGameObject())
caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID);
if (!caster)
caster = m_caster;
if (target != m_caster && !target->IsWithinLOSInMap(caster, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2))
return false;
}
}
}
return true;
}
bool Spell::CheckEffectTarget(GameObject const* target, SpellEffectInfo const* effect) const
{
if (!effect->IsEffect())
return false;
switch (effect->Effect)
{
case SPELL_EFFECT_GAMEOBJECT_DAMAGE:
case SPELL_EFFECT_GAMEOBJECT_REPAIR:
case SPELL_EFFECT_GAMEOBJECT_SET_DESTRUCTION_STATE:
if (target->GetGoType() != GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING)
return false;
break;
default:
break;
}
return true;
}
bool Spell::CheckEffectTarget(Item const* /*target*/, SpellEffectInfo const* effect) const
{
if (!effect->IsEffect())
return false;
return true;
}
bool Spell::IsTriggered() const
{
return (_triggeredCastFlags & TRIGGERED_FULL_MASK) != 0;
}
bool Spell::IsIgnoringCooldowns() const
{
return (_triggeredCastFlags & TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD) != 0;
}
bool Spell::IsProcDisabled() const
{
return (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS) != 0;
}
bool Spell::IsChannelActive() const
{
return m_caster->GetChannelSpellId() != 0;
}
bool Spell::IsAutoActionResetSpell() const
{
/// @todo changed SPELL_INTERRUPT_FLAG_AUTOATTACK -> SPELL_INTERRUPT_FLAG_INTERRUPT to fix compile - is this check correct at all?
if (IsTriggered() || !(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_INTERRUPT))
return false;
if (!m_casttime && m_spellInfo->HasAttribute(SPELL_ATTR6_NOT_RESET_SWING_IF_INSTANT))
return false;
return true;
}
bool Spell::IsNeedSendToClient() const
{
return m_SpellVisual || m_spellInfo->IsChanneled() ||
(m_spellInfo->HasAttribute(SPELL_ATTR8_AURA_SEND_AMOUNT)) || m_spellInfo->HasHitDelay() || (!m_triggeredByAuraSpell && !IsTriggered());
}
bool Spell::HaveTargetsForEffect(uint8 effect) const
{
for (std::vector<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr)
if (itr->effectMask & (1 << effect))
return true;
for (std::vector<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr)
if (itr->effectMask & (1 << effect))
return true;
for (std::vector<ItemTargetInfo>::const_iterator itr = m_UniqueItemInfo.begin(); itr != m_UniqueItemInfo.end(); ++itr)
if (itr->effectMask & (1 << effect))
return true;
return false;
}
SpellEvent::SpellEvent(Spell* spell) : BasicEvent()
{
m_Spell = spell;
}
SpellEvent::~SpellEvent()
{
if (m_Spell->getState() != SPELL_STATE_FINISHED)
m_Spell->cancel();
if (m_Spell->IsDeletable())
{
delete m_Spell;
}
else
{
TC_LOG_ERROR("spells", "~SpellEvent: %s %s tried to delete non-deletable spell %u. Was not deleted, causes memory leak.",
(m_Spell->GetCaster()->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), m_Spell->GetCaster()->GetGUID().ToString().c_str(), m_Spell->m_spellInfo->Id);
ABORT();
}
}
bool SpellEvent::Execute(uint64 e_time, uint32 p_time)
{
// update spell if it is not finished
if (m_Spell->getState() != SPELL_STATE_FINISHED)
m_Spell->update(p_time);
// check spell state to process
switch (m_Spell->getState())
{
case SPELL_STATE_FINISHED:
{
// spell was finished, check deletable state
if (m_Spell->IsDeletable())
{
// check, if we do have unfinished triggered spells
return true; // spell is deletable, finish event
}
// event will be re-added automatically at the end of routine)
break;
}
case SPELL_STATE_DELAYED:
{
// first, check, if we have just started
if (m_Spell->GetDelayStart() != 0)
{
// no, we aren't, do the typical update
// check, if we have channeled spell on our hands
/*
if (m_Spell->m_spellInfo->IsChanneled())
{
// evented channeled spell is processed separately, cast once after delay, and not destroyed till finish
// check, if we have casting anything else except this channeled spell and autorepeat
if (m_Spell->GetCaster()->IsNonMeleeSpellCast(false, true, true))
{
// another non-melee non-delayed spell is cast now, abort
m_Spell->cancel();
}
else
{
// Set last not triggered spell for apply spellmods
((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, true);
// do the action (pass spell to channeling state)
m_Spell->handle_immediate();
// And remove after effect handling
((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, false);
}
// event will be re-added automatically at the end of routine)
}
else
*/
{
// run the spell handler and think about what we can do next
uint64 t_offset = e_time - m_Spell->GetDelayStart();
uint64 n_offset = m_Spell->handle_delayed(t_offset);
if (n_offset)
{
// re-add us to the queue
m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false);
return false; // event not complete
}
// event complete
// finish update event will be re-added automatically at the end of routine)
}
}
else
{
// delaying had just started, record the moment
m_Spell->SetDelayStart(e_time);
// handle effects on caster if the spell has travel time but also affects the caster in some way
uint64 n_offset = m_Spell->handle_delayed(0);
if (m_Spell->m_spellInfo->LaunchDelay)
ASSERT(n_offset == uint64(std::floor(m_Spell->m_spellInfo->LaunchDelay * 1000.0f)));
else
ASSERT(n_offset == m_Spell->GetDelayMoment());
// re-plan the event for the delay moment
m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false);
return false; // event not complete
}
break;
}
default:
{
// all other states
// event will be re-added automatically at the end of routine)
break;
}
}
// spell processing not complete, plan event on the next update interval
m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false);
return false; // event not complete
}
void SpellEvent::Abort(uint64 /*e_time*/)
{
// oops, the spell we try to do is aborted
if (m_Spell->getState() != SPELL_STATE_FINISHED)
m_Spell->cancel();
}
bool SpellEvent::IsDeletable() const
{
return m_Spell->IsDeletable();
}
bool Spell::IsValidDeadOrAliveTarget(Unit const* target) const
{
if (target->IsAlive())
return !m_spellInfo->IsRequiringDeadTarget();
if (m_spellInfo->IsAllowingDeadTarget())
return true;
return false;
}
void Spell::HandleLaunchPhase()
{
// handle effects with SPELL_EFFECT_HANDLE_LAUNCH mode
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
// don't do anything for empty effect
if (!effect || !effect->IsEffect())
continue;
HandleEffects(NULL, NULL, NULL, effect->EffectIndex, SPELL_EFFECT_HANDLE_LAUNCH);
}
float multiplier[MAX_SPELL_EFFECTS];
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
if (effect && (m_applyMultiplierMask & (1 << effect->EffectIndex)))
multiplier[effect->EffectIndex] = effect->CalcDamageMultiplier(m_originalCaster, this);
PrepareTargetProcessing();
for (auto ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
TargetInfo& target = *ihit;
uint32 mask = target.effectMask;
if (!mask)
continue;
DoAllEffectOnLaunchTarget(target, multiplier);
}
FinishTargetProcessing();
}
void Spell::DoAllEffectOnLaunchTarget(TargetInfo& targetInfo, float* multiplier)
{
Unit* unit = NULL;
// In case spell hit target, do all effect on that target
if (targetInfo.missCondition == SPELL_MISS_NONE)
unit = m_caster->GetGUID() == targetInfo.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, targetInfo.targetGUID);
// In case spell reflect from target, do all effect on caster (if hit)
else if (targetInfo.missCondition == SPELL_MISS_REFLECT && targetInfo.reflectResult == SPELL_MISS_NONE)
unit = m_caster;
if (!unit)
return;
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
if (effect && (targetInfo.effectMask & (1<<effect->EffectIndex)))
{
m_damage = 0;
m_healing = 0;
HandleEffects(unit, NULL, NULL, effect->EffectIndex, SPELL_EFFECT_HANDLE_LAUNCH_TARGET);
if (m_damage > 0)
{
if (effect->IsTargetingArea() || effect->IsAreaAuraEffect() || effect->IsEffect(SPELL_EFFECT_PERSISTENT_AREA_AURA))
{
m_damage = int32(float(m_damage) * unit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE, m_spellInfo->SchoolMask));
if (m_caster->GetTypeId() != TYPEID_PLAYER)
m_damage = int32(float(m_damage) * unit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CREATURE_AOE_DAMAGE_AVOIDANCE, m_spellInfo->SchoolMask));
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
uint32 targetAmount = m_UniqueTargetInfo.size();
if (targetAmount > 20)
m_damage = m_damage * 20/targetAmount;
}
}
}
if (m_applyMultiplierMask & (1 << effect->EffectIndex))
{
m_damage = int32(m_damage * m_damageMultipliers[effect->EffectIndex]);
m_damageMultipliers[effect->EffectIndex] *= multiplier[effect->EffectIndex];
}
targetInfo.damage += m_damage;
}
}
targetInfo.crit = m_caster->IsSpellCrit(unit, this, nullptr, m_spellSchoolMask, m_attackType);
}
SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& skillId, int32& reqSkillValue, int32& skillValue)
{
if (!lockId) // possible case for GO and maybe for items.
return SPELL_CAST_OK;
// Get LockInfo
LockEntry const* lockInfo = sLockStore.LookupEntry(lockId);
if (!lockInfo)
return SPELL_FAILED_BAD_TARGETS;
SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex);
if (!effect)
return SPELL_FAILED_BAD_TARGETS; // no idea about correct error
bool reqKey = false; // some locks not have reqs
for (int j = 0; j < MAX_LOCK_CASE; ++j)
{
switch (lockInfo->Type[j])
{
// check key item (many fit cases can be)
case LOCK_KEY_ITEM:
if (lockInfo->Index[j] && m_CastItem && int32(m_CastItem->GetEntry()) == lockInfo->Index[j])
return SPELL_CAST_OK;
reqKey = true;
break;
// check key skill (only single first fit case can be)
case LOCK_KEY_SKILL:
{
// wrong locktype, skip
if (effect->MiscValue != lockInfo->Index[j])
continue;
reqKey = true;
skillId = SkillByLockType(LockType(lockInfo->Index[j]));
if (skillId != SKILL_NONE || lockInfo->Index[j] == LOCKTYPE_LOCKPICKING)
{
reqSkillValue = lockInfo->Skill[j];
// castitem check: rogue using skeleton keys. the skill values should not be added in this case.
skillValue = 0;
if (!m_CastItem && m_caster->GetTypeId() == TYPEID_PLAYER)
skillValue = m_caster->ToPlayer()->GetSkillValue(skillId);
else if (lockInfo->Index[j] == LOCKTYPE_LOCKPICKING)
skillValue = m_caster->getLevel() * 5;
else if (!m_CastItem && m_caster->IsPlayer())
skillValue = m_caster->ToPlayer()->GetSkillValue(skillId);
// skill bonus provided by casting spell (mostly item spells)
// add the effect base points modifier from the spell cast (cheat lock / skeleton key etc.)
if (effect->TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET || effect->TargetB.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET)
skillValue += effect->CalcValue();
if (skillValue < reqSkillValue)
return SPELL_FAILED_LOW_CASTLEVEL;
}
return SPELL_CAST_OK;
}
}
}
if (reqKey)
return SPELL_FAILED_BAD_TARGETS;
return SPELL_CAST_OK;
}
void Spell::SetSpellValue(SpellValueMod mod, int32 value)
{
if (mod < SPELLVALUE_BASE_POINT_END)
{
m_spellValue->EffectBasePoints[mod] = value;
m_spellValue->CustomBasePointsMask |= 1 << mod;
return;
}
if (mod >= SPELLVALUE_TRIGGER_SPELL && mod < SPELLVALUE_TRIGGER_SPELL_END)
{
if (m_spellInfo->GetEffect(mod - SPELLVALUE_TRIGGER_SPELL) != nullptr)
m_spellValue->EffectTriggerSpell[mod - SPELLVALUE_TRIGGER_SPELL] = (uint32)value;
return;
}
switch (mod)
{
case SPELLVALUE_RADIUS_MOD:
m_spellValue->RadiusMod = (float)value / 10000;
break;
case SPELLVALUE_MAX_TARGETS:
m_spellValue->MaxAffectedTargets = (uint32)value;
break;
case SPELLVALUE_AURA_STACK:
m_spellValue->AuraStackAmount = uint8(value);
break;
case SPELLVALUE_DURATION:
m_spellValue->Duration = (uint32)value;
break;
default:
break;
}
}
void Spell::PrepareTargetProcessing()
{
}
void Spell::FinishTargetProcessing()
{
SendSpellExecuteLog();
}
void Spell::LoadScripts()
{
sScriptMgr->CreateSpellScripts(m_spellInfo->Id, m_loadedScripts, this);
for (auto itr = m_loadedScripts.begin(); itr != m_loadedScripts.end(); ++itr)
{
TC_LOG_DEBUG("spells", "Spell::LoadScripts: Script `%s` for spell `%u` is loaded now", (*itr)->_GetScriptName()->c_str(), m_spellInfo->Id);
(*itr)->Register();
}
}
void Spell::CallScriptBeforeCastHandlers()
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_BEFORE_CAST);
auto hookItrEnd = (*scritr)->BeforeCast.end(), hookItr = (*scritr)->BeforeCast.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptOnPrepareHandlers()
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_ON_PREPARE);
auto hookItrEnd = (*scritr)->OnPrepare.end(), hookItr = (*scritr)->OnPrepare.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptOnCastHandlers()
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_ON_CAST);
auto hookItrEnd = (*scritr)->OnCast.end(), hookItr = (*scritr)->OnCast.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptAfterCastHandlers()
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_AFTER_CAST);
auto hookItrEnd = (*scritr)->AfterCast.end(), hookItr = (*scritr)->AfterCast.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptOnTakePowerHandlers(SpellPowerCost& powerCost)
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_TAKE_POWER);
auto hookItrEnd = (*scritr)->OnTakePower.end(), hookItr = (*scritr)->OnTakePower.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr, powerCost);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptOnCalcCastTimeHandlers()
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_CALC_CAST_TIME);
auto hookItrEnd = (*scritr)->OnCalcCastTime.end(), hookItr = (*scritr)->OnCalcCastTime.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr, m_casttime);
(*scritr)->_FinishScriptCall();
}
}
SpellCastResult Spell::CallScriptCheckCastHandlers()
{
SpellCastResult retVal = SPELL_CAST_OK;
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_CHECK_CAST);
auto hookItrEnd = (*scritr)->OnCheckCast.end(), hookItr = (*scritr)->OnCheckCast.begin();
for (; hookItr != hookItrEnd; ++hookItr)
{
SpellCastResult tempResult = (*hookItr).Call(*scritr);
if (retVal == SPELL_CAST_OK)
retVal = tempResult;
}
(*scritr)->_FinishScriptCall();
}
return retVal;
}
void Spell::PrepareScriptHitHandlers()
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
(*scritr)->_InitHit();
}
bool Spell::CallScriptEffectHandlers(SpellEffIndex effIndex, SpellEffectHandleMode mode)
{
// execute script effect handler hooks and check if effects was prevented
bool preventDefault = false;
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
HookList<SpellScript::EffectHandler>::iterator effItr, effEndItr;
SpellScriptHookType hookType;
switch (mode)
{
case SPELL_EFFECT_HANDLE_LAUNCH:
effItr = (*scritr)->OnEffectLaunch.begin();
effEndItr = (*scritr)->OnEffectLaunch.end();
hookType = SPELL_SCRIPT_HOOK_EFFECT_LAUNCH;
break;
case SPELL_EFFECT_HANDLE_LAUNCH_TARGET:
effItr = (*scritr)->OnEffectLaunchTarget.begin();
effEndItr = (*scritr)->OnEffectLaunchTarget.end();
hookType = SPELL_SCRIPT_HOOK_EFFECT_LAUNCH_TARGET;
break;
case SPELL_EFFECT_HANDLE_HIT:
effItr = (*scritr)->OnEffectHit.begin();
effEndItr = (*scritr)->OnEffectHit.end();
hookType = SPELL_SCRIPT_HOOK_EFFECT_HIT;
break;
case SPELL_EFFECT_HANDLE_HIT_TARGET:
effItr = (*scritr)->OnEffectHitTarget.begin();
effEndItr = (*scritr)->OnEffectHitTarget.end();
hookType = SPELL_SCRIPT_HOOK_EFFECT_HIT_TARGET;
break;
default:
ABORT();
return false;
}
(*scritr)->_PrepareScriptCall(hookType);
for (; effItr != effEndItr; ++effItr)
// effect execution can be prevented
if (!(*scritr)->_IsEffectPrevented(effIndex) && (*effItr).IsEffectAffected(m_spellInfo, effIndex))
(*effItr).Call(*scritr, effIndex);
if (!preventDefault)
preventDefault = (*scritr)->_IsDefaultEffectPrevented(effIndex);
(*scritr)->_FinishScriptCall();
}
return preventDefault;
}
void Spell::CallScriptSuccessfulDispel(SpellEffIndex effIndex)
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_EFFECT_SUCCESSFUL_DISPEL);
auto hookItrEnd = (*scritr)->OnEffectSuccessfulDispel.end(), hookItr = (*scritr)->OnEffectSuccessfulDispel.begin();
for (; hookItr != hookItrEnd; ++hookItr)
hookItr->Call(*scritr, effIndex);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptBeforeHitHandlers(SpellMissInfo missInfo)
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_BEFORE_HIT);
auto hookItrEnd = (*scritr)->BeforeHit.end(), hookItr = (*scritr)->BeforeHit.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr, missInfo);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptOnHitHandlers()
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_HIT);
auto hookItrEnd = (*scritr)->OnHit.end(), hookItr = (*scritr)->OnHit.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptAfterHitHandlers()
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_AFTER_HIT);
auto hookItrEnd = (*scritr)->AfterHit.end(), hookItr = (*scritr)->AfterHit.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptObjectAreaTargetSelectHandlers(std::list<WorldObject*>& targets, SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_OBJECT_AREA_TARGET_SELECT);
auto hookItrEnd = (*scritr)->OnObjectAreaTargetSelect.end(), hookItr = (*scritr)->OnObjectAreaTargetSelect.begin();
for (; hookItr != hookItrEnd; ++hookItr)
if (hookItr->IsEffectAffected(m_spellInfo, effIndex) && targetType.GetTarget() == hookItr->GetTarget())
hookItr->Call(*scritr, targets);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptObjectTargetSelectHandlers(WorldObject*& target, SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_OBJECT_TARGET_SELECT);
auto hookItrEnd = (*scritr)->OnObjectTargetSelect.end(), hookItr = (*scritr)->OnObjectTargetSelect.begin();
for (; hookItr != hookItrEnd; ++hookItr)
if (hookItr->IsEffectAffected(m_spellInfo, effIndex) && targetType.GetTarget() == hookItr->GetTarget())
hookItr->Call(*scritr, target);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptOnSummonHandlers(Creature* creature)
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_ON_SUMMON);
auto hookItrEnd = (*scritr)->OnEffectSummon.end(), hookItr = (*scritr)->OnEffectSummon.begin();
for (; hookItr != hookItrEnd; ++hookItr)
hookItr->Call(*scritr, creature);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptDestinationTargetSelectHandlers(SpellDestination& target, SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType)
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_DESTINATION_TARGET_SELECT);
auto hookItrEnd = (*scritr)->OnDestinationTargetSelect.end(), hookItr = (*scritr)->OnDestinationTargetSelect.begin();
for (; hookItr != hookItrEnd; ++hookItr)
if (hookItr->IsEffectAffected(m_spellInfo, effIndex) && targetType.GetTarget() == hookItr->GetTarget())
hookItr->Call(*scritr, target);
(*scritr)->_FinishScriptCall();
}
}
void Spell::CallScriptCalcCritChanceHandlers(Unit* victim, float& chance)
{
for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr)
{
(*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_CALC_CRIT_CHANCE);
auto hookItrEnd = (*scritr)->OnCalcCritChance.end(), hookItr = (*scritr)->OnCalcCritChance.begin();
for (; hookItr != hookItrEnd; ++hookItr)
(*hookItr).Call(*scritr, victim, chance);
(*scritr)->_FinishScriptCall();
}
}
bool Spell::CheckScriptEffectImplicitTargets(uint32 effIndex, uint32 effIndexToCheck)
{
// Skip if there are not any script
if (m_loadedScripts.empty())
return true;
for (auto itr = m_loadedScripts.begin(); itr != m_loadedScripts.end(); ++itr)
{
auto targetSelectHookEnd = (*itr)->OnObjectTargetSelect.end(), targetSelectHookItr = (*itr)->OnObjectTargetSelect.begin();
for (; targetSelectHookItr != targetSelectHookEnd; ++targetSelectHookItr)
if (((*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && !(*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck)) ||
(!(*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && (*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck)))
return false;
auto areaTargetSelectHookEnd = (*itr)->OnObjectAreaTargetSelect.end(), areaTargetSelectHookItr = (*itr)->OnObjectAreaTargetSelect.begin();
for (; areaTargetSelectHookItr != areaTargetSelectHookEnd; ++areaTargetSelectHookItr)
if (((*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && !(*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck)) ||
(!(*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && (*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck)))
return false;
}
return true;
}
bool Spell::CanExecuteTriggersOnHit(uint32 effMask, SpellInfo const* triggeredByAura /*= nullptr*/) const
{
bool only_on_caster = (triggeredByAura && (triggeredByAura->HasAttribute(SPELL_ATTR4_PROC_ONLY_ON_CASTER)));
// If triggeredByAura has SPELL_ATTR4_PROC_ONLY_ON_CASTER then it can only proc on a cast spell with TARGET_UNIT_CASTER
for (SpellEffectInfo const* effect : m_spellInfo->GetEffects())
{
if (effect && ((effMask & (1 << effect->EffectIndex)) && (!only_on_caster || (effect->TargetA.GetTarget() == TARGET_UNIT_CASTER))))
return true;
}
return false;
}
void Spell::PrepareTriggersExecutedOnHit()
{
// handle SPELL_AURA_ADD_TARGET_TRIGGER auras:
// save auras which were present on spell caster on cast, to prevent triggered auras from affecting caster
// and to correctly calculate proc chance when combopoints are present
Unit::AuraEffectList const& targetTriggers = m_caster->GetAuraEffectsByType(SPELL_AURA_ADD_TARGET_TRIGGER);
for (AuraEffect const* aurEff : targetTriggers)
{
if (!aurEff->IsAffectingSpell(m_spellInfo))
continue;
if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(aurEff->GetSpellEffectInfo()->TriggerSpell, GetCastDifficulty()))
{
// calculate the chance using spell base amount, because aura amount is not updated on combo-points change
// this possibly needs fixing
int32 auraBaseAmount = aurEff->GetBaseAmount();
// proc chance is stored in effect amount
int32 chance = m_caster->CalculateSpellDamage(nullptr, aurEff->GetSpellInfo(), aurEff->GetEffIndex(), &auraBaseAmount);
chance *= aurEff->GetBase()->GetStackAmount();
// build trigger and add to the list
m_hitTriggerSpells.emplace_back(spellInfo, aurEff->GetSpellInfo(), chance);
}
}
}
// Global cooldowns management
enum GCDLimits
{
MIN_GCD = 750,
MAX_GCD = 1500
};
bool Spell::HasGlobalCooldown() const
{
// Only players or controlled units have global cooldown
if (m_caster->GetTypeId() != TYPEID_PLAYER && !m_caster->GetCharmInfo())
return false;
return m_caster->GetSpellHistory()->HasGlobalCooldown(m_spellInfo);
}
void Spell::TriggerGlobalCooldown()
{
int32 gcd = m_spellInfo->StartRecoveryTime;
if (!gcd || !m_spellInfo->StartRecoveryCategory)
return;
// Only players or controlled units have global cooldown
if (m_caster->GetTypeId() != TYPEID_PLAYER && !m_caster->GetCharmInfo())
return;
if (m_caster->GetTypeId() == TYPEID_PLAYER)
if (m_caster->ToPlayer()->GetCommandStatus(CHEAT_COOLDOWN))
return;
// Global cooldown can't leave range 1..1.5 secs
// There are some spells (mostly not cast directly by player) that have < 1 sec and > 1.5 sec global cooldowns
// but as tests show are not affected by any spell mods.
if (m_spellInfo->StartRecoveryTime >= MIN_GCD && m_spellInfo->StartRecoveryTime <= MAX_GCD)
{
// gcd modifier auras are applied only to own spells and only players have such mods
if (Player* modOwner = m_caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_GLOBAL_COOLDOWN, gcd, this);
bool isMeleeOrRangedSpell = m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE ||
m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED ||
m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO) ||
m_spellInfo->HasAttribute(SPELL_ATTR0_ABILITY);
// Apply haste rating
if (gcd > MIN_GCD && ((m_spellInfo->StartRecoveryCategory == 133 && !isMeleeOrRangedSpell) || m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_MOD_GLOBAL_COOLDOWN_BY_HASTE, m_spellInfo)))
{
gcd = int32(float(gcd) * m_caster->m_unitData->ModSpellHaste);
RoundToInterval<int32>(gcd, MIN_GCD, MAX_GCD);
}
if (gcd > MIN_GCD && m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_MOD_GLOBAL_COOLDOWN_BY_HASTE_REGEN, m_spellInfo))
{
gcd = int32(float(gcd) * m_caster->m_unitData->ModHasteRegen);
RoundToInterval<int32>(gcd, MIN_GCD, MAX_GCD);
}
}
m_caster->GetSpellHistory()->AddGlobalCooldown(m_spellInfo, gcd);
}
void Spell::CancelGlobalCooldown()
{
if (!m_spellInfo->StartRecoveryTime)
return;
// Cancel global cooldown when interrupting current cast
if (m_caster->GetCurrentSpell(CURRENT_GENERIC_SPELL) != this)
return;
// Only players or controlled units have global cooldown
if (m_caster->GetTypeId() != TYPEID_PLAYER && !m_caster->GetCharmInfo())
return;
m_caster->GetSpellHistory()->CancelGlobalCooldown(m_spellInfo);
}
namespace Trinity
{
WorldObjectSpellTargetCheck::WorldObjectSpellTargetCheck(Unit* caster, Unit* referer, SpellInfo const* spellInfo,
SpellTargetCheckTypes selectionType, ConditionContainer* condList) : _caster(caster), _referer(referer), _spellInfo(spellInfo),
_targetSelectionType(selectionType), _condList(condList)
{
if (condList)
_condSrcInfo = new ConditionSourceInfo(nullptr, caster);
else
_condSrcInfo = nullptr;
}
WorldObjectSpellTargetCheck::~WorldObjectSpellTargetCheck()
{
delete _condSrcInfo;
}
bool WorldObjectSpellTargetCheck::operator()(WorldObject* target)
{
if (_spellInfo->CheckTarget(_caster, target, true) != SPELL_CAST_OK)
return false;
Unit* unitTarget = target->ToUnit();
if (Corpse* corpseTarget = target->ToCorpse())
{
// use ofter for party/assistance checks
if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID()))
unitTarget = owner;
else
return false;
}
if (unitTarget)
{
switch (_targetSelectionType)
{
case TARGET_CHECK_ENEMY:
if (unitTarget->IsTotem())
return false;
if (!_caster->_IsValidAttackTarget(unitTarget, _spellInfo))
return false;
break;
case TARGET_CHECK_ALLY:
if (unitTarget->IsTotem())
return false;
if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo))
return false;
break;
case TARGET_CHECK_PARTY:
if (unitTarget->IsTotem())
return false;
if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo))
return false;
if (!_referer->IsInPartyWith(unitTarget))
return false;
break;
case TARGET_CHECK_RAID_CLASS:
if (_referer->getClass() != unitTarget->getClass())
return false;
/* fallthrough */
case TARGET_CHECK_RAID_DEATH:
case TARGET_CHECK_RAID:
if (_targetSelectionType == TARGET_CHECK_RAID_DEATH)
if (!_referer->isDead())
return false;
if (unitTarget->IsTotem())
return false;
if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo))
return false;
if (!_referer->IsInRaidWith(unitTarget))
return false;
break;
case TARGET_CHECK_DEATH:
if (!unitTarget->isDead())
return false;
break;
case TARGET_CHECK_SUMMONED:
if (!unitTarget->IsSummon())
return false;
if (unitTarget->ToTempSummon()->GetSummonerGUID() != _caster->GetGUID())
return false;
break;
case TARGET_CHECK_THREAT:
if (_referer->getThreatManager().getThreat(unitTarget, true) <= 0.0f)
return false;
break;
case TARGET_CHECK_TAP:
if (_referer->GetTypeId() != TYPEID_UNIT || unitTarget->GetTypeId() != TYPEID_PLAYER)
return false;
if (!_referer->ToCreature()->IsTappedBy(unitTarget->ToPlayer()))
return false;
break;
default:
break;
}
}
if (!_condSrcInfo)
return true;
_condSrcInfo->mConditionTargets[0] = target;
return sConditionMgr->IsObjectMeetToConditions(*_condSrcInfo, *_condList);
}
WorldObjectSpellNearbyTargetCheck::WorldObjectSpellNearbyTargetCheck(float range, Unit* caster, SpellInfo const* spellInfo,
SpellTargetCheckTypes selectionType, ConditionContainer* condList)
: WorldObjectSpellTargetCheck(caster, caster, spellInfo, selectionType, condList), _range(range), _position(caster) { }
bool WorldObjectSpellNearbyTargetCheck::operator()(WorldObject* target)
{
float dist = target->GetDistance(*_position);
if (dist < _range && WorldObjectSpellTargetCheck::operator ()(target))
{
_range = dist;
return true;
}
return false;
}
WorldObjectSpellAreaTargetCheck::WorldObjectSpellAreaTargetCheck(float range, Position const* position, Unit* caster,
Unit* referer, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionContainer* condList)
: WorldObjectSpellTargetCheck(caster, referer, spellInfo, selectionType, condList), _range(range), _position(position) { }
bool WorldObjectSpellAreaTargetCheck::operator()(WorldObject* target)
{
if (target->ToGameObject())
{
// isInRange including the dimension of the GO
bool isInRange = target->ToGameObject()->IsInRange(_position->GetPositionX(), _position->GetPositionY(), _position->GetPositionZ(), _range);
if (!isInRange)
return false;
}
else
{
bool isInsideCylinder = target->IsWithinDist2d(_position, _range) && std::abs(target->GetPositionZ() - _position->GetPositionZ()) <= _range;
if (!isInsideCylinder)
return false;
}
return WorldObjectSpellTargetCheck::operator ()(target);
}
WorldObjectSpellConeTargetCheck::WorldObjectSpellConeTargetCheck(float coneAngle, float lineWidth, float range, Unit* caster,
SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionContainer* condList)
: WorldObjectSpellAreaTargetCheck(range, caster, caster, caster, spellInfo, selectionType, condList), _coneAngle(coneAngle), _lineWidth(lineWidth) { }
bool WorldObjectSpellConeTargetCheck::operator()(WorldObject* target)
{
if (_spellInfo->HasAttribute(SPELL_ATTR0_CU_CONE_BACK))
{
if (!_caster->isInBack(target, _coneAngle))
return false;
}
else if (_spellInfo->HasAttribute(SPELL_ATTR0_CU_CONE_LINE))
{
if (!_caster->HasInLine(target, target->GetCombatReach(), _lineWidth))
return false;
}
else
{
if (!_caster->IsWithinBoundaryRadius(target->ToUnit()))
// ConeAngle > 0 -> select targets in front
// ConeAngle < 0 -> select targets in back
if (_caster->HasInArc(_coneAngle, target) != G3D::fuzzyGe(_coneAngle, 0.f))
return false;
}
return WorldObjectSpellAreaTargetCheck::operator ()(target);
}
WorldObjectSpellTrajTargetCheck::WorldObjectSpellTrajTargetCheck(float range, Position const* position, Unit* caster, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionContainer* condList)
: WorldObjectSpellTargetCheck(caster, caster, spellInfo, selectionType, condList), _range(range), _position(position) { }
bool WorldObjectSpellTrajTargetCheck::operator()(WorldObject* target)
{
// return all targets on missile trajectory (0 - size of a missile)
if (!_caster->HasInLine(target, target->GetCombatReach(), TRAJECTORY_MISSILE_SIZE))
return false;
if (target->GetExactDist2d(_position) > _range)
return false;
return WorldObjectSpellTargetCheck::operator ()(target);
}
} //namespace Trinity
| AshamaneProject/AshamaneCore | src/server/game/Spells/Spell.cpp | C++ | gpl-2.0 | 327,065 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Matroska;
use PHPExiftool\Driver\AbstractTag;
class CodecInfoURL extends AbstractTag
{
protected $Id = 1785920;
protected $Name = 'CodecInfoURL';
protected $FullName = 'Matroska::Main';
protected $GroupName = 'Matroska';
protected $g0 = 'Matroska';
protected $g1 = 'Matroska';
protected $g2 = 'Video';
protected $Type = 'string';
protected $Writable = false;
protected $Description = 'Codec Info URL';
}
| Droces/casabio | vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/Matroska/CodecInfoURL.php | PHP | gpl-2.0 | 721 |
package org.rosuda.deducer.widgets.event;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class RKeyListener extends RListener implements KeyListener{
public void keyPressed(KeyEvent arg0) {
eventOccured(arg0,"keyPressed");
}
public void keyReleased(KeyEvent arg0) {
eventOccured(arg0,"keyReleased");
}
public void keyTyped(KeyEvent arg0) {
eventOccured(arg0,"keyTyped");
}
}
| ifellows/Deducer | org/org/rosuda/deducer/widgets/event/RKeyListener.java | Java | gpl-2.0 | 420 |
package org.apache.xmlrpc;
public interface SessionHandler {
void checkSession(Integer SessionId, Integer UserId) throws InvalidSessionException;
}
| BayCEER/bayeos-xmlrpc | src/main/java/org/apache/xmlrpc/SessionHandler.java | Java | gpl-2.0 | 156 |