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
/* This file is part of HexEd Copyright (C) 2008-2015 Stephen Robinson <hacks@esar.org.uk> HexEd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; class TitleLabel : Label { public TitleLabel() { SetStyle(ControlStyles.SupportsTransparentBackColor, true); Font = new Font(Font.FontFamily, 10, FontStyle.Bold); Padding = new Padding(2); ForeColor = SystemColors.ActiveCaptionText; BackColor = Color.Transparent; } protected override void OnCreateControl() { Graphics g = CreateGraphics(); SizeF size = g.MeasureString("Hg", Font); g.Dispose(); Height = (int)size.Height + 6; } protected override void OnPaintBackground(PaintEventArgs e) { base.OnPaintBackground(e); LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, SystemColors.ButtonShadow, Color.Transparent, 0.0F); e.Graphics.FillRectangle(brush, ClientRectangle); brush.Dispose(); } }
esar/hexed
TitleLabel.cs
C#
gpl-2.0
1,591
#include <unistd.h> int main(void) { while(1) fork(); return 0; }
bartgee/forkbomb
src/forkbomb.cpp
C++
gpl-2.0
80
<?php function ois_edit_skin($skin) { if (isset($_GET['delete'])) { if (check_admin_referer('trash')) { // Now we can delete the skin! $all_skins = get_option('ois_skins'); $id = $_GET['delete']; if (!empty($all_skins)) { foreach ($all_skins as $num=>$la_skin) { if ($la_skin['id'] == $id) { $all_skins[$num]['status'] = 'trash'; break; } } update_option('ois_skins', $all_skins); $cur_location = explode("?", $_SERVER['REQUEST_URI']); $new_location = 'http://' . $_SERVER["HTTP_HOST"] . $cur_location[0] . '?page=addskin&update=trash'; echo '<script type="text/javascript"> window.location = "' . $new_location . $updated_message . '"; </script>'; } } } else if (isset($_GET['draft'])) { if (check_admin_referer('draft')) { // Now we can delete the skin! $all_skins = get_option('ois_skins'); $id = $_GET['draft']; if (!empty($all_skins)) { foreach ($all_skins as $num=>$la_skin) { if ($la_skin['id'] == $id) { $all_skins[$num]['status'] = 'draft'; break; } } update_option('ois_skins', $all_skins); $cur_location = explode("?", $_SERVER['REQUEST_URI']); $new_location = 'http://' . $_SERVER["HTTP_HOST"] . $cur_location[0] . '?page=addskin&update=draft'; echo '<script type="text/javascript"> window.location = "' . $new_location . $updated_message . '"; </script>'; } } } else { if (isset($_GET['range'])) { $stats_range = $_GET['range']; } else { $stats_range = 20; } if (isset($_POST['newskin_design_section'])) { ois_handle_edit_skin($_POST); } if (isset($_GET['updated']) && $_GET['updated'] == 'true') { ois_notification('Successfully Updated Your Skin!', 'margin: 5px 0 0 0 ;', ''); } else if (isset($_GET['created']) && $_GET['created'] == 'true') { $uri = explode('?', $_SERVER['REQUEST_URI']); $stats_url = $uri[0] . '?page=stats'; ois_notification('Your new skin is now live on your site. If you enabled split-testing, you can view how it is performing <a href="' . $stats_url . '">here</a>.', 'margin: 5px 0 0 0 ;', ''); } ois_section_title(stripslashes($skin['title']), stripslashes($skin['description']), ''); $feedburner_id = get_option('ois_feedburner_id'); $mailchimp_id = get_option('ois_mailchimp_id'); $mailchimp_api = get_option('ois_mailchimp_api'); $aweber_id = get_option('ois_aweber_id'); $optin_accounts = array ( 'FeedburnerID' => $feedburner_id, 'MailChimpID' => $mailchimp_id, 'MailChimpAPI' => $mailchimp_api, 'AweberID' => $aweber_id, ); $all_stats = get_option('ois_stats'); //print_r($all_stats); $impressions = array(); $submits = array(); if (!empty($all_stats)) { foreach ($all_stats as $stats) { if (!empty($stats['s'])) { if ($stats['s'] == $skin['id']) { if (!empty($stats['m']) && $stats['m'] == 'yes') { array_push($submits, $stats); } else { array_push($impressions, $stats); } } } } } $uri = explode('?', $_SERVER['REQUEST_URI']); $edit_url = $uri[0] . '?page=addskin&id=' . $skin['id']; ?> <div class="ois_rolo_description"></div> <div> <h2 class="nav-tab-wrapper"> <a href="<?php echo $_SERVER['REQUEST_URI']; ?>" class="nav-tab nav-tab-active">Skin Performance</a> <a href="<?php echo $edit_url; ?>" class="nav-tab">Edit Skin</a> </h2> </div> <style> .ois_stats_option, .ois_stats_days_option { padding: 5px 9px;; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; -moz-box-shadow: 1px 1px 1px 1px #f1f5f9; -webkit-box-shadow: 1px 1px 1px 1px #f1f5f9; box-shadow: 1px 1px 1px 1px #f1f5f9; border: 1px solid #e3e9f0; margin: 5px; } .ois_stats_option:hover, .ois_stats_days_option:hover { background-color: #f7f9fb; -moz-box-shadow: 1px 1px 1px 1px #eee; -webkit-box-shadow: 1px 1px 1px 1px #eee; box-shadow: 1px 1px 1px 1px #eee; } div.ois_stat_options{ padding: 15px 0 15px 5px; } .ois_plotarea { margin: 12px 8px 10px 8px; height: 255px; } .ois_vis_a_active, .ois_stats_days_a_active { padding: 5px 12px; background-color: #f0f4f8 !important; } .ois_code_snippet { padding: 5px; background-color: #fffeee; border: 1px dashed #fff222; font-family: "Georgia"; } .ois_stats_table { margin-top: 10px !important; } </style> <table class="widefat" style="width:95%; margin: 10px 0;"> <tbody> <tr class="alternate"> <td> <h3 style="margin:5px 0;">Custom Positioning</h3> <p style="line-height:20px;"> To use this skin as a shortcode, simply put <span class="ois_code_snippet" id="ois_use_shortcode">[ois skin="<?php echo $skin['title']; ?>"]</span> into any of your posts.<br/>To use it on a php page, such as <em>header.php</em> or <em>footer.php</em>, use the php code <span class="ois_code_snippet" id="ois_do_shortcode">echo do_shortcode( '[ois skin="<?php echo $skin['title']; ?>"]' );</span>. </p> </div> </td> </tr> </tbody> </table> <style> .ois_column_left { float:left; width:45%; padding-right: 5%; } .ois_column_right { float:right; width:45%; padding-right: 5%; } .ois_skin_action { margin: 0 5px; } </style> <?php // STATISTICS // $stats_disable = get_option('stats_disable'); if ($stats_disable != 'yes') { ?> <script src="<?php echo WP_PLUGIN_URL; ?>/OptinSkin/admin/special_includes/flot/jquery.flot.js" language="javascript" type="text/javascript"></script> <!--[if IE]><script language="javascript" type="text/javascript" src="<?php echo WP_PLUGIN_URL; ?>/OptinSkin/admin/special_includes/flot/excanvas.pack.js"></script><![endif]--> <script language="javascript" type="text/javascript"> jQuery(function ($) { // For signups var signups_data = [ { color: '#5793c3', label: "Number of Signups", data: [ <?php // Data for Submits $submits_data = array(); for ($i = 0; $i < $stats_range; $i++) { $x = 0; // for each day if (!empty($submits)) { foreach ($submits as $submit) { // go through all impressions if (strtotime($submit['t']) < strtotime('-' . $i . ' days') && strtotime($submit['t']) > strtotime('-' . ($i + 1) . ' days')) { // if within this day $x++; } } } array_unshift($submits_data, $x); } foreach ($submits_data as $i=>$quantity) { echo '[' . $i . ', ' . $quantity . '],'; } ?> ] } ]; var signups_options = { yaxis: { color: "#000", tickColor: "#e6eff6", tickDecimals: 0, min: 0, }, xaxis: { color: "#000", tickColor: "#e6eff6", min: 0, tickSize: 30, ticks: [ <?php if ($stats_range <= 60) { for ($i = 0; $i < $stats_range; $i++) { $date = explode('-', date('Y-m-d', strtotime('-' . $i . ' days'))); echo '[' . (($stats_range - 1) - $i) . ', \'' . $date[1] . '/' . $date[2] . '\'],'; } } ?> ] }, legend: { show: true, margin: 10, backgroundOpacity: 0.5, }, grid: { hoverable: true, clickable: true, aboveData: false, backgroundColor: null, color: "rgba(87, 147, 195, 0.5)", borderColor: "#444", }, interaction: { }, points: { show: true, radius: 3, }, lines: { show: true, fill: true, fillColor: "rgba(87, 147, 195, 0.4)", }, }; var ois_signups_plot = $("#ois_signups_plot"); $.plot( ois_signups_plot , signups_data, signups_options ); // For impressions var impressions_data = [ { color: '#5793c3', label: "Number of Impressions", data: [ <?php // Data for Impressions $impression_data = array(); for ($i = 0; $i < $stats_range; $i++) { $x = 0; // for each day if (!empty($impressions)) { foreach ($impressions as $impression) { // go through all impressions if (strtotime($impression['t']) < strtotime('-' . $i . ' days') && strtotime($impression['t']) > strtotime('-' . ($i + 1) . ' days')) { // if within this day $x++; } } } array_unshift($impression_data, $x); } foreach ($impression_data as $i=>$quantity) { echo '[' . $i . ', ' . $quantity . '],'; } ?> ] } ]; var impressions_options = { yaxis: { tickDecimals: 0, min: 0, color: "#000", tickColor: "#e6eff6", }, xaxis: { color: "#000", tickColor: "#e6eff6", min: 0, ticks: [ <?php if ($stats_range <= 60) { for ($i = 0; $i < $stats_range; $i++) { $date = explode('-', date('Y-m-d', strtotime('-' . $i . ' days'))); echo '[' . (($stats_range - 1) - $i) . ', \'' . $date[1] . '/' . $date[2] . '\'],'; } } ?> ] }, legend: { show: true, margin: 10, backgroundOpacity: 0.5, }, grid: { hoverable: true, clickable: true, aboveData: false, }, interaction: { }, points: { show: true, radius: 3, }, lines: { show: true, fill: true, fillColor: "rgba(87, 147, 195, 0.4)", }, }; var ois_impressions_plot = $("#ois_impressions_plot"); $.plot( ois_impressions_plot , impressions_data, impressions_options ); // For Conversions var conversions_data = [ { color: '#5793c3', label: "Conversion Rates", data: [ <?php // Data for Conversions if (!empty($impression_data)) { foreach ($impression_data as $i=>$quantity) { if ($quantity > 0) { $rate = $submits_data[$i]/$quantity; echo '[' . $i . ', ' . ($rate * 100) . '],';; } else { echo '[' . $i . ', 0],'; } } } ?> ] } ]; var conversions_options = { yaxis: { min: 0, color: "#000", tickColor: "#e6eff6", tickDecimals: 2, }, xaxis: { color: "#000", tickColor: "#e6eff6", min: 0, ticks: [ <?php if ($stats_range <= 60) { for ($i = 0; $i < $stats_range; $i++) { $date = explode('-', date('Y-m-d', strtotime('-' . $i . ' days'))); echo '[' . (($stats_range - 1) - $i) . ', \'' . $date[1] . '/' . $date[2] . '\'],'; } } ?> ] }, legend: { show: true, margin: 10, backgroundOpacity: 0.5, }, grid: { hoverable: true, clickable: true, aboveData: false, }, interaction: { }, points: { show: true, radius: 3, }, lines: { show: true, fill: true, fillColor: "rgba(87, 147, 195, 0.4)", }, }; var ois_conversions_plot = $("#ois_conversions_plot"); $.plot( ois_conversions_plot , conversions_data, conversions_options ); function ois_stat_showTooltip(x, y, contents) { $('<div id="tooltip">' + contents + '</div>').css( { position: 'absolute', display: 'none', top: y + 5, left: x + 5, border: '1px solid #fdd', padding: '2px', 'background-color': '#fee', opacity: 0.80 }).appendTo("body").fadeIn(200); } var previousPoint = null; $("#ois_plotarea").bind("plothover", function (event, pos, item) { $("#x").text(pos.x); $("#y").text(pos.y); if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0], y = item.datapoint[1]; ois_stat_showTooltip(item.pageX, item.pageY, y); } } else { $("#tooltip").remove(); previousPoint = null; } }); $('#ois_a_impressions').click(function() { $('#ois_chart_title').text('Impressions in the Last <?php echo $stats_range; ?> Days'); $('.ois_plotarea').hide(); $('#ois_impressions_plot').show(); }); $('#ois_a_signups').click(function() { $('#ois_chart_title').text('Signups in the Last <?php echo $stats_range; ?> Days'); $('.ois_plotarea').hide(); $('#ois_signups_plot').show(); }); $('#ois_a_conversions').click(function() { $('#ois_chart_title').text('Conversion Rates in the Last <?php echo $stats_range; ?> Days'); $('.ois_plotarea').hide(); $('#ois_conversions_plot').show(); }); $('.ois_plotarea').hide(); $('#ois_signups_plot').show(); $('.ois_vis_a').click(function () { $('.ois_vis_a_active').removeClass('ois_vis_a_active'); $(this).parent().addClass('ois_vis_a_active'); }); $('.ois_code_snippet').click(function () { selectText($(this).attr('id')); }); function selectText(element) { var doc = document; var text = doc.getElementById(element); if (doc.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(text); range.select(); } else if (window.getSelection) { var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(text); selection.removeAllRanges(); selection.addRange(range); } } }); </script> <table class="widefat" style="width:95%; margin-bottom:10px;"> <thead> <th id="ois_chart_title">Signups in the Last <?php echo $stats_range; ?> Days</th> </thead> <tbody> <tr class="alternate"> <td> <div id="ois_signups_plot" class="ois_plotarea"> <div style="text-align:center;"> <p> <img style="width: 80px;" src="<?php echo WP_PLUGIN_URL; ?>/OptinSkin/admin/images/circle_load.gif" /> </p> <p>Loading a Visualization of Your Data...</p> </div> </div> <div id="ois_impressions_plot" class="ois_plotarea"> </div> <div id="ois_conversions_plot" class="ois_plotarea"> </div> </td> </tr> <tr> <td> <div class="ois_stat_options"> <strong>Visualize Statistics: </strong> <span class="ois_stats_option ois_vis_a_active"> <a href="javascript:void();" id="ois_a_signups" class="ois_vis_a">Signups</a> </span> <span class="ois_stats_option"> <a href="javascript:void();" id="ois_a_impressions" class="ois_vis_a">Impressions</a> </span> <span class="ois_stats_option"> <a href="javascript:void();" id="ois_a_conversions" class="ois_vis_a">Conversion Rate</a> </span> <?php $useable_uri = explode('&range=', $_SERVER['REQUEST_URI']); $days = array(20, 30, 60, 90); $days = array_reverse($days); foreach ($days as $day) { echo '<span class="ois_stats_days_option '; if ($stats_range == $day) { echo 'ois_stats_days_a_active'; } echo '" style="float:right;margin-top:-7px;"> <a href="' . $useable_uri[0] . '&range=' . $day . '" id="ois_a_lol" class="ois_stats_days_a ">' . $day . ' Days</a> </span>'; } ?> </div> </td> </tr> </tbody> </table> <div class="wrapper"> <div class="ois_column_left"> <?php /* ois_start_stat_table(array ('title' => '10 Ten Referring Websites', 'first_sub_style' => 'style="width:150px;"', 'subs' => array ('Domain', '1 Day', '7 Days', '30 Days', 'All Time'), 'data' => array ( 'google.com' => array(2, 3, 2, 4), ), ) ); </tbody> </table>*/ // Top Posts $post_stats_submits = array(); $post_stats_impressions = array(); $all_posts = get_posts(); if (!empty($all_posts)) { foreach ($all_posts as $post) { $post_id = $post->ID; $post_stats_submits[$post_id] = 0; $post_stats_impressions[$post_id] = 0; foreach ($submits as $submit) { if ($submit['p'] == $post_id) { $post_stats_submits[$post_id]++; } } foreach ($impressions as $impression) { if ($impression['p'] == $post_id) { $post_stats_impressions[$post_id]++; } } } } asort($post_stats_impressions); $post_stats_impressions = array_reverse($post_stats_impressions, true); asort($post_stats_submits); $post_stats_submits = array_reverse($post_stats_submits, true); ?> <table class="widefat ois_stats_table"> <thead> <th>Top 10 Posts</th> <th>Signups</th> <th>Impressions</th> <th>Conversion Rate</th> </thead> <tbody> <?php $count = 0; $max_count = 10; if (!empty($post_stats_submits)) { foreach ($post_stats_submits as $post_num=>$stats) { if ($count < $max_count) { $this_post = get_post($post_num); if (strlen($this_post->post_title) > 26) { $title = substr($this_post->post_title, 0, 26) . '...'; } else { $title = $this_post->post_title; } if ($post_stats_impressions[$post_num]) { $num_imp = $post_stats_impressions[$post_num]; } else { $num_imp = 0; } // conversion rate if ($num_imp > 0) { $rate = round(($stats/$num_imp * 100), 1); } else { $rate = 0; } echo '<tr>'; echo '<th scope="row"><a href="' . $this_post->guid . '">' . $title . '</a></th>'; echo '<td>' . $stats . '</td>'; echo '<td>' . $num_imp . '</td>'; echo '<td>' . $rate . '%</td>'; echo '</tr>'; $count++; } else { break; } } } ?> </tbody> </table> </td> </tr> </tbody> </table> </div> <div class="ois_column_right"> <table class="widefat" style="margin-bottom: 10px; margin-top: 10px;"> <thead> <tr> <th>Actions for Skin</th> </tr> </thead> <tbody> <tr class="alternate"> <td> <p style="padding-top:5px;"> <a class="ois_skin_action" href="<?php echo $edit_url; ?>">Edit Skin</a> | <a class="ois_skin_action" href="<?php echo wp_nonce_url( $_SERVER['REQUEST_URI'], 'trash'); ?>&delete=<?php echo $skin['id']; ?>">Move to Trash</a> | <a href="<?php echo wp_nonce_url( $_SERVER['REQUEST_URI'], 'draft'); ?>&draft=<?php echo $skin['id']; ?>">Move to Drafts</a></p> </td> </tr> </tbody> </table> </div> <?php $num_data = get_option('ois_cleanup_period'); if (!$num_data) { $num_data = 31; // 31 is default. update_option('ois_cleanup_period', $num_data); } ?> </div> <?php ois_section_end(); ?> <div style="clear:both"></div> <p style="padding: 8px; text-align:center; margin: 45px 0 0 0; -webkit-box-shadow: rgba(0, 0, 0, 0.199219) 1px 2px 3px 1px; box-shadow: rgba(0, 0, 0, 0.199219) 1px 2px 3px 1px; background-color: #FCFCFC;"> <em>Note:</em> statistics are only kept in the database for <?php echo $num_data; ?> days, so as not to slow down the system. You can change this option in your OptinSkin&trade; settings. </p> <?php } function ois_start_stat_table($attr) { ?> <table class="widefat" style="margin-top:15px;"> <thead> <tr> <th <?php $title_style; ?>> <?php echo $attr['title']; ?> </th> </tr> </thead> <tbody> <tr> <td> <table> <thead> <tr> <?php $i; foreach ($attr['subs'] as $sub) { if ($i == 0) { echo '<th ' . $attr['first_sub_style'] . ' >'; } else { echo '<th>'; } echo $sub . '</th>'; $i++; } ?> </tr> </thead> <tbody> <?php foreach ($attr['data'] as $name=>$data) { echo '<tr>'; echo '<th scope="row">' . $name . '</th>'; foreach ($data as $datum) { echo '<td>' . $datum . '</td>'; } echo '</tr>'; } ?> </tbody> </table> </td> </tr> </tbody> </table> <?php } } } ?>
User1m/livefundstarter
wp-content/plugins/OptinSkin/admin/admin_edit_skin.php
PHP
gpl-2.0
19,920
<?php /** * @package Gantry5 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2021 RocketTheme, LLC * @license Dual License: MIT or GNU/GPLv2 and later * * http://opensource.org/licenses/MIT * http://www.gnu.org/licenses/gpl-2.0.html * * Gantry Framework code that extends GPL code is considered GNU/GPLv2 and later */ namespace Gantry\Component\Twig\TokenParser; use Twig\Token; /** * Adds stylesheets to document. * * {% styles with { priority: 2 } %} * <link rel="stylesheet" href="{{ url('gantry-assets://css/font-awesome.min.css') }}" type="text/css"/> * {% endstyles -%} */ class TokenParserStyles extends TokenParserAssets { /** * @param Token $token * @return bool */ public function decideBlockEnd(Token $token) { return $token->test('endstyles'); } /** * Gets the tag name associated with this token parser. * * @return string The tag name */ public function getTag() { return 'styles'; } }
emundus/v6
libraries/gantry5/src/classes/Gantry/Component/Twig/TokenParser/TokenParserStyles.php
PHP
gpl-2.0
1,048
/*FreeMind - A Program for creating and viewing Mindmaps *Copyright (C) 2000-2011 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitri Polivaev and others. * *See COPYING for Details * *This program is free software; you can redistribute it and/or *modify it under the terms of the GNU General Public License *as published by the Free Software Foundation; either version 2 *of the License, or (at your option) any later version. * *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 plugins.map; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JDialog; import javax.swing.Timer; import org.openstreetmap.gui.jmapviewer.Coordinate; import org.openstreetmap.gui.jmapviewer.JMapViewer; import org.openstreetmap.gui.jmapviewer.Tile; import org.openstreetmap.gui.jmapviewer.TileController; import org.openstreetmap.gui.jmapviewer.interfaces.TileCache; import org.openstreetmap.gui.jmapviewer.interfaces.TileLoaderListener; import org.openstreetmap.gui.jmapviewer.interfaces.TileSource; import freemind.main.FreeMind; import freemind.main.Resources; import freemind.modes.mindmapmode.MindMapController; /** * @author foltin * @date 24.10.2011 */ final class JCursorMapViewer extends JMapViewer { private static final class ScalableTileController extends TileController { private ScalableTileController(TileSource pSource, TileCache pTileCache, TileLoaderListener pListener) { super(pSource, pTileCache, pListener); } @Override public Tile getTile(int tilex, int tiley, int zoom) { int max = (1 << zoom); if (tilex < 0 || tilex >= max || tiley < 0 || tiley >= max) return null; Tile tile = tileCache.getTile(tileSource, tilex, tiley, zoom); if (tile == null) { int scale = Resources.getInstance().getIntProperty(FreeMind.SCALING_FACTOR_PROPERTY, 100); if(scale >= 200){ tile = new ScaledTile(this, tileSource, tilex, tiley, zoom); } else { tile = new Tile(tileSource, tilex, tiley, zoom); } tileCache.addTile(tile); tile.loadPlaceholderFromCache(tileCache); } return super.getTile(tilex, tiley, zoom); } } private static final class ScaledTile extends Tile { private BufferedImage scaledImage = null; private TileController tileController; private ScaledTile(TileController pTileController, TileSource pSource, int pXtile, int pYtile, int pZoom) { super(pSource, pXtile, pYtile, pZoom); tileController = pTileController; } @Override public void paint(Graphics pG, int pX, int pY) { if(scaledImage == null){ int xtile_low = xtile >> 1; int ytile_low = ytile >> 1; Tile tile = tileController.getTile(xtile_low, ytile_low, zoom-1); if (tile != null && tile.isLoaded()) { int tileSize = source.getTileSize(); int translate_x = (xtile % 2) * tileSize/2; int translate_y = (ytile % 2) * tileSize/2; BufferedImage image2 = tile.getImage(); scaledImage = new BufferedImage(tileSize, tileSize, image2.getType()); Graphics2D g = scaledImage.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(image2, 0, 0, scaledImage.getWidth(), scaledImage.getHeight(), translate_x, translate_y, translate_x+tileSize/2, translate_y+tileSize/2, null); g.dispose(); } } if(scaledImage != null){ pG.drawImage(scaledImage, pX, pY, null); } else { pG.drawImage(getImage(), pX, pY, null); } } } boolean mShowCursor; boolean mUseCursor; Coordinate mCursorPosition; Stroke mStroke; Stroke mRectangularStroke = new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 10.0f, new float[] { 10.0f, 10.0f }, 0.0f); private FreeMindMapController mFreeMindMapController; private final MapDialog mMapHook; private boolean mHideFoldedNodes = true; private Coordinate mRectangularStart; private Coordinate mRectangularEnd; private boolean mDrawRectangular = false; private int mCursorLength; /** * @param pMindMapController * @param pMapDialog * @param pMapHook * */ public JCursorMapViewer(MindMapController pMindMapController, JDialog pMapDialog, TileCache pTileCache, MapDialog pMapHook) { super(pTileCache, 8); tileController = new ScalableTileController(tileSource, pTileCache, this); int scaleProperty = Resources.getInstance().getIntProperty(FreeMind.SCALING_FACTOR_PROPERTY, 100); mCursorLength = 15 * scaleProperty/100; mStroke = new BasicStroke(2 * scaleProperty / 100); mMapHook = pMapHook; mFreeMindMapController = new FreeMindMapController(this, pMindMapController, pMapDialog, pMapHook); Action updateCursorAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { mShowCursor = !mShowCursor; repaint(); } }; new Timer(1000, updateCursorAction).start(); setFocusable(false); } public FreeMindMapController getFreeMindMapController() { return mFreeMindMapController; } public boolean isUseCursor() { return mUseCursor; } public void setUseCursor(boolean pUseCursor) { mUseCursor = pUseCursor; repaint(); } public Coordinate getCursorPosition() { return mCursorPosition; } public void setCursorPosition(Coordinate pCursorPosition) { mCursorPosition = pCursorPosition; repaint(); } /* * (non-Javadoc) * * @see * org.openstreetmap.gui.jmapviewer.JMapViewer#paintComponent(java.awt.Graphics * ) */ protected void paintComponent(Graphics g) { super.paintComponent(g); if (g instanceof Graphics2D) { Graphics2D g2d = (Graphics2D) g; Stroke oldStroke = g2d.getStroke(); Color oldColor = g2d.getColor(); // do cursor if (mUseCursor && mShowCursor) { Point position = getMapPosition(mCursorPosition); if (position != null) { int size_h = mCursorLength; g2d.setStroke(mStroke); g2d.setColor(Color.RED); g2d.drawLine(position.x - size_h, position.y, position.x + size_h, position.y); g2d.drawLine(position.x, position.y - size_h, position.x, position.y + size_h); } } if (mDrawRectangular) { g2d.setColor(Color.BLACK); g2d.setStroke(mRectangularStroke); Rectangle r = getRectangle(mRectangularStart, mRectangularEnd); if (r != null) { g2d.drawRect(r.x, r.y, r.width, r.height); } } g2d.setColor(oldColor); g2d.setStroke(oldStroke); } } public Rectangle getRectangle(Coordinate rectangularStart, Coordinate rectangularEnd) { Point positionStart = getMapPosition(rectangularStart); Point positionEnd = getMapPosition(rectangularEnd); Rectangle r = null; if (positionStart != null && positionEnd != null) { int x = Math.min(positionStart.x, positionEnd.x); int y = Math.min(positionStart.y, positionEnd.y); int width = Math.abs(positionStart.x - positionEnd.x); int height = Math.abs(positionStart.y - positionEnd.y); r = new Rectangle(x, y, width, height); } return r; } public TileController getTileController() { return tileController; } /* (non-Javadoc) * @see org.openstreetmap.gui.jmapviewer.JMapViewer#initializeZoomSlider() */ protected void initializeZoomSlider() { super.initializeZoomSlider(); //focus zoomSlider.setFocusable(false); zoomInButton.setFocusable(false); zoomOutButton.setFocusable(false); } /** * @param pHideFoldedNodes */ public void setHideFoldedNodes(boolean pHideFoldedNodes) { mHideFoldedNodes = pHideFoldedNodes; repaint(); } public boolean isHideFoldedNodes() { return mHideFoldedNodes; } public void setRectangular(Coordinate pRectangularStart, Coordinate pRectangularEnd) { mRectangularStart = pRectangularStart; mRectangularEnd = pRectangularEnd; } public boolean isDrawRectangular() { return mDrawRectangular; } public void setDrawRectangular(boolean pDrawRectangular) { mDrawRectangular = pDrawRectangular; } /** * @param pMapCenterLatitude * @param pMapCenterLongitude * @param pZoom */ public void setDisplayPositionByLatLon(double pMapCenterLatitude, double pMapCenterLongitude, int pZoom) { super.setDisplayPosition(new Coordinate(pMapCenterLatitude, pMapCenterLongitude), pZoom); } }
derekprovance/Freemind
plugins/map/JCursorMapViewer.java
Java
gpl-2.0
9,023
<?php /** * @package Yendif Player * @author Yendif Technologies Pvt Ltd. (email : admin@yendifplayer.com) * @license GPL-2.0+ * @link http://yendifplayer.com/ * @copyright 2014 Yendif Technologies Pvt Ltd. */ class Yendif_Player_Settings_View { /** * Instance of the model object. * * @since 1.0.0 * * @var object */ private $model = null; /** * Constructor of this class. * * @since 1.0.0 */ public function __construct( $model ) { $this->model = $model; } /** * Load the default layout * * @since 1.0.0 */ public function default_layout() { $item = $this->model->item(); include_once( 'tmpl/default.php' ); } }
AASP/cosmic-wordpress
wp-content/plugins/yendif-player/admin/views/settings/view.html.php
PHP
gpl-2.0
741
package io.github.dousha.randomCraft.randomcraft; import java.util.HashMap; // WHY DOESN'T JAVA HAVE A STRUCT public class ItemDescription implements Cloneable{ public boolean type; // false = in, true = out, I would use #define in c/c++! public String itemname; @Deprecated public int itemid; public boolean isMajor; public int leastAmount; public double base; public String formula; public double arg1, arg2, arg3; public boolean isMagic; // TODO: make it works public HashMap<String, String> enchantments; // <name, level> // ----^-----------------------^----------- public String giveMethod; @Override public Object clone(){ ItemDescription o = null; try{ o = (ItemDescription) super.clone(); } catch(CloneNotSupportedException ex){ ex.printStackTrace(); } return o; } }
dousha/MySpigotPlugins
RandomCraft/src/main/java/io/github/dousha/randomCraft/randomcraft/ItemDescription.java
Java
gpl-2.0
815
package fr.lelouet.rpg.model; import fr.lelouet.rpg.model.character.CharStats; public class Character extends CharStats { public Character(RPGGame system) { super(system); } /** * * @return true if this character is an avatar */ public boolean isPlayer() { return true; } public int lvl; }
glelouet/RPG
Model/src/main/java/fr/lelouet/rpg/model/Character.java
Java
gpl-2.0
312
<?php function eme_new_event() { $event = array ( "event_id" => '', "event_name" => '', "event_status" => get_option('eme_event_initial_state'), "event_start_date" => date("Y-m-d"), "event_start_time" => '', "event_end_date" => date("Y-m-d"), "event_end_time" => '', "event_notes" => '', "event_rsvp" => get_option('eme_rsvp_reg_for_new_events')? 1:0, "use_paypal" => get_option('eme_paypal_business')? 1:0, "use_2co" => get_option('eme_2co_business')? 1:0, "use_webmoney" => get_option('eme_webmoney_purse')? 1:0, "use_fdgg" => get_option('eme_fdgg_store_name')? 1:0, "use_mollie" => get_option('eme_mollie_api_key')? 1:0, "price" => get_option('eme_default_price'), "currency" => get_option('eme_default_currency'), "rsvp_number_days" => get_option('eme_rsvp_number_days'), "rsvp_number_hours" => get_option('eme_rsvp_number_hours'), "registration_requires_approval" => get_option('eme_rsvp_require_approval')? 1:0, "registration_wp_users_only" => get_option('eme_rsvp_registered_users_only')? 1:0, "event_seats" => get_option('eme_rsvp_default_number_spaces'), "location_id" => 0, "event_author" => 0, "event_contactperson_id" => get_option('eme_default_contact_person'), "event_category_ids" => '', "event_attributes" => array(), "event_properties" => array(), "event_page_title_format" => '', "event_single_event_format" => '', "event_contactperson_email_body" => '', "event_respondent_email_body" => '', "event_registration_pending_email_body" => '', "event_registration_updated_email_body" => '', "event_registration_form_format" => '', "event_cancel_form_format" => '', "event_registration_recorded_ok_html" => '', "event_slug" => '', "event_image_url" => '', "event_image_id" => 0, "event_external_ref" => '', "event_url" => '', "recurrence_id" => 0 ); $event['event_properties'] = eme_init_event_props($event['event_properties']); return $event; } function eme_init_event_props($props) { if (!isset($props['auto_approve'])) $props['auto_approve']=0; if (!isset($props['ignore_pending'])) $props['ignore_pending']=0; if (!isset($props['all_day'])) $props['all_day']=0; if (!isset($props['take_attendance'])) $props['take_attendance']=0; if (!isset($props['min_allowed'])) $props['min_allowed']=get_option('eme_rsvp_addbooking_min_spaces'); if (!isset($props['max_allowed'])) $props['max_allowed']=get_option('eme_rsvp_addbooking_max_spaces'); if (!isset($props['rsvp_end_target'])) $props['rsvp_end_target']=get_option('eme_rsvp_end_target'); $template_override=array('event_page_title_format_tpl','event_single_event_format_tpl','event_contactperson_email_body_tpl','event_registration_recorded_ok_html_tpl','event_respondent_email_body_tpl','event_registration_pending_email_body_tpl','event_registration_updated_email_body_tpl','event_registration_form_format_tpl','event_cancel_form_format_tpl'); foreach ($template_override as $template) { if (!isset($props[$template])) $props[$template]=0; } return $props; } function eme_new_event_page() { // check the user is allowed to make changes if ( !current_user_can( get_option('eme_cap_add_event') ) ) { return; } $title = __ ( "Insert New Event", 'eme' ); $event = eme_new_event(); if (isset($_GET['eme_admin_action']) && $_GET['eme_admin_action'] == "insert_event") { eme_events_page(); } else { eme_event_form ($event, $title, 0); } } function eme_events_page() { global $wpdb; $extra_conditions = array(); $action = isset($_GET['eme_admin_action']) ? $_GET['eme_admin_action'] : ''; $event_ID = isset($_GET['event_id']) ? intval($_GET['event_id']) : ''; $recurrence_ID = isset($_GET['recurrence_id']) ? intval($_GET['recurrence_id']) : ''; $selectedEvents = isset($_GET['events']) ? $_GET['events'] : ''; $current_userid=get_current_user_id(); // if the delete event button is pushed while editing an event, set the action if (isset($_POST['event_delete_button'])) { $selectedEvents=array($event_ID); $action = "deleteEvents"; } // if the delete recurrence button is pushed while editing a recurrence, set the action if (isset($_POST['event_deleteRecurrence_button'])) { $recurrence=eme_get_recurrence($recurrence_ID); $selectedEvents=array($recurrence['event_id']); $action = "deleteRecurrence"; } // in case some generic actions were taken (like disable hello or disable donate), ignore all other actions if (isset($_GET['disable_hello_to_user']) || isset($_GET['disable_donate_message']) || isset($_GET['dbupdate']) || isset($_GET['disable_legacy_warning'])) { $action =""; } if ($action == 'publicEvents') { if (current_user_can(get_option('eme_cap_edit_events'))) { eme_change_event_state($selectedEvents,STATUS_PUBLIC); $feedback_message = __ ( 'Event(s) published!', 'eme' ); } else { $feedback_message = __ ( 'You have no right to edit events!', 'eme' ); } eme_events_table ($feedback_message); return; } if ($action == 'privateEvents') { if (current_user_can(get_option('eme_cap_edit_events'))) { eme_change_event_state($selectedEvents,STATUS_PRIVATE); $feedback_message = __ ( 'Event(s) made private!', 'eme' ); } else { $feedback_message = __ ( 'You have no right to edit events!', 'eme' ); } eme_events_table ($feedback_message); return; } if ($action == 'draftEvents') { if (current_user_can(get_option('eme_cap_edit_events'))) { eme_change_event_state($selectedEvents,STATUS_DRAFT); $feedback_message = __ ( 'Event(s) changed to draft!', 'eme' ); } else { $feedback_message = __ ( 'You have no right to edit events!', 'eme' ); } eme_events_table ($feedback_message); return; } // DELETE action (either from the event list, or when the delete button is pushed while editing an event) if ($action == 'deleteEvents') { if (current_user_can(get_option('eme_cap_edit_events'))) { foreach ( $selectedEvents as $event_ID ) { $tmp_event = array(); $tmp_event = eme_get_event ( $event_ID ); if ($tmp_event['recurrence_id']>0) { # if the event is part of a recurrence and it is the last event of the recurrence, delete the recurrence # else just delete the singe event if (eme_recurrence_count($tmp_event['recurrence_id'])==1) { $tmp_recurrence=eme_get_recurrence($tmp_event['recurrence_id']); eme_db_delete_recurrence ($tmp_event,$tmp_recurrence ); } else { eme_db_delete_event($tmp_event); } } else { eme_db_delete_event($tmp_event); } } $feedback_message = __ ( 'Event(s) deleted!', 'eme' ); } else { $feedback_message = __ ( 'You have no right to delete events!', 'eme' ); } eme_events_table ($feedback_message); return; } // DELETE action (either from the event list, or when the delete button is pushed while editing a recurrence) if ($action == 'deleteRecurrence') { if (current_user_can(get_option('eme_cap_edit_events'))) { foreach ( $selectedEvents as $event_ID ) { $tmp_event = array(); $tmp_event = eme_get_event($event_ID); if ($tmp_event['recurrence_id']>0) { $tmp_recurrence=eme_get_recurrence($tmp_event['recurrence_id']); eme_db_delete_recurrence ($tmp_event,$tmp_recurrence ); } } $feedback_message = __ ( 'Event(s) deleted!', 'eme' ); } else { $feedback_message = __ ( 'You have no right to delete events!', 'eme' ); } eme_events_table ($feedback_message); return; } // UPDATE or CREATE action if ($action == 'insert_event' || $action == 'update_event' || $action == 'update_recurrence') { if ( ! (current_user_can( get_option('eme_cap_add_event')) || current_user_can( get_option('eme_cap_edit_events'))) ) { $feedback_message = __('You have no right to insert or update events','eme'); eme_events_table ($feedback_message); return; } $event = array(); $location = eme_new_location (); $event['event_name'] = isset($_POST['event_name']) ? trim(stripslashes ( $_POST['event_name'] )) : ''; if (!current_user_can( get_option('eme_cap_publish_event')) ) { $event['event_status']=STATUS_DRAFT; } else { $event['event_status'] = isset($_POST['event_status']) ? stripslashes ( $_POST['event_status'] ) : get_option('eme_event_initial_state'); } $event['event_start_date'] = isset($_POST['event_start_date']) ? $_POST['event_start_date'] : ''; // for compatibility: check also the POST variable event_date $event['event_start_date'] = isset($_POST['event_date']) ? $_POST['event_date'] : $event['event_start_date']; $event['event_end_date'] = isset($_POST['event_end_date']) ? $_POST['event_end_date'] : ''; if (!_eme_is_date_valid($event['event_start_date'])) $event['event_start_date'] = ""; if (!_eme_is_date_valid($event['event_end_date'])) $event['event_end_date'] = ""; if (isset($_POST['event_start_time']) && !empty($_POST['event_start_time'])) { $event['event_start_time'] = date ("H:i:00", strtotime ($_POST['event_start_time'])); } else { $event['event_start_time'] = "00:00:00"; } if (isset($_POST['event_end_time']) && !empty($_POST['event_end_time'])) { $event['event_end_time'] = date ("H:i:00", strtotime ($_POST['event_end_time'])); } else { $event['event_end_time'] = "00:00:00"; } $recurrence['recurrence_freq'] = isset($_POST['recurrence_freq']) ? $_POST['recurrence_freq'] : ''; if ($recurrence['recurrence_freq'] == 'specific') { $recurrence['recurrence_specific_days'] = isset($_POST['recurrence_start_date']) ? $_POST['recurrence_start_date'] : $event['event_start_date']; $recurrence['recurrence_start_date'] = ""; $recurrence['recurrence_end_date'] = ""; } else { $recurrence['recurrence_specific_days'] = ""; $recurrence['recurrence_start_date'] = isset($_POST['recurrence_start_date']) ? $_POST['recurrence_start_date'] : $event['event_start_date']; $recurrence['recurrence_end_date'] = isset($_POST['recurrence_end_date']) ? $_POST['recurrence_end_date'] : $event['event_end_date']; } if (!_eme_is_date_valid($recurrence['recurrence_start_date'])) $recurrence['recurrence_start_date'] = ""; if (!_eme_is_date_valid($recurrence['recurrence_end_date'])) $recurrence['recurrence_end_date'] = $recurrence['recurrence_start_date']; if (!_eme_are_dates_valid($recurrence['recurrence_specific_days'])) $recurrence['recurrence_specific_days'] = ""; if ($recurrence['recurrence_freq'] == 'weekly') { if (isset($_POST['recurrence_bydays'])) { $recurrence['recurrence_byday'] = implode ( ",", $_POST['recurrence_bydays']); } else { $recurrence['recurrence_byday'] = ''; } } else { if (isset($_POST['recurrence_byday'])) { $recurrence['recurrence_byday'] = $_POST['recurrence_byday']; } else { $recurrence['recurrence_byday'] = ''; } } $recurrence['recurrence_interval'] = isset($_POST['recurrence_interval']) ? $_POST['recurrence_interval'] : 1; if ($recurrence['recurrence_interval'] ==0) $recurrence['recurrence_interval']=1; $recurrence['recurrence_byweekno'] = isset($_POST['recurrence_byweekno']) ? $_POST['recurrence_byweekno'] : ''; $event['event_rsvp'] = (isset ($_POST['event_rsvp']) && is_numeric($_POST['event_rsvp'])) ? $_POST['event_rsvp']:0; $event['rsvp_number_days'] = (isset ($_POST['rsvp_number_days']) && is_numeric($_POST['rsvp_number_days'])) ? $_POST['rsvp_number_days']:0; $event['rsvp_number_hours'] = (isset ($_POST['rsvp_number_hours']) && is_numeric($_POST['rsvp_number_hours'])) ? $_POST['rsvp_number_hours']:0; $event['registration_requires_approval'] = (isset ($_POST['registration_requires_approval']) && is_numeric($_POST['registration_requires_approval'])) ? $_POST['registration_requires_approval']:0; $event['registration_wp_users_only'] = (isset ($_POST['registration_wp_users_only']) && is_numeric($_POST['registration_wp_users_only'])) ? $_POST['registration_wp_users_only']:0; $event['event_seats'] = isset ($_POST['event_seats']) ? $_POST['event_seats']:0; if (preg_match("/\|\|/",$event['event_seats'])) { $multiseat=preg_split("/\|\|/",$event['event_seats']); foreach ($multiseat as $key=>$value) { if (!is_numeric($value)) $multiseat[$key]=0; } $event['event_seats'] = eme_convert_array2multi($multiseat); } else { if (!is_numeric($event['event_seats'])) $event['event_seats'] = 0; } $event['use_paypal'] = (isset ($_POST['use_paypal']) && is_numeric($_POST['use_paypal'])) ? $_POST['use_paypal']:0; $event['use_2co'] = (isset ($_POST['use_2co']) && is_numeric($_POST['use_2co'])) ? $_POST['use_2co']:0; $event['use_webmoney'] = (isset ($_POST['use_webmoney']) && is_numeric($_POST['use_webmoney'])) ? $_POST['use_webmoney']:0; $event['use_fdgg'] = (isset ($_POST['use_fdgg']) && is_numeric($_POST['use_fdgg'])) ? $_POST['use_fdgg']:0; $event['use_mollie'] = (isset ($_POST['use_mollie']) && is_numeric($_POST['use_mollie'])) ? $_POST['use_mollie']:0; $event['price'] = isset ($_POST['price']) ? $_POST['price']:0; if (preg_match("/\|\|/",$event['price'])) { $multiprice=preg_split("/\|\|/",$event['price']); foreach ($multiprice as $key=>$value) { if (!is_numeric($value)) $multiprice[$key]=0; } $event['price'] = eme_convert_array2multi($multiprice); } else { if (!is_numeric($event['price'])) $event['price'] = 0; } $event['currency'] = isset ($_POST['currency']) ? $_POST['currency']:""; if (isset ( $_POST['event_contactperson_id'] ) && $_POST['event_contactperson_id'] != '') { $event['event_contactperson_id'] = $_POST['event_contactperson_id']; } else { $event['event_contactperson_id'] = 0; } //if (! _eme_is_time_valid ( $event_end_time )) // $event_end_time = $event_start_time; $location['location_name'] = isset($_POST['location_name']) ? trim(stripslashes($_POST['location_name'])) : ''; $location['location_address'] = isset($_POST['location_address']) ? stripslashes($_POST['location_address']) : ''; $location['location_town'] = isset($_POST['location_town']) ? stripslashes($_POST['location_town']) : ''; $location['location_latitude'] = isset($_POST['location_latitude']) ? $_POST['location_latitude'] : ''; $location['location_longitude'] = isset($_POST['location_longitude']) ? $_POST['location_longitude'] : ''; $location['location_author']=$current_userid; $location['location_description'] = ""; //switched to WP TinyMCE field //$event['event_notes'] = stripslashes ( $_POST['event_notes'] ); $event['event_notes'] = isset($_POST['content']) ? stripslashes($_POST['content']) : ''; $event['event_page_title_format'] = isset($_POST['event_page_title_format']) ? stripslashes ( $_POST['event_page_title_format'] ) : ''; $event['event_single_event_format'] = isset($_POST['event_single_event_format']) ? stripslashes ( $_POST['event_single_event_format'] ) : ''; $event['event_contactperson_email_body'] = isset($_POST['event_contactperson_email_body']) ? stripslashes ( $_POST['event_contactperson_email_body'] ) : ''; $event['event_registration_recorded_ok_html'] = isset($_POST['event_registration_recorded_ok_html']) ? stripslashes ( $_POST['event_registration_recorded_ok_html'] ) : ''; $event['event_respondent_email_body'] = isset($_POST['event_respondent_email_body']) ? stripslashes ( $_POST['event_respondent_email_body'] ) : ''; $event['event_registration_pending_email_body'] = isset($_POST['event_registration_pending_email_body']) ? stripslashes ( $_POST['event_registration_pending_email_body'] ) : ''; $event['event_registration_updated_email_body'] = isset($_POST['event_registration_updated_email_body']) ? stripslashes ( $_POST['event_registration_updated_email_body'] ) : ''; $event['event_registration_form_format'] = isset($_POST['event_registration_form_format']) ? stripslashes ( $_POST['event_registration_form_format'] ) : ''; $event['event_cancel_form_format'] = isset($_POST['event_cancel_form_format']) ? stripslashes ( $_POST['event_cancel_form_format'] ) : ''; $event['event_url'] = isset($_POST['event_url']) ? eme_strip_tags ( $_POST['event_url'] ) : ''; $event['event_image_url'] = isset($_POST['event_image_url']) ? eme_strip_tags ( $_POST['event_image_url'] ) : ''; $event['event_image_id'] = isset($_POST['event_image_id']) ? intval ( $_POST['event_image_id'] ) : 0; $event['event_slug'] = isset($_POST['event_slug']) ? eme_permalink_convert(eme_strip_tags ( $_POST['event_slug'] )) : eme_permalink_convert($event['event_name']); if (isset ($_POST['event_category_ids'])) { // the category id's need to begin and end with a comma // this is needed so we can later search for a specific // cat using LIKE '%,$cat,%' $event['event_category_ids']=""; foreach ($_POST['event_category_ids'] as $cat) { if (is_numeric($cat)) { if (empty($event['event_category_ids'])) { $event['event_category_ids'] = "$cat"; } else { $event['event_category_ids'] .= ",$cat"; } } } } else { $event['event_category_ids']=""; } $event_attributes = array(); for($i=1 ; isset($_POST["mtm_{$i}_ref"]) && trim($_POST["mtm_{$i}_ref"])!='' ; $i++ ) { if(trim($_POST["mtm_{$i}_name"]) != '') { $event_attributes[$_POST["mtm_{$i}_ref"]] = stripslashes($_POST["mtm_{$i}_name"]); } } $event['event_attributes'] = serialize($event_attributes); $event_properties = array(); $event_properties = eme_init_event_props($event_properties); foreach($_POST as $key=>$value) { if (preg_match('/eme_prop_(.+)/', $key, $matches)) { $event_properties[$matches[1]] = stripslashes($value); } } $event['event_properties'] = serialize($event_properties); $validation_result = eme_validate_event ( $event ); if ($validation_result != "OK") { // validation unsuccessful echo "<div id='message' class='error '> <p>" . __ ( "Ach, there's a problem here:", "eme" ) . " $validation_result</p> </div>"; eme_event_form ( $event, "Edit event $event_ID", $event_ID ); return; } // validation successful if(isset($_POST['location-select-id']) && $_POST['location-select-id'] != "") { $event['location_id'] = $_POST['location-select-id']; } else { if (empty($location['location_name']) && empty($location['location_address']) && empty($location['location_town'])) { $event['location_id'] = 0; } else { $related_location = eme_get_identical_location ( $location ); // print_r($related_location); if ($related_location) { $event['location_id'] = $related_location['location_id']; } else { $new_location = eme_insert_location ( $location ); if (!$new_location) { echo "<div id='message' class='error '> <p>" . __ ( "Could not create the new location for this event: either you don't have the right to insert locations or there's a DB problem.", "eme" ) . "</p> </div>"; return; } $event['location_id'] = $new_location['location_id']; } } } if (! $event_ID && ! $recurrence_ID) { $event['event_author']=$current_userid; // new event or new recurrence if (isset($_POST['repeated_event']) && $_POST['repeated_event']) { //insert new recurrence if (!eme_db_insert_recurrence ( $event, $recurrence )) { $feedback_message = __ ( 'Database insert failed!', 'eme' ); } else { $feedback_message = __ ( 'New recurrent event inserted!', 'eme' ); //if (has_action('eme_insert_event_action')) do_action('eme_insert_event_action',$event); } } else { // INSERT new event if (!eme_db_insert_event($event)) { $feedback_message = __ ( 'Database insert failed!', 'eme' ); } else { $feedback_message = __ ( 'New event successfully inserted!', 'eme' ); } } } else { // something exists if ($recurrence_ID) { $tmp_recurrence = eme_get_recurrence ( $recurrence_ID ); if (current_user_can( get_option('eme_cap_edit_events')) || (current_user_can( get_option('eme_cap_author_event')) && ($tmp_recurrence['event_author']==$current_userid || $tmp_recurrence['event_contactperson_id']==$current_userid))) { // UPDATE old recurrence $recurrence['recurrence_id'] = $recurrence_ID; //print_r($recurrence); if (eme_db_update_recurrence ($event, $recurrence )) { $feedback_message = __ ( 'Recurrence updated!', 'eme' ); //if (has_action('eme_update_event_action')) do_action('eme_update_event_action',$event); } else { $feedback_message = __ ( 'Something went wrong with the recurrence update...', 'eme' ); } } else { $feedback_message = sprintf(__("You have no right to update '%s'",'eme'),$tmp_event['event_name']); } } else { $tmp_event = eme_get_event ( $event_ID ); if (current_user_can( get_option('eme_cap_edit_events')) || (current_user_can( get_option('eme_cap_author_event')) && ($tmp_event['event_author']==$current_userid || $tmp_event['event_contactperson_id']==$current_userid))) { if (isset($_POST['repeated_event']) && $_POST['repeated_event']) { // we go from single event to recurrence: create the recurrence and delete the single event eme_db_insert_recurrence ( $event, $recurrence ); eme_db_delete_event ( $tmp_event ); $feedback_message = __ ( 'New recurrent event inserted!', 'eme' ); //if (has_action('eme_insert_event_action')) do_action('eme_insert_event_action',$event); } else { // UPDATE old event // unlink from recurrence in case it was generated by one $event['recurrence_id'] = 0; if (eme_db_update_event ($event,$event_ID)) { $feedback_message = sprintf(__("Updated '%s'",'eme'),$event['event_name']); } else { $feedback_message = sprintf(__("Failed to update '%s'",'eme'),$event['event_name']); } //if (has_action('eme_update_event_action')) do_action('eme_update_event_action',$event); } } else { $feedback_message = sprintf(__("You have no right to update '%s'",'eme'),$tmp_event['event_name']); } } } //$wpdb->query($sql); eme_events_table ($feedback_message); return; } if ($action == 'edit_event') { if (! $event_ID) { if (current_user_can( get_option('eme_cap_add_event'))) { $title = __ ( "Insert New Event", 'eme' ); eme_event_form ( $event, $title, $event_ID ); } else { $feedback_message = __('You have no right to add events!','eme'); eme_events_table ($feedback_message); } } else { $event = eme_get_event ( $event_ID ); if (current_user_can( get_option('eme_cap_edit_events')) || (current_user_can( get_option('eme_cap_author_event')) && ($event['event_author']==$current_userid || $event['event_contactperson_id']==$current_userid))) { // UPDATE event $title = sprintf(__("Edit Event '%s'",'eme'),$event['event_name']); eme_event_form ( $event, $title, $event_ID ); } else { $feedback_message = sprintf(__("You have no right to update '%s'",'eme'),$event['event_name']); eme_events_table ($feedback_message); } } return; } //Add duplicate event if requested if ($action == 'duplicate_event') { $event = eme_get_event ( $event_ID ); // make it look like a new event unset($event['event_id']); unset($event['recurrence_id']); $event['event_name'].= __(" (Copy)","eme"); if (current_user_can( get_option('eme_cap_edit_events')) || (current_user_can( get_option('eme_cap_author_event')) && ($event['event_author']==$current_userid || $event['event_contactperson_id']==$current_userid))) { $title = sprintf(__("Edit event copy '%s'",'eme'),$event['event_name']); eme_event_form ( $event, $title, 0 ); } else { $feedback_message = sprintf(__("You have no right to copy '%s'",'eme'),$event['event_name']); eme_events_table ($feedback_message); } return; } if ($action == 'edit_recurrence') { $recurrence = eme_get_recurrence ( $recurrence_ID ); if (current_user_can( get_option('eme_cap_edit_events')) || (current_user_can( get_option('eme_cap_author_event')) && ($recurrence['event_author']==$current_userid || $recurrence['event_contactperson_id']==$current_userid))) { $title = __ ( "Edit Recurrence", 'eme' ) . " '" . $recurrence['event_name'] . "'"; eme_event_form ( $recurrence, $title, $recurrence_ID ); } else { $feedback_message = __('You have no right to update','eme'). " '" . $recurrence['event_name'] . "' !"; eme_events_table ($feedback_message); } return; } if ($action == "-1" || $action == "") { // No action, only showing the events list $scope = isset($_GET['scope']) ? $_GET['scope'] : ''; switch ($scope) { case "past" : $title = __ ( 'Past Events', 'eme' ); break; case "all" : $title = __ ( 'All Events', 'eme' ); break; default : $title = __ ( 'Future Events', 'eme' ); $scope = "future"; } eme_events_table ("", $scope ); return; } } // array of all pages, bypasses the filter I set up :) function eme_get_all_pages() { global $wpdb; $query = "SELECT id, post_title FROM " . $wpdb->prefix . "posts WHERE post_type = 'page' AND post_status='publish'"; $pages = $wpdb->get_results ( $query, ARRAY_A ); // get_pages() is better, but uses way more memory and it might be filtered by eme_filter_get_pages() //$pages = get_pages(); $output = array (); $output[] = __( 'Please select a page','eme' ); foreach ( $pages as $page ) { $output[$page['id']] = $page['post_title']; // $output[$page->ID] = $page->post_title; } return $output; } //This is the content of the event page function eme_events_page_content() { global $wpdb; $format_header = eme_replace_placeholders(get_option('eme_event_list_item_format_header' )); $format_header = ( $format_header != '' ) ? $format_header : DEFAULT_EVENT_LIST_HEADER_FORMAT; $format_footer = eme_replace_placeholders(get_option('eme_event_list_item_format_footer' )); $format_footer = ( $format_footer != '' ) ? $format_footer : DEFAULT_EVENT_LIST_FOOTER_FORMAT; if (get_query_var('eme_pmt_result') && get_option('eme_payment_show_custom_return_page')) { // show the result of a payment, but not for a multi-booking payment result $result=get_query_var('eme_pmt_result'); if ($result == 'succes') { $format = get_option('eme_payment_succes_format'); } else { $format = get_option('eme_payment_fail_format'); } if (get_option('eme_payment_add_bookingid_to_return') && get_query_var('eme_pmt_id') && get_query_var('event_id')) { $event = eme_get_event(intval(get_query_var('event_id'))); $payment_id=intval(get_query_var('eme_pmt_id')); $booking_ids = eme_get_payment_booking_ids($payment_id); if ($booking_ids) { // since each booking is for a different event, we can't know which one to show // so we show only the first one $booking = eme_get_booking($booking_ids[0]); return eme_replace_booking_placeholders($format,$event,$booking); } else { return; } } elseif (get_query_var('event_id')) { $event = eme_get_event(intval(get_query_var('event_id'))); return eme_replace_placeholders($format,$event); } else { return $format; } } elseif (get_query_var('eme_pmt_id')) { $payment_id=intval(get_query_var('eme_pmt_id')); $booking_ids = eme_get_payment_booking_ids($payment_id); if (count($booking_ids)==1) $page_body = eme_payment_form("",$payment_id); else $page_body = eme_multipayment_form($payment_id); return $page_body; } if (get_query_var('eme_town')) { $eme_town=eme_sanitize_request(get_query_var('eme_town')); $location_ids = join(',',eme_get_town_location_ids($eme_town)); $stored_format = get_option('eme_event_list_item_format'); if (count($location_ids)>0) { $format_header = eme_replace_placeholders(get_option('eme_location_list_item_format_header' )); $format_header = ( $format_header != '' ) ? $format_header : DEFAULT_EVENT_LIST_HEADER_FORMAT; $format_footer = eme_replace_placeholders(get_option('eme_location_list_item_format_footer' )); $format_footer = ( $format_footer != '' ) ? $format_footer : DEFAULT_EVENT_LIST_FOOTER_FORMAT; $page_body = $format_header . eme_get_events_list ( get_option('eme_event_list_number_items' ), "future", "ASC", $stored_format, 0, '','',0,'','',0,$location_ids) . $format_footer; } else { $page_body = "<div id='events-no-events'>" . get_option('eme_no_events_message') . "</div>"; } return $page_body; } if (get_query_var('location_id')) { $location = eme_get_location ( intval(get_query_var('location_id'))); $single_location_format = get_option('eme_single_location_format' ); $page_body = eme_replace_locations_placeholders ( $single_location_format, $location ); return $page_body; } if (!get_query_var('calendar_day') && get_query_var('eme_event_cat')) { $eme_event_cat=eme_sanitize_request(get_query_var('eme_event_cat')); $cat_ids = join(',',eme_get_category_ids($eme_event_cat)); $stored_format = get_option('eme_event_list_item_format'); if (!empty($cat_ids)) { $page_body = $format_header . eme_get_events_list ( get_option('eme_event_list_number_items' ), "future", "ASC", $stored_format, 0, $cat_ids) . $format_footer; } else { $page_body = "<div id='events-no-events'>" . get_option('eme_no_events_message') . "</div>"; } return $page_body; } //if (isset ( $_REQUEST['event_id'] ) && $_REQUEST['event_id'] != '') { if (eme_is_single_event_page()) { // single event page $event_ID = intval(get_query_var('event_id')); $event = eme_get_event ( $event_ID ); if (!empty($event['event_single_event_format'])) $single_event_format = $event['event_single_event_format']; elseif ($event['event_properties']['event_single_event_format_tpl']>0) $single_event_format = eme_get_template_format($event['event_properties']['event_single_event_format_tpl']); else $single_event_format = get_option('eme_single_event_format' ); //$page_body = eme_replace_placeholders ( $single_event_format, $event, 'stop' ); if (count($event) > 0 && ($event['event_status'] == STATUS_PRIVATE && is_user_logged_in() || $event['event_status'] != STATUS_PRIVATE)) $page_body = eme_replace_placeholders ( $single_event_format, $event ); return $page_body; } elseif (get_query_var('calendar_day')) { $scope = eme_sanitize_request(get_query_var('calendar_day')); $events_count = eme_events_count_for ( $scope ); $location_id = isset( $_GET['location_id'] ) ? urldecode($_GET['location_id']) : ''; $category = isset( $_GET['category'] ) ? urldecode($_GET['category']) : ''; $notcategory = isset( $_GET['notcategory'] ) ? urldecode($_GET['notcategory']) : ''; $author = isset( $_GET['author'] ) ? urldecode($_GET['author']) : ''; $contact_person = isset( $_GET['contact_person'] ) ? urldecode($_GET['contact_person']) : ''; if ($events_count > 1) { // more than one event, so we show the list $event_list_item_format = get_option('eme_event_list_item_format' ); //Add headers and footers to the events list $page_body = $format_header . eme_get_events_list( 0, $scope, "ASC", $event_list_item_format, $location_id,$category,'',0, $author, $contact_person, 0,'',0,1,0, $notcategory ) . $format_footer; } else { // only one event for that day, so we show that event or redir to the configured external url for it $events = eme_get_events ( 0, $scope); $event = $events[0]; if ($event['event_url'] != '') { // url not empty, so we redirect to it $page_body = '<script type="text/javascript">window.location.href="'.$event['event_url'].'";</script>'; } else { if (!empty($event['event_single_event_format'])) $single_event_format = $event['event_single_event_format']; elseif ($event['event_properties']['event_single_event_format_tpl']>0) $single_event_format = eme_get_template_format($event['event_properties']['event_single_event_format_tpl']); else $single_event_format = get_option('eme_single_event_format' ); $page_body = eme_replace_placeholders ( $single_event_format, $event ); } } return $page_body; } else { // Multiple events page (isset($_GET['scope'])) ? $scope = eme_sanitize_request($_GET['scope']) : $scope = "future"; $stored_format = get_option('eme_event_list_item_format' ); if (get_option('eme_display_calendar_in_events_page' )){ $page_body = eme_get_calendar ('full=1'); }else{ $page_body = $format_header . eme_get_events_list ( get_option('eme_event_list_number_items' ), $scope, "ASC", $stored_format, 0 ) . $format_footer; } return $page_body; } } function eme_events_count_for($date) { global $wpdb; $table_name = $wpdb->prefix . EVENTS_TBNAME; $conditions = array (); if (!is_admin()) { if (is_user_logged_in()) { $conditions[] = "event_status IN (".STATUS_PUBLIC.",".STATUS_PRIVATE.")"; } else { $conditions[] = "event_status=".STATUS_PUBLIC; } } $conditions[] = "((event_start_date like '$date') OR (event_start_date <= '$date' AND event_end_date >= '$date'))"; $where = implode ( " AND ", $conditions ); if ($where != "") $where = " WHERE " . $where; $sql = "SELECT COUNT(*) FROM $table_name $where"; return $wpdb->get_var ( $sql ); } // filter function to call the event page when appropriate function eme_filter_events_page($data) { global $wp_current_filter; // we need to make sure we do this only once. Reason being: other plugins can call the_content as well // Suppose you add a shortcode from another plugin to the detail part of an event and that other plugin // calls apply_filter('the_content'), then this would cause recursion since that call would call our filter again // If the_content is the current filter definition (last element in the array), when there's more than one // (this is possible since one filter can call another, apply_filters does this), we can be in such a loop // And since our event content is only meant to be shown as content of a page (the_content is then the only element // in the $wp_current_filter array), we can then skip it //print_r($wp_current_filter); $eme_count_arr=array_count_values($wp_current_filter); $eme_event_parsed=0; $eme_loop_protection=get_option('eme_loop_protection'); switch ($eme_loop_protection) { case "default": if (count($wp_current_filter)>1 && end($wp_current_filter)=='the_content') $eme_event_parsed=1; break; case "older": if (count($wp_current_filter)>1 && end($wp_current_filter)=='the_content' && $eme_count_arr['the_content']>1) $eme_event_parsed=1; break; case "desperate": if ((count($wp_current_filter)>1 && end($wp_current_filter)=='the_content') || $eme_count_arr['the_content']>1) $eme_event_parsed=1; break; } // we change the content of the page only if we're "in the loop", // otherwise this filter also gets applied if e.g. a widget calls // the_content or the_excerpt to get the content of a page if (in_the_loop() && eme_is_events_page() && !$eme_event_parsed) { return eme_events_page_content (); } else { return $data; } } add_filter ( 'the_content', 'eme_filter_events_page' ); function eme_page_title($data) { $events_page_id = get_option('eme_events_page' ); $events_page = get_page ( $events_page_id ); $events_page_title = $events_page->post_title; // make sure we only replace the title for the events page, not anything // from the menu (which is also in the loop ...) if (($data == $events_page_title) && in_the_loop() && eme_is_events_page()) { if (get_query_var('calendar_day')) { $date = eme_sanitize_request(get_query_var('calendar_day')); $events_N = eme_events_count_for ( $date ); if ($events_N == 1) { $events = eme_get_events ( 0, eme_sanitize_request(get_query_var('calendar_day'))); $event = $events[0]; if (!empty($event['event_page_title_format'])) $stored_page_title_format = $event['event_page_title_format']; elseif ($event['event_properties']['event_page_title_format_tpl']>0) $stored_page_title_format = eme_get_template_format($event['event_properties']['event_page_title_format_tpl']); else $stored_page_title_format = get_option('eme_event_page_title_format' ); $page_title = eme_replace_placeholders ( $stored_page_title_format, $event ); return $page_title; } } if (eme_is_single_event_page()) { // single event page $event_ID = intval(get_query_var('event_id')); $event = eme_get_event ( $event_ID ); if (!empty($event['event_page_title_format'])) $stored_page_title_format = $event['event_page_title_format']; elseif ($event['event_properties']['event_page_title_format_tpl']>0) $stored_page_title_format = eme_get_template_format($event['event_properties']['event_page_title_format_tpl']); else $stored_page_title_format = get_option('eme_event_page_title_format' ); $page_title = eme_replace_placeholders ( $stored_page_title_format, $event ); return $page_title; } elseif (eme_is_single_location_page()) { $location = eme_get_location ( intval(get_query_var('location_id'))); $stored_page_title_format = get_option('eme_location_page_title_format' ); $page_title = eme_replace_locations_placeholders ( $stored_page_title_format, $location ); return $page_title; } else { // Multiple events page $page_title = get_option('eme_events_page_title' ); return $page_title; } } else { return $data; } } function eme_html_title($data) { //$events_page_id = get_option('eme_events_page' ); if (eme_is_events_page()) { if (get_query_var('calendar_day')) { $date = eme_sanitize_request(get_query_var('calendar_day')); $events_N = eme_events_count_for ( $date ); if ($events_N == 1) { $events = eme_get_events ( 0, eme_sanitize_request(get_query_var('calendar_day'))); $event = $events[0]; $stored_html_title_format = get_option('eme_event_html_title_format' ); $html_title = eme_strip_tags(eme_replace_placeholders ( $stored_html_title_format, $event )); return $html_title; } } if (eme_is_single_event_page()) { // single event page $event_ID = intval(get_query_var('event_id')); $event = eme_get_event ( $event_ID ); $stored_html_title_format = get_option('eme_event_html_title_format' ); $html_title = eme_strip_tags(eme_replace_placeholders ( $stored_html_title_format, $event )); return $html_title; } elseif (eme_is_single_location_page()) { $location = eme_get_location ( intval(get_query_var('location_id'))); $stored_html_title_format = get_option('eme_location_html_title_format' ); $html_title = eme_strip_tags(eme_replace_locations_placeholders ( $stored_html_title_format, $location )); return $html_title; } else { // Multiple events page $html_title = get_option('eme_events_page_title' ); return $html_title; } } else { return $data; } } // the filter single_post_title influences the html header title and the page title // we want to prevent html tags in the html header title (if you add html in the 'single event title format', it will show) add_filter ( 'single_post_title', 'eme_html_title' ); add_filter ( 'the_title', 'eme_page_title' ); function eme_template_redir() { # We need to catch the request as early as possible, but # since it needs to be working for both permalinks and normal, # I can't use just any action hook. parse_query seems to do just fine if (get_query_var('event_id')) { $event_id = intval(get_query_var('event_id')); if (!eme_check_event_exists($event_id)) { // header('Location: '.home_url('404.php')); status_header(404); nocache_headers(); include( get_404_template() ); exit; } } if (get_query_var('location_id')) { $location_id = intval(get_query_var('location_id')); if (!eme_check_location_exists($location_id)) { // header('Location: '.home_url('404.php')); status_header(404); nocache_headers(); include( get_404_template() ); exit; } } // Enqueue jQuery script to make sure it's loaded wp_enqueue_script ( 'jquery' ); } // filter out the events page in the get_pages call function eme_filter_get_pages($data) { //$output = array (); $events_page_id = get_option('eme_events_page' ); $list_events_page = get_option('eme_list_events_page' ); // if we want the page to be shown, just return everything unfiltered if ($list_events_page) { return $data; } else { foreach ($data as $key => $item) { if ($item->ID == $events_page_id) { //$output[] = $item; unset($data[$key]); } } //return $output; return $data; } } add_filter ( 'get_pages', 'eme_filter_get_pages' ); //filter out the events page in the admin section function exclude_this_page( $query ) { if( !is_admin() ) return $query; global $pagenow; $events_page_id = get_option('eme_events_page' ); if( 'edit.php' == $pagenow && ( get_query_var('post_type') && 'page' == get_query_var('post_type') ) ) $query->set( 'post__not_in', array($events_page_id) ); return $query; } // TEMPLATE TAGS // exposed function, for theme makers //Added a category option to the get events list method and shortcode function eme_get_events_list($limit, $scope = "future", $order = "ASC", $format = '', $echo = 1, $category = '',$showperiod = '', $long_events = 0, $author = '', $contact_person='', $paging=0, $location_id = "", $user_registered_only = 0, $show_ongoing=1, $link_showperiod=0, $notcategory = '', $show_recurrent_events_once= 0, $template_id = 0, $template_id_header=0, $template_id_footer=0, $no_events_message="") { global $post; if ($limit === "") { $limit = get_option('eme_event_list_number_items' ); } if (strpos ( $limit, "=" )) { // allows the use of arguments without breaking the legacy code $eme_event_list_number_events=get_option('eme_event_list_number_items' ); $defaults = array ('limit' => $eme_event_list_number_events, 'scope' => 'future', 'order' => 'ASC', 'format' => '', 'echo' => 1 , 'category' => '', 'showperiod' => '', $author => '', $contact_person => '', 'paging'=>0, 'long_events' => 0, 'location_id' => 0, 'show_ongoing' => 1, 'link_showperiod' => 0, 'notcategory' => '', 'show_recurrent_events_once' => 0, 'template_id' => 0, 'template_id_header' => 0, 'template_id_footer' => 0, 'no_events_message' => ''); $r = wp_parse_args ( $limit, $defaults ); extract ( $r ); // for AND categories: the user enters "+" and this gets translated to " " by wp_parse_args // so we fix it again $category = preg_replace("/ /","+",$category); $notcategory = preg_replace("/ /","+",$notcategory); } $echo = ($echo==="true" || $echo==="1") ? true : $echo; $long_events = ($long_events==="true" || $long_events==="1") ? true : $long_events; $paging = ($paging==="true" || $paging==="1") ? true : $paging; $show_ongoing = ($show_ongoing==="true" || $show_ongoing==="1") ? true : $show_ongoing; $echo = ($echo==="false" || $echo==="0") ? false : $echo; $long_events = ($long_events==="false" || $long_events==="0") ? false : $long_events; $paging = ($paging==="false" || $paging==="0") ? false : $paging; $show_ongoing = ($show_ongoing==="false" || $show_ongoing==="0") ? false : $show_ongoing; if ($scope == "") $scope = "future"; if ($order != "DESC") $order = "ASC"; $eme_format_header=""; $eme_format_footer=""; if ($template_id) { $format = eme_get_template_format($template_id); } if ($template_id_header) { $format_header = eme_get_template_format($template_id_header); $eme_format_header=eme_replace_placeholders($format_header); } if ($template_id_footer) { $format_footer = eme_get_template_format($template_id_footer); $eme_format_footer=eme_replace_placeholders($format_footer); } if (empty($format)) { $format = get_option('eme_event_list_item_format' ); if (empty($eme_format_header)) { $eme_format_header = eme_replace_placeholders(get_option('eme_event_list_item_format_header' )); $eme_format_header = ( $eme_format_header != '' ) ? $eme_format_header : DEFAULT_EVENT_LIST_HEADER_FORMAT; } if (empty($eme_format_footer)) { $eme_format_footer = eme_replace_placeholders(get_option('eme_event_list_item_format_footer' )); $eme_format_footer = ( $eme_format_footer != '' ) ? $eme_format_footer : DEFAULT_EVENT_LIST_FOOTER_FORMAT; } } // for registered users: we'll add a list of event_id's for that user only $extra_conditions = ""; if ($user_registered_only == 1 && is_user_logged_in()) { $current_userid=get_current_user_id(); $person_id=eme_get_person_id_by_wp_id($current_userid); $list_of_event_ids=join(",",eme_get_event_ids_by_booker_id($person_id)); if (!empty($list_of_event_ids)) { $extra_conditions = " (event_id in ($list_of_event_ids))"; } else { // user has no registered events, then make sure none are shown $extra_conditions = " (event_id = 0)"; } } $prev_text = ""; $next_text = ""; $limit_start=0; $limit_end=0; // for browsing: if limit=0,paging=1 and only for this_week,this_month or today if ($limit>0 && $paging==1 && isset($_GET['eme_offset'])) { $limit_offset=intval($_GET['eme_offset']); } else { $limit_offset=0; } // if extra scope_filter is found (from the eme_filter shortcode), then no paging // since it won't work anyway if (isset($_REQUEST["eme_scope_filter"])) $paging=0; if ($paging==1 && $limit==0) { $scope_offset=0; $scope_text = ""; if (isset($_GET['eme_offset'])) $scope_offset=$_GET['eme_offset']; $prev_offset=$scope_offset-1; $next_offset=$scope_offset+1; if ($scope=="this_week") { $start_of_week = get_option('start_of_week'); $day_offset=date('w')-$start_of_week; if ($day_offset<0) $day_offset+=7; $limit_start=eme_date_calc("-$day_offset days +$scope_offset week"); $limit_end=eme_date_calc("+6 days",$limit_start); $scope = "$limit_start--$limit_end"; $scope_text = eme_localised_date($limit_start)." -- ".eme_localised_date($limit_end); $prev_text = __('Previous week','eme'); $next_text = __('Next week','eme'); } elseif ($scope=="this_month") { $limit_start = eme_date_calc("first day of $scope_offset month"); $limit_end = eme_date_calc("last day of $scope_offset month"); $scope = "$limit_start--$limit_end"; $scope_text = eme_localised_date($limit_start,get_option('eme_show_period_monthly_dateformat')); $prev_text = __('Previous month','eme'); $next_text = __('Next month','eme'); } elseif ($scope=="this_year") { $year=date('Y')+$scope_offset; $limit_start = "$year-01-01"; $limit_end = "$year-12-31"; $scope = "$limit_start--$limit_end"; $scope_text = eme_localised_date($limit_start,get_option('eme_show_period_yearly_dateformat')); $prev_text = __('Previous year','eme'); $next_text = __('Next year','eme'); } elseif ($scope=="today") { $scope = date('Y-m-d',strtotime("$scope_offset days")); $limit_start = $scope; $limit_end = $scope; $scope_text = eme_localised_date($limit_start); $prev_text = __('Previous day','eme'); $next_text = __('Next day','eme'); } elseif ($scope=="tomorrow") { $scope_offset++; $scope = date('Y-m-d',strtotime("$scope_offset days")); $limit_start = $scope; $limit_end = $scope; $scope_text = eme_localised_date($limit_start); $prev_text = __('Previous day','eme'); $next_text = __('Next day','eme'); } } // We request $limit+1 events, so we know if we need to show the pagination link or not. if ($limit==0) { $events = eme_get_events ( 0, $scope, $order, $limit_offset, $location_id, $category, $author, $contact_person, $show_ongoing, $notcategory, $show_recurrent_events_once, $extra_conditions ); } else { $events = eme_get_events ( $limit+1, $scope, $order, $limit_offset, $location_id, $category, $author, $contact_person, $show_ongoing, $notcategory, $show_recurrent_events_once, $extra_conditions ); } $events_count=count($events); // get the paging output ready $pagination_top = "<div id='events-pagination-top'> "; $nav_hidden_class="style='visibility:hidden;'"; if ($paging==1 && $limit>0) { // for normal paging and there're no events, we go back to offset=0 and try again if ($events_count==0) { $limit_offset=0; $events = eme_get_events ( $limit+1, $scope, $order, $limit_offset, $location_id, $category, $author, $contact_person, $show_ongoing, $notcategory, $show_recurrent_events_once, $extra_conditions ); $events_count=count($events); } $prev_text=__('Previous page','eme'); $next_text=__('Next page','eme'); $page_number = floor($limit_offset/$limit) + 1; $this_page_url=get_permalink($post->ID); //$this_page_url=$_SERVER['REQUEST_URI']; // remove the offset info $this_page_url= remove_query_arg('eme_offset',$this_page_url); // we add possible fields from the filter section $eme_filters["eme_eventAction"]=1; $eme_filters["eme_cat_filter"]=1; $eme_filters["eme_loc_filter"]=1; $eme_filters["eme_town_filter"]=1; $eme_filters["eme_scope_filter"]=1; foreach ($_REQUEST as $key => $item) { if (isset($eme_filters[$key])) { # if you selected multiple items, $item is an array, but rawurlencode needs a string if (is_array($item)) $item=join(',',eme_sanitize_request($item)); $this_page_url=add_query_arg(array($key=>$item),$this_page_url); } } // we always provide the text, so everything stays in place (but we just hide it if needed, and change the link to empty // to prevent going on indefinitely and thus allowing search bots to go on for ever if ($events_count > $limit) { $forward = $limit_offset + $limit; $backward = $limit_offset - $limit; if ($backward < 0) $pagination_top.= "<a class='eme_nav_left' $nav_hidden_class href='#'>&lt;&lt; $prev_text</a>"; else $pagination_top.= "<a class='eme_nav_left' href='".add_query_arg(array('eme_offset'=>$backward),$this_page_url)."'>&lt;&lt; $prev_text</a>"; $pagination_top.= "<a class='eme_nav_right' href='".add_query_arg(array('eme_offset'=>$forward),$this_page_url)."'>$next_text &gt;&gt;</a>"; $pagination_top.= "<span class='eme_nav_center'>".__('Page ','eme').$page_number."</span>"; } if ($events_count <= $limit && $limit_offset>0) { $forward = 0; $backward = $limit_offset - $limit; if ($backward < 0) $pagination_top.= "<a class='eme_nav_left' $nav_hidden_class href='#'>&lt;&lt; $prev_text</a>"; else $pagination_top.= "<a class='eme_nav_left' href='".add_query_arg(array('eme_offset'=>$backward),$this_page_url)."'>&lt;&lt; $prev_text</a>"; $pagination_top.= "<a class='eme_nav_right' $nav_hidden_class href='#'>$next_text &gt;&gt;</a>"; $pagination_top.= "<span class='eme_nav_center'>".__('Page ','eme').$page_number."</span>"; } } if ($paging==1 && $limit==0) { $this_page_url=$_SERVER['REQUEST_URI']; // remove the offset info $this_page_url= remove_query_arg('eme_offset',$this_page_url); // we add possible fields from the filter section $eme_filters["eme_eventAction"]=1; $eme_filters["eme_cat_filter"]=1; $eme_filters["eme_loc_filter"]=1; $eme_filters["eme_town_filter"]=1; $eme_filters["eme_scope_filter"]=1; foreach ($_REQUEST as $key => $item) { if (isset($eme_filters[$key])) { # if you selected multiple items, $item is an array, but rawurlencode needs a string if (is_array($item)) $item=join(',',eme_sanitize_request($item)); $this_page_url=add_query_arg(array($key=>$item),$this_page_url); } } // to prevent going on indefinitely and thus allowing search bots to go on for ever, // we stop providing links if there are no more events left $older_events=eme_get_events ( 1, "--".$limit_start, $order, 0, $location_id, $category, $author, $contact_person, $show_ongoing, $notcategory, $show_recurrent_events_once, $extra_conditions ); $newer_events=eme_get_events ( 1, "++".$limit_end, $order, 0, $location_id, $category, $author, $contact_person, $show_ongoing, $notcategory, $show_recurrent_events_once, $extra_conditions ); if (count($older_events)>0) $pagination_top.= "<a class='eme_nav_left' href='".add_query_arg(array('eme_offset'=>$prev_offset),$this_page_url) ."'>&lt;&lt; $prev_text</a>"; else $pagination_top.= "<a class='eme_nav_left' $nav_hidden_class href='#'>&lt;&lt; $prev_text</a>"; if (count($newer_events)>0) $pagination_top.= "<a class='eme_nav_right' href='".add_query_arg(array('eme_offset'=>$next_offset),$this_page_url) ."'>$next_text &gt;&gt;</a>"; else $pagination_top.= "<a class='eme_nav_right' $nav_hidden_class href='#'>$next_text &gt;&gt;</a>"; $pagination_top.= "<span class='eme_nav_center'>$scope_text</span>"; } $pagination_top.= "</div>"; $pagination_bottom = str_replace("events-pagination-top","events-pagination-bottom",$pagination_top); $output = ""; if ($events_count>0) { # if we want to show events per period, we first need to determine on which days events occur # this code is identical to that in eme_calendar.php for "long events" if (! empty ( $showperiod )) { $eventful_days= array(); $i=1; foreach ( $events as $event ) { // we requested $limit+1 events, so we need to break at the $limit, if reached if ($limit>0 && $i>$limit) break; $event_start_date = strtotime($event['event_start_date']); $event_end_date = strtotime($event['event_end_date']); if ($event_end_date < $event_start_date) $event_end_date=$event_start_date; if ($long_events) { //Show events on every day that they are still going on while( $event_start_date <= $event_end_date ) { $event_eventful_date = date('Y-m-d', $event_start_date); if(isset($eventful_days[$event_eventful_date]) && is_array($eventful_days[$event_eventful_date]) ) { $eventful_days[$event_eventful_date][] = $event; } else { $eventful_days[$event_eventful_date] = array($event); } $event_start_date += (60*60*24); } } else { //Only show events on the day that they start if ( isset($eventful_days[$event['event_start_date']]) && is_array($eventful_days[$event['event_start_date']]) ) { $eventful_days[$event['event_start_date']][] = $event; } else { $eventful_days[$event['event_start_date']] = array($event); } } $i++; } # now that we now the days on which events occur, loop through them $curyear=""; $curmonth=""; $curday=""; foreach($eventful_days as $day_key => $day_events) { $theyear = date ("Y", strtotime($day_key)); $themonth = date ("m", strtotime($day_key)); $theday = date ("d", strtotime($day_key)); if ($showperiod == "yearly" && $theyear != $curyear) { $output .= "<li class='eme_period'>".eme_localised_date ($day_key,get_option('eme_show_period_yearly_dateformat'))."</li>"; } elseif ($showperiod == "monthly" && "$theyear$themonth" != "$curyear$curmonth") { $output .= "<li class='eme_period'>".eme_localised_date ($day_key,get_option('eme_show_period_monthly_dateformat'))."</li>"; } elseif ($showperiod == "daily" && "$theyear$themonth$theday" != "$curyear$curmonth$curday") { $output .= "<li class='eme_period'>"; if ($link_showperiod) { $eme_link=eme_calendar_day_url($theyear."-".$themonth."-".$theday); $output .= "<a href=\"$eme_link\">".eme_localised_date ($day_key)."</a>"; } else { $output .= eme_localised_date ($day_key); } $output .= "</li>"; } $curyear=$theyear; $curmonth=$themonth; $curday=$theday; foreach($day_events as $event) { $output .= eme_replace_placeholders ( $format, $event ); } } } else { $i=1; foreach ( $events as $event ) { // we requested $limit+1 events, so we need to break at the $limit, if reached if ($limit>0 && $i>$limit) break; $output .= eme_replace_placeholders ( $format, $event ); $i++; } } // end if (! empty ( $showperiod )) { //Add headers and footers to output $output = $eme_format_header . $output . $eme_format_footer; } else { if (empty($no_events_message)) $no_events_message=get_option('eme_no_events_message'); $output = "<div id='events-no-events'>" . $eme_no_events_message . "</div>"; } // add the pagination if needed if ($paging==1 && $events_count>0) $output = $pagination_top . $output . $pagination_bottom; // see how to return the output if ($echo) echo $output; else return $output; } function eme_get_events_list_shortcode($atts) { $eme_event_list_number_events=get_option('eme_event_list_number_items' ); extract ( shortcode_atts ( array ('limit' => $eme_event_list_number_events, 'scope' => 'future', 'order' => 'ASC', 'format' => '', 'category' => '', 'showperiod' => '', 'author' => '', 'contact_person' => '', 'paging' => 0, 'long_events' => 0, 'location_id' => 0, 'user_registered_only' => 0, 'show_ongoing' => 1, 'link_showperiod' => 0, 'notcategory' => '', 'show_recurrent_events_once' => 0, 'template_id' => 0, 'template_id_header' => 0, 'template_id_footer' => 0, 'no_events_message' => '' ), $atts ) ); // the filter list overrides the settings if (isset($_REQUEST['eme_eventAction']) && $_REQUEST['eme_eventAction'] == 'filter') { if (isset($_REQUEST['eme_scope_filter']) && !empty($_REQUEST['eme_scope_filter'])) { $scope = eme_sanitize_request($_REQUEST['eme_scope_filter']); } if (isset($_REQUEST['eme_loc_filter']) && !empty($_REQUEST['eme_loc_filter'])) { if (is_array($_REQUEST['eme_loc_filter'])) $location_id=join(',',eme_sanitize_request($_REQUEST['eme_loc_filter'])); else $location_id=eme_sanitize_request($_REQUEST['eme_loc_filter']); } if (isset($_REQUEST['eme_town_filter']) && !empty($_REQUEST['eme_town_filter'])) { $towns=eme_sanitize_request($_REQUEST['eme_town_filter']); if (empty($location_id)) $location_id = join(',',eme_get_town_location_ids($towns)); else $location_id .= ",".join(',',eme_get_town_location_ids($towns)); } if (isset($_REQUEST['eme_cat_filter']) && !empty($_REQUEST['eme_cat_filter'])) { if (is_array($_REQUEST['eme_cat_filter'])) $category=join(',',eme_sanitize_request($_REQUEST['eme_cat_filter'])); else $category=eme_sanitize_request($_REQUEST['eme_cat_filter']); } } // if format is given as argument, sometimes people need url-encoded strings inside so wordpress doesn't get confused, so we decode them here again $format = urldecode($format); // for format: sometimes people want to give placeholders as options, but when using the shortcode inside // another (e.g. when putting[eme_events format="#_EVENTNAME"] inside the "display single event" setting, // the replacement of the placeholders happens too soon (placeholders get replaced first, before any other // shortcode is interpreted). So we add the option that people can use "#OTHER_", and we replace this with // "#_" here $format = preg_replace('/#OTHER/', "#", $format); $result = eme_get_events_list ( $limit,$scope,$order,$format,0,$category,$showperiod,$long_events,$author,$contact_person,$paging,$location_id,$user_registered_only,$show_ongoing,$link_showperiod,$notcategory,$show_recurrent_events_once,$template_id,$template_id_header,$template_id_footer,$no_events_message); return $result; } function eme_display_single_event($event_id,$template_id=0) { $event = eme_get_event ( intval($event_id) ); if ($template_id) { $single_event_format= eme_get_template_format($template_id); } else { if (!empty($event['event_single_event_format'])) $single_event_format = $event['event_single_event_format']; elseif ($event['event_properties']['event_single_event_format_tpl']>0) $single_event_format = eme_get_template_format($event['event_properties']['event_single_event_format_tpl']); else $single_event_format = get_option('eme_single_event_format' ); } $page_body = eme_replace_placeholders ($single_event_format, $event); return $page_body; } function eme_display_single_event_shortcode($atts) { extract ( shortcode_atts ( array ('id'=>'','template_id'=>0), $atts ) ); return eme_display_single_event($id,$template_id); } function eme_get_events_page($justurl = 0, $echo = 1, $text = '') { if (strpos ( $justurl, "=" )) { // allows the use of arguments without breaking the legacy code $defaults = array ('justurl' => 0, 'text' => '', 'echo' => 1 ); $r = wp_parse_args ( $justurl, $defaults ); extract ( $r ); } $echo = ($echo==="true" || $echo==="1") ? true : $echo; $justurl = ($justurl==="true" || $justurl==="1") ? true : $justurl; $echo = ($echo==="false" || $echo==="0") ? false : $echo; $justurl = ($justurl==="false" || $justurl==="0") ? false : $justurl; $page_link = get_permalink ( get_option ( 'eme_events_page' ) ); if ($justurl) { $result = $page_link; } else { if ($text == '') $text = get_option ( 'eme_events_page_title' ); $result = "<a href='$page_link' title='$text'>$text</a>"; } if ($echo) echo $result; else return $result; } function eme_get_events_page_shortcode($atts) { extract ( shortcode_atts ( array ('justurl' => 0, 'text' => '' ), $atts ) ); $result = eme_get_events_page ( "justurl=$justurl&text=$text&echo=0" ); return $result; } // API function function eme_are_events_available($scope = "future",$order = "ASC", $location_id = "", $category = '', $author = '', $contact_person = '') { if ($scope == "") $scope = "future"; $events = eme_get_events ( 1, $scope, $order, 0, $location_id, $category, $author, $contact_person); if (empty ( $events )) return FALSE; else return TRUE; } function eme_count_events_older_than($scope) { global $wpdb; $events_table = $wpdb->prefix.EVENTS_TBNAME; $sql = "SELECT COUNT(*) from $events_table WHERE event_start_date<'".$scope."'"; return $wpdb->get_var($sql); } function eme_count_events_newer_than($scope) { global $wpdb; $events_table = $wpdb->prefix.EVENTS_TBNAME; $sql = "SELECT COUNT(*) from $events_table WHERE event_end_date>'".$scope."'"; return $wpdb->get_var($sql); } // main function querying the database event table function eme_get_events($o_limit, $scope = "future", $order = "ASC", $o_offset = 0, $location_id = "", $category = "", $author = "", $contact_person = "", $show_ongoing=1, $notcategory = "", $show_recurrent_events_once=0, $extra_conditions = "") { global $wpdb; $events_table = $wpdb->prefix.EVENTS_TBNAME; $bookings_table = $wpdb->prefix.BOOKINGS_TBNAME; if ($o_limit === "") { $o_limit = get_option('eme_event_list_number_items' ); } if ($o_limit > 0) { $limit = "LIMIT ".intval($o_limit); } else { $limit=""; } if ($o_offset >0) { if ($o_limit == 0) { $limit = "LIMIT ".intval($o_offset); } $offset = "OFFSET ".intval($o_offset); } else { $offset=""; } if ($order != "DESC") $order = "ASC"; $today = date("Y-m-d"); $this_time = date ("H:i:00"); $conditions = array (); // extra sql conditions we put in front, most of the time this is the most // effective place if ($extra_conditions != "") { $conditions[] = $extra_conditions; } // if we're not in the admin itf, we don't want draft events if (!is_admin()) { if (is_user_logged_in()) { $conditions[] = "event_status IN (".STATUS_PUBLIC.",".STATUS_PRIVATE.")"; } else { $conditions[] = "event_status=".STATUS_PUBLIC; } if (get_option('eme_rsvp_hide_full_events')) { // COALESCE is used in case the SUM returns NULL // this is a correlated subquery, so the FROM clause should specify events_table again, so it will search in the outer query for events_table.event_id $conditions[] = "(event_rsvp=0 OR (event_rsvp=1 AND event_seats > (SELECT COALESCE(SUM(booking_seats),0) AS booked_seats FROM $bookings_table WHERE $bookings_table.event_id = $events_table.event_id)))"; } if (get_option('eme_rsvp_hide_rsvp_ended_events')) { $conditions[] = "(event_rsvp=0 OR (event_rsvp=1 AND (event_end_date < '$today' OR UNIX_TIMESTAMP(CONCAT(event_start_date,' ',event_start_time))-rsvp_number_days*60*60*24-rsvp_number_hours*60*60 > UNIX_TIMESTAMP()) ))"; } } if (preg_match ( "/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $scope )) { //$conditions[] = " event_start_date like '$scope'"; if ($show_ongoing) $conditions[] = " ((event_start_date LIKE '$scope') OR (event_start_date <= '$scope' AND event_end_date >= '$scope'))"; else $conditions[] = " (event_start_date LIKE '$scope') "; } elseif (preg_match ( "/^--([0-9]{4}-[0-9]{2}-[0-9]{2})$/", $scope, $matches )) { $limit_start = $matches[1]; if ($show_ongoing) $conditions[] = " (event_start_date < '$limit_start') "; else $conditions[] = " (event_end_date < '$limit_start') "; } elseif (preg_match ( "/^\+\+([0-9]{4}-[0-9]{2}-[0-9]{2})$/", $scope, $matches )) { $limit_start = $matches[1]; $conditions[] = " (event_start_date > '$limit_start') "; } elseif (preg_match ( "/^0000-([0-9]{2})$/", $scope, $matches )) { $year=date('Y'); $month=$matches[1]; $number_of_days_month=eme_days_in_month($month,$year); $limit_start = "$year-$month-01"; $limit_end = "$year-$month-$number_of_days_month"; if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "this_week") { // this comes from global wordpress preferences $start_of_week = get_option('start_of_week'); $day_offset=date('w')-$start_of_week; if ($day_offset<0) $day_offset+=7; $limit_start=eme_date_calc("-$day_offset days"); $limit_end=eme_date_calc("+6 days",$start_day); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "next_week") { // this comes from global wordpress preferences $start_of_week = get_option('start_of_week'); $day_offset=date('w')-$start_of_week; if ($day_offset<0) $day_offset+=7; $day_offset+=7; // add 7 days for next week $limit_start=eme_date_calc("$day_offset days"); $limit_end=eme_date_calc("+6 days",$start_day); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "this_month") { $limit_start= eme_date_calc("first day of this month"); $limit_end= eme_date_calc("last day of this month"); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "this_year") { $year=date('Y'); $limit_start = "$year-01-01"; $limit_end = "$year-12-31"; if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "next_month") { // the year/month should be based on the first of the month, so if we are the 13th, we substract 12 days to get to day 1 // Reason: monthly offsets needs to be calculated based on the first day of the current month, not the current day, // otherwise if we're now on the 31st we'll skip next month since it has only 30 days $limit_start= eme_date_calc("first day of next month"); $limit_end= eme_date_calc("last day of next month"); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif (preg_match ( "/^([0-9]{4}-[0-9]{2}-[0-9]{2})--([0-9]{4}-[0-9]{2}-[0-9]{2})$/", $scope, $matches )) { $limit_start=$matches[1]; $limit_end=$matches[2]; if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif (preg_match ( "/^([0-9]{4}-[0-9]{2}-[0-9]{2})--today$/", $scope, $matches )) { $limit_start=$matches[1]; $limit_end=$today; if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif (preg_match ( "/^today--([0-9]{4}-[0-9]{2}-[0-9]{2})$/", $scope, $matches )) { $limit_start=$today; $limit_end=$matches[1]; if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif (preg_match ( "/^\+(\d+)d$/", $scope, $matches )) { $limit_start = $today; $days=$matches[1]; $limit_end=eme_date_calc("+$days days"); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif (preg_match ( "/^\-(\d+)d$/", $scope, $matches )) { $limit_end = $today; $days=$matches[1]; $limit_start=eme_date_calc("-$days days"); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif (preg_match ( "/^(\-?\+?\d+)d--(\-?\+?\d+)d$/", $scope, $matches )) { $day1=$matches[1]; $day2=$matches[2]; $limit_start=eme_date_calc("$day1 days"); $limit_end=eme_date_calc("$day2 days"); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif (preg_match ( "/^relative\-(\d+)d--([0-9]{4}-[0-9]{2}-[0-9]{2})$/", $scope, $matches )) { $days=$matches[1]; $limit_end=$matches[2]; $limit_start=eme_date_calc("-$days days",strtotime($limit_end)); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif (preg_match ( "/^([0-9]{4}-[0-9]{2}-[0-9]{2})--relative\+(\d+)d$/", $scope, $matches )) { $limit_start=$matches[1]; $days=$matches[2]; $limit_end=eme_date_calc("+$days days",strtotime($limit_start)); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif (preg_match ( "/^\+(\d+)m$/", $scope, $matches )) { // the year/month should be based on the first of the month, so if we are the 13th, we substract 12 days to get to day 1 // Reason: monthly offsets needs to be calculated based on the first day of the current month, not the current day, // otherwise if we're now on the 31st we'll skip next month since it has only 30 days $day_offset=date('j')-1; $months_in_future=$matches[1]++; $limit_start= eme_date_calc("first day of this month"); $limit_end = eme_date_calc("last day of +$months_in_future month"); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif (preg_match ( "/^\-(\d+)m$/", $scope, $matches )) { // the year/month should be based on the first of the month, so if we are the 13th, we substract 12 days to get to day 1 // Reason: monthly offsets needs to be calculated based on the first day of the current month, not the current day, // otherwise if we're now on the 31st we'll skip next month since it has only 30 days $day_offset=date('j')-1; $months_in_past=$matches[1]++; $limit_start = eme_date_calc("first day of -$months_in_past month"); $limit_end = eme_date_calc("last day of last month"); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif (preg_match ( "/^(\-?\+?\d+)m--(\-?\+?\d+)m$/", $scope, $matches )) { $day_offset=date('j')-1; $months1=$matches[1]; $months2=$matches[2]; $limit_start = eme_date_calc("first day of $months1 month"); $limit_end = eme_date_calc("last day of $months2 month"); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "today--this_week") { $start_of_week = get_option('start_of_week'); $day_offset=date('w')-$start_of_week; if ($day_offset<0) $day_offset+=7; $end_day=$day_offset+6; $limit_start = $today; $limit_end = eme_date_calc("+$end_day days"); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "today--this_week_plus_one") { $start_of_week = get_option('start_of_week'); $day_offset=date('w')-$start_of_week; if ($day_offset<0) $day_offset+=7; $end_day=$day_offset+7; $limit_start = $today; $limit_end = eme_date_calc("+$end_day days"); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "today--this_month") { $limit_start = $today; $limit_end = date('Y-m-d', strtotime("last day of this month")); if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "today--this_year") { $limit_start = $today; $limit_end = "$year-12-31"; if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "this_week--today") { $start_of_week = get_option('start_of_week'); $day_offset=date('w')-$start_of_week; if ($day_offset<0) $day_offset+=7; $limit_start = eme_date_calc("-$day_offset days"); $limit_end = $today; if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "this_month--today") { $limit_start = eme_date_calc("first day of this month"); $limit_end = $today; if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "this_year--today") { $limit_start = "$year-01-01"; $limit_end = $today; if ($show_ongoing) $conditions[] = " ((event_start_date BETWEEN '$limit_start' AND '$limit_end') OR (event_end_date BETWEEN '$limit_start' AND '$limit_end') OR (event_start_date <= '$limit_start' AND event_end_date >= '$limit_end'))"; else $conditions[] = " (event_start_date BETWEEN '$limit_start' AND '$limit_end')"; } elseif ($scope == "tomorrow--future") { if ($show_ongoing) $conditions[] = " (event_start_date > '$today' OR (event_end_date > '$today' AND event_end_date != '0000-00-00' AND event_end_date IS NOT NULL))"; else $conditions[] = " (event_start_date > '$today')"; } elseif ($scope == "past") { //$conditions[] = " (event_end_date < '$today' OR (event_end_date = '$today' and event_end_time < '$this_time' )) "; // not taking the hour into account until we can enter timezone info as well if ($show_ongoing) $conditions[] = " event_end_date < '$today'"; else $conditions[] = " event_start_date < '$today'"; } elseif ($scope == "today") { if ($show_ongoing) $conditions[] = " (event_start_date = '$today' OR (event_start_date <= '$today' AND event_end_date >= '$today'))"; else $conditions[] = " (event_start_date = '$today')"; } elseif ($scope == "tomorrow") { $tomorrow = eme_date_calc("tomorrow"); if ($show_ongoing) $conditions[] = " (event_start_date = '$tomorrow' OR (event_start_date <= '$tomorrow' AND event_end_date >= '$tomorrow'))"; else $conditions[] = " (event_start_date = '$tomorrow')"; } elseif ($scope == "ongoing") { // only shows ongoing events, for this we try to use the date and time, but it might be incorrect since there's no user timezone info $conditions[] = " (CONCAT(event_start_date,' ',event_start_time)<='$today $this_time' AND CONCAT(event_end_date,' ',event_end_time)>= '$today $this_time')"; } else { if ($scope != "all") $scope = "future"; if ($scope == "future") { //$conditions[] = " ((event_start_date = '$today' AND event_start_time >= '$this_time') OR (event_start_date > '$today') OR (event_end_date > '$today' AND event_end_date != '0000-00-00' AND event_end_date IS NOT NULL) OR (event_end_date = '$today' AND event_end_time >= '$this_time'))"; // not taking the hour into account until we can enter timezone info as well if ($show_ongoing) $conditions[] = " (event_start_date >= '$today' OR (event_end_date >= '$today' AND event_end_date != '0000-00-00' AND event_end_date IS NOT NULL))"; else $conditions[] = " (event_start_date >= '$today')"; } } // when used inside a location description, you can use this_location to indicate the current location being viewed if ($location_id == "this_location" && get_query_var('location_id')) { $location_id = get_query_var('location_id'); } if (is_numeric($location_id)) { if ($location_id>0) $conditions[] = " location_id = $location_id"; } elseif ($location_id == "none") { $conditions[] = " location_id = ''"; } elseif ( preg_match('/,/', $location_id) ) { $location_ids=explode(',', $location_id); $location_conditions = array(); foreach ($location_ids as $loc) { if (is_numeric($loc) && $loc>0) { $location_conditions[] = " location_id = $loc"; } elseif ($loc == "none") { $location_conditions[] = " location_id = ''"; } } $conditions[] = "(".implode(' OR', $location_conditions).")"; } elseif ( preg_match('/\+/', $location_id) ) { $location_ids=explode('+', $location_id); $location_conditions = array(); foreach ($location_ids as $loc) { if (is_numeric($loc) && $loc>0) $location_conditions[] = " location_id = $loc"; } $conditions[] = "(".implode(' AND', $location_conditions).")"; } elseif ( preg_match('/ /', $location_id) ) { // url decoding of '+' is ' ' $location_ids=explode(' ', $location_id); $location_conditions = array(); foreach ($location_ids as $loc) { if (is_numeric($loc) && $loc>0) $location_conditions[] = " location_id = $loc"; } $conditions[] = "(".implode(' AND', $location_conditions).")"; } if (get_option('eme_categories_enabled')) { if (is_numeric($category)) { if ($category>0) $conditions[] = " FIND_IN_SET($category,event_category_ids)"; } elseif ($category == "none") { $conditions[] = "event_category_ids = ''"; } elseif ( preg_match('/,/', $category) ) { $category = explode(',', $category); $category_conditions = array(); foreach ($category as $cat) { if (is_numeric($cat) && $cat>0) { $category_conditions[] = " FIND_IN_SET($cat,event_category_ids)"; } elseif ($cat == "none") { $category_conditions[] = " event_category_ids = ''"; } } $conditions[] = "(".implode(' OR', $category_conditions).")"; } elseif ( preg_match('/\+/', $category) ) { $category = explode('+', $category); $category_conditions = array(); foreach ($category as $cat) { if (is_numeric($cat) && $cat>0) $category_conditions[] = " FIND_IN_SET($cat,event_category_ids)"; } $conditions[] = "(".implode(' AND ', $category_conditions).")"; } elseif ( preg_match('/ /', $category) ) { // url decoding of '+' is ' ' $category = explode(' ', $category); $category_conditions = array(); foreach ($category as $cat) { if (is_numeric($cat) && $cat>0) $category_conditions[] = " FIND_IN_SET($cat,event_category_ids)"; } $conditions[] = "(".implode(' AND ', $category_conditions).")"; } } if (get_option('eme_categories_enabled')) { if (is_numeric($notcategory)) { if ($notcategory>0) $conditions[] = " NOT FIND_IN_SET($notcategory,event_category_ids)"; } elseif ($notcategory == "none") { $conditions[] = "event_category_ids != ''"; } elseif ( preg_match('/,/', $notcategory) ) { $notcategory = explode(',', $notcategory); $category_conditions = array(); foreach ($notcategory as $cat) { if (is_numeric($cat) && $cat>0) { $category_conditions[] = " NOT FIND_IN_SET($cat,event_category_ids)"; } elseif ($cat == "none") { $category_conditions[] = " event_category_ids != ''"; } } $conditions[] = "(".implode(' OR', $category_conditions).")"; } elseif ( preg_match('/\+/', $notcategory) ) { $notcategory = explode('+', $notcategory); $category_conditions = array(); foreach ($notcategory as $cat) { if (is_numeric($cat) && $cat>0) $category_conditions[] = " NOT FIND_IN_SET($cat,event_category_ids)"; } $conditions[] = "(".implode(' AND ', $category_conditions).")"; } elseif ( preg_match('/ /', $notcategory) ) { // url decoding of '+' is ' ' $notcategory = explode(' ', $notcategory); $category_conditions = array(); foreach ($notcategory as $cat) { if (is_numeric($cat) && $cat>0) $category_conditions[] = " NOT FIND_IN_SET($cat,event_category_ids)"; } } } // now filter the author ID if ($author != '' && !preg_match('/,/', $author)){ $authinfo=get_user_by('login', $author); $conditions[] = " event_author = ".$authinfo->ID; }elseif( preg_match('/,/', $author) ){ $authors = explode(',', $author); $author_conditions = array(); foreach($authors as $authname) { $authinfo=get_user_by('login', $authname); $author_conditions[] = " event_author = ".$authinfo->ID; } $conditions[] = "(".implode(' OR ', $author_conditions).")"; } // now filter the contact ID if ($contact_person != '' && !preg_match('/,/', $contact_person)){ $authinfo=get_user_by('login', $contact_person); $conditions[] = " event_contactperson_id = ".$authinfo->ID; }elseif( preg_match('/,/', $contact_person) ){ $contact_persons = explode(',', $contact_person); $contact_person_conditions = array(); foreach($contact_persons as $authname) { $authinfo=get_user_by('login', $authname); $contact_person_conditions[] = " event_contactperson_id = ".$authinfo->ID; } $conditions[] = "(".implode(' OR ', $contact_person_conditions).")"; } // extra conditions for authors: if we're in the admin itf, return only the events for which you have the right to change anything $current_userid=get_current_user_id(); if (is_admin() && !current_user_can( get_option('eme_cap_edit_events')) && !current_user_can( get_option('eme_cap_list_events')) && current_user_can( get_option('eme_cap_author_event'))) { $conditions[] = "(event_author = $current_userid OR event_contactperson_id= $current_userid)"; } $where = implode ( " AND ", $conditions ); if ($show_recurrent_events_once) { if ($where != "") $where = " AND " . $where; $sql = "SELECT * FROM $events_table WHERE (recurrence_id>0 $where) group by recurrence_id union all SELECT * FROM $events_table WHERE (recurrence_id=0 $where) ORDER BY event_start_date $order , event_start_time $order $limit $offset"; } else { if ($where != "") $where = " WHERE " . $where; $sql = "SELECT * FROM $events_table $where ORDER BY event_start_date $order , event_start_time $order $limit $offset"; } $wpdb->show_errors = true; $events = $wpdb->get_results ( $sql, ARRAY_A ); $inflated_events = array (); if (! empty ( $events )) { //$wpdb->print_error(); foreach ( $events as $this_event ) { $this_event = eme_get_event_data($this_event); array_push ( $inflated_events, $this_event ); } if (has_filter('eme_event_list_filter')) $inflated_events=apply_filters('eme_event_list_filter',$inflated_events); } return $inflated_events; } function eme_get_event($event_id) { global $wpdb; if (!$event_id) { return eme_new_event(); } $events_table = $wpdb->prefix . EVENTS_TBNAME; $conditions = array (); if (is_array($event_id)) { $conditions[] = "event_id IN (".join(',',$event_id).")"; } else { $event_id = intval($event_id); $conditions[] = "event_id = $event_id"; } // if we're not in the admin itf, we don't want draft events if (!is_admin()) { if (is_user_logged_in()) { if (! (current_user_can( get_option('eme_cap_edit_events')) || current_user_can( get_option('eme_cap_author_event')) || current_user_can( get_option('eme_cap_add_event')) || current_user_can( get_option('eme_cap_publish_event')) )) { $conditions[] = "event_status IN (".STATUS_PUBLIC.",".STATUS_PRIVATE.")"; } } else { $conditions[] = "event_status=".STATUS_PUBLIC; } } $where = implode ( " AND ", $conditions ); if ($where != "") $where = " WHERE " . $where; $sql = "SELECT * FROM $events_table $where"; if (!is_array($event_id)) { //$wpdb->show_errors(true); $event = $wpdb->get_row ( $sql, ARRAY_A ); //$wpdb->print_error(); if (!$event) { return eme_new_event(); } $event = eme_get_event_data($event); return $event; } else { $events = $wpdb->get_results ( $sql, ARRAY_A ); foreach ( $events as $key=>$event ) { $events[$key] = eme_get_event_data($event); } return $events; } } function eme_get_event_data($event) { if ($event['event_end_date'] == "") { $event['event_end_date'] = $event['event_start_date']; } if (is_serialized($event['event_attributes'])) $event['event_attributes'] = @unserialize($event['event_attributes']); $event['event_attributes'] = (!is_array($event['event_attributes'])) ? array() : $event['event_attributes'] ; if (is_serialized($event['event_properties'])) $event['event_properties'] = @unserialize($event['event_properties']); $event['event_properties'] = (!is_array($event['event_properties'])) ? array() : $event['event_properties'] ; $event['event_properties'] = eme_init_event_props($event['event_properties']); // don't forget the images (for the older events that didn't use the wp gallery) if (empty($event['event_image_id']) && empty($event['event_image_url'])) $event['event_image_url'] = eme_image_url_for_event($event); if (has_filter('eme_event_filter')) $event=apply_filters('eme_event_filter',$event); return $event; } function eme_events_table($message="",$scope="future") { if (!empty($message)) { echo "<div id='message' class='updated fade'><p>".eme_trans_sanitize_html($message)."</p></div>"; } //$list_limit = get_option('eme_events_admin_limit'); //if ($list_limit<5 || $list_limit>200) { // $list_limit=20; // update_option('eme_events_admin_limit',$list_limit); //} //$offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0; //$events = eme_get_events ( $limit+1, "future", "ASC", $offset ); $o_category = isset($_GET['category']) ? intval($_GET['category']) : 0; $status = isset($_GET['event_status']) ? intval($_GET['event_status']) : ''; if(!empty($status)) { $extra_conditions = 'event_status = '.$status; } else { $extra_conditions = ''; } //$events = eme_get_events ( 0, $scope, "ASC", $offset, "", $o_category, '', '', 1, '', 0, $extra_conditions); $events = eme_get_events ( 0, $scope, "ASC", 0, "", $o_category, '', '', 1, '', 0, $extra_conditions); $events_count = count ( $events ); $scope_names = array (); $scope_names['past'] = __ ( 'Past events', 'eme' ); $scope_names['all'] = __ ( 'All events', 'eme' ); $scope_names['future'] = __ ( 'Future events', 'eme' ); ?> <div class="wrap"> <div id="icon-events" class="icon32"><br /> </div> <h2><?php echo $scope_names[$scope]; ?></h2> <?php admin_show_warnings(); ?> <!--<div id='new-event' class='switch-tab'><a href="<?php echo admin_url("admin.php?page=events-manager&amp;eme_admin_action=edit_event")?>><?php _e ( 'New Event ...', 'eme' ); ?></a></div>--> <?php $event_status_array = eme_status_array (); ?> <div class="tablenav"> <form id="posts-filter" action="" method="get"> <input type='hidden' name='page' value='events-manager' /> <select name="scope"> <?php foreach ( $scope_names as $key => $value ) { $selected = ""; if ($key == $scope) $selected = "selected='selected'"; echo "<option value='$key' $selected>$value</option> "; } ?> </select> <select id="event_status" name="event_status"> <option value="0"><?php _e('Event Status','eme'); ?></option> <?php foreach($event_status_array as $event_status_key => $event_status_value): ?> <option value="<?php echo $event_status_key; ?>" <?php if (isset($_GET['event_status']) && ($_GET['event_status'] == $event_status_key)) echo 'selected="selected"'; ?>><?php echo $event_status_value; ?></option> <?php endforeach; ?> </select> <select name="category"> <option value='0'><?php _e('All categories','eme'); ?></option> <?php $categories = eme_get_categories(); foreach ( $categories as $category) { $selected = ""; if ($o_category == $category['category_id']) $selected = "selected='selected'"; echo "<option value='".$category['category_id']."' $selected>".$category['category_name']."</option>"; } ?> </select> <input id="post-query-submit" class="button-secondary" type="submit" value="<?php _e ( 'Filter' )?>" /> </form> <br /> <br /> <?php if ($events_count>0) { ?> <form id="eme_events_listform" action="" method="get"> <input type='hidden' name='page' value='events-manager' /> <select name="eme_admin_action"> <option value="-1" selected="selected"><?php _e ( 'Bulk Actions' ); ?></option> <option value="deleteEvents"><?php _e ( 'Delete selected events','eme' ); ?></option> <option value="deleteRecurrence"><?php _e ( 'Delete selected recurrent events','eme' ); ?></option> <option value="publicEvents"><?php _e ( 'Publish selected events','eme' ); ?></option> <option value="privateEvents"><?php _e ( 'Make selected events private','eme' ); ?></option> <option value="draftEvents"><?php _e ( 'Make selected events draft','eme' ); ?></option> </select> <input type="submit" value="<?php _e ( 'Apply' ); ?>" name="doaction2" id="doaction2" class="button-secondary action" /> <div class="clear"></div> <br /> <table class="widefat hover stripe" id="eme_admin_events"> <thead> <tr> <th class='manage-column column-cb check-column' scope='col'><input class='select-all' type="checkbox" value='1' /></th> <th><?php _e ('ID','eme'); ?></th> <th><?php _e ( 'Name', 'eme' ); ?></th> <th><?php _e ( 'Status', 'eme' ); ?></th> <th></th> <th><?php _e ( 'Location', 'eme' ); ?></th> <th><?php _e ( 'Date and time', 'eme' ); ?></th> <th></th> </tr> </thead> <tbody> <?php foreach ( $events as $event ) { $localised_start_date = eme_localised_date($event['event_start_date']); $localised_start_time = eme_localised_time($event['event_start_time']); $localised_end_date = eme_localised_date($event['event_end_date']); $localised_end_time = eme_localised_time($event['event_end_time']); $startstring=strtotime($event['event_start_date']." ".$event['event_start_time']); $today = date ( "Y-m-d" ); $location_summary = ""; if (isset($event['location_id']) && $event['location_id']) { $location = eme_get_location ( $event['location_id'] ); $location_summary = "<b>" . eme_trans_sanitize_html($location['location_name']) . "</b><br />" . eme_trans_sanitize_html($location['location_address']) . " - " . eme_trans_sanitize_html($location['location_town']); } $style = ""; if ($event['event_start_date'] < $today) $style = "style ='background-color: #FADDB7;'"; ?> <tr <?php echo "$style"; ?>> <td><input type='checkbox' class='row-selector' value='<?php echo $event['event_id']; ?>' name='events[]' /></td> <td><?php echo $event['event_id']; ?></td> <td><strong> <a class="row-title" href="<?php echo admin_url("admin.php?page=events-manager&amp;eme_admin_action=edit_event&amp;event_id=".$event['event_id']); ?>"><?php echo eme_trans_sanitize_html($event['event_name']); ?></a> </strong> <?php $categories = explode(',', $event['event_category_ids']); foreach($categories as $cat){ $category = eme_get_category($cat); if($category) echo "<br /><span title='".__('Category','eme').": ".eme_trans_sanitize_html($category['category_name'])."'>".eme_trans_sanitize_html($category['category_name'])."</span>"; } if ($event['event_rsvp']) { $booked_seats = eme_get_booked_seats($event['event_id']); $available_seats = eme_get_available_seats($event['event_id']); $pending_seats = eme_get_pending_seats($event['event_id']); $total_seats = $event['event_seats']; if (eme_is_multi($event['event_seats'])) { $available_seats_string = $available_seats.' ('.eme_convert_array2multi(eme_get_available_multiseats($event['event_id'])).')'; $pending_seats_string = $pending_seats.' ('.eme_convert_array2multi(eme_get_pending_multiseats($event['event_id'])).')'; $total_seats_string = eme_get_multitotal($total_seats) .' ('.$event['event_seats'].')'; } else { $available_seats_string = $available_seats; $pending_seats_string = $pending_seats; $total_seats_string = $total_seats; } if ($pending_seats >0) echo "<br />".__('RSVP Info: ','eme').__('Free: ','eme' ).$available_seats_string.", ".__('Pending: ','eme').$pending_seats_string.", ".__('Max: ','eme').$total_seats_string; else echo "<br />".__('RSVP Info: ','eme').__('Free: ','eme' ).$available_seats_string.", ".__('Max: ','eme').$total_seats_string; if ($booked_seats>0) { $printable_address = admin_url("admin.php?page=eme-people&amp;eme_admin_action=booking_printable&amp;event_id=".$event['event_id']); $csv_address = admin_url("admin.php?page=eme-people&amp;eme_admin_action=booking_csv&amp;event_id=".$event['event_id']); echo " (<a id='booking_printable_".$event['event_id']."' href='$printable_address'>".__('Printable view','eme')."</a>)"; echo " (<a id='booking_csv_".$event['event_id']."' href='$csv_address'>".__('CSV export','eme')."</a>)"; } } ?> </td> <td> <?php if (isset ($event_status_array[$event['event_status']])) { echo $event_status_array[$event['event_status']]; $event_url = eme_event_url($event); if ($event['event_status'] == STATUS_DRAFT) echo "<br /> <a href='$event_url'>".__('Preview event','eme')."</a>"; else echo "<br /> <a href='$event_url'>".__('View event','eme')."</a>"; } ?> </td> <td> <a href="<?php echo admin_url("admin.php?page=events-manager&amp;eme_admin_action=duplicate_event&amp;event_id=".$event['event_id']); ?>" title="<?php _e ( 'Duplicate this event', 'eme' ); ?>"><strong>+</strong></a> </td> <td> <?php echo $location_summary; ?> </td> <td data-sort="<?php echo $startstring; ?>"> <?php echo $localised_start_date; if ($localised_end_date !='' && $localised_end_date!=$localised_start_date) echo " - " . $localised_end_date; ?><br /> <?php if ($event['event_properties']['all_day']==1) _e('All day','eme'); else echo "$localised_start_time - $localised_end_time"; ?> </td> <td> <?php if ($event['recurrence_id']) { $recurrence_desc = eme_get_recurrence_desc ( $event['recurrence_id'] ); ?> <b><?php echo $recurrence_desc; ?> <br /> <a href="<?php echo admin_url("admin.php?page=events-manager&amp;eme_admin_action=edit_recurrence&amp;recurrence_id=".$event['recurrence_id']); ?>"><?php print sprintf (__( 'Edit Recurrence ID %d', 'eme' ),$event['recurrence_id']); ?></a></b> <?php } ?> </td> </tr> <?php } ?> </tbody> </table> </form> <?php } else { echo "<div id='events-admin-no-events'>" . get_option('eme_no_events_message') . "</div></div>"; } ?> <script type="text/javascript"> jQuery(document).ready( function() { jQuery('#eme_admin_events').dataTable( { <?php $locale_code = get_locale(); $locale_file = EME_PLUGIN_DIR. "js/jquery-datatables/i18n/$locale_code.json"; $locale_file_url = EME_PLUGIN_URL. "js/jquery-datatables/i18n/$locale_code.json"; if ($locale_code != "en_US" && file_exists($locale_file)) { ?> "language": { "url": "<?php echo $locale_file_url; ?>" }, <?php } ?> "stateSave": true, "pagingType": "full", "columnDefs": [ { "sortable": false, "targets": [0,4,7] } ] } ); jQuery('form').on('click','input:submit[name=doaction2]',function() { if (jQuery('select[name=eme_admin_action]').val() == "deleteEvents" || jQuery('select[name=eme_admin_action]').val() == "deleteRecurrence") { return window.confirm(this.title || 'Do you really want to delete these events?'); } else { return true; } }); } ); </script> </div> </div> <?php } function eme_event_form($event, $title, $element) { admin_show_warnings(); global $plugin_page; $event_status_array = eme_status_array (); $saved_bydays = array(); $currency_array = eme_currency_array(); // let's determine if it is a new event, handy // or, in case of validation errors, $event can already contain info, but no $element (=event id) // so we create a new event and copy over the info into $event for the elements that do not exist if (! $element) { $is_new_event=1; $new_event=eme_new_event(); $event = array_replace_recursive($new_event,$event); } else { $is_new_event=0; } $show_recurrent_form = 0; if (isset($_GET['eme_admin_action']) && $_GET['eme_admin_action'] == "edit_recurrence") { $pref = "recurrence"; $form_destination = "admin.php?page=events-manager&amp;eme_admin_action=update_recurrence&amp;recurrence_id=" . $element; $saved_bydays = explode ( ",", $event['recurrence_byday'] ); $show_recurrent_form = 1; } else { $pref = "event"; // even for new events, after the 'save' button is clicked, we want to go to the list of events // so we use page=events-manager too, not page=eme-new_event if ($is_new_event) $form_destination = "admin.php?page=events-manager&amp;eme_admin_action=insert_event"; else $form_destination = "admin.php?page=events-manager&amp;eme_admin_action=update_event&amp;event_id=" . $element; if (isset($event['recurrence_id']) && $event['recurrence_id']) { # editing a single event of an recurrence: don't show the recurrence form $show_recurrent_form = 0; } else { # for single non-recurrent events: we show the form, so we can make it recurrent if we want to # but for that, we need to set the recurrence fields, otherwise we get warnings $show_recurrent_form = 1; $event['recurrence_id'] = 0; $event['recurrence_freq'] = ''; $event['recurrence_start_date'] = $event['event_start_date']; $event['recurrence_end_date'] = $event['event_end_date']; $event['recurrence_interval'] = ''; $event['recurrence_byweekno'] = ''; $event['recurrence_byday'] = ''; $event['recurrence_specific_days'] = ''; } } if (!isset($event['recurrence_start_date'])) $event['recurrence_start_date']=$event['event_start_date']; if (!isset($event['recurrence_end_date'])) $event['recurrence_end_date']=$event['event_end_date']; $freq_options = array ("daily" => __ ( 'Daily', 'eme' ), "weekly" => __ ( 'Weekly', 'eme' ), "monthly" => __ ( 'Monthly', 'eme' ), "specific" => __('Specific days', 'eme' ) ); $days_names = array (1 => __ ( 'Mon' ), 2 => __ ( 'Tue' ), 3 => __ ( 'Wed' ), 4 => __ ( 'Thu' ), 5 => __ ( 'Fri' ), 6 => __ ( 'Sat' ), 7 => __ ( 'Sun' ) ); $weekno_options = array ("1" => __ ( 'first', 'eme' ), '2' => __ ( 'second', 'eme' ), '3' => __ ( 'third', 'eme' ), '4' => __ ( 'fourth', 'eme' ), '5' => __ ( 'fifth', 'eme' ), '-1' => __ ( 'last', 'eme' ), "0" => __('Start day') ); $event_RSVP_checked = ($event['event_rsvp']) ? "checked='checked'" : ""; $event_number_spaces=$event['event_seats']; $registration_wp_users_only = ($event['registration_wp_users_only']) ? "checked='checked'" : ""; $registration_requires_approval = ($event['registration_requires_approval']) ? "checked='checked'" : ""; $use_paypal_checked = ($event['use_paypal']) ? "checked='checked'" : ""; $use_2co_checked = ($event['use_2co']) ? "checked='checked'" : ""; $use_webmoney_checked = ($event['use_webmoney']) ? "checked='checked'" : ""; $use_fdgg_checked = ($event['use_fdgg']) ? "checked='checked'" : ""; $use_mollie_checked = ($event['use_mollie']) ? "checked='checked'" : ""; // all properties $eme_prop_auto_approve_checked = ($event['event_properties']['auto_approve']) ? "checked='checked'" : ""; $eme_prop_ignore_pending_checked = ($event['event_properties']['ignore_pending']) ? "checked='checked'" : ""; $eme_prop_take_attendance = ($event['event_properties']['take_attendance']) ? "checked='checked'" : ""; $eme_prop_all_day_checked = ($event['event_properties']['all_day']) ? "checked='checked'" : ""; // the next javascript will fill in the values for localised-start-date, ... form fields and jquery datepick will fill in also to "to_submit" form fields ?> <script type="text/javascript"> jQuery(document).ready( function() { var dateFormat = jQuery("#localised-start-date").datepick( "option", "dateFormat" ); var loc_start_date = jQuery.datepick.newDate(<?php echo date('Y,n,j',strtotime($event['event_start_date'])); ?>); jQuery("#localised-start-date").datepick("setDate", jQuery.datepick.formatDate(dateFormat, loc_start_date)); var loc_end_date = jQuery.datepick.newDate(<?php echo date('Y,n,j',strtotime($event['event_end_date'])); ?>); jQuery("#localised-end-date").datepick("setDate", jQuery.datepick.formatDate(dateFormat, loc_end_date)); <?php if ($pref == "recurrence" && $event['recurrence_freq'] == 'specific') { ?> var mydates = []; <?php foreach (explode(',',$event['recurrence_specific_days']) as $specific_day) { ?> mydates.push(jQuery.datepick.newDate(<?php echo date('Y,n,j',strtotime($specific_day)); ?>)); <?php } ?> jQuery("#localised-rec-start-date").datepick("setDate", mydates); <?php } else { ?> var rec_start_date = jQuery.datepick.newDate(<?php echo date('Y,n,j',strtotime($event['recurrence_start_date'])); ?>); jQuery("#localised-rec-start-date").datepick("setDate", jQuery.datepick.formatDate(dateFormat, rec_start_date)); <?php } ?> var rec_end_date = jQuery.datepick.newDate(<?php echo date('Y,n,j',strtotime($event['recurrence_end_date'])); ?>); jQuery("#localised-rec-end-date").datepick("setDate", jQuery.datepick.formatDate(dateFormat, rec_end_date)); }); </script> <form id="eventForm" name="eventForm" method="post" enctype="multipart/form-data" action="<?php echo $form_destination; ?>"> <div class="wrap"> <div id="icon-events" class="icon32"><br /></div> <h2><?php echo eme_trans_sanitize_html($title); ?></h2> <?php if ($event['recurrence_id']) { ?> <p id='recurrence_warning'> <?php if (isset ( $_GET['eme_admin_action'] ) && ($_GET['eme_admin_action'] == 'edit_recurrence')) { _e ( 'WARNING: This is a recurrence.', 'eme' )?> <br /> <?php _e ( 'Modifying these data all the events linked to this recurrence will be rescheduled', 'eme' ); } else { _e ( 'WARNING: This is a recurring event.', 'eme' ); _e ( 'If you change these data and save, this will become an independent event.', 'eme' ); } ?> </p> <?php } ?> <div id="poststuff" class="metabox-holder has-right-sidebar"> <!-- SIDEBAR --> <div id="side-info-column" class='inner-sidebar'> <div id='side-sortables' class="meta-box-sortables"> <?php if(current_user_can( get_option('eme_cap_author_event'))) { ?> <!-- status postbox --> <div class="postbox "> <div class="handlediv" title="Click to toggle."><br /> </div> <h3 class='hndle'><span> <?php _e ( 'Event Status', 'eme' ); ?> </span></h3> <div class="inside"> <p><?php _e('Status','eme'); ?> <select id="event_status" name="event_status"> <?php foreach ( $event_status_array as $key=>$value) { if ($event['event_status'] && ($event['event_status']==$key)) { $selected = "selected='selected'"; } else { $selected = ""; } echo "<option value='$key' $selected>$value</option>"; } ?> </select><br /> <?php _e('Private events are only visible for logged in users, draft events are not visible from the front end.','eme'); ?> </p> </div> </div> <?php } ?> <?php if(get_option('eme_recurrence_enabled') && $show_recurrent_form ) : ?> <!-- recurrence postbox --> <div class="postbox "> <div class="handlediv" title="Click to toggle."><br /> </div> <h3 class='hndle'><span> <?php _e ( "Recurrence", 'eme' ); ?> </span></h3> <div class="inside"> <?php $recurrence_YES = ""; if ($event['recurrence_id']) $recurrence_YES = "checked='checked' disabled='disabled'"; ?> <p> <input id="event-recurrence" type="checkbox" name="repeated_event" value="1" <?php echo $recurrence_YES; ?> /> </p> <div id="event_recurrence_pattern"> <p>Frequency: <select id="recurrence-frequency" name="recurrence_freq"> <?php eme_option_items ( $freq_options, $event['recurrence_freq'] ); ?> </select> </p> <div id="recurrence-intervals"> <p> <?php _e ( 'Every', 'eme' )?> <input id="recurrence-interval" name='recurrence_interval' size='2' value='<?php if (isset ($event['recurrence_interval'])) echo $event['recurrence_interval']; ?>' /> <span class='interval-desc' id="interval-daily-singular"> <?php _e ( 'day', 'eme' )?> </span> <span class='interval-desc' id="interval-daily-plural"> <?php _e ( 'days', 'eme' ) ?> </span> <span class='interval-desc' id="interval-weekly-singular"> <?php _e ( 'week', 'eme' )?> </span> <span class='interval-desc' id="interval-weekly-plural"> <?php _e ( 'weeks', 'eme' )?> </span> <span class='interval-desc' id="interval-monthly-singular"> <?php _e ( 'month', 'eme' )?> </span> <span class='interval-desc' id="interval-monthly-plural"> <?php _e ( 'months', 'eme' )?> </span> </p> <p class="alternate-selector" id="weekly-selector"> <?php eme_checkbox_items ( 'recurrence_bydays[]', $days_names, $saved_bydays ); ?> <br /> <?php _e ( 'If you leave this empty, the recurrence start date will be used as a reference.', 'eme' )?> </p> <p class="alternate-selector" id="monthly-selector"> <?php _e ( 'Every', 'eme' )?> <select id="monthly-modifier" name="recurrence_byweekno"> <?php eme_option_items ( $weekno_options, $event['recurrence_byweekno'] ); ?> </select> <select id="recurrence-weekday" name="recurrence_byday"> <?php eme_option_items ( $days_names, $event['recurrence_byday'] ); ?> </select> <?php _e ( 'Day of month', 'eme' )?> <br /> <?php _e ( 'If you use "Start day" as day of the month, the recurrence start date will be used as a reference.', 'eme' )?> &nbsp; </p> </div> </div> <p id="recurrence-tip"> <?php _e ( 'Check if your event happens more than once.', 'eme' )?> </p> <p id="recurrence-tip-2"> <?php _e ( 'The event start and end date only define the duration of an event in case of a recurrence.', 'eme' )?> </p> </div> </div> <?php endif; ?> <?php if($event['event_author']) : ?> <!-- owner postbox --> <div class="postbox "> <div class="handlediv" title="Click to toggle."><br /> </div> <h3 class='hndle'><span> <?php _e ( 'Author', 'eme' ); ?> </span></h3> <div class="inside"> <p><?php _e('Author of this event: ','eme'); ?> <?php $owner_user_info = get_userdata($event['event_author']); echo eme_sanitize_html($owner_user_info->display_name); ?> </p> </div> </div> <?php endif; ?> <div class="postbox "> <div class="handlediv" title="Click to toggle."><br /> </div> <h3 class='hndle'><span> <?php _e ( 'Contact Person', 'eme' ); ?> </span></h3> <div class="inside"> <p><?php _e('Contact','eme'); ?> <?php wp_dropdown_users ( array ('name' => 'event_contactperson_id', 'show_option_none' => __ ( "Event author", 'eme' ), 'selected' => $event['event_contactperson_id'] ) ); // if it is not a new event and there's no contact person defined, then the event author becomes contact person // So let's display a warning what this means if there's no author (like when submitting via the frontend submission form) if (!$is_new_event && $event['event_contactperson_id']<1 && $event['event_author']<1) print "<br />". __( 'Since the author is undefined for this event, any reference to the contact person (like when using #_CONTACTPERSON when sending mails), will use the admin user info.', 'eme' ); ?> </p> </div> </div> <?php if(get_option('eme_rsvp_enabled')) : ?> <div class="postbox "> <div class="handlediv" title="Click to toggle."><br /> </div> <h3 class='hndle'><span><?php _e('RSVP','eme'); ?></span></h3> <div class="inside"> <p> <input id="rsvp-checkbox" name='event_rsvp' value='1' type='checkbox' <?php echo $event_RSVP_checked; ?> /> <?php _e ( 'Enable registration for this event', 'eme' )?> </p> <div id='rsvp-data'> <p> <input id="approval_required-checkbox" name='registration_requires_approval' value='1' type='checkbox' <?php echo $registration_requires_approval; ?> /> <?php _e ( 'Require approval for registration','eme' ); ?> <br /> <input id="eme_prop_auto_approve" name='eme_prop_auto_approve' value='1' type='checkbox' <?php echo $eme_prop_auto_approve_checked; ?> /> <?php _e ( 'Auto-approve registration upon payment','eme' ); ?> <br /> <input id="eme_prop_ignore_pending" name='eme_prop_ignore_pending' value='1' type='checkbox' <?php echo $eme_prop_ignore_pending_checked; ?> /> <?php _e ( 'Consider pending registrations as available seats for new bookings','eme' ); ?> <br /> <input id="wp_member_required-checkbox" name='registration_wp_users_only' value='1' type='checkbox' <?php echo $registration_wp_users_only; ?> /> <?php _e ( 'Require WP membership for registration','eme' ); ?> <br /> <input id="eme_prop_take_attendance" name='eme_prop_take_attendance' value='1' type='checkbox' <?php echo $eme_prop_take_attendance; ?> /> <?php _e ( 'Only take attendance (0 or 1 seat) for this event','eme' ); ?> <br /><table> <tr> <td><?php _e ( 'Spaces','eme' ); ?> :</td> <td><input id="seats-input" type="text" name="event_seats" maxlength='125' title="<?php _e('For multiseat events, seperate the values by \'||\'','eme'); ?>" value="<?php echo $event_number_spaces; ?>" /></td> </tr> <tr> <td><?php _e ( 'Price: ','eme' ); ?></td> <td><input id="price" type="text" name="price" maxlength='125' title="<?php _e('For multiprice events, seperate the values by \'||\'','eme'); ?>" value="<?php echo $event['price']; ?>" /></td> </tr> <tr> <td><?php _e ( 'Currency: ','eme' ); ?></td> <td><select id="currency" name="currency"> <?php foreach ( $currency_array as $key=>$value) { if ($event['currency'] && ($event['currency']==$key)) { $selected = "selected='selected'"; } elseif (!$event['currency'] && ($key==get_option('eme_default_currency'))) { $selected = "selected='selected'"; } else { $selected = ""; } echo "<option value='$key' $selected>$value</option>"; } ?> </select></td> </tr> <tr> <td><?php _e ( 'Max number of spaces to book','eme' ); ?></td> <td><input id="eme_prop_max_allowed" type="text" name="eme_prop_max_allowed" maxlength='125' title="<?php echo __('The maximum number of spaces a person can book in one go.','eme').' '.__('(is multi-compatible)','eme'); ?>" value="<?php echo $event['event_properties']['max_allowed']; ?>" /></td> </tr> <tr> <td><?php _e ( 'Min number of spaces to book','eme' ); ?></td> <td><input id="eme_prop_min_allowed" type="text" name="eme_prop_min_allowed" maxlength='125' title="<?php echo __('The minimum number of spaces a person can book in one go (it can be 0, for e.g. just an attendee list).','eme').' '.__('(is multi-compatible)','eme'); ?>" value="<?php echo $event['event_properties']['min_allowed']; ?>" /></td> </tr></table> <br /> <?php _e ( 'Allow RSVP until ','eme' ); ?> <br /> <input id="rsvp_number_days" type="text" name="rsvp_number_days" maxlength='2' size='2' value="<?php echo $event['rsvp_number_days']; ?>" /> <?php _e ( 'days','eme' ); ?> <input id="rsvp_number_hours" type="text" name="rsvp_number_hours" maxlength='2' size='2' value="<?php echo $event['rsvp_number_hours']; ?>" /> <?php _e ( 'hours','eme' ); ?> <br /> <?php _e ( 'before the event ','eme' ); $eme_rsvp_end_target_list = array('start'=>__('starts','eme'),'end'=>__('ends','eme')); echo eme_ui_select($event['event_properties']['rsvp_end_target'],'eme_prop_rsvp_end_target',$eme_rsvp_end_target_list); ?> <br /> <br /> <?php _e ( 'Payment methods','eme' ); ?><br /> <input id="paypal-checkbox" name='use_paypal' value='1' type='checkbox' <?php echo $use_paypal_checked; ?> /><?php _e ( 'Paypal','eme' ); ?><br /> <input id="2co-checkbox" name='use_2co' value='1' type='checkbox' <?php echo $use_2co_checked; ?> /><?php _e ( '2Checkout','eme' ); ?><br /> <input id="webmoney-checkbox" name='use_webmoney' value='1' type='checkbox' <?php echo $use_webmoney_checked; ?> /><?php _e ( 'Webmoney','eme' ); ?><br /> <input id="fdgg-checkbox" name='use_fdgg' value='1' type='checkbox' <?php echo $use_fdgg_checked; ?> /><?php _e ( 'First Data','eme' ); ?><br /> <input id="mollie-checkbox" name='use_mollie' value='1' type='checkbox' <?php echo $use_mollie_checked; ?> /><?php _e ( 'Mollie','eme' ); ?><br /> </p> <?php if ($event['event_rsvp'] && $pref != "recurrence") { // show the compact bookings table only when not editing a recurrence eme_bookings_compact_table ( $event['event_id'] ); } ?> </div> </div> </div> <?php endif; ?> <?php if(get_option('eme_categories_enabled')) :?> <div class="postbox "> <div class="handlediv" title="Click to toggle."><br /> </div> <h3 class='hndle'><span> <?php _e ( 'Category', 'eme' ); ?> </span></h3> <div class="inside"> <?php $categories = eme_get_categories(); foreach ( $categories as $category) { if ($event['event_category_ids'] && in_array($category['category_id'],explode(",",$event['event_category_ids']))) { $selected = "checked='checked'"; } else { $selected = ""; } ?> <input type="checkbox" name="event_category_ids[]" value="<?php echo $category['category_id']; ?>" <?php echo $selected ?> /><?php echo $category['category_name']; ?><br /> <?php } ?> </div> </div> <?php endif; ?> </div> </div> <!-- END OF SIDEBAR --> <div id="post-body"> <div id="post-body-content" class="meta-box-sortables"> <?php if($plugin_page === 'eme-new_event' && get_option("eme_fb_app_id")) { ?> <div id="fb-root"></div> <script> window.fbAsyncInit = function() { // init the FB JS SDK FB.init({ appId : '<?php echo get_option("eme_fb_app_id");?>',// App ID from the app dashboard channelUrl : '<?php echo plugins_url( "eme_fb_channel.php", __FILE__ )?>', // Channel file for x-domain comms status : true, // Check Facebook Login status xfbml : true // Look for social plugins on the page }); // Additional initialization code such as adding Event Listeners goes here FB.Event.subscribe('auth.authResponseChange', function(response) { if (response.status === 'connected') { jQuery('#fb-import-box').show(); } else if (response.status === 'not_authorized') { jQuery('#fb-import-box').hide(); } else { jQuery('#fb-import-box').hide(); } }); }; // Load the SDK asynchronously (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <fb:login-button id="fb-login-button" width="200" autologoutlink="true" scope="user_events" max-rows="1"></fb:login-button> <br /> <br /> <div id='fb-import-box' style='display:none'> Facebook event url : <input type='text' id='fb-event-url' class='widefat' /> <br /> <br /> <input type='button' class='button' value='Import' id='import-fb-event-btn' /> <br /> <br /> </div> <?php } ?> <?php $screens = array( 'events_page_eme-new_event', 'toplevel_page_events-manager' ); foreach ($screens as $screen) { if ($event['event_page_title_format']=="" && $event['event_properties']['event_page_title_format_tpl']==0) add_filter('postbox_classes_'.$screen.'_div_event_page_title_format','eme_closed'); if ($event['event_single_event_format']=="" && $event['event_properties']['event_single_event_format_tpl']==0) add_filter('postbox_classes_'.$screen.'_div_event_single_event_format','eme_closed'); if ($event['event_contactperson_email_body']=="" && $event['event_properties']['event_contactperson_email_body_tpl']==0) add_filter('postbox_classes_'.$screen.'_div_event_contactperson_email_body','eme_closed'); if ($event['event_registration_recorded_ok_html']=="" && $event['event_properties']['event_registration_recorded_ok_html_tpl']==0) add_filter('postbox_classes_'.$screen.'_div_event_registration_recorded_ok_html','eme_closed'); if ($event['event_respondent_email_body']=="" && $event['event_properties']['event_respondent_email_body_tpl']==0) add_filter('postbox_classes_'.$screen.'_div_event_respondent_email_body','eme_closed'); if ($event['event_registration_pending_email_body']=="" && $event['event_properties']['event_registration_pending_email_body_tpl']==0) add_filter('postbox_classes_'.$screen.'_div_event_registration_pending_email_body','eme_closed'); if ($event['event_registration_updated_email_body']=="" && $event['event_properties']['event_registration_updated_email_body_tpl']==0) add_filter('postbox_classes_'.$screen.'_div_event_registration_updated_email_body','eme_closed'); if ($event['event_registration_form_format']=="" && $event['event_properties']['event_registration_form_format_tpl']==0) add_filter('postbox_classes_'.$screen.'_div_event_registration_form_format','eme_closed'); if ($event['event_cancel_form_format']=="" && $event['event_properties']['event_cancel_form_format_tpl']==0) add_filter('postbox_classes_'.$screen.'_div_event_cancel_form_format','eme_closed'); } // we can only give one parameter to do_meta_boxes, but we don't want to list the templates each time // so temporary we store the array in the $event var and unset it afterwards $templates_array=eme_get_templates_array_by_id(); // the first element is something empty or a "no templates" string, but we need to keep the array indexes // so we concatenate using "+", not array_merge if (is_array($templates_array) && count($templates_array)>0) $templates_array=array(0=>'')+$templates_array; else $templates_array=array(0=>__('No templates defined yet!','eme')); $event['templates_array']=$templates_array; if ($is_new_event) { // we add the meta boxes only on the page we're currently at, so for duplicate event it is the same as for edit event // see the eme_admin_event_boxes function if (isset($_GET['eme_admin_action']) && $_GET['eme_admin_action'] == 'duplicate_event') do_meta_boxes('toplevel_page_events-manager',"post",$event); else do_meta_boxes('events_page_eme-new_event',"post",$event); } else { do_meta_boxes('toplevel_page_events-manager',"post",$event); } unset($event['templates_array']); ?> </div> <p class="submit"> <?php if ($is_new_event) { ?> <input type="submit" class="button-primary" id="event_update_button" name="event_update_button" value="<?php _e ( 'Save' ); ?> &raquo;" /> <?php } else { $delete_button_text=__ ( 'Are you sure you want to delete this event?', 'eme' ); $deleteRecurrence_button_text=__ ( 'Are you sure you want to delete this recurrence?', 'eme' ); ?> <?php if ($pref == "recurrence") { ?> <input type="submit" class="button-primary" id="event_update_button" name="event_update_button" value="<?php _e ( 'Update' ); ?> &raquo;" /> <?php } else { ?> <input type="submit" class="button-primary" id="event_update_button" name="event_update_button" value="<?php _e ( 'Update' ); ?> &raquo;" /> <?php } ?> <input type="submit" class="button-primary" id="event_delete_button" name="event_delete_button" value="<?php _e ( 'Delete Event', 'eme' ); ?> &raquo;" onclick="return areyousure('<?php echo $delete_button_text; ?>');" /> <?php if ($event['recurrence_id']) { ?> <input type="submit" class="button-primary" id="event_deleteRecurrence_button" name="event_deleteRecurrence_button" value="<?php _e ( 'Delete Recurrence', 'eme' ); ?> &raquo;" onclick="return areyousure('<?php echo $deleteRecurrence_button_text; ?>');" /> <?php } ?> <?php } ?> </p> </div> </div> </div> <?php wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false ); ?> <?php wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false ); ?> </form> <?php } function eme_validate_event($event) { $required_fields = array("event_name" => __('The event name', 'eme')); $troubles = ""; if (empty($event['event_name'])) { $troubles .= "<li>".$required_fields['event_name'].__(" is missing!", "eme")."</li>"; } if (isset($_POST['repeated_event']) && $_POST['repeated_event'] == "1" && (!isset($_POST['recurrence_end_date']) || $_POST['recurrence_end_date'] == "")) $troubles .= "<li>".__ ( 'Since the event is repeated, you must specify an event date for the recurrence.', 'eme' )."</li>"; if (eme_is_multi($event['event_seats']) && !eme_is_multi($event['price'])) $troubles .= "<li>".__ ( 'Since the event contains multiple seat categories (multiseat), you must specify the price per category (multiprice) as well.', 'eme' )."</li>"; if (eme_is_multi($event['event_seats']) && eme_is_multi($event['price'])) { $count1=count(eme_convert_multi2array($event['event_seats'])); $count2=count(eme_convert_multi2array($event['price'])); if ($count1 != $count2) $troubles .= "<li>".__ ( 'Since the event contains multiple seat categories (multiseat), you must specify the exact same amount of prices (multiprice) as well.', 'eme' )."</li>"; } if (is_serialized($event['event_properties'])) $event_properties = unserialize($event['event_properties']); if (eme_is_multi($event_properties['max_allowed']) && eme_is_multi($event['price'])) { $count1=count(eme_convert_multi2array($event_properties['max_allowed'])); $count2=count(eme_convert_multi2array($event['price'])); if ($count1 != $count2) $troubles .= "<li>".__ ( 'Since this is a multiprice event and you decided to limit the max amount of seats to book (for one booking) per price category, you must specify the exact same amount of "max seats to book" as you did for the prices.', 'eme' )."</li>"; } if (eme_is_multi($event_properties['min_allowed']) && eme_is_multi($event['price'])) { $count1=count(eme_convert_multi2array($event_properties['min_allowed'])); $count2=count(eme_convert_multi2array($event['price'])); if ($count1 != $count2) $troubles .= "<li>".__ ( 'Since this is a multiprice event and you decided to limit the min amount of seats to book (for one booking) per price category, you must specify the exact same amount of "min seats to book" as you did for the prices.', 'eme' )."</li>"; } if (empty($troubles)) { return "OK"; } else { $message = __('Ach, some problems here:', 'eme')."<ul>\n$troubles</ul>"; return $message; } } function eme_closed($data) { $data[]="closed"; return $data; } // General script to make sure hidden fields are shown when containing data function eme_admin_event_script() { // check if the user wants AM/PM or 24 hour notation // make sure that escaped characters are filtered out first $time_format = preg_replace('/\\\\./','',get_option('time_format')); $show24Hours = 'true'; if (preg_match ( "/g|h/", $time_format )) $show24Hours = 'false'; // jquery ui locales are with dashes, not underscores $locale_code = get_locale(); $use_select_for_locations = get_option('eme_use_select_for_locations')?1:0; $lang = eme_detect_lang(); if (!empty($lang)) { $use_select_for_locations=1; } ?> <script type="text/javascript"> //<![CDATA[ var show24Hours = <?php echo $show24Hours;?>; var locale_code = '<?php echo $locale_code;?>'; var firstDayOfWeek = <?php echo get_option('start_of_week');?>; var eme_locations_search_url = "<?php echo EME_PLUGIN_URL; ?>locations-search.php"; var gmap_enabled = <?php echo get_option('eme_gmap_is_active')?1:0; ?>; var use_select_for_locations = <?php echo $use_select_for_locations; ?>; function eme_event_page_title_format(){ var tmp_value='<?php echo rawurlencode(get_option('eme_event_page_title_format' )); ?>'; tmp_value=unescape(tmp_value).replace(/\r\n/g,"\n"); return tmp_value; } function eme_single_event_format(){ var tmp_value='<?php echo rawurlencode(get_option('eme_single_event_format' )); ?>'; tmp_value=unescape(tmp_value).replace(/\r\n/g,"\n"); return tmp_value; } function eme_contactperson_email_body(){ var tmp_value='<?php echo rawurlencode(get_option('eme_contactperson_email_body' )); ?>'; tmp_value=unescape(tmp_value).replace(/\r\n/g,"\n"); return tmp_value; } function eme_respondent_email_body(){ var tmp_value='<?php echo rawurlencode(get_option('eme_respondent_email_body' )); ?>'; tmp_value=unescape(tmp_value).replace(/\r\n/g,"\n"); return tmp_value; } function eme_registration_recorded_ok_html(){ var tmp_value='<?php echo rawurlencode(get_option('eme_registration_recorded_ok_html' )); ?>'; tmp_value=unescape(tmp_value).replace(/\r\n/g,"\n"); return tmp_value; } function eme_registration_pending_email_body(){ var tmp_value='<?php echo rawurlencode(get_option('eme_registration_pending_email_body' )); ?>'; tmp_value=unescape(tmp_value).replace(/\r\n/g,"\n"); return tmp_value; } function eme_registration_updated_email_body(){ var tmp_value='<?php echo rawurlencode(get_option('eme_registration_updated_email_body' )); ?>'; tmp_value=unescape(tmp_value).replace(/\r\n/g,"\n"); return tmp_value; } function eme_registration_form_format(){ var tmp_value='<?php echo rawurlencode(get_option('eme_registration_form_format' )); ?>'; tmp_value=unescape(tmp_value).replace(/\r\n/g,"\n"); return tmp_value; } function eme_cancel_form_format(){ var tmp_value='<?php echo rawurlencode(get_option('eme_cancel_form_format' )); ?>'; tmp_value=unescape(tmp_value).replace(/\r\n/g,"\n"); return tmp_value; } //]]> </script> <?php } //function eme_admin_options_save() { // if (is_admin() && isset($_GET['settings-updated']) && $_GET['settings-updated']) { // return; // } //} function eme_admin_event_boxes() { global $plugin_page; $screens = array( 'events_page_eme-new_event', 'toplevel_page_events-manager' ); foreach ($screens as $screen) { if (preg_match("/$plugin_page/",$screen)) { // we need titlediv for qtranslate as ID add_meta_box("titlediv", __('Name', 'eme'), "eme_meta_box_div_event_name",$screen,"post"); add_meta_box("div_recurrence_date", __('Recurrence dates', 'eme'), "eme_meta_box_div_recurrence_date",$screen,"post"); add_meta_box("div_event_date", __('Event date', 'eme'), "eme_meta_box_div_event_date",$screen,"post"); add_meta_box("div_event_time", __('Event time', 'eme'), "eme_meta_box_div_event_time",$screen,"post"); add_meta_box("div_event_page_title_format", __('Single Event Title Format', 'eme'), "eme_meta_box_div_event_page_title_format",$screen,"post"); add_meta_box("div_event_single_event_format", __('Single Event Format', 'eme'), "eme_meta_box_div_event_single_event_format",$screen,"post"); add_meta_box("div_event_contactperson_email_body", __('Contact Person Email Format', 'eme'), "eme_meta_box_div_event_contactperson_email_body",$screen,"post"); add_meta_box("div_event_registration_recorded_ok_html", __('Booking recorded html Format', 'eme'), "eme_meta_box_div_event_registration_recorded_ok_html",$screen,"post"); add_meta_box("div_event_respondent_email_body", __('Respondent Email Format', 'eme'), "eme_meta_box_div_event_respondent_email_body",$screen,"post"); add_meta_box("div_event_registration_pending_email_body", __('Registration Pending Email Format', 'eme'), "eme_meta_box_div_event_registration_pending_email_body",$screen,"post"); add_meta_box("div_event_registration_updated_email_body", __('Registration Updated Email Format', 'eme'), "eme_meta_box_div_event_registration_updated_email_body",$screen,"post"); add_meta_box("div_event_registration_form_format", __('Registration Form Format', 'eme'), "eme_meta_box_div_event_registration_form_format",$screen,"post"); add_meta_box("div_event_cancel_form_format", __('Cancel Registration Form Format', 'eme'), "eme_meta_box_div_event_cancel_form_format",$screen,"post"); add_meta_box("div_location_name", __('Location', 'eme'), "eme_meta_box_div_location_name",$screen,"post"); add_meta_box("div_event_notes", __('Details', 'eme'), "eme_meta_box_div_event_notes",$screen,"post"); add_meta_box("div_event_image", __('Event image', 'eme'), "eme_meta_box_div_event_image",$screen,"post"); if (get_option('eme_attributes_enabled')) add_meta_box("div_event_attributes", __('Attributes', 'eme'), "eme_meta_box_div_event_attributes",$screen,"post"); add_meta_box("div_event_url", __('External link', 'eme'), "eme_meta_box_div_event_url",$screen,"post"); } } } function eme_meta_box_div_event_name($event){ ?> <!-- we need title for qtranslate as ID --> <input type="text" id="title" name="event_name" value="<?php echo eme_sanitize_html($event['event_name']); ?>" /> <br /> <?php _e ( 'The event name. Example: Birthday party', 'eme' )?> <br /> <br /> <?php if ($event['event_id'] && $event['event_name'] != "") { _e ('Permalink: ', 'eme' ); echo trailingslashit(home_url()).eme_permalink_convert(get_option ( 'eme_permalink_events_prefix')).$event['event_id']."/"; $slug = $event['event_slug'] ? $event['event_slug'] : $event['event_name']; $slug = untrailingslashit(eme_permalink_convert($slug)); ?> <input type="text" id="slug" name="event_slug" value="<?php echo $slug; ?>" /><?php echo user_trailingslashit(""); ?> <?php } } function eme_meta_box_div_event_date($event){ $eme_prop_all_day_checked = ($event['event_properties']['all_day']) ? "checked='checked'" : ""; ?> <input id="localised-start-date" type="text" name="localised_event_start_date" value="" style="background: #FCFFAA;" readonly="readonly" /> <input id="start-date-to-submit" type="hidden" name="event_start_date" value="" /> <input id="localised-end-date" type="text" name="localised_event_end_date" value="" style="background: #FCFFAA;" readonly="readonly" /> <input id="end-date-to-submit" type="hidden" name="event_end_date" value="" /> <span id='event-date-explanation'> <?php _e ( 'The event beginning and end date.', 'eme' ); ?> </span> <br /> <span id='event-date-recursive-explanation'> <?php _e ( 'In case of a recurrent event, use the beginning and end date to just indicate the duration of one event in days. The real start date is determined by the recurrence scheme being used.', 'eme' ); ?> </span> <br /> <br /> <input id="eme_prop_all_day" name='eme_prop_all_day' value='1' type='checkbox' <?php echo $eme_prop_all_day_checked; ?> /> <?php _e ( 'This event lasts all day', 'eme' ); ?> <?php } function eme_meta_box_div_recurrence_date($event){ ?> <input id="localised-rec-start-date" type="text" name="localised_recurrence_date" value="" style="background: #FCFFAA;" readonly="readonly" /> <input id="rec-start-date-to-submit" type="text" name="recurrence_start_date" value="" /> <input id="localised-rec-end-date" type="text" name="localised_recurrence_end_date" value="" style="background: #FCFFAA;" readonly="readonly" /> <input id="rec-end-date-to-submit" type="text" name="recurrence_end_date" value="" /> <br /> <span id='recurrence-dates-explanation'> <?php _e ( 'The recurrence beginning and end date.', 'eme' ); ?> </span> <span id='recurrence-dates-explanation-specificdates'> <?php _e ( 'Select all the dates you want the event to begin on.', 'eme' ); ?> </span> <?php } function eme_meta_box_div_event_page_title_format($event) { ?> <?php _e('Either choose from a template: ','eme'); echo eme_ui_select($event['event_properties']['event_page_title_format_tpl'],'eme_prop_event_page_title_format_tpl',$event['templates_array']); ?><br /> <?php _e('Or enter your own (if anything is entered here, it takes precedence over the selected template): ','eme');?><br /> <textarea name="event_page_title_format" id="event_page_title_format" rows="6" cols="60"><?php echo eme_sanitize_html($event['event_page_title_format']);?></textarea> <br /> <p><?php _e ( 'The format of the single event title.','eme');?> <br /> <?php _e ('Only fill this in if you want to override the default settings.', 'eme' );?> </p> <?php } function eme_meta_box_div_event_time($event) { // check if the user wants AM/PM or 24 hour notation // make sure that escaped characters are filtered out first $time_format = preg_replace('/\\\\./','',get_option('time_format')); $hours_locale = '24'; if (preg_match ( "/g|h/", $time_format )) { $event_start_time = date("h:iA", strtotime($event['event_start_time'])); $event_end_time = date("h:iA", strtotime($event['event_end_time'])); } else { $event_start_time = $event['event_start_time']; $event_end_time = $event['event_end_time']; } ?> <input id="start-time" type="text" size="8" maxlength="8" name="event_start_time" value="<?php echo $event_start_time; ?>" /> - <input id="end-time" type="text" size="8" maxlength="8" name="event_end_time" value="<?php echo $event_end_time; ?>" /> <br /> <?php _e ( 'The time of the event beginning and end', 'eme' )?> . <?php } function eme_meta_box_div_event_single_event_format($event) { ?> <p><?php _e ( 'The format of the single event page.','eme');?> <br /> <?php _e ('Only fill this in if you want to override the default settings.', 'eme' );?> </p> <?php _e('Either choose from a template: ','eme'); echo eme_ui_select($event['event_properties']['event_single_event_format_tpl'],'eme_prop_event_single_event_format_tpl',$event['templates_array']); ?><br /> <?php _e('Or enter your own (if anything is entered here, it takes precedence over the selected template): ','eme');?><br /> <textarea name="event_single_event_format" id="event_single_event_format" rows="6" cols="60"><?php echo eme_sanitize_html($event['event_single_event_format']);?></textarea> <?php } function eme_meta_box_div_event_contactperson_email_body($event) { ?> <p><?php _e ( 'The format of the email which will be sent to the contact person.','eme');?> <br /> <?php _e ('Only fill this in if you want to override the default settings.', 'eme' );?> </p> <?php _e('Either choose from a template: ','eme'); echo eme_ui_select($event['event_properties']['event_contactperson_email_body_tpl'],'eme_prop_event_contactperson_email_body_tpl',$event['templates_array']); ?><br /> <?php _e('Or enter your own (if anything is entered here, it takes precedence over the selected template): ','eme');?><br /> <textarea name="event_contactperson_email_body" id="event_contactperson_email_body" rows="6" cols="60"><?php echo eme_sanitize_html($event['event_contactperson_email_body']);?></textarea> <?php } function eme_meta_box_div_event_registration_recorded_ok_html($event) { ?> <p><?php _e ( 'The text (html allowed) shown to the user when the booking has been made successfully.','eme');?> <br /> <?php _e ('Only fill this in if you want to override the default settings.', 'eme' );?> </p> <?php _e('Either choose from a template: ','eme'); echo eme_ui_select($event['event_properties']['event_registration_recorded_ok_html_tpl'],'eme_prop_event_registration_recorded_ok_html_tpl',$event['templates_array']); ?><br /> <?php _e('Or enter your own (if anything is entered here, it takes precedence over the selected template): ','eme');?><br /> <textarea name="event_registration_recorded_ok_html" id="event_registration_recorded_ok_html" rows="6" cols="60"><?php echo eme_sanitize_html($event['event_registration_recorded_ok_html']);?></textarea> <?php } function eme_meta_box_div_event_respondent_email_body($event) { ?> <p><?php _e ( 'The format of the email which will be sent to the respondent.','eme');?> <br /> <?php _e ('Only fill this in if you want to override the default settings.', 'eme' );?> </p> <?php _e('Either choose from a template: ','eme'); echo eme_ui_select($event['event_properties']['event_respondent_email_body_tpl'],'eme_prop_event_respondent_email_body_tpl',$event['templates_array']); ?><br /> <?php _e('Or enter your own (if anything is entered here, it takes precedence over the selected template): ','eme');?><br /> <textarea name="event_respondent_email_body" id="event_respondent_email_body" rows="6" cols="60"><?php echo eme_sanitize_html($event['event_respondent_email_body']);?></textarea> <?php } function eme_meta_box_div_event_registration_pending_email_body($event) { ?> <p><?php _e ( 'The format of the email which will be sent to the respondent if the registration is pending.','eme');?> <br /> <?php _e ('Only fill this in if you want to override the default settings.', 'eme' );?> </p> <?php _e('Either choose from a template: ','eme'); echo eme_ui_select($event['event_properties']['event_registration_pending_email_body_tpl'],'eme_prop_event_registration_pending_email_body_tpl',$event['templates_array']); ?><br /> <?php _e('Or enter your own (if anything is entered here, it takes precedence over the selected template): ','eme');?><br /> <textarea name="event_registration_pending_email_body" id="event_registration_pending_email_body" rows="6" cols="60"><?php echo eme_sanitize_html($event['event_registration_pending_email_body']);?></textarea> <?php } function eme_meta_box_div_event_registration_updated_email_body($event) { ?> <p><?php _e ( 'The format of the email which will be sent to the respondent if the registration has been updated by an admin.','eme');?> <br /> <?php _e ('Only fill this in if you want to override the default settings.', 'eme' );?> </p> <?php _e('Either choose from a template: ','eme'); echo eme_ui_select($event['event_properties']['event_registration_updated_email_body_tpl'],'eme_prop_event_registration_updated_email_body_tpl',$event['templates_array']); ?><br /> <?php _e('Or enter your own (if anything is entered here, it takes precedence over the selected template): ','eme');?><br /> <textarea name="event_registration_updated_email_body" id="event_registration_updated_email_body" rows="6" cols="60"><?php echo eme_sanitize_html($event['event_registration_updated_email_body']);?></textarea> <?php } function eme_meta_box_div_event_registration_form_format($event) { ?> <p><?php _e ( 'The registration form format.','eme');?> <br /> <?php _e ('Only fill this in if you want to override the default settings.', 'eme' );?> </p> <?php _e('Either choose from a template: ','eme'); echo eme_ui_select($event['event_properties']['event_registration_form_format_tpl'],'eme_prop_event_registration_form_format_tpl',$event['templates_array']); ?><br /> <?php _e('Or enter your own (if anything is entered here, it takes precedence over the selected template): ','eme');?><br /> <textarea name="event_registration_form_format" id="event_registration_form_format" rows="6" cols="60"><?php echo eme_sanitize_html($event['event_registration_form_format']);?></textarea> <?php } function eme_meta_box_div_event_cancel_form_format($event) { ?> <p><?php _e ( 'The cancel registration form format.','eme');?> <br /> <?php _e ('Only fill this in if you want to override the default settings.', 'eme' );?> </p> <?php _e('Either choose from a template: ','eme'); echo eme_ui_select($event['event_properties']['event_cancel_form_format_tpl'],'eme_prop_event_cancel_form_format_tpl',$event['templates_array']); ?><br /> <?php _e('Or enter your own (if anything is entered here, it takes precedence over the selected template): ','eme');?><br /> <textarea name="event_cancel_form_format" id="event_cancel_form_format" rows="6" cols="60"><?php echo eme_sanitize_html($event['event_cancel_form_format']);?></textarea> <?php } function eme_meta_box_div_location_name($event) { $use_select_for_locations = get_option('eme_use_select_for_locations'); // qtranslate there? Then we need the select, otherwise locations will be created again... $lang = eme_detect_lang(); if (!empty($lang)) { $use_select_for_locations=1; } $gmap_is_active = get_option('eme_gmap_is_active' ); $location = eme_get_location ( $event['location_id'] ); ?> <table id="eme-location-data"> <?php if($use_select_for_locations) { $location_0 = eme_new_location(); $location_0['location_id']=0; $locations = eme_get_locations(); ?> <tr> <th><?php _e('Location','eme') ?></th> <td> <select name="location-select-id" id='location-select-id' size="1"> <option value="<?php echo $location_0['location_id'] ?>" ><?php echo eme_trans_sanitize_html($location_0['location_name']) ?></option> <?php $selected_location=$location_0; foreach($locations as $tmp_location) { $selected = ""; if (isset($location['location_id']) && $location['location_id'] == $tmp_location['location_id']) { $selected_location=$location; $selected = "selected='selected' "; } ?> <option value="<?php echo $tmp_location['location_id'] ?>" <?php echo $selected ?>><?php echo eme_trans_sanitize_html($tmp_location['location_name']) ?></option> <?php } ?> </select> <input type='hidden' name='location-select-name' value='<?php echo eme_trans_sanitize_html($selected_location['location_name'])?>' /> <input type='hidden' name='location-select-town' value='<?php echo eme_trans_sanitize_html($selected_location['location_town'])?>' /> <input type='hidden' name='location-select-address' value='<?php echo eme_trans_sanitize_html($selected_location['location_address'])?>' /> <input type='hidden' name='location-select-latitude' value='<?php echo eme_trans_sanitize_html($selected_location['location_latitude'])?>' /> <input type='hidden' name='location-select-longitude' value='<?php echo eme_trans_sanitize_html($selected_location['location_longitude'])?>' /> </td> <?php if ($gmap_is_active) { ?> <td> <div id='eme-admin-map-not-found'> <p> <?php _e ( 'Map not found','eme' ); ?> </p> </div> <div id='eme-admin-location-map'></div></td> <?php } ?> </tr> <tr > <td colspan='2' rowspan='5' style='vertical-align: top'> <?php _e ( 'Select a location for your event', 'eme' )?> </td> </tr> <?php } else { ?> <tr> <th><?php _e ( 'Name','eme' )?>&nbsp;</th> <td><input id="location_name" type="text" name="location_name" value="<?php echo eme_trans_sanitize_html($location['location_name'])?>" /></td> <?php if ($gmap_is_active) { ?> <td rowspan='6'> <div id='eme-admin-map-not-found'> <p> <?php _e ( 'Map not found','eme' ); ?> </p> </div> <div id='eme-admin-location-map'></div></td> <?php } ?> </tr> <tr> <td colspan='2'> <?php _e ( 'The name of the location where the event takes place. You can use the name of a venue, a square, etc', 'eme' );?> <br /> <?php _e ( 'If you leave this empty, the map will NOT be shown for this event', 'eme' );?> </td> </tr> <tr> <th><?php _e ( 'Address:', 'eme' )?> &nbsp;</th> <td><input id="location_address" type="text" name="location_address" value="<?php echo $location['location_address']; ?>" /></td> </tr> <tr> <td colspan='2'> <?php _e ( 'The address of the location where the event takes place. Example: 21, Dominick Street', 'eme' )?> </td> </tr> <tr> <th><?php _e ( 'Town:', 'eme' )?> &nbsp;</th> <td><input id="location_town" type="text" name="location_town" value="<?php echo $location['location_town']?>" /></td> </tr> <tr> <td colspan='2'> <?php _e ( 'The town where the location is located. If you\'re using the Google Map integration and want to avoid geotagging ambiguities include the country in the town field. Example: Verona, Italy.', 'eme' )?> </td> </tr> <tr> <th><?php _e ( 'Latitude:', 'eme' )?> &nbsp;</th> <td><input id="location_latitude" type="text" name="location_latitude" value="<?php echo $location['location_latitude']?>" /></td> </tr> <tr> <th><?php _e ( 'Longitude:', 'eme' )?> &nbsp;</th> <td><input id="location_longitude" type="text" name="location_longitude" value="<?php echo $location['location_longitude']?>" /></td> </tr> <tr> <td colspan='2'> <?php _e ( 'If you\'re using the Google Map integration and are really serious about the correct place, use these.', 'eme' )?> </td> </tr> <?php } ?> </table> <?php } function eme_meta_box_div_event_notes($event) { ?> <div id="<?php echo user_can_richedit() ? 'postdivrich' : 'postdiv'; ?>" class="postarea"> <!-- we need content for qtranslate as ID --> <?php wp_editor($event['event_notes'],"content"); ?> </div> <br /> <?php _e ( 'Details about the event', 'eme' )?> <?php } function eme_meta_box_div_event_image($event) { if (isset($event['event_image_id']) && !empty($event['event_image_id'])) $event['event_image_url'] = wp_get_attachment_url($event['event_image_id']); ?> <div id="event_current_image" class="postarea"> <?php if (isset($event['event_image_url']) && !empty($event['event_image_url'])) { _e('Current image:', 'eme'); echo "<img id='eme_event_image_example' src='".$event['event_image_url']."' width='200' />"; echo "<input type='hidden' name='event_image_url' id='event_image_url' value='".$event['event_image_url']."' />"; } else { echo "<img id='eme_event_image_example' src='' alt='' width='200' />"; echo "<input type='hidden' name='event_image_url' id='event_image_url' />"; } if (isset($event['event_image_id']) && !empty($event['event_image_id'])) { echo "<input type='hidden' name='event_image_id' id='event_image_id' value='".$event['event_image_id']."' />"; } else { echo "<input type='hidden' name='event_image_id' id='event_image_id' />"; } // based on code found at http://codestag.com/how-to-use-wordpress-3-5-media-uploader-in-theme-options/ ?> </div> <br /> <div class="uploader"> <input type="button" name="event_image_button" id="event_image_button" value="<?php _e ( 'Set a featured image', 'eme' )?>" /> <input type="button" id="eme_remove_old_image" name="eme_remove_old_image" value=" <?php _e ( 'Unset featured image', 'eme' )?>" /> </div> <script> jQuery(document).ready(function($){ $('#eme_remove_old_image').click(function(e) { $('#event_image_url').val(''); $('#event_image_id').val(''); $('#eme_event_image_example' ).attr("src",''); }); $('#event_image_button').click(function(e) { e.preventDefault(); var custom_uploader = wp.media({ title: '<?php _e ( 'Select the image to be used as featured image', 'eme' )?>', button: { text: '<?php _e ( 'Set featured image', 'eme' )?>' }, // Tell the modal to show only images. library: { type: 'image' }, multiple: false // Set this to true to allow multiple files to be selected }) .on('select', function() { var attachment = custom_uploader.state().get('selection').first().toJSON(); $('#event_image_url').val(attachment.url); $('#event_image_id').val(attachment.id); $('#eme_event_image_example' ).attr("src",attachment.url); }) .open(); }); }); </script> <?php } function eme_meta_box_div_event_attributes($event) { eme_attributes_form($event); } function eme_meta_box_div_event_url($event) { ?> <input type="text" id="event_url" name="event_url" value="<?php echo eme_sanitize_html($event['event_url']); ?>" /> <br /> <?php _e ( 'If this is filled in, the single event URL will point to this url instead of the standard event page.', 'eme' )?> <?php } function eme_admin_map_script() { $lang_js_trans_function=eme_detect_lang_js_trans_function(); ?> <script type="text/javascript"> //<![CDATA[ var lang = '<?php echo eme_detect_lang(); ?>'; var lang_trans_function = '<?php echo $lang_js_trans_function; ?>'; function loadMap(location, town, address) { var latlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 13, center: latlng, scrollwheel: <?php echo get_option('eme_gmap_zooming') ? 'true' : 'false'; ?>, disableDoubleClickZoom: true, mapTypeControlOptions: { mapTypeIds:[google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE] }, mapTypeId: google.maps.MapTypeId.ROADMAP } jQuery("#eme-admin-location-map").show(); var map = new google.maps.Map(document.getElementById("eme-admin-location-map"), myOptions); var geocoder = new google.maps.Geocoder(); if (address !="") { searchKey = address + ", " + town; } else { searchKey = location + ", " + town; } <?php if (!empty($lang_js_trans_function)) { ?> if (lang!='' && typeof(lang_trans_function)=='function' ) { location=window[lang_js_trans_function](lang,location); } <?php } ?> if (address !="" || town!="") { geocoder.geocode( { 'address': searchKey}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); var infowindow = new google.maps.InfoWindow({ content: '<div class=\"eme-location-balloon\"><strong>' + location +'</strong><p>' + address + '</p><p>' + town + '</p></div>' }); infowindow.open(map,marker); jQuery('input#location_latitude').val(results[0].geometry.location.lat()); jQuery('input#location_longitude').val(results[0].geometry.location.lng()); jQuery("#eme-admin-location-map").show(); jQuery('#eme-admin-map-not-found').hide(); } else { jQuery("#eme-admin-location-map").hide(); jQuery('#eme-admin-map-not-found').show(); } }); } else { jQuery("#eme-admin-location-map").hide(); jQuery('#eme-admin-map-not-found').show(); } } function loadMapLatLong(location, town, address, lat, long) { if (lat === undefined) { lat = 0; } if (long === undefined) { long = 0; } <?php if (!empty($lang_js_trans_function)) { ?> if (lang!='' && typeof(lang_trans_function)=='function' ) { location=window[lang_js_trans_function](lang,location); } <?php } ?> if (lat != 0 && long != 0) { var latlng = new google.maps.LatLng(lat, long); var myOptions = { zoom: 13, center: latlng, scrollwheel: <?php echo get_option('eme_gmap_zooming') ? 'true' : 'false'; ?>, disableDoubleClickZoom: true, mapTypeControlOptions: { mapTypeIds:[google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE] }, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("eme-admin-location-map"), myOptions); var marker = new google.maps.Marker({ map: map, position: latlng }); var infowindow = new google.maps.InfoWindow({ content: '<div class=\"eme-location-balloon\"><strong>' + location +'</strong><p>' + address + '</p><p>' + town + '</p></div>' }); infowindow.open(map,marker); jQuery("#eme-admin-location-map").show(); jQuery('#eme-admin-map-not-found').hide(); } else { loadMap(location, town, address); } } function eme_displayAddress(ignore_coord){ var gmap_enabled = <?php echo get_option('eme_gmap_is_active')?1:0; ?>; if (gmap_enabled) { eventLocation = jQuery("input[name=location_name]").val(); eventTown = jQuery("input#location_town").val(); eventAddress = jQuery("input#location_address").val(); if (ignore_coord) { loadMapLatLong(eventLocation, eventTown, eventAddress); } else { eventLat = jQuery("input#location_latitude").val(); eventLong = jQuery("input#location_longitude").val(); loadMapLatLong(eventLocation, eventTown, eventAddress, eventLat, eventLong); } } } function eme_SelectdisplayAddress(){ var gmap_enabled = <?php echo get_option('eme_gmap_is_active')?1:0; ?>; if (gmap_enabled) { eventLocation = jQuery("input[name='location-select-name']").val(); eventTown = jQuery("input[name='location-select-town']").val(); eventAddress = jQuery("input[name='location-select-address']").val(); eventLat = jQuery("input[name='location-select-latitude']").val(); eventLong = jQuery("input[name='location-select-longitude']").val(); loadMapLatLong(eventLocation, eventTown, eventAddress, eventLat, eventLong); } } jQuery(document).ready(function() { jQuery("#eme-admin-location-map").hide(); jQuery('#eme-admin-map-not-found').show(); <?php $use_select_for_locations = get_option('eme_use_select_for_locations'); // translate plugin there? Then we need the select $lang = eme_detect_lang(); if (!empty($lang)) { $use_select_for_locations=1; } // if we're editing an event *AND* the use_select_for_locations var is set // then we do the select thing // We check on the edit event because this javascript is also executed for editing locations, and then we don't care // about the use_select_for_locations parameter // For new events we do nothing if the use_select_for_locations var is set, because there's nothing to show. if (isset($_REQUEST['eme_admin_action']) && ($_REQUEST['eme_admin_action'] == 'edit_event' || $_REQUEST['eme_admin_action'] == 'duplicate_event' || $_REQUEST['eme_admin_action'] == 'edit_recurrence')) { if ($use_select_for_locations) { ?> eme_SelectdisplayAddress(); <?php } else { ?> eme_displayAddress(0); <?php } ?> <?php } elseif (isset($_REQUEST['eme_admin_action']) && ($_REQUEST['eme_admin_action'] == 'addlocation' || $_REQUEST['eme_admin_action'] == 'editlocation')) { ?> eme_displayAddress(0); <?php } ?> jQuery("input[name='location_name']").change(function(){ eme_displayAddress(0); }); jQuery("input#location_town").change(function(){ eme_displayAddress(1); }); jQuery("input#location_address").change(function(){ eme_displayAddress(1); }); jQuery("input#location_latitude").change(function(){ eme_displayAddress(0); }); jQuery("input#location_longitude").change(function(){ eme_displayAddress(0); }); }); jQuery(document).unload(function() { GUnload(); }); //]]> </script> <?php } function eme_rss_link($justurl = 0, $echo = 1, $text = "RSS", $scope="future", $order = "ASC",$category='',$author='',$contact_person='',$limit=5, $location_id='',$title='') { if (strpos ( $justurl, "=" )) { // allows the use of arguments without breaking the legacy code $defaults = array ('justurl' => 0, 'echo' => 1, 'text' => 'RSS', 'scope' => 'future', 'order' => 'ASC', 'category' => '', 'author' => '', 'contact_person' => '', 'limit' => 5, 'location_id' => '', 'title' => '' ); $r = wp_parse_args ( $justurl, $defaults ); extract ( $r ); $echo = $r['echo']; } $echo = ($echo==="true" || $echo==="1") ? true : $echo; $echo = ($echo==="false" || $echo==="O") ? false : $echo; if ($text == '') $text = "RSS"; $url = site_url ("/?eme_rss=main&scope=$scope&order=$order&category=$category&author=$author&contact_person=$contact_person&limit=$limit&location_id=$location_id&title=".urlencode($title)); $link = "<a href='$url'>$text</a>"; if ($justurl) $result = $url; else $result = $link; if ($echo) echo $result; else return $result; } function eme_rss_link_shortcode($atts) { extract ( shortcode_atts ( array ('justurl' => 0, 'text' => 'RSS', 'scope' => 'future', 'order' => 'ASC', 'category' => '', 'author' => '', 'contact_person' => '', 'limit' => 5, 'location_id' => '', 'title' => '' ), $atts ) ); $result = eme_rss_link ( "justurl=$justurl&echo=0&text=$text&limit=$limit&scope=$scope&order=$order&category=$category&author=$author&contact_person=$contact_person&location_id=$location_id&title=".urlencode($title) ); return $result; } function eme_rss() { if (isset($_GET['limit'])) { $limit=intval($_GET['limit']); } else { $limit=get_option('eme_event_list_number_items' ); } if (isset($_GET['author'])) { $author=$_GET['author']; } else { $author=""; } if (isset($_GET['contact_person'])) { $contact_person=$_GET['contact_person']; } else { $contact_person=""; } if (isset($_GET['order'])) { $order=$_GET['order']; } else { $order="ASC"; } if (isset($_GET['category'])) { $category=$_GET['category']; } else { $category=0; } if (isset($_GET['location_id'])) { $location_id=$_GET['location_id']; } else { $location_id=''; } if (isset($_GET['scope'])) { $scope=$_GET['scope']; } else { $scope="future"; } if (isset($_GET['title'])) { $main_title=$_GET['title']; } else { $main_title=get_option('eme_rss_main_title' ); } echo "<?xml version='1.0'?>\n"; ?> <rss version="2.0"> <channel> <title><?php echo eme_sanitize_rss($main_title); ?></title> <link><?php $events_page_link = eme_get_events_page(true, false); echo eme_sanitize_rss($events_page_link); ?></link> <description><?php echo eme_sanitize_rss(get_option('eme_rss_main_description' )); ?></description> <docs> http://blogs.law.harvard.edu/tech/rss </docs> <generator> Weblog Editor 2.0 </generator> <?php $title_format = get_option('eme_rss_title_format'); $description_format = get_option('eme_rss_description_format'); $events = eme_get_events ( $limit, $scope, $order, 0, $location_id, $category, $author, $contact_person ); # some RSS readers don't like it when an empty feed without items is returned, so we add a dummy item then if (empty ( $events )) { echo "<item>\n"; echo "<title></title>\n"; echo "<link></link>\n"; echo "</item>\n"; } else { foreach ( $events as $event ) { $title = eme_sanitize_rss(eme_replace_placeholders ( $title_format, $event, "rss" )); $description = eme_sanitize_rss(eme_replace_placeholders ( $description_format, $event, "rss" )); $event_link = eme_sanitize_rss(eme_event_url($event)); echo "<item>\n"; echo "<title>$title</title>\n"; echo "<link>$event_link</link>\n"; if (get_option('eme_rss_show_pubdate' )) { if (get_option('eme_rss_pubdate_startdate' )) { $timezoneoffset=date('O'); echo "<pubDate>".eme_localised_date ($event['event_start_date']." ".$event['event_start_time'],'D, d M Y H:i:s $timezoneoffset')."</pubDate>\n"; } else { echo "<pubDate>".eme_localised_date ($event['modif_date_gmt'],'D, d M Y H:i:s +0000')."</pubDate>\n"; } } echo "<description>$description</description>\n"; if (get_option('eme_categories_enabled')) { $categories = eme_sanitize_rss(eme_replace_placeholders ( "#_CATEGORIES", $event, "rss" )); echo "<category>$categories</category>\n"; } echo "</item>\n"; } } ?> </channel> </rss> <?php } function eme_general_head() { if (eme_is_single_event_page()) { $event=eme_get_event(get_query_var('event_id')); // I don't know if the canonical rel-link is needed, but since WP adds it by default ... $canon_url=eme_event_url($event); echo "<link rel=\"canonical\" href=\"$canon_url\" />\n"; $extra_headers_format=get_option('eme_event_html_headers_format'); if ($extra_headers_format != "") { $extra_headers_lines = explode ("\n",$extra_headers_format); foreach ($extra_headers_lines as $extra_header_format) { # the text format already removes most of html code, so let's use that $extra_header = strip_shortcodes(eme_replace_placeholders ($extra_header_format, $event, "text",0 )); # the text format converts \n to \r\n but we want one line only $extra_header = trim(preg_replace('/\r\n/', "", $extra_header)); if ($extra_header != "") echo $extra_header."\n"; } } } elseif (eme_is_single_location_page()) { $location=eme_get_location(get_query_var('location_id')); $canon_url=eme_location_url($location); echo "<link rel=\"canonical\" href=\"$canon_url\" />\n"; $extra_headers_format=get_option('eme_location_html_headers_format'); if ($extra_headers_format != "") { $extra_headers_lines = explode ("\n",$extra_headers_format); foreach ($extra_headers_lines as $extra_header_format) { # the text format already removes most of html code, so let's use that $extra_header = strip_shortcodes(eme_replace_locations_placeholders ($extra_header_format, $location, "text", 0 )); # the text format converts \n to \r\n but we want one line only $extra_header = trim(preg_replace('/\r\n/', "", $extra_header)); if ($extra_header != "") echo $extra_header."\n"; } } } $gmap_is_active = get_option('eme_gmap_is_active' ); $load_js_in_header = get_option('eme_load_js_in_header' ); if ($gmap_is_active && $load_js_in_header) { echo "<script type='text/javascript' src='".EME_PLUGIN_URL."js/eme_location_map.js'></script>\n"; } } function eme_change_canonical_url() { if (eme_is_single_event_page() || eme_is_single_location_page()) { remove_action( 'wp_head', 'rel_canonical' ); } } function eme_general_footer() { global $eme_need_gmap_js; $gmap_is_active = get_option('eme_gmap_is_active' ); $load_js_in_header = get_option('eme_load_js_in_header' ); // we only include the map js if wanted/needed if (!$load_js_in_header && $gmap_is_active && $eme_need_gmap_js) { echo "<script type='text/javascript' src='".EME_PLUGIN_URL."js/eme_location_map.js'></script>\n"; } } function eme_db_insert_event($event,$event_is_part_of_recurrence=0) { global $wpdb; $table_name = $wpdb->prefix . EVENTS_TBNAME; $event['creation_date']=current_time('mysql', false); $event['modif_date']=current_time('mysql', false); $event['creation_date_gmt']=current_time('mysql', true); $event['modif_date_gmt']=current_time('mysql', true); // remove possible unwanted fields if (isset($event['event_id'])) { unset($event['event_id']); } // some sanity checks if ($event['event_end_date']<$event['event_start_date']) { $event['event_end_date']=$event['event_start_date']; } if (!is_serialized($event['event_attributes'])) $event['event_attributes'] = serialize($event['event_attributes']); if (!is_serialized($event['event_properties'])) $event['event_properties'] = serialize($event['event_properties']); $event_properties = @unserialize($event['event_properties']); if ($event_properties['all_day']) { $event['event_start_time']="00:00:00"; $event['event_end_time']="23:59:59"; } // if the end day/time is lower than the start day/time, then put // the end day one day ahead, but only if // the end time has been filled in, if it is empty then we keep // the end date as it is if ($event['event_end_time'] != "00:00:00") { $startstring=strtotime($event['event_start_date']." ".$event['event_start_time']); $endstring=strtotime($event['event_end_date']." ".$event['event_end_time']); if ($endstring<$startstring) { $event['event_end_date']=date("Y-m-d",strtotime($event['event_start_date'] . " + 1 days")); } } if (has_filter('eme_event_preinsert_filter')) $event=apply_filters('eme_event_preinsert_filter',$event); $wpdb->show_errors(true); if (!$wpdb->insert ( $table_name, $event )) { $wpdb->print_error(); return false; } else { $event_ID = $wpdb->insert_id; $event['event_id']=$event_ID; // the eme_insert_event_action is only executed for single events, not those part of a recurrence if (!$event_is_part_of_recurrence && has_action('eme_insert_event_action')) do_action('eme_insert_event_action',$event); return $event_ID; } } function eme_db_update_event($event,$event_id,$event_is_part_of_recurrence=0) { global $wpdb; $table_name = $wpdb->prefix . EVENTS_TBNAME; // make sure we don't update the auto-increment id, which is the event id // it is ok to do so, but should not change anyway if (isset($event['event_id'])) { unset($event['event_id']); } // backwards compatible: older versions gave directly the where array instead of the event_id if (!is_array($event_id)) $where=array('event_id' => $event_id); else $where = $event_id; $event['modif_date']=current_time('mysql', false); $event['modif_date_gmt']=current_time('mysql', true); // some sanity checks if ($event['event_end_date']<$event['event_start_date']) { $event['event_end_date']=$event['event_start_date']; } if (!is_serialized($event['event_attributes'])) $event['event_attributes'] = serialize($event['event_attributes']); if (!is_serialized($event['event_properties'])) $event['event_properties'] = serialize($event['event_properties']); $event_properties = @unserialize($event['event_properties']); if ($event_properties['all_day']) { $event['event_start_time']="00:00:00"; $event['event_end_time']="23:59:59"; } // if the end day/time is lower than the start day/time, then put // the end day one day ahead, but only if // the end time has been filled in, if it is empty then we keep // the end date as it is if ($event['event_end_time'] != "00:00:00") { $startstring=strtotime($event['event_start_date']." ".$event['event_start_time']); $endstring=strtotime($event['event_end_date']." ".$event['event_end_time']); if ($endstring<$startstring) { $event['event_end_date']=date("Y-m-d",strtotime($event['event_start_date'] . " + 1 days")); } } if (has_filter('eme_event_preupdate_filter')) $event=apply_filters('eme_event_preupdate_filter',$event); $wpdb->show_errors(true); if ($wpdb->update ( $table_name, $event, $where ) === false) { $wpdb->print_error(); $wpdb->show_errors(false); return false; } else { $event['event_id']=$event_id; // the eme_update_event_action is only executed for single events, not those part of a recurrence if (!$event_is_part_of_recurrence && has_action('eme_update_event_action')) { // we do this call so all parameters for the event are filled, otherwise for an update this might not be the case $event = eme_get_event($event_id); do_action('eme_update_event_action',$event); } $wpdb->show_errors(false); return true; } } function eme_change_event_state($events,$state) { global $wpdb; $table_name = $wpdb->prefix . EVENTS_TBNAME; if (is_array($events)) $events_to_change=join(',',$events); else $event_to_change=$events; $sql = "UPDATE $table_name set event_status=$state WHERE event_id in (".$events_to_change.")"; $wpdb->query($sql); } function eme_db_delete_event($event,$event_is_part_of_recurrence=0) { global $wpdb; $table_name = $wpdb->prefix . EVENTS_TBNAME; $wpdb->show_errors(false); $sql = $wpdb->prepare("DELETE FROM $table_name WHERE event_id = %d",$event['event_id']); // also delete associated image $image_basename= IMAGE_UPLOAD_DIR."/event-".$event['event_id']; eme_delete_image_files($image_basename); if ($wpdb->query($sql)) { eme_delete_all_bookings_for_event_id($event['event_id']); // the eme_delete_event_action is only executed for single events, not those part of a recurrence if (!$event_is_part_of_recurrence && has_action('eme_delete_event_action')) do_action('eme_delete_event_action',$event); } } add_filter ( 'favorite_actions', 'eme_favorite_menu' ); function eme_favorite_menu($actions) { // add quick link to our favorite plugin $actions['admin.php?page=eme-new_event'] = array (__ ( 'Add an event', 'eme' ), get_option('eme_cap_add_event') ); return $actions; } function eme_alert_events_page() { global $pagenow; $events_page_id = get_option('eme_events_page' ); if ($pagenow == 'post.php' && ( get_query_var('post_type') && 'page' == get_query_var('post_type') ) && isset ( $_GET['eme_admin_action'] ) && $_GET['eme_admin_action'] == 'edit' && isset ( $_GET['post'] ) && $_GET['post'] == "$events_page_id") { $message = sprintf ( __ ( "This page corresponds to <strong>Events Made Easy</strong> events page. Its content will be overriden by <strong>Events Made Easy</strong>. If you want to display your content, you can can assign another page to <strong>Events Made Easy</strong> in the the <a href='%s'>Settings</a>. ", 'eme' ), 'admin.php?page=eme-options' ); $notice = "<div class='error'><p>$message</p></div>"; echo $notice; } } function eme_admin_enqueue_js(){ global $plugin_page; wp_enqueue_script('eme'); wp_enqueue_style('eme',EME_PLUGIN_URL.'events_manager.css'); $file_name= get_stylesheet_directory()."/eme.css"; if (file_exists($file_name)) { wp_enqueue_style('eme2',get_stylesheet_directory_uri().'/eme.css'); } if ( in_array( $plugin_page, array('eme-locations', 'eme-new_event', 'events-manager') ) ) { // we need this to have the "postbox" javascript loaded, so closing/opening works for those divs wp_enqueue_script('post'); if (get_option('eme_gmap_is_active' )) { wp_enqueue_script('eme-google-maps'); // we use add_action admin_head, to include the eme_admin_map_script javascript after all the other javascripts // defined by enqueue script are loaded in the header, otherwise we get the 'green screen of death' for the map in the beginning // since the eme_admin_map_script javascript would get executed before the google map api got loaded add_action('admin_head', 'eme_admin_map_script'); } } //if ( in_array( $plugin_page, array('eme-locations', 'eme-new_event', 'events-manager','eme-options') ) ) { if ( in_array( $plugin_page, array('eme-new_event', 'events-manager','eme-options') ) ) { // both datepick and timeentry need jquery.plugin, so let's include it upfront wp_enqueue_script('eme-jquery-datepick'); //wp_enqueue_style('jquery-ui-autocomplete',EME_PLUGIN_URL."js/jquery-autocomplete/jquery.autocomplete.css"); wp_enqueue_style('eme-jquery-datepick',EME_PLUGIN_URL."js/jquery-datepick/jquery.datepick.css"); wp_enqueue_script('jquery-ui-autocomplete'); // jquery ui locales are with dashes, not underscores $locale_code = get_locale(); $locale_code = preg_replace( "/_/","-", $locale_code ); $locale_file = EME_PLUGIN_DIR. "js/jquery-datepick/jquery.datepick-$locale_code.js"; $locale_file_url = EME_PLUGIN_URL. "js/jquery-datepick/jquery.datepick-$locale_code.js"; // for english, no translation code is needed) if ($locale_code != "en-US") { if (!file_exists($locale_file)) { $locale_code = substr ( $locale_code, 0, 2 ); $locale_file = EME_PLUGIN_DIR. "js/jquery-datepick/jquery.datepick-$locale_code.js"; $locale_file_url = EME_PLUGIN_URL. "js/jquery-datepick/jquery.datepick-$locale_code.js"; } if (file_exists($locale_file)) wp_enqueue_script('eme-jquery-datepick-locale',$locale_file_url); } } if ( in_array( $plugin_page, array('eme-new_event', 'events-manager') ) ) { wp_enqueue_script( 'eme-jquery-timeentry'); // Now we can localize the script with our data. // in our case: replace in the registered script "eme-events" the string eme.translate_name, eme.translate_date, eme.translate_fields_missing and // eme.translate_enddate_required $translation_array = array( 'translate_name' => __('Name','eme'), 'translate_date' => __('Date','eme'), 'translate_fields_missing' => __('Some required fields are missing:','eme'), 'translate_enddate_required' => __('Since the event is repeated, you must specify an end date','eme') ); wp_localize_script( 'eme-events', 'eme', $translation_array ); wp_enqueue_script( 'eme-events'); // some inline js that gets shown at the top eme_admin_event_script(); eme_admin_event_boxes(); } if ( in_array( $plugin_page, array('eme-options') ) ) { wp_enqueue_script('eme-options'); } if ( in_array( $plugin_page, array('eme-send-mails') ) ) { wp_enqueue_script('eme-sendmails'); } if ( in_array( $plugin_page, array('eme-registration-approval','eme-registration-seats','events-manager','eme-people') ) ) { wp_enqueue_script('eme-jquery-datatables'); wp_enqueue_script('eme-datatables-clearsearch'); wp_enqueue_style('eme-jquery-datatables',EME_PLUGIN_URL.'js/jquery-datatables/css/jquery.dataTables.css'); } } # return number of days until next event or until the specified event function eme_countdown($atts) { extract ( shortcode_atts ( array ('id'=>''), $atts ) ); $now = date("Y-m-d"); if ($id!="") { $event=eme_get_event($id); } else { $newest_event_array=eme_get_events(1); $event=$newest_event_array[0]; } $start_date=$event['event_start_date']; return eme_daydifference($now,$start_date); } function eme_image_url_for_event($event) { if (isset($event['recurrence_id']) && $event['recurrence_id']>0) { $image_basename= IMAGE_UPLOAD_DIR."/recurrence-".$event['recurrence_id']; $image_baseurl= IMAGE_UPLOAD_URL."/recurrence-".$event['recurrence_id']; } else { $image_basename= IMAGE_UPLOAD_DIR."/event-".$event['event_id']; $image_baseurl= IMAGE_UPLOAD_URL."/event-".$event['event_id']; } $mime_types = array('gif','jpg','png'); foreach($mime_types as $type) { $file_path = $image_basename.".".$type; $file_url = $image_baseurl.".".$type; if (file_exists($file_path)) { return $file_url; } } return ''; } ?> $mime_types = array('gif','jpg','png'); foreach($mime_types as $type) { $file_path = $image_basename.".".$type; $file_url = $image_baseurl.".".$type; if (file_exists($file_path)) { return $file_url; } } return ''; } ?>
kalote/claudiaetorso
wp-content/plugins/events-made-easy/eme_events.php
PHP
gpl-2.0
200,166
# pygopherd -- Gopher-based protocol server in Python # module: serve up gopherspace via http # $Id: http.py,v 1.21 2002/04/26 15:18:10 jgoerzen Exp $ # Copyright (C) 2002 John Goerzen # <jgoerzen@complete.org> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # 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 import SocketServer import re, binascii import os, stat, os.path, mimetypes, urllib, time from pygopherd import handlers, protocols, GopherExceptions from pygopherd.protocols.base import BaseGopherProtocol import pygopherd.version import cgi class HTTPProtocol(BaseGopherProtocol): def canhandlerequest(self): self.requestparts = map(lambda arg: arg.strip(), self.request.split(" ")) return len(self.requestparts) == 3 and \ (self.requestparts[0] == 'GET' or self.requestparts[0] == 'HEAD') and \ self.requestparts[2][0:5] == 'HTTP/' def headerslurp(self): if hasattr(self.requesthandler, 'pygopherd_http_slurped'): # Already slurped. self.httpheaders = self.requesthandler.pygopherd_http_slurped return # Slurp up remaining lines. self.httpheaders = {} while 1: line = self.rfile.readline() if not len(line): break line = line.strip() if not len(line): break splitline = line.split(':', 1) if len(splitline) == 2: self.httpheaders[splitline[0].lower()] = splitline[1] self.requesthandler.pygopherd_http_slurped = self.httpheaders def handle(self): self.canhandlerequest() # To get self.requestparts self.iconmapping = eval(self.config.get("protocols.http.HTTPProtocol", "iconmapping")) self.headerslurp() splitted = self.requestparts[1].split('?') self.selector = splitted[0] self.selector = urllib.unquote(self.selector) self.selector = self.slashnormalize(self.selector) self.formvals = {} if len(splitted) >= 2: self.formvals = cgi.parse_qs(splitted[1]) if self.formvals.has_key('searchrequest'): self.searchrequest = self.formvals['searchrequest'][0] icon = re.match('/PYGOPHERD-HTTPPROTO-ICONS/(.+)$', self.selector) if icon: iconname = icon.group(1) if icons.has_key(iconname): self.wfile.write("HTTP/1.0 200 OK\r\n") self.wfile.write("Last-Modified: Fri, 14 Dec 2001 21:19:47 GMT\r\n") self.wfile.write("Content-Type: image/gif\r\n\r\n") if self.requestparts[0] == 'HEAD': return self.wfile.write(binascii.unhexlify(icons[iconname])) return try: handler = self.gethandler() self.log(handler) self.entry = handler.getentry() handler.prepare() self.wfile.write("HTTP/1.0 200 OK\r\n") if self.entry.getmtime() != None: gmtime = time.gmtime(self.entry.getmtime()) mtime = time.strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime) self.wfile.write("Last-Modified: " + mtime + "\r\n") mimetype = self.entry.getmimetype() mimetype = self.adjustmimetype(mimetype) self.wfile.write("Content-Type: " + mimetype + "\r\n\r\n") if self.requestparts[0] == 'GET': if handler.isdir(): self.writedir(self.entry, handler.getdirlist()) else: self.handlerwrite(self.wfile) except GopherExceptions.FileNotFound, e: self.filenotfound(str(e)) except IOError, e: GopherExceptions.log(e, self, None) self.filenotfound(e[1]) def handlerwrite(self, wfile): self.handler.write(wfile) def adjustmimetype(self, mimetype): if mimetype == None: return 'text/plain' if mimetype == 'application/gopher-menu': return 'text/html' return mimetype def renderobjinfo(self, entry): url = None # Decision time.... if re.match('(/|)URL:', entry.getselector()): # It's a plain URL. Make it that. url = re.match('(/|)URL:(.+)$', entry.getselector()).group(2) elif (not entry.gethost()) and (not entry.getport()): # It's a link to our own server. Make it as such. (relative) url = urllib.quote(entry.getselector()) else: # Link to a different server. Make it a gopher URL. url = entry.geturl(self.server.server_name, 70) # OK. Render. return self.getrenderstr(entry, url) def getrenderstr(self, entry, url): retstr = '<TR><TD>' retstr += self.getimgtag(entry) retstr += "</TD>\n<TD>&nbsp;" if entry.gettype() != 'i' and entry.gettype() != '7': retstr += '<A HREF="%s">' % url retstr += "<TT>" if entry.getname() != None: retstr += cgi.escape(entry.getname()).replace(" ", " &nbsp;") else: retstr += cgi.escape(entry.getselector()).replace(" ", " &nbsp;") retstr += "</TT>" if entry.gettype() != 'i' and entry.gettype() != '7': retstr += '</A>' if (entry.gettype() == '7'): retstr += '<BR><FORM METHOD="GET" ACTION="%s">' % url retstr += '<INPUT TYPE="text" NAME="searchrequest" SIZE="30">' retstr += '<INPUT TYPE="submit" NAME="Submit" VALUE="Submit">' retstr += '</FORM>' retstr += '</TD><TD><FONT SIZE="-2">' if entry.getmimetype(): subtype = re.search('/.+$', entry.getmimetype()) if subtype: retstr += cgi.escape(subtype.group()[1:]) retstr += '</FONT></TD></TR>\n' return retstr def renderdirstart(self, entry): retstr ='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">' retstr += "\n<HTML><HEAD><TITLE>Gopher" if self.entry.getname(): retstr += ": " + cgi.escape(self.entry.getname()) retstr += "</TITLE></HEAD><BODY>" if self.config.has_option("protocols.http.HTTPProtocol", "pagetopper"): retstr += re.sub('GOPHERURL', self.entry.geturl(self.server.server_name, self.server.server_port), self.config.get("protocols.http.HTTPProtocol", "pagetopper")) retstr += "<H1>Gopher" if self.entry.getname(): retstr += ": " + cgi.escape(self.entry.getname()) retstr += '</H1><TABLE WIDTH="100%" CELLSPACING="1" CELLPADDING="0">' return retstr def renderdirend(self, entry): retstr = "</TABLE><HR>\n[<A HREF=\"/\">server top</A>]" retstr += " [<A HREF=\"%s\">view with gopher</A>]" % \ entry.geturl(self.server.server_name, self.server.server_port) retstr += '<BR>Generated by <A HREF="%s">%s</A>' % ( pygopherd.version.homepage, pygopherd.version.productname) return retstr + "\n</BODY></HTML>\n" def filenotfound(self, msg): self.wfile.write("HTTP/1.0 404 Not Found\r\n") self.wfile.write("Content-Type: text/html\r\n\r\n") self.wfile.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">') self.wfile.write("""\n<HTML><HEAD><TITLE>Selector Not Found</TITLE> <H1>Selector Not Found</H1> <TT>""") self.wfile.write(cgi.escape(msg)) self.wfile.write("</TT><HR>Pygopherd</BODY></HTML>\n") def getimgtag(self, entry): name = 'generic.gif' if self.iconmapping.has_key(entry.gettype()): name = self.iconmapping[entry.gettype()] return '<IMG ALT=" * " SRC="%s" WIDTH="20" HEIGHT="22" BORDER="0">' % \ ('/PYGOPHERD-HTTPPROTO-ICONS/' + name) icons = { 'binary.gif': '47494638396114001600c20000ffffffccffffcccccc99999933333300000000000000000021fe4e546869732061727420697320696e20746865207075626c696320646f6d61696e2e204b6576696e204875676865732c206b6576696e68406569742e636f6d2c2053657074656d62657220313939350021f90401000001002c000000001400160000036948babcf1301040ab9d24be590a105d210013a9715e07a8a509a16beab5ae14df6a41e8fc76839d5168e8b3182983e4a0e0038a6e1525d396931d97be2ad482a55a55c6eec429f484a7b4e339eb215fd138ebda1b7fb3eb73983bafee8b094a8182493b114387885309003b', 'binhex.gif': '47494638396114001600c20000ffffffccffff99999966666633333300000000000000000021fe4e546869732061727420697320696e20746865207075626c696320646f6d61696e2e204b6576696e204875676865732c206b6576696e68406569742e636f6d2c2053657074656d62657220313939350021f90401000001002c000000001400160000036948babcf1301040ab9d24be59baefc0146adce78555068914985e2b609e0551df9b3c17ba995b408a602828e48a2681856894f44cc1628e07a42e9b985d14ab1b7c9440a9131c0c733b229bb5222ecdb6bfd6da3cd5d29d688a1aee2c97db044482834336113b884d09003b', 'folder.gif': '47494638396114001600c20000ffffffffcc99ccffff99663333333300000000000000000021fe4e546869732061727420697320696e20746865207075626c696320646f6d61696e2e204b6576696e204875676865732c206b6576696e68406569742e636f6d2c2053657074656d62657220313939350021f90401000002002c000000001400160000035428badcfe30ca4959b9f8ce12baef45c47d64a629c5407a6a8906432cc72b1c8ef51a13579e0f3c9c8f05ec0d4945e171673cb2824e2234da495261569856c5ddc27882d46c3c2680c3e6b47acd232c4cf08c3b01003b', 'image3.gif': '47494638396114001600e30000ffffffff3333ccffff9999996600003333330099cc00993300336600000000000000000000000000000000000000000021fe4e546869732061727420697320696e20746865207075626c696320646f6d61696e2e204b6576696e204875676865732c206b6576696e68406569742e636f6d2c2053657074656d62657220313939350021f90401000002002c0000000014001600000479b0c849a7b85814c0bbdf45766d5e49861959762a3a76442c132ae0aa44a0ef49d1ff2f4e6ea74b188f892020c70c3007d04152b3aa46a7adcaa42355160ee0f041d5a572bee23017cb1abbbf6476d52a0720ee78fc5a8930f8ff06087b66768080832a7d8a81818873744a8f8805519596503e19489b9c5311003b', 'sound1.gif': '47494638396114001600c20000ffffffff3333ccffffcccccc99999966000033333300000021fe4e546869732061727420697320696e20746865207075626c696320646f6d61696e2e204b6576696e204875676865732c206b6576696e68406569742e636f6d2c2053657074656d62657220313939350021f90401000002002c000000001400160000036b28badcfe3036c34290ea1c61558f07b171170985c0687e0d9a729e77693401dc5bd7154148fcb6db6b77e1b984c20d4fb03406913866717a842aa7d22af22acd120cdf6fd2d49cd10e034354871518de06b43a17334de42a36243e187d4a7b1a762c7b140b8418898a0b09003b', 'text.gif': '47494638396114001600c20000ffffffccffff99999933333300000000000000000000000021fe4e546869732061727420697320696e20746865207075626c696320646f6d61696e2e204b6576696e204875676865732c206b6576696e68406569742e636f6d2c2053657074656d62657220313939350021f90401000001002c000000001400160000035838babcf1300c40ab9d23be693bcf11d75522b88dd7057144eb52c410cf270abb6e8db796e00b849aadf20b4a6ebb1705281c128daca412c03c3a7b50a4f4d9bc5645dae9f78aed6e975932baebfc0e7ef0b84f1691da8d09003b', 'generic.gif': '47494638396114001600c20000ffffffccffff99999933333300000000000000000000000021fe4e546869732061727420697320696e20746865207075626c696320646f6d61696e2e204b6576696e204875676865732c206b6576696e68406569742e636f6d2c2053657074656d62657220313939350021f90401000001002c000000001400160000035038babcf1300c40ab9d23be693bcf11d75522b88dd705892831b8f08952446d13f24c09bc804b3a4befc70a027c39e391a8ac2081cd65d2f82c06ab5129b4898d76b94c2f71d02b9b79afc86dcdfe2500003b', 'blank.gif': '47494638396114001600a10000ffffffccffff00000000000021fe4e546869732061727420697320696e20746865207075626c696320646f6d61696e2e204b6576696e204875676865732c206b6576696e68406569742e636f6d2c2053657074656d62657220313939350021f90401000001002c00000000140016000002138c8fa9cbed0fa39cb4da8bb3debcfb0f864901003b'}
mas90/pygopherd
pygopherd/protocols/http.py
Python
gpl-2.0
12,731
// leave this line at the top for all g_xxxx.cpp files... #include "g_headers.h" #include "G_Local.h" typedef map < string, int > timer_m; timer_m g_timers[ MAX_GENTITIES ]; /* ------------------------- TIMER_Clear ------------------------- */ void TIMER_Clear( void ) { for ( int i = 0; i < MAX_GENTITIES; i++ ) { g_timers[i].clear(); } } /* ------------------------- TIMER_Clear ------------------------- */ void TIMER_Clear( gentity_t *ent ) { // rudimentary safety checks, might be other things to check? if ( ent && ent->s.number > 0 && ent->s.number < MAX_GENTITIES ) { g_timers[ent->s.number].clear(); } } /* ------------------------- TIMER_Save ------------------------- */ void TIMER_Save( void ) { int j; gentity_t *ent; for ( j = 0, ent = &g_entities[0]; j < MAX_GENTITIES; j++, ent++ ) { int numTimers = g_timers[ent->s.number].size(); int i; //Write out the timer information gi.AppendToSaveGame('TIME', (void *)&numTimers, sizeof(numTimers)); timer_m::iterator ti; for ( i = 0, ti = g_timers[ j ].begin(); i < numTimers; i++, ti++ ) { const char *id = ((*ti).first).c_str(); int length = strlen( id ); //Write out the string size and data gi.AppendToSaveGame('TSLN', (void *) &length, sizeof(length) ); gi.AppendToSaveGame('TSNM', (void *) id, length ); //Write out the timer data gi.AppendToSaveGame('TDTA', (void *) &(*ti).second, sizeof( (*ti).second ) ); } } } /* ------------------------- TIMER_Load ------------------------- */ void TIMER_Load( void ) { int j; gentity_t *ent; for ( j = 0, ent = &g_entities[0]; j < MAX_GENTITIES; j++, ent++ ) { int numTimers; gi.ReadFromSaveGame( 'TIME', (void *)&numTimers, sizeof(numTimers) ); //Make sure there's something to read if ( numTimers == 0 ) continue; //Read back all entries for ( int i = 0; i < numTimers; i++ ) { int length, time; char tempBuffer[1024]; //FIXME: Blech! gi.ReadFromSaveGame( 'TSLN', (void *) &length, sizeof( length ) ); //Validity check, though this will never happen (unless of course you pass in gibberish) if ( length >= 1024 ) { assert(0); continue; } //Read the id and time gi.ReadFromSaveGame( 'TSNM', (char *) tempBuffer, length ); gi.ReadFromSaveGame( 'TDTA', (void *) &time, sizeof( time ) ); //Restore it g_timers[ j ][(const char *) tempBuffer ] = time; } } } /* ------------------------- TIMER_Set ------------------------- */ void TIMER_Set( gentity_t *ent, const char *identifier, int duration ) { g_timers[ent->s.number][identifier] = level.time + duration; } /* ------------------------- TIMER_Get ------------------------- */ int TIMER_Get( gentity_t *ent, const char *identifier ) { timer_m::iterator ti; ti = g_timers[ent->s.number].find( identifier ); if ( ti == g_timers[ent->s.number].end() ) { //assert(0); return -1; } return (*ti).second; } /* ------------------------- TIMER_Done ------------------------- */ qboolean TIMER_Done( gentity_t *ent, const char *identifier ) { timer_m::iterator ti; ti = g_timers[ent->s.number].find( identifier ); if ( ti == g_timers[ent->s.number].end() ) return true; return ( (*ti).second < level.time ); } /* ------------------------- TIMER_Done2 Returns false if timer has been started but is not done...or if timer was never started ------------------------- */ qboolean TIMER_Done2( gentity_t *ent, const char *identifier, qboolean remove ) { timer_m::iterator ti; ti = g_timers[ent->s.number].find( identifier ); if ( ti == g_timers[ent->s.number].end() ) { return qfalse; } qboolean res =((*ti).second < level.time ); if ( res && remove ) { // Timer is done and it was requested that it should be removed. g_timers[ent->s.number].erase( ti ); } return res; } /* ------------------------- TIMER_Exists ------------------------- */ qboolean TIMER_Exists( gentity_t *ent, const char *identifier ) { timer_m::iterator ti; ti = g_timers[ent->s.number].find( identifier ); if ( ti == g_timers[ent->s.number].end( )) { return qfalse; } return qtrue; } /* ------------------------- TIMER_Remove Utility to get rid of any timer ------------------------- */ void TIMER_Remove( gentity_t *ent, const char *identifier ) { timer_m::iterator ti; ti = g_timers[ent->s.number].find( identifier ); if ( ti != g_timers[ent->s.number].end() ) { g_timers[ent->s.number].erase( ti ); } } /* ------------------------- TIMER_Start ------------------------- */ qboolean TIMER_Start( gentity_t *self, const char *identifier, int duration ) { if ( TIMER_Done( self, identifier ) ) { TIMER_Set( self, identifier, duration ); return qtrue; } return qfalse; }
grayj/Jedi-Outcast
code/game/G_Timer.cpp
C++
gpl-2.0
4,730
/*global gdn, jQuery*/ jQuery(($) => { const $preview = $('<div class="Preview"></div>') .insertBefore('#ConversationForm .bodybox-wrap, #Form_ConversationMessage .bodybox-wrap') .hide(); const $textbox = $('#ConversationForm textarea[name="Body"], #Form_ConversationMessage textarea[name="Body"]'); $('<a class="Button PreviewButton">' + gdn.getMeta('conversationsPreview.preview') + '</a>') .insertBefore('#ConversationForm input[type="submit"], #Form_ConversationMessage input[type="submit"]') .click(({target}) => { const $this = $(target); if ($this.hasClass('WriteButton')) { $preview.hide(); $textbox.show(); $this .addClass('PreviewButton') .removeClass('WriteButton') .text(gdn.getMeta('conversationsPreview.preview')); return; } gdn.disable($this); $this.toggleClass('PreviewButton').toggleClass('WriteButton'); $.post( gdn.url('messages/preview'), { Body: $this.closest('form').find('textarea[name="Body"]').val(), Format: $this.closest('form').find('input[name="Format"]').val(), TransientKey: gdn.definition('TransientKey') }, (data) => { $preview.html(data).show(); $textbox.hide(); $this .addClass('WriteButton') .removeClass('PreviewButton') .text(gdn.getMeta('conversationsPreview.edit')); $(document).trigger('PreviewLoaded'); }, 'html' ).always(() => { gdn.enable($this); }); }); $(document).on('MessageAdded', () => { $('.WriteButton').click(); }); });
bleistivt/conversationspreview
js/preview.js
JavaScript
gpl-2.0
1,997
package com.eng.univates.bd; import java.util.List; import javax.ejb.Remote; import com.eng.univates.pojo.Filter; import com.eng.univates.pojo.Ocorrencia; import com.eng.univates.pojo.Usuario; import com.vividsolutions.jts.geom.Point; @Remote public interface OcorrenciaBD extends CrudBD<Ocorrencia, Integer> { public String convertPontosGeo(); public List<Ocorrencia> getPontosConvertidos(); public List<String> getDescricaoFatos(); public List<Ocorrencia> filtraMapa(Filter filtro); public List<Ocorrencia> pontosBatalhao(Usuario usuario, Point localViatura, Double distance); }
rdanieli/heatmapGPS
hmGPS/ejb/src/main/java/com/eng/univates/bd/OcorrenciaBD.java
Java
gpl-2.0
598
/* * Copyright 2013, Red Hat, Inc. and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.zanata.file; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.zanata.ApplicationConfiguration; import org.zanata.dao.DocumentDAO; import org.zanata.model.HDocument; import org.zanata.model.HProject; import org.zanata.model.HProjectIteration; import org.zanata.model.HRawDocument; import org.zanata.rest.service.VirusScanner; import com.google.common.io.Files; @Name("filePersistService") @Scope(ScopeType.STATELESS) @AutoCreate @Slf4j public class FileSystemPersistService implements FilePersistService { private static final String RAW_DOCUMENTS_SUBDIRECTORY = "documents"; @In("applicationConfiguration") private ApplicationConfiguration appConfig; @In private DocumentDAO documentDAO; @In private VirusScanner virusScanner; @Override public void persistRawDocumentContentFromFile(HRawDocument rawDocument, File fromFile, String extension) { String fileName = generateFileNameFor(rawDocument, extension); rawDocument.setFileId(fileName); File newFile = getFileForName(fileName); try { Files.copy(fromFile, newFile); } catch (IOException e) { // FIXME damason: throw something more specific and handle at call // sites throw new RuntimeException(e); } GlobalDocumentId globalId = getGlobalId(rawDocument); log.info("Persisted raw document {} to file {}", globalId, newFile.getAbsolutePath()); virusScanner.scan(newFile, globalId.toString()); } @Override public void copyAndPersistRawDocument(HRawDocument fromDoc, HRawDocument toDoc) { File file = getFileForRawDocument(fromDoc); persistRawDocumentContentFromFile(toDoc, file, FilenameUtils.getExtension(file.getName())); } private File getFileForName(String fileName) { File docsPath = ensureDocsDirectory(); File newFile = new File(docsPath, fileName); return newFile; } private File ensureDocsDirectory() { String basePathStringOrNull = appConfig.getDocumentFileStorageLocation(); if (basePathStringOrNull == null) { throw new RuntimeException( "Document storage location is not configured in JNDI."); } File docsDirectory = new File(basePathStringOrNull, RAW_DOCUMENTS_SUBDIRECTORY); docsDirectory.mkdirs(); return docsDirectory; } private static String generateFileNameFor(HRawDocument rawDocument, String extension) { // Could change to use id of rawDocument, and throw if rawDocument has // no id yet. String idAsString = rawDocument.getDocument().getId().toString(); return idAsString + "." + extension; } // TODO damason: put this in a more appropriate location private static GlobalDocumentId getGlobalId(HRawDocument rawDocument) { HDocument document = rawDocument.getDocument(); HProjectIteration version = document.getProjectIteration(); HProject project = version.getProject(); GlobalDocumentId id = new GlobalDocumentId(project.getSlug(), version.getSlug(), document.getDocId()); return id; } @Override public InputStream getRawDocumentContentAsStream(HRawDocument document) throws RawDocumentContentAccessException { File rawFile = getFileForRawDocument(document); try { return new FileInputStream(rawFile); } catch (FileNotFoundException e) { // FIXME damason: throw more specific exception and handle at call // sites throw new RuntimeException(e); } } @Override public boolean hasPersistedDocument(GlobalDocumentId id) { HDocument doc = documentDAO.getByGlobalId(id); if (doc != null) { HRawDocument rawDocument = doc.getRawDocument(); return rawDocument != null && getFileForRawDocument(rawDocument).exists(); } return false; } private File getFileForRawDocument(HRawDocument rawDocument) { return getFileForName(rawDocument.getFileId()); } }
itsazzad/zanata-server
zanata-war/src/main/java/org/zanata/file/FileSystemPersistService.java
Java
gpl-2.0
5,646
/* Copyright (C) 2017 Axel Müller <axel.mueller@avanux.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. */ export class StartingCurrentSwitch { static get TYPE(): string { return 'de.avanux.smartapplianceenabler.control.StartingCurrentSwitch'; } '@class' = StartingCurrentSwitch.TYPE; powerThreshold: number; startingCurrentDetectionDuration: number; finishedCurrentDetectionDuration: number; minRunningTime: number; public constructor(init?: Partial<StartingCurrentSwitch>) { Object.assign(this, init); } }
camueller/SmartApplianceEnabler
src/main/angular/src/app/control/startingcurrent/starting-current-switch.ts
TypeScript
gpl-2.0
1,175
package info.thecodinglive.service; import info.thecodinglive.model.Team; import info.thecodinglive.repository.TeamDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional public class TeamServiceImpl implements TeamService{ @Autowired private TeamDao teamDao; @Override public void addTeam(Team team) { teamDao.addTeam(team); } @Override public void updateTeam(Team team) { teamDao.updateTeam(team); } @Override public Team getTeam(int id) { return teamDao.getTeam(id); } @Override public void deleteTeam(int id) { teamDao.deleteTeam(id); } @Override public List<Team> getTeams() { return teamDao.getTeams(); } }
thecodinglive/hanbit-gradle-book-example
ch06/src/main/java/info/thecodinglive/service/TeamServiceImpl.java
Java
gpl-2.0
902
<?php /** * @file * Contains \Drupal\fillpdf\Service\FillPdfLinkManipulator. */ namespace Drupal\fillpdf\Service; use Drupal\Component\Utility\UrlHelper; use Drupal\Core\Url; use Drupal\fillpdf\Entity\FillPdfForm; use Drupal\fillpdf\FillPdfLinkManipulatorInterface; use Symfony\Component\HttpFoundation\Request; /** * {@inheritDoc} */ class FillPdfLinkManipulator implements FillPdfLinkManipulatorInterface { /** * @param Request $request The request containing the query string to parse. * @return array * * @todo: Maybe this should return a FillPdfLinkContext object or something? * Guess it depends on how much I end up needing to change it. */ public function parseRequest(Request $request) { // @todo: Use Url::fromRequest when/if it lands in core. See https://www.drupal.org/node/2605530 $path = $request->getUri(); $request_url = $this->createUrlFromString($path); return $this->parseLink($request_url); } /** * @param $url * * @see FillPdfLinkManipulatorInterface::parseUrlString() * * @return \Drupal\Core\Url */ protected function createUrlFromString($url) { $url_parts = UrlHelper::parse($url); $path = $url_parts['path']; $query = $url_parts['query']; $link = Url::fromUri($path, ['query' => $query]); return $link; } /** * {@inheritDoc} */ public function parseLink(Url $link) { $query = $link->getOption('query'); if (!$query) { throw new \InvalidArgumentException('The \Drupal\Core\Url you pass in must have its \'query\' option set.'); } $request_context = [ 'entity_ids' => NULL, 'fid' => NULL, 'sample' => NULL, 'force_download' => FALSE, 'flatten' => TRUE, ]; if (!empty($query['sample'])) { $sample = TRUE; } // Is this just the PDF populated with sample data? $request_context['sample'] = $sample; if (!empty($query['fid'])) { $request_context['fid'] = $query['fid']; } else { throw new \InvalidArgumentException('fid parameter missing from query string; cannot determine how to proceed, so failing.'); } if (!empty($query['entity_type'])) { $request_context['entity_type'] = $query['entity_type']; } $request_context['entity_ids'] = $entity_ids = []; if (!empty($query['entity_id']) || !empty($query['entity_ids'])) { $entity_ids = (!empty($query['entity_id']) ? [$query['entity_id']] : $query['entity_ids']); // Re-key entity IDs so they can be loaded easily with loadMultiple(). // If we have type information, add it to the types array, and remove it // in order to make sure we only store the ID in the entity_ids key. foreach ($entity_ids as $entity_id) { $entity_id_parts = explode(':', $entity_id); if (count($entity_id_parts) == 2) { $entity_type = $entity_id_parts[0]; $entity_id = $entity_id_parts[1]; } elseif (!empty($request_context['entity_type'])) { $entity_type = $request_context['entity_type']; } else { $entity_type = 'node'; } $request_context['entity_ids'] += [ $entity_type => [], ]; $request_context['entity_ids'][$entity_type][$entity_id] = $entity_id; } } else { // Populate defaults. $fillpdf_form = FillPdfForm::load($request_context['fid']); $default_entity_id = $fillpdf_form->default_entity_id->value; if ($default_entity_id) { $default_entity_type = $fillpdf_form->default_entity_type->value; if (empty($default_entity_type)) { $default_entity_type = 'node'; } $request_context['entity_ids'] = [ $default_entity_type => [$default_entity_id => $default_entity_id], ]; } } // We've processed the shorthand forms, so unset them. unset($request_context['entity_id'], $request_context['entity_type']); if (!$query['download'] && (int) $query['download'] == 1) { $request_context['force_download'] = TRUE; } if ($query['flatten'] && (int) $query['flatten'] == 0) { $request_context['flatten'] = FALSE; } return $request_context; } public function parseUrlString($url) { $link = $this->createUrlFromString($url); return $this->parseLink($link); } /** * {@inheritdoc} */ public function generateLink(array $parameters) { $query = []; if (!isset($parameters['fid'])) { throw new \InvalidArgumentException("The $parameters argument must contain the fid key (the FillPdfForm's ID)."); } $query['fid'] = $parameters['fid']; // Only set the following properties if they're not at their default values. // This makes the resulting Url a bit cleaner. // Structure: // '<key in context array>' => [ // ['<key in query string>', <default system value>] // ... // ] // @todo: Create a value object for FillPdfMergeContext and get the defaults here from that $parameter_info = [ 'sample' => ['sample', FALSE], 'force_download' => ['download', FALSE], 'flatten' => ['flatten', TRUE], ]; foreach ($parameter_info as $context_key => $info) { $query_key = $info[0]; $parameter_default = $info[1]; if (isset($parameters[$context_key]) && $parameters[$context_key] != $parameter_default) { $query[$query_key] = $parameters[$context_key]; } } // $query['entity_ids'] contains entity IDs indexed by entity type. // Collapse these into the entity_type:entity_id format. $query['entity_ids'] = []; $entity_info = $parameters['entity_ids']; foreach ($entity_info as $entity_type => $entity_ids) { foreach ($entity_ids as $entity_id) { $query['entity_ids'][] = "{$entity_type}:{$entity_id}"; } } $fillpdf_link = Url::fromRoute('fillpdf.populate_pdf', [], ['query' => $query]); return $fillpdf_link; } }
AshishNaik021/iimisac-d8
modules/fillpdf/src/Service/FillPdfLinkManipulator.php
PHP
gpl-2.0
6,027
<?php /** * 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; under version 2 * of the License (non-upgradable). * * 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. * * Copyright (c) 2018 (original work) Open Assessment Technologies SA; * */ namespace oat\taoTestCenter\model\routing; use oat\tao\model\routing\AbstractApiRoute; /** * Route for RestApi controllers * @author Aleh Hutnikau, <hutnikau@1pt.com> */ class ApiRoute extends AbstractApiRoute { const REST_CONTROLLER_PREFIX = 'oat\\taoTestCenter\\controller\\Rest'; /** * @inheritdoc * @return string */ public static function getControllerPrefix() { return self::REST_CONTROLLER_PREFIX; } }
oat-sa/extension-tao-testcenter
model/routing/ApiRoute.php
PHP
gpl-2.0
1,246
package org.lastbamboo.common.sip.stack.message.header; import java.io.IOException; import java.net.InetAddress; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.id.uuid.UUID; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.littleshoot.util.RuntimeIoException; /** * Factory for creating SIP headers. */ public class SipHeaderFactoryImpl implements SipHeaderFactory { private final Logger LOG = LoggerFactory.getLogger(SipHeaderFactoryImpl.class); private static int sequenceNumber = 1; public SipHeader createHeader(final String name, final String value) { final List<SipHeaderValue> headerValues; try { headerValues = createHeaderValues(value); } catch (final IOException e) { LOG.error("Could not parse header"); throw new RuntimeIoException(e); } return new SipHeaderImpl(name, headerValues); } /** * Creates a list of header values. * * @param headerValueString The header value string. * @return A list of header value instances. * @throws IOException If the header values don't match the expected * syntax. * * TODO: This should really be handled at the protocol reading level * rather than re-parsing read data here. */ private List<SipHeaderValue> createHeaderValues( final String headerValueString) throws IOException { final List<SipHeaderValue> valuesList = new ArrayList<SipHeaderValue>(); if (!StringUtils.contains(headerValueString, ",")) { final SipHeaderValue value = new SipHeaderValueImpl(headerValueString); valuesList.add(value); return valuesList; } final String[] values = StringUtils.split(headerValueString, ","); for (int i = 0; i < values.length; i++) { final SipHeaderValue value = new SipHeaderValueImpl(values[i].trim()); valuesList.add(value); } return valuesList; } public SipHeader createSentByVia(final InetAddress address) { final String baseValue = "SIP/2.0/TCP " + address.getHostAddress(); final Map<String, String> params = createParams(SipHeaderParamNames.BRANCH, createBranchId()); return new SipHeaderImpl(SipHeaderNames.VIA, new SipHeaderValueImpl(baseValue, params)); } public SipHeader createMaxForwards(final int maxForwards) { final String valueString = Integer.toString(maxForwards); final SipHeaderValue value = new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP); return new SipHeaderImpl(SipHeaderNames.MAX_FORWARDS, value); } public SipHeader createSupported() { final String valueString = "outbound"; final SipHeaderValue value = new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP); return new SipHeaderImpl(SipHeaderNames.SUPPORTED, value); } public SipHeader createTo(final URI sipUri) { final String valueString = "Anonymous <"+sipUri+">"; final SipHeaderValue value = new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP); return new SipHeaderImpl(SipHeaderNames.TO, value); } public SipHeader createTo(final SipHeader originalTo) { final SipHeaderValue value = originalTo.getValue(); final Map<String, String> params = value.getParams(); params.put(SipHeaderParamNames.TAG, createTagValue()); final SipHeaderValue copy = new SipHeaderValueImpl(value.getBaseValue(), params); return new SipHeaderImpl(SipHeaderNames.TO, copy); } public SipHeader createFrom(final String displayName, final URI sipUri) { final String baseValue = displayName + " <"+sipUri+">"; final Map<String, String> params = createParams(SipHeaderParamNames.TAG, createTagValue()); final SipHeaderValue value = new SipHeaderValueImpl(baseValue, params); return new SipHeaderImpl(SipHeaderNames.FROM, value); } public SipHeader createCallId() { final String valueString = createCallIdValue(); final SipHeaderValue value = new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP); return new SipHeaderImpl(SipHeaderNames.CALL_ID, value); } public SipHeader createCSeq(final String method) { final String valueString = createCSeqValue(method); final SipHeaderValue value = new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP); return new SipHeaderImpl(SipHeaderNames.CSEQ, value); } public SipHeader createContact(final URI contactUri, final UUID instanceId) { final String baseValue = "<"+contactUri+">"; final String sipInstanceValue = "\"<"+instanceId.toUrn()+">\""; final Map<String, String> params = createParams(SipHeaderParamNames.SIP_INSTANCE, sipInstanceValue); final SipHeaderValue value = new SipHeaderValueImpl(baseValue, params); return new SipHeaderImpl(SipHeaderNames.CONTACT, value); } public SipHeader createExpires(final int millis) { final String valueString = Integer.toString(millis); final SipHeaderValue value = new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP); return new SipHeaderImpl(SipHeaderNames.EXPIRES, value); } public SipHeader createContentLength(final int contentLength) { final String valueString = Integer.toString(contentLength); final SipHeaderValue value = new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP); return new SipHeaderImpl(SipHeaderNames.CONTENT_LENGTH, value); } private String createTagValue() { final UUID id = UUID.randomUUID(); final String urn = id.toUrn(); return urn.substring(9, 19); } private String createCallIdValue() { final UUID id = UUID.randomUUID(); return id.toUrn().substring(10, 18); } private String createBranchId() { final UUID id = UUID.randomUUID(); return "z9hG4bK"+id.toUrn().substring(10, 17); } private String createCSeqValue(final String method) { sequenceNumber++; return sequenceNumber + " " + method; } /** * Generates the parameters map. This is the complete parameters for the * common case where a header only has a single parameter. Otherwise, * calling methods can add additional parameters to the map. * * @param name The name of the first parameter to add. * @param value The value of the first parameter to add. * @return The map mapping parameter names to parameter values. */ private Map<String, String> createParams(final String name, final String value) { final Map<String, String> params = new HashMap<String, String>(); params.put(name, value); return params; } }
adamfisk/littleshoot-client
common/sip/stack/src/main/java/org/lastbamboo/common/sip/stack/message/header/SipHeaderFactoryImpl.java
Java
gpl-2.0
7,606
package testing; /** * Copyright (C) 2015 Matthew Mussomele * * This file is part of ChoiceOptimizationAlgorithm * * ChoiceOptimizationAlgorithm is free software: you can redistribute it * and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import duty_scheduler.RA; import duty_scheduler.RA.RABuilder; import duty_scheduler.Duty; import duty_scheduler.Schedule; import duty_scheduler.Schedule.ScheduleBuilder; import java.util.ArrayList; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; /** * JUnit Testing Class for the duty_scheduler.Schedule class. * * @author Matthew Mussomele */ public class TestSchedule { private static final int THIS_YEAR = 2015; private ScheduleBuilder testBuilder; private Schedule test; private ArrayList<RA> raList; private ArrayList<Duty> dutyList; /** * Fill the four instance variables with some simple test instances before every test. */ @Before public void setUp() { dutyList = new ArrayList<Duty>(); for (int i = 0; i < 6; i += 1) { dutyList.add(new Duty(THIS_YEAR, 1, i + 1, "/")); } raList = new ArrayList<RA>(); for (int i = 0; i < 2; i += 1) { RABuilder builder = new RABuilder(String.format("RA%d", i), 6, 3); for (int j = 0; j < 6; j += 1) { if (i == 0) { builder.putPreference(dutyList.get(j), j); } else { builder.putPreference(dutyList.get(j), 5 - j); } } raList.add(builder.build()); } ScheduleBuilder builder = new ScheduleBuilder(raList.size(), dutyList.size()); for (int i = 0; i < 3; i += 1) { builder.putAssignment(raList.get(0), dutyList.get(5 - i)); } for (int i = 0; i < 3; i += 1) { builder.putAssignment(raList.get(1), dutyList.get(i)); } testBuilder = builder; test = builder.build(); } /** * Tests that the ScheduleBuilder works and properly returns a Schedule instance */ @Test public void testBuild() { for (int i = 0; i < raList.size(); i += 1) { assertTrue(testBuilder.doneAssigning(raList.get(i))); } assertNotNull(test); } /** * Tests that the built Schedule's basic functions perform to the requirements of the package. * These tests are to ensure that these methods are not changed by a programmer in such a way * that would cause Schedules to be lost in a Hash or Tree based structure. */ @Test public void testBasics() { for (int i = 0; i < raList.size(); i += 1) { for (Duty duty : test.getAssignments(raList.get(i))) { assertTrue(dutyList.contains(duty)); } } assertTrue(test.equals(test)); assertEquals(0, test.compareTo(test)); } }
Unit4TechProjects/ChoiceOptimization
testing/TestSchedule.java
Java
gpl-2.0
3,494
// // -------------------------------------------------------------------------- // Gurux Ltd // // // // Filename: $HeadURL$ // // Version: $Revision$, // $Date$ // $Author$ // // Copyright (c) Gurux Ltd // //--------------------------------------------------------------------------- // // DESCRIPTION // // This file is a part of Gurux Device Framework. // // Gurux Device Framework is Open Source 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. // Gurux Device Framework 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. // // More information of Gurux products: https://www.gurux.org // // This code is licensed under the GNU General Public License v2. // Full text may be retrieved at http://www.gnu.org/licenses/gpl-2.0.txt //--------------------------------------------------------------------------- using Gurux.DLMS.Objects.Enums; using System; namespace Gurux.DLMS.Objects { public class GXApplicationContextName { /// <summary> /// Constructor /// </summary> public GXApplicationContextName() { JointIsoCtt = 2; Country = 16; CountryName = 756; IdentifiedOrganization = 5; DlmsUA = 8; ApplicationContext = 1; ContextId = ApplicationContextName.LogicalName; } public byte JointIsoCtt { get; set; } public byte Country { get; set; } public UInt16 CountryName { get; set; } public byte IdentifiedOrganization { get; set; } public byte DlmsUA { get; set; } public byte ApplicationContext { get; set; } public ApplicationContextName ContextId { get; set; } public override string ToString() { return JointIsoCtt.ToString() + " " + Country.ToString() + " " + CountryName.ToString() + " " + IdentifiedOrganization.ToString() + " " + DlmsUA.ToString() + " " + ApplicationContext.ToString() + " " + ContextId.ToString(); } } }
Gurux/Gurux.DLMS.Net
Development/Objects/GXApplicationContextName.cs
C#
gpl-2.0
2,668
# # Copyright 2019-2022 Ghent University # # This file is part of vsc-mympirun, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # the Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/hpcugent/vsc-mympirun # # vsc-mympirun 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 v2. # # vsc-mympirun 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 vsc-mympirun. If not, see <http://www.gnu.org/licenses/>. # """ End-to-end tests for mypmirun """ import os import logging logging.basicConfig(level=logging.DEBUG) from pmi_utils import PMITest from vsc.utils.affinity import sched_getaffinity, sched_setaffinity class TaskPrologEnd2End(PMITest): def setUp(self): """Prepare to run test.""" super(TaskPrologEnd2End, self).setUp() self.script = os.path.join(os.path.dirname(self.script), 'mytaskprolog.py') def test_simple(self): origaff = sched_getaffinity() aff = sched_getaffinity() aff.set_bits([1]) # only use first core (we can always assume there is one core sched_setaffinity(aff) self.pmirun([], pattern='export CUDA_VISIBLE_DEVICES=0') # restore sched_setaffinity(origaff)
hpcugent/vsc-mympirun
test/mytaskprolog.py
Python
gpl-2.0
1,831
from fabric.api import local def html(): local('hovercraft -t ./sixfeetup_hovercraft formation_flask.rst ./build/')
domofwk/domofwk-docs
source/formations/flask/fabfile.py
Python
gpl-2.0
122
/** * */ package co.innovate.rentavoz.services.ciudad; import java.util.List; import co.innovate.rentavoz.model.Ciudad; import co.innovate.rentavoz.model.Departamento; import co.innovate.rentavoz.services.GenericService; /** * @author <a href="mailto:elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a> * @project rentavoz3 * @class CiudadService * @date 13/01/2014 * */ public interface CiudadService extends GenericService<Ciudad, Integer> { /** * @author <a href="elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a> * @date 13/01/2014 * @param criterio * @param departamento * @return */ List<Ciudad> findByCriterio(String criterio, Departamento departamento); /** * * @author <a href="elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a> * @date 1/02/2014 * @param criterio * @return */ List<Ciudad> findByCriterio(String criterio); }
kaisenlean/rentavoz3
src/main/java/co/innovate/rentavoz/services/ciudad/CiudadService.java
Java
gpl-2.0
887
(function (root, factory) { if (root === undefined && window !== undefined) root = window; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define('wavesurfer', [], function () { return (root['WaveSurfer'] = factory()); }); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); } else { root['WaveSurfer'] = factory(); } }(this, function () { 'use strict'; var WaveSurfer = { defaultParams: { audioContext : null, audioRate : 1, autoCenter : true, backend : 'WebAudio', barHeight : 1, closeAudioContext: false, container : null, cursorColor : '#333', cursorWidth : 1, dragSelection : true, fillParent : true, forceDecode : false, height : 128, hideScrollbar : false, interact : true, loopSelection : true, mediaContainer: null, mediaControls : false, mediaType : 'audio', minPxPerSec : 20, partialRender : false, pixelRatio : window.devicePixelRatio || screen.deviceXDPI / screen.logicalXDPI, progressColor : '#555', normalize : false, renderer : 'MultiCanvas', scrollParent : false, skipLength : 2, splitChannels : false, waveColor : '#999', }, init: function (params) { // Extract relevant parameters (or defaults) this.params = WaveSurfer.util.extend({}, this.defaultParams, params); this.container = 'string' == typeof params.container ? document.querySelector(this.params.container) : this.params.container; if (!this.container) { throw new Error('Container element not found'); } if (this.params.mediaContainer == null) { this.mediaContainer = this.container; } else if (typeof this.params.mediaContainer == 'string') { this.mediaContainer = document.querySelector(this.params.mediaContainer); } else { this.mediaContainer = this.params.mediaContainer; } if (!this.mediaContainer) { throw new Error('Media Container element not found'); } // Used to save the current volume when muting so we can // restore once unmuted this.savedVolume = 0; // The current muted state this.isMuted = false; // Will hold a list of event descriptors that need to be // cancelled on subsequent loads of audio this.tmpEvents = []; // Holds any running audio downloads this.currentAjax = null; this.createDrawer(); this.createBackend(); this.createPeakCache(); this.isDestroyed = false; }, createDrawer: function () { var my = this; this.drawer = Object.create(WaveSurfer.Drawer[this.params.renderer]); this.drawer.init(this.container, this.params); this.drawer.on('redraw', function () { my.drawBuffer(); my.drawer.progress(my.backend.getPlayedPercents()); }); // Click-to-seek this.drawer.on('click', function (e, progress) { setTimeout(function () { my.seekTo(progress); }, 0); }); // Relay the scroll event from the drawer this.drawer.on('scroll', function (e) { if (my.params.partialRender) { my.drawBuffer(); } my.fireEvent('scroll', e); }); }, createBackend: function () { var my = this; if (this.backend) { this.backend.destroy(); } // Back compat if (this.params.backend == 'AudioElement') { this.params.backend = 'MediaElement'; } if (this.params.backend == 'WebAudio' && !WaveSurfer.WebAudio.supportsWebAudio()) { this.params.backend = 'MediaElement'; } this.backend = Object.create(WaveSurfer[this.params.backend]); this.backend.init(this.params); this.backend.on('finish', function () { my.fireEvent('finish'); }); this.backend.on('play', function () { my.fireEvent('play'); }); this.backend.on('pause', function () { my.fireEvent('pause'); }); this.backend.on('audioprocess', function (time) { my.drawer.progress(my.backend.getPlayedPercents()); my.fireEvent('audioprocess', time); }); }, createPeakCache: function() { if (this.params.partialRender) { this.peakCache = Object.create(WaveSurfer.PeakCache); this.peakCache.init(); } }, getDuration: function () { return this.backend.getDuration(); }, getCurrentTime: function () { return this.backend.getCurrentTime(); }, play: function (start, end) { this.fireEvent('interaction', this.play.bind(this, start, end)); this.backend.play(start, end); }, pause: function () { this.backend.isPaused() || this.backend.pause(); }, playPause: function () { this.backend.isPaused() ? this.play() : this.pause(); }, isPlaying: function () { return !this.backend.isPaused(); }, skipBackward: function (seconds) { this.skip(-seconds || -this.params.skipLength); }, skipForward: function (seconds) { this.skip(seconds || this.params.skipLength); }, skip: function (offset) { var position = this.getCurrentTime() || 0; var duration = this.getDuration() || 1; position = Math.max(0, Math.min(duration, position + (offset || 0))); this.seekAndCenter(position / duration); }, seekAndCenter: function (progress) { this.seekTo(progress); this.drawer.recenter(progress); }, seekTo: function (progress) { this.fireEvent('interaction', this.seekTo.bind(this, progress)); var paused = this.backend.isPaused(); // avoid draw wrong position while playing backward seeking if (!paused) { this.backend.pause(); } // avoid small scrolls while paused seeking var oldScrollParent = this.params.scrollParent; this.params.scrollParent = false; this.backend.seekTo(progress * this.getDuration()); this.drawer.progress(this.backend.getPlayedPercents()); if (!paused) { this.backend.play(); } this.params.scrollParent = oldScrollParent; this.fireEvent('seek', progress); }, stop: function () { this.pause(); this.seekTo(0); this.drawer.progress(0); }, /** * Set the playback volume. * * @param {Number} newVolume A value between 0 and 1, 0 being no * volume and 1 being full volume. */ setVolume: function (newVolume) { this.backend.setVolume(newVolume); }, /** * Get the playback volume. */ getVolume: function () { return this.backend.getVolume(); }, /** * Set the playback rate. * * @param {Number} rate A positive number. E.g. 0.5 means half the * normal speed, 2 means double speed and so on. */ setPlaybackRate: function (rate) { this.backend.setPlaybackRate(rate); }, /** * Get the playback rate. */ getPlaybackRate: function () { return this.backend.getPlaybackRate(); }, /** * Toggle the volume on and off. It not currenly muted it will * save the current volume value and turn the volume off. * If currently muted then it will restore the volume to the saved * value, and then rest the saved value. */ toggleMute: function () { this.setMute(!this.isMuted); }, setMute: function (mute) { // ignore all muting requests if the audio is already in that state if (mute === this.isMuted) { return; } if (mute) { // If currently not muted then save current volume, // turn off the volume and update the mute properties this.savedVolume = this.backend.getVolume(); this.backend.setVolume(0); this.isMuted = true; } else { // If currently muted then restore to the saved volume // and update the mute properties this.backend.setVolume(this.savedVolume); this.isMuted = false; } }, /** * Get the current mute status. */ getMute: function () { return this.isMuted; }, /** * Get the list of current set filters as an array. * * Filters must be set with setFilters method first */ getFilters: function() { return this.backend.filters || []; }, toggleScroll: function () { this.params.scrollParent = !this.params.scrollParent; this.drawBuffer(); }, toggleInteraction: function () { this.params.interact = !this.params.interact; }, drawBuffer: function () { var nominalWidth = Math.round( this.getDuration() * this.params.minPxPerSec * this.params.pixelRatio ); var parentWidth = this.drawer.getWidth(); var width = nominalWidth; var start = this.drawer.getScrollX(); var end = Math.min(start + parentWidth, width); // Fill container if (this.params.fillParent && (!this.params.scrollParent || nominalWidth < parentWidth)) { width = parentWidth; start = 0; end = width; } if (this.params.partialRender) { var newRanges = this.peakCache.addRangeToPeakCache(width, start, end); for (var i = 0; i < newRanges.length; i++) { var peaks = this.backend.getPeaks(width, newRanges[i][0], newRanges[i][1]); this.drawer.drawPeaks(peaks, width, newRanges[i][0], newRanges[i][1]); } } else { start = 0; end = width; var peaks = this.backend.getPeaks(width, start, end); this.drawer.drawPeaks(peaks, width, start, end); } this.fireEvent('redraw', peaks, width); }, zoom: function (pxPerSec) { this.params.minPxPerSec = pxPerSec; this.params.scrollParent = true; this.drawBuffer(); this.drawer.progress(this.backend.getPlayedPercents()); this.drawer.recenter( this.getCurrentTime() / this.getDuration() ); this.fireEvent('zoom', pxPerSec); }, /** * Internal method. */ loadArrayBuffer: function (arraybuffer) { this.decodeArrayBuffer(arraybuffer, function (data) { if (!this.isDestroyed) { this.loadDecodedBuffer(data); } }.bind(this)); }, /** * Directly load an externally decoded AudioBuffer. */ loadDecodedBuffer: function (buffer) { this.backend.load(buffer); this.drawBuffer(); this.fireEvent('ready'); }, /** * Loads audio data from a Blob or File object. * * @param {Blob|File} blob Audio data. */ loadBlob: function (blob) { var my = this; // Create file reader var reader = new FileReader(); reader.addEventListener('progress', function (e) { my.onProgress(e); }); reader.addEventListener('load', function (e) { my.loadArrayBuffer(e.target.result); }); reader.addEventListener('error', function () { my.fireEvent('error', 'Error reading file'); }); reader.readAsArrayBuffer(blob); this.empty(); }, /** * Loads audio and re-renders the waveform. */ load: function (url, peaks, preload) { this.empty(); this.isMuted = false; switch (this.params.backend) { case 'WebAudio': return this.loadBuffer(url, peaks); case 'MediaElement': return this.loadMediaElement(url, peaks, preload); } }, /** * Loads audio using Web Audio buffer backend. */ loadBuffer: function (url, peaks) { var load = (function (action) { if (action) { this.tmpEvents.push(this.once('ready', action)); } return this.getArrayBuffer(url, this.loadArrayBuffer.bind(this)); }).bind(this); if (peaks) { this.backend.setPeaks(peaks); this.drawBuffer(); this.tmpEvents.push(this.once('interaction', load)); } else { return load(); } }, /** * Either create a media element, or load * an existing media element. * @param {String|HTMLElement} urlOrElt Either a path to a media file, * or an existing HTML5 Audio/Video * Element * @param {Array} [peaks] Array of peaks. Required to bypass * web audio dependency */ loadMediaElement: function (urlOrElt, peaks, preload) { var url = urlOrElt; if (typeof urlOrElt === 'string') { this.backend.load(url, this.mediaContainer, peaks, preload); } else { var elt = urlOrElt; this.backend.loadElt(elt, peaks); // If peaks are not provided, // url = element.src so we can get peaks with web audio url = elt.src; } this.tmpEvents.push( this.backend.once('canplay', (function () { this.drawBuffer(); this.fireEvent('ready'); }).bind(this)), this.backend.once('error', (function (err) { this.fireEvent('error', err); }).bind(this)) ); // If no pre-decoded peaks provided or pre-decoded peaks are // provided with forceDecode flag, attempt to download the // audio file and decode it with Web Audio. if (peaks) { this.backend.setPeaks(peaks); } if ((!peaks || this.params.forceDecode) && this.backend.supportsWebAudio()) { this.getArrayBuffer(url, (function (arraybuffer) { this.decodeArrayBuffer(arraybuffer, (function (buffer) { this.backend.buffer = buffer; this.backend.setPeaks(null); this.drawBuffer(); this.fireEvent('waveform-ready'); }).bind(this)); }).bind(this)); } }, decodeArrayBuffer: function (arraybuffer, callback) { this.arraybuffer = arraybuffer; this.backend.decodeArrayBuffer( arraybuffer, (function (data) { // Only use the decoded data if we haven't been destroyed or another decode started in the meantime if (!this.isDestroyed && this.arraybuffer == arraybuffer) { callback(data); this.arraybuffer = null; } }).bind(this), this.fireEvent.bind(this, 'error', 'Error decoding audiobuffer') ); }, getArrayBuffer: function (url, callback) { var my = this; var ajax = WaveSurfer.util.ajax({ url: url, responseType: 'arraybuffer' }); this.currentAjax = ajax; this.tmpEvents.push( ajax.on('progress', function (e) { my.onProgress(e); }), ajax.on('success', function (data, e) { callback(data); my.currentAjax = null; }), ajax.on('error', function (e) { my.fireEvent('error', 'XHR error: ' + e.target.statusText); my.currentAjax = null; }) ); return ajax; }, onProgress: function (e) { if (e.lengthComputable) { var percentComplete = e.loaded / e.total; } else { // Approximate progress with an asymptotic // function, and assume downloads in the 1-3 MB range. percentComplete = e.loaded / (e.loaded + 1000000); } this.fireEvent('loading', Math.round(percentComplete * 100), e.target); }, /** * Exports PCM data into a JSON array and opens in a new window. */ exportPCM: function (length, accuracy, noWindow) { length = length || 1024; accuracy = accuracy || 10000; noWindow = noWindow || false; var peaks = this.backend.getPeaks(length, accuracy); var arr = [].map.call(peaks, function (val) { return Math.round(val * accuracy) / accuracy; }); var json = JSON.stringify(arr); if (!noWindow) { window.open('data:application/json;charset=utf-8,' + encodeURIComponent(json)); } return json; }, /** * Save waveform image as data URI. * * The default format is 'image/png'. Other supported types are * 'image/jpeg' and 'image/webp'. */ exportImage: function(format, quality) { if (!format) { format = 'image/png'; } if (!quality) { quality = 1; } return this.drawer.getImage(format, quality); }, cancelAjax: function () { if (this.currentAjax) { this.currentAjax.xhr.abort(); this.currentAjax = null; } }, clearTmpEvents: function () { this.tmpEvents.forEach(function (e) { e.un(); }); }, /** * Display empty waveform. */ empty: function () { if (!this.backend.isPaused()) { this.stop(); this.backend.disconnectSource(); } this.cancelAjax(); this.clearTmpEvents(); this.drawer.progress(0); this.drawer.setWidth(0); this.drawer.drawPeaks({ length: this.drawer.getWidth() }, 0); }, /** * Remove events, elements and disconnect WebAudio nodes. */ destroy: function () { this.fireEvent('destroy'); this.cancelAjax(); this.clearTmpEvents(); this.unAll(); this.backend.destroy(); this.drawer.destroy(); this.isDestroyed = true; } }; WaveSurfer.create = function (params) { var wavesurfer = Object.create(WaveSurfer); wavesurfer.init(params); return wavesurfer; }; WaveSurfer.util = { extend: function (dest) { var sources = Array.prototype.slice.call(arguments, 1); sources.forEach(function (source) { Object.keys(source).forEach(function (key) { dest[key] = source[key]; }); }); return dest; }, debounce: function (func, wait, immediate) { var args, context, timeout; var later = function() { timeout = null; if (!immediate) { func.apply(context, args); } }; return function() { context = this; args = arguments; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) { func.apply(context, args); } }; }, min: function (values) { var min = +Infinity; for (var i in values) { if (values[i] < min) { min = values[i]; } } return min; }, max: function (values) { var max = -Infinity; for (var i in values) { if (values[i] > max) { max = values[i]; } } return max; }, getId: function () { return 'wavesurfer_' + Math.random().toString(32).substring(2); }, ajax: function (options) { var ajax = Object.create(WaveSurfer.Observer); var xhr = new XMLHttpRequest(); var fired100 = false; xhr.open(options.method || 'GET', options.url, true); xhr.responseType = options.responseType || 'json'; xhr.addEventListener('progress', function (e) { ajax.fireEvent('progress', e); if (e.lengthComputable && e.loaded == e.total) { fired100 = true; } }); xhr.addEventListener('load', function (e) { if (!fired100) { ajax.fireEvent('progress', e); } ajax.fireEvent('load', e); if (200 == xhr.status || 206 == xhr.status) { ajax.fireEvent('success', xhr.response, e); } else { ajax.fireEvent('error', e); } }); xhr.addEventListener('error', function (e) { ajax.fireEvent('error', e); }); xhr.send(); ajax.xhr = xhr; return ajax; } }; /* Observer */ WaveSurfer.Observer = { /** * Attach a handler function for an event. */ on: function (event, fn) { if (!this.handlers) { this.handlers = {}; } var handlers = this.handlers[event]; if (!handlers) { handlers = this.handlers[event] = []; } handlers.push(fn); // Return an event descriptor return { name: event, callback: fn, un: this.un.bind(this, event, fn) }; }, /** * Remove an event handler. */ un: function (event, fn) { if (!this.handlers) { return; } var handlers = this.handlers[event]; if (handlers) { if (fn) { for (var i = handlers.length - 1; i >= 0; i--) { if (handlers[i] == fn) { handlers.splice(i, 1); } } } else { handlers.length = 0; } } }, /** * Remove all event handlers. */ unAll: function () { this.handlers = null; }, /** * Attach a handler to an event. The handler is executed at most once per * event type. */ once: function (event, handler) { var my = this; var fn = function () { handler.apply(this, arguments); setTimeout(function () { my.un(event, fn); }, 0); }; return this.on(event, fn); }, fireEvent: function (event) { if (!this.handlers) { return; } var handlers = this.handlers[event]; var args = Array.prototype.slice.call(arguments, 1); handlers && handlers.forEach(function (fn) { fn.apply(null, args); }); } }; /* Make the main WaveSurfer object an observer */ WaveSurfer.util.extend(WaveSurfer, WaveSurfer.Observer); 'use strict'; WaveSurfer.WebAudio = { scriptBufferSize: 256, PLAYING_STATE: 0, PAUSED_STATE: 1, FINISHED_STATE: 2, supportsWebAudio: function () { return !!(window.AudioContext || window.webkitAudioContext); }, getAudioContext: function () { if (!WaveSurfer.WebAudio.audioContext) { WaveSurfer.WebAudio.audioContext = new ( window.AudioContext || window.webkitAudioContext ); } return WaveSurfer.WebAudio.audioContext; }, getOfflineAudioContext: function (sampleRate) { if (!WaveSurfer.WebAudio.offlineAudioContext) { WaveSurfer.WebAudio.offlineAudioContext = new ( window.OfflineAudioContext || window.webkitOfflineAudioContext )(1, 2, sampleRate); } return WaveSurfer.WebAudio.offlineAudioContext; }, init: function (params) { this.params = params; this.ac = params.audioContext || this.getAudioContext(); this.lastPlay = this.ac.currentTime; this.startPosition = 0; this.scheduledPause = null; this.states = [ Object.create(WaveSurfer.WebAudio.state.playing), Object.create(WaveSurfer.WebAudio.state.paused), Object.create(WaveSurfer.WebAudio.state.finished) ]; this.createVolumeNode(); this.createScriptNode(); this.createAnalyserNode(); this.setState(this.PAUSED_STATE); this.setPlaybackRate(this.params.audioRate); this.setLength(0); }, disconnectFilters: function () { if (this.filters) { this.filters.forEach(function (filter) { filter && filter.disconnect(); }); this.filters = null; // Reconnect direct path this.analyser.connect(this.gainNode); } }, setState: function (state) { if (this.state !== this.states[state]) { this.state = this.states[state]; this.state.init.call(this); } }, // Unpacked filters setFilter: function () { this.setFilters([].slice.call(arguments)); }, /** * @param {Array} filters Packed ilters array */ setFilters: function (filters) { // Remove existing filters this.disconnectFilters(); // Insert filters if filter array not empty if (filters && filters.length) { this.filters = filters; // Disconnect direct path before inserting filters this.analyser.disconnect(); // Connect each filter in turn filters.reduce(function (prev, curr) { prev.connect(curr); return curr; }, this.analyser).connect(this.gainNode); } }, createScriptNode: function () { if (this.ac.createScriptProcessor) { this.scriptNode = this.ac.createScriptProcessor(this.scriptBufferSize); } else { this.scriptNode = this.ac.createJavaScriptNode(this.scriptBufferSize); } this.scriptNode.connect(this.ac.destination); }, addOnAudioProcess: function () { var my = this; this.scriptNode.onaudioprocess = function () { var time = my.getCurrentTime(); if (time >= my.getDuration()) { my.setState(my.FINISHED_STATE); my.fireEvent('pause'); } else if (time >= my.scheduledPause) { my.pause(); } else if (my.state === my.states[my.PLAYING_STATE]) { my.fireEvent('audioprocess', time); } }; }, removeOnAudioProcess: function () { this.scriptNode.onaudioprocess = null; }, createAnalyserNode: function () { this.analyser = this.ac.createAnalyser(); this.analyser.connect(this.gainNode); }, /** * Create the gain node needed to control the playback volume. */ createVolumeNode: function () { // Create gain node using the AudioContext if (this.ac.createGain) { this.gainNode = this.ac.createGain(); } else { this.gainNode = this.ac.createGainNode(); } // Add the gain node to the graph this.gainNode.connect(this.ac.destination); }, /** * Set the gain to a new value. * * @param {Number} newGain The new gain, a floating point value * between 0 and 1. 0 being no gain and 1 being maximum gain. */ setVolume: function (newGain) { this.gainNode.gain.value = newGain; }, /** * Get the current gain. * * @returns {Number} The current gain, a floating point value * between 0 and 1. 0 being no gain and 1 being maximum gain. */ getVolume: function () { return this.gainNode.gain.value; }, decodeArrayBuffer: function (arraybuffer, callback, errback) { if (!this.offlineAc) { this.offlineAc = this.getOfflineAudioContext(this.ac ? this.ac.sampleRate : 44100); } this.offlineAc.decodeAudioData(arraybuffer, (function (data) { callback(data); }).bind(this), errback); }, /** * Set pre-decoded peaks. */ setPeaks: function (peaks) { this.peaks = peaks; }, /** * Set the rendered length (different from the length of the audio). */ setLength: function (length) { // No resize, we can preserve the cached peaks. if (this.mergedPeaks && length == ((2 * this.mergedPeaks.length - 1) + 2)) { return; } this.splitPeaks = []; this.mergedPeaks = []; // Set the last element of the sparse array so the peak arrays are // appropriately sized for other calculations. var channels = this.buffer ? this.buffer.numberOfChannels : 1; for (var c = 0; c < channels; c++) { this.splitPeaks[c] = []; this.splitPeaks[c][2 * (length - 1)] = 0; this.splitPeaks[c][2 * (length - 1) + 1] = 0; } this.mergedPeaks[2 * (length - 1)] = 0; this.mergedPeaks[2 * (length - 1) + 1] = 0; }, /** * Compute the max and min value of the waveform when broken into * <length> subranges. * @param {Number} length How many subranges to break the waveform into. * @param {Number} first First sample in the required range. * @param {Number} last Last sample in the required range. * @returns {Array} Array of 2*<length> peaks or array of arrays * of peaks consisting of (max, min) values for each subrange. */ getPeaks: function (length, first, last) { if (this.peaks) { return this.peaks; } this.setLength(length); var sampleSize = this.buffer.length / length; var sampleStep = ~~(sampleSize / 10) || 1; var channels = this.buffer.numberOfChannels; for (var c = 0; c < channels; c++) { var peaks = this.splitPeaks[c]; var chan = this.buffer.getChannelData(c); for (var i = first; i <= last; i++) { var start = ~~(i * sampleSize); var end = ~~(start + sampleSize); var min = 0; var max = 0; for (var j = start; j < end; j += sampleStep) { var value = chan[j]; if (value > max) { max = value; } if (value < min) { min = value; } } peaks[2 * i] = max; peaks[2 * i + 1] = min; if (c == 0 || max > this.mergedPeaks[2 * i]) { this.mergedPeaks[2 * i] = max; } if (c == 0 || min < this.mergedPeaks[2 * i + 1]) { this.mergedPeaks[2 * i + 1] = min; } } } return this.params.splitChannels ? this.splitPeaks : this.mergedPeaks; }, getPlayedPercents: function () { return this.state.getPlayedPercents.call(this); }, disconnectSource: function () { if (this.source) { this.source.disconnect(); } }, destroy: function () { if (!this.isPaused()) { this.pause(); } this.unAll(); this.buffer = null; this.disconnectFilters(); this.disconnectSource(); this.gainNode.disconnect(); this.scriptNode.disconnect(); this.analyser.disconnect(); // close the audioContext if closeAudioContext option is set to true if (this.params.closeAudioContext) { // check if browser supports AudioContext.close() if (typeof this.ac.close === 'function' && this.ac.state != 'closed') { this.ac.close(); } // clear the reference to the audiocontext this.ac = null; // clear the actual audiocontext, either passed as param or the // global singleton if (!this.params.audioContext) { WaveSurfer.WebAudio.audioContext = null; } else { this.params.audioContext = null; } // clear the offlineAudioContext WaveSurfer.WebAudio.offlineAudioContext = null; } }, load: function (buffer) { this.startPosition = 0; this.lastPlay = this.ac.currentTime; this.buffer = buffer; this.createSource(); }, createSource: function () { this.disconnectSource(); this.source = this.ac.createBufferSource(); //adjust for old browsers. this.source.start = this.source.start || this.source.noteGrainOn; this.source.stop = this.source.stop || this.source.noteOff; this.source.playbackRate.value = this.playbackRate; this.source.buffer = this.buffer; this.source.connect(this.analyser); }, isPaused: function () { return this.state !== this.states[this.PLAYING_STATE]; }, getDuration: function () { if (!this.buffer) { return 0; } return this.buffer.duration; }, seekTo: function (start, end) { if (!this.buffer) { return; } this.scheduledPause = null; if (start == null) { start = this.getCurrentTime(); if (start >= this.getDuration()) { start = 0; } } if (end == null) { end = this.getDuration(); } this.startPosition = start; this.lastPlay = this.ac.currentTime; if (this.state === this.states[this.FINISHED_STATE]) { this.setState(this.PAUSED_STATE); } return { start: start, end: end }; }, getPlayedTime: function () { return (this.ac.currentTime - this.lastPlay) * this.playbackRate; }, /** * Plays the loaded audio region. * * @param {Number} start Start offset in seconds, * relative to the beginning of a clip. * @param {Number} end When to stop * relative to the beginning of a clip. */ play: function (start, end) { if (!this.buffer) { return; } // need to re-create source on each playback this.createSource(); var adjustedTime = this.seekTo(start, end); start = adjustedTime.start; end = adjustedTime.end; this.scheduledPause = end; this.source.start(0, start, end - start); if (this.ac.state == 'suspended') { this.ac.resume && this.ac.resume(); } this.setState(this.PLAYING_STATE); this.fireEvent('play'); }, /** * Pauses the loaded audio. */ pause: function () { this.scheduledPause = null; this.startPosition += this.getPlayedTime(); this.source && this.source.stop(0); this.setState(this.PAUSED_STATE); this.fireEvent('pause'); }, /** * Returns the current time in seconds relative to the audioclip's duration. */ getCurrentTime: function () { return this.state.getCurrentTime.call(this); }, /** * Returns the current playback rate. */ getPlaybackRate: function () { return this.playbackRate; }, /** * Set the audio source playback rate. */ setPlaybackRate: function (value) { value = value || 1; if (this.isPaused()) { this.playbackRate = value; } else { this.pause(); this.playbackRate = value; this.play(); } } }; WaveSurfer.WebAudio.state = {}; WaveSurfer.WebAudio.state.playing = { init: function () { this.addOnAudioProcess(); }, getPlayedPercents: function () { var duration = this.getDuration(); return (this.getCurrentTime() / duration) || 0; }, getCurrentTime: function () { return this.startPosition + this.getPlayedTime(); } }; WaveSurfer.WebAudio.state.paused = { init: function () { this.removeOnAudioProcess(); }, getPlayedPercents: function () { var duration = this.getDuration(); return (this.getCurrentTime() / duration) || 0; }, getCurrentTime: function () { return this.startPosition; } }; WaveSurfer.WebAudio.state.finished = { init: function () { this.removeOnAudioProcess(); this.fireEvent('finish'); }, getPlayedPercents: function () { return 1; }, getCurrentTime: function () { return this.getDuration(); } }; WaveSurfer.util.extend(WaveSurfer.WebAudio, WaveSurfer.Observer); 'use strict'; WaveSurfer.MediaElement = Object.create(WaveSurfer.WebAudio); WaveSurfer.util.extend(WaveSurfer.MediaElement, { init: function (params) { this.params = params; // Dummy media to catch errors this.media = { currentTime: 0, duration: 0, paused: true, playbackRate: 1, play: function () {}, pause: function () {} }; this.mediaType = params.mediaType.toLowerCase(); this.elementPosition = params.elementPosition; this.setPlaybackRate(this.params.audioRate); this.createTimer(); }, /** * Create a timer to provide a more precise `audioprocess' event. */ createTimer: function () { var my = this; var playing = false; var onAudioProcess = function () { if (my.isPaused()) { return; } my.fireEvent('audioprocess', my.getCurrentTime()); // Call again in the next frame var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame; requestAnimationFrame(onAudioProcess); }; this.on('play', onAudioProcess); }, /** * Create media element with url as its source, * and append to container element. * @param {String} url path to media file * @param {HTMLElement} container HTML element * @param {Array} peaks array of peak data * @param {String} preload HTML 5 preload attribute value */ load: function (url, container, peaks, preload) { var my = this; var media = document.createElement(this.mediaType); media.controls = this.params.mediaControls; media.autoplay = this.params.autoplay || false; media.preload = preload == null ? 'auto' : preload; media.src = url; media.style.width = '100%'; var prevMedia = container.querySelector(this.mediaType); if (prevMedia) { container.removeChild(prevMedia); } container.appendChild(media); this._load(media, peaks); }, /** * Load existing media element. * @param {MediaElement} elt HTML5 Audio or Video element * @param {Array} peaks array of peak data */ loadElt: function (elt, peaks) { var my = this; var media = elt; media.controls = this.params.mediaControls; media.autoplay = this.params.autoplay || false; this._load(media, peaks); }, /** * Private method called by both load (from url) * and loadElt (existing media element). * @param {MediaElement} media HTML5 Audio or Video element * @param {Array} peaks array of peak data * @private */ _load: function (media, peaks) { var my = this; // load must be called manually on iOS, otherwise peaks won't draw // until a user interaction triggers load --> 'ready' event if (typeof media.load == 'function') { media.load(); } media.addEventListener('error', function () { my.fireEvent('error', 'Error loading media element'); }); media.addEventListener('canplay', function () { my.fireEvent('canplay'); }); media.addEventListener('ended', function () { my.fireEvent('finish'); }); this.media = media; this.peaks = peaks; this.onPlayEnd = null; this.buffer = null; this.setPlaybackRate(this.playbackRate); }, isPaused: function () { return !this.media || this.media.paused; }, getDuration: function () { var duration = (this.buffer || this.media).duration; if (duration >= Infinity) { // streaming audio duration = this.media.seekable.end(0); } return duration; }, getCurrentTime: function () { return this.media && this.media.currentTime; }, getPlayedPercents: function () { return (this.getCurrentTime() / this.getDuration()) || 0; }, getPlaybackRate: function () { return this.playbackRate || this.media.playbackRate; }, /** * Set the audio source playback rate. */ setPlaybackRate: function (value) { this.playbackRate = value || 1; this.media.playbackRate = this.playbackRate; }, seekTo: function (start) { if (start != null) { this.media.currentTime = start; } this.clearPlayEnd(); }, /** * Plays the loaded audio region. * * @param {Number} start Start offset in seconds, * relative to the beginning of a clip. * @param {Number} end End offset in seconds, * relative to the beginning of a clip. */ play: function (start, end) { this.seekTo(start); this.media.play(); end && this.setPlayEnd(end); this.fireEvent('play'); }, /** * Pauses the loaded audio. */ pause: function () { this.media && this.media.pause(); this.clearPlayEnd(); this.fireEvent('pause'); }, setPlayEnd: function (end) { var my = this; this.onPlayEnd = function (time) { if (time >= end) { my.pause(); my.seekTo(end); } }; this.on('audioprocess', this.onPlayEnd); }, clearPlayEnd: function () { if (this.onPlayEnd) { this.un('audioprocess', this.onPlayEnd); this.onPlayEnd = null; } }, getPeaks: function (length, start, end) { if (this.buffer) { return WaveSurfer.WebAudio.getPeaks.call(this, length, start, end); } return this.peaks || []; }, getVolume: function () { return this.media.volume; }, setVolume: function (val) { this.media.volume = val; }, destroy: function () { this.pause(); this.unAll(); this.media && this.media.parentNode && this.media.parentNode.removeChild(this.media); this.media = null; } }); //For backwards compatibility WaveSurfer.AudioElement = WaveSurfer.MediaElement; 'use strict'; WaveSurfer.Drawer = { init: function (container, params) { this.container = container; this.params = params; this.width = 0; this.height = params.height * this.params.pixelRatio; this.lastPos = 0; this.initDrawer(params); this.createWrapper(); this.createElements(); }, createWrapper: function () { this.wrapper = this.container.appendChild( document.createElement('wave') ); this.style(this.wrapper, { display: 'block', position: 'relative', userSelect: 'none', webkitUserSelect: 'none', height: this.params.height + 'px' }); if (this.params.fillParent || this.params.scrollParent) { this.style(this.wrapper, { width: '100%', overflowX: this.params.hideScrollbar ? 'hidden' : 'auto', overflowY: 'hidden' }); } this.setupWrapperEvents(); }, handleEvent: function (e, noPrevent) { !noPrevent && e.preventDefault(); var clientX = e.targetTouches ? e.targetTouches[0].clientX : e.clientX; var bbox = this.wrapper.getBoundingClientRect(); var nominalWidth = this.width; var parentWidth = this.getWidth(); var progress; if (!this.params.fillParent && nominalWidth < parentWidth) { progress = ((clientX - bbox.left) * this.params.pixelRatio / nominalWidth) || 0; if (progress > 1) { progress = 1; } } else { progress = ((clientX - bbox.left + this.wrapper.scrollLeft) / this.wrapper.scrollWidth) || 0; } return progress; }, setupWrapperEvents: function () { var my = this; this.wrapper.addEventListener('click', function (e) { var scrollbarHeight = my.wrapper.offsetHeight - my.wrapper.clientHeight; if (scrollbarHeight != 0) { // scrollbar is visible. Check if click was on it var bbox = my.wrapper.getBoundingClientRect(); if (e.clientY >= bbox.bottom - scrollbarHeight) { // ignore mousedown as it was on the scrollbar return; } } if (my.params.interact) { my.fireEvent('click', e, my.handleEvent(e)); } }); this.wrapper.addEventListener('scroll', function (e) { my.fireEvent('scroll', e); }); }, drawPeaks: function (peaks, length, start, end) { this.setWidth(length); this.params.barWidth ? this.drawBars(peaks, 0, start, end) : this.drawWave(peaks, 0, start, end); }, style: function (el, styles) { Object.keys(styles).forEach(function (prop) { if (el.style[prop] !== styles[prop]) { el.style[prop] = styles[prop]; } }); return el; }, resetScroll: function () { if (this.wrapper !== null) { this.wrapper.scrollLeft = 0; } }, recenter: function (percent) { var position = this.wrapper.scrollWidth * percent; this.recenterOnPosition(position, true); }, recenterOnPosition: function (position, immediate) { var scrollLeft = this.wrapper.scrollLeft; var half = ~~(this.wrapper.clientWidth / 2); var target = position - half; var offset = target - scrollLeft; var maxScroll = this.wrapper.scrollWidth - this.wrapper.clientWidth; if (maxScroll == 0) { // no need to continue if scrollbar is not there return; } // if the cursor is currently visible... if (!immediate && -half <= offset && offset < half) { // we'll limit the "re-center" rate. var rate = 5; offset = Math.max(-rate, Math.min(rate, offset)); target = scrollLeft + offset; } // limit target to valid range (0 to maxScroll) target = Math.max(0, Math.min(maxScroll, target)); // no use attempting to scroll if we're not moving if (target != scrollLeft) { this.wrapper.scrollLeft = target; } }, getScrollX: function() { return Math.round(this.wrapper.scrollLeft * this.params.pixelRatio); }, getWidth: function () { return Math.round(this.container.clientWidth * this.params.pixelRatio); }, setWidth: function (width) { if (this.width == width) { return; } this.width = width; if (this.params.fillParent || this.params.scrollParent) { this.style(this.wrapper, { width: '' }); } else { this.style(this.wrapper, { width: ~~(this.width / this.params.pixelRatio) + 'px' }); } this.updateSize(); }, setHeight: function (height) { if (height == this.height) { return; } this.height = height; this.style(this.wrapper, { height: ~~(this.height / this.params.pixelRatio) + 'px' }); this.updateSize(); }, progress: function (progress) { var minPxDelta = 1 / this.params.pixelRatio; var pos = Math.round(progress * this.width) * minPxDelta; if (pos < this.lastPos || pos - this.lastPos >= minPxDelta) { this.lastPos = pos; if (this.params.scrollParent && this.params.autoCenter) { var newPos = ~~(this.wrapper.scrollWidth * progress); this.recenterOnPosition(newPos); } this.updateProgress(pos); } }, destroy: function () { this.unAll(); if (this.wrapper) { this.container.removeChild(this.wrapper); this.wrapper = null; } }, /* Renderer-specific methods */ initDrawer: function () {}, createElements: function () {}, updateSize: function () {}, drawWave: function (peaks, max) {}, clearWave: function () {}, updateProgress: function (position) {} }; WaveSurfer.util.extend(WaveSurfer.Drawer, WaveSurfer.Observer); 'use strict'; WaveSurfer.Drawer.Canvas = Object.create(WaveSurfer.Drawer); WaveSurfer.util.extend(WaveSurfer.Drawer.Canvas, { createElements: function () { var waveCanvas = this.wrapper.appendChild( this.style(document.createElement('canvas'), { position: 'absolute', zIndex: 1, left: 0, top: 0, bottom: 0 }) ); this.waveCc = waveCanvas.getContext('2d'); this.progressWave = this.wrapper.appendChild( this.style(document.createElement('wave'), { position: 'absolute', zIndex: 2, left: 0, top: 0, bottom: 0, overflow: 'hidden', width: '0', display: 'none', boxSizing: 'border-box', borderRightStyle: 'solid', borderRightWidth: this.params.cursorWidth + 'px', borderRightColor: this.params.cursorColor }) ); if (this.params.waveColor != this.params.progressColor) { var progressCanvas = this.progressWave.appendChild( document.createElement('canvas') ); this.progressCc = progressCanvas.getContext('2d'); } }, updateSize: function () { var width = Math.round(this.width / this.params.pixelRatio); this.waveCc.canvas.width = this.width; this.waveCc.canvas.height = this.height; this.style(this.waveCc.canvas, { width: width + 'px'}); this.style(this.progressWave, { display: 'block'}); if (this.progressCc) { this.progressCc.canvas.width = this.width; this.progressCc.canvas.height = this.height; this.style(this.progressCc.canvas, { width: width + 'px'}); } this.clearWave(); }, clearWave: function () { this.waveCc.clearRect(0, 0, this.width, this.height); if (this.progressCc) { this.progressCc.clearRect(0, 0, this.width, this.height); } }, drawBars: function (peaks, channelIndex, start, end) { var my = this; // Split channels if (peaks[0] instanceof Array) { var channels = peaks; if (this.params.splitChannels) { this.setHeight(channels.length * this.params.height * this.params.pixelRatio); channels.forEach(function(channelPeaks, i) { my.drawBars(channelPeaks, i, start, end); }); return; } else { peaks = channels[0]; } } // Bar wave draws the bottom only as a reflection of the top, // so we don't need negative values var hasMinVals = [].some.call(peaks, function (val) { return val < 0; }); // Skip every other value if there are negatives. var peakIndexScale = 1; if (hasMinVals) { peakIndexScale = 2; } // A half-pixel offset makes lines crisp var $ = 0.5 / this.params.pixelRatio; var width = this.width; var height = this.params.height * this.params.pixelRatio; var offsetY = height * channelIndex || 0; var halfH = height / 2; var length = peaks.length / peakIndexScale; var bar = this.params.barWidth * this.params.pixelRatio; var gap = Math.max(this.params.pixelRatio, ~~(bar / 2)); var step = bar + gap; var absmax = 1 / this.params.barHeight; if (this.params.normalize) { var max = WaveSurfer.util.max(peaks); var min = WaveSurfer.util.min(peaks); absmax = -min > max ? -min : max; } var scale = length / width; this.waveCc.fillStyle = this.params.waveColor; if (this.progressCc) { this.progressCc.fillStyle = this.params.progressColor; } [ this.waveCc, this.progressCc ].forEach(function (cc) { if (!cc) { return; } for (var i = (start / scale); i < (end / scale); i += step) { var peak = peaks[Math.floor(i * scale * peakIndexScale)] || 0; var h = Math.round(peak / absmax * halfH); cc.fillRect(i + $, halfH - h + offsetY, bar + $, h * 2); } }, this); }, drawWave: function (peaks, channelIndex, start, end) { var my = this; // Split channels if (peaks[0] instanceof Array) { var channels = peaks; if (this.params.splitChannels) { this.setHeight(channels.length * this.params.height * this.params.pixelRatio); channels.forEach(function(channelPeaks, i) { my.drawWave(channelPeaks, i, start, end); }); return; } else { peaks = channels[0]; } } // Support arrays without negative peaks var hasMinValues = [].some.call(peaks, function (val) { return val < 0; }); if (!hasMinValues) { var reflectedPeaks = []; for (var i = 0, len = peaks.length; i < len; i++) { reflectedPeaks[2 * i] = peaks[i]; reflectedPeaks[2 * i + 1] = -peaks[i]; } peaks = reflectedPeaks; } // A half-pixel offset makes lines crisp var $ = 0.5 / this.params.pixelRatio; var height = this.params.height * this.params.pixelRatio; var offsetY = height * channelIndex || 0; var halfH = height / 2; var length = ~~(peaks.length / 2); var scale = 1; if (this.params.fillParent && this.width != length) { scale = this.width / length; } var absmax = 1 / this.params.barHeight; if (this.params.normalize) { var max = WaveSurfer.util.max(peaks); var min = WaveSurfer.util.min(peaks); absmax = -min > max ? -min : max; } this.waveCc.fillStyle = this.params.waveColor; if (this.progressCc) { this.progressCc.fillStyle = this.params.progressColor; } [ this.waveCc, this.progressCc ].forEach(function (cc) { if (!cc) { return; } cc.beginPath(); cc.moveTo(start * scale + $, halfH + offsetY); for (var i = start; i < end; i++) { var h = Math.round(peaks[2 * i] / absmax * halfH); cc.lineTo(i * scale + $, halfH - h + offsetY); } // Draw the bottom edge going backwards, to make a single // closed hull to fill. for (var i = end - 1; i >= start; i--) { var h = Math.round(peaks[2 * i + 1] / absmax * halfH); cc.lineTo(i * scale + $, halfH - h + offsetY); } cc.closePath(); cc.fill(); // Always draw a median line cc.fillRect(0, halfH + offsetY - $, this.width, $); }, this); }, updateProgress: function (pos) { this.style(this.progressWave, { width: pos + 'px' }); }, getImage: function(type, quality) { return this.waveCc.canvas.toDataURL(type, quality); } }); 'use strict'; WaveSurfer.Drawer.MultiCanvas = Object.create(WaveSurfer.Drawer); WaveSurfer.util.extend(WaveSurfer.Drawer.MultiCanvas, { initDrawer: function (params) { this.maxCanvasWidth = params.maxCanvasWidth != null ? params.maxCanvasWidth : 4000; this.maxCanvasElementWidth = Math.round(this.maxCanvasWidth / this.params.pixelRatio); if (this.maxCanvasWidth <= 1) { throw 'maxCanvasWidth must be greater than 1.'; } else if (this.maxCanvasWidth % 2 == 1) { throw 'maxCanvasWidth must be an even number.'; } this.hasProgressCanvas = this.params.waveColor != this.params.progressColor; this.halfPixel = 0.5 / this.params.pixelRatio; this.canvases = []; }, createElements: function () { this.progressWave = this.wrapper.appendChild( this.style(document.createElement('wave'), { position: 'absolute', zIndex: 2, left: 0, top: 0, bottom: 0, overflow: 'hidden', width: '0', display: 'none', boxSizing: 'border-box', borderRightStyle: 'solid', borderRightWidth: this.params.cursorWidth + 'px', borderRightColor: this.params.cursorColor }) ); this.addCanvas(); }, updateSize: function () { var totalWidth = Math.round(this.width / this.params.pixelRatio), requiredCanvases = Math.ceil(totalWidth / this.maxCanvasElementWidth); while (this.canvases.length < requiredCanvases) { this.addCanvas(); } while (this.canvases.length > requiredCanvases) { this.removeCanvas(); } for (var i in this.canvases) { // Add some overlap to prevent vertical white stripes, keep the width even for simplicity. var canvasWidth = this.maxCanvasWidth + 2 * Math.ceil(this.params.pixelRatio / 2); if (i == this.canvases.length - 1) { canvasWidth = this.width - (this.maxCanvasWidth * (this.canvases.length - 1)); } this.updateDimensions(this.canvases[i], canvasWidth, this.height); this.clearWaveForEntry(this.canvases[i]); } }, addCanvas: function () { var entry = {}, leftOffset = this.maxCanvasElementWidth * this.canvases.length; entry.wave = this.wrapper.appendChild( this.style(document.createElement('canvas'), { position: 'absolute', zIndex: 1, left: leftOffset + 'px', top: 0, bottom: 0, height: '100%' }) ); entry.waveCtx = entry.wave.getContext('2d'); if (this.hasProgressCanvas) { entry.progress = this.progressWave.appendChild( this.style(document.createElement('canvas'), { position: 'absolute', left: leftOffset + 'px', top: 0, bottom: 0, height: '100%' }) ); entry.progressCtx = entry.progress.getContext('2d'); } this.canvases.push(entry); }, removeCanvas: function () { var lastEntry = this.canvases.pop(); lastEntry.wave.parentElement.removeChild(lastEntry.wave); if (this.hasProgressCanvas) { lastEntry.progress.parentElement.removeChild(lastEntry.progress); } }, updateDimensions: function (entry, width, height) { var elementWidth = Math.round(width / this.params.pixelRatio), totalWidth = Math.round(this.width / this.params.pixelRatio); // Where the canvas starts and ends in the waveform, represented as a decimal between 0 and 1. entry.start = (entry.waveCtx.canvas.offsetLeft / totalWidth) || 0; entry.end = entry.start + elementWidth / totalWidth; entry.waveCtx.canvas.width = width; entry.waveCtx.canvas.height = height; this.style(entry.waveCtx.canvas, { width: elementWidth + 'px'}); this.style(this.progressWave, { display: 'block'}); if (this.hasProgressCanvas) { entry.progressCtx.canvas.width = width; entry.progressCtx.canvas.height = height; this.style(entry.progressCtx.canvas, { width: elementWidth + 'px'}); } }, clearWave: function () { for (var i in this.canvases) { this.clearWaveForEntry(this.canvases[i]); } }, clearWaveForEntry: function (entry) { entry.waveCtx.clearRect(0, 0, entry.waveCtx.canvas.width, entry.waveCtx.canvas.height); if (this.hasProgressCanvas) { entry.progressCtx.clearRect(0, 0, entry.progressCtx.canvas.width, entry.progressCtx.canvas.height); } }, drawBars: function (peaks, channelIndex, start, end) { var my = this; // Split channels if (peaks[0] instanceof Array) { var channels = peaks; if (this.params.splitChannels) { this.setHeight(channels.length * this.params.height * this.params.pixelRatio); channels.forEach(function(channelPeaks, i) { my.drawBars(channelPeaks, i, start, end); }); return; } else { peaks = channels[0]; } } // Bar wave draws the bottom only as a reflection of the top, // so we don't need negative values var hasMinVals = [].some.call(peaks, function (val) { return val < 0; }); // Skip every other value if there are negatives. var peakIndexScale = 1; if (hasMinVals) { peakIndexScale = 2; } // A half-pixel offset makes lines crisp var width = this.width; var height = this.params.height * this.params.pixelRatio; var offsetY = height * channelIndex || 0; var halfH = height / 2; var length = peaks.length / peakIndexScale; var bar = this.params.barWidth * this.params.pixelRatio; var gap = Math.max(this.params.pixelRatio, ~~(bar / 2)); var step = bar + gap; var absmax = 1 / this.params.barHeight; if (this.params.normalize) { var max = WaveSurfer.util.max(peaks); var min = WaveSurfer.util.min(peaks); absmax = -min > max ? -min : max; } var scale = length / width; for (var i = (start / scale); i < (end / scale); i += step) { var peak = peaks[Math.floor(i * scale * peakIndexScale)] || 0; var h = Math.round(peak / absmax * halfH); this.fillRect(i + this.halfPixel, halfH - h + offsetY, bar + this.halfPixel, h * 2); } }, drawWave: function (peaks, channelIndex, start, end) { var my = this; // Split channels if (peaks[0] instanceof Array) { var channels = peaks; if (this.params.splitChannels) { this.setHeight(channels.length * this.params.height * this.params.pixelRatio); channels.forEach(function(channelPeaks, i) { my.drawWave(channelPeaks, i, start, end); }); return; } else { peaks = channels[0]; } } // Support arrays without negative peaks var hasMinValues = [].some.call(peaks, function (val) { return val < 0; }); if (!hasMinValues) { var reflectedPeaks = []; for (var i = 0, len = peaks.length; i < len; i++) { reflectedPeaks[2 * i] = peaks[i]; reflectedPeaks[2 * i + 1] = -peaks[i]; } peaks = reflectedPeaks; } // A half-pixel offset makes lines crisp var height = this.params.height * this.params.pixelRatio; var offsetY = height * channelIndex || 0; var halfH = height / 2; var absmax = 1 / this.params.barHeight; if (this.params.normalize) { var max = WaveSurfer.util.max(peaks); var min = WaveSurfer.util.min(peaks); absmax = -min > max ? -min : max; } this.drawLine(peaks, absmax, halfH, offsetY, start, end); // Always draw a median line this.fillRect(0, halfH + offsetY - this.halfPixel, this.width, this.halfPixel); }, drawLine: function (peaks, absmax, halfH, offsetY, start, end) { for (var index in this.canvases) { var entry = this.canvases[index]; this.setFillStyles(entry); this.drawLineToContext(entry, entry.waveCtx, peaks, absmax, halfH, offsetY, start, end); this.drawLineToContext(entry, entry.progressCtx, peaks, absmax, halfH, offsetY, start, end); } }, drawLineToContext: function (entry, ctx, peaks, absmax, halfH, offsetY, start, end) { if (!ctx) { return; } var length = peaks.length / 2; var scale = 1; if (this.params.fillParent && this.width != length) { scale = this.width / length; } var first = Math.round(length * entry.start), last = Math.round(length * entry.end); if (first > end || last < start) { return; } var canvasStart = Math.max(first, start); var canvasEnd = Math.min(last, end); ctx.beginPath(); ctx.moveTo((canvasStart - first) * scale + this.halfPixel, halfH + offsetY); for (var i = canvasStart; i < canvasEnd; i++) { var peak = peaks[2 * i] || 0; var h = Math.round(peak / absmax * halfH); ctx.lineTo((i - first) * scale + this.halfPixel, halfH - h + offsetY); } // Draw the bottom edge going backwards, to make a single // closed hull to fill. for (var i = canvasEnd - 1; i >= canvasStart; i--) { var peak = peaks[2 * i + 1] || 0; var h = Math.round(peak / absmax * halfH); ctx.lineTo((i - first) * scale + this.halfPixel, halfH - h + offsetY); } ctx.closePath(); ctx.fill(); }, fillRect: function (x, y, width, height) { var startCanvas = Math.floor(x / this.maxCanvasWidth); var endCanvas = Math.min(Math.ceil((x + width) / this.maxCanvasWidth) + 1, this.canvases.length); for (var i = startCanvas; i < endCanvas; i++) { var entry = this.canvases[i], leftOffset = i * this.maxCanvasWidth; var intersection = { x1: Math.max(x, i * this.maxCanvasWidth), y1: y, x2: Math.min(x + width, i * this.maxCanvasWidth + entry.waveCtx.canvas.width), y2: y + height }; if (intersection.x1 < intersection.x2) { this.setFillStyles(entry); this.fillRectToContext(entry.waveCtx, intersection.x1 - leftOffset, intersection.y1, intersection.x2 - intersection.x1, intersection.y2 - intersection.y1); this.fillRectToContext(entry.progressCtx, intersection.x1 - leftOffset, intersection.y1, intersection.x2 - intersection.x1, intersection.y2 - intersection.y1); } } }, fillRectToContext: function (ctx, x, y, width, height) { if (!ctx) { return; } ctx.fillRect(x, y, width, height); }, setFillStyles: function (entry) { entry.waveCtx.fillStyle = this.params.waveColor; if (this.hasProgressCanvas) { entry.progressCtx.fillStyle = this.params.progressColor; } }, updateProgress: function (pos) { this.style(this.progressWave, { width: pos + 'px' }); }, /** * Combine all available canvasses together. * * @param {String} type - an optional value of a format type. Default is image/png. * @param {Number} quality - an optional value between 0 and 1. Default is 0.92. * */ getImage: function(type, quality) { var availableCanvas = []; this.canvases.forEach(function (entry) { availableCanvas.push(entry.wave.toDataURL(type, quality)); }); return availableCanvas.length > 1 ? availableCanvas : availableCanvas[0]; } }); 'use strict'; WaveSurfer.Drawer.SplitWavePointPlot = Object.create(WaveSurfer.Drawer.Canvas); WaveSurfer.util.extend(WaveSurfer.Drawer.SplitWavePointPlot, { defaultPlotParams: { plotNormalizeTo: 'whole', plotTimeStart: 0, plotMin: 0, plotMax: 1, plotColor : '#f63', plotProgressColor : '#F00', plotPointHeight: 2, plotPointWidth: 2, plotSeparator: true, plotSeparatorColor: 'black', plotRangeDisplay: false, plotRangeUnits: '', plotRangePrecision: 4, plotRangeIgnoreOutliers: false, plotRangeFontSize: 12, plotRangeFontType: 'Ariel', waveDrawMedianLine: true, plotFileDelimiter: '\t' }, //object variables that get manipulated by various object functions plotTimeStart: 0, //the start time of our wave according to plot data plotTimeEnd: -1, //the end of our wave according to plot data plotArrayLoaded: false, plotArray: [], //array of plot data objects containing time and plot value plotPoints: [], //calculated average plot points corresponding to value of our wave plotMin: 0, plotMax: 1, /** * Initializes the plot array. If params.plotFileUrl is provided an ajax call will be * executed and drawing of the wave is delayed until plot info is retrieved * @param params */ initDrawer: function (params) { var my = this; //set defaults if not passed in for(var paramName in this.defaultPlotParams) { if(this.params[paramName] === undefined) { this.params[paramName] = this.defaultPlotParams[paramName]; } } //set the plotTimeStart this.plotTimeStart = this.params.plotTimeStart; //check to see if plotTimeEnd if(this.params.plotTimeEnd !== undefined) { this.plotTimeEnd = this.params.plotTimeEnd; } //set the plot array if (Array.isArray(params.plotArray)) { this.plotArray = params.plotArray; this.plotArrayLoaded = true; } //Need to load the plot array from ajax with our callback else { var onPlotArrayLoaded = function (plotArray) { my.plotArray = plotArray; my.plotArrayLoaded = true; my.fireEvent('plot_array_loaded'); }; this.loadPlotArrayFromFile(params.plotFileUrl, onPlotArrayLoaded, this.params.plotFileDelimiter); } }, /** * Draw the peaks - this overrides the drawer.js function and does the following additional steps * - ensures that the plotArray has already been loaded, if not it loads via ajax * - moves the wave form to where channel 1 would normally be * @param peaks * @param length * @param start * @param end */ drawPeaks: function (peaks, length, start, end) { //make sure that the plot array is already loaded if (this.plotArrayLoaded == true) { this.setWidth(length); //fake that we are splitting channels this.splitChannels = true; this.params.height = this.params.height/2; if (peaks[0] instanceof Array) { peaks = peaks[0]; } this.params.barWidth ? this.drawBars(peaks, 1, start, end) : this.drawWave(peaks, 1, start, end); //set the height back to the original this.params.height = this.params.height*2; this.calculatePlots(); this.drawPlots(); } //otherwise wait for the plot array to be loaded and then draw again else { var my = this; my.on('plot-array-loaded', function () { my.drawPeaks(peaks, length, start, end); }); } }, /** * Loop through the calculated plot values and actually draw them */ drawPlots: function() { var height = this.params.height * this.params.pixelRatio / 2; var $ = 0.5 / this.params.pixelRatio; this.waveCc.fillStyle = this.params.plotColor; if(this.progressCc) { this.progressCc.fillStyle = this.params.plotProgressColor; } for(var i in this.plotPoints) { var x = parseInt(i); var y = height - this.params.plotPointHeight - (this.plotPoints[i] * (height - this.params.plotPointHeight)); var pointHeight = this.params.plotPointHeight; this.waveCc.fillRect(x, y, this.params.plotPointWidth, pointHeight); if(this.progressCc) { this.progressCc.fillRect(x, y, this.params.plotPointWidth, pointHeight); } } //draw line to separate the two waves if(this.params.plotSeparator) { this.waveCc.fillStyle = this.params.plotSeparatorColor; this.waveCc.fillRect(0, height, this.width, $); } if(this.params.plotRangeDisplay) { this.displayPlotRange(); } }, /** * Display the range for the plot graph */ displayPlotRange: function() { var fontSize = this.params.plotRangeFontSize * this.params.pixelRatio; var maxRange = this.plotMax.toPrecision(this.params.plotRangePrecision) + ' ' + this.params.plotRangeUnits; var minRange = this.plotMin.toPrecision(this.params.plotRangePrecision) + ' ' + this.params.plotRangeUnits; this.waveCc.font = fontSize.toString() + 'px ' + this.params.plotRangeFontType; this.waveCc.fillText(maxRange, 3, fontSize); this.waveCc.fillText(minRange, 3, this.height/2); }, /** * This function loops through the plotArray and converts it to the plot points * to be drawn on the canvas keyed by their position */ calculatePlots: function() { //reset plots array this.plotPoints = {}; //make sure we have our plotTimeEnd this.calculatePlotTimeEnd(); var pointsForAverage = []; var previousWaveIndex = -1; var maxPlot = 0; var minPlot = 99999999999999; var maxSegmentPlot = 0; var minSegmentPlot = 99999999999999; var duration = this.plotTimeEnd - this.plotTimeStart; //loop through our plotArray and map values to wave indexes and take the average values for each wave index for(var i = 0; i < this.plotArray.length; i++) { var dataPoint = this.plotArray[i]; if(dataPoint.value > maxPlot) {maxPlot = dataPoint.value;} if(dataPoint.value < minPlot) {minPlot = dataPoint.value;} //make sure we are in the specified range if(dataPoint.time >= this.plotTimeStart && dataPoint.time <= this.plotTimeEnd) { //get the wave index corresponding to the data point var waveIndex = Math.round(this.width * (dataPoint.time - this.plotTimeStart) / duration); pointsForAverage.push(dataPoint.value); //if we have moved on to a new position in our wave record average and reset previousWaveIndex if(waveIndex !== previousWaveIndex) { if(pointsForAverage.length > 0) { //get the average plot for this point var avgPlot = this.avg(pointsForAverage); //check for min max if(avgPlot > maxSegmentPlot) {maxSegmentPlot = avgPlot;} if(avgPlot < minSegmentPlot) {minSegmentPlot = avgPlot;} //add plot to the position this.plotPoints[previousWaveIndex] = avgPlot; pointsForAverage = []; } } previousWaveIndex = waveIndex; } } //normalize the plots points if(this.params.plotNormalizeTo == 'whole') { this.plotMin = minPlot; this.plotMax = maxPlot; } else if(this.params.plotNormalizeTo == 'values') { this.plotMin = this.params.plotMin; this.plotMax = this.params.plotMax; } else { this.plotMin = minSegmentPlot; this.plotMax = maxSegmentPlot; } this.normalizeValues(); }, /** * Function to take all of the plots in this.plots and normalize them from 0 to one * depending on this.plotMin and this.plotMax values */ normalizeValues: function() { var normalizedValues = {}; //check to make sure we should be normalizing if(this.params.plotNormalizeTo === 'none') {return;} for(var i in this.plotPoints) { //get the normalized value between 0 and 1 var normalizedValue = (this.plotPoints[i] - this.plotMin) / (this.plotMax - this.plotMin); //check if the value is above our specified range max if(normalizedValue > 1) { if(!this.params.plotRangeIgnoreOutliers) { normalizedValues[i] = 1; } } //check if hte value is below our specified rant else if(normalizedValue < 0) { if(!this.params.plotRangeIgnoreOutliers) { normalizedValues[i] = 0; } } //in our range add the normalized value else { normalizedValues[i] = normalizedValue; } } this.plotPoints = normalizedValues; }, /** * */ /** * Function to load the plot array from a external file * * The text file should contain a series of lines. * Each line should contain [audio time] [delimiter character] [plot value] * e.g. "1.2355 [tab] 124.2321" * * @param plotFileUrl url of the file containing time and value information * @param onSuccess function to run on success * @param delimiter the delimiter that separates the time and values on each line */ loadPlotArrayFromFile: function(plotFileUrl, onSuccess, delimiter) { //default delimiter to tab character if (delimiter === undefined) {delimiter = '\t';} var plotArray = []; var options = { url: plotFileUrl, responseType: 'text' }; var fileAjax = WaveSurfer.util.ajax(options); fileAjax.on('load', function (data) { if (data.currentTarget.status == 200) { //split the file by line endings var plotLines = data.currentTarget.responseText.split('\n'); //loop through each line and find the time and plot values (delimited by tab) for (var i = 0; i < plotLines.length; i++) { var plotParts = plotLines[i].split(delimiter); if(plotParts.length == 2) { plotArray.push({time: parseFloat(plotParts[0]), value: parseFloat(plotParts[1])}); } } //run success function onSuccess(plotArray); } }); }, /*** * Calculate the end time of the plot */ calculatePlotTimeEnd: function() { if(this.params.plotTimeEnd !== undefined) { this.plotTimeEnd = this.params.plotTimeEnd; } else { this.plotTimeEnd = this.plotArray[this.plotArray.length -1].time; } }, /** * Quick convenience function to average numbers in an array * @param array of values * @returns {number} */ avg: function(values) { var sum = values.reduce(function(a, b) {return a+b;}); return sum/values.length; } }); WaveSurfer.util.extend(WaveSurfer.Drawer.SplitWavePointPlot, WaveSurfer.Observer); 'use strict'; WaveSurfer.PeakCache = { init: function() { this.clearPeakCache(); }, clearPeakCache: function() { // Flat array with entries that are always in pairs to mark the // beginning and end of each subrange. This is a convenience so we can // iterate over the pairs for easy set difference operations. this.peakCacheRanges = []; // Length of the entire cachable region, used for resetting the cache // when this changes (zoom events, for instance). this.peakCacheLength = -1; }, addRangeToPeakCache: function(length, start, end) { if (length != this.peakCacheLength) { this.clearPeakCache(); this.peakCacheLength = length; } // Return ranges that weren't in the cache before the call. var uncachedRanges = []; var i = 0; // Skip ranges before the current start. while (i < this.peakCacheRanges.length && this.peakCacheRanges[i] < start) { i++; } // If |i| is even, |start| falls after an existing range. Otherwise, // |start| falls between an existing range, and the uncached region // starts when we encounter the next node in |peakCacheRanges| or // |end|, whichever comes first. if (i % 2 == 0) { uncachedRanges.push(start); } while (i < this.peakCacheRanges.length && this.peakCacheRanges[i] <= end) { uncachedRanges.push(this.peakCacheRanges[i]); i++; } // If |i| is even, |end| is after all existing ranges. if (i % 2 == 0) { uncachedRanges.push(end); } // Filter out the 0-length ranges. uncachedRanges = uncachedRanges.filter(function(item, pos, arr) { if (pos == 0) { return item != arr[pos + 1]; } else if (pos == arr.length - 1) { return item != arr[pos - 1]; } else { return item != arr[pos - 1] && item != arr[pos + 1]; } }); // Merge the two ranges together, uncachedRanges will either contain // wholly new points, or duplicates of points in peakCacheRanges. If // duplicates are detected, remove both and extend the range. this.peakCacheRanges = this.peakCacheRanges.concat(uncachedRanges); this.peakCacheRanges = this.peakCacheRanges.sort(function(a, b) { return a - b; }).filter(function(item, pos, arr) { if (pos == 0) { return item != arr[pos + 1]; } else if (pos == arr.length - 1) { return item != arr[pos - 1]; } else { return item != arr[pos - 1] && item != arr[pos + 1]; } }); // Push the uncached ranges into an array of arrays for ease of // iteration in the functions that call this. var uncachedRangePairs = []; for (i = 0; i < uncachedRanges.length; i += 2) { uncachedRangePairs.push([uncachedRanges[i], uncachedRanges[i+1]]); } return uncachedRangePairs; }, // For testing getCacheRanges: function() { var peakCacheRangePairs = []; for (var i = 0; i < this.peakCacheRanges.length; i += 2) { peakCacheRangePairs.push([this.peakCacheRanges[i], this.peakCacheRanges[i+1]]); } return peakCacheRangePairs; } }; 'use strict'; /* Init from HTML */ (function () { var init = function () { var containers = document.querySelectorAll('wavesurfer'); Array.prototype.forEach.call(containers, function (el) { var params = WaveSurfer.util.extend({ container: el, backend: 'MediaElement', mediaControls: true }, el.dataset); el.style.display = 'block'; var wavesurfer = WaveSurfer.create(params); if (el.dataset.peaks) { var peaks = JSON.parse(el.dataset.peaks); } wavesurfer.load(el.dataset.url, peaks); }); }; if (document.readyState === 'complete') { init(); } else { window.addEventListener('load', init); } }()); return WaveSurfer; }));
NaturalHistoryMuseum/scratchpads2
sites/all/libraries/wavesurfer/dist/wavesurfer.js
JavaScript
gpl-2.0
86,080
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2001 Dirk Mueller (mueller@kde.org) * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved. * (C) 2006 Alexey Proskuryakov (ap@nypop.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "FormAssociatedElement.h" #include "EditorClient.h" #include "FormController.h" #include "Frame.h" #include "HTMLFormControlElement.h" #include "HTMLFormElement.h" #include "HTMLNames.h" #include "HTMLObjectElement.h" #include "IdTargetObserver.h" #include "ValidityState.h" namespace WebCore { using namespace HTMLNames; class FormAttributeTargetObserver : IdTargetObserver { WTF_MAKE_FAST_ALLOCATED; public: static PassOwnPtr<FormAttributeTargetObserver> create(const AtomicString& id, FormAssociatedElement*); virtual void idTargetChanged() OVERRIDE; private: FormAttributeTargetObserver(const AtomicString& id, FormAssociatedElement*); FormAssociatedElement* m_element; }; FormAssociatedElement::FormAssociatedElement() : m_form(0) { } FormAssociatedElement::~FormAssociatedElement() { setForm(0); } ValidityState* FormAssociatedElement::validity() { if (!m_validityState) m_validityState = ValidityState::create(this); return m_validityState.get(); } void FormAssociatedElement::didMoveToNewDocument(Document* oldDocument) { HTMLElement* element = toHTMLElement(this); if (oldDocument && element->fastHasAttribute(formAttr)) resetFormAttributeTargetObserver(); } void FormAssociatedElement::insertedInto(ContainerNode* insertionPoint) { resetFormOwner(); if (!insertionPoint->inDocument()) return; HTMLElement* element = toHTMLElement(this); if (element->fastHasAttribute(formAttr)) resetFormAttributeTargetObserver(); } void FormAssociatedElement::removedFrom(ContainerNode* insertionPoint) { HTMLElement* element = toHTMLElement(this); if (insertionPoint->inDocument() && element->fastHasAttribute(formAttr)) m_formAttributeTargetObserver = nullptr; // If the form and element are both in the same tree, preserve the connection to the form. // Otherwise, null out our form and remove ourselves from the form's list of elements. if (m_form && element->highestAncestor() != m_form->highestAncestor()) setForm(0); } HTMLFormElement* FormAssociatedElement::findAssociatedForm(const HTMLElement* element, HTMLFormElement* currentAssociatedForm) { const AtomicString& formId(element->fastGetAttribute(formAttr)); if (!formId.isNull() && element->inDocument()) { // The HTML5 spec says that the element should be associated with // the first element in the document to have an ID that equal to // the value of form attribute, so we put the result of // treeScope()->getElementById() over the given element. HTMLFormElement* newForm = 0; Element* newFormCandidate = element->treeScope()->getElementById(formId); if (newFormCandidate && newFormCandidate->hasTagName(formTag)) newForm = static_cast<HTMLFormElement*>(newFormCandidate); return newForm; } if (!currentAssociatedForm) return element->findFormAncestor(); return currentAssociatedForm; } void FormAssociatedElement::formRemovedFromTree(const Node* formRoot) { ASSERT(m_form); if (toHTMLElement(this)->highestAncestor() != formRoot) setForm(0); } void FormAssociatedElement::setForm(HTMLFormElement* newForm) { if (m_form == newForm) return; willChangeForm(); if (m_form) m_form->removeFormElement(this); m_form = newForm; if (m_form) m_form->registerFormElement(this); didChangeForm(); } void FormAssociatedElement::willChangeForm() { } void FormAssociatedElement::didChangeForm() { } void FormAssociatedElement::formWillBeDestroyed() { ASSERT(m_form); if (!m_form) return; willChangeForm(); m_form = 0; didChangeForm(); } void FormAssociatedElement::resetFormOwner() { HTMLFormElement* originalForm = m_form; setForm(findAssociatedForm(toHTMLElement(this), m_form)); HTMLElement* element = toHTMLElement(this); if (m_form && m_form != originalForm && m_form->inDocument()) element->document()->didAssociateFormControl(element); } void FormAssociatedElement::formAttributeChanged() { HTMLElement* element = toHTMLElement(this); if (!element->fastHasAttribute(formAttr)) { // The form attribute removed. We need to reset form owner here. HTMLFormElement* originalForm = m_form; setForm(element->findFormAncestor()); HTMLElement* element = toHTMLElement(this); if (m_form && m_form != originalForm && m_form->inDocument()) element->document()->didAssociateFormControl(element); m_formAttributeTargetObserver = nullptr; } else { resetFormOwner(); if (element->inDocument()) resetFormAttributeTargetObserver(); } } bool FormAssociatedElement::customError() const { const HTMLElement* element = toHTMLElement(this); return element->willValidate() && !m_customValidationMessage.isEmpty(); } bool FormAssociatedElement::hasBadInput() const { return false; } bool FormAssociatedElement::patternMismatch() const { return false; } bool FormAssociatedElement::rangeOverflow() const { return false; } bool FormAssociatedElement::rangeUnderflow() const { return false; } bool FormAssociatedElement::stepMismatch() const { return false; } bool FormAssociatedElement::tooLong() const { return false; } bool FormAssociatedElement::typeMismatch() const { return false; } bool FormAssociatedElement::valid() const { bool someError = typeMismatch() || stepMismatch() || rangeUnderflow() || rangeOverflow() || tooLong() || patternMismatch() || valueMissing() || hasBadInput() || customError(); return !someError; } bool FormAssociatedElement::valueMissing() const { return false; } String FormAssociatedElement::customValidationMessage() const { return m_customValidationMessage; } String FormAssociatedElement::validationMessage() const { return customError() ? m_customValidationMessage : String(); } void FormAssociatedElement::setCustomValidity(const String& error) { m_customValidationMessage = error; } void FormAssociatedElement::resetFormAttributeTargetObserver() { m_formAttributeTargetObserver = FormAttributeTargetObserver::create(toHTMLElement(this)->fastGetAttribute(formAttr), this); } void FormAssociatedElement::formAttributeTargetChanged() { resetFormOwner(); } const AtomicString& FormAssociatedElement::name() const { const AtomicString& name = toHTMLElement(this)->getNameAttribute(); return name.isNull() ? emptyAtom : name; } bool FormAssociatedElement::isFormControlElementWithState() const { return false; } const HTMLElement* toHTMLElement(const FormAssociatedElement* associatedElement) { if (associatedElement->isFormControlElement()) return static_cast<const HTMLFormControlElement*>(associatedElement); // Assumes the element is an HTMLObjectElement const HTMLElement* element = static_cast<const HTMLObjectElement*>(associatedElement); ASSERT(element->hasTagName(objectTag)); return element; } HTMLElement* toHTMLElement(FormAssociatedElement* associatedElement) { return const_cast<HTMLElement*>(toHTMLElement(static_cast<const FormAssociatedElement*>(associatedElement))); } PassOwnPtr<FormAttributeTargetObserver> FormAttributeTargetObserver::create(const AtomicString& id, FormAssociatedElement* element) { return adoptPtr(new FormAttributeTargetObserver(id, element)); } FormAttributeTargetObserver::FormAttributeTargetObserver(const AtomicString& id, FormAssociatedElement* element) : IdTargetObserver(toHTMLElement(element)->treeScope()->idTargetObserverRegistry(), id) , m_element(element) { } void FormAttributeTargetObserver::idTargetChanged() { m_element->formAttributeTargetChanged(); } } // namespace Webcore
166MMX/openjdk.java.net-openjfx-8u40-rt
modules/web/src/main/native/Source/WebCore/html/FormAssociatedElement.cpp
C++
gpl-2.0
8,934
package de.konqi.fitapi.common.importer; import java.io.IOException; import java.io.InputStream; /** * Created by konqi on 08.05.2016. */ public interface Importer { void importFromStream(String userEmail, InputStream is) throws IOException; }
konqi/fit-precinct
src/main/java/de/konqi/fitapi/common/importer/Importer.java
Java
gpl-2.0
252
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2016 Zomboided # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # This module is a bunch of functions that are called from the settings # menu to manage various files groups. import xbmcaddon import xbmcgui import xbmcvfs import datetime import os from libs.vpnproviders import removeGeneratedFiles, cleanPassFiles, providers, usesUserKeys, usesMultipleKeys, getUserKeys from libs.vpnproviders import getUserCerts, getVPNDisplay, getVPNLocation, removeDownloadedFiles, isAlternative, resetAlternative from libs.utility import debugTrace, errorTrace, infoTrace, newPrint, getID, getName from libs.vpnplatform import getLogPath, getUserDataPath, writeVPNLog, copySystemdFiles, addSystemd, removeSystemd, generateVPNs from libs.common import resetVPNConnections, isVPNConnected, disconnectVPN, suspendConfigUpdate, resumeConfigUpdate, dnsFix, getVPNRequestedProfile from libs.common import resetVPNProvider, setAPICommand from libs.ipinfo import resetIPServices try: from libs.generation import generateAll except: pass action = sys.argv[1] debugTrace("-- Entered managefiles.py with parameter " + action + " --") if not getID() == "": addon = xbmcaddon.Addon(getID()) addon_name = getName() # Reset the ovpn files if action == "ovpn": if getVPNRequestedProfile() == "": if xbmcgui.Dialog().yesno(addon_name, "Resetting the VPN provider will disconnect and reset all VPN connections, and then remove any files that have been created. Continue?"): suspendConfigUpdate() # Disconnect so that live files are not being modified resetVPNConnections(addon) infoTrace("managefiles.py", "Resetting the VPN provider") # Delete the generated files, and reset the locations so it can be selected again removeGeneratedFiles() # Delete any values that have previously been validated vpn_provider = getVPNLocation(addon.getSetting("vpn_provider")) if isAlternative(vpn_provider): resetAlternative(vpn_provider) # Reset the IP service error counts, etc resetIPServices() addon = xbmcaddon.Addon(getID()) resetVPNProvider(addon) addon = xbmcaddon.Addon(getID()) resumeConfigUpdate() xbmcgui.Dialog().ok(addon_name, "Reset the VPN provider. Validate a connection to start using a VPN again.") else: xbmcgui.Dialog().ok(addon_name, "Connection to VPN being attempted and has been aborted. Try again in a few seconds.") setAPICommand("Disconnect") # Generate the VPN provider files if action == "generate": # Only used during development to create location files generateAll() xbmcgui.Dialog().ok(addon_name, "Regenerated some or all of the VPN location files.") # Delete all of the downloaded VPN files if action == "downloads": debugTrace("Deleting all downloaded VPN files") removeDownloadedFiles() xbmcgui.Dialog().ok(addon_name, "Deleted all of the downloaded VPN files. They'll be downloaded again if required.") # Copy the log file elif action == "log": log_path = "" dest_path = "" try: log_path = getLogPath() start_dir = "" dest_folder = xbmcgui.Dialog().browse(0, "Select folder to copy log file into", "files", "", False, False, start_dir, False) dest_path = "kodi " + datetime.datetime.now().strftime("%y-%m-%d %H-%M-%S") + ".log" dest_path = dest_folder + dest_path.replace(" ", "_") # Write VPN log to log before copying writeVPNLog() debugTrace("Copying " + log_path + " to " + dest_path) addon = xbmcaddon.Addon(getID()) infoTrace("managefiles.py", "Copying log file to " + dest_path + ". Using version " + addon.getSetting("version_number")) xbmcvfs.copy(log_path, dest_path) if not xbmcvfs.exists(dest_path): raise IOError('Failed to copy log ' + log_path + " to " + dest_path) dialog_message = "Copied log file to: " + dest_path except: errorTrace("managefiles.py", "Failed to copy log from " + log_path + " to " + dest_path) if xbmcvfs.exists(log_path): dialog_message = "Error copying log, try copying it to a different location." else: dialog_messsage = "Could not find the kodi.log file." errorTrace("managefiles.py", dialog_message + " " + log_path + ", " + dest_path) xbmcgui.Dialog().ok("Log Copy", dialog_message) # Delete the user key and cert files elif action == "user": if addon.getSetting("1_vpn_validated") == "" or xbmcgui.Dialog().yesno(addon_name, "Deleting key and certificate files will disconnect and reset all VPN connections. Connections must be re-validated before use. Continue?"): # Disconnect so that live files are not being modified if isVPNConnected(): resetVPNConnections(addon) # Select the provider provider_list = [] for provider in providers: if usesUserKeys(provider): provider_list.append(getVPNDisplay(provider)) provider_list.sort() index = xbmcgui.Dialog().select("Select VPN provider", provider_list) provider_display = provider_list[index] provider = getVPNLocation(provider_display) # Get the key/cert pairs for that provider and offer up for deletion user_keys = getUserKeys(provider) user_certs = getUserCerts(provider) if len(user_keys) > 0 or len(user_certs) > 0: still_deleting = True while still_deleting: if len(user_keys) > 0 or len(user_certs) > 0: # Build a list of things to display. We should always have pairs, but if # something didn't copy or the user has messed with the dir this will cope all_user = [] single_pair = "user [I](Same key and certificate used for all connections)[/I]" for key in user_keys: list_item = os.path.basename(key) list_item = list_item.replace(".key", "") if list_item == "user": list_item = single_pair all_user.append(list_item) for cert in user_certs: list_item = os.path.basename(cert) list_item = list_item.replace(".crt", "") if list_item == "user": list_item = single_pair if not list_item in all_user: all_user.append(list_item) all_user.sort() # Offer a delete all option if there are multiple keys all_item = "[I]Delete all key and certificate files[/I]" if usesMultipleKeys(provider): all_user.append(all_item) # Add in a finished option finished_item = "[I]Finished[/I]" all_user.append(finished_item) # Get the pair to delete index = xbmcgui.Dialog().select("Select key and certificate to delete, or [I]Finished[/I]", all_user) if all_user[index] == finished_item: still_deleting = False else: if all_user[index] == single_pair : all_user[index] = "user" if all_user[index] == all_item: if xbmcgui.Dialog().yesno(addon_name, "Are you sure you want to delete all key and certificate files for " + provider_display + "?"): for item in all_user: if not item == all_item and not item == finished_item: path = getUserDataPath(provider + "/" + item) try: if xbmcvfs.exists(path + ".key"): xbmcvfs.delete(path + ".key") if xbmcvfs.exists(path + ".txt"): xbmcvfs.delete(path + ".txt") if xbmcvfs.exists(path + ".crt"): xbmcvfs.delete(path + ".crt") except: xbmcgui.Dialog().ok(addon_name, "Couldn't delete one of the key or certificate files: " + path) else: path = getUserDataPath(provider + "/" + all_user[index]) try: if xbmcvfs.exists(path+".key"): xbmcvfs.delete(path + ".key") if xbmcvfs.exists(path + ".txt"): xbmcvfs.delete(path + ".txt") if xbmcvfs.exists(path + ".crt"): xbmcvfs.delete(path + ".crt") except: xbmcgui.Dialog().ok(addon_name, "Couldn't delete one of the key or certificate files: " + path) # Fetch the directory list again user_keys = getUserKeys(provider) user_certs = getUserCerts(provider) if len(user_keys) == 0 and len(user_certs) == 0: xbmcgui.Dialog().ok(addon_name, "All key and certificate files for " + provider_display + " have been deleted.") else: still_deleting = False else: xbmcgui.Dialog().ok(addon_name, "No key and certificate files exist for " + provider_display + ".") # Fix the user defined files with DNS goodness if action == "dns": dnsFix() command = "Addon.OpenSettings(" + getID() + ")" xbmc.executebuiltin(command) else: errorTrace("managefiles.py", "VPN service is not ready") debugTrace("-- Exit managefiles.py --")
Zomboided/VPN-Manager
managefiles.py
Python
gpl-2.0
11,679
package nl.HAN.ASD.APP.dataStructures; import com.google.gag.annotation.disclaimer.WrittenWhile; import java.util.*; /** * Created by Pim van Gurp, 9/9/2015. */ @SuppressWarnings({"NullableProblems", "ConstantConditions"}) public class MyArrayList<T> implements List<T>, Iterable<T> { /** * Amount of elements in array. Can differ from array.length */ private int length; /** * Internal array for storing elements */ private T[] array; /** * Constructor for MyArrayList where attributes are initialized */ @SuppressWarnings("unchecked") public MyArrayList() { array = (T[]) new Object[3]; length = 0; } /** * Private iterator class * used to iterate over all all array elements. * Works with foreach loops. */ private class MyIterator implements Iterator<T> { private MyArrayList<T> array; private int current; MyIterator(MyArrayList<T> array) { this.array = array; this.current = 0; } @Override public boolean hasNext() { return current < array.length; } @Override public T next() { if(!hasNext()) throw new NoSuchElementException(); return array.get(current++); } } /** * Amount of elements in array. * Can differ from array.length * @return amount of elements in array as int */ @Override public int size() { return length; } /** * Check if array contains no elements * @return 1 array has no elements * 0 array has elements */ @Override public boolean isEmpty() { return length == 0; } /** * Get an element at a custom position * using an index * @param index position of element to get * @return element at index position */ @Override public T get(int index) { if(index > size() || index < 0) throw new IndexOutOfBoundsException(); //noinspection unchecked return array[index]; } /** * Set a position of the array with a new element * @param index position in array * @param element value to set * @return new element that got added */ @Override public T set(int index, T element) { if(index > size() || index < 0) throw new IndexOutOfBoundsException(); array[index] = element; return element; } /** * Add a new element to array * @param index position in array * @param element new value */ @Override public void add(int index, T element) { if(length == array.length) increaseArraySize(); array[index] = element; length++; } /** * Add a new element to the array at the end * of the array * @param element new value to add at the end * @return if element is added */ @Override public boolean add(T element) { if(length == array.length) increaseArraySize(); array[length++] = element; return true; } /** * Internal function to increase the array if * there are no more free positions */ @SuppressWarnings("unchecked") private void increaseArraySize() { T[] old = array; array = (T[]) new Object[old.length*2+1]; System.arraycopy(old, 0, array, 0, old.length); } /** * Return the attribute array * @return array containing all the arrayList values */ @Override public Object[] toArray() { return array; } /** * Used because the toArray below can't be changed * @param i random * @return array representation */ @SuppressWarnings("UnusedParameters") @WrittenWhile("Way too late") public T[] toArray(int i) { //noinspection unchecked return array; } /** * Return the attribute array casted to T * @param a I Really don't know * @return casted array */ @SuppressWarnings("unchecked") @Override public T[] toArray(Object[] a) { return array; } /** * Remove a custom element using index * @param index position to remove * @return removed element */ @Override public T remove(int index) { if(isEmpty()) return null; T removed = array[index]; //noinspection ManualArrayCopy for(int i = index+1; i < length; i++) { array[i-1] = array[i]; } length--; return removed; } /** * Used to reset the array and make it empty. */ @SuppressWarnings("unchecked") @Override public void clear() { array = (T[]) new Object[3]; length = 0; } /** * Print all array elements as a single String * @return string containing all array elements */ @Override public String toString() { String result = " "; for(int i = 0; i < array.length; i ++) { if( "".equals( get(i).toString() ) ) continue; result += " ["+ get(i) +"],"; } return result.substring(0, result.length()-1); } @SuppressWarnings("unchecked") @Override public Iterator iterator() { return new MyIterator(this); } /*----------------------------------------------*/ @Override public boolean remove(Object o) { return false; } @Override public boolean contains(Object o) { return false; } @Override public boolean addAll(Collection c) { return false; } @Override public boolean addAll(int index, Collection c) { return false; } @Override public int indexOf(Object o) { return 0; } @Override public int lastIndexOf(Object o) { return 0; } @SuppressWarnings("unchecked") @Override public ListIterator listIterator() { return null; } @SuppressWarnings("unchecked") @Override public ListIterator listIterator(int index) { return null; } @SuppressWarnings("unchecked") @Override public List subList(int fromIndex, int toIndex) { return null; } @Override public boolean retainAll(Collection c) { return false; } @Override public boolean removeAll(Collection c) { return false; } @Override public boolean containsAll(Collection c) { return false; } }
PimvanGurp/advanced-java
src/nl/HAN/ASD/APP/dataStructures/MyArrayList.java
Java
gpl-2.0
6,537
/** * Copyright 2007 Wei-ju Wu * * This file is part of TinyUML. * * TinyUML 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. * * TinyUML 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 TinyUML; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package test.mdauml.umldraw.shared; import org.jmock.Mock; import org.jmock.cglib.MockObjectTestCase; import com.nilledom.draw.CompositeNode; import com.nilledom.model.RelationEndType; import com.nilledom.model.RelationType; import com.nilledom.model.UmlRelation; import com.nilledom.umldraw.clazz.ClassElement; import com.nilledom.umldraw.shared.NoteConnection; import com.nilledom.umldraw.shared.NoteElement; /** * A test class for NoteElement. * @author Wei-ju Wu * @version 1.0 */ public class NoteElementTest extends MockObjectTestCase { /** * Tests the clone() method. */ public void testClone() { Mock mockParent1 = mock(CompositeNode.class); NoteElement note = NoteElement.getPrototype(); assertNull(note.getParent()); assertNull(note.getModelElement()); note.setOrigin(0, 0); note.setSize(100, 80); note.setLabelText("oldlabel"); note.setParent((CompositeNode) mockParent1.proxy()); NoteElement cloned = (NoteElement) note.clone(); assertTrue(note != cloned); assertEquals(note.getParent(), cloned.getParent()); assertEquals("oldlabel", cloned.getLabelText()); note.setLabelText("mylabel"); assertFalse(cloned.getLabelText() == note.getLabelText()); // now test the label mockParent1.expects(atLeastOnce()).method("getAbsoluteX1") .will(returnValue(0.0)); mockParent1.expects(atLeastOnce()).method("getAbsoluteY1") .will(returnValue(0.0)); assertNotNull(cloned.getLabelAt(20, 20)); assertNull(cloned.getLabelAt(-1.0, -2.0)); assertTrue(cloned.getLabelAt(20.0, 20.0) != note.getLabelAt(20.0, 20.0)); assertTrue(cloned.getLabelAt(20.0, 20.0).getSource() == cloned); assertTrue(cloned.getLabelAt(20.0, 20.0).getParent() == cloned); } /** * Tests the NoteConnection class. */ public void testNoteConnection() { // relation has no effect NoteConnection connection = NoteConnection.getPrototype(); connection.setRelation(new UmlRelation()); assertNull(connection.getModelElement()); } }
proyectos-fiuba-romera/nilledom
src/test/java/test/mdauml/umldraw/shared/NoteElementTest.java
Java
gpl-2.0
2,826
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Downloadable\Test\Unit\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable; /** * Class LinksTest * * @package Magento\Downloadable\Test\Unit\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable * * @deprecated * @see \Magento\Downloadable\Ui\DataProvider\Product\Form\Modifier\Links */ class LinksTest extends \PHPUnit\Framework\TestCase { /** * @var \Magento\Downloadable\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable\Links */ protected $block; /** * @var \Magento\Catalog\Model\Product */ protected $productModel; /** * @var \Magento\Downloadable\Model\Product\Type */ protected $downloadableProductModel; /** * @var \Magento\Downloadable\Model\Link */ protected $downloadableLinkModel; /** * @var \Magento\Framework\Escaper */ protected $escaper; /** * @var \Magento\Downloadable\Helper\File */ protected $fileHelper; /** * @var \Magento\Framework\Registry */ protected $coreRegistry; /** * @var \Magento\Backend\Model\Url */ protected $urlBuilder; protected function setUp() { $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->urlBuilder = $this->createPartialMock(\Magento\Backend\Model\Url::class, ['getUrl']); $attributeFactory = $this->createMock(\Magento\Eav\Model\Entity\AttributeFactory::class); $urlFactory = $this->createMock(\Magento\Backend\Model\UrlFactory::class); $this->fileHelper = $this->createPartialMock(\Magento\Downloadable\Helper\File::class, [ 'getFilePath', 'ensureFileInFilesystem', 'getFileSize' ]); $this->productModel = $this->createPartialMock(\Magento\Catalog\Model\Product::class, [ '__wakeup', 'getTypeId', 'getTypeInstance', 'getStoreId' ]); $this->downloadableProductModel = $this->createPartialMock(\Magento\Downloadable\Model\Product\Type::class, [ '__wakeup', 'getLinks' ]); $this->downloadableLinkModel = $this->createPartialMock(\Magento\Downloadable\Model\Link::class, [ '__wakeup', 'getId', 'getTitle', 'getPrice', 'getNumberOfDownloads', 'getLinkUrl', 'getLinkType', 'getSampleFile', 'getSampleType', 'getSortOrder', 'getLinkFile', 'getStoreTitle' ]); $this->coreRegistry = $this->createPartialMock(\Magento\Framework\Registry::class, [ '__wakeup', 'registry' ]); $this->escaper = $this->createPartialMock(\Magento\Framework\Escaper::class, ['escapeHtml']); $this->block = $objectManagerHelper->getObject( \Magento\Downloadable\Block\Adminhtml\Catalog\Product\Edit\Tab\Downloadable\Links::class, [ 'urlBuilder' => $this->urlBuilder, 'attributeFactory' => $attributeFactory, 'urlFactory' => $urlFactory, 'coreRegistry' => $this->coreRegistry, 'escaper' => $this->escaper, 'downloadableFile' => $this->fileHelper ] ); } /** * Test that getConfig method retrieve \Magento\Framework\DataObject object */ public function testGetConfig() { $this->assertInstanceOf(\Magento\Framework\DataObject::class, $this->block->getConfig()); } public function testGetLinkData() { $expectingFileData = [ 'file' => [ 'file' => 'file/link.gif', 'name' => '<a href="final_url">link.gif</a>', 'size' => '1.1', 'status' => 'old', ], 'sample_file' => [ 'file' => 'file/sample.gif', 'name' => '<a href="final_url">sample.gif</a>', 'size' => '1.1', 'status' => 'old', ], ]; $this->productModel->expects($this->any())->method('getTypeId') ->will($this->returnValue('downloadable')); $this->productModel->expects($this->any())->method('getTypeInstance') ->will($this->returnValue($this->downloadableProductModel)); $this->productModel->expects($this->any())->method('getStoreId') ->will($this->returnValue(0)); $this->downloadableProductModel->expects($this->any())->method('getLinks') ->will($this->returnValue([$this->downloadableLinkModel])); $this->coreRegistry->expects($this->any())->method('registry') ->will($this->returnValue($this->productModel)); $this->downloadableLinkModel->expects($this->any())->method('getId') ->will($this->returnValue(1)); $this->downloadableLinkModel->expects($this->any())->method('getTitle') ->will($this->returnValue('Link Title')); $this->downloadableLinkModel->expects($this->any())->method('getPrice') ->will($this->returnValue('10')); $this->downloadableLinkModel->expects($this->any())->method('getNumberOfDownloads') ->will($this->returnValue('6')); $this->downloadableLinkModel->expects($this->any())->method('getLinkUrl') ->will($this->returnValue(null)); $this->downloadableLinkModel->expects($this->any())->method('getLinkType') ->will($this->returnValue('file')); $this->downloadableLinkModel->expects($this->any())->method('getSampleFile') ->will($this->returnValue('file/sample.gif')); $this->downloadableLinkModel->expects($this->any())->method('getSampleType') ->will($this->returnValue('file')); $this->downloadableLinkModel->expects($this->any())->method('getSortOrder') ->will($this->returnValue(0)); $this->downloadableLinkModel->expects($this->any())->method('getLinkFile') ->will($this->returnValue('file/link.gif')); $this->downloadableLinkModel->expects($this->any())->method('getStoreTitle') ->will($this->returnValue('Store Title')); $this->escaper->expects($this->any())->method('escapeHtml') ->will($this->returnValue('Link Title')); $this->fileHelper->expects($this->any())->method('getFilePath') ->will($this->returnValue('/file/path/link.gif')); $this->fileHelper->expects($this->any())->method('ensureFileInFilesystem') ->will($this->returnValue(true)); $this->fileHelper->expects($this->any())->method('getFileSize') ->will($this->returnValue('1.1')); $this->urlBuilder->expects($this->any())->method('getUrl') ->will($this->returnValue('final_url')); $linkData = $this->block->getLinkData(); foreach ($linkData as $link) { $fileSave = $link->getFileSave(0); $sampleFileSave = $link->getSampleFileSave(0); $this->assertEquals($expectingFileData['file'], $fileSave); $this->assertEquals($expectingFileData['sample_file'], $sampleFileSave); } } }
kunj1988/Magento2
app/code/Magento/Downloadable/Test/Unit/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/LinksTest.php
PHP
gpl-2.0
7,483
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>MaSIS &mdash; <?php print $this->page_title ?></title> <link rel="stylesheet" href="styles/main.css" type="text/css" /> <link rel="stylesheet" href="styles/login.css" type="text/css" /> </head> <body> <div id="members" class="group"> <h1><?php print $this->page_title ?></h1> <?php print $this->page_content ?> </div> </body> </html>
figure002/masis
pages/login.php
PHP
gpl-2.0
618
using System.Collections; using System.Collections.Generic; using UnityEngine; using Uduino; public class MegaReadWrite : MonoBehaviour { // Be sure to select Arduino MEGA as board type // If your board is not detected, increase Discover delay to 1.5s or more. int pin14; int digitalPin42; void Start () { // Set pin mode when the board is detected. Getting the value when the board is connected UduinoManager.Instance.OnBoardConnected += BoardConnected; // You can setup Arduino type by code but I recommand to set the arduino board type with the inspector panel. //UduinoManager.Instance.SetBoardType("Arduino Mega"); //If you have one board connected //digitalPin42 = BoardsTypeList.Boards.GetPin("42"); // returns 42 // UduinoManager.Instance.pinMode(digitalPin42, PinMode.Output); // Debug.Log("The pin 42 pinout for Arduino Mega is " + pin14); } void BoardConnected(UduinoDevice device) { // if(UduinoManager.Instance.isConnected()) // implemented in the next version. Safe to remove { pin14 = UduinoManager.Instance.GetPinFromBoard("A14"); UduinoManager.Instance.pinMode(pin14, PinMode.Input); Debug.Log("The pin A14 pinout for Arduino Mega is " + pin14); digitalPin42 = UduinoManager.Instance.GetPinFromBoard("42"); UduinoManager.Instance.pinMode(digitalPin42, PinMode.Output); Debug.Log("The pin 42 pinout for Arduino Mega is " + digitalPin42); } } private void Update() { int value = UduinoManager.Instance.analogRead(pin14); if(value != -1) Debug.Log("Analog Value : " + value); UduinoManager.Instance.digitalWrite(digitalPin42, State.HIGH); } }
BeAnotherLab/The-Machine-to-be-Another-Unity
Assets/Uduino/Examples/Advanced/Arduino Mega/MegaReadWrite.cs
C#
gpl-2.0
1,806
/* * This file is part of MetaTheme. * Copyright (c) 2004 Martin Dvorak <jezek2@advel.cz> * * MetaTheme 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. * * MetaTheme 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 MetaTheme; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package metatheme; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseAdapter; import java.awt.event.KeyEvent; import javax.swing.*; import javax.swing.plaf.*; import javax.swing.plaf.basic.BasicMenuItemUI; import javax.swing.plaf.basic.BasicGraphicsUtils; public class MetaThemeMenuItemUI extends BasicMenuItemUI implements MT { private ThemeEngine engine; private JMenuItem mi; private int type; public MetaThemeMenuItemUI(JMenuItem i) { super(); engine = ThemeEngine.get(); mi = i; type = MT_MENU_ITEM; if (mi instanceof JCheckBoxMenuItem) { type = MT_MENU_ITEM_CHECK; } else if (mi instanceof JRadioButtonMenuItem) { type = MT_MENU_ITEM_RADIO; } else if (mi instanceof JMenu) { type = MT_MENU_ITEM_ARROW; } } public static ComponentUI createUI(JComponent c) { return new MetaThemeMenuItemUI((JMenuItem)c); } protected void paintMenuItem(Graphics g, JComponent c, Icon checkIcon, Icon arrowIcon, Color background, Color foreground, int defaultTextIconGap) { JMenuItem menuItem = (JMenuItem)c; ButtonModel model = menuItem.getModel(); int x,y; int maxpmw = 16; Font font = menuItem.getFont(); FontMetrics fm = menuItem.getFontMetrics(font); int state = Utils.getState(menuItem); paintBackground(g, menuItem, null); Icon icon = menuItem.getIcon(); if (icon != null) { if (icon.getIconWidth() > maxpmw) { maxpmw = icon.getIconWidth(); } if ((state & MT_DISABLED) != 0) { icon = (Icon)menuItem.getDisabledIcon(); } else if (model.isPressed() && model.isArmed()) { icon = (Icon)menuItem.getPressedIcon(); if (icon == null) { icon = (Icon)menuItem.getIcon(); } } else { icon = (Icon)menuItem.getIcon(); } } if (type == MT_MENU_ITEM_CHECK || type == MT_MENU_ITEM_RADIO) { if ((state & MT_ACTIVE) != 0) { x = engine.metricSize[MT_MENU_BORDER].width; y = engine.metricSize[MT_MENU_BORDER].height; engine.drawWidget(g, type, state, x, y, maxpmw, menuItem.getHeight() - 2*y, c); } } else { if (icon != null) { y = (menuItem.getHeight() - icon.getIconHeight() - 1) / 2; icon.paintIcon(menuItem, g, engine.metricSize[MT_MENU_ITEM_BORDER].width, y); } } String text = menuItem.getText(); if (text != null) { g.setFont(font); paintText(g, menuItem, new Rectangle(0, 0, menuItem.getWidth(), menuItem.getHeight()), text); } KeyStroke accelerator = menuItem.getAccelerator(); String acceleratorText = ""; if (accelerator != null) { int modifiers = accelerator.getModifiers(); if (modifiers > 0) { acceleratorText = KeyEvent.getKeyModifiersText(modifiers); acceleratorText += /*acceleratorDelimiter*/"-"; } int keyCode = accelerator.getKeyCode(); if (keyCode != 0) { acceleratorText += KeyEvent.getKeyText(keyCode); } else { acceleratorText += accelerator.getKeyChar(); } } if (acceleratorText != null && !acceleratorText.equals("")) { x = menuItem.getWidth() - engine.metricSize[MT_MENU_ITEM_BORDER].width - 3; y = (menuItem.getHeight() - fm.getHeight() + 1) / 2; x -= SwingUtilities.computeStringWidth(fm, acceleratorText); g.setFont(font); engine.drawString(g, MT_MENU_ITEM, state, x, y, acceleratorText, engine.palette[Utils.getTextColor(state, MT_FOREGROUND, true)], -1); } if (type == MT_MENU_ITEM_ARROW) { x = menuItem.getWidth() - 1 - engine.metricSize[MT_MENU_ITEM_BORDER].width - 8; y = engine.metricSize[MT_MENU_ITEM_BORDER].height; engine.drawWidget(g, MT_MENU_ITEM_ARROW, state, x, y, 8, menuItem.getHeight() - 2*y, c); } } protected void paintBackground(Graphics g, JMenuItem menuItem, Color bgColor) { Dimension size = menuItem.getSize(); int state = Utils.getState(menuItem); Color oldColor = g.getColor(); engine.drawWidget(g, MT_MENU_ITEM, state, 0, 0, size.width, size.height, menuItem); g.setColor(oldColor); } protected void paintText(Graphics g, JMenuItem menuItem, Rectangle textRect, String text) { FontMetrics fm = g.getFontMetrics(); int mnemIndex = menuItem.getDisplayedMnemonicIndex(); int state = Utils.getState(menuItem); Rectangle tr = new Rectangle(textRect); int maxpmw = 16; Icon icon = menuItem.getIcon(); if (icon != null && icon.getIconWidth() > maxpmw) maxpmw = icon.getIconWidth(); tr.x += engine.metricSize[MT_MENU_ITEM_BORDER].width + maxpmw + 3; tr.y += (tr.height - fm.getHeight() + 1) / 2; int sc = MT_FOREGROUND; if ((state & MT_SELECTED) != 0) sc = MT_SELECTED_FOREGROUND; engine.drawString(g, MT_MENU_ITEM, state, tr.x, tr.y, text, engine.palette[Utils.getTextColor(state, MT_FOREGROUND, true)], mnemIndex); } protected Dimension getPreferredMenuItemSize(JComponent c, Icon checkIcon, Icon arrowIcon, int defaultTextIconGap) { Dimension d = super.getPreferredMenuItemSize(c, checkIcon, arrowIcon, defaultTextIconGap); if (d.height <= 18) d.height -= 3; d.width += engine.metricSize[MT_MENU_ITEM_BORDER].width * 2; d.height += engine.metricSize[MT_MENU_ITEM_BORDER].height * 2; if (d.height < 18) d.height = 18; return d; } }
Icenowy/metatheme
toolkits/java/metatheme/MetaThemeMenuItemUI.java
Java
gpl-2.0
6,011
/* Copyright (C) 2003 - 2016 by David White <dave@whitevine.net> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ /** * @file * Show screen with scrolling credits. */ #include "leader_scroll_dialog.hpp" #include "wml_separators.hpp" #include "map/map.hpp" //#include "construct_dialog.hpp" //#include "display.hpp" //#include "gettext.hpp" #include "marked-up_text.hpp" #include "resources.hpp" #include "units/unit.hpp" // //#include <boost/foreach.hpp> /** * @namespace about * Display credits %about all contributors. * * This module is used from the startup screen. \n * When show_about() is called, a list of contributors * to the game will be presented to the user. */ namespace gui { void status_table(display& gui, int selected) { std::stringstream heading; heading << HEADING_PREFIX << _("Leader") << COLUMN_SEPARATOR << ' ' << COLUMN_SEPARATOR << _("Team") << COLUMN_SEPARATOR << _("Gold") << COLUMN_SEPARATOR << _("Villages") << COLUMN_SEPARATOR << _("status^Units") << COLUMN_SEPARATOR << _("Upkeep") << COLUMN_SEPARATOR << _("Income"); gui::menu::basic_sorter sorter; sorter.set_redirect_sort(0,1).set_alpha_sort(1).set_alpha_sort(2).set_numeric_sort(3) .set_numeric_sort(4).set_numeric_sort(5).set_numeric_sort(6).set_numeric_sort(7); std::vector<std::string> items; std::vector<bool> leader_bools; items.push_back(heading.str()); const gamemap& map = gui.get_map(); const unit_map& units = gui.get_units(); assert(&gui.get_teams() == resources::teams); const std::vector<team>& teams = gui.get_teams(); const team& viewing_team = teams[gui.viewing_team()]; unsigned total_villages = 0; // a variable to check if there are any teams to show in the table bool status_table_empty = true; //if the player is under shroud or fog, they don't get //to see details about the other sides, only their own //side, allied sides and a ??? is shown to demonstrate //lack of information about the other sides But he see //all names with in colors for(size_t n = 0; n != teams.size(); ++n) { if(teams[n].hidden()) { continue; } status_table_empty=false; const bool known = viewing_team.knows_about_team(n, network::nconnections() > 0); const bool enemy = viewing_team.is_enemy(n+1); std::stringstream str; const team_data data = gui.get_disp_context().calculate_team_data(teams[n],n+1); unit_map::const_iterator leader = units.find_leader(n + 1); std::string leader_name; //output the number of the side first, and this will //cause it to be displayed in the correct color if(leader != units.end()) { const bool fogged = viewing_team.fogged(leader->get_location()); // Add leader image. If it's fogged // show only a random leader image. if (!fogged || known || game_config::debug) { str << IMAGE_PREFIX << leader->absolute_image(); leader_bools.push_back(true); leader_name = leader->name(); } else { str << IMAGE_PREFIX << std::string("units/unknown-unit.png"); leader_bools.push_back(false); leader_name = "Unknown"; } // if (gamestate_.classification().campaign_type == game_classification::CAMPAIGN_TYPE::MULTIPLAYER) // leader_name = teams[n].current_player(); #ifndef LOW_MEM str << leader->image_mods(); #endif } else { leader_bools.push_back(false); } str << COLUMN_SEPARATOR << team::get_side_highlight(n) << leader_name << COLUMN_SEPARATOR << (data.teamname.empty() ? teams[n].team_name() : data.teamname) << COLUMN_SEPARATOR; if(!known && !game_config::debug) { // We don't spare more info (only name) // so let's go on next side ... items.push_back(str.str()); continue; } if(game_config::debug) { str << utils::half_signed_value(data.gold) << COLUMN_SEPARATOR; } else if(enemy && viewing_team.uses_fog()) { str << ' ' << COLUMN_SEPARATOR; } else { str << utils::half_signed_value(data.gold) << COLUMN_SEPARATOR; } str << data.villages; if(!(viewing_team.uses_fog() || viewing_team.uses_shroud())) { str << "/" << map.villages().size(); } str << COLUMN_SEPARATOR << data.units << COLUMN_SEPARATOR << data.upkeep << COLUMN_SEPARATOR << (data.net_income < 0 ? font::BAD_TEXT : font::NULL_MARKUP) << utils::signed_value(data.net_income); total_villages += data.villages; items.push_back(str.str()); } if (total_villages > map.villages().size()) { //TODO // ERR_NG << "Logic error: map has " << map.villages().size() // << " villages but status table shows " << total_villages << " owned in total\n"; } if (status_table_empty) { // no sides to show - display empty table std::stringstream str; str << " "; for (int i=0;i<7;++i) str << COLUMN_SEPARATOR << " "; leader_bools.push_back(false); items.push_back(str.str()); } int result = 0; { leader_scroll_dialog slist(gui, _("Current Status"), leader_bools, selected, gui::DIALOG_FORWARD); slist.add_button(new gui::dialog_button(gui.video(), _("More >"), gui::button::TYPE_PRESS, gui::DIALOG_FORWARD), gui::dialog::BUTTON_EXTRA_LEFT); slist.set_menu(items, &sorter); slist.get_menu().move_selection(selected); result = slist.show(); selected = slist.get_menu().selection(); } // this will kill the dialog before scrolling if (result >= 0) { //TODO // gui.scroll_to_leader(units_, selected+1); } else if (result == gui::DIALOG_FORWARD) scenario_settings_table(gui, selected); } void scenario_settings_table(display& gui, int selected) { std::stringstream heading; heading << HEADING_PREFIX << _("scenario settings^Leader") << COLUMN_SEPARATOR << COLUMN_SEPARATOR << _("scenario settings^Side") << COLUMN_SEPARATOR << _("scenario settings^Start\nGold") << COLUMN_SEPARATOR << _("scenario settings^Base\nIncome") << COLUMN_SEPARATOR << _("scenario settings^Gold Per\nVillage") << COLUMN_SEPARATOR << _("scenario settings^Support Per\nVillage") << COLUMN_SEPARATOR << _("scenario settings^Fog") << COLUMN_SEPARATOR << _("scenario settings^Shroud"); gui::menu::basic_sorter sorter; sorter.set_redirect_sort(0,1).set_alpha_sort(1).set_numeric_sort(2) .set_numeric_sort(3).set_numeric_sort(4).set_numeric_sort(5) .set_numeric_sort(6).set_alpha_sort(7).set_alpha_sort(8); std::vector<std::string> items; std::vector<bool> leader_bools; items.push_back(heading.str()); //const gamemap& map = gui.get_map(); const unit_map& units = gui.get_units(); const std::vector<team>& teams = gui.get_teams(); const team& viewing_team = teams[gui.viewing_team()]; bool settings_table_empty = true; bool fogged; for(size_t n = 0; n != teams.size(); ++n) { if(teams[n].hidden()) { continue; } settings_table_empty = false; std::stringstream str; unit_map::const_iterator leader = units.find_leader(n + 1); if(leader != units.end()) { // Add leader image. If it's fogged // show only a random leader image. fogged=viewing_team.fogged(leader->get_location()); if (!fogged || viewing_team.knows_about_team(n, network::nconnections() > 0) || game_config::debug) { str << IMAGE_PREFIX << leader->absolute_image(); leader_bools.push_back(true); } else { str << IMAGE_PREFIX << std::string("units/unknown-unit.png"); leader_bools.push_back(false); } #ifndef LOW_MEM str << "~RC(" << leader->team_color() << '>' << team::get_side_color_index(n+1) << ")"; #endif } else { leader_bools.push_back(false); } str << COLUMN_SEPARATOR << team::get_side_highlight(n) << teams[n].side_name() << COLUMN_SEPARATOR << n + 1 << COLUMN_SEPARATOR << teams[n].start_gold() << COLUMN_SEPARATOR << teams[n].base_income() << COLUMN_SEPARATOR << teams[n].village_gold() << COLUMN_SEPARATOR << teams[n].village_support() << COLUMN_SEPARATOR << (teams[n].uses_fog() ? _("yes") : _("no")) << COLUMN_SEPARATOR << (teams[n].uses_shroud() ? _("yes") : _("no")) << COLUMN_SEPARATOR; items.push_back(str.str()); } if (settings_table_empty) { // no sides to show - display empty table std::stringstream str; for (int i=0;i<8;++i) str << " " << COLUMN_SEPARATOR; leader_bools.push_back(false); items.push_back(str.str()); } int result = 0; { leader_scroll_dialog slist(gui, _("Scenario Settings"), leader_bools, selected, gui::DIALOG_BACK); slist.set_menu(items, &sorter); slist.get_menu().move_selection(selected); slist.add_button(new gui::dialog_button(gui.video(), _(" < Back"), gui::button::TYPE_PRESS, gui::DIALOG_BACK), gui::dialog::BUTTON_EXTRA_LEFT); result = slist.show(); selected = slist.get_menu().selection(); } // this will kill the dialog before scrolling if (result >= 0) { //TODO //gui_->scroll_to_leader(units_, selected+1); } else if (result == gui::DIALOG_BACK) status_table(gui, selected); } } // end namespace about
Dugy/wesnoth-names
src/leader_scroll_dialog.cpp
C++
gpl-2.0
9,320
/** \file * SVG <feSpecularLighting> implementation. * */ /* * Authors: * hugo Rodrigues <haa.rodrigues@gmail.com> * Jean-Rene Reinhard <jr@komite.net> * Abhishek Sharma * * Copyright (C) 2006 Hugo Rodrigues * 2007 authors * * Released under GNU GPL, read the file 'COPYING' for more information */ #include "strneq.h" #include "attributes.h" #include "svg/svg.h" #include "sp-object.h" #include "svg/svg-color.h" #include "svg/svg-icc-color.h" #include "filters/specularlighting.h" #include "filters/distantlight.h" #include "filters/pointlight.h" #include "filters/spotlight.h" #include "xml/repr.h" #include "display/nr-filter.h" #include "display/nr-filter-specularlighting.h" /* FeSpecularLighting base class */ static void sp_feSpecularLighting_children_modified(SPFeSpecularLighting *sp_specularlighting); SPFeSpecularLighting::SPFeSpecularLighting() : SPFilterPrimitive() { this->surfaceScale = 1; this->specularConstant = 1; this->specularExponent = 1; this->lighting_color = 0xffffffff; this->icc = NULL; //TODO kernelUnit this->renderer = NULL; this->surfaceScale_set = FALSE; this->specularConstant_set = FALSE; this->specularExponent_set = FALSE; this->lighting_color_set = FALSE; } SPFeSpecularLighting::~SPFeSpecularLighting() { } /** * Reads the Inkscape::XML::Node, and initializes SPFeSpecularLighting variables. For this to get called, * our name must be associated with a repr via "sp_object_type_register". Best done through * sp-object-repr.cpp's repr_name_entries array. */ void SPFeSpecularLighting::build(SPDocument *document, Inkscape::XML::Node *repr) { SPFilterPrimitive::build(document, repr); /*LOAD ATTRIBUTES FROM REPR HERE*/ this->readAttr( "surfaceScale" ); this->readAttr( "specularConstant" ); this->readAttr( "specularExponent" ); this->readAttr( "kernelUnitLength" ); this->readAttr( "lighting-color" ); } /** * Drops any allocated memory. */ void SPFeSpecularLighting::release() { SPFilterPrimitive::release(); } /** * Sets a specific value in the SPFeSpecularLighting. */ void SPFeSpecularLighting::set(unsigned int key, gchar const *value) { gchar const *cend_ptr = NULL; gchar *end_ptr = NULL; switch(key) { /*DEAL WITH SETTING ATTRIBUTES HERE*/ //TODO test forbidden values case SP_ATTR_SURFACESCALE: end_ptr = NULL; if (value) { this->surfaceScale = g_ascii_strtod(value, &end_ptr); if (end_ptr) { this->surfaceScale_set = TRUE; } else { g_warning("this: surfaceScale should be a number ... defaulting to 1"); } } //if the attribute is not set or has an unreadable value if (!value || !end_ptr) { this->surfaceScale = 1; this->surfaceScale_set = FALSE; } if (this->renderer) { this->renderer->surfaceScale = this->surfaceScale; } this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; case SP_ATTR_SPECULARCONSTANT: end_ptr = NULL; if (value) { this->specularConstant = g_ascii_strtod(value, &end_ptr); if (end_ptr && this->specularConstant >= 0) { this->specularConstant_set = TRUE; } else { end_ptr = NULL; g_warning("this: specularConstant should be a positive number ... defaulting to 1"); } } if (!value || !end_ptr) { this->specularConstant = 1; this->specularConstant_set = FALSE; } if (this->renderer) { this->renderer->specularConstant = this->specularConstant; } this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; case SP_ATTR_SPECULAREXPONENT: end_ptr = NULL; if (value) { this->specularExponent = g_ascii_strtod(value, &end_ptr); if (this->specularExponent >= 1 && this->specularExponent <= 128) { this->specularExponent_set = TRUE; } else { end_ptr = NULL; g_warning("this: specularExponent should be a number in range [1, 128] ... defaulting to 1"); } } if (!value || !end_ptr) { this->specularExponent = 1; this->specularExponent_set = FALSE; } if (this->renderer) { this->renderer->specularExponent = this->specularExponent; } this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; case SP_ATTR_KERNELUNITLENGTH: //TODO kernelUnit //this->kernelUnitLength.set(value); /*TODOif (feSpecularLighting->renderer) { feSpecularLighting->renderer->surfaceScale = feSpecularLighting->renderer; } */ this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; case SP_PROP_LIGHTING_COLOR: cend_ptr = NULL; this->lighting_color = sp_svg_read_color(value, &cend_ptr, 0xffffffff); //if a value was read if (cend_ptr) { while (g_ascii_isspace(*cend_ptr)) { ++cend_ptr; } if (strneq(cend_ptr, "icc-color(", 10)) { if (!this->icc) this->icc = new SVGICCColor(); if ( ! sp_svg_read_icc_color( cend_ptr, this->icc ) ) { delete this->icc; this->icc = NULL; } } this->lighting_color_set = TRUE; } else { //lighting_color already contains the default value this->lighting_color_set = FALSE; } if (this->renderer) { this->renderer->lighting_color = this->lighting_color; } this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); break; default: SPFilterPrimitive::set(key, value); break; } } /** * Receives update notifications. */ void SPFeSpecularLighting::update(SPCtx *ctx, guint flags) { if (flags & (SP_OBJECT_MODIFIED_FLAG)) { this->readAttr( "surfaceScale" ); this->readAttr( "specularConstant" ); this->readAttr( "specularExponent" ); this->readAttr( "kernelUnitLength" ); this->readAttr( "lighting-color" ); } SPFilterPrimitive::update(ctx, flags); } /** * Writes its settings to an incoming repr object, if any. */ Inkscape::XML::Node* SPFeSpecularLighting::write(Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags) { /* TODO: Don't just clone, but create a new repr node and write all * relevant values _and children_ into it */ if (!repr) { repr = this->getRepr()->duplicate(doc); //repr = doc->createElement("svg:feSpecularLighting"); } if (this->surfaceScale_set) { sp_repr_set_css_double(repr, "surfaceScale", this->surfaceScale); } if (this->specularConstant_set) { sp_repr_set_css_double(repr, "specularConstant", this->specularConstant); } if (this->specularExponent_set) { sp_repr_set_css_double(repr, "specularExponent", this->specularExponent); } /*TODO kernelUnits */ if (this->lighting_color_set) { gchar c[64]; sp_svg_write_color(c, sizeof(c), this->lighting_color); repr->setAttribute("lighting-color", c); } SPFilterPrimitive::write(doc, repr, flags); return repr; } /** * Callback for child_added event. */ void SPFeSpecularLighting::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref) { SPFilterPrimitive::child_added(child, ref); sp_feSpecularLighting_children_modified(this); this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } /** * Callback for remove_child event. */ void SPFeSpecularLighting::remove_child(Inkscape::XML::Node *child) { SPFilterPrimitive::remove_child(child); sp_feSpecularLighting_children_modified(this); this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } void SPFeSpecularLighting::order_changed(Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, Inkscape::XML::Node *new_ref) { SPFilterPrimitive::order_changed(child, old_ref, new_ref); sp_feSpecularLighting_children_modified(this); this->parent->requestModified(SP_OBJECT_MODIFIED_FLAG); } static void sp_feSpecularLighting_children_modified(SPFeSpecularLighting *sp_specularlighting) { if (sp_specularlighting->renderer) { sp_specularlighting->renderer->light_type = Inkscape::Filters::NO_LIGHT; if (SP_IS_FEDISTANTLIGHT(sp_specularlighting->children)) { sp_specularlighting->renderer->light_type = Inkscape::Filters::DISTANT_LIGHT; sp_specularlighting->renderer->light.distant = SP_FEDISTANTLIGHT(sp_specularlighting->children); } if (SP_IS_FEPOINTLIGHT(sp_specularlighting->children)) { sp_specularlighting->renderer->light_type = Inkscape::Filters::POINT_LIGHT; sp_specularlighting->renderer->light.point = SP_FEPOINTLIGHT(sp_specularlighting->children); } if (SP_IS_FESPOTLIGHT(sp_specularlighting->children)) { sp_specularlighting->renderer->light_type = Inkscape::Filters::SPOT_LIGHT; sp_specularlighting->renderer->light.spot = SP_FESPOTLIGHT(sp_specularlighting->children); } } } void SPFeSpecularLighting::build_renderer(Inkscape::Filters::Filter* filter) { g_assert(this != NULL); g_assert(filter != NULL); int primitive_n = filter->add_primitive(Inkscape::Filters::NR_FILTER_SPECULARLIGHTING); Inkscape::Filters::FilterPrimitive *nr_primitive = filter->get_primitive(primitive_n); Inkscape::Filters::FilterSpecularLighting *nr_specularlighting = dynamic_cast<Inkscape::Filters::FilterSpecularLighting*>(nr_primitive); g_assert(nr_specularlighting != NULL); this->renderer = nr_specularlighting; sp_filter_primitive_renderer_common(this, nr_primitive); nr_specularlighting->specularConstant = this->specularConstant; nr_specularlighting->specularExponent = this->specularExponent; nr_specularlighting->surfaceScale = this->surfaceScale; nr_specularlighting->lighting_color = this->lighting_color; nr_specularlighting->set_icc(this->icc); //We assume there is at most one child nr_specularlighting->light_type = Inkscape::Filters::NO_LIGHT; if (SP_IS_FEDISTANTLIGHT(this->children)) { nr_specularlighting->light_type = Inkscape::Filters::DISTANT_LIGHT; nr_specularlighting->light.distant = SP_FEDISTANTLIGHT(this->children); } if (SP_IS_FEPOINTLIGHT(this->children)) { nr_specularlighting->light_type = Inkscape::Filters::POINT_LIGHT; nr_specularlighting->light.point = SP_FEPOINTLIGHT(this->children); } if (SP_IS_FESPOTLIGHT(this->children)) { nr_specularlighting->light_type = Inkscape::Filters::SPOT_LIGHT; nr_specularlighting->light.spot = SP_FESPOTLIGHT(this->children); } //nr_offset->set_dx(sp_offset->dx); //nr_offset->set_dy(sp_offset->dy); } /* 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:fileencoding=utf-8:textwidth=99 :
danieljabailey/inkscape_experiments
src/filters/specularlighting.cpp
C++
gpl-2.0
11,839
<?php //include_once "inc/header.php"; ?> <!-- Content top –––––––––––––––––––––––––––––––––––––––––––––––––– --> <div class="content"> <div class="container"> <div class="row"> <div class="twelve columns"><!-- Top info --> <div class="infotop"> <p>Deftly tailored from very fine woven egyptian cotton, these shirts are smooth to the touch, though still maintain their elegant shape. Essential pieces that easily cross from the week into the weekend.</p> </div> </div><!-- End Top info --> </div> </div> </div> <!-- Content produk –––––––––––––––––––––––––––––––––––––––––––––––––– --> <div class="content"> <div class="container"> <div class="row"> <div class="three columns"> <a class="tab_link" title="#p1a" href="#p1a"> <div class="produk"> <div class="barang"><img src="<?php echo img_url(); ?>bnew.png"/></div> <div class="gmbproduk"><img class="gmbproduk" src="<?php echo prod_small_url() . '1.jpg'?>"/></div> <div class="hoverproduk"> <div class="hpnam"><img src="<?php echo img_url(); ?>hp4.png" /></div> </div> </div> </a> </div> <div class="three columns"> <a class="tab_link" title="#p1b" href="#p1b"> <div class="produk"> <div class="barang"><img src="<?php echo img_url(); ?>bnew.png"/></div> <div class="gmbproduk"><img class="gmbproduk" src="<?php echo prod_small_url() ?>2.jpg"/></div> <div class="hoverproduk"> <div class="hpnam"><img src="<?php echo img_url(); ?>hp4.png" /></div> </div> </div> </a> </div> <div class="three columns"> <a class="tab_link" title="#p1c" href="#p1c"> <div class="produk"> <div class="barang"><img src="<?php echo img_url(); ?>bbin.png"/></div> <div class="gmbproduk"><img class="gmbproduk" src="<?php echo prod_small_url() ?>3.jpg"/></div> <div class="hoverproduk"> <div class="hpnam"><img src="<?php echo img_url(); ?>hp4.png" /></div> </div> </div> </a> </div> <div class="three columns"> <a class="tab_link" title="#p1d" href="#p1d"> <div class="produk"> <div class="barang"><img src="<?php echo img_url(); ?>bbin.png"/></div> <div class="gmbproduk"><img class="gmbproduk" src="<?php echo prod_small_url() ?>4.jpg"/></div> <div class="hoverproduk"> <div class="hpnam"><img src="<?php echo img_url(); ?>hp4.png" /></div> </div> </div> </a> </div> <div class="twelve columns"> <div id="p1a" class="tab_text"> <div id="slider1"> <a class="control_next"><img src="<?php echo img_url(); ?>arr/arrRight.png"/></a> <a class="control_prev"><img src="<?php echo img_url(); ?>arr/arrLeft.png"/></a> <ul> <li> <div class="acc1"> <img class="one-half column gmbprodukc" src="<?php echo prod_small_url(); ?>1.jpg"/> <img class="one-half column gmbprodukc" src="<?php echo prod_small_url(); ?>2.jpg"/> </div> </li> <li> <div class="acc2"> <img class="one-half column gmbprodukc" src="<?php echo prod_small_url(); ?>1.jpg"/> <div class="one-half column"> <h6 class="kiri">Aføn D Shirt (Produk 1)</h6> <div class="row" style="margin-bottom:1px !important;"> <div class="one-half column kiri">(toscamanu)</div> <div class="one-half column kanan">USD $25</div> </div> <div class='item' style='background-image: url("<?php echo img_url(); ?>arr/arrBottom.png");'>DESCRIPTION</div> <div class='item-data active' style="display: block;"> <div> Carfied from 100% long staple cotton fabric, we’re confident our Short Sleeve is the best shirt you”ll ever wear. Combining a clean aesthetic with a classic fit, it’s available in a host of colours and is the perfect foundation for your everyday looks. </div> </div> <div class='item'>COLOURS</div> <div class='item-data'> <div class="row"> <div class="two columns"> <img width="100%" src="<?php echo img_url(); ?>color/1.jpg"/> </div> <div class="two columns"> <img width="100%" src="<?php echo img_url(); ?>color/2.jpg"/> </div> <div class="two columns"> <img width="100%" src="<?php echo img_url(); ?>color/3.jpg"/> </div> <div class="two columns"> <img width="100%" src="<?php echo img_url(); ?>color/4.jpg"/> </div> </div> </div> <div class='item'>SIZING</div> <div class='item-data' > <table class="u-full-width"> <thead> <tr> <th>SIZE</th> <th>S</th> <th>M</th> <th>L</th> <th>XL</th> </tr> </thead> <tbody> <tr> <td>CHEST</td> <td>18.1" 46cm</td> <td>19.3" 49cm</td> <td>20.1" 51cm</td> <td>20,8" 53cm</td> </tr> <tr> <td>LENGHT</td> <td>26,7" 68cm</td> <td>27,9" 71cm</td> <td>28,7" 73cm</td> <td>29,5" 75cm</td> </tr> </tbody> </table> </div> <div> </div> <div class='item'>FABRIC</div> <div class='item-data' > <div> 100% Egyptian cotton, Classic fit, True to size - if between sizes opt for the smaller, Model wears a size Medium, Model measures - height: 6’2”/188cm, chest: 40”/101.5cm, waist: 32''/81cm, Machine wash at 40 degrees, Made in Indonesia. </div> </div> <div class='item'>SHIPPING & RETURNS</div> <div class='item-data' > <div> FREE SHIPPING purchase over $200, Standard Post: 10-12 working days. <p>For full delivery and returns information, <u>click here</u>.</p> Due to the high volume of orders during promotions or sales, we regret we cannot make any amendments to purchases once ordered and the processing of returns will take longer than normal. </div> </div> <div class="twelve columns"> <div class="one-half column"> <select class="u-full-width" id="inputSize"> <option value="Option 1">SELECT SIZE</option> <option value="Option 2">Small</option> <option value="Option 3">Medium</option> <option value="Option 2">Large</option> <option value="Option 3">Extra Large</option> </select> <input value="ADD TO WISHLIST" type="submit" class="button button-primary u-full-width"> <div class="sosmed"> <img width="15%" src="<?php echo img_url(); ?>twitter.png"></img> <img width="15%" src="<?php echo img_url(); ?>instagram.png"></img> <img width="15%" src="<?php echo img_url(); ?>facebook.png"></img> <img width="15%" src="<?php echo img_url(); ?>tumblr.png"></img> <img width="15%" src="<?php echo img_url(); ?>pinterest.png"></img> <img width="15%" src="<?php echo img_url(); ?>youtube.png"></img> </div> </div> <div class="one-half column"> QUANTITY<input value="-" type="submit" class="butq" style="padding: 0px 15px;margin-left:5px;"><input value="1" type="text" class="butq"><input value="+" type="submit" class="butq" style="padding: 0px 15px;"> <input value="ADD TO BASKET" type="submit" class="button button-primary u-full-width" style="margin-top:10px;"> <a href="D006.html"><u><i><b>Email a Friend</b></i></u></a> </div> </div> </div> </div> </li> </ul> </div> <!--<div style="clear: both"></div>--> <div class="kiri" style="float: left;margin-top: 10px;">|#| Kushin = [in] "Aføn D Shirt" (toscamanu) TM</div> <div class=""><a class="tutup closetab"><img src="<?php echo img_url(); ?>close-icon.png"></img></a></div> </div> <div id="p1b" class="tab_text"> <div id="slider2"> <a class="control_next"><img src="<?php echo img_url(); ?>arr/arrRight.png"/></a> <a class="control_prev"><img src="<?php echo img_url(); ?>arr/arrLeft.png"/></a> <ul> <li> <div class="acc1"> <img class="one-half column gmbprodukc" src="<?php echo prod_small_url(); ?>1.jpg"/> <img class="one-half column gmbprodukc" src="<?php echo prod_small_url(); ?>2.jpg"/> </div> </li> <li> <div class="acc2"> <img class="one-half column gmbprodukc" src="<?php echo prod_small_url(); ?>1.jpg"/> <div class="one-half column"> <h6 class="kiri">Aføn D Shirt (Produk 1)</h6> <div class="row" style="margin-bottom:1px !important;"> <div class="one-half column kiri">(toscamanu)</div> <div class="one-half column kanan">USD $25</div> </div> <div class='item' style='background-image: url("<?php echo img_url(); ?>arr/arrBottom.png");'>DESCRIPTION</div> <div class='item-data active' style="display: block;"> <div> Carfied from 100% long staple cotton fabric, we’re confident our Short Sleeve is the best shirt you”ll ever wear. Combining a clean aesthetic with a classic fit, it’s available in a host of colours and is the perfect foundation for your everyday looks. </div> </div> <div class='item'>COLOURS</div> <div class='item-data'> <div class="row"> <div class="two columns"> <img width="100%" src="<?php echo img_url(); ?>color/1.jpg"/> </div> <div class="two columns"> <img width="100%" src="<?php echo img_url(); ?>color/2.jpg"/> </div> <div class="two columns"> <img width="100%" src="<?php echo img_url(); ?>color/3.jpg"/> </div> <div class="two columns"> <img width="100%" src="<?php echo img_url(); ?>color/4.jpg"/> </div> </div> </div> <div class='item'>SIZING</div> <div class='item-data' > <table class="u-full-width"> <thead> <tr> <th>SIZE</th> <th>S</th> <th>M</th> <th>L</th> <th>XL</th> </tr> </thead> <tbody> <tr> <td>CHEST</td> <td>18.1" 46cm</td> <td>19.3" 49cm</td> <td>20.1" 51cm</td> <td>20,8" 53cm</td> </tr> <tr> <td>LENGHT</td> <td>26,7" 68cm</td> <td>27,9" 71cm</td> <td>28,7" 73cm</td> <td>29,5" 75cm</td> </tr> </tbody> </table> </div> <div> </div> <div class='item'>FABRIC</div> <div class='item-data' > <div> 100% Egyptian cotton, Classic fit, True to size - if between sizes opt for the smaller, Model wears a size Medium, Model measures - height: 6’2”/188cm, chest: 40”/101.5cm, waist: 32''/81cm, Machine wash at 40 degrees, Made in Indonesia. </div> </div> <div class='item'>SHIPPING & RETURNS</div> <div class='item-data' > <div> FREE SHIPPING purchase over $200, Standard Post: 10-12 working days. <p>For full delivery and returns information, <u>click here</u>.</p> Due to the high volume of orders during promotions or sales, we regret we cannot make any amendments to purchases once ordered and the processing of returns will take longer than normal. </div> </div> <div class="twelve columns"> <div class="one-half column"> <select class="u-full-width" id="inputSize"> <option value="Option 1">SELECT SIZE</option> <option value="Option 2">Small</option> <option value="Option 3">Medium</option> <option value="Option 2">Large</option> <option value="Option 3">Extra Large</option> </select> <input value="ADD TO WISHLIST" type="submit" class="button button-primary u-full-width"> <div class="sosmed"> <img width="15%" src="<?php echo img_url(); ?>twitter.png"></img> <img width="15%" src="<?php echo img_url(); ?>instagram.png"></img> <img width="15%" src="<?php echo img_url(); ?>facebook.png"></img> <img width="15%" src="<?php echo img_url(); ?>tumblr.png"></img> <img width="15%" src="<?php echo img_url(); ?>pinterest.png"></img> <img width="15%" src="<?php echo img_url(); ?>youtube.png"></img> </div> </div> <div class="one-half column"> QUANTITY<input value="-" type="submit" class="butq" style="padding: 0px 15px;margin-left:5px;"><input value="1" type="text" class="butq"><input value="+" type="submit" class="butq" style="padding: 0px 15px;"> <input value="ADD TO BASKET" type="submit" class="button button-primary u-full-width" style="margin-top:10px;"> <a href="D006.html"><u><i><b>Email a Friend</b></i></u></a> </div> </div> </div> </div> </li> </ul> </div> <!--<div style="clear: both"></div>--> <div class="kiri" style="float: left;margin-top: 10px;">|#| Kushin = [in] "Aføn D Shirt" (toscamanu) TM</div> <div class=""><a class="tutup closetab"><img src="<?php echo img_url(); ?>close-icon.png"></img></a></div> </div> <div id="p1c" class="tab_text"> p1c content. <div class="closetab">close</div> </div> <div id="p1d" class="tab_text"> p1d content. <div class="closetab">close</div> </div> </div> </div> <div class="row"> <div class="three columns"> <a class="tab_link" title="#p2a" href="#p2a"> <img src="<?php echo prod_small_url(); ?>1.jpg"/> </a> </div> <div class="three columns"> <a class="tab_link" title="#p2b" href="#p2b"> <img src="<?php echo prod_small_url(); ?>2.jpg"/> </a> </div> <div class="three columns"> <a class="tab_link" title="#p2c" href="#p2c"> <img src="<?php echo prod_small_url(); ?>3.jpg"/> </a> </div> <div class="three columns"> <a class="tab_link" title="#p2d" href="#p2d"> <img src="<?php echo prod_small_url(); ?>4.jpg"/> </a> </div> <div class="twelve columns"> <div id="p2a" class="tab_text"> p2a content. <div class="closetab">close</div> </div> <div id="p2b" class="tab_text"> p2b content. <div class="closetab">close</div> </div> <div id="p2c" class="tab_text"> p2c content. <div class="closetab">close</div> </div> <div id="p2d" class="tab_text"> p2d content. <div class="closetab">close</div> </div> </div> </div> <div class="row"> <div class="three columns"> <a class="tab_link" title="#p3a" href="#p3a"> <img src="<?php echo prod_small_url(); ?>1.jpg"/> </a> </div> <div class="three columns"> <a class="tab_link" title="#p3b" href="#p3b"> <img src="<?php echo prod_small_url(); ?>2.jpg"/> </a> </div> <div class="three columns"> <a class="tab_link" title="#p3c" href="#p3c"> <img src="<?php echo prod_small_url(); ?>3.jpg"/> </a> </div> <div class="three columns"> <a class="tab_link" title="#p3d" href="#p3d"> <img src="<?php echo prod_small_url(); ?>4.jpg"/> </a> </div> </div> </div><!-- End container --> </div><!-- End home info --> <script> $(document).ready(function(){ $('.tab_link').tab(); $('#slider1,#slider2').slide(); $('.item').accordion(); }); </script> <?php //include_once "inc/footer.php";?>
kris120197/sklad
application/views/shop/template/b002.php
PHP
gpl-2.0
25,990
/* * Copyright (C) 2011-2021 Project SkyFire <https://www.projectskyfire.org/> * Copyright (C) 2008-2021 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2021 MaNGOS <https://www.getmangos.eu/> * Copyright (C) 2006-2014 ScriptDev2 <https://github.com/scriptdev2/scriptdev2/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "blackrock_spire.h" enum Spells { SPELL_CURSEOFBLOOD = 24673, SPELL_HEX = 16708, SPELL_CLEAVE = 20691, }; enum Events { EVENT_CURSE_OF_BLOOD = 1, EVENT_HEX = 2, EVENT_CLEAVE = 3, }; class boss_shadow_hunter_voshgajin : public CreatureScript { public: boss_shadow_hunter_voshgajin() : CreatureScript("boss_shadow_hunter_voshgajin") { } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new boss_shadowvoshAI(creature); } struct boss_shadowvoshAI : public BossAI { boss_shadowvoshAI(Creature* creature) : BossAI(creature, DATA_SHADOW_HUNTER_VOSHGAJIN) { } void Reset() OVERRIDE { _Reset(); //DoCast(me, SPELL_ICEARMOR, true); } void EnterCombat(Unit* /*who*/) OVERRIDE { _EnterCombat(); events.ScheduleEvent(EVENT_CURSE_OF_BLOOD, 2 * IN_MILLISECONDS); events.ScheduleEvent(EVENT_HEX, 8 * IN_MILLISECONDS); events.ScheduleEvent(EVENT_CLEAVE, 14 * IN_MILLISECONDS); } void JustDied(Unit* /*killer*/) OVERRIDE { _JustDied(); } void UpdateAI(uint32 diff) OVERRIDE { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_CURSE_OF_BLOOD: DoCastVictim(SPELL_CURSEOFBLOOD); events.ScheduleEvent(EVENT_CURSE_OF_BLOOD, 45 * IN_MILLISECONDS); break; case EVENT_HEX: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) DoCast(target, SPELL_HEX); events.ScheduleEvent(EVENT_HEX, 15 * IN_MILLISECONDS); break; case EVENT_CLEAVE: DoCastVictim(SPELL_CLEAVE); events.ScheduleEvent(EVENT_CLEAVE, 7 * IN_MILLISECONDS); break; } } DoMeleeAttackIfReady(); } }; }; void AddSC_boss_shadowvosh() { new boss_shadow_hunter_voshgajin(); }
ProjectSkyfire/SkyFire.548
src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_shadow_hunter_voshgajin.cpp
C++
gpl-2.0
3,515
/** * Copyright 2014 Red Hat, Inc. * * This software is licensed to you under the GNU General Public * License as published by the Free Software Foundation; either version * 2 of the License (GPLv2) or (at your option) any later version. * There is NO WARRANTY for this software, express or implied, * including the implied warranties of MERCHANTABILITY, * NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should * have received a copy of GPLv2 along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. **/ describe('Controller: ContentViewVersionsController', function() { var $scope beforeEach(module('Bastion.content-views', 'Bastion.test-mocks')); beforeEach(inject(function($injector) { var $controller = $injector.get('$controller'), ContentView = $injector.get('MockResource').$new(), translate = function (string) { return string; }; $scope = $injector.get('$rootScope').$new(); $scope.contentView = ContentView.get({id: 1}); $scope.reloadVersions = function () {}; $scope.taskTypes = { promotion: "promotion", publish: "publish" }; spyOn($scope, 'reloadVersions'); $controller('ContentViewVersionsController', { $scope: $scope, translate: translate }); })); it("puts an empty table object on the scope", function() { expect($scope.table).toBeDefined(); }); it("correctly hide a version's progress", function() { var version = {active_history: [], task: {state: 'running', progressbar: {type: 'success'}}}; expect($scope.hideProgress(version)).toBe(true); version = {active_history: [{}], task: {state: 'running', progressbar: {type: 'success'}}}; expect($scope.hideProgress(version)).toBe(false); version = {active_history: [], task: {state: 'stopped', progressbar: {type: 'success'}}}; expect($scope.hideProgress(version)).toBe(true); version = {active_history: [{}], task: {state: 'stopped', progressbar: {type: 'error'}}}; expect($scope.hideProgress(version)).toBe(false); }); it("determines what history text to display", function() { var version = {active_history: [], last_event: {environment: {name: 'test'}, task: {label: $scope.taskTypes.promotion} }}; expect($scope.historyText(version)).toBe("Promoted to test"); version.last_event.task.label = $scope.taskTypes.publish; expect($scope.historyText(version)).toBe("Published"); }); });
dustints/katello
engines/bastion/test/content-views/details/content-view-versions.controller.test.js
JavaScript
gpl-2.0
2,686
<?php /* ----------------------------------------------------------------- * $Id: create_pdf.php 1457 2015-04-21 09:38:44Z akausch $ * Copyright (c) 2011-2021 commerce:SEO by Webdesign Erfurt * http://www.commerce-seo.de * ------------------------------------------------------------------ * based on: * (c) 2000-2001 The Exchange Project (earlier name of osCommerce) * (c) 2002-2003 osCommerce - www.oscommerce.com * (c) 2003 nextcommerce - www.nextcommerce.org * (c) 2005 xt:Commerce - www.xt-commerce.com * Released under the GNU General Public License * --------------------------------------------------------------- */ defined("_VALID_XTC") or die("Direct access to this location isn't allowed."); require_once('includes/application_top.php'); define('FPDF_FONTPATH', DIR_FS_ADMIN . 'pdf/font/'); $pdf_query = xtc_db_query("SELECT pdf_key, pdf_value FROM orders_pdf_profile WHERE languages_id = '0';"); while ($pdf = xtc_db_fetch_array($pdf_query)) { define($pdf['pdf_key'], $pdf['pdf_value']); } require_once(DIR_FS_INC . 'xtc_get_order_data.inc.php'); require_once(DIR_FS_INC . 'xtc_get_attributes_model.inc.php'); require_once(DIR_FS_INC . 'xtc_not_null.inc.php'); require_once(DIR_FS_INC . 'xtc_format_price_order.inc.php'); include_once(DIR_WS_CLASSES . 'class.order.php'); $order = new order($_GET['oID']); $type = $_POST['type']; $type = $_GET['type']; $sprach_id = $_POST['pdf_language_id']; $sprache = $order->info['language']; require_once('pdf/pdf_bill.php'); $pdf = new PDF_Bill(); $pdf->Init(($type == 'rechnung' ? FILENAME_BILL : FILENAME_PACKINSLIP)); if (PDF_LIEFERSCHEIN) { $kundenadresse = xtc_address_format($order->customer['format_id'], $order->delivery, 1, '', '<br>'); } else { $kundenadresse = xtc_address_format($order->customer['format_id'], $order->billing, 1, '', '<br>'); } $pdf->Adresse(utf8_decode(str_replace("<br>", "\n", $kundenadresse)), TEXT_PDF_SHOPADRESSEKLEIN); $logo = DIR_FS_CATALOG . 'templates/' . CURRENT_TEMPLATE . '/img/' . LAYOUT_LOGO_FILE; if (file_exists($logo) && LAYOUT_LOGO_FILE != '') { $pdf->Logo($logo); } if (PDF_RECHNUNG_DATE_ACT == 'true' && $_POST['pdf_bill_versandzusatzdate'] == '') { $date_purchased = time(); $date_purchased = date("d.m.Y", $date_purchased); } elseif ($_POST['pdf_bill_versandzusatzdate'] == '') { $date_purchased = xtc_date_short($order->info['date_purchased']); } else { $date_purchased = $_POST['pdf_bill_versandzusatzdate']; } if ($order->info['payment_method'] != '' && $order->info['payment_method'] != 'no_payment') { include(DIR_FS_CATALOG . 'lang/' . $sprache . '/modules/payment/' . $order->info['payment_method'] . '.php'); $payment_method = constant(strtoupper('MODULE_PAYMENT_' . $order->info['payment_method'] . '_TEXT_TITLE')); $payment_method = strip_tags($payment_method); $payment_method = html_entity_decode($payment_method); $payment_method = utf8_decode($payment_method); } else { $payment_method = ''; } if (PDF_RECHNUNG_OID == 'true') { $pdf_re_id = (int) $_GET['oID']; } else { $pdf_re_id = $_POST['pdf_bill_nr']; } // Kunden ID abfragen $order_check = xtc_db_fetch_array(xtc_db_query("SELECT customers_id FROM " . TABLE_ORDERS . " WHERE orders_id = '" . (int) $_GET['oID'] . "' LIMIT 1;")); $customer_gender = xtc_db_fetch_array(xtc_db_query("SELECT customers_gender FROM " . TABLE_CUSTOMERS . " WHERE customers_id = '" . (int) $order_check['customers_id'] . "' LIMIT 1;")); $pdf->Rechnungsdaten($order->customer['csID'], $_GET['oID'], $order->customer['vat_id'], $pdf_re_id, $date_purchased, $payment_method, PDF_LIEFERSCHEIN); $pdf->RechnungStart($pdf_re_id, $_GET['oID'], utf8_decode($order->customer['lastname']), $customer_gender['customers_gender'], PDF_LIEFERSCHEIN); $pdf->ListeKopf(PDF_LIEFERSCHEIN); // Produktinfos $order_query = xtc_db_query("SELECT * FROM " . TABLE_ORDERS_PRODUCTS . " WHERE orders_id='" . (int) $_GET['oID'] . "'"); $order_data = array(); // Ausgabe der Produkte while ($order_data_values = xtc_db_fetch_array($order_query)) { $attributes_query = xtc_db_query("SELECT * FROM " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " WHERE orders_products_id='" . $order_data_values['orders_products_id'] . "' ORDER BY orders_products_attributes_id ASC"); $attributes_data = ''; $attributes_model = ''; while ($attributes_data_values = xtc_db_fetch_array($attributes_query)) { $attributes_data .= $attributes_data_values['products_options'] . ': ' . $attributes_data_values['products_options_values'] . "\n"; $attributes_model .= xtc_get_attributes_model($order_data_values['products_id'], $attributes_data_values['products_options_values'], $attributes_data_values['products_options']) . "\n"; } $orderinfosingleprice = str_replace('€', 'EUR', xtc_format_price_order($order_data_values['products_price'], 1, $order->info['currency'])); $orderinfosingleprice = str_replace('&euro;', 'EUR', $orderinfosingleprice); $orderinfosumleprice = str_replace('€', 'EUR', xtc_format_price_order($order_data_values['final_price'], 1, $order->info['currency'])); $orderinfosumleprice = str_replace('&euro;', 'EUR', $orderinfosumleprice); $orderinfocurreny = str_replace('&euro;', 'EUR', $orderinfocurreny); $pdf->ListeProduktHinzu($order_data_values['products_quantity'], utf8_decode(strip_tags($order_data_values['products_name'])), utf8_decode(trim($attributes_data)), $order_data_values['products_model'], trim($attributes_model, $type), $orderinfosingleprice, $orderinfosumleprice, $type); } if (!PDF_LIEFERSCHEIN) { $oder_total_query = xtc_db_query("SELECT title, text, class, value, sort_order FROM " . TABLE_ORDERS_TOTAL . " WHERE orders_id='" . $_GET['oID'] . "' ORDER BY sort_order ASC"); $order_data = array(); while ($oder_total_values = xtc_db_fetch_array($oder_total_query)) { $ordervaluetext = str_replace('€', 'EUR', $oder_total_values['text']); $ordervaluetext = str_replace('&euro;', 'EUR', $ordervaluetext); $order_data[] = array('title' => utf8_decode(html_entity_decode($oder_total_values['title'])), 'class' => $oder_total_values['class'], 'value' => $oder_total_values['value'], 'text' => $ordervaluetext); } $pdf->Betrag($order_data, PDF_LIEFERSCHEIN); } /** BEGIN BILLPAY CHANGED * */ if ($order->info['payment_method'] == 'billpay' || $order->info['payment_method'] == 'billpaydebit' || $order->info['payment_method'] == 'billpaytransactioncredit') { require_once(DIR_FS_CATALOG . DIR_WS_INCLUDES . '/billpay/utils/billpay_display_pdf_data.php'); } /** EOF BILLPAY CHANGED * */ $pdf->RechnungEnde($order->customer['vat_id'], $order->info['shipping_method'], PDF_LIEFERSCHEIN); if ($_POST['pdf_bill_versandzusatz'] != '') { $pdf_zusatz = strip_tags($_POST['pdf_bill_versandzusatz']); $pdf->Kommentar($pdf_zusatz, $order->info['shipping_method'], PDF_LIEFERSCHEIN); } elseif (MODULE_CUSTOMERS_PDF_INVOICE_PRINT_COMMENT == 'true') { $pdf->Kommentar($order->info['comments'], $order->info['shipping_method'], PDF_LIEFERSCHEIN); } if ($order->info['payment_method'] == 'invoice' || $order->info['payment_method'] == 'moneyorder') { $invoiceinfo = TEXT_PDF_INVOICE_TEXT; $pdf->Invoice($invoiceinfo); } $lieferadresse = xtc_address_format($order->customer['format_id'], $order->delivery, 1, '', ', '); $pdf->LieferAdresse(utf8_decode($lieferadresse)); if (!PDF_LIEFERSCHEIN) { $pdf_name = cseo_get_pdf($_POST['oID'], true) . '.pdf'; $pdf->Output($pdf_name, 'F'); $check_pdf = xtc_db_query("SELECT bill_name FROM orders_pdf WHERE order_id = '" . $_POST['oID'] . "'"); if (xtc_db_num_rows($check_pdf, true) > 1) { xtc_db_query("UPDATE orders_pdf SET bill_name = '" . $pdf_name . "', pdf_bill_nr = '" . $pdf_re_id . "', pdf_generate_date = NOW() WHERE order_id = '" . $_POST['oID'] . "' "); } else { xtc_db_query("INSERT INTO orders_pdf (order_id, bill_name, pdf_bill_nr, pdf_generate_date) VALUES ('" . $_POST['oID'] . "', '" . $pdf_name . "', '" . $pdf_re_id . "', NOW());"); } $_SESSION['msg']['gp'] = '<div id="success_msg">' . SUCCESS_ORDER_GENEREATE . '</div>'; if ($_POST['pdf_rechnung_senden'] != '1') { xtc_redirect(xtc_href_link(FILENAME_ORDERS, 'page=' . $_POST['page'] . '&action=edit&oID=' . $_POST['oID'] . '#pdf')); } } else { $pdf_name = cseo_get_pdf_delivery($_POST['oID'], true) . '.pdf'; $pdf->Output($pdf_name, 'F'); $check_pdf = xtc_db_query("SELECT delivery_name FROM orders_pdf_delivery WHERE order_id = '" . $_POST['oID'] . "'"); if (xtc_db_num_rows($check_pdf, true) > 1) { xtc_db_query("UPDATE orders_pdf_delivery SET delivery_name = '" . $pdf_name . "', pdf_delivery_nr = '" . $pdf_re_id . "', pdf_generate_date = NOW() WHERE order_id = '" . $_POST['oID'] . "' "); } else { xtc_db_query("INSERT INTO orders_pdf_delivery (order_id, delivery_name, pdf_delivery_nr, pdf_generate_date) VALUES ('" . $_POST['oID'] . "', '" . $pdf_name . "', '" . $pdf_re_id . "', NOW());"); } $_SESSION['msg']['gp'] = '<div id="success_msg">' . SUCCESS_ORDER_GENEREATE . '</div>'; }
commerceseo/v2next
admin/create_pdf.php
PHP
gpl-2.0
9,473
/****************************************************************************** * * This file is part of canu, a software program that assembles whole-genome * sequencing reads into contigs. * * This software is based on: * 'Celera Assembler' (http://wgs-assembler.sourceforge.net) * the 'kmer package' (http://kmer.sourceforge.net) * both originally distributed by Applera Corporation under the GNU General * Public License, version 2. * * Canu branched from Celera Assembler at its revision 4587. * Canu branched from the kmer project at its revision 1994. * * This file is derived from: * * kmer/libutil/splitToWords.H * * Modifications by: * * Brian P. Walenz from 2005-JUL-12 to 2014-APR-11 * are Copyright 2005-2006,2012,2014 J. Craig Venter Institute, and * are subject to the GNU General Public License version 2 * * Brian P. Walenz from 2014-DEC-05 to 2015-AUG-11 * are Copyright 2014-2015 Battelle National Biodefense Institute, and * are subject to the BSD 3-Clause License * * Brian P. Walenz beginning on 2016-FEB-25 * are a 'United States Government Work', and * are released in the public domain * * File 'README.licenses' in the root directory of this distribution contains * full conditions and disclaimers for each license. */ #ifndef SPLITTOWORDS_H #define SPLITTOWORDS_H class splitToWords { public: splitToWords() { _argWords = 0; _maxWords = 0; _arg = 0L; _maxChars = 0; _cmd = 0L; }; splitToWords(char *cmd) { _argWords = 0; _maxWords = 0; _arg = 0L; _maxChars = 0; _cmd = 0L; split(cmd); }; ~splitToWords() { delete [] _cmd; delete [] _arg; }; void split(char *cmd) { // Step Zero: // // Count the length of the string, in words and in characters. // For simplicity, we overcount words, by just counting white-space. // // Then, allocate space for a temporary copy of the string, and a // set of pointers into the temporary copy (much like argv). // uint32 cmdChars = 1; // 1 == Space for terminating 0 uint32 cmdWords = 2; // 2 == Space for first word and terminating 0L for (char *tmp=cmd; *tmp; tmp++) { cmdWords += (*tmp == ' ') ? 1 : 0; cmdWords += (*tmp == '\t') ? 1 : 0; cmdChars++; } if (cmdChars > _maxChars) { delete [] _cmd; _cmd = new char [cmdChars]; _maxChars = cmdChars; } if (cmdWords > _maxWords) { delete [] _arg; _arg = new char * [cmdWords]; _maxWords = cmdWords; } _argWords = 0; // Step One: // // Determine where the words are in the command string, copying the // string to _cmd and storing words in _arg. // bool isFirst = true; char *cmdI = cmd; char *cmdO = _cmd; while (*cmdI) { // If we are at a non-space character, we are in a word. If // this is the first character in the word, save the word in // the args list. // // Otherwise we are at a space and thus not in a word. Make // all spaces be string terminators, and declare that we are // at the start of a word. // if ((*cmdI != ' ') && (*cmdI != '\t') && (*cmdI != '\n') && (*cmdI != '\r')) { *cmdO = *cmdI; if (isFirst) { _arg[_argWords++] = cmdO; isFirst = false; } } else { *cmdO = 0; isFirst = true; } cmdI++; cmdO++; } // Finish off the list by terminating the last arg, and // terminating the list of args. // *cmdO = 0; _arg[_argWords] = 0L; }; uint32 numWords(void) { return(_argWords); }; char *getWord(uint32 i) { return(_arg[i]); }; char *operator[](uint32 i) { return(_arg[i]); }; int64 operator()(uint32 i) { return(strtoull(_arg[i], NULL, 10)); }; private: uint32 _argWords; uint32 _maxWords; char **_arg; uint32 _maxChars; char *_cmd; }; #endif // SPLITTOWORDS_H
sgblanch/canu
src/AS_UTL/splitToWords.H
C++
gpl-2.0
4,157
<?php /** * @package fairy * the default content for monniya style */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> <div class="post-meta"> <?php setPostViews(get_the_ID()); fairy_posted_on(); ?> </div><!-- .entry-meta --> </header><!-- .entry-header --> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'fairy' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <?php fairy_entry_footer(); ?> </footer><!-- .entry-footer --> </article><!-- #post-## -->
monniya/wordpress
wp-content/themes/fairy/content-single.php
PHP
gpl-2.0
734
using System.Data; using System.Linq; namespace Travelling.DataLayer.DatabaseTypes { public class SqlServerCEDatabaseType : DatabaseType { public override string BuildPageQuery(long skip, long take, PagingHelper.SQLParts parts, ref object[] args) { var sqlPage = string.Format("{0}\nOFFSET @{1} ROWS FETCH NEXT @{2} ROWS ONLY", parts.sql, args.Length, args.Length + 1); args = args.Concat(new object[] { skip, take }).ToArray(); return sqlPage; } public override object ExecuteInsert<T>(Database db, IDbCommand cmd, string primaryKeyName, T poco, object[] args) { db.ExecuteNonQueryHelper(cmd); return db.ExecuteScalar<object>("SELECT @@@IDENTITY AS NewID;"); } public override IsolationLevel GetDefaultTransactionIsolationLevel() { return IsolationLevel.ReadCommitted; } public override string GetProviderName() { return "System.Data.SqlServerCe.4.0"; } } }
binlyzhuo/travelling
src/Travelling.DataLayer/DatabaseTypes/SqlServerCEDatabaseType.cs
C#
gpl-2.0
1,054
using System; using System.Collections.Generic; using System.Text; using System.Linq; using AKMII.DMRA.Common; using AKMII.DMRA.DataAccess; using AKMII.DMRA.Business.Rule; namespace AKMII.DMRA.Business.Management { public class OrderManager { private OrderAccessor orderAccessor; private ZipAccessor zipAccessor; public OrderManager() { orderAccessor = new OrderAccessor(); zipAccessor = new ZipAccessor(); } public bool InsertOrderRepeatRemark(string mdnumber, int month, int year, int zipId, string reason) { bool result = false; try { result = orderAccessor.AddOrderRepeatRemark(mdnumber, month, year, zipId, reason); } catch (Exception ex) { Logger.Error("Exception occurs in add order repeat remark", ex); } return result; } public bool ManageOrder(Order order) { bool result = false; try { result = orderAccessor.AddOrder(order.Id, order.AccountId, order.PeroidYear, order.PeroidMonth, ConstructZipIdString(order.Zips)); } catch (Exception ex) { Logger.Error("Exception occurs in manage order", ex); } return result; } public bool ManageOrder(Order order, string agentName, int week) { bool result1 = false; bool result2 = false; try { string assignment = week.ToString() + " " + agentName; result1 = orderAccessor.AddOrderNew(order.Id, order.AccountId, order.PeroidYear, order.PeroidMonth, ConstructZipIdString(order.Zips.Where(c => string.IsNullOrEmpty(c.UserAssigned) || c.UserAssigned == assignment).ToList<LeadBlock>()), assignment); result2 = zipAccessor.UpdateZipAssigned(assignment, ConstructMapZipIdString(order.Zips.Where(c => string.IsNullOrEmpty(c.UserAssigned) || c.UserAssigned == assignment).ToList<LeadBlock>()), order.PeroidMonth, order.PeroidYear, (order.PeroidMonth == CurrentPeriod.Month && order.PeroidYear == CurrentPeriod.Year)); } catch (Exception ex) { Logger.Error("Exception occurs in manage order by agent and week", ex); } return result1 && result2; } public bool ManageOrder(Order order, int operationType) { bool result = false; try { if (operationType == 0) { result = orderAccessor.AddMapOrder(order.Id, order.AccountId, order.PeroidYear, order.PeroidMonth, ConstructMapZipIdString(order.Zips)); } else if (operationType == 1) { result = orderAccessor.DeleteMapOrder(order.Id, order.AccountId, order.PeroidYear, order.PeroidMonth, ConstructMapZipIdString(order.Zips)); } else { //Noting to do } } catch (Exception ex) { Logger.Error("Exception occurs in manage map order", ex); } return result; } public bool ManageOrder(Order order, int operationType, string agentName, int week) { bool result1 = false; bool result2 = false; try { if (operationType == 0) { result1 = orderAccessor.AddMapOrder(order.Id, order.AccountId, order.PeroidYear, order.PeroidMonth, ConstructMapZipIdString(order.Zips)); result2 = zipAccessor.UpdateZipAssigned(week.ToString() + " " + agentName, ConstructMapZipIdString(order.Zips.Where(c => string.IsNullOrEmpty(c.UserAssigned)).ToList<LeadBlock>()), order.PeroidMonth, order.PeroidYear, (order.PeroidMonth == CurrentPeriod.Month && order.PeroidYear == CurrentPeriod.Year)); } else if (operationType == 1) { result1 = orderAccessor.DeleteMapOrder(order.Id, order.AccountId, order.PeroidYear, order.PeroidMonth, ConstructMapZipIdString(order.Zips)); result2 = zipAccessor.UpdateZipAssigned(null, ConstructMapZipIdString(order.Zips), order.PeroidMonth, order.PeroidYear, (order.PeroidMonth == CurrentPeriod.Month && order.PeroidYear == CurrentPeriod.Year)); } else { //Noting to do } } catch (Exception ex) { Logger.Error("Exception occurs in manage map order", ex); } return result1 && result2; } public bool ManageOrder(Order order, int operationType, string zipName) { bool result = false; try { order.Zips = zipAccessor.GetLeadBlock(zipName); if (operationType == 0) { result = orderAccessor.AddMapOrder(order.Id, order.AccountId, order.PeroidYear, order.PeroidMonth, ConstructMapZipIdString(order.Zips)); } else if (operationType == 1) { result = orderAccessor.DeleteMapOrder(order.Id, order.AccountId, order.PeroidYear, order.PeroidMonth, ConstructMapZipIdString(order.Zips)); } else { //Noting to do } } catch (Exception ex) { Logger.Error("Exception occurs in manage map order for zip code", ex); } return result; } public List<LeadBlock> GetOrderHistory(string AccountID, int Year, int Month) { List<LeadBlock> zips = null; try { zips=orderAccessor.GetOrderHistory(AccountID, Year, Month); } catch (Exception ex) { Logger.Error("Exception occous in GetOrderHistory", ex); } return zips; } public bool PurchaseOrder(int orderId) { bool result = false; try { result = orderAccessor.UpdateOrderStatus(orderId); } catch (Exception ex) { Logger.Error("Exception occurs in purchase order", ex); } return result; } public bool PurchaseOrder(int orderId, int PurchasedStatus) { bool result = false; try { result = orderAccessor.UpdateOrderStatus(orderId,PurchasedStatus); } catch (Exception ex) { Logger.Error("Exception occurs in purchase order", ex); } return result; } public Order GetOrder(string userId, int month, int year) { Order order = null; try { order = orderAccessor.GetOrderByIdAndDate(userId, month, year); if (order != null) { order.Zips = zipAccessor.GetLeadBlock(userId, month, year, 1); } } catch (Exception ex) { Logger.Error("Exception occurs in get order", ex); } return order; } private string ConstructMapZipIdString(List<LeadBlock> zips) { StringBuilder allZipIds = new StringBuilder(string.Empty); if (zips != null && zips.Count > 0) { for (int i = 0; i < zips.Count; i++) { allZipIds.Append(zips[i].ZipId.ToString()); if (i != (zips.Count - 1)) { allZipIds.Append(','); } } } return allZipIds.ToString(); } private string ConstructZipIdString(List<LeadBlock> zips) { StringBuilder allZipIds = new StringBuilder(string.Empty); if (zips != null && zips.Count > 0) { for (int i = 0; i < zips.Count; i++) { allZipIds.Append(zips[i].ZipId.ToString() + ";" + Convert.ToInt32(zips[i].Type).ToString()); if (i != (zips.Count - 1)) { allZipIds.Append(','); } } } return allZipIds.ToString(); } } }
limao4223127/NCR_Pay
Agent Lead Spanish/AKMII.DMRA.Business/Management/OrderManager.cs
C#
gpl-2.0
9,471
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package com.github.smeny.jpc.emulator.execution.opcodes.pm; import com.github.smeny.jpc.emulator.execution.*; import com.github.smeny.jpc.emulator.execution.decoder.*; import com.github.smeny.jpc.emulator.processor.*; import com.github.smeny.jpc.emulator.processor.fpu64.*; import static com.github.smeny.jpc.emulator.processor.Processor.*; public class fsub_ST5_ST1 extends Executable { public fsub_ST5_ST1(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); } public Branch execute(Processor cpu) { double freg0 = cpu.fpu.ST(5); double freg1 = cpu.fpu.ST(1); if ((freg0 == Double.NEGATIVE_INFINITY && freg1 == Double.NEGATIVE_INFINITY) || (freg0 == Double.POSITIVE_INFINITY && freg1 == Double.POSITIVE_INFINITY)) cpu.fpu.setInvalidOperation(); cpu.fpu.setST(5, freg0-freg1); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
smeny/JPC
src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/pm/fsub_ST5_ST1.java
Java
gpl-2.0
2,064
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_GKEHub_SetIamPolicyRequest extends Google_Model { protected $policyType = 'Google_Service_GKEHub_Policy'; protected $policyDataType = ''; public $updateMask; /** * @param Google_Service_GKEHub_Policy */ public function setPolicy(Google_Service_GKEHub_Policy $policy) { $this->policy = $policy; } /** * @return Google_Service_GKEHub_Policy */ public function getPolicy() { return $this->policy; } public function setUpdateMask($updateMask) { $this->updateMask = $updateMask; } public function getUpdateMask() { return $this->updateMask; } }
palasthotel/grid-wordpress-box-social
vendor/google/apiclient-services/src/Google/Service/GKEHub/SetIamPolicyRequest.php
PHP
gpl-2.0
1,222
package com.survivorserver.Dasfaust.WebMarket.mojang.http; public class HttpBody { private String bodyString; public HttpBody(String bodyString) { this.bodyString = bodyString; } public byte[] getBytes() { return bodyString != null ? bodyString.getBytes() : new byte[0]; } }
Dasfaust/WebMarket
src/main/java/com/survivorserver/Dasfaust/WebMarket/mojang/http/HttpBody.java
Java
gpl-2.0
316
<?php namespace Akeeba\Engine\Postproc\Connector\Amazon\Guzzle\Service\Description; use Akeeba\Engine\Postproc\Connector\Amazon\Guzzle\Common\ToArrayInterface; /** * Interface defining data objects that hold the information of an API operation */ interface OperationInterface extends ToArrayInterface { const TYPE_PRIMITIVE = 'primitive'; const TYPE_CLASS = 'class'; const TYPE_DOCUMENTATION = 'documentation'; const TYPE_MODEL = 'model'; /** * Get the service description that the operation belongs to * * @return ServiceDescriptionInterface|null */ public function getServiceDescription(); /** * Set the service description that the operation belongs to * * @param ServiceDescriptionInterface $description Service description * * @return self */ public function setServiceDescription(ServiceDescriptionInterface $description); /** * Get the params of the operation * * @return array */ public function getParams(); /** * Returns an array of parameter names * * @return array */ public function getParamNames(); /** * Check if the operation has a specific parameter by name * * @param string $name Name of the param * * @return bool */ public function hasParam($name); /** * Get a single parameter of the operation * * @param string $param Parameter to retrieve by name * * @return Parameter|null */ public function getParam($param); /** * Get the HTTP method of the operation * * @return string|null */ public function getHttpMethod(); /** * Get the concrete operation class that implements this operation * * @return string */ public function getClass(); /** * Get the name of the operation * * @return string|null */ public function getName(); /** * Get a short summary of what the operation does * * @return string|null */ public function getSummary(); /** * Get a longer text field to explain the behavior of the operation * * @return string|null */ public function getNotes(); /** * Get the documentation URL of the operation * * @return string|null */ public function getDocumentationUrl(); /** * Get what is returned from the method. Can be a primitive, class name, or model. For example, the responseClass * could be 'array', which would inherently use a responseType of 'primitive'. Using a class name would set a * responseType of 'class'. Specifying a model by ID will use a responseType of 'model'. * * @return string|null */ public function getResponseClass(); /** * Get information about how the response is unmarshalled: One of 'primitive', 'class', 'model', or 'documentation' * * @return string */ public function getResponseType(); /** * Get notes about the response of the operation * * @return string|null */ public function getResponseNotes(); /** * Get whether or not the operation is deprecated * * @return bool */ public function getDeprecated(); /** * Get the URI that will be merged into the generated request * * @return string */ public function getUri(); /** * Get the errors that could be encountered when executing the operation * * @return array */ public function getErrorResponses(); /** * Get extra data from the operation * * @param string $name Name of the data point to retrieve * * @return mixed|null */ public function getData($name); }
jug-berlin/joomla.berlin
administrator/components/com_akeeba/engine/Postproc/Connector/Amazon/Guzzle/Service/Description/OperationInterface.php
PHP
gpl-2.0
3,801
using System; using System.Drawing; using Sdl.Desktop.IntegrationApi.Interfaces; namespace Sdl.Community.InSource.Notifications { public class InSourceCommand : IStudioNotificationCommand { private readonly Action action; public event EventHandler CanExecuteChanged; public InSourceCommand(Action action) { this.action = action; } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { action(); } public string CommandText { get; set; } public string CommandToolTip { get; set; } public Icon CommandIcon { get; set; } } }
sdl/Sdl-Community
InSource/Notifications/InSourceCommand.cs
C#
gpl-2.0
614
<?php namespace PoradnikPiwny\Entities\Proxies\__CG__\PoradnikPiwny\Entities; /** * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE. */ class BeerSearchConnection extends \PoradnikPiwny\Entities\BeerSearchConnection implements \Doctrine\ORM\Proxy\Proxy { private $_entityPersister; private $_identifier; public $__isInitialized__ = false; public function __construct($entityPersister, $identifier) { $this->_entityPersister = $entityPersister; $this->_identifier = $identifier; } /** @private */ public function __load() { if (!$this->__isInitialized__ && $this->_entityPersister) { $this->__isInitialized__ = true; if (method_exists($this, "__wakeup")) { // call this after __isInitialized__to avoid infinite recursion // but before loading to emulate what ClassMetadata::newInstance() // provides. $this->__wakeup(); } if ($this->_entityPersister->load($this->_identifier, $this) === null) { throw new \Doctrine\ORM\EntityNotFoundException(); } unset($this->_entityPersister, $this->_identifier); } } /** @private */ public function __isInitialized() { return $this->__isInitialized__; } public function getId() { if ($this->__isInitialized__ === false) { return (int) $this->_identifier["id"]; } $this->__load(); return parent::getId(); } public function setId($id) { $this->__load(); return parent::setId($id); } public function getBeerSearch() { $this->__load(); return parent::getBeerSearch(); } public function setBeerSearch($beerSearch) { $this->__load(); return parent::setBeerSearch($beerSearch); } public function getBeer() { $this->__load(); return parent::getBeer(); } public function setBeer($beer) { $this->__load(); return parent::setBeer($beer); } public function __sleep() { return array('__isInitialized__', 'id', 'beerSearch', 'beer'); } public function __clone() { if (!$this->__isInitialized__ && $this->_entityPersister) { $this->__isInitialized__ = true; $class = $this->_entityPersister->getClassMetadata(); $original = $this->_entityPersister->load($this->_identifier); if ($original === null) { throw new \Doctrine\ORM\EntityNotFoundException(); } foreach ($class->reflFields as $field => $reflProperty) { $reflProperty->setValue($this, $reflProperty->getValue($original)); } unset($this->_entityPersister, $this->_identifier); } } }
deallas/PoradnikPiwny
library/PoradnikPiwny/Entities/Proxies/__CG__PoradnikPiwnyEntitiesBeerSearchConnection.php
PHP
gpl-2.0
2,930
<script type="text/javascript" src=" http://api.sandbox.premium-itc.com/js/pitc.wapi.js"></script> <script language="javascript"> /*var pitc; // Build pitc only once: may be included in both parent and child pages (function ($) { if (pitc === undefined) { pitc = {}; pitc.wapi = {}; pitc.wapi.useXdr = false; pitc.wapi.xdrDelay = 500; // ms pitc.wapi.get = function (url, onSuccess) { // Source: http://classically.me/blogs/cross-domain-ajax-requests-jquery-and-xdomainrequest (modified) if (pitc.wapi.useXdr && $.browser.msie && (parseInt($.browser.version, 10) === 7 || parseInt($.browser.version, 10) === 8 || parseInt($.browser.version, 10) === 9)) { if (window.XDomainRequest) { var xdr = new XDomainRequest(); if (xdr) { xdr.onload = function () { if (onSuccess) { onSuccess(this.responseText); } }; // Define all handlers to prevent request abortion // Source: http://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment xdr.onerror = function () { }; xdr.ontimeout = function () { }; xdr.onprogress = function () { }; xdr.timeout = 0; xdr.open('GET', url); // Do not unwrap .send method. Required to run on a separate thread. // Source: http://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment setTimeout(function () { xdr.send(); }, pitc.wapi.xdrDelay); // Don't go into jQuery fallback (see below) return; } } } // Fallback: use jquery for IE10 and other browsers // AND anything that fails within IE7 8 9 specific processing $.get(url, onSuccess, "text"); }; pitc.wapi.widgets = {}; pitc.wapi.loadWidget = function (element, url) { if (element in pitc.wapi.widgets) { pitc.wapi.widgets[element].load(url); return; } var widget = {}; widget.element = element; widget.url = url; widget.previous = ""; widget.display = ""; widget.load = function (url) { widget.previous = widget.url; widget.url = url; // Append extra technical parameters var addWidget = url.indexOf("wapiw") < 0; var addDisplay = url.indexOf("wapid") < 0 && widget.display != ''; if (addWidget) { if (url.indexOf('?') >= 0) { url += "&"; } else { url += "?"; } url += "wapiw=" + encodeURIComponent(widget.element); } if (addDisplay) { if (url.indexOf('?') >= 0) { url += "&"; } else { url += "?"; } url += "wapid=" + encodeURIComponent(widget.display); } pitc.wapi.get(url, function (data) { $(widget.element).html(data); }); }; widget.back = function () { if (widget.previous != "") { widget.load(widget.previous); widget.previous = ""; } }; pitc.wapi.widgets[element] = widget; widget.load(url); return widget; }; pitc.wapi.getWidget = function (element) { if (element in pitc.wapi.widgets) { return pitc.wapi.widgets[element]; } else { // Build fake widget that act as main window var widget = {}; widget.element = element; widget.url = ""; widget.previous = ""; widget.display = ""; widget.load = function (url) { window.location = url; }; widget.back = function () { window.history.back(); }; return widget; } }; pitc.wapi.loadXml = function (element, url) { pitc.wapi.get(url, function (data) { $(element).text(data); // prettyPrint(); }); }; pitc.wapi.loadJson = function (element, url) { pitc.wapi.get(url, function (data) { $(element).text(data); // prettyPrint(); }); }; pitc.wapi.loadJsonp = function (element, url) { $.getJSON(url + "?callback=?", function (data) { $(element).text(JSON.stringify(data, null, " ")); }); }; } })(jQuery);*/ </script> <script language="javascript"> jQuery(document).ready(function ($) { //pitc.wapi.loadWidget('#widget', 'http://api.sandbox.premium-itc.com/api/pitc.ccn/list/widget/bix5bb1py3'); pitc.wapi.loadWidget('#widget', 'http://api.sandbox.premium-itc.com/api/pitc.ccn/get/widget/bix5bb1py3<?php echo '?id='.$idcc_full.'&type='.$type.'&wapiw='.$wapiw; ?>'); }); </script> <div id="widget"> </div>
Hellrikh/test
wp-content/plugins/tarificateur/templates/tarificateur-show-ccn-prevoyance.php
PHP
gpl-2.0
6,136
<?php /* core/themes/classy/templates/block/block.html.twig */ class __TwigTemplate_bfe7de7029fe23539e40b1b3d2a1fb03458b678ab1f31a91b772626576939d2c extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( 'content' => array($this, 'block_content'), ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array("set" => 29, "if" => 37, "block" => 41); $filters = array("clean_class" => 31); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array('set', 'if', 'block'), array('clean_class'), array() ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 29 $context["classes"] = array(0 => "block", 1 => ("block-" . \Drupal\Component\Utility\Html::getClass($this->getAttribute( // line 31 (isset($context["configuration"]) ? $context["configuration"] : null), "provider", array()))), 2 => ("block-" . \Drupal\Component\Utility\Html::getClass( // line 32 (isset($context["plugin_id"]) ? $context["plugin_id"] : null)))); // line 35 echo "<div"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (isset($context["classes"]) ? $context["classes"] : null)), "method"), "html", null, true)); echo "> "; // line 36 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["title_prefix"]) ? $context["title_prefix"] : null), "html", null, true)); echo " "; // line 37 if ((isset($context["label"]) ? $context["label"] : null)) { // line 38 echo " <h2"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["title_attributes"]) ? $context["title_attributes"] : null), "html", null, true)); echo ">"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["label"]) ? $context["label"] : null), "html", null, true)); echo "</h2> "; } // line 40 echo " "; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["title_suffix"]) ? $context["title_suffix"] : null), "html", null, true)); echo " "; // line 41 $this->displayBlock('content', $context, $blocks); // line 44 echo "</div> "; } // line 41 public function block_content($context, array $blocks = array()) { // line 42 echo " "; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["content"]) ? $context["content"] : null), "html", null, true)); echo " "; } public function getTemplateName() { return "core/themes/classy/templates/block/block.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 82 => 42, 79 => 41, 74 => 44, 72 => 41, 67 => 40, 59 => 38, 57 => 37, 53 => 36, 48 => 35, 46 => 32, 45 => 31, 44 => 29,); } public function getSource() { return "{# /** * @file * Theme override to display a block. * * Available variables: * - plugin_id: The ID of the block implementation. * - label: The configured label of the block if visible. * - configuration: A list of the block's configuration values. * - label: The configured label for the block. * - label_display: The display settings for the label. * - provider: The module or other provider that provided this block plugin. * - Block plugin specific settings will also be stored here. * - content: The content of this block. * - attributes: array of HTML attributes populated by modules, intended to * be added to the main container tag of this template. * - id: A valid HTML ID and guaranteed unique. * - title_attributes: Same as attributes, except applied to the main title * tag that appears in the template. * - title_prefix: Additional output populated by modules, intended to be * displayed in front of the main title tag that appears in the template. * - title_suffix: Additional output populated by modules, intended to be * displayed after the main title tag that appears in the template. * * @see template_preprocess_block() */ #} {% set classes = [ 'block', 'block-' ~ configuration.provider|clean_class, 'block-' ~ plugin_id|clean_class, ] %} <div{{ attributes.addClass(classes) }}> {{ title_prefix }} {% if label %} <h2{{ title_attributes }}>{{ label }}</h2> {% endif %} {{ title_suffix }} {% block content %} {{ content }} {% endblock %} </div> "; } }
ijisthee/dr8_c1_prd
sites/default/files/php/twig/5950fd5a54b19_block.html.twig_IN1I9oXrcwZUfj1L4CZRKjtGc/e-KEHTy1bHxjQyEJEUjjaTyko65jzTOpXNmtkgttEp0.php
PHP
gpl-2.0
6,068
<?php /** * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * * @author Myeongjin <aranet100@gmail.com> */ $lang['menu'] = '주간 사용자 로그인/로그아웃'; $lang['date'] = '날짜'; $lang['ip'] = 'IP 주소'; $lang['action'] = '행동'; $lang['range'] = '보여줄 날짜 범위:'; $lang['off'] = '로그아웃됨'; $lang['in'] = '영구적으로 로그인됨'; $lang['tin'] = '일시적으로 로그인됨'; $lang['fail'] = '실패한 로그인 시도';
ofsole/dokuwiki
lib/plugins/loglog/lang/ko/lang.php
PHP
gpl-2.0
636
# -*- coding: utf-8 -*- """ uds.warnings ~~~~~~~~~~~~ :copyright: Copyright (c) 2015, National Institute of Information and Communications Technology.All rights reserved. :license: GPL2, see LICENSE for more details. """ import warnings def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. :param func: :return: new_func """ def new_func(*args, **kwargs): warnings.warn("Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning) return func(*args, **kwargs) new_func.__name__ = func.__name__ new_func.__doc__ = func.__doc__ new_func.__dict__.update(func.__dict__) return new_func # Examples of use @deprecated def some_old_function(x, y): return x + y class SomeClass: @deprecated def some_old_method(self, x, y): return x + y
nict-isp/uds-sdk
uds/warnings.py
Python
gpl-2.0
979
/* Copyright (C) 2022, Specify Collections Consortium * * Specify Collections Consortium, Biodiversity Institute, University of Kansas, * 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA, support@specifysoftware.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package edu.ku.brc.specify.tools.schemalocale; import static edu.ku.brc.ui.UIRegistry.getResourceString; import java.awt.BorderLayout; import java.awt.Dialog; import java.awt.Frame; import java.awt.HeadlessException; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.*; import edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterIFace; import edu.ku.brc.specify.conversion.BasicSQLUtils; import edu.ku.brc.specify.datamodel.*; import edu.ku.brc.specify.datamodel.Collection; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.Session; import edu.ku.brc.af.core.AppContextMgr; import edu.ku.brc.af.core.SchemaI18NService; import edu.ku.brc.af.core.db.DBTableIdMgr; import edu.ku.brc.af.core.expresssearch.QueryAdjusterForDomain; import edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatMgr; import edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterMgr; import edu.ku.brc.af.ui.weblink.WebLinkMgr; import edu.ku.brc.dbsupport.DBConnection; import edu.ku.brc.dbsupport.DataProviderFactory; import edu.ku.brc.dbsupport.DataProviderSessionIFace; import edu.ku.brc.dbsupport.HibernateUtil; import edu.ku.brc.helpers.SwingWorker; import edu.ku.brc.specify.config.SpecifyAppContextMgr; import edu.ku.brc.specify.config.SpecifyWebLinkMgr; import edu.ku.brc.ui.CommandAction; import edu.ku.brc.ui.CommandDispatcher; import edu.ku.brc.ui.CustomDialog; import edu.ku.brc.ui.ToggleButtonChooserDlg; import edu.ku.brc.ui.ToggleButtonChooserPanel; import edu.ku.brc.ui.UIRegistry; import edu.ku.brc.ui.dnd.SimpleGlassPane; import javax.persistence.Basic; /** * @author rods * * @code_status Alpha * * Created Date: Sep 27, 2007 * */ public class SchemaLocalizerDlg extends CustomDialog implements LocalizableIOIFace, PropertyChangeListener { private static final Logger log = Logger.getLogger(SchemaLocalizerDlg.class); //CommandAction stuff public final static String SCHEMA_LOCALIZER = "SCHEMA_LOCALIZER"; private static String SCHEMALOCDLG = "SchemaLocalizerDlg"; protected Byte schemaType; protected DBTableIdMgr tableMgr; // used to hold changes to formatters before committing them to DB protected DataObjFieldFormatMgr dataObjFieldFormatMgrCache = new DataObjFieldFormatMgr(DataObjFieldFormatMgr.getInstance()); protected UIFieldFormatterMgr uiFieldFormatterMgrCache = new UIFieldFormatterMgr(UIFieldFormatterMgr.getInstance()); protected SpecifyWebLinkMgr webLinkMgrCache = new SpecifyWebLinkMgr((SpecifyWebLinkMgr)WebLinkMgr.getInstance()); protected SchemaLocalizerPanel schemaLocPanel; protected LocalizableIOIFace localizableIOIFace; protected LocalizableStrFactory localizableStrFactory; protected Vector<SpLocaleContainer> tables = new Vector<SpLocaleContainer>(); protected Hashtable<Integer, LocalizableContainerIFace> tableHash = new Hashtable<Integer, LocalizableContainerIFace>(); protected Vector<SpLocaleContainer> changedTables = new Vector<SpLocaleContainer>(); protected Hashtable<Integer, LocalizableContainerIFace> changedTableHash = new Hashtable<Integer, LocalizableContainerIFace>(); protected Vector<LocalizableJListItem> tableDisplayItems; protected Hashtable<String, LocalizableJListItem> tableDisplayItemsHash = new Hashtable<String, LocalizableJListItem>(); protected Hashtable<LocalizableJListItem, Vector<LocalizableJListItem>> itemJListItemsHash = new Hashtable<LocalizableJListItem, Vector<LocalizableJListItem>>(); // Used for Copying Locales protected Vector<LocalizableStrIFace> namesList = new Vector<LocalizableStrIFace>(); protected Vector<LocalizableStrIFace> descsList = new Vector<LocalizableStrIFace>(); protected List<PickList> pickLists = null; protected boolean wasSaved = false; /** * @param frame * @param schemaType * @throws HeadlessException */ public SchemaLocalizerDlg(final Frame frame, final Byte schemaType, final DBTableIdMgr tableMgr) throws HeadlessException { //super(frame, "", true, OKCANCELAPPLYHELP, null); super(frame, "", true, OKCANCELHELP, null); this.schemaType = schemaType; this.tableMgr = tableMgr; if (schemaType == SpLocaleContainer.WORKBENCH_SCHEMA) { helpContext = "wb_schema_config"; } else { helpContext = "SL_HELP_CONTEXT"; } } /* (non-Javadoc) * @see edu.ku.brc.ui.CustomDialog#createUI() */ @Override public void createUI() { setApplyLabel(getResourceString("SL_CHANGE_LOCALE")); super.createUI(); localizableStrFactory = new LocalizableStrFactory() { public LocalizableStrIFace create() { SpLocaleItemStr str = new SpLocaleItemStr(); str.initialize(); return str; } public LocalizableStrIFace create(String text, Locale locale) { return new SpLocaleItemStr(text, locale); // no initialize needed for this constructor } }; LocalizerBasePanel.setLocalizableStrFactory(localizableStrFactory); //DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); //List<SpLocaleContainer> list = session.getDataList(SpLocaleContainer.class); localizableIOIFace = this; localizableIOIFace.load(true); schemaLocPanel = new SchemaLocalizerPanel(this, dataObjFieldFormatMgrCache, uiFieldFormatterMgrCache, webLinkMgrCache, schemaType); schemaLocPanel.setLocalizableIO(localizableIOIFace); schemaLocPanel.setUseDisciplines(false); okBtn.setEnabled(false); schemaLocPanel.setSaveBtn(okBtn); schemaLocPanel.setStatusBar(UIRegistry.getStatusBar()); schemaLocPanel.buildUI(); schemaLocPanel.setHasChanged(localizableIOIFace.didModelChangeDuringLoad()); contentPanel = schemaLocPanel; mainPanel.add(contentPanel, BorderLayout.CENTER); setTitle(); pack(); } /** * */ public void setTitle() { if (schemaType == SpLocaleContainer.WORKBENCH_SCHEMA) { super.setTitle(getResourceString("WBSCHEMA_CONFIG") +" - " + SchemaI18NService.getCurrentLocale().getDisplayName()); } else { super.setTitle(getResourceString("SCHEMA_CONFIG") +" - " + SchemaI18NService.getCurrentLocale().getDisplayName()); } } /* (non-Javadoc) * @see edu.ku.brc.ui.CustomDialog#okButtonPressed() */ @Override protected void okButtonPressed() { saveAndShutdown(); } /** * */ protected void finishedSaving() { super.okButtonPressed(); } /** * Saves the changes. */ protected void saveAndShutdown() { // Check to make sure whether the current container has changes. if (schemaLocPanel.hasTableInfoChanged() && schemaLocPanel.getCurrentContainer() != null) { localizableIOIFace.containerChanged(schemaLocPanel.getCurrentContainer()); } schemaLocPanel.setSaveBtn(null); enabledDlgBtns(false); UIRegistry.getStatusBar().setText(getResourceString("SL_SAVING_SCHEMA_LOC")); UIRegistry.getStatusBar().setIndeterminate(SCHEMALOCDLG, true); final SimpleGlassPane glassPane = new SimpleGlassPane(getResourceString("SchemaLocalizerFrame.SAVING"), 18); setGlassPane(glassPane); glassPane.setVisible(true); getOkBtn().setEnabled(false); SwingWorker workerThread = new SwingWorker() { @Override public Object construct() { int disciplineeId = AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId(); String accNumFormatSql = "select ci.format from splocalecontaineritem ci inner join splocalecontainer c " + " on c.splocalecontainerid = ci.splocalecontainerid where ci.name = 'accessionNumber' " + " and c.name = 'accession' and c.disciplineid = " + disciplineeId; String accNumFormat = BasicSQLUtils.querySingleObj(accNumFormatSql); save(); String newAccNumFormat = BasicSQLUtils.querySingleObj(accNumFormatSql); if (newAccNumFormat != null && !newAccNumFormat.equals(accNumFormat)) { updateAccAutoNumberingTbls(newAccNumFormat, accNumFormat); } else if (newAccNumFormat == null && accNumFormat != null) { clearAccAutoNumberingTbls(); } //SchemaI18NService.getInstance().loadWithLocale(new Locale("de", "", "")); SchemaI18NService.getInstance().loadWithLocale(schemaType, disciplineeId, tableMgr, Locale.getDefault()); SpecifyAppContextMgr.getInstance().setForceReloadViews(true); UIFieldFormatterMgr.getInstance().load(); WebLinkMgr.getInstance().reload(); DataObjFieldFormatMgr.getInstance().load(); return null; } private void clearAccAutoNumberingTbls() { int divId = AppContextMgr.getInstance().getClassObject(Division.class).getDivisionId(); String sql = "delete from autonumsch_div where divisionid = " + divId; BasicSQLUtils.update(sql); if (!BasicSQLUtils.getCount("select count(*) from autonumsch_div where divisionid = " + divId).equals(0)) { log.error("error executing sql: " + sql); } } private void updateAccAutoNumberingTbls(final String newAccNumFormat, final String oldAccNumFormat) { //System.out.println("Updating AutoNumbering Tables"); UIFieldFormatterIFace newF = UIFieldFormatterMgr.getInstance().getFormatter(newAccNumFormat); boolean isNumericOnly = newF == null ? false : newF.isNumeric(); boolean isIncrementer = newF == null ? false : newF.isIncrementer(); if (isIncrementer) { int divId = AppContextMgr.getInstance().getClassObject(Division.class).getDivisionId(); Integer autoNumSchemeIdNewFmt = BasicSQLUtils.querySingleObj("select autonumberingschemeid from autonumberingscheme where tablenumber = 7 and formatname = '" + newAccNumFormat + "' limit 1"); Integer autoNumSchemeIdOldFmt = BasicSQLUtils.querySingleObj("select autonumberingschemeid from autonumberingscheme where tablenumber = 7 and formatname = '" + oldAccNumFormat + "' limit 1"); List<String> sqls = new ArrayList<>(); if (autoNumSchemeIdNewFmt == null) { sqls.add("insert into autonumberingscheme(TimestampCreated,TimestampModified,Version,FormatName,IsNumericOnly,SchemeClassName,SchemeName,TableNumber)" + "values(now(), now(), 0, '" + newAccNumFormat + "', " + (isNumericOnly ? "true" : "false") + ", '', 'Accession Numbering Scheme', 7)"); } boolean addDiv = autoNumSchemeIdNewFmt == null; if (!addDiv) { List<Object> newFmtDivs = BasicSQLUtils.querySingleCol("select divisionid from autonumsch_div where autonumberingschemeid =" + autoNumSchemeIdNewFmt); addDiv = true; for (Object div : newFmtDivs) { if (div.equals(divId)) { addDiv = false; break; } } } if (addDiv) { sqls.add("insert into autonumsch_div(DivisionID, AutoNumberingSchemeID)" + "values(" + divId + ",(select autonumberingschemeid from autonumberingscheme where tablenumber = 7 and formatname = '" + newAccNumFormat + "'))"); } if (autoNumSchemeIdOldFmt != null) { List<Object> oldFmtDivs = BasicSQLUtils.querySingleCol("select divisionid from autonumsch_div where autonumberingschemeid =" + autoNumSchemeIdOldFmt); boolean removeDiv = false; boolean removeAns = true; for (Object div : oldFmtDivs) { if (div.equals(divId)) { removeDiv = true; } else { removeAns = false; } } if (removeDiv) { sqls.add("delete from autonumsch_div where divisionid = " + divId + " and autonumberingschemeid = " + autoNumSchemeIdOldFmt); } if (removeAns) { sqls.add("delete from autonumberingscheme where autonumberingschemeid = " + autoNumSchemeIdOldFmt); } } for (String sql : sqls) { int result = BasicSQLUtils.update(sql); if (result != 1) { log.error("error executing sql: " + sql); } } } } @Override public void finished() { glassPane.setVisible(false); enabledDlgBtns(true); UIRegistry.getStatusBar().setProgressDone(SCHEMALOCDLG); UIRegistry.getStatusBar().setText(""); finishedSaving(); } }; // start the background task workerThread.start(); } /** * @return */ public boolean wasSaved() { return wasSaved; } /* (non-Javadoc) * @see edu.ku.brc.ui.CustomDialog#applyButtonPressed() */ @Override protected void applyButtonPressed() { Vector<DisplayLocale> list = new Vector<DisplayLocale>(); for (Locale locale : Locale.getAvailableLocales()) { if (StringUtils.isEmpty(locale.getCountry())) { list.add(new DisplayLocale(locale)); } } Collections.sort(list); ToggleButtonChooserDlg<DisplayLocale> dlg = new ToggleButtonChooserDlg<DisplayLocale>((Dialog)null, "CHOOSE_LOCALE", list, ToggleButtonChooserPanel.Type.RadioButton); dlg.setUseScrollPane(true); dlg.setVisible(true); if (!dlg.isCancelled()) { schemaLocPanel.localeChanged(dlg.getSelectedObject().getLocale()); setTitle(); } } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#createResourceFiles() */ @Override public boolean createResourceFiles() { return false; } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#didModelChangeDuringLoad() */ @Override public boolean didModelChangeDuringLoad() { return false; } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#getContainerDisplayItems() */ @Override public Vector<LocalizableJListItem> getContainerDisplayItems() { final String ATTACHMENT = "attachment"; Connection connection = null; Statement stmt = null; ResultSet rs = null; try { tableDisplayItems = new Vector<LocalizableJListItem>(); int dispId = AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId(); String sql = String.format("SELECT SpLocaleContainerID, Name FROM splocalecontainer WHERE DisciplineID = %d AND SchemaType = %d ORDER BY Name", dispId, schemaType); connection = DBConnection.getInstance().createConnection(); stmt = connection.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { String tblName = rs.getString(2); boolean isAttachment = false;//(tblName.startsWith(ATTACHMENT) || tblName.endsWith(ATTACHMENT)) && !tblName.equals(ATTACHMENT); boolean isAuditLogTbl = "spauditlog".equalsIgnoreCase(tblName) || "spauditlogfield".equalsIgnoreCase(tblName); System.out.println(tblName+" "+isAttachment); if (shouldIncludeAppTables() || isAuditLogTbl || !(tblName.startsWith("sp") || isAttachment || tblName.startsWith("autonum") || tblName.equals("picklist") || tblName.equals("attributedef") || tblName.equals("recordset") || //tblName.equals("inforequest") || tblName.startsWith("workbench") || tblName.endsWith("treedef") || tblName.endsWith("treedefitem") || tblName.endsWith("attr") || tblName.endsWith("reltype"))) { tableDisplayItems.add(new LocalizableJListItem(rs.getString(2), rs.getInt(1), null)); } } } catch (Exception ex) { ex.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, ex); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (connection != null) { connection.close(); } } catch (Exception e) { e.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, e); } } return tableDisplayItems; } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#getContainer(edu.ku.brc.specify.tools.schemalocale.LocalizableJListItem, edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFaceListener) */ @Override public LocalizableContainerIFace getContainer(LocalizableJListItem item, LocalizableIOIFaceListener l) { loadTable(item.getId(), item.getName(), l); return null; } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#getDisplayItems(edu.ku.brc.specify.tools.schemalocale.LocalizableJListItem) */ @Override public Vector<LocalizableJListItem> getDisplayItems(LocalizableJListItem containerArg) { Vector<LocalizableJListItem> items = itemJListItemsHash.get(containerArg); if (items == null) { LocalizableContainerIFace cont = tableHash.get(containerArg.getId()); if (cont != null) { SpLocaleContainer container = (SpLocaleContainer)cont; items = new Vector<LocalizableJListItem>(); for (LocalizableItemIFace item : container.getContainerItems()) { SpLocaleContainerItem cItem = (SpLocaleContainerItem)item; cItem.getNames(); cItem.getDescs(); items.add(new LocalizableJListItem(cItem.getName(), cItem.getId(), null)); } itemJListItemsHash.put(containerArg, items); Collections.sort(items); } else { log.error("Couldn't find container ["+containerArg.getName()+"]"); } } return items; } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#getItem(edu.ku.brc.specify.tools.schemalocale.LocalizableContainerIFace, edu.ku.brc.specify.tools.schemalocale.LocalizableJListItem) */ @Override public LocalizableItemIFace getItem(LocalizableContainerIFace containerArg, LocalizableJListItem item) { SpLocaleContainer container = (SpLocaleContainer)containerArg; // Make sure the items are loaded before getting them. if (container != null) { for (LocalizableItemIFace cItem : container.getItems()) { if (cItem.getName().equals(item.getName())) { return cItem; } } } else { log.error("Couldn't merge container ["+containerArg.getName()+"]"); } return null; } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#load(boolean) */ @Override public boolean load(final boolean useCurrentLocaleOnly) { enabledDlgBtns(true); return true; } /** * @param sessionArg * @param containerId * @return */ protected SpLocaleContainer loadTable(final DataProviderSessionIFace sessionArg, final int containerId) { SpLocaleContainer container = null; DataProviderSessionIFace session = null; try { session = sessionArg != null ? sessionArg : DataProviderFactory.getInstance().createSession(); int dispId = AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId(); String sql = String.format("FROM SpLocaleContainer WHERE disciplineId = %d AND spLocaleContainerId = %d", dispId, containerId); container = (SpLocaleContainer)session.getData(sql); tables.add(container); tableHash.put(container.getId(), container); for (SpLocaleContainerItem item : container.getItems()) { // force Load of lazy collections container.getDescs().size(); container.getNames().size(); item.getDescs().size(); item.getNames().size(); } return container; } catch (Exception e) { e.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, e); } finally { if (session != null && sessionArg == null) { session.close(); } } return null; } /** * @param containerId */ protected void loadTable(final int containerId, final String name, final LocalizableIOIFaceListener l) { LocalizableContainerIFace cntr = tableHash.get(containerId); if (cntr != null) { l.containterRetrieved(cntr); return; } UIRegistry.getStatusBar().setIndeterminate(name, true); UIRegistry.getStatusBar().setText(UIRegistry.getResourceString("LOADING_SCHEMA")); enabledDlgBtns(false); schemaLocPanel.enableUIControls(false); SwingWorker workerThread = new SwingWorker() { protected SpLocaleContainer container = null; @Override public Object construct() { container = loadTable(null, containerId); return null; } @Override public void finished() { l.containterRetrieved(container); enabledDlgBtns(true); //schemaLocPanel.enableUIControls(true); UIRegistry.getStatusBar().setProgressDone(name); UIRegistry.getStatusBar().setText(""); schemaLocPanel.getContainerList().setEnabled(true); } }; // start the background task workerThread.start(); } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#save() */ @Override public boolean save() { schemaLocPanel.getAllDataFromUI(); SimpleGlassPane glassPane = (SimpleGlassPane)getGlassPane(); if (glassPane != null) { glassPane.setProgress(0); } // apply changes to formatters and save them to db DataObjFieldFormatMgr.getInstance().applyChanges(dataObjFieldFormatMgrCache); UIFieldFormatterMgr.getInstance().applyChanges(uiFieldFormatterMgrCache); WebLinkMgr.getInstance().applyChanges(webLinkMgrCache); if (changedTables.size() > 0) { DataProviderSessionIFace session = null; try { session = DataProviderFactory.getInstance().createSession(); double step = 100.0 / (double)changedTables.size(); double total = 0.0; session.beginTransaction(); for (SpLocaleContainer container : changedTables) { SpLocaleContainer dbContainer = session.merge(container); session.saveOrUpdate(dbContainer); for (SpLocaleItemStr str : dbContainer.getNames()) { session.saveOrUpdate(session.merge(str)); //System.out.println(c.getName()+" - "+str.getText()); } for (SpLocaleItemStr str : dbContainer.getDescs()) { session.saveOrUpdate(session.merge(str)); //System.out.println(c.getName()+" - "+str.getText()); } for (SpLocaleContainerItem item : dbContainer.getItems()) { SpLocaleContainerItem i = session.merge(item); session.saveOrUpdate(i); for (SpLocaleItemStr str : i.getNames()) { session.saveOrUpdate(session.merge(str)); //System.out.println(i.getName()+" - "+str.getText()); } for (SpLocaleItemStr str : i.getDescs()) { session.saveOrUpdate(session.merge(str)); //System.out.println(i.getName()+" - "+str.getText()); } } total += step; System.err.println(total+" "+step); if (glassPane != null) { glassPane.setProgress((int)total); } } session.commit(); session.flush(); if (glassPane != null) { glassPane.setProgress(100); } } catch (Exception ex) { ex.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, ex); } finally { if (session != null) { session.close(); } } //notify app of localizer changes CommandAction cmd = new CommandAction(SCHEMA_LOCALIZER, SCHEMA_LOCALIZER, null); CommandDispatcher.dispatch(cmd); } else { log.warn("No Changes were saved!"); } return true; } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#containerChanged(edu.ku.brc.specify.tools.schemalocale.LocalizableContainerIFace) */ @Override public void containerChanged(LocalizableContainerIFace container) { if (container instanceof SpLocaleContainer) { if (changedTableHash.get(container.getId()) == null) { changedTables.add((SpLocaleContainer)container); changedTableHash.put(container.getId(), container); } } } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#isLocaleInUse(java.util.Locale) */ @Override public boolean isLocaleInUse(final Locale locale) { // First check the aDatabase because the extra locales are not loaded automatically. if (isLocaleInUseInDB(schemaType, locale)) { return true; } // Now check memory Hashtable<String, Boolean> localeHash = new Hashtable<String, Boolean>(); for (SpLocaleContainer container : tables) { SchemaLocalizerXMLHelper.checkForLocales(container, localeHash); for (LocalizableItemIFace f : container.getContainerItems()) { SchemaLocalizerXMLHelper.checkForLocales(f, localeHash); } } return localeHash.get(SchemaLocalizerXMLHelper.makeLocaleKey(locale)) != null; } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#getLocalesInUse() */ @Override public Vector<Locale> getLocalesInUse() { Hashtable<String, Boolean> localeHash = new Hashtable<String, Boolean>(); // Add any from the Database Vector<Locale> localeList = getLocalesInUseInDB(schemaType); for (Locale locale : localeList) { localeHash.put(SchemaLocalizerXMLHelper.makeLocaleKey(locale.getLanguage(), locale.getCountry(), locale.getVariant()), true); } for (SpLocaleContainer container : tables) { SchemaLocalizerXMLHelper.checkForLocales(container, localeHash); for (LocalizableItemIFace f : container.getContainerItems()) { SchemaLocalizerXMLHelper.checkForLocales(f, localeHash); } } localeList.clear(); for (String key : localeHash.keySet()) { String[] toks = StringUtils.split(key, "_"); localeList.add(new Locale(toks[0], "", "")); } return localeList; } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#shouldIncludeAppTables() */ @Override public boolean shouldIncludeAppTables() { return false; } /** * Return the locales in the database * @return the list of locale */ public static Vector<Locale> getLocalesInUseInDB(final Byte schemaType) { Vector<Locale> locales = new Vector<>(); String sql = "SELECT DISTINCT nms.language, trim(ifnull(nms.country,'')) FROM splocalecontainer ctn " + "INNER JOIN splocalecontaineritem itm on itm.splocalecontainerid = ctn.splocalecontainerid " + "INNER JOIN splocaleitemstr nms on nms.splocalecontaineritemnameid = itm.splocalecontaineritemid " + "WHERE ctn.disciplineid = " + AppContextMgr.getInstance().getClassObject(Discipline.class).getId() + " AND nms.language IS NOT NULL AND ctn.schemaType = " + schemaType; log.debug(sql); List<Object[]> list = BasicSQLUtils.query(sql); for (Object[] lang : list) { String language = lang[0].toString(); String country = lang[1] == null ? "" : lang[1].toString(); locales.add(new Locale(language, country, "")); } return locales; } /** * Check the Database to see if the Locale is being used. * @param schemaTypeArg the which set of locales * @param locale the locale in question * @return true/false */ public boolean isLocaleInUseInDB(final Byte schemaTypeArg, final Locale locale) { Session session = HibernateUtil.getNewSession(); try { String sql = String.format("SELECT DISTINCT nms.language FROM SpLocaleContainer as ctn " + "INNER JOIN ctn.items as itm " + "INNER JOIN itm.names nms " + "INNER JOIN ctn.discipline as d " + "WHERE d.userGroupScopeId = DSPLNID AND nms.language = '%s' AND ctn.schemaType = %d", locale.getLanguage(), schemaTypeArg); sql = QueryAdjusterForDomain.getInstance().adjustSQL(sql); Query query = session.createQuery(sql); List<?> list = query.list(); return list.size() > 0; } catch (Exception ex) { ex.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, ex); } finally { session.close(); } return false; } /** * @param enable */ protected void enabledDlgBtns(final boolean enable) { okBtn.setEnabled(enable ? (schemaLocPanel != null ? schemaLocPanel.hasChanged() : false) : false); cancelBtn.setEnabled(enable); if (applyBtn != null) { applyBtn.setEnabled(enable); } helpBtn.setEnabled(enable); } /** * @param item * @param srcLocale * @param dstLocale */ public void copyLocale(final LocalizableItemIFace item, final Locale srcLocale, final Locale dstLocale) { item.fillNames(namesList); LocalizableStrIFace srcName = null; for (LocalizableStrIFace nm : namesList) { if (nm.isLocale(srcLocale)) { srcName = nm; break; } } if (srcName != null) { LocalizableStrIFace name = localizableStrFactory.create(srcName.getText(), dstLocale); item.addName(name); } item.fillDescs(descsList); LocalizableStrIFace srcDesc = null; for (LocalizableStrIFace d : descsList) { if (d.isLocale(srcLocale)) { srcDesc = d; break; } } if (srcDesc != null) { LocalizableStrIFace desc = localizableStrFactory.create(srcDesc.getText(), dstLocale); item.addDesc(desc); } } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#copyLocale(java.util.Locale, java.util.Locale, java.beans.PropertyChangeListener) */ @Override public void copyLocale(final LocalizableIOIFaceListener lcl, Locale srcLocale, Locale dstLocale, final PropertyChangeListener pcl) { UIRegistry.getStatusBar().setProgressRange(SCHEMALOCDLG, 0, getContainerDisplayItems().size()); DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); try { double step = 100.0 / (double)tableDisplayItems.size(); double total = 0.0; for (LocalizableJListItem listItem : tableDisplayItems) { //System.out.println(listItem.getName()); SpLocaleContainer container = (SpLocaleContainer)tableHash.get(listItem.getId()); if (container == null) { container = loadTable(session, listItem.getId()); tableHash.put(listItem.getId(), container); } if (container != null) { copyLocale(container, srcLocale, dstLocale); for (LocalizableItemIFace field : container.getItems()) { //System.out.println(" "+field.getName()); copyLocale(field, srcLocale, dstLocale); } containerChanged(container); if (pcl != null) { pcl.propertyChange(new PropertyChangeEvent(this, "progress", total, (int)(total+step))); } } else { log.error("Couldn't find Container["+listItem.getId()+"]"); } total += step; } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, ex); ex.printStackTrace(); } finally { session.close(); UIRegistry.getStatusBar().setProgressDone(SCHEMALOCDLG); } pcl.propertyChange(new PropertyChangeEvent(this, "progress", 99, 100)); } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#getPickLists(java.lang.String) */ @SuppressWarnings("unchecked") @Override public List<PickList> getPickLists(final String disciplineName) { if (StringUtils.isNotEmpty(disciplineName)) { return null; } if (pickLists == null) { DataProviderSessionIFace session = null; try { session = DataProviderFactory.getInstance().createSession(); pickLists = new Vector<PickList>(); // unchecked warning: Criteria results are always the requested class String sql = "SELECT name, type, tableName, fieldName, pickListId FROM PickList WHERE collectionId = "+ AppContextMgr.getInstance().getClassObject(Collection.class).getCollectionId() + " ORDER BY name"; List<?> list = session.getDataList(sql); for (Object row : list) { Object[] data = (Object[])row; PickList pl = new PickList(); pl.initialize(); pl.setName((String)data[0]); pl.setType((Byte)data[1]); pl.setTableName((String)data[2]); pl.setFieldName((String)data[3]); pl.setPickListId((Integer)data[4]); pickLists.add(pl); } //pickLists = (List<PickList>)session.getDataList(sql); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, ex); log.error(ex); ex.printStackTrace(); } finally { if (session != null) { session.close(); } } } return pickLists; } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#exportToDirectory(java.io.File) */ @Override public boolean exportToDirectory(File expportDir) { throw new RuntimeException("Export is not implemented."); } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#hasUpdatablePickLists() */ @Override public boolean hasUpdatablePickLists() { return true; } /* (non-Javadoc) * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent) */ @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("copyStart")) { enabledDlgBtns(false); } else if (evt.getPropertyName().equals("copyEnd")) { enabledDlgBtns(true); } } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#exportSingleLanguageToDirectory(java.io.File, java.util.Locale) */ @Override public boolean exportSingleLanguageToDirectory(File expportFile, Locale locale) { throw new RuntimeException("Not Impl"); } /* (non-Javadoc) * @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#hasChanged() */ @Override public boolean hasChanged() { throw new RuntimeException("Not Impl"); } }
specify/specify6
src/edu/ku/brc/specify/tools/schemalocale/SchemaLocalizerDlg.java
Java
gpl-2.0
43,764
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package grupp07.model; import java.util.ArrayList; import javafx.scene.paint.Color; import javafx.util.Pair; /** * * @author gast */ public abstract class Player { private String name; private Color playerColor; /** This function should return the wished next move for player. * * @return a tuple of the wished move containing two Integers for player. */ public abstract Pair nextMove(); /** This function may use the supplied list of possible moves for * the actual game. The player returns a wished move, that may be one of * the supplied ones. * * @param coords is a list of possible moves for the current player to * choose from. This could guide a computer player for example. * @return */ public abstract Pair nextMove(ArrayList<Pair<Integer, Integer>> coords); /** This function gets the players color. * * @return the player's color. */ public Color getColor(){ return playerColor; } /** This function sets the players color. * * @param color the player to use color. */ public void setColor(Color color){ playerColor = color; } /** This function gets the name of the player. * * @return the name of the player */ public String getName(){ return name; } /** This function sets the players name * * @param name the player's name. */ public void setName(String name){ this.name = name; } }
henwist/OOM_lab2
src/grupp07/model/Player.java
Java
gpl-2.0
1,814
<?php /* * This file is part of EC-CUBE * * Copyright(c) 2000-2007 LOCKON CO.,LTD. All Rights Reserved. * * http://www.lockon.co.jp/ * * 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. */ // {{{ requires require_once("../require.php"); require_once(CLASS_EX_PATH . "page_extends/admin/ownersstore/LC_Page_Admin_OwnersStore_Log_Ex.php"); // }}} // {{{ generate page $objPage = new LC_Page_Admin_OwnersStore_Log_Ex(); $objPage->init(); $objPage->process(); register_shutdown_function(array($objPage, "destroy")); ?>
RyotaKaji/eccube-2.4.1
html/admin/ownersstore/log.php
PHP
gpl-2.0
1,189
/** @file io/xmlparser.cc xml parsing class used in xmlreader.cc */ /////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004-2004 California Institute of Technology // Copyright (c) 2004-2007 University of Southern California // Rob Peters <https://github.com/rjpcal/> // // created: Tue May 25 10:29:42 2004 // // -------------------------------------------------------------------- // // This file is part of GroovX. // [https://github.com/rjpcal/groovx] // // GroovX 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. // // GroovX 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 GroovX; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. // /////////////////////////////////////////////////////////////////////// #include "io/xmlparser.h" #include "rutz/error.h" #include "rutz/fstring.h" #include "rutz/sfmt.h" #include <cstdio> // for EOF #include <istream> #include <limits> #include "rutz/trace.h" #include "rutz/debug.h" GVX_DBG_REGISTER #ifndef XML_STATUS_OK #define XML_STATUS_OK 1 #define XML_STATUS_ERROR 0 #endif io::xml_parser::xml_parser(std::istream& is, int bufsize) : m_parser(XML_ParserCreate(/*encoding*/0)), m_stream(is), m_buf_size(bufsize) { GVX_TRACE("io::xml_parser::xml_parser"); if (m_parser == nullptr) { throw rutz::error("couldn't allocate memory for XML_Parser", SRC_POS); } XML_SetUserData(m_parser, this); XML_SetElementHandler(m_parser, &c_element_start, &c_element_end); XML_SetCharacterDataHandler(m_parser, &c_character_data); } io::xml_parser::~xml_parser() { GVX_TRACE("io::xml_parser::~xml_parser"); XML_ParserFree(m_parser); } void io::xml_parser::character_data(const char* /*text*/, size_t /*length*/) { GVX_TRACE("io::xml_parser::character_data"); } void io::xml_parser::c_element_start(void* data, const char* el, const char** attr) { GVX_TRACE("io::xml_parser::c_element_start"); io::xml_parser* p = static_cast<io::xml_parser*>(data); GVX_ASSERT(p != nullptr); p->element_start(el, attr); } void io::xml_parser::c_element_end(void* data, const char* el) { GVX_TRACE("io::xml_parser::c_element_end"); io::xml_parser* p = static_cast<io::xml_parser*>(data); GVX_ASSERT(p != nullptr); p->element_end(el); } void io::xml_parser::c_character_data(void* data, const char* text, int length) { GVX_TRACE("io::xml_parser::c_character_data"); io::xml_parser* p = static_cast<io::xml_parser*>(data); GVX_ASSERT(p != nullptr); GVX_ASSERT(length >= 0); p->character_data(text, size_t(length)); } void io::xml_parser::parse() { GVX_TRACE("io::xml_parser::parse"); while (1) { void* const buf = XML_GetBuffer(m_parser, m_buf_size); if (buf == nullptr) { throw rutz::error("couldn't get buffer in io::xml_parser::parse()", SRC_POS); } // very strangely I wasn't able to get things to work using a // readsome() approach here... m_stream.read(static_cast<char*>(buf), m_buf_size); const ssize_t len = m_stream.gcount(); if (!m_stream.eof() && m_stream.fail()) { throw rutz::error("read error in io::xml_parser::parse()", SRC_POS); } const int peek = m_stream.peek(); const int done = (peek == EOF); if (GVX_DBG_LEVEL() >= 3) { dbg_eval(3, buf); dbg_eval(3, m_buf_size); dbg_eval(3, len); dbg_eval(3, peek); dbg_eval_nl(3, done); } GVX_ASSERT(len < std::numeric_limits<int>::max()); // alternate: use XML_Parse(m_parser, m_buf, len, done) if we have // our own memory buffer if (XML_ParseBuffer(m_parser, int(len), done) != XML_STATUS_OK) { throw rutz::error (rutz::sfmt("xml parse error at input line %d:\n%s", int(XML_GetCurrentLineNumber(m_parser)), XML_ErrorString(XML_GetErrorCode(m_parser))), SRC_POS); } if (done) return; } } #if 0 // here's a simple subclass of io::xml_parser that prints an outline // of an XML file just to show that everything is getting parsed // properly class Outliner : public io::xml_parser { public: Outliner(std::istream& is) : io::xml_parser(is), m_depth(0) {} virtual ~Outliner() {} protected: virtual void element_start(const char* el, const char** attr) override; virtual void element_end(const char* el) override; private: int m_depth; }; void Outliner::element_start(const char* el, const char** attr) { for (int i = 0; i < m_depth; i++) printf(" "); printf("%s", el); for (int i = 0; attr[i]; i += 2) { printf(" %s='%s'", attr[i], attr[i + 1]); } printf("\n"); ++m_depth; } void Outliner::element_end(const char* el) { --m_depth; } #endif
rjpcal/groovx
src/io/xmlparser.cc
C++
gpl-2.0
5,403
package org.wordpress.android.ui.notifications; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationManagerCompat; import org.wordpress.android.push.GCMMessageService; /* * Clears the notification map when a user dismisses a notification */ public class NotificationDismissBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int notificationId = intent.getIntExtra("notificationId", 0); if (notificationId == GCMMessageService.GROUP_NOTIFICATION_ID) { GCMMessageService.clearNotifications(); } else { GCMMessageService.removeNotification(notificationId); // Dismiss the grouped notification if a user dismisses all notifications from a wear device if (!GCMMessageService.hasNotifications()) { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.cancel(GCMMessageService.GROUP_NOTIFICATION_ID); } } } }
mzorz/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/notifications/NotificationDismissBroadcastReceiver.java
Java
gpl-2.0
1,155
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace Zen.Massage.Site { public static class ClaimsHelpers { private static readonly string AdminClaim = "http://schemas.zenmassage.com/claims/administrator"; private static readonly string UserIdClaim = "http://schemas.zenmassage.com/claims/userid"; private static readonly string TherapistClaim = "http://schemas.zenmassage.com/claims/therapist"; public static Guid GetUserIdClaim(this ClaimsPrincipal principal) { if (!principal.HasClaim(c => c.Type == UserIdClaim)) { return Guid.Empty; } // TODO: Validate issuer return principal.Claims .Where(c => c.Type == UserIdClaim) .Select(c => Guid.Parse(c.Value)) .FirstOrDefault(); } public static bool HasAdminClaim(this ClaimsPrincipal principal) { // TODO: Validate issuer return principal.HasClaim(c => c.Type == AdminClaim); } public static bool HasTherapistClaim(this ClaimsPrincipal principal) { // TODO: Validate issuer return principal.HasClaim(c => c.Type == TherapistClaim); } } }
dementeddevil/zenmassage
src/Zen.Massage.Site/ClaimsHelpers.cs
C#
gpl-2.0
1,360
__author__ = 'dako' class SessionHelper: def __init__(self, app): self.app = app def login(self, username, password): wd = self.app.wd self.app.open_home_page() wd.find_element_by_name("user").click() wd.find_element_by_name("user").clear() wd.find_element_by_name("user").send_keys(username) wd.find_element_by_name("pass").click() wd.find_element_by_name("pass").clear() wd.find_element_by_name("pass").send_keys(password) wd.find_element_by_css_selector('input[type="submit"]').click() def logout(self): wd = self.app.wd wd.find_element_by_link_text("Logout").click() def is_logged_in(self): wd = self.app.wd return len(wd.find_elements_by_link_text("Logout")) > 0 def is_logged_in_as(self, username): wd = self.app.wd return self.get_logged_user() == username def get_logged_user(self): wd = self.app.wd return wd.find_element_by_xpath("//div/div[1]/form/b").text[1:-1] def ensure_logout(self): wd = self.app.wd if self.is_logged_in(): self.logout() def ensure_login(self, username, password): wd = self.app.wd if self.is_logged_in(): if self.is_logged_in_as(username): return else: self.logout() self.login(username, password)
EvilDako/PyTraining
fixture/session.py
Python
gpl-2.0
1,421
package com.nowgroup.scspro.service.cat; import com.nowgroup.scspro.dto.cat.Storage; import com.nowgroup.scspro.dto.geo.State; import com.nowgroup.scspro.service.BaseService; public interface StorageService extends BaseService<Storage> { State getStateInStorage(int id); }
inspiraCode/scspro
scspro-parent/scspro_service/src/main/java/com/nowgroup/scspro/service/cat/StorageService.java
Java
gpl-2.0
279
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Computer_Drafter.Models { class MotherboardModel : PartModel { private List<string> amdChipsets; private List<string> intelChipsets; private string selChipset; private List<string> memCaps; private string selMemCap; private List<string> memTypes; private string selMemType; private string selMemFreq; #region Properties public List<string> AmdChipsets { get { return amdChipsets; } } public List<string> IntelChipsets { get { return intelChipsets; } } public string SelectedChipset { get { return selChipset; } set { selChipset = value; } } public List<string> MemoryCapacities { get { return memCaps; } } public string SelectedMemoryCapacity { get { return selMemCap; } set { selMemCap = value; } } public List<string> MemoryTypes { get { return memTypes; } } public string SelectedMemoryType { get { return selMemType; } set { selMemType = value; } } public List<string> MemoryFrequencies { get { return FrequencyData.GetFrequencies; } } public string SelectedMemoryFreq { get { return selMemFreq; } set { selMemFreq = value; } } #endregion public MotherboardModel() { amdChipsets = new List<string>(); amdChipsets.Add("740"); amdChipsets.Add("760"); amdChipsets.Add("760G"); amdChipsets.Add("770"); amdChipsets.Add("870"); amdChipsets.Add("880"); amdChipsets.Add("880G"); amdChipsets.Add("890"); amdChipsets.Add("970"); amdChipsets.Add("990X"); amdChipsets.Add("990FX"); amdChipsets.Add("G34 Opteron"); intelChipsets = new List<string>(); intelChipsets.Add("B85"); intelChipsets.Add("H81"); intelChipsets.Add("H87"); intelChipsets.Add("H97"); intelChipsets.Add("Q85"); intelChipsets.Add("Q87"); intelChipsets.Add("Z77"); intelChipsets.Add("Z87"); intelChipsets.Add("Z97"); intelChipsets.Add("X79"); intelChipsets.Add("X99"); intelChipsets.Add("Xeon"); memCaps = new List<string>(); memCaps.Add("16GB"); memCaps.Add("32GB"); memCaps.Add("64GB"); memCaps.Add("128GB"); memCaps.Add("256GB"); memCaps.Add("512GB"); memCaps.Add("768GB"); memCaps.Add("1024GB"); memCaps.Add("1.5TB"); memTypes = new List<string>(); memTypes.Add("DDR"); memTypes.Add("DDR2"); memTypes.Add("DDR3"); memTypes.Add("DDR4"); } } }
VesnaBrucoms/computer-drafter-wpf
Computer Drafter/Models/MotherboardModel.cs
C#
gpl-2.0
3,228
<?php /* Plugin Name: WordPress Backup to Dropbox Plugin URI: http://wpb2d.com Description: Keep your valuable WordPress website, its media and database backed up in Dropbox! Need help? Please email support@wpb2d.com Version: 4.5 Author: Michael De Wildt Author URI: http://www.mikeyd.com.au License: Copyright 2011-2015 Awesoft Pty. Ltd. (email : michael.dewildt@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 */ define('BACKUP_TO_DROPBOX_VERSION', '4.5'); define('BACKUP_TO_DROPBOX_DATABASE_VERSION', '2'); define('EXTENSIONS_DIR', str_replace('/', DIRECTORY_SEPARATOR, WP_CONTENT_DIR . '/plugins/wordpress-backup-to-dropbox/Classes/Extension/')); define('CHUNKED_UPLOAD_THREASHOLD', 10485760); //10 MB define('MINUMUM_PHP_VERSION', '5.2.16'); define('NO_ACTIVITY_WAIT_TIME', 300); //5 mins to allow for socket timeouts and long uploads if (function_exists('spl_autoload_register')) { spl_autoload_register('wpb2d_autoload'); } else { require_once 'Dropbox/Dropbox/API.php'; require_once 'Dropbox/Dropbox/OAuth/Consumer/ConsumerAbstract.php'; require_once 'Dropbox/Dropbox/OAuth/Consumer/Curl.php'; require_once 'Classes/Extension/Base.php'; require_once 'Classes/Extension/Manager.php'; require_once 'Classes/Extension/DefaultOutput.php'; require_once 'Classes/Processed/Base.php'; require_once 'Classes/Processed/Files.php'; require_once 'Classes/Processed/DBTables.php'; require_once 'Classes/DatabaseBackup.php'; require_once 'Classes/FileList.php'; require_once 'Classes/DropboxFacade.php'; require_once 'Classes/Config.php'; require_once 'Classes/BackupController.php'; require_once 'Classes/Logger.php'; require_once 'Classes/Factory.php'; require_once 'Classes/UploadTracker.php'; } function wpb2d_autoload($className) { $fileName = str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; if (preg_match('/^WPB2D/', $fileName)) { $fileName = 'Classes' . str_replace('WPB2D', '', $fileName); } elseif (preg_match('/^Dropbox/', $fileName)) { $fileName = 'Dropbox' . DIRECTORY_SEPARATOR . $fileName; } else { return false; } $path = dirname(__FILE__) . DIRECTORY_SEPARATOR . $fileName; if (file_exists($path)) { require_once $path; } } function wpb2d_style() { //Register stylesheet wp_register_style('wpb2d-style', plugins_url('wp-backup-to-dropbox.css', __FILE__) ); wp_enqueue_style('wpb2d-style'); } /** * A wrapper function that adds an options page to setup Dropbox Backup * @return void */ function backup_to_dropbox_admin_menu() { $imgUrl = plugin_dir_url(__FILE__) . 'Images/WordPressBackupToDropbox_16.png'; $text = __('WPB2D', 'wpbtd'); add_menu_page($text, $text, 'activate_plugins', 'backup-to-dropbox', 'backup_to_dropbox_admin_menu_contents', $imgUrl, '80.0564'); $text = __('Backup Settings', 'wpbtd'); add_submenu_page('backup-to-dropbox', $text, $text, 'activate_plugins', 'backup-to-dropbox', 'backup_to_dropbox_admin_menu_contents'); if (version_compare(PHP_VERSION, MINUMUM_PHP_VERSION) >= 0) { $text = __('Backup Monitor', 'wpbtd'); add_submenu_page('backup-to-dropbox', $text, $text, 'activate_plugins', 'backup-to-dropbox-monitor', 'backup_to_dropbox_monitor'); WPB2D_Extension_Manager::construct()->add_menu_items(); $text = __('Premium Extensions', 'wpbtd'); add_submenu_page('backup-to-dropbox', $text, $text, 'activate_plugins', 'backup-to-dropbox-premium', 'backup_to_dropbox_premium'); } } /** * A wrapper function that includes the backup to Dropbox options page * @return void */ function backup_to_dropbox_admin_menu_contents() { $uri = plugin_dir_url(__FILE__); if(version_compare(PHP_VERSION, MINUMUM_PHP_VERSION) >= 0) { include 'Views/wpb2d-options.php'; } else { include 'Views/wpb2d-deprecated.php'; } } /** * A wrapper function that includes the backup to Dropbox monitor page * @return void */ function backup_to_dropbox_monitor() { if (!WPB2D_Factory::get('dropbox')->is_authorized()) { backup_to_dropbox_admin_menu_contents(); } else { $uri = plugin_dir_url(__FILE__); include 'Views/wpb2d-monitor.php'; } } /** * A wrapper function that includes the backup to Dropbox premium page * @return void */ function backup_to_dropbox_premium() { wp_enqueue_script('jquery-ui-core'); wp_enqueue_script('jquery-ui-tabs'); $uri = plugin_dir_url(__FILE__); include 'Views/wpb2d-premium.php'; } /** * A wrapper function for the file tree AJAX request * @return void */ function backup_to_dropbox_file_tree() { include 'Views/wpb2d-file-tree.php'; die(); } /** * A wrapper function for the progress AJAX request * @return void */ function backup_to_dropbox_progress() { include 'Views/wpb2d-progress.php'; die(); } /** * A wrapper function that executes the backup * @return void */ function execute_drobox_backup() { WPB2D_Factory::get('logger')->delete_log(); WPB2D_Factory::get('logger')->log(sprintf(__('Backup started on %s.', 'wpbtd'), date("l F j, Y", strtotime(current_time('mysql'))))); $time = ini_get('max_execution_time'); WPB2D_Factory::get('logger')->log(sprintf( __('Your time limit is %s and your memory limit is %s'), $time ? $time . ' ' . __('seconds', 'wpbtd') : __('unlimited', 'wpbtd'), ini_get('memory_limit') )); if (ini_get('safe_mode')) { WPB2D_Factory::get('logger')->log(__("Safe mode is enabled on your server so the PHP time and memory limit cannot be set by the backup process. So if your backup fails it's highly probable that these settings are too low.", 'wpbtd')); } WPB2D_Factory::get('config')->set_option('in_progress', true); if (defined('WPB2D_TEST_MODE')) { run_dropbox_backup(); } else { wp_schedule_single_event(time(), 'run_dropbox_backup_hook'); wp_schedule_event(time(), 'every_min', 'monitor_dropbox_backup_hook'); } } /** * @return void */ function monitor_dropbox_backup() { $config = WPB2D_Factory::get('config'); $mtime = filemtime(WPB2D_Factory::get('logger')->get_log_file()); if ($config->get_option('in_progress') && ($mtime < time() - NO_ACTIVITY_WAIT_TIME)) { WPB2D_Factory::get('logger')->log(sprintf(__('There has been no backup activity for a long time. Attempting to resume the backup.' , 'wpbtd'), 5)); $config->set_option('is_running', false); wp_schedule_single_event(time(), 'run_dropbox_backup_hook'); } } /** * @return void */ function run_dropbox_backup() { $options = WPB2D_Factory::get('config'); if (!$options->get_option('is_running')) { $options->set_option('is_running', true); WPB2D_BackupController::construct()->execute(); } } /** * Adds a set of custom intervals to the cron schedule list * @param $schedules * @return array */ function backup_to_dropbox_cron_schedules($schedules) { $new_schedules = array( 'every_min' => array( 'interval' => 60, 'display' => 'WPB2D - Monitor' ), 'daily' => array( 'interval' => 86400, 'display' => 'WPB2D - Daily' ), 'weekly' => array( 'interval' => 604800, 'display' => 'WPB2D - Weekly' ), 'fortnightly' => array( 'interval' => 1209600, 'display' => 'WPB2D - Fortnightly' ), 'monthly' => array( 'interval' => 2419200, 'display' => 'WPB2D - Once Every 4 weeks' ), 'two_monthly' => array( 'interval' => 4838400, 'display' => 'WPB2D - Once Every 8 weeks' ), 'three_monthly' => array( 'interval' => 7257600, 'display' => 'WPB2D - Once Every 12 weeks' ), ); return array_merge($schedules, $new_schedules); } function wpb2d_install() { $wpdb = WPB2D_Factory::db(); require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); $table_name = $wpdb->prefix . 'wpb2d_options'; dbDelta("CREATE TABLE $table_name ( name varchar(50) NOT NULL, value varchar(255) NOT NULL, UNIQUE KEY name (name) );"); $table_name = $wpdb->prefix . 'wpb2d_processed_files'; dbDelta("CREATE TABLE $table_name ( file varchar(255) NOT NULL, offset int NOT NULL DEFAULT 0, uploadid varchar(50), UNIQUE KEY file (file) );"); $table_name = $wpdb->prefix . 'wpb2d_processed_dbtables'; dbDelta("CREATE TABLE $table_name ( name varchar(255) NOT NULL, count int NOT NULL DEFAULT 0, UNIQUE KEY name (name) );"); $table_name = $wpdb->prefix . 'wpb2d_excluded_files'; dbDelta("CREATE TABLE $table_name ( file varchar(255) NOT NULL, isdir tinyint(1) NOT NULL, UNIQUE KEY file (file) );"); //Ensure that there where no insert errors $errors = array(); global $EZSQL_ERROR; if ($EZSQL_ERROR) { foreach ($EZSQL_ERROR as $error) { if (preg_match("/^CREATE TABLE {$wpdb->prefix}wpb2d_/", $error['query'])) $errors[] = $error['error_str']; } delete_option('wpb2d-init-errors'); add_option('wpb2d-init-errors', implode($errors, '<br />'), false, 'no'); } //Only set the DB version if there are no errors if (empty($errors)) { WPB2D_Factory::get('config')->set_option('database_version', BACKUP_TO_DROPBOX_DATABASE_VERSION); } } function wpb2d_init() { try { if (WPB2D_Factory::get('config')->get_option('database_version') < BACKUP_TO_DROPBOX_DATABASE_VERSION) { wpb2d_install(); } if (!get_option('wpb2d-premium-extensions')) { add_option('wpb2d-premium-extensions', array(), false, 'no'); } } catch (Exception $e) { error_log($e->getMessage()); } } function get_sanitized_home_path() { //Needed for get_home_path() function and may not be loaded require_once(ABSPATH . 'wp-admin/includes/file.php'); //If site address and WordPress address differ but are not in a different directory //then get_home_path will return '/' and cause issues. $home_path = get_home_path(); if ($home_path == '/') { $home_path = ABSPATH; } return rtrim(str_replace('/', DIRECTORY_SEPARATOR, $home_path), DIRECTORY_SEPARATOR); } //More cron shedules add_filter('cron_schedules', 'backup_to_dropbox_cron_schedules'); //Backup hooks add_action('monitor_dropbox_backup_hook', 'monitor_dropbox_backup'); add_action('run_dropbox_backup_hook', 'run_dropbox_backup'); add_action('execute_periodic_drobox_backup', 'execute_drobox_backup'); add_action('execute_instant_drobox_backup', 'execute_drobox_backup'); //Register database install register_activation_hook(__FILE__, 'wpb2d_install'); add_action('admin_init', 'wpb2d_init'); add_action('admin_enqueue_scripts', 'wpb2d_style'); //i18n language text domain load_plugin_textdomain('wpbtd', false, 'wordpress-backup-to-dropbox/Languages/'); if (is_admin()) { //WordPress filters and actions add_action('wp_ajax_file_tree', 'backup_to_dropbox_file_tree'); add_action('wp_ajax_progress', 'backup_to_dropbox_progress'); if (defined('MULTISITE') && MULTISITE) { add_action('network_admin_menu', 'backup_to_dropbox_admin_menu'); } else { add_action('admin_menu', 'backup_to_dropbox_admin_menu'); } }
Rockdrill/intranet
wp-content/plugins/wordpress-backup-to-dropbox/wp-backup-to-dropbox.php
PHP
gpl-2.0
12,259
// Copyright (c) 2012- PPSSPP 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.0 or later versions. // 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 2.0 for more details. // A copy of the GPL 2.0 should have been included with the program. // If not, see http://www.gnu.org/licenses/ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. #include "Core/MIPS/MIPS.h" #include "Core/MIPS/MIPSTables.h" #include "Core/MIPS/MIPSAnalyst.h" #include "Core/MIPS/x86/Jit.h" #include "Core/MIPS/x86/Asm.h" #include "Core/MIPS/x86/RegCache.h" using namespace Gen; static const int allocationOrder[] = { // R12, when used as base register, for example in a LEA, can generate bad code! Need to look into this. #ifdef _M_X64 #ifdef _WIN32 RSI, RDI, R13, R14, R8, R9, R10, R11, R12, //, RCX #else RBP, R13, R14, R8, R9, R10, R11, R12, //, RCX #endif #elif _M_IX86 ESI, EDI, EBP, EDX, ECX, // Let's try to free up EBX as well. #endif }; GPRRegCache::GPRRegCache() : emit(0), mips(0) { memset(regs, 0, sizeof(regs)); memset(xregs, 0, sizeof(xregs)); } void GPRRegCache::Start(MIPSState *mips, MIPSAnalyst::AnalysisResults &stats) { this->mips = mips; for (int i = 0; i < NUM_X_REGS; i++) { xregs[i].free = true; xregs[i].dirty = false; xregs[i].allocLocked = false; } for (int i = 0; i < NUM_MIPS_GPRS; i++) { regs[i].location = GetDefaultLocation(i); regs[i].away = false; regs[i].locked = false; } // todo: sort to find the most popular regs /* int maxPreload = 2; for (int i = 0; i < NUM_MIPS_GPRS; i++) { if (stats.numReads[i] > 2 || stats.numWrites[i] >= 2) { LoadToX64(i, true, false); //stats.firstRead[i] <= stats.firstWrite[i], false); maxPreload--; if (!maxPreload) break; } }*/ //Find top regs - preload them (load bursts ain't bad) //But only preload IF written OR reads >= 3 } // these are MIPS reg indices void GPRRegCache::Lock(int p1, int p2, int p3, int p4) { regs[p1].locked = true; if (p2 != 0xFF) regs[p2].locked = true; if (p3 != 0xFF) regs[p3].locked = true; if (p4 != 0xFF) regs[p4].locked = true; } // these are x64 reg indices void GPRRegCache::LockX(int x1, int x2, int x3, int x4) { if (xregs[x1].allocLocked) { PanicAlert("RegCache: x %i already locked!", x1); } xregs[x1].allocLocked = true; if (x2 != 0xFF) xregs[x2].allocLocked = true; if (x3 != 0xFF) xregs[x3].allocLocked = true; if (x4 != 0xFF) xregs[x4].allocLocked = true; } void GPRRegCache::UnlockAll() { for (int i = 0; i < NUM_MIPS_GPRS; i++) regs[i].locked = false; } void GPRRegCache::UnlockAllX() { for (int i = 0; i < NUM_X_REGS; i++) xregs[i].allocLocked = false; } X64Reg GPRRegCache::GetFreeXReg() { int aCount; const int *aOrder = GetAllocationOrder(aCount); for (int i = 0; i < aCount; i++) { X64Reg xr = (X64Reg)aOrder[i]; if (!xregs[xr].allocLocked && xregs[xr].free) { return (X64Reg)xr; } } //Okay, not found :( Force grab one //TODO - add a pass to grab xregs whose mipsreg is not used in the next 3 instructions for (int i = 0; i < aCount; i++) { X64Reg xr = (X64Reg)aOrder[i]; if (xregs[xr].allocLocked) continue; int preg = xregs[xr].mipsReg; if (!regs[preg].locked) { StoreFromRegister(preg); return xr; } } //Still no dice? Die! _assert_msg_(DYNA_REC, 0, "Regcache ran out of regs"); return (X64Reg) -1; } void GPRRegCache::FlushR(X64Reg reg) { if (reg >= NUM_X_REGS) PanicAlert("Flushing non existent reg"); if (!xregs[reg].free) StoreFromRegister(xregs[reg].mipsReg); } int GPRRegCache::SanityCheck() const { for (int i = 0; i < NUM_MIPS_GPRS; i++) { if (regs[i].away) { if (regs[i].location.IsSimpleReg()) { Gen::X64Reg simple = regs[i].location.GetSimpleReg(); if (xregs[simple].allocLocked) return 1; if (xregs[simple].mipsReg != i) return 2; } else if (regs[i].location.IsImm()) return 3; } } return 0; } void GPRRegCache::DiscardRegContentsIfCached(int preg) { if (regs[preg].away && regs[preg].location.IsSimpleReg()) { X64Reg xr = regs[preg].location.GetSimpleReg(); xregs[xr].free = true; xregs[xr].dirty = false; xregs[xr].mipsReg = -1; regs[preg].away = false; regs[preg].location = GetDefaultLocation(preg); } } void GPRRegCache::SetImmediate32(int preg, u32 immValue) { // ZERO is always zero. Let's just make sure. if (preg == 0) immValue = 0; DiscardRegContentsIfCached(preg); regs[preg].away = true; regs[preg].location = Imm32(immValue); } bool GPRRegCache::IsImmediate(int preg) const { // Always say yes for ZERO, even if it's in a temp reg. if (preg == 0) return true; return regs[preg].location.IsImm(); } u32 GPRRegCache::GetImmediate32(int preg) const { _dbg_assert_msg_(JIT, IsImmediate(preg), "Reg %d must be an immediate.", preg); // Always 0 for ZERO. if (preg == 0) return 0; return regs[preg].location.GetImmValue(); } const int *GPRRegCache::GetAllocationOrder(int &count) { count = sizeof(allocationOrder) / sizeof(const int); return allocationOrder; } OpArg GPRRegCache::GetDefaultLocation(int reg) const { return M(&mips->r[reg]); } void GPRRegCache::KillImmediate(int preg, bool doLoad, bool makeDirty) { if (regs[preg].away) { if (regs[preg].location.IsImm()) BindToRegister(preg, doLoad, makeDirty); else if (regs[preg].location.IsSimpleReg()) xregs[RX(preg)].dirty |= makeDirty; } } void GPRRegCache::BindToRegister(int i, bool doLoad, bool makeDirty) { if (!regs[i].away && regs[i].location.IsImm()) PanicAlert("Bad immediate"); if (!regs[i].away || (regs[i].away && regs[i].location.IsImm())) { X64Reg xr = GetFreeXReg(); if (xregs[xr].dirty) PanicAlert("Xreg already dirty"); if (xregs[xr].allocLocked) PanicAlert("GetFreeXReg returned locked register"); xregs[xr].free = false; xregs[xr].mipsReg = i; xregs[xr].dirty = makeDirty || regs[i].location.IsImm(); OpArg newloc = ::Gen::R(xr); if (doLoad) { // Force ZERO to be 0. if (i == 0) emit->MOV(32, newloc, Imm32(0)); else emit->MOV(32, newloc, regs[i].location); } for (int j = 0; j < 32; j++) { if (i != j && regs[j].location.IsSimpleReg() && regs[j].location.GetSimpleReg() == xr) { ERROR_LOG(JIT, "BindToRegister: Strange condition"); Crash(); } } regs[i].away = true; regs[i].location = newloc; } else { // reg location must be simplereg; memory locations // and immediates are taken care of above. xregs[RX(i)].dirty |= makeDirty; } if (xregs[RX(i)].allocLocked) { PanicAlert("Seriously WTF, this reg should have been flushed"); } } void GPRRegCache::StoreFromRegister(int i) { if (regs[i].away) { bool doStore; if (regs[i].location.IsSimpleReg()) { X64Reg xr = RX(i); xregs[xr].free = true; xregs[xr].mipsReg = -1; doStore = xregs[xr].dirty; xregs[xr].dirty = false; } else { //must be immediate - do nothing doStore = true; } OpArg newLoc = GetDefaultLocation(i); // But never store to ZERO. if (doStore && i != 0) emit->MOV(32, newLoc, regs[i].location); regs[i].location = newLoc; regs[i].away = false; } } void GPRRegCache::Flush() { for (int i = 0; i < NUM_X_REGS; i++) { if (xregs[i].allocLocked) PanicAlert("Someone forgot to unlock X64 reg %i.", i); } for (int i = 0; i < NUM_MIPS_GPRS; i++) { if (regs[i].locked) { PanicAlert("Somebody forgot to unlock MIPS reg %i.", i); } if (regs[i].away) { if (regs[i].location.IsSimpleReg()) { X64Reg xr = RX(i); StoreFromRegister(i); xregs[xr].dirty = false; } else if (regs[i].location.IsImm()) { StoreFromRegister(i); } else { _assert_msg_(DYNA_REC,0,"Jit64 - Flush unhandled case, reg %i PC: %08x", i, mips->pc); } } } }
glaubitz/ppsspp-debian
Core/MIPS/x86/RegCache.cpp
C++
gpl-2.0
8,092
<?php use HRNParis\mediapartners as mediapartners; use HRNParis\main as main; include_once('controllers/mediapartners_main.php'); include_once('controllers/main.php'); $main = new main\main; $sponsors = new mediapartners\mediapartners_main; ?> <!doctype html> <html lang="en"> <head> <meta name="description" content="The fastest growing HR event in the world. Paris October 24 - 25"> <meta name="keywords" content="HR Conference, HR Tech Europe, HR Tech Conference, HR Congress, HR Tech Congress, iRecruit, disruptHR "> <meta name="author" content="HRN Europe - The Pan European HR Network"> <meta name="developer" content="Developed by: TesseracT - bottyan.tamas@web-developer.hu, Benedek Nagy - trialshock@gmail.com, Myrrdhinn - balazs.pentek@web-developer.hu"> <meta charset="utf-8" /> <meta name="viewport" content="initial-scale=1, maximum-scale=1"> <title>HR Tech World Congress | Press</title> <!-- Open Graph data --> <meta property="og:site_name" content="HR Tech World Congress"/> <meta property="og:title" content="HR Tech World Congress | Press"/> <meta property="og:description" content="The fastest growing HR event in the world! Paris October 24 - 25"/> <meta property="og:url" content="http://hrtechcongress.com/press"> <meta property="og:type" content="website"/> <meta property="og:image" content="http://hrtechcongress.com/img/preview-images/preview-image-1.jpg" /> <meta property="og:image" content="http://hrtechcongress.com/img/preview-images/preview-image-2.jpg" /> <meta property="og:image" content="http://hrtechcongress.com/img/preview-images/preview-image-3.jpg" /> <!--Include Raleway Google Font --> <link href='http://fonts.googleapis.com/css?family=Raleway:400,100,200,300,500,600,700,800,900' rel='stylesheet' type='text/css'> <!-- Include Source Sans Prog Google Font --> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,200,200italic,300,300italic,400italic,600,600italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <!--Include Include Proxima Nova Font (Adobe Typekit) --> <script src="//use.typekit.net/gku8ogo.js"></script> <script>try{Typekit.load();}catch(e){}</script> <!--Include Font Awesome --> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <!-- Favicon --> <link rel="apple-touch-icon" sizes="57x57" href="img/favicon/apple-touch-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="img/favicon/apple-touch-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="img/favicon/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="img/favicon/apple-touch-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="img/favicon/apple-touch-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="img/favicon/apple-touch-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="img/favicon/apple-touch-icon-144x144.png"> <link rel="icon" type="image/png" href="img/favicon/favicon-32x32.png" sizes="32x32"> <link rel="icon" type="image/png" href="img/favicon/favicon-96x96.png" sizes="96x96"> <link rel="icon" type="image/png" href="img/favicon/favicon-16x16.png" sizes="16x16"> <link rel="manifest" href="img/favicon/manifest.json"> <meta name="msapplication-TileColor" content="#da532c"> <meta name="msapplication-TileImage" content="img/favicon/mstile-144x144.png"> <meta name="theme-color" content="#ffffff"> <link rel="shortcut icon" href="favicon.ico"> <!-- Include General CSS Definitions --> <link rel="stylesheet" href="css/general.css" /> <!-- Include the Navigation Menu`s CSS Definitions --> <link rel="stylesheet" href="css/menu.css" /> <!-- Include Custom CSS Definitions --> <link rel="stylesheet" href="css/press.css" /> <link rel="stylesheet" href="css/travel-icons.css" /> <!-- Include Footer CSS Definitions --> <link rel="stylesheet" href="css/footer.css" /> <!-- Include jQuery --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <!-- Scroll to top JS --> <script src="js/gotopscroll.js"></script> <!-- Mobile Menu JS --> <script src="js/menu.js"></script> <!-- Include Reveal Modal --> <link rel="stylesheet" href="vendor/reveal/reveal.css"> <script src="vendor/reveal/jquery.reveal.js" type="text/javascript"></script> <!-- Travel JS --> <script src="js/press.js"></script> <!-- Thank you modal --> <script type="text/javascript"> $(document).ready(function() { if(window.location.href.indexOf('#ThankYouBrochureModal') != -1) { jQuery("#ThankYouBrochureModal").reveal(); } if(window.location.href.indexOf('#ThankYouJoinModal') != -1) { jQuery("#ThankYouJoinModal").reveal(); } }); </script> <!-- END Thank you modal --> <!-- GOOGLE ANALYTICS TRACKING SCRIPT --> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-55976467-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body> <nav> <div id="MobileMenuContainer"> <a href="http://hrtechcongress.com" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'LogoHome']);"> <div id="MobileMenuLogo"></div> </a> <div id="MobileMenuButton" onClick='ShowMobileMenu()'></div> <div id="MobileNav" class="sidebar"> <div id="MobileMenuListContainer"> <img id="MobileMenuCloseButton" src="img/menu/mobile-close-button.png" alt="X" onClick='HideMobileMenu()'> <ul id="MobileUl"> <li><a href="http://hrtechcongress.com#AboutSection" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'About']);" title="About">About</a></li> <li><a href="speakers" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Speakers']);" title="Speakers">Speakers</a></li> <li><a href="sponsors" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Sponsors']);" title="Sponsors">Sponsors</a></li> <li><a href="press" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Press']);" title="Press" id="MobileMenuItemHovered">Press</a></li> <li><a href="agenda" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Agenda']);" title="Agenda">Agenda</a></li> <li><a href="travel" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Travel']);" title="Travel">Travel</a></li> <li><a href="floorplan" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Floorplan']);" title="Floorplan">Floorplan</a></li> <li><a href="http://blog.hrtecheurope.com/" onClick="_gaq.push(['_trackEvent', 'Navigation', 'ExternalForward', 'Blog']);" title="Blog">Blog</a></li> <li><a href="contact" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Contact']);" title="Get In Touch">Get In Touch</a></li> <li><a href="tickets" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Tickets']);" title="Get Tickets"><i class="fa fa-ticket"></i> Get Tickets</a></li> </ul> </div> </div> </div> </nav> <!-- MAIN MENU --> <nav id="DesktopMenu"> <a href="http://hrtechcongress.com" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'LogoHome']);"> <div id="HRTechDesktopLogo"> </div> </a> <ul id="DesktopMenuList"> <a href="http://hrtechcongress.com#AboutSection" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'About']);" title="About"> <li class="DesktopMenuItem" id="MenuItemAbout">ABOUT</li> </a> <a href="speakers" title="Speakers" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Speakers']);"> <li class="DesktopMenuItem" id="MenuItemSpeakers">SPEAKERS</li> </a> <a href="sponsors" title="Sponsors" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Sponsors']);"> <li class="DesktopMenuItem" id="MenuItemSponsors">SPONSORS</li> </a> <a href="press" title="Press" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Press']);"> <li class="DesktopMenuItem DesktopMenuItemHovered">PRESS</li> </a> <a href="agenda" title="Agenda" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Agenda']);"> <li class="DesktopMenuItem">AGENDA</li> </a> <li class="DesktopMenuItem" id="InfoDD"><a href="#" title="" >INFORMATION</a> <!-- Information Dropdown --> <div id="InformationMenu"> <div class="ArrowUpDD"></div> <ul class="Dropdown" id="InformationDropdown"> <a href="travel" title="Travel" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Travel']);"><li>Travel</li></a> <a href="floorplan" title="Floorplan" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Floorplan']);"><li>Floorplan</li></a> <a href="contact" title="Get in Touch" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Contact']);"><li>Get in Touch</li></a> <a href="http://blog.hrtecheurope.com/" title="Blog" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Blog']);"><li>Blog</li></a> </ul> </div> </li> <!-- Information Dropdown --> <a href="tickets" title="Get Tickets" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Tickets']);"> <li class="DesktopMenuItem" id="DesktopGetTickets"><i class="fa fa-ticket"></i> GET TICKETS</li> </a> </ul> <div id="DesktopMenuSocialIcons"> <a href="https://twitter.com/hrtechworld" target="_blank" title="Twitter" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Twitter']);"> <div id="DesktopMenuTwitterIcon" class="DesktopMenuSocialIcon"></div> </a> <a href="https://www.linkedin.com/grp/home?gid=1909337" target="_blank" title="LinkedIn" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'LinkedIn']);"> <div id="DesktopMenuLinkedInIcon" class="DesktopMenuSocialIcon"></div> </a> <a href="https://www.facebook.com/worldhrtech?ref=hl" target="_blank" title="Facebook" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Facebook']);"> <div id="DesktopMenuFacebookIcon" class="DesktopMenuSocialIcon"></div> </a> <a href="http://www.slideshare.net/hrtecheurope/presentations" target="_blank" title="Slideshare" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Slideshare']);"> <div id="DesktopMenuSlideShareIcon" class="DesktopMenuSocialIcon"></div> </a> <a href="https://www.flickr.com/photos/hrtecheurope/sets/with/72157651210562997" target="_blank" title="Flickr" onClick="_gaq.push(['_trackEvent', 'Navigation', 'InternalForward', 'Flickr']);"> <div id="DesktopMenuFlickrIcon" class="DesktopMenuSocialIcon"></div> </a> </div> </nav> <!-- END MAIN MENU --> <!-- Social Share Widget --> <!-- Twitter share Link --> <script> $(document).ready(function() { $('.twittershare').click(function(event) { var width = 575, height = 400, left = ($(window).width() - width) / 2, top = ($(window).height() - height) / 2, url = this.href, opts = 'status=1' + ',width=' + width + ',height=' + height + ',top=' + top + ',left=' + left; window.open(url, 'twitter', opts); return false; }) }); </script> <!-- Twitter share Link --> <div id="SocialWidgetWrapper"> <a href="http://www.facebook.com/share.php?u=http://hrtechcongress.com/press&title=HRTechCongress" target="_blank" onClick="_gaq.push(['_trackEvent', 'FloatingSocialShare', 'ExternalForward', 'Facebook']);"> <div id="FacebookShare"><i class="fa fa-facebook"></i></div> </a> <a href="https://twitter.com/home?status=Journalist+%26+Bloggers+of+HR+Tech+World+-+Sharing+News+and+Updates+Live%21%0Ahttp://hrtechcongress.com/press%0A%23hrtechworld %23hrtech" class="twittershare twitter" data-text="HR Tech World Congress 2015 – Unleash Your People!" onClick="_gaq.push(['_trackEvent', 'FloatingSocialShare', 'ExternalForward', 'Twitter']);"> <div id="TwitterShare"><i class="fa fa-twitter"></i></div> </a> <a target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&url=http://hrtechcongress.com/press&title=HR Tech World Congress 2015 – Unleash Your People!" onClick="_gaq.push(['_trackEvent', 'FloatingSocialShare', 'ExternalForward', 'LinkedIn']);"> <div id="LinkedInShare"><i class="fa fa-linkedin"></i></div> </a> </div> <!--END Social Share Widget --> <!-- Header --> <header> <div id="HeaderInnerContainer"> <h1>Press</h1> <p id="LightParagraph">A buzzing space for Media, Bloggers, Editors, Journalists and Reporters - from all over the world to share the latest news in HR and Technology.</p> <a href="" title="Join Press" data-reveal-id="JoinPressModal" onClick="_gaq.push(['_trackEvent', 'PressPage', 'ExternalForward', 'JoinPress']);"><div id="BookNowHeaderButton" class="FontRaleway">Join Press</div></a> <div id="ScrollDownHeaderLinkContainer"> <a href="#TabPanelAnchor" title="Scroll down for more..." > <span>Scroll Down For More...</span> <img id="ScrollDownIcon" src="img/press/scroll-down-icon.png" alt="Scroll Down"> </a> </div> </div> </header> <!-- END Header --> <!-- Tab Panel Buttons --> <div id="TabPanelButtonsContainer"> <div id="MediaPartnersButton" class="TabPanelButton" onClick="_gaq.push(['_trackEvent', 'PressPage', 'OpenCollapsiblePanel', 'MediaPartners']);"> <div class="ArrowUp"></div> <span class="DesktopText">Media Partners</span> <i class="icon icon-media-partners"></i> </div> <div id="BlogSquadButton" class="TabPanelButton" onClick="_gaq.push(['_trackEvent', 'PressPage', 'OpenCollapsiblePanel', 'BlogSquad']);"> <div class="ArrowUp"></div> <span class="DesktopText">Blog Squad</span> <i class="icon icon-blog-squad"></i> </div> </div> <!-- END Tab Panel Buttons --> <!-- Tab Panels --> <a id="TabPanelAnchor" style="position: relative; top: -8vw;"></a> <div id="TabPanelWrapper"> <!-- Media Partners --> <section class="TabPanel" id="MediaPartners"> <h2 class="InvisibleHeadline">Media Partners</h2> <?php $content = $sponsors->sponsors_grid(1); echo $content; ?> </section> <!-- END Media Partners --> <!-- Blog Squad --> <section class="TabPanel" id="BlogSquad"> <h2 class="InvisibleHeadline">Blog Squad</h2> <div id="BloggerContainer"> <ul> <?php $content = $main->press(1); if(isset($content)) { echo $content; } ?> </ul> </div> <script src="vendor/sliphover/jquery.sliphover.js"></script> <script type="text/javascript"> $(function(){ $('#BlogSquad').sliphover({ }); }) </script> </section> <!-- END Blog Squad --> </div> <!-- END Tab Panels --> <!-- FOOTER --> <footer> <div id="FooterWrapper"> <div id="FooterLeftWrapper"> <h2 class="Contact FontRaleway">CONTACT</h2> <h3 class="Contact FontProximaNova"><i class="fa fa-phone"></i>+36 1 201 1469</h3> <h3 class="Contact FontProximaNova"><i class="fa fa-phone"></i>UK/IE +44 20 34 689 689</h3> <h3 class="Contact FontProximaNova"><i class="fa fa-envelope"></i>hrn@hrneurope.com</h3> <div id="GetInTouchButtonContainer"> <span data-reveal-id="DownloadBrochureModal" onClick="_gaq.push(['_trackEvent', 'Footer', 'ModalOpen', 'DownloadBrochure']);"> <button class="BlueButton FontRaleway" id="DownloadBrochureButton" >Request Brochure</button> </span> </div> </div> <div id="FooterRightWrapper"> <form> <h2>SIGN UP FOR NEWSLETTER</h2> <input type="text"> <input type="submit" value="SEND" onClick="_gaq.push(['_trackEvent', 'Footer', 'FormSubmission', 'SignUpForNewsletter']);"> </form> <div id="FooterSocialIconsContainer"> <a href="https://twitter.com/hrtechworld" target="_blank" title="HR Tech World - Twitter" onClick="_gaq.push(['_trackEvent', 'Footer', 'ExternalForward', 'Twitter']);"> <div id="FooterTwitter" class="FooterSocialIcon"></div> </a> <a href="https://www.facebook.com/worldhrtech?ref=hl" target="_blank" title="HR Tech Europe - Facebook" onClick="_gaq.push(['_trackEvent', 'Footer', 'ExternalForward', 'Facebook']);"> <div id="FooterFacebook" class="FooterSocialIcon"></div> </a> <a href="https://www.linkedin.com/grp/home?gid=1909337" target="_blank" title="HR Tech Europe - LinkedIn" onClick="_gaq.push(['_trackEvent', 'Footer', 'ExternalForward', 'LinkedIn']);"> <div id="FooterLinkedIn" class="FooterSocialIcon"></div> </a> <a href="http://www.slideshare.net/hrtecheurope/presentations" target="_blank" title="HR Tech Europe - SlideShare" onClick="_gaq.push(['_trackEvent', 'Footer', 'ExternalForward', 'SlideShare']);"> <div id="FooterSlideShare" class="FooterSocialIcon"></div> </a> <a href="https://www.flickr.com/photos/hrtecheurope/sets/with/72157651210562997" target="_blank" title="HR Tech Europe - Flickr" onClick="_gaq.push(['_trackEvent', 'Footer', 'ExternalForward', 'Flickr']);"> <div id="FooterFlickr" class="FooterSocialIcon"></div> </a> </div> </div> </div> <div id="TransparentFooter"> <div id="TransparentFooterInnerContainer"> <div id="TransparentFooterImage"><img src="img/footer/footer-hrtech-logo.png" alt="HR Tech World Congress logo"></div> <div id="TransparentFooterTextContainer"> <h6 class="TransparentFooterText FontRaleway" id="CopyrightText">Copyright &copy; 2015 HRN Europe. All Rights Reserved.</h6> <h6 class="TransparentFooterText FontRaleway" id="PrivacyText">Privacy Policy | Terms and Conditions</h6> </div> <div style="clear: both;"></div> </div> </div> </footer> <!-- END FOOTER --> <!-- Go to Top Button --> <a href="#" class="GoTopButton"> <div id="GoTopImg"><i class="fa fa-caret-up"></i></div> </a> <!-- END Go to Top Button --> <!-- Download Brochure Modal --> <div id="DownloadBrochureModal" class="reveal-modal" data-reveal> <a class="close-reveal-modal">&#215;</a> <h2>Download Brochure</h2> <p>Thank you for your request. Please fill in all the fields below!</p> <!-- BEGINING of : DOWNLOAD BROCHURE MODAL FORM --> <form action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST"> <input type=hidden name="oid" value="00DD0000000nwgk"> <input type=hidden name="retURL" value="http://hrtechcongress.com/press#ThankYouBrochureModal"> <div class="InputFieldsContainer"> <input required placeholder="First Name *" id="first_name" maxlength="40" name="first_name" size="20" type="text" /> <input required placeholder="Last Name *" id="last_name" maxlength="80" name="last_name" size="20" type="text" /> </div> <div class="InputFieldsContainer"> <input required placeholder="Email Address *" id="email" maxlength="80" name="email" size="20" type="text" /> <input required placeholder="Phone Number *" id="phone" maxlength="40" name="phone" size="20" type="text" /> </div> <div class="InputFieldsContainer"> <input required placeholder="Company *" id="company" maxlength="40" name="company" size="20" type="text" /> <input required placeholder="Job Title *" id="title" maxlength="40" name="title" size="20" type="text" /> </div> <select style="display:none;" id="lead_source" name="lead_source"> <option selected="selected" value="HRTechParis2015-DownloadPDF">HRTechParis2015-DownloadPDF</option> </select> <input onClick="_gaq.push(['_trackEvent', 'DownloadPDFForm', 'FromSubmission', 'InquirySent']);" class="submitbutton" type="submit" name="submit" value="SEND"> </form> <!-- END of : DOWNLOAD BROCHURE MODAL FORM --> </div> <!-- END Download Brochure Modal --> <!-- Thank You Brochure Modal --> <div id="ThankYouBrochureModal" class="reveal-modal" data-reveal> <a class="close-reveal-modal">&#215;</a> <h2>Thank you!</h2> <p>You shall receive an email shortly from one of our team.</p> </div> <!-- END Thank You Modal --> <!-- Join Press Modal --> <div id="JoinPressModal" class="reveal-modal" data-reveal> <a class="close-reveal-modal">&#215;</a> <h2>Join Press</h2> <!-- BEGINING of : JOIN PRESS MODAL FORM --> <form method="POST"> <input type=hidden name="retURL" value="http://hrtechcongress.com/press#ThankYouJoinModal"> <div class="InputFieldsContainer"> <input required placeholder="First Name *" id="press_first_name" maxlength="40" name="first_name" size="20" type="text" /> <input required placeholder="Last Name *" id="press_last_name" maxlength="80" name="last_name" size="20" type="text" /> </div> <div class="InputFieldsContainer"> <input required placeholder="Email Address *" id="press_email" maxlength="80" name="email" size="20" type="text" /> <input required placeholder="Phone Number *" id="press_phone" maxlength="40" name="phone" size="20" type="text" /> </div> <div class="InputFieldsContainer"> <input required placeholder="Company *" id="press_company" maxlength="40" name="company" size="20" type="text" /> <input required placeholder="Job Title *" id="press_title" maxlength="40" name="title" size="20" type="text" /> </div> <input onClick="_gaq.push(['_trackEvent', 'JoinPressForm', 'FromSubmission', 'InquirySent']);" class="submitbutton" id="JoinPressButton" type="submit" name="submit" value="SEND"> </form> <!-- END of : JOIN PRESS MODAL FORM --> </div> <!-- END Join Press Modal --> <!-- Thank You Brochure Modal --> <div id="ThankYouJoinModal" class="reveal-modal" data-reveal> <a class="close-reveal-modal">&#215;</a> <h2>Thank you!</h2> <p>You shall receive an email shortly from one of our team.</p> </div> <!-- END Thank You Modal --> <!-- Named anchor Hashtag script --> <script type="text/javascript"> $('a[href*=#]:not([href=#])').click(function(){ $('html, body').animate({ scrollTop: $( $(this).attr('href') ).offset().top }, 1000); return false; }); </script> <!-- Start of Async HubSpot Analytics Code --> <script type="text/javascript"> (function(d,s,i,r) { if (d.getElementById(i)){return;} var n=d.createElement(s),e=d.getElementsByTagName(s)[0]; n.id=i;n.src='//js.hs-analytics.net/analytics/'+(Math.ceil(new Date()/r)*r)+'/412210.js'; e.parentNode.insertBefore(n, e); })(document,"script","hs-analytics",300000); </script> <!-- End of Async HubSpot Analytics Code --> </body> </html>
HRNIT/paris2015
press.php
PHP
gpl-2.0
23,265
//BE NAME DOOST #include <iostream> #include <string> #include <vector> #include <algorithm> #include <cmath> #include <set> #include <iostream> using namespace std; int main() { string a,b; cin>>a>>b; set <char> d; for(int i=0;i<a.size();i++) d.insert(a[i]); int B=0,C=0; for(int i=0;i<b.size();i++) { if(a[i]==b[i]) B++; else { set <char> tmp=d; int s=tmp.size(); tmp.insert(b[i]); if(s==tmp.size()) C++; } } cout<<B<<" "<<C; }
hrmon/judges
SGU/accepted/p486.cpp
C++
gpl-2.0
470
package server.thread.systemSettingsThread; import java.io.IOException; import java.io.ObjectInputStream; import java.net.Socket; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import server.serverMain.serverMain; import server.thread.systemMessageThread.sendSystemMessageThread; import common.message.mainInfo; import common.message.node_public; import common.message.systemSettings; /** * 2011年10月 * * 山东科技大学信息学院 版权所有 * * 联系邮箱:415939252@qq.com * * Copyright © 1999-2012, sdust, All Rights Reserved * * @author 王昌帅 * */ public class setting_dealingThread extends Thread { Socket client; systemSettings settings; Statement state1; public setting_dealingThread(Socket s_client) throws IOException, SQLException { this.state1 = serverMain.con1.createStatement(); this.client = s_client; // start(); } public void run() { try { ObjectInputStream oin = new ObjectInputStream(client.getInputStream()); settings = (systemSettings) oin.readObject(); String sql_update = "update whetherCanAdd set can = " + settings.whetherCanAdd + " where qq = '" + settings.qq + "';"; state1.execute(sql_update); state1.close(); String text = new String("您的设置已生效"); sendSystemMessageThread sender = new sendSystemMessageThread(settings.qq, text); client.close(); } catch (Exception e) { e.printStackTrace(); } } }
wangchangshuai/fei_Q
server/src/server/thread/systemSettingsThread/setting_dealingThread.java
Java
gpl-2.0
1,584
<?php /** * Description of class-fscf-util * Utility class sets default variables, wp actions, and sanitize functions * Functions are called statically, so no need to instantiate the class * @authors Mike Challis and Ken Carlson */ class FSCF_Util { static $global_defaults, $form_defaults, $field_defaults; static $global_options, $form_options, $admin_notices; static function setup() { // Come here when the plugin is run // load plugin textdomain for languages add_action('plugins_loaded', 'FSCF_Util::fscf_init_languages'); // imports old settings on plugin activate or first time upgrade from 3.xx to 4.xx add_action('init', 'FSCF_Util::import',1); // will start PHP session only if they are enabled (not enabled by default) add_action('init', 'FSCF_Util::fscf_init_session',1); // process the form POST logic add_action('init', 'FSCF_Process::process_form',10); // use shortcode to print the contact form or process contact form logic // can use dashes or underscores: [si-contact-form] or [si_contact_form] add_shortcode('si_contact_form', 'FSCF_Display::process_short_code', 1); add_shortcode('si-contact-form', 'FSCF_Display::process_short_code', 1); // If you want to use shortcodes in your widgets or footer add_filter('widget_text', 'do_shortcode'); add_filter('wp_footer', 'do_shortcode'); if ( is_admin() ) { // Set up admin actions add_action( 'admin_menu', 'FSCF_Options::register_options_page' ); // imports old settings on plugin activate or first time upgrade from 3.xx to 4.xx add_action( 'admin_init', 'FSCF_Util::import',1 ); add_action( 'admin_init', 'FSCF_Options::initialize_options' ); add_action( 'admin_notices', 'FSCF_Util::admin_notice' ); add_action( 'admin_enqueue_scripts', 'FSCF_Util::enqueue_admin_scripts' ); add_action( 'admin_footer', 'FSCF_Util::fscf_admin_footer' ); // adds "Settings" link to the plugin action page add_filter( 'plugin_action_links', 'FSCF_Util::fscf_plugin_action_links',10,2); } else { add_action( 'wp_footer', 'FSCF_Util::fscf_wp_footer' ); } return; } static function import() { // called all the time // Load global options self::$global_options = get_option( 'fs_contact_global' ); if ( self::$global_options ) { // Update the options tables entries if necessary self::update_options_version(); } else { // an import might be needed, run it now self::import_forced(); } // New options table entries for individual forms will be created by FSCF_Options::get_options() // when it is called, so don't need to do it here. return; } static function import_forced($force = '') { // conditionally imports old settings only if they exist // see if upgrading from an older version $old_global_options = get_option('si_contact_form_gb'); if ($old_global_options) { // import now require_once FSCF_PATH . 'includes/class-fscf-import.php'; FSCF_Import::import_old_version($force); } else { // old options did not exist self::$global_options = FSCF_Util::get_global_options(); // Is this is a really old version, prior to 2.6.5 (earlier versions did not have global options) $temp = get_option( 'si_contact_form' ); if ( ! empty($temp) ) { FSCF_Util::add_admin_notice(__( '<b>Warning</b>: Fast Secure Contact Form cannot import settings because the previous version is too old. Installed as new.', 'si-contact-form' ), 'error'); self::$global_options['import_success'] = false; self::$global_options['import_msg'] = true; update_option( 'fs_contact_global', self::$global_options ); } } return; } static function fscf_init_languages() { if (function_exists('load_plugin_textdomain')) { load_plugin_textdomain('si-contact-form', false, 'si-contact-form/languages' ); } } static function fscf_init_session() { self::get_global_options(); // start the PHP session if enabled - used by shortcode attributes (and the CAPTCHA, but only when enable_php_sessions) // PHP Sessions are no longer enabled by default allowing for best compatibility with servers, caching, themes, and other plugins. // This should resolve any PHP sessions related issues some users had. if ( self::$global_options['enable_php_sessions'] == 'true' ) { FSCF_Util::start_session(); } } static function enqueue_admin_scripts( $hook ) { // Add jquery and css for tabs on options page only for this plugin if( strpos ( $hook, 'si-contact-form' ) > 0 ) { wp_enqueue_script('thickbox'); // for constant contact addon wp_enqueue_style('thickbox'); // for constant contact addon wp_enqueue_script( 'jquery-ui-core' ); wp_enqueue_script( 'jquery-ui-tabs' ); wp_enqueue_script( 'jquery-ui-sortable' ); // used for drag and drop ordering of fields wp_enqueue_script( 'fscf_scripts_admin', plugins_url( 'si-contact-form/includes/fscf-scripts-admin.js' ), false, FSCF_BUILD ); wp_enqueue_script( 'fscf_scripts', plugins_url( 'si-contact-form/includes/fscf-scripts.js' ), false, FSCF_BUILD ); // Load jquery-ui css, depending on WP version if ( version_compare( get_bloginfo('version'), '3.5', '<' ) ) wp_enqueue_style( 'jquery-ui', plugins_url( 'si-contact-form/includes/jquery-ui-1820.css' ) ); else wp_enqueue_style( 'jquery-ui', plugins_url( 'si-contact-form/includes/jquery-ui-191.css' ) ); // Set up array of phrases used in scripts-admin.js for translation // NOTE: Some of the phrases below are used to match button values in FSCF_Option. // These must match EXACTLY, or the button presses will not be recognized // XXX consider storing button values in constants so that they WILL be the same $translation_array = array( 'save_changes' => __('Save Changes', 'si-contact-form'), 'send_test' => __('Send Test', 'si-contact-form'), 'copy_settings' => __('Copy Settings', 'si-contact-form'), 'backup_settings' => __('Backup Settings', 'si-contact-form'), 'restore_settings' => __('Restore Settings', 'si-contact-form'), 'confirm_change' => __('Are you sure you want to permanently make this change?', 'si-contact-form'), 'unsaved_changes' => __('You have unsaved changes.', 'si-contact-form'), 'reset_form' => __('Reset Form', 'si-contact-form'), 'reset_all_styles' => __('Reset Styles on all forms', 'si-contact-form'), 'delete_form' => __('Delete Form', 'si-contact-form'), 'import_old_forms' => __('Import forms from 3.xx version', 'si-contact-form'), ); wp_localize_script( 'fscf_scripts_admin', 'fscf_transl', $translation_array ); wp_enqueue_style( 'fscf-styles-admin', plugins_url( 'si-contact-form/includes/fscf-styles-admin.css' ), false, FSCF_BUILD ); } } static function add_date_js() { // add js for forms with date fields //wp_enqueue_style( 'fscf_date_style', plugins_url( 'si-contact-form/date/ctf_epoch_styles.css' ), false, FSCF_BUILD ); wp_enqueue_script( 'fscf_date_js', plugins_url( 'si-contact-form/date/ctf_epoch_classes.js' ), false, FSCF_BUILD ); echo FSCF_Display::$add_date_js; $string = ' var'; $date_var_string = ''; foreach ( FSCF_Display::$add_date_js_array as $v ) { $date_var_string .= ' dp_cal' . "$v,"; } $date_var_string = substr( $date_var_string, 0, -1 ); $string .= "$date_var_string;\n"; if (FSCF_Display::$fscf_use_window_onload) $string .= ' window.onload = function () { '; foreach ( FSCF_Display::$add_date_js_array as $v ) { $string .= " dp_cal$v = new Epoch('epoch_popup$v','popup',document.getElementById('fscf_field$v'));\n"; } if (FSCF_Display::$fscf_use_window_onload) $string .= " };\n"; $string .= "</script>\n"; echo $string; ?> <script type="text/javascript"> //<![CDATA[ var fscf_css = "\n\ <style type='text/css'>\n\ @import url('<?php echo plugins_url( 'si-contact-form/date/ctf_epoch_styles.css').'?ver='.FSCF_BUILD; ?>');\n\ </style>\n\ "; jQuery(document).ready(function($) { $('head').append(fscf_css); }); //]]> </script> <?php echo "<!-- Fast Secure Contact Form plugin - end date field js -->\n\n"; } static function fscf_wp_footer() { // Add js and css needed for the forms if ( isset(FSCF_Display::$add_fscf_script) && FSCF_Display::$add_fscf_script ) { // only include if a form is on this page or post wp_enqueue_script( 'jquery-ui-core' ); // needed for the feature "Has the form already been submitted? If so, reset the form" //wp_enqueue_style( 'fscf-styles', plugins_url( 'si-contact-form/includes/fscf-styles.css' ), false, FSCF_BUILD ); wp_enqueue_script( 'fscf_scripts', plugins_url( 'si-contact-form/includes/fscf-scripts.js' ), false, FSCF_BUILD ); } if ( isset(FSCF_Display::$add_placeholder_script) && FSCF_Display::$add_placeholder_script ) { // makes placeholder work on old browsers wp_enqueue_script( 'fscf_placeholders', plugins_url( 'si-contact-form/includes/fscf-placeholders.min.js' ), false, FSCF_BUILD ); } if ( isset(FSCF_Display::$add_date_js) && FSCF_Display::$add_date_js != '' ) { // add js for forms with date fields FSCF_Util::add_date_js(); } } static function fscf_admin_footer() { // add placeholder javascript in form preview page only if needed if ( isset(FSCF_Display::$placeholder) && FSCF_Display::$placeholder) { // makes placeholder work on old browsers wp_enqueue_script( 'fscf_placeholders', plugins_url( 'si-contact-form/includes/fscf-placeholders.min.js' ), false, FSCF_BUILD ); } if ( isset(FSCF_Display::$add_date_js) && FSCF_Display::$add_date_js != '' ) { // add js for forms with date fields FSCF_Util::add_date_js(); } } static function admin_notice() { // Displays admin notices, if any, at top of admin screen // The notice will appear the next time the WP 'admin_notices' action occurs self::get_global_options(); if ( ! empty(self::$global_options['admin_notices'])) { foreach ( self::$global_options['admin_notices'] as $notice ) { echo $notice; } unset(self::$global_options['admin_notices']); update_option( 'fs_contact_global', self::$global_options ); } } static function add_admin_notice($text, $type) { // Adds an admin notice, to be displayed at the top of the admin screen self::get_global_options (); self::$global_options['admin_notices'][] = ' <div class="' . $type . '"> <p>' . $text . '</p> </div> '; update_option( 'fs_contact_global', self::$global_options ); } static function fscf_plugin_action_links( $links, $file ) { //Static so we don't call plugin_basename on every plugin row. static $this_plugin; if ( ! $this_plugin ) $this_plugin = plugin_basename( FSCF_FILE ); if ( $file == $this_plugin ) { $settings_link = '<a href="plugins.php?page=si-contact-form/si-contact-form.php">' . __( 'Settings', 'si-contact-form' ) . '</a>'; array_unshift( $links, $settings_link ); // before other links } return $links; } // end function fscf_plugin_action_links static function start_session() { // Start PHP Session - used optionally by CAPTCHA and shortcode attributes // NOTE: PHP sessions are OFF by default! and not recommended for best compatibility with servers, caching, themes, and other plugins // this has to be set before any header output // start cookie session if ( !isset( $_SESSION ) ) { // play nice with other plugins //set the $_SESSION cookie into HTTPOnly mode for better security if ( version_compare( PHP_VERSION, '5.2.0' ) >= 0 ) // supported on PHP version 5.2.0 and higher @ini_set( "session.cookie_httponly", 1 ); session_cache_limiter( 'private, must-revalidate' ); session_start(); } } // end function start_session static function get_global_options() { // get plugin options from the WP Options table // if the options array does not exist, use the defaults // Load global options self::$global_options = get_option( 'fs_contact_global' ); if ( ! self::$global_options ) { // Global options array does not exist, so create it if ( !isset( self::$global_defaults ) ) self::set_defaults( ); update_option( 'fs_contact_global', self::$global_defaults ); self::$global_options = get_option( 'fs_contact_global' ); } // if I added any new $global_defaults settings without changing the plugin version number // fill in any missing $global_options with the $global_defaults value so there will be no errors if ( ! isset( self::$global_defaults ) ) self::set_defaults ( ); if ( is_array(self::$global_options) ) self::$global_options = array_merge( self::$global_defaults, self::$global_options ); return(self::$global_options); } // end function get_global_options() static function get_form_options( $form_num, $use_defaults ) { // Get form options for $form_num from WP Options table // If $use_defaults is true, use defaults if form does not exist if ( ! isset( self::$global_defaults ) ) self::set_defaults ( ); // Load global options if necessary if ( ! isset( self::$global_options ) ) self::get_global_options(); $form_options = false; if ( is_numeric($form_num) && $form_num > 0 ) { // Load form options $form_option_name = 'fs_contact_form' . $form_num; $form_options = get_option( $form_option_name ); if ( ! $form_options && $use_defaults ) { // Form options array doesn't exist, so create it if ( "" == self::$form_defaults['form_name'] ) self::$form_defaults['form_name'] = __('Form', 'si-contact-form') .' '. $form_num; update_option( $form_option_name, self::$form_defaults ); $form_options = get_option( $form_option_name ); } } // if I added any new $form_defaults settings without changing the plugin version number // fill in any missing $form_options with the $form_defaults value so there will be no errors if ( is_array($form_options) ) $form_options = array_merge( self::$form_defaults, $form_options ); return($form_options); } static function update_options_version() { // Updates the global and form options table entries if necessary // Called on plugin activation if global options exist if ( version_compare( FSCF_VERSION, self::$global_options['fscf_version'], '>' ) ) { // Update the global options // Unset any removed global options here: // if ( version_compare( self::$global_options['fscf_version'], '4.0', '<' ) ) { // this is where you can run code on a specific version increase specified above } // Merge in global defaults in case there are new global options entries if ( !isset( self::$global_defaults ) ) self::set_defaults(); self::$global_options = array_merge( self::$global_defaults, self::$global_options ); self::$global_options['fscf_version'] = FSCF_VERSION; update_option( 'fs_contact_global', self::$global_options ); // Update the form options foreach ( self::$global_options['form_list'] as $key => $form ) { self::$form_options = get_option( 'fs_contact_form' . $key ); if ( self::$form_options ) { self::$form_options = array_merge( self::$form_defaults, self::$form_options ); // Note: any deleted form options will be removed the next time the form is saved // Update the field arrays foreach ( self::$form_options['fields'] as $k => $fld ) { self::$form_options['fields'][$k] = array_merge ( self::$field_defaults, $fld ); } update_option( 'fs_contact_form' . $key, self::$form_options ); } } // end outer foreach } } // end function update_options_version() static function set_defaults() { // Set up default values // Default global options array self::$global_defaults = array( 'fscf_version' => FSCF_VERSION, 'donated' => 'false', 'vcita_auto_install' => 'false', // vCita Global Settings 'vcita_dismiss' => 'false', // vCita Global Settings 'vcita_initialized' => 'false', // vCita Global Settings 'vcita_show_disable_msg' => 'false', // vCita Global Settings 'vcita_site' => 'www.vcita.com', // vCita Global Settings 'enable_php_sessions' => 'false', 'num_standard_fields' => '4', // Number of fields defined as standard fields // .. if you change this, there are lots of other changes needed to the code! 'max_form_num' => '2', // Highest form ID (used to assign ID to new form) // When forms are deleted, the remaining forms are NOT renumberd, so max_form_num might be greater than // the number of existing forms // import may add a setting: 'import_success' = 'true' (successful) or 'false" (couldn't import) 'form_list' => array( '1' => 'Form 1', '2' => 'Form 2' ) ); // Default style settings $style_defaults = self::set_style_defaults(); // Default options for a single contact form self::$form_defaults = array( 'form_name' => __('New Form', 'si-contact-form'), 'welcome' => __('<p>Comments or questions are welcome.</p>', 'si-contact-form'), 'after_form_note' => '', 'email_to' => __('Webmaster', 'si-contact-form').','.get_option('admin_email'), 'php_mailer_enable' => 'wordpress', 'email_from' => '', 'email_from_enforced' => 'false', 'email_reply_to' => '', 'email_bcc' => '', 'email_subject' => get_option('blogname') . ' ' .__('Contact:', 'si-contact-form'), 'email_subject_list' => '', 'name_format' => 'name', 'preserve_space_enable' => 'false', 'double_email' => 'false', 'name_case_enable' => 'false', 'sender_info_enable' => 'true', 'domain_protect' => 'true', 'domain_protect_names' => '', 'anchor_enable' => 'true', 'email_check_dns' => 'false', 'email_check_easy' => 'false', 'email_html' => 'false', 'email_inline_label' => 'false', 'email_hide_empty' => 'false', 'print_form_enable' => 'false', 'email_keep_attachments' => 'false', 'akismet_disable' => 'false', 'akismet_send_anyway' => 'true', 'captcha_enable' => 'true', 'captcha_small' => 'false', 'captcha_perm' => 'false', 'captcha_perm_level' => 'read', 'honeypot_enable' => 'false', 'redirect_enable' => 'true', 'redirect_seconds' => '3', 'redirect_url' => get_option('home'), 'redirect_query' => 'false', 'redirect_ignore' => '', 'redirect_rename' => '', 'redirect_add' => '', 'redirect_email_off' => 'false', 'silent_send' => 'off', 'silent_url' => '', 'silent_ignore' => '', 'silent_rename' => '', 'silent_add' => '', 'silent_conditional_field' => '', 'silent_conditional_value' => '', 'silent_email_off' => 'false', 'export_ignore' => '', 'export_rename' => '', 'export_add' => '', 'export_email_off' => 'false', 'date_format' => 'mm/dd/yyyy', 'cal_start_day' => '0', 'time_format' => '12', 'attach_types' => 'doc,docx,pdf,txt,gif,jpg,jpeg,png', 'attach_size' => '1mb', 'textarea_html_allow' => 'false', 'enable_areyousure' => 'false', 'enable_submit_oneclick' => 'true', 'auto_respond_enable' => 'false', 'auto_respond_html' => 'false', 'auto_respond_from_name' => get_option('blogname'), 'auto_respond_from_email' => get_option('admin_email'), 'auto_respond_reply_to' => get_option('admin_email'), 'auto_respond_subject' => '', 'auto_respond_message' => '', 'req_field_indicator_enable' => 'true', 'req_field_label_enable' => 'true', 'req_field_indicator' => ' *', 'border_enable' => 'false', 'external_style' => 'false', 'aria_required' => 'false', 'auto_fill_enable' => 'true', 'form_attributes' => '', 'submit_attributes' => '', 'success_page_html' => '', 'title_border' => __( 'Contact Form', 'si-contact-form' ), 'title_dept' => '', 'title_select' => '', 'title_name' => '', 'title_fname' => '', 'title_mname' => '', 'title_miname' => '', 'title_lname' => '', 'title_email' => '', 'title_email2' => '', 'title_subj' => '', 'title_mess' => '', 'title_capt' => '', 'title_submit' => '', 'title_submitting' => '', 'title_reset' => '', 'title_areyousure' => '', 'text_message_sent' => '', 'text_print_button' => '', 'tooltip_required' => '', 'tooltip_captcha' => '', 'tooltip_refresh' => '', 'tooltip_filetypes' => '', 'tooltip_filesize' => '', 'enable_reset' => 'false', 'enable_credit_link' => 'false', 'error_contact_select' => '', 'error_name' => '', 'error_email' => '', 'error_email_check' => '', 'error_email2' => '', 'error_url' => '', 'error_date' => '', 'error_time' => '', 'error_maxlen' => '', 'error_field' => '', 'error_subject' => '', 'error_select' => '', 'error_input' => '', 'error_captcha_blank' => '', 'error_captcha_wrong' => '', 'error_correct' => '', 'error_spambot' => '', 'fields' => array(), 'vcita_scheduling_button' => 'false', 'vcita_scheduling_button_label' => '', 'vcita_approved' => 'false', 'vcita_uid' => '', 'vcita_email' => '', 'vcita_email_new' => ((get_option('admin_email') == 'user@example.com') ? '' : get_option('admin_email')), 'vcita_confirm_token' => '', 'vcita_confirm_tokens' => '', 'vcita_initialized' => 'false', 'vcita_link' => 'false', 'vcita_first_name' => '', 'vcita_last_name' => '', 'vcita_scheduling_button_label' => 'Schedule an Appointment', 'vcita_scheduling_link_text' => 'Click above to schedule an appointment using vCita Online Scheduling', ); // Merge in the style settings // Do it this way so we also have the style settings in a separate array to make validation easier self::$form_defaults = array_merge(self::$form_defaults, $style_defaults); self::get_field_defaults(); // Add the standard fields (Name, Email, Subject, Message) // The main plugin file defines constants to refer to the standard field codes $name = array( 'standard' => '1', // standard field number, otherwise '0' (internal) NEW 'req' => 'true', 'label' => __('Name:', 'si-contact-form'), 'slug' => 'full_name', 'type' => 'text' ); $email = array( 'standard' => '2', // standard field number, otherwise '0' (internal) NEW 'req' => 'true', 'label' => __('Email:', 'si-contact-form'), 'slug' => 'email', 'type' => 'text' ); $subject = array( 'standard' => '3', // standard field number, otherwise '0' (internal) NEW 'req' => 'true', 'label' => __('Subject:', 'si-contact-form'), 'slug' => 'subject', 'type' => 'text' ); $message = array( 'standard' => '4', // standard field number, otherwise '0' (internal) NEW 'req' => 'true', 'label' => __('Message:', 'si-contact-form'), 'slug' => 'message', 'type' => 'textarea' ); // Add the standard fields to the form fields array self::$form_defaults['fields'][] = array_merge(self::$field_defaults, $name); self::$form_defaults['fields'][] = array_merge(self::$field_defaults, $email); self::$form_defaults['fields'][] = array_merge(self::$field_defaults, $subject); self::$form_defaults['fields'][] = array_merge(self::$field_defaults, $message); return(self::$form_defaults); } // end function set_form_defaults() static function set_style_defaults() { // Set up default style values // Called by set_defaults() and FSCF_Options::validate() $style_defaults = array( // labels on top (default) // Alignment DIVs 'form_style' => 'width:99%; max-width:555px;', // Form DIV, how wide is the form DIV 'left_box_style' => 'float:left; width:55%; max-width:270px;', // left box DIV, container for vcita 'right_box_style' => 'float:left; width:235px;', // right box DIV, container for vcita 'clear_style' => 'clear:both;', // clear both 'field_left_style' => 'clear:left; float:left; width:99%; max-width:550px; margin-right:10px;', // field left (wider) 'field_prefollow_style' => 'clear:left; float:left; width:99%; max-width:250px; margin-right:10px;', // field pre follow (narrower) 'field_follow_style' => 'float:left; padding-left:10px; width:99%; max-width:250px;', // field follow 'title_style' => 'text-align:left; padding-top:5px;', // Input labels alignment DIV 'field_div_style' => 'text-align:left;', // Input fields alignment DIV 'captcha_div_style_sm' => 'width:175px; height:50px; padding-top:2px;', // Small CAPTCHA DIV 'captcha_div_style_m' => 'width:250px; height:65px; padding-top:2px;', // Large CAPTCHA DIV 'captcha_image_style' => 'border-style:none; margin:0; padding:0px; padding-right:5px; float:left;', // CAPTCHA image alignment 'captcha_reload_image_style' => 'border-style:none; margin:0; padding:0px; vertical-align:bottom;', // CAPTCHA reload image alignment 'submit_div_style' => 'text-align:left; clear:both; padding-top:15px;', // Submit DIV 'border_style' => 'border:1px solid black; width:99%; max-width:550px; padding:10px;', // style of the form fieldset box (if enabled) // Styles of labels, fields and text 'required_style' => 'text-align:left;', // required field indicator 'required_text_style' => 'text-align:left;', // required field text 'hint_style' => 'font-size:x-small; font-weight:normal;', // small text hints like please enter your email again 'error_style' => 'text-align:left; color:red;', // Input validation messages 'redirect_style' => 'text-align:left;', // Redirecting message 'fieldset_style' => 'border:1px solid black; width:97%; max-width:500px; padding:10px;', // style of the fieldset box (for field) 'label_style' => 'text-align:left;', // Field labels 'option_label_style' => 'display:inline;', // Options labels 'field_style' => 'text-align:left; margin:0; width:99%; max-width:250px;', // Input text fields (out of place here?) 'captcha_input_style' => 'text-align:left; margin:0; width:50px;', // CAPTCHA input field 'textarea_style' => 'text-align:left; margin:0; width:99%; max-width:250px; height:120px;', // Input Textarea 'select_style' => 'text-align:left;', // Input Select 'checkbox_style' => 'width:13px;', // Input checkbox 'radio_style' => 'width:13px;', // Input radio 'placeholder_style' => 'opacity:0.6; color:#333333;', // placeholder style 'button_style' => 'cursor:pointer; margin:0;', // Submit button 'reset_style' => 'cursor:pointer; margin:0;', // Reset button 'vcita_button_style' => 'text-decoration:none; display:block; text-align:center; background:linear-gradient(to bottom, #ed6a31 0%, #e55627 100%); color:#fff !important; padding:8px;', 'vcita_div_button_style' => 'border-left:1px dashed #ccc; margin-top:25px; padding:8px 20px;', // vCita button div box 'powered_by_style' => 'font-size:x-small; font-weight:normal; padding-top:5px; text-align:center;', // the "powered by" link ); return($style_defaults); } // end function set_style_defaults() static function get_field_defaults() { // Default array for a single field self::$field_defaults = array( 'standard' => '0', // standard field number, otherwise '0' (internal) NEW 'options' => '', // Options list for select, radio, and checkbox-multiple 'default' => '', 'inline' => 'false', // Should checkboxes and radio buttons be displayed inline? 'req' => 'false', // required field? 'disable' => 'false', 'follow' => 'false', // controls if this field will be displayed following the previous one on the same line 'hide_label' => 'false', // controls if this field will have a hidden label on the form 'placeholder' => 'false', // controls if the default text will be a placeholder 'label' => __('New Field:', 'si-contact-form'), 'slug' => '', // slug used for query vars, subject and email tags 'type' => 'text', 'max_len' => '', 'label_css' => '', 'input_css' => '', 'attributes' => '', 'regex' => '', 'regex_error' => '', 'notes' => '', 'notes_after' => '', ); return (self::$field_defaults); } static function get_form_defaults() { // Returns the defaults for a form if ( empty(self::$form_defaults) ) self::set_defaults ( ); return(self::$form_defaults); } static function update_lang(&$form_options) { // global FSCF_Options::$form_options, FSCF_Options::$form_optionsion_defaults; // Update a few language options in the form options array // $form_options is a form options array, passed by reference so it can be changed here. // Had to do this becuse the options were actually needed to be set before the language translator was initialized // Update translation for these options (for when switched from English to another lang) if ( $form_options['welcome'] == '<p>Comments or questions are welcome.</p>' ) { $form_options['welcome'] = __( '<p>Comments or questions are welcome.</p>', 'si-contact-form' ); } if ( $form_options['email_to'] == 'Webmaster,' . get_option( 'admin_email' ) ) { $form_options['email_to'] = __( 'Webmaster', 'si-contact-form' ) . ',' . get_option( 'admin_email' ); } if ( $form_options['email_subject'] == get_option( 'blogname' ) . ' ' . 'Contact:' ) { $form_options['email_subject'] = get_option( 'blogname' ) . ' ' . __( 'Contact:', 'si-contact-form' ); } } // end function si_contact_update_lang // checks proper email syntax (not perfect, none of these are, but this is the best I can find) static function validate_email($email) { //check for all the non-printable codes in the standard ASCII set, //including null bytes and newlines, and return false immediately if any are found. if (preg_match("/[\\000-\\037]/",$email)) { return false; } // There's no perfect regular expression to validate email addresses! // http://fightingforalostcause.net/misc/2006/compare-email-regex.php $pattern = "/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,12}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD"; // 09/17/2014 above is updated for new generic top-level domains (gTLDs) released in 2014 and beyond up to 12 characters like .training // (note: does not do IPv6, does not support Internationalized Domain Names, sorry) if (!empty(FSCF_Process::$form_options['email_check_easy']) && FSCF_Process::$form_options['email_check_easy'] == 'true') { $pattern = "/^\S+@\S+$/"; // check for @ sign with non whitespace on either side } if(!preg_match($pattern, $email)){ return false; } // Make sure the domain exists with a DNS check (if enabled in options) // MX records are not mandatory for email delivery, this is why this function also checks A and CNAME records. // if the checkdnsrr function does not exist (skip this extra check, the syntax check will have to do) // checkdnsrr available in Linux: PHP 4.3.0 and higher & Windows: PHP 5.3.0 and higher if (!empty(FSCF_Process::$form_options['email_check_dns']) && FSCF_Process::$form_options['email_check_dns'] == 'true') { if( function_exists('checkdnsrr') ) { list($user,$domain) = explode('@',$email); if(!checkdnsrr($domain.'.', 'MX') && !checkdnsrr($domain.'.', 'A') && !checkdnsrr($domain.'.', 'CNAME')) { // domain not found in DNS return false; } } } return true; } // end function validate_email static function get_captcha_url_cf() { // The captcha URL cannot be on a different domain as the site rewrites to or the cookie won't work // also the path has to be correct or the image won't load. // WP_PLUGIN_URL was not getting the job done! this code should fix it. //http://media.example.com/wordpress WordPress address get_option( 'siteurl' ) //http://tada.example.com Blog address get_option( 'home' ) //http://example.com/wordpress WordPress address get_option( 'siteurl' ) //http://example.com/ Blog address get_option( 'home' ) // even works on multisite, network activated $site_uri = parse_url(get_option('home')); $home_uri = parse_url(get_option('siteurl')); $captcha_url_cf = plugins_url( 'captcha' , FSCF_FILE ); if ($site_uri['host'] == $home_uri['host']) { // use $captcha_url_cf above } else { $captcha_url_cf = get_option( 'home' ) . '/'.PLUGINDIR.'/si-contact-form/captcha'; } // set the type of request (SSL or not) if ( is_ssl() ) { $captcha_url_cf = preg_replace('|http://|', 'https://', $captcha_url_cf); } return $captcha_url_cf; } static function trim_array(&$a) { // Trim string elements in an array, recursing nested arrays // Parameter: $a is an array, passed by reference so we can change its value foreach ($a as $key => $val) { if ( is_array($val) ) { self::trim_array($val); $a[$key] = $val; } else if ( is_string($val) ) { $a[$key] = trim($val); } } } static function unencode_html(&$a) { // Unencode html entities in an array, recursing nested arrays // unencode < > & " ' (less than, greater than, ampersand, double quote, single quote). // Parameter: $a is an array, passed by reference so we can change its value foreach( $a as $key => $val ) { if ( is_array( $val ) ) { self::unencode_html($val); $a[$key] = $val; } else if ( is_string( $val ) ) { $a[$key] = str_replace('&lt;','<',$val); $a[$key] = str_replace('&gt;','>',$val); $a[$key] = str_replace('&#39;',"'",$val); $a[$key] = str_replace('&quot;','"',$val); $a[$key] = str_replace('&amp;','&',$val); } } } // functions for protecting and validating form input vars static function clean_input($string, $preserve_space = 0) { // cleans an input string, or an array of strings if ( is_string($string) ) { if ( $preserve_space ) return self::sanitize_string(strip_tags(stripslashes($string)),$preserve_space); return trim(self::sanitize_string(strip_tags(stripslashes($string)))); } elseif ( is_array($string) ) { reset($string); while (list($key, $value) = each($string)) { $string[$key] = self::clean_input($value,$preserve_space); } return $string; } else { return $string; } } // end function clean_input // functions for protecting and validating form vars static function sanitize_string($string, $preserve_space = 0) { if(!$preserve_space) $string = preg_replace("/ +/", ' ', trim($string)); return preg_replace("/[<>]/", '_', $string); } // end function sanitize_string static function name_case($name) { // A function knowing about name case (i.e. caps on McDonald etc) // Usage: $name = name_case($name); // Consider moving this function to FSCF_Process if ( FSCF_Process::$form_options['name_case_enable'] !== 'true' ) { return $name; // name_case setting is disabled for si contact } if ( $name == '' ) return ''; $break = 0; $newname = strtoupper( $name[0] ); for ( $i = 1; $i < strlen( $name ); $i++ ) { $subed = substr( $name, $i, 1 ); if ( ((ord( $subed ) > 64) && (ord( $subed ) < 123)) || ((ord( $subed ) > 48) && (ord( $subed ) < 58)) ) { $word_check = substr( $name, $i - 2, 2 ); if ( !strcasecmp( $word_check, 'Mc' ) || !strcasecmp( $word_check, "O'" ) ) { $newname .= strtoupper( $subed ); } else if ( $break ) { $newname .= strtoupper( $subed ); } else { $newname .= strtolower( $subed ); } $break = 0; } else { // not a letter - a boundary $newname .= $subed; $break = 1; } } return $newname; } // end function name_case // checks proper url syntax (not perfect, none of these are, but this is the best I can find) // tutorialchip.com/php/preg_match-examples-7-useful-code-snippets/ static function validate_url($url) { $regex = "((https?|ftp)\:\/\/)?"; // Scheme $regex .= "([a-zA-Z0-9+!*(),;?&=\$_.-]+(\:[a-zA-Z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass $regex .= "([a-zA-Z0-9-.]*)\.([a-zA-Z]{2,12})"; // Host or IP $regex .= "(\:[0-9]{2,5})?"; // Port $regex .= "(\/#\!)?"; // Path hash bang (twitter) (mike challis added) $regex .= "(\/([a-zA-Z0-9+\$_-]\.?)+)*\/?"; // Path $regex .= "(\?[a-zA-Z+&\$_.-][a-zA-Z0-9;:@&%=+\/\$_.-]*)?"; // GET Query $regex .= "(#[a-zA-Z_.-][a-zA-Z0-9+\$_.-]*)?"; // Anchor return preg_match("/^$regex$/", $url); } // end function validate_url } // end class FSCF_Util // end of file
dinhkk/viking_vietnam
wp-content/plugins/si-contact-form/includes/class-fscf-util.php
PHP
gpl-2.0
37,762
#!/usr/bin/env python # -*- coding: utf-8 -*- from time import gmtime, strftime import ephem import wx.calendar # Test # here = ephem.Observer() # here.lat = '-17.576166667' # here.lon = '-149.618575000' class App(wx.App): def OnInit(self): self.frame = MyFrame("Lunacy", (50, 60), (640, 220)) self.frame.Show() self.SetTopWindow(self.frame) return True ########################################################################## ## Class MyFrame ########################################################################### class MyFrame(wx.Frame): def __init__(self, title, pos, size): wx.Frame.__init__(self, None, -1, title, pos, size) path = "/usr/share/pixmaps/pidgin/emotes/default/moon.png" icon = wx.Icon(path, wx.BITMAP_TYPE_PNG) self.SetIcon(icon) self.SetSizeHintsSz(wx.Size(640, 220), wx.DefaultSize) gSizer1 = wx.GridSizer(1, 2, 0, 0) fgSizer1 = wx.FlexGridSizer(1, 1, 0, 0) fgSizer1.SetFlexibleDirection(wx.BOTH) fgSizer1.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED) cal = wx.calendar.CalendarCtrl(self, wx.ID_ANY, wx.DefaultDateTime, wx.DefaultPosition, wx.DefaultSize, wx.calendar.CAL_SHOW_HOLIDAYS | wx.calendar.CAL_SHOW_SURROUNDING_WEEKS | wx.calendar.CAL_SUNDAY_FIRST | wx.SUNKEN_BORDER, u"Date of Lunacy") self.cal = cal self.cal.SetFont(wx.Font(12, 74, 90, 90, False, "Sans")) self.cal.SetToolTipString(u"Date for Next Event") self.cal.SetHelpText(u"Renders Lunar/Solar events for the date.") self.Bind(wx.calendar.EVT_CALENDAR_SEL_CHANGED, self.OnDateSelect, id=cal.GetId()) fgSizer1.Add(self.cal, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5) fgSizer1.AddSpacer(( 0, 5), 1, wx.EXPAND, 5) gSizer1.Add(fgSizer1, 1, 0, 0) fgSizer2 = wx.FlexGridSizer(8, 3, 3, 0) fgSizer2.SetFlexibleDirection(wx.HORIZONTAL) fgSizer2.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED) fgSizer2.SetMinSize(wx.Size(-1, 220)) self.staticText_Moonrise = wx.StaticText(self, wx.ID_ANY, u"Moonrise", wx.DefaultPosition, wx.DefaultSize, 0) self.staticText_Moonrise.Wrap(-1) self.staticText_Moonrise.SetFont(wx.Font(12, 74, 90, 90, False, "Sans")) fgSizer2.Add(self.staticText_Moonrise, 0, 0, 5) self.mrtime = wx.StaticText(self, wx.ID_ANY, u"next rise", wx.DefaultPosition, wx.DefaultSize, 0) self.mrtime.Wrap(-1) fgSizer2.Add(self.mrtime, 0, 0, 5) self.mraz = wx.StaticText(self, wx.ID_ANY, u"azimuth", wx.DefaultPosition, wx.DefaultSize, 0) self.mraz.Wrap(-1) fgSizer2.Add(self.mraz, 0, 0, 5) self.staticText_Moonset = wx.StaticText(self, wx.ID_ANY, u"Moonset", wx.DefaultPosition, wx.DefaultSize, 0) self.staticText_Moonset.Wrap(-1) self.staticText_Moonset.SetFont(wx.Font(12, 74, 90, 90, False, "Sans")) fgSizer2.Add(self.staticText_Moonset, 0, 0, 10) self.mstime = wx.StaticText(self, wx.ID_ANY, u"next set", wx.DefaultPosition, wx.DefaultSize, 0) self.mstime.Wrap(-1) fgSizer2.Add(self.mstime, 0, 0, 5) self.msaz = wx.StaticText(self, wx.ID_ANY, u"azimuth", wx.DefaultPosition, wx.DefaultSize, 0) self.msaz.Wrap(-1) fgSizer2.Add(self.msaz, 0, 0, 5) self.staticText_Phase = wx.StaticText(self, wx.ID_ANY, u"Phase", wx.DefaultPosition, wx.DefaultSize, 0) self.staticText_Phase.Wrap(-1) self.staticText_Phase.SetFont(wx.Font(12, 74, 90, 90, False, "Sans")) fgSizer2.Add(self.staticText_Phase, 0, 0, 10) self.moonphase = wx.StaticText(self, wx.ID_ANY, u"moonphase", wx.DefaultPosition, wx.DefaultSize, 0) self.moonphase.Wrap(-1) fgSizer2.Add(self.moonphase, 0, 0, 5) self.phasepercent = wx.StaticText(self, wx.ID_ANY, u"% illuminated", wx.DefaultPosition, wx.DefaultSize, 0) self.phasepercent.Wrap(-1) fgSizer2.Add(self.phasepercent, 0, 0, 5) self.staticText_NewMoon = wx.StaticText(self, wx.ID_ANY, u"New Moon ", wx.DefaultPosition, wx.DefaultSize, wx.ST_NO_AUTORESIZE) self.staticText_NewMoon.Wrap(-1) self.staticText_NewMoon.SetFont(wx.Font(12, 74, 90, 90, False, "Sans")) fgSizer2.Add(self.staticText_NewMoon, 0, 0, 10) self.newmoondate = wx.StaticText(self, wx.ID_ANY, u"next new moon", wx.DefaultPosition, wx.DefaultSize, 0) self.newmoondate.Wrap(-1) fgSizer2.Add(self.newmoondate, 0, 0, 10) self.newmoonhour = wx.StaticText(self, wx.ID_ANY, u"hour", wx.DefaultPosition, wx.DefaultSize, 0) self.newmoonhour.Wrap(-1) fgSizer2.Add(self.newmoonhour, 0, 0, 10) self.staticText_FullMoon = wx.StaticText(self, wx.ID_ANY, u"Full Moon", wx.DefaultPosition, wx.DefaultSize, 0) self.staticText_FullMoon.Wrap(-1) self.staticText_FullMoon.SetFont(wx.Font(12, 74, 90, 90, False, "Sans")) fgSizer2.Add(self.staticText_FullMoon, 0, 0, 10) self.fullmoondate = wx.StaticText(self, wx.ID_ANY, u"next full moon", wx.DefaultPosition, wx.DefaultSize, 0) self.fullmoondate.Wrap(-1) fgSizer2.Add(self.fullmoondate, 0, 0, 5) self.fullmoonhour = wx.StaticText(self, wx.ID_ANY, u"hour", wx.DefaultPosition, wx.DefaultSize, 0) self.fullmoonhour.Wrap(-1) fgSizer2.Add(self.fullmoonhour, 0, 0, 5) self.staticText_Sunrise = wx.StaticText(self, wx.ID_ANY, u"Sunrise", wx.DefaultPosition, wx.DefaultSize, 0) self.staticText_Sunrise.Wrap(-1) self.staticText_Sunrise.SetFont(wx.Font(12, 74, 90, 90, False, "Sans")) fgSizer2.Add(self.staticText_Sunrise, 0, 0, 10) self.srtime = wx.StaticText(self, wx.ID_ANY, u"next rise", wx.DefaultPosition, wx.DefaultSize, 0) self.srtime.Wrap(-1) fgSizer2.Add(self.srtime, 0, 0, 5) self.sraz = wx.StaticText(self, wx.ID_ANY, u"azimuth", wx.DefaultPosition, wx.DefaultSize, 0) self.sraz.Wrap(-1) fgSizer2.Add(self.sraz, 0, 0, 5) self.staticText_SolarNoon = wx.StaticText(self, wx.ID_ANY, u"High Noon", wx.DefaultPosition, wx.DefaultSize, 0) self.staticText_SolarNoon.Wrap(-1) self.staticText_SolarNoon.SetFont(wx.Font(12, 74, 90, 90, False, "Sans")) fgSizer2.Add(self.staticText_SolarNoon, 0, 0, 10) self.sntime = wx.StaticText(self, wx.ID_ANY, u"solar noon", wx.DefaultPosition, wx.DefaultSize, 0) self.sntime.Wrap(-1) fgSizer2.Add(self.sntime, 0, 0, 5) self.snaltitude = wx.StaticText(self, wx.ID_ANY, u"altitude", wx.DefaultPosition, wx.DefaultSize, 0) self.snaltitude.Wrap(-1) fgSizer2.Add(self.snaltitude, 0, 0, 5) self.staticText_Sunset = wx.StaticText(self, wx.ID_ANY, u"Sunset", wx.DefaultPosition, wx.DefaultSize, 0) self.staticText_Sunset.Wrap(-1) self.staticText_Sunset.SetFont(wx.Font(12, 74, 90, 90, False, "Sans")) fgSizer2.Add(self.staticText_Sunset, 0, 0, 10) self.sstime = wx.StaticText(self, wx.ID_ANY, u"next set", wx.DefaultPosition, wx.DefaultSize, 0) self.sstime.Wrap(-1) fgSizer2.Add(self.sstime, 0, 0, 5) self.ssaz = wx.StaticText(self, wx.ID_ANY, u"azimuth", wx.DefaultPosition, wx.DefaultSize, 0) self.ssaz.Wrap(-1) fgSizer2.Add(self.ssaz, 0, 0, 5) gSizer1.Add(fgSizer2, 1, wx.TOP, 5) self.SetSizer(gSizer1) self.Layout() self.Centre(wx.BOTH) def __del__(self): pass def OnDateSelect(self, evt): f = open(r'/etc/nx.lat') # Lat/lon files for Navigatrix lat = f.readline(12) f.close() f = open(r'/etc/nx.lon') lon = f.readline(12) f.close() lat = float(lat) lon = float(lon) degrees = int(lat) mnn = (lat - degrees) * 60 minutes = int(mnn) seconds = round(((mnn - minutes) * 60), 3) lat = str(degrees) + str(minutes) + str(seconds) degrees = int(lon) mnn = (lon - degrees) * 60 minutes = int(mnn) seconds = round(((mnn - minutes) * 60), 3) lon = str(degrees) + str(minutes) + str(seconds) here = ephem.Observer() here.lat = lat here.lon = lon here.pressure = 0 # barometric pressure not factored here.horizon = '-0:34' # fudge factor from the US Navel Observatory here.elevation = 2.0 # 2 Meters elevation here.temp = 25.0 # and a balmy 25 degrees cal = evt.GetEventObject() year = (str(self.cal.GetDate().GetYear())) month = (str(self.cal.GetDate().GetMonth() + 1)) day = (str(self.cal.GetDate().GetDay())) hour = strftime("%H:%M:%S", gmtime()) datefig = year + '/' + month + '/' + day + ' ' + hour here.date = datefig sun = ephem.Sun(here) moon = ephem.Moon(here) moon.compute(here) # # Moon Rise # # mrtime = str(here.next_rising(moon)) mrtime = here.next_rising(moon) lt = ephem.localtime(mrtime) mrtime = str(lt).split() mrtime = mrtime[1].split(".") self.mrtime.SetLabel(str(mrtime[0])) mraz = str(moon.az).partition(':') self.mraz.SetLabel(str(mraz[0]) + u'\u00B0 from North') # # Moonset moon.compute(here) # # mstime = here.next_setting(moon) lt = ephem.localtime(mstime) mstime = str(lt).split() mstime = mstime[1].split(".") self.mstime.SetLabel(mstime[0]) msaz = str(moon.az).partition(':') self.msaz.SetLabel(str(msaz[0]) + u'\u00B0 from North') # # Moon Phase # TODO Clearly these numbers are pulled out of a hat. # they are a very rough approximation of the phases and # do not account for waxing and waning phasepercent = int(moon.moon_phase * 100) self.phasepercent.SetLabel(str(phasepercent) + " %") if phasepercent <= 2.0: moonphase = "New Moon" if 2.1 < phasepercent <= 20.0: moonphase = "Crescent" if 20.1 < phasepercent <= 60.0: moonphase = "Quarter Moon" if 60.1 < phasepercent <= 95.0: moonphase = "Gibbous" if phasepercent > 95.1: moonphase = "Full Moon" self.moonphase.SetLabel(moonphase) # # New Moon Date # newmoondate = ephem.next_new_moon(datefig) lt = ephem.localtime(newmoondate) newmoondate = str(lt).split() newmoonhour = newmoondate[1].split(".") self.newmoondate.SetLabel(str(newmoondate[0])) self.newmoonhour.SetLabel(str(newmoonhour[0])) # # Full Moon Date # fullmoondate = ephem.next_full_moon(datefig) lt = ephem.localtime(fullmoondate) fullmoondate = str(lt).split() fullmoonhour = fullmoondate[1].split(".") self.fullmoondate.SetLabel(str(fullmoondate[0])) self.fullmoonhour.SetLabel(str(fullmoonhour[0])) # # Sun Rise # sun.compute(here) srtime = here.next_rising(sun) lt = ephem.localtime(srtime) srtime = str(lt).split() srtime = srtime[1].split(".") self.srtime.SetLabel(srtime[0]) sraz = str(sun.az).partition(':') self.sraz.SetLabel(str(sraz[0]) + u'\u00B0 from North') # # High Noon # sntime = here.next_transit(sun) lt = ephem.localtime(sntime) sntime = str(lt).split() sntime = sntime[1].split(".") self.sntime.SetLabel(sntime[0]) snaltitude = str(sun.alt).partition(':') self.snaltitude.SetLabel(str(snaltitude[0]) + u'\u00B0 above Horizon') # # Sun Set # sstime = here.next_setting(sun) lt = ephem.localtime(sstime) sstime = str(lt).split() sstime = sstime[1].split(".") self.sstime.SetLabel(sstime[0]) ssaz = str(sun.az).partition(':') self.ssaz.SetLabel(str(ssaz[0]) + u'\u00B0 from North') if __name__ == '__main__': app = App() app.MainLoop()
wadda/Lunacy
lunacy.py
Python
gpl-2.0
10,999
// // ContractDescriptionGenerator.cs // // Author: // Atsushi Enomoto <atsushi@ximian.com> // Atsushi Enomoto <atsushi@xamarin.com> // // Copyright (C) 2005-2007 Novell, Inc. http://www.novell.com // Copyright (C) 2011 Xamarin, Inc. http://xamarin.com // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net.Security; using System.Reflection; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Channels; namespace System.ServiceModel.Description { internal static class ContractDescriptionGenerator { public delegate bool GetOperationContractAttributeExtender (MethodBase method, object[] customAttributes, ref OperationContractAttribute oca); static List <GetOperationContractAttributeExtender> getOperationContractAttributeExtenders; public static void RegisterGetOperationContractAttributeExtender (GetOperationContractAttributeExtender extender) { if (extender == null) return; if (getOperationContractAttributeExtenders == null) getOperationContractAttributeExtenders = new List <GetOperationContractAttributeExtender> (); if (getOperationContractAttributeExtenders.Contains (extender)) return; getOperationContractAttributeExtenders.Add (extender); } public static OperationContractAttribute GetOperationContractAttribute (MethodBase method) { object [] matts = method.GetCustomAttributes (typeof (OperationContractAttribute), false); OperationContractAttribute oca; if (matts.Length == 0) oca = null; else oca = matts [0] as OperationContractAttribute; if (getOperationContractAttributeExtenders != null && getOperationContractAttributeExtenders.Count > 0) { foreach (var extender in getOperationContractAttributeExtenders) if (extender (method, matts, ref oca)) break; } return oca; } static void GetServiceContractAttribute (Type type, Dictionary<Type,ServiceContractAttribute> table) { for (; type != null; type = type.BaseType) { foreach (ServiceContractAttribute i in type.GetCustomAttributes ( typeof (ServiceContractAttribute), true)) table [type] = i; foreach (Type t in type.GetInterfaces ()) GetServiceContractAttribute (t, table); } } public static Dictionary<Type, ServiceContractAttribute> GetServiceContractAttributes (Type type) { Dictionary<Type, ServiceContractAttribute> table = new Dictionary<Type, ServiceContractAttribute> (); GetServiceContractAttribute (type, table); return table; } public static ContractDescription GetContract (Type contractType) { return GetContract (contractType, (Type) null); } public static ContractDescription GetContract ( Type contractType, object serviceImplementation) { if (serviceImplementation == null) throw new ArgumentNullException ("serviceImplementation"); return GetContract (contractType, serviceImplementation.GetType ()); } public static MessageContractAttribute GetMessageContractAttribute (Type type) { for (Type t = type; t != null; t = t.BaseType) { object [] matts = t.GetCustomAttributes ( typeof (MessageContractAttribute), true); if (matts.Length > 0) return (MessageContractAttribute) matts [0]; } return null; } public static ContractDescription GetCallbackContract (Type serviceType, Type callbackType) { return GetContract (callbackType, null, serviceType); } public static ContractDescription GetContract ( Type givenContractType, Type givenServiceType) { return GetContract (givenContractType, givenServiceType, null); } static ContractDescription GetContract (Type givenContractType, Type givenServiceType, Type serviceTypeForCallback) { var ret = GetContractInternal (givenContractType, givenServiceType, serviceTypeForCallback); if (ret == null) throw new InvalidOperationException (String.Format ("Attempted to get contract type from '{0}' which neither is a service contract nor does it inherit service contract.", serviceTypeForCallback ?? givenContractType)); return ret; } internal static ContractDescription GetContractInternal (Type givenContractType, Type givenServiceType, Type serviceTypeForCallback) { if (givenContractType == null) throw new ArgumentNullException ("givenContractType"); // FIXME: serviceType should be used for specifying attributes like OperationBehavior. Type exactContractType = null; ServiceContractAttribute sca = null; Dictionary<Type, ServiceContractAttribute> contracts = GetServiceContractAttributes (serviceTypeForCallback ?? givenServiceType ?? givenContractType); if (contracts.ContainsKey (givenContractType)) { exactContractType = givenContractType; sca = contracts [givenContractType]; } else { foreach (Type t in contracts.Keys) if (t.IsAssignableFrom(givenContractType)) { if (t.IsAssignableFrom (exactContractType)) // exact = IDerived, t = IBase continue; if (sca != null && (exactContractType == null || !exactContractType.IsAssignableFrom (t))) // t = IDerived, exact = IBase throw new InvalidOperationException ("The contract type of " + givenContractType + " is ambiguous: can be either " + exactContractType + " or " + t); exactContractType = t; sca = contracts [t]; } } if (exactContractType == null) exactContractType = givenContractType; if (sca == null) { if (serviceTypeForCallback != null) sca = contracts.Values.First (); else return null; // no contract } string name = sca.Name ?? exactContractType.Name; string ns = sca.Namespace ?? "http://tempuri.org/"; ContractDescription cd = new ContractDescription (name, ns); cd.ContractType = exactContractType; cd.CallbackContractType = sca.CallbackContract; cd.SessionMode = sca.SessionMode; if (sca.ConfigurationName != null) cd.ConfigurationName = sca.ConfigurationName; else cd.ConfigurationName = exactContractType.FullName; if (sca.HasProtectionLevel) cd.ProtectionLevel = sca.ProtectionLevel; /* * Calling `FillOperationsForInterface(cd, X, null, false)' followed by * `FillOperationsForInterface(cd, X, Y, false)' would attempt to populate * the behavior list for 'X' twice (bug #6187). * * Therefor, we manually iterate over the list of interfaces here instead of * using ContractDescription.GetInheritedContracts(). * */ var inherited = new Collection<ContractDescription> (); foreach (var it in cd.ContractType.GetInterfaces ()) { var icd = GetContractInternal (it, givenServiceType, null); if (icd != null) inherited.Add (icd); } foreach (var icd in inherited) { foreach (var od in icd.Operations) if (!cd.Operations.Any(o => o.Name == od.Name && o.SyncMethod == od.SyncMethod && o.BeginMethod == od.BeginMethod && o.InCallbackContract == od.InCallbackContract)) cd.Operations.Add (od); } FillOperationsForInterface (cd, cd.ContractType, givenServiceType, false); if (cd.CallbackContractType != null) FillOperationsForInterface (cd, cd.CallbackContractType, null, true); // FIXME: enable this when I found where this check is needed. /* if (cd.Operations.Count == 0) throw new InvalidOperationException (String.Format ("The service contract type {0} has no operation. At least one operation must exist.", contractType)); */ return cd; } static void FillOperationsForInterface (ContractDescription cd, Type exactContractType, Type givenServiceType, bool isCallback) { // FIXME: load Behaviors MethodInfo [] contractMethods = /*exactContractType.IsInterface ? GetAllMethods (exactContractType) :*/ exactContractType.GetMethods (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); MethodInfo [] serviceMethods = contractMethods; if (givenServiceType != null && exactContractType.IsInterface) { var l = new List<MethodInfo> (); foreach (Type t in GetAllInterfaceTypes (exactContractType)) l.AddRange (givenServiceType.GetInterfaceMap (t).TargetMethods); serviceMethods = l.ToArray (); } for (int i = 0; i < contractMethods.Length; ++i) { MethodInfo mi = contractMethods [i]; OperationContractAttribute oca = GetOperationContractAttribute (mi); if (oca == null) continue; MethodInfo end = null; if (oca.AsyncPattern) { if (String.Compare ("Begin", 0, mi.Name,0, 5) != 0) throw new InvalidOperationException ("For async operation contract patterns, the initiator method name must start with 'Begin'."); string endName = "End" + mi.Name.Substring (5); end = mi.DeclaringType.GetMethod (endName); if (end == null) throw new InvalidOperationException (String.Format ("'{0}' method is missing. For async operation contract patterns, corresponding End method is required for each Begin method.", endName)); if (GetOperationContractAttribute (end) != null) throw new InvalidOperationException ("Async 'End' method must not have OperationContractAttribute. It is automatically treated as the EndMethod of the corresponding 'Begin' method."); } OperationDescription od = GetOrCreateOperation (cd, mi, serviceMethods [i], oca, end, isCallback, givenServiceType); if (end != null) od.EndMethod = end; } } static MethodInfo [] GetAllMethods (Type type) { var l = new List<MethodInfo> (); foreach (var t in GetAllInterfaceTypes (type)) { #if FULL_AOT_RUNTIME // The MethodBase[] from t.GetMethods () is cast to a IEnumerable <MethodInfo> // when passed to List<MethodInfo>.AddRange, which in turn casts it to // ICollection <MethodInfo>. The full-aot compiler has no idea of this, so // we're going to make it aware. int c = ((ICollection <MethodInfo>) t.GetMethods ()).Count; #endif l.AddRange (t.GetMethods ()); } return l.ToArray (); } static IEnumerable<Type> GetAllInterfaceTypes (Type type) { yield return type; foreach (var t in type.GetInterfaces ()) foreach (var tt in GetAllInterfaceTypes (t)) yield return tt; } static OperationDescription GetOrCreateOperation ( ContractDescription cd, MethodInfo mi, MethodInfo serviceMethod, OperationContractAttribute oca, MethodInfo endMethod, bool isCallback, Type givenServiceType) { string name = oca.Name ?? (oca.AsyncPattern ? mi.Name.Substring (5) : mi.Name); OperationDescription od = cd.Operations.FirstOrDefault (o => o.Name == name && o.InCallbackContract == isCallback); if (od == null) { od = new OperationDescription (name, cd); od.IsOneWay = oca.IsOneWay; if (oca.HasProtectionLevel) od.ProtectionLevel = oca.ProtectionLevel; if (HasInvalidMessageContract (mi, oca.AsyncPattern)) throw new InvalidOperationException (String.Format ("The operation {0} contains more than one parameters and one or more of them are marked with MessageContractAttribute, but the attribute must be used within an operation that has only one parameter.", od.Name)); var xfa = serviceMethod.GetCustomAttribute<XmlSerializerFormatAttribute> (false); if (xfa != null) od.Behaviors.Add (new XmlSerializerOperationBehavior (od, xfa)); var dfa = serviceMethod.GetCustomAttribute<DataContractFormatAttribute> (false); if (dfa != null) od.Behaviors.Add (new DataContractSerializerOperationBehavior (od, dfa)); od.Messages.Add (GetMessage (od, mi, oca, true, isCallback, null)); if (!od.IsOneWay) { var asyncReturnType = endMethod != null ? endMethod.ReturnType : null; var md = GetMessage (od, endMethod ?? mi, oca, false, isCallback, asyncReturnType); od.Messages.Add (md); var mpa = mi.ReturnParameter.GetCustomAttribute<MessageParameterAttribute> (true); if (mpa != null) { var mpd = md.Body.Parts.FirstOrDefault (pd => pd.Name == mpa.Name); if (mpd != null) { md.Body.Parts.Remove (mpd); md.Body.ReturnValue = mpd; mpd.Name = mpa.Name; } else if (md.Body.ReturnValue == null) throw new InvalidOperationException (String.Format ("Specified message part '{0}' in MessageParameterAttribute on the return value, was not found", mpa.Name)); } } var knownTypeAtts = cd.ContractType.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false).Union ( mi.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false)).Union ( serviceMethod.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false)); foreach (ServiceKnownTypeAttribute a in knownTypeAtts) foreach (Type t in a.GetTypes (givenServiceType)) od.KnownTypes.Add (t); foreach (FaultContractAttribute a in mi.GetCustomAttributes (typeof (FaultContractAttribute), false)) { var fname = a.Name ?? a.DetailType.Name + "Fault"; var fns = a.Namespace ?? cd.Namespace; var fd = new FaultDescription (a.Action ?? cd.Namespace + cd.Name + "/" + od.Name + fname) { DetailType = a.DetailType, Name = fname, Namespace = fns }; #if !NET_2_1 if (a.HasProtectionLevel) fd.ProtectionLevel = a.ProtectionLevel; #endif od.Faults.Add (fd); } cd.Operations.Add (od); } else if ((oca.AsyncPattern && od.BeginMethod != null && od.BeginMethod != mi || !oca.AsyncPattern && od.SyncMethod != null && od.SyncMethod != mi) && od.InCallbackContract == isCallback) throw new InvalidOperationException (String.Format ("contract '{1}' cannot have two operations for '{0}' that have the identical names and different set of parameters.", name, cd.Name)); if (oca.AsyncPattern) od.BeginMethod = mi; else od.SyncMethod = mi; od.IsInitiating = oca.IsInitiating; od.IsTerminating = oca.IsTerminating; if (mi != serviceMethod) foreach (object obj in mi.GetCustomAttributes (typeof (IOperationBehavior), true)) od.Behaviors.Add ((IOperationBehavior) obj); if (serviceMethod != null) { foreach (object obj in serviceMethod.GetCustomAttributes (typeof(IOperationBehavior),true)) od.Behaviors.Add ((IOperationBehavior) obj); } #if !NET_2_1 if (od.Behaviors.Find<OperationBehaviorAttribute>() == null) od.Behaviors.Add (new OperationBehaviorAttribute ()); #endif // FIXME: fill KnownTypes, Behaviors and Faults. if (isCallback) od.InCallbackContract = true; else od.InOrdinalContract = true; return od; } static bool HasInvalidMessageContract (MethodInfo mi, bool async) { var pars = mi.GetParameters (); if (async) { if (pars.Length > 3) { if (pars.Take (pars.Length - 2).Any (par => par.ParameterType.GetCustomAttribute<MessageContractAttribute> (true) != null)) return true; } } else { if (pars.Length > 1) { if (pars.Any (par => par.ParameterType.GetCustomAttribute<MessageContractAttribute> (true) != null)) return true; } } return false; } static MessageDescription GetMessage ( OperationDescription od, MethodInfo mi, OperationContractAttribute oca, bool isRequest, bool isCallback, Type asyncReturnType) { ContractDescription cd = od.DeclaringContract; ParameterInfo [] plist = mi.GetParameters (); Type messageType = null; string action = isRequest ? oca.Action : oca.ReplyAction; MessageContractAttribute mca; Type retType = asyncReturnType; if (!isRequest && retType == null) retType = mi.ReturnType; // If the argument is only one and has [MessageContract] // then infer it as a typed messsage if (isRequest) { int len = mi.Name.StartsWith ("Begin", StringComparison.Ordinal) ? 3 : 1; mca = plist.Length != len ? null : GetMessageContractAttribute (plist [0].ParameterType); if (mca != null) messageType = plist [0].ParameterType; } else { mca = GetMessageContractAttribute (retType); if (mca != null) messageType = retType; } if (action == null) action = String.Concat (cd.Namespace, cd.Namespace.Length == 0 ? "urn:" : cd.Namespace.EndsWith ("/") ? "" : "/", cd.Name, "/", od.Name, isRequest ? String.Empty : "Response"); MessageDescription md; if (mca != null) md = CreateMessageDescription (messageType, cd.Namespace, action, isRequest, isCallback, mca); else md = CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, isCallback, retType); // ReturnValue if (!isRequest) { MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (mi.ReturnTypeCustomAttributes), od.Name + "Result", md.Body.WrapperNamespace); mp.Index = 0; mp.Type = mca != null ? typeof (void) : retType; md.Body.ReturnValue = mp; } return md; } public static MessageDescription CreateMessageDescription ( Type messageType, string defaultNamespace, string action, bool isRequest, bool isCallback, MessageContractAttribute mca) { MessageDescription md = new MessageDescription (action, isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output) { IsRequest = isRequest }; md.MessageType = MessageFilterOutByRef (messageType); if (mca.HasProtectionLevel) md.ProtectionLevel = mca.ProtectionLevel; MessageBodyDescription mb = md.Body; if (mca.IsWrapped) { mb.WrapperName = mca.WrapperName ?? messageType.Name; mb.WrapperNamespace = mca.WrapperNamespace ?? defaultNamespace; } int index = 0; foreach (MemberInfo bmi in messageType.GetMembers (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { Type mtype = null; string mname = null; if (bmi is FieldInfo) { FieldInfo fi = (FieldInfo) bmi; mtype = fi.FieldType; mname = fi.Name; } else if (bmi is PropertyInfo) { PropertyInfo pi = (PropertyInfo) bmi; mtype = pi.PropertyType; mname = pi.Name; } else continue; var mha = bmi.GetCustomAttribute<MessageHeaderAttribute> (false); if (mha != null) { var pd = CreateHeaderDescription (mha, mname, defaultNamespace); pd.Type = MessageFilterOutByRef (mtype); pd.MemberInfo = bmi; md.Headers.Add (pd); } var mpa = bmi.GetCustomAttribute<MessagePropertyAttribute> (false); if (mpa != null) { var pd = new MessagePropertyDescription (mpa.Name ?? mname); pd.Type = MessageFilterOutByRef (mtype); pd.MemberInfo = bmi; md.Properties.Add (pd); } var mba = GetMessageBodyMemberAttribute (bmi); if (mba != null) { var pd = CreatePartCore (mba, mname, defaultNamespace); if (pd.Index <= 0) pd.Index = index++; pd.Type = MessageFilterOutByRef (mtype); pd.MemberInfo = bmi; mb.Parts.Add (pd); } } return md; } public static MessageDescription CreateMessageDescription ( OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, bool isCallback, Type retType) { var dir = isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output; MessageDescription md = new MessageDescription (action, dir) { IsRequest = isRequest }; MessageBodyDescription mb = md.Body; mb.WrapperName = name + (isRequest ? String.Empty : "Response"); mb.WrapperNamespace = defaultNamespace; if (oca.HasProtectionLevel) md.ProtectionLevel = oca.ProtectionLevel; // Parts int index = 0; foreach (ParameterInfo pi in plist) { // AsyncCallback and state are extraneous. if (oca.AsyncPattern) { if (isRequest && pi.Position == plist.Length - 2) break; if (!isRequest && pi.Position == plist.Length - 1) break; } // They are ignored: // - out parameter in request // - neither out nor ref parameter in reply if (isRequest && pi.IsOut) continue; if (!isRequest && !pi.IsOut && !pi.ParameterType.IsByRef) continue; MessagePartDescription pd = CreatePartCore (GetMessageParameterAttribute (pi), pi.Name, defaultNamespace); pd.Index = index++; pd.Type = MessageFilterOutByRef (pi.ParameterType); mb.Parts.Add (pd); } return md; } // public static void FillMessageBodyDescriptionByContract ( // Type messageType, MessageBodyDescription mb) // { // } static MessageHeaderDescription CreateHeaderDescription (MessageHeaderAttribute mha, string defaultName, string defaultNamespace) { var ret = CreatePartCore<MessageHeaderDescription> (mha, defaultName, defaultNamespace, delegate (string n, string ns) { return new MessageHeaderDescription (n, ns); }); ret.Actor = mha.Actor; ret.MustUnderstand = mha.MustUnderstand; ret.Relay = mha.Relay; return ret; } static MessagePartDescription CreatePartCore ( MessageParameterAttribute mpa, string defaultName, string defaultNamespace) { string pname = null; if (mpa != null && mpa.Name != null) pname = mpa.Name; if (pname == null) pname = defaultName; return new MessagePartDescription (pname, defaultNamespace); } static MessagePartDescription CreatePartCore (MessageBodyMemberAttribute mba, string defaultName, string defaultNamespace) { var ret = CreatePartCore<MessagePartDescription> (mba, defaultName, defaultNamespace, delegate (string n, string ns) { return new MessagePartDescription (n, ns); }); ret.Index = mba.Order; return ret; } static T CreatePartCore<T> (MessageContractMemberAttribute mba, string defaultName, string defaultNamespace, Func<string,string,T> creator) { string pname = null, pns = null; if (mba != null) { if (mba.Name != null) pname = mba.Name; if (mba.Namespace != null) pns = mba.Namespace; } if (pname == null) pname = defaultName; if (pns == null) pns = defaultNamespace; return creator (pname, pns); } static Type MessageFilterOutByRef (Type type) { return type == null ? null : type.IsByRef ? type.GetElementType () : type; } static MessageParameterAttribute GetMessageParameterAttribute (ICustomAttributeProvider provider) { object [] attrs = provider.GetCustomAttributes ( typeof (MessageParameterAttribute), true); return attrs.Length > 0 ? (MessageParameterAttribute) attrs [0] : null; } static MessageBodyMemberAttribute GetMessageBodyMemberAttribute (MemberInfo mi) { object [] matts = mi.GetCustomAttributes ( typeof (MessageBodyMemberAttribute), true); return matts.Length > 0 ? (MessageBodyMemberAttribute) matts [0] : null; } } }
hardvain/mono-compiler
class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs
C#
gpl-2.0
23,695
#include<cstdio> #include<cstring> #include<algorithm> #define maxn 1010 using namespace std; struct node { int len, weight; bool vis; node(int len = 0, int weight = 0, bool vis = false) :len(len), weight(weight), vis(vis){} }num[maxn]; int sum; bool cmp(node a, node b) { if (a.len == b.len) return a.weight < b.weight; return a.len < b.len; } int main (void) { while (scanf("%d", &sum) != EOF) { for (int i = 1; i <= sum; i++) { scanf("%d %d", &num[i].len, &num[i].weight); num[i].vis = false; } sort(num + 1, num + sum + 1, cmp); int temp = sum; int ans = 0; while (temp) { node now = node(-1, -1); ans++; for (int i = 1; i <= sum; i++) { if (!num[i].vis && num[i].len >= now.len && num[i].weight >= now.weight) { num[i].vis = true; temp--; now = num[i]; } } } printf("%d\n", ans); } return 0; }
sunmoyi/ACM
ACM 2015/零件分组.cpp
C++
gpl-2.0
933
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator https://lammps.sandia.gov/, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Mark Stevens (SNL) ------------------------------------------------------------------------- */ #include "dihedral_opls.h" #include <cmath> #include "atom.h" #include "comm.h" #include "neighbor.h" #include "force.h" #include "update.h" #include "memory.h" #include "error.h" using namespace LAMMPS_NS; #define TOLERANCE 0.05 #define SMALL 0.001 #define SMALLER 0.00001 /* ---------------------------------------------------------------------- */ DihedralOPLS::DihedralOPLS(LAMMPS *lmp) : Dihedral(lmp) { writedata = 1; } /* ---------------------------------------------------------------------- */ DihedralOPLS::~DihedralOPLS() { if (allocated && !copymode) { memory->destroy(setflag); memory->destroy(k1); memory->destroy(k2); memory->destroy(k3); memory->destroy(k4); } } /* ---------------------------------------------------------------------- */ void DihedralOPLS::compute(int eflag, int vflag) { int i1,i2,i3,i4,n,type; double vb1x,vb1y,vb1z,vb2x,vb2y,vb2z,vb3x,vb3y,vb3z,vb2xm,vb2ym,vb2zm; double edihedral,f1[3],f2[3],f3[3],f4[3]; double sb1,sb2,sb3,rb1,rb3,c0,b1mag2,b1mag,b2mag2; double b2mag,b3mag2,b3mag,ctmp,r12c1,c1mag,r12c2; double c2mag,sc1,sc2,s1,s12,c,p,pd,a,a11,a22; double a33,a12,a13,a23,sx2,sy2,sz2; double s2,cx,cy,cz,cmag,dx,phi,si,siinv,sin2; edihedral = 0.0; ev_init(eflag,vflag); double **x = atom->x; double **f = atom->f; int **dihedrallist = neighbor->dihedrallist; int ndihedrallist = neighbor->ndihedrallist; int nlocal = atom->nlocal; int newton_bond = force->newton_bond; for (n = 0; n < ndihedrallist; n++) { i1 = dihedrallist[n][0]; i2 = dihedrallist[n][1]; i3 = dihedrallist[n][2]; i4 = dihedrallist[n][3]; type = dihedrallist[n][4]; // 1st bond vb1x = x[i1][0] - x[i2][0]; vb1y = x[i1][1] - x[i2][1]; vb1z = x[i1][2] - x[i2][2]; // 2nd bond vb2x = x[i3][0] - x[i2][0]; vb2y = x[i3][1] - x[i2][1]; vb2z = x[i3][2] - x[i2][2]; vb2xm = -vb2x; vb2ym = -vb2y; vb2zm = -vb2z; // 3rd bond vb3x = x[i4][0] - x[i3][0]; vb3y = x[i4][1] - x[i3][1]; vb3z = x[i4][2] - x[i3][2]; // c0 calculation sb1 = 1.0 / (vb1x*vb1x + vb1y*vb1y + vb1z*vb1z); sb2 = 1.0 / (vb2x*vb2x + vb2y*vb2y + vb2z*vb2z); sb3 = 1.0 / (vb3x*vb3x + vb3y*vb3y + vb3z*vb3z); rb1 = sqrt(sb1); rb3 = sqrt(sb3); c0 = (vb1x*vb3x + vb1y*vb3y + vb1z*vb3z) * rb1*rb3; // 1st and 2nd angle b1mag2 = vb1x*vb1x + vb1y*vb1y + vb1z*vb1z; b1mag = sqrt(b1mag2); b2mag2 = vb2x*vb2x + vb2y*vb2y + vb2z*vb2z; b2mag = sqrt(b2mag2); b3mag2 = vb3x*vb3x + vb3y*vb3y + vb3z*vb3z; b3mag = sqrt(b3mag2); ctmp = vb1x*vb2x + vb1y*vb2y + vb1z*vb2z; r12c1 = 1.0 / (b1mag*b2mag); c1mag = ctmp * r12c1; ctmp = vb2xm*vb3x + vb2ym*vb3y + vb2zm*vb3z; r12c2 = 1.0 / (b2mag*b3mag); c2mag = ctmp * r12c2; // cos and sin of 2 angles and final c sin2 = MAX(1.0 - c1mag*c1mag,0.0); sc1 = sqrt(sin2); if (sc1 < SMALL) sc1 = SMALL; sc1 = 1.0/sc1; sin2 = MAX(1.0 - c2mag*c2mag,0.0); sc2 = sqrt(sin2); if (sc2 < SMALL) sc2 = SMALL; sc2 = 1.0/sc2; s1 = sc1 * sc1; s2 = sc2 * sc2; s12 = sc1 * sc2; c = (c0 + c1mag*c2mag) * s12; cx = vb1y*vb2z - vb1z*vb2y; cy = vb1z*vb2x - vb1x*vb2z; cz = vb1x*vb2y - vb1y*vb2x; cmag = sqrt(cx*cx + cy*cy + cz*cz); dx = (cx*vb3x + cy*vb3y + cz*vb3z)/cmag/b3mag; // error check if (c > 1.0 + TOLERANCE || c < (-1.0 - TOLERANCE)) { int me; MPI_Comm_rank(world,&me); if (screen) { char str[128]; sprintf(str,"Dihedral problem: %d " BIGINT_FORMAT " " TAGINT_FORMAT " " TAGINT_FORMAT " " TAGINT_FORMAT " " TAGINT_FORMAT, me,update->ntimestep, atom->tag[i1],atom->tag[i2],atom->tag[i3],atom->tag[i4]); error->warning(FLERR,str,0); fprintf(screen," 1st atom: %d %g %g %g\n", me,x[i1][0],x[i1][1],x[i1][2]); fprintf(screen," 2nd atom: %d %g %g %g\n", me,x[i2][0],x[i2][1],x[i2][2]); fprintf(screen," 3rd atom: %d %g %g %g\n", me,x[i3][0],x[i3][1],x[i3][2]); fprintf(screen," 4th atom: %d %g %g %g\n", me,x[i4][0],x[i4][1],x[i4][2]); } } if (c > 1.0) c = 1.0; if (c < -1.0) c = -1.0; // force & energy // p = sum (i=1,4) k_i * (1 + (-1)**(i+1)*cos(i*phi) ) // pd = dp/dc phi = acos(c); if (dx < 0.0) phi *= -1.0; si = sin(phi); if (fabs(si) < SMALLER) si = SMALLER; siinv = 1.0/si; p = k1[type]*(1.0 + c) + k2[type]*(1.0 - cos(2.0*phi)) + k3[type]*(1.0 + cos(3.0*phi)) + k4[type]*(1.0 - cos(4.0*phi)) ; pd = k1[type] - 2.0*k2[type]*sin(2.0*phi)*siinv + 3.0*k3[type]*sin(3.0*phi)*siinv - 4.0*k4[type]*sin(4.0*phi)*siinv; if (eflag) edihedral = p; a = pd; c = c * a; s12 = s12 * a; a11 = c*sb1*s1; a22 = -sb2 * (2.0*c0*s12 - c*(s1+s2)); a33 = c*sb3*s2; a12 = -r12c1 * (c1mag*c*s1 + c2mag*s12); a13 = -rb1*rb3*s12; a23 = r12c2 * (c2mag*c*s2 + c1mag*s12); sx2 = a12*vb1x + a22*vb2x + a23*vb3x; sy2 = a12*vb1y + a22*vb2y + a23*vb3y; sz2 = a12*vb1z + a22*vb2z + a23*vb3z; f1[0] = a11*vb1x + a12*vb2x + a13*vb3x; f1[1] = a11*vb1y + a12*vb2y + a13*vb3y; f1[2] = a11*vb1z + a12*vb2z + a13*vb3z; f2[0] = -sx2 - f1[0]; f2[1] = -sy2 - f1[1]; f2[2] = -sz2 - f1[2]; f4[0] = a13*vb1x + a23*vb2x + a33*vb3x; f4[1] = a13*vb1y + a23*vb2y + a33*vb3y; f4[2] = a13*vb1z + a23*vb2z + a33*vb3z; f3[0] = sx2 - f4[0]; f3[1] = sy2 - f4[1]; f3[2] = sz2 - f4[2]; // apply force to each of 4 atoms if (newton_bond || i1 < nlocal) { f[i1][0] += f1[0]; f[i1][1] += f1[1]; f[i1][2] += f1[2]; } if (newton_bond || i2 < nlocal) { f[i2][0] += f2[0]; f[i2][1] += f2[1]; f[i2][2] += f2[2]; } if (newton_bond || i3 < nlocal) { f[i3][0] += f3[0]; f[i3][1] += f3[1]; f[i3][2] += f3[2]; } if (newton_bond || i4 < nlocal) { f[i4][0] += f4[0]; f[i4][1] += f4[1]; f[i4][2] += f4[2]; } if (evflag) ev_tally(i1,i2,i3,i4,nlocal,newton_bond,edihedral,f1,f3,f4, vb1x,vb1y,vb1z,vb2x,vb2y,vb2z,vb3x,vb3y,vb3z); } } /* ---------------------------------------------------------------------- */ void DihedralOPLS::allocate() { allocated = 1; int n = atom->ndihedraltypes; memory->create(k1,n+1,"dihedral:k1"); memory->create(k2,n+1,"dihedral:k2"); memory->create(k3,n+1,"dihedral:k3"); memory->create(k4,n+1,"dihedral:k4"); memory->create(setflag,n+1,"dihedral:setflag"); for (int i = 1; i <= n; i++) setflag[i] = 0; } /* ---------------------------------------------------------------------- set coeffs for one type ------------------------------------------------------------------------- */ void DihedralOPLS::coeff(int narg, char **arg) { if (narg != 5) error->all(FLERR,"Incorrect args for dihedral coefficients"); if (!allocated) allocate(); int ilo,ihi; utils::bounds(FLERR,arg[0],1,atom->ndihedraltypes,ilo,ihi,error); double k1_one = utils::numeric(FLERR,arg[1],false,lmp); double k2_one = utils::numeric(FLERR,arg[2],false,lmp); double k3_one = utils::numeric(FLERR,arg[3],false,lmp); double k4_one = utils::numeric(FLERR,arg[4],false,lmp); // store 1/2 factor with prefactor int count = 0; for (int i = ilo; i <= ihi; i++) { k1[i] = 0.5*k1_one; k2[i] = 0.5*k2_one; k3[i] = 0.5*k3_one; k4[i] = 0.5*k4_one; setflag[i] = 1; count++; } if (count == 0) error->all(FLERR,"Incorrect args for dihedral coefficients"); } /* ---------------------------------------------------------------------- proc 0 writes out coeffs to restart file ------------------------------------------------------------------------- */ void DihedralOPLS::write_restart(FILE *fp) { fwrite(&k1[1],sizeof(double),atom->ndihedraltypes,fp); fwrite(&k2[1],sizeof(double),atom->ndihedraltypes,fp); fwrite(&k3[1],sizeof(double),atom->ndihedraltypes,fp); fwrite(&k4[1],sizeof(double),atom->ndihedraltypes,fp); } /* ---------------------------------------------------------------------- proc 0 reads coeffs from restart file, bcasts them ------------------------------------------------------------------------- */ void DihedralOPLS::read_restart(FILE *fp) { allocate(); if (comm->me == 0) { utils::sfread(FLERR,&k1[1],sizeof(double),atom->ndihedraltypes,fp,nullptr,error); utils::sfread(FLERR,&k2[1],sizeof(double),atom->ndihedraltypes,fp,nullptr,error); utils::sfread(FLERR,&k3[1],sizeof(double),atom->ndihedraltypes,fp,nullptr,error); utils::sfread(FLERR,&k4[1],sizeof(double),atom->ndihedraltypes,fp,nullptr,error); } MPI_Bcast(&k1[1],atom->ndihedraltypes,MPI_DOUBLE,0,world); MPI_Bcast(&k2[1],atom->ndihedraltypes,MPI_DOUBLE,0,world); MPI_Bcast(&k3[1],atom->ndihedraltypes,MPI_DOUBLE,0,world); MPI_Bcast(&k4[1],atom->ndihedraltypes,MPI_DOUBLE,0,world); for (int i = 1; i <= atom->ndihedraltypes; i++) setflag[i] = 1; } /* ---------------------------------------------------------------------- proc 0 writes to data file ------------------------------------------------------------------------- */ void DihedralOPLS::write_data(FILE *fp) { for (int i = 1; i <= atom->ndihedraltypes; i++) fprintf(fp,"%d %g %g %g %g\n",i,2.0*k1[i],2.0*k2[i],2.0*k3[i],2.0*k4[i]); }
rbberger/lammps
src/MOLECULE/dihedral_opls.cpp
C++
gpl-2.0
10,302
var Class = { create: function() { return function() { //vararg this.initialize.apply(this, arguments); } } }; Color = Class.create(); Color.prototype = { red: 0, green: 0, blue: 0, initialize: function(r,g,b) { this.red = r; this.green = g; this.blue = b; } } function bench(x) { var d = new Date; var colors = new Array(16); for (var i=0;i<1e8;i++) { colors[i&0xf] = (new Color(1,2,3)); } print(new Date - d); return colors; } bench(17); print("Swapping out call"); Function.prototype.call = function() { throw "This should not happen, apply should be called instead"; }; bench(17); print("All done!");
hazzik/nashorn
test/examples/apply_to_call_benchmark.js
JavaScript
gpl-2.0
674
/****************************************************************************** * Copyright (C) 2007 by Anton Maksimenko * * antonmx@post.kek.jp * * * * 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 /// @author antonmx <antonmx@synchrotron.org.au> /// @date Thu Sep 11 18:57:51 2008 /// /// @brief Processes the RC of the analyzer and prepares data function /// to be used in the EDEI process. /// #include "../common/common.h" #include "../common/edei.h" using namespace std; /// \CLARGS struct clargs { Path command; ///< Command name as it was invoked. Path fdname; ///< Name of the output \FD "FD" file. EDEIoptions edeiopt; ///< Options for the EDEI processing. bool beverbose; ///< Be verbose flag /// \CLARGSF clargs(int argc, char *argv[]); }; clargs:: clargs(int argc, char *argv[]){ beverbose = false; poptmx::OptionTable table ("Converts the rocking curve of the analyzer to the function used in the EDEI.", "I use this program only to develop and debug the EDEI algorithm. If you" " you are not interested in it, you don't need this program."); table .add(poptmx::NOTE, "ARGUMENTS:") /*.add(poptmx::ARGUMENT, &edeiopt.RCname, "RC", EDEIoptions::rcOptionShortDesc, EDEIoptions::rcOptionDesc, "")*/ .add(poptmx::ARGUMENT, &edeiopt.FDname, "FD", EDEIoptions::fdOptionShortDesc, EDEIoptions::fdOptionDesc, "processed-<RC>") .add(poptmx::NOTE, "OPTIONS:") .add(edeiopt.options()) .add_standard_options(&beverbose) .add(poptmx::MAN, "SEE ALSO:", SeeAlsoList); if ( ! table.parse(argc,argv) ) exit(0); if ( ! table.count() ) { table.usage(); exit(0); } command = table.name(); if ( ! table.count(&edeiopt.RCname) ) exit_on_error(command, string () + "Missing required argument: "+table.desc(&edeiopt.RCname)+"."); if ( ! table.count(&edeiopt.FDname) ) edeiopt.FDname = upgrade(edeiopt.RCname, "processed-"); } /// \MAIN{rc2fd} int main(int argc, char *argv[]) { const clargs args(argc, argv); const EDEIprocess proc(args.edeiopt.RCname, args.edeiopt.Gm, args.edeiopt.Gp, args.edeiopt.mpinter, args.edeiopt.smooth, args.edeiopt.acof); proc.saveFD(args.edeiopt.RCname); exit(0); }
antonmx/ctas
src/executables/rc2fd.cpp
C++
gpl-2.0
3,586
/* * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.nodes.java; import com.oracle.graal.api.meta.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.nodes.type.*; /** * The {@code StoreIndexedNode} represents a write to an array element. */ public final class StoreIndexedNode extends AccessIndexedNode implements StateSplit, Lowerable, Virtualizable { @Input private ValueNode value; @Input(notDataflow = true) private FrameState stateAfter; public FrameState stateAfter() { return stateAfter; } public void setStateAfter(FrameState x) { assert x == null || x.isAlive() : "frame state must be in a graph"; updateUsages(stateAfter, x); stateAfter = x; } public boolean hasSideEffect() { return true; } public ValueNode value() { return value; } /** * Creates a new StoreIndexedNode. * * @param array the node producing the array * @param index the node producing the index * @param elementKind the element type * @param value the value to store into the array */ public StoreIndexedNode(ValueNode array, ValueNode index, Kind elementKind, ValueNode value) { super(StampFactory.forVoid(), array, index, elementKind); this.value = value; } @Override public void virtualize(VirtualizerTool tool) { State arrayState = tool.getObjectState(array()); if (arrayState != null && arrayState.getState() == EscapeState.Virtual) { ValueNode indexValue = tool.getReplacedValue(index()); int index = indexValue.isConstant() ? indexValue.asConstant().asInt() : -1; if (index >= 0 && index < arrayState.getVirtualObject().entryCount()) { ResolvedJavaType componentType = arrayState.getVirtualObject().type().getComponentType(); if (componentType.isPrimitive() || value.objectStamp().alwaysNull() || (value.objectStamp().type() != null && componentType.isAssignableFrom(value.objectStamp().type()))) { tool.setVirtualEntry(arrayState, index, value()); tool.delete(); } } } } }
rjsingh/graal
graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/java/StoreIndexedNode.java
Java
gpl-2.0
3,269
package net.demo.model; import javax.persistence.*; /** * Created by toannh on 10/9/14. */ @Entity @Table(name = "USER_ROLE") public class UserRole { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String username; private String role; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "username") private User user; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
toannh/demo
src/main/java/net/demo/model/UserRole.java
Java
gpl-2.0
836
/** * Pennyworth - A new smarthome protocol. * Copyright (C) 2012 Dream-Crusher Labs LLC * * 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. */ /* * SerialComm.cpp * * Created on: Jun 20, 2012 * Author: jmonk */ #include "SerialComm.h" #include <stdio.h> #include <termios.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> namespace dvs { SerialComm::SerialComm(char* device) { struct termios tc; // terminal control structure std::string dev(device); name = "Serial "; name.append(dev); fd = open(device, O_RDWR | O_NOCTTY); // really ought to check for error tcgetattr(fd, &tc); cfmakeraw(&tc); // tc.c_iflag = IGNPAR; // tc.c_oflag = 0; // tc.c_cflag = CS8 | CREAD | CLOCAL; //8 bit chars enable receiver no modem status lines // tc.c_lflag =0 ; //todo baud rate should not be hard coded cfsetispeed(&tc, B9600); cfsetospeed(&tc, B9600); //todo should have bits per character set tcsetattr(fd, TCSANOW, &tc); fcntl(fd, F_SETFL, O_NONBLOCK); StartPacket p; sendPacket(&p); Server::getServer()->addListener(fd, new CommHandler(this)); } } /* namespace dvs */
DCLMonk/Pennyworth
Server/Comm/SerialComm.cpp
C++
gpl-2.0
1,942
/*************************************************************************** qgshttptransaction.cpp - Tracks a HTTP request with its response, with particular attention to tracking HTTP redirect responses ------------------- begin : 17 Mar, 2005 copyright : (C) 2005 by Brendan Morley email : morb at ozemail dot com dot au ***************************************************************************/ /*************************************************************************** * * * 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 <fstream> #include "qgshttptransaction.h" #include "qgslogger.h" #include "qgsconfig.h" #include <QApplication> #include <QUrl> #include <QSettings> #include <QTimer> static int HTTP_PORT_DEFAULT = 80; //XXX Set the connection name when creating the provider instance //XXX in qgswmsprovider. When creating a QgsHttpTransaction, pass //XXX the user/pass combination to the constructor. Then set the //XXX username and password using QHttp::setUser. QgsHttpTransaction::QgsHttpTransaction( const QString& uri, const QString& proxyHost, int proxyPort, const QString& proxyUser, const QString& proxyPass, QNetworkProxy::ProxyType proxyType, const QString& userName, const QString& password ) : http( NULL ) , httpid( 0 ) , httpactive( false ) , httpurl( uri ) , httphost( proxyHost ) , httpredirections( 0 ) , mWatchdogTimer( NULL ) { Q_UNUSED( proxyPort ); Q_UNUSED( proxyUser ); Q_UNUSED( proxyPass ); Q_UNUSED( proxyType ); Q_UNUSED( userName ); Q_UNUSED( password ); QSettings s; mNetworkTimeoutMsec = s.value( "/qgis/networkAndProxy/networkTimeout", "20000" ).toInt(); } QgsHttpTransaction::QgsHttpTransaction() : http( NULL ) , httpid( 0 ) , httpactive( false ) , httpredirections( 0 ) , mWatchdogTimer( NULL ) { QSettings s; mNetworkTimeoutMsec = s.value( "/qgis/networkAndProxy/networkTimeout", "20000" ).toInt(); } QgsHttpTransaction::~QgsHttpTransaction() { QgsDebugMsg( "deconstructing." ); } void QgsHttpTransaction::setCredentials( const QString& username, const QString& password ) { mUserName = username; mPassword = password; } void QgsHttpTransaction::getAsynchronously() { //TODO } bool QgsHttpTransaction::getSynchronously( QByteArray &respondedContent, int redirections, const QByteArray* postData ) { httpredirections = redirections; QgsDebugMsg( "Entered." ); QgsDebugMsg( "Using '" + httpurl + "'." ); QgsDebugMsg( "Creds: " + mUserName + "/" + mPassword ); int httpport; QUrl qurl( httpurl ); http = new QHttp(); // Create a header so we can set the user agent (Per WMS RFC). QHttpRequestHeader header( "GET", qurl.host() ); // Set host in the header if ( qurl.port( HTTP_PORT_DEFAULT ) == HTTP_PORT_DEFAULT ) { header.setValue( "Host", qurl.host() ); } else { header.setValue( "Host", QString( "%1:%2" ).arg( qurl.host() ).arg( qurl.port() ) ); } // Set the user agent to QGIS plus the version name header.setValue( "User-agent", QString( "QGIS - " ) + VERSION ); // Set the host in the QHttp object http->setHost( qurl.host(), qurl.port( HTTP_PORT_DEFAULT ) ); // Set the username and password if supplied for this connection // If we have username and password set in header if ( !mUserName.isEmpty() && !mPassword.isEmpty() ) { http->setUser( mUserName, mPassword ); } if ( !QgsHttpTransaction::applyProxySettings( *http, httpurl ) ) { httphost = qurl.host(); httpport = qurl.port( HTTP_PORT_DEFAULT ); } else { //proxy enabled, read httphost and httpport from settings QSettings settings; httphost = settings.value( "proxy/proxyHost", "" ).toString(); httpport = settings.value( "proxy/proxyPort", "" ).toString().toInt(); } // int httpid1 = http->setHost( qurl.host(), qurl.port() ); mWatchdogTimer = new QTimer( this ); QgsDebugMsg( "qurl.host() is '" + qurl.host() + "'." ); httpresponse.truncate( 0 ); // Some WMS servers don't like receiving a http request that // includes the scheme, host and port (the // http://www.address.bit:80), so remove that from the url before // executing an http GET. //Path could be just '/' so we remove the 'http://' first QString pathAndQuery = httpurl.remove( 0, httpurl.indexOf( qurl.host() ) ); pathAndQuery = httpurl.remove( 0, pathAndQuery.indexOf( qurl.path() ) ); if ( !postData ) //do request with HTTP GET { header.setRequest( "GET", pathAndQuery ); // do GET using header containing user-agent httpid = http->request( header ); } else //do request with HTTP POST { header.setRequest( "POST", pathAndQuery ); // do POST using header containing user-agent httpid = http->request( header, *postData ); } connect( http, SIGNAL( requestStarted( int ) ), this, SLOT( dataStarted( int ) ) ); connect( http, SIGNAL( responseHeaderReceived( const QHttpResponseHeader& ) ), this, SLOT( dataHeaderReceived( const QHttpResponseHeader& ) ) ); connect( http, SIGNAL( readyRead( const QHttpResponseHeader& ) ), this, SLOT( dataReceived( const QHttpResponseHeader& ) ) ); connect( http, SIGNAL( dataReadProgress( int, int ) ), this, SLOT( dataProgress( int, int ) ) ); connect( http, SIGNAL( requestFinished( int, bool ) ), this, SLOT( dataFinished( int, bool ) ) ); connect( http, SIGNAL( done( bool ) ), this, SLOT( transactionFinished( bool ) ) ); connect( http, SIGNAL( stateChanged( int ) ), this, SLOT( dataStateChanged( int ) ) ); // Set up the watchdog timer connect( mWatchdogTimer, SIGNAL( timeout() ), this, SLOT( networkTimedOut() ) ); mWatchdogTimer->setSingleShot( true ); mWatchdogTimer->start( mNetworkTimeoutMsec ); QgsDebugMsg( "Starting get with id " + QString::number( httpid ) + "." ); QgsDebugMsg( "Setting httpactive = true" ); httpactive = true; // A little trick to make this function blocking while ( httpactive ) { // Do something else, maybe even network processing events qApp->processEvents(); } QgsDebugMsg( "Response received." ); #ifdef QGISDEBUG // QString httpresponsestring(httpresponse); // QgsDebugMsg("Response received; being '" + httpresponsestring + "'."); #endif delete http; http = 0; // Did we get an error? If so, bail early if ( !mError.isEmpty() ) { QgsDebugMsg( "Processing an error '" + mError + "'." ); return false; } // Do one level of redirection // TODO make this recursable // TODO detect any redirection loops if ( !httpredirecturl.isEmpty() ) { QgsDebugMsg( "Starting get of '" + httpredirecturl + "'." ); QgsHttpTransaction httprecurse( httpredirecturl, httphost, httpport ); httprecurse.setCredentials( mUserName, mPassword ); // Do a passthrough for the status bar text connect( &httprecurse, SIGNAL( statusChanged( QString ) ), this, SIGNAL( statusChanged( QString ) ) ); httprecurse.getSynchronously( respondedContent, ( redirections + 1 ) ); return true; } respondedContent = httpresponse; return true; } QString QgsHttpTransaction::responseContentType() { return httpresponsecontenttype; } void QgsHttpTransaction::dataStarted( int id ) { Q_UNUSED( id ); QgsDebugMsg( "ID=" + QString::number( id ) + "." ); } void QgsHttpTransaction::dataHeaderReceived( const QHttpResponseHeader& resp ) { QgsDebugMsg( "statuscode " + QString::number( resp.statusCode() ) + ", reason '" + resp.reasonPhrase() + "', content type: '" + resp.value( "Content-Type" ) + "'." ); // We saw something come back, therefore restart the watchdog timer mWatchdogTimer->start( mNetworkTimeoutMsec ); if ( resp.statusCode() == 302 ) // Redirect { // Grab the alternative URL // (ref: "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html") httpredirecturl = resp.value( "Location" ); } else if ( resp.statusCode() == 200 ) // OK { // NOOP } else { mError = tr( "WMS Server responded unexpectedly with HTTP Status Code %1 (%2)" ) .arg( resp.statusCode() ) .arg( resp.reasonPhrase() ); } httpresponsecontenttype = resp.value( "Content-Type" ); } void QgsHttpTransaction::dataReceived( const QHttpResponseHeader& resp ) { Q_UNUSED( resp ); // TODO: Match 'resp' with 'http' if we move to multiple http connections #if 0 // Comment this out for now - leave the coding of progressive rendering to another day. char* temp; if ( 0 < http->readBlock( temp, http->bytesAvailable() ) ) { httpresponse.append( temp ); } #endif // QgsDebugMsg("received '" + data + "'."); } void QgsHttpTransaction::dataProgress( int done, int total ) { // QgsDebugMsg("got " + QString::number(done) + " of " + QString::number(total)); // We saw something come back, therefore restart the watchdog timer mWatchdogTimer->start( mNetworkTimeoutMsec ); emit dataReadProgress( done ); emit totalSteps( total ); QString status; if ( total ) { status = tr( "Received %1 of %2 bytes" ).arg( done ).arg( total ); } else { status = tr( "Received %1 bytes (total unknown)" ).arg( done ); } emit statusChanged( status ); } void QgsHttpTransaction::dataFinished( int id, bool error ) { #ifdef QGISDEBUG QgsDebugMsg( "ID=" + QString::number( id ) + "." ); // The signal that this slot is connected to, QHttp::requestFinished, // appears to get called at the destruction of the QHttp if it is // still working at the time of the destruction. // // This situation may occur when we've detected a timeout and // we already set httpactive = false. // // We have to detect this special case so that the last known error string is // not overwritten (it should rightfully refer to the timeout event). if ( !httpactive ) { QgsDebugMsg( "http activity loop already false." ); return; } if ( error ) { QgsDebugMsg( "however there was an error." ); QgsDebugMsg( "error: " + http->errorString() ); mError = tr( "HTTP response completed, however there was an error: %1" ).arg( http->errorString() ); } else { QgsDebugMsg( "no error." ); } #else Q_UNUSED( id ); Q_UNUSED( error ); #endif // Don't do this here as the request could have simply been // to set the hostname - see transactionFinished() instead #if 0 // TODO httpresponse = http->readAll(); // QgsDebugMsg("Setting httpactive = false"); httpactive = false; #endif } void QgsHttpTransaction::transactionFinished( bool error ) { #ifdef QGISDEBUG QgsDebugMsg( "entered." ); #if 0 // The signal that this slot is connected to, QHttp::requestFinished, // appears to get called at the destruction of the QHttp if it is // still working at the time of the destruction. // // This situation may occur when we've detected a timeout and // we already set httpactive = false. // // We have to detect this special case so that the last known error string is // not overwritten (it should rightfully refer to the timeout event). if ( !httpactive ) { // QgsDebugMsg("http activity loop already false."); return; } #endif if ( error ) { QgsDebugMsg( "however there was an error." ); QgsDebugMsg( "error: " + http->errorString() ); mError = tr( "HTTP transaction completed, however there was an error: %1" ).arg( http->errorString() ); } else { QgsDebugMsg( "no error." ); } #else Q_UNUSED( error ); #endif // TODO httpresponse = http->readAll(); QgsDebugMsg( "Setting httpactive = false" ); httpactive = false; } void QgsHttpTransaction::dataStateChanged( int state ) { QgsDebugMsg( "state " + QString::number( state ) + "." ); // We saw something come back, therefore restart the watchdog timer mWatchdogTimer->start( mNetworkTimeoutMsec ); switch ( state ) { case QHttp::Unconnected: QgsDebugMsg( "There is no connection to the host." ); emit statusChanged( tr( "Not connected" ) ); break; case QHttp::HostLookup: QgsDebugMsg( "A host name lookup is in progress." ); emit statusChanged( tr( "Looking up '%1'" ).arg( httphost ) ); break; case QHttp::Connecting: QgsDebugMsg( "An attempt to connect to the host is in progress." ); emit statusChanged( tr( "Connecting to '%1'" ).arg( httphost ) ); break; case QHttp::Sending: QgsDebugMsg( "The client is sending its request to the server." ); emit statusChanged( tr( "Sending request '%1'" ).arg( httpurl ) ); break; case QHttp::Reading: QgsDebugMsg( "The client's request has been sent and the client is reading the server's response." ); emit statusChanged( tr( "Receiving reply" ) ); break; case QHttp::Connected: QgsDebugMsg( "The connection to the host is open, but the client is neither sending a request, nor waiting for a response." ); emit statusChanged( tr( "Response is complete" ) ); break; case QHttp::Closing: QgsDebugMsg( "The connection is closing down, but is not yet closed. (The state will be Unconnected when the connection is closed.)" ); emit statusChanged( tr( "Closing down connection" ) ); break; } } void QgsHttpTransaction::networkTimedOut() { QgsDebugMsg( "entering." ); mError = tr( "Network timed out after %n second(s) of inactivity.\n" "This may be a problem in your network connection or at the WMS server.", "inactivity timeout", mNetworkTimeoutMsec / 1000 ); QgsDebugMsg( "Setting httpactive = false" ); httpactive = false; QgsDebugMsg( "exiting." ); } QString QgsHttpTransaction::errorString() { return mError; } bool QgsHttpTransaction::applyProxySettings( QHttp& http, const QString& url ) { QSettings settings; //check if proxy is enabled bool proxyEnabled = settings.value( "proxy/proxyEnabled", false ).toBool(); if ( !proxyEnabled ) { return false; } //check if the url should go through proxy QString proxyExcludedURLs = settings.value( "proxy/proxyExcludedUrls", "" ).toString(); if ( !proxyExcludedURLs.isEmpty() ) { QStringList excludedURLs = proxyExcludedURLs.split( "|" ); QStringList::const_iterator exclIt = excludedURLs.constBegin(); for ( ; exclIt != excludedURLs.constEnd(); ++exclIt ) { if ( url.startsWith( *exclIt ) ) { return false; //url does not go through proxy } } } //read type, host, port, user, passw from settings QString proxyHost = settings.value( "proxy/proxyHost", "" ).toString(); int proxyPort = settings.value( "proxy/proxyPort", "" ).toString().toInt(); QString proxyUser = settings.value( "proxy/proxyUser", "" ).toString(); QString proxyPassword = settings.value( "proxy/proxyPassword", "" ).toString(); QString proxyTypeString = settings.value( "proxy/proxyType", "" ).toString(); QNetworkProxy::ProxyType proxyType = QNetworkProxy::NoProxy; if ( proxyTypeString == "DefaultProxy" ) { proxyType = QNetworkProxy::DefaultProxy; } else if ( proxyTypeString == "Socks5Proxy" ) { proxyType = QNetworkProxy::Socks5Proxy; } else if ( proxyTypeString == "HttpProxy" ) { proxyType = QNetworkProxy::HttpProxy; } else if ( proxyTypeString == "HttpCachingProxy" ) { proxyType = QNetworkProxy::HttpCachingProxy; } else if ( proxyTypeString == "FtpCachingProxy" ) { proxyType = QNetworkProxy::FtpCachingProxy; } http.setProxy( QNetworkProxy( proxyType, proxyHost, proxyPort, proxyUser, proxyPassword ) ); return true; } void QgsHttpTransaction::abort() { if ( http ) { http->abort(); } } // ENDS
dakcarto/QGIS
src/core/qgshttptransaction.cpp
C++
gpl-2.0
16,693
package gof.behaviour.mediator; public class Colleague1 extends Colleague { public Colleague1(Mediator m){ super(m); } @Override public void action() { System.out.println("Colleague1"); } }
expleeve/GoF23
src/gof/behaviour/mediator/Colleague1.java
Java
gpl-2.0
218
#-------------------------------------------------- # Revision = $Rev: 20 $ # Date = $Date: 2011-08-05 20:42:24 +0200 (Fri, 05 Aug 2011) $ # Author = $Author: stefan $ #-------------------------------------------------- from pluginInterfaces import PluginFit, Parameter,leastsqFit import numpy as np class PluginFitThreeBodyBeta(PluginFit): def __init__(self): pass def fit(self,array,errarray,param,xmin=0,xmax=0, fitAxes=[]): """return the data that is needed for plotting the fitting result""" """0...a, 1...xc, 2...k, 3...y0""" self.params = [Parameter(v) for v in param] def f(x): return self.params[0]()/(1+np.exp(-(x-self.params[1]())/self.params[2]()))+self.params[3]() self.simpleFitAllAxes(f,array,errarray,xmin,xmax, fitAxes) return self.generateDataFromParameters(f,[np.amin(array[0,:]),np.amax(array[0,:])], np.size(fitAxes)+1, xmin, xmax, fitAxes) def getInitialParameters(self,data): """find the best initial values and return them""" dx = np.abs(data[0,0] - data[0,-1]) mi = np.amin(data[1,:]) ma = np.amax(data[1,:]) xc = (np.amax(data[0,:])-np.amin(data[0,:]))/2+np.amin(data[0,:]) return [ma-mi,xc,dx*2,mi] def getParameters(self): """return the fit parameters""" return np.array(["a","xc","dx","y0"]) def getFitModelStr(self): """return a string of the implemented fitting model, i.e. 'linear fit (y=A*x +B)'""" return "Sigmoidal" def getResultStr(self): """return a special result, i.e. 'Frequency = blabla'""" return "nothing fitted"
wakalixes/sqldataplot
plugins/pluginFitSigmoidal.py
Python
gpl-2.0
1,665
package org.globalgamejam.maze.tweens; import aurelienribon.tweenengine.TweenAccessor; import com.badlogic.gdx.graphics.g2d.Sprite; public class SpriteTween implements TweenAccessor<Sprite> { public static final int BOUNCE = 1; public static final int ALPHA = 2; public static final int ROTATION = 3; @Override public int getValues(Sprite target, int tweenType, float[] returnValues) { switch (tweenType) { case BOUNCE: returnValues[0] = target.getY(); return 1; case ALPHA: returnValues[0] = target.getColor().a; return 1; case ROTATION: returnValues[0] = target.getRotation(); return 1; default: return 0; } } @Override public void setValues(Sprite target, int tweenType, float[] newValues) { switch (tweenType) { case BOUNCE: target.setY(newValues[0]); break; case ALPHA: target.setColor(target.getColor().r, target.getColor().g, target.getColor().b, newValues[0]); break; case ROTATION: target.setRotation(newValues[0]); break; } } }
MyRealityCoding/maze
maze/src/org/globalgamejam/maze/tweens/SpriteTween.java
Java
gpl-2.0
1,020
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package norm import ( "strings" "testing" ) type PositionTest struct { input string pos int buffer string // expected contents of reorderBuffer, if applicable } type positionFunc func(rb *reorderBuffer, s string) int func runPosTests(t *testing.T, name string, f Form, fn positionFunc, tests []PositionTest) { rb := reorderBuffer{} rb.init(f, nil) for i, test := range tests { rb.reset() rb.src = inputString(test.input) rb.nsrc = len(test.input) pos := fn(&rb, test.input) if pos != test.pos { t.Errorf("%s:%d: position is %d; want %d", name, i, pos, test.pos) } runes := []rune(test.buffer) if rb.nrune != len(runes) { t.Errorf("%s:%d: reorder buffer lenght is %d; want %d", name, i, rb.nrune, len(runes)) continue } for j, want := range runes { found := rune(rb.runeAt(j)) if found != want { t.Errorf("%s:%d: rune at %d is %U; want %U", name, i, j, found, want) } } } } var decomposeSegmentTests = []PositionTest{ // illegal runes {"\xC0", 0, ""}, {"\u00E0\x80", 2, "\u0061\u0300"}, // starter {"a", 1, "a"}, {"ab", 1, "a"}, // starter + composing {"a\u0300", 3, "a\u0300"}, {"a\u0300b", 3, "a\u0300"}, // with decomposition {"\u00C0", 2, "A\u0300"}, {"\u00C0b", 2, "A\u0300"}, // long {strings.Repeat("\u0300", 31), 62, strings.Repeat("\u0300", 31)}, // ends with incomplete UTF-8 encoding {"\xCC", 0, ""}, {"\u0300\xCC", 2, "\u0300"}, } func decomposeSegmentF(rb *reorderBuffer, s string) int { rb.src = inputString(s) rb.nsrc = len(s) return decomposeSegment(rb, 0) } func TestDecomposeSegment(t *testing.T) { runPosTests(t, "TestDecomposeSegment", NFC, decomposeSegmentF, decomposeSegmentTests) } var firstBoundaryTests = []PositionTest{ // no boundary {"", -1, ""}, {"\u0300", -1, ""}, {"\x80\x80", -1, ""}, // illegal runes {"\xff", 0, ""}, {"\u0300\xff", 2, ""}, {"\u0300\xc0\x80\x80", 2, ""}, // boundaries {"a", 0, ""}, {"\u0300a", 2, ""}, // Hangul {"\u1103\u1161", 0, ""}, {"\u110B\u1173\u11B7", 0, ""}, {"\u1161\u110B\u1173\u11B7", 3, ""}, {"\u1173\u11B7\u1103\u1161", 6, ""}, // too many combining characters. {strings.Repeat("\u0300", maxCombiningChars-1), -1, ""}, {strings.Repeat("\u0300", maxCombiningChars), 60, ""}, {strings.Repeat("\u0300", maxCombiningChars+1), 60, ""}, } func firstBoundaryF(rb *reorderBuffer, s string) int { return rb.f.form.FirstBoundary([]byte(s)) } func firstBoundaryStringF(rb *reorderBuffer, s string) int { return rb.f.form.FirstBoundaryInString(s) } func TestFirstBoundary(t *testing.T) { runPosTests(t, "TestFirstBoundary", NFC, firstBoundaryF, firstBoundaryTests) runPosTests(t, "TestFirstBoundaryInString", NFC, firstBoundaryStringF, firstBoundaryTests) } var decomposeToLastTests = []PositionTest{ // ends with inert character {"Hello!", 6, ""}, {"\u0632", 2, ""}, {"a\u0301\u0635", 5, ""}, // ends with non-inert starter {"a", 0, "a"}, {"a\u0301a", 3, "a"}, {"a\u0301\u03B9", 3, "\u03B9"}, {"a\u0327", 0, "a\u0327"}, // illegal runes {"\xFF", 1, ""}, {"aa\xFF", 3, ""}, {"\xC0\x80\x80", 3, ""}, {"\xCC\x80\x80", 3, ""}, // ends with incomplete UTF-8 encoding {"a\xCC", 2, ""}, // ends with combining characters {"\u0300\u0301", 0, "\u0300\u0301"}, {"a\u0300\u0301", 0, "a\u0300\u0301"}, {"a\u0301\u0308", 0, "a\u0301\u0308"}, {"a\u0308\u0301", 0, "a\u0308\u0301"}, {"aaaa\u0300\u0301", 3, "a\u0300\u0301"}, {"\u0300a\u0300\u0301", 2, "a\u0300\u0301"}, {"\u00C0", 0, "A\u0300"}, {"a\u00C0", 1, "A\u0300"}, // decomposing {"a\u0300\uFDC0", 3, "\u0645\u062C\u064A"}, {"\uFDC0" + strings.Repeat("\u0300", 26), 0, "\u0645\u062C\u064A" + strings.Repeat("\u0300", 26)}, // Hangul {"a\u1103", 1, "\u1103"}, {"a\u110B", 1, "\u110B"}, {"a\u110B\u1173", 1, "\u110B\u1173"}, // See comment in composition.go:compBoundaryAfter. {"a\u110B\u1173\u11B7", 1, "\u110B\u1173\u11B7"}, {"a\uC73C", 1, "\u110B\u1173"}, {"다음", 3, "\u110B\u1173\u11B7"}, {"다", 0, "\u1103\u1161"}, {"\u1103\u1161\u110B\u1173\u11B7", 6, "\u110B\u1173\u11B7"}, {"\u110B\u1173\u11B7\u1103\u1161", 9, "\u1103\u1161"}, {"다음음", 6, "\u110B\u1173\u11B7"}, {"음다다", 6, "\u1103\u1161"}, // buffer overflow {"a" + strings.Repeat("\u0300", 30), 3, strings.Repeat("\u0300", 29)}, {"\uFDFA" + strings.Repeat("\u0300", 14), 3, strings.Repeat("\u0300", 14)}, // weird UTF-8 {"a\u0300\u11B7", 0, "a\u0300\u11B7"}, } func decomposeToLast(rb *reorderBuffer, s string) int { buf := decomposeToLastBoundary(rb, []byte(s)) return len(buf) } func TestDecomposeToLastBoundary(t *testing.T) { runPosTests(t, "TestDecomposeToLastBoundary", NFKC, decomposeToLast, decomposeToLastTests) } var lastBoundaryTests = []PositionTest{ // ends with inert character {"Hello!", 6, ""}, {"\u0632", 2, ""}, // ends with non-inert starter {"a", 0, ""}, // illegal runes {"\xff", 1, ""}, {"aa\xff", 3, ""}, {"a\xff\u0300", 1, ""}, {"\xc0\x80\x80", 3, ""}, {"\xc0\x80\x80\u0300", 3, ""}, // ends with incomplete UTF-8 encoding {"\xCC", -1, ""}, {"\xE0\x80", -1, ""}, {"\xF0\x80\x80", -1, ""}, {"a\xCC", 0, ""}, {"\x80\xCC", 1, ""}, {"\xCC\xCC", 1, ""}, // ends with combining characters {"a\u0300\u0301", 0, ""}, {"aaaa\u0300\u0301", 3, ""}, {"\u0300a\u0300\u0301", 2, ""}, {"\u00C0", 0, ""}, {"a\u00C0", 1, ""}, // decomposition may recombine {"\u0226", 0, ""}, // no boundary {"", -1, ""}, {"\u0300\u0301", -1, ""}, {"\u0300", -1, ""}, {"\x80\x80", -1, ""}, {"\x80\x80\u0301", -1, ""}, // Hangul {"다음", 3, ""}, {"다", 0, ""}, {"\u1103\u1161\u110B\u1173\u11B7", 6, ""}, {"\u110B\u1173\u11B7\u1103\u1161", 9, ""}, // too many combining characters. {strings.Repeat("\u0300", maxCombiningChars-1), -1, ""}, {strings.Repeat("\u0300", maxCombiningChars), 60, ""}, {strings.Repeat("\u0300", maxCombiningChars+1), 62, ""}, } func lastBoundaryF(rb *reorderBuffer, s string) int { return rb.f.form.LastBoundary([]byte(s)) } func TestLastBoundary(t *testing.T) { runPosTests(t, "TestLastBoundary", NFC, lastBoundaryF, lastBoundaryTests) } var quickSpanTests = []PositionTest{ {"", 0, ""}, // starters {"a", 1, ""}, {"abc", 3, ""}, {"\u043Eb", 3, ""}, // incomplete last rune. {"\xCC", 1, ""}, {"a\xCC", 2, ""}, // incorrectly ordered combining characters {"\u0300\u0316", 0, ""}, {"\u0300\u0316cd", 0, ""}, // have a maximum number of combining characters. {strings.Repeat("\u035D", 30) + "\u035B", 62, ""}, {"a" + strings.Repeat("\u035D", 30) + "\u035B", 63, ""}, {"Ɵ" + strings.Repeat("\u035D", 30) + "\u035B", 64, ""}, {"aa" + strings.Repeat("\u035D", 30) + "\u035B", 64, ""}, } var quickSpanNFDTests = []PositionTest{ // needs decomposing {"\u00C0", 0, ""}, {"abc\u00C0", 3, ""}, // correctly ordered combining characters {"\u0300", 2, ""}, {"ab\u0300", 4, ""}, {"ab\u0300cd", 6, ""}, {"\u0300cd", 4, ""}, {"\u0316\u0300", 4, ""}, {"ab\u0316\u0300", 6, ""}, {"ab\u0316\u0300cd", 8, ""}, {"ab\u0316\u0300\u00C0", 6, ""}, {"\u0316\u0300cd", 6, ""}, {"\u043E\u0308b", 5, ""}, // incorrectly ordered combining characters {"ab\u0300\u0316", 1, ""}, // TODO: we could skip 'b' as well. {"ab\u0300\u0316cd", 1, ""}, // Hangul {"같은", 0, ""}, } var quickSpanNFCTests = []PositionTest{ // okay composed {"\u00C0", 2, ""}, {"abc\u00C0", 5, ""}, // correctly ordered combining characters {"ab\u0300", 1, ""}, {"ab\u0300cd", 1, ""}, {"ab\u0316\u0300", 1, ""}, {"ab\u0316\u0300cd", 1, ""}, {"\u00C0\u035D", 4, ""}, // we do not special case leading combining characters {"\u0300cd", 0, ""}, {"\u0300", 0, ""}, {"\u0316\u0300", 0, ""}, {"\u0316\u0300cd", 0, ""}, // incorrectly ordered combining characters {"ab\u0300\u0316", 1, ""}, {"ab\u0300\u0316cd", 1, ""}, // Hangul {"같은", 6, ""}, } func doQuickSpan(rb *reorderBuffer, s string) int { return rb.f.form.QuickSpan([]byte(s)) } func doQuickSpanString(rb *reorderBuffer, s string) int { return rb.f.form.QuickSpanString(s) } func TestQuickSpan(t *testing.T) { runPosTests(t, "TestQuickSpanNFD1", NFD, doQuickSpan, quickSpanTests) runPosTests(t, "TestQuickSpanNFD2", NFD, doQuickSpan, quickSpanNFDTests) runPosTests(t, "TestQuickSpanNFC1", NFC, doQuickSpan, quickSpanTests) runPosTests(t, "TestQuickSpanNFC2", NFC, doQuickSpan, quickSpanNFCTests) runPosTests(t, "TestQuickSpanStringNFD1", NFD, doQuickSpanString, quickSpanTests) runPosTests(t, "TestQuickSpanStringNFD2", NFD, doQuickSpanString, quickSpanNFDTests) runPosTests(t, "TestQuickSpanStringNFC1", NFC, doQuickSpanString, quickSpanTests) runPosTests(t, "TestQuickSpanStringNFC2", NFC, doQuickSpanString, quickSpanNFCTests) } var isNormalTests = []PositionTest{ {"", 1, ""}, // illegal runes {"\xff", 1, ""}, // starters {"a", 1, ""}, {"abc", 1, ""}, {"\u043Eb", 1, ""}, // incorrectly ordered combining characters {"\u0300\u0316", 0, ""}, {"ab\u0300\u0316", 0, ""}, {"ab\u0300\u0316cd", 0, ""}, {"\u0300\u0316cd", 0, ""}, } var isNormalNFDTests = []PositionTest{ // needs decomposing {"\u00C0", 0, ""}, {"abc\u00C0", 0, ""}, // correctly ordered combining characters {"\u0300", 1, ""}, {"ab\u0300", 1, ""}, {"ab\u0300cd", 1, ""}, {"\u0300cd", 1, ""}, {"\u0316\u0300", 1, ""}, {"ab\u0316\u0300", 1, ""}, {"ab\u0316\u0300cd", 1, ""}, {"\u0316\u0300cd", 1, ""}, {"\u043E\u0308b", 1, ""}, // Hangul {"같은", 0, ""}, } var isNormalNFCTests = []PositionTest{ // okay composed {"\u00C0", 1, ""}, {"abc\u00C0", 1, ""}, // need reordering {"a\u0300", 0, ""}, {"a\u0300cd", 0, ""}, {"a\u0316\u0300", 0, ""}, {"a\u0316\u0300cd", 0, ""}, // correctly ordered combining characters {"ab\u0300", 1, ""}, {"ab\u0300cd", 1, ""}, {"ab\u0316\u0300", 1, ""}, {"ab\u0316\u0300cd", 1, ""}, {"\u00C0\u035D", 1, ""}, {"\u0300", 1, ""}, {"\u0316\u0300cd", 1, ""}, // Hangul {"같은", 1, ""}, } func isNormalF(rb *reorderBuffer, s string) int { if rb.f.form.IsNormal([]byte(s)) { return 1 } return 0 } func TestIsNormal(t *testing.T) { runPosTests(t, "TestIsNormalNFD1", NFD, isNormalF, isNormalTests) runPosTests(t, "TestIsNormalNFD2", NFD, isNormalF, isNormalNFDTests) runPosTests(t, "TestIsNormalNFC1", NFC, isNormalF, isNormalTests) runPosTests(t, "TestIsNormalNFC2", NFC, isNormalF, isNormalNFCTests) } type AppendTest struct { left string right string out string } type appendFunc func(f Form, out []byte, s string) []byte func runAppendTests(t *testing.T, name string, f Form, fn appendFunc, tests []AppendTest) { for i, test := range tests { out := []byte(test.left) out = fn(f, out, test.right) outs := string(out) if len(outs) != len(test.out) { t.Errorf("%s:%d: length is %d; want %d", name, i, len(outs), len(test.out)) } if outs != test.out { // Find first rune that differs and show context. ir := []rune(outs) ig := []rune(test.out) for j := 0; j < len(ir) && j < len(ig); j++ { if ir[j] == ig[j] { continue } if j -= 3; j < 0 { j = 0 } for e := j + 7; j < e && j < len(ir) && j < len(ig); j++ { t.Errorf("%s:%d: runeAt(%d) = %U; want %U", name, i, j, ir[j], ig[j]) } break } } } } var appendTests = []AppendTest{ // empty buffers {"", "", ""}, {"a", "", "a"}, {"", "a", "a"}, {"", "\u0041\u0307\u0304", "\u01E0"}, // segment split across buffers {"", "a\u0300b", "\u00E0b"}, {"a", "\u0300b", "\u00E0b"}, {"a", "\u0300\u0316", "\u00E0\u0316"}, {"a", "\u0316\u0300", "\u00E0\u0316"}, {"a", "\u0300a\u0300", "\u00E0\u00E0"}, {"a", "\u0300a\u0300a\u0300", "\u00E0\u00E0\u00E0"}, {"a", "\u0300aaa\u0300aaa\u0300", "\u00E0aa\u00E0aa\u00E0"}, {"a\u0300", "\u0327", "\u00E0\u0327"}, {"a\u0327", "\u0300", "\u00E0\u0327"}, {"a\u0316", "\u0300", "\u00E0\u0316"}, {"\u0041\u0307", "\u0304", "\u01E0"}, // Hangul {"", "\u110B\u1173", "\uC73C"}, {"", "\u1103\u1161", "\uB2E4"}, {"", "\u110B\u1173\u11B7", "\uC74C"}, {"", "\u320E", "\x28\uAC00\x29"}, {"", "\x28\u1100\u1161\x29", "\x28\uAC00\x29"}, {"\u1103", "\u1161", "\uB2E4"}, {"\u110B", "\u1173\u11B7", "\uC74C"}, {"\u110B\u1173", "\u11B7", "\uC74C"}, {"\uC73C", "\u11B7", "\uC74C"}, // UTF-8 encoding split across buffers {"a\xCC", "\x80", "\u00E0"}, {"a\xCC", "\x80b", "\u00E0b"}, {"a\xCC", "\x80a\u0300", "\u00E0\u00E0"}, {"a\xCC", "\x80\x80", "\u00E0\x80"}, {"a\xCC", "\x80\xCC", "\u00E0\xCC"}, {"a\u0316\xCC", "\x80a\u0316\u0300", "\u00E0\u0316\u00E0\u0316"}, // ending in incomplete UTF-8 encoding {"", "\xCC", "\xCC"}, {"a", "\xCC", "a\xCC"}, {"a", "b\xCC", "ab\xCC"}, {"\u0226", "\xCC", "\u0226\xCC"}, // illegal runes {"", "\x80", "\x80"}, {"", "\x80\x80\x80", "\x80\x80\x80"}, {"", "\xCC\x80\x80\x80", "\xCC\x80\x80\x80"}, {"", "a\x80", "a\x80"}, {"", "a\x80\x80\x80", "a\x80\x80\x80"}, {"", "a\x80\x80\x80\x80\x80\x80", "a\x80\x80\x80\x80\x80\x80"}, {"a", "\x80\x80\x80", "a\x80\x80\x80"}, // overflow {"", strings.Repeat("\x80", 33), strings.Repeat("\x80", 33)}, {strings.Repeat("\x80", 33), "", strings.Repeat("\x80", 33)}, {strings.Repeat("\x80", 33), strings.Repeat("\x80", 33), strings.Repeat("\x80", 66)}, // overflow of combining characters {strings.Repeat("\u0300", 33), "", strings.Repeat("\u0300", 33)}, // weird UTF-8 {"\u00E0\xE1", "\x86", "\u00E0\xE1\x86"}, {"a\u0300\u11B7", "\u0300", "\u00E0\u11B7\u0300"}, {"a\u0300\u11B7\u0300", "\u0300", "\u00E0\u11B7\u0300\u0300"}, {"\u0300", "\xF8\x80\x80\x80\x80\u0300", "\u0300\xF8\x80\x80\x80\x80\u0300"}, {"\u0300", "\xFC\x80\x80\x80\x80\x80\u0300", "\u0300\xFC\x80\x80\x80\x80\x80\u0300"}, {"\xF8\x80\x80\x80\x80\u0300", "\u0300", "\xF8\x80\x80\x80\x80\u0300\u0300"}, {"\xFC\x80\x80\x80\x80\x80\u0300", "\u0300", "\xFC\x80\x80\x80\x80\x80\u0300\u0300"}, {"\xF8\x80\x80\x80", "\x80\u0300\u0300", "\xF8\x80\x80\x80\x80\u0300\u0300"}, } func appendF(f Form, out []byte, s string) []byte { return f.Append(out, []byte(s)...) } func appendStringF(f Form, out []byte, s string) []byte { return f.AppendString(out, s) } func bytesF(f Form, out []byte, s string) []byte { buf := []byte{} buf = append(buf, out...) buf = append(buf, s...) return f.Bytes(buf) } func stringF(f Form, out []byte, s string) []byte { outs := string(out) + s return []byte(f.String(outs)) } func TestAppend(t *testing.T) { runAppendTests(t, "TestAppend", NFKC, appendF, appendTests) runAppendTests(t, "TestAppendString", NFKC, appendStringF, appendTests) runAppendTests(t, "TestBytes", NFKC, bytesF, appendTests) runAppendTests(t, "TestString", NFKC, stringF, appendTests) } func doFormBenchmark(b *testing.B, inf, f Form, s string) { b.StopTimer() in := inf.Bytes([]byte(s)) buf := make([]byte, 2*len(in)) b.SetBytes(int64(len(in))) b.StartTimer() for i := 0; i < b.N; i++ { buf = f.Append(buf[0:0], in...) buf = buf[0:0] } } var ascii = strings.Repeat("There is nothing to change here! ", 500) func BenchmarkNormalizeAsciiNFC(b *testing.B) { doFormBenchmark(b, NFC, NFC, ascii) } func BenchmarkNormalizeAsciiNFD(b *testing.B) { doFormBenchmark(b, NFC, NFD, ascii) } func BenchmarkNormalizeAsciiNFKC(b *testing.B) { doFormBenchmark(b, NFC, NFKC, ascii) } func BenchmarkNormalizeAsciiNFKD(b *testing.B) { doFormBenchmark(b, NFC, NFKD, ascii) } func BenchmarkNormalizeNFC2NFC(b *testing.B) { doFormBenchmark(b, NFC, NFC, txt_all) } func BenchmarkNormalizeNFC2NFD(b *testing.B) { doFormBenchmark(b, NFC, NFD, txt_all) } func BenchmarkNormalizeNFD2NFC(b *testing.B) { doFormBenchmark(b, NFD, NFC, txt_all) } func BenchmarkNormalizeNFD2NFD(b *testing.B) { doFormBenchmark(b, NFD, NFD, txt_all) } // Hangul is often special-cased, so we test it separately. func BenchmarkNormalizeHangulNFC2NFC(b *testing.B) { doFormBenchmark(b, NFC, NFC, txt_kr) } func BenchmarkNormalizeHangulNFC2NFD(b *testing.B) { doFormBenchmark(b, NFC, NFD, txt_kr) } func BenchmarkNormalizeHangulNFD2NFC(b *testing.B) { doFormBenchmark(b, NFD, NFC, txt_kr) } func BenchmarkNormalizeHangulNFD2NFD(b *testing.B) { doFormBenchmark(b, NFD, NFD, txt_kr) } func doTextBenchmark(b *testing.B, s string) { b.StopTimer() b.SetBytes(int64(len(s)) * 4) in := []byte(s) var buf = make([]byte, 0, 2*len(in)) b.StartTimer() for i := 0; i < b.N; i++ { NFC.Append(buf, in...) NFD.Append(buf, in...) NFKC.Append(buf, in...) NFKD.Append(buf, in...) } } func BenchmarkCanonicalOrdering(b *testing.B) { doTextBenchmark(b, txt_canon) } func BenchmarkExtendedLatin(b *testing.B) { doTextBenchmark(b, txt_vn) } func BenchmarkMiscTwoByteUtf8(b *testing.B) { doTextBenchmark(b, twoByteUtf8) } func BenchmarkMiscThreeByteUtf8(b *testing.B) { doTextBenchmark(b, threeByteUtf8) } func BenchmarkHangul(b *testing.B) { doTextBenchmark(b, txt_kr) } func BenchmarkJapanese(b *testing.B) { doTextBenchmark(b, txt_jp) } func BenchmarkChinese(b *testing.B) { doTextBenchmark(b, txt_cn) } // Tests sampled from the Canonical ordering tests (Part 2) of // http://unicode.org/Public/UNIDATA/NormalizationTest.txt const txt_canon = `\u0061\u0315\u0300\u05AE\u0300\u0062 \u0061\u0300\u0315\u0300\u05AE\u0062 \u0061\u0302\u0315\u0300\u05AE\u0062 \u0061\u0307\u0315\u0300\u05AE\u0062 \u0061\u0315\u0300\u05AE\u030A\u0062 \u0061\u059A\u0316\u302A\u031C\u0062 \u0061\u032E\u059A\u0316\u302A\u0062 \u0061\u0338\u093C\u0334\u0062 \u0061\u059A\u0316\u302A\u0339 \u0061\u0341\u0315\u0300\u05AE\u0062 \u0061\u0348\u059A\u0316\u302A\u0062 \u0061\u0361\u0345\u035D\u035C\u0062 \u0061\u0366\u0315\u0300\u05AE\u0062 \u0061\u0315\u0300\u05AE\u0486\u0062 \u0061\u05A4\u059A\u0316\u302A\u0062 \u0061\u0315\u0300\u05AE\u0613\u0062 \u0061\u0315\u0300\u05AE\u0615\u0062 \u0061\u0617\u0315\u0300\u05AE\u0062 \u0061\u0619\u0618\u064D\u064E\u0062 \u0061\u0315\u0300\u05AE\u0654\u0062 \u0061\u0315\u0300\u05AE\u06DC\u0062 \u0061\u0733\u0315\u0300\u05AE\u0062 \u0061\u0744\u059A\u0316\u302A\u0062 \u0061\u0315\u0300\u05AE\u0745\u0062 \u0061\u09CD\u05B0\u094D\u3099\u0062 \u0061\u0E38\u0E48\u0E38\u0C56\u0062 \u0061\u0EB8\u0E48\u0E38\u0E49\u0062 \u0061\u0F72\u0F71\u0EC8\u0F71\u0062 \u0061\u1039\u05B0\u094D\u3099\u0062 \u0061\u05B0\u094D\u3099\u1A60\u0062 \u0061\u3099\u093C\u0334\u1BE6\u0062 \u0061\u3099\u093C\u0334\u1C37\u0062 \u0061\u1CD9\u059A\u0316\u302A\u0062 \u0061\u2DED\u0315\u0300\u05AE\u0062 \u0061\u2DEF\u0315\u0300\u05AE\u0062 \u0061\u302D\u302E\u059A\u0316\u0062` // Taken from http://creativecommons.org/licenses/by-sa/3.0/vn/ const txt_vn = `Với các điều kiện sau: Ghi nhận công của tác giả. Nếu bạn sử dụng, chuyển đổi, hoặc xây dựng dự án từ nội dung được chia sẻ này, bạn phải áp dụng giấy phép này hoặc một giấy phép khác có các điều khoản tương tự như giấy phép này cho dự án của bạn. Hiểu rằng: Miễn — Bất kỳ các điều kiện nào trên đây cũng có thể được miễn bỏ nếu bạn được sự cho phép của người sở hữu bản quyền. Phạm vi công chúng — Khi tác phẩm hoặc bất kỳ chương nào của tác phẩm đã trong vùng dành cho công chúng theo quy định của pháp luật thì tình trạng của nó không bị ảnh hưởng bởi giấy phép trong bất kỳ trường hợp nào.` // Taken from http://creativecommons.org/licenses/by-sa/1.0/deed.ru const txt_ru = `При обязательном соблюдении следующих условий: Attribution — Вы должны атрибутировать произведение (указывать автора и источник) в порядке, предусмотренном автором или лицензиаром (но только так, чтобы никоим образом не подразумевалось, что они поддерживают вас или использование вами данного произведения). Υπό τις ακόλουθες προϋποθέσεις:` // Taken from http://creativecommons.org/licenses/by-sa/3.0/gr/ const txt_gr = `Αναφορά Δημιουργού — Θα πρέπει να κάνετε την αναφορά στο έργο με τον τρόπο που έχει οριστεί από το δημιουργό ή το χορηγούντο την άδεια (χωρίς όμως να εννοείται με οποιονδήποτε τρόπο ότι εγκρίνουν εσάς ή τη χρήση του έργου από εσάς). Παρόμοια Διανομή — Εάν αλλοιώσετε, τροποποιήσετε ή δημιουργήσετε περαιτέρω βασισμένοι στο έργο θα μπορείτε να διανέμετε το έργο που θα προκύψει μόνο με την ίδια ή παρόμοια άδεια.` // Taken from http://creativecommons.org/licenses/by-sa/3.0/deed.ar const txt_ar = `بموجب الشروط التالية نسب المصنف — يجب عليك أن تنسب العمل بالطريقة التي تحددها المؤلف أو المرخص (ولكن ليس بأي حال من الأحوال أن توحي وتقترح بتحول أو استخدامك للعمل). المشاركة على قدم المساواة — إذا كنت يعدل ، والتغيير ، أو الاستفادة من هذا العمل ، قد ينتج عن توزيع العمل إلا في ظل تشابه او تطابق فى واحد لهذا الترخيص.` // Taken from http://creativecommons.org/licenses/by-sa/1.0/il/ const txt_il = `בכפוף לתנאים הבאים: ייחוס — עליך לייחס את היצירה (לתת קרדיט) באופן המצויין על-ידי היוצר או מעניק הרישיון (אך לא בשום אופן המרמז על כך שהם תומכים בך או בשימוש שלך ביצירה). שיתוף זהה — אם תחליט/י לשנות, לעבד או ליצור יצירה נגזרת בהסתמך על יצירה זו, תוכל/י להפיץ את יצירתך החדשה רק תחת אותו הרישיון או רישיון דומה לרישיון זה.` const twoByteUtf8 = txt_ru + txt_gr + txt_ar + txt_il // Taken from http://creativecommons.org/licenses/by-sa/2.0/kr/ const txt_kr = `다음과 같은 조건을 따라야 합니다: 저작자표시 (Attribution) — 저작자나 이용허락자가 정한 방법으로 저작물의 원저작자를 표시하여야 합니다(그러나 원저작자가 이용자나 이용자의 이용을 보증하거나 추천한다는 의미로 표시해서는 안됩니다). 동일조건변경허락 — 이 저작물을 이용하여 만든 이차적 저작물에는 본 라이선스와 동일한 라이선스를 적용해야 합니다.` // Taken from http://creativecommons.org/licenses/by-sa/3.0/th/ const txt_th = `ภายใต้เงื่อนไข ดังต่อไปนี้ : แสดงที่มา — คุณต้องแสดงที่ มาของงานดังกล่าว ตามรูปแบบที่ผู้สร้างสรรค์หรือผู้อนุญาตกำหนด (แต่ ไม่ใช่ในลักษณะที่ว่า พวกเขาสนับสนุนคุณหรือสนับสนุนการที่ คุณนำงานไปใช้) อนุญาตแบบเดียวกัน — หากคุณดัดแปลง เปลี่ยนรูป หรื อต่อเติมงานนี้ คุณต้องใช้สัญญาอนุญาตแบบเดียวกันหรือแบบที่เหมื อนกับสัญญาอนุญาตที่ใช้กับงานนี้เท่านั้น` const threeByteUtf8 = txt_th // Taken from http://creativecommons.org/licenses/by-sa/2.0/jp/ const txt_jp = `あなたの従うべき条件は以下の通りです。 表示 — あなたは原著作者のクレジットを表示しなければなりません。 継承 — もしあなたがこの作品を改変、変形または加工した場合、 あなたはその結果生じた作品をこの作品と同一の許諾条件の下でのみ 頒布することができます。` // http://creativecommons.org/licenses/by-sa/2.5/cn/ const txt_cn = `您可以自由: 复制、发行、展览、表演、放映、 广播或通过信息网络传播本作品 创作演绎作品 对本作品进行商业性使用 惟须遵守下列条件: 署名 — 您必须按照作者或者许可人指定的方式对作品进行署名。 相同方式共享 — 如果您改变、转换本作品或者以本作品为基础进行创作, 您只能采用与本协议相同的许可协议发布基于本作品的演绎作品。` const txt_cjk = txt_cn + txt_jp + txt_kr const txt_all = txt_vn + twoByteUtf8 + threeByteUtf8 + txt_cjk
chapuni/gcc
libgo/go/exp/norm/normalize_test.go
GO
gpl-2.0
24,941
<?php namespace RainLab\GoogleAnalytics; /** * The plugin.php file (called the plugin initialization script) defines the plugin information class. */ use System\Classes\PluginBase; class Plugin extends PluginBase { public function pluginDetails() { return [ 'name' => 'Google Analytics', 'description' => 'Provides the Google Analytics tracking and reporting.', 'author' => 'Alexey Bobkov, Samuel Georges', 'icon' => 'icon-bar-chart-o' ]; } public function registerComponents() { return [ '\RainLab\GoogleAnalytics\Components\Tracker' => 'googleTracker' ]; } public function registerReportWidgets() { return [ 'RainLab\GoogleAnalytics\ReportWidgets\TrafficOverview'=>[ 'name'=>'Google Analytics traffic overview', 'context'=>'dashboard' ], 'RainLab\GoogleAnalytics\ReportWidgets\TrafficSources'=>[ 'name'=>'Google Analytics traffic sources', 'context'=>'dashboard' ], 'RainLab\GoogleAnalytics\ReportWidgets\Browsers'=>[ 'name'=>'Google Analytics browsers', 'context'=>'dashboard' ], 'RainLab\GoogleAnalytics\ReportWidgets\TrafficGoal'=>[ 'name'=>'Google Analytics traffic goal', 'context'=>'dashboard' ], 'RainLab\GoogleAnalytics\ReportWidgets\TopPages'=>[ 'name'=>'Google Analytics top pages', 'context'=>'dashboard' ] ]; } public function registerSettings() { return [ 'config' => [ 'label' => 'Google Analytics', 'icon' => 'icon-bar-chart-o', 'description' => 'Configure Google Analytics API code and tracking options.', 'class' => 'RainLab\GoogleAnalytics\Models\Settings', 'order' => 100 ] ]; } }
imfaber/imfaber_v2
plugins/rainlab/googleanalytics/Plugin.php
PHP
gpl-2.0
2,066
#include "pessoa_cpp.hpp" Pessoa::Pessoa() { } Pessoa::Pessoa(QString nome, int idade, float altura) { this->setNome(nome); this->idade = idade; this->altura = altura; } Pessoa::~Pessoa() { qDebug() << "Deletando a pessoa " << this; } void Pessoa::setNome(QString nome) { this->nome = nome + "Foi!"; } void Pessoa::setIdade(int idade) { this->idade = idade; } void Pessoa::setAltura(float altura) { this->altura = altura; } Pessoa * Pessoa::casar(const Pessoa * other) { Pessoa * resultado = new Pessoa(this->nome + other->nome, this->idade + other->idade, this->altura + other->altura); return resultado; } #ifndef QT_NO_DEBUG void Pessoa::print() { qDebug() << ":: Pessoa ::"; qDebug() << "Endereco: " << this; qDebug() << "Nome: " << this->nome; qDebug() << "Idade: " << this->idade; qDebug() << "Altura: " << this->altura; qDebug() << ":: -------------- ::"; } #endif
Luccas-A/ecom008_2014_1_13211694
pessoa_cpp.cpp
C++
gpl-2.0
1,014
<?php /** * $ModDesc * * @version $Id: $file.php $Revision * @package modules * @subpackage $Subpackage. * @copyright Copyright (C) April 2051 JowWow.net <@emai:troy@jowwow.net>.All rights reserved. * @license GNU General Public License version 2 */ // no direct access defined('_JEXEC') or die; /** * Get a collection of categories */ class JFormFieldLoftoolbar extends JFormField { /* * Category name * * @access protected * @var string */ protected $type = 'fgroup'; /** * fetch Element */ protected function getInput(){ // echo '<pre>'.print_r($this->element,1); ?> <ul class="lof-toolbar-items"> <?php foreach( $this->element->children() as $option ) { ?> <!--?php echo $option->data();?></li>--> <?php } ?> </ul> <?php } function getLabel(){ return ; } } ?>
N6REJ/JowSlider
libs/elements/loftoolbar.php
PHP
gpl-2.0
857
<?php /* * @package Montser Platform */ get_header( ); ?> <h2>エコ回収の実績</h2> <section class="contents" id=""> <div class="container"> <h3 class="twelvecol col last"> <span class="hl1">実績</span> <span class="hl2"><span>1</span></span> <span class="hl3">ただ今、エコ回収されています。</span> </h3> <!--#contents .container--></div> <!--#contents--></section> <section class="contents" id="chart"> <div class="container"> <h3 class="twelvecol col last"> <span class="hl1">実績</span> <div class="hl2"><span>2</span></div> <span class="hl3">エコ回収10年の歩み</span> </h3> <div> <div class="eightcol"> <div> <h4>年々成長中です。</h4> <p>あるいはたとえばご論旨を強いるものはどう高等と与えたので、<br />その通りにはするだてについて釣へ至るていますで。</p> <canvas id="lineChart" width="700" height="250">></canvas> </div> <div id="doughnutCharts"> <h4>2013年<span id="goodsVal"></span>品のモノをエコ回収しました。</h4> <ul> <li> <canvas id="doughnutChart1" width="130"></canvas> <div id="doughnutLegend1"></div> </li> <li> <canvas id="doughnutChart2" width="130"></canvas> <div id="doughnutLegend2"></div> </li> <li> <canvas id="doughnutChart3" width="130"></canvas> <div id="doughnutLegend3"></div> </li> <li> <canvas id="doughnutChart4" width="130"></canvas> <div id="doughnutLegend4"></div> </li> <li class="last"> <canvas id="doughnutChart5" width="130"></canvas> <div id="doughnutLegend5"></div> </li> </ul> </div> <div id="imgCharts"> <h4>2013年<span id="peopleVal"></span>人がエコ回収を利用しました。</h4> <ul class="fivecol col"> <li> <div>女性<span id="femaleVal"></span>%</div> <div class="imgPercent"><span id="userFemale"></span></div> </li> <li> <div>男性<span id="maleVal"></span>%</div> <div class="imgPercent"><span id="userMale"></span></div> </li> </ul> <ul class="fivecol col"> <li> <div>個人<span id="personVal"></span>%</div> <div class="imgPercent"><span id="house1"></span></div> </li> <li> <div>法人<span id="companyVal"></span>%</div> <div class="imgPercent"><span id="house2"></span></div> </li> </ul> <div id="japan" class="twocol col last"> <img src="<?php echo bloginfo("template_url"); ?>/assets/img/accomplishment/demo_japan.png" /> <div>東京<br /><span id="tokyoVal"></span>%</div> </div> </div> </div> <div class="fourcol last" id="milestone"> <ul> <li id="case1"><span class="year">2014</span><span>うしたため安危の時その向うはあなたごろ</span></li> <li id="case2"><span class="year">2014</span><span>うしたため安危の時その向うはあなたごろ</span></li> <li id="case3"><span class="year">2014</span><span>うしたため安危の時その向うはあなたごろ</span></li> <li id="case4"><span class="year">2014</span><span>うしたため安危の時その向うはあなたごろ</span></li> <li id="case5"><span class="year">2014</span><span>うしたため安危の時その向うはあなたごろ</span></li> <li id="case6"><span class="year">2014</span><span>うしたため安危の時その向うはあなたごろ</span></li> <li id="case7"><span class="year">2014</span><span>うしたため安危の時その向うはあなたごろ</span></li> </ul> </div> </div> <!--#chart .container--></div> <!--#chart--></section> <section class="contents" id="partner"> <div class="container"> <h3 class="twelvecol col last"> <span class="hl1">実績</span> <span class="hl2"><span>3</span></span> <span class="hl3">大手企業と提携しています</span> </h3> <div> <img src="<?php echo bloginfo("template_url"); ?>/assets/img/accomplishment/demo_logo.png" /> </div> <!--#partner .container--></div> <!--#partner--></section> <section class="contents" id="media"> <div class="container"> <h3 class="twelvecol col last"> <span class="hl1">実績</span> <span class="hl2"><span>3</span></span> <span class="hl3">様々なメディアに取り上げて頂いています</span> </h3> <div class="row"> <div class="col threecol"> <div class="circleTrimming"><img src="<?php echo bloginfo("template_url"); ?>/assets/img/accomplishment/demo_photo1.jpg" /></div> <h4>メディアA</h4> <ul> <li>そうしたため安危の時その向うは</li> <li>あなたごろで行くんかと木下さん</li> </ul> <p>あるいはたとえばご論旨を強いるものはどう高等と与えだので、その通りにはするだてについて釣へ至るています</p> </div> <div class="col threecol"> <div class="circleTrimming"><img src="<?php echo bloginfo("template_url"); ?>/assets/img/accomplishment/demo_photo1.jpg" /></div> <h4>メディアB</h4> <ul> <li>そうしたため安危の時その向うは</li> <li>あなたごろで行くんかと木下さん</li> </ul> <p>あるいはたとえばご論旨を強いるものはどう高等と与えだので、その通りにはするだてについて釣へ至るています</p> </div> <div class="col threecol"> <div class="circleTrimming"><img src="<?php echo bloginfo("template_url"); ?>/assets/img/accomplishment/demo_photo1.jpg" /></div> <h4>メディアC</h4> <ul> <li>そうしたため安危の時その向うは</li> <li>あなたごろで行くんかと木下さん</li> </ul> <p>あるいはたとえばご論旨を強いるものはどう高等と与えだので、その通りにはするだてについて釣へ至るています</p> </div> <div class="col threecol last"> <div class="circleTrimming"><img src="<?php echo bloginfo("template_url"); ?>/assets/img/accomplishment/demo_photo1.jpg" /></div> <h4>メディアD</h4> <ul> <li>そうしたため安危の時その向うは</li> <li>あなたごろで行くんかと木下さん</li> </ul> <p>あるいはたとえばご論旨を強いるものはどう高等と与えだので、その通りにはするだてについて釣へ至るています</p> </div> </div> <!--#media .container--></div> <!--#media--></section> <script type="text/javascript" src="<?php echo bloginfo("template_url"); ?>/assets/js/Chart.min.js"></script> <script type="text/javascript" src="<?php echo bloginfo("template_url"); ?>/assets/js/chart.js"></script> <?php get_footer(); ?>
eleewinroader/mp-ecokaishu
wp-content/themes/ecokaishu/archive-accomplishment.php
PHP
gpl-2.0
7,011
<?php /** * Shortcode attributes * @var $atts * @var $style * @var $faq_cat * Shortcode class * @var $this WPBakeryShortCode_Faq */ $output = ''; $atts = vc_map_get_attributes( $this->getShortcode(), $atts ); extract( $atts ); $output = '<div class="">'; if($faq_cat == 0){ $args = array( 'taxonomy' => 'faq_entries', 'hide_empty'=> 0 ); $categories = get_categories($args); if(count($categories) > 0){ $output .='<!-- Portfolio Filter --><nav id="faq-filter" class="">'; $output .= '<ul class="">'; $output .= '<li class="active all"><a href="#" data-filter="*">'.__('View All', 'codeless').'</a><span></span></li>'; foreach($categories as $cat): $output .= '<li class="other"><a href="#" data-filter=".'.esc_attr($cat->category_nicename).'">'.esc_attr($cat->cat_name).'</a><span></span></li>'; endforeach; $output .='</ul>'; $output .= '</nav>'; } } $nr = rand(0, 5000); $output .= '<div class="accordion faq '.esc_attr($style).'" id="accordion'.esc_attr($nr).'">'; if((int) $faq_cat == 0) $query_post = array('posts_per_page'=> 9999, 'post_type'=> 'faq' ); else{ $query_post = array('posts_per_page'=> 9999, 'post_type'=> 'faq', 'tax_query' => array( array( 'taxonomy' => 'testimonial_entries', 'field' => 'id', 'terms' => (int) $faq_cat, 'operator' => 'IN')) ); } $i = 0; $loop = new WP_Query($query_post); if($loop->have_posts()){ while($loop->have_posts()){ $i++; $loop->the_post(); $sort_classes = ""; $item_categories = get_the_terms( get_the_ID(), 'faq_entries' ); if(is_object($item_categories) || is_array($item_categories)) { foreach ($item_categories as $cat) { $sort_classes .= $cat->slug.' '; } } $output .= '<div class="accordion-group '.esc_attr($sort_classes).'">'; $output .= '<div class="accordion-heading '.( ($i == 1)?'in_head':'' ).'">'; $id = rand(0, 50000); $output .= '<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion'.esc_attr($nr).'" href="#toggle'.esc_attr($id).'">'; $output .= get_the_title(); $output .= '</a>'; $output .= '</div>'; $output .= '<div id="toggle'.esc_attr($id).'" class="accordion-body '.( ($i == 1)?'in':'' ).' collapse ">'; $output .= '<div class="accordion-inner">'; $output .= get_the_content(); $output .= '</div>'; $output .= '</div>'; $output .= '</div>'; } } $output .= '</div>'; $output .= '</div>'; echo $output; ?>
jzornow/cotton_consulting
wp-content/themes/specular/vc_templates/faq.php
PHP
gpl-2.0
3,805
package sellpotato.sellpotato.Model; /** * @author Freddy * @version 1.0 * @created 08-ene-2015 19:29:24 */ public class IGoogleApiMaps { public IGoogleApiMaps(){ } public void finalize() throws Throwable { } public void DibujarRuta(){ } public double CombertirDireccionPunto(){ return 0; } }//end IGoogleApiMaps
pollorijas/SellPotato
SellPotato/app/src/main/java/sellpotato/sellpotato/Model/IGoogleApiMaps.java
Java
gpl-2.0
333
// IT lang variables tinyMCE.addToLang('',{ bold_desc : 'Grassetto (Ctrl+B)', italic_desc : 'Corsivo (Ctrl+I)', underline_desc : 'Sottolineato (Ctrl+U)', striketrough_desc : 'Barrato', justifyleft_desc : 'Allinea a sinistra', justifycenter_desc : 'Allinea al centro', justifyright_desc : 'Allinea a destra', justifyfull_desc : 'Giustifica', bullist_desc : 'Elenco puntato', numlist_desc : 'Elenco numerato', outdent_desc : 'Riduci rientro', indent_desc : 'Aumenta rientro', undo_desc : 'Annulla (Ctrl+Z)', redo_desc : 'Ripeti (Ctrl+Y)', link_desc : 'Inserisci o modifica link', unlink_desc : 'Elimina link', image_desc : 'Inserisci o modifica immagine', cleanup_desc : 'Pulisci il codice HTML', focus_alert : 'Fare clic su un\' istanza dell\'editor prima di eseguire questo comando', edit_confirm : 'Vuoi usare l\'editor visuale in quest\'area di testo?', insert_link_title : 'Inserisci o modifica link', insert : 'Inserisci', update : 'Modifica', cancel : 'Annulla', insert_link_url : 'URL del collegamento', insert_link_target : 'Destinazione', insert_link_target_same : 'Apri il link nella stessa finestra', insert_link_target_blank : 'Apri il link in una nuova finestra', insert_image_title : 'Inserisci o modifica immagine', insert_image_src : 'URL dell\'immagine', insert_image_alt : 'Descrizione', help_desc : 'Aiuto', bold_img : "bold.gif", italic_img : "italic.gif", underline_img : "underline.gif", clipboard_msg : 'Le operazioni di taglia, copia e incolla non sono disponibili in Firefox. Vuoi ricevere ulteriori informazioni al riguardo?', popup_blocked : 'Un blocco popup sta impedendo l\'utilizzo di alcune funzionalit&agrave;. Dovresti disabilitare il blocco per questo sito.', insert_image_delta_width : 50, insert_link_delta_width : 75 });
pzingg/saugus_elgg
_tinymce/jscripts/tiny_mce/langs/it.js
JavaScript
gpl-2.0
1,801
/* Copyright 2015 Roychoudhury, Abhishek */ package org.abhishek.fileanalytics.lifecycle; public interface Destroyable { void destroy(); boolean destroyed(); }
aroychoudhury/fileanalytics
src/main/java/org/abhishek/fileanalytics/lifecycle/Destroyable.java
Java
gpl-2.0
165
(function ($) { Drupal.viewsSlideshow = Drupal.viewsSlideshow || {}; /** * Views Slideshow Controls */ Drupal.viewsSlideshowControls = Drupal.viewsSlideshowControls || {}; /** * Implement the play hook for controls. */ Drupal.viewsSlideshowControls.play = function (options) { // Route the control call to the correct control type. // Need to use try catch so we don't have to check to make sure every part // of the object is defined. try { if (typeof Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type].play == 'function') { Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type].play(options); } } catch(err) { // Don't need to do anything on error. } try { if (typeof Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type].play == 'function') { Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type].play(options); } } catch(err) { // Don't need to do anything on error. } }; /** * Implement the pause hook for controls. */ Drupal.viewsSlideshowControls.pause = function (options) { // Route the control call to the correct control type. // Need to use try catch so we don't have to check to make sure every part // of the object is defined. try { if (typeof Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type].pause == 'function') { Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type].pause(options); } } catch(err) { // Don't need to do anything on error. } try { if (typeof Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type].pause == 'function') { Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type].pause(options); } } catch(err) { // Don't need to do anything on error. } }; /** * Views Slideshow Text Controls */ // Add views slieshow api calls for views slideshow text controls. Drupal.behaviors.viewsSlideshowControlsText = { attach: function (context) { // Process previous link $('.views_slideshow_controls_text_previous:not(.views-slideshow-controls-text-previous-processed)', context).addClass('views-slideshow-controls-text-previous-processed').each(function() { var uniqueID = $(this).attr('id').replace('views_slideshow_controls_text_previous_', ''); $(this).click(function() { Drupal.viewsSlideshow.action({ "action": 'previousSlide', "slideshowID": uniqueID }); return false; }); }); // Process next link $('.views_slideshow_controls_text_next:not(.views-slideshow-controls-text-next-processed)', context).addClass('views-slideshow-controls-text-next-processed').each(function() { var uniqueID = $(this).attr('id').replace('views_slideshow_controls_text_next_', ''); $(this).click(function() { Drupal.viewsSlideshow.action({ "action": 'nextSlide', "slideshowID": uniqueID }); return false; }); }); // Process pause link $('.views_slideshow_controls_text_pause:not(.views-slideshow-controls-text-pause-processed)', context).addClass('views-slideshow-controls-text-pause-processed').each(function() { var uniqueID = $(this).attr('id').replace('views_slideshow_controls_text_pause_', ''); $(this).click(function() { if (Drupal.settings.viewsSlideshow[uniqueID].paused) { Drupal.viewsSlideshow.action({ "action": 'play', "slideshowID": uniqueID, "force": true }); } else { Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": uniqueID, "force": true }); } return false; }); }); } }; Drupal.viewsSlideshowControlsText = Drupal.viewsSlideshowControlsText || {}; /** * Implement the pause hook for text controls. */ Drupal.viewsSlideshowControlsText.pause = function (options) { var pauseText = Drupal.theme.prototype['viewsSlideshowControlsPause'] ? Drupal.theme('viewsSlideshowControlsPause') : ''; $('#views_slideshow_controls_text_pause_' + options.slideshowID + ' a').text(pauseText); }; /** * Implement the play hook for text controls. */ Drupal.viewsSlideshowControlsText.play = function (options) { var playText = Drupal.theme.prototype['viewsSlideshowControlsPlay'] ? Drupal.theme('viewsSlideshowControlsPlay') : ''; $('#views_slideshow_controls_text_pause_' + options.slideshowID + ' a').text(playText); }; // Theme the resume control. Drupal.theme.prototype.viewsSlideshowControlsPause = function () { return Drupal.t('Resume'); }; // Theme the pause control. Drupal.theme.prototype.viewsSlideshowControlsPlay = function () { return Drupal.t('Pause'); }; /** * Views Slideshow Pager */ Drupal.viewsSlideshowPager = Drupal.viewsSlideshowPager || {}; /** * Implement the transitionBegin hook for pagers. */ Drupal.viewsSlideshowPager.transitionBegin = function (options) { // Route the pager call to the correct pager type. // Need to use try catch so we don't have to check to make sure every part // of the object is defined. try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].transitionBegin == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].transitionBegin(options); } } catch(err) { // Don't need to do anything on error. } try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].transitionBegin == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].transitionBegin(options); } } catch(err) { // Don't need to do anything on error. } }; /** * Implement the goToSlide hook for pagers. */ Drupal.viewsSlideshowPager.goToSlide = function (options) { // Route the pager call to the correct pager type. // Need to use try catch so we don't have to check to make sure every part // of the object is defined. try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].goToSlide == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].goToSlide(options); } } catch(err) { // Don't need to do anything on error. } try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].goToSlide == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].goToSlide(options); } } catch(err) { // Don't need to do anything on error. } }; /** * Implement the previousSlide hook for pagers. */ Drupal.viewsSlideshowPager.previousSlide = function (options) { // Route the pager call to the correct pager type. // Need to use try catch so we don't have to check to make sure every part // of the object is defined. try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].previousSlide == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].previousSlide(options); } } catch(err) { // Don't need to do anything on error. } try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].previousSlide == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].previousSlide(options); } } catch(err) { // Don't need to do anything on error. } }; /** * Implement the nextSlide hook for pagers. */ Drupal.viewsSlideshowPager.nextSlide = function (options) { // Route the pager call to the correct pager type. // Need to use try catch so we don't have to check to make sure every part // of the object is defined. try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].nextSlide == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].nextSlide(options); } } catch(err) { // Don't need to do anything on error. } try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].nextSlide == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].nextSlide(options); } } catch(err) { // Don't need to do anything on error. } }; /** * Views Slideshow Pager Fields */ // Add views slieshow api calls for views slideshow pager fields. Drupal.behaviors.viewsSlideshowPagerFields = { attach: function (context) { // Process pause on hover. $('.views_slideshow_pager_field:not(.views-slideshow-pager-field-processed)', context).addClass('views-slideshow-pager-field-processed').each(function() { // Parse out the location and unique id from the full id. var pagerInfo = $(this).attr('id').split('_'); var location = pagerInfo[2]; pagerInfo.splice(0, 3); var uniqueID = pagerInfo.join('_'); // Add the activate and pause on pager hover event to each pager item. if (Drupal.settings.viewsSlideshowPagerFields[uniqueID][location].activatePauseOnHover) { $(this).children().each(function(index, pagerItem) { var mouseIn = function() { Drupal.viewsSlideshow.action({ "action": 'goToSlide', "slideshowID": uniqueID, "slideNum": index }); Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": uniqueID }); } var mouseOut = function() { Drupal.viewsSlideshow.action({ "action": 'play', "slideshowID": uniqueID }); } if (jQuery.fn.hoverIntent) { $(pagerItem).hoverIntent(mouseIn, mouseOut); } else { $(pagerItem).hover(mouseIn, mouseOut); } }); } else { $(this).children().each(function(index, pagerItem) { $(pagerItem).click(function() { Drupal.viewsSlideshow.action({ "action": 'goToSlide', "slideshowID": uniqueID, "slideNum": index }); }); }); } }); } }; Drupal.viewsSlideshowPagerFields = Drupal.viewsSlideshowPagerFields || {}; /** * Implement the transitionBegin hook for pager fields pager. */ Drupal.viewsSlideshowPagerFields.transitionBegin = function (options) { for (pagerLocation in Drupal.settings.viewsSlideshowPager[options.slideshowID]) { // Remove active class from pagers $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').removeClass('active'); // Add active class to active pager. $('#views_slideshow_pager_field_item_'+ pagerLocation + '_' + options.slideshowID + '_' + options.slideNum).addClass('active'); } }; /** * Implement the goToSlide hook for pager fields pager. */ Drupal.viewsSlideshowPagerFields.goToSlide = function (options) { for (pagerLocation in Drupal.settings.viewsSlideshowPager[options.slideshowID]) { // Remove active class from pagers $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').removeClass('active'); // Add active class to active pager. $('#views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_' + options.slideNum).addClass('active'); } }; /** * Implement the previousSlide hook for pager fields pager. */ Drupal.viewsSlideshowPagerFields.previousSlide = function (options) { for (pagerLocation in Drupal.settings.viewsSlideshowPager[options.slideshowID]) { // Get the current active pager. var pagerNum = $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"].active').attr('id').replace('views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_', ''); // If we are on the first pager then activate the last pager. // Otherwise activate the previous pager. if (pagerNum == 0) { pagerNum = $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').length() - 1; } else { pagerNum--; } // Remove active class from pagers $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').removeClass('active'); // Add active class to active pager. $('#views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_' + pagerNum).addClass('active'); } }; /** * Implement the nextSlide hook for pager fields pager. */ Drupal.viewsSlideshowPagerFields.nextSlide = function (options) { for (pagerLocation in Drupal.settings.viewsSlideshowPager[options.slideshowID]) { // Get the current active pager. var pagerNum = $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"].active').attr('id').replace('views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_', ''); var totalPagers = $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').length(); // If we are on the last pager then activate the first pager. // Otherwise activate the next pager. pagerNum++; if (pagerNum == totalPagers) { pagerNum = 0; } // Remove active class from pagers $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').removeClass('active'); // Add active class to active pager. $('#views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_' + slideNum).addClass('active'); } }; /** * Views Slideshow Slide Counter */ Drupal.viewsSlideshowSlideCounter = Drupal.viewsSlideshowSlideCounter || {}; /** * Implement the transitionBegin for the slide counter. */ Drupal.viewsSlideshowSlideCounter.transitionBegin = function (options) { $('#views_slideshow_slide_counter_' + options.slideshowID + ' .num').text(options.slideNum + 1); }; /** * This is used as a router to process actions for the slideshow. */ Drupal.viewsSlideshow.action = function (options) { // Set default values for our return status. var status = { 'value': true, 'text': '' } // If an action isn't specified return false. if (typeof options.action == 'undefined' || options.action == '') { status.value = false; status.text = Drupal.t('There was no action specified.'); return error; } // If we are using pause or play switch paused state accordingly. if (options.action == 'pause') { Drupal.settings.viewsSlideshow[options.slideshowID].paused = 1; // If the calling method is forcing a pause then mark it as such. if (options.force) { Drupal.settings.viewsSlideshow[options.slideshowID].pausedForce = 1; } } else if (options.action == 'play') { // If the slideshow isn't forced pause or we are forcing a play then play // the slideshow. // Otherwise return telling the calling method that it was forced paused. if (!Drupal.settings.viewsSlideshow[options.slideshowID].pausedForce || options.force) { Drupal.settings.viewsSlideshow[options.slideshowID].paused = 0; Drupal.settings.viewsSlideshow[options.slideshowID].pausedForce = 0; } else { status.value = false; status.text += ' ' + Drupal.t('This slideshow is forced paused.'); return status; } } // We use a switch statement here mainly just to limit the type of actions // that are available. switch (options.action) { case "goToSlide": case "transitionBegin": case "transitionEnd": // The three methods above require a slide number. Checking if it is // defined and it is a number that is an integer. if (typeof options.slideNum == 'undefined' || typeof options.slideNum !== 'number' || parseInt(options.slideNum) != (options.slideNum - 0)) { status.value = false; status.text = Drupal.t('An invalid integer was specified for slideNum.'); } case "pause": case "play": case "nextSlide": case "previousSlide": // Grab our list of methods. var methods = Drupal.settings.viewsSlideshow[options.slideshowID]['methods']; // if the calling method specified methods that shouldn't be called then // exclude calling them. var excludeMethodsObj = {}; if (typeof options.excludeMethods !== 'undefined') { // We need to turn the excludeMethods array into an object so we can use the in // function. for (var i=0; i < excludeMethods.length; i++) { excludeMethodsObj[excludeMethods[i]] = ''; } } // Call every registered method and don't call excluded ones. for (i = 0; i < methods[options.action].length; i++) { if (Drupal[methods[options.action][i]] != undefined && typeof Drupal[methods[options.action][i]][options.action] == 'function' && !(methods[options.action][i] in excludeMethodsObj)) { Drupal[methods[options.action][i]][options.action](options); } } break; // If it gets here it's because it's an invalid action. default: status.value = false; status.text = Drupal.t('An invalid action "!action" was specified.', { "!action": options.action }); } return status; }; })(jQuery); ; (function($){ Drupal.behaviors.contextReactionBlock = {attach: function(context) { $('form.context-editor:not(.context-block-processed)') .addClass('context-block-processed') .each(function() { var id = $(this).attr('id'); Drupal.contextBlockEditor = Drupal.contextBlockEditor || {}; $(this).bind('init.pageEditor', function(event) { Drupal.contextBlockEditor[id] = new DrupalContextBlockEditor($(this)); }); $(this).bind('start.pageEditor', function(event, context) { // Fallback to first context if param is empty. if (!context) { context = $(this).data('defaultContext'); } Drupal.contextBlockEditor[id].editStart($(this), context); }); $(this).bind('end.pageEditor', function(event) { Drupal.contextBlockEditor[id].editFinish(); }); }); // // Admin Form ======================================================= // // ContextBlockForm: Init. $('#context-blockform:not(.processed)').each(function() { $(this).addClass('processed'); Drupal.contextBlockForm = new DrupalContextBlockForm($(this)); Drupal.contextBlockForm.setState(); }); // ContextBlockForm: Attach block removal handlers. // Lives in behaviors as it may be required for attachment to new DOM elements. $('#context-blockform a.remove:not(.processed)').each(function() { $(this).addClass('processed'); $(this).click(function() { $(this).parents('tr').eq(0).remove(); Drupal.contextBlockForm.setState(); return false; }); }); }}; /** * Context block form. Default form for editing context block reactions. */ DrupalContextBlockForm = function(blockForm) { this.state = {}; this.setState = function() { $('table.context-blockform-region', blockForm).each(function() { var region = $(this).attr('id').split('context-blockform-region-')[1]; var blocks = []; $('tr', $(this)).each(function() { var bid = $(this).attr('id'); var weight = $(this).find('select').val(); blocks.push({'bid' : bid, 'weight' : weight}); }); Drupal.contextBlockForm.state[region] = blocks; }); // Serialize here and set form element value. $('form input.context-blockform-state').val(JSON.stringify(this.state)); // Hide enabled blocks from selector that are used $('table.context-blockform-region tr').each(function() { var bid = $(this).attr('id'); $('div.context-blockform-selector input[value='+bid+']').parents('div.form-item').eq(0).hide(); }); // Show blocks in selector that are unused $('div.context-blockform-selector input').each(function() { var bid = $(this).val(); if ($('table.context-blockform-region tr#'+bid).size() === 0) { $(this).parents('div.form-item').eq(0).show(); } }); }; // make sure we update the state right before submits, this takes care of an // apparent race condition between saving the state and the weights getting set // by tabledrag $('#ctools-export-ui-edit-item-form').submit(function() { Drupal.contextBlockForm.setState(); }); // Tabledrag // Add additional handlers to update our blocks. $.each(Drupal.settings.tableDrag, function(base) { var table = $('#' + base + ':not(.processed)', blockForm); if (table && table.is('.context-blockform-region')) { table.addClass('processed'); table.bind('mouseup', function(event) { Drupal.contextBlockForm.setState(); return; }); } }); // Add blocks to a region $('td.blocks a', blockForm).each(function() { $(this).click(function() { var region = $(this).attr('href').split('#')[1]; var selected = $("div.context-blockform-selector input:checked"); if (selected.size() > 0) { selected.each(function() { // create new block markup var block = document.createElement('tr'); var text = $(this).parents('div.form-item').eq(0).hide().children('label').text(); var select = '<div class="form-item form-type-select"><select class="tabledrag-hide form-select">'; var i; for (i = -10; i < 10; ++i) { select += '<option>' + i + '</option>'; } select += '</select></div>'; $(block).attr('id', $(this).attr('value')).addClass('draggable'); $(block).html("<td>"+ text + "</td><td>" + select + "</td><td><a href='' class='remove'>X</a></td>"); // add block item to region var base = "context-blockform-region-"+ region; Drupal.tableDrag[base].makeDraggable(block); $('table#'+base).append(block); if ($.cookie('Drupal.tableDrag.showWeight') == 1) { $('table#'+base).find('.tabledrag-hide').css('display', ''); $('table#'+base).find('.tabledrag-handle').css('display', 'none'); } else { $('table#'+base).find('.tabledrag-hide').css('display', 'none'); $('table#'+base).find('.tabledrag-handle').css('display', ''); } Drupal.attachBehaviors($('table#'+base)); Drupal.contextBlockForm.setState(); $(this).removeAttr('checked'); }); } return false; }); }); }; /** * Context block editor. AHAH editor for live block reaction editing. */ DrupalContextBlockEditor = function(editor) { this.editor = editor; this.state = {}; this.blocks = {}; this.regions = {}; // Category selector handler. // Also set to "Choose a category" option as browsers can retain // form values from previous page load. $('select.context-block-browser-categories', editor).change(function() { var category = $(this).val(); var params = { containment: 'document', revert: true, dropOnEmpty: true, placeholder: 'draggable-placeholder', forcePlaceholderSize: true, helper: 'clone', appendTo: 'body', connectWith: ($.ui.version === '1.6') ? ['.ui-sortable'] : '.ui-sortable' }; $('div.category', editor).hide().sortable('destroy'); $('div.category-'+category, editor).show().sortable(params); }); $('select.context-block-browser-categories', editor).val(0).change(); return this; }; DrupalContextBlockEditor.prototype.initBlocks = function(blocks) { var self = this; this.blocks = blocks; blocks.each(function() { if($(this).hasClass('context-block-empty')) { $(this).removeClass('context-block-hidden'); } $(this).addClass('draggable'); $(this).prepend($('<a class="context-block-handle"></a>')); $(this).prepend($('<a class="context-block-remove"></a>').click(function() { $(this).parent ('.block').eq(0).fadeOut('medium', function() { $(this).remove(); self.updateBlocks(); }); return false; })); }); }; DrupalContextBlockEditor.prototype.initRegions = function(regions) { this.regions = regions; }; /** * Update UI to match the current block states. */ DrupalContextBlockEditor.prototype.updateBlocks = function() { var browser = $('div.context-block-browser'); // For all enabled blocks, mark corresponding addables as having been added. $('.block, .admin-block').each(function() { var bid = $(this).attr('id').split('block-')[1]; // Ugh. $('#context-block-addable-'+bid, browser).draggable('disable').addClass('context-block-added').removeClass('context-block-addable'); }); // For all hidden addables with no corresponding blocks, mark as addable. $('.context-block-item', browser).each(function() { var bid = $(this).attr('id').split('context-block-addable-')[1]; if ($('#block-'+bid).size() === 0) { $(this).draggable('enable').removeClass('context-block-added').addClass('context-block-addable'); } }); // Mark empty regions. $(this.regions).each(function() { if ($('.block:has(a.context-block)', this).size() > 0) { $(this).removeClass('context-block-region-empty'); } else { $(this).addClass('context-block-region-empty'); } }); }; /** * Live update a region. */ DrupalContextBlockEditor.prototype.updateRegion = function(event, ui, region, op) { switch (op) { case 'over': $(region).removeClass('context-block-region-empty'); break; case 'out': if ( // jQuery UI 1.8 $('.draggable-placeholder', region).size() === 1 && $('.block:has(a.context-block)', region).size() == 0 // jQuery UI 1.6 // $('div.draggable-placeholder', region).size() === 0 && // $('div.block:has(a.context-block)', region).size() == 1 && // $('div.block:has(a.context-block)', region).attr('id') == ui.item.attr('id') ) { $(region).addClass('context-block-region-empty'); } break; } }; /** * Remove script elements while dragging & dropping. */ DrupalContextBlockEditor.prototype.scriptFix = function(event, ui, editor, context) { if ($('script', ui.item)) { var placeholder = $(Drupal.settings.contextBlockEditor.scriptPlaceholder); var label = $('div.handle label', ui.item).text(); placeholder.children('strong').html(label); $('script', ui.item).parent().empty().append(placeholder); } }; /** * Add a block to a region through an AHAH load of the block contents. */ DrupalContextBlockEditor.prototype.addBlock = function(event, ui, editor, context) { var self = this; if (ui.item.is('.context-block-addable')) { var bid = ui.item.attr('id').split('context-block-addable-')[1]; // Construct query params for our AJAX block request. var params = Drupal.settings.contextBlockEditor.params; params.context_block = bid + ',' + context; // Replace item with loading block. var blockLoading = $('<div class="context-block-item context-block-loading"><span class="icon"></span></div>'); ui.item.addClass('context-block-added'); ui.item.after(blockLoading); ui.sender.append(ui.item); $.getJSON(Drupal.settings.contextBlockEditor.path, params, function(data) { if (data.status) { var newBlock = $(data.block); if ($('script', newBlock)) { $('script', newBlock).remove(); } blockLoading.fadeOut(function() { $(this).replaceWith(newBlock); self.initBlocks(newBlock); self.updateBlocks(); Drupal.attachBehaviors(); }); } else { blockLoading.fadeOut(function() { $(this).remove(); }); } }); } else if (ui.item.is(':has(a.context-block)')) { self.updateBlocks(); } }; /** * Update form hidden field with JSON representation of current block visibility states. */ DrupalContextBlockEditor.prototype.setState = function() { var self = this; $(this.regions).each(function() { var region = $('a.context-block-region', this).attr('id').split('context-block-region-')[1]; var blocks = []; $('a.context-block', $(this)).each(function() { if ($(this).attr('class').indexOf('edit-') != -1) { var bid = $(this).attr('id').split('context-block-')[1]; var context = $(this).attr('class').split('edit-')[1].split(' ')[0]; context = context ? context : 0; var block = {'bid': bid, 'context': context}; blocks.push(block); } }); self.state[region] = blocks; }); // Serialize here and set form element value. $('input.context-block-editor-state', this.editor).val(JSON.stringify(this.state)); }; /** * Disable text selection. */ DrupalContextBlockEditor.prototype.disableTextSelect = function() { if ($.browser.safari) { $('.block:has(a.context-block):not(:has(input,textarea))').css('WebkitUserSelect','none'); } else if ($.browser.mozilla) { $('.block:has(a.context-block):not(:has(input,textarea))').css('MozUserSelect','none'); } else if ($.browser.msie) { $('.block:has(a.context-block):not(:has(input,textarea))').bind('selectstart.contextBlockEditor', function() { return false; }); } else { $(this).bind('mousedown.contextBlockEditor', function() { return false; }); } }; /** * Enable text selection. */ DrupalContextBlockEditor.prototype.enableTextSelect = function() { if ($.browser.safari) { $('*').css('WebkitUserSelect',''); } else if ($.browser.mozilla) { $('*').css('MozUserSelect',''); } else if ($.browser.msie) { $('*').unbind('selectstart.contextBlockEditor'); } else { $(this).unbind('mousedown.contextBlockEditor'); } }; /** * Start editing. Attach handlers, begin draggable/sortables. */ DrupalContextBlockEditor.prototype.editStart = function(editor, context) { var self = this; // This is redundant to the start handler found in context_ui.js. // However it's necessary that we trigger this class addition before // we call .sortable() as the empty regions need to be visible. $(document.body).addClass('context-editing'); this.editor.addClass('context-editing'); this.disableTextSelect(); this.initBlocks($('.block:has(a.context-block.edit-'+context+')')); this.initRegions($('a.context-block-region').parent()); this.updateBlocks(); // First pass, enable sortables on all regions. $(this.regions).each(function() { var region = $(this); var params = { containment: 'document', revert: true, dropOnEmpty: true, placeholder: 'draggable-placeholder', forcePlaceholderSize: true, items: '> .block:has(a.context-block.editable)', handle: 'a.context-block-handle', start: function(event, ui) { self.scriptFix(event, ui, editor, context); }, stop: function(event, ui) { self.addBlock(event, ui, editor, context); }, receive: function(event, ui) { self.addBlock(event, ui, editor, context); }, over: function(event, ui) { self.updateRegion(event, ui, region, 'over'); }, out: function(event, ui) { self.updateRegion(event, ui, region, 'out'); } }; region.sortable(params); }); // Second pass, hook up all regions via connectWith to each other. $(this.regions).each(function() { $(this).sortable('option', 'connectWith', ['.ui-sortable']); }); // Terrible, terrible workaround for parentoffset issue in Safari. // The proper fix for this issue has been committed to jQuery UI, but was // not included in the 1.6 release. Therefore, we do a browser agent hack // to ensure that Safari users are covered by the offset fix found here: // http://dev.jqueryui.com/changeset/2073. if ($.ui.version === '1.6' && $.browser.safari) { $.browser.mozilla = true; } }; /** * Finish editing. Remove handlers. */ DrupalContextBlockEditor.prototype.editFinish = function() { this.editor.removeClass('context-editing'); this.enableTextSelect(); // Remove UI elements. $(this.blocks).each(function() { $('a.context-block-handle, a.context-block-remove', this).remove(); if($(this).hasClass('context-block-empty')) { $(this).addClass('context-block-hidden'); } $(this).removeClass('draggable'); }); this.regions.sortable('destroy'); this.setState(); // Unhack the user agent. if ($.ui.version === '1.6' && $.browser.safari) { $.browser.mozilla = false; } }; })(jQuery); ; (function ($) { Drupal.behaviors.textarea = { attach: function (context, settings) { $('.form-textarea-wrapper.resizable', context).once('textarea', function () { var staticOffset = null; var textarea = $(this).addClass('resizable-textarea').find('textarea'); var grippie = $('<div class="grippie"></div>').mousedown(startDrag); grippie.insertAfter(textarea); function startDrag(e) { staticOffset = textarea.height() - e.pageY; textarea.css('opacity', 0.25); $(document).mousemove(performDrag).mouseup(endDrag); return false; } function performDrag(e) { textarea.height(Math.max(32, staticOffset + e.pageY) + 'px'); return false; } function endDrag(e) { $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag); textarea.css('opacity', 1); } }); } }; })(jQuery); ; /** * JavaScript behaviors for the front-end display of webforms. */ (function ($) { Drupal.behaviors.webform = Drupal.behaviors.webform || {}; Drupal.behaviors.webform.attach = function(context) { // Calendar datepicker behavior. Drupal.webform.datepicker(context); }; Drupal.webform = Drupal.webform || {}; Drupal.webform.datepicker = function(context) { $('div.webform-datepicker').each(function() { var $webformDatepicker = $(this); var $calendar = $webformDatepicker.find('input.webform-calendar'); var startDate = $calendar[0].className.replace(/.*webform-calendar-start-(\d{4}-\d{2}-\d{2}).*/, '$1').split('-'); var endDate = $calendar[0].className.replace(/.*webform-calendar-end-(\d{4}-\d{2}-\d{2}).*/, '$1').split('-'); var firstDay = $calendar[0].className.replace(/.*webform-calendar-day-(\d).*/, '$1'); // Convert date strings into actual Date objects. startDate = new Date(startDate[0], startDate[1] - 1, startDate[2]); endDate = new Date(endDate[0], endDate[1] - 1, endDate[2]); // Ensure that start comes before end for datepicker. if (startDate > endDate) { var laterDate = startDate; startDate = endDate; endDate = laterDate; } var startYear = startDate.getFullYear(); var endYear = endDate.getFullYear(); // Set up the jQuery datepicker element. $calendar.datepicker({ dateFormat: 'yy-mm-dd', yearRange: startYear + ':' + endYear, firstDay: parseInt(firstDay), minDate: startDate, maxDate: endDate, onSelect: function(dateText, inst) { var date = dateText.split('-'); $webformDatepicker.find('select.year, input.year').val(+date[0]); $webformDatepicker.find('select.month').val(+date[1]); $webformDatepicker.find('select.day').val(+date[2]); }, beforeShow: function(input, inst) { // Get the select list values. var year = $webformDatepicker.find('select.year, input.year').val(); var month = $webformDatepicker.find('select.month').val(); var day = $webformDatepicker.find('select.day').val(); // If empty, default to the current year/month/day in the popup. var today = new Date(); year = year ? year : today.getFullYear(); month = month ? month : today.getMonth() + 1; day = day ? day : today.getDate(); // Make sure that the default year fits in the available options. year = (year < startYear || year > endYear) ? startYear : year; // jQuery UI Datepicker will read the input field and base its date off // of that, even though in our case the input field is a button. $(input).val(year + '-' + month + '-' + day); } }); // Prevent the calendar button from submitting the form. $calendar.click(function(event) { $(this).focus(); event.preventDefault(); }); }); } })(jQuery); ; (function ($) { /** * Automatically display the guidelines of the selected text format. */ Drupal.behaviors.filterGuidelines = { attach: function (context) { $('.filter-guidelines', context).once('filter-guidelines') .find(':header').hide() .closest('.filter-wrapper').find('select.filter-list') .bind('change', function () { $(this).closest('.filter-wrapper') .find('.filter-guidelines-item').hide() .siblings('.filter-guidelines-' + this.value).show(); }) .change(); } }; })(jQuery); ; (function ($) { /** * Toggle the visibility of a fieldset using smooth animations. */ Drupal.toggleFieldset = function (fieldset) { var $fieldset = $(fieldset); if ($fieldset.is('.collapsed')) { var $content = $('> .fieldset-wrapper', fieldset).hide(); $fieldset .removeClass('collapsed') .trigger({ type: 'collapsed', value: false }) .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide')); $content.slideDown({ duration: 'fast', easing: 'linear', complete: function () { Drupal.collapseScrollIntoView(fieldset); fieldset.animating = false; }, step: function () { // Scroll the fieldset into view. Drupal.collapseScrollIntoView(fieldset); } }); } else { $fieldset.trigger({ type: 'collapsed', value: true }); $('> .fieldset-wrapper', fieldset).slideUp('fast', function () { $fieldset .addClass('collapsed') .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Show')); fieldset.animating = false; }); } }; /** * Scroll a given fieldset into view as much as possible. */ Drupal.collapseScrollIntoView = function (node) { var h = document.documentElement.clientHeight || document.body.clientHeight || 0; var offset = document.documentElement.scrollTop || document.body.scrollTop || 0; var posY = $(node).offset().top; var fudge = 55; if (posY + node.offsetHeight + fudge > h + offset) { if (node.offsetHeight > h) { window.scrollTo(0, posY); } else { window.scrollTo(0, posY + node.offsetHeight - h + fudge); } } }; Drupal.behaviors.collapse = { attach: function (context, settings) { $('fieldset.collapsible', context).once('collapse', function () { var $fieldset = $(this); // Expand fieldset if there are errors inside, or if it contains an // element that is targeted by the uri fragment identifier. var anchor = location.hash && location.hash != '#' ? ', ' + location.hash : ''; if ($('.error' + anchor, $fieldset).length) { $fieldset.removeClass('collapsed'); } var summary = $('<span class="summary"></span>'); $fieldset. bind('summaryUpdated', function () { var text = $.trim($fieldset.drupalGetSummary()); summary.html(text ? ' (' + text + ')' : ''); }) .trigger('summaryUpdated'); // Turn the legend into a clickable link, but retain span.fieldset-legend // for CSS positioning. var $legend = $('> legend .fieldset-legend', this); $('<span class="fieldset-legend-prefix element-invisible"></span>') .append($fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide')) .prependTo($legend) .after(' '); // .wrapInner() does not retain bound events. var $link = $('<a class="fieldset-title" href="#"></a>') .prepend($legend.contents()) .appendTo($legend) .click(function () { var fieldset = $fieldset.get(0); // Don't animate multiple times. if (!fieldset.animating) { fieldset.animating = true; Drupal.toggleFieldset(fieldset); } return false; }); $legend.append(summary); }); } }; })(jQuery); ; (function ($) { /** * Attaches sticky table headers. */ Drupal.behaviors.tableHeader = { attach: function (context, settings) { if (!$.support.positionFixed) { return; } $('table.sticky-enabled', context).once('tableheader', function () { $(this).data("drupal-tableheader", new Drupal.tableHeader(this)); }); } }; /** * Constructor for the tableHeader object. Provides sticky table headers. * * @param table * DOM object for the table to add a sticky header to. */ Drupal.tableHeader = function (table) { var self = this; this.originalTable = $(table); this.originalHeader = $(table).children('thead'); this.originalHeaderCells = this.originalHeader.find('> tr > th'); this.displayWeight = null; // React to columns change to avoid making checks in the scroll callback. this.originalTable.bind('columnschange', function (e, display) { // This will force header size to be calculated on scroll. self.widthCalculated = (self.displayWeight !== null && self.displayWeight === display); self.displayWeight = display; }); // Clone the table header so it inherits original jQuery properties. Hide // the table to avoid a flash of the header clone upon page load. this.stickyTable = $('<table class="sticky-header"/>') .insertBefore(this.originalTable) .css({ position: 'fixed', top: '0px' }); this.stickyHeader = this.originalHeader.clone(true) .hide() .appendTo(this.stickyTable); this.stickyHeaderCells = this.stickyHeader.find('> tr > th'); this.originalTable.addClass('sticky-table'); $(window) .bind('scroll.drupal-tableheader', $.proxy(this, 'eventhandlerRecalculateStickyHeader')) .bind('resize.drupal-tableheader', { calculateWidth: true }, $.proxy(this, 'eventhandlerRecalculateStickyHeader')) // Make sure the anchor being scrolled into view is not hidden beneath the // sticky table header. Adjust the scrollTop if it does. .bind('drupalDisplaceAnchor.drupal-tableheader', function () { window.scrollBy(0, -self.stickyTable.outerHeight()); }) // Make sure the element being focused is not hidden beneath the sticky // table header. Adjust the scrollTop if it does. .bind('drupalDisplaceFocus.drupal-tableheader', function (event) { if (self.stickyVisible && event.clientY < (self.stickyOffsetTop + self.stickyTable.outerHeight()) && event.$target.closest('sticky-header').length === 0) { window.scrollBy(0, -self.stickyTable.outerHeight()); } }) .triggerHandler('resize.drupal-tableheader'); // We hid the header to avoid it showing up erroneously on page load; // we need to unhide it now so that it will show up when expected. this.stickyHeader.show(); }; /** * Event handler: recalculates position of the sticky table header. * * @param event * Event being triggered. */ Drupal.tableHeader.prototype.eventhandlerRecalculateStickyHeader = function (event) { var self = this; var calculateWidth = event.data && event.data.calculateWidth; // Reset top position of sticky table headers to the current top offset. this.stickyOffsetTop = Drupal.settings.tableHeaderOffset ? eval(Drupal.settings.tableHeaderOffset + '()') : 0; this.stickyTable.css('top', this.stickyOffsetTop + 'px'); // Save positioning data. var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight; if (calculateWidth || this.viewHeight !== viewHeight) { this.viewHeight = viewHeight; this.vPosition = this.originalTable.offset().top - 4 - this.stickyOffsetTop; this.hPosition = this.originalTable.offset().left; this.vLength = this.originalTable[0].clientHeight - 100; calculateWidth = true; } // Track horizontal positioning relative to the viewport and set visibility. var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft; var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - this.vPosition; this.stickyVisible = vOffset > 0 && vOffset < this.vLength; this.stickyTable.css({ left: (-hScroll + this.hPosition) + 'px', visibility: this.stickyVisible ? 'visible' : 'hidden' }); // Only perform expensive calculations if the sticky header is actually // visible or when forced. if (this.stickyVisible && (calculateWidth || !this.widthCalculated)) { this.widthCalculated = true; var $that = null; var $stickyCell = null; var display = null; var cellWidth = null; // Resize header and its cell widths. // Only apply width to visible table cells. This prevents the header from // displaying incorrectly when the sticky header is no longer visible. for (var i = 0, il = this.originalHeaderCells.length; i < il; i += 1) { $that = $(this.originalHeaderCells[i]); $stickyCell = this.stickyHeaderCells.eq($that.index()); display = $that.css('display'); if (display !== 'none') { cellWidth = $that.css('width'); // Exception for IE7. if (cellWidth === 'auto') { cellWidth = $that[0].clientWidth + 'px'; } $stickyCell.css({'width': cellWidth, 'display': display}); } else { $stickyCell.css('display', 'none'); } } this.stickyTable.css('width', this.originalTable.css('width')); } }; })(jQuery); ; (function ($) { Drupal.behaviors.tokenTree = { attach: function (context, settings) { $('table.token-tree', context).once('token-tree', function () { $(this).treeTable(); }); } }; Drupal.behaviors.tokenInsert = { attach: function (context, settings) { // Keep track of which textfield was last selected/focused. $('textarea, input[type="text"]', context).focus(function() { Drupal.settings.tokenFocusedField = this; }); $('.token-click-insert .token-key', context).once('token-click-insert', function() { var newThis = $('<a href="javascript:void(0);" title="' + Drupal.t('Insert this token into your form') + '">' + $(this).html() + '</a>').click(function(){ if (typeof Drupal.settings.tokenFocusedField == 'undefined') { alert(Drupal.t('First click a text field to insert your tokens into.')); } else { var myField = Drupal.settings.tokenFocusedField; var myValue = $(this).text(); //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); } else { myField.value += myValue; } $('html,body').animate({scrollTop: $(myField).offset().top}, 500); } return false; }); $(this).html(newThis); }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.pathFieldsetSummaries = { attach: function (context) { $('fieldset.path-form', context).drupalSetSummary(function (context) { var path = $('.form-item-path-alias input').val(); var automatic = $('.form-item-path-pathauto input').attr('checked'); if (automatic) { return Drupal.t('Automatic alias'); } if (path) { return Drupal.t('Alias: @alias', { '@alias': path }); } else { return Drupal.t('No alias'); } }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.menuFieldsetSummaries = { attach: function (context) { $('fieldset.block-form', context).drupalSetSummary(function (context) { if ($('#edit-media-gallery-expose-block-und', context).attr('checked')) { return Drupal.t('Enabled'); } else { return Drupal.t('Not enabled'); } }); } }; Drupal.behaviors.media_gallery_form = {}; Drupal.behaviors.media_gallery_form.attach = function (context, settings) { // Change the "Presentation settings" image to match the radio buttons / checkbox. var inputs = $('.presentation-settings input', context); if (inputs.length) { inputs.bind('change', Drupal.behaviors.media_gallery_form.format_select); Drupal.behaviors.media_gallery_form.format_select(); } }; Drupal.behaviors.media_gallery_form.format_select = function (event) { var radioValue = $('.presentation-settings input:radio:checked').val(); var icon = $('.presentation-settings .setting-icon'); var checkbox = $('.presentation-settings .field-name-media-gallery-lightbox-extras input'); // Depending on the radio button chosen add a class if (radioValue == 'node') { icon.attr('class', 'setting-icon display-page'); // Disable the checkbox checkbox.attr('disabled', true); } else { icon.attr('class', 'setting-icon display-lightbox'); // Turn on the checkbox checkbox.attr('disabled', false); // Add a class if the checkbox is checked if (checkbox.is(':checked')) { icon.attr('class', 'setting-icon display-extras'); } } }; })(jQuery); ;
mikeusry/HolidayInnAthens
hotel_athens_ga/js/js_i0lWZY61n-2X7sezox7DfNdyQ2tsrQFGHT9wlJhktj8.js
JavaScript
gpl-2.0
51,563
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- """ sha1Hash_test.py Unit tests for sha1.py """ from crypto.hash.sha1Hash import SHA1 import unittest import struct assert struct.calcsize('!IIIII') == 20, '5 integers should be 20 bytes' class SHA1_FIPS180_TestCases(unittest.TestCase): """ SHA-1 tests from FIPS180-1 Appendix A, B and C """ def testFIPS180_1_Appendix_A(self): """ APPENDIX A. A SAMPLE MESSAGE AND ITS MESSAGE DIGEST """ hashAlg = SHA1() message = 'abc' message_digest = 0xA9993E36L, 0x4706816AL, 0xBA3E2571L, 0x7850C26CL, 0x9CD0D89DL md_string = _toBString(message_digest) assert( hashAlg(message) == md_string ), 'FIPS180 Appendix A test Failed' def testFIPS180_1_Appendix_B(self): """ APPENDIX B. A SECOND SAMPLE MESSAGE AND ITS MESSAGE DIGEST """ hashAlg = SHA1() message = 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq' message_digest = 0x84983E44L, 0x1C3BD26EL, 0xBAAE4AA1L, 0xF95129E5L, 0xE54670F1L md_string = _toBString(message_digest) assert( hashAlg(message) == md_string ), 'FIPS180 Appendix B test Failed' def testFIPS180_1_Appendix_C(self): """ APPENDIX C. A THIRD SAMPLE MESSAGE AND ITS MESSAGE DIGEST Let the message be the binary-coded form of the ASCII string which consists of 1,000,000 repetitions of "a". """ hashAlg = SHA1() message = 1000000*'a' message_digest = 0x34AA973CL, 0xD4C4DAA4L, 0xF61EEB2BL, 0xDBAD2731L, 0x6534016FL md_string = _toBString(message_digest) assert( hashAlg(message) == md_string ), 'FIPS180 Appendix C test Failed' def _toBlock(binaryString): """ Convert binary string to blocks of 5 words of uint32() """ return [uint32(word) for word in struct.unpack('!IIIII', binaryString)] def _toBString(block): """ Convert block (5 words of 32 bits to binary string """ return ''.join([struct.pack('!I',word) for word in block]) if __name__ == '__main__': # Run the tests from the command line unittest.main()
dknlght/dkodi
src/script.module.cryptopy/lib/crypto/hash/sha1Hash_test.py
Python
gpl-2.0
2,199
<? session_start(); include "../config.php"; include "../includes/database.php"; include "hw_filemgr_class.php"; $path="../upload/0001/94598031"; $std_id=$_GET['account']; echo $_SESSION['std_id']; if($hw_id!="") $_SESSION['hw_id']=$hw_id; else $hw_id=$_SESSION['hw_id']; if($std_id=="")$std_id="s4598000"; $result = $db->Query(" select * from course, hw where course.course_id = hw.course_id and hw.hw_id = '".$hw_id."' "); $row = $db->Fetch_array( $result ); $course_name=$row[course_name]; $hw_name=$row[hw_name]; $_SESSION['path'] = $path; $filemg=new FileMgr($path); if ($_POST['del']) { $filemg->delFiles($_POST['selfile']); } $filemg->getFileList(); $my_array=array(); for($i=0;$i<sizeof($filemg->_filename);$i++) { $filename_a="<span class='style6'><a href='hw_mg_edit.php?filename=".$filemg->_filename[$i]."'>".$filemg->_filename[$i]."</a></span>"; $item="<td><input name='selfile[]' type='checkbox' value='".$filemg->_filename[$i]."'></td>\n"; $item=$item."<td>".$filename_a."</td>\n". "<td align='right'><span class='style6'>".$filemg->_filesize[$i]."</span></td>\n". "<td align='middle'><span class='style6'>".$filemg->_filetime[$i]."</span></td>\n"; array_push($my_array,$item); } $tpl->assign("my_array",$my_array); $tpl->assign("std_id",$std_id); $tpl->assign("course_name",$course_name); $tpl->assign("hw_name",$hw_name); $tpl->display("HW_Mgr/view.htm"); ?>
snowwolf725/Code-Homework-Grading-System
HW_Mgr/view.php
PHP
gpl-2.0
1,434
<?php $output = ''; $links = ''; if ($node->nid) { $children_list = eds_profile_book_children($node->nid); //echo '<pre>'; //var_dump($node); //echo '</pre>'; //exit; if ($prev = book_prev($node->book)) { // Previous page drupal_add_html_head_link(array('rel' => 'prev', 'href' => url($prev['href']))); $links .= l(t('< ') . $prev['title'], $prev['href'], array('attributes' => array('class' => 'page-previous', 'title' => t('Go to previous page')))); } // if ($node->field_parent) { // // Parent page // drupal_add_html_head_link(array('rel' => 'up', 'href' => url('node/'. $node->field_parent['und'][0]['value']))); // $links .= l(t('up'), // 'node/'. $node->field_parent['und'][0]['value'], // array('class' => 'page-up', 'title' => t('Go to parent page'))); // } if ($node->book['plid'] && $parent = book_link_load($node->book['plid'])) { // Parent page drupal_add_html_head_link(array('rel' => 'up', 'href' => url($parent['href']))); $links .= l(t('up'), $parent['href'], array('attributes' => array('class' => 'page-up', 'title' => t('Go to parent page')))); } if ($next = book_next($node->book)) { // Next page drupal_add_html_head_link(array('rel' => 'next', 'href' => url($next['href']))); $links .= l($next['title'] . t(' >'), $next['href'], array('attributes' => array('class' => 'page-next', 'title' => t('Go to next page')))); } if ((isset($children_list) || isset($links)) && (!isset($node->no_links))) { // Add wrapers $output = '<div class="book-navigation">'; if (isset($children_list)) { $output .= '<div class="book-children">'. $children_list .'</div>'; } if (isset($links)) { $output .= '<div class="page-links clearfix">'. $links .'</div>'; } $output .= '</div>'; } } //echo '<pre>'; //var_dump($output); //echo '</pre>'; //exit; echo $output;
Roma48/ekreative_test_task
sites/all/modules/edsuite/eds_profile/templates/eds_profile_book_children.tpl.php
PHP
gpl-2.0
2,079
/* * jQuery.liveFilter * * Copyright (c) 2009 Mike Merritt * * Forked by Lim Chee Aun (cheeaun.com) * */ (function($){ $.fn.liveFilter = function(inputEl, filterEl, options){ var defaults = { filterChildSelector: null, filter: function(el, val){ return $(el).text().toUpperCase().indexOf(val.toUpperCase()) >= 0; }, before: function(){}, after: function(){} }; var options = $.extend(defaults, options); var el = $(this).find(filterEl); if (options.filterChildSelector) el = el.find(options.filterChildSelector); var filter = options.filter; $(inputEl).keyup(function(){ var val = $(this).val(); var contains = el.filter(function(){ return filter(this, val); }); var containsNot = el.not(contains); if (options.filterChildSelector){ contains = contains.parents(filterEl); containsNot = containsNot.parents(filterEl).hide(); } options.before.call(this, contains, containsNot); contains.show(); containsNot.hide(); if (val === '') { contains.show(); containsNot.show(); } options.after.call(this, contains, containsNot); }); } })(jQuery);
unicef/uPortal
sites/all/themes/uportal_backend_theme/scripts/plugins/jquery.liveFilter.js
JavaScript
gpl-2.0
1,210
#!C:\Users\SeanSaito\Dev\aviato\flask\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'kartograph.py==0.6.8','console_scripts','kartograph' __requires__ = 'kartograph.py==0.6.8' import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point('kartograph.py==0.6.8', 'console_scripts', 'kartograph')() )
hrishioa/Aviato
flask/Scripts/kartograph-script.py
Python
gpl-2.0
364
# Copyright 2006 John Duda # This file is part of Infoshopkeeper. # Infoshopkeeper 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 any later version. # Infoshopkeeper 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 Infoshopkeeper; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA from wxPython.wx import * import os import datetime from objects.emprunt import Emprunt from popups.members import AddMemberPanel, ShowMembersPanel class CheckoutPopup(wxDialog): def __init__(self, parent): self.parent=parent wxDialog.__init__(self, parent,-1,"Check out items") self.mastersizer = wxBoxSizer(wxVERTICAL) self.static1 = wxStaticText(self, -1, "Check out to :") self.mastersizer.Add(self.static1) self.notebook = wxNotebook(self, -1, style=wxNB_TOP) self.new_member_panel = AddMemberPanel(parent=self.notebook, main_window=parent, on_successful_add=self.Borrow, cancel=self.Close) self.notebook.AddPage(self.new_member_panel, "New member") self.show_member_panel = ShowMembersPanel(parent=self.notebook, main_window=parent, motherDialog=self, on_select=self.Borrow) self.notebook.AddPage(self.show_member_panel, "Existing member") self.mastersizer.Add(self.notebook) self.SetSizer(self.mastersizer) for i in self.parent.orderbox.items: print i.database_id, "... ", i.id #self.b = wxButton(self, -1, "Checkout", (15, 80)) #EVT_BUTTON(self, self.b.GetId(), self.Checkout) #self.b.SetDefault() self.mastersizer.SetSizeHints(self) def Borrow(self, id): borrower = self.parent.membersList.get(id) print borrower for i in self.parent.orderbox.items: # Check if this work on sqlobject 0.7... I got # lots of problem on 0.6.1, and itemID __isn't__ # defined in emprunt, which is plain weirdness e = Emprunt(borrower = id, itemID=i.database_id) print i.database_id self.parent.orderbox.setBorrowed() self.parent.orderbox.void() self.Close() def OnCancel(self,event): self.EndModal(1) def Checkout(self,event): borrower=self.borrower.GetValue() if len(borrower)>0: today="%s" % datetime.date.today() self.parent.orderbox.change_status(today+"-"+borrower) self.parent.orderbox.void() self.Close()
johm/infoshopkeeper
popups/checkout.py
Python
gpl-2.0
2,958
/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2014 Mark Samman <mark.samman@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "otpch.h" #include "pugicast.h" #include "items.h" #include "commands.h" #include "creature.h" #include "monster.h" #include "game.h" #include "tile.h" #include "house.h" #include "actions.h" #include "combat.h" #include "iologindata.h" #include "iomarket.h" #include "chat.h" #include "talkaction.h" #include "spells.h" #include "configmanager.h" #include "ban.h" #include "raids.h" #include "database.h" #include "server.h" #include "ioguild.h" #include "quests.h" #include "globalevent.h" #include "mounts.h" #include "bed.h" #include "scheduler.h" #include "monster.h" #include "spawn.h" #include "connection.h" #include "events.h" extern ConfigManager g_config; extern Actions* g_actions; extern Chat g_chat; extern TalkActions* g_talkActions; extern Spells* g_spells; extern Vocations g_vocations; extern GlobalEvents* g_globalEvents; extern Events* g_events; Game::Game() : wildcardTree(false), offlineTrainingWindow(std::numeric_limits<uint32_t>::max(), "Choose a Skill", "Please choose a skill:") { gameState = GAME_STATE_NORMAL; worldType = WORLD_TYPE_PVP; services = nullptr; lastStageLevel = 0; playersRecord = 0; motdNum = 0; useLastStageLevel = false; stagesEnabled = false; lastBucket = 0; //(1440 minutes/day)/(3600 seconds/day)*10 seconds event interval int32_t dayCycle = 3600; lightHourDelta = 1440 * 10 / dayCycle; lightHour = SUNRISE + (SUNSET - SUNRISE) / 2; lightLevel = LIGHT_LEVEL_DAY; lightState = LIGHT_STATE_DAY; offlineTrainingWindow.choices.emplace_back("Sword Fighting and Shielding", SKILL_SWORD); offlineTrainingWindow.choices.emplace_back("Axe Fighting and Shielding", SKILL_AXE); offlineTrainingWindow.choices.emplace_back("Club Fighting and Shielding", SKILL_CLUB); offlineTrainingWindow.choices.emplace_back("Distance Fighting and Shielding", SKILL_DISTANCE); offlineTrainingWindow.choices.emplace_back("Magic Level and Shielding", SKILL_MAGLEVEL); offlineTrainingWindow.buttons.emplace_back("Okay", 1); offlineTrainingWindow.buttons.emplace_back("Cancel", 0); offlineTrainingWindow.defaultEnterButton = 1; offlineTrainingWindow.defaultEscapeButton = 0; offlineTrainingWindow.priority = true; } Game::~Game() { for (const auto& it : guilds) { delete it.second; } } void Game::start(ServiceManager* servicer) { services = servicer; g_scheduler.addEvent(createSchedulerTask(EVENT_LIGHTINTERVAL, std::bind(&Game::checkLight, this))); g_scheduler.addEvent(createSchedulerTask(EVENT_CREATURE_THINK_INTERVAL, std::bind(&Game::checkCreatures, this, 0))); g_scheduler.addEvent(createSchedulerTask(EVENT_DECAYINTERVAL, std::bind(&Game::checkDecay, this))); } GameState_t Game::getGameState() const { return gameState; } void Game::setWorldType(WorldType_t type) { worldType = type; } void Game::setGameState(GameState_t newState) { if (gameState == GAME_STATE_SHUTDOWN) { return; //this cannot be stopped } if (gameState == newState) { return; } gameState = newState; switch (newState) { case GAME_STATE_INIT: { commands.loadFromXml(); loadExperienceStages(); groups.load(); g_chat.load(); Spawns::getInstance()->startup(); Raids::getInstance()->loadFromXml(); Raids::getInstance()->startup(); Quests::getInstance()->loadFromXml(); Mounts::getInstance()->loadFromXml(); loadMotdNum(); loadPlayersRecord(); g_globalEvents->startup(); break; } case GAME_STATE_SHUTDOWN: { g_globalEvents->execute(GLOBALEVENT_SHUTDOWN); //kick all players that are still online auto it = players.begin(); while (it != players.end()) { it->second->kickPlayer(true); it = players.begin(); } saveMotdNum(); saveGameState(); g_dispatcher.addTask( createTask(std::bind(&Game::shutdown, this))); g_scheduler.stop(); g_dispatcher.stop(); break; } case GAME_STATE_CLOSED: { /* kick all players without the CanAlwaysLogin flag */ auto it = players.begin(); while (it != players.end()) { if (!it->second->hasFlag(PlayerFlag_CanAlwaysLogin)) { it->second->kickPlayer(true); it = players.begin(); } else { ++it; } } saveGameState(); break; } default: break; } } void Game::saveGameState() { if (gameState == GAME_STATE_NORMAL) { setGameState(GAME_STATE_MAINTAIN); } std::cout << "Saving server..." << std::endl; for (const auto& it : players) { it.second->loginPosition = it.second->getPosition(); IOLoginData::savePlayer(it.second); } map.saveMap(); if (gameState == GAME_STATE_MAINTAIN) { setGameState(GAME_STATE_NORMAL); } } int32_t Game::loadMainMap(const std::string& filename) { Monster::despawnRange = g_config.getNumber(ConfigManager::DEFAULT_DESPAWNRANGE); Monster::despawnRadius = g_config.getNumber(ConfigManager::DEFAULT_DESPAWNRADIUS); return map.loadMap("data/world/" + filename + ".otbm"); } void Game::loadMap(const std::string& path) { map.loadMap(path); } Cylinder* Game::internalGetCylinder(Player* player, const Position& pos) { if (pos.x != 0xFFFF) { return getTile(pos.x, pos.y, pos.z); } //container if (pos.y & 0x40) { uint8_t from_cid = pos.y & 0x0F; return player->getContainerByID(from_cid); } //inventory return player; } Thing* Game::internalGetThing(Player* player, const Position& pos, int32_t index, uint32_t spriteId /*= 0*/, stackPosType_t type /*= STACKPOS_NORMAL*/) { if (pos.x != 0xFFFF) { Tile* tile = getTile(pos.x, pos.y, pos.z); if (tile) { /*look at*/ if (type == STACKPOS_LOOK) { return tile->getTopVisibleThing(player); } Thing* thing; /*for move operations*/ if (type == STACKPOS_MOVE) { Item* item = tile->getTopDownItem(); if (item && item->isMoveable()) { thing = item; } else { thing = tile->getTopVisibleCreature(player); } } else if (type == STACKPOS_USEITEM) { //First check items with topOrder 2 (ladders, signs, splashes) Item* item = tile->getItemByTopOrder(2); if (item && g_actions->hasAction(item)) { thing = item; } else { //then down items thing = tile->getTopDownItem(); if (!thing) { thing = tile->getTopTopItem(); //then last we check items with topOrder 3 (doors etc) if (!thing) { thing = tile->ground; } } } } else if (type == STACKPOS_USE) { thing = tile->getTopDownItem(); } else { thing = tile->__getThing(index); } if (player && tile->hasFlag(TILESTATE_SUPPORTS_HANGABLE)) { //do extra checks here if the thing is accessable if (thing && thing->getItem()) { if (tile->hasProperty(CONST_PROP_ISVERTICAL)) { if (player->getPosition().x + 1 == tile->getPosition().x) { thing = nullptr; } } else { // horizontal if (player->getPosition().y + 1 == tile->getPosition().y) { thing = nullptr; } } } } return thing; } } else { //container if (pos.y & 0x40) { uint8_t fromCid = pos.y & 0x0F; uint8_t slot = pos.z; Container* parentContainer = player->getContainerByID(fromCid); if (!parentContainer) { return nullptr; } if (parentContainer->getID() == ITEM_BROWSEFIELD) { Tile* tile = parentContainer->getTile(); if (tile && tile->hasFlag(TILESTATE_SUPPORTS_HANGABLE)) { if (tile->hasProperty(CONST_PROP_ISVERTICAL)) { if (player->getPosition().x + 1 == tile->getPosition().x) { return nullptr; } } else { // horizontal if (player->getPosition().y + 1 == tile->getPosition().y) { return nullptr; } } } } return parentContainer->getItemByIndex(player->getContainerIndex(fromCid) + slot); } else if (pos.y == 0 && pos.z == 0) { const ItemType& it = Item::items.getItemIdByClientId(spriteId); if (it.id == 0) { return nullptr; } int32_t subType; if (it.isFluidContainer() && index < int32_t(sizeof(reverseFluidMap) / sizeof(int8_t))) { subType = reverseFluidMap[index]; } else { subType = -1; } return findItemOfType(player, it.id, true, subType); } else { //inventory slots_t slot = static_cast<slots_t>(pos.y); return player->getInventoryItem(slot); } } return nullptr; } void Game::internalGetPosition(Item* item, Position& pos, uint8_t& stackpos) { pos.x = 0; pos.y = 0; pos.z = 0; stackpos = 0; Cylinder* topParent = item->getTopParent(); if (topParent) { if (Player* player = dynamic_cast<Player*>(topParent)) { pos.x = 0xFFFF; Container* container = dynamic_cast<Container*>(item->getParent()); if (container) { pos.y = (uint16_t)0x40 | (uint16_t)player->getContainerID(container); pos.z = container->__getIndexOfThing(item); stackpos = pos.z; } else { pos.y = player->__getIndexOfThing(item); stackpos = pos.y; } } else if (Tile* tile = topParent->getTile()) { pos = tile->getPosition(); stackpos = tile->__getIndexOfThing(item); } } } void Game::setTile(Tile* newTile) { return map.setTile(newTile->getPosition(), newTile); } Tile* Game::getTile(int32_t x, int32_t y, int32_t z) { return map.getTile(x, y, z); } Tile* Game::getTile(const Position& pos) { return map.getTile(pos.x, pos.y, pos.z); } QTreeLeafNode* Game::getLeaf(uint32_t x, uint32_t y) { return map.getLeaf(x, y); } Creature* Game::getCreatureByID(uint32_t id) { if (id <= Player::playerAutoID) { return getPlayerByID(id); } else if (id <= Monster::monsterAutoID) { return getMonsterByID(id); } else if (id <= Npc::npcAutoID) { return getNpcByID(id); } return nullptr; } Monster* Game::getMonsterByID(uint32_t id) { if (id == 0) { return nullptr; } auto it = monsters.find(id); if (it == monsters.end()) { return nullptr; } return it->second; } Npc* Game::getNpcByID(uint32_t id) { if (id == 0) { return nullptr; } auto it = npcs.find(id); if (it == npcs.end()) { return nullptr; } return it->second; } Player* Game::getPlayerByID(uint32_t id) { if (id == 0) { return nullptr; } auto it = players.find(id); if (it == players.end()) { return nullptr; } return it->second; } Creature* Game::getCreatureByName(const std::string& s) { if (s.empty()) { return nullptr; } const std::string& lowerCaseName = asLowerCaseString(s); auto m_it = mappedPlayerNames.find(lowerCaseName); if (m_it != mappedPlayerNames.end()) { return m_it->second; } for (const auto& it : npcs) { if (lowerCaseName == asLowerCaseString(it.second->getName())) { return it.second; } } for (const auto& it : monsters) { if (lowerCaseName == asLowerCaseString(it.second->getName())) { return it.second; } } return nullptr; } Npc* Game::getNpcByName(const std::string& s) { if (s.empty()) { return nullptr; } const char* npcName = s.c_str(); for (const auto& it : npcs) { if (strcasecmp(npcName, it.second->getName().c_str()) == 0) { return it.second; } } return nullptr; } Player* Game::getPlayerByName(const std::string& s) { if (s.empty()) { return nullptr; } auto it = mappedPlayerNames.find(asLowerCaseString(s)); if (it == mappedPlayerNames.end()) { return nullptr; } return it->second; } Player* Game::getPlayerByGUID(const uint32_t& guid) { if (guid == 0) { return nullptr; } for (const auto& it : players) { if (guid == it.second->getGUID()) { return it.second; } } return nullptr; } ReturnValue Game::getPlayerByNameWildcard(const std::string& s, Player*& player) { size_t strlen = s.length(); if (strlen == 0 || strlen > 20) { return RET_PLAYERWITHTHISNAMEISNOTONLINE; } if (s.back() == '~') { const std::string& query = asLowerCaseString(s.substr(0, strlen - 1)); std::string result; ReturnValue ret = wildcardTree.findOne(query, result); if (ret != RET_NOERROR) { return ret; } player = getPlayerByName(result); } else { player = getPlayerByName(s); } if (!player) { return RET_PLAYERWITHTHISNAMEISNOTONLINE; } return RET_NOERROR; } Player* Game::getPlayerByAccount(uint32_t acc) { for (const auto& it : players) { if (it.second->getAccount() == acc) { return it.second; } } return nullptr; } bool Game::internalPlaceCreature(Creature* creature, const Position& pos, bool extendedPos /*=false*/, bool forced /*= false*/) { if (creature->getParent() != nullptr) { return false; } if (!map.placeCreature(pos, creature, extendedPos, forced)) { return false; } creature->useThing2(); creature->setID(); creature->addList(); if (!creature->getPlayer()) { g_events->eventMonsterOnAppear(creature); } return true; } bool Game::placeCreature(Creature* creature, const Position& pos, bool extendedPos /*=false*/, bool forced /*= false*/) { if (!internalPlaceCreature(creature, pos, extendedPos, forced)) { return false; } SpectatorVec list; getSpectators(list, creature->getPosition(), true); for (Creature* spectator : list) { if (Player* tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendCreatureAppear(creature, creature->getPosition(), true); } } for (Creature* spectator : list) { spectator->onCreatureAppear(creature, true); } Cylinder* creatureParent = creature->getParent(); int32_t newIndex = creatureParent->__getIndexOfThing(creature); creatureParent->postAddNotification(creature, nullptr, newIndex); // TODO: Move this code to Player::onCreatureAppear where creature == this. Player* player = creature->getPlayer(); if (player) { int32_t offlineTime; if (player->getLastLogout() != 0) { // Not counting more than 21 days to prevent overflow when multiplying with 1000 (for milliseconds). offlineTime = std::min<int32_t>(time(nullptr) - player->getLastLogout(), 86400 * 21); } else { offlineTime = 0; } Condition* conditionMuted = player->getCondition(CONDITION_MUTED, CONDITIONID_DEFAULT); if (conditionMuted && conditionMuted->getTicks() > 0) { conditionMuted->setTicks(conditionMuted->getTicks() - (offlineTime * 1000)); if (conditionMuted->getTicks() <= 0) { player->removeCondition(conditionMuted); } else { player->addCondition(conditionMuted->clone()); } } Condition* conditionTrade = player->getCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_ADVERTISING); if (conditionTrade && conditionTrade->getTicks() > 0) { conditionTrade->setTicks(conditionTrade->getTicks() - (offlineTime * 1000)); if (conditionTrade->getTicks() <= 0) { player->removeCondition(conditionTrade); } else { player->addCondition(conditionTrade->clone()); } } Condition* conditionTradeRook = player->getCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_ADVERTISINGROOKGAARD); if (conditionTradeRook && conditionTradeRook->getTicks() > 0) { conditionTradeRook->setTicks(conditionTradeRook->getTicks() - (offlineTime * 1000)); if (conditionTradeRook->getTicks() <= 0) { player->removeCondition(conditionTradeRook); } else { player->addCondition(conditionTradeRook->clone()); } } Condition* conditionHelp = player->getCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_HELP); if (conditionHelp && conditionHelp->getTicks() > 0) { conditionHelp->setTicks(conditionHelp->getTicks() - (offlineTime * 1000)); if (conditionHelp->getTicks() <= 0) { player->removeCondition(conditionHelp); } else { player->addCondition(conditionHelp->clone()); } } Condition* conditionYell = player->getCondition(CONDITION_YELLTICKS, CONDITIONID_DEFAULT); if (conditionYell && conditionYell->getTicks() > 0) { conditionYell->setTicks(conditionYell->getTicks() - (offlineTime * 1000)); if (conditionYell->getTicks() <= 0) { player->removeCondition(conditionYell); } else { player->addCondition(conditionYell->clone()); } } if (player->isPremium()) { int32_t value; player->getStorageValue(STORAGEVALUE_PROMOTION, value); if (player->isPromoted() && value != 1) { player->addStorageValue(STORAGEVALUE_PROMOTION, 1); } else if (!player->isPromoted() && value == 1) { player->setVocation(g_vocations.getPromotedVocation(player->getVocationId())); } } else if (player->isPromoted()) { player->setVocation(player->vocation->getFromVocation()); } bool sentStats = false; int16_t oldStaminaMinutes = player->getStaminaMinutes(); player->regenerateStamina(offlineTime); int32_t offlineTrainingSkill = player->getOfflineTrainingSkill(); if (offlineTrainingSkill != -1) { player->setOfflineTrainingSkill(-1); uint32_t offlineTrainingTime = std::max<int32_t>(0, std::min<int32_t>(offlineTime, std::min<int32_t>(43200, player->getOfflineTrainingTime() / 1000))); if (offlineTime >= 600) { player->removeOfflineTrainingTime(offlineTrainingTime * 1000); int32_t remainder = offlineTime - offlineTrainingTime; if (remainder > 0) { player->addOfflineTrainingTime(remainder * 1000); } if (offlineTrainingTime >= 60) { std::ostringstream ss; ss << "During your absence you trained for "; int32_t hours = offlineTrainingTime / 3600; if (hours > 1) { ss << hours << " hours"; } else if (hours == 1) { ss << "1 hour"; } int32_t minutes = (offlineTrainingTime % 3600) / 60; if (minutes != 0) { if (hours != 0) { ss << " and "; } if (minutes > 1) { ss << minutes << " minutes"; } else { ss << "1 minute"; } } ss << '.'; player->sendTextMessage(MESSAGE_EVENT_ADVANCE, ss.str()); Vocation* vocation; if (player->isPromoted()) { vocation = player->getVocation(); } else { int32_t promotedVocationId = g_vocations.getPromotedVocation(player->getVocationId()); vocation = g_vocations.getVocation(promotedVocationId); if (!vocation) { vocation = player->getVocation(); } } bool sendUpdateSkills = false; if (offlineTrainingSkill == SKILL_CLUB || offlineTrainingSkill == SKILL_SWORD || offlineTrainingSkill == SKILL_AXE) { float modifier = vocation->getAttackSpeed() / 1000.f; sendUpdateSkills = player->addOfflineTrainingTries((skills_t)offlineTrainingSkill, (offlineTrainingTime / modifier) / 2); } else if (offlineTrainingSkill == SKILL_DISTANCE) { float modifier = vocation->getAttackSpeed() / 1000.f; sendUpdateSkills = player->addOfflineTrainingTries((skills_t)offlineTrainingSkill, (offlineTrainingTime / modifier) / 4); } else if (offlineTrainingSkill == SKILL_MAGLEVEL) { int32_t gainTicks = vocation->getManaGainTicks() * 2; if (gainTicks == 0) { gainTicks = 1; } player->addOfflineTrainingTries(SKILL_MAGLEVEL, offlineTrainingTime * (vocation->getManaGainAmount() / gainTicks)); } if (player->addOfflineTrainingTries(SKILL_SHIELD, offlineTrainingTime / 4) || sendUpdateSkills) { player->sendSkills(); } } player->sendStats(); sentStats = true; } else { player->sendTextMessage(MESSAGE_EVENT_ADVANCE, "You must be logged out for more than 10 minutes to start offline training."); } } else { uint16_t oldMinutes = player->getOfflineTrainingTime() / 60 / 1000; player->addOfflineTrainingTime(offlineTime * 1000); uint16_t newMinutes = player->getOfflineTrainingTime() / 60 / 1000; if (oldMinutes != newMinutes) { player->sendStats(); sentStats = true; } } if (!sentStats && player->getStaminaMinutes() != oldStaminaMinutes) { player->sendStats(); } } addCreatureCheck(creature); creature->onPlacedCreature(); return true; } bool Game::removeCreature(Creature* creature, bool isLogout /*= true*/) { if (creature->isRemoved()) { return false; } Tile* tile = creature->getTile(); std::vector<int32_t> oldStackPosVector; SpectatorVec list; getSpectators(list, tile->getPosition(), true); for (Creature* spectator : list) { if (Player* player = spectator->getPlayer()) { oldStackPosVector.push_back(player->canSeeCreature(creature) ? tile->getStackposOfCreature(player, creature) : -1); } } int32_t index = tile->__getIndexOfThing(creature); if (!Map::removeCreature(creature)) { return false; } const Position& tilePosition = tile->getPosition(); //send to client size_t i = 0; for (Creature* spectator : list) { if (Player* player = spectator->getPlayer()) { player->sendRemoveTileThing(tilePosition, oldStackPosVector[i++]); } } //event method for (Creature* spectator : list) { spectator->onCreatureDisappear(creature, index, isLogout); } creature->getParent()->postRemoveNotification(creature, nullptr, index, true); creature->removeList(); creature->setRemoved(); ReleaseCreature(creature); removeCreatureCheck(creature); for (Creature* summon : creature->summons) { summon->setLossSkill(false); removeCreature(summon); } creature->onRemovedCreature(); return true; } void Game::playerMoveThing(uint32_t playerId, const Position& fromPos, uint16_t spriteId, uint8_t fromStackPos, const Position& toPos, uint8_t count) { Player* player = getPlayerByID(playerId); if (!player) { return; } uint8_t fromIndex = 0; if (fromPos.x == 0xFFFF) { if (fromPos.y & 0x40) { fromIndex = fromPos.z; } else { fromIndex = fromPos.y; } } else { fromIndex = fromStackPos; } Thing* thing = internalGetThing(player, fromPos, fromIndex, spriteId, STACKPOS_MOVE); if (!thing) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } Cylinder* toCylinder = internalGetCylinder(player, toPos); if (!toCylinder) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } if (Creature* movingCreature = thing->getCreature()) { if (Position::areInRange<1, 1, 0>(movingCreature->getPosition(), player->getPosition())) { SchedulerTask* task = createSchedulerTask(1000, std::bind(&Game::playerMoveCreature, this, player->getID(), movingCreature->getID(), movingCreature->getPosition(), toCylinder->getPosition())); player->setNextActionTask(task); } else { playerMoveCreature(playerId, movingCreature->getID(), movingCreature->getPosition(), toCylinder->getPosition()); } } else if (thing->getItem()) { playerMoveItem(playerId, fromPos, spriteId, fromStackPos, toPos, count); } } void Game::playerMoveCreature(uint32_t playerId, uint32_t movingCreatureId, const Position& movingCreatureOrigPos, const Position& toPos) { Player* player = getPlayerByID(playerId); if (!player) { return; } Tile* toTile = getTile(toPos); if (!toTile) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } Creature* movingCreature = getCreatureByID(movingCreatureId); if (!movingCreature) { return; } if (!player->canDoAction()) { uint32_t delay = player->getNextActionTime(); SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerMoveCreature, this, playerId, movingCreatureId, movingCreatureOrigPos, toPos)); player->setNextActionTask(task); return; } player->setNextActionTask(nullptr); if (!Position::areInRange<1, 1, 0>(movingCreatureOrigPos, player->getPosition())) { //need to walk to the creature first before moving it std::list<Direction> listDir; if (player->getPathTo(movingCreatureOrigPos, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); SchedulerTask* task = createSchedulerTask(1500, std::bind(&Game::playerMoveCreature, this, playerId, movingCreatureId, movingCreatureOrigPos, toPos)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RET_THEREISNOWAY); } return; } if ((!movingCreature->isPushable() && !player->hasFlag(PlayerFlag_CanPushAllCreatures)) || (movingCreature->isInGhostMode() && !player->isAccessPlayer())) { player->sendCancelMessage(RET_NOTMOVEABLE); return; } //check throw distance const Position& movingCreaturePos = movingCreature->getPosition(); if ((Position::getDistanceX(movingCreaturePos, toPos) > movingCreature->getThrowRange()) || (Position::getDistanceY(movingCreaturePos, toPos) > movingCreature->getThrowRange()) || (Position::getDistanceZ(movingCreaturePos, toPos) * 4 > movingCreature->getThrowRange())) { player->sendCancelMessage(RET_DESTINATIONOUTOFREACH); return; } Tile* movingCreatureTile = movingCreature->getTile(); if (!movingCreatureTile) { player->sendCancelMessage(RET_NOTMOVEABLE); return; } if (player != movingCreature) { if (toTile->hasProperty(CONST_PROP_BLOCKPATH)) { player->sendCancelMessage(RET_NOTENOUGHROOM); return; } else if ((movingCreature->getZone() == ZONE_PROTECTION && !toTile->hasFlag(TILESTATE_PROTECTIONZONE)) || (movingCreature->getZone() == ZONE_NOPVP && !toTile->hasFlag(TILESTATE_NOPVPZONE))) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } else { if (CreatureVector* tileCreatures = toTile->getCreatures()) { for (Creature* tileCreature : *tileCreatures) { if (!tileCreature->isInGhostMode()) { player->sendCancelMessage(RET_NOTENOUGHROOM); return; } } } Npc* movingNpc = movingCreature->getNpc(); if (movingNpc && !Spawns::getInstance()->isInZone(movingNpc->getMasterPos(), movingNpc->getMasterRadius(), toPos)) { player->sendCancelMessage(RET_NOTENOUGHROOM); return; } } } if (!g_events->eventPlayerOnMoveCreature(player, movingCreature, movingCreaturePos, toPos)) { return; } ReturnValue ret = internalMoveCreature(movingCreature, movingCreatureTile, toTile); if (ret != RET_NOERROR) { player->sendCancelMessage(ret); } } ReturnValue Game::internalMoveCreature(Creature* creature, Direction direction, uint32_t flags /*= 0*/) { Cylinder* fromTile = creature->getTile(); Cylinder* toTile = nullptr; creature->setLastPosition(creature->getPosition()); const Position& currentPos = creature->getPosition(); Position destPos = currentPos; bool diagonalMovement; switch (direction) { case NORTHWEST: case NORTHEAST: case SOUTHWEST: case SOUTHEAST: diagonalMovement = true; break; default: diagonalMovement = false; break; } destPos = getNextPosition(direction, destPos); if (creature->getPlayer() && !diagonalMovement) { //try go up if (currentPos.z != 8 && creature->getTile()->hasHeight(3)) { Tile* tmpTile = getTile(currentPos.x, currentPos.y, currentPos.getZ() - 1); if (tmpTile == nullptr || (tmpTile->ground == nullptr && !tmpTile->hasProperty(CONST_PROP_BLOCKSOLID))) { tmpTile = getTile(destPos.x, destPos.y, destPos.getZ() - 1); if (tmpTile && tmpTile->ground && !tmpTile->hasProperty(CONST_PROP_BLOCKSOLID)) { flags = flags | FLAG_IGNOREBLOCKITEM | FLAG_IGNOREBLOCKCREATURE; if (!tmpTile->floorChange()) { destPos.z--; } } } } else { //try go down Tile* tmpTile = getTile(destPos); if (currentPos.z != 7 && (tmpTile == nullptr || (tmpTile->ground == nullptr && !tmpTile->hasProperty(CONST_PROP_BLOCKSOLID)))) { tmpTile = getTile(destPos.x, destPos.y, destPos.z + 1); if (tmpTile && tmpTile->hasHeight(3)) { flags |= FLAG_IGNOREBLOCKITEM | FLAG_IGNOREBLOCKCREATURE; destPos.z++; } } } } toTile = getTile(destPos); ReturnValue ret = RET_NOTPOSSIBLE; if (toTile != nullptr) { ret = internalMoveCreature(creature, fromTile, toTile, flags); } return ret; } ReturnValue Game::internalMoveCreature(Creature* creature, Cylinder* fromCylinder, Cylinder* toCylinder, uint32_t flags /*= 0*/) { //check if we can move the creature to the destination ReturnValue ret = toCylinder->__queryAdd(0, creature, 1, flags); if (ret != RET_NOERROR) { return ret; } fromCylinder->getTile()->moveCreature(creature, toCylinder); int32_t index = 0; Item* toItem = nullptr; Cylinder* subCylinder = nullptr; uint32_t n = 0; while ((subCylinder = toCylinder->__queryDestination(index, creature, &toItem, flags)) != toCylinder) { toCylinder->getTile()->moveCreature(creature, subCylinder); if (creature->getParent() != subCylinder) { //could happen if a script move the creature break; } toCylinder = subCylinder; flags = 0; //to prevent infinite loop if (++n >= MAP_MAX_LAYERS) { break; } } return RET_NOERROR; } void Game::playerMoveItem(uint32_t playerId, const Position& fromPos, uint16_t spriteId, uint8_t fromStackPos, const Position& toPos, uint8_t count) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (!player->canDoAction()) { uint32_t delay = player->getNextActionTime(); SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerMoveItem, this, playerId, fromPos, spriteId, fromStackPos, toPos, count)); player->setNextActionTask(task); return; } player->setNextActionTask(nullptr); Cylinder* fromCylinder = internalGetCylinder(player, fromPos); uint8_t fromIndex = 0; if (fromPos.x == 0xFFFF) { if (fromPos.y & 0x40) { fromIndex = fromPos.z; } else { fromIndex = static_cast<uint8_t>(fromPos.y); } } else { fromIndex = fromStackPos; } Thing* thing = internalGetThing(player, fromPos, fromIndex, spriteId, STACKPOS_MOVE); if (!thing || !thing->getItem()) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } Item* item = thing->getItem(); Cylinder* toCylinder = internalGetCylinder(player, toPos); uint8_t toIndex = 0; if (toPos.x == 0xFFFF) { if (toPos.y & 0x40) { toIndex = toPos.z; } else { toIndex = toPos.y; } } if (fromCylinder == nullptr || toCylinder == nullptr || item == nullptr || item->getClientID() != spriteId) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } if (!item->isPushable() || item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) { player->sendCancelMessage(RET_NOTMOVEABLE); return; } const Position& playerPos = player->getPosition(); const Position& mapFromPos = fromCylinder->getTile()->getPosition(); if (playerPos.z != mapFromPos.z) { player->sendCancelMessage(playerPos.z > mapFromPos.z ? RET_FIRSTGOUPSTAIRS : RET_FIRSTGODOWNSTAIRS); return; } if (!Position::areInRange<1, 1>(playerPos, mapFromPos)) { //need to walk to the item first before using it std::list<Direction> listDir; if (player->getPathTo(item->getPosition(), listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerMoveItem, this, playerId, fromPos, spriteId, fromStackPos, toPos, count)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RET_THEREISNOWAY); } return; } const Tile* toCylinderTile = toCylinder->getTile(); const Position& mapToPos = toCylinderTile->getPosition(); //hangable item specific code if (item->isHangable() && toCylinderTile->hasFlag(TILESTATE_SUPPORTS_HANGABLE)) { //destination supports hangable objects so need to move there first bool vertical = toCylinderTile->hasProperty(CONST_PROP_ISVERTICAL); if (vertical) { if (playerPos.x + 1 == mapToPos.x) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } } else { // horizontal if (playerPos.y + 1 == mapToPos.y) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } } if (!Position::areInRange<1, 1, 0>(playerPos, mapToPos)) { Position walkPos = mapToPos; if (vertical) { walkPos.x++; } else { walkPos.y++; } Position itemPos = fromPos; uint8_t itemStackPos = fromStackPos; if (fromPos.x != 0xFFFF && Position::areInRange<1, 1>(mapFromPos, playerPos) && !Position::areInRange<1, 1, 0>(mapFromPos, walkPos)) { //need to pickup the item first Item* moveItem = nullptr; ReturnValue ret = internalMoveItem(fromCylinder, player, INDEX_WHEREEVER, item, count, &moveItem); if (ret != RET_NOERROR) { player->sendCancelMessage(ret); return; } //changing the position since its now in the inventory of the player internalGetPosition(moveItem, itemPos, itemStackPos); } std::list<Direction> listDir; if (player->getPathTo(walkPos, listDir, 0, 0, true, true)) { g_dispatcher.addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerMoveItem, this, playerId, itemPos, spriteId, itemStackPos, toPos, count)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RET_THEREISNOWAY); } return; } } if ((Position::getDistanceX(playerPos, mapToPos) > item->getThrowRange()) || (Position::getDistanceY(playerPos, mapToPos) > item->getThrowRange()) || (Position::getDistanceZ(mapFromPos, mapToPos) * 4 > item->getThrowRange())) { player->sendCancelMessage(RET_DESTINATIONOUTOFREACH); return; } if (!canThrowObjectTo(mapFromPos, mapToPos)) { player->sendCancelMessage(RET_CANNOTTHROW); return; } if (!g_events->eventPlayerOnMoveItem(player, item, count, fromPos, toPos)) { return; } ReturnValue ret = internalMoveItem(fromCylinder, toCylinder, toIndex, item, count, nullptr, 0, player); if (ret != RET_NOERROR) { player->sendCancelMessage(ret); } } ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, int32_t index, Item* item, uint32_t count, Item** _moveItem, uint32_t flags /*= 0*/, Creature* actor/* = nullptr*/, Item* tradeItem/* = nullptr*/) { if (!toCylinder) { return RET_NOTPOSSIBLE; } Tile* fromTile = fromCylinder->getTile(); if (fromTile) { auto it = browseFields.find(fromTile); if (it != browseFields.end() && it->second == fromCylinder) { fromCylinder = fromTile; } } Item* toItem = nullptr; Cylinder* subCylinder; int floorN = 0; while ((subCylinder = toCylinder->__queryDestination(index, item, &toItem, flags)) != toCylinder) { toCylinder = subCylinder; flags = 0; //to prevent infinite loop if (++floorN >= MAP_MAX_LAYERS) { break; } } //destination is the same as the source? if (item == toItem) { return RET_NOERROR; //silently ignore move } //check if we can add this item ReturnValue ret = toCylinder->__queryAdd(index, item, count, flags, actor); if (ret == RET_NEEDEXCHANGE) { //check if we can add it to source cylinder ret = fromCylinder->__queryAdd(fromCylinder->__getIndexOfThing(item), toItem, toItem->getItemCount(), 0); if (ret == RET_NOERROR) { //check how much we can move uint32_t maxExchangeQueryCount = 0; ReturnValue retExchangeMaxCount = fromCylinder->__queryMaxCount(INDEX_WHEREEVER, toItem, toItem->getItemCount(), maxExchangeQueryCount, 0); if (retExchangeMaxCount != RET_NOERROR && maxExchangeQueryCount == 0) { return retExchangeMaxCount; } if (toCylinder->__queryRemove(toItem, toItem->getItemCount(), flags) == RET_NOERROR) { int32_t oldToItemIndex = toCylinder->__getIndexOfThing(toItem); toCylinder->__removeThing(toItem, toItem->getItemCount()); fromCylinder->__addThing(toItem); if (oldToItemIndex != -1) { toCylinder->postRemoveNotification(toItem, fromCylinder, oldToItemIndex, true); } int32_t newToItemIndex = fromCylinder->__getIndexOfThing(toItem); if (newToItemIndex != -1) { fromCylinder->postAddNotification(toItem, toCylinder, newToItemIndex); } ret = toCylinder->__queryAdd(index, item, count, flags); toItem = nullptr; } } } if (ret != RET_NOERROR) { return ret; } //check how much we can move uint32_t maxQueryCount = 0; ReturnValue retMaxCount = toCylinder->__queryMaxCount(index, item, count, maxQueryCount, flags); if (retMaxCount != RET_NOERROR && maxQueryCount == 0) { return retMaxCount; } uint32_t m; if (item->isStackable()) { m = std::min<uint32_t>(count, maxQueryCount); } else { m = maxQueryCount; } Item* moveItem = item; //check if we can remove this item ret = fromCylinder->__queryRemove(item, m, flags); if (ret != RET_NOERROR) { return ret; } if (tradeItem) { if (toCylinder->getItem() == tradeItem) { return RET_NOTENOUGHROOM; } Cylinder* tmpCylinder = toCylinder->getParent(); while (tmpCylinder) { if (tmpCylinder->getItem() == tradeItem) { return RET_NOTENOUGHROOM; } tmpCylinder = tmpCylinder->getParent(); } } //remove the item int32_t itemIndex = fromCylinder->__getIndexOfThing(item); Item* updateItem = nullptr; fromCylinder->__removeThing(item, m); bool isCompleteRemoval = item->isRemoved(); //update item(s) if (item->isStackable()) { uint32_t n; if (toItem && toItem->getID() == item->getID()) { n = std::min<uint32_t>(100 - toItem->getItemCount(), m); toCylinder->__updateThing(toItem, toItem->getID(), toItem->getItemCount() + n); updateItem = toItem; } else { n = 0; } int32_t newCount = m - n; if (newCount > 0) { moveItem = Item::CreateItem(item->getID(), newCount); } else { moveItem = nullptr; } if (item->isRemoved()) { ReleaseItem(item); } } //add item if (moveItem /*m - n > 0*/) { toCylinder->__addThing(index, moveItem); } if (itemIndex != -1) { fromCylinder->postRemoveNotification(item, toCylinder, itemIndex, isCompleteRemoval); } if (moveItem) { int32_t moveItemIndex = toCylinder->__getIndexOfThing(moveItem); if (moveItemIndex != -1) { toCylinder->postAddNotification(moveItem, fromCylinder, moveItemIndex); } } if (updateItem) { int32_t updateItemIndex = toCylinder->__getIndexOfThing(updateItem); if (updateItemIndex != -1) { toCylinder->postAddNotification(updateItem, fromCylinder, updateItemIndex); } } if (_moveItem) { if (moveItem) { *_moveItem = moveItem; } else { *_moveItem = item; } } //we could not move all, inform the player if (item->isStackable() && maxQueryCount < count) { return retMaxCount; } return ret; } ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t index /*= INDEX_WHEREEVER*/, uint32_t flags/* = 0*/, bool test/* = false*/) { uint32_t remainderCount = 0; return internalAddItem(toCylinder, item, index, flags, test, remainderCount); } ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t index, uint32_t flags, bool test, uint32_t& remainderCount) { remainderCount = 0; if (toCylinder == nullptr || item == nullptr) { return RET_NOTPOSSIBLE; } Cylinder* destCylinder = toCylinder; Item* toItem = nullptr; toCylinder = toCylinder->__queryDestination(index, item, &toItem, flags); //check if we can add this item ReturnValue ret = toCylinder->__queryAdd(index, item, item->getItemCount(), flags); if (ret != RET_NOERROR) { return ret; } /* Check if we can move add the whole amount, we do this by checking against the original cylinder, since the queryDestination can return a cylinder that might only hold a part of the full amount. */ uint32_t maxQueryCount = 0; ret = destCylinder->__queryMaxCount(INDEX_WHEREEVER, item, item->getItemCount(), maxQueryCount, flags); if (ret != RET_NOERROR) { return ret; } if (test) { return RET_NOERROR; } if (item->isStackable() && toItem && toItem->getID() == item->getID()) { uint32_t m = std::min<uint32_t>(item->getItemCount(), maxQueryCount); uint32_t n = 0; if (toItem->getID() == item->getID()) { n = std::min<uint32_t>(100 - toItem->getItemCount(), m); toCylinder->__updateThing(toItem, toItem->getID(), toItem->getItemCount() + n); } int32_t count = m - n; if (count > 0) { if (item->getItemCount() != count) { Item* remainderItem = Item::CreateItem(item->getID(), count); if (internalAddItem(destCylinder, remainderItem, INDEX_WHEREEVER, flags, false) != RET_NOERROR) { ReleaseItem(remainderItem); remainderCount = count; } } else { toCylinder->__addThing(index, item); int32_t itemIndex = toCylinder->__getIndexOfThing(item); if (itemIndex != -1) { toCylinder->postAddNotification(item, nullptr, itemIndex); } } } else { //fully merged with toItem, item will be destroyed item->onRemoved(); ReleaseItem(item); int32_t itemIndex = toCylinder->__getIndexOfThing(toItem); if (itemIndex != -1) { toCylinder->postAddNotification(toItem, nullptr, itemIndex); } } } else { toCylinder->__addThing(index, item); int32_t itemIndex = toCylinder->__getIndexOfThing(item); if (itemIndex != -1) { toCylinder->postAddNotification(item, nullptr, itemIndex); } } return RET_NOERROR; } ReturnValue Game::internalRemoveItem(Item* item, int32_t count /*= -1*/, bool test /*= false*/, uint32_t flags /*= 0*/) { Cylinder* cylinder = item->getParent(); if (cylinder == nullptr) { return RET_NOTPOSSIBLE; } Tile* fromTile = cylinder->getTile(); if (fromTile) { auto it = browseFields.find(fromTile); if (it != browseFields.end() && it->second == cylinder) { cylinder = fromTile; } } if (count == -1) { count = item->getItemCount(); } //check if we can remove this item ReturnValue ret = cylinder->__queryRemove(item, count, flags | FLAG_IGNORENOTMOVEABLE); if (ret != RET_NOERROR) { return ret; } if (!item->canRemove()) { return RET_NOTPOSSIBLE; } if (!test) { int32_t index = cylinder->__getIndexOfThing(item); //remove the item cylinder->__removeThing(item, count); bool isCompleteRemoval = false; if (item->isRemoved()) { isCompleteRemoval = true; ReleaseItem(item); } cylinder->postRemoveNotification(item, nullptr, index, isCompleteRemoval); } item->onRemoved(); return RET_NOERROR; } ReturnValue Game::internalPlayerAddItem(Player* player, Item* item, bool dropOnMap /*= true*/, slots_t slot /*= CONST_SLOT_WHEREEVER*/) { uint32_t remainderCount = 0; ReturnValue ret = internalAddItem(player, item, (int32_t)slot, 0, false, remainderCount); if (remainderCount > 0) { Item* remainderItem = Item::CreateItem(item->getID(), remainderCount); ReturnValue remaindRet = internalAddItem(player->getTile(), remainderItem, INDEX_WHEREEVER, FLAG_NOLIMIT); if (remaindRet != RET_NOERROR) { ReleaseItem(remainderItem); } } if (ret != RET_NOERROR && dropOnMap) { ret = internalAddItem(player->getTile(), item, INDEX_WHEREEVER, FLAG_NOLIMIT); } return ret; } Item* Game::findItemOfType(Cylinder* cylinder, uint16_t itemId, bool depthSearch /*= true*/, int32_t subType /*= -1*/) { if (cylinder == nullptr) { return nullptr; } std::vector<Container*> containers; for (int32_t i = cylinder->__getFirstIndex(), j = cylinder->__getLastIndex(); i < j; ++i) { Thing* thing = cylinder->__getThing(i); if (!thing) { continue; } Item* item = thing->getItem(); if (!item) { continue; } if (item->getID() == itemId && (subType == -1 || subType == item->getSubType())) { return item; } if (depthSearch) { Container* container = item->getContainer(); if (container) { containers.push_back(container); } } } size_t i = 0; while (i < containers.size()) { Container* container = containers[i++]; for (Item* item : container->getItemList()) { if (item->getID() == itemId && (subType == -1 || subType == item->getSubType())) { return item; } Container* tmpContainer = item->getContainer(); if (tmpContainer) { containers.push_back(tmpContainer); } } } return nullptr; } bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/) { if (cylinder == nullptr) { return false; } if (money <= 0) { return true; } std::vector<Container*> containers; typedef std::multimap<uint64_t, Item*, std::less<uint64_t>> MoneyMap; typedef MoneyMap::value_type moneymap_pair; MoneyMap moneyMap; uint64_t moneyCount = 0; for (int32_t i = cylinder->__getFirstIndex(), j = cylinder->__getLastIndex(); i < j; ++i) { Thing* thing = cylinder->__getThing(i); if (!thing) { continue; } Item* item = thing->getItem(); if (!item) { continue; } Container* container = item->getContainer(); if (container) { containers.push_back(container); } else if (item->getWorth() != 0) { moneyCount += item->getWorth(); moneyMap.insert(moneymap_pair(item->getWorth(), item)); } } size_t i = 0; while (i < containers.size()) { Container* container = containers[i++]; for (Item* item : container->getItemList()) { Container* tmpContainer = item->getContainer(); if (tmpContainer) { containers.push_back(tmpContainer); } else if (item->getWorth() != 0) { moneyCount += item->getWorth(); moneyMap.insert(moneymap_pair(item->getWorth(), item)); } } } /*not enough money*/ if (moneyCount < money) { return false; } for (MoneyMap::const_iterator mit = moneyMap.begin(), mend = moneyMap.end(); mit != mend && money > 0; ++mit) { Item* item = mit->second; internalRemoveItem(item); if (mit->first > money) { /* Remove a monetary value from an item*/ uint64_t remaind = item->getWorth() - money; addMoney(cylinder, remaind, flags); money = 0; } else { money -= mit->first; } } return money == 0; } void Game::addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/) { uint32_t crys = money / 10000; money -= crys * 10000; while (crys > 0) { Item* remaindItem = Item::CreateItem(ITEM_CRYSTAL_COIN, std::min<int32_t>(100, crys)); ReturnValue ret = internalAddItem(cylinder, remaindItem, INDEX_WHEREEVER, flags); if (ret != RET_NOERROR) { internalAddItem(cylinder->getTile(), remaindItem, INDEX_WHEREEVER, FLAG_NOLIMIT); } crys -= std::min<int32_t>(100, crys); } uint16_t plat = money / 100; if (plat != 0) { Item* remaindItem = Item::CreateItem(ITEM_PLATINUM_COIN, plat); ReturnValue ret = internalAddItem(cylinder, remaindItem, INDEX_WHEREEVER, flags); if (ret != RET_NOERROR) { internalAddItem(cylinder->getTile(), remaindItem, INDEX_WHEREEVER, FLAG_NOLIMIT); } money -= plat * 100; } if (money != 0) { Item* remaindItem = Item::CreateItem(ITEM_GOLD_COIN, money); ReturnValue ret = internalAddItem(cylinder, remaindItem, INDEX_WHEREEVER, flags); if (ret != RET_NOERROR) { internalAddItem(cylinder->getTile(), remaindItem, INDEX_WHEREEVER, FLAG_NOLIMIT); } } } Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) { if (item->getID() == newId && (newCount == -1 || (newCount == item->getSubType() && newCount != 0))) { //chargeless item placed on map = infinite return item; } Cylinder* cylinder = item->getParent(); if (cylinder == nullptr) { return nullptr; } Tile* fromTile = cylinder->getTile(); if (fromTile) { auto it = browseFields.find(fromTile); if (it != browseFields.end() && it->second == cylinder) { cylinder = fromTile; } } int32_t itemIndex = cylinder->__getIndexOfThing(item); if (itemIndex == -1) { return item; } if (!item->canTransform()) { return item; } const ItemType& curType = Item::items[item->getID()]; const ItemType& newType = Item::items[newId]; if (curType.alwaysOnTop != newType.alwaysOnTop) { //This only occurs when you transform items on tiles from a downItem to a topItem (or vice versa) //Remove the old, and add the new ReturnValue ret = internalRemoveItem(item); if (ret != RET_NOERROR) { return item; } Item* newItem; if (newCount == -1) { newItem = Item::CreateItem(newId); } else { newItem = Item::CreateItem(newId, newCount); } if (!newItem) { return nullptr; } newItem->stealAttributes(item); ret = internalAddItem(cylinder, newItem, INDEX_WHEREEVER, FLAG_NOLIMIT); if (ret != RET_NOERROR) { delete newItem; return nullptr; } return newItem; } if (curType.type == newType.type) { //Both items has the same type so we can safely change id/subtype if (newCount == 0 && (item->isStackable() || item->hasAttribute(ITEM_ATTRIBUTE_CHARGES))) { if (item->isStackable()) { internalRemoveItem(item); return nullptr; } else { int32_t newItemId = newId; if (curType.id == newType.id) { newItemId = curType.decayTo; } if (newItemId == -1) { internalRemoveItem(item); return nullptr; } else if (newItemId != newId) { //Replacing the the old item with the new while maintaining the old position Item* newItem = Item::CreateItem(newItemId, 1); if (newItem == nullptr) { return nullptr; } cylinder->__replaceThing(itemIndex, newItem); cylinder->postAddNotification(newItem, cylinder, itemIndex); item->setParent(nullptr); cylinder->postRemoveNotification(item, cylinder, itemIndex, true); ReleaseItem(item); return newItem; } else { return transformItem(item, newItemId); } } } else { cylinder->postRemoveNotification(item, cylinder, itemIndex, false); uint16_t itemId = item->getID(); int32_t count = item->getSubType(); if (curType.id != newType.id) { if (newType.group != curType.group) { item->setDefaultSubtype(); } itemId = newId; } if (newCount != -1 && newType.hasSubType()) { count = newCount; } cylinder->__updateThing(item, itemId, count); cylinder->postAddNotification(item, cylinder, itemIndex); return item; } } //Replacing the the old item with the new while maintaining the old position Item* newItem; if (newCount == -1) { newItem = Item::CreateItem(newId); } else { newItem = Item::CreateItem(newId, newCount); } if (newItem == nullptr) { return nullptr; } cylinder->__replaceThing(itemIndex, newItem); cylinder->postAddNotification(newItem, cylinder, itemIndex); item->setParent(nullptr); cylinder->postRemoveNotification(item, cylinder, itemIndex, true); ReleaseItem(item); return newItem; } ReturnValue Game::internalTeleport(Thing* thing, const Position& newPos, bool pushMove/* = true*/, uint32_t flags /*= 0*/) { if (newPos == thing->getPosition()) { return RET_NOERROR; } else if (thing->isRemoved()) { return RET_NOTPOSSIBLE; } Tile* toTile = getTile(newPos.x, newPos.y, newPos.z); if (toTile) { if (Creature* creature = thing->getCreature()) { ReturnValue ret = toTile->__queryAdd(0, creature, 1, FLAG_NOLIMIT); if (ret != RET_NOERROR) { return ret; } creature->getTile()->moveCreature(creature, toTile, !pushMove); return RET_NOERROR; } else if (Item* item = thing->getItem()) { return internalMoveItem(item->getParent(), toTile, INDEX_WHEREEVER, item, item->getItemCount(), nullptr, flags); } } return RET_NOTPOSSIBLE; } //Implementation of player invoked events void Game::playerMove(uint32_t playerId, Direction direction) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->resetIdleTime(); player->setNextWalkActionTask(nullptr); player->startAutoWalk(std::list<Direction> { direction }); } bool Game::playerBroadcastMessage(Player* player, const std::string& text) const { if (!player->hasFlag(PlayerFlag_CanBroadcast)) { return false; } std::cout << "> " << player->getName() << " broadcasted: \"" << text << "\"." << std::endl; for (const auto& it : players) { it.second->sendPrivateMessage(player, TALKTYPE_BROADCAST, text); } return true; } void Game::playerCreatePrivateChannel(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player || !player->isPremium()) { return; } ChatChannel* channel = g_chat.createChannel(*player, CHANNEL_PRIVATE); if (!channel || !channel->addUser(*player)) { return; } player->sendCreatePrivateChannel(channel->getId(), channel->getName()); } void Game::playerChannelInvite(uint32_t playerId, const std::string& name) { Player* player = getPlayerByID(playerId); if (!player) { return; } PrivateChatChannel* channel = g_chat.getPrivateChannel(*player); if (!channel) { return; } Player* invitePlayer = getPlayerByName(name); if (!invitePlayer) { return; } if (player == invitePlayer) { return; } channel->invitePlayer(*player, *invitePlayer); } void Game::playerChannelExclude(uint32_t playerId, const std::string& name) { Player* player = getPlayerByID(playerId); if (!player) { return; } PrivateChatChannel* channel = g_chat.getPrivateChannel(*player); if (!channel) { return; } Player* excludePlayer = getPlayerByName(name); if (!excludePlayer) { return; } if (player == excludePlayer) { return; } channel->excludePlayer(*player, *excludePlayer); } void Game::playerRequestChannels(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->sendChannelsDialog(); } void Game::playerOpenChannel(uint32_t playerId, uint16_t channelId) { Player* player = getPlayerByID(playerId); if (!player) { return; } ChatChannel* channel = g_chat.addUserToChannel(*player, channelId); if (!channel) { return; } const InvitedMap* invitedUsers = channel->getInvitedUsersPtr(); const UsersMap* users; if (!channel->isPublicChannel()) { users = &channel->getUsers(); } else { users = nullptr; } player->sendChannel(channel->getId(), channel->getName(), users, invitedUsers); } void Game::playerCloseChannel(uint32_t playerId, uint16_t channelId) { Player* player = getPlayerByID(playerId); if (!player) { return; } g_chat.removeUserFromChannel(*player, channelId); } void Game::playerOpenPrivateChannel(uint32_t playerId, std::string& receiver) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (!IOLoginData::formatPlayerName(receiver)) { player->sendCancel("A player with this name does not exist."); return; } player->sendOpenPrivateChannel(receiver); } void Game::playerCloseNpcChannel(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } SpectatorVec list; getSpectators(list, player->getPosition()); for (Creature* spectator : list) { if (Npc* npc = spectator->getNpc()) { npc->onPlayerCloseChannel(player); } } } void Game::playerReceivePing(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->receivePing(); } void Game::playerReceivePingBack(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->sendPingBack(); } void Game::playerAutoWalk(uint32_t playerId, const std::list<Direction>& listDir) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->resetIdleTime(); player->setNextWalkTask(nullptr); player->startAutoWalk(listDir); } void Game::playerStopAutoWalk(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->stopWalk(); } void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t fromStackPos, uint16_t fromSpriteId, const Position& toPos, uint8_t toStackPos, uint16_t toSpriteId, bool isHotkey) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (isHotkey && !g_config.getBoolean(ConfigManager::AIMBOT_HOTKEY_ENABLED)) { return; } Thing* thing = internalGetThing(player, fromPos, fromStackPos, fromSpriteId, STACKPOS_USEITEM); if (!thing) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } Item* item = thing->getItem(); if (!item || !item->isUseable() || item->getClientID() != fromSpriteId) { player->sendCancelMessage(RET_CANNOTUSETHISOBJECT); return; } Position walkToPos = fromPos; ReturnValue ret = g_actions->canUse(player, fromPos); if (ret == RET_NOERROR) { ret = g_actions->canUse(player, toPos, item); if (ret == RET_TOOFARAWAY) { walkToPos = toPos; } } if (ret != RET_NOERROR) { if (ret == RET_TOOFARAWAY) { Position itemPos = fromPos; uint8_t itemStackPos = fromStackPos; if (fromPos.x != 0xFFFF && toPos.x != 0xFFFF && Position::areInRange<1, 1, 0>(fromPos, player->getPosition()) && !Position::areInRange<1, 1, 0>(fromPos, toPos)) { Item* moveItem = nullptr; ret = internalMoveItem(item->getParent(), player, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem); if (ret != RET_NOERROR) { player->sendCancelMessage(ret); return; } //changing the position since its now in the inventory of the player internalGetPosition(moveItem, itemPos, itemStackPos); } std::list<Direction> listDir; if (player->getPathTo(walkToPos, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerUseItemEx, this, playerId, itemPos, itemStackPos, fromSpriteId, toPos, toStackPos, toSpriteId, isHotkey)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RET_THEREISNOWAY); } return; } player->sendCancelMessage(ret); return; } if (!player->canDoAction()) { uint32_t delay = player->getNextActionTime(); SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerUseItemEx, this, playerId, fromPos, fromStackPos, fromSpriteId, toPos, toStackPos, toSpriteId, isHotkey)); player->setNextActionTask(task); return; } player->resetIdleTime(); player->setNextActionTask(nullptr); g_actions->useItemEx(player, fromPos, toPos, toStackPos, item, isHotkey); } void Game::playerUseItem(uint32_t playerId, const Position& pos, uint8_t stackPos, uint8_t index, uint16_t spriteId, bool isHotkey) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (isHotkey && !g_config.getBoolean(ConfigManager::AIMBOT_HOTKEY_ENABLED)) { return; } Thing* thing = internalGetThing(player, pos, stackPos, spriteId, STACKPOS_USEITEM); if (!thing) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } Item* item = thing->getItem(); if (!item || item->isUseable() || item->getClientID() != spriteId) { player->sendCancelMessage(RET_CANNOTUSETHISOBJECT); return; } ReturnValue ret = g_actions->canUse(player, pos); if (ret != RET_NOERROR) { if (ret == RET_TOOFARAWAY) { std::list<Direction> listDir; if (player->getPathTo(pos, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerUseItem, this, playerId, pos, stackPos, index, spriteId, isHotkey)); player->setNextWalkActionTask(task); return; } ret = RET_THEREISNOWAY; } player->sendCancelMessage(ret); return; } if (!player->canDoAction()) { uint32_t delay = player->getNextActionTime(); SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerUseItem, this, playerId, pos, stackPos, index, spriteId, isHotkey)); player->setNextActionTask(task); return; } player->resetIdleTime(); player->setNextActionTask(nullptr); g_actions->useItem(player, pos, index, item, isHotkey); } void Game::playerUseWithCreature(uint32_t playerId, const Position& fromPos, uint8_t fromStackPos, uint32_t creatureId, uint16_t spriteId, bool isHotkey) { Player* player = getPlayerByID(playerId); if (!player) { return; } Creature* creature = getCreatureByID(creatureId); if (!creature) { return; } if (!Position::areInRange<7, 5, 0>(creature->getPosition(), player->getPosition())) { return; } if (!g_config.getBoolean(ConfigManager::AIMBOT_HOTKEY_ENABLED)) { if (creature->getPlayer() || isHotkey) { player->sendCancelMessage(RET_DIRECTPLAYERSHOOT); return; } } Thing* thing = internalGetThing(player, fromPos, fromStackPos, spriteId, STACKPOS_USEITEM); if (!thing) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } Item* item = thing->getItem(); if (!item || !item->isUseable() || item->getClientID() != spriteId) { player->sendCancelMessage(RET_CANNOTUSETHISOBJECT); return; } Position toPos = creature->getPosition(); Position walkToPos = fromPos; ReturnValue ret = g_actions->canUse(player, fromPos); if (ret == RET_NOERROR) { ret = g_actions->canUse(player, toPos, item); if (ret == RET_TOOFARAWAY) { walkToPos = toPos; } } if (ret != RET_NOERROR) { if (ret == RET_TOOFARAWAY) { Position itemPos = fromPos; uint8_t itemStackPos = fromStackPos; if (fromPos.x != 0xFFFF && Position::areInRange<1, 1, 0>(fromPos, player->getPosition()) && !Position::areInRange<1, 1, 0>(fromPos, toPos)) { Item* moveItem = nullptr; ret = internalMoveItem(item->getParent(), player, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem); if (ret != RET_NOERROR) { player->sendCancelMessage(ret); return; } //changing the position since its now in the inventory of the player internalGetPosition(moveItem, itemPos, itemStackPos); } std::list<Direction> listDir; if (player->getPathTo(walkToPos, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerUseWithCreature, this, playerId, itemPos, itemStackPos, creatureId, spriteId, isHotkey)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RET_THEREISNOWAY); } return; } player->sendCancelMessage(ret); return; } if (!player->canDoAction()) { uint32_t delay = player->getNextActionTime(); SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerUseWithCreature, this, playerId, fromPos, fromStackPos, creatureId, spriteId, isHotkey)); player->setNextActionTask(task); return; } player->resetIdleTime(); player->setNextActionTask(nullptr); g_actions->useItemEx(player, fromPos, creature->getPosition(), creature->getParent()->__getIndexOfThing(creature), item, isHotkey, creatureId); } void Game::playerCloseContainer(uint32_t playerId, uint8_t cid) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->closeContainer(cid); player->sendCloseContainer(cid); } void Game::playerMoveUpContainer(uint32_t playerId, uint8_t cid) { Player* player = getPlayerByID(playerId); if (!player) { return; } Container* container = player->getContainerByID(cid); if (!container) { return; } Container* parentContainer = dynamic_cast<Container*>(container->getRealParent()); if (!parentContainer) { Tile* tile = container->getTile(); if (!tile) { return; } auto it = browseFields.find(tile); if (it == browseFields.end()) { parentContainer = new Container(tile); parentContainer->useThing2(); browseFields[tile] = parentContainer; g_scheduler.addEvent(createSchedulerTask(30000, std::bind(&Game::decreaseBrowseFieldRef, this, tile->getPosition()))); } else { parentContainer = it->second; } } player->addContainer(cid, parentContainer); player->sendContainer(cid, parentContainer, parentContainer->hasParent(), player->getContainerIndex(cid)); } void Game::playerUpdateContainer(uint32_t playerId, uint8_t cid) { Player* player = getPlayerByID(playerId); if (!player) { return; } Container* container = player->getContainerByID(cid); if (!container) { return; } player->sendContainer(cid, container, container->hasParent(), player->getContainerIndex(cid)); } void Game::playerRotateItem(uint32_t playerId, const Position& pos, uint8_t stackPos, const uint16_t spriteId) { Player* player = getPlayerByID(playerId); if (!player) { return; } Thing* thing = internalGetThing(player, pos, stackPos); if (!thing) { return; } Item* item = thing->getItem(); if (!item || item->getClientID() != spriteId || !item->isRoteable() || item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } if (pos.x != 0xFFFF && !Position::areInRange<1, 1, 0>(pos, player->getPosition())) { std::list<Direction> listDir; if (player->getPathTo(pos, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerRotateItem, this, playerId, pos, stackPos, spriteId)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RET_THEREISNOWAY); } return; } uint16_t newId = Item::items[item->getID()].rotateTo; if (newId != 0) { transformItem(item, newId); } } void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std::string& text) { Player* player = getPlayerByID(playerId); if (!player) { return; } uint16_t maxTextLength = 0; uint32_t internalWindowTextId = 0; Item* writeItem = player->getWriteItem(internalWindowTextId, maxTextLength); if (text.length() > maxTextLength || windowTextId != internalWindowTextId) { return; } if (!writeItem || writeItem->isRemoved()) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } Cylinder* topParent = writeItem->getTopParent(); Player* owner = dynamic_cast<Player*>(topParent); if (owner && owner != player) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } if (!Position::areInRange<1, 1, 0>(writeItem->getPosition(), player->getPosition())) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } if (!g_events->eventPlayerOnTextEdit(player, writeItem, text)) { player->setWriteItem(nullptr); return; } if (!text.empty()) { if (writeItem->getText() != text) { writeItem->setText(text); writeItem->setWriter(player->getName()); writeItem->setDate(time(nullptr)); } } else { writeItem->resetText(); writeItem->resetWriter(); writeItem->resetDate(); } uint16_t newId = Item::items[writeItem->getID()].writeOnceItemId; if (newId != 0) { transformItem(writeItem, newId); } player->setWriteItem(nullptr); } void Game::playerBrowseField(uint32_t playerId, const Position& pos) { Player* player = getPlayerByID(playerId); if (!player) { return; } const Position& playerPos = player->getPosition(); if (playerPos.z != pos.z) { player->sendCancelMessage(playerPos.z > pos.z ? RET_FIRSTGOUPSTAIRS : RET_FIRSTGODOWNSTAIRS); return; } if (!Position::areInRange<1, 1>(playerPos, pos)) { std::list<Direction> listDir; if (player->getPathTo(pos, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); SchedulerTask* task = createSchedulerTask(400, std::bind( &Game::playerBrowseField, this, playerId, pos )); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RET_THEREISNOWAY); } return; } Tile* tile = getTile(pos); if (!tile) { return; } if (!g_events->eventPlayerOnBrowseField(player, pos)) { return; } Container* container; auto it = browseFields.find(tile); if (it == browseFields.end()) { container = new Container(tile); container->useThing2(); browseFields[tile] = container; g_scheduler.addEvent(createSchedulerTask(30000, std::bind(&Game::decreaseBrowseFieldRef, this, tile->getPosition()))); } else { container = it->second; } uint8_t dummyContainerId = 0xF - ((pos.x % 3) * 3 + (pos.y % 3)); Container* openContainer = player->getContainerByID(dummyContainerId); if (openContainer) { player->onCloseContainer(openContainer); player->closeContainer(dummyContainerId); } else { player->addContainer(dummyContainerId, container); player->sendContainer(dummyContainerId, container, false, 0); } } void Game::playerSeekInContainer(uint32_t playerId, uint8_t containerId, uint16_t index) { Player* player = getPlayerByID(playerId); if (!player) { return; } Container* container = player->getContainerByID(containerId); if (!container || !container->hasPagination()) { return; } if ((index % container->capacity()) != 0 || index >= container->size()) { return; } player->setContainerIndex(containerId, index); player->sendContainer(containerId, container, false, index); } void Game::playerUpdateHouseWindow(uint32_t playerId, uint8_t listId, uint32_t windowTextId, const std::string& text) { Player* player = getPlayerByID(playerId); if (!player) { return; } uint32_t internalWindowTextId; uint32_t internalListId; House* house = player->getEditHouse(internalWindowTextId, internalListId); if (house && internalWindowTextId == windowTextId && listId == 0) { house->setAccessList(internalListId, text); player->setEditHouse(nullptr); } } void Game::playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t stackPos, uint32_t tradePlayerId, uint16_t spriteId) { Player* player = getPlayerByID(playerId); if (!player) { return; } Player* tradePartner = getPlayerByID(tradePlayerId); if (!tradePartner || tradePartner == player) { player->sendTextMessage(MESSAGE_INFO_DESCR, "Sorry, not possible."); return; } if (!Position::areInRange<2, 2, 0>(tradePartner->getPosition(), player->getPosition())) { std::ostringstream ss; ss << tradePartner->getName() << " tells you to move closer."; player->sendTextMessage(MESSAGE_INFO_DESCR, ss.str()); return; } if (!canThrowObjectTo(tradePartner->getPosition(), player->getPosition())) { player->sendCancelMessage(RET_CREATUREISNOTREACHABLE); return; } Item* tradeItem = dynamic_cast<Item*>(internalGetThing(player, pos, stackPos, spriteId, STACKPOS_USE)); if (!tradeItem || tradeItem->getClientID() != spriteId || !tradeItem->isPickupable() || tradeItem->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } const Position& playerPosition = player->getPosition(); const Position& tradeItemPosition = tradeItem->getPosition(); if (playerPosition.z != tradeItemPosition.z) { player->sendCancelMessage(playerPosition.z > tradeItemPosition.z ? RET_FIRSTGOUPSTAIRS : RET_FIRSTGODOWNSTAIRS); return; } if (!Position::areInRange<1, 1>(tradeItemPosition, playerPosition)) { std::list<Direction> listDir; if (player->getPathTo(pos, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerRequestTrade, this, playerId, pos, stackPos, tradePlayerId, spriteId)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RET_THEREISNOWAY); } return; } Container* tradeItemContainer = tradeItem->getContainer(); if (tradeItemContainer) { for (const auto& it : tradeItems) { Item* item = it.first; if (tradeItem == item) { player->sendTextMessage(MESSAGE_INFO_DESCR, "This item is already being traded."); return; } if (tradeItemContainer->isHoldingItem(item)) { player->sendTextMessage(MESSAGE_INFO_DESCR, "This item is already being traded."); return; } Container* container = item->getContainer(); if (container && container->isHoldingItem(tradeItem)) { player->sendTextMessage(MESSAGE_INFO_DESCR, "This item is already being traded."); return; } } } else { for (const auto& it : tradeItems) { Item* item = it.first; if (tradeItem == item) { player->sendTextMessage(MESSAGE_INFO_DESCR, "This item is already being traded."); return; } Container* container = item->getContainer(); if (container && container->isHoldingItem(tradeItem)) { player->sendTextMessage(MESSAGE_INFO_DESCR, "This item is already being traded."); return; } } } Container* tradeContainer = tradeItem->getContainer(); if (tradeContainer && tradeContainer->getItemHoldingCount() + 1 > 100) { player->sendTextMessage(MESSAGE_INFO_DESCR, "You can not trade more than 100 items."); return; } if (!g_events->eventPlayerOnTradeRequest(player, tradePartner, tradeItem)) { return; } internalStartTrade(player, tradePartner, tradeItem); } bool Game::internalStartTrade(Player* player, Player* tradePartner, Item* tradeItem) { if (player->tradeState != TRADE_NONE && !(player->tradeState == TRADE_ACKNOWLEDGE && player->tradePartner == tradePartner)) { player->sendCancelMessage(RET_YOUAREALREADYTRADING); return false; } else if (tradePartner->tradeState != TRADE_NONE && tradePartner->tradePartner != player) { player->sendCancelMessage(RET_THISPLAYERISALREADYTRADING); return false; } player->tradePartner = tradePartner; player->tradeItem = tradeItem; player->tradeState = TRADE_INITIATED; tradeItem->useThing2(); tradeItems[tradeItem] = player->getID(); player->sendTradeItemRequest(player, tradeItem, true); if (tradePartner->tradeState == TRADE_NONE) { std::ostringstream ss; ss << player->getName() << " wants to trade with you."; tradePartner->sendTextMessage(MESSAGE_EVENT_ADVANCE, ss.str()); tradePartner->tradeState = TRADE_ACKNOWLEDGE; tradePartner->tradePartner = player; } else { Item* counterOfferItem = tradePartner->tradeItem; player->sendTradeItemRequest(tradePartner, counterOfferItem, false); tradePartner->sendTradeItemRequest(player, tradeItem, false); } return true; } void Game::playerAcceptTrade(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (!(player->getTradeState() == TRADE_ACKNOWLEDGE || player->getTradeState() == TRADE_INITIATED)) { return; } Player* tradePartner = player->tradePartner; if (!tradePartner) { return; } if (!canThrowObjectTo(tradePartner->getPosition(), player->getPosition())) { player->sendCancelMessage(RET_CREATUREISNOTREACHABLE); return; } player->setTradeState(TRADE_ACCEPT); if (tradePartner->getTradeState() == TRADE_ACCEPT) { Item* tradeItem1 = player->tradeItem; Item* tradeItem2 = tradePartner->tradeItem; player->setTradeState(TRADE_TRANSFER); tradePartner->setTradeState(TRADE_TRANSFER); std::map<Item*, uint32_t>::iterator it = tradeItems.find(tradeItem1); if (it != tradeItems.end()) { ReleaseItem(it->first); tradeItems.erase(it); } it = tradeItems.find(tradeItem2); if (it != tradeItems.end()) { ReleaseItem(it->first); tradeItems.erase(it); } bool isSuccess = false; ReturnValue ret1 = internalAddItem(tradePartner, tradeItem1, INDEX_WHEREEVER, 0, true); ReturnValue ret2 = internalAddItem(player, tradeItem2, INDEX_WHEREEVER, 0, true); if (ret1 == RET_NOERROR && ret2 == RET_NOERROR) { ret1 = internalRemoveItem(tradeItem1, tradeItem1->getItemCount(), true); ret2 = internalRemoveItem(tradeItem2, tradeItem2->getItemCount(), true); if (ret1 == RET_NOERROR && ret2 == RET_NOERROR) { Cylinder* cylinder1 = tradeItem1->getParent(); Cylinder* cylinder2 = tradeItem2->getParent(); uint32_t count1 = tradeItem1->getItemCount(); uint32_t count2 = tradeItem2->getItemCount(); ret1 = internalMoveItem(cylinder1, tradePartner, INDEX_WHEREEVER, tradeItem1, count1, nullptr, FLAG_IGNOREAUTOSTACK, nullptr, tradeItem2); if (ret1 == RET_NOERROR) { internalMoveItem(cylinder2, player, INDEX_WHEREEVER, tradeItem2, count2, nullptr, FLAG_IGNOREAUTOSTACK); tradeItem1->onTradeEvent(ON_TRADE_TRANSFER, tradePartner); tradeItem2->onTradeEvent(ON_TRADE_TRANSFER, player); isSuccess = true; } } } if (!isSuccess) { std::string errorDescription; if (tradePartner->tradeItem) { errorDescription = getTradeErrorDescription(ret1, tradeItem1); tradePartner->sendTextMessage(MESSAGE_EVENT_ADVANCE, errorDescription); tradePartner->tradeItem->onTradeEvent(ON_TRADE_CANCEL, tradePartner); } if (player->tradeItem) { errorDescription = getTradeErrorDescription(ret2, tradeItem2); player->sendTextMessage(MESSAGE_EVENT_ADVANCE, errorDescription); player->tradeItem->onTradeEvent(ON_TRADE_CANCEL, player); } } player->setTradeState(TRADE_NONE); player->tradeItem = nullptr; player->tradePartner = nullptr; player->sendTradeClose(); tradePartner->setTradeState(TRADE_NONE); tradePartner->tradeItem = nullptr; tradePartner->tradePartner = nullptr; tradePartner->sendTradeClose(); } } std::string Game::getTradeErrorDescription(ReturnValue ret, Item* item) { if (item) { if (ret == RET_NOTENOUGHCAPACITY) { std::ostringstream ss; ss << "You do not have enough capacity to carry"; if (item->isStackable() && item->getItemCount() > 1) { ss << " these objects."; } else { ss << " this object."; } ss << std::endl << ' ' << item->getWeightDescription(); return ss.str(); } else if (ret == RET_NOTENOUGHROOM || ret == RET_CONTAINERNOTENOUGHROOM) { std::ostringstream ss; ss << "You do not have enough room to carry"; if (item->isStackable() && item->getItemCount() > 1) { ss << " these objects."; } else { ss << " this object."; } return ss.str(); } } return "Trade could not be completed."; } void Game::playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t index) { Player* player = getPlayerByID(playerId); if (!player) { return; } Player* tradePartner = player->tradePartner; if (!tradePartner) { return; } Item* tradeItem; if (lookAtCounterOffer) { tradeItem = tradePartner->getTradeItem(); } else { tradeItem = player->getTradeItem(); } if (!tradeItem) { return; } const Position& playerPosition = player->getPosition(); const Position& tradeItemPosition = tradeItem->getPosition(); int32_t lookDistance = std::max<int32_t>(Position::getDistanceX(playerPosition, tradeItemPosition), Position::getDistanceY(playerPosition, tradeItemPosition)); if (index == 0) { g_events->eventPlayerOnLookInTrade(player, tradePartner, tradeItem, lookDistance); return; } Container* tradeContainer = tradeItem->getContainer(); if (!tradeContainer) { return; } std::vector<const Container*> containers {tradeContainer}; size_t i = 0; while (i < containers.size()) { const Container* container = containers[i++]; for (Item* item : container->getItemList()) { Container* tmpContainer = item->getContainer(); if (tmpContainer) { containers.push_back(tmpContainer); } if (--index == 0) { g_events->eventPlayerOnLookInTrade(player, tradePartner, item, lookDistance); return; } } } } void Game::playerCloseTrade(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } internalCloseTrade(player); } bool Game::internalCloseTrade(Player* player) { Player* tradePartner = player->tradePartner; if ((tradePartner && tradePartner->getTradeState() == TRADE_TRANSFER) || player->getTradeState() == TRADE_TRANSFER) { return true; } if (player->getTradeItem()) { std::map<Item*, uint32_t>::iterator it = tradeItems.find(player->getTradeItem()); if (it != tradeItems.end()) { ReleaseItem(it->first); tradeItems.erase(it); } player->tradeItem->onTradeEvent(ON_TRADE_CANCEL, player); player->tradeItem = nullptr; } player->setTradeState(TRADE_NONE); player->tradePartner = nullptr; player->sendTextMessage(MESSAGE_STATUS_SMALL, "Trade cancelled."); player->sendTradeClose(); if (tradePartner) { if (tradePartner->getTradeItem()) { std::map<Item*, uint32_t>::iterator it = tradeItems.find(tradePartner->getTradeItem()); if (it != tradeItems.end()) { ReleaseItem(it->first); tradeItems.erase(it); } tradePartner->tradeItem->onTradeEvent(ON_TRADE_CANCEL, tradePartner); tradePartner->tradeItem = nullptr; } tradePartner->setTradeState(TRADE_NONE); tradePartner->tradePartner = nullptr; tradePartner->sendTextMessage(MESSAGE_STATUS_SMALL, "Trade cancelled."); tradePartner->sendTradeClose(); } return true; } void Game::playerPurchaseItem(uint32_t playerId, uint16_t spriteId, uint8_t count, uint8_t amount, bool ignoreCap/* = false*/, bool inBackpacks/* = false*/) { if (amount == 0 || amount > 100) { return; } Player* player = getPlayerByID(playerId); if (!player) { return; } int32_t onBuy, onSell; Npc* merchant = player->getShopOwner(onBuy, onSell); if (!merchant) { return; } const ItemType& it = Item::items.getItemIdByClientId(spriteId); if (it.id == 0) { return; } uint8_t subType; if (it.isSplash() || it.isFluidContainer()) { subType = clientFluidToServer(count); } else { subType = count; } if (!player->hasShopItemForSale(it.id, subType)) { return; } merchant->onPlayerTrade(player, onBuy, it.id, subType, amount, ignoreCap, inBackpacks); } void Game::playerSellItem(uint32_t playerId, uint16_t spriteId, uint8_t count, uint8_t amount, bool ignoreEquipped) { if (amount == 0 || amount > 100) { return; } Player* player = getPlayerByID(playerId); if (!player) { return; } int32_t onBuy, onSell; Npc* merchant = player->getShopOwner(onBuy, onSell); if (!merchant) { return; } const ItemType& it = Item::items.getItemIdByClientId(spriteId); if (it.id == 0) { return; } uint8_t subType; if (it.isSplash() || it.isFluidContainer()) { subType = clientFluidToServer(count); } else { subType = count; } merchant->onPlayerTrade(player, onSell, it.id, subType, amount, ignoreEquipped); } void Game::playerCloseShop(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->closeShopWindow(); } void Game::playerLookInShop(uint32_t playerId, uint16_t spriteId, uint8_t count) { Player* player = getPlayerByID(playerId); if (!player) { return; } int32_t onBuy, onSell; Npc* merchant = player->getShopOwner(onBuy, onSell); if (!merchant) { return; } const ItemType& it = Item::items.getItemIdByClientId(spriteId); if (it.id == 0) { return; } int32_t subType; if (it.isFluidContainer() || it.isSplash()) { subType = clientFluidToServer(count); } else { subType = count; } if (!player->hasShopItemForSale(it.id, subType)) { return; } if (!g_events->eventPlayerOnLookInShop(player, &it, subType)) { return; } std::ostringstream ss; ss << "You see " << Item::getDescription(it, 1, nullptr, subType); player->sendTextMessage(MESSAGE_INFO_DESCR, ss.str()); } void Game::playerLookAt(uint32_t playerId, const Position& pos, uint16_t spriteId, uint8_t stackPos) { Player* player = getPlayerByID(playerId); if (!player) { return; } Thing* thing = internalGetThing(player, pos, stackPos, spriteId, STACKPOS_LOOK); if (!thing) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } Position thingPos = thing->getPosition(); if (!player->canSee(thingPos)) { player->sendCancelMessage(RET_NOTPOSSIBLE); return; } Position playerPos = player->getPosition(); int32_t lookDistance; if (thing != player) { lookDistance = std::max<int32_t>(Position::getDistanceX(playerPos, thingPos), Position::getDistanceY(playerPos, thingPos)); if (playerPos.z != thingPos.z) { lookDistance += 15; } } else { lookDistance = -1; } g_events->eventPlayerOnLook(player, pos, thing, stackPos, lookDistance); } void Game::playerLookInBattleList(uint32_t playerId, uint32_t creatureId) { Player* player = getPlayerByID(playerId); if (!player) { return; } Creature* creature = getCreatureByID(creatureId); if (!creature) { return; } if (!player->canSeeCreature(creature)) { return; } const Position& creaturePos = creature->getPosition(); if (!player->canSee(creaturePos)) { return; } int32_t lookDistance; if (creature != player) { const Position& playerPos = player->getPosition(); lookDistance = std::max<int32_t>(Position::getDistanceX(playerPos, creaturePos), Position::getDistanceY(playerPos, creaturePos)); if (playerPos.z != creaturePos.z) { lookDistance += 15; } } else { lookDistance = -1; } g_events->eventPlayerOnLookInBattleList(player, creature, lookDistance); } void Game::playerCancelAttackAndFollow(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } playerSetAttackedCreature(playerId, 0); playerFollowCreature(playerId, 0); player->stopWalk(); } void Game::playerSetAttackedCreature(uint32_t playerId, uint32_t creatureId) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (player->getAttackedCreature() && creatureId == 0) { player->setAttackedCreature(nullptr); player->sendCancelTarget(); return; } Creature* attackCreature = getCreatureByID(creatureId); if (!attackCreature) { player->setAttackedCreature(nullptr); player->sendCancelTarget(); return; } ReturnValue ret = Combat::canTargetCreature(player, attackCreature); if (ret != RET_NOERROR) { player->sendCancelMessage(ret); player->sendCancelTarget(); player->setAttackedCreature(nullptr); return; } player->setAttackedCreature(attackCreature); g_dispatcher.addTask(createTask(std::bind(&Game::updateCreatureWalk, this, player->getID()))); } void Game::playerFollowCreature(uint32_t playerId, uint32_t creatureId) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->setAttackedCreature(nullptr); g_dispatcher.addTask(createTask(std::bind(&Game::updateCreatureWalk, this, player->getID()))); player->setFollowCreature(getCreatureByID(creatureId)); } void Game::playerSetFightModes(uint32_t playerId, fightMode_t fightMode, chaseMode_t chaseMode, secureMode_t secureMode) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->setFightMode(fightMode); player->setChaseMode(chaseMode); player->setSecureMode(secureMode); } void Game::playerRequestAddVip(uint32_t playerId, const std::string& name) { if (name.length() > 20) { return; } Player* player = getPlayerByID(playerId); if (!player) { return; } Player* vipPlayer = getPlayerByName(name); if (!vipPlayer) { uint32_t guid; bool specialVip; std::string formattedName = name; if (!IOLoginData::getGuidByNameEx(guid, specialVip, formattedName)) { player->sendTextMessage(MESSAGE_STATUS_SMALL, "A player with this name does not exist."); return; } if (specialVip && !player->hasFlag(PlayerFlag_SpecialVIP)) { player->sendTextMessage(MESSAGE_STATUS_SMALL, "You can not add this player."); return; } player->addVIP(guid, formattedName, VIPSTATUS_OFFLINE); } else { if (vipPlayer->hasFlag(PlayerFlag_SpecialVIP) && !player->hasFlag(PlayerFlag_SpecialVIP)) { player->sendTextMessage(MESSAGE_STATUS_SMALL, "You can not add this player."); return; } if (!vipPlayer->isInGhostMode() || player->isAccessPlayer()) { player->addVIP(vipPlayer->getGUID(), vipPlayer->getName(), VIPSTATUS_ONLINE); } else { player->addVIP(vipPlayer->getGUID(), vipPlayer->getName(), VIPSTATUS_OFFLINE); } } } void Game::playerRequestRemoveVip(uint32_t playerId, uint32_t guid) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->removeVIP(guid); } void Game::playerRequestEditVip(uint32_t playerId, uint32_t guid, const std::string& description, uint32_t icon, bool notify) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->editVIP(guid, description, icon, notify); } void Game::playerTurn(uint32_t playerId, Direction dir) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (!g_events->eventPlayerOnTurn(player, dir)) { return; } player->resetIdleTime(); internalCreatureTurn(player, dir); } void Game::playerRequestOutfit(uint32_t playerId) { if (!g_config.getBoolean(ConfigManager::ALLOW_CHANGEOUTFIT)) { return; } Player* player = getPlayerByID(playerId); if (!player) { return; } player->sendOutfitWindow(); } void Game::playerToggleMount(uint32_t playerId, bool mount) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->toggleMount(mount); } void Game::playerChangeOutfit(uint32_t playerId, Outfit_t outfit) { if (!g_config.getBoolean(ConfigManager::ALLOW_CHANGEOUTFIT)) { return; } Player* player = getPlayerByID(playerId); if (!player) { return; } if (!player->hasRequestedOutfit()) { return; } player->hasRequestedOutfit(false); if (outfit.lookMount != 0) { Mount* mount = Mounts::getInstance()->getMountByClientID(outfit.lookMount); if (!mount) { return; } if (!player->hasMount(mount)) { return; } if (player->isMounted()) { Mount* prevMount = Mounts::getInstance()->getMountByID(player->getCurrentMount()); if (prevMount) { changeSpeed(player, mount->speed - prevMount->speed); } player->setCurrentMount(mount->id); } else { player->setCurrentMount(mount->id); outfit.lookMount = 0; } } else if (player->isMounted()) { player->dismount(); } if (player->canWear(outfit.lookType, outfit.lookAddons)) { player->defaultOutfit = outfit; if (player->hasCondition(CONDITION_OUTFIT)) { return; } internalCreatureChangeOutfit(player, outfit); } } void Game::playerShowQuestLog(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->sendQuestLog(); } void Game::playerShowQuestLine(uint32_t playerId, uint16_t questId) { Player* player = getPlayerByID(playerId); if (!player) { return; } Quest* quest = Quests::getInstance()->getQuestByID(questId); if (!quest) { return; } player->sendQuestLine(quest); } void Game::playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, const std::string& receiver, const std::string& text) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->resetIdleTime(); uint32_t muteTime = player->isMuted(); if (muteTime > 0) { std::ostringstream ss; ss << "You are still muted for " << muteTime << " seconds."; player->sendTextMessage(MESSAGE_STATUS_SMALL, ss.str()); return; } if (playerSayCommand(player, text)) { return; } if (playerSaySpell(player, type, text)) { return; } if (!text.empty() && text.front() == '/' && player->isAccessPlayer()) { return; } if (type != TALKTYPE_PRIVATE_PN) { player->removeMessageBuffer(); } switch (type) { case TALKTYPE_SAY: internalCreatureSay(player, TALKTYPE_SAY, text, false); break; case TALKTYPE_WHISPER: playerWhisper(player, text); break; case TALKTYPE_YELL: playerYell(player, text); break; case TALKTYPE_PRIVATE_TO: case TALKTYPE_PRIVATE_RED_TO: playerSpeakTo(player, type, receiver, text); break; case TALKTYPE_CHANNEL_O: case TALKTYPE_CHANNEL_Y: case TALKTYPE_CHANNEL_R1: g_chat.talkToChannel(*player, type, text, channelId); break; case TALKTYPE_PRIVATE_PN: playerSpeakToNpc(player, text); break; case TALKTYPE_BROADCAST: playerBroadcastMessage(player, text); break; default: break; } } bool Game::playerSayCommand(Player* player, const std::string& text) { if (text.empty()) { return false; } char firstCharacter = text.front(); for (char commandTag : commandTags) { if (commandTag == firstCharacter) { if (commands.exeCommand(*player, text)) { return true; } } } return false; } bool Game::playerSaySpell(Player* player, SpeakClasses type, const std::string& text) { std::string words = text; TalkActionResult_t result = g_talkActions->playerSaySpell(player, type, words); if (result == TALKACTION_BREAK) { return true; } result = g_spells->playerSaySpell(player, words); if (result == TALKACTION_BREAK) { if (!g_config.getBoolean(ConfigManager::EMOTE_SPELLS)) { return internalCreatureSay(player, TALKTYPE_SAY, words, false); } else { return internalCreatureSay(player, TALKTYPE_MONSTER_SAY, words, false); } } else if (result == TALKACTION_FAILED) { return true; } return false; } bool Game::playerWhisper(Player* player, const std::string& text) { SpectatorVec list; getSpectators(list, player->getPosition(), false, false, Map::maxClientViewportX, Map::maxClientViewportX, Map::maxClientViewportY, Map::maxClientViewportY); //send to client for (Creature* spectator : list) { if (Player* spectatorPlayer = spectator->getPlayer()) { if (!Position::areInRange<1, 1>(player->getPosition(), spectatorPlayer->getPosition())) { spectatorPlayer->sendCreatureSay(player, TALKTYPE_WHISPER, "pspsps"); } else { spectatorPlayer->sendCreatureSay(player, TALKTYPE_WHISPER, text); } } } //event method for (Creature* spectator : list) { spectator->onCreatureSay(player, TALKTYPE_WHISPER, text); } return true; } bool Game::playerYell(Player* player, const std::string& text) { if (player->getLevel() == 1) { player->sendTextMessage(MESSAGE_STATUS_SMALL, "You may not yell as long as you are on level 1."); return false; } if (player->hasCondition(CONDITION_YELLTICKS)) { player->sendCancelMessage(RET_YOUAREEXHAUSTED); return false; } if (player->getAccountType() < ACCOUNT_TYPE_GAMEMASTER) { Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_YELLTICKS, 30000, 0); player->addCondition(condition); } internalCreatureSay(player, TALKTYPE_YELL, asUpperCaseString(text), false); return true; } bool Game::playerSpeakTo(Player* player, SpeakClasses type, const std::string& receiver, const std::string& text) { Player* toPlayer = getPlayerByName(receiver); if (!toPlayer) { player->sendTextMessage(MESSAGE_STATUS_SMALL, "A player with this name is not online."); return false; } if (type == TALKTYPE_PRIVATE_RED_TO && (player->hasFlag(PlayerFlag_CanTalkRedPrivate) || player->getAccountType() >= ACCOUNT_TYPE_GAMEMASTER)) { type = TALKTYPE_PRIVATE_RED_FROM; } else { type = TALKTYPE_PRIVATE_FROM; } toPlayer->sendPrivateMessage(player, type, text); toPlayer->onCreatureSay(player, type, text); if (toPlayer->isInGhostMode() && !player->isAccessPlayer()) { player->sendTextMessage(MESSAGE_STATUS_SMALL, "A player with this name is not online."); } else { std::ostringstream ss; ss << "Message sent to " << toPlayer->getName() << '.'; player->sendTextMessage(MESSAGE_STATUS_SMALL, ss.str()); } return true; } bool Game::playerSpeakToNpc(Player* player, const std::string& text) { SpectatorVec list; getSpectators(list, player->getPosition()); for (Creature* spectator : list) { if (spectator->getNpc()) { spectator->onCreatureSay(player, TALKTYPE_PRIVATE_PN, text); } } return true; } //-- bool Game::canThrowObjectTo(const Position& fromPos, const Position& toPos, bool checkLineOfSight /*= true*/, int32_t rangex /*= Map::maxClientViewportX*/, int32_t rangey /*= Map::maxClientViewportY*/) const { return map.canThrowObjectTo(fromPos, toPos, checkLineOfSight, rangex, rangey); } bool Game::isSightClear(const Position& fromPos, const Position& toPos, bool floorCheck) const { return map.isSightClear(fromPos, toPos, floorCheck); } bool Game::internalCreatureTurn(Creature* creature, Direction dir) { if (creature->getDirection() == dir) { return false; } creature->setDirection(dir); //send to client SpectatorVec list; getSpectators(list, creature->getPosition(), true, true); for (Creature* spectator : list) { spectator->getPlayer()->sendCreatureTurn(creature); } return true; } bool Game::internalCreatureSay(Creature* creature, SpeakClasses type, const std::string& text, bool ghostMode, SpectatorVec* listPtr/* = nullptr*/, const Position* pos/* = nullptr*/) { if (text.empty()) { return false; } if (!pos) { pos = &creature->getPosition(); } SpectatorVec list; if (!listPtr || listPtr->empty()) { // This somewhat complex construct ensures that the cached SpectatorVec // is used if available and if it can be used, else a local vector is // used (hopefully the compiler will optimize away the construction of // the temporary when it's not used). if (type != TALKTYPE_YELL && type != TALKTYPE_MONSTER_YELL) { getSpectators(list, *pos, false, false, Map::maxClientViewportX, Map::maxClientViewportX, Map::maxClientViewportY, Map::maxClientViewportY); } else { getSpectators(list, *pos, true, false, 18, 18, 14, 14); } } else { list = (*listPtr); } //send to client for (Creature* spectator : list) { if (Player* tmpPlayer = spectator->getPlayer()) { if (!ghostMode || tmpPlayer->canSeeCreature(creature)) { tmpPlayer->sendCreatureSay(creature, type, text, pos); } } } //event method for (Creature* spectator : list) { spectator->onCreatureSay(creature, type, text); if (creature != spectator) { g_events->eventCreatureOnHear(spectator, creature, text, type, creature->getPosition()); } } return true; } void Game::checkCreatureWalk(uint32_t creatureId) { Creature* creature = getCreatureByID(creatureId); if (creature && creature->getHealth() > 0) { creature->onWalk(); cleanup(); } } void Game::updateCreatureWalk(uint32_t creatureId) { Creature* creature = getCreatureByID(creatureId); if (creature && creature->getHealth() > 0) { creature->goToFollowCreature(); } } void Game::checkCreatureAttack(uint32_t creatureId) { Creature* creature = getCreatureByID(creatureId); if (creature && creature->getHealth() > 0) { creature->onAttacking(0); } } void Game::addCreatureCheck(Creature* creature) { creature->creatureCheck = true; if (creature->inCheckCreaturesVector) { // already in a vector return; } creature->inCheckCreaturesVector = true; checkCreatureLists[uniform_random(0, EVENT_CREATURECOUNT - 1)].push_back(creature); creature->useThing2(); } void Game::removeCreatureCheck(Creature* creature) { if (creature->inCheckCreaturesVector) { creature->creatureCheck = false; } } void Game::checkCreatures(size_t index) { g_scheduler.addEvent(createSchedulerTask(EVENT_CHECK_CREATURE_INTERVAL, std::bind(&Game::checkCreatures, this, (index + 1) % EVENT_CREATURECOUNT))); auto& checkCreatureList = checkCreatureLists[index]; for (auto it = checkCreatureList.begin(), end = checkCreatureList.end(); it != end;) { Creature* creature = *it; if (creature->creatureCheck) { if (creature->getHealth() > 0) { creature->onThink(EVENT_CREATURE_THINK_INTERVAL); creature->onAttacking(EVENT_CREATURE_THINK_INTERVAL); creature->executeConditions(EVENT_CREATURE_THINK_INTERVAL); } else { creature->onDeath(); } ++it; } else { creature->inCheckCreaturesVector = false; it = checkCreatureList.erase(it); ReleaseCreature(creature); } } cleanup(); } void Game::changeSpeed(Creature* creature, int32_t varSpeedDelta) { int32_t varSpeed = creature->getSpeed() - creature->getBaseSpeed(); varSpeed += varSpeedDelta; creature->setSpeed(varSpeed); //send to clients SpectatorVec list; getSpectators(list, creature->getPosition(), false, true); for (Creature* spectator : list) { spectator->getPlayer()->sendChangeSpeed(creature, creature->getStepSpeed()); } } void Game::internalCreatureChangeOutfit(Creature* creature, const Outfit_t& outfit) { if (!g_events->eventCreatureOnChangeOutfit(creature, outfit, creature->getCurrentOutfit())) { return; } creature->setCurrentOutfit(outfit); if (creature->isInvisible()) { return; } //send to clients SpectatorVec list; getSpectators(list, creature->getPosition(), true, true); for (Creature* spectator : list) { spectator->getPlayer()->sendCreatureChangeOutfit(creature, outfit); } } void Game::internalCreatureChangeVisible(Creature* creature, bool visible) { //send to clients SpectatorVec list; getSpectators(list, creature->getPosition(), true, true); for (Creature* spectator : list) { spectator->getPlayer()->sendCreatureChangeVisible(creature, visible); } } void Game::changeLight(const Creature* creature) { //send to clients SpectatorVec list; getSpectators(list, creature->getPosition(), true, true); for (Creature* spectator : list) { spectator->getPlayer()->sendCreatureLight(creature); } } bool Game::combatBlockHit(CombatType_t combatType, Creature* attacker, Creature* target, int32_t& healthChange, bool checkDefense, bool checkArmor, bool field) { if (combatType == COMBAT_NONE) { return true; } if (target->getPlayer() && target->getPlayer()->isInGhostMode()) { return true; } if (healthChange > 0) { return false; } const Position& targetPos = target->getPosition(); SpectatorVec list; getSpectators(list, targetPos, false, true); if (!target->isAttackable() || Combat::canDoCombat(attacker, target) != RET_NOERROR) { if (!target->isInGhostMode()) { addMagicEffect(list, targetPos, CONST_ME_POFF); } return true; } int32_t damage = -healthChange; BlockType_t blockType = target->blockHit(attacker, combatType, damage, checkDefense, checkArmor, field); healthChange = -damage; if (blockType == BLOCK_DEFENSE) { addMagicEffect(list, targetPos, CONST_ME_POFF); return true; } else if (blockType == BLOCK_ARMOR) { addMagicEffect(list, targetPos, CONST_ME_BLOCKHIT); return true; } else if (blockType == BLOCK_IMMUNITY) { uint8_t hitEffect = 0; switch (combatType) { case COMBAT_UNDEFINEDDAMAGE: break; case COMBAT_ENERGYDAMAGE: case COMBAT_FIREDAMAGE: case COMBAT_PHYSICALDAMAGE: case COMBAT_ICEDAMAGE: case COMBAT_DEATHDAMAGE: { hitEffect = CONST_ME_BLOCKHIT; break; } case COMBAT_EARTHDAMAGE: { hitEffect = CONST_ME_GREEN_RINGS; break; } case COMBAT_HOLYDAMAGE: { hitEffect = CONST_ME_HOLYDAMAGE; break; } default: { hitEffect = CONST_ME_POFF; break; } } addMagicEffect(list, targetPos, hitEffect); return true; } return false; } void Game::combatGetTypeInfo(CombatType_t combatType, Creature* target, TextColor_t& color, uint8_t& effect) { switch (combatType) { case COMBAT_PHYSICALDAMAGE: { Item* splash = nullptr; switch (target->getRace()) { case RACE_VENOM: color = TEXTCOLOR_LIGHTGREEN; effect = CONST_ME_HITBYPOISON; splash = Item::CreateItem(ITEM_SMALLSPLASH, FLUID_GREEN); break; case RACE_BLOOD: color = TEXTCOLOR_RED; effect = CONST_ME_DRAWBLOOD; splash = Item::CreateItem(ITEM_SMALLSPLASH, FLUID_BLOOD); break; case RACE_UNDEAD: color = TEXTCOLOR_LIGHTGREY; effect = CONST_ME_HITAREA; break; case RACE_FIRE: color = TEXTCOLOR_ORANGE; effect = CONST_ME_DRAWBLOOD; break; case RACE_ENERGY: color = TEXTCOLOR_PURPLE; effect = CONST_ME_ENERGYHIT; break; default: color = TEXTCOLOR_NONE; effect = CONST_ME_NONE; break; } if (splash) { internalAddItem(target->getTile(), splash, INDEX_WHEREEVER, FLAG_NOLIMIT); startDecay(splash); } break; } case COMBAT_ENERGYDAMAGE: { color = TEXTCOLOR_PURPLE; effect = CONST_ME_ENERGYHIT; break; } case COMBAT_EARTHDAMAGE: { color = TEXTCOLOR_LIGHTGREEN; effect = CONST_ME_GREEN_RINGS; break; } case COMBAT_DROWNDAMAGE: { color = TEXTCOLOR_LIGHTBLUE; effect = CONST_ME_LOSEENERGY; break; } case COMBAT_FIREDAMAGE: { color = TEXTCOLOR_ORANGE; effect = CONST_ME_HITBYFIRE; break; } case COMBAT_ICEDAMAGE: { color = TEXTCOLOR_SKYBLUE; effect = CONST_ME_ICEATTACK; break; } case COMBAT_HOLYDAMAGE: { color = TEXTCOLOR_YELLOW; effect = CONST_ME_HOLYDAMAGE; break; } case COMBAT_DEATHDAMAGE: { color = TEXTCOLOR_DARKRED; effect = CONST_ME_SMALLCLOUDS; break; } case COMBAT_LIFEDRAIN: { color = TEXTCOLOR_RED; effect = CONST_ME_MAGIC_RED; break; } default: { color = TEXTCOLOR_NONE; effect = CONST_ME_NONE; break; } } } bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage& damage) { const Position& targetPos = target->getPosition(); if (damage.primary.value > 0) { if (target->getHealth() <= 0) { return false; } Player* attackerPlayer; if (attacker) { attackerPlayer = attacker->getPlayer(); } else { attackerPlayer = nullptr; } Player* targetPlayer = target->getPlayer(); if (attackerPlayer && targetPlayer) { if (g_config.getBoolean(ConfigManager::CANNOT_ATTACK_SAME_LOOKFEET) && attackerPlayer->defaultOutfit.lookFeet == target->defaultOutfit.lookFeet && damage.primary.type != COMBAT_HEALING) { return false; } if (attackerPlayer->getSkull() == SKULL_BLACK && attackerPlayer->getSkullClient(targetPlayer) == SKULL_NONE) { return false; } } if (damage.origin != ORIGIN_NONE) { g_events->eventCreatureOnChangeHealth(target, attacker, damage); damage.origin = ORIGIN_NONE; return combatChangeHealth(attacker, target, damage); } int32_t realHealthChange = target->getHealth(); target->gainHealth(attacker, damage.primary.value); realHealthChange = target->getHealth() - realHealthChange; if (realHealthChange > 0 && !target->isInGhostMode()) { std::string damageString = std::to_string(realHealthChange); std::string pluralString = (realHealthChange != 1 ? "s." : "."); std::string spectatorMessage = ucfirst(target->getNameDescription()); if (!attacker) { spectatorMessage += " was healed for " + damageString + " hitpoint" + pluralString; } else { spectatorMessage += " healed "; if (attacker == target) { spectatorMessage += (targetPlayer ? (targetPlayer->getSex() == PLAYERSEX_FEMALE ? "herself" : "himself") : "itself"); } else { spectatorMessage += target->getNameDescription(); } spectatorMessage += " for " + damageString + " hitpoint" + pluralString; } TextMessage message; message.position = targetPos; message.primary.value = realHealthChange; message.primary.color = TEXTCOLOR_MAYABLUE; SpectatorVec list; getSpectators(list, targetPos, false, true); for (Creature* spectator : list) { Player* tmpPlayer = spectator->getPlayer(); if (tmpPlayer == attackerPlayer && attackerPlayer != targetPlayer) { message.type = MESSAGE_HEALED; message.text = "You heal " + target->getNameDescription() + " for " + damageString + " hitpoint" + pluralString; } else if (tmpPlayer == targetPlayer) { message.type = MESSAGE_HEALED; if (!attacker) { message.text = "You were healed for " + damageString + " hitpoint" + pluralString; } else if (targetPlayer == attackerPlayer) { message.text = "You heal yourself for " + damageString + " hitpoint" + pluralString; } else { message.text = "You were healed by " + attacker->getNameDescription() + " for " + damageString + " hitpoint" + pluralString; } } else { message.type = MESSAGE_HEALED_OTHERS; message.text = spectatorMessage; } tmpPlayer->sendTextMessage(message); } } } else { SpectatorVec list; getSpectators(list, targetPos, true, true); if (!target->isAttackable() || Combat::canDoCombat(attacker, target) != RET_NOERROR) { addMagicEffect(list, targetPos, CONST_ME_POFF); return true; } Player* attackerPlayer; if (attacker) { attackerPlayer = attacker->getPlayer(); } else { attackerPlayer = nullptr; } Player* targetPlayer = target->getPlayer(); if (attackerPlayer && targetPlayer) { if (g_config.getBoolean(ConfigManager::CANNOT_ATTACK_SAME_LOOKFEET) && attacker->defaultOutfit.lookFeet == target->defaultOutfit.lookFeet && damage.primary.type != COMBAT_HEALING) { return false; } if (attackerPlayer->getSkull() == SKULL_BLACK && attackerPlayer->getSkullClient(targetPlayer) == SKULL_NONE) { return false; } } damage.primary.value = std::abs(damage.primary.value); damage.secondary.value = std::abs(damage.secondary.value); int32_t healthChange = damage.primary.value + damage.secondary.value; if (healthChange == 0) { return true; } TextMessage message; message.position = targetPos; if (target->hasCondition(CONDITION_MANASHIELD) && damage.primary.type != COMBAT_UNDEFINEDDAMAGE) { int32_t manaDamage = std::min<int32_t>(target->getMana(), healthChange); if (manaDamage != 0) { if (damage.origin != ORIGIN_NONE) { g_events->eventCreatureOnChangeMana(target, attacker, healthChange, damage.origin); if (healthChange == 0) { return true; } manaDamage = std::min<int32_t>(target->getMana(), healthChange); } target->drainMana(attacker, manaDamage); addMagicEffect(list, targetPos, CONST_ME_LOSEENERGY); std::string damageString = std::to_string(manaDamage); std::string spectatorMessage = ucfirst(target->getNameDescription()) + " loses " + damageString + " mana"; if (attacker) { spectatorMessage += " blocking an attack by "; if (attacker == target) { spectatorMessage += (targetPlayer ? (targetPlayer->getSex() == PLAYERSEX_FEMALE ? "herself" : "himself") : "itself"); } else { spectatorMessage += attacker->getNameDescription(); } } spectatorMessage += '.'; message.primary.value = manaDamage; message.primary.color = TEXTCOLOR_BLUE; for (Creature* spectator : list) { Player* tmpPlayer = spectator->getPlayer(); if (tmpPlayer->getPosition().z == targetPos.z) { if (tmpPlayer == attackerPlayer && attackerPlayer != targetPlayer) { message.type = MESSAGE_DAMAGE_DEALT; message.text = ucfirst(target->getNameDescription()) + " loses " + damageString + " mana blocking your attack."; } else if (tmpPlayer == targetPlayer) { message.type = MESSAGE_DAMAGE_RECEIVED; if (!attacker) { message.text = "You lose " + damageString + " mana."; } else if (targetPlayer == attackerPlayer) { message.text = "You lose " + damageString + " mana blocking an attack by yourself."; } else { message.text = "You lose " + damageString + " mana blocking an attack by " + attacker->getNameDescription() + '.'; } } else { message.type = MESSAGE_DAMAGE_OTHERS; message.text = spectatorMessage; } tmpPlayer->sendTextMessage(message); } } damage.primary.value -= manaDamage; if (damage.primary.value < 0) { damage.secondary.value = std::max<int32_t>(0, damage.secondary.value + damage.primary.value); damage.primary.value = 0; } } } int32_t realDamage = damage.primary.value + damage.secondary.value; if (realDamage == 0) { return true; } if (damage.origin != ORIGIN_NONE) { g_events->eventCreatureOnChangeHealth(target, attacker, damage); damage.origin = ORIGIN_NONE; return combatChangeHealth(attacker, target, damage); } int32_t targetHealth = target->getHealth(); if (damage.primary.value >= targetHealth) { damage.primary.value = targetHealth; damage.secondary.value = 0; } else if (damage.secondary.value) { damage.secondary.value = std::min<int32_t>(damage.secondary.value, targetHealth - damage.primary.value); } realDamage = damage.primary.value + damage.secondary.value; if (realDamage == 0) { return true; } else if (realDamage >= targetHealth) { if (!g_events->eventCreatureOnPrepareDeath(target, attacker)) { return false; } } target->drainHealth(attacker, realDamage); addCreatureHealth(list, target); message.primary.value = damage.primary.value; message.secondary.value = damage.secondary.value; uint8_t hitEffect; if (message.primary.value) { combatGetTypeInfo(damage.primary.type, target, message.primary.color, hitEffect); if (hitEffect != CONST_ME_NONE) { addMagicEffect(list, targetPos, hitEffect); } } if (message.secondary.value) { combatGetTypeInfo(damage.secondary.type, target, message.secondary.color, hitEffect); if (hitEffect != CONST_ME_NONE) { addMagicEffect(list, targetPos, hitEffect); } } if (message.primary.color != TEXTCOLOR_NONE || message.secondary.color != TEXTCOLOR_NONE) { std::string damageString = std::to_string(realDamage); std::string pluralString = (realDamage != 1 ? "s" : ""); std::string spectatorMessage = ucfirst(target->getNameDescription()) + " loses " + damageString + " hitpoint" + pluralString; if (attacker) { spectatorMessage += " due to "; if (attacker == target) { spectatorMessage += (targetPlayer ? (targetPlayer->getSex() == PLAYERSEX_FEMALE ? "her" : "his") : "its"); spectatorMessage += " own attack"; } else { spectatorMessage += "an attack by " + target->getNameDescription(); } } spectatorMessage += '.'; for (Creature* spectator : list) { Player* tmpPlayer = spectator->getPlayer(); if (tmpPlayer->getPosition().z == targetPos.z) { if (tmpPlayer == attackerPlayer && attackerPlayer != targetPlayer) { message.type = MESSAGE_DAMAGE_DEALT; message.text = ucfirst(target->getNameDescription()) + " loses " + damageString + " hitpoint" + pluralString + " due to your attack."; } else if (tmpPlayer == targetPlayer) { message.type = MESSAGE_DAMAGE_RECEIVED; if (!attacker) { message.text = "You lose " + damageString + " hitpoint" + pluralString + '.'; } else if (targetPlayer == attackerPlayer) { message.text = "You lose " + damageString + " hitpoint" + pluralString + " due to your own attack."; } else { message.text = "You lose " + damageString + " hitpoint" + pluralString + " due to an attack by " + attacker->getNameDescription() + '.'; } } else { message.type = MESSAGE_DAMAGE_OTHERS; message.text = spectatorMessage; } tmpPlayer->sendTextMessage(message); } } } } return true; } bool Game::combatChangeMana(Creature* attacker, Creature* target, int32_t manaChange, CombatOrigin origin) { if (manaChange > 0) { if (attacker) { Player* attackerPlayer = attacker->getPlayer(); Player* targetPlayer = target->getPlayer(); if (attackerPlayer && targetPlayer) { if (g_config.getBoolean(ConfigManager::CANNOT_ATTACK_SAME_LOOKFEET) && attacker->defaultOutfit.lookFeet == target->defaultOutfit.lookFeet) { return false; } if (attackerPlayer->getSkull() == SKULL_BLACK && attackerPlayer->getSkullClient(targetPlayer) == SKULL_NONE) { return false; } } } if (origin != ORIGIN_NONE) { g_events->eventCreatureOnChangeMana(target, attacker, manaChange, origin); return combatChangeMana(attacker, target, manaChange, ORIGIN_NONE); } target->changeMana(manaChange); } else { const Position& targetPos = target->getPosition(); if (!target->isAttackable() || Combat::canDoCombat(attacker, target) != RET_NOERROR) { addMagicEffect(targetPos, CONST_ME_POFF); return false; } Player* attackerPlayer; if (attacker) { attackerPlayer = attacker->getPlayer(); } else { attackerPlayer = nullptr; } Player* targetPlayer = target->getPlayer(); if (attackerPlayer && targetPlayer) { if (g_config.getBoolean(ConfigManager::CANNOT_ATTACK_SAME_LOOKFEET) && attacker->defaultOutfit.lookFeet == target->defaultOutfit.lookFeet) { return false; } if (attackerPlayer->getSkull() == SKULL_BLACK && attackerPlayer->getSkullClient(targetPlayer) == SKULL_NONE) { return false; } } int32_t manaLoss = std::min<int32_t>(target->getMana(), -manaChange); BlockType_t blockType = target->blockHit(attacker, COMBAT_MANADRAIN, manaLoss); if (blockType != BLOCK_NONE) { addMagicEffect(targetPos, CONST_ME_POFF); return false; } if (manaLoss <= 0) { return true; } if (origin != ORIGIN_NONE) { g_events->eventCreatureOnChangeMana(target, attacker, manaChange, origin); return combatChangeMana(attacker, target, manaChange, ORIGIN_NONE); } target->drainMana(attacker, manaLoss); std::string damageString = std::to_string(manaLoss); std::string spectatorMessage = ucfirst(target->getNameDescription()) + " loses " + damageString + " mana"; if (attacker) { spectatorMessage += " blocking an attack by "; if (attacker == target) { spectatorMessage += (targetPlayer ? (targetPlayer->getSex() == PLAYERSEX_FEMALE ? "herself" : "himself") : "itself"); } else { spectatorMessage += attacker->getNameDescription(); } } spectatorMessage += '.'; TextMessage message; message.position = targetPos; message.primary.value = manaLoss; message.primary.color = TEXTCOLOR_BLUE; SpectatorVec list; getSpectators(list, targetPos, false, true); for (Creature* spectator : list) { Player* tmpPlayer = spectator->getPlayer(); if (tmpPlayer == attackerPlayer && attackerPlayer != targetPlayer) { message.type = MESSAGE_DAMAGE_DEALT; message.text = ucfirst(target->getNameDescription()) + " loses " + damageString + " mana blocking your attack."; } else if (tmpPlayer == targetPlayer) { message.type = MESSAGE_DAMAGE_RECEIVED; if (!attacker) { message.text = "You lose " + damageString + " mana."; } else if (targetPlayer == attackerPlayer) { message.text = "You lose " + damageString + " mana blocking an attack by yourself."; } else { message.text = "You lose " + damageString + " mana blocking an attack by " + attacker->getNameDescription() + '.'; } } else { message.type = MESSAGE_DAMAGE_OTHERS; message.text = spectatorMessage; } tmpPlayer->sendTextMessage(message); } } return true; } void Game::addCreatureHealth(const Creature* target) { SpectatorVec list; getSpectators(list, target->getPosition(), true, true); addCreatureHealth(list, target); } void Game::addCreatureHealth(const SpectatorVec& list, const Creature* target) { for (Creature* spectator : list) { if (Player* tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendCreatureHealth(target); } } } void Game::addMagicEffect(const Position& pos, uint8_t effect) { SpectatorVec list; getSpectators(list, pos, true, true); addMagicEffect(list, pos, effect); } void Game::addMagicEffect(const SpectatorVec& list, const Position& pos, uint8_t effect) { for (Creature* spectator : list) { if (Player* tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendMagicEffect(pos, effect); } } } void Game::addDistanceEffect(const Position& fromPos, const Position& toPos, uint8_t effect) { SpectatorVec list; getSpectators(list, fromPos, false, true); getSpectators(list, toPos, false, true); addDistanceEffect(list, fromPos, toPos, effect); } void Game::addDistanceEffect(const SpectatorVec& list, const Position& fromPos, const Position& toPos, uint8_t effect) { for (Creature* spectator : list) { if (Player* tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendDistanceShoot(fromPos, toPos, effect); } } } void Game::startDecay(Item* item) { if (!item || !item->canDecay()) { return; } ItemDecayState_t decayState = item->getDecaying(); if (decayState == DECAYING_TRUE) { return; } if (item->getDuration() > 0) { item->useThing2(); item->setDecaying(DECAYING_TRUE); toDecayItems.push_front(item); } else { internalDecayItem(item); } } void Game::internalDecayItem(Item* item) { const ItemType& it = Item::items[item->getID()]; if (it.decayTo != 0) { Item* newItem = transformItem(item, it.decayTo); startDecay(newItem); } else { ReturnValue ret = internalRemoveItem(item); if (ret != RET_NOERROR) { std::cout << "DEBUG, internalDecayItem failed, error code: " << (int32_t) ret << "item id: " << item->getID() << std::endl; } } } void Game::checkDecay() { g_scheduler.addEvent(createSchedulerTask(EVENT_DECAYINTERVAL, std::bind(&Game::checkDecay, this))); size_t bucket = (lastBucket + 1) % EVENT_DECAY_BUCKETS; for (auto it = decayItems[bucket].begin(); it != decayItems[bucket].end();) { Item* item = *it; if (!item->canDecay()) { item->setDecaying(DECAYING_FALSE); ReleaseItem(item); it = decayItems[bucket].erase(it); continue; } int32_t decreaseTime = EVENT_DECAYINTERVAL * EVENT_DECAY_BUCKETS; int32_t duration = item->getDuration(); if (duration - decreaseTime < 0) { decreaseTime = duration; } duration -= decreaseTime; item->decreaseDuration(decreaseTime); if (duration <= 0) { it = decayItems[bucket].erase(it); internalDecayItem(item); ReleaseItem(item); } else if (duration < EVENT_DECAYINTERVAL * EVENT_DECAY_BUCKETS) { it = decayItems[bucket].erase(it); size_t newBucket = (bucket + ((duration + EVENT_DECAYINTERVAL / 2) / 1000)) % EVENT_DECAY_BUCKETS; if (newBucket == bucket) { internalDecayItem(item); ReleaseItem(item); } else { decayItems[newBucket].push_back(item); } } else { ++it; } } lastBucket = bucket; cleanup(); } void Game::checkLight() { g_scheduler.addEvent(createSchedulerTask(EVENT_LIGHTINTERVAL, std::bind(&Game::checkLight, this))); lightHour += lightHourDelta; if (lightHour > 1440) { lightHour -= 1440; } if (std::abs(lightHour - SUNRISE) < 2 * lightHourDelta) { lightState = LIGHT_STATE_SUNRISE; } else if (std::abs(lightHour - SUNSET) < 2 * lightHourDelta) { lightState = LIGHT_STATE_SUNSET; } int32_t newLightLevel = lightLevel; bool lightChange = false; switch (lightState) { case LIGHT_STATE_SUNRISE: { newLightLevel += (LIGHT_LEVEL_DAY - LIGHT_LEVEL_NIGHT) / 30; lightChange = true; break; } case LIGHT_STATE_SUNSET: { newLightLevel -= (LIGHT_LEVEL_DAY - LIGHT_LEVEL_NIGHT) / 30; lightChange = true; break; } default: break; } if (newLightLevel <= LIGHT_LEVEL_NIGHT) { lightLevel = LIGHT_LEVEL_NIGHT; lightState = LIGHT_STATE_NIGHT; } else if (newLightLevel >= LIGHT_LEVEL_DAY) { lightLevel = LIGHT_LEVEL_DAY; lightState = LIGHT_STATE_DAY; } else { lightLevel = newLightLevel; } if (lightChange) { LightInfo lightInfo; getWorldLightInfo(lightInfo); for (const auto& it : players) { it.second->sendWorldLight(lightInfo); } } } void Game::getWorldLightInfo(LightInfo& lightInfo) const { lightInfo.level = lightLevel; lightInfo.color = 0xD7; } void Game::addCommandTag(char tag) { for (char commandTag : commandTags) { if (commandTag == tag) { return; } } commandTags.push_back(tag); } void Game::resetCommandTag() { commandTags.clear(); } void Game::shutdown() { std::cout << "Shutting down server..." << std::flush; g_scheduler.shutdown(); g_dispatcher.shutdown(); Spawns::getInstance()->clear(); Raids::getInstance()->clear(); cleanup(); if (services) { services->stop(); } ConnectionManager::getInstance()->closeAll(); std::cout << " done!" << std::endl; } void Game::cleanup() { //free memory for (auto creature : ToReleaseCreatures) { creature->releaseThing2(); } ToReleaseCreatures.clear(); for (auto item : ToReleaseItems) { item->releaseThing2(); } ToReleaseItems.clear(); for (Item* item : toDecayItems) { const uint32_t dur = item->getDuration(); if (dur >= EVENT_DECAYINTERVAL * EVENT_DECAY_BUCKETS) { decayItems[lastBucket].push_back(item); } else { decayItems[(lastBucket + 1 + dur / 1000) % EVENT_DECAY_BUCKETS].push_back(item); } } toDecayItems.clear(); } void Game::ReleaseCreature(Creature* creature) { ToReleaseCreatures.push_back(creature); } void Game::ReleaseItem(Item* item) { ToReleaseItems.push_back(item); } void Game::broadcastMessage(const std::string& text, MessageClasses type) const { std::cout << "> Broadcasted message: \"" << text << "\"." << std::endl; for (const auto& it : players) { it.second->sendTextMessage(type, text); } } void Game::updateCreatureWalkthrough(const Creature* creature) { //send to clients SpectatorVec list; getSpectators(list, creature->getPosition(), true, true); for (Creature* spectator : list) { Player* tmpPlayer = spectator->getPlayer(); tmpPlayer->sendCreatureWalkthrough(creature, tmpPlayer->canWalkthroughEx(creature)); } } void Game::updatePlayerSkull(Player* player) { if (getWorldType() != WORLD_TYPE_PVP) { return; } SpectatorVec list; getSpectators(list, player->getPosition(), true, true); for (Creature* spectator : list) { spectator->getPlayer()->sendCreatureSkull(player); } } void Game::updatePlayerShield(Player* player) { SpectatorVec list; getSpectators(list, player->getPosition(), true, true); for (Creature* spectator : list) { spectator->getPlayer()->sendCreatureShield(player); } } void Game::updatePlayerHelpers(const Player& player) { uint32_t creatureId = player.getID(); uint16_t helpers = player.getHelpers(); SpectatorVec list; getSpectators(list, player.getPosition(), true, true); for (Creature* spectator : list) { spectator->getPlayer()->sendCreatureHelpers(creatureId, helpers); } } void Game::updateCreatureType(Creature* creature) { const Player* masterPlayer = nullptr; uint32_t creatureId = creature->getID(); CreatureType_t creatureType = creature->getType(); if (creatureType == CREATURETYPE_MONSTER) { const Creature* master = creature->getMaster(); if (master) { masterPlayer = master->getPlayer(); if (masterPlayer) { creatureType = CREATURETYPE_SUMMON_OTHERS; } } } //send to clients SpectatorVec list; getSpectators(list, creature->getPosition(), true, true); if (creatureType == CREATURETYPE_SUMMON_OTHERS) { for (Creature* spectator : list) { Player* player = spectator->getPlayer(); if (masterPlayer == player) { player->sendCreatureType(creatureId, CREATURETYPE_SUMMON_OWN); } else { player->sendCreatureType(creatureId, creatureType); } } } else { for (Creature* spectator : list) { spectator->getPlayer()->sendCreatureType(creatureId, creatureType); } } } void Game::updatePremium(Account& account) { bool save = false; time_t timeNow = time(nullptr); if (account.premiumDays != 0 && account.premiumDays != std::numeric_limits<uint16_t>::max()) { if (account.lastDay == 0) { account.lastDay = timeNow; save = true; } else { uint32_t days = (timeNow - account.lastDay) / 86400; if (days > 0) { if (days >= account.premiumDays) { account.premiumDays = 0; account.lastDay = 0; } else { account.premiumDays -= days; uint32_t remainder = (timeNow - account.lastDay) % 86400; account.lastDay = timeNow - remainder; } save = true; } } } else if (account.lastDay != 0) { account.lastDay = 0; save = true; } if (save && !IOLoginData::saveAccount(account)) { std::cout << "> ERROR: Failed to save account: " << account.name << "!" << std::endl; } } void Game::loadMotdNum() { Database* db = Database::getInstance(); DBResult_ptr result = db->storeQuery("SELECT `value` FROM `server_config` WHERE `config` = 'motd_num'"); if (result) { motdNum = result->getDataInt("value"); } else { db->executeQuery("INSERT INTO `server_config` (`config`, `value`) VALUES ('motd_num', '0')"); } result = db->storeQuery("SELECT `value` FROM `server_config` WHERE `config` = 'motd_hash'"); if (result) { motdHash = result->getDataString("value"); if (motdHash != transformToSHA1(g_config.getString(ConfigManager::MOTD))) { ++motdNum; } } else { db->executeQuery("INSERT INTO `server_config` (`config`, `value`) VALUES ('motd_hash', '')"); } } void Game::saveMotdNum() const { Database* db = Database::getInstance(); std::ostringstream query; query << "UPDATE `server_config` SET `value` = '" << motdNum << "' WHERE `config` = 'motd_num'"; db->executeQuery(query.str()); query.str(""); query << "UPDATE `server_config` SET `value` = '" << transformToSHA1(g_config.getString(ConfigManager::MOTD)) << "' WHERE `config` = 'motd_hash'"; db->executeQuery(query.str()); } void Game::checkPlayersRecord() { const size_t playersOnline = getPlayersOnline(); if (playersOnline > playersRecord) { uint32_t previousRecord = playersRecord; playersRecord = playersOnline; for (const auto& it : g_globalEvents->getEventMap(GLOBALEVENT_RECORD)) { it.second->executeRecord(playersRecord, previousRecord); } updatePlayersRecord(); } } void Game::updatePlayersRecord() const { Database* db = Database::getInstance(); std::ostringstream query; query << "UPDATE `server_config` SET `value` = '" << playersRecord << "' WHERE `config` = 'players_record'"; db->executeQuery(query.str()); } void Game::loadPlayersRecord() { Database* db = Database::getInstance(); DBResult_ptr result = db->storeQuery("SELECT `value` FROM `server_config` WHERE `config` = 'players_record'"); if (result) { playersRecord = result->getDataInt("value"); } else { db->executeQuery("INSERT INTO `server_config` (`config`, `value`) VALUES ('players_record', '0')"); } } uint64_t Game::getExperienceStage(uint32_t level) { if (!stagesEnabled) { return g_config.getNumber(ConfigManager::RATE_EXPERIENCE); } if (useLastStageLevel && level >= lastStageLevel) { return stages[lastStageLevel]; } return stages[level]; } bool Game::loadExperienceStages() { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file("data/XML/stages.xml"); if (!result) { std::cout << "[Error - Game::loadExperienceStages] Failed to load data/XML/stages.xml: " << result.description() << std::endl; return false; } for (pugi::xml_node stageNode = doc.child("stages").first_child(); stageNode; stageNode = stageNode.next_sibling()) { if (strcasecmp(stageNode.name(), "config") == 0) { stagesEnabled = stageNode.attribute("enabled").as_bool(); } else { uint32_t minLevel, maxLevel, multiplier; pugi::xml_attribute minLevelAttribute = stageNode.attribute("minlevel"); if (minLevelAttribute) { minLevel = pugi::cast<uint32_t>(minLevelAttribute.value()); } else { minLevel = 1; } pugi::xml_attribute maxLevelAttribute = stageNode.attribute("maxlevel"); if (maxLevelAttribute) { maxLevel = pugi::cast<uint32_t>(maxLevelAttribute.value()); } else { maxLevel = 0; lastStageLevel = minLevel; useLastStageLevel = true; } pugi::xml_attribute multiplierAttribute = stageNode.attribute("multiplier"); if (multiplierAttribute) { multiplier = pugi::cast<uint32_t>(multiplierAttribute.value()); } else { multiplier = 1; } if (useLastStageLevel) { stages[lastStageLevel] = multiplier; } else { for (uint32_t i = minLevel; i <= maxLevel; ++i) { stages[i] = multiplier; } } } } return true; } void Game::playerInviteToParty(uint32_t playerId, uint32_t invitedId) { Player* player = getPlayerByID(playerId); if (!player) { return; } Player* invitedPlayer = getPlayerByID(invitedId); if (!invitedPlayer || invitedPlayer->isInviting(player)) { return; } if (invitedPlayer->getParty()) { std::ostringstream ss; ss << invitedPlayer->getName() << " is already in a party."; player->sendTextMessage(MESSAGE_INFO_DESCR, ss.str()); return; } Party* party = player->getParty(); if (!party) { party = new Party(player); } else if (party->getLeader() != player) { return; } party->invitePlayer(*invitedPlayer); } void Game::playerJoinParty(uint32_t playerId, uint32_t leaderId) { Player* player = getPlayerByID(playerId); if (!player) { return; } Player* leader = getPlayerByID(leaderId); if (!leader || !leader->isInviting(player)) { return; } Party* party = leader->getParty(); if (!party || party->getLeader() != leader) { return; } if (player->getParty()) { player->sendTextMessage(MESSAGE_INFO_DESCR, "You are already in a party."); return; } party->joinParty(*player); } void Game::playerRevokePartyInvitation(uint32_t playerId, uint32_t invitedId) { Player* player = getPlayerByID(playerId); if (!player) { return; } Party* party = player->getParty(); if (!party || party->getLeader() != player) { return; } Player* invitedPlayer = getPlayerByID(invitedId); if (!invitedPlayer || !player->isInviting(invitedPlayer)) { return; } party->revokeInvitation(*invitedPlayer); } void Game::playerPassPartyLeadership(uint32_t playerId, uint32_t newLeaderId) { Player* player = getPlayerByID(playerId); if (!player) { return; } Party* party = player->getParty(); if (!party || party->getLeader() != player) { return; } Player* newLeader = getPlayerByID(newLeaderId); if (!newLeader || !player->isPartner(newLeader)) { return; } party->passPartyLeadership(newLeader); } void Game::playerLeaveParty(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } Party* party = player->getParty(); if (!party || player->hasCondition(CONDITION_INFIGHT)) { return; } party->leaveParty(player); } void Game::playerEnableSharedPartyExperience(uint32_t playerId, bool sharedExpActive) { Player* player = getPlayerByID(playerId); if (!player) { return; } Party* party = player->getParty(); if (!party || player->hasCondition(CONDITION_INFIGHT)) { return; } party->setSharedExperience(player, sharedExpActive); } void Game::sendGuildMotd(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } Guild* guild = player->getGuild(); if (guild) { player->sendChannelMessage("Message of the Day", guild->getMotd(), TALKTYPE_CHANNEL_R1, CHANNEL_GUILD); } } void Game::kickPlayer(uint32_t playerId, bool displayEffect) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->kickPlayer(displayEffect); } void Game::playerReportBug(uint32_t playerId, const std::string& bug) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (player->getAccountType() == ACCOUNT_TYPE_NORMAL) { return; } std::string fileName = "data/reports/" + player->getName() + " report.txt"; FILE* file = fopen(fileName.c_str(), "a"); if (file) { const Position& position = player->getPosition(); fprintf(file, "------------------------------\nName: %s [Position X: %u Y: %u Z: %u]\nBug Report: %s\n", player->getName().c_str(), position.x, position.y, position.z, bug.c_str()); fclose(file); } player->sendTextMessage(MESSAGE_EVENT_DEFAULT, "Your report has been sent to " + g_config.getString(ConfigManager::SERVER_NAME) + "."); } void Game::playerDebugAssert(uint32_t playerId, const std::string& assertLine, const std::string& date, const std::string& description, const std::string& comment) { Player* player = getPlayerByID(playerId); if (!player) { return; } // TODO: move debug assertions to database FILE* file = fopen("client_assertions.txt", "a"); if (file) { fprintf(file, "----- %s - %s (%s) -----\n", formatDate(time(nullptr)).c_str(), player->getName().c_str(), convertIPToString(player->getIP()).c_str()); fprintf(file, "%s\n%s\n%s\n%s\n", assertLine.c_str(), date.c_str(), description.c_str(), comment.c_str()); fclose(file); } } void Game::playerLeaveMarket(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } player->setInMarket(false); } void Game::playerBrowseMarket(uint32_t playerId, uint16_t spriteId) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (!player->isInMarket()) { return; } const ItemType& it = Item::items.getItemIdByClientId(spriteId); if (it.id == 0) { return; } if (it.wareId == 0) { return; } const MarketOfferList& buyOffers = IOMarket::getActiveOffers(MARKETACTION_BUY, it.id); const MarketOfferList& sellOffers = IOMarket::getActiveOffers(MARKETACTION_SELL, it.id); player->sendMarketBrowseItem(it.id, buyOffers, sellOffers); player->sendMarketDetail(it.id); } void Game::playerBrowseMarketOwnOffers(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (!player->isInMarket()) { return; } const MarketOfferList& buyOffers = IOMarket::getOwnOffers(MARKETACTION_BUY, player->getGUID()); const MarketOfferList& sellOffers = IOMarket::getOwnOffers(MARKETACTION_SELL, player->getGUID()); player->sendMarketBrowseOwnOffers(buyOffers, sellOffers); } void Game::playerBrowseMarketOwnHistory(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (!player->isInMarket()) { return; } const HistoryMarketOfferList& buyOffers = IOMarket::getOwnHistory(MARKETACTION_BUY, player->getGUID()); const HistoryMarketOfferList& sellOffers = IOMarket::getOwnHistory(MARKETACTION_SELL, player->getGUID()); player->sendMarketBrowseOwnHistory(buyOffers, sellOffers); } void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t spriteId, uint16_t amount, uint32_t price, bool anonymous) { if (amount == 0 || amount > 64000) { return; } if (price == 0 || price > 999999999) { return; } if (type != MARKETACTION_BUY && type != MARKETACTION_SELL) { return; } Player* player = getPlayerByID(playerId); if (!player) { return; } if (!player->isInMarket()) { return; } if (g_config.getBoolean(ConfigManager::MARKET_PREMIUM) && !player->isPremium()) { player->sendMarketLeave(); return; } const ItemType& itt = Item::items.getItemIdByClientId(spriteId); if (itt.id == 0 || itt.wareId == 0) { return; } const ItemType& it = Item::items.getItemIdByClientId(itt.wareId); if (it.id == 0 || it.wareId == 0) { return; } if (!it.stackable && amount > 2000) { return; } const int32_t maxOfferCount = g_config.getNumber(ConfigManager::MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER); if (maxOfferCount > 0) { const int32_t offerCount = IOMarket::getPlayerOfferCount(player->getGUID()); if (offerCount == -1 || offerCount >= maxOfferCount) { return; } } uint64_t fee = (price / 100.) * amount; if (fee < 20) { fee = 20; } else if (fee > 1000) { fee = 1000; } if (type == MARKETACTION_SELL) { if (fee > player->bankBalance) { return; } DepotChest* depotChest = player->getDepotChest(player->getLastDepotId(), false); if (!depotChest) { return; } ItemList itemList; uint32_t count = 0; std::vector<Container*> containers {depotChest, player->getInbox()}; bool enough = false; size_t i = 0; do { Container* container = containers[i++]; for (Item* item : container->getItemList()) { Container* c = item->getContainer(); if (c && !c->empty()) { containers.push_back(c); continue; } const ItemType& itemType = Item::items[item->getID()]; if (itemType.wareId != it.wareId) { continue; } if (item->hasAttributes()) { bool badAttribute = false; ItemAttributes* attributes = item->getAttributes(); for (const auto& attr : attributes->getList()) { if (attr.type == ITEM_ATTRIBUTE_CHARGES) { uint16_t charges = static_cast<uint16_t>(0xFFFF & reinterpret_cast<ptrdiff_t>(attr.value)); if (charges != itemType.charges) { badAttribute = true; break; } } else if (attr.type == ITEM_ATTRIBUTE_DURATION) { uint32_t duration = static_cast<uint32_t>(0xFFFFFFFF & reinterpret_cast<ptrdiff_t>(attr.value)); if (duration != itemType.decayTime) { badAttribute = true; break; } } else { badAttribute = true; break; } } if (badAttribute) { continue; } } itemList.push_back(item); count += Item::countByType(item, -1); if (count >= amount) { enough = true; break; } } if (enough) { break; } } while (i < containers.size()); if (!enough) { return; } if (it.stackable) { uint16_t tmpAmount = amount; for (Item* item : itemList) { uint16_t removeCount = std::min<uint16_t>(tmpAmount, item->getItemCount()); tmpAmount -= removeCount; internalRemoveItem(item, removeCount); if (tmpAmount == 0) { break; } } } else { for (Item* item : itemList) { internalRemoveItem(item); } } player->bankBalance -= fee; } else { uint64_t totalPrice = (uint64_t)price * amount; totalPrice += fee; if (totalPrice > player->bankBalance) { return; } player->bankBalance -= totalPrice; } IOMarket::createOffer(player->getGUID(), (MarketAction_t)type, it.id, amount, price, anonymous); player->sendMarketEnter(player->getLastDepotId()); const MarketOfferList& buyOffers = IOMarket::getActiveOffers(MARKETACTION_BUY, it.id); const MarketOfferList& sellOffers = IOMarket::getActiveOffers(MARKETACTION_SELL, it.id); player->sendMarketBrowseItem(it.id, buyOffers, sellOffers); } void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (!player->isInMarket()) { return; } MarketOfferEx offer = IOMarket::getOfferByCounter(timestamp, counter); if (offer.id == 0 || offer.playerId != player->getGUID()) { return; } if (offer.type == MARKETACTION_BUY) { player->bankBalance += (uint64_t)offer.price * offer.amount; player->sendMarketEnter(player->getLastDepotId()); } else { const ItemType& it = Item::items[offer.itemId]; if (it.id == 0) { return; } if (it.stackable) { uint16_t tmpAmount = offer.amount; while (tmpAmount > 0) { int32_t stackCount = std::min<int32_t>(100, tmpAmount); Item* item = Item::CreateItem(it.id, stackCount); if (internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RET_NOERROR) { delete item; break; } tmpAmount -= stackCount; } } else { int32_t subType; if (it.charges != 0) { subType = it.charges; } else { subType = -1; } for (uint16_t i = 0; i < offer.amount; ++i) { Item* item = Item::CreateItem(it.id, subType); if (internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RET_NOERROR) { delete item; break; } } } } IOMarket::moveOfferToHistory(offer.id, OFFERSTATE_CANCELLED); offer.amount = 0; offer.timestamp += g_config.getNumber(ConfigManager::MARKET_OFFER_DURATION); player->sendMarketCancelOffer(offer); } void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter, uint16_t amount) { if (amount == 0 || amount > 64000) { return; } Player* player = getPlayerByID(playerId); if (!player) { return; } if (!player->isInMarket()) { return; } MarketOfferEx offer = IOMarket::getOfferByCounter(timestamp, counter); if (offer.id == 0) { return; } if (amount > offer.amount) { return; } const ItemType& it = Item::items[offer.itemId]; if (it.id == 0) { return; } uint64_t totalPrice = (uint64_t)offer.price * amount; if (offer.type == MARKETACTION_BUY) { DepotChest* depotChest = player->getDepotChest(player->getLastDepotId(), false); if (!depotChest) { return; } ItemList itemList; uint32_t count = 0; std::vector<Container*> containers {depotChest, player->getInbox()}; bool enough = false; size_t i = 0; do { Container* container = containers[i++]; for (Item* item : container->getItemList()) { Container* c = item->getContainer(); if (c && !c->empty()) { containers.push_back(c); continue; } const ItemType& itemType = Item::items[item->getID()]; if (itemType.wareId != it.wareId) { continue; } if (item->hasAttributes()) { bool badAttribute = false; ItemAttributes* attributes = item->getAttributes(); for (const auto& attr : attributes->getList()) { if (attr.type == ITEM_ATTRIBUTE_CHARGES) { uint16_t charges = static_cast<uint16_t>(0xFFFF & reinterpret_cast<ptrdiff_t>(attr.value)); if (charges != itemType.charges) { badAttribute = true; break; } } else if (attr.type == ITEM_ATTRIBUTE_DURATION) { uint32_t duration = static_cast<uint32_t>(0xFFFFFFFF & reinterpret_cast<ptrdiff_t>(attr.value)); if (duration != itemType.decayTime) { badAttribute = true; break; } } else { badAttribute = true; break; } } if (badAttribute) { continue; } } itemList.push_back(item); count += Item::countByType(item, -1); if (count >= amount) { enough = true; break; } } if (enough) { break; } } while (i < containers.size()); if (!enough) { return; } Player* buyerPlayer = getPlayerByGUID(offer.playerId); if (!buyerPlayer) { buyerPlayer = new Player(nullptr); if (!IOLoginData::loadPlayerById(buyerPlayer, offer.playerId)) { delete buyerPlayer; return; } } if (it.stackable) { uint16_t tmpAmount = amount; for (Item* item : itemList) { uint16_t removeCount = std::min<uint16_t>(tmpAmount, item->getItemCount()); tmpAmount -= removeCount; internalRemoveItem(item, removeCount); if (tmpAmount == 0) { break; } } } else { for (Item* item : itemList) { internalRemoveItem(item); } } player->bankBalance += totalPrice; if (it.stackable) { uint16_t tmpAmount = amount; while (tmpAmount > 0) { uint16_t stackCount = std::min<uint16_t>(100, tmpAmount); Item* item = Item::CreateItem(it.id, stackCount); if (internalAddItem(buyerPlayer->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RET_NOERROR) { delete item; break; } tmpAmount -= stackCount; } } else { int32_t subType; if (it.charges != 0) { subType = it.charges; } else { subType = -1; } for (uint16_t i = 0; i < amount; ++i) { Item* item = Item::CreateItem(it.id, subType); if (internalAddItem(buyerPlayer->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RET_NOERROR) { delete item; break; } } } if (buyerPlayer->isOffline()) { IOLoginData::savePlayer(buyerPlayer); delete buyerPlayer; } else { buyerPlayer->onReceiveMail(); } } else { if (totalPrice > player->bankBalance) { return; } player->bankBalance -= totalPrice; if (it.stackable) { uint16_t tmpAmount = amount; while (tmpAmount > 0) { uint16_t stackCount = std::min<uint16_t>(100, tmpAmount); Item* item = Item::CreateItem(it.id, stackCount); if (internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RET_NOERROR) { delete item; break; } tmpAmount -= stackCount; } } else { int32_t subType; if (it.charges != 0) { subType = it.charges; } else { subType = -1; } for (uint16_t i = 0; i < amount; ++i) { Item* item = Item::CreateItem(it.id, subType); if (internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RET_NOERROR) { delete item; break; } } } Player* sellerPlayer = getPlayerByGUID(offer.playerId); if (sellerPlayer) { sellerPlayer->bankBalance += totalPrice; } else { IOLoginData::increaseBankBalance(offer.playerId, totalPrice); } player->onReceiveMail(); } const int32_t marketOfferDuration = g_config.getNumber(ConfigManager::MARKET_OFFER_DURATION); IOMarket::appendHistory(player->getGUID(), (offer.type == MARKETACTION_BUY ? MARKETACTION_SELL : MARKETACTION_BUY), offer.itemId, amount, offer.price, offer.timestamp + marketOfferDuration, OFFERSTATE_ACCEPTEDEX); IOMarket::appendHistory(offer.playerId, offer.type, offer.itemId, amount, offer.price, offer.timestamp + marketOfferDuration, OFFERSTATE_ACCEPTED); offer.amount -= amount; if (offer.amount == 0) { IOMarket::deleteOffer(offer.id); } else { IOMarket::acceptOffer(offer.id, amount); } player->sendMarketEnter(player->getLastDepotId()); offer.timestamp += marketOfferDuration; player->sendMarketAcceptOffer(offer); } void Game::checkExpiredMarketOffers() { const ExpiredMarketOfferList& expiredBuyOffers = IOMarket::getExpiredOffers(MARKETACTION_BUY); for (const ExpiredMarketOffer& offer : expiredBuyOffers) { uint64_t totalPrice = (uint64_t)offer.price * offer.amount; Player* player = getPlayerByGUID(offer.playerId); if (player) { player->bankBalance += totalPrice; } else { IOLoginData::increaseBankBalance(offer.playerId, totalPrice); } IOMarket::moveOfferToHistory(offer.id, OFFERSTATE_EXPIRED); } const ExpiredMarketOfferList& expiredSellOffers = IOMarket::getExpiredOffers(MARKETACTION_SELL); for (const ExpiredMarketOffer& offer : expiredSellOffers) { Player* player = getPlayerByGUID(offer.playerId); if (!player) { player = new Player(nullptr); if (!IOLoginData::loadPlayerById(player, offer.playerId)) { delete player; continue; } } const ItemType& itemType = Item::items[offer.itemId]; if (itemType.id == 0) { continue; } if (itemType.stackable) { uint16_t tmpAmount = offer.amount; while (tmpAmount > 0) { uint16_t stackCount = std::min<uint16_t>(100, tmpAmount); Item* item = Item::CreateItem(itemType.id, stackCount); if (internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RET_NOERROR) { delete item; break; } tmpAmount -= stackCount; } } else { int32_t subType; if (itemType.charges != 0) { subType = itemType.charges; } else { subType = -1; } for (uint16_t i = 0; i < offer.amount; ++i) { Item* item = Item::CreateItem(itemType.id, subType); if (internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RET_NOERROR) { delete item; break; } } } if (player->isOffline()) { IOLoginData::savePlayer(player); delete player; } IOMarket::moveOfferToHistory(offer.id, OFFERSTATE_EXPIRED); } int32_t checkExpiredMarketOffersEachMinutes = g_config.getNumber(ConfigManager::CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES); if (checkExpiredMarketOffersEachMinutes <= 0) { return; } g_scheduler.addEvent(createSchedulerTask(checkExpiredMarketOffersEachMinutes * 60 * 1000, std::bind(&Game::checkExpiredMarketOffers, this))); } void Game::parsePlayerExtendedOpcode(uint32_t playerId, uint8_t opcode, const std::string& buffer) { Player* player = getPlayerByID(playerId); if (!player) { return; } g_events->eventPlayerOnExtendedOpcode(player, opcode, buffer); } void Game::forceAddCondition(uint32_t creatureId, Condition* condition) { Creature* creature = getCreatureByID(creatureId); if (!creature) { delete condition; return; } creature->addCondition(condition, true); } void Game::forceRemoveCondition(uint32_t creatureId, ConditionType_t type) { Creature* creature = getCreatureByID(creatureId); if (!creature) { return; } creature->removeCondition(type, true); } void Game::sendOfflineTrainingDialog(Player* player) { if (!player) { return; } if (!player->hasModalWindowOpen(offlineTrainingWindow.id)) { player->sendModalWindow(offlineTrainingWindow); } } void Game::playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, uint8_t button, uint8_t choice) { Player* player = getPlayerByID(playerId); if (!player) { return; } if (!player->hasModalWindowOpen(modalWindowId)) { return; } player->onModalWindowHandled(modalWindowId); // offline training, hardcoded if (modalWindowId == std::numeric_limits<uint32_t>::max()) { if (button == 1) { if (choice == SKILL_SWORD || choice == SKILL_AXE || choice == SKILL_CLUB || choice == SKILL_DISTANCE || choice == SKILL_MAGLEVEL) { BedItem* bedItem = player->getBedItem(); if (bedItem && bedItem->sleep(player)) { player->setOfflineTrainingSkill(choice); return; } } } else { player->sendTextMessage(MESSAGE_EVENT_ADVANCE, "Offline training aborted."); } player->setBedItem(nullptr); } else { g_events->eventPlayerOnModalWindow(player, modalWindowId, button, choice); } } void Game::addPlayer(Player* player) { const std::string& lowercase_name = asLowerCaseString(player->getName()); mappedPlayerNames[lowercase_name] = player; wildcardTree.insert(lowercase_name); players[player->getID()] = player; } void Game::removePlayer(Player* player) { const std::string& lowercase_name = asLowerCaseString(player->getName()); mappedPlayerNames.erase(lowercase_name); wildcardTree.remove(lowercase_name); players.erase(player->getID()); } void Game::addNpc(Npc* npc) { npcs[npc->getID()] = npc; } void Game::removeNpc(Npc* npc) { npcs.erase(npc->getID()); } void Game::addMonster(Monster* monster) { monsters[monster->getID()] = monster; } void Game::removeMonster(Monster* monster) { monsters.erase(monster->getID()); } Guild* Game::getGuild(uint32_t id) const { auto it = guilds.find(id); if (it == guilds.end()) { return nullptr; } return it->second; } void Game::addGuild(Guild* guild) { guilds[guild->getId()] = guild; } void Game::decreaseBrowseFieldRef(const Position& pos) { Tile* tile = getTile(pos); if (!tile) { return; } auto it = browseFields.find(tile); if (it != browseFields.end()) { it->second->releaseThing2(); } } Group* Game::getGroup(uint32_t id) { return groups.getGroup(id); } void Game::internalRemoveItems(std::vector<Item*> itemList, uint32_t amount, bool stackable) { if (stackable) { for (Item* item : itemList) { if (item->getItemCount() > amount) { internalRemoveItem(item, amount); break; } else { amount -= item->getItemCount(); internalRemoveItem(item); } } } else { for (Item* item : itemList) { internalRemoveItem(item); } } } BedItem* Game::getBedBySleeper(uint32_t guid) const { auto it = bedSleepersMap.find(guid); if (it == bedSleepersMap.end()) { return nullptr; } return it->second; } void Game::setBedSleeper(BedItem* bed, uint32_t guid) { bedSleepersMap[guid] = bed; } void Game::removeBedSleeper(uint32_t guid) { auto it = bedSleepersMap.find(guid); if (it != bedSleepersMap.end()) { bedSleepersMap.erase(it); } }
EvilHero90/OTChronos
src/game.cpp
C++
gpl-2.0
154,982
from datetime import * from Tweetstream import * from UserAnalyser import * from TimeAnalyser import * import math import sys import pickle #Frequency over the common def load_list(filein): d = dict() for l in filein: l = eval(l) d[l[0]] = l[1] return d if __name__ == "__main__": follow = load_list(open(sys.argv[5], 'r')) keywords = open(sys.argv[2], 'r').readline().strip("\n").split(",") userstream = Tweetstream(jsonfilee=sys.argv[3], jsonformat=False, keywords=keywords) topicstream = Tweetstream(jsonfilee=sys.argv[1], jsonformat=False, keywords=keywords) ua = UserAnalyser (sys.argv[4], keywords = keywords) ua.load_usersVectors() ua.load_idf() ua.load_usersScore() rank = dict() # normalizar pelo numero de kw no topic vector c = 0 for t in userstream: rank[t['id']] = 0 n = 0 if t['user_id'] in follow: c += 1 for fuser in follow[t['user_id']]: if fuser in ua.usersScore: rank[t['id']] += ua.usersScore[fuser] n += 1 if n > 0: rank[t['id']] /= n print c #prinit score, nwindow pickle.dump(rank, open(sys.argv[4]+"_rank_USER_followers.pick", 'w'), pickle.HIGHEST_PROTOCOL)
agdavis/contextual_features
gen_user_followers.py
Python
gpl-2.0
1,139