repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
VesnaBrucoms/computer-drafter-wpf
|
Computer Drafter/InputOutput/Directory.cs
|
2080
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Computer_Drafter.InputOutput
{
static class Directory
{
/// <summary>
/// Returns a list of every file in a directory with a specified extension.
/// </summary>
public static List<string> GetFiles(string filePath, string extension)
{
if (!System.IO.Directory.Exists(filePath) || System.IO.Directory.GetFiles(filePath) == null || System.IO.Directory.GetFiles(filePath).Length == 0)
{
return new List<string>();
}
else
{
List<string> files = new List<string>();
foreach (string file in System.IO.Directory.GetFiles(filePath))
{
if (file.EndsWith(extension))
{
string[] split = file.Split('\\');
files.Add(split[split.Length - 1]);
}
}
return files;
}
}
public static string CheckDirectoryExists(string directory)
{
if (!System.IO.Directory.Exists(directory))
{
DialogResult result = MessageBox.Show(directory + " does not exist.\n\nDo you want to create it?", "Directory", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
if (result == DialogResult.Yes)
{
System.IO.Directory.CreateDirectory(directory);
return directory;
}
else if (result == DialogResult.No)
{
return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
else
{
return null;
}
}
else
{
return directory;
}
}
}
}
|
gpl-2.0
|
veskoy/HackBulgaria_Winter2015
|
Application Problems/Problem 2/solution.rb
|
2141
|
def count_word_occurances(word, data)
occurances = 0
# First let's check the rows
data.each do |row|
row_string = row.join('')
occurances += 1 if row_string.include?(word) or row_string.include?(word.reverse)
end
# After that we can continue with the cols
table_width = data[0].length
table_height = data.length
(0..table_width).map do |i|
col_string = ''
(0..table_height).map do |k|
unless (data[k].nil? or data[k][i].nil?) then col_string += data[k][i] end
end
occurances += 1 if col_string.include?(word) or col_string.include?(word.reverse)
end
# Finally let's see the diagonals
word_length = word.length # We won't need to check the diagonals which lengths are less than the word's length
diagonals, current_diagonal = [], []
# Start with diagonals from top left to bottom right
(0..table_height).map do |y|
x = 0
(y == 0 ? data : data.drop(y)).each do |row|
current_diagonal.push(row[x])
x += 1
end
diagonals.push(current_diagonal.clone)
current_diagonal.clear
end
(1..table_width).map do |x|
y=0
(x..table_width).map do |i|
current_diagonal.push(data[y][i])
y += 1
end
diagonals.push(current_diagonal.clone)
current_diagonal.clear
end
# Now let's get the diagonals from top right to bottom left
(0..table_height).map do |y|
x = table_width
(y == 0 ? data : data.drop(y)).each do |row|
current_diagonal.push(row[x])
x -= 1
end
diagonals.push(current_diagonal.clone)
current_diagonal.clear
end
(((0..table_width-1).to_a).reverse).map do |x|
y=0
(((0..x).to_a).reverse).map do |i|
current_diagonal.push(data[y][i])
y += 1
end
diagonals.push(current_diagonal.clone)
current_diagonal.clear
end
diagonals.each do |row|
diag_string = row.join('')
occurances += 1 if diag_string.include?(word) or diag_string.include?(word.reverse)
end
occurances
end
data_table = [
['i','v','a','n'],
['e','v','n','h'],
['i','n','a','v'],
['m','v','v','n'],
['q','r','i','t']
]
puts count_word_occurances('ivan', data_table)
|
gpl-2.0
|
mramir8274/x.ybot
|
bot/seedbot.lua
|
9950
|
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '1.0'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
-- mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"plugin",
"autoleave",
"echo",
"google",
"googleimg",
"server",
"txt2img",
"well",
"webshot",
"dic",
"inv",
"map",
"robot",
"gps",
"calculator",
"s2a",
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"antitag",
"arabic_lock",
"set",
"get",
"broadcast",
"download_media",
"invite",
"xy",
"block",
"tagall",
"lockeng",
"feed",
"id",
"all",
"leave_ban"
},
sudo_users = {144438066},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[Teleseed v2 - Open Source
An advance Administration bot based on yagop/telegram-bot
https://github.com/SEEDTEAM/TeleSeed
Admin
@oO_amir_oO
Special thanks to
@rm13790115
Our channels
@extremerobos
]],
help_text_realm = [[
Realm Commands:
!creategroup [Name]
Create a group
!createrealm [Name]
Create a realm
!setname [Name]
Set realm name
!setabout [GroupID] [Text]
Set a group's about text
!setrules [GroupID] [Text]
Set a group's rules
!lock [GroupID] [setting]
Lock a group's setting
!unlock [GroupID] [setting]
Unock a group's setting
!wholist
Get a list of members in group/realm
!who
Get a file of members in group/realm
!type
Get group type
!kill chat [GroupID]
Kick all memebers and delete group
!kill realm [RealmID]
Kick all members and delete realm
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only
!list groups
Get a list of all groups
!list realms
Get a list of all realms
!log
Grt a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
Only sudo users can run this command
!br [group_id] [text]
!br 123456789 Hello !
This command will send text to [group_id]
**U can use both "/" and "!"
*Only admins and sudo can add bots in group
*Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only admins and sudo can use res, setowner, commands
]],
help_text = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
return group id or user id
!help
!lock [member|name|bots|leave]
Locks [member|name|bots|leaveing]
!unlock [member|name|bots|leave]
Unlocks [member|name|bots|leaving]
!set rules <text>
Set <text> as rules
!set about <text>
Set <text> as about
!settings
Returns group settings
!newlink
create/revoke your group link
!link
returns group link
!owner
returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] <text>
Save <text> as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
returns user id
"!res @username"
!log
will return group logs
!banlist
will return group ban list
!tagall ***
!web ***
!calc ***
!img ***
!src ***
!dic ***
!echo ***
!map ***
!covn ***
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
|
gpl-2.0
|
cyberpython/java-gnome
|
generated/bindings/org/gnome/gtk/GtkCellRendererSpinner.java
|
2502
|
/*
* java-gnome, a UI library for writing GTK and GNOME programs from Java!
*
* Copyright © 2006-2011 Operational Dynamics Consulting, Pty Ltd and Others
*
* The code in this file, and the program it is a part of, is made available
* to you by its authors as open source software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License version
* 2 ("GPL") 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 GPL for more details.
*
* You should have received a copy of the GPL along with this program. If not,
* see http://www.gnu.org/licenses/. The authors of this program may be
* contacted through http://java-gnome.sourceforge.net/.
*
* Linking this library statically or dynamically with other modules is making
* a combined work based on this library. Thus, the terms and conditions of
* the GPL cover the whole combination. As a special exception (the
* "Claspath Exception"), the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module. An independent
* module is a module which is not derived from or based on this library. If
* you modify this library, you may extend the Classpath Exception to your
* version of the library, but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version.
*/
package org.gnome.gtk;
/*
* THIS FILE IS GENERATED CODE!
*
* To modify its contents or behaviour, either update the generation program,
* change the information in the source defs file, or implement an override for
* this class.
*/
import org.gnome.gtk.Plumbing;
final class GtkCellRendererSpinner extends Plumbing
{
private GtkCellRendererSpinner() {}
static final long createCellRendererSpinner() {
long result;
synchronized (lock) {
result = gtk_cell_renderer_spinner_new();
return result;
}
}
private static native final long gtk_cell_renderer_spinner_new();
}
|
gpl-2.0
|
lorea/event_connector
|
views/default/forms/event_connector/import.php
|
647
|
<?php
/**
* iCal import form body
*
* @package ElggEventConnector
*/
?>
<div>
<label><?php echo elgg_echo("event_connector:upload:file"); ?></label>
<br />
<?php echo elgg_view("input/file", array('name' => 'upload')); ?>
</div>
<div>
<label><?php echo elgg_echo('access'); ?></label>
<br />
<?php echo elgg_view('input/access', array('name' => 'access_id', 'value' => ACCESS_DEFAULT)); ?>
</div>
<div class="elgg-foot">
<?php
echo elgg_view('input/hidden', array('name' => "container_guid", 'value' => $vars['container_guid']));
echo elgg_view('input/submit', array('value' => elgg_echo("save")));
?>
</div>
|
gpl-2.0
|
alucardxlx/matts-uo-server
|
Server/Party.cs
|
1572
|
/***************************************************************************
* Party.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id: Party.cs 4 2006-06-15 04:28:39Z mark $
*
***************************************************************************/
/***************************************************************************
*
* 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.
*
***************************************************************************/
using System;
namespace Server
{
public abstract class PartyCommands
{
private static PartyCommands m_Handler;
public static PartyCommands Handler{ get{ return m_Handler; } set{ m_Handler = value; } }
public abstract void OnAdd( Mobile from );
public abstract void OnRemove( Mobile from, Mobile target );
public abstract void OnPrivateMessage( Mobile from, Mobile target, string text );
public abstract void OnPublicMessage( Mobile from, string text );
public abstract void OnSetCanLoot( Mobile from, bool canLoot );
public abstract void OnAccept( Mobile from, Mobile leader );
public abstract void OnDecline( Mobile from, Mobile leader );
}
}
|
gpl-2.0
|
hh-italian-group/hh-bbtautau
|
Studies/python/TrainingTF1.py
|
3431
|
# Definition of the training for the HH-btag NN
# This file is part of https://github.com/hh-italian-group/hh-bbtautau.
import tensorflow as tf
from keras import Model
config = tf.ConfigProto(allow_soft_placement=False, device_count = {'CPU' : 1, 'GPU' : 1})
config.gpu_options.allow_growth = True
session = tf.Session(config=config)
from keras.callbacks import CSVLogger
from keras.callbacks import Callback
from keras.optimizers import adam
from keras import backend as K
K.set_session(session)
import argparse
import json
import numpy as np
import InputsProducer
import ParametrizedModelTF1 as pm
from CalculateWeigths import CreateSampleWeigts, CrossCheckWeights
import ROOT
parser = argparse.ArgumentParser()
parser.add_argument("-params", "--params")
parser.add_argument("-output", "--output")
parser.add_argument("-training_variables", "--training_variables")
parser.add_argument("-n_epoch", "--n_epoch", type=int)
parser.add_argument("-patience", "--patience", type=int)
parser.add_argument("-validation_split", "--validation_split", type=float)
parser.add_argument("-parity", "--parity", type=int)
parser.add_argument("-f", "--file", nargs='+')
parser.add_argument('-seed', '--seed', nargs='?', default=12345, type=int)
args = parser.parse_args()
file_name = pm.ListToVector(args.file)
with open(args.params) as f:
params = json.load(f)
class WeightsSaver(Callback):
def __init__(self, N):
self.N = N
self.epoch = 0
def on_epoch_end(self, epoch, logs={}):
if self.epoch % self.N == 0:
name = '{}_par{}_weight_epoch_{}.h5'.format(args.output, args.parity, self.epoch )
# name = ('weights_epoch_%04d.h5') % self.epoch
self.model.save_weights(name)
self.epoch += 1
def PerformTraining(file_name, n_epoch, params):
np.random.seed(args.seed)
data = InputsProducer.CreateRootDF(file_name, 0, True, True)
X, Y, Z, var_pos, var_pos_z, var_name = InputsProducer.CreateXY(data, args.training_variables)
print(var_pos)
w = CreateSampleWeigts(X, Z)
Y = Y.reshape(Y.shape[0:2])
tf.set_random_seed(args.seed)
model = pm.HHModel(var_pos, 10,'../config/mean_std_red.json', '../config/min_max_red.json', params)
opt = adam(lr=10 ** params['learning_rate_exp'])
model.compile(loss=K.binary_crossentropy, optimizer=opt)
model.summary()
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', mode='min', patience=args.patience)
csv_logger = CSVLogger('{}_par{}_training_history.csv'.format(args.output, args.parity), append=False, separator=',')
save_best_only = tf.keras.callbacks.ModelCheckpoint(filepath='{}_par{}_best_weights.h5'.format(args.output, args.parity),
monitor='val_loss', mode='min', save_weights_only=True,
save_best_only=True, verbose=1)
model.fit(X, Y, sample_weight=w, validation_split=args.validation_split, epochs=args.n_epoch, batch_size=100,
callbacks=[csv_logger, save_best_only,early_stop, WeightsSaver(1)],verbose=2)
model.save('{}_par_{}_all_model'.format(args.output,args.parity ))
model.save_weights('{}_par{}_final_weights.h5'.format(args.output, args.parity))
with open('{}_par{}_params.json'.format(args.output, args.parity), 'w') as f:
f.write(json.dumps(params, indent=4))
PerformTraining(file_name, args.n_epoch, params)
|
gpl-2.0
|
janrose/gpsmid
|
GpsMidGraph/de/ueller/midlet/gps/routing/Connection.java
|
563
|
package de.ueller.midlet.gps.routing;
public class Connection {
/**
* represent time in s or length in m depending on the search mode
*/
public int cost;
// public Integer toId=null;
public int toId=-1;
// public RouteNode to=null;
public byte startBearing=0;
public byte endBearing=0;
public Connection(){
}
public Connection(RouteNode to, int cost, byte bs, byte be) {
// this.to = to;
this.toId=to.id;
this.cost=cost;
this.startBearing=bs;
this.endBearing=be;
}
public String toString(){
return "connection to " + toId;
}
}
|
gpl-2.0
|
fnatter/freeplane-debian-dev
|
freeplane/src/main/java/org/freeplane/features/filter/hidden/HiddenNodeContoller.java
|
1938
|
package org.freeplane.features.filter.hidden;
import org.freeplane.core.enumeration.NodeEnumerationAttributeHandler;
import org.freeplane.core.io.ReadManager;
import org.freeplane.core.io.WriteManager;
import org.freeplane.features.icon.IStateIconProvider;
import org.freeplane.features.icon.IconController;
import org.freeplane.features.icon.UIIcon;
import org.freeplane.features.icon.factory.IconStoreFactory;
import org.freeplane.features.map.NodeModel;
import org.freeplane.features.mode.ModeController;
import org.freeplane.features.mode.mindmapmode.MModeController;
public class HiddenNodeContoller {
public static void registerModeSpecificActions(MModeController controller) {
controller.addAction(new HideNodeAction());
controller.addAction(new ShowHiddenNodesAction());
}
public static void install(ModeController controller) {
final ReadManager readManager = controller.getMapController().getReadManager();
final WriteManager writeManager = controller.getMapController().getWriteManager();
new NodeEnumerationAttributeHandler<NodeVisibility>(NodeVisibility.class).registerBy(readManager, writeManager);
new NodeEnumerationAttributeHandler<NodeVisibilityConfiguration>(NodeVisibilityConfiguration.class).registerBy(readManager, writeManager);
registerStateIconProvider(controller);
}
private static UIIcon hiddenNodeIcon;
private static void registerStateIconProvider(ModeController modeController) {
modeController.getExtension(IconController.class).addStateIconProvider(new IStateIconProvider() {
@Override
public UIIcon getStateIcon(NodeModel node) {
if (node.getExtension(NodeVisibility.class) != NodeVisibility.HIDDEN) {
return null;
}
if (hiddenNodeIcon == null) {
hiddenNodeIcon = IconStoreFactory.ICON_STORE.getUIIcon("hidden.png");
}
return hiddenNodeIcon;
}
@Override
public boolean mustIncludeInIconRegistry() {
return true;
}
});
}
}
|
gpl-2.0
|
decafio/SimpleSupport
|
SimpleSupport/App_Start/RouteConfig.cs
|
583
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SimpleSupport
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
|
gpl-2.0
|
Automattic/o2
|
modules/to-do/js/views/extend-post.js
|
4739
|
var ResolvedPostExtendsPost = ( function( $ ) {
return {
initialize: function() {
_.bindAll( this, 'onResolvedPostsSuccess', 'onResolvedPostsError' );
var postMeta = this.model.get( 'postMeta' );
if ( 'undefined' !== typeof postMeta.resolvedPostsAuditLogs ) {
this.model.auditLogs = new o2.Collections.AuditLogs( postMeta.resolvedPostsAuditLogs );
} else {
this.model.auditLogs = new o2.Collections.AuditLogs();
}
this.listenTo( this.model, 'o2-post-rendered', this.onRenderPostView );
this.listenTo( this.model, 'o2-post-rendered', this.addAllAuditLogViews );
this.listenTo( this.model.auditLogs, 'add', this.addOneAuditLog );
this.listenTo( this.model.auditLogs, 'reset', this.addAllAuditLogViews );
},
events: {
'click a.o2-resolve-link': 'onClickResolvedPosts',
'mouseenter .o2-resolve-wrap': 'onHoverResolvedPosts',
'mouseleave .o2-resolve-wrap': 'onBlurResolvedPosts',
'touchend a.o2-resolve-link': 'onClickResolvedPosts'
},
onClickResolvedPosts: function( event ) {
event.preventDefault();
event.stopPropagation();
if ( $( event.target ).hasClass( 'o2-disabled-action' ) ) {
return false;
}
var currentState = this.getPostModelCurrentState();
var nextState = o2.PostActionStates.getNextState( 'resolvedposts', currentState );
var link = this.$el.find( '.o2-resolve-link' );
o2.PostActionStates.setState( link, nextState );
this.setPostModelState( nextState );
var pluginData = {};
pluginData.callback = 'o2_resolved_posts';
pluginData.data = {
postID: this.model.get( 'postID' ),
nextState: nextState
};
this.model.save( {
pluginData: pluginData
}, {
patch: true,
silent: true,
success: this.onResolvedPostsSuccess,
error: this.onResolvedPostsError
} );
},
onResolvedPostsSuccess: function( model, resp ) {
var auditLog = new o2.Models.AuditLog( resp.data.auditLog );
this.model.auditLogs.add( auditLog );
},
onResolvedPostsError: function( model, xhr ) {
var currentState = this.getPostModelCurrentState();
var link = this.$el.find( '.o2-resolve-link' );
o2.PostActionStates.setState( link, currentState );
var responseText = '';
var errorText = '';
try {
responseText = $.parseJSON( xhr.responseText );
errorText = responseText.errorText;
} catch ( e ) {
errorText = xhr.responseText;
}
o2.Notifications.add( {
type: 'error',
text: errorText,
sticky: true
} );
},
onHoverResolvedPosts: function( event ) {
event.preventDefault();
if ( ( 'undefined' !== typeof o2.options.isMobileOrTablet ) && o2.options.isMobileOrTablet ) {
return;
}
var log = this.$( '.o2-resolve-wrap ul' );
if ( log.find( 'li' ).length ) {
this.$( 'li' ).show();
log.fadeIn( 500 );
}
},
onBlurResolvedPosts: function( event ) {
event.preventDefault();
if ( ( 'undefined' !== typeof o2.options.isMobileOrTablet ) && o2.options.isMobileOrTablet ) {
return;
}
var log = this.$( '.o2-resolve-wrap ul' );
if ( log.find( 'li' ).length ) {
log.fadeOut( 500 );
}
},
onRenderPostView: function() {
var currentState = this.getPostModelCurrentState();
var link = this.$el.find( '.o2-resolve-link' );
o2.PostActionStates.setState( link, currentState );
},
addOneAuditLog: function( auditLog ) {
this.addOneAuditLogView( auditLog );
},
addOneAuditLogView: function( auditLog ) {
var auditLogView = new o2.Views.AuditLog( {
model: auditLog,
parent: this
} );
var list = this.$( '.o2-resolve-wrap ul' );
list.prepend( auditLogView.render().el );
// Disable any hovercards
list.find( 'img' ).addClass( 'no-grav nocard' );
if ( auditLog.isNew() ) {
var newAuditLog = list.children( ':first' );
newAuditLog.hide().fadeIn( 500 );
var originalBackgroundColor = newAuditLog.css( 'background-color' );
newAuditLog.css( 'background-color', '#ffc' );
newAuditLog.animate( { 'background-color': originalBackgroundColor }, 3000 );
}
},
addAllAuditLogViews: function() {
this.$( '.o2-resolve-wrap ul' ).html( '' );
this.model.auditLogs.forEach( this.addOneAuditLogView, this );
},
getPostModelCurrentState: function() {
var postMeta = this.model.get( 'postMeta' );
var currentState = postMeta.resolvedPostsPostState;
if ( 'undefined' === typeof currentState ) {
currentState = 'normal';
}
return currentState;
},
setPostModelState: function( slug ) {
var postMeta = this.model.get( 'postMeta' );
postMeta.resolvedPostsPostState = slug;
this.model.set( { postMeta: postMeta } );
}
};
} )( jQuery );
Cocktail.mixin( o2.Views.Post, ResolvedPostExtendsPost );
|
gpl-2.0
|
m-godefroid76/devrestofactory
|
wp-content/themes/triven/content-menu-home.php
|
1620
|
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="menu-index-pro">
<div class="menu-image-pro-home">
<?php if( has_post_format( 'gallery' ) ): ?>
<div class="flexslider gallery-progression">
<ul class="slides">
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => '-1',
'post_status' => null,
'post_parent' => $post->ID,
'orderby' => 'menu_order',
'order' => 'ASC'
);
$attachments = get_posts($args);
?>
<?php
if($attachments):
foreach($attachments as $attachment):
?>
<?php $thumbnail = wp_get_attachment_image_src($attachment->ID, 'progression-menu'); ?>
<?php $image = wp_get_attachment_image_src($attachment->ID, 'large'); ?>
<li><a href="<?php echo $image[0]; ?>" rel="prettyPhoto[gallery]"><img src="<?php echo $thumbnail[0]; ?>" alt="<?php echo $attachment->post_title; ?>" /></a></li>
<?php endforeach; endif; ?>
</ul>
</div>
<?php else: ?>
<?php if(has_post_thumbnail()): ?>
<?php $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large'); ?>
<a href="<?php echo $image[0]; ?>" rel="prettyPhoto"><?php the_post_thumbnail('progression-menu'); ?></a>
<?php endif; ?>
<?php endif; ?>
</div>
<div class="menu-content-pro-home">
<h5><?php the_title(); ?></h5>
<div class="menu_content_pro-home"><?php echo excerpt(18); ?></div>
</div>
<div class="clearfix"></div>
</div><!-- close .portfolio-index-text -->
</article><!-- #post-## -->
|
gpl-2.0
|
waqarmuneer/RN-Cor
|
administrator/components/com_rednet/admin.rednet.php
|
1658
|
<?php
/**
* @version 1.0
* @package joomla
* @subpackage Rednet
* @author
* @copyright Copyright (C) 2012, . All rights reserved.
* @license
*/
//--No direct access
defined('_JEXEC') or die('Resrtricted Access');
// Require the base controller
require_once( JPATH_COMPONENT.DS.'controller.php' );
jimport('joomla.application.component.model');
require_once( JPATH_COMPONENT.DS.'models'.DS.'model.php' );
// Component Helper
jimport('joomla.application.component.helper');
//add Helperpath to JHTML
JHTML::addIncludePath(JPATH_COMPONENT.DS.'helpers');
//include Helper
require_once(JPATH_COMPONENT.DS.'helpers'.DS.'rednet.php');
//Use the JForms, even in Joomla 1.5
$jv = new JVersion();
$GLOBALS['alt_libdir'] = ($jv->RELEASE < 1.6) ? JPATH_COMPONENT_ADMINISTRATOR : null;
//set the default view
$controller = JRequest::getWord('view', 'role');
//add submenu for 1.6
if ($jv->RELEASE > 1.5) {
RednetHelper::addSubmenu($controller);
}
$ControllerConfig = array();
// Require specific controller if requested
if ( $controller) {
$path = JPATH_COMPONENT.DS.'controllers'.DS.$controller.'.php';
$ControllerConfig = array('viewname'=>strtolower($controller),'mainmodel'=>strtolower($controller),'itemname'=>ucfirst(strtolower($controller)));
if ( file_exists($path)) {
require_once $path;
} else {
$controller = '';
}
}
// Create the controller
$classname = 'RednetController'.$controller;
$controller = new $classname($ControllerConfig );
// Perform the Request task
$controller->execute( JRequest::getVar( 'task' ) );
// Redirect if set by the controller
$controller->redirect();
|
gpl-2.0
|
noahjohn9259/emberrcom
|
wp-content/plugins/wp-admin-icons/includes/wp-admin-icons-options.php
|
16053
|
<div class="wrap">
<h2>WP-Admin Icons
<span class="whoBy">By: <a href="http://imdev.in" target="_blank" title="Visit Devin Walker's Site">Devin Walker</a></span>
</h2>
<div class="adminFacebook">
<iframe src="//www.facebook.com/plugins/like.php?href=https%3A%2F%2Fwww.facebook.com%2Fpages%2FWordImpress%2F353658958080509&send=false&layout=button_count&width=100&show_faces=false&font&colorscheme=light&action=like&height=21&appId=220596284639969" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:21px;" allowTransparency="true"></iframe>
</div>
<div class="moreOptions">
<h4>More Useful Options</h4>
<p>Hide all admin icons in left menu?</p>
<form method="post" action="options.php">
<?php settings_fields('icons-settings-group-more'); ?>
<?php $options = get_option('admin-icons-options-more'); ?>
<input type="checkbox" value="true" name="admin-icons-options-more[removeIcons]" <?php $removeIcons = $options['removeIcons']; if ($removeIcons == "true") {
echo 'checked';
} ?> >
<p>Hide the WordPress Logo in the top-left admin menu bar?</p>
<input type="checkbox" value="true" name="admin-icons-options-more[removeLogo]" <?php $removeLogo = $options['removeLogo']; if ($removeLogo == "true") {
echo 'checked';
} ?> >
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>"/>
</p>
</form>
</div>
<div class="credits">
<h3>How to Use:</h3>
<p>Using WP-Admin Icons is easy, simply choose an icon from the list and then the icon you'd like to replace using the drop-down selection and click submit. If you'd like to clear that icon simply click "Clear Icon".</p>
<h4>What this Plugin Does:</h4>
<p>This plugin allows you to replace nearly all default icons in the WordPress admin interface.
<strong>This plugin supports custom post types</strong>.</p>
<h3>Support</h3>
<p>If you are having trouble using this plugin please post in the <a href="http://wordpress.org/support/plugin/wp-admin-icons" target="_blank">WordPress forums.</a></p>
<h3>Credits</h3>
<p><strong>Icon Design Credit</strong>:<br/> <a href="http://p.yusukekamiyamane.com/" target="_blank">Yusuke Kamiyamane</a></p>
<p>A Plugin to easily set your WordPress Admin Icons by
<strong><a href="http://imdev.in/" target="_blank" title="Visit Devin's Personal Site">Devin Walker</a></strong> from
<a href="http://www.wordimpress.com" target="_blank" title="Visit WordImpress">WordImpress</a>.</p>
</div>
<table class="widefat wpAdminIconsTable">
<thead>
<tr>
<th>Use an WP-Admin Icon</th>
</tr>
</thead>
<tr valign="top">
<th>
<ul class="iconList"></ul>
<a href="#" class="moreIcons" page="1">More Icons »</a>
</th>
</tr>
</table>
<table class="widefat myWpAdminIconsTable">
<thead>
<tr>
<th>Your Uploaded Icon</th>
</tr>
</thead>
<tr valign="top">
<th>
<ul class="myIconList"></ul>
</th>
</tr>
</table>
<table class="widefat iconsTable" align="left">
<thead>
<tr>
<th>Choose an Icon</th>
<th class="explain">Explanation</th>
</tr>
</thead>
<tr valign="top">
<th>
<a href="#" class="loadIcons">Show Included Admin Icons</a></th>
<th><p class="explanation">Check out some of our 1800+ WP admin icons you can use!</p>
</th>
<tr>
<th><a href="#" class="loadMyIcons">Show My Uploaded Icons</a><br/>
</th>
<th><p class="explanation">If you have uploaded your own custom icons you can set them here.</p>
</th>
</tr>
<tr>
<th><a href="#" id="uploadShow">Upload a Custom Icon Sprite</a><br/>
</th>
<th>
<p class="explanation">Have your own icon? Upload it to set as an admin icon. Please note: The icon should be a PNG sprite with same canvas size as included icons. Use the included icons as templates for your custom icons.</p>
</th>
</tr>
</table>
<table class="widefat uploadIconTable">
<thead>
<tr>
<th>Upload Your Own</th>
</tr>
</thead>
<tr valign="top">
<th>
<p>Uploaded icons will appear in the "My Admin Icons" section after upload. Please use .png files as icons.</p>
<form name="newad" method="post" enctype="multipart/form-data" action="<?php bloginfo('url'); ?>/wp-content/plugins/wp-admin-icons/includes/uploader.php">
<table class="uploader">
<tr>
<td><input type="file" name="icon"></td>
</tr>
<tr>
<td><input name="Submit" type="submit" value="Upload" class="button-primary"></td>
</tr>
</table>
</form>
</th>
</tr>
</table>
<!-- end icons table -->
<form method="post" action="options.php">
<?php settings_fields('icons-settings-group'); ?>
<?php $options = get_option('admin-icons-options'); ?>
<table class="widefat setIconTable">
<thead>
<tr>
<th>New Icon</th>
<th>Icon to Replace</th>
<th>Save Changes</th>
</tr>
</thead>
<tr>
<td class="iconChangerBox">
<div class="noIcon">None</div>
</td>
<td>
<div id="newIconHiddenField"></div>
<!-- Admin icons drop down -->
<select name="admin-icons-options[iconToReplace]" id="iconDropDown">
<option select="selected">Select...</option>
<option value="dashboard">Dashboard</option>
<option value="posts">Posts</option>
<option value="media">Media</option>
<option value="links">Links</option>
<option value="pages">Pages</option>
<option value="comments">Comments</option>
<option value="appearance">Appearance</option>
<option value="plugins">Plugins</option>
<option value="users">Users</option>
<option value="tools">Tools</option>
<option value="settings">Settings</option>
<?php
$args = array(
'_builtin' => false
);
$post_types = get_post_types($args, 'names');
foreach ($post_types as $post_type) {
echo ' <option value="' . $post_type . '">' . $post_type . '</option>';
}
?>
</select></td>
<td><p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>"/>
</p></td>
</tr>
</table>
<table class="widefat setIconTable iconInPlaceTable">
<thead>
<tr>
<th>Icon Type</th>
<th>Current Icon</th>
<th>Clear Icon</th>
</tr>
</thead>
<tr valign="top">
<td><p>Dashboard</p></td>
<td>
<div class="currentIcon"><img src="<?php echo $options['dashboardIconURL']; ?>"/></div>
<input type="text" name="admin-icons-options[dashboardIconURL]" value="<?php echo $options['dashboardIconURL']; ?>" id="new-dashboard-icon" class="hiddenField"/>
</td>
<td>
<div class="submit clearIconWrap">
<input type="submit" class="button-primary clearIcon" value="Clear Icon" onclick="this.value = ''; jQuery(this).css('display','none'); " name="admin-icons-options[dashboardIconURL]"/>
</div>
</td>
</tr>
<tr valign="top">
<td><p>Posts</p></td>
<td>
<div class="currentIcon"><img src="<?php echo $options['postIconURL']; ?>"/></div>
<input type="text" name="admin-icons-options[postIconURL]" value="<?php echo $options['postIconURL']; ?>" id="new-posts-icon" class="hiddenField"/>
</td>
<td>
<div class="submit clearIconWrap">
<input type="submit" class="button-primary clearIcon" value="Clear Icon" onclick="this.value = ''; jQuery(this).css('display','none');" name="admin-icons-options[postIconURL]"/>
</div>
</td>
</tr>
<tr valign="top">
<td><p>Media</p></td>
<td>
<div class="currentIcon"><img src="<?php echo $options['mediaIconURL']; ?>"/></div>
<input type="text" name="admin-icons-options[mediaIconURL]" value="<?php echo $options['mediaIconURL']; ?>" id="new-media-icon" class="hiddenField"/>
</td>
<td>
<div class="submit clearIconWrap">
<input type="submit" class="button-primary clearIcon" value="Clear Icon" onclick="this.value = ''; jQuery(this).css('display','none');" name="admin-icons-options[mediaIconURL]"/>
</div>
</td>
</tr>
<tr valign="top">
<td><p>Links</p></td>
<td>
<div class="currentIcon"><img src="<?php echo $options['linksIconURL']; ?>"/></div>
<input type="text" name="admin-icons-options[linksIconURL]" value="<?php echo $options['linksIconURL']; ?>" id="new-links-icon" class="hiddenField"/>
</td>
<td>
<div class="submit clearIconWrap">
<input type="submit" class="button-primary clearIcon" value="Clear Icon" onclick="this.value = ''; jQuery(this).css('display','none');" name="admin-icons-options[linksIconURL]"/>
</div>
</td>
</tr>
<tr valign="top">
<td><p>Pages</p></td>
<td>
<div class="currentIcon"><img src="<?php echo $options['pagesIconURL']; ?>"/></div>
<input type="text" name="admin-icons-options[pagesIconURL]" value="<?php echo $options['pagesIconURL']; ?>" id="new-pages-icon" class="hiddenField"/>
</td>
<td>
<div class="submit clearIconWrap">
<input type="submit" class="button-primary clearIcon" value="Clear Icon" onclick="this.value = ''; jQuery(this).css('display','none');" name="admin-icons-options[pagesIconURL]"/>
</div>
</td>
</tr>
<tr valign="top">
<td><p>Comments</p></td>
<td>
<div class="currentIcon"><img src="<?php echo $options['commentsIconURL']; ?>"/></div>
<input type="text" name="admin-icons-options[commentsIconURL]" value="<?php echo $options['commentsIconURL']; ?>" id="new-comments-icon" class="hiddenField"/>
</td>
<td>
<div class="submit clearIconWrap">
<input type="submit" class="button-primary clearIcon" value="Clear Icon" onclick="this.value = ''; jQuery(this).css('display','none');" name="admin-icons-options[commentsIconURL]"/>
</div>
</td>
</tr>
<tr valign="top">
<td><p>Appearance</p></td>
<td>
<div class="currentIcon"><img src="<?php echo $options['appearanceIconURL']; ?>"/></div>
<input type="text" name="admin-icons-options[appearanceIconURL]" value="<?php echo $options['appearanceIconURL']; ?>" id="new-appearance-icon" class="hiddenField"/>
</td>
<td>
<div class="submit clearIconWrap">
<input type="submit" class="button-primary clearIcon" value="Clear Icon" onclick="this.value = ''; jQuery(this).css('display','none');" name="admin-icons-options[appearanceIconURL]"/>
</div>
</td>
</tr>
<tr valign="top">
<td><p>Plugins</p></td>
<td>
<div class="currentIcon"><img src="<?php echo $options['pluginsIconURL']; ?>"/></div>
<input type="text" name="admin-icons-options[pluginsIconURL]" value="<?php echo $options['pluginsIconURL']; ?>" id="new-plugins-icon" class="hiddenField"/>
</td>
<td>
<div class="submit clearIconWrap">
<input type="submit" class="button-primary clearIcon" value="Clear Icon" onclick="this.value = ''; jQuery(this).css('display','none');" name="admin-icons-options[pluginsIconURL]"/>
</div>
</td>
</tr>
<tr valign="top">
<td><p>Users</p></td>
<td>
<div class="currentIcon"><img src="<?php echo $options['usersIconURL']; ?>"/></div>
<input type="text" name="admin-icons-options[usersIconURL]" value="<?php echo $options['usersIconURL']; ?>" id="new-users-icon" class="hiddenField"/>
</td>
<td>
<div class="submit clearIconWrap">
<input type="submit" class="button-primary clearIcon" value="Clear Icon" onclick="this.value = ''; jQuery(this).css('display','none');" name="admin-icons-options[usersIconURL]"/>
</div>
</td>
</tr>
<tr valign="top">
<td><p>Tools</p></td>
<td>
<div class="currentIcon"><img src="<?php echo $options['toolsIconURL']; ?>"/></div>
<input type="text" name="admin-icons-options[toolsIconURL]" value="<?php echo $options['toolsIconURL']; ?>" id="new-tools-icon" class="hiddenField"/>
</td>
<td>
<div class="submit clearIconWrap">
<input type="submit" class="button-primary clearIcon" value="Clear Icon" onclick="this.value = ''; jQuery(this).css('display','none');" name="admin-icons-options[toolsIconURL]"/>
</div>
</td>
</tr>
<tr valign="top">
<td><p>Settings</p></td>
<td>
<div class="currentIcon"><img src="<?php echo $options['settingsIconURL']; ?>"/></div>
<input type="text" name="admin-icons-options[settingsIconURL]" value="<?php echo $options['settingsIconURL']; ?>" id="new-settings-icon" class="hiddenField"/>
</td>
<td>
<div class="submit clearIconWrap">
<input type="submit" class="button-primary clearIcon" value="Clear Icon" onclick="this.value = ''; jQuery(this).css('display','none');" name="admin-icons-options[settingsIconURL]"/>
</div>
</td>
</tr>
<?php
$args = array(
'_builtin' => false
);
$post_types = get_post_types($args, 'names');
foreach ($post_types as $post_type) {
echo '<tr valign="top"><td><p>' . $post_type . '</p></td>';
$thisPostTypeOption = $post_type . 'IconURL';
echo '<td><div class="currentIcon"><img src="' . $options[$thisPostTypeOption] . '" />';
echo '</div><input type="text" name="admin-icons-options[' . $thisPostTypeOption . ']" value="' . $options[$thisPostTypeOption];
echo '" id="new-' . $post_type . '-icon" class="hiddenField" /></td>';
echo '<td> <div class="submit clearIconWrap"><input type="submit" class="button-primary clearIcon" value="Clear Icon" onclick="this.value = \'\';jQuery(this).css(\'display\',\'none\');" name="admin-icons-options[' . $thisPostTypeOption . ']" />
</div></td>';
echo '</tr>';
} ?>
</table>
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>"/>
</p>
</form>
</div>
|
gpl-2.0
|
shahora/kurdishgram1
|
TMeesagesProj/src/main/java/org/vidogram/ui/Components/TimerDrawable.java
|
5226
|
package org.vidogram.ui.Components;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import org.vidogram.messenger.AndroidUtilities;
import org.vidogram.messenger.FileLog;
import org.vidogram.ui.ActionBar.Theme;
public class TimerDrawable extends Drawable
{
private Paint linePaint = new Paint(1);
private Paint paint = new Paint(1);
private int time = 0;
private int timeHeight = 0;
private StaticLayout timeLayout;
private TextPaint timePaint = new TextPaint(1);
private float timeWidth = 0.0F;
public TimerDrawable(Context paramContext)
{
this.timePaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
this.timePaint.setTextSize(AndroidUtilities.dp(11.0F));
this.linePaint.setStrokeWidth(AndroidUtilities.dp(1.0F));
this.linePaint.setStyle(Paint.Style.STROKE);
}
public void draw(Canvas paramCanvas)
{
int j = getIntrinsicWidth();
int k = getIntrinsicHeight();
if (this.time == 0)
{
this.paint.setColor(Theme.getColor("chat_secretTimerBackground"));
this.linePaint.setColor(Theme.getColor("chat_secretTimerText"));
paramCanvas.drawCircle(AndroidUtilities.dpf2(9.0F), AndroidUtilities.dpf2(9.0F), AndroidUtilities.dpf2(7.5F), this.paint);
paramCanvas.drawCircle(AndroidUtilities.dpf2(9.0F), AndroidUtilities.dpf2(9.0F), AndroidUtilities.dpf2(8.0F), this.linePaint);
this.paint.setColor(Theme.getColor("chat_secretTimerText"));
paramCanvas.drawLine(AndroidUtilities.dp(9.0F), AndroidUtilities.dp(9.0F), AndroidUtilities.dp(13.0F), AndroidUtilities.dp(9.0F), this.linePaint);
paramCanvas.drawLine(AndroidUtilities.dp(9.0F), AndroidUtilities.dp(5.0F), AndroidUtilities.dp(9.0F), AndroidUtilities.dp(9.5F), this.linePaint);
paramCanvas.drawRect(AndroidUtilities.dpf2(7.0F), AndroidUtilities.dpf2(0.0F), AndroidUtilities.dpf2(11.0F), AndroidUtilities.dpf2(1.5F), this.paint);
}
while (true)
{
if ((this.time != 0) && (this.timeLayout != null))
{
int i = 0;
if (AndroidUtilities.density == 3.0F)
i = -1;
paramCanvas.translate(i + (int)(j / 2 - Math.ceil(this.timeWidth / 2.0F)), (k - this.timeHeight) / 2);
this.timeLayout.draw(paramCanvas);
}
return;
this.paint.setColor(Theme.getColor("chat_secretTimerBackground"));
this.timePaint.setColor(Theme.getColor("chat_secretTimerText"));
paramCanvas.drawCircle(AndroidUtilities.dp(9.5F), AndroidUtilities.dp(9.5F), AndroidUtilities.dp(9.5F), this.paint);
}
}
public int getIntrinsicHeight()
{
return AndroidUtilities.dp(19.0F);
}
public int getIntrinsicWidth()
{
return AndroidUtilities.dp(19.0F);
}
public int getOpacity()
{
return 0;
}
public void setAlpha(int paramInt)
{
}
public void setColorFilter(ColorFilter paramColorFilter)
{
}
public void setTime(int paramInt)
{
this.time = paramInt;
String str2;
String str1;
if ((this.time >= 1) && (this.time < 60))
{
str2 = "" + paramInt;
str1 = str2;
if (str2.length() < 2)
str1 = str2 + "s";
}
while (true)
{
this.timeWidth = this.timePaint.measureText(str1);
try
{
this.timeLayout = new StaticLayout(str1, this.timePaint, (int)Math.ceil(this.timeWidth), Layout.Alignment.ALIGN_NORMAL, 1.0F, 0.0F, false);
this.timeHeight = this.timeLayout.getHeight();
invalidateSelf();
return;
if ((this.time >= 60) && (this.time < 3600))
{
str2 = "" + paramInt / 60;
str1 = str2;
if (str2.length() >= 2)
continue;
str1 = str2 + "m";
continue;
}
if ((this.time >= 3600) && (this.time < 86400))
{
str2 = "" + paramInt / 60 / 60;
str1 = str2;
if (str2.length() >= 2)
continue;
str1 = str2 + "h";
continue;
}
if ((this.time >= 86400) && (this.time < 604800))
{
str2 = "" + paramInt / 60 / 60 / 24;
str1 = str2;
if (str2.length() >= 2)
continue;
str1 = str2 + "d";
continue;
}
str2 = "" + paramInt / 60 / 60 / 24 / 7;
if (str2.length() < 2)
{
str1 = str2 + "w";
continue;
}
str1 = str2;
if (str2.length() <= 2)
continue;
str1 = "c";
}
catch (Exception localException)
{
while (true)
{
this.timeLayout = null;
FileLog.e(localException);
}
}
}
}
}
/* Location: C:\Documents and Settings\soran\Desktop\s\classes.jar
* Qualified Name: org.vidogram.ui.Components.TimerDrawable
* JD-Core Version: 0.6.0
*/
|
gpl-2.0
|
koying/xbmc-vidonme
|
xbmc/settings/GUIWindowSettings.cpp
|
1004
|
/*
* Copyright (C) 2005-2013 Team XBMC
* http://www.xbmc.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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "system.h"
#include "GUIWindowSettings.h"
#include "guilib/Key.h"
CGUIWindowSettings::CGUIWindowSettings(void)
: CGUIWindow(WINDOW_SETTINGS_MENU, "Settings.xml")
{
m_loadType = KEEP_IN_MEMORY;
}
CGUIWindowSettings::~CGUIWindowSettings(void)
{
}
|
gpl-2.0
|
chusopr/kdepim-ktimetracker-akonadi
|
libkleo/backends/qgpgme/qgpgmekeylistjob.cpp
|
5431
|
/*
qgpgmekeylistjob.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2004,2008 Klarälvdalens Datakonsult AB
Libkleopatra 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.
Libkleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "qgpgmekeylistjob.h"
#include <gpgme++/key.h>
#include <gpgme++/context.h>
#include <gpgme++/keylistresult.h>
#include <gpg-error.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kdebug.h>
#include <QStringList>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cassert>
using namespace Kleo;
using namespace GpgME;
using namespace boost;
QGpgMEKeyListJob::QGpgMEKeyListJob( Context * context )
: mixin_type( context ),
mResult(), mSecretOnly( false )
{
lateInitialization();
}
QGpgMEKeyListJob::~QGpgMEKeyListJob() {}
static KeyListResult do_list_keys( Context * ctx, const QStringList & pats, std::vector<Key> & keys, bool secretOnly ) {
const _detail::PatternConverter pc( pats );
if ( const Error err = ctx->startKeyListing( pc.patterns(), secretOnly ) )
return KeyListResult( 0, err );
Error err;
do
keys.push_back( ctx->nextKey( err ) );
while ( !err );
keys.pop_back();
const KeyListResult result = ctx->endKeyListing();
ctx->cancelPendingOperation();
return result;
}
static QGpgMEKeyListJob::result_type list_keys( Context * ctx, QStringList pats, bool secretOnly ) {
if ( pats.size() < 2 ) {
std::vector<Key> keys;
const KeyListResult r = do_list_keys( ctx, pats, keys, secretOnly );
return make_tuple( r, keys, QString(), Error() );
}
// The communication channel between gpgme and gpgsm is limited in
// the number of patterns that can be transported, but they won't
// say to how much, so we need to find out ourselves if we get a
// LINE_TOO_LONG error back...
// We could of course just feed them single patterns, and that would
// probably be easier, but the performance penalty would currently
// be noticeable.
unsigned int chunkSize = pats.size();
retry:
std::vector<Key> keys;
keys.reserve( pats.size() );
KeyListResult result;
do {
const KeyListResult this_result = do_list_keys( ctx, pats.mid( 0, chunkSize ), keys, secretOnly );
if ( this_result.error().code() == GPG_ERR_LINE_TOO_LONG ) {
// got LINE_TOO_LONG, try a smaller chunksize:
chunkSize /= 2;
if ( chunkSize < 1 )
// chunks smaller than one can't be -> return the error.
return make_tuple( this_result, keys, QString(), Error() );
else
goto retry;
} else if ( this_result.error().code() == GPG_ERR_EOF ) {
// early end of keylisting (can happen when ~/.gnupg doesn't
// exist). Fakeing an empty result:
return make_tuple( KeyListResult(), std::vector<Key>(), QString(), Error() );
}
// ok, that seemed to work...
result.mergeWith( this_result );
if ( result.error().code() )
break;
pats = pats.mid( chunkSize );
} while ( !pats.empty() );
return make_tuple( result, keys, QString(), Error() );
}
Error QGpgMEKeyListJob::start( const QStringList & patterns, bool secretOnly ) {
mSecretOnly = secretOnly;
run( boost::bind( &list_keys, _1, patterns, secretOnly ) );
return Error();
}
KeyListResult QGpgMEKeyListJob::exec( const QStringList & patterns, bool secretOnly, std::vector<Key> & keys ) {
mSecretOnly = secretOnly;
const result_type r = list_keys( context(), patterns, secretOnly );
resultHook( r );
keys = get<1>( r );
return get<0>( r );
}
void QGpgMEKeyListJob::resultHook( const result_type & tuple ) {
mResult = get<0>( tuple );
Q_FOREACH( const Key & key, get<1>( tuple ) )
emit nextKey( key );
}
void QGpgMEKeyListJob::showErrorDialog( QWidget * parent, const QString & caption ) const {
if ( !mResult.error() || mResult.error().isCanceled() )
return;
const QString msg = i18n( "<qt><p>An error occurred while fetching "
"the keys from the backend:</p>"
"<p><b>%1</b></p></qt>" ,
QString::fromLocal8Bit( mResult.error().asString() ) );
KMessageBox::error( parent, msg, caption );
}
#include "qgpgmekeylistjob.moc"
|
gpl-2.0
|
iammdmusa/muri
|
template-parts/content-gallery.php
|
2957
|
<?php
/**
* Template part for displaying posts.
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package muri
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="cat-post-section">
<div class="row item">
<h2 class="post-title">
<a href="<?php the_permalink();?>">
<?php the_title();?>
</a>
</h2>
<?php
$cats = array();
global $post;
foreach(wp_get_post_categories($post->ID) as $c)
{
$cat = get_category($c);
array_push($cats,$cat->name);
}
$post_categories = '';
if(sizeOf($cats)>0)
{
$post_categories = sprintf(esc_html_x('%s','post category','muri'),'<a href="'.esc_url( get_category_link( $cat->term_id ) ) .'">'.implode(',',$cats).'</a>');
}
?>
<div class="post-meta">
<span class="author">
<i class="fa fa-user"></i>
<a href="<?php echo esc_url(get_author_posts_url( get_the_author_meta( 'ID' )));?>">
<?php echo esc_html( get_the_author() );?>
</a>
</span>
<span class="date">
<i class="fa fa-calendar"></i>
<?php echo date_i18n( get_option( 'date_format' ), strtotime( '11/15-1976' ) );?>
</span>
<span class="in-cate">
<i class="fa fa-pencil"></i>
<?php echo $post_categories; ?>
</span>
</div>
<?php
global $post;
preg_match('/ids="([^"]+)"/', get_the_content(), $match);
$img_id = $match[1];
$imgArray = explode(",",$img_id);
$img = array();
?>
<!-- content -->
<div class="row gallery">
<?php
foreach ($imgArray as $imgSrcId => $imgUrl) {
$imgSrcId = wp_get_attachment_image_src($imgUrl, 'full');
$html = '<div class="img-gallery">
<a class="image-link" href="'.$imgSrcId[0].'">
<img src="'.$imgSrcId[0].'" alt="" class="img-responsive">
</a>
</div>';
echo $html;
}
?>
</div>
<p class="post-desc">
<?php echo excerpt(40);?>
</p>
<p>
<a href="<?php the_permalink();?>" class="btn btn-default btn-txt"><i class="fa fa-long-arrow-right"></i><?php _e('LEARN MORE','muri');?></a>
</p>
</div>
</div>
</article><!-- #post-## -->
|
gpl-2.0
|
kunj1988/Magento2
|
lib/internal/Magento/Framework/View/Test/Unit/Element/Html/Link/CurrentTest.php
|
3919
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\View\Test\Unit\Element\Html\Link;
class CurrentTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $_urlBuilderMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $_requestMock;
/**
* @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
*/
protected $_objectManager;
protected function setUp()
{
$this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
$this->_urlBuilderMock = $this->createMock(\Magento\Framework\UrlInterface::class);
$this->_requestMock = $this->createMock(\Magento\Framework\App\Request\Http::class);
}
public function testGetUrl()
{
$path = 'test/path';
$url = 'http://example.com/asdasd';
$this->_urlBuilderMock->expects($this->once())->method('getUrl')->with($path)->will($this->returnValue($url));
/** @var \Magento\Framework\View\Element\Html\Link\Current $link */
$link = $this->_objectManager->getObject(
\Magento\Framework\View\Element\Html\Link\Current::class,
['urlBuilder' => $this->_urlBuilderMock]
);
$link->setPath($path);
$this->assertEquals($url, $link->getHref());
}
public function testIsCurrentIfIsset()
{
/** @var \Magento\Framework\View\Element\Html\Link\Current $link */
$link = $this->_objectManager->getObject(\Magento\Framework\View\Element\Html\Link\Current::class);
$link->setCurrent(true);
$this->assertTrue($link->isCurrent());
}
/**
* Test if the current url is the same as link path
*
* @return void
*/
public function testIsCurrent()
{
$path = 'test/index';
$url = 'http://example.com/test/index';
$this->_requestMock->expects($this->once())
->method('getPathInfo')
->will($this->returnValue('/test/index/'));
$this->_requestMock->expects($this->once())
->method('getModuleName')
->will($this->returnValue('test'));
$this->_requestMock->expects($this->once())
->method('getControllerName')
->will($this->returnValue('index'));
$this->_requestMock->expects($this->once())
->method('getActionName')
->will($this->returnValue('index'));
$this->_urlBuilderMock->expects($this->at(0))
->method('getUrl')
->with($path)
->will($this->returnValue($url));
$this->_urlBuilderMock->expects($this->at(1))
->method('getUrl')
->with('test/index')
->will($this->returnValue($url));
/** @var \Magento\Framework\View\Element\Html\Link\Current $link */
$link = $this->_objectManager->getObject(
\Magento\Framework\View\Element\Html\Link\Current::class,
[
'urlBuilder' => $this->_urlBuilderMock,
'request' => $this->_requestMock
]
);
$link->setPath($path);
$this->assertTrue($link->isCurrent());
}
public function testIsCurrentFalse()
{
$this->_urlBuilderMock->expects($this->at(0))->method('getUrl')->will($this->returnValue('1'));
$this->_urlBuilderMock->expects($this->at(1))->method('getUrl')->will($this->returnValue('2'));
/** @var \Magento\Framework\View\Element\Html\Link\Current $link */
$link = $this->_objectManager->getObject(
\Magento\Framework\View\Element\Html\Link\Current::class,
['urlBuilder' => $this->_urlBuilderMock, 'request' => $this->_requestMock]
);
$this->assertFalse($link->isCurrent());
}
}
|
gpl-2.0
|
JeroenDeDauw/mediawiki-extensions-WikibaseQueryEngine
|
WikibaseQueryEngine.php
|
2913
|
<?php
/**
* Entry point for the Query component of Wikibase.
*
* @since 0.1
*
* @file
* @ingroup WikibaseQueryEngine
*
* @licence GNU GPL v2+
* @author Jeroen De Dauw < jeroendedauw@gmail.com >
*/
if ( defined( 'WIKIBASE_QUERYENGINE_VERSION' ) ) {
// Do not initialize more then once.
return;
}
define( 'WIKIBASE_QUERYENGINE_VERSION', '0.1 alpha' );
// Attempt to include the dependencies mif one of them has not been loaded yet.
// This is the path to the autoloader generated by composer in case of a composer install.
if ( ( !defined( 'Ask_VERSION' ) || !defined( 'DataValues_VERSION' ) || !defined( 'WIKIBASE_DATAMODEL_VERSION' ) || !defined( 'WIKIBASE_DATABASE_VERSION' ) )
&& is_readable( __DIR__ . '/vendor/autoload.php' ) ) {
include_once( __DIR__ . '/vendor/autoload.php' );
}
// Attempt to include the DataValues lib if that hasn't been done yet.
if ( !defined( 'DataValues_VERSION' ) && file_exists( __DIR__ . '/../DataValues/DataValues.php' ) ) {
include_once( __DIR__ . '/../DataValues/DataValues.php' );
}
// Attempt to include the Ask lib if that hasn't been done yet.
if ( !defined( 'Ask_VERSION' ) && file_exists( __DIR__ . '/../Ask/Ask.php' ) ) {
include_once( __DIR__ . '/../Ask/Ask.php' );
}
// Attempt to include the DataModel lib if that hasn't been done yet.
if ( !defined( 'WIKIBASE_DATAMODEL_VERSION' ) && file_exists( __DIR__ . '/../WikibaseDataModel/WikibaseDataModel.php' ) ) {
include_once( __DIR__ . '/../WikibaseDataModel/WikibaseDataModel.php' );
}
// Attempt to include the Ask lib if that hasn't been done yet.
if ( !defined( 'WIKIBASE_DATABASE_VERSION' ) && file_exists( __DIR__ . '/../WikibaseDatabase/WikibaseDatabase.php' ) ) {
include_once( __DIR__ . '/../WikibaseDatabase/WikibaseDatabase.php' );
}
spl_autoload_register( function ( $className ) {
$className = ltrim( $className, '\\' );
$fileName = '';
$namespace = '';
if ( $lastNsPos = strripos( $className, '\\') ) {
$namespace = substr( $className, 0, $lastNsPos );
$className = substr( $className, $lastNsPos + 1 );
$fileName = str_replace( '\\', '/', $namespace ) . '/';
}
$fileName .= str_replace( '_', '/', $className ) . '.php';
$namespaceSegments = explode( '\\', $namespace );
$inQueryEngineNamespace = count( $namespaceSegments ) > 1
&& $namespaceSegments[0] === 'Wikibase'
&& $namespaceSegments[1] === 'QueryEngine';
if ( $inQueryEngineNamespace ) {
$inTestNamespace = count( $namespaceSegments ) > 2 && $namespaceSegments[2] === 'Tests';
if ( !$inTestNamespace ) {
$pathParts = explode( '/', $fileName );
array_shift( $pathParts );
array_shift( $pathParts );
$fileName = implode( '/', $pathParts );
require_once __DIR__ . '/src/' . $fileName;
}
}
} );
// @codeCoverageIgnoreStart
if ( defined( 'MEDIAWIKI' ) ) {
call_user_func( function() {
require_once __DIR__ . '/WikibaseQueryEngine.mw.php';
} );
}
// @codeCoverageIgnoreEnd
|
gpl-2.0
|
dipacs/Viwib
|
trunk/src/Viwib/src/com/eagerlogic/viwib/connectors/common/CommonConnector.java
|
19129
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.eagerlogic.viwib.connectors.common;
import com.eagerlogic.viwib.MyCookieManager;
import com.eagerlogic.viwib.connectors.Category;
import com.eagerlogic.viwib.connectors.ASiteConnector;
import com.eagerlogic.viwib.connectors.NewestTorrents;
import com.eagerlogic.viwib.connectors.SearchResult;
import com.eagerlogic.viwib.connectors.SiteConfig;
import com.eagerlogic.viwib.connectors.SortCategory;
import com.eagerlogic.viwib.connectors.TorrentDescriptor;
import com.eagerlogic.viwib.connectors.ncore.NCoreSiteConnector;
import com.eagerlogic.viwib.utils.URLCoder;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.image.Image;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
*
* @author dipacs
*/
public class CommonConnector extends ASiteConnector {
private SiteConfig siteConfig = null;
public CommonConnector(String siteUrl) {
super(siteUrl);
}
@Override
public SiteConfig getConfig() {
if (this.siteConfig != null) {
return this.siteConfig;
}
SiteConfig res = new SiteConfig();
String jsonStr = this.request(this.getSiteUrl() + "/viwib.json");
if (jsonStr == null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, "Can't find '" + this.getSiteUrl() + "/viwib.json'.");
return null;
}
try {
JSONObject root = (JSONObject) JSONValue.parseWithException(jsonStr);
// parsing version
String version = (String) root.get("version");
if (version == null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, "The 'version' attribute is missing from viwib.json");
return null;
}
res.setVersion(version);
// parsing name
String name = (String) root.get("name");
if (name == null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, "The 'name' attribute is missing from viwib.json");
return null;
}
res.setName(name);
// parsing description
String description = (String) root.get("description");
res.setDescription(description);
// parsing url
String url = (String) root.get("url");
if (url == null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, "The 'url' attribute is missing from viwib.json");
return null;
}
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://" + url;
}
if (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
res.setUrl(url);
// parsing apiUrl
String apiUrl = (String) root.get("apiUrl");
if (apiUrl == null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, "The 'apiUrl' attribute is missing from viwib.json");
return null;
}
res.setApiUrl(apiUrl);
// parsing needLogin
Boolean needLogin = (Boolean) root.get("needLogin");
if (needLogin == null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, "The 'needLogin' attribute is missing from viwib.json");
return null;
}
res.setNeedLogin(needLogin == Boolean.TRUE);
// parsing keepAliveInterval
Number keepAliveInterval = (Long) root.get("keepAliveInterval");
if (keepAliveInterval == null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, "The 'keepAliveInterval' attribute is missing from viwib.json");
return null;
}
res.setKeepAliveInterval(keepAliveInterval.intValue());
// parsing categories
String err = parseCategories(root, res);
if (err != null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, err);
return null;
}
// parsing sort categories
JSONArray sortCatsArr = (JSONArray) root.get("sortCategories");
if (sortCatsArr == null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, "The 'sortCategories' attribute is missing from viwib.json");
return null;
}
err = parseSortCategories(sortCatsArr, res);
if (err != null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, err);
return null;
}
this.siteConfig = res;
return this.siteConfig;
} catch (Throwable ex) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
private String parseCategories(JSONObject root, SiteConfig res) {
JSONArray categories = (JSONArray) root.get("categories");
if (categories == null) {
return "The 'categories' attribute is missing from viwib.json";
}
ArrayList<Category> catList = new ArrayList<Category>();
for (Object catObj : categories) {
JSONObject cat = (JSONObject) catObj;
Category category = new Category();
String err = parseCategory(cat, category);
if (err != null) {
return err;
}
catList.add(category);
}
res.setCategories(catList.toArray(new Category[catList.size()]));
return null;
}
private String parseSortCategories(JSONArray scArr, SiteConfig res) {
ArrayList<SortCategory> sortCats = new ArrayList<SortCategory>();
for (Object scObjObj : scArr) {
JSONObject scObj = (JSONObject) scObjObj;
String id = (String) scObj.get("id");
if (id == null) {
return "Missing 'id' attribute of SortCategory in viwib.json.";
}
String name = (String) scObj.get("name");
if (name == null) {
return "Missing 'name' attribute of SortCategory in viwib.json.";
}
Boolean descendent = (Boolean) scObj.get("isDescending");
if (descendent == null) {
return "Missing 'isDescending' attribute of SortCategory in viwib.json.";
}
SortCategory sc = new SortCategory(id, name);
sc.setDesc(descendent == Boolean.TRUE);
sortCats.add(sc);
}
res.setSortCategories(sortCats.toArray(new SortCategory[sortCats.size()]));
return null;
}
private String parseCategory(JSONObject cat, Category res) {
// parsing id
String id = (String) cat.get("id");
if (id == null) {
return "The 'id' attribute of a category is missing in the viwib.json";
}
res.setId(id);
// parsing name
String name = (String) cat.get("name");
if (name == null) {
return "The 'name' attribute of a category is missing in the viwib.json";
}
res.setName(name);
// parsing description
String description = (String) cat.get("description");
res.setDescription(description);
// parsing adult
Boolean adult = (Boolean) cat.get("adult");
if (adult == null) {
return "The 'adult' attribute of a category is missing in the viwib.json";
}
res.setAdult(adult == Boolean.TRUE);
// parsing children
ArrayList<Category> childList = new ArrayList<Category>();
JSONArray children = (JSONArray) cat.get("children");
if (children != null) {
for (Object childObj : children) {
JSONObject child = (JSONObject) childObj;
Category c = new Category();
String err = parseCategory(child, c);
if (err != null) {
return err;
}
childList.add(c);
}
}
if (childList.size() > 0) {
res.setChildren(childList.toArray(new Category[childList.size()]));
}
return null;
}
@Override
public SearchResult search(String term, Category[] categories, SortCategory sortCategory, int pageIndex) {
String url = this.getConfig().getUrl() + this.getConfig().getApiUrl();
url += "?";
// ssid
if (this.getConfig().isNeedLogin()) {
url += "ssid=" + URLCoder.encode(this.getSsid()) + "&";
}
// action
url += "action=search&";
// search term
url += "s=" + URLCoder.encode(term);
// categories
url += "&cat=";
String cats = "";
boolean isFirst = true;
for (Category cat : categories) {
if (isFirst) {
isFirst = false;
} else {
cats += ",";
}
cats += cat.getId();
}
url += URLCoder.encode(cats);
// sort
url += "&sort=" + URLCoder.encode(sortCategory.getId());
// sort order
String desc = "false";
if (sortCategory.isDesc()) {
desc = "true";
}
url+= "&desc=" + desc;
// page index
url += "&page=" + pageIndex;
String jsonStr = this.request(url);
if (jsonStr == null) {
throw new RuntimeException("Can't access the server.");
}
try {
SearchResult res = new SearchResult();
JSONObject results = (JSONObject) JSONValue.parseWithException(jsonStr);
// parsing total count
Number totalCount = (Number) results.get("totalCount");
if (totalCount == null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, "The 'totalCount' attribute is missing from the result.");
throw new RuntimeException("The 'totalCount' attribute is missing from the result.");
}
res.setTotalCount(totalCount.intValue());
// parsing page index
Number pi = (Number) results.get("pageIndex");
if (pi == null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, "The 'pageIndex' attribute is missing from the result.");
throw new RuntimeException("The 'pageIndex' attribute is missing from the result.");
}
res.setPageIndex(pi.intValue());
// parsing page size
Number pageSize = (Number) results.get("pageIndex");
if (pageSize == null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, "The 'pageSize' attribute is missing from the result.");
throw new RuntimeException("The 'pageSize' attribute is missing from the result.");
}
res.setPageSize(pageSize.intValue());
// parsing results
JSONArray resultsJArray = (JSONArray) results.get("results");
if (resultsJArray == null) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, "The 'results' attribute is missing from the result.");
throw new RuntimeException("The 'results' attribute is missing from the result.");
}
ArrayList<TorrentDescriptor> descriptors = new ArrayList<TorrentDescriptor>();
for (Object o : resultsJArray) {
JSONObject jo = (JSONObject) o;
try {
TorrentDescriptor td = parseResultItem(jo);
descriptors.add(td);
}catch (Throwable t) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, t.getMessage());
throw new RuntimeException(t.getMessage());
}
}
res.setResult(descriptors.toArray(new TorrentDescriptor[descriptors.size()]));
return res;
} catch (ParseException ex) {
Logger.getLogger(CommonConnector.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException("Invalid response from the server.");
}
}
private TorrentDescriptor parseResultItem(JSONObject resItem) {
TorrentDescriptor res = new TorrentDescriptor();
// parsing id
String id = (String) resItem.get("id");
if (id == null) {
throw new RuntimeException("The 'id' attribute is missing from the result.");
}
res.setId(id);
// parsing name
String name = (String) resItem.get("name");
if (name == null) {
throw new RuntimeException("The 'name' attribute is missing from the result.");
}
res.setName(name);
// parsing description
String description = (String) resItem.get("description");
if (description == null) {
throw new RuntimeException("The 'description' attribute is missing from the result.");
}
res.setDescription(description);
// parsing torrentUrl
String torrentUrl = (String) resItem.get("torrentUrl");
if (torrentUrl == null) {
throw new RuntimeException("The 'torrentUrl' attribute is missing from the result.");
}
res.setTorrentUrl(torrentUrl);
// parsing coverUrl
String coverUrl = (String) resItem.get("coverUrl");
res.setTorrentUrl(coverUrl);
// parsing dateAdded
String dateAdded = (String) resItem.get("dateAdded");
if (dateAdded == null) {
throw new RuntimeException("The 'dateAdded' attribute is missing from the result.");
}
res.setDateAdded(dateAdded);
// parsing seeders
Number seeds = (Number) resItem.get("seeders");
if (seeds == null) {
throw new RuntimeException("The 'seeders' attribute is missing from the result.");
}
res.setSeeds(seeds.intValue());
// parsing leeches
Number leechers = (Number) resItem.get("leechers");
if (leechers == null) {
throw new RuntimeException("The 'leechers' attribute is missing from the result.");
}
res.setLeeches(leechers.intValue());
// parsing downloaded
Number downloaded = (Number) resItem.get("downloaded");
if (downloaded == null) {
throw new RuntimeException("The 'downloaded' attribute is missing from the result.");
}
res.setDownloaded(downloaded.intValue());
// parsing size
String size = (String) resItem.get("size");
if (size == null) {
throw new RuntimeException("The 'size' attribute is missing from the result.");
}
res.setSize(size);
// parsing categoryId
String categoryId = (String) resItem.get("categoryId");
if (categoryId == null) {
throw new RuntimeException("The 'categoryId' attribute is missing from the result.");
}
res.setCategoryId(categoryId);
return res;
}
@Override
public void login(String username, String password) {
if (!getConfig().isNeedLogin()) {
return;
}
String url = this.getSiteUrl() + this.getConfig().getApiUrl();
url += "?action=login";
url += "&un=" + URLCoder.encode(username);
url += "&pw=" + URLCoder.encode(password);
String response = request(url);
if (response == null) {
throw new RuntimeException("The server does not answer.");
}
try {
JSONObject jo = (JSONObject) new JSONParser().parse(response);
String ssid = (String) jo.get("ssid");
if (ssid == null) {
String err = (String) jo.get("error");
if (err == null) {
throw new RuntimeException("Invalid answer from the server");
}
throw new RuntimeException(err);
}
this.setSsid(ssid);
} catch (ParseException ex) {
throw new RuntimeException(ex);
}
}
@Override
public void keepAlive(String ssid) {
if (!getConfig().isNeedLogin()) {
return;
}
if (this.getSsid() == null) {
return;
}
String url = this.getSiteUrl() + this.getConfig().getApiUrl();
url += "?action=keepalive";
url += "&ssid=" + URLCoder.encode(this.getSsid());
request(url);
}
@Override
public double getSeedProgress(String torrentId) {
String url = this.getSiteUrl() + this.getConfig().getApiUrl();
url += "?action=getSeedProgress";
if (this.getSsid() != null) {
url += "&ssid=" + URLCoder.encode(this.getSsid());
}
url += "&tid=" + URLCoder.encode(torrentId);
String response = request(url);
if (response == null) {
System.out.println("The server does not answered for the getSeedProgress.");
throw new RuntimeException("The server does not answered for the getSeedProgress request.");
}
try {
JSONObject jo = (JSONObject) new JSONParser().parse(response);
Double progress = (Double) jo.get("progress");
if (progress == null) {
throw new RuntimeException("The returned seed progress is null.");
}
if (progress < 0.0) {
progress = 0.0;
}
return progress;
} catch (ParseException ex) {
throw new RuntimeException(ex);
}
}
@Override
public void logout() {
if (!getConfig().isNeedLogin()) {
return;
}
if (this.getSsid() == null) {
return;
}
String url = this.getSiteUrl() + this.getConfig().getApiUrl();
url += "?action=logout";
url += "&ssid=" + URLCoder.encode(this.getSsid());
request(url);
}
}
|
gpl-2.0
|
apigee/apigee-edge-drupal
|
modules/apigee_edge_teams/src/Entity/TeamTitleProvider.php
|
1775
|
<?php
/**
* Copyright 2018 Google Inc.
*
* 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.
*/
namespace Drupal\apigee_edge_teams\Entity;
use Drupal\apigee_edge\Entity\EdgeEntityTitleProvider;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Team specific title additions and overrides.
*/
class TeamTitleProvider extends EdgeEntityTitleProvider {
/**
* Provides a title for the team members listing page.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
* @param \Drupal\Core\Entity\EntityInterface $_entity
* (optional) An entity, passed in directly from the request attributes.
*
* @return string|null
* The title for the team members listing page, null if an entity was found.
*/
public function teamMembersList(RouteMatchInterface $route_match, EntityInterface $_entity = NULL) {
if ($entity = $this->doGetEntity($route_match, $_entity)) {
return $this->t('@entity_type Members', [
'@entity_type' => ucfirst($this->entityTypeManager->getDefinition($entity->getEntityTypeId())->getSingularLabel()),
]);
}
}
}
|
gpl-2.0
|
iammyr/Benchmark
|
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest06877.java
|
2510
|
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest06877")
public class BenchmarkTest06877 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheValue("foo");
String bar;
// Simple if statement that assigns param to bar on true condition
int i = 196;
if ( (500/42) + i > 200 )
bar = param;
else bar = "This should never happen";
String a1 = "";
String a2 = "";
String osName = System.getProperty("os.name");
if (osName.indexOf("Windows") != -1) {
a1 = "cmd.exe";
a2 = "/c";
} else {
a1 = "sh";
a2 = "-c";
}
String[] args = {a1, a2, "echo", bar};
ProcessBuilder pb = new ProcessBuilder();
pb.command(args);
try {
Process p = pb.start();
org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
} catch (IOException e) {
System.out.println("Problem executing cmdi - java.lang.ProcessBuilder(java.util.List) Test Case");
throw new ServletException(e);
}
}
}
|
gpl-2.0
|
weavermj/inquire
|
administrator/components/com_dropfiles/helpers/installer.php
|
2620
|
<?php
/**
* Dropfiles
*
* We developed this code with our hearts and passion.
* We hope you found it useful, easy to understand and to customize.
* Otherwise, please feel free to contact us at contact@joomunited.com *
* @package Dropfiles
* @copyright Copyright (C) 2013 JoomUnited (http://www.joomunited.com). All rights reserved.
* @copyright Copyright (C) 2013 Damien Barrère (http://www.crac-design.com). All rights reserved.
* @license GNU General Public License version 2 or later; http://www.gnu.org/licenses/gpl-2.0.html
*/
// no direct access
defined('_JEXEC') or die;
class DropfilesInstallerHelper{
/**
* Install an extension from a folder
* @param string $folder
* @param boolean $enable
* @return boolean
*/
static public function install($folder,$enable=false){
// Get an installer instance
$installer = new JInstaller();
// Install the package
if (!$installer->install($folder)) {
// There was an error installing the package
$result = false;
} else {
// Package installed sucessfully
$result = true;
//enable plugin or module
if($enable){
$group = $installer->manifest->attributes()->group;
$name = $installer->manifest->name;
$dbo = JFactory::getDbo();
$query = 'UPDATE #__extensions SET enabled=1 WHERE name='.$dbo->quote($name).' AND folder='.$dbo->quote($group);
$dbo->setQuery($query);
$dbo->query($query);
}
//Unset the last plugin message
$installer->set('message','');
}
return $result;
}
/**
* Enable an extension
* @param type $name
* @param type $type
* @return type
*/
static public function enableExtension($element, $type='',$folder=''){
$dbo = JFactory::getDbo();
$query = 'UPDATE #__extensions SET enabled=1 WHERE element='.$dbo->quote($element);
if($type!=''){
$query .= ' AND type='.$dbo->quote($type);
}
if($folder!=''){
$query .= ' AND folder='.$dbo->quote($folder);
}
$dbo->setQuery($query);
return $dbo->query($query);
}
static public function uninstall($folder){
// $installer = new JInstaller();
//
// // Install the package
// if ($installer-> uninstall()) {
// return true;
// }
// return false;
}
}
?>
|
gpl-2.0
|
raeldc/nooku-server
|
administrator/components/com_banners/dispatcher.php
|
926
|
<?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Weblinks
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Component Dispatcher
*
* @author Jeremy Wilken <http://nooku.assembla.com/profile/gnomeontherun>
* @category Nooku
* @package Nooku_Server
* @subpackage Weblinks
*/
class ComBannersDispatcher extends ComDefaultDispatcher
{
public function _actionAuthorize(KCommandContext $context)
{
$result = parent::_actionAuthorize($context);
if(!JFactory::getUser()->authorize( 'com_weblinks', 'manage' ))
{
throw new KDispatcherException(JText::_('ALERTNOTAUTH'), KHttpResponse::FORBIDDEN);
$result = false;
}
return $result;
}
}
|
gpl-2.0
|
timothy003/TrinityCore-m4a
|
src/bindings/scripts/scripts/zone/karazhan/boss_shade_of_aran.cpp
|
22299
|
/* Copyright (C) 2006 - 2008 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_Shade_of_Aran
SD%Complete: 95
SDComment: Flame wreath missing cast animation, mods won't triggere. Drinking may cause client crash (core related)
SDCategory: Karazhan
EndScriptData */
#include "precompiled.h"
#include "../../creature/simple_ai.h"
#include "def_karazhan.h"
#include "GameObject.h"
//Aggro
#define SAY_AGGRO1 "Please, no more. My son... he's gone mad!"
#define SOUND_AGGRO1 9241
#define SAY_AGGRO2 "I'll not be tortured again!"
#define SOUND_AGGRO2 9323
#define SAY_AGGRO3 "Who are you? What do you want? Stay away from me!"
#define SOUND_AGGRO3 9324
//Flame Wreath
#define SAY_FLAMEWREATH1 "I'll show you this beaten dog still has some teeth!"
#define SOUND_FLAMEWREATH1 9245
#define SAY_FLAMEWREATH2 "Burn you hellish fiends!"
#define SOUND_FLAMEWREATH2 9326
//Blizzard
#define SAY_BLIZZARD1 "I'll freeze you all!"
#define SOUND_BLIZZARD1 9246
#define SAY_BLIZZARD2 "Back to the cold dark with you!"
#define SOUND_BLIZZARD2 9327
//Arcane Explosion
#define SAY_EXPLOSION1 "Yes, yes, my son is quite powerful... but I have powers of my own!"
#define SOUND_EXPLOSION1 9242
#define SAY_EXPLOSION2 "I am not some simple jester! I am Nielas Aran!"
#define SOUND_EXPLOSION2 9325
//Low Mana / AoE Pyroblast
#define SAY_DRINK "Surely you would not deny an old man a replenishing drink? No, no I thought not."
#define SOUND_DRINK 9248
//Summon Water Elementals
#define SAY_ELEMENTALS "I'm not finished yet! No, I have a few more tricks up me sleeve."
#define SOUND_ELEMENTALS 9251
//Player Death
#define SAY_KILL1 "I want this nightmare to be over!"
#define SOUND_KILL1 9250
#define SAY_KILL2 "Torment me no more!"
#define SOUND_KILL2 9328
//Time over
#define SAY_TIMEOVER "You've wasted enough of my time. Let these games be finished!"
#define SOUND_TIMEOVER 9247
//Aran's death
#define SAY_DEATH "At last... The nightmare is.. over..."
#define SOUND_DEATH 9244
//Atiesh is equipped by a raid member
#define SAY_ATIESH "Where did you get that?! Did HE send you?!"
#define SOUND_ATIESH 9249
//Spells
#define SPELL_FROSTBOLT 29954
#define SPELL_FIREBALL 29953
#define SPELL_ARCMISSLE 29955
#define SPELL_CHAINSOFICE 29991
#define SPELL_DRAGONSBREATH 29964
#define SPELL_MASSSLOW 30035
#define SPELL_FLAME_WREATH 29946
#define SPELL_AOE_CS 29961
#define SPELL_PLAYERPULL 32265
#define SPELL_AEXPLOSION 29973
#define SPELL_MASS_POLY 29963
#define SPELL_BLINK_CENTER 29967
#define SPELL_ELEMENTALS 29962
#define SPELL_CONJURE 29975
#define SPELL_DRINK 30024
#define SPELL_POTION 32453
#define SPELL_AOE_PYROBLAST 29978
//Creature Spells
#define SPELL_CIRCULAR_BLIZZARD 29951 //29952 is the REAL circular blizzard that leaves persistant blizzards that last for 10 seconds
#define SPELL_WATERBOLT 31012
#define SPELL_SHADOW_PYRO 29978
//Creatures
#define CREATURE_WATER_ELEMENTAL 17167
#define CREATURE_SHADOW_OF_ARAN 18254
#define CREATURE_ARAN_BLIZZARD 17161
enum SuperSpell
{
SUPER_FLAME = 0,
SUPER_BLIZZARD,
SUPER_AE,
};
struct TRINITY_DLL_DECL boss_aranAI : public ScriptedAI
{
boss_aranAI(Creature *c) : ScriptedAI(c)
{
pInstance = ((ScriptedInstance*)c->GetInstanceData());
Reset();
}
ScriptedInstance* pInstance;
uint32 SecondarySpellTimer;
uint32 NormalCastTimer;
uint32 SuperCastTimer;
uint32 BerserkTimer;
uint32 CloseDoorTimer; // Don't close the door right on aggro in case some people are still entering.
uint8 LastSuperSpell;
uint32 FlameWreathTimer;
uint32 FlameWreathCheckTime;
uint64 FlameWreathTarget[3];
float FWTargPosX[3];
float FWTargPosY[3];
uint32 CurrentNormalSpell;
uint32 ArcaneCooldown;
uint32 FireCooldown;
uint32 FrostCooldown;
uint32 DrinkInturruptTimer;
bool ElementalsSpawned;
bool Drinking;
bool DrinkInturrupted;
void Reset()
{
SecondarySpellTimer = 5000;
NormalCastTimer = 0;
SuperCastTimer = 35000;
BerserkTimer = 720000;
CloseDoorTimer = 15000;
LastSuperSpell = rand()%3;
FlameWreathTimer = 0;
FlameWreathCheckTime = 0;
CurrentNormalSpell = 0;
ArcaneCooldown = 0;
FireCooldown = 0;
FrostCooldown = 0;
DrinkInturruptTimer = 10000;
ElementalsSpawned = false;
Drinking = false;
DrinkInturrupted = false;
if(pInstance)
{
// Not in progress
pInstance->SetData(DATA_SHADEOFARAN_EVENT, NOT_STARTED);
if(GameObject* Door = GameObject::GetGameObject(*m_creature, pInstance->GetData64(DATA_GAMEOBJECT_LIBRARY_DOOR)))
Door->SetGoState(0);
}
}
void KilledUnit(Unit *victim)
{
switch(rand()%2)
{
case 0:
DoYell(SAY_KILL1, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(victim, SOUND_KILL1);
break;
case 1:
DoYell(SAY_KILL2, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(victim, SOUND_KILL2);
break;
}
}
void JustDied(Unit *victim)
{
DoYell(SAY_DEATH, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(NULL, SOUND_DEATH);
if(pInstance)
{
pInstance->SetData(DATA_SHADEOFARAN_EVENT, DONE);
if(GameObject* Door = GameObject::GetGameObject(*m_creature, pInstance->GetData64(DATA_GAMEOBJECT_LIBRARY_DOOR)))
Door->SetGoState(0);
}
}
void Aggro(Unit *who)
{
switch(rand()%3)
{
case 0:
DoYell(SAY_AGGRO1, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(m_creature, SOUND_AGGRO1);
break;
case 1:
DoYell(SAY_AGGRO2, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(m_creature, SOUND_AGGRO2);
break;
case 2:
DoYell(SAY_AGGRO3, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(m_creature, SOUND_AGGRO3);
break;
}
if(pInstance)
pInstance->SetData(DATA_SHADEOFARAN_EVENT, IN_PROGRESS);
}
void FlameWreathEffect()
{
std::vector<Unit*> targets;
std::list<HostilReference *> t_list = m_creature->getThreatManager().getThreatList();
if(!t_list.size())
return;
//store the threat list in a different container
for(std::list<HostilReference *>::iterator itr = t_list.begin(); itr!= t_list.end(); ++itr)
{
Unit *target = Unit::GetUnit(*m_creature, (*itr)->getUnitGuid());
//only on alive players
if(target && target->isAlive() && target->GetTypeId() == TYPEID_PLAYER )
targets.push_back( target);
}
//cut down to size if we have more than 3 targets
while(targets.size() > 3)
targets.erase(targets.begin()+rand()%targets.size());
uint32 i = 0;
for(std::vector<Unit*>::iterator itr = targets.begin(); itr!= targets.end(); ++itr)
{
if(*itr)
{
FlameWreathTarget[i] = (*itr)->GetGUID();
FWTargPosX[i] = (*itr)->GetPositionX();
FWTargPosY[i] = (*itr)->GetPositionY();
m_creature->CastSpell((*itr), SPELL_FLAME_WREATH, true);
i++;
}
}
}
void UpdateAI(const uint32 diff)
{
if (!m_creature->SelectHostilTarget() || !m_creature->getVictim() )
return;
if(CloseDoorTimer)
if(CloseDoorTimer <= diff)
{
if(pInstance)
if(GameObject* Door = GameObject::GetGameObject(*m_creature, pInstance->GetData64(DATA_GAMEOBJECT_LIBRARY_DOOR)))
Door->SetGoState(1);
CloseDoorTimer = 0;
}
else CloseDoorTimer -= diff;
//Cooldowns for casts
if (ArcaneCooldown)
if (ArcaneCooldown >= diff)
ArcaneCooldown -= diff;
else ArcaneCooldown = 0;
if (FireCooldown)
if (FireCooldown >= diff)
FireCooldown -= diff;
else FireCooldown = 0;
if (FrostCooldown)
if (FrostCooldown >= diff)
FrostCooldown -= diff;
else FrostCooldown = 0;
if(!Drinking && m_creature->GetMaxPower(POWER_MANA) && (m_creature->GetPower(POWER_MANA)*100 / m_creature->GetMaxPower(POWER_MANA)) < 20)
{
Drinking = true;
m_creature->InterruptNonMeleeSpells(false);
DoYell(SAY_DRINK, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(m_creature, SOUND_DRINK);
if (!DrinkInturrupted)
{
m_creature->CastSpell(m_creature, SPELL_MASS_POLY, true);
m_creature->CastSpell(m_creature, SPELL_CONJURE, false);
m_creature->CastSpell(m_creature, SPELL_DRINK, false);
//Sitting down
m_creature->SetUInt32Value(UNIT_FIELD_BYTES_1, 1);
DrinkInturruptTimer = 10000;
}
}
//Drink Inturrupt
if (Drinking && DrinkInturrupted)
{
Drinking = false;
m_creature->RemoveAurasDueToSpell(SPELL_DRINK);
m_creature->SetUInt32Value(UNIT_FIELD_BYTES_1, 0);
m_creature->SetPower(POWER_MANA, m_creature->GetMaxPower(POWER_MANA)-32000);
m_creature->CastSpell(m_creature, SPELL_POTION, false);
}
//Drink Inturrupt Timer
if (Drinking && !DrinkInturrupted)
if (DrinkInturruptTimer >= diff)
DrinkInturruptTimer -= diff;
else
{
m_creature->SetUInt32Value(UNIT_FIELD_BYTES_1, 0);
m_creature->CastSpell(m_creature, SPELL_POTION, true);
m_creature->CastSpell(m_creature, SPELL_AOE_PYROBLAST, false);
DrinkInturrupted = true;
Drinking = false;
}
//Don't execute any more code if we are drinking
if (Drinking)
return;
//Normal casts
if(NormalCastTimer < diff)
{
if (!m_creature->IsNonMeleeSpellCasted(false))
{
Unit* target = NULL;
target = SelectUnit(SELECT_TARGET_RANDOM, 0);
if (!target)
return;
uint32 Spells[3];
uint8 AvailableSpells = 0;
//Check for what spells are not on cooldown
if (!ArcaneCooldown)
{
Spells[AvailableSpells] = SPELL_ARCMISSLE;
AvailableSpells++;
}
if (!FireCooldown)
{
Spells[AvailableSpells] = SPELL_FIREBALL;
AvailableSpells++;
}
if (!FrostCooldown)
{
Spells[AvailableSpells] = SPELL_FROSTBOLT;
AvailableSpells++;
}
//If no available spells wait 1 second and try again
if (AvailableSpells)
{
CurrentNormalSpell = Spells[rand() % AvailableSpells];
DoCast(target, CurrentNormalSpell);
}
}
NormalCastTimer = 1000;
}else NormalCastTimer -= diff;
if(SecondarySpellTimer < diff)
{
switch (rand()%2)
{
case 0:
DoCast(m_creature, SPELL_AOE_CS);
break;
case 1:
Unit* pUnit;
pUnit = SelectUnit(SELECT_TARGET_RANDOM, 0);
if (pUnit)
DoCast(pUnit, SPELL_CHAINSOFICE);
break;
}
SecondarySpellTimer = 5000 + (rand()%15000);
}else SecondarySpellTimer -= diff;
if(SuperCastTimer < diff)
{
uint8 Available[2];
switch (LastSuperSpell)
{
case SUPER_AE:
Available[0] = SUPER_FLAME;
Available[1] = SUPER_BLIZZARD;
break;
case SUPER_FLAME:
Available[0] = SUPER_AE;
Available[1] = SUPER_BLIZZARD;
break;
case SUPER_BLIZZARD:
Available[0] = SUPER_FLAME;
Available[1] = SUPER_AE;
break;
}
LastSuperSpell = Available[rand()%2];
switch (LastSuperSpell)
{
case SUPER_AE:
if (rand()%2)
{
DoYell(SAY_EXPLOSION1, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(m_creature, SOUND_EXPLOSION1);
}else
{
DoYell(SAY_EXPLOSION2, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(m_creature, SOUND_EXPLOSION2);
}
m_creature->CastSpell(m_creature, SPELL_BLINK_CENTER, true);
m_creature->CastSpell(m_creature, SPELL_PLAYERPULL, true);
m_creature->CastSpell(m_creature, SPELL_MASSSLOW, true);
m_creature->CastSpell(m_creature, SPELL_AEXPLOSION, false);
break;
case SUPER_FLAME:
if (rand()%2)
{
DoYell(SAY_FLAMEWREATH1, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(m_creature, SOUND_FLAMEWREATH1);
}else
{
DoYell(SAY_FLAMEWREATH2, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(m_creature, SOUND_FLAMEWREATH2);
}
FlameWreathTimer = 20000;
FlameWreathCheckTime = 500;
FlameWreathTarget[0] = 0;
FlameWreathTarget[1] = 0;
FlameWreathTarget[2] = 0;
FlameWreathEffect();
break;
case SUPER_BLIZZARD:
if (rand()%2)
{
DoYell(SAY_BLIZZARD1, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(m_creature, SOUND_BLIZZARD1);
}else
{
DoYell(SAY_BLIZZARD2, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(m_creature, SOUND_BLIZZARD2);
}
Creature* Spawn = NULL;
Spawn = DoSpawnCreature(CREATURE_ARAN_BLIZZARD, 0, 0, 0, 0, TEMPSUMMON_TIMED_DESPAWN, 25000);
if (Spawn)
{
Spawn->setFaction(m_creature->getFaction());
Spawn->CastSpell(Spawn, SPELL_CIRCULAR_BLIZZARD, false);
}
break;
}
SuperCastTimer = 35000 + (rand()%5000);
}else SuperCastTimer -= diff;
if(!ElementalsSpawned && m_creature->GetHealth()*100 / m_creature->GetMaxHealth() < 40)
{
ElementalsSpawned = true;
for (uint32 i = 0; i < 4; i++)
{
Creature* pUnit = DoSpawnCreature(CREATURE_WATER_ELEMENTAL, 0, 0, 0, 0, TEMPSUMMON_TIMED_DESPAWN, 90000);
if (pUnit)
{
pUnit->Attack(m_creature->getVictim(), true);
pUnit->setFaction(m_creature->getFaction());
}
}
DoYell(SAY_ELEMENTALS, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(m_creature, SOUND_ELEMENTALS);
}
if(BerserkTimer < diff)
{
for (uint32 i = 0; i < 5; i++)
{
Creature* pUnit = DoSpawnCreature(CREATURE_SHADOW_OF_ARAN, 0, 0, 0, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000);
if (pUnit)
{
pUnit->Attack(m_creature->getVictim(), true);
pUnit->setFaction(m_creature->getFaction());
}
}
DoYell(SAY_TIMEOVER, LANG_UNIVERSAL, NULL);
DoPlaySoundToSet(m_creature, SOUND_TIMEOVER);
BerserkTimer = 60000;
}else BerserkTimer -= diff;
//Flame Wreath check
if (FlameWreathTimer)
{
if (FlameWreathTimer >= diff)
FlameWreathTimer -= diff;
else FlameWreathTimer = 0;
if (FlameWreathCheckTime < diff)
{
for (uint32 i = 0; i < 3; i++)
{
if (!FlameWreathTarget[i])
continue;
Unit* pUnit = Unit::GetUnit(*m_creature, FlameWreathTarget[i]);
if (pUnit && pUnit->GetDistance2d(FWTargPosX[i], FWTargPosY[i]) > 3)
{
pUnit->CastSpell(pUnit, 20476, true, 0, 0, m_creature->GetGUID());
pUnit->CastSpell(pUnit, 11027, true);
FlameWreathTarget[i] = 0;
}
}
FlameWreathCheckTime = 500;
}else FlameWreathCheckTime -= diff;
}
if (ArcaneCooldown && FireCooldown && FrostCooldown)
DoMeleeAttackIfReady();
}
void DamageTaken(Unit* pAttacker, uint32 &damage)
{
if (!DrinkInturrupted && Drinking && damage)
DrinkInturrupted = true;
}
void SpellHit(Unit* pAttacker, const SpellEntry* Spell)
{
//We only care about inturrupt effects and only if they are durring a spell currently being casted
if ((Spell->Effect[0]!=SPELL_EFFECT_INTERRUPT_CAST &&
Spell->Effect[1]!=SPELL_EFFECT_INTERRUPT_CAST &&
Spell->Effect[2]!=SPELL_EFFECT_INTERRUPT_CAST) || !m_creature->IsNonMeleeSpellCasted(false))
return;
//Inturrupt effect
m_creature->InterruptNonMeleeSpells(false);
//Normally we would set the cooldown equal to the spell duration
//but we do not have access to the DurationStore
switch (CurrentNormalSpell)
{
case SPELL_ARCMISSLE:
ArcaneCooldown = 5000;
break;
case SPELL_FIREBALL:
FireCooldown = 5000;
break;
case SPELL_FROSTBOLT:
FrostCooldown = 5000;
break;
}
}
};
struct TRINITY_DLL_DECL water_elementalAI : public ScriptedAI
{
water_elementalAI(Creature *c) : ScriptedAI(c) {Reset();}
uint32 CastTimer;
void Reset()
{
CastTimer = 2000 + (rand()%3000);
}
void Aggro(Unit* who) {}
void UpdateAI(const uint32 diff)
{
if (!m_creature->SelectHostilTarget() || !m_creature->getVictim() )
return;
if(CastTimer < diff)
{
DoCast(m_creature->getVictim(), SPELL_WATERBOLT);
CastTimer = 2000 + (rand()%3000);
}else CastTimer -= diff;
}
};
CreatureAI* GetAI_boss_aran(Creature *_Creature)
{
return new boss_aranAI (_Creature);
}
CreatureAI* GetAI_water_elemental(Creature *_Creature)
{
return new water_elementalAI (_Creature);
}
// CONVERT TO ACID
CreatureAI* GetAI_shadow_of_aran(Creature *_Creature)
{
outstring_log("SD2: Convert simpleAI script for Creature Entry %u to ACID", _Creature->GetEntry());
SimpleAI* ai = new SimpleAI (_Creature);
ai->Spell[0].Enabled = true;
ai->Spell[0].Spell_Id = SPELL_SHADOW_PYRO;
ai->Spell[0].Cooldown = 5000;
ai->Spell[0].First_Cast = 1000;
ai->Spell[0].Cast_Target_Type = CAST_HOSTILE_TARGET;
ai->EnterEvadeMode();
return ai;
}
void AddSC_boss_shade_of_aran()
{
Script *newscript;
newscript = new Script;
newscript->Name="boss_shade_of_aran";
newscript->GetAI = GetAI_boss_aran;
m_scripts[nrscripts++] = newscript;
newscript = new Script;
newscript->Name="mob_shadow_of_aran";
newscript->GetAI = GetAI_shadow_of_aran;
m_scripts[nrscripts++] = newscript;
newscript = new Script;
newscript->Name="mob_aran_elemental";
newscript->GetAI = GetAI_water_elemental;
m_scripts[nrscripts++] = newscript;
//newscript = new Script;
//newscript->Name="mob_aran_blizzard";
//newscript->GetAI = GetAI_boss_aran;
//m_scripts[nrscripts++] = newscript;
}
|
gpl-2.0
|
Archimedez/FunnyGame
|
Galactic Conflict/GalacticConflict/GalacticConflict/TitleMenuState.cs
|
961
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tao.OpenGl;
namespace GalacticConflict {
class TitleMenuState : IGameObject {
double _currentRotation = 0;
public void Update(double elapsedTime) {
_currentRotation = 10 * elapsedTime;
}
public void Render() {
Gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);
Gl.glPointSize(5.0f);
Gl.glRotated(_currentRotation, 0, 1, 0);
Gl.glBegin(Gl.GL_TRIANGLE_STRIP);
{
Gl.glColor4d(1.0, 0.0, 0.0, 0.5);
Gl.glVertex3d(-50, 0, 0);
Gl.glColor3d(0.0, 1.0, 0.0);
Gl.glVertex3d(50, 0, 0);
Gl.glColor3d(0.0, 0.0, 1.0);
Gl.glVertex3d(0, 50, 0);
}
Gl.glEnd();
Gl.glFinish();
}
}
}
|
gpl-2.0
|
Kagami/tistore
|
src/file-list/file-item.js
|
1605
|
/**
* View/action logic for the single file inside list.
* @module tistore/file-list/file-item
*/
import React from "react";
import Icon from "react-fa";
import {showSize} from "../util";
export default class FileItem extends React.PureComponent {
getIconName() {
const status = this.props.status;
switch (status) {
case "start":
return "hourglass-o";
case "pause":
return "pause";
case "complete":
return "check";
case "error":
return "warning";
default:
return "play";
}
}
getLinkText() {
const url = this.props.url;
const hostIdx = url.indexOf("//") + 2;
// Remove nonimportant junk.
return url.slice(hostIdx);
}
handleNameClick = (e) => {
e.preventDefault();
global.nw.Shell.openItem(this.props.path);
}
getNameNode() {
if (this.props.status === "error") {
return this.props.errorMsg;
} else if (this.props.path) {
return <a href="" onClick={this.handleNameClick}>{this.props.name}</a>;
} else {
return "-";
}
}
getSizeText() {
return this.props.size != null ? showSize(this.props.size) : "";
}
render() {
const cls = `tistore_file-row tistore_file-${this.props.status}`;
const icon = this.getIconName();
return (
<tr className={cls}>
<td className="tistore_file-icon"><Icon name={icon} /></td>
<td className="tistore_file-link">{this.getLinkText()}</td>
<td className="tistore_file-name">{this.getNameNode()}</td>
<td className="tistore_file-size">{this.getSizeText()}</td>
</tr>
);
}
}
|
gpl-2.0
|
tonglin/pdPm
|
public_html/typo3_src-6.1.7/typo3/sysext/core/Classes/Core/Bootstrap.php
|
40844
|
<?php
namespace TYPO3\CMS\Core\Core;
/***************************************************************
* Copyright notice
*
* (c) 2012-2013 Christian Kuhn <lolli@schwarzbu.ch>
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
* A copy is found in the textfile GPL.txt and important notices to the license
* from the author is found in LICENSE.txt distributed with these scripts.
*
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
use \TYPO3\CMS\Core\Utility;
require 'SystemEnvironmentBuilder.php';
/**
* This class encapsulates bootstrap related methods.
* It is required directly as the very first thing in entry scripts and
* used to define all base things like constants and pathes and so on.
*
* Most methods in this class have dependencies to each other. They can
* not be called in arbitrary order. The methods are ordered top down, so
* a method at the beginning has lower dependencies than a method further
* down. Do not fiddle with the load order in own scripts except you know
* exactly what you are doing!
*
* @author Christian Kuhn <lolli@schwarzbu.ch>
*/
class Bootstrap {
/**
* @var \TYPO3\CMS\Core\Core\Bootstrap
*/
static protected $instance = NULL;
/**
* Unique Request ID
*
* @var string
*/
protected $requestId;
/**
* Disable direct creation of this object.
*/
protected function __construct() {
$this->requestId = uniqid();
}
/**
* Disable direct cloning of this object.
*/
protected function __clone() {
}
/**
* Return 'this' as singleton
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
static public function getInstance() {
if (is_null(self::$instance)) {
self::$instance = new \TYPO3\CMS\Core\Core\Bootstrap();
}
return self::$instance;
}
/**
* Gets the request's unique ID
*
* @return string Unique request ID
* @internal This is not a public API method, do not use in own extensions
*/
public function getRequestId() {
return $this->requestId;
}
/**
* Prevent any unwanted output that may corrupt AJAX/compression.
* This does not interfere with "die()" or "echo"+"exit()" messages!
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function startOutputBuffering() {
ob_start();
return $this;
}
/**
* Run the base setup that checks server environment,
* determines pathes, populates base files and sets common configuration.
*
* Script execution will be aborted if something fails here.
*
* @param string $relativePathPart Relative path of the entry script back to document root
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function baseSetup($relativePathPart = '') {
\TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::run($relativePathPart);
return $this;
}
/**
* Redirect to install tool if LocalConfiguration.php is missing
*
* @param string $pathUpToDocumentRoot Can contain eg. '../' if called from a sub directory
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function redirectToInstallToolIfLocalConfigurationFileDoesNotExist($pathUpToDocumentRoot = '') {
/** @var $configurationManager \TYPO3\CMS\Core\Configuration\ConfigurationManager */
$configurationManager = Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Configuration\\ConfigurationManager');
if (
!file_exists($configurationManager->getLocalConfigurationFileLocation())
&& !file_exists($configurationManager->getLocalconfFileLocation())
) {
require_once __DIR__ . '/../Utility/HttpUtility.php';
Utility\HttpUtility::redirect($pathUpToDocumentRoot . 'typo3/install/index.php?mode=123&step=1&password=joh316');
}
return $this;
}
/**
* Includes LocalConfiguration.php and sets several
* global settings depending on configuration.
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function loadConfigurationAndInitialize() {
$this->getInstance()
->populateLocalConfiguration()
->registerExtDirectComponents()
->initializeCachingFramework()
->registerAutoloader()
->checkUtf8DatabaseSettingsOrDie()
->transferDeprecatedCurlSettings()
->setCacheHashOptions()
->enforceCorrectProxyAuthScheme()
->setDefaultTimezone()
->initializeL10nLocales()
->configureImageProcessingOptions()
->convertPageNotFoundHandlingToBoolean()
->registerGlobalDebugFunctions()
// SwiftMailerAdapter is
// @deprecated since 6.1, will be removed two versions later - will be removed together with \TYPO3\CMS\Core\Utility\MailUtility::mail()
->registerSwiftMailer()
->configureExceptionHandling()
->setMemoryLimit()
->defineTypo3RequestTypes();
return $this;
}
/**
* Load TYPO3_LOADED_EXT and ext_localconf
*
* @param boolean $allowCaching
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function loadTypo3LoadedExtAndExtLocalconf($allowCaching = TRUE) {
$this->getInstance()
->populateTypo3LoadedExtGlobal($allowCaching)
->loadAdditionalConfigurationFromExtensions($allowCaching);
return $this;
}
/**
* Load TYPO3_LOADED_EXT, recreate class loader registry and load ext_localconf
*
* @param boolean $allowCaching
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function reloadTypo3LoadedExtAndClassLoaderAndExtLocalconf() {
$bootstrap = $this->getInstance();
$bootstrap->populateTypo3LoadedExtGlobal(FALSE);
\TYPO3\CMS\Core\Core\ClassLoader::loadClassLoaderCache();
$bootstrap->loadAdditionalConfigurationFromExtensions(FALSE);
return $this;
}
/**
* Sets up additional configuration applied in all scopes
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function applyAdditionalConfigurationSettings() {
$this->getInstance()
->deprecationLogForOldExtCacheSetting()
->initializeExceptionHandling()
->setFinalCachingFrameworkCacheConfiguration()
->defineLoggingAndExceptionConstants()
->unsetReservedGlobalVariables();
return $this;
}
/**
* Throws an exception if no browser could be identified
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @throws \RuntimeException
* @internal This is not a public API method, do not use in own extensions
*/
public function checkValidBrowserOrDie() {
// Checks for proper browser
if (empty($GLOBALS['CLIENT']['BROWSER'])) {
throw new \RuntimeException('Browser Error: Your browser version looks incompatible with this TYPO3 version!', 1294587023);
}
return $this;
}
/**
* Populate the local configuration.
* Merge default TYPO3_CONF_VARS with content of typo3conf/LocalConfiguration.php,
* execute typo3conf/AdditionalConfiguration.php, define database related constants.
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function populateLocalConfiguration() {
try {
Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Configuration\\ConfigurationManager')
->exportConfiguration();
} catch (\Exception $e) {
die($e->getMessage());
}
define('TYPO3_db', $GLOBALS['TYPO3_CONF_VARS']['DB']['database']);
define('TYPO3_db_username', $GLOBALS['TYPO3_CONF_VARS']['DB']['username']);
define('TYPO3_db_password', $GLOBALS['TYPO3_CONF_VARS']['DB']['password']);
define('TYPO3_db_host', $GLOBALS['TYPO3_CONF_VARS']['DB']['host']);
define('TYPO3_extTableDef_script',
isset($GLOBALS['TYPO3_CONF_VARS']['DB']['extTablesDefinitionScript'])
? $GLOBALS['TYPO3_CONF_VARS']['DB']['extTablesDefinitionScript']
: 'extTables.php');
define('TYPO3_user_agent', 'User-Agent: ' . $GLOBALS['TYPO3_CONF_VARS']['HTTP']['userAgent']);
return $this;
}
/**
* Register default ExtDirect components
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function registerExtDirectComponents() {
if (TYPO3_MODE === 'BE') {
Utility\ExtensionManagementUtility::registerExtDirectComponent('TYPO3.Components.PageTree.DataProvider', 'TYPO3\\CMS\\Backend\\Tree\\Pagetree\\ExtdirectTreeDataProvider', 'web', 'user,group');
Utility\ExtensionManagementUtility::registerExtDirectComponent('TYPO3.Components.PageTree.Commands', 'TYPO3\\CMS\\Backend\\Tree\\Pagetree\\ExtdirectTreeCommands', 'web', 'user,group');
Utility\ExtensionManagementUtility::registerExtDirectComponent('TYPO3.Components.PageTree.ContextMenuDataProvider', 'TYPO3\\CMS\\Backend\\ContextMenu\\Pagetree\\Extdirect\\ContextMenuConfiguration', 'web', 'user,group');
Utility\ExtensionManagementUtility::registerExtDirectComponent('TYPO3.LiveSearchActions.ExtDirect', 'TYPO3\\CMS\\Backend\\Search\\LiveSearch\\ExtDirect\\LiveSearchDataProvider', 'web_list', 'user,group');
Utility\ExtensionManagementUtility::registerExtDirectComponent('TYPO3.BackendUserSettings.ExtDirect', 'TYPO3\\CMS\\Backend\\User\\ExtDirect\\BackendUserSettingsDataProvider');
if (Utility\ExtensionManagementUtility::isLoaded('context_help')) {
Utility\ExtensionManagementUtility::registerExtDirectComponent('TYPO3.CSH.ExtDirect', 'TYPO3\\CMS\\ContextHelp\\ExtDirect\\ContextHelpDataProvider');
}
Utility\ExtensionManagementUtility::registerExtDirectComponent('TYPO3.ExtDirectStateProvider.ExtDirect', 'TYPO3\\CMS\\Backend\\InterfaceState\\ExtDirect\\DataProvider');
Utility\ExtensionManagementUtility::registerExtDirectComponent(
'TYPO3.Components.DragAndDrop.CommandController',
Utility\ExtensionManagementUtility::extPath('backend') . 'Classes/View/PageLayout/Extdirect/ExtdirectPageCommands.php:TYPO3\\CMS\\Backend\\View\\PageLayout\\ExtDirect\\ExtdirectPageCommands', 'web', 'user,group'
);
}
return $this;
}
/**
* Initialize caching framework
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function initializeCachingFramework() {
\TYPO3\CMS\Core\Cache\Cache::initializeCachingFramework();
return $this;
}
/**
* Register autoloader
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function registerAutoloader() {
if (PHP_VERSION_ID < 50307) {
\TYPO3\CMS\Core\Compatibility\CompatbilityClassLoaderPhpBelow50307::registerAutoloader();
} else {
\TYPO3\CMS\Core\Core\ClassLoader::registerAutoloader();
}
return $this;
}
/**
* Checking for UTF-8 in the settings since TYPO3 4.5
*
* Since TYPO3 4.5, everything other than UTF-8 is deprecated.
*
* [BE][forceCharset] is set to the charset that TYPO3 is using
* [SYS][setDBinit] is used to set the DB connection
* and both settings need to be adjusted for UTF-8 in order to work properly
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function checkUtf8DatabaseSettingsOrDie() {
// Check if [BE][forceCharset] has been set in localconf.php
if (isset($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'])) {
// die() unless we're already on UTF-8
if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] != 'utf-8' &&
$GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] &&
TYPO3_enterInstallScript !== '1') {
die('This installation was just upgraded to a new TYPO3 version. Since TYPO3 4.7, utf-8 is always enforced.<br />' .
'The configuration option $GLOBALS[\'TYPO3_CONF_VARS\'][BE][forceCharset] was marked as deprecated in TYPO3 4.5 and is now ignored.<br />' .
'You have configured the value to something different, which is not supported anymore.<br />' .
'Please proceed to the Update Wizard in the TYPO3 Install Tool to update your configuration.'
);
} else {
unset($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']);
}
}
if (isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit']) &&
$GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit'] !== '-1' &&
preg_match('/SET NAMES [\'"]?utf8[\'"]?/i', $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit']) === FALSE &&
TYPO3_enterInstallScript !== '1') {
// Only accept "SET NAMES utf8" for this setting, otherwise die with a nice error
die('This TYPO3 installation is using the $GLOBALS[\'TYPO3_CONF_VARS\'][\'SYS\'][\'setDBinit\'] property with the following value:' . chr(10) .
$GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit'] . chr(10) . chr(10) .
'It looks like UTF-8 is not used for this connection.' . chr(10) . chr(10) .
'Everything other than UTF-8 is unsupported since TYPO3 4.7.' . chr(10) .
'The DB, its connection and TYPO3 should be migrated to UTF-8 therefore. Please check your setup.'
);
} else {
$GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit'] = 'SET NAMES utf8;';
}
return $this;
}
/**
* Parse old curl options and set new http ones instead
*
* @TODO : This code segment must still be finished
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function transferDeprecatedCurlSettings() {
if (!empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer'])) {
$proxyParts = Utility\GeneralUtility::revExplode(':', $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer'], 2);
$GLOBALS['TYPO3_CONF_VARS']['HTTP']['proxy_host'] = $proxyParts[0];
$GLOBALS['TYPO3_CONF_VARS']['HTTP']['proxy_port'] = $proxyParts[1];
}
if (!empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass'])) {
$userPassParts = explode(':', $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass'], 2);
$GLOBALS['TYPO3_CONF_VARS']['HTTP']['proxy_user'] = $userPassParts[0];
$GLOBALS['TYPO3_CONF_VARS']['HTTP']['proxy_password'] = $userPassParts[1];
}
return $this;
}
/**
* Set cacheHash options
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function setCacheHashOptions() {
$GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash'] = array(
'cachedParametersWhiteList' => Utility\GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashOnlyForParameters'], TRUE),
'excludedParameters' => Utility\GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParameters'], TRUE),
'requireCacheHashPresenceParameters' => Utility\GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashRequiredParameters'], TRUE)
);
if (trim($GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParametersIfEmpty']) === '*') {
$GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludeAllEmptyParameters'] = TRUE;
} else {
$GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludedParametersIfEmpty'] = Utility\GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParametersIfEmpty'], TRUE);
}
return $this;
}
/**
* $GLOBALS['TYPO3_CONF_VARS']['HTTP']['proxy_auth_scheme'] must be either
* 'digest' or 'basic' with fallback to 'basic'
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function enforceCorrectProxyAuthScheme() {
$GLOBALS['TYPO3_CONF_VARS']['HTTP']['proxy_auth_scheme'] === 'digest' ?: ($GLOBALS['TYPO3_CONF_VARS']['HTTP']['proxy_auth_scheme'] = 'basic');
return $this;
}
/**
* Set default timezone
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function setDefaultTimezone() {
$timeZone = $GLOBALS['TYPO3_CONF_VARS']['SYS']['phpTimeZone'];
if (empty($timeZone)) {
// Time zone from the server environment (TZ env or OS query)
$defaultTimeZone = @date_default_timezone_get();
if ($defaultTimeZone !== '') {
$timeZone = $defaultTimeZone;
} else {
$timeZone = 'UTC';
}
}
// Set default to avoid E_WARNINGs with PHP > 5.3
date_default_timezone_set($timeZone);
return $this;
}
/**
* Initialize the locales handled by TYPO3
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function initializeL10nLocales() {
\TYPO3\CMS\Core\Localization\Locales::initialize();
return $this;
}
/**
* Based on the configuration of the image processing some options are forced
* to simplify configuration settings and combinations
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function configureImageProcessingOptions() {
if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['image_processing']) {
$GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] = 0;
$GLOBALS['TYPO3_CONF_VARS']['GFX']['gdlib'] = 0;
}
if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['im']) {
$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path'] = '';
$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'] = '';
$GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] = 'gif,jpg,jpeg,png';
$GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails'] = 0;
}
if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_version_5']) {
$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_negate_mask'] = 1;
$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_no_effects'] = 1;
$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_mask_temp_ext_gif'] = 1;
if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_version_5'] === 'gm') {
$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_negate_mask'] = 0;
$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_imvMaskState'] = 0;
$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_no_effects'] = 1;
$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_v5effects'] = -1;
}
}
if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_imvMaskState']) {
$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_negate_mask'] = $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_negate_mask'] ? 0 : 1;
}
return $this;
}
/**
* Convert type of "pageNotFound_handling" setting in case it was written as a
* string (e.g. if edited in Install Tool)
*
* @TODO : Remove, if the Install Tool handles such data types correctly
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function convertPageNotFoundHandlingToBoolean() {
if (!strcasecmp($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], 'TRUE')) {
$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] = TRUE;
}
return $this;
}
/**
* Register xdebug(), debug(), debugBegin() and debugEnd() as global functions
*
* Note: Yes, this is possible in php! xdebug() is then a global function, even
* if registerGlobalDebugFunctions() is encapsulated in class scope.
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function registerGlobalDebugFunctions() {
require_once('GlobalDebugFunctions.php');
return $this;
}
/**
* Mail sending via Swift Mailer
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @deprecated since 6.1, will be removed two versions later - will be removed together with \TYPO3\CMS\Core\Utility\MailUtility::mail()
*/
protected function registerSwiftMailer() {
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/utility/class.t3lib_utility_mail.php']['substituteMailDelivery'][] =
'TYPO3\\CMS\\Core\\Mail\\SwiftMailerAdapter';
return $this;
}
/**
* Configure and set up exception and error handling
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function configureExceptionHandling() {
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['errors']['exceptionHandler'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['productionExceptionHandler'];
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['errors']['exceptionalErrors'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['exceptionalErrors'];
// Turn error logging on/off.
if (($displayErrors = intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['displayErrors'])) != '-1') {
// Special value "2" enables this feature only if $GLOBALS['TYPO3_CONF_VARS'][SYS][devIPmask] matches
if ($displayErrors == 2) {
if (Utility\GeneralUtility::cmpIP(Utility\GeneralUtility::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask'])) {
$displayErrors = 1;
} else {
$displayErrors = 0;
}
}
if ($displayErrors == 0) {
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['errors']['exceptionalErrors'] = 0;
}
if ($displayErrors == 1) {
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['errors']['exceptionHandler'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['debugExceptionHandler'];
define('TYPO3_ERRORHANDLER_MODE', 'debug');
}
@ini_set('display_errors', $displayErrors);
} elseif (Utility\GeneralUtility::cmpIP(Utility\GeneralUtility::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask'])) {
// With displayErrors = -1 (default), turn on debugging if devIPmask matches:
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['errors']['exceptionHandler'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['debugExceptionHandler'];
}
return $this;
}
/**
* Set PHP memory limit depending on value of
* $GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit']
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function setMemoryLimit() {
if (intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit']) > 16) {
@ini_set('memory_limit', (intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit']) . 'm'));
}
return $this;
}
/**
* Define TYPO3_REQUESTTYPE* constants
* so devs exactly know what type of request it is
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function defineTypo3RequestTypes() {
define('TYPO3_REQUESTTYPE_FE', 1);
define('TYPO3_REQUESTTYPE_BE', 2);
define('TYPO3_REQUESTTYPE_CLI', 4);
define('TYPO3_REQUESTTYPE_AJAX', 8);
define('TYPO3_REQUESTTYPE_INSTALL', 16);
define('TYPO3_REQUESTTYPE', (TYPO3_MODE == 'FE' ? TYPO3_REQUESTTYPE_FE : 0) | (TYPO3_MODE == 'BE' ? TYPO3_REQUESTTYPE_BE : 0) | (defined('TYPO3_cliMode') && TYPO3_cliMode ? TYPO3_REQUESTTYPE_CLI : 0) | (defined('TYPO3_enterInstallScript') && TYPO3_enterInstallScript ? TYPO3_REQUESTTYPE_INSTALL : 0) | ($GLOBALS['TYPO3_AJAX'] ? TYPO3_REQUESTTYPE_AJAX : 0));
return $this;
}
/**
* Set up $GLOBALS['TYPO3_LOADED_EXT'] array with basic information
* about extensions.
*
* @param boolean $allowCaching
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function populateTypo3LoadedExtGlobal($allowCaching = TRUE) {
$GLOBALS['TYPO3_LOADED_EXT'] = Utility\ExtensionManagementUtility::loadTypo3LoadedExtensionInformation($allowCaching);
return $this;
}
/**
* Load extension configuration files (ext_localconf.php)
*
* The ext_localconf.php files in extensions are meant to make changes
* to the global $TYPO3_CONF_VARS configuration array.
*
* @param boolean $allowCaching
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function loadAdditionalConfigurationFromExtensions($allowCaching = TRUE) {
Utility\ExtensionManagementUtility::loadExtLocalconf($allowCaching);
return $this;
}
/**
* Write deprecation log if deprecated extCache setting was set in the instance.
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @deprecated since 6.0, the check will be removed two version later.
*/
protected function deprecationLogForOldExtCacheSetting() {
if (isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['extCache']) && $GLOBALS['TYPO3_CONF_VARS']['SYS']['extCache'] !== -1) {
Utility\GeneralUtility::deprecationLog('Setting $GLOBALS[\'TYPO3_CONF_VARS\'][\'SYS\'][\'extCache\'] is unused and can be removed from localconf.php');
}
return $this;
}
/**
* Initialize exception handling
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function initializeExceptionHandling() {
if ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['errors']['exceptionHandler'] !== '') {
if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandler'] !== '') {
// Register an error handler for the given errorHandlerErrors
$errorHandler = Utility\GeneralUtility::makeInstance($GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandler'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandlerErrors']);
// Set errors which will be converted in an exception
$errorHandler->setExceptionalErrors($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['errors']['exceptionalErrors']);
}
// Instantiate the exception handler once to make sure object is registered
// @TODO: Figure out if this is really needed
Utility\GeneralUtility::makeInstance($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['errors']['exceptionHandler']);
}
return $this;
}
/**
* Extensions may register new caches, so we set the
* global cache array to the manager again at this point
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function setFinalCachingFrameworkCacheConfiguration() {
$GLOBALS['typo3CacheManager']->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
return $this;
}
/**
* Define logging and exception constants
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function defineLoggingAndExceptionConstants() {
define('TYPO3_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_DLOG']);
define('TYPO3_ERROR_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_errorDLOG']);
define('TYPO3_EXCEPTION_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_exceptionDLOG']);
return $this;
}
/**
* Unsetting reserved global variables:
* Those are set in "ext:core/ext_tables.php" file:
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
*/
protected function unsetReservedGlobalVariables() {
unset($GLOBALS['PAGES_TYPES']);
unset($GLOBALS['TCA']);
unset($GLOBALS['TBE_MODULES']);
unset($GLOBALS['TBE_STYLES']);
unset($GLOBALS['FILEICONS']);
// Those set in init.php:
unset($GLOBALS['WEBMOUNTS']);
unset($GLOBALS['FILEMOUNTS']);
unset($GLOBALS['BE_USER']);
// Those set otherwise:
unset($GLOBALS['TBE_MODULES_EXT']);
unset($GLOBALS['TCA_DESCR']);
unset($GLOBALS['LOCAL_LANG']);
unset($GLOBALS['TYPO3_AJAX']);
return $this;
}
/**
* Initialize database connection in $GLOBALS and connect if requested
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function initializeTypo3DbGlobal() {
/** @var $databaseConnection \TYPO3\CMS\Core\Database\DatabaseConnection */
$databaseConnection = Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\DatabaseConnection');
$databaseConnection->setDatabaseName(TYPO3_db);
$databaseConnection->setDatabaseUsername(TYPO3_db_username);
$databaseConnection->setDatabasePassword(TYPO3_db_password);
$databaseHost = TYPO3_db_host;
if (isset($GLOBALS['TYPO3_CONF_VARS']['DB']['port'])) {
$databaseConnection->setDatabasePort($GLOBALS['TYPO3_CONF_VARS']['DB']['port']);
} elseif (strpos($databaseHost, ':') > 0) {
// @TODO: Find a way to handle this case in the install tool and drop this
list($databaseHost, $databasePort) = explode(':', $databaseHost);
$databaseConnection->setDatabasePort($databasePort);
}
if (isset($GLOBALS['TYPO3_CONF_VARS']['DB']['socket'])) {
$databaseConnection->setDatabaseSocket($GLOBALS['TYPO3_CONF_VARS']['DB']['socket']);
}
$databaseConnection->setDatabaseHost($databaseHost);
$databaseConnection->debugOutput = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sqlDebug'];
if (
isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect'])
&& !$GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect']
) {
$databaseConnection->setPersistentDatabaseConnection(TRUE);
}
$isDatabaseHostLocalHost = $databaseHost === 'localhost' || $databaseHost === '127.0.0.1' || $databaseHost === '::1';
if (
isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'])
&& $GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress']
&& !$isDatabaseHostLocalHost
) {
$databaseConnection->setConnectionCompression(TRUE);
}
if (!empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit'])) {
$commandsAfterConnect = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(
LF,
str_replace('\' . LF . \'', LF, $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit']),
TRUE
);
$databaseConnection->setInitializeCommandsAfterConnect($commandsAfterConnect);
}
$GLOBALS['TYPO3_DB'] = $databaseConnection;
return $this;
}
/**
* Check adminOnly configuration variable and redirects
* to an URL in file typo3conf/LOCK_BACKEND or exit the script
*
* @throws \RuntimeException
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function checkLockedBackendAndRedirectOrDie() {
if ($GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'] < 0) {
throw new \RuntimeException('TYPO3 Backend locked: Backend and Install Tool are locked for maintenance. [BE][adminOnly] is set to "' . intval($GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly']) . '".', 1294586847);
}
if (@is_file((PATH_typo3conf . 'LOCK_BACKEND'))) {
if (TYPO3_PROCEED_IF_NO_USER === 2) {
} else {
$fileContent = Utility\GeneralUtility::getUrl(PATH_typo3conf . 'LOCK_BACKEND');
if ($fileContent) {
header('Location: ' . $fileContent);
} else {
throw new \RuntimeException('TYPO3 Backend locked: Browser backend is locked for maintenance. Remove lock by removing the file "typo3conf/LOCK_BACKEND" or use CLI-scripts.', 1294586848);
}
die;
}
}
return $this;
}
/**
* Compare client IP with IPmaskList and exit the script run
* if the client is not allowed to access the backend
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function checkBackendIpOrDie() {
if (trim($GLOBALS['TYPO3_CONF_VARS']['BE']['IPmaskList'])) {
if (!Utility\GeneralUtility::cmpIP(Utility\GeneralUtility::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['BE']['IPmaskList'])) {
// Send Not Found header - if the webserver can make use of it
header('Status: 404 Not Found');
// Just point us away from here...
header('Location: http://');
// ... and exit good!
die;
}
}
return $this;
}
/**
* Check lockSSL configuration variable and redirect
* to https version of the backend if needed
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function checkSslBackendAndRedirectIfNeeded() {
if (intval($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'])) {
if (intval($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'])) {
$sslPortSuffix = ':' . intval($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort']);
} else {
$sslPortSuffix = '';
}
if ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'] == 3) {
$requestStr = substr(Utility\GeneralUtility::getIndpEnv('TYPO3_REQUEST_SCRIPT'), strlen(Utility\GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir));
if ($requestStr === 'index.php' && !Utility\GeneralUtility::getIndpEnv('TYPO3_SSL')) {
list(, $url) = explode('://', Utility\GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'), 2);
list($server, $address) = explode('/', $url, 2);
header('Location: https://' . $server . $sslPortSuffix . '/' . $address);
die;
}
} elseif (!Utility\GeneralUtility::getIndpEnv('TYPO3_SSL')) {
if (intval($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL']) === 2) {
list(, $url) = explode('://', Utility\GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir, 2);
list($server, $address) = explode('/', $url, 2);
header('Location: https://' . $server . $sslPortSuffix . '/' . $address);
} else {
// Send Not Found header - if the webserver can make use of it...
header('Status: 404 Not Found');
// Just point us away from here...
header('Location: http://');
}
// ... and exit good!
die;
}
}
return $this;
}
/**
* Load TCA for frontend
*
* This method is *only* executed in frontend scope. The idea is to execute the
* whole TCA and ext_tables (which manipulate TCA) on first frontend access,
* and then cache the full TCA on disk to be used for the next run again.
*
* This way, ext_tables.php ist not executed every time, but $GLOBALS['TCA']
* is still always there.
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function loadCachedTca() {
$cacheIdentifier = 'tca_fe_' . sha1((TYPO3_version . PATH_site . 'tca_fe'));
/** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
$codeCache = $GLOBALS['typo3CacheManager']->getCache('cache_core');
if ($codeCache->has($cacheIdentifier)) {
$codeCache->requireOnce($cacheIdentifier);
} else {
$this->loadExtensionTables(TRUE);
$phpCodeToCache = '$GLOBALS[\'TCA\'] = ' . var_export($GLOBALS['TCA'], TRUE) . ';';
$codeCache->set($cacheIdentifier, $phpCodeToCache);
}
return $this;
}
/**
* Load ext_tables and friends.
*
* This will mainly set up $TCA and several other global arrays
* through API's like extMgm.
* Executes ext_tables.php files of loaded extensions or the
* according cache file if exists.
*
* @param boolean $allowCaching True, if reading compiled ext_tables file from cache is allowed
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function loadExtensionTables($allowCaching = TRUE) {
Utility\ExtensionManagementUtility::loadBaseTca($allowCaching);
Utility\ExtensionManagementUtility::loadExtTables($allowCaching);
$this->executeExtTablesAdditionalFile();
$this->runExtTablesPostProcessingHooks();
return $this;
}
/**
* Execute TYPO3_extTableDef_script if defined and exists
*
* Note: For backwards compatibility some global variables are
* explicitly set as global to be used without $GLOBALS[] in
* the extension table script. It is discouraged to access variables like
* $TBE_MODULES directly, but we can not prohibit
* this without heavily breaking backwards compatibility.
*
* @TODO : We could write a scheduler / reports module or an update checker
* @TODO : It should be defined, which global arrays are ok to be manipulated
*
* @return void
*/
protected function executeExtTablesAdditionalFile() {
// It is discouraged to use those global variables directly, but we
// can not prohibit this without breaking backwards compatibility
global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
global $TBE_MODULES, $TBE_MODULES_EXT, $TCA;
global $PAGES_TYPES, $TBE_STYLES, $FILEICONS;
global $_EXTKEY;
// Load additional ext tables script if the file exists
$extTablesFile = PATH_typo3conf . TYPO3_extTableDef_script;
if (file_exists($extTablesFile) && is_file($extTablesFile)) {
include $extTablesFile;
}
// Apply TCA onto tables to be categorized
\TYPO3\CMS\Core\Category\CategoryRegistry::getInstance()->applyTca();
}
/**
* Check for registered ext tables hooks and run them
*
* @throws \UnexpectedValueException
* @return void
*/
protected function runExtTablesPostProcessingHooks() {
if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['extTablesInclusion-PostProcessing'])) {
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['extTablesInclusion-PostProcessing'] as $classReference) {
/** @var $hookObject \TYPO3\CMS\Core\Database\TableConfigurationPostProcessingHookInterface */
$hookObject = Utility\GeneralUtility::getUserObj($classReference);
if (!$hookObject instanceof \TYPO3\CMS\Core\Database\TableConfigurationPostProcessingHookInterface) {
throw new \UnexpectedValueException('$hookObject must implement interface TYPO3\\CMS\\Core\\Database\\TableConfigurationPostProcessingHookInterface', 1320585902);
}
$hookObject->processData();
}
}
}
/**
* Initialize sprite manager
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function initializeSpriteManager() {
\TYPO3\CMS\Backend\Sprite\SpriteManager::initialize();
return $this;
}
/**
* Initialize backend user object in globals
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function initializeBackendUser() {
/** @var $backendUser \TYPO3\CMS\Core\Authentication\BackendUserAuthentication */
$backendUser = Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
$backendUser->warningEmail = $GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr'];
$backendUser->lockIP = $GLOBALS['TYPO3_CONF_VARS']['BE']['lockIP'];
$backendUser->auth_timeout_field = intval($GLOBALS['TYPO3_CONF_VARS']['BE']['sessionTimeout']);
$backendUser->OS = TYPO3_OS;
if (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI) {
$backendUser->dontSetCookie = TRUE;
}
// The global must be available very early, because methods below
// might trigger code which relies on it. See: #45625
$GLOBALS['BE_USER'] = $backendUser;
$backendUser->start();
$backendUser->checkCLIuser();
$backendUser->backendCheckLogin();
return $this;
}
/**
* Initialize backend user mount points
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function initializeBackendUserMounts() {
// Includes deleted mount pages as well! @TODO: Figure out why ...
$GLOBALS['WEBMOUNTS'] = $GLOBALS['BE_USER']->returnWebmounts();
$GLOBALS['BE_USER']->getFileStorages();
$GLOBALS['FILEMOUNTS'] = $GLOBALS['BE_USER']->groupData['filemounts'];
return $this;
}
/**
* Initialize language object
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function initializeLanguageObject() {
/** @var $GLOBALS['LANG'] \TYPO3\CMS\Lang\LanguageService */
$GLOBALS['LANG'] = Utility\GeneralUtility::makeInstance('TYPO3\CMS\Lang\LanguageService');
$GLOBALS['LANG']->init($GLOBALS['BE_USER']->uc['lang']);
return $this;
}
/**
* Throw away all output that may have happened during bootstrapping by weird extensions
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function endOutputBufferingAndCleanPreviousOutput() {
ob_clean();
return $this;
}
/**
* Initialize output compression if configured
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function initializeOutputCompression() {
if (extension_loaded('zlib') && $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel']) {
if (Utility\MathUtility::canBeInterpretedAsInteger($GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel'])) {
@ini_set('zlib.output_compression_level', $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel']);
}
ob_start('ob_gzhandler');
}
return $this;
}
/**
* Initialize module menu object
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function initializeModuleMenuObject() {
/** @var $moduleMenuUtility \TYPO3\CMS\Backend\Module\ModuleController */
$moduleMenuUtility = Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Module\\ModuleController');
$moduleMenuUtility->createModuleMenu();
return $this;
}
/**
* Things that should be performed to shut down the framework.
* This method is called in all important scripts for a clean
* shut down of the system.
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function shutdown() {
if (PHP_VERSION_ID < 50307) {
\TYPO3\CMS\Core\Compatibility\CompatbilityClassLoaderPhpBelow50307::unregisterAutoloader();
} else {
\TYPO3\CMS\Core\Core\ClassLoader::unregisterAutoloader();
}
return $this;
}
/**
* Provides an instance of "template" for backend-modules to
* work with.
*
* @return \TYPO3\CMS\Core\Core\Bootstrap
* @internal This is not a public API method, do not use in own extensions
*/
public function initializeBackendTemplate() {
$GLOBALS['TBE_TEMPLATE'] = Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Template\\DocumentTemplate');
return $this;
}
}
?>
|
gpl-2.0
|
babchai/wp_store2
|
wp-content/plugins/wpstorecart/js/anytime/anytimec.js
|
60759
|
/* anytimec.js 4.1094 (anytime.js 4.1094)
Copyright 2008-2010 Andrew M. Andrews III (www.AMA3.com). Some Rights
Reserved. This work licensed under the Creative Commons Attribution-
Noncommercial-Share Alike 3.0 Unported License except in jurisdicitons
for which the license has been ported by Creative Commons International,
where the work is licensed under the applicable ported license instead.
For a copy of the unported license, visit
http://creativecommons.org/licenses/by-nc-sa/3.0/
or send a letter to Creative Commons, 171 Second Street, Suite 300,
San Francisco, California, 94105, USA. For ported versions of the
license, visit http://creativecommons.org/international/
Any+Time is a trademark of Andrew M. Andrews III. */
var AnyTime={pad:function(val,len)
{var str=String(Math.abs(val));while(str.length<len)
str='0'+str;if(val<0)
str='-'+str;return str;}};(function($)
{var __oneDay=(24*60*60*1000);var __daysIn=[31,28,31,30,31,30,31,31,30,31,30,31];var __iframe=null;var __initialized=false;var __msie6=(navigator.userAgent.indexOf('MSIE 6')>0);var __msie7=(navigator.userAgent.indexOf('MSIE 7')>0);var __pickers=[];jQuery.prototype.AnyTime_picker=function(options)
{return this.each(function(i){AnyTime.picker(this.id,options);});}
jQuery.prototype.AnyTime_noPicker=function()
{return this.each(function(i){AnyTime.noPicker(this.id);});}
jQuery.prototype.AnyTime_height=function(inclusive)
{return(__msie6?Number(this.css('height').replace(/[^0-9]/g,'')):this.outerHeight(inclusive));};jQuery.prototype.AnyTime_width=function(inclusive)
{return(__msie6?(1+Number(this.css('width').replace(/[^0-9]/g,''))):this.outerWidth(inclusive));};jQuery.prototype.AnyTime_current=function(isCurrent,isLegal)
{if(isCurrent)
{this.removeClass('AnyTime-out-btn ui-state-default ui-state-disabled ui-state-highlight');this.addClass('AnyTime-cur-btn ui-state-default ui-state-highlight');}
else
{this.removeClass('AnyTime-cur-btn ui-state-highlight');if(!isLegal)
this.addClass('AnyTime-out-btn ui-state-disabled');else
{this.removeClass('AnyTime-out-btn ui-state-disabled');if(this.hasClass('AnyTime-min-one-btn-empty'))console.debug('removing min-one-button-empty state!');}}};jQuery.prototype.AnyTime_clickCurrent=function()
{this.find('.AnyTime-cur-btn').triggerHandler('click');}
$(document).ready(function()
{if(window.location.hostname.length&&(window.location.hostname!='www.ama3.com'))
$(document.body).append('<img src="http://www.ama3.com/anytime/ping/?4.1094'+(AnyTime.utcLabel?".tz":"")+'" width="0" height="0" />');if(__msie6)
{__iframe=$('<iframe frameborder="0" scrolling="no"></iframe>');__iframe.src="javascript:'<html></html>';";$(__iframe).css({display:'block',height:'1px',left:'0',top:'0',width:'1px',zIndex:0});$(document.body).append(__iframe);}
for(var id in __pickers)
__pickers[id].onReady();__initialized=true;});AnyTime.Converter=function(options)
{var _flen=0;var _longDay=9;var _longMon=9;var _shortDay=6;var _shortMon=3;var _offAl=Number.MIN_VALUE;var _offCap=Number.MIN_VALUE;var _offF=Number.MIN_VALUE;var _offFSI=(-1);var _offP=Number.MIN_VALUE;var _offPSI=(-1);var _captureOffset=false;this.fmt='%Y-%m-%d %T';this.dAbbr=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];this.dNames=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];this.eAbbr=['BCE','CE'];this.mAbbr=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];this.mNames=['January','February','March','April','May','June','July','August','September','October','November','December'];this.baseYear=null;this.dAt=function(str,pos)
{return((str.charCodeAt(pos)>='0'.charCodeAt(0))&&(str.charCodeAt(pos)<='9'.charCodeAt(0)));};this.format=function(date)
{var d=new Date(date.getTime());if((_offAl==Number.MIN_VALUE)&&(_offF!=Number.MIN_VALUE))
d.setTime((d.getTime()+(d.getTimezoneOffset()*60000))+(_offF*60000));var t;var str='';for(var f=0;f<_flen;f++)
{if(this.fmt.charAt(f)!='%')
str+=this.fmt.charAt(f);else
{var ch=this.fmt.charAt(f+1)
switch(ch)
{case'a':str+=this.dAbbr[d.getDay()];break;case'B':if(d.getFullYear()<0)
str+=this.eAbbr[0];break;case'b':str+=this.mAbbr[d.getMonth()];break;case'C':if(d.getFullYear()>0)
str+=this.eAbbr[1];break;case'c':str+=d.getMonth()+1;break;case'd':t=d.getDate();if(t<10)str+='0';str+=String(t);break;case'D':t=String(d.getDate());str+=t;if((t.length==2)&&(t.charAt(0)=='1'))
str+='th';else
{switch(t.charAt(t.length-1))
{case'1':str+='st';break;case'2':str+='nd';break;case'3':str+='rd';break;default:str+='th';break;}}
break;case'E':str+=this.eAbbr[(d.getFullYear()<0)?0:1];break;case'e':str+=d.getDate();break;case'H':t=d.getHours();if(t<10)str+='0';str+=String(t);break;case'h':case'I':t=d.getHours()%12;if(t==0)
str+='12';else
{if(t<10)str+='0';str+=String(t);}
break;case'i':t=d.getMinutes();if(t<10)str+='0';str+=String(t);break;case'k':str+=d.getHours();break;case'l':t=d.getHours()%12;if(t==0)
str+='12';else
str+=String(t);break;case'M':str+=this.mNames[d.getMonth()];break;case'm':t=d.getMonth()+1;if(t<10)str+='0';str+=String(t);break;case'p':str+=((d.getHours()<12)?'AM':'PM');break;case'r':t=d.getHours()%12;if(t==0)
str+='12:';else
{if(t<10)str+='0';str+=String(t)+':';}
t=d.getMinutes();if(t<10)str+='0';str+=String(t)+':';t=d.getSeconds();if(t<10)str+='0';str+=String(t);str+=((d.getHours()<12)?'AM':'PM');break;case'S':case's':t=d.getSeconds();if(t<10)str+='0';str+=String(t);break;case'T':t=d.getHours();if(t<10)str+='0';str+=String(t)+':';t=d.getMinutes();if(t<10)str+='0';str+=String(t)+':';t=d.getSeconds();if(t<10)str+='0';str+=String(t);break;case'W':str+=this.dNames[d.getDay()];break;case'w':str+=d.getDay();break;case'Y':str+=AnyTime.pad(d.getFullYear(),4);break;case'y':t=d.getFullYear()%100;str+=AnyTime.pad(t,2);break;case'Z':str+=AnyTime.pad(Math.abs(d.getFullYear()),4);break;case'z':str+=Math.abs(d.getFullYear());break;case'%':str+='%';break;case'#':t=(_offAl!=Number.MIN_VALUE)?_offAl:(_offF==Number.MIN_VALUE)?(0-d.getTimezoneOffset()):_offF;if(t>=0)
str+='+';str+=t;break;case'@':t=(_offAl!=Number.MIN_VALUE)?_offAl:(_offF==Number.MIN_VALUE)?(0-d.getTimezoneOffset()):_offF;if(AnyTime.utcLabel&&AnyTime.utcLabel[t])
{if((_offFSI>0)&&(_offFSI<AnyTime.utcLabel[t].length))
str+=AnyTime.utcLabel[t][_offFSI];else
str+=AnyTime.utcLabel[t][0];break;}
str+='UTC';ch=':';case'+':case'-':case':':case';':t=(_offAl!=Number.MIN_VALUE)?_offAl:(_offF==Number.MIN_VALUE)?(0-d.getTimezoneOffset()):_offF;if(t<0)
str+='-';else
str+='+';t=Math.abs(t);str+=((ch=='+')||(ch==':'))?AnyTime.pad(Math.floor(t/60),2):Math.floor(t/60);if((ch==':')||(ch==';'))
str+=':';str+=AnyTime.pad(t%60,2);break;case'f':case'j':case'U':case'u':case'V':case'v':case'X':case'x':throw'%'+ch+' not implemented by AnyTime.Converter';default:str+=this.fmt.substr(f,2);}
f++;}}
return str;};this.getUtcParseOffsetCaptured=function()
{return _offCap;};this.getUtcParseOffsetSubIndex=function()
{return _offPSI;};this.parse=function(str)
{_offCap=_offP;_offPSI=(-1);var era=1;var time=new Date();var slen=str.length;var s=0;var tzSign=1,tzOff=_offP;var i,matched,sub,sublen,temp;for(var f=0;f<_flen;f++)
{if(this.fmt.charAt(f)=='%')
{var ch=this.fmt.charAt(f+1);switch(ch)
{case'a':matched=false;for(sublen=0;s+sublen<slen;sublen++)
{sub=str.substr(s,sublen);for(i=0;i<12;i++)
if(this.dAbbr[i]==sub)
{matched=true;s+=sublen;break;}
if(matched)
break;}
if(!matched)
throw'unknown weekday: '+str.substr(s);break;case'B':sublen=this.eAbbr[0].length;if((s+sublen<=slen)&&(str.substr(s,sublen)==this.eAbbr[0]))
{era=(-1);s+=sublen;}
break;case'b':matched=false;for(sublen=0;s+sublen<slen;sublen++)
{sub=str.substr(s,sublen);for(i=0;i<12;i++)
if(this.mAbbr[i]==sub)
{time.setMonth(i);matched=true;s+=sublen;break;}
if(matched)
break;}
if(!matched)
throw'unknown month: '+str.substr(s);break;case'C':sublen=this.eAbbr[1].length;if((s+sublen<=slen)&&(str.substr(s,sublen)==this.eAbbr[1]))
s+=sublen;break;case'c':if((s+1<slen)&&this.dAt(str,s+1))
{time.setMonth((Number(str.substr(s,2))-1)%12);s+=2;}
else
{time.setMonth((Number(str.substr(s,1))-1)%12);s++;}
break;case'D':if((s+1<slen)&&this.dAt(str,s+1))
{time.setDate(Number(str.substr(s,2)));s+=4;}
else
{time.setDate(Number(str.substr(s,1)));s+=3;}
break;case'd':time.setDate(Number(str.substr(s,2)));s+=2;break;case'E':sublen=this.eAbbr[0].length;if((s+sublen<=slen)&&(str.substr(s,sublen)==this.eAbbr[0]))
{era=(-1);s+=sublen;}
else if((s+(sublen=this.eAbbr[1].length)<=slen)&&(str.substr(s,sublen)==this.eAbbr[1]))
s+=sublen;else
throw'unknown era: '+str.substr(s);break;case'e':if((s+1<slen)&&this.dAt(str,s+1))
{time.setDate(Number(str.substr(s,2)));s+=2;}
else
{time.setDate(Number(str.substr(s,1)));s++;}
break;case'f':s+=6;break;case'H':time.setHours(Number(str.substr(s,2)));s+=2;break;case'h':case'I':time.setHours(Number(str.substr(s,2)));s+=2;break;case'i':time.setMinutes(Number(str.substr(s,2)));s+=2;break;case'k':if((s+1<slen)&&this.dAt(str,s+1))
{time.setHours(Number(str.substr(s,2)));s+=2;}
else
{time.setHours(Number(str.substr(s,1)));s++;}
break;case'l':if((s+1<slen)&&this.dAt(str,s+1))
{time.setHours(Number(str.substr(s,2)));s+=2;}
else
{time.setHours(Number(str.substr(s,1)));s++;}
break;case'M':matched=false;for(sublen=_shortMon;s+sublen<=slen;sublen++)
{if(sublen>_longMon)
break;sub=str.substr(s,sublen);for(i=0;i<12;i++)
{if(this.mNames[i]==sub)
{time.setMonth(i);matched=true;s+=sublen;break;}}
if(matched)
break;}
break;case'm':time.setMonth((Number(str.substr(s,2))-1)%12);s+=2;break;case'p':if(str.charAt(s)=='P')
{if(time.getHours()==12)
time.setHours(0);else
time.setHours(time.getHours()+12);}
s+=2;break;case'r':time.setHours(Number(str.substr(s,2)));time.setMinutes(Number(str.substr(s+3,2)));time.setSeconds(Number(str.substr(s+6,2)));if(str.substr(s+8,1)=='P')
{if(time.getHours()==12)
time.setHours(0);else
time.setHours(time.getHours()+12);}
s+=10;break;case'S':case's':time.setSeconds(Number(str.substr(s,2)));s+=2;break;case'T':time.setHours(Number(str.substr(s,2)));time.setMinutes(Number(str.substr(s+3,2)));time.setSeconds(Number(str.substr(s+6,2)));s+=8;break;case'W':matched=false;for(sublen=_shortDay;s+sublen<=slen;sublen++)
{if(sublen>_longDay)
break;sub=str.substr(s,sublen);for(i=0;i<7;i++)
{if(this.dNames[i]==sub)
{matched=true;s+=sublen;break;}}
if(matched)
break;}
break;case'Y':i=4;if(str.substr(s,1)=='-')
i++;time.setFullYear(Number(str.substr(s,i)));s+=i;break;case'y':i=2;if(str.substr(s,1)=='-')
i++;temp=Number(str.substr(s,i));if(typeof(this.baseYear)=='number')
temp+=this.baseYear;else if(temp<70)
temp+=2000;else
temp+=1900;time.setFullYear(temp);s+=i;break;case'Z':time.setFullYear(Number(str.substr(s,4)));s+=4;break;case'z':i=0;while((s<slen)&&this.dAt(str,s))
i=(i*10)+Number(str.charAt(s++));time.setFullYear(i);break;case'#':if(str.charAt(s++)=='-')
tzSign=(-1);for(tzOff=0;(s<slen)&&(String(i=Number(str.charAt(s)))==str.charAt(s));s++)
tzOff=(tzOff*10)+i;tzOff*=tzSign;break;case'@':_offPSI=(-1);if(AnyTime.utcLabel)
{matched=false;for(tzOff in AnyTime.utcLabel)
{for(i=0;i<AnyTime.utcLabel[tzOff].length;i++)
{sub=AnyTime.utcLabel[tzOff][i];sublen=sub.length;if((s+sublen<=slen)&&(str.substr(s,sublen)==sub))
{matched=true;break;}}
if(matched)
break;}
if(matched)
{_offPSI=i;tzOff=Number(tzOff);break;}}
if((s+9<slen)||(str.substr(s,3)!="UTC"))
throw'unknown time zone: '+str.substr(s);s+=3;ch=':';case'-':case'+':case':':case';':if(str.charAt(s++)=='-')
tzSign=(-1);tzOff=Number(str.charAt(s));if((ch=='+')||(ch==':')||((s+3<slen)&&(String(Number(str.charAt(s+3)))!==str.charAt(s+3))))
tzOff=(tzOff*10)+Number(str.charAt(++s));tzOff*=60;if((ch==':')||(ch==';'))
s++;tzOff=(tzOff+Number(str.substr(++s,2)))*tzSign;s+=2;break;case'j':case'U':case'u':case'V':case'v':case'w':case'X':case'x':throw'%'+this.fmt.charAt(f+1)+' not implemented by AnyTime.Converter';case'%':default:throw'%'+this.fmt.charAt(f+1)+' reserved for future use';break;}
f++;}
else if(this.fmt.charAt(f)!=str.charAt(s))
throw str+' is not in "'+this.fmt+'" format';else
s++;}
if(era<0)
time.setFullYear(0-time.getFullYear());if(tzOff!=Number.MIN_VALUE)
{if(_captureOffset)
_offCap=tzOff;else
time.setTime((time.getTime()-(tzOff*60000))-(time.getTimezoneOffset()*60000));}
return time;};this.setUtcFormatOffsetAlleged=function(offset)
{var prev=_offAl;_offAl=offset;return prev;};this.setUtcFormatOffsetSubIndex=function(subIndex)
{var prev=_offFSI;_offFSI=subIndex;return prev;};(function(_this)
{var i;options=jQuery.extend(true,{},options||{});if(options.baseYear)
_this.baseYear=Number(options.baseYear);if(options.format)
_this.fmt=options.format;_flen=_this.fmt.length;if(options.dayAbbreviations)
_this.dAbbr=$.makeArray(options.dayAbbreviations);if(options.dayNames)
{_this.dNames=$.makeArray(options.dayNames);_longDay=1;_shortDay=1000;for(i=0;i<7;i++)
{var len=_this.dNames[i].length;if(len>_longDay)
_longDay=len;if(len<_shortDay)
_shortDay=len;}}
if(options.eraAbbreviations)
_this.eAbbr=$.makeArray(options.eraAbbreviations);if(options.monthAbbreviations)
_this.mAbbr=$.makeArray(options.monthAbbreviations);if(options.monthNames)
{_this.mNames=$.makeArray(options.monthNames);_longMon=1;_shortMon=1000;for(i=0;i<12;i++)
{var len=_this.mNames[i].length;if(len>_longMon)
_longMon=len;if(len<_shortMon)
_shortMon=len;}}
if(typeof options.utcFormatOffsetImposed!="undefined")
_offF=options.utcFormatOffsetImposed;if(typeof options.utcParseOffsetAssumed!="undefined")
_offP=options.utcParseOffsetAssumed;if(options.utcParseOffsetCapture)
_captureOffset=true;})(this);};AnyTime.noPicker=function(id)
{if(__pickers[id])
{__pickers[id].cleanup();delete __pickers[id];}};AnyTime.picker=function(id,options)
{if(__pickers[id])
throw'Cannot create another AnyTime picker for "'+id+'"';var _this=null;__pickers[id]={twelveHr:false,ajaxOpts:null,denyTab:true,askEra:false,cloak:null,conv:null,bMinW:0,bMinH:0,dMinW:0,dMinH:0,div:null,dB:null,dD:null,dY:null,dMo:null,dDoM:null,hDoM:null,hMo:null,hTitle:null,hY:null,dT:null,dH:null,dM:null,dS:null,dO:null,earliest:null,fBtn:null,fDOW:0,hBlur:null,hClick:null,hFocus:null,hKeydown:null,hKeypress:null,id:null,inp:null,latest:null,lastAjax:null,lostFocus:false,lX:'X',lY:'Year',lO:'Time Zone',oBody:null,oConv:null,oCur:null,oDiv:null,oLab:null,oListMinW:0,oMinW:0,oSel:null,offMin:Number.MIN_VALUE,offSI:-1,offStr:"",pop:true,time:null,tMinW:0,tMinH:0,url:null,wMinW:0,wMinH:0,yAhead:null,y0XXX:null,yCur:null,yDiv:null,yLab:null,yNext:null,yPast:null,yPrior:null,initialize:function(id)
{_this=this;this.id='AnyTime--'+id;options=jQuery.extend(true,{},options||{});options.utcParseOffsetCapture=true;this.conv=new AnyTime.Converter(options);if(options.placement)
{if(options.placement=='inline')
this.pop=false;else if(options.placement!='popup')
throw'unknown placement: '+options.placement;}
if(options.ajaxOptions)
{this.ajaxOpts=jQuery.extend({},options.ajaxOptions);if(!this.ajaxOpts.success)
this.ajaxOpts.success=function(data,status){_this.inp.val(data);};}
if(options.earliest)
{if(typeof options.earliest.getTime=='function')
this.earliest=options.earliest.getTime();else
this.earliest=this.conv.parse(options.earliest.toString());}
if(options.firstDOW)
{if((options.firstDOW<0)||(options.firstDOW>6))
throw new Exception('illegal firstDOW: '+options.firstDOW);this.fDOW=options.firstDOW;}
if(options.latest)
{if(typeof options.latest.getTime=='function')
this.latest=options.latest.getTime();else
this.latest=this.conv.parse(options.latest.toString());}
this.lX=options.labelDismiss||'X';this.lY=options.labelYear||'Year';this.lO=options.labelTimeZone||'Time Zone';var i;var t;var lab;var shownFields=0;var format=this.conv.fmt;if(typeof options.askEra!='undefined')
this.askEra=options.askEra;else
this.askEra=(format.indexOf('%B')>=0)||(format.indexOf('%C')>=0)||(format.indexOf('%E')>=0);var askYear=(format.indexOf('%Y')>=0)||(format.indexOf('%y')>=0)||(format.indexOf('%Z')>=0)||(format.indexOf('%z')>=0);var askMonth=(format.indexOf('%b')>=0)||(format.indexOf('%c')>=0)||(format.indexOf('%M')>=0)||(format.indexOf('%m')>=0);var askDoM=(format.indexOf('%D')>=0)||(format.indexOf('%d')>=0)||(format.indexOf('%e')>=0);var askDate=askYear||askMonth||askDoM;this.twelveHr=(format.indexOf('%h')>=0)||(format.indexOf('%I')>=0)||(format.indexOf('%l')>=0)||(format.indexOf('%r')>=0);var askHour=this.twelveHr||(format.indexOf('%H')>=0)||(format.indexOf('%k')>=0)||(format.indexOf('%T')>=0);var askMinute=(format.indexOf('%i')>=0)||(format.indexOf('%r')>=0)||(format.indexOf('%T')>=0);var askSec=((format.indexOf('%r')>=0)||(format.indexOf('%S')>=0)||(format.indexOf('%s')>=0)||(format.indexOf('%T')>=0));if(askSec&&(typeof options.askSecond!='undefined'))
askSec=options.askSecond;var askOff=((format.indexOf('%#')>=0)||(format.indexOf('%+')>=0)||(format.indexOf('%-')>=0)||(format.indexOf('%:')>=0)||(format.indexOf('%;')>=0)||(format.indexOf('%<')>=0)||(format.indexOf('%>')>=0)||(format.indexOf('%@')>=0));var askTime=askHour||askMinute||askSec||askOff;if(askOff)
this.oConv=new AnyTime.Converter({format:options.formatUtcOffset||format.match(/\S*%[-+:;<>#@]\S*/g).join(' ')});this.inp=$('#'+id);this.div=$('<div class="AnyTime-win AnyTime-pkr ui-widget ui-widget-content ui-corner-all" style="width:0;height:0" id="'+this.id+'" aria-live="off"/>');this.inp.after(this.div);this.wMinW=this.div.outerWidth(!$.browser.safari);this.wMinH=this.div.AnyTime_height(true);this.hTitle=$('<h5 class="AnyTime-hdr ui-widget-header ui-corner-top"/>');this.div.append(this.hTitle);this.dB=$('<div class="AnyTime-body" style="width:0;height:0"/>');this.div.append(this.dB);this.bMinW=this.dB.outerWidth(true);this.bMinH=this.dB.AnyTime_height(true);if(options.hideInput)
this.inp.css({border:0,height:'1px',margin:0,padding:0,width:'1px'});var t=null;var xDiv=null;if(this.pop)
{xDiv=$('<div class="AnyTime-x-btn ui-state-default">'+this.lX+'</div>');this.hTitle.append(xDiv);xDiv.click(function(e){_this.dismiss(e);});}
var lab='';if(askDate)
{this.dD=$('<div class="AnyTime-date" style="width:0;height:0"/>');this.dB.append(this.dD);this.dMinW=this.dD.outerWidth(true);this.dMinH=this.dD.AnyTime_height(true);if(askYear)
{this.yLab=$('<h6 class="AnyTime-lbl AnyTime-lbl-yr">'+this.lY+'</h6>');this.dD.append(this.yLab);this.dY=$('<ul class="AnyTime-yrs ui-helper-reset" />');this.dD.append(this.dY);this.yPast=this.btn(this.dY,'<',this.newYear,['yrs-past'],'- '+this.lY);this.yPrior=this.btn(this.dY,'1',this.newYear,['yr-prior'],'-1 '+this.lY);this.yCur=this.btn(this.dY,'2',this.newYear,['yr-cur'],this.lY);this.yCur.removeClass('ui-state-default');this.yCur.addClass('AnyTime-cur-btn ui-state-default ui-state-highlight');this.yNext=this.btn(this.dY,'3',this.newYear,['yr-next'],'+1 '+this.lY);this.yAhead=this.btn(this.dY,'>',this.newYear,['yrs-ahead'],'+ '+this.lY);shownFields++;}
if(askMonth)
{lab=options.labelMonth||'Month';this.hMo=$('<h6 class="AnyTime-lbl AnyTime-lbl-month">'+lab+'</h6>');this.dD.append(this.hMo);this.dMo=$('<ul class="AnyTime-mons" />');this.dD.append(this.dMo);for(i=0;i<12;i++)
{var mBtn=this.btn(this.dMo,this.conv.mAbbr[i],function(event)
{var elem=$(event.target);if(elem.hasClass("AnyTime-out-btn"))
return;var mo=event.target.AnyTime_month;var t=new Date(this.time.getTime());if(t.getDate()>__daysIn[mo])
t.setDate(__daysIn[mo])
t.setMonth(mo);this.set(t);this.upd(elem);},['mon','mon'+String(i+1)],lab+' '+this.conv.mNames[i]);mBtn[0].AnyTime_month=i;}
shownFields++;}
if(askDoM)
{lab=options.labelDayOfMonth||'Day of Month';this.hDoM=$('<h6 class="AnyTime-lbl AnyTime-lbl-dom">'+lab+'</h6>');this.dD.append(this.hDoM);this.dDoM=$('<table border="0" cellpadding="0" cellspacing="0" class="AnyTime-dom-table"/>');this.dD.append(this.dDoM);t=$('<thead class="AnyTime-dom-head"/>');this.dDoM.append(t);var tr=$('<tr class="AnyTime-dow"/>');t.append(tr);for(i=0;i<7;i++)
tr.append('<th class="AnyTime-dow AnyTime-dow'+String(i+1)+'">'+this.conv.dAbbr[(this.fDOW+i)%7]+'</th>');var tbody=$('<tbody class="AnyTime-dom-body" />');this.dDoM.append(tbody);for(var r=0;r<6;r++)
{tr=$('<tr class="AnyTime-wk AnyTime-wk'+String(r+1)+'"/>');tbody.append(tr);for(i=0;i<7;i++)
this.btn(tr,'x',function(event)
{var elem=$(event.target);if(elem.hasClass("AnyTime-out-btn"))
return;var dom=Number(elem.html());if(dom)
{var t=new Date(this.time.getTime());t.setDate(dom);this.set(t);this.upd(elem);}},['dom'],lab);}
shownFields++;}}
if(askTime)
{this.dT=$('<div class="AnyTime-time" style="width:0;height:0" />');this.dB.append(this.dT);this.tMinW=this.dT.outerWidth(true);this.tMinH=this.dT.AnyTime_height(true);if(askHour)
{this.dH=$('<div class="AnyTime-hrs"/>');this.dT.append(this.dH);lab=options.labelHour||'Hour';this.dH.append($('<h6 class="AnyTime-lbl AnyTime-lbl-hr">'+lab+'</h6>'));var amDiv=$('<ul class="AnyTime-hrs-am"/>');this.dH.append(amDiv);var pmDiv=$('<ul class="AnyTime-hrs-pm"/>');this.dH.append(pmDiv);for(i=0;i<12;i++)
{if(this.twelveHr)
{if(i==0)
t='12am';else
t=String(i)+'am';}
else
t=AnyTime.pad(i,2);this.btn(amDiv,t,this.newHour,['hr','hr'+String(i)],lab+' '+t);if(this.twelveHr)
{if(i==0)
t='12pm';else
t=String(i)+'pm';}
else
t=i+12;this.btn(pmDiv,t,this.newHour,['hr','hr'+String(i+12)],lab+' '+t);}
shownFields++;}
if(askMinute)
{this.dM=$('<div class="AnyTime-mins"/>');this.dT.append(this.dM);lab=options.labelMinute||'Minute';this.dM.append($('<h6 class="AnyTime-lbl AnyTime-lbl-min">'+lab+'</h6>'));var tensDiv=$('<ul class="AnyTime-mins-tens"/>');this.dM.append(tensDiv);for(i=0;i<6;i++)
this.btn(tensDiv,i,function(event)
{var elem=$(event.target);if(elem.hasClass("AnyTime-out-btn"))
return;var t=new Date(this.time.getTime());t.setMinutes((Number(elem.text())*10)+(this.time.getMinutes()%10));this.set(t);this.upd(elem);},['min-ten','min'+i+'0'],lab+' '+i+'0');for(;i<12;i++)
this.btn(tensDiv,' ',$.noop,['min-ten','min'+i+'0'],lab+' '+i+'0').addClass('AnyTime-min-ten-btn-empty ui-state-default ui-state-disabled');var onesDiv=$('<ul class="AnyTime-mins-ones"/>');this.dM.append(onesDiv);for(i=0;i<10;i++)
this.btn(onesDiv,i,function(event)
{var elem=$(event.target);if(elem.hasClass("AnyTime-out-btn"))
return;var t=new Date(this.time.getTime());t.setMinutes((Math.floor(this.time.getMinutes()/10)*10)+Number(elem.text()));this.set(t);this.upd(elem);},['min-one','min'+i],lab+' '+i);for(;i<12;i++)
this.btn(onesDiv,' ',$.noop,['min-one','min'+i+'0'],lab+' '+i).addClass('AnyTime-min-one-btn-empty ui-state-default ui-state-disabled');shownFields++;}
if(askSec)
{this.dS=$('<div class="AnyTime-secs"/>');this.dT.append(this.dS);lab=options.labelSecond||'Second';this.dS.append($('<h6 class="AnyTime-lbl AnyTime-lbl-sec">'+lab+'</h6>'));var tensDiv=$('<ul class="AnyTime-secs-tens"/>');this.dS.append(tensDiv);for(i=0;i<6;i++)
this.btn(tensDiv,i,function(event)
{var elem=$(event.target);if(elem.hasClass("AnyTime-out-btn"))
return;var t=new Date(this.time.getTime());t.setSeconds((Number(elem.text())*10)+(this.time.getSeconds()%10));this.set(t);this.upd(elem);},['sec-ten','sec'+i+'0'],lab+' '+i+'0');for(;i<12;i++)
this.btn(tensDiv,' ',$.noop,['sec-ten','sec'+i+'0'],lab+' '+i+'0').addClass('AnyTime-sec-ten-btn-empty ui-state-default ui-state-disabled');var onesDiv=$('<ul class="AnyTime-secs-ones"/>');this.dS.append(onesDiv);for(i=0;i<10;i++)
this.btn(onesDiv,i,function(event)
{var elem=$(event.target);if(elem.hasClass("AnyTime-out-btn"))
return;var t=new Date(this.time.getTime());t.setSeconds((Math.floor(this.time.getSeconds()/10)*10)+Number(elem.text()));this.set(t);this.upd(elem);},['sec-one','sec'+i],lab+' '+i);for(;i<12;i++)
this.btn(onesDiv,' ',$.noop,['sec-one','sec'+i+'0'],lab+' '+i).addClass('AnyTime-sec-one-btn-empty ui-state-default ui-state-disabled');shownFields++;}
if(askOff)
{this.dO=$('<div class="AnyTime-offs" />');this.dT.append(this.dO);this.oMinW=this.dO.outerWidth(true);this.oLab=$('<h6 class="AnyTime-lbl AnyTime-lbl-off">'+this.lO+'</h6>');this.dO.append(this.oLab);var offDiv=$('<ul class="AnyTime-off-list ui-helper-reset" />');this.dO.append(offDiv);this.oCur=this.btn(offDiv,'',this.newOffset,['off','off-cur'],lab);this.oCur.removeClass('ui-state-default');this.oCur.addClass('AnyTime-cur-btn ui-state-default ui-state-highlight');this.oCur.css({overflow:"hidden"});this.oSel=this.btn(offDiv,'±',this.newOffset,['off','off-select'],'+/- '+this.lO);this.oListMinW=this.oCur.outerWidth(true)+this.oSel.outerWidth(true);shownFields++;}}
if(options.labelTitle)
this.hTitle.append(options.labelTitle);else if(shownFields>1)
this.hTitle.append('Select a '+(askDate?(askTime?'Date and Time':'Date'):'Time'));else
this.hTitle.append('Select');try
{this.time=this.conv.parse(this.inp.val());this.offMin=this.conv.getUtcParseOffsetCaptured();this.offSI=this.conv.getUtcParseOffsetSubIndex();}
catch(e)
{this.time=new Date();}
this.lastAjax=this.time;if(this.pop)
{this.div.hide();if(__iframe)
__iframe.hide();this.div.css('position','absolute');}
this.inp.blur(this.hBlur=function(e)
{_this.inpBlur(e);});this.inp.click(this.hClick=function(e)
{_this.showPkr(e);});this.inp.focus(this.hFocus=function(e)
{if(_this.lostFocus)
_this.showPkr(e);_this.lostFocus=false;});this.inp.keydown(this.hKeydown=function(e)
{_this.key(e);});this.inp.keypress(this.hKeypress=function(e)
{if($.browser.opera&&_this.denyTab)
e.preventDefault();});this.div.click(function(e)
{_this.lostFocus=false;_this.inp.focus();});$(window).resize(function(e)
{_this.pos(e);});if(__initialized)
this.onReady();},ajax:function()
{if(this.ajaxOpts&&(this.time.getTime()!=this.lastAjax.getTime()))
{try
{var opts=jQuery.extend({},this.ajaxOpts);if(typeof opts.data=='object')
opts.data[this.inp[0].name||this.inp[0].id]=this.inp.val();else
{var opt=(this.inp[0].name||this.inp[0].id)+'='+encodeURI(this.inp.val());if(opts.data)
opts.data+='&'+opt;else
opts.data=opt;}
$.ajax(opts);this.lastAjax=this.time;}
catch(e)
{}}
return;},askOffset:function(event)
{if(!this.oDiv)
{this.makeCloak();this.oDiv=$('<div class="AnyTime-win AnyTime-off-selector ui-widget ui-widget-content ui-corner-all" style="position:absolute" />');this.div.append(this.oDiv);var title=$('<h5 class="AnyTime-hdr AnyTime-hdr-off-selector ui-widget-header ui-corner-top" />');this.oDiv.append(title);this.oBody=$('<div class="AnyTime-body AnyTime-body-off-selector" style="overflow:auto;white-space:nowrap" />');this.oDiv.append(this.oBody);var oBHS=this.oBody.AnyTime_height(true);var oBWS=this.oBody.AnyTime_width(true);var oTWS=title.AnyTime_width(true);var xDiv=$('<div class="AnyTime-x-btn ui-state-default">'+this.lX+'</div>');title.append(xDiv);xDiv.click(function(e){_this.dismissODiv(e);});title.append(this.lO);if(__msie6||__msie7)
title.width(String(this.lO.length*0.8)+"em");var oBW=title.AnyTime_width(true)-oBWS;var cont=$('<ul class="AnyTime-off-off" />');var last=null;this.oBody.append(cont);var useSubIndex=(this.oConv.fmt.indexOf('%@')>=0);var btnW=0;if(AnyTime.utcLabel)
for(var o=-720;o<720;o++)
if(AnyTime.utcLabel[o])
{this.oConv.setUtcFormatOffsetAlleged(o);for(var i=0;i<AnyTime.utcLabel[o].length;i++)
{this.oConv.setUtcFormatOffsetSubIndex(i);last=this.btn(cont,this.oConv.format(this.time),this.newOPos,['off-off'],o);last[0].AnyTime_offMin=o;last[0].AnyTime_offSI=i;var w=last.width();if(w>btnW)
btnW=w;if(!useSubIndex)
break;}}
if(last)
last.addClass('AnyTime-off-off-last-btn');this.oBody.find('.AnyTime-off-off-btn').width(btnW);if(last)
{var lW=last.AnyTime_width(true);if(lW>oBW)
oBW=lW+1;}
this.oBody.width(oBW);oBW=this.oBody.AnyTime_width(true);this.oDiv.width(oBW);if(__msie6||__msie7)
title.width(oBW-oTWS);var oH=this.oDiv.AnyTime_height(true);var oHmax=this.div.height()*0.75;if(oH>oHmax)
{oH=oHmax;this.oBody.height(oH-(title.AnyTime_height(true)+oBHS));this.oBody.width(this.oBody.width()+20);this.oDiv.width(this.oDiv.width()+20);if(__msie6||__msie7)
title.width(this.oBody.AnyTime_width(true)-oTWS);}
if(!__msie7)
this.oDiv.height(String(oH)+'px');}
else
{this.cloak.show();this.oDiv.show();}
this.pos(event);this.updODiv(null);var f=this.oDiv.find('.AnyTime-off-off-btn.AnyTime-cur-btn:first');if(!f.length)
f=this.oDiv.find('.AnyTime-off-off-btn:first');this.setFocus(f);},askYear:function(event)
{if(!this.yDiv)
{this.makeCloak();this.yDiv=$('<div class="AnyTime-win AnyTime-yr-selector ui-widget ui-widget-content ui-corner-all" style="position:absolute" />');this.div.append(this.yDiv);var title=$('<h5 class="AnyTime-hdr AnyTime-hdr-yr-selector ui-widget-header ui-corner-top" />');this.yDiv.append(title);var xDiv=$('<div class="AnyTime-x-btn ui-state-default">'+this.lX+'</div>');title.append(xDiv);xDiv.click(function(e){_this.dismissYDiv(e);});title.append(this.lY);var yBody=$('<div class="AnyTime-body AnyTime-body-yr-selector" />');var yW=yBody.AnyTime_width(true);var yH=0;this.yDiv.append(yBody);cont=$('<ul class="AnyTime-yr-mil" />');yBody.append(cont);this.y0XXX=this.btn(cont,0,this.newYPos,['mil','mil0'],this.lY+' '+0+'000');for(i=1;i<10;i++)
this.btn(cont,i,this.newYPos,['mil','mil'+i],this.lY+' '+i+'000');yW+=cont.AnyTime_width(true);if(yH<cont.AnyTime_height(true))
yH=cont.AnyTime_height(true);cont=$('<ul class="AnyTime-yr-cent" />');yBody.append(cont);for(i=0;i<10;i++)
this.btn(cont,i,this.newYPos,['cent','cent'+i],this.lY+' '+i+'00');yW+=cont.AnyTime_width(true);if(yH<cont.AnyTime_height(true))
yH=cont.AnyTime_height(true);cont=$('<ul class="AnyTime-yr-dec" />');yBody.append(cont);for(i=0;i<10;i++)
this.btn(cont,i,this.newYPos,['dec','dec'+i],this.lY+' '+i+'0');yW+=cont.AnyTime_width(true);if(yH<cont.AnyTime_height(true))
yH=cont.AnyTime_height(true);cont=$('<ul class="AnyTime-yr-yr" />');yBody.append(cont);for(i=0;i<10;i++)
this.btn(cont,i,this.newYPos,['yr','yr'+i],this.lY+' '+i);yW+=cont.AnyTime_width(true);if(yH<cont.AnyTime_height(true))
yH=cont.AnyTime_height(true);if(this.askEra)
{cont=$('<ul class="AnyTime-yr-era" />');yBody.append(cont);this.btn(cont,this.conv.eAbbr[0],function(event)
{var t=new Date(this.time.getTime());var year=t.getFullYear();if(year>0)
t.setFullYear(0-year);this.set(t);this.updYDiv($(event.target));},['era','bce'],this.conv.eAbbr[0]);this.btn(cont,this.conv.eAbbr[1],function(event)
{var t=new Date(this.time.getTime());var year=t.getFullYear();if(year<0)
t.setFullYear(0-year);this.set(t);this.updYDiv($(event.target));},['era','ce'],this.conv.eAbbr[1]);yW+=cont.AnyTime_width(true);if(yH<cont.AnyTime_height(true))
yH=cont.AnyTime_height(true);}
if($.browser.msie)
yW+=1;else if($.browser.safari)
yW+=2;yH+=yBody.AnyTime_height(true);yBody.css('width',String(yW)+'px');if(!__msie7)
yBody.css('height',String(yH)+'px');if(__msie6||__msie7)
title.width(yBody.outerWidth(true));yH+=title.AnyTime_height(true);if(title.AnyTime_width(true)>yW)
yW=title.AnyTime_width(true);this.yDiv.css('width',String(yW)+'px');if(!__msie7)
this.yDiv.css('height',String(yH)+'px');}
else
{this.cloak.show();this.yDiv.show();}
this.pos(event);this.updYDiv(null);this.setFocus(this.yDiv.find('.AnyTime-yr-btn.AnyTime-cur-btn:first'));},inpBlur:function(event)
{if(this.oDiv&&this.oDiv.is(":visible"))
{_this.inp.focus();return;}
this.lostFocus=true;setTimeout(function()
{if(_this.lostFocus)
{_this.div.find('.AnyTime-focus-btn').removeClass('AnyTime-focus-btn ui-state-focus');if(_this.pop)
_this.dismiss(event);else
_this.ajax();}},334);},btn:function(parent,text,handler,classes,title)
{var tagName=((parent[0].nodeName.toLowerCase()=='ul')?'li':'td');var div$='<'+tagName+' class="AnyTime-btn';for(var i=0;i<classes.length;i++)
div$+=' AnyTime-'+classes[i]+'-btn';var div=$(div$+' ui-state-default">'+text+'</'+tagName+'>');parent.append(div);div.AnyTime_title=title;div.click(function(e)
{_this.tempFunc=handler;_this.tempFunc(e);});div.dblclick(function(e)
{var elem=$(this);if(elem.is('.AnyTime-off-off-btn'))
_this.dismissODiv(e);else if(elem.is('.AnyTime-mil-btn')||elem.is('.AnyTime-cent-btn')||elem.is('.AnyTime-dec-btn')||elem.is('.AnyTime-yr-btn')||elem.is('.AnyTime-era-btn'))
_this.dismissYDiv(e);else if(_this.pop)
_this.dismiss(e);});return div;},cleanup:function(event)
{this.inp.unbind('blur',this.hBlur);this.inp.unbind('click',this.hClick);this.inp.unbind('focus',this.hFocus);this.inp.unbind('keydown',this.hKeydown);this.inp.unbind('keypress',this.hKeypress);this.div.remove();},dismiss:function(event)
{this.ajax();this.div.hide();if(__iframe)
__iframe.hide();if(this.yDiv)
this.dismissYDiv();if(this.oDiv)
this.dismissODiv();this.lostFocus=true;},dismissODiv:function(event)
{this.oDiv.hide();this.cloak.hide();this.setFocus(this.oCur);},dismissYDiv:function(event)
{this.yDiv.hide();this.cloak.hide();this.setFocus(this.yCur);},setFocus:function(btn)
{if(!btn.hasClass('AnyTime-focus-btn'))
{this.div.find('.AnyTime-focus-btn').removeClass('AnyTime-focus-btn ui-state-focus');this.fBtn=btn;btn.removeClass('ui-state-default ui-state-highlight');btn.addClass('AnyTime-focus-btn ui-state-default ui-state-highlight ui-state-focus');}
if(btn.hasClass('AnyTime-off-off-btn'))
{var oBT=this.oBody.offset().top;var btnT=btn.offset().top;var btnH=btn.AnyTime_height(true);if(btnT-btnH<oBT)
this.oBody.scrollTop(btnT+this.oBody.scrollTop()-(this.oBody.innerHeight()+oBT)+(btnH*2));else if(btnT+btnH>oBT+this.oBody.innerHeight())
this.oBody.scrollTop((btnT+this.oBody.scrollTop())-(oBT+btnH));}},key:function(event)
{var t=null;var elem=this.div.find('.AnyTime-focus-btn');var key=event.keyCode||event.which;this.denyTab=true;if(key==16)
{}
else if((key==10)||(key==13)||(key==27))
{if(this.oDiv&&this.oDiv.is(':visible'))
this.dismissODiv(event);else if(this.yDiv&&this.yDiv.is(':visible'))
this.dismissYDiv(event);else if(this.pop)
this.dismiss(event);}
else if((key==33)||((key==9)&&event.shiftKey))
{if(this.fBtn.hasClass('AnyTime-off-off-btn'))
{if(key==9)
this.dismissODiv(event);}
else if(this.fBtn.hasClass('AnyTime-mil-btn'))
{if(key==9)
this.dismissYDiv(event);}
else if(this.fBtn.hasClass('AnyTime-cent-btn'))
this.yDiv.find('.AnyTime-mil-btn.AnyTime-cur-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-dec-btn'))
this.yDiv.find('.AnyTime-cent-btn.AnyTime-cur-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-yr-btn'))
this.yDiv.find('.AnyTime-dec-btn.AnyTime-cur-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-era-btn'))
this.yDiv.find('.AnyTime-yr-btn.AnyTime-cur-btn').triggerHandler('click');else if(this.fBtn.parents('.AnyTime-yrs').length)
{if(key==9)
{this.denyTab=false;return;}}
else if(this.fBtn.hasClass('AnyTime-mon-btn'))
{if(this.dY)
this.yCur.triggerHandler('click');else if(key==9)
{this.denyTab=false;return;}}
else if(this.fBtn.hasClass('AnyTime-dom-btn'))
{if((key==9)&&event.shiftKey)
{this.denyTab=false;return;}
else
{t=new Date(this.time.getTime());if(event.shiftKey)
t.setFullYear(t.getFullYear()-1);else
{var mo=t.getMonth()-1;if(t.getDate()>__daysIn[mo])
t.setDate(__daysIn[mo])
t.setMonth(mo);}
this.keyDateChange(t);}}
else if(this.fBtn.hasClass('AnyTime-hr-btn'))
{t=this.dDoM||this.dMo;if(t)
t.AnyTime_clickCurrent();else if(this.dY)
this.yCur.triggerHandler('click');else if(key==9)
{this.denyTab=false;return;}}
else if(this.fBtn.hasClass('AnyTime-min-ten-btn'))
{t=this.dH||this.dDoM||this.dMo;if(t)
t.AnyTime_clickCurrent();else if(this.dY)
this.yCur.triggerHandler('click');else if(key==9)
{this.denyTab=false;return;}}
else if(this.fBtn.hasClass('AnyTime-min-one-btn'))
this.dM.AnyTime_clickCurrent();else if(this.fBtn.hasClass('AnyTime-sec-ten-btn'))
{if(this.dM)
t=this.dM.find('.AnyTime-mins-ones');else
t=this.dH||this.dDoM||this.dMo;if(t)
t.AnyTime_clickCurrent();else if(this.dY)
this.yCur.triggerHandler('click');else if(key==9)
{this.denyTab=false;return;}}
else if(this.fBtn.hasClass('AnyTime-sec-one-btn'))
this.dS.AnyTime_clickCurrent();else if(this.fBtn.hasClass('AnyTime-off-btn'))
{if(this.dS)
t=this.dS.find('.AnyTime-secs-ones');else if(this.dM)
t=this.dM.find('.AnyTime-mins-ones');else
t=this.dH||this.dDoM||this.dMo;if(t)
t.AnyTime_clickCurrent();else if(this.dY)
this.yCur.triggerHandler('click');else if(key==9)
{this.denyTab=false;return;}}}
else if((key==34)||(key==9))
{if(this.fBtn.hasClass('AnyTime-mil-btn'))
this.yDiv.find('.AnyTime-cent-btn.AnyTime-cur-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-cent-btn'))
this.yDiv.find('.AnyTime-dec-btn.AnyTime-cur-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-dec-btn'))
this.yDiv.find('.AnyTime-yr-btn.AnyTime-cur-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-yr-btn'))
{t=this.yDiv.find('.AnyTime-era-btn.AnyTime-cur-btn');if(t.length)
t.triggerHandler('click');else if(key==9)
this.dismissYDiv(event);}
else if(this.fBtn.hasClass('AnyTime-era-btn'))
{if(key==9)
this.dismissYDiv(event);}
else if(this.fBtn.hasClass('AnyTime-off-off-btn'))
{if(key==9)
this.dismissODiv(event);}
else if(this.fBtn.parents('.AnyTime-yrs').length)
{t=this.dDoM||this.dMo||this.dH||this.dM||this.dS||this.dO;if(t)
t.AnyTime_clickCurrent();else if(key==9)
{this.denyTab=false;return;}}
else if(this.fBtn.hasClass('AnyTime-mon-btn'))
{t=this.dDoM||this.dH||this.dM||this.dS||this.dO;if(t)
t.AnyTime_clickCurrent();else if(key==9)
{this.denyTab=false;return;}}
else if(this.fBtn.hasClass('AnyTime-dom-btn'))
{if(key==9)
{t=this.dH||this.dM||this.dS||this.dO;if(t)
t.AnyTime_clickCurrent();else
{this.denyTab=false;return;}}
else
{t=new Date(this.time.getTime());if(event.shiftKey)
t.setFullYear(t.getFullYear()+1);else
{var mo=t.getMonth()+1;if(t.getDate()>__daysIn[mo])
t.setDate(__daysIn[mo])
t.setMonth(mo);}
this.keyDateChange(t);}}
else if(this.fBtn.hasClass('AnyTime-hr-btn'))
{t=this.dM||this.dS||this.dO;if(t)
t.AnyTime_clickCurrent();else if(key==9)
{this.denyTab=false;return;}}
else if(this.fBtn.hasClass('AnyTime-min-ten-btn'))
this.dM.find('.AnyTime-mins-ones .AnyTime-cur-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-min-one-btn'))
{t=this.dS||this.dO;if(t)
t.AnyTime_clickCurrent();else if(key==9)
{this.denyTab=false;return;}}
else if(this.fBtn.hasClass('AnyTime-sec-ten-btn'))
this.dS.find('.AnyTime-secs-ones .AnyTime-cur-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-sec-one-btn'))
{if(this.dO)
this.dO.AnyTime_clickCurrent();else if(key==9)
{this.denyTab=false;return;}}
else if(this.fBtn.hasClass('AnyTime-off-btn'))
{if(key==9)
{this.denyTab=false;return;}}}
else if(key==35)
{if(this.fBtn.hasClass('AnyTime-mil-btn')||this.fBtn.hasClass('AnyTime-cent-btn')||this.fBtn.hasClass('AnyTime-dec-btn')||this.fBtn.hasClass('AnyTime-yr-btn')||this.fBtn.hasClass('AnyTime-era-btn'))
{t=this.yDiv.find('.AnyTime-ce-btn');if(!t.length)
t=this.yDiv.find('.AnyTime-yr9-btn');t.triggerHandler('click');}
else if(this.fBtn.hasClass('AnyTime-dom-btn'))
{t=new Date(this.time.getTime());t.setDate(1);t.setMonth(t.getMonth()+1);t.setDate(t.getDate()-1);if(event.ctrlKey)
t.setMonth(11);this.keyDateChange(t);}
else if(this.dS)
this.dS.find('.AnyTime-sec9-btn').triggerHandler('click');else if(this.dM)
this.dM.find('.AnyTime-min9-btn').triggerHandler('click');else if(this.dH)
this.dH.find('.AnyTime-hr23-btn').triggerHandler('click');else if(this.dDoM)
this.dDoM.find('.AnyTime-dom-btn-filled:last').triggerHandler('click');else if(this.dMo)
this.dMo.find('.AnyTime-mon12-btn').triggerHandler('click');else if(this.dY)
this.yAhead.triggerHandler('click');}
else if(key==36)
{if(this.fBtn.hasClass('AnyTime-mil-btn')||this.fBtn.hasClass('AnyTime-cent-btn')||this.fBtn.hasClass('AnyTime-dec-btn')||this.fBtn.hasClass('AnyTime-yr-btn')||this.fBtn.hasClass('AnyTime-era-btn'))
{this.yDiv.find('.AnyTime-mil0-btn').triggerHandler('click');}
else if(this.fBtn.hasClass('AnyTime-dom-btn'))
{t=new Date(this.time.getTime());t.setDate(1);if(event.ctrlKey)
t.setMonth(0);this.keyDateChange(t);}
else if(this.dY)
this.yCur.triggerHandler('click');else if(this.dMo)
this.dMo.find('.AnyTime-mon1-btn').triggerHandler('click');else if(this.dDoM)
this.dDoM.find('.AnyTime-dom-btn-filled:first').triggerHandler('click');else if(this.dH)
this.dH.find('.AnyTime-hr0-btn').triggerHandler('click');else if(this.dM)
this.dM.find('.AnyTime-min00-btn').triggerHandler('click');else if(this.dS)
this.dS.find('.AnyTime-sec00-btn').triggerHandler('click');}
else if(key==37)
{if(this.fBtn.hasClass('AnyTime-dom-btn'))
this.keyDateChange(new Date(this.time.getTime()-__oneDay));else
this.keyBack();}
else if(key==38)
{if(this.fBtn.hasClass('AnyTime-dom-btn'))
this.keyDateChange(new Date(this.time.getTime()-(7*__oneDay)));else
this.keyBack();}
else if(key==39)
{if(this.fBtn.hasClass('AnyTime-dom-btn'))
this.keyDateChange(new Date(this.time.getTime()+__oneDay));else
this.keyAhead();}
else if(key==40)
{if(this.fBtn.hasClass('AnyTime-dom-btn'))
this.keyDateChange(new Date(this.time.getTime()+(7*__oneDay)));else
this.keyAhead();}
else if(((key==86)||(key==118))&&event.ctrlKey)
{this.inp.val("").change();var _this=this;setTimeout(function(){_this.showPkr(null);},100);return;}
else
this.showPkr(null);event.preventDefault();},keyAhead:function()
{if(this.fBtn.hasClass('AnyTime-mil9-btn'))
this.yDiv.find('.AnyTime-cent0-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-cent9-btn'))
this.yDiv.find('.AnyTime-dec0-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-dec9-btn'))
this.yDiv.find('.AnyTime-yr0-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-yr9-btn'))
this.yDiv.find('.AnyTime-bce-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-sec9-btn'))
{}
else if(this.fBtn.hasClass('AnyTime-sec50-btn'))
this.dS.find('.AnyTime-sec0-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-min9-btn'))
{if(this.dS)
this.dS.find('.AnyTime-sec00-btn').triggerHandler('click');}
else if(this.fBtn.hasClass('AnyTime-min50-btn'))
this.dM.find('.AnyTime-min0-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-hr23-btn'))
{if(this.dM)
this.dM.find('.AnyTime-min00-btn').triggerHandler('click');else if(this.dS)
this.dS.find('.AnyTime-sec00-btn').triggerHandler('click');}
else if(this.fBtn.hasClass('AnyTime-hr11-btn'))
this.dH.find('.AnyTime-hr12-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-mon12-btn'))
{if(this.dDoM)
this.dDoM.AnyTime_clickCurrent();else if(this.dH)
this.dH.find('.AnyTime-hr0-btn').triggerHandler('click');else if(this.dM)
this.dM.find('.AnyTime-min00-btn').triggerHandler('click');else if(this.dS)
this.dS.find('.AnyTime-sec00-btn').triggerHandler('click');}
else if(this.fBtn.hasClass('AnyTime-yrs-ahead-btn'))
{if(this.dMo)
this.dMo.find('.AnyTime-mon1-btn').triggerHandler('click');else if(this.dH)
this.dH.find('.AnyTime-hr0-btn').triggerHandler('click');else if(this.dM)
this.dM.find('.AnyTime-min00-btn').triggerHandler('click');else if(this.dS)
this.dS.find('.AnyTime-sec00-btn').triggerHandler('click');}
else if(this.fBtn.hasClass('AnyTime-yr-cur-btn'))
this.yNext.triggerHandler('click');else
this.fBtn.next().triggerHandler('click');},keyBack:function()
{if(this.fBtn.hasClass('AnyTime-cent0-btn'))
this.yDiv.find('.AnyTime-mil9-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-dec0-btn'))
this.yDiv.find('.AnyTime-cent9-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-yr0-btn'))
this.yDiv.find('.AnyTime-dec9-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-bce-btn'))
this.yDiv.find('.AnyTime-yr9-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-yr-cur-btn'))
this.yPrior.triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-mon1-btn'))
{if(this.dY)
this.yCur.triggerHandler('click');}
else if(this.fBtn.hasClass('AnyTime-hr0-btn'))
{if(this.dDoM)
this.dDoM.AnyTime_clickCurrent();else if(this.dMo)
this.dMo.find('.AnyTime-mon12-btn').triggerHandler('click');else if(this.dY)
this.yNext.triggerHandler('click');}
else if(this.fBtn.hasClass('AnyTime-hr12-btn'))
this.dH.find('.AnyTime-hr11-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-min00-btn'))
{if(this.dH)
this.dH.find('.AnyTime-hr23-btn').triggerHandler('click');else if(this.dDoM)
this.dDoM.AnyTime_clickCurrent();else if(this.dMo)
this.dMo.find('.AnyTime-mon12-btn').triggerHandler('click');else if(this.dY)
this.yNext.triggerHandler('click');}
else if(this.fBtn.hasClass('AnyTime-min0-btn'))
this.dM.find('.AnyTime-min50-btn').triggerHandler('click');else if(this.fBtn.hasClass('AnyTime-sec00-btn'))
{if(this.dM)
this.dM.find('.AnyTime-min9-btn').triggerHandler('click');else if(this.dH)
this.dH.find('.AnyTime-hr23-btn').triggerHandler('click');else if(this.dDoM)
this.dDoM.AnyTime_clickCurrent();else if(this.dMo)
this.dMo.find('.AnyTime-mon12-btn').triggerHandler('click');else if(this.dY)
this.yNext.triggerHandler('click');}
else if(this.fBtn.hasClass('AnyTime-sec0-btn'))
this.dS.find('.AnyTime-sec50-btn').triggerHandler('click');else
this.fBtn.prev().triggerHandler('click');},keyDateChange:function(newDate)
{if(this.fBtn.hasClass('AnyTime-dom-btn'))
{this.set(newDate);this.upd(null);this.setFocus(this.dDoM.find('.AnyTime-cur-btn'));}},makeCloak:function()
{if(!this.cloak)
{this.cloak=$('<div class="AnyTime-cloak" style="position:absolute" />');this.div.append(this.cloak);this.cloak.click(function(e)
{if(_this.oDiv&&_this.oDiv.is(":visible"))
_this.dismissODiv(e);else
_this.dismissYDiv(e);});}
else
this.cloak.show();},newHour:function(event)
{var h;var t;var elem=$(event.target);if(elem.hasClass("AnyTime-out-btn"))
return;if(!this.twelveHr)
h=Number(elem.text());else
{var str=elem.text();t=str.indexOf('a');if(t<0)
{t=Number(str.substr(0,str.indexOf('p')));h=((t==12)?12:(t+12));}
else
{t=Number(str.substr(0,t));h=((t==12)?0:t);}}
t=new Date(this.time.getTime());t.setHours(h);this.set(t);this.upd(elem);},newOffset:function(event)
{if(event.target==this.oSel[0])
this.askOffset(event);else
{this.upd(this.oCur);}},newOPos:function(event)
{var elem=$(event.target);this.offMin=elem[0].AnyTime_offMin;this.offSI=elem[0].AnyTime_offSI;var t=new Date(this.time.getTime());this.set(t);this.updODiv(elem);},newYear:function(event)
{var elem=$(event.target);if(elem.hasClass("AnyTime-out-btn"))
return;var txt=elem.text();if((txt=='<')||(txt=='<'))
this.askYear(event);else if((txt=='>')||(txt=='>'))
this.askYear(event);else
{var t=new Date(this.time.getTime());t.setFullYear(Number(txt));this.set(t);this.upd(this.yCur);}},newYPos:function(event)
{var elem=$(event.target);if(elem.hasClass("AnyTime-out-btn"))
return;var era=1;var year=this.time.getFullYear();if(year<0)
{era=(-1);year=0-year;}
year=AnyTime.pad(year,4);if(elem.hasClass('AnyTime-mil-btn'))
year=elem.html()+year.substring(1,4);else if(elem.hasClass('AnyTime-cent-btn'))
year=year.substring(0,1)+elem.html()+year.substring(2,4);else if(elem.hasClass('AnyTime-dec-btn'))
year=year.substring(0,2)+elem.html()+year.substring(3,4);else
year=year.substring(0,3)+elem.html();if(year=='0000')
year=1;var t=new Date(this.time.getTime());t.setFullYear(era*year);this.set(t);this.updYDiv(elem);},onReady:function()
{this.lostFocus=true;if(!this.pop)
this.upd(null);else
{if(this.div.parent()!=document.body)
this.div.appendTo(document.body);}},pos:function(event)
{if(this.pop)
{var off=this.inp.offset();var bodyWidth=$(document.body).outerWidth(true);var pickerWidth=this.div.outerWidth(true);var left=off.left;if(left+pickerWidth>bodyWidth-20)
left=bodyWidth-(pickerWidth+20);var top=off.top-this.div.outerHeight(true);if(top<0)
top=off.top+this.inp.outerHeight(true);this.div.css({top:String(top)+'px',left:String(left<0?0:left)+'px'});}
var wOff=this.div.offset();if(this.oDiv&&this.oDiv.is(":visible"))
{var oOff=this.oLab.offset();if(this.div.css('position')=='absolute')
{oOff.top-=wOff.top;oOff.left=oOff.left-wOff.left;wOff={top:0,left:0};}
var oW=this.oDiv.AnyTime_width(true);var wW=this.div.AnyTime_width(true);if(oOff.left+oW>wOff.left+wW)
{oOff.left=(wOff.left+wW)-oW;if(oOff.left<2)
oOff.left=2;}
var oH=this.oDiv.AnyTime_height(true);var wH=this.div.AnyTime_height(true);oOff.top+=this.oLab.AnyTime_height(true);if(oOff.top+oH>wOff.top+wH)
oOff.top=oOff.top-oH;if(oOff.top<wOff.top)
oOff.top=wOff.top;this.oDiv.css({top:oOff.top+'px',left:oOff.left+'px'});}
else if(this.yDiv&&this.yDiv.is(":visible"))
{var yOff=this.yLab.offset();if(this.div.css('position')=='absolute')
{yOff.top-=wOff.top;yOff.left=yOff.left-wOff.left;wOff={top:0,left:0};}
yOff.left+=((this.yLab.outerWidth(true)-this.yDiv.outerWidth(true))/2);this.yDiv.css({top:yOff.top+'px',left:yOff.left+'px'});}
if(this.cloak)
this.cloak.css({top:wOff.top+'px',left:wOff.left+'px',height:String(this.div.outerHeight(true)-2)+'px',width:String(this.div.outerWidth(!$.browser.safari)-2)+'px'});},set:function(newTime)
{var t=newTime.getTime();if(this.earliest&&(t<this.earliest))
this.time=new Date(this.earliest);else if(this.latest&&(t>this.latest))
this.time=new Date(this.latest);else
this.time=newTime;},showPkr:function(event)
{try
{this.time=this.conv.parse(this.inp.val());this.offMin=this.conv.getUtcParseOffsetCaptured();this.offSI=this.conv.getUtcParseOffsetSubIndex();}
catch(e)
{this.time=new Date();}
this.set(this.time);this.upd(null);fBtn=null;var cb='.AnyTime-cur-btn:first';if(this.dDoM)
fBtn=this.dDoM.find(cb);else if(this.yCur)
fBtn=this.yCur;else if(this.dMo)
fBtn=this.dMo.find(cb);else if(this.dH)
fBtn=this.dH.find(cb);else if(this.dM)
fBtn=this.dM.find(cb);else if(this.dS)
fBtn=this.dS.find(cb);this.setFocus(fBtn);this.pos(event);if(this.pop&&__iframe)
setTimeout(function()
{var pos=_this.div.offset();__iframe.css({height:String(_this.div.outerHeight(true))+'px',left:String(pos.left)+'px',position:'absolute',top:String(pos.top)+'px',width:String(_this.div.outerWidth(true))+'px'});__iframe.show();},300);},upd:function(fBtn)
{var cmpLo=new Date(this.time.getTime());cmpLo.setMonth(0,1);cmpLo.setHours(0,0,0,0);var cmpHi=new Date(this.time.getTime());cmpHi.setMonth(11,31);cmpHi.setHours(23,59,59,999);var current=this.time.getFullYear();if(this.earliest&&this.yPast)
{cmpHi.setYear(current-2);if(cmpHi.getTime()<this.earliest)
this.yPast.addClass('AnyTime-out-btn ui-state-disabled');else
this.yPast.removeClass('AnyTime-out-btn ui-state-disabled');}
if(this.yPrior)
{this.yPrior.text(AnyTime.pad((current==1)?(-1):(current-1),4));if(this.earliest)
{cmpHi.setYear(current-1);if(cmpHi.getTime()<this.earliest)
this.yPrior.addClass('AnyTime-out-btn ui-state-disabled');else
this.yPrior.removeClass('AnyTime-out-btn ui-state-disabled');}}
if(this.yCur)
this.yCur.text(AnyTime.pad(current,4));if(this.yNext)
{this.yNext.text(AnyTime.pad((current==-1)?1:(current+1),4));if(this.latest)
{cmpLo.setYear(current+1);if(cmpLo.getTime()>this.latest)
this.yNext.addClass('AnyTime-out-btn ui-state-disabled');else
this.yNext.removeClass('AnyTime-out-btn ui-state-disabled');}}
if(this.latest&&this.yAhead)
{cmpLo.setYear(current+2);if(cmpLo.getTime()>this.latest)
this.yAhead.addClass('AnyTime-out-btn ui-state-disabled');else
this.yAhead.removeClass('AnyTime-out-btn ui-state-disabled');}
cmpLo.setFullYear(this.time.getFullYear());cmpHi.setFullYear(this.time.getFullYear());var i=0;current=this.time.getMonth();$('#'+this.id+' .AnyTime-mon-btn').each(function()
{cmpLo.setMonth(i);cmpHi.setDate(1);cmpHi.setMonth(i+1);cmpHi.setDate(0);$(this).AnyTime_current(i==current,((!_this.earliest)||(cmpHi.getTime()>=_this.earliest))&&((!_this.latest)||(cmpLo.getTime()<=_this.latest)));i++;});cmpLo.setMonth(this.time.getMonth());cmpHi.setMonth(this.time.getMonth(),1);current=this.time.getDate();var currentMonth=this.time.getMonth();var dow1=cmpLo.getDay();if(this.fDOW>dow1)
dow1+=7;var wom=0,dow=0;$('#'+this.id+' .AnyTime-wk').each(function()
{dow=_this.fDOW;$(this).children().each(function()
{if(dow-_this.fDOW<7)
{var td=$(this);if(((wom==0)&&(dow<dow1))||(cmpLo.getMonth()!=currentMonth))
{td.html(' ');td.removeClass('AnyTime-dom-btn-filled AnyTime-cur-btn ui-state-default ui-state-highlight');td.addClass('AnyTime-dom-btn-empty');if(wom)
{if((cmpLo.getDate()==1)&&(dow!=0))
td.addClass('AnyTime-dom-btn-empty-after-filled');else
td.removeClass('AnyTime-dom-btn-empty-after-filled');if(cmpLo.getDate()<=7)
td.addClass('AnyTime-dom-btn-empty-below-filled');else
td.removeClass('AnyTime-dom-btn-empty-below-filled');cmpLo.setDate(cmpLo.getDate()+1);cmpHi.setDate(cmpHi.getDate()+1);}
else
{td.addClass('AnyTime-dom-btn-empty-above-filled');if(dow==dow1-1)
td.addClass('AnyTime-dom-btn-empty-before-filled');else
td.removeClass('AnyTime-dom-btn-empty-before-filled');}
td.addClass('ui-state-default ui-state-disabled');}
else
{i=cmpLo.getDate();td.text(i);td.removeClass('AnyTime-dom-btn-empty AnyTime-dom-btn-empty-above-filled AnyTime-dom-btn-empty-before-filled '+'AnyTime-dom-btn-empty-after-filled AnyTime-dom-btn-empty-below-filled '+'ui-state-default ui-state-disabled');td.addClass('AnyTime-dom-btn-filled ui-state-default');td.AnyTime_current(i==current,((!_this.earliest)||(cmpHi.getTime()>=_this.earliest))&&((!_this.latest)||(cmpLo.getTime()<=_this.latest)));cmpLo.setDate(i+1);cmpHi.setDate(i+1);}}
dow++;});wom++;});cmpLo.setMonth(this.time.getMonth(),this.time.getDate());cmpHi.setMonth(this.time.getMonth(),this.time.getDate());var not12=!this.twelveHr;var h=this.time.getHours();$('#'+this.id+' .AnyTime-hr-btn').each(function()
{var html=this.innerHTML;var i;if(not12)
i=Number(html);else
{i=Number(html.substring(0,html.length-2));if(html.charAt(html.length-2)=='a')
{if(i==12)
i=0;}
else if(i<12)
i+=12;}
cmpLo.setHours(i);cmpHi.setHours(i);$(this).AnyTime_current(h==i,((!_this.earliest)||(cmpHi.getTime()>=_this.earliest))&&((!_this.latest)||(cmpLo.getTime()<=_this.latest)));cmpLo.setHours(cmpLo.getHours()+1);});cmpLo.setMonth(this.time.getMonth(),this.time.getDate());cmpLo.setHours(this.time.getHours(),0);cmpHi.setMonth(this.time.getMonth(),this.time.getDate());cmpHi.setHours(this.time.getHours(),9);var mi=this.time.getMinutes();var tens=String(Math.floor(mi/10));var ones=String(mi%10);$('#'+this.id+' .AnyTime-min-ten-btn:not(.AnyTime-min-ten-btn-empty)').each(function()
{$(this).AnyTime_current(this.innerHTML==tens,((!_this.earliest)||(cmpHi.getTime()>=_this.earliest))&&((!_this.latest)||(cmpLo.getTime()<=_this.latest)));cmpLo.setMinutes(cmpLo.getMinutes()+10);cmpHi.setMinutes(cmpHi.getMinutes()+10);});cmpLo.setHours(this.time.getHours(),Math.floor(this.time.getMinutes()/10)*10);cmpHi.setHours(this.time.getHours(),Math.floor(this.time.getMinutes()/10)*10);$('#'+this.id+' .AnyTime-min-one-btn:not(.AnyTime-min-one-btn-empty)').each(function()
{$(this).AnyTime_current(this.innerHTML==ones,((!_this.earliest)||(cmpHi.getTime()>=_this.earliest))&&((!_this.latest)||(cmpLo.getTime()<=_this.latest)));cmpLo.setMinutes(cmpLo.getMinutes()+1);cmpHi.setMinutes(cmpHi.getMinutes()+1);});cmpLo.setMonth(this.time.getMonth(),this.time.getDate());cmpLo.setHours(this.time.getHours(),this.time.getMinutes(),0);cmpHi.setMonth(this.time.getMonth(),this.time.getDate());cmpHi.setHours(this.time.getHours(),this.time.getMinutes(),9);var mi=this.time.getSeconds();var tens=String(Math.floor(mi/10));var ones=String(mi%10);$('#'+this.id+' .AnyTime-sec-ten-btn:not(.AnyTime-sec-ten-btn-empty)').each(function()
{$(this).AnyTime_current(this.innerHTML==tens,((!_this.earliest)||(cmpHi.getTime()>=_this.earliest))&&((!_this.latest)||(cmpLo.getTime()<=_this.latest)));cmpLo.setSeconds(cmpLo.getSeconds()+10);cmpHi.setSeconds(cmpHi.getSeconds()+10);});cmpLo.setMinutes(this.time.getMinutes(),Math.floor(this.time.getSeconds()/10)*10);cmpHi.setMinutes(this.time.getMinutes(),Math.floor(this.time.getSeconds()/10)*10);$('#'+this.id+' .AnyTime-sec-one-btn:not(.AnyTime-sec-one-btn-empty)').each(function()
{$(this).AnyTime_current(this.innerHTML==ones,((!_this.earliest)||(cmpHi.getTime()>=_this.earliest))&&((!_this.latest)||(cmpLo.getTime()<=_this.latest)));cmpLo.setSeconds(cmpLo.getSeconds()+1);cmpHi.setSeconds(cmpHi.getSeconds()+1);});if(this.oConv)
{this.oConv.setUtcFormatOffsetAlleged(this.offMin);this.oConv.setUtcFormatOffsetSubIndex(this.offSI);var tzs=this.oConv.format(this.time);this.oCur.html(tzs);}
if(fBtn)
this.setFocus(fBtn);this.conv.setUtcFormatOffsetAlleged(this.offMin);this.conv.setUtcFormatOffsetSubIndex(this.offSI);this.inp.val(this.conv.format(this.time)).change();this.div.show();var d,totH=0,totW=0,dYW=0,dMoW=0,dDoMW=0;if(this.dY)
{totW=dYW=this.dY.outerWidth(true);totH=this.yLab.AnyTime_height(true)+this.dY.AnyTime_height(true);}
if(this.dMo)
{dMoW=this.dMo.outerWidth(true);if(dMoW>totW)
totW=dMoW;totH+=this.hMo.AnyTime_height(true)+this.dMo.AnyTime_height(true);}
if(this.dDoM)
{dDoMW=this.dDoM.outerWidth(true);if(dDoMW>totW)
totW=dDoMW;if(__msie6||__msie7)
{if(dMoW>dDoMW)
this.dDoM.css('width',String(dMoW)+'px');else if(dYW>dDoMW)
this.dDoM.css('width',String(dYW)+'px');}
totH+=this.hDoM.AnyTime_height(true)+this.dDoM.AnyTime_height(true);}
if(this.dD)
{this.dD.css({width:String(totW)+'px',height:String(totH)+'px'});totW+=this.dMinW;totH+=this.dMinH;}
var w=0,h=0,timeH=0,timeW=0;if(this.dH)
{w=this.dH.outerWidth(true);timeW+=w+1;h=this.dH.AnyTime_height(true);if(h>timeH)
timeH=h;}
if(this.dM)
{w=this.dM.outerWidth(true);timeW+=w+1;h=this.dM.AnyTime_height(true);if(h>timeH)
timeH=h;}
if(this.dS)
{w=this.dS.outerWidth(true);timeW+=w+1;h=this.dS.AnyTime_height(true);if(h>timeH)
timeH=h;}
if(this.dO)
{w=this.oMinW;if(timeW<w+1)
timeW=w+1;timeH+=this.dO.AnyTime_height(true);}
if(this.dT)
{this.dT.css({width:String(timeW)+'px',height:String(timeH)+'px'});timeW+=this.tMinW+1;timeH+=this.tMinH;totW+=timeW;if(timeH>totH)
totH=timeH;if(this.dO)
{var dOW=this.dT.width()-(this.oMinW+1);this.dO.css({width:String(dOW)+"px"});this.oCur.css({width:String(dOW-(this.oListMinW+4))+"px"});}}
this.dB.css({height:String(totH)+'px',width:String(totW)+'px'});totH+=this.bMinH;totW+=this.bMinW;totH+=this.hTitle.AnyTime_height(true)+this.wMinH;totW+=this.wMinW;if(this.hTitle.outerWidth(true)>totW)
totW=this.hTitle.outerWidth(true);this.div.css({height:String(totH)+'px',width:String(totW)+'px'});if(!this.pop)
this.ajax();},updODiv:function(fBtn)
{var cur,matched=false,def=null;this.oDiv.find('.AnyTime-off-off-btn').each(function()
{if(this.AnyTime_offMin==_this.offMin)
{if(this.AnyTime_offSI==_this.offSI)
$(this).AnyTime_current(matched=true,true);else
{$(this).AnyTime_current(false,true);if(def==null)
def=$(this);}}
else
$(this).AnyTime_current(false,true);});if((!matched)&&(def!=null))
def.AnyTime_current(true,true);this.conv.setUtcFormatOffsetAlleged(this.offMin);this.conv.setUtcFormatOffsetSubIndex(this.offSI);this.inp.val(this.conv.format(this.time)).change();this.upd(fBtn);},updYDiv:function(fBtn)
{var i,legal;var era=1;var yearValue=this.time.getFullYear();if(yearValue<0)
{era=(-1);yearValue=0-yearValue;}
yearValue=AnyTime.pad(yearValue,4);var eY=_this.earliest&&new Date(_this.earliest).getFullYear();var lY=_this.latest&&new Date(_this.latest).getFullYear();i=0;this.yDiv.find('.AnyTime-mil-btn').each(function()
{legal=(((!_this.earliest)||(era*(i+(era<0?0:999))>=eY))&&((!_this.latest)||(era*(i+(era>0?0:999))<=lY)));$(this).AnyTime_current(this.innerHTML==yearValue.substring(0,1),legal);i+=1000;});i=(Math.floor(yearValue/1000)*1000);this.yDiv.find('.AnyTime-cent-btn').each(function()
{legal=(((!_this.earliest)||(era*(i+(era<0?0:99))>=eY))&&((!_this.latest)||(era*(i+(era>0?0:99))<=lY)));$(this).AnyTime_current(this.innerHTML==yearValue.substring(1,2),legal);i+=100;});i=(Math.floor(yearValue/100)*100);this.yDiv.find('.AnyTime-dec-btn').each(function()
{legal=(((!_this.earliest)||(era*(i+(era<0?0:9))>=eY))&&((!_this.latest)||(era*(i+(era>0?0:9))<=lY)));$(this).AnyTime_current(this.innerHTML==yearValue.substring(2,3),legal);i+=10;});i=(Math.floor(yearValue/10)*10);this.yDiv.find('.AnyTime-yr-btn').each(function()
{legal=(((!_this.earliest)||(era*i>=eY))&&((!_this.latest)||(era*i<=lY)));$(this).AnyTime_current(this.innerHTML==yearValue.substring(3),legal);i+=1;});this.yDiv.find('.AnyTime-bce-btn').each(function()
{$(this).AnyTime_current(era<0,(!_this.earliest)||(_this.earliest<0));});this.yDiv.find('.AnyTime-ce-btn').each(function()
{$(this).AnyTime_current(era>0,(!_this.latest)||(_this.latest>0));});this.conv.setUtcFormatOffsetAlleged(this.offMin);this.conv.setUtcFormatOffsetSubIndex(this.offSI);this.inp.val(this.conv.format(this.time)).change();this.upd(fBtn);}};__pickers[id].initialize(id);}})(jQuery);
|
gpl-2.0
|
havran/Drupal.sk
|
docroot/drupal/core/modules/quickedit/js/editors/formEditor.js
|
7907
|
/**
* @file
* Form-based in-place editor. Works for any field type.
*/
(function ($, Drupal) {
"use strict";
/**
* @constructor
*
* @augments Drupal.quickedit.EditorView
*/
Drupal.quickedit.editors.form = Drupal.quickedit.EditorView.extend(/** @lends Drupal.quickedit.editors.form# */{
/**
* Tracks form container DOM element that is used while in-place editing.
*
* @type {jQuery}
*/
$formContainer: null,
/**
* Holds the {@link Drupal.Ajax} object.
*
* @type {Drupal.Ajax}
*/
formSaveAjax: null,
/**
* @inheritdoc
*
* @param {object} fieldModel
* @param {string} state
*/
stateChange: function (fieldModel, state) {
var from = fieldModel.previous('state');
var to = state;
switch (to) {
case 'inactive':
break;
case 'candidate':
if (from !== 'inactive') {
this.removeForm();
}
break;
case 'highlighted':
break;
case 'activating':
// If coming from an invalid state, then the form is already loaded.
if (from !== 'invalid') {
this.loadForm();
}
break;
case 'active':
break;
case 'changed':
break;
case 'saving':
this.save();
break;
case 'saved':
break;
case 'invalid':
this.showValidationErrors();
break;
}
},
/**
* @inheritdoc
*
* @return {object}
*/
getQuickEditUISettings: function () {
return {padding: true, unifiedToolbar: true, fullWidthToolbar: true, popup: true};
},
/**
* Loads the form for this field, displays it on top of the actual field.
*/
loadForm: function () {
var fieldModel = this.fieldModel;
// Generate a DOM-compatible ID for the form container DOM element.
var id = 'quickedit-form-for-' + fieldModel.id.replace(/[\/\[\]]/g, '_');
// Render form container.
var $formContainer = this.$formContainer = $(Drupal.theme('quickeditFormContainer', {
id: id,
loadingMsg: Drupal.t('Loading…')
}));
$formContainer
.find('.quickedit-form')
.addClass('quickedit-editable quickedit-highlighted quickedit-editing')
.attr('role', 'dialog');
// Insert form container in DOM.
if (this.$el.css('display') === 'inline') {
$formContainer.prependTo(this.$el.offsetParent());
// Position the form container to render on top of the field's element.
var pos = this.$el.position();
$formContainer.css('left', pos.left).css('top', pos.top);
}
else {
$formContainer.insertBefore(this.$el);
}
// Load form, insert it into the form container and attach event handlers.
var formOptions = {
fieldID: fieldModel.get('fieldID'),
$el: this.$el,
nocssjs: false,
// Reset an existing entry for this entity in the PrivateTempStore (if
// any) when loading the field. Logically speaking, this should happen
// in a separate request because this is an entity-level operation, not
// a field-level operation. But that would require an additional
// request, that might not even be necessary: it is only when a user
// loads a first changed field for an entity that this needs to happen:
// precisely now!
reset: !fieldModel.get('entity').get('inTempStore')
};
Drupal.quickedit.util.form.load(formOptions, function (form, ajax) {
Drupal.AjaxCommands.prototype.insert(ajax, {
data: form,
selector: '#' + id + ' .placeholder'
});
$formContainer
.on('formUpdated.quickedit', ':input', function (event) {
var state = fieldModel.get('state');
// If the form is in an invalid state, it will persist on the page.
// Set the field to activating so that the user can correct the
// invalid value.
if (state === 'invalid') {
fieldModel.set('state', 'activating');
}
// Otherwise assume that the fieldModel is in a candidate state and
// set it to changed on formUpdate.
else {
fieldModel.set('state', 'changed');
}
})
.on('keypress.quickedit', 'input', function (event) {
if (event.keyCode === 13) {
return false;
}
});
// The in-place editor has loaded; change state to 'active'.
fieldModel.set('state', 'active');
});
},
/**
* Removes the form for this field, detaches behaviors and event handlers.
*/
removeForm: function () {
if (this.$formContainer === null) {
return;
}
delete this.formSaveAjax;
// Allow form widgets to detach properly.
Drupal.detachBehaviors(this.$formContainer.get(0), null, 'unload');
this.$formContainer
.off('change.quickedit', ':input')
.off('keypress.quickedit', 'input')
.remove();
this.$formContainer = null;
},
/**
* @inheritdoc
*/
save: function () {
var $formContainer = this.$formContainer;
var $submit = $formContainer.find('.quickedit-form-submit');
var editorModel = this.model;
var fieldModel = this.fieldModel;
function cleanUpAjax() {
Drupal.quickedit.util.form.unajaxifySaving(formSaveAjax);
formSaveAjax = null;
}
// Create an AJAX object for the form associated with the field.
var formSaveAjax = Drupal.quickedit.util.form.ajaxifySaving({
nocssjs: false,
other_view_modes: fieldModel.findOtherViewModes()
}, $submit);
// Successfully saved.
formSaveAjax.commands.quickeditFieldFormSaved = function (ajax, response, status) {
cleanUpAjax();
// First, transition the state to 'saved'.
fieldModel.set('state', 'saved');
// Second, set the 'htmlForOtherViewModes' attribute, so that when this
// field is rerendered, the change can be propagated to other instances
// of this field, which may be displayed in different view modes.
fieldModel.set('htmlForOtherViewModes', response.other_view_modes);
// Finally, set the 'html' attribute on the field model. This will cause
// the field to be rerendered.
_.defer(function () {
fieldModel.set('html', response.data);
});
};
// Unsuccessfully saved; validation errors.
formSaveAjax.commands.quickeditFieldFormValidationErrors = function (ajax, response, status) {
editorModel.set('validationErrors', response.data);
fieldModel.set('state', 'invalid');
};
// The quickeditFieldForm AJAX command is called upon attempting to save
// the form; Form API will mark which form items have errors, if any. This
// command is invoked only if validation errors exist and then it runs
// before editFieldFormValidationErrors().
formSaveAjax.commands.quickeditFieldForm = function (ajax, response, status) {
Drupal.AjaxCommands.prototype.insert(ajax, {
data: response.data,
selector: '#' + $formContainer.attr('id') + ' form'
});
};
// Click the form's submit button; the scoped AJAX commands above will
// handle the server's response.
$submit.trigger('click.quickedit');
},
/**
* @inheritdoc
*/
showValidationErrors: function () {
this.$formContainer
.find('.quickedit-form')
.addClass('quickedit-validation-error')
.find('form')
.prepend(this.model.get('validationErrors'));
}
});
})(jQuery, Drupal);
|
gpl-2.0
|
dmzx/Member-time-counter
|
language/fr/membertimecounter.php
|
1238
|
<?php
/**
*
* Member time counter extension for the phpBB Forum Software package.
* French translation by Taka5124 (http://webdvdbdhd.com) & Galixte (http://www.galixte.com)
*
* @copyright (c) 2015 dmzx <http://www.dmzx-web.net>
* @license GNU General Public License, version 2 (GPL-2.0)
*
*/
/**
* DO NOT CHANGE
*/
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
// DEVELOPERS PLEASE NOTE
//
// All language files should use UTF-8 as their encoding and the files must not contain a BOM.
//
// Placeholders can now contain order information, e.g. instead of
// 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows
// translators to re-order the output of data while ensuring it remains correct
//
// You do not need this where single placeholders are used, e.g. 'Message %d' is fine
// equally where a string contains only two placeholders which are used to wrap text
// in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine
//
// Some characters you may want to copy&paste:
// ’ « » “ ” …
//
$lang = array_merge($lang, array(
'MEMBER_FOR' => 'Membre depuis',
'YEARS' => 'an(s)',
'MONTHS' => 'mois',
'AND' => 'et',
));
|
gpl-2.0
|
mauriziopireddu/KittenCompilatori
|
src/absyn/Assert.java
|
2498
|
package absyn;
import java.io.FileWriter;
import bytecode.NEWSTRING;
import bytecode.VIRTUALCALL;
import bytecode.CONST;
import bytecode.RETURN;
import semantical.TypeChecker;
import translation.Block;
import types.ClassType;
import types.IntType;
import types.TypeList;
public class Assert extends Command {
private final Expression asserted;
public Assert(int pos, Expression asserted) {
super(pos);
this.asserted = asserted;
}
public Expression getAsserted() {
return asserted;
}
@Override
protected void toDotAux(FileWriter where) throws java.io.IOException {
linkToNode("asserted", asserted.toDot(where), where);
}
@Override
// effettua l'analisi semantica specifica a ciascun comando
protected TypeChecker typeCheckAux(TypeChecker checker) {
asserted.mustBeBoolean(checker);
boolean expected = checker.isTesting();
if (expected != true)
error("assert not defined in method test");
return checker;
}
@Override
public boolean checkForDeadcode() {
// TODO Auto-generated method stub
return false;
}
@Override
//con translate costruiamo un blocco per assert dato che il bytecode di kitten
//e un grafo di blocchi di codice contenente codice sequenziale
public Block translate(Block continuation) {
String out = makeFailureMessage();
//creo il blocco (non ha predecessori ne sucessori)
Block failed = new Block(new RETURN(IntType.INSTANCE));
failed = new CONST(-1).followedBy(failed); //aggiungiamo i vari elementi sopra al blocco failed
//virtualcall chiama il metodo output e parametri formali di tipo t risalendo nella catena delle superclassi
//il ricevitore e e i parametri attuali della chiamata si trovano nello stack al momento della chiamata
// vengono sostituiti alla fine con il valore di ritorno del metodo
failed = new VIRTUALCALL(ClassType.mkFromFileName("String.kit"),
ClassType.mkFromFileName("String.kit").methodLookup("output", TypeList.EMPTY)).followedBy(failed);
failed = new NEWSTRING(out).followedBy(failed);
//traduce l'espressione assumendo che sia di tipo boolean (garantito precedentemente da type-checking)
return asserted.translateForTesting(continuation, failed);
//prende continuation oppure il blocco failed che abbiamo costruito
}
private String makeFailureMessage() {
String pos = getTypeChecker().calculatePosition(getPos());
return "Assert fallita a: " + pos;
}
}
|
gpl-2.0
|
Siot/tigervnc
|
unix/xserver/hw/vnc/vncExtInit.cc
|
11362
|
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
* Copyright 2011-2015 Pierre Ossman for Cendio AB
*
* This 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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
#include <stdio.h>
#include <errno.h>
#include <rfb/Configuration.h>
#include <rfb/Logger_stdio.h>
#include <rfb/LogWriter.h>
#include <rfb/util.h>
#include <rfb/ServerCore.h>
#include <rdr/HexOutStream.h>
#include <rfb/LogWriter.h>
#include <rfb/Hostname.h>
#include <rfb/Region.h>
#include <network/TcpSocket.h>
#include "XserverDesktop.h"
#include "vncExtInit.h"
#include "vncHooks.h"
#include "vncBlockHandler.h"
#include "XorgGlue.h"
using namespace rfb;
static rfb::LogWriter vlog("vncext");
// We can't safely get this from Xorg
#define MAXSCREENS 16
static unsigned long vncExtGeneration = 0;
static bool initialised = false;
static XserverDesktop* desktop[MAXSCREENS] = { 0, };
void* vncFbptr[MAXSCREENS] = { 0, };
int vncFbstride[MAXSCREENS];
int vncInetdSock = -1;
rfb::StringParameter httpDir("httpd",
"Directory containing files to serve via HTTP",
"");
rfb::IntParameter httpPort("httpPort", "TCP port to listen for HTTP",0);
rfb::AliasParameter rfbwait("rfbwait", "Alias for ClientWaitTimeMillis",
&rfb::Server::clientWaitTimeMillis);
rfb::IntParameter rfbport("rfbport", "TCP port to listen for RFB protocol",0);
rfb::StringParameter desktopName("desktop", "Name of VNC desktop","x11");
rfb::BoolParameter localhostOnly("localhost",
"Only allow connections from localhost",
false);
rfb::StringParameter interface("interface",
"listen on the specified network address",
"all");
rfb::BoolParameter avoidShiftNumLock("AvoidShiftNumLock",
"Avoid fake Shift presses for keys affected by NumLock.",
true);
static PixelFormat vncGetPixelFormat(int scrIdx)
{
int depth, bpp;
int trueColour, bigEndian;
int redMask, greenMask, blueMask;
int redShift, greenShift, blueShift;
int redMax, greenMax, blueMax;
vncGetScreenFormat(scrIdx, &depth, &bpp, &trueColour, &bigEndian,
&redMask, &greenMask, &blueMask);
if (!trueColour) {
vlog.error("pseudocolour not supported");
abort();
}
redShift = ffs(redMask) - 1;
greenShift = ffs(greenMask) - 1;
blueShift = ffs(blueMask) - 1;
redMax = redMask >> redShift;
greenMax = greenMask >> greenShift;
blueMax = blueMask >> blueShift;
return PixelFormat(bpp, depth, bigEndian, trueColour,
redMax, greenMax, blueMax,
redShift, greenShift, blueShift);
}
void vncExtensionInit(void)
{
int ret;
if (vncExtGeneration == vncGetServerGeneration()) {
vlog.error("vncExtensionInit: called twice in same generation?");
return;
}
vncExtGeneration = vncGetServerGeneration();
if (vncGetScreenCount() > MAXSCREENS) {
vlog.error("vncExtensionInit: too many screens");
return;
}
if (sizeof(ShortRect) != sizeof(struct UpdateRect)) {
vlog.error("vncExtensionInit: Incompatible ShortRect size");
return;
}
ret = vncAddExtension();
if (ret == -1)
return;
vlog.info("VNC extension running!");
try {
if (!initialised) {
rfb::initStdIOLoggers();
initialised = true;
}
for (int scr = 0; scr < vncGetScreenCount(); scr++) {
if (!desktop[scr]) {
std::list<network::TcpListener*> listeners;
std::list<network::TcpListener*> httpListeners;
if (scr == 0 && vncInetdSock != -1) {
if (network::TcpSocket::isSocket(vncInetdSock) &&
!network::TcpSocket::isConnected(vncInetdSock))
{
listeners.push_back(new network::TcpListener(vncInetdSock));
vlog.info("inetd wait");
}
} else {
const char *addr = interface;
int port = rfbport;
if (port == 0) port = 5900 + atoi(vncGetDisplay());
port += 1000 * scr;
if (strcasecmp(addr, "all") == 0)
addr = 0;
if (localhostOnly)
network::createLocalTcpListeners(&listeners, port);
else
network::createTcpListeners(&listeners, addr, port);
vlog.info("Listening for VNC connections on %s interface(s), port %d",
localhostOnly ? "local" : (const char*)interface,
port);
CharArray httpDirStr(httpDir.getData());
if (httpDirStr.buf[0]) {
port = httpPort;
if (port == 0) port = 5800 + atoi(vncGetDisplay());
port += 1000 * scr;
if (localhostOnly)
network::createLocalTcpListeners(&httpListeners, port);
else
network::createTcpListeners(&httpListeners, addr, port);
vlog.info("Listening for HTTP connections on %s interface(s), port %d",
localhostOnly ? "local" : (const char*)interface,
port);
}
}
CharArray desktopNameStr(desktopName.getData());
PixelFormat pf = vncGetPixelFormat(scr);
desktop[scr] = new XserverDesktop(scr,
listeners,
httpListeners,
desktopNameStr.buf,
pf,
vncGetScreenWidth(scr),
vncGetScreenHeight(scr),
vncFbptr[scr],
vncFbstride[scr]);
vlog.info("created VNC server for screen %d", scr);
if (scr == 0 && vncInetdSock != -1 && listeners.empty()) {
network::Socket* sock = new network::TcpSocket(vncInetdSock);
desktop[scr]->addClient(sock, false);
vlog.info("added inetd sock");
}
}
vncHooksInit(scr);
}
} catch (rdr::Exception& e) {
vlog.error("vncExtInit: %s",e.str());
}
vncRegisterBlockHandlers();
}
int vncExtensionIsActive(int scrIdx)
{
return (desktop[scrIdx] != NULL);
}
void vncCallReadBlockHandlers(fd_set * fds, struct timeval ** timeout)
{
for (int scr = 0; scr < vncGetScreenCount(); scr++)
if (desktop[scr])
desktop[scr]->readBlockHandler(fds, timeout);
}
void vncCallReadWakeupHandlers(fd_set * fds, int nfds)
{
for (int scr = 0; scr < vncGetScreenCount(); scr++)
if (desktop[scr])
desktop[scr]->readWakeupHandler(fds, nfds);
}
void vncCallWriteBlockHandlers(fd_set * fds, struct timeval ** timeout)
{
for (int scr = 0; scr < vncGetScreenCount(); scr++)
if (desktop[scr])
desktop[scr]->writeBlockHandler(fds, timeout);
}
void vncCallWriteWakeupHandlers(fd_set * fds, int nfds)
{
for (int scr = 0; scr < vncGetScreenCount(); scr++)
if (desktop[scr])
desktop[scr]->writeWakeupHandler(fds, nfds);
}
int vncGetAvoidShiftNumLock(void)
{
return (bool)avoidShiftNumLock;
}
void vncUpdateDesktopName(void)
{
for (int scr = 0; scr < vncGetScreenCount(); scr++) {
if (desktop[scr] == NULL)
continue;
desktop[scr]->setDesktopName(desktopName);
}
}
void vncServerCutText(const char *text, size_t len)
{
for (int scr = 0; scr < vncGetScreenCount(); scr++) {
if (desktop[scr] == NULL)
continue;
desktop[scr]->serverCutText(text, len);
}
}
int vncConnectClient(const char *addr)
{
if (desktop[0] == NULL)
return -1;
if (strlen(addr) == 0) {
try {
desktop[0]->disconnectClients();
} catch (rdr::Exception& e) {
vlog.error("Disconnecting all clients: %s",e.str());
return -1;
}
return 0;
}
char *host;
int port;
getHostAndPort(addr, &host, &port, 5500);
try {
network::Socket* sock = new network::TcpSocket(host, port);
delete [] host;
desktop[0]->addClient(sock, true);
} catch (rdr::Exception& e) {
vlog.error("Reverse connection: %s",e.str());
return -1;
}
return 0;
}
void vncGetQueryConnect(uint32_t *opaqueId, const char**username,
const char **address, int *timeout)
{
for (int scr = 0; scr < vncGetScreenCount(); scr++) {
if (desktop[scr] == NULL)
continue;
desktop[scr]->getQueryConnect(opaqueId, username, address, timeout);
if (opaqueId != 0)
break;
}
}
void vncApproveConnection(uint32_t opaqueId, int approve)
{
for (int scr = 0; scr < vncGetScreenCount(); scr++) {
if (desktop[scr] == NULL)
continue;
desktop[scr]->approveConnection(opaqueId, approve,
"Connection rejected by local user");
}
}
void vncBell()
{
for (int scr = 0; scr < vncGetScreenCount(); scr++) {
if (desktop[scr] == NULL)
continue;
desktop[scr]->bell();
}
}
void vncAddChanged(int scrIdx, const struct UpdateRect *extents,
int nRects, const struct UpdateRect *rects)
{
Region reg;
reg.setExtentsAndOrderedRects((const ShortRect*)extents,
nRects, (const ShortRect*)rects);
desktop[scrIdx]->add_changed(reg);
}
void vncAddCopied(int scrIdx, const struct UpdateRect *extents,
int nRects, const struct UpdateRect *rects,
int dx, int dy)
{
Region reg;
reg.setExtentsAndOrderedRects((const ShortRect*)extents,
nRects, (const ShortRect*)rects);
desktop[scrIdx]->add_copied(reg, rfb::Point(dx, dy));
}
void vncSetCursor(int scrIdx, int width, int height, int hotX, int hotY,
const unsigned char *rgbaData)
{
desktop[scrIdx]->setCursor(width, height, hotX, hotY, rgbaData);
}
void vncPreScreenResize(int scrIdx)
{
// We need to prevent the RFB core from accessing the framebuffer
// for a while as there might be updates thrown our way inside
// the routines that change the screen (i.e. before we have a
// pointer to the new framebuffer).
desktop[scrIdx]->blockUpdates();
}
void vncPostScreenResize(int scrIdx, int success, int width, int height)
{
if (success) {
// Let the RFB core know of the new dimensions and framebuffer
desktop[scrIdx]->setFramebuffer(width, height,
vncFbptr[scrIdx], vncFbstride[scrIdx]);
}
desktop[scrIdx]->unblockUpdates();
if (success) {
// Mark entire screen as changed
desktop[scrIdx]->add_changed(Region(Rect(0, 0, width, height)));
}
}
void vncRefreshScreenLayout(int scrIdx)
{
desktop[scrIdx]->refreshScreenLayout();
}
|
gpl-2.0
|
yakimanjusuki-git1/git1_test
|
wp-config.php
|
4279
|
<?php
/**
* WordPress の基本設定
*
* このファイルは、MySQL、テーブル接頭辞、秘密鍵、言語、ABSPATH の設定を含みます。
* より詳しい情報は {@link http://wpdocs.sourceforge.jp/wp-config.php_%E3%81%AE%E7%B7%A8%E9%9B%86
* wp-config.php の編集} を参照してください。MySQL の設定情報はホスティング先より入手できます。
*
* このファイルはインストール時に wp-config.php 作成ウィザードが利用します。
* ウィザードを介さず、このファイルを "wp-config.php" という名前でコピーして直接編集し値を
* 入力してもかまいません。
*
* @package WordPress
*/
// 注意:
// Windows の "メモ帳" でこのファイルを編集しないでください !
// 問題なく使えるテキストエディタ
// (http://wpdocs.sourceforge.jp/Codex:%E8%AB%87%E8%A9%B1%E5%AE%A4 参照)
// を使用し、必ず UTF-8 の BOM なし (UTF-8N) で保存してください。
// ** MySQL 設定 - この情報はホスティング先から入手してください。 ** //
/** WordPress のためのデータベース名 */
define('DB_NAME', 'wp');
/** MySQL データベースのユーザー名 */
define('DB_USER', 'wp');
/** MySQL データベースのパスワード */
define('DB_PASSWORD', 'wp');
/** MySQL のホスト名 */
define('DB_HOST', 'localhost');
/** データベースのテーブルを作成する際のデータベースの文字セット */
define('DB_CHARSET', 'utf8');
/** データベースの照合順序 (ほとんどの場合変更する必要はありません) */
define('DB_COLLATE', '');
/**#@+
* 認証用ユニークキー
*
* それぞれを異なるユニーク (一意) な文字列に変更してください。
* {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org の秘密鍵サービス} で自動生成することもできます。
* 後でいつでも変更して、既存のすべての cookie を無効にできます。これにより、すべてのユーザーを強制的に再ログインさせることになります。
*
* @since 2.6.0
*/
define('AUTH_KEY', 'put your unique phrase here');
define('SECURE_AUTH_KEY', 'put your unique phrase here');
define('LOGGED_IN_KEY', 'put your unique phrase here');
define('NONCE_KEY', 'put your unique phrase here');
define('AUTH_SALT', 'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT', 'put your unique phrase here');
define('NONCE_SALT', 'put your unique phrase here');
/**#@-*/
/**
* WordPress データベーステーブルの接頭辞
*
* それぞれにユニーク (一意) な接頭辞を与えることで一つのデータベースに複数の WordPress を
* インストールすることができます。半角英数字と下線のみを使用してください。
*/
$table_prefix = 'wp_';
/**
* ローカル言語 - このパッケージでは初期値として 'ja' (日本語 UTF-8) が設定されています。
*
* WordPress のローカル言語を設定します。設定した言語に対応する MO ファイルが
* wp-content/languages にインストールされている必要があります。たとえば de_DE.mo を
* wp-content/languages にインストールし WPLANG を 'de_DE' に設定すると、ドイツ語がサポートされます。
*/
define('WPLANG', 'ja');
/**
* 開発者へ: WordPress デバッグモード
*
* この値を true にすると、開発中に注意 (notice) を表示します。
* テーマおよびプラグインの開発者には、その開発環境においてこの WP_DEBUG を使用することを強く推奨します。
*/
// define('WP_DEBUG', false);
define('WP_DEBUG', true);
/* 編集が必要なのはここまでです ! WordPress でブログをお楽しみください。 */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
define('FS_METHOD', 'direct');
|
gpl-2.0
|
KanoComputing/kano-repository-manager
|
lib/dr/build_environments.rb
|
5056
|
# Copyright (C) 2014-2019 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
module Dr
module BuildEnvironments
@@build_environments = {
:kano => {
:name =>"Kano OS (Wheezy)",
:arches => ["armhf"],
:repos => {
:raspbian => {
:url => "http://www.mirrorservice.org/sites/archive.raspbian.org/raspbian/",
:key => "http://www.mirrorservice.org/sites/archive.raspbian.org/raspbian.public.key",
:src => true,
:codename => "wheezy",
:components => "main contrib non-free rpi"
},
:raspi_foundation => {
:url => "http://dev.kano.me/mirrors/raspberrypi/",
:key => "http://dev.kano.me/mirrors/raspberrypi/raspberrypi.gpg.key",
:src => false,
:codename => "wheezy",
:components => "main"
},
:kano => {
:url => "http://dev.kano.me/archive/",
:key => "http://dev.kano.me/archive/repo.gpg.key",
:src => false,
:codename => "devel",
:components => "main"
}
},
:base_repo => :raspbian,
:packages => []
},
:kano_stretch => {
:name =>"Kano OS (Stretch)",
:arches => ["armhf"],
:repos => {
:stretch_bootstrap => {
# This is used to debootstrap the system which suffers from the
# problem that S3 doesn't like serving URLs with `+` in the path
# so use the proxied version of:
# staging.stretch.raspbian.repo.os.kano.me
:url => "http://build.os.kano.me/",
:key => "http://build.os.kano.me/raspbian.public.key",
:src => true,
:codename => "stretch",
:components => "main contrib non-free rpi",
:build_only => true
},
:raspbian_stretch => {
:url => "http://staging.stretch.raspbian.repo.os.kano.me/",
:key => "http://staging.stretch.raspbian.repo.os.kano.me/raspbian.public.key",
:src => true,
:codename => "stretch",
:components => "main contrib non-free rpi"
},
:raspi_foundation_stretch => {
:url => "http://dev.kano.me/raspberrypi-stretch/",
:key => "http://dev.kano.me/raspberrypi-stretch/raspberrypi.gpg.key",
:src => false,
:codename => "stretch",
:components => "main"
},
:kano_stretch => {
:url => "http://dev.kano.me/archive-stretch/",
:key => "http://dev.kano.me/archive-stretch/repo.gpg.key",
:src => false,
:codename => "devel",
:components => "main"
}
},
:base_repo => :stretch_bootstrap,
:packages => []
},
:kano_jessie => {
:name =>"Kano OS (Jessie)",
:arches => ["armhf"],
:repos => {
:raspbian_jessie => {
:url => "http://staging.jessie.raspbian.repo.os.kano.me/",
:key => "http://staging.jessie.raspbian.repo.os.kano.me/raspbian.public.key",
:src => true,
:codename => "jessie",
:components => "main contrib non-free rpi"
},
:raspi_foundation_jessie => {
:url => "http://dev.kano.me/raspberrypi-jessie/",
:key => "http://dev.kano.me/raspberrypi-jessie/raspberrypi.gpg.key",
:src => false,
:codename => "jessie",
:components => "main"
},
:kano_jessie => {
:url => "http://dev.kano.me/archive-jessie/",
:key => "http://dev.kano.me/archive-jessie/repo.gpg.key",
:src => false,
:codename => "devel",
:components => "main"
}
},
:base_repo => :raspbian_jessie,
:packages => []
},
:wheezy => {
:name => "Debian Wheezy",
:arches => ["x86_64"],
:repos => {
:wheezy => {
:url => "http://ftp.uk.debian.org/debian/",
:key => "https://ftp-master.debian.org/keys/archive-key-7.0.asc",
:src => true,
:codename => "wheezy",
:components => "main contrib non-free"
}
},
:base_repo => :wheezy,
:packages => []
},
:jessie => {
:name => "Debian Jessie",
:arches => ["x86_64"],
:repos => {
:wheezy => {
:url => "http://ftp.uk.debian.org/debian/",
:key => "https://ftp-master.debian.org/keys/archive-key-8.asc",
:src => true,
:codename => "jessie",
:components => "main contrib non-free"
}
},
:base_repo => :wheezy,
:packages => []
}
}
def build_environments
@@build_environments
end
def add_build_environment(name, benv)
@@build_environments[name.to_sym] = benv
end
end
end
|
gpl-2.0
|
mkandra/GridImageSearch
|
src/com/mbkandra16/apps/gridimagesearch/models/ImageResult.java
|
1129
|
package com.mbkandra16.apps.gridimagesearch.models;
import java.io.Serializable;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ImageResult implements Serializable{
/**
*
*/
private static final long serialVersionUID = -8850560755118316229L;
public String fullUrl;
public String thumbUrl;
public String title;
// new ImageResult (..raw item json..)
public ImageResult(JSONObject json) {
try {
this.fullUrl = json.getString("url");
this.thumbUrl = json.getString("tbUrl");
this.title = json.getString("title");
} catch (JSONException e) {
e.printStackTrace();
}
}
// Take an array of json images and return arrayList of image results
// ImageResult.fromJSONArray([...,...])
public static ArrayList<ImageResult> fromJSONArray(JSONArray array) {
ArrayList<ImageResult> results = new ArrayList<ImageResult>();
for (int i = 0; i < array.length(); i++) {
try {
results.add(new ImageResult(array.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return results;
}
}
|
gpl-2.0
|
giucam/ssu
|
ssud/main.cpp
|
785
|
/**
* @file main.cpp
* @copyright 2013 Jolla Ltd.
* @author Bernd Wachter <bwachter@lart.info>
* @date 2013
*/
#include <QCoreApplication>
#include <QTranslator>
#include <QLocale>
#include <QLibraryInfo>
#include "libssunetworkproxy/ssunetworkproxy.h"
#include "ssud.h"
int main(int argc, char** argv){
QCoreApplication app(argc, argv);
QCoreApplication::setOrganizationName("Jolla");
QCoreApplication::setOrganizationDomain("http://www.jollamobile.com");
QCoreApplication::setApplicationName("ssud");
QTranslator qtTranslator;
qtTranslator.load("qt_" + QLocale::system().name(),
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
app.installTranslator(&qtTranslator);
set_application_proxy_factory();
Ssud ssud;
app.exec();
}
|
gpl-2.0
|
ibennetch/phpmyadmin
|
test/selenium/XssTest.php
|
1013
|
<?php
/**
* Selenium TestCase for SQL query window related tests
*/
declare(strict_types=1);
namespace PhpMyAdmin\Tests\Selenium;
/**
* XssTest class
*
* @group selenium
*/
class XssTest extends TestBase
{
/**
* Create a test database for this test class
*
* @var bool
*/
protected static $createDatabase = false;
protected function setUp(): void
{
parent::setUp();
$this->login();
}
/**
* Tests the SQL query tab with a null query
*
* @group large
*/
public function testQueryTabWithNullValue(): void
{
if ($this->isSafari()) {
$this->markTestSkipped('Alerts not supported on Safari browser.');
}
$this->waitForElement('partialLinkText', 'SQL')->click();
$this->waitAjax();
$this->waitForElement('id', 'querybox');
$this->byId('button_submit_query')->click();
$this->assertEquals('Missing value in the form!', $this->alertText());
}
}
|
gpl-2.0
|
FredQiao/wxmseo
|
wp-content/themes/tangstyle/sidebar-single.php
|
1726
|
<div id="sidebar">
<div id="search">
<form id="searchform" method="get" action="<?php bloginfo('home'); ?>">
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" size="30" x-webkit-speech />
<button type="submit" id="searchsubmit"><i class="iconfont">ő</i></button>
</form>
</div>
<div class="sidebar">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('内容页侧栏') ) : ?>
<div class="widget">
<h3>分类目录</h3>
<ul>
<?php wp_list_categories('depth=1&title_li=0&orderby=name&show_count=1'); ?>
</ul>
</div>
<div id="related_post" class="widget">
<h3><?php $category = get_the_category(); echo $category[0]->cat_name; ?> 下的最新文章</h3>
<?php
if(is_single()){
$cats = get_the_category();
}
foreach($cats as $cat){
$posts = get_posts(array(
'category' => $cat->cat_ID,
'exclude' => $post->ID,
'showposts' => 10,
));
echo '<ul>';
foreach($posts as $post){
echo '<li><a href="'.get_permalink($post->ID).'">'.$post->post_title.'</a></li>';
}
echo '</ul>';
}
?>
</div>
<div class="widget">
<h3>随机文章</h3>
<ul>
<?php $rand_posts = get_posts('numberposts=10&orderby=rand'); foreach( $rand_posts as $post ) : ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php echo mb_strimwidth(get_the_title(), 0, 42, '...'); ?></a></li>
<?php endforeach; ?>
</ul>
</div>
<div class="widget">
<h3>标签云</h3>
<div class="tagcloud"><?php wp_tag_cloud();?></div>
</div>
<?php endif; ?>
</div>
</div>
|
gpl-2.0
|
gunnarku/mysql-8.0
|
plugin/semisync/semisync_master_ack_receiver.cc
|
7752
|
/* Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "my_config.h"
#include <errno.h>
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_psi_config.h"
#include "mysql/psi/mysql_stage.h"
#include "semisync_master.h"
#include "semisync_master_ack_receiver.h"
#include "semisync_master_socket_listener.h"
extern ReplSemiSyncMaster repl_semisync;
#ifdef HAVE_PSI_INTERFACE
extern PSI_stage_info stage_waiting_for_semi_sync_ack_from_slave;
extern PSI_stage_info stage_waiting_for_semi_sync_slave;
extern PSI_stage_info stage_reading_semi_sync_ack;
extern PSI_mutex_key key_ss_mutex_Ack_receiver_mutex;
extern PSI_cond_key key_ss_cond_Ack_receiver_cond;
extern PSI_thread_key key_ss_thread_Ack_receiver_thread;
#endif
/* Callback function of ack receive thread */
extern "C" {
static void *ack_receive_handler(void *arg)
{
my_thread_init();
reinterpret_cast<Ack_receiver *>(arg)->run();
my_thread_end();
my_thread_exit(0);
return NULL;
}
} // extern "C"
Ack_receiver::Ack_receiver()
{
const char *kWho = "Ack_receiver::Ack_receiver";
function_enter(kWho);
m_status= ST_DOWN;
mysql_mutex_init(key_ss_mutex_Ack_receiver_mutex, &m_mutex,
MY_MUTEX_INIT_FAST);
mysql_cond_init(key_ss_cond_Ack_receiver_cond, &m_cond);
function_exit(kWho);
}
Ack_receiver::~Ack_receiver()
{
const char *kWho = "Ack_receiver::~Ack_receiver";
function_enter(kWho);
stop();
mysql_mutex_destroy(&m_mutex);
mysql_cond_destroy(&m_cond);
function_exit(kWho);
}
bool Ack_receiver::start()
{
const char *kWho = "Ack_receiver::start";
function_enter(kWho);
if(m_status == ST_DOWN)
{
my_thread_attr_t attr;
m_status= ST_UP;
if (DBUG_EVALUATE_IF("rpl_semisync_simulate_create_thread_failure", 1, 0) ||
my_thread_attr_init(&attr) != 0 ||
my_thread_attr_setdetachstate(&attr, MY_THREAD_CREATE_JOINABLE) != 0 ||
#ifndef _WIN32
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) != 0 ||
#endif
mysql_thread_create(key_ss_thread_Ack_receiver_thread, &m_pid,
&attr, ack_receive_handler, this))
{
sql_print_error("Failed to start semi-sync ACK receiver thread, "
" could not create thread(errno:%d)", errno);
m_status= ST_DOWN;
return function_exit(kWho, true);
}
(void) my_thread_attr_destroy(&attr);
}
return function_exit(kWho, false);
}
void Ack_receiver::stop()
{
const char *kWho = "Ack_receiver::stop";
function_enter(kWho);
int ret;
if (m_status == ST_UP)
{
mysql_mutex_lock(&m_mutex);
m_status= ST_STOPPING;
mysql_cond_broadcast(&m_cond);
while (m_status == ST_STOPPING)
mysql_cond_wait(&m_cond, &m_mutex);
mysql_mutex_unlock(&m_mutex);
/*
When arriving here, the ack thread already exists. Join failure has no
side effect aganst semisync. So we don't return an error.
*/
ret= my_thread_join(&m_pid, NULL);
if (DBUG_EVALUATE_IF("rpl_semisync_simulate_thread_join_failure", -1, ret))
sql_print_error("Failed to stop ack receiver thread on my_thread_join, "
"errno(%d)", errno);
}
function_exit(kWho);
}
bool Ack_receiver::add_slave(THD *thd)
{
Slave slave;
const char *kWho = "Ack_receiver::add_slave";
function_enter(kWho);
slave.thd= thd;
slave.vio= thd->get_protocol_classic()->get_vio();
slave.vio->mysql_socket.m_psi= NULL;
slave.vio->read_timeout= 1;
/* push_back() may throw an exception */
try
{
mysql_mutex_lock(&m_mutex);
DBUG_EXECUTE_IF("rpl_semisync_simulate_add_slave_failure", throw 1;);
m_slaves.push_back(slave);
m_slaves_changed= true;
mysql_cond_broadcast(&m_cond);
mysql_mutex_unlock(&m_mutex);
}
catch (...)
{
mysql_mutex_unlock(&m_mutex);
return function_exit(kWho, true);
}
return function_exit(kWho, false);
}
void Ack_receiver::remove_slave(THD *thd)
{
const char *kWho = "Ack_receiver::remove_slave";
function_enter(kWho);
mysql_mutex_lock(&m_mutex);
Slave_vector_it it;
for (it= m_slaves.begin(); it != m_slaves.end(); it++)
{
if (it->thd == thd)
{
m_slaves.erase(it);
m_slaves_changed= true;
break;
}
}
mysql_mutex_unlock(&m_mutex);
function_exit(kWho);
}
inline void Ack_receiver::set_stage_info(const PSI_stage_info &stage)
{
#ifdef HAVE_PSI_STAGE_INTERFACE
MYSQL_SET_STAGE(stage.m_key, __FILE__, __LINE__);
#endif /* HAVE_PSI_STAGE_INTERFACE */
}
inline void Ack_receiver::wait_for_slave_connection()
{
set_stage_info(stage_waiting_for_semi_sync_slave);
mysql_cond_wait(&m_cond, &m_mutex);
}
/* Auxilary function to initialize a NET object with given net buffer. */
static void init_net(NET *net, unsigned char *buff, unsigned int buff_len)
{
memset(net, 0, sizeof(NET));
net->max_packet= buff_len;
net->buff= buff;
net->buff_end= buff + buff_len;
net->read_pos= net->buff;
}
void Ack_receiver::run()
{
NET net;
unsigned char net_buff[REPLY_MESSAGE_MAX_LENGTH];
uint i;
#ifdef HAVE_POLL
Poll_socket_listener listener(m_slaves);
#else
Select_socket_listener listener(m_slaves);
#endif //HAVE_POLL
sql_print_information("Starting ack receiver thread");
init_net(&net, net_buff, REPLY_MESSAGE_MAX_LENGTH);
mysql_mutex_lock(&m_mutex);
m_slaves_changed= true;
mysql_mutex_unlock(&m_mutex);
while (1)
{
Slave_vector_it it;
int ret;
mysql_mutex_lock(&m_mutex);
if (unlikely(m_status == ST_STOPPING))
goto end;
set_stage_info(stage_waiting_for_semi_sync_ack_from_slave);
if (unlikely(m_slaves_changed))
{
if (unlikely(m_slaves.empty()))
{
wait_for_slave_connection();
mysql_mutex_unlock(&m_mutex);
continue;
}
if (!listener.init_slave_sockets())
goto end;
m_slaves_changed= false;
}
ret= listener.listen_on_sockets();
if (ret <= 0)
{
mysql_mutex_unlock(&m_mutex);
ret= DBUG_EVALUATE_IF("rpl_semisync_simulate_select_error", -1, ret);
if (ret == -1 && errno != EINTR)
sql_print_information("Failed to wait on semi-sync dump sockets, "
"error: errno=%d", socket_errno);
/* Sleep 1us, so other threads can catch the m_mutex easily. */
my_sleep(1);
continue;
}
set_stage_info(stage_reading_semi_sync_ack);
i= 0;
while (i < m_slaves.size())
{
if (listener.is_socket_active(i))
{
ulong len;
net_clear(&net, 0);
net.vio= m_slaves[i].vio;
len= my_net_read(&net);
if (likely(len != packet_error))
repl_semisync.reportReplyPacket(m_slaves[i].server_id(),
net.read_pos, len);
else if (net.last_errno == ER_NET_READ_ERROR)
listener.clear_socket_info(i);
}
i++;
}
mysql_mutex_unlock(&m_mutex);
}
end:
sql_print_information("Stopping ack receiver thread");
m_status= ST_DOWN;
mysql_cond_broadcast(&m_cond);
mysql_mutex_unlock(&m_mutex);
}
|
gpl-2.0
|
wbread/Elxis-2009.3_aphrodite_rev2681
|
administrator/tools/empty_temporary/language/russian.php
|
1437
|
<?php
/**
* @ Version: 2008.0
* @ Copyright: Copyright (C) 2006-2008 Elxis.org. All rights reserved.
* @ Package: Elxis
* @ Subpackage: Tools
* @ Author: Elxis Team
* @ Translator: Coursar
* @ Translator URL: http://www.elxis.ru
* # Translator E-mail: info@elxis.ru
* @ Description: Russian language for empty temporary tool
* @ License: http://www.gnu.org/copyleft/gpl.html GNU/GPL
* Elxis CMS is a Free Software
*
* ---- THIS FILE MUST BE ENCODED AS UTF-8! ----
*
*/
defined( '_VALID_MOS' ) or die( 'Доступ запрещён.' );
define('_TEMPTEMP_FOUND', 'Найдено');
define('_TEMPTEMP_DIRS', 'каталогов');
define('_TEMPTEMP_AND', 'и');
define('_TEMPTEMP_FILES', 'файлов');
define('_TEMPTEMP_NFOUND', 'Не найдено каталогов и файлов');
define('_TEMPTEMP_FORDEL', 'для удаления');
define('_TEMPTEMP_AWERRORS', 'Операция завершена с ошибками!');
define('_TEMPTEMP_ERRORLST', 'Список ошибок');
define('_TEMPTEMP_ACOMPSUCC', 'Операция успешно завершена!');
define('_TEMPTEMP_CRITERR', 'Произошла критическая ошибка!');
define('_TEMPTEMP_ERRDESC', 'Каталог /tmpr должен быть доступен для записи или должен быть включен FTP для выполнения данной операции.');
define('_TEMPTEMP_REPORT', 'Отчёт');
?>
|
gpl-2.0
|
nerdfiles/brooklynmeatballcompany_com
|
wp-content/themes/bmc/doc/source/conf.py
|
7175
|
# -*- coding: utf-8 -*-
#
# Brooklyn Meatball Company Website documentation build configuration file, created by
# sphinx-quickstart on Tue Nov 6 23:02:35 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Brooklyn Meatball Company Website'
copyright = u'2012, Aharon Alexander'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.0.1'
# The full version, including alpha/beta/rc tags.
release = '0.0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'BrooklynMeatballCompanyWebsitedoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'BrooklynMeatballCompanyWebsite.tex', u'Brooklyn Meatball Company Website Documentation',
u'Aharon Alexander', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'brooklynmeatballcompanywebsite', u'Brooklyn Meatball Company Website Documentation',
[u'Aharon Alexander'], 1)
]
|
gpl-2.0
|
kenhys/tokyodebian-monthly-report
|
utils/gae/enquete.py
|
13582
|
# Enquete page editing and submitting.
# coding=utf-8
from google.appengine.api import users
import StringIO
import csv
import schema
import webapp_generic
import throttled_mail_sender
class EnqueteAdminEdit(webapp_generic.WebAppGenericProcessor):
"""Admin edits the enquete questionnaire."""
def get(self):
eventid = self.request.get('eventid')
user = users.get_current_user()
event = self.event_cache.get_cached(eventid)
if event == None:
self.http_error_message('Event id %s not found' % (eventid))
return
if not self.check_auth_owner(event):
self.http_error_message('Not your event')
return
enquete = self.enquete_cache.get_uncached(eventid)
if enquete == None:
enquete = schema.EventEnquete()
template_values = {
'eventid': event.eventid,
'event_title': event.title,
'overall_message': enquete.overall_message,
'question_text': '\n'.join(enquete.question_text),
}
self.template_render_output(template_values, 'EnqueteAdminEdit.html')
class EnqueteAdminEditDone(webapp_generic.WebAppGenericProcessor):
"""Admin submits edits to the enquete questionnaire."""
def post(self):
eventid = self.request.get('eventid')
user = users.get_current_user()
event = self.event_cache.get_cached(eventid)
if event == None:
self.http_error_message('Event id %s not found' % (eventid))
return
if not self.check_auth_owner(event):
self.http_error_message('Not your event')
return
enquete = self.enquete_cache.get_uncached(eventid)
if enquete == None:
enquete = schema.EventEnquete()
enquete.eventid = eventid
enquete.overall_message = self.request.get('overall_message')
enquete.question_text = self.request.get('question_text').splitlines()
enquete.put()
self.enquete_cache.invalidate_cache(eventid)
template_values = {
'eventid': eventid,
}
self.template_render_output(template_values, 'Thanks.html')
class EnqueteAdminSendMail(webapp_generic.WebAppGenericProcessor):
"""Send mail to all participants by request of the administrator.
This code will queue the mail through GAE taskqueue."""
def get(self):
eventid = self.request.get('eventid')
user = users.get_current_user()
event = self.event_cache.get_cached(eventid)
if event == None:
self.http_error_message('Event id %s not found' % (eventid))
return
if not self.check_auth_owner(event):
self.http_error_message('Not your event')
return
enquete = self.enquete_cache.get_cached(eventid)
if enquete == None:
self.http_error_message('Enquete for event id %s not found' %
(eventid))
return
attendances, num_attend, num_enkai_attend = self.load_users_with_eventid(eventid)
self.response.headers['Content-type'] = 'text/plain; charset=utf-8'
for attendance in attendances:
mail_template = {
'eventid': eventid,
'event': event,
'user_realname': attendance.user_realname,
'admin_email': user.email()
}
mail_message = self.template_render(
mail_template, 'EnqueteAdminSendMail.txt')
mail_title = "[Debian登録システム] イベント %s のアンケートの依頼" % event.title.encode('utf-8')
throttled_mail_sender.send_mail(
eventid,
attendance.user.email(),
mail_title,
mail_message)
# show page content
self.response.out.write(mail_message)
class EnqueteRespond(webapp_generic.WebAppGenericProcessor):
"""Page for user to enter form for enquete."""
# TODO: should I allow for editing ?
def get(self):
eventid = self.request.get('eventid')
user = users.get_current_user()
attendance = self.load_attendance_with_eventid_and_user(eventid, user)
if attendance == None:
self.http_error_message('User not registered in event %s' %
(eventid))
return
event = self.event_cache.get_cached(eventid)
if event == None:
self.http_error_message('Event id %s not found' % (eventid))
return
enquete = self.enquete_cache.get_cached(eventid)
if enquete == None:
self.http_error_message('Enquete for event id %s not found' %
(eventid))
return
question_text_array = []
for sequence, question_item in enumerate(enquete.question_text):
question_text_array.append({
'name': 'question' + str(sequence),
'question_text': question_item,
})
template_values = {
'eventid': eventid,
'event': event,
'overall_message': enquete.overall_message,
'question_text_array': question_text_array,
}
self.template_render_output(template_values, 'EnqueteRespond.html')
class EnqueteRespondDone(webapp_generic.WebAppGenericProcessor):
"""User has responded to enquete and sends the result. We will
store the resulting data to database."""
def post(self):
eventid = self.request.get('eventid')
user = users.get_current_user()
event = self.event_cache.get_cached(eventid)
if event == None:
self.http_error_message('Event id %s not found' % (eventid))
return
attendance = self.load_attendance_with_eventid_and_user(eventid, user)
if attendance == None:
self.http_error_message('User not registered in event %s' %
(eventid))
return
enquete = self.enquete_cache.get_cached(eventid)
if enquete == None:
self.http_error_message('Enquete for event id %s not found' %
(eventid))
return
enquete_response = schema.EventEnqueteResponse()
enquete_response.eventid = eventid
enquete_response.user = user
enquete_response.overall_comment = self.request.get('overall_comment')
for sequence, question_item in enumerate(enquete.question_text):
enquete_response.question_response.append(long(self.request.get('question' + str(sequence))))
enquete_response.put()
self.enquete_response_cache.invalidate_cache(eventid)
template_values = {
'eventid': eventid,
}
self.template_render_output(template_values, 'Thanks.html')
# send mail backup of the enquete.
question_text_array = []
for question_text, question_response in zip(enquete.question_text, enquete_response.question_response):
question_text_array.append({
'question_text': question_text,
'value': question_response,
})
mail_template = {
'eventid': eventid,
'user_realname': attendance.user_realname,
'question_text_array': question_text_array,
'overall_comment': enquete_response.overall_comment,
}
mail_message = self.template_render(
mail_template, 'EnqueteRespondDone.txt')
mail_title = "[Debian登録システム] イベント %s のアンケート結果" % event.title.encode('utf-8')
throttled_mail_sender.send_mail(
eventid,
user.email(),
mail_title,
mail_message)
def convert_score_to_string(value):
"""Convert score to string for processing with R. 0 is converted to NA."""
if value == 0:
return 'NA'
return str(value)
class EnqueteAdminShowEnqueteResult(webapp_generic.WebAppGenericProcessor):
"""Admin lists enquete results summary."""
def get(self):
eventid = self.request.get('eventid')
event = self.event_cache.get_cached(eventid)
if event == None:
self.http_error_message('Event id %s not found' % (eventid))
return
if not self.check_auth_owner(event):
self.http_error_message('Not your event')
return
enquete = self.enquete_cache.get_cached(eventid)
if enquete == None:
self.http_error_message('Enquete for event id %s not found' %
(eventid))
return
enquete_responses = self.enquete_response_cache.get_cached(eventid)
if enquete_responses == None:
self.http_error_message('Event id %s has not enquete response' % (eventid))
return
# Output csv buffer for doing output in csv format.
string_io = StringIO.StringIO()
csv_writer = csv.writer(string_io)
csv_writer.writerow([x.encode('utf-8') for x in enquete.question_text] +
['自由記入'])
for enquete_response in enquete_responses:
csv_writer.writerow(
[convert_score_to_string(x)
for x in enquete_response.question_response] +
[enquete_response.overall_comment.encode('utf-8')]
)
self.response.headers['Content-type'] = 'text/csv; charset=utf-8'
self.response.headers['Content-Disposition'] = 'attachment; filename=enquete.csv'
self.response.out.write(string_io.getvalue())
class EnqueteAdminShowAllEnqueteResults(webapp_generic.WebAppGenericProcessor):
"""Admin lists all enquete results."""
def conditional_get_enquete_map(self, enquete_map_of_user_key, key):
"""Get the key from enquete map with optional mapping of 0 to NA."""
return convert_score_to_string(enquete_map_of_user_key.get(key, 'NA'))
def generate_question_key(self, event, question_text, eventid):
"""Generate a key string used for question.
The string should be reasonably unique and also readable for
later analysis with R.
Returns utf-8 string."""
return (
event.title + '-' + question_text + '-' + eventid[:4]
).encode('utf-8')
def get(self):
"""List all enquete results in a big matrix."""
# Output csv buffer for doing output in csv format.
string_io = StringIO.StringIO()
csv_writer = csv.writer(string_io)
user = users.get_current_user()
events = self.load_event_with_owners(user)
# dict contains user -> event -> score.
enquete_map = {}
# questions dict which is eventid + question -> True.
list_of_questions = {}
for event in events:
eventid = event.eventid
# load event information for the title. If an event didn't
# exist, that's weird, but allow for an error.
event = self.event_cache.get_cached(eventid)
if event == None:
self.http_error_message('Event id %s not found' % (eventid))
continue
enquete = self.enquete_cache.get_cached(eventid)
if enquete == None:
# There wasn't an enquete for this eventid, which is a
# reasonable error condition before enquete is
# created.
continue
enquete_responses = self.enquete_response_cache.get_cached(eventid)
if enquete_responses == None:
# It's also possible that there is no enquete response
# for an enquete.
continue
# We now have a list of enquete responses and matching events.
for i in range(len(enquete.question_text)):
# a key to use for the map. Use the first 4 letters of
# the hash and question name to make it reasonably
# unique.
question_key = self.generate_question_key(event,
enquete.question_text[i],
eventid)
list_of_questions[question_key] = True
for enquete_response in enquete_responses:
if len(enquete_response.question_response) < i:
# check for data corruption case where enquete
# was updated after the respose was made
continue
enquete_map.setdefault(
enquete_response.user.email(),
{})[question_key] = (
enquete_response.question_response[i])
self.response.headers['Content-type'] = 'text/csv; charset=utf-8'
self.response.headers['Content-Disposition'] = 'attachment; filename=enquete.csv'
sorted_list_of_questions = sorted(list_of_questions.keys())
csv_writer.writerow(sorted_list_of_questions)
for user_email in enquete_map.iterkeys():
csv_writer.writerow(
[self.conditional_get_enquete_map(
enquete_map[user_email], x)
for x in sorted_list_of_questions])
self.response.out.write(string_io.getvalue())
|
gpl-2.0
|
Spawck/HarkenScythe2
|
src/main/java/com/spawck/hs2/enchantment/EnchantmentSoulsteal.java
|
1109
|
/**
* This class was created by <spawck> as part of the Harken Scythe 2
* mod for Minecraft.
*
* Harken Scythe 2 is open-source and distributed under the
* GNU GPL v2 License.
* (https://www.gnu.org/licenses/gpl-2.0.html)
*
* Harken Scythe 2 is based on the original Harken Scythe mod created
* by Jade_Knightblazer:
*
* Harken Scythe (c) Jade_Knightblazer 2012-2013
* (http://bit.ly/18EyAZo)
*
* File created @[Mar 5, 2015, 10:42:28 AM]
*/
package com.spawck.hs2.enchantment;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnumEnchantmentType;
import com.spawck.hs2.reference.Names;
/**
* @author spawck
* Email: spawck@autistici.org
*
*/
public class EnchantmentSoulsteal extends Enchantment
{
public EnchantmentSoulsteal(int effectId)
{
super(effectId, 1, EnumEnchantmentType.weapon);
this.setName(Names.Enchantments.SOULSTEAL);
}
@Override
public int getMinEnchantability(int level)
{
return 100;
}
@Override
public int getMaxEnchantability(int level)
{
return 100;
}
@Override
public int getMaxLevel()
{
return 3;
}
}
|
gpl-2.0
|
sirvaliance/netlib
|
src/main/java/org/silvertunnel/netlib/layer/tor/util/TorNoAnswerException.java
|
1273
|
/**
* OnionCoffee - Anonymous Communication through TOR Network
* Copyright (C) 2005-2007 RWTH Aachen University, Informatik IV
*
* 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
*/
package org.silvertunnel.netlib.layer.tor.util;
/**
* this exception is used to handle timeout-related problems.
*
* @author Michael Koellejan
*/
public class TorNoAnswerException extends TorException {
private static final long serialVersionUID = 1L;
//private int waitedFor = 0;
public TorNoAnswerException() {
super();
}
public TorNoAnswerException(String s, int waitedFor) {
super(s);
//this.waitedFor = waitedFor;
}
}
|
gpl-2.0
|
AlexDAlexeev/redmine_backlogs
|
app/models/rb_stats.rb
|
7557
|
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class RbStats < ActiveRecord::Base
attr_protected :created_at # hack, all attributes will be mass asigment
REDMINE_PROPERTIES = ['estimated_hours', 'fixed_version_id', 'status_id', 'story_points', 'remaining_hours']
JOURNALED_PROPERTIES = {
'estimated_hours' => :float,
'remaining_hours' => :float,
'story_points' => :float,
'fixed_version_id' => :int,
'status_open' => :bool,
'status_success' => :bool,
}
belongs_to :issue
def self.journal(j)
j.rb_journal_properties_saved ||= []
case Backlogs.platform
when :redmine
j.details.each{|detail|
next if j.rb_journal_properties_saved.include?(detail.prop_key)
next unless detail.property == 'attr' && RbJournal::REDMINE_PROPERTIES.include?(detail.prop_key)
j.rb_journal_properties_saved << detail.prop_key
create_journal(j, detail, j.journalized_id, j.created_on)
}
when :chiliproject
if j.type == 'IssueJournal'
RbJournal::REDMINE_PROPERTIES.each{|prop|
next if j.details[prop].nil?
create_journal(j, prop, j.journaled_id, j.created_on)
}
end
end
end
def self.create_journal(j, prop, issue_id, timestamp)
if journal_property_key(prop) == 'status_id'
begin
status = IssueStatus.find(journal_property_value(prop, j))
rescue ActiveRecord::RecordNotFound
status = nil
end
changes = [ { :property => 'status_open', :value => status && !status.is_closed },
{ :property => 'status_success', :value => status && !status.backlog_is?(:success) } ]
else
changes = [ { :property => journal_property_key(prop), :value => journal_property_value(prop, j) } ]
end
changes.each{|change|
RbJournal.new(:issue_id => issue_id, :timestamp => timestamp, :change => change).save
}
end
def self.journal_property_key(property)
case Backlogs.platform
when :redmine
return property.prop_key
when :chiliproject
return property
end
end
def self.journal_property_value(property, j)
case Backlogs.platform
when :redmine
return property.value
when :chiliproject
return j.details[property][1]
end
end
def self.rebuild(issue)
RbJournal.delete_all(:issue_id => issue.id)
changes = {}
RbJournal::REDMINE_PROPERTIES.each{|prop| changes[prop] = [] }
case Backlogs.platform
when :redmine
JournalDetail.find(:all, :order => "journals.created_on asc" , :joins => :journal,
:conditions => ["property = 'attr' and prop_key in (?)
and journalized_type = 'Issue' and journalized_id = ?",
RbJournal::REDMINE_PROPERTIES, issue.id]).each {|detail|
changes[detail.prop_key] << {:time => detail.journal.created_on, :old => detail.old_value, :new => detail.value}
}
when :chiliproject
# has to be here because the ChiliProject journal design easily allows for one to delete issue statuses that remain
# in the journal, because even the already-feeble rails integrity constraints can't be enforced. This also mean it's
# not really reliable to use statuses for historic burndown calculation. Those are the breaks if you let programmers
# do database design.
valid_statuses = IssueStatus.connection.select_values("select id from #{IssueStatus.table_name}").collect{|x| x.to_i}
issue.journals.reject{|j| j.created_at < issue.created_on}.each{|j|
RbJournal::REDMINE_PROPERTIES.each{|prop|
delta = j.changes[prop]
next unless delta
if prop == 'status_id'
next if changes[prop].size == 0 && !valid_statuses.include?(delta[0])
next unless valid_statuses.include?(delta[1])
end
changes[prop] << {:time => j.created_at, :old => delta[0], :new => delta[1]}
}
}
end
RbJournal::REDMINE_PROPERTIES.each{|prop|
if changes[prop].size > 0
changes[prop].unshift({:time => issue.created_on, :new => changes[prop][0][:old]})
else
changes[prop] = [{:time => issue.created_on, :new => issue.send(prop.intern)}]
end
}
issue_status = {}
changes['status_id'].collect{|change| change[:new]}.compact.uniq.each{|id|
begin
issue_status[id] = IssueStatus.find(Integer(id))
rescue ActiveRecord::RecordNotFound
issue_status[id] = nil
end
}
['status_open', 'status_success'].each{|p| changes[p] = [] }
changes['status_id'].each{|change|
status = issue_status[change[:new]]
changes['status_open'] << change.merge(:new => status && !status.is_closed?)
changes['status_success'] << change.merge(:new => status && status.backlog_is?(:success))
}
changes.delete('status_id')
changes.each_pair{|prop, updates|
updates.each{|change|
RbJournal.new(:issue_id => issue.id, :timestamp => change[:time], :change => {:property => prop, :value => change[:new]}).save
}
}
end
def to_s
"<#{RbJournal.table_name} issue=#{issue_id}: #{property}=#{value.inspect} @ #{timestamp}>"
end
def self.changes_to_s(changes, prefix = '')
s = ''
changes.each_pair{|k, v|
s << "#{prefix}#{k}\n"
v.each{|change|
s << "#{prefix} @#{change[:time]}: #{change[:new]}\n"
}
}
return s
end
def change=(prop)
self.property = prop[:property]
self.value = prop[:value]
end
def property
return self[:property].to_sym
end
def property=(name)
name = name.to_s
raise "Unknown journal property #{name.inspect}" unless RbJournal::JOURNALED_PROPERTIES.include?(name)
self[:property] = name
end
def value
v = self[:value]
# this test against blank *only* works when not storing string properties! Otherwise test against nil? here and handle
# blank? per-type
return nil if v.blank?
case RbJournal::JOURNALED_PROPERTIES[self[:property]]
when :bool
return (v == 'true')
when :int
return Integer(v)
when :float
return Float(v)
else
raise "Unknown journal property #{self[:property].inspect}"
end
end
def value=(v)
# this test against blank *only* works when not storing string properties! Otherwise test against nil? here and handle
# blank? per-type
self[:value] = v.blank? ? nil : case RbJournal::JOURNALED_PROPERTIES[self[:property]]
when :bool
v ? 'true' : 'false'
when :int, :float
v.to_s
else
raise "Unknown journal property #{self[:property].inspect}"
end
end
end
|
gpl-2.0
|
mdavid/vtd-xml
|
src/Ximpleware.VTDXml.Test/Tests/DuplicateNavTest.cs
|
1876
|
/*
* Copyright (C) 2002-2009 XimpleWare, info@ximpleware.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/* In this C# program, we demonstrate how to use AutoPilot and VTDNav
* class to filter elements of a particular name space. We also are going
* to use VTDGen's parseFile to simplify programming.
*/
using System;
using com.ximpleware;
using NUnit.Framework;
namespace Ximpleware.VTDXml
{
partial class Test
{
[Test]
public static void DuplicateNav()
{
VTDGen vg = new VTDGen();
if (vg.parseFile("./XmlDataFiles/mix.xml", true))
{
VTDNav vn = vg.getNav();
// duplicated VTDNav instances share the same XML, LC buffers and VTD buffers.
VTDNav vn2 = vn.duplicateNav();
VTDNav vn3 = vn.duplicateNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("//*");
int i;
while ((i = ap.evalXPath()) != -1)
{
Console.WriteLine("element name: " + vn.toString(i));
}
}
}
}
}
|
gpl-2.0
|
nulled/nulled
|
www/planetxmail.com/mle/affsignup.php
|
44
|
<?php
include("mlpsecure/affsignup.inc");
?>
|
gpl-2.0
|
kdeforche/jwt
|
src/eu/webtoolkit/jwt/WAbstractEvent.java
|
313
|
/*
* Copyright (C) 2009 Emweb bv, Herent, Belgium.
*
* See the LICENSE file for terms of use.
*/
package eu.webtoolkit.jwt;
/**
* Internal class {@link WAbstractEvent}
*/
public interface WAbstractEvent {
/**
* Internal method.
*/
public WAbstractEvent createFromJSEvent(JavaScriptEvent jsEvent);
}
|
gpl-2.0
|
voitureblanche/kaleidoscope
|
app/src/androidTest/java/gelmir/free/fr/kaleidoscope/ExampleInstrumentedTest.java
|
738
|
package gelmir.free.fr.kaleidoscope;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("gelmir.free.fr.kaleidoscope", appContext.getPackageName());
}
}
|
gpl-2.0
|
cdavid/wattsapp2
|
themes/bootstrap/about.php
|
342
|
<?php if (!defined('APPLICATION')) exit();
$ThemeInfo['bootstrap'] = array(
'Name' => 'Twitter BootStrap for Vanilla',
'Description' => 'Bootstrap is a toolkit from Twitter designed to kickstart development of webapps and sites.',
'Version' => '1.0',
'Author' => 'Catalin David',
'AuthorEmail' => 'c.david@jacobs-university.de'
);
|
gpl-2.0
|
jukkar/eca-web
|
src/bluezutils.py
|
2286
|
#
# ECA web UI
#
# Copyright (C) 2013 Intel Corporation. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 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
import dbus
SERVICE_NAME = "org.bluez"
ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter1"
DEVICE_INTERFACE = SERVICE_NAME + ".Device1"
def get_managed_objects():
bus = dbus.SystemBus()
manager = dbus.Interface(bus.get_object("org.bluez", "/"),
"org.freedesktop.DBus.ObjectManager")
return manager.GetManagedObjects()
def find_adapter(pattern=None):
return find_adapter_in_objects(get_managed_objects(), pattern)
def find_adapter_in_objects(objects, pattern=None):
bus = dbus.SystemBus()
for path, ifaces in objects.iteritems():
adapter = ifaces.get(ADAPTER_INTERFACE)
if adapter is None:
continue
if not pattern or pattern == adapter["Address"] or \
path.endswith(pattern):
obj = bus.get_object(SERVICE_NAME, path)
return dbus.Interface(obj, ADAPTER_INTERFACE)
raise Exception("Bluetooth adapter not found")
def find_device(device_address, adapter_pattern=None):
return find_device_in_objects(get_managed_objects(), device_address,
adapter_pattern)
def find_device_in_objects(objects, device_address, adapter_pattern=None):
bus = dbus.SystemBus()
path_prefix = ""
if adapter_pattern:
adapter = find_adapter_in_objects(objects, adapter_pattern)
path_prefix = adapter.object_path
for path, ifaces in objects.iteritems():
device = ifaces.get(DEVICE_INTERFACE)
if device is None:
continue
if (device["Address"] == device_address and
path.startswith(path_prefix)):
obj = bus.get_object(SERVICE_NAME, path)
return dbus.Interface(obj, DEVICE_INTERFACE)
raise Exception("Bluetooth device not found")
|
gpl-2.0
|
PriyankaKhante/nlp_spf
|
parser.ccg.rules.lambda/src/edu/uw/cs/lil/tiny/parser/ccg/rules/lambda/typeshifting/AdverbialTypeShifting.java
|
2611
|
/*******************************************************************************
* UW SPF - The University of Washington Semantic Parsing Framework
* <p>
* Copyright (C) 2013 Yoav Artzi
* <p>
* 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 any later version.
* <p>
* 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.
* <p>
* 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.uw.cs.lil.tiny.parser.ccg.rules.lambda.typeshifting;
import edu.uw.cs.lil.tiny.ccg.categories.syntax.ComplexSyntax;
import edu.uw.cs.lil.tiny.ccg.categories.syntax.Slash;
import edu.uw.cs.lil.tiny.ccg.categories.syntax.Syntax;
import edu.uw.cs.lil.tiny.explat.IResourceRepository;
import edu.uw.cs.lil.tiny.explat.ParameterizedExperiment.Parameters;
import edu.uw.cs.lil.tiny.explat.resources.IResourceObjectCreator;
import edu.uw.cs.lil.tiny.explat.resources.usage.ResourceUsage;
/**
* AP => S\S
*
* @author Yoav Artzi
*/
public class AdverbialTypeShifting extends AbstractUnaryRuleForThreading {
private static final Syntax S_BS_S_SYNTAX = new ComplexSyntax(Syntax.S,
Syntax.S,
Slash.BACKWARD);
public AdverbialTypeShifting() {
this("shift_ap");
}
public AdverbialTypeShifting(String name) {
super(name, Syntax.AP);
}
@Override
protected Syntax getSourceSyntax() {
return Syntax.AP;
}
@Override
protected Syntax getTargetSyntax() {
return S_BS_S_SYNTAX;
}
public static class Creator implements
IResourceObjectCreator<AdverbialTypeShifting> {
private final String type;
public Creator() {
this("rule.shifting.ap");
}
public Creator(String type) {
this.type = type;
}
@Override
public AdverbialTypeShifting create(Parameters params,
IResourceRepository repo) {
return new AdverbialTypeShifting();
}
@Override
public String type() {
return type;
}
@Override
public ResourceUsage usage() {
return new ResourceUsage.Builder(type, AdverbialTypeShifting.class)
.build();
}
}
}
|
gpl-2.0
|
unofficial-opensource-apple/llvmgcc42
|
llvmCore/lib/Target/ARM/AsmPrinter/ARMMCInstLower.cpp
|
5054
|
//===-- ARMMCInstLower.cpp - Convert ARM MachineInstr to an MCInst --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains code to lower ARM MachineInstrs to their corresponding
// MCInst records.
//
//===----------------------------------------------------------------------===//
#include "ARMMCInstLower.h"
//#include "llvm/CodeGen/MachineModuleInfoImpls.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
//#include "llvm/MC/MCStreamer.h"
#include "llvm/Target/Mangler.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/SmallString.h"
using namespace llvm;
#if 0
const ARMSubtarget &ARMMCInstLower::getSubtarget() const {
return AsmPrinter.getSubtarget();
}
MachineModuleInfoMachO &ARMMCInstLower::getMachOMMI() const {
assert(getSubtarget().isTargetDarwin() &&"Can only get MachO info on darwin");
return AsmPrinter.MMI->getObjFileInfo<MachineModuleInfoMachO>();
}
#endif
MCSymbol *ARMMCInstLower::
GetGlobalAddressSymbol(const MachineOperand &MO) const {
// FIXME: HANDLE PLT references how??
switch (MO.getTargetFlags()) {
default: assert(0 && "Unknown target flag on GV operand");
case 0: break;
}
return Printer.Mang->getSymbol(MO.getGlobal());
}
MCSymbol *ARMMCInstLower::
GetExternalSymbolSymbol(const MachineOperand &MO) const {
// FIXME: HANDLE PLT references how??
switch (MO.getTargetFlags()) {
default: assert(0 && "Unknown target flag on GV operand");
case 0: break;
}
return Printer.GetExternalSymbolSymbol(MO.getSymbolName());
}
MCSymbol *ARMMCInstLower::
GetJumpTableSymbol(const MachineOperand &MO) const {
SmallString<256> Name;
raw_svector_ostream(Name) << Printer.MAI->getPrivateGlobalPrefix() << "JTI"
<< Printer.getFunctionNumber() << '_' << MO.getIndex();
#if 0
switch (MO.getTargetFlags()) {
default: llvm_unreachable("Unknown target flag on GV operand");
}
#endif
// Create a symbol for the name.
return Ctx.GetOrCreateTemporarySymbol(Name.str());
}
MCSymbol *ARMMCInstLower::
GetConstantPoolIndexSymbol(const MachineOperand &MO) const {
SmallString<256> Name;
raw_svector_ostream(Name) << Printer.MAI->getPrivateGlobalPrefix() << "CPI"
<< Printer.getFunctionNumber() << '_' << MO.getIndex();
#if 0
switch (MO.getTargetFlags()) {
default: llvm_unreachable("Unknown target flag on GV operand");
}
#endif
// Create a symbol for the name.
return Ctx.GetOrCreateTemporarySymbol(Name.str());
}
MCOperand ARMMCInstLower::
LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const {
// FIXME: We would like an efficient form for this, so we don't have to do a
// lot of extra uniquing.
const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, Ctx);
#if 0
switch (MO.getTargetFlags()) {
default: llvm_unreachable("Unknown target flag on GV operand");
}
#endif
if (!MO.isJTI() && MO.getOffset())
Expr = MCBinaryExpr::CreateAdd(Expr,
MCConstantExpr::Create(MO.getOffset(), Ctx),
Ctx);
return MCOperand::CreateExpr(Expr);
}
void ARMMCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
OutMI.setOpcode(MI->getOpcode());
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
MCOperand MCOp;
switch (MO.getType()) {
default:
MI->dump();
assert(0 && "unknown operand type");
case MachineOperand::MO_Register:
// Ignore all implicit register operands.
if (MO.isImplicit()) continue;
assert(!MO.getSubReg() && "Subregs should be eliminated!");
MCOp = MCOperand::CreateReg(MO.getReg());
break;
case MachineOperand::MO_Immediate:
MCOp = MCOperand::CreateImm(MO.getImm());
break;
case MachineOperand::MO_MachineBasicBlock:
MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
MO.getMBB()->getSymbol(), Ctx));
break;
case MachineOperand::MO_GlobalAddress:
MCOp = LowerSymbolOperand(MO, GetGlobalAddressSymbol(MO));
break;
case MachineOperand::MO_ExternalSymbol:
MCOp = LowerSymbolOperand(MO, GetExternalSymbolSymbol(MO));
break;
case MachineOperand::MO_JumpTableIndex:
MCOp = LowerSymbolOperand(MO, GetJumpTableSymbol(MO));
break;
case MachineOperand::MO_ConstantPoolIndex:
MCOp = LowerSymbolOperand(MO, GetConstantPoolIndexSymbol(MO));
break;
case MachineOperand::MO_BlockAddress:
MCOp = LowerSymbolOperand(MO, Printer.GetBlockAddressSymbol(
MO.getBlockAddress()));
break;
}
OutMI.addOperand(MCOp);
}
}
|
gpl-2.0
|
JoomAce/AceSQL
|
com_acesql/controllers/edit.php
|
2673
|
<?php
/**
* @version 1.0.0
* @package AceSQL
* @subpackage AceSQL
* @copyright 2009-2012 JoomAce LLC, www.joomace.net
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
*
* Based on EasySQL Component
* @copyright (C) 2008 - 2011 Serebro All rights reserved
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link http://www.lurm.net
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
class AcesqlControllerEdit extends AcesqlController {
public function __construct($default = array()) {
parent::__construct($default);
$this->_model = $this->getModel('edit');
}
public function add() {
// Check for request forgeries
JRequest::checkToken() or jexit('Invalid Token');
if ($this->_model->add($this->_table, $this->_query)) {
$msg = "Yes";
}
else {
$msg = "No";
}
$vars = '&ja_tbl_g='.base64_encode($this->_table).'&ja_qry_g='.base64_encode($this->_query);
$this->setRedirect('index.php?option=com_acesql'.$vars, $msg);
}
public function apply() {
// Check for request forgeries
JRequest::checkToken() or jexit('Invalid Token');
if ($this->_model->save($this->_table, $this->_query)) {
$msg = JText::_('COM_ACESQL_SAVE_TRUE');
}
else {
$msg = JText::_('COM_ACESQL_SAVE_FALSE');
}
$id = JRequest::getInt('id', JRequest::getInt('id', null, 'post'), 'get');
$key = JRequest::getCmd('key', JRequest::getCmd('key', null, 'post'), 'get');
$vars = '&ja_tbl_g='.base64_encode($this->_table).'&ja_qry_g='.base64_encode($this->_query).'&key='.$key.'&id='.$id;
$this->setRedirect('index.php?option=com_acesql&task=edit'.$vars, $msg);
}
public function save() {
// Check for request forgeries
JRequest::checkToken() or jexit('Invalid Token');
if ($this->_model->save($this->_table, $this->_query)) {
$msg = JText::_('COM_ACESQL_SAVE_TRUE');
}
else {
$msg = JText::_('COM_ACESQL_SAVE_FALSE');
}
$vars = '&ja_tbl_g='.base64_encode($this->_table).'&ja_qry_g='.base64_encode($this->_query);
$this->setRedirect('index.php?option=com_acesql'.$vars, $msg);
}
public function cancel() {
// Check for request forgeries
JRequest::checkToken() or jexit('Invalid Token');
$vars = '&ja_tbl_g='.base64_encode($this->_table).'&ja_qry_g='.base64_encode($this->_query);
$this->setRedirect('index.php?option=com_acesql'.$vars, $msg);
}
}
|
gpl-2.0
|
zyprosoft/ROCBOSS
|
index.php
|
786
|
<?php
session_start();
# 开发调试时建议设为 E_ALL ,运营时请设为 0
error_reporting(0);
date_default_timezone_set('PRC');
define('ROC', TRUE);
# 定义项目根目录,若是子目录则为 '/子目录名/'
define('ROOT', '/');
# 引入框架核心文件
require 'system/Roc.php';
# 引入框架路由文件
require 'system/Router.php';
# 载入应用配置
require 'application/config/config.php';
# 载入系统类库
Roc::loadSystemLibs(array(
# 系统加密类
'Secret',
# 系统过滤类
'Filter',
# 系统数据库操作类
'DB',
# 系统模板引擎类
'Template',
# 系统图像类
'Image',
# 系统分页类
'Page',
# 系统工具类
'Utils'
));
# 获取路由
$Router = Router::getRouter();
# 开启框架
Roc::Start($Router);
?>
|
gpl-2.0
|
PagerDuty/optimizely-gem
|
lib/optimizely/engine.rb
|
8499
|
module Optimizely
class Engine
BASE_URL = "https://www.optimizelyapis.com/experiment/v1/"
attr_accessor :url
# Initialize Optimizely using an API token.
#
# == Options:
# +:api_token+:: Use an API token you received before.
# +:timeout+:: Set Net:HTTP timeout in seconds (default is 300).
#
def initialize(options={})
@options = options
check_init_auth_requirements
end
# Initalize the Token so it can be used in every request we'll do later on.
# Besides that also set the authentication header.
def token=(token)
@token = token
set_headers
end
# Returns the list of projects available to the authenticated user.
#
# == Usage
# optimizely = Optimizely.new({ api_token: 'oauth2_token' })
# projects = optimizely.projects # Look up all projects.
#
def projects
if @projects.nil?
response = self.get("projects")
@projects = response.collect { |project_json| Project.new(project_json) }
end
@projects
end
# Returns the details for a specific project.
#
# == Usage
# optimizely = Optimizely.new({ api_token: 'oauth2_token' })
# project = optimizely.project(12345) # Look up the project.
#
def project(id)
@url = "projects/#{id}"
raise OptimizelyError::NoProjectID, "A Project ID is required to retrieve the project." if id.nil?
if @project.nil?
response = self.get(@url)
@project = Project.new(response)
end
@project
end
# Returns the list of experiments for a specified project.
#
# == Usage
# optimizely = Optimizely.new({ api_token: 'oauth2_token' })
# experiments = optimizely.experiments(12345) # Look up all experiments for a project.
#
def experiments(project_id)
raise OptimizelyError::NoProjectID, "A Project ID is required to retrieve experiments." if project_id.nil?
if @experiments.nil?
response = self.get("projects/#{project_id}/experiments")
@experiments = response.collect { |response_json| Experiment.new(response_json) }
end
@experiments
end
# Returns the details for a specific experiment.
#
# == Usage
# optimizely = Optimizely.new({ api_token: 'oauth2_token' })
# experiment = optimizely.experiment(12345) # Look up the experiment.
#
def experiment(id)
@url = "experiments/#{id}"
raise OptimizelyError::NoExperimentID, "An Experiment ID is required to retrieve the experiment." if id.nil?
if @experiment.nil?
response = self.get(@url)
@experiment = Experiment.new(response)
end
@experiment
end
# Returns the list of variations for a specified experiment.
#
# == Usage
# optimizely = Optimizely.new({ api_token: 'oauth2_token' })
# variations = optimizely.variations(12345) # Look up all variations for an experiment.
#
def variations(experiment_id)
raise OptimizelyError::NoExperimentID, "An Experiment ID is required to retrieve variations." if experiment_id.nil?
if @variations.nil?
response = self.get("projects/#{experiment_id}/variations")
@variations = response.collect { |variation_json| Variation.new(variation_json) }
end
@variations
end
# Returns the details for a specific variation.
#
# == Usage
# optimizely = Optimizely.new({ api_token: 'oauth2_token' })
# variation = optimizely.variation(12345) # Look up the variation.
#
def variation(id)
@url = "variations/#{id}"
raise OptimizelyError::NoVariationID, "A Variation ID is required to retrieve the variation." if id.nil?
if @variation.nil?
response = self.get(@url)
@variation = Variation.new(response)
end
@variation
end
# Returns the list of audiences for a specified project.
#
# == Usage
# optimizely = Optimizely.new({ api_token: 'oauth2_token' })
# audiences = optimizely.audiences(12345) # Look up all audiences for a project.
#
def audiences(project_id)
raise OptimizelyError::NoProjectID, "A Project ID is required to retrieve audiences." if project_id.nil?
if @audiences.nil?
response = self.get("projects/#{project_id}/audiences")
@audiences = response.collect { |audience_json| Audience.new(audience_json) }
end
@audiences
end
# Returns the details for a specific audience.
#
# == Usage
# optimizely = Optimizely.new({ api_token: 'oauth2_token' })
# audience = optimizely.audience(12345) # Look up the audience.
#
def audience(id)
@url = "audiences/#{id}"
raise OptimizelyError::NoAudienceID, "An Audience ID is required to retrieve the audience." if id.nil?
if @audience.nil?
response = self.get(@url)
@audience = Audience.new(response)
end
@audience
end
# Return the parsed JSON data for a request that is done to the Optimizely REST API.
def get(url)
uri = URI.parse("#{BASE_URL}#{url}/")
https = Net::HTTP.new(uri.host, uri.port)
https.read_timeout = @options[:timeout] if @options[:timeout]
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
https.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri, @headers)
response = https.request(request)
# Response code error checking
if response.code != '200'
check_response(response.code, response.body)
else
parse_json(response.body)
end
end
def post
uri = URI.parse("#{BASE_URL}#{url}/")
https = Net::HTTP.new(uri.host, uri.port)
https.read_timeout = @options[:timeout] if @options[:timeout]
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
https.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri, @headers)
response = https.request(request)
# Response code error checking
check_response(response.code, response.body) if response.code != '201'
end
def put
uri = URI.parse("#{BASE_URL}#{url}/")
https = Net::HTTP.new(uri.host, uri.port)
https.read_timeout = @options[:timeout] if @options[:timeout]
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
https.use_ssl = true
request = Net::HTTP::Put.new(uri.request_uri, @headers)
response = https.request(request)
# Response code error checking
check_response(response.code, response.body) if response.code != '202'
end
def delete
raise OptimizelyError::NoId, "An ID is required to delete data." if @url.nil?
uri = URI.parse("#{BASE_URL}#{@url}")
https = Net::HTTP.new(uri.host, uri.port)
https.read_timeout = @options[:timeout] if @options[:timeout]
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
https.use_ssl = true
request = Net::HTTP::Delete.new(uri.request_uri, @headers)
response = https.request(request)
# Response code error checking
check_response(response.code, response.body) if response.code != '204'
end
def check_response(code, body)
case code
when '400'
raise OptimizelyError::BadRequest, body + "Your request was not sent in valid JSON. (status code: #{code})."
when '401'
raise OptimizelyError::Unauthorized, "Your API token was missing or included in the body rather than the header (status code: #{code})."
when '403'
raise OptimizelyError::Forbidden, body + "You provided an API token but it was invalid or revoked, or if you don't have read/ write access to the entity you're trying to view/edit (status code: #{code})."
when '404'
raise OptimizelyError::NotFound, body + "The id used in the request was inaccurate or you didn't have permission to view/edit it (status code: #{code})."
else
raise OptimizelyError::UnknownError, body + " (status code: #{code})."
end
end
private
# If there is no API token or an empty API token raise an exception.
def check_init_auth_requirements
if @options[:api_token].nil? || @options[:api_token].empty?
raise OptimizelyError::NoAPIToken, "An API token is required to initialize Optimizely."
else
self.token = @options[:api_token]
end
end
# As the authentication for the Optimizely Experiments API is handled via the
# Token header in every request we set the header + also make clear we expect JSON.
def set_headers
@headers = {}
@headers['Token'] = @token
@headers['Content-Type'] = "application/json"
end
# Parse the JSON data that's been requested through the get method.
def parse_json(data)
json = JSON.parse(data)
json
end
end
end
|
gpl-2.0
|
jaapgeurts/snap
|
src/main/java/snap/AuthorizationException.java
|
255
|
package snap;
public class AuthorizationException extends SnapException
{
public AuthorizationException(String message)
{
super(message);
}
public AuthorizationException(String message, Throwable cause)
{
super(message, cause);
}
}
|
gpl-2.0
|
chisimba/chisimba
|
app/lib/pear/I18Nv2/Locale/pl.php
|
560
|
<?php
/**
* $Id$
*/
$this->dateFormats = array(
I18Nv2_DATETIME_SHORT => '%d.%m.%y',
I18Nv2_DATETIME_DEFAULT => '%d.%m.%Y',
I18Nv2_DATETIME_MEDIUM => '%d %b %Y',
I18Nv2_DATETIME_LONG => '%d %B %Y',
I18Nv2_DATETIME_FULL => '%A, %d %B %Y'
);
$this->timeFormats = array(
I18Nv2_DATETIME_SHORT => '%H:%M',
I18Nv2_DATETIME_DEFAULT => '%H:%M:%S',
I18Nv2_DATETIME_MEDIUM => '%H:%M:%S',
I18Nv2_DATETIME_LONG => '%H:%M:%S %Z',
I18Nv2_DATETIME_FULL => 'godz. %H:%M %Z'
);
?>
|
gpl-2.0
|
miranda-ng/miranda-ng
|
plugins/FTPFileYM/src/job_generic.cpp
|
6509
|
/*
FTP File YM plugin
Copyright (C) 2007-2010 Jan Holub
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, see <http://www.gnu.org/licenses/>.
*/
#include "stdafx.h"
GenericJob::GenericJob(MCONTACT hContact, int iFtpNum, EMode mode) :
m_hContact(hContact),
m_iFtpNum(iFtpNum),
m_mode(mode),
m_status(STATUS_CREATED),
m_ftp(ftpList[m_iFtpNum])
{
m_tszFilePath[0] = 0;
m_tszFileName[0] = 0;
m_szSafeFileName[0] = 0;
}
GenericJob::GenericJob(GenericJob *job) :
m_hContact(job->m_hContact),
m_iFtpNum(job->m_iFtpNum),
m_mode(job->m_mode),
m_status(job->m_status),
m_ftp(job->m_ftp),
m_tab(job->m_tab)
{
wcsncpy_s(m_tszFilePath, job->m_tszFilePath, _TRUNCATE);
wcsncpy_s(m_tszFileName, job->m_tszFileName, _TRUNCATE);
strncpy_s(m_szSafeFileName, job->m_szSafeFileName, _TRUNCATE);
}
GenericJob::~GenericJob()
{
for (UINT i = 0; i < m_files.size(); i++)
mir_free(m_files[i]);
}
int GenericJob::openFileDialog()
{
wchar_t temp[MAX_PATH] = L"";
mir_snwprintf(temp, L"%s\0*.*\0", TranslateT("All Files (*.*)"));
OPENFILENAME ofn = { 0 };
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = nullptr;
ofn.lpstrFilter = temp;
ofn.nFilterIndex = 1;
ofn.lpstrFile = m_tszFilePath;
ofn.lpstrTitle = TranslateT("FTP File - Select files");
ofn.nMaxFile = _countof(m_tszFilePath);
ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_EXPLORER | OFN_NOCHANGEDIR;
return GetOpenFileName(&ofn);
}
int GenericJob::openFolderDialog()
{
BROWSEINFO bi = {};
bi.lpszTitle = TranslateT("FTP File - Select a folder");
bi.ulFlags = BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON | BIF_DONTGOBELOWDOMAIN;
LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
if (pidl != nullptr) {
SHGetPathFromIDList(pidl, m_tszFilePath);
CoTaskMemFree(pidl);
return 1;
}
return 0;
}
void GenericJob::getFilesFromOpenDialog()
{
wchar_t stzFile[MAX_PATH];
size_t length = mir_wstrlen(m_tszFilePath);
if (m_tszFilePath[0] && m_tszFilePath[length + 1]) // multiple files
{
wchar_t *ptr = m_tszFilePath + length + 1;
while (ptr[0]) {
mir_snwprintf(stzFile, L"%s\\%s", m_tszFilePath, ptr);
addFile(stzFile);
ptr += mir_wstrlen(ptr) + 1;
}
}
else {
addFile(m_tszFilePath);
}
}
int GenericJob::getFilesFromFolder(wchar_t *stzFolder)
{
wchar_t stzFile[MAX_PATH], stzDirSave[MAX_PATH];
GetCurrentDirectory(MAX_PATH, stzDirSave);
if (!SetCurrentDirectory(stzFolder)) {
Utils::msgBox(TranslateT("Folder not found!"), MB_OK | MB_ICONERROR);
return 0;
}
WIN32_FIND_DATA ffd;
HANDLE hFind = FindFirstFile(L"*.*", &ffd);
while (hFind != INVALID_HANDLE_VALUE) {
if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
mir_snwprintf(stzFile, L"%s\\%s", stzFolder, ffd.cFileName);
addFile(stzFile);
}
if (!FindNextFile(hFind, &ffd))
break;
}
FindClose(hFind);
SetCurrentDirectory(stzDirSave);
if (m_files.size() == 0) {
Utils::msgBox(TranslateT("The selected folder does not contain any files.\nFTP File sends files only from the selected folder, not from subfolders."), MB_OK | MB_ICONERROR);
return 0;
}
return 1;
}
int GenericJob::getFiles()
{
if (m_mode == FTP_ZIPFOLDER) {
if (!openFolderDialog()) return 0;
return getFilesFromFolder(m_tszFilePath);
}
else {
if (!openFileDialog()) return 0;
getFilesFromOpenDialog();
}
return 1;
}
int GenericJob::getFiles(void **objects, int objCount, uint32_t flags)
{
if (m_mode == FTP_ZIPFOLDER) {
wchar_t *folder;
if (flags & FUPL_UNICODE)
folder = mir_wstrdup((wchar_t *)objects[0]);
else
folder = mir_a2u((char *)objects[0]);
int result = getFilesFromFolder(folder);
FREE(folder);
return result;
}
else {
for (int i = 0; i < objCount; i++) {
wchar_t *fileName;
if (flags & FUPL_UNICODE)
fileName = mir_wstrdup((wchar_t *)objects[i]);
else
fileName = mir_a2u((char *)objects[i]);
addFile(fileName);
FREE(fileName);
}
}
return (m_files.size() == 0) ? 0 : 1;
}
void GenericJob::addFile(wchar_t *fileName)
{
wchar_t *buff = mir_wstrdup(fileName);
m_files.push_back(buff);
}
void GenericJob::setStatus(EStatus _status)
{
m_status = _status;
refreshTab(true);
}
bool GenericJob::isCompleted()
{
return m_status == STATUS_COMPLETED;
}
bool GenericJob::isPaused()
{
return m_status == STATUS_PAUSED;
}
bool GenericJob::isWaitting()
{
return m_status == STATUS_WAITING;
}
bool GenericJob::isCanceled()
{
return m_status == STATUS_CANCELED;
}
bool GenericJob::isConnecting()
{
return (m_status == STATUS_CONNECTING || m_status == STATUS_CREATED);
}
wchar_t *GenericJob::getStatusString()
{
switch (m_status) {
case STATUS_CANCELED: return TranslateT("CANCELED");
case STATUS_COMPLETED: return TranslateT("COMPLETED");
case STATUS_CONNECTING: return TranslateT("CONNECTING...");
case STATUS_CREATED: return TranslateT("CREATED");
case STATUS_PACKING: return TranslateT("PACKING...");
case STATUS_PAUSED: return TranslateT("PAUSED");
case STATUS_UPLOADING: return TranslateT("UPLOADING...");
case STATUS_WAITING: return TranslateT("WAITING...");
default:
return TranslateT("UNKNOWN");
}
}
void GenericJob::refreshTab(bool bTabChanged)
{
if (bTabChanged) {
if (m_hContact != NULL) {
SendDlgItemMessage(uDlg->m_hwnd, IDC_BTN_PROTO, BM_SETIMAGE, IMAGE_ICON, (LPARAM)Skin_LoadProtoIcon(Proto_GetBaseAccountName(m_hContact), ID_STATUS_ONLINE));
SetDlgItemText(uDlg->m_hwnd, IDC_UP_CONTACT, Clist_GetContactDisplayName(m_hContact));
}
else {
SendDlgItemMessage(uDlg->m_hwnd, IDC_BTN_PROTO, BM_SETIMAGE, IMAGE_ICON, (LPARAM)Utils::loadIconEx("main"));
SetDlgItemTextA(uDlg->m_hwnd, IDC_UP_CONTACT, m_ftp->m_szServer);
}
SetDlgItemText(uDlg->m_hwnd, IDC_UP_FILE, m_tszFileName);
SetDlgItemTextA(uDlg->m_hwnd, IDC_UP_SERVER, m_ftp->m_szServer);
}
}
|
gpl-2.0
|
OHSU-FM/reindeer
|
spec/factories/user_external_factory.rb
|
137
|
# FactoryBot.define do
# factory :user_external do
# user
# ident_type "TestQuestion"
# ident { ident_type }
# end
# end
|
gpl-2.0
|
gouldcwilliam/HelpDeskTools
|
HelpDeskTools/Tools/EmailReport/Properties/AssemblyInfo.cs
|
1398
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EmailReport")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EmailReport")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e46738cd-43a1-41ec-818b-2363e6c605a8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
gpl-2.0
|
chiamingyen/sgw745
|
src/core/types/pmwikiarea.php
|
12266
|
<?php
/**************************************************************************\
* Simple Groupware 0.743 *
* http://www.simple-groupware.de *
* Copyright (C) 2002-2012 by Thomas Bley *
* ------------------------------------------------------------------------ *
* 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; only version 2 *
* of the License, no 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 *
* Version 2 along with this program; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, *
* MA 02111-1307, USA. *
\**************************************************************************/
class type_pmwikiarea extends type_default {
static function form_render_value($name, $value, $smarty) {
static $init = false;
if ($init === false) $init = <<<EOT
<script>
function pmwikiarea_preview(field,pagename,title) {
var obj = getObj("preview_"+field);
obj.style.display = "";
ajax("type_pmwikiarea::ajax_render_preview",[getObj(field).value,getObj(pagename).value,getObj(title).value,tname],function(data){ set_html(obj,data); });
}
// Copyright (C) 2001-2007 Patrick R. Michaud (pmichaud § pobox.com)
function insMarkup(mopen, mclose, mtext, id) {
var tarea = document.getElementById(id);
if (tarea.setSelectionRange > "") {
var p0 = tarea.selectionStart;
var p1 = tarea.selectionEnd;
var top = tarea.scrollTop;
var str = mtext;
var cur0 = p0 + mopen.length;
var cur1 = p0 + mopen.length + str.length;
while (p1 > p0 && tarea.value.substring(p1-1, p1) == ' ') p1--;
if (p1 > p0) {
str = tarea.value.substring(p0, p1);
cur0 = p0 + mopen.length + str.length + mclose.length;
cur1 = cur0;
}
tarea.value = tarea.value.substring(0,p0)
+ mopen + str + mclose
+ tarea.value.substring(p1);
tarea.focus();
tarea.selectionStart = cur0;
tarea.selectionEnd = cur1;
tarea.scrollTop = top;
} else if (document.selection) {
var str = document.selection.createRange().text;
tarea.focus();
range = document.selection.createRange()
if (str == "") {
range.text = mopen + mtext + mclose;
range.moveStart('character', -mclose.length - mtext.length );
range.moveEnd('character', -mclose.length );
} else {
if (str.charAt(str.length - 1) == " ") {
mclose = mclose + " ";
str = str.substr(0, str.length - 1);
}
range.text = mopen + str + mclose;
}
range.select();
} else { tarea.value += mopen + mtext + mclose; }
return;
}
</script>
EOT;
$prefix = $smarty->prefix;
$output = $init.<<<EOT
<div style="max-width:710px;">
<div style="float:right; padding-top:2px;">
<input type="button" value="{t}Preview{/t}" accesskey="p" onclick="pmwikiarea_preview('{$name}','{$prefix}pagename','{$prefix}title'); getObj('{$name}').focus();">
</div>
<div id="wikiedit">
<a href="javascript:insMarkup('\'\'\'','\'\'\'','Strong','{$name}');"><img src="ext/cms/icons/strong.gif" title="{t}bold{/t}"></a>
<a href="javascript:insMarkup('\'\'','\'\'','Emphasized','{$name}');"><img src="ext/cms/icons/em.gif" title="{t}italic{/t}"></a>
<a href="javascript:insMarkup('[[',']]','Page link','{$name}');"><img src="ext/cms/icons/pagelink.gif" title="{t}link to internal page{/t}"></a>
<a href="javascript:insMarkup('[[',']]','http:// | link text','{$name}');"><img src="ext/cms/icons/extlink.gif" title="{t}link to external page{/t}"></a>
<a href="javascript:insMarkup('Attach:','','file.ext','{$name}');"><img src="ext/cms/icons/attach.gif" title="{t}attach file{/t}"></a>
<a href="javascript:insMarkup('----','\\n','','{$name}');"><img src="ext/cms/icons/hr.gif" title="{t}horizontal line{/t}"></a>
<a href="javascript:insMarkup('\'+','+\'','Big text','{$name}');"><img src="ext/cms/icons/big.gif" title="{t}big text{/t}"></a>
<a href="javascript:insMarkup('\'-','-\'','Small text','{$name}');"><img src="ext/cms/icons/small.gif" title="{t}small text{/t}"></a>
<a href="javascript:insMarkup('\'^','^\'','Superscript','{$name}');"><img src="ext/cms/icons/sup.gif" title="{t}superscript{/t}"></a>
<a href="javascript:insMarkup('\'_','_\'','Subscript','{$name}');"><img src="ext/cms/icons/sub.gif" title="{t}subscript{/t}"></a>
<a href="javascript:insMarkup('\\n!! ','\\n','Heading','{$name}');"><img src="ext/cms/icons/h.gif" title="{t}heading{/t}"></a>
<a href="javascript:insMarkup('\\n!!! ','\\n','Subheading','{$name}');"><img src="ext/cms/icons/h3.gif" title="{t}subheading{/t}"></a>
<a href="javascript:insMarkup('%25center%25 ','','','{$name}');"><img src="ext/cms/icons/center.gif" title="{t}centered{/t}"></a>
<a href="javascript:insMarkup('%25right%25 ','','','{$name}');"><img src="ext/cms/icons/right.gif" title="{t}right-aligned{/t}"></a>
<a href="javascript:insMarkup('\\n->','\\n','Indented text','{$name}');"><img src="ext/cms/icons/indent.gif" title="{t}indent text{/t}"></a>
<a href="javascript:insMarkup('\\n# ','\\n','Ordered list','{$name}');"><img src="ext/cms/icons/ol.gif" title="{t}numbered{/t}"></a>
<a href="javascript:insMarkup('\\n* ','\\n','Unordered list','{$name}');"><img src="ext/cms/icons/ul.gif" title="{t}bulleted{/t}"></a>
<a href="javascript:insMarkup('(:table border=1 width=80%:)\\n(:cell style=\'padding:5px\;\':)\\n1a\\n(:cell style=\'padding:5px\;\':)\\n1b\\n(:cellnr style=\'padding:5px\;\':)\\n2a\\n(:cell style=\'padding:5px\;\':)\\n2b\\n(:tableend:)\\n\\n','','','{$name}');">
<img src="ext/cms/icons/table.gif" title="{t}Table{/t}"></a>
<a href="javascript:insMarkup('(:graphviz [= digraph {\\n\\n} =]:)\\n\\n','','','{$name}');"><img src="ext/cms/icons/graphviz.gif" title="Graphviz"></a>
<a href="javascript:insMarkup('(:get_table folder="{t}Id{/t} / {t}Path{/t}" view={t}View{/t} fields_hidden="{t}Comma separated values{/t}" limit="{t}Maximum number of assets per page{/t}" filter="{t}Filter{/t} (URL)" groupby={t}Field{/t}:)\\n\\n','','','{$name}');"><img src="ext/cms/icons/extjs.gif" title="ExtJS {t}Table{/t}"></a>
<a href="javascript:insMarkup('(:include_page url="" height="":)\\n\\n','','','{$name}');"><img src="ext/cms/icons/iframe.gif" title="{t}Include page{/t}"></a>
</div>
<link rel="stylesheet" href="ext/cms/styles.css" type="text/css"/>
<textarea name="{$name}" id="{$name}" style="font-size:10pt; font-family:Courier; width:100%; height:96px; color:#555; background-color:#FFF;">{$value}</textarea>
<div class="wikibody">
<div id="preview_{$name}" style="display:none; padding:8px;"><img src="ext/images/loading.gif"/></div>
</div>
<div style="font-size:90%; margin-top:8px; margin-bottom:8px; padding-left:2px;">
<b>PmWiki:</b> <a onclick="nWin('{t}http://www.pmwiki.org/PmWiki/{/t}BasicEditing');">{t}Basic editing{/t}</a> -
<a onclick="nWin('{t}http://www.pmwiki.org/PmWiki/{/t}TextFormattingRules');">{t}Text formatting rules{/t}</a> -
<a onclick="nWin('{t}http://www.pmwiki.org/PmWiki/{/t}Images');">{t}Images{/t}</a> -
<a onclick="nWin('{t}http://www.pmwiki.org/PmWiki/{/t}Tables');">{t}Simple tables{/t}</a> -
<a onclick="nWin('{t}http://www.pmwiki.org/PmWiki/{/t}TableDirectives');">{t}Advanced tables{/t}</a> -
<a onclick="nWin('{t}http://www.pmwiki.org/PmWiki/{/t}WikiStyles');">{t}WikiStyles{/t}</a> --
<a onclick="nWin('{t}http://www.pmwiki.org/PmWiki/{/t}DocumentationIndex');">{t}Documentation index{/t}</a>
<br/><br/>
<b>{t}Paragraphs{/t}:</b> {t}for a new paragraph, use a blank line{/t}, <b>{t}Line break{/t}:</b> <b>\\</b> {t}or{/t} [[<<]], {t}Join lines{/t}: <b>\</b><br/>
<div style="padding-left:70px;"><b>-></b> {t}indent text{/t}, <b>-<</b> {t}hanging text{/t}</div>
<br/>
<b>{t}Lists{/t}:</b> <b>*</b> {t}bulleted{/t}, <b>#</b> {t}numbered{/t}, <b>:</b>{t}term{/t}<b>:</b>{t}definition for definition lists{/t}<br/>
<b>{t}Emphasis{/t}:</b> <b>''</b><i>{t}italic{/t}</i><b>''</b>, <b>'''bold'''</b>, <b>'''''<i>{t}bold italic{/t}</i>'''''</b>, <b>@@</b>{t}monospace{/t}<b>@@</b><br/>
<br/>
<b>{t}Links{/t}:</b> <b>[[</b>{t}another page{/t}<b>]]</b>, <b>[[</b>http://www.example.com<b>]]</b>, <b>[[</b>{t}another page{/t} <b>|</b> {t}link text{/t}<b>]]</b>, <b>[[#</b>{t}Anchor{/t}<b>]]</b><br/>
<b>{t}Groups{/t}:</b> [[{t}Group{/t}/{t}Page{/t}]] {t}displays{/t} {t}Page{/t},
[[{t}Group{/t}.{t}Page{/t}]] {t}displays{/t} {t}Group{/t}.{t}Page{/t},
[[{t}Group{/t}(.{t}Page{/t})]] {t}displays{/t} {t}Group{/t}
<br/><br/>
<b>{t}Separators{/t}:</b> <b>!!</b>, <b>!!!</b> {t}headings{/t}, <b>----</b> {t}horizontal line{/t}<br/>
<b>{t}Other{/t}:</b> <b>[+</b><span style="font-size: 120%;">{t}big{/t}</span><b>+]</b>,
<b>[++</b><span style="font-size: 144%;">{t}bigger{/t}</span><b>++]</b>,
<b>[-</b><span style="font-size: 83%;">{t}small{/t}</span><b>-]</b>,
<b>[--</b><span style="font-size: 69%;">{t}smaller{/t}</span><b>--]</b>,
<b>'^</b><sup>{t}superscript{/t}</sup><b>^'</b>,
<b>'_</b><sub>{t}subscript{/t}</sub><b>_'</b>,
<b>{ldelim}+</b><ins>{t}inserted{/t}</ins><b>+{rdelim}</b>,
<b>{ldelim}-</b><del>{t}deleted{/t}</del><b>-{rdelim}</b>
<br/><br/>
<b>{t}Prevent formatting{/t}:</b> <b>[=</b>...<b>=]</b>, <b>{t}Preformatted block{/t}:</b> <b>[@</b>...<b>@]</b>,
<b>Graphviz:</b> (:graphviz [= digraph { ... } =]:)
<br/>
<b>ExtJS {t}Table{/t}:</b> (:get_table folder=... view=... :)
</div>
</div>
EOT;
$init = "";
return $output;
}
static function render_value($value, $value_raw, $preview, $unused) {
if ($preview) {
$id = uniqid();
$value = modify::htmlfield(modify::htmlunquote($value),true,true);
$value_raw = modify::nl2br($value_raw);
return <<<EOT
<div class="wikibody">
<div id="html_{$id}" style="padding:8px;">{$value}</div>
<div id="data_{$id}" style="display:none; padding:8px;">{$value_raw}</div>
</div>
<input type="button" value="{t}Source code{/t} / HTML" onclick="showhide('data_{$id}'); showhide('html_{$id}');" style="margin-bottom:1px;">
EOT;
}
return modify::nl2br($value_raw);
}
static function render_page($str,$args,$row) {
$row = array(
"pagename" => $row["pagename"]["data"][0],
"title" => $row["title"]["data"][0],
"data" => $str,
"staticcache" => @$row["staticcache"]["data"][0],
"lastmodified" => $row["lastmodified"],
"table"=>$row["_table"],
);
if (empty($row["data"])) return "";
$title = $row["title"] ? $row["title"] : $row["pagename"];
if (($pos = strpos($title,"."))) $title = substr($title,$pos+1);
return "<h1 class='pagetitle'>".modify::htmlquote($title)."</h1><div id='wikitext'>".
pmwiki_render($row["pagename"],"(:groupheader:)".$row["data"]."(:groupfooter:)",$row["table"],$row["staticcache"],$row["lastmodified"])."</div>";
}
static function ajax_render_preview($text, $pagename, $title, $table) {
if (empty($text)) return "";
if ($title=="") $title = $pagename;
if (($pos = strpos($title,"."))) $title = substr($title,$pos+1);
return sys_remove_trans("{t}Preview{/t}")."<br/><br/><h1 class='pagetitle'>".modify::htmlquote($title)."</h1>".
"<div id='wikitext'>".modify::htmlfield(pmwiki_render($pagename,"(:groupheader:)".$text."(:groupfooter:)",$table))."</div>";
}
static function export_as_html() {
return true;
}
}
|
gpl-2.0
|
NguyenHiep/learn-wp
|
wp-content/themes/sahifa/framework/functions/theme-functions.php
|
78962
|
<?php
/*-----------------------------------------------------------------------------------*/
# Get Theme Options
/*-----------------------------------------------------------------------------------*/
function tie_get_option( $name ) {
$get_options = get_option( 'tie_options' );
if( !empty( $get_options[$name] ))
return $get_options[$name];
return false ;
}
/*-----------------------------------------------------------------------------------*/
# Setup Theme
/*-----------------------------------------------------------------------------------*/
add_action( 'after_setup_theme', 'tie_setup' );
function tie_setup() {
add_theme_support( 'automatic-feed-links' );
add_theme_support( 'woocommerce' );
add_theme_support( 'title-tag' );
add_theme_support( 'html5', array( 'comment-list', 'comment-form', 'search-form', 'gallery', 'caption' ) );
add_theme_support( 'post-thumbnails' );
add_filter( 'enable_post_format_ui', '__return_false' );
load_theme_textdomain( 'tie', get_template_directory() . '/languages' );
register_nav_menus( array(
'top-menu' => __( 'Top Menu Navigation', 'tie' ),
'primary' => __( 'Primary Navigation', 'tie' )
) );
}
/*-----------------------------------------------------------------------------------*/
# Post Thumbnails
/*-----------------------------------------------------------------------------------*/
if ( function_exists( 'add_image_size' ) ){
add_image_size( 'tie-small' ,110, 75, true );
add_image_size( 'tie-medium' ,310, 165, true );
add_image_size( 'tie-large' ,310, 205, true );
add_image_size( 'slider' ,660, 330, true );
add_image_size( 'big-slider' ,1050, 525, true );
}
/*-----------------------------------------------------------------------------------*/
# Get score
/*-----------------------------------------------------------------------------------*/
function tie_get_score( $post_id = false , $size = 'small'){
if(function_exists('taqyeem_get_score')) {
taqyeem_get_score( $post_id , $size );
}
}
/*-----------------------------------------------------------------------------------*/
# Custom Dashboard login page logo
/*-----------------------------------------------------------------------------------*/
function tie_login_logo(){
if( tie_get_option('dashboard_logo') )
echo '<style type="text/css"> .login h1 a { background-image:url('.tie_get_option('dashboard_logo').') !important; background-size: 274px 63px; width: 326px; height: 67px; } </style>';
}
add_action('login_head', 'tie_login_logo');
function tie_login_logo_url() {
return tie_get_option('dashboard_logo_url');
}
if( tie_get_option('dashboard_logo_url') )
add_filter( 'login_headerurl', 'tie_login_logo_url' );
/*-----------------------------------------------------------------------------------*/
# Custom Gravatar
/*-----------------------------------------------------------------------------------*/
function tie_custom_gravatar ($avatar) {
$tie_gravatar = tie_get_option( 'gravatar' );
if($tie_gravatar){
$custom_avatar = tie_get_option( 'gravatar' );
$avatar[$custom_avatar] = "Custom Gravatar";
}
return $avatar;
}
add_filter( 'avatar_defaults', 'tie_custom_gravatar' );
/*-----------------------------------------------------------------------------------*/
# Custom Favicon
/*-----------------------------------------------------------------------------------*/
function tie_favicon() {
$default_favicon = get_template_directory_uri()."/favicon.ico";
$custom_favicon = tie_get_option('favicon');
$favicon = (empty($custom_favicon)) ? $default_favicon : $custom_favicon;
echo '<link rel="shortcut icon" href="'.$favicon.'" title="Favicon" />';
}
add_action('wp_head', 'tie_favicon');
/*-----------------------------------------------------------------------------------*/
# Exclude pages From Search
/*-----------------------------------------------------------------------------------*/
function tie_search_filter($query) {
if( is_search() && $query->is_main_query() ){
if ( tie_get_option( 'search_exclude_pages' ) && !is_admin() ){
$post_types = get_post_types(array( 'public' => true, 'exclude_from_search' => false ));
unset($post_types['page']);
$query->set('post_type', $post_types );
}
if ( tie_get_option( 'search_cats' ))
$query->set( 'cat', tie_get_option( 'search_cats' ) && !is_admin() );
}
return $query;
}
add_filter('pre_get_posts','tie_search_filter');
/*-----------------------------------------------------------------------------------*/
# Random article
/*-----------------------------------------------------------------------------------*/
add_action('init', 'tie_random_post');
function tie_random_post(){
if ( isset($_GET['tierand']) ){
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand',
'no_found_rows' => true,
'ignore_sticky_posts' => true
);
$random = new WP_Query( $args );
if ($random->have_posts()) {
while ($random->have_posts()) : $random->the_post();
$URL = get_permalink();
endwhile;
wp_reset_query(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Refresh" content="0; url=<?php echo $URL; ?>">
</head>
<body>
</body>
</html>
<?php }
die;
}
}
/*-----------------------------------------------------------------------------------*/
#Author Box
/*-----------------------------------------------------------------------------------*/
function tie_author_box($avatar = true, $social = true, $name = false , $user_id = false ){
if( $avatar ) :
?>
<div class="author-bio">
<div class="author-avatar">
<?php echo get_avatar( get_the_author_meta( 'user_email' , $user_id ), 90 ); ?>
</div><!-- #author-avatar -->
<?php endif; ?>
<div class="author-description">
<?php if( !empty( $name ) ): ?>
<h3><a href="<?php echo get_author_posts_url( $user_id ); ?>"><?php echo $name ?> </a></h3>
<?php endif; ?>
<?php the_author_meta( 'description' , $user_id ); ?>
</div><!-- #author-description -->
<?php if( $social ) : ?>
<div class="author-social flat-social">
<?php if ( get_the_author_meta( 'url' , $user_id ) ) : ?>
<a class="social-site" href="<?php echo esc_url( get_the_author_meta( 'url' , $user_id ) ); ?>"><i class="fa fa-home"></i></a>
<?php endif ?>
<?php if ( get_the_author_meta( 'facebook' , $user_id ) ) : ?>
<a class="social-facebook" href="<?php echo esc_url( get_the_author_meta( 'facebook' , $user_id ) ); ?>"><i class="fa fa-facebook"></i></a>
<?php endif ?>
<?php if ( get_the_author_meta( 'twitter' , $user_id ) ) : ?>
<a class="social-twitter" href="http://twitter.com/<?php the_author_meta( 'twitter' , $user_id ); ?>"><i class="fa fa-twitter"></i><span> @<?php the_author_meta( 'twitter' , $user_id ); ?></span></a>
<?php endif ?>
<?php if ( get_the_author_meta( 'google' , $user_id ) ) : ?>
<a class="social-google-plus" href="<?php echo esc_url( get_the_author_meta( 'google' , $user_id ) ); ?>"><i class="fa fa-google-plus"></i></a>
<?php endif ?>
<?php if ( get_the_author_meta( 'linkedin' , $user_id ) ) : ?>
<a class="social-linkedin" href="<?php echo esc_url( get_the_author_meta( 'linkedin' , $user_id ) ); ?>"><i class="fa fa-linkedin"></i></a>
<?php endif ?>
<?php if ( get_the_author_meta( 'flickr' , $user_id ) ) : ?>
<a class="social-flickr" href="<?php echo esc_url( get_the_author_meta( 'flickr' , $user_id ) ); ?>"><i class="fa fa-flickr"></i></a>
<?php endif ?>
<?php if ( get_the_author_meta( 'youtube' , $user_id ) ) : ?>
<a class="social-youtube" href="<?php echo esc_url( get_the_author_meta( 'youtube' , $user_id ) ); ?>"><i class="fa fa-youtube"></i></a>
<?php endif ?>
<?php if ( get_the_author_meta( 'pinterest' , $user_id ) ) : ?>
<a class="social-pinterest" href="<?php echo esc_url( get_the_author_meta( 'pinterest' , $user_id ) ); ?>"><i class="fa fa-pinterest"></i></a>
<?php endif ?>
<?php if ( get_the_author_meta( 'behance' , $user_id ) ) : ?>
<a class="social-behance" href="<?php echo esc_url( get_the_author_meta( 'behance' , $user_id ) ); ?>"><i class="fa fa-behance"></i></a>
<?php endif ?>
<?php if ( get_the_author_meta( 'instagram' , $user_id ) ) : ?>
<a class="social-instagram" href="<?php echo esc_url( get_the_author_meta( 'instagram' , $user_id ) ); ?>"><i class="fa fa-instagram"></i></a>
<?php endif ?>
</div>
<?php endif; ?>
<div class="clear"></div>
</div>
<?php
}
/*-----------------------------------------------------------------------------------*/
# Social
/*-----------------------------------------------------------------------------------*/
function tie_get_social( $newtab = true, $colored = true, $tooltip='ttip' ){
$social = tie_get_option('social');
@extract($social);
if ( !empty( $newtab ) ) $newtab = "target=\"_blank\"";
else $newtab = '';
if ( !empty( $colored ) ) $colored = " social-colored";
else $colored = '';
?>
<div class="social-icons<?php echo $colored ?>">
<?php
// RSS
if ( !tie_get_option('rss_icon') ){
if ( tie_get_option('rss_url') != '' && tie_get_option('rss_url') != ' ' ) $rss = tie_get_option('rss_url') ;
else $rss = get_bloginfo('rss2_url');
?><a class="<?php echo $tooltip; ?>" title="Rss" href="<?php echo esc_url( $rss ) ; ?>" <?php echo $newtab; ?>><i class="fa fa-rss"></i></a><?php
}
// Google+
if ( !empty($google_plus) && $google_plus != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Google+" href="<?php echo esc_url( $google_plus ); ?>" <?php echo $newtab; ?>><i class="fa fa-google-plus"></i></a><?php
}
// Facebook
if ( !empty($facebook) && $facebook != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Facebook" href="<?php echo esc_url( $facebook ); ?>" <?php echo $newtab; ?>><i class="fa fa-facebook"></i></a><?php
}
// Twitter
if ( !empty($twitter) && $twitter != ' ') {
?><a class="<?php echo $tooltip; ?>" title="Twitter" href="<?php echo esc_url( $twitter ); ?>" <?php echo $newtab; ?>><i class="fa fa-twitter"></i></a><?php
}
// Pinterest
if ( !empty($Pinterest) && $Pinterest != ' ') {
?><a class="<?php echo $tooltip; ?>" title="Pinterest" href="<?php echo esc_url( $Pinterest ); ?>" <?php echo $newtab; ?>><i class="fa fa-pinterest"></i></a><?php
}
// dribbble
if ( !empty($dribbble) && $dribbble != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Dribbble" href="<?php echo esc_url( $dribbble ); ?>" <?php echo $newtab; ?>><i class="fa fa-dribbble"></i></a><?php
}
// LinkedIN
if ( !empty($linkedin) && $linkedin != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="LinkedIn" href="<?php echo esc_url( $linkedin ); ?>" <?php echo $newtab; ?>><i class="fa fa-linkedin"></i></a><?php
}
// evernote
if ( !empty($evernote) && $evernote != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Evernote" href="<?php echo esc_url( $evernote ); ?>" <?php echo $newtab; ?>><i class="tieicon-evernote"></i></a><?php
}
// Flickr
if ( !empty($flickr) && $flickr != ' ') {
?><a class="<?php echo $tooltip; ?>" title="Flickr" href="<?php echo esc_url( $flickr ); ?>" <?php echo $newtab; ?>><i class="tieicon-flickr"></i></a><?php
}
// Picasa
if ( !empty($picasa) && $picasa != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Picasa" href="<?php echo esc_url( $picasa ); ?>" <?php echo $newtab; ?>><i class="tieicon-picasa"></i></a><?php
}
// YouTube
if ( !empty($youtube) && $youtube != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Youtube" href="<?php echo esc_url( $youtube ); ?>" <?php echo $newtab; ?>><i class="fa fa-youtube"></i></a><?php
}
// Skype
if ( !empty($skype) && $skype != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Skype" href="<?php echo esc_url( $skype ); ?>" <?php echo $newtab; ?>><i class="fa fa-skype"></i></a><?php
}
// Digg
if ( !empty($digg) && $digg != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Digg" href="<?php echo esc_url( $digg ); ?>" <?php echo $newtab; ?>><i class="fa fa-digg"></i></a><?php
}
// Reddit
if ( !empty($reddit) && $reddit != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Reddit" href="<?php echo esc_url( $reddit ); ?>" <?php echo $newtab; ?>><i class="fa fa-reddit"></i></a><?php
}
// Delicious
if ( !empty($delicious) && $delicious != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Delicious" href="<?php echo esc_url( $delicious ); ?>" <?php echo $newtab; ?>><i class="fa fa-delicious"></i></a><?php
}
// stumbleuponUpon
if ( !empty($stumbleupon) && $stumbleupon != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="StumbleUpon" href="<?php echo esc_url( $stumbleupon ); ?>" <?php echo $newtab; ?>><i class="fa fa-stumbleupon"></i></a><?php
}
// Tumblr
if ( !empty($tumblr) && $tumblr != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Tumblr" href="<?php echo esc_url( $tumblr ); ?>" <?php echo $newtab; ?>><i class="fa fa-tumblr"></i></a><?php
}
// Vimeo
if ( !empty($vimeo) && $vimeo != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Vimeo" href="<?php echo esc_url( $vimeo ); ?>" <?php echo $newtab; ?>><i class="tieicon-vimeo"></i></a><?php
}
// Blogger
if ( !empty($blogger) && $blogger != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Blogger" href="<?php echo esc_url( $blogger ); ?>" <?php echo $newtab; ?>><i class="tieicon-blogger"></i></a><?php
}
// Wordpress
if ( !empty($wordpress) && $wordpress != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="WordPress" href="<?php echo esc_url( $wordpress ); ?>" <?php echo $newtab; ?>><i class="fa fa-wordpress"></i></a><?php
}
// Yelp
if ( !empty($yelp) && $yelp != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Yelp" href="<?php echo esc_url( $yelp ); ?>" <?php echo $newtab; ?>><i class="fa fa-yelp"></i></a><?php
}
// Last.fm
if ( !empty($lastfm) && $lastfm != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Last.fm" href="<?php echo esc_url( $lastfm ); ?>" <?php echo $newtab; ?>><i class="fa fa-lastfm"></i></a><?php
}
// grooveshark
if ( !empty($grooveshark) && $grooveshark != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Grooveshark" href="<?php echo esc_url( $grooveshark ); ?>" <?php echo $newtab; ?>><i class="tieicon-grooveshark"></i></a><?php
}
// sharethis
if ( !empty($sharethis) && $sharethis != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="ShareThis" href="<?php echo esc_url( $sharethis ); ?>" <?php echo $newtab; ?>><i class="fa fa-share-alt"></i></a><?php
}
// dropbox
if ( !empty($dropbox) && $dropbox != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Dropbox" href="<?php echo esc_url( $dropbox ); ?>" <?php echo $newtab; ?>><i class="fa fa-dropbox"></i></a><?php
}
// xing.me
if ( !empty($xing) && $xing != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Xing" href="<?php echo esc_url( $xing ); ?>" <?php echo $newtab; ?>><i class="fa fa-xing"></i></a><?php
}
// DeviantArt
if ( !empty($deviantart) && $deviantart != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="DeviantArt" href="<?php echo esc_url( $deviantart ); ?>" <?php echo $newtab; ?>><i class="tieicon-deviantart"></i></a><?php
}
// Apple
if ( !empty($apple) && $apple != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Apple" href="<?php echo esc_url( $apple ); ?>" <?php echo $newtab; ?>><i class="fa fa-apple"></i></a><?php
}
// foursquare
if ( !empty($foursquare) && $foursquare != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Foursquare" href="<?php echo esc_url( $foursquare ); ?>" <?php echo $newtab; ?>><i class="fa fa-foursquare"></i></a><?php
}
// github
if ( !empty($github) && $github != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Github" href="<?php echo esc_url( $github ); ?>" <?php echo $newtab; ?>><i class="fa fa-github"></i></a><?php
}
// soundcloud
if ( !empty($soundcloud) && $soundcloud != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="SoundCloud" href="<?php echo esc_url( $soundcloud ); ?>" <?php echo $newtab; ?>><i class="fa fa-soundcloud"></i></a><?php
}
// behance
if ( !empty( $behance ) && $behance != '' && $behance != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Behance" href="<?php echo esc_url( $behance ); ?>" <?php echo $newtab; ?>><i class="fa fa-behance"></i></a><?php
}
// instagram
if ( !empty( $instagram ) && $instagram != '' && $instagram != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="instagram" href="<?php echo esc_url( $instagram ); ?>" <?php echo $newtab; ?>><i class="tieicon-instagram"></i></a><?php
}
// paypal
if ( !empty( $paypal ) && $paypal != '' && $paypal != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="paypal" href="<?php echo esc_url( $paypal ); ?>" <?php echo $newtab; ?>><i class="fa fa-paypal"></i></a><?php
}
// spotify
if ( !empty( $spotify ) && $spotify != '' && $spotify != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="spotify" href="<?php echo esc_url( $spotify ); ?>" <?php echo $newtab; ?>><i class="fa fa-spotify"></i></a><?php
}
// viadeo
if ( !empty( $viadeo ) && $viadeo != '' && $viadeo != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="viadeo" href="<?php echo esc_url( $viadeo ); ?>" <?php echo $newtab; ?>><i class="tieicon-viadeo"></i></a><?php
}
// Google Play
if ( !empty( $google_play ) && $google_play != '' && $google_play != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Google Play" href="<?php echo esc_url( $google_play ); ?>" <?php echo $newtab; ?>><i class="fa fa-play"></i></a><?php
}
// 500PX
if ( !empty($px500) && $px500 != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="500px" href="<?php echo esc_url( $px500 ); ?>" <?php echo $newtab; ?>><i class="tieicon-fivehundredpx"></i></a><?php
}
// Forrst
if ( !empty($forrst) && $forrst != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="Forrst" href="<?php echo esc_url( $forrst ); ?>" <?php echo $newtab; ?>><i class="tieicon-forrst"></i></a><?php
}
// VK
if ( !empty($vk) && $vk != ' ' ) {
?><a class="<?php echo $tooltip; ?>" title="vk.com" href="<?php echo esc_url( $vk ); ?>" <?php echo $newtab; ?>><i class="fa fa-vk"></i></a><?php
} ?>
<?php //Custom Social Networking
for( $i=1 ; $i<=5 ; $i++ ){
if ( tie_get_option( "custom_social_icon_$i" ) && tie_get_option( "custom_social_url_$i" ) ) {
?><a class="<?php echo $tooltip; ?>" <?php if ( tie_get_option( "custom_social_title_$i" ) ) echo ' title="'.tie_get_option( "custom_social_title_$i" ).'"'; ?> href="<?php echo esc_url( tie_get_option( 'custom_social_url_'.$i ) ) ?>" <?php echo $newtab; ?>><i class="fa <?php echo tie_get_option( "custom_social_icon_$i" ) ?>"></i></a><?php
}
}
?>
</div>
<?php
}
/*-----------------------------------------------------------------------------------*/
# Change The Default WordPress Excerpt Length
/*-----------------------------------------------------------------------------------*/
function tie_excerpt_global_length( $length ) {
if( tie_get_option( 'exc_length' ) )
return tie_get_option( 'exc_length' );
else return 60;
}
function tie_excerpt_home_length( $length ) {
global $get_meta;
if( !empty( $get_meta[ 'home_exc_length' ][0] ) )
return $get_meta[ 'home_exc_length' ][0];
else
return 15;
}
function tie_excerpt(){
add_filter( 'excerpt_length', 'tie_excerpt_global_length', 999 );
echo get_the_excerpt();
}
function tie_excerpt_home(){
add_filter( 'excerpt_length', 'tie_excerpt_home_length', 999 );
echo get_the_excerpt();
}
/*-----------------------------------------------------------------------------------*/
# Read More Functions
/*-----------------------------------------------------------------------------------*/
function tie_remove_excerpt( $more ) {
return ' ...';
}
add_filter('excerpt_more', 'tie_remove_excerpt');
/*-----------------------------------------------------------------------------------*/
# Page Navigation
/*-----------------------------------------------------------------------------------*/
function tie_pagenavi( $query = false, $num = false ){
?>
<div class="pagination">
<?php tie_get_pagenavi( $query, $num ) ?>
</div>
<?php
}
/*-----------------------------------------------------------------------------------*/
# Get Post Audio
/*-----------------------------------------------------------------------------------*/
function tie_audio(){
global $post;
$get_meta = get_post_custom($post->ID);
$mp3 = $get_meta["tie_audio_mp3"][0] ;
$m4a = $get_meta["tie_audio_m4a"][0] ;
$oga = $get_meta["tie_audio_oga"][0] ;
echo do_shortcode('[audio mp3="'.$mp3.'" ogg="'.$oga.'" m4a="'.$m4a.'"]');
}
/*-----------------------------------------------------------------------------------*/
# Get Post Video
/*-----------------------------------------------------------------------------------*/
function tie_video(){
$wp_embed = new WP_Embed();
global $post;
$get_meta = get_post_custom($post->ID);
if( !empty( $get_meta["tie_video_url"][0] ) ){
$video_url = $get_meta["tie_video_url"][0];
$protocol = is_ssl() ? 'https' : 'http';
if( !is_ssl() ){
$video_url = str_replace ( 'https://', 'http://', $video_url );
}
$video_output = $wp_embed->run_shortcode('[embed width="660" height="371.25"]'.$video_url.'[/embed]');
if( $video_output == '<a href="'.$video_url.'">'.$video_url.'</a>' ){
$width = '660' ;
$height = '371.25';
$video_link = @parse_url($video_url);
if ( $video_link['host'] == 'www.youtube.com' || $video_link['host'] == 'youtube.com' ) {
parse_str( @parse_url( $video_url, PHP_URL_QUERY ), $my_array_of_vars );
$video = $my_array_of_vars['v'] ;
$video_output ='<iframe width="'.$width.'" height="'.$height.'" src="'.$protocol.'://www.youtube.com/embed/'.$video.'?rel=0&wmode=opaque" frameborder="0" allowfullscreen></iframe>';
}
elseif( $video_link['host'] == 'www.youtu.be' || $video_link['host'] == 'youtu.be' ){
$video = substr(@parse_url($video_url, PHP_URL_PATH), 1);
$video_output ='<iframe width="'.$width.'" height="'.$height.'" src="'.$protocol.'://www.youtube.com/embed/'.$video.'?rel=0&wmode=opaque" frameborder="0" allowfullscreen></iframe>';
}elseif( $video_link['host'] == 'www.vimeo.com' || $video_link['host'] == 'vimeo.com' ){
$video = (int) substr(@parse_url($video_url, PHP_URL_PATH), 1);
$video_output='<iframe src="'.$protocol.'://player.vimeo.com/video/'.$video.'?wmode=opaque" width="'.$width.'" height="'.$height.'" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
}
elseif( $video_link['host'] == 'www.dailymotion.com' || $video_link['host'] == 'dailymotion.com' ){
$video = substr(@parse_url($video_url, PHP_URL_PATH), 7);
$video_id = strtok($video, '_');
$video_output='<iframe frameborder="0" width="'.$width.'" height="'.$height.'" src="'.$protocol.'://www.dailymotion.com/embed/video/'.$video_id.'"></iframe>';
}
}
}
elseif( !empty( $get_meta["tie_embed_code"][0] ) ){
$embed_code = $get_meta["tie_embed_code"][0];
$video_output = htmlspecialchars_decode( $embed_code);
}
elseif( !empty( $get_meta["tie_video_self"][0] ) ){
$video_self = $get_meta["tie_video_self"][0];
$video_output = do_shortcode( '[video width="1280" height="720" mp4="'.$get_meta["tie_video_self"][0].'"][/video]' );
}
if( !empty($video_output) ) echo $video_output; ?>
<?php
}
/*-----------------------------------------------------------------------------------*/
# Post Video embed URL
/*-----------------------------------------------------------------------------------*/
function tie_video_embed(){
global $post;
$get_meta = get_post_custom($post->ID);
if( !empty( $get_meta["tie_video_url"][0] ) ){
$video_output = tie_get_video_embed( $get_meta["tie_video_url"][0] );
}
if( !empty($video_output) ) return $video_output;
else false; ?>
<?php
}
/*-----------------------------------------------------------------------------------*/
# Get Video embed URL
/*-----------------------------------------------------------------------------------*/
function tie_get_video_embed( $video_url ){
$protocol = is_ssl() ? 'https' : 'http';
$video_link = @parse_url($video_url);
if ( $video_link['host'] == 'www.youtube.com' || $video_link['host'] == 'youtube.com' ) {
parse_str( @parse_url( $video_url, PHP_URL_QUERY ), $my_array_of_vars );
$video = $my_array_of_vars['v'] ;
$video_output = $protocol.'://www.youtube.com/embed/'.$video.'?rel=0&wmode=opaque&autohide=1&border=0&egm=0&showinfo=0';
}
elseif( $video_link['host'] == 'www.youtu.be' || $video_link['host'] == 'youtu.be' ){
$video = substr(@parse_url($video_url, PHP_URL_PATH), 1);
$video_output = $protocol.'://www.youtube.com/embed/'.$video.'?rel=0&wmode=opaque&autohide=1&border=0&egm=0&showinfo=0';
}elseif( $video_link['host'] == 'www.vimeo.com' || $video_link['host'] == 'vimeo.com' ){
$video = (int) substr(@parse_url($video_url, PHP_URL_PATH), 1);
$video_output= $protocol.'://player.vimeo.com/video/'.$video.'?wmode=opaque';
}else{
$video_output = $video_url;
}
if( !empty($video_output) ) return $video_output; ?>
<?php
}
/*-----------------------------------------------------------------------------------*/
# Tie Excerpt
/*-----------------------------------------------------------------------------------*/
function tie_content_limit($text, $chars = 120) {
$text = $text." ";
$text = mb_substr( $text , 0 , $chars , 'UTF-8');
$text = $text."...";
return $text;
}
/*-----------------------------------------------------------------------------------*/
# Queue Comments reply js
/*-----------------------------------------------------------------------------------*/
function tie_comments_queue_js(){
if ( (!is_admin()) && is_singular() && comments_open() && get_option('thread_comments') )
wp_enqueue_script( 'comment-reply' );
}
add_action('wp_print_scripts', 'tie_comments_queue_js');
/*-----------------------------------------------------------------------------------*/
# Remove recent comments_ style
/*-----------------------------------------------------------------------------------*/
function tie_remove_recent_comments_style() {
add_filter( 'show_recent_comments_widget_style', '__return_false' );
}
add_action( 'widgets_init', 'tie_remove_recent_comments_style' );
/*-----------------------------------------------------------------------------------*/
# tie Thumb SRC
/*-----------------------------------------------------------------------------------*/
function tie_thumb_src( $size = 'tie-small' ){
global $post;
$image_id = get_post_thumbnail_id($post->ID);
$image_url = wp_get_attachment_image_src($image_id, $size );
return $image_url[0];
}
/*-----------------------------------------------------------------------------------*/
# tie Thumb
/*-----------------------------------------------------------------------------------*/
function tie_slider_img_src( $image_id , $size ){
global $post;
$image_url = wp_get_attachment_image_src($image_id, $size );
return $image_url[0];
}
/*-----------------------------------------------------------------------------------*/
# Add user's social accounts
/*-----------------------------------------------------------------------------------*/
add_action( 'show_user_profile', 'tie_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'tie_show_extra_profile_fields' );
function tie_show_extra_profile_fields( $user ) {
wp_enqueue_media();
?>
<h3><?php _e( 'Cover Image', 'tie' ) ?></h3>
<table class="form-table">
<tr>
<th><label for="author-cover-bg"><?php _e( 'Cover Image', 'tie' ) ?></label></th>
<td>
<?php $author_cover_bg = get_the_author_meta( 'author-cover-bg', $user->ID ) ; ?>
<input id="author-cover-bg" class="img-path" type="text" size="56" style="direction:ltr; text-laign:left" name="author-cover-bg" value="<?php if( !empty( $author_cover_bg ) ) echo esc_attr( $author_cover_bg ); ?>" />
<input id="upload_author-cover-bg_button" type="button" class="button" value="<?php _e( 'Upload', 'tie' ) ?>" />
<div id="author-cover-bg-preview" class="img-preview" <?php if( empty( $author_cover_bg ) ) echo 'style="display:none;"' ?>>
<img src="<?php if( !empty( $author_cover_bg ) ) echo $author_cover_bg ; else echo get_template_directory_uri().'/framework/admin/images/empty.png'; ?>" alt="" />
<a class="del-img" title="Delete"></a>
</div>
<script type='text/javascript'>
jQuery('#author-cover-bg').change(function(){
jQuery('#author-cover-bg-preview').show();
jQuery('#author-cover-bg-preview img').attr("src", jQuery(this).val());
});
tie_set_uploader( 'author-cover-bg' );
</script>
</td>
</tr>
</table>
<h3><?php _e( 'Custom Author widget', 'tie' ) ?></h3>
<table class="form-table">
<tr>
<th><label for="author_widget_content"><?php _e( 'Custom Author widget content', 'tie' ) ?></label></th>
<td>
<textarea name="author_widget_content" id="author_widget_content" rows="5" cols="30"><?php echo esc_attr( get_the_author_meta( 'author_widget_content', $user->ID ) ); ?></textarea>
<br /><span class="description"><?php _e( 'Supports: Text, HTML and Shortcodes.', 'tie' ) ?></span>
</td>
</tr>
</table>
<h3><?php _e( 'Social Networking', 'tie' ) ?></h3>
<table class="form-table">
<tr>
<th><label for="google"><?php _e( 'Google+ URL', 'tie' ) ?></label></th>
<td>
<input type="text" name="google" id="google" value="<?php echo esc_url( get_the_author_meta( 'google', $user->ID ) ); ?>" class="regular-text" /><br />
</td>
</tr>
<tr>
<th><label for="twitter"><?php _e( 'Twitter Username', 'tie' ) ?></label></th>
<td>
<input type="text" name="twitter" id="twitter" value="<?php echo esc_attr( get_the_author_meta( 'twitter', $user->ID ) ); ?>" class="regular-text" /><br />
</td>
</tr>
<tr>
<th><label for="facebook"><?php _e( 'Facebook URL', 'tie' ) ?></label></th>
<td>
<input type="text" name="facebook" id="facebook" value="<?php echo esc_url( get_the_author_meta( 'facebook', $user->ID ) ); ?>" class="regular-text" /><br />
</td>
</tr>
<tr>
<th><label for="linkedin"><?php _e( 'LinkedIn URL', 'tie' ) ?></label></th>
<td>
<input type="text" name="linkedin" id="linkedin" value="<?php echo esc_url( get_the_author_meta( 'linkedin', $user->ID ) ); ?>" class="regular-text" /><br />
</td>
</tr>
<tr>
<th><label for="flickr"><?php _e( 'Flickr URL', 'tie' ) ?></label></th>
<td>
<input type="text" name="flickr" id="flickr" value="<?php echo esc_url( get_the_author_meta( 'flickr', $user->ID ) ); ?>" class="regular-text" /><br />
</td>
</tr>
<tr>
<th><label for="youtube"><?php _e( 'YouTube URL', 'tie' ) ?></label></th>
<td>
<input type="text" name="youtube" id="youtube" value="<?php echo esc_url( get_the_author_meta( 'youtube', $user->ID ) ); ?>" class="regular-text" /><br />
</td>
</tr>
<tr>
<th><label for="pinterest"><?php _e( 'Pinterest URL', 'tie' ) ?></label></th>
<td>
<input type="text" name="pinterest" id="pinterest" value="<?php echo esc_url( get_the_author_meta( 'pinterest', $user->ID ) ); ?>" class="regular-text" /><br />
</td>
</tr>
<tr>
<th><label for="behance"><?php _e( 'Behance URL', 'tie' ) ?></label></th>
<td>
<input type="text" name="behance" id="behance" value="<?php echo esc_url( get_the_author_meta( 'behance', $user->ID ) ); ?>" class="regular-text" /><br />
</td>
</tr>
<tr>
<th><label for="instagram"><?php _e( 'Instagram URL', 'tie' ) ?></label></th>
<td>
<input type="text" name="instagram" id="instagram" value="<?php echo esc_url( get_the_author_meta( 'instagram', $user->ID ) ); ?>" class="regular-text" /><br />
</td>
</tr>
</table>
<?php }
## Save user's social accounts
add_action( 'personal_options_update', 'tie_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'tie_save_extra_profile_fields' );
function tie_save_extra_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) return false;
update_user_meta( $user_id, 'author_widget_content', $_POST['author_widget_content'] );
update_user_meta( $user_id, 'author-cover-bg', $_POST['author-cover-bg'] );
update_user_meta( $user_id, 'google', $_POST['google'] );
update_user_meta( $user_id, 'pinterest', $_POST['pinterest'] );
update_user_meta( $user_id, 'twitter', $_POST['twitter'] );
update_user_meta( $user_id, 'facebook', $_POST['facebook'] );
update_user_meta( $user_id, 'linkedin', $_POST['linkedin'] );
update_user_meta( $user_id, 'flickr', $_POST['flickr'] );
update_user_meta( $user_id, 'youtube', $_POST['youtube'] );
update_user_meta( $user_id, 'instagram', $_POST['instagram'] );
update_user_meta( $user_id, 'behance', $_POST['behance'] );
}
/*-----------------------------------------------------------------------------------*/
# Get Feeds
/*-----------------------------------------------------------------------------------*/
function tie_get_feeds( $feed , $number = 10 ){
include_once(ABSPATH . WPINC . '/feed.php');
$rss = @fetch_feed( $feed );
if (!is_wp_error( $rss ) ){
$maxitems = $rss->get_item_quantity($number);
$rss_items = $rss->get_items(0, $maxitems);
}
if ( empty( $maxitems ) ) {
$out = "<ul><li>". __( 'No items.', 'tie' )."</li></ul>";
}else{
$out = "<ul>";
foreach ( $rss_items as $item ) :
$out .= '<li><a target="_blank" href="'. esc_url( $item->get_permalink() ) .'" title="'. __( "Posted ", "tie" ).$item->get_date("j F Y | g:i a").'">'. esc_html( $item->get_title() ) .'</a></li>';
endforeach;
$out .='</ul>';
}
return $out;
}
/*-----------------------------------------------------------------------------------*/
# Tie Wp Footer
/*-----------------------------------------------------------------------------------*/
add_action('wp_footer', 'tie_wp_footer');
function tie_wp_footer() {
if ( tie_get_option('footer_code')) echo htmlspecialchars_decode( stripslashes(tie_get_option('footer_code') ));
//Reading Position Indicator
if ( tie_get_option( 'reading_indicator' ) && is_singular() ) echo '<div id="reading-position-indicator"></div>';
}
/*-----------------------------------------------------------------------------------*/
# News In Picture
/*-----------------------------------------------------------------------------------*/
function tie_last_news_pic($order , $posts_number = 12 , $cats = 1 ){
global $post;
$original_post = $post;
if( $order == 'random')
$args = array(
'posts_per_page' => $posts_number,
'cat' => $cats,
'orderby' => 'rand',
'no_found_rows' => true,
'ignore_sticky_posts' => true
);
else
$args = array(
'posts_per_page' => $posts_number,
'cat' => $cats,
'no_found_rows' => true,
'ignore_sticky_posts' => true
);
$get_posts_query = new WP_Query( $args );
if ( $get_posts_query->have_posts() ):
while ( $get_posts_query->have_posts() ) : $get_posts_query->the_post()?>
<?php if ( function_exists("has_post_thumbnail") && has_post_thumbnail() ) : ?>
<div <?php tie_post_class( 'post-thumbnail' ); ?>>
<a class="ttip" title="<?php the_title();?>" href="<?php the_permalink(); ?>" ><?php the_post_thumbnail( 'tie-small' ); ?><span class="fa overlay-icon"></span></a>
</div><!-- post-thumbnail /-->
<?php endif; ?>
<?php
endwhile;
endif;
$post = $original_post;
wp_reset_query();
}
/*-----------------------------------------------------------------------------------*/
# Get Most Recent posts
/*-----------------------------------------------------------------------------------*/
function tie_last_posts($posts_number = 5 , $thumb = true){
global $post;
$original_post = $post;
$args = array(
'posts_per_page' => $posts_number,
'no_found_rows' => true,
'ignore_sticky_posts' => true
);
$get_posts_query = new WP_Query( $args );
if ( $get_posts_query->have_posts() ):
while ( $get_posts_query->have_posts() ) : $get_posts_query->the_post()?>
<li <?php tie_post_class(); ?>>
<?php if ( function_exists("has_post_thumbnail") && has_post_thumbnail() && $thumb ) : ?>
<div class="post-thumbnail">
<a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_post_thumbnail( 'tie-small' ); ?><span class="fa overlay-icon"></span></a>
</div><!-- post-thumbnail /-->
<?php endif; ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h3>
<?php tie_get_score(); ?> <?php tie_get_time(); ?>
</li>
<?php
endwhile;
endif;
$post = $original_post;
wp_reset_query();
}
/*-----------------------------------------------------------------------------------*/
# Get Most Recent posts from Category
/*-----------------------------------------------------------------------------------*/
function tie_last_posts_cat($posts_number = 5 , $thumb = true , $cats = 1){
global $post;
$original_post = $post;
$args = array(
'posts_per_page' => $posts_number,
'cat' => $cats,
'no_found_rows' => true,
'ignore_sticky_posts' => true
);
$get_posts_query = new WP_Query( $args );
if ( $get_posts_query->have_posts() ):
while ( $get_posts_query->have_posts() ) : $get_posts_query->the_post()?>
<li <?php tie_post_class(); ?>>
<?php if ( function_exists("has_post_thumbnail") && has_post_thumbnail() && $thumb ) : ?>
<div class="post-thumbnail">
<a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_post_thumbnail( 'tie-small' ); ?><span class="fa overlay-icon"></span></a>
</div><!-- post-thumbnail /-->
<?php endif; ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h3>
<?php tie_get_score(); ?> <?php tie_get_time() ?>
</li>
<?php
endwhile;
endif;
$post = $original_post;
wp_reset_query();
}
/*-----------------------------------------------------------------------------------*/
# Get Most Recent posts from Category - Timeline
/*-----------------------------------------------------------------------------------*/
function tie_last_posts_cat_timeline($posts_number = 5 , $cats = 1){
global $post;
$original_post = $post;
$args = array(
'posts_per_page' => $posts_number,
'cat' => $cats,
'no_found_rows' => true,
'ignore_sticky_posts' => true
);
$get_posts_query = new WP_Query( $args );
if ( $get_posts_query->have_posts() ):
while ( $get_posts_query->have_posts() ) : $get_posts_query->the_post()?>
<li>
<a href="<?php the_permalink(); ?>">
<?php tie_get_time() ?>
<h3><?php the_title();?></h3>
</a>
</li>
<?php
endwhile;
endif;
$post = $original_post;
wp_reset_query();
}
/*-----------------------------------------------------------------------------------*/
# Get Most Recent posts from Category with Authors
/*-----------------------------------------------------------------------------------*/
function tie_last_posts_cat_authors($posts_number = 5 , $thumb = true , $cats = 1){
global $post;
$original_post = $post;
$args = array(
'posts_per_page' => $posts_number,
'cat' => $cats,
'no_found_rows' => true,
'ignore_sticky_posts' => true
);
$get_posts_query = new WP_Query( $args );
if ( $get_posts_query->have_posts() ):
while ( $get_posts_query->have_posts() ) : $get_posts_query->the_post()?>
<li>
<?php if ( function_exists("has_post_thumbnail") && has_post_thumbnail() && $thumb ) : ?>
<div class="post-thumbnail">
<a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) )?>" title=""><?php echo get_avatar( get_the_author_meta( 'user_email' ), apply_filters( 'MFW_author_bio_avatar_size', 50 ) ); ?></a>
</div><!-- post-thumbnail /-->
<?php endif; ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h3>
<strong><a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) )?>" title=""><?php echo get_the_author() ?> </a></strong>
</li>
<?php
endwhile;
endif;
$post = $original_post;
wp_reset_query();
}
/*-----------------------------------------------------------------------------------*/
# Get Random posts
/*-----------------------------------------------------------------------------------*/
function tie_random_posts($posts_number = 5 , $thumb = true){
global $post;
$original_post = $post;
$args = array(
'posts_per_page' => $posts_number,
'orderby' => 'rand',
'no_found_rows' => true,
'ignore_sticky_posts' => true
);
$get_posts_query = new WP_Query( $args );
if ( $get_posts_query->have_posts() ):
while ( $get_posts_query->have_posts() ) : $get_posts_query->the_post()?>
<li <?php tie_post_class(); ?>>
<?php if ( function_exists("has_post_thumbnail") && has_post_thumbnail() && $thumb ) : ?>
<div class="post-thumbnail">
<a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_post_thumbnail( 'tie-small' ); ?><span class="fa overlay-icon"></span></a>
</div><!-- post-thumbnail /-->
<?php endif; ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php tie_get_score(); ?><?php tie_get_time(); ?>
</li>
<?php
endwhile;
endif;
$post = $original_post;
wp_reset_query();
}
/*-----------------------------------------------------------------------------------*/
# Get Popular posts
/*-----------------------------------------------------------------------------------*/
function tie_popular_posts( $posts_number = 5 , $thumb = true){
global $post;
$original_post = $post;
$args = array(
'orderby' => 'comment_count',
'order' => 'DESC',
'posts_per_page' => $posts_number,
'post_status' => 'publish',
'no_found_rows' => true,
'ignore_sticky_posts' => true
);
$popularposts = new WP_Query( $args );
if ( $popularposts->have_posts() ):
while ( $popularposts->have_posts() ) : $popularposts->the_post()?>
<li <?php tie_post_class(); ?>>
<?php if ( function_exists("has_post_thumbnail") && has_post_thumbnail() && $thumb ) : ?>
<div class="post-thumbnail">
<a href="<?php the_permalink() ?>" title="<?php the_title_attribute( ) ?>" rel="bookmark"><?php the_post_thumbnail( 'tie-small' ); ?><span class="fa overlay-icon"></span></a>
</div><!-- post-thumbnail /-->
<?php endif; ?>
<h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
<?php tie_get_score(); ?> <?php tie_get_time(); ?>
<?php if ( get_comments_number() != 0 ) : ?>
<span class="post-comments post-comments-widget"><i class="fa fa-comments"></i><?php comments_popup_link( '0' , '1' , '%' ); ?></span>
<?php endif; ?>
</li>
<?php
endwhile;
endif;
$post = $original_post;
wp_reset_query();
}
/*-----------------------------------------------------------------------------------*/
# Get Popular posts / Views
/*-----------------------------------------------------------------------------------*/
function tie_most_viewed( $posts_number = 5 , $thumb = true){
global $post;
$original_post = $post;
$args = array(
'orderby' => 'meta_value_num',
'meta_key' => 'tie_views',
'posts_per_page' => $posts_number,
'post_status' => 'publish',
'no_found_rows' => true,
'ignore_sticky_posts' => true
);
$popularposts = new WP_Query( $args );
if ( $popularposts->have_posts() ):
while ( $popularposts->have_posts() ) : $popularposts->the_post()?>
<li <?php tie_post_class(); ?>>
<?php if ( function_exists("has_post_thumbnail") && has_post_thumbnail() && $thumb ) : ?>
<div class="post-thumbnail">
<a href="<?php echo get_permalink( $post->ID ) ?>" title="<?php the_title_attribute() ?>" rel="bookmark"><?php the_post_thumbnail( 'tie-small' ); ?><span class="fa overlay-icon"></span></a>
</div><!-- post-thumbnail /-->
<?php endif; ?>
<h3><a href="<?php echo get_permalink( $post->ID ) ?>"><?php the_title(); ?></a></h3>
<?php tie_get_score(); ?> <?php tie_get_time(); ?>
<?php if( tie_get_option( 'post_views' ) ): ?>
<span class="post-views-widget"><?php echo tie_views(); ?><span>
<?php endif; ?>
</li>
<?php
endwhile;
endif;
$post = $original_post;
wp_reset_query();
}
/*-----------------------------------------------------------------------------------*/
# Get Most commented posts
/*-----------------------------------------------------------------------------------*/
function tie_most_commented($comment_posts = 5 , $avatar_size = 55){
$comments = get_comments('status=approve&number='.$comment_posts);
foreach ($comments as $comment) { ?>
<li>
<div class="post-thumbnail" style="width:<?php echo $avatar_size ?>px">
<?php echo get_avatar( $comment, $avatar_size ); ?>
</div>
<a href="<?php echo get_permalink($comment->comment_post_ID ); ?>#comment-<?php echo $comment->comment_ID; ?>">
<?php echo strip_tags($comment->comment_author); ?>: <?php echo wp_html_excerpt( $comment->comment_content, 80 ); ?>... </a>
</li>
<?php }
}
/*-----------------------------------------------------------------------------------*/
# Get Best Reviews posts
/*-----------------------------------------------------------------------------------*/
function tie_best_reviews_posts( $posts_number = 5 , $thumb = true){
global $post;
$original_post = $post;
$args = array(
'orderby' => 'meta_value_num',
'meta_key' => 'taq_review_score',
'posts_per_page' => $posts_number,
'post_status' => 'publish',
'no_found_rows' => true,
'ignore_sticky_posts' => true
);
$best_views = new WP_Query( $args );
if ( $best_views->have_posts() ):
while ( $best_views->have_posts() ) : $best_views->the_post()?>
<li <?php tie_post_class(); ?>>
<?php if ( function_exists("has_post_thumbnail") && has_post_thumbnail() && $thumb ) : ?>
<div class="post-thumbnail">
<a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_post_thumbnail( 'tie-small' ); ?><span class="fa overlay-icon"></span></a>
</div><!-- post-thumbnail /-->
<?php endif; ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php tie_get_score(); ?> <?php tie_get_time(); ?>
</li>
<?php
endwhile;
endif;
$post = $original_post;
wp_reset_query();
}
/*-----------------------------------------------------------------------------------*/
# Google Map Function
/*-----------------------------------------------------------------------------------*/
function tie_google_maps($src , $width = 610 , $height = 440 , $class="") {
return '<div class="google-map '.$class.'"><iframe width="'.$width.'" height="'.$height.'" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'.$src.'&output=embed"></iframe></div>';
}
/*-----------------------------------------------------------------------------------*/
# Soundcloud Function
/*-----------------------------------------------------------------------------------*/
function tie_soundcloud($url , $autoplay = 'false' ) {
global $post;
$color = $tie_post_color = $cat_id = '';
if( is_singular() ){
$get_meta = get_post_custom($post->ID);
if( !empty( $get_meta["post_color"][0] ) )
$tie_post_color = $get_meta["post_color"][0];
}
if( empty($tie_post_color) ){
if( is_category() ){
$cat_id = get_query_var('cat');
}
elseif( is_single() ){
$category = get_the_category($post->ID);
if( !empty( $category[0]->cat_ID ) )
$cat_id = $category[0]->cat_ID;
}
$tie_cats_options = get_option( 'tie_cats_options' );
if( !empty( $tie_cats_options[ $cat_id ] ) )
$cat_option = $tie_cats_options[ $cat_id ];
if( !empty( $cat_option['cat_color'] ) )
$tie_post_color = $cat_option['cat_color'];
}
if( empty($tie_post_color) && tie_get_option( 'theme_skin' ) && !tie_get_option( 'global_color' ) ) $tie_post_color = tie_get_option( 'theme_skin' );
if( empty($tie_post_color) && tie_get_option( 'global_color' ) ) $tie_post_color = tie_get_option( 'global_color' );
if( !empty( $tie_post_color ) ){
$tie_post_color = str_replace ( '#' , '' , $tie_post_color );
$color = '&color='.$tie_post_color;
}
return '<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url='.$url.$color.'&auto_play='.$autoplay.'&show_artwork=true"></iframe>';
}
/*-----------------------------------------------------------------------------------*/
# Login Form
/*-----------------------------------------------------------------------------------*/
function tie_login_form( $login_only = 0 ) {
global $user_ID, $user_identity, $user_level;
$redirect = site_url();
if ( $user_ID ) : ?>
<?php if( empty( $login_only ) ): ?>
<div id="user-login">
<span class="author-avatar"><?php echo get_avatar( $user_ID, $size = '90'); ?></span>
<p class="welcome-text"><?php _eti( 'Welcome' ) ?> <strong><?php echo $user_identity ?></strong> .</p>
<ul>
<li><a href="<?php echo admin_url() ?>"><?php _eti( 'Dashboard' ) ?> </a></li>
<li><a href="<?php echo admin_url() ?>profile.php"><?php _eti( 'Your Profile' ) ?> </a></li>
<li><a href="<?php echo wp_logout_url($redirect); ?>"><?php _eti( 'Logout' ) ?> </a></li>
</ul>
<div class="clear"></div>
</div>
<?php endif; ?>
<?php else: ?>
<div id="login-form">
<form name="loginform" id="loginform" action="<?php echo esc_url( site_url( 'wp-login.php', 'login_post' ) ) ?>" method="post">
<p id="log-username"><input type="text" name="log" id="log" value="<?php _eti( 'Username' ) ?>" onfocus="if (this.value == '<?php _eti( 'Username' ) ?>') {this.value = '';}" onblur="if (this.value == '') {this.value = '<?php _eti( 'Username' ) ?>';}" size="33" /></p>
<p id="log-pass"><input type="password" name="pwd" id="pwd" value="<?php _eti( 'Password' ) ?>" onfocus="if (this.value == '<?php _eti( 'Password' ) ?>') {this.value = '';}" onblur="if (this.value == '') {this.value = '<?php _eti( 'Password' ) ?>';}" size="33" /></p>
<input type="submit" name="submit" value="<?php _eti( 'Log in' ) ?>" class="login-button" />
<label for="rememberme"><input name="rememberme" id="rememberme" type="checkbox" checked="checked" value="forever" /> <?php _eti( 'Remember Me' ) ?></label>
<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>"/>
</form>
<ul class="login-links">
<?php echo wp_register() ?>
<li><a href="<?php echo wp_lostpassword_url($redirect) ?>"><?php _eti( 'Lost your password?' ) ?></a></li>
</ul>
</div>
<?php endif;
}
/*-----------------------------------------------------------------------------------*/
# OG Meta for posts
/*-----------------------------------------------------------------------------------*/
function tie_og_data() {
global $post ;
if ( function_exists("has_post_thumbnail") && has_post_thumbnail() )
$post_thumb = tie_thumb_src( 'slider' ) ;
else{
$protocol = is_ssl() ? 'https' : 'http';
$get_meta = get_post_custom($post->ID);
if( !empty( $get_meta["tie_video_url"][0] ) ){
$video_url = $get_meta["tie_video_url"][0];
$video_link = @parse_url($video_url);
if ( $video_link['host'] == 'www.youtube.com' || $video_link['host'] == 'youtube.com' ) {
parse_str( @parse_url( $video_url, PHP_URL_QUERY ), $my_array_of_vars );
$video = $my_array_of_vars['v'] ;
$post_thumb = $protocol.'://img.youtube.com/vi/'.$video.'/0.jpg';
}
elseif( $video_link['host'] == 'www.vimeo.com' || $video_link['host'] == 'vimeo.com' ){
$video = (int) substr(@parse_url($video_url, PHP_URL_PATH), 1);
$url = $protocol.'://vimeo.com/api/v2/video/'.$video.'.php';;
$contents = @file_get_contents($url);
$thumb = @unserialize(trim($contents));
$post_thumb = $thumb[0]['thumbnail_large'];
}
}
}
$og_title = strip_shortcodes(strip_tags(( get_the_title() ))) ;
$og_description = htmlspecialchars(strip_tags(strip_shortcodes($post->post_content)));
$og_type = 'article';
if( is_home() || is_front_page() ){
$og_title = get_bloginfo('name');
$og_description = get_bloginfo( 'description' );
$og_type = 'website';
}
?>
<meta property="og:title" content="<?php echo $og_title ?>"/>
<meta property="og:type" content="<?php echo $og_type ?>"/>
<meta property="og:description" content="<?php echo tie_content_limit( $og_description , 100 ) ?>"/>
<meta property="og:url" content="<?php the_permalink(); ?>"/>
<meta property="og:site_name" content="<?php echo get_bloginfo( 'name' ) ?>"/>
<?php
if( !empty($post_thumb) )
echo '<meta property="og:image" content="'. $post_thumb .'" />'."\n";
}
/*-----------------------------------------------------------------------------------*/
# For Empty Widgets Titles
/*-----------------------------------------------------------------------------------*/
function tie_widget_title($title){
if( empty( $title ) )
return ' ';
else return $title;
}
add_filter('widget_title', 'tie_widget_title');
/*-----------------------------------------------------------------------------------*/
# Get the post time
/*-----------------------------------------------------------------------------------*/
function tie_get_time( $return = false ){
global $post ;
if( tie_get_option( 'time_format' ) == 'none' ){
return false;
}elseif( tie_get_option( 'time_format' ) == 'modern' ){
$to = current_time('timestamp'); //time();
$from = get_the_time('U') ;
$diff = (int) abs($to - $from);
if ($diff <= 3600) {
$mins = round($diff / 60);
if ($mins <= 1) {
$mins = 1;
}
$since = sprintf(_n('%s min', '%s mins', $mins), $mins) .' '. __ti( 'ago' );
}
else if (($diff <= 86400) && ($diff > 3600)) {
$hours = round($diff / 3600);
if ($hours <= 1) {
$hours = 1;
}
$since = sprintf(_n('%s hour', '%s hours', $hours), $hours) .' '. __ti( 'ago' );
}
elseif ($diff >= 86400) {
$days = round($diff / 86400);
if ($days <= 1) {
$days = 1;
$since = sprintf(_n('%s day', '%s days', $days), $days) .' '. __ti( 'ago' );
}
elseif( $days > 29){
$since = get_the_time(get_option('date_format'));
}
else{
$since = sprintf(_n('%s day', '%s days', $days), $days) .' '. __ti( 'ago' );
}
}
}else{
$since = get_the_time(get_option('date_format'));
}
$post_time = '<span class="tie-date"><i class="fa fa-clock-o"></i>'.$since.'</span>';
if( $return )
return $post_time;
else
echo $post_time;
}
/*-----------------------------------------------------------------------------------*/
# Custom Classes for body
/*-----------------------------------------------------------------------------------*/
add_filter('body_class','tie_body_custom_class');
function tie_body_custom_class($classes) {
if( tie_get_option('dark_skin') )
$classes[] = 'dark-skin';
if( tie_get_option('lazy_load') )
$classes[] = 'lazy-enabled';
return $classes;
}
/*-----------------------------------------------------------------------------------*/
# Fix Shortcodes
/*-----------------------------------------------------------------------------------*/
function tie_fix_shortcodes($content){
$array = array (
'[raw]' => '',
'[/raw]' => '',
'<p>[raw]' => '',
'[/raw]</p>' => '',
'[/raw]<br />' => '',
'<p>[' => '[',
']</p>' => ']',
']<br />' => ']'
);
$content = strtr($content, $array);
return $content;
}
add_filter('the_content', 'tie_fix_shortcodes');
/*-----------------------------------------------------------------------------------*/
# Check if the current page is wp-login.php or wp-register.php
/*-----------------------------------------------------------------------------------*/
function tie_is_login_page() {
return in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php'));
}
/*-----------------------------------------------------------------------------------*/
# Posts Classes
/*-----------------------------------------------------------------------------------*/
/* function tie_post_format_class($classes) {
global $post;
$post_format = get_post_meta($post->ID, 'tie_post_head', true);
if( !empty($post_format) )
$classes[] = 'tie_'.$post_format;
return $classes;
}
add_filter('post_class', 'tie_post_format_class'); */
function tie_post_class( $classes = false ) {
global $post;
$post_format = get_post_meta($post->ID, 'tie_post_head', true);
if( !empty($post_format) ){
if( !empty($classes) ) $classes .= ' ';
$classes .= 'tie_'.$post_format;
}
if( !empty($classes) )
echo 'class="'.$classes.'"';
}
function tie_get_post_class( $classes = false ) {
global $post;
$post_format = get_post_meta($post->ID, 'tie_post_head', true);
if( !empty($post_format) ){
if( !empty($classes) ) $classes .= ' ';
$classes .= 'tie_'.$post_format;
}
if( !empty($classes) )
return 'class="'.$classes.'"';
}
/*-----------------------------------------------------------------------------------*/
# Languages Switcher
/*-----------------------------------------------------------------------------------*/
function tie_language_selector_flags(){
if( function_exists( 'icl_get_languages' )){
$languages = icl_get_languages('skip_missing=0&orderby=code');
if(!empty($languages)){
echo '<div id="tie_lang_switcher">';
foreach($languages as $l){
if(!$l['active']) echo '<a href="'.$l['url'].'">';
echo '<img src="'.$l['country_flag_url'].'" height="12" alt="'.$l['language_code'].'" width="18" />';
if(!$l['active']) echo '</a>';
}
echo '</div>';
}
}
}
/*-----------------------------------------------------------------------------------*/
# Show dropcap and highlight shortcodes in excerpts
/*-----------------------------------------------------------------------------------*/
function tie_remove_shortcodes($text = '') {
$raw_excerpt = $text;
if ( '' == $text ) {
$text = get_the_content('');
$text = preg_replace( '/(\[(padding)\s?.*?\])/' , '' , $text);
$text = str_replace( array ( '[/padding]', '[dropcap]', '[/dropcap]', '[highlight]', '[/highlight]', '[tie_slideshow]', '[/tie_slideshow]', '[tie_slide]', '[/tie_slide]') ,"",$text);
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$excerpt_length = apply_filters('excerpt_length', 55);
$excerpt_more = apply_filters('excerpt_more', ' ' . '[…]');
$text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
}
return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}
add_filter( 'get_the_excerpt', 'tie_remove_shortcodes', 1);
/*-----------------------------------------------------------------------------------*/
# WP 3.6.0
/*-----------------------------------------------------------------------------------*/
// For old theme versions Video shortcode
function tie_video_fix_shortcodes($content){
$v = '/(\[(video)\s?.*?\])(.+?)(\[(\/video)\])/';
$content = preg_replace( $v , '[embed]$3[/embed]' , $content);
return $content;
}
add_filter('the_content', 'tie_video_fix_shortcodes', 0);
/*-----------------------------------------------------------------------------------*/
# Custom Comments Template
/*-----------------------------------------------------------------------------------*/
function tie_custom_comments( $comment, $args, $depth ) {
$GLOBALS['comment'] = $comment ;
?>
<li id="comment-<?php comment_ID(); ?>">
<div <?php comment_class('comment-wrap'); ?> >
<div class="comment-avatar"><?php echo get_avatar( $comment, 65 ); ?></div>
<div class="comment-content">
<div class="author-comment">
<?php printf( '%s ', sprintf( '<cite class="fn">%s</cite>', get_comment_author_link() ) ); ?>
<div class="comment-meta commentmetadata"><a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>"> <?php printf( __ti( '%1$s at %2$s' ), get_comment_date(), get_comment_time() ); ?></a><?php edit_comment_link( __ti( 'Edit' ), ' ' ); ?></div><!-- .comment-meta .commentmetadata -->
<div class="clear"></div>
</div>
<?php if ( $comment->comment_approved == '0' ) : ?>
<em class="comment-awaiting-moderation"><?php _eti( 'Your comment is awaiting moderation.' ); ?></em>
<br />
<?php endif; ?>
<?php comment_text(); ?>
</div>
<div class="reply"><?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?></div><!-- .reply -->
</div><!-- #comment-## -->
<?php
}
/*-----------------------------------------------------------------------------------*/
# Custom Pings Template
/*-----------------------------------------------------------------------------------*/
function tie_custom_pings($comment, $args, $depth) {
$GLOBALS['comment'] = $comment; ?>
<li class="comment pingback">
<p><?php _eti( 'Pingback:' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __ti( 'Edit' ), ' ' ); ?></p>
<?php
}
/*-----------------------------------------------------------------------------------*/
# TGM ACTIVATION PLUGIN
/*-----------------------------------------------------------------------------------*/
add_action( 'tgmpa_register', 'tie_theme_register_required_plugins' );
function tie_theme_register_required_plugins() {
$plugins = array(
array(
'name' => 'Instagramy',
'slug' => 'instagramy',
'source' => get_template_directory_uri() . '/framework/plugins/instagramy.zip',
'required' => true,
'version' => '',
'force_activation' => false,
'force_deactivation' => true,
'external_url' => '',
),
array(
'name' => 'Taqyeem',
'slug' => 'taqyeem',
'source' => get_template_directory_uri() . '/framework/plugins/taqyeem.zip',
'required' => true,
'version' => '',
'force_activation' => false,
'force_deactivation' => true,
'external_url' => '',
),
array(
'name' => 'Taqyeem - Buttons Addon',
'slug' => 'taqyeem-buttons',
'source' => get_template_directory_uri() . '/framework/plugins/taqyeem-buttons.zip',
'required' => true,
'version' => '',
'force_activation' => false,
'force_deactivation' => true,
'external_url' => '',
),
array(
'name' => 'Taqyeem - Predefined Criteria Addon',
'slug' => 'taqyeem-predefined',
'source' => get_template_directory_uri() . '/framework/plugins/taqyeem-predefined.zip',
'required' => true,
'version' => '',
'force_activation' => false,
'force_deactivation' => true,
'external_url' => '',
),
/*
array(
'name' => 'Animated Gif Resize',
'slug' => 'animated-gif-resize',
'required' => false,
),
*/
array(
'name' => 'Contact Form 7',
'slug' => 'contact-form-7',
'required' => true,
),
array(
'name' => 'WooCommerce',
'slug' => 'woocommerce',
'required' => false,
),
);
$config = array(
'default_path' => '', // Default absolute path to pre-packaged plugins.
//'menu' => 'tie-install-plugins', // Menu slug.
'has_notices' => true, // Show admin notices or not.
'dismissable' => true, // If false, a user cannot dismiss the nag message.
'dismiss_msg' => '', // If 'dismissable' is false, this message will be output at top of nag.
'is_automatic' => false, // Automatically activate plugins after installation or not.
'message' => '', // Message to output right before the plugins table.
'strings' => array(
'page_title' => __( 'Install Required Plugins', 'tie' ),
'menu_title' => __( 'Install Plugins', 'tie' ),
'installing' => __( 'Installing Plugin: %s', 'tie' ), // %s = plugin name.
'oops' => __( 'Something went wrong with the plugin API.', 'tie' ),
'notice_can_install_required' => _n_noop( 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.' ), // %1$s = plugin name(s).
'notice_can_install_recommended' => _n_noop( 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.' ), // %1$s = plugin name(s).
'notice_cannot_install' => _n_noop( 'Sorry, but you do not have the correct permissions to install the %s plugin. Contact the administrator of this site for help on getting the plugin installed.', 'Sorry, but you do not have the correct permissions to install the %s plugins. Contact the administrator of this site for help on getting the plugins installed.' ), // %1$s = plugin name(s).
'notice_can_activate_required' => _n_noop( 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.' ), // %1$s = plugin name(s).
'notice_can_activate_recommended' => _n_noop( 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.' ), // %1$s = plugin name(s).
'notice_cannot_activate' => _n_noop( 'Sorry, but you do not have the correct permissions to activate the %s plugin. Contact the administrator of this site for help on getting the plugin activated.', 'Sorry, but you do not have the correct permissions to activate the %s plugins. Contact the administrator of this site for help on getting the plugins activated.' ), // %1$s = plugin name(s).
'notice_ask_to_update' => _n_noop( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.' ), // %1$s = plugin name(s).
'notice_cannot_update' => _n_noop( 'Sorry, but you do not have the correct permissions to update the %s plugin. Contact the administrator of this site for help on getting the plugin updated.', 'Sorry, but you do not have the correct permissions to update the %s plugins. Contact the administrator of this site for help on getting the plugins updated.' ), // %1$s = plugin name(s).
'install_link' => _n_noop( 'Begin installing plugin', 'Begin installing plugins' ),
'activate_link' => _n_noop( 'Begin activating plugin', 'Begin activating plugins' ),
'return' => __( 'Return to Required Plugins Installer', 'tie' ),
'plugin_activated' => __( 'Plugin activated successfully.', 'tie' ),
'complete' => __( 'All plugins installed and activated successfully. %s', 'tie' ), // %s = dashboard link.
)
);
tgmpa( $plugins, $config );
}
/*-----------------------------------------------------------------------------------*/
# BANNERS
/*-----------------------------------------------------------------------------------*/
function tie_banner( $banner , $before= false , $after = false){
if(tie_get_option( $banner )):
echo $before;
$protocol = is_ssl() ? 'https' : 'http';
if(tie_get_option( $banner.'_img' )):
$target = $nofollow ="";
if( tie_get_option( $banner.'_tab' )) $target='target="_blank"';
if( tie_get_option( $banner.'_nofollow' )) $nofollow='rel="nofollow"'; ?>
<a href="<?php echo tie_get_option( $banner.'_url' ) ?>" title="<?php echo tie_get_option( $banner.'_alt') ?>" <?php echo $target; echo $nofollow ?>>
<img src="<?php echo tie_get_option( $banner.'_img' ) ?>" alt="<?php echo tie_get_option( $banner.'_alt') ?>" />
</a>
<?php elseif( tie_get_option( $banner.'_publisher' ) ): ?>
<script type="text/javascript">
var adWidth = jQuery(document).width();
google_ad_client = "<?php echo tie_get_option( $banner.'_publisher' ) ?>";
<?php if( $banner != 'banner_above' && $banner != 'banner_below' ){ ?>if ( adWidth >= 768 ) {
google_ad_slot = "<?php echo tie_get_option( $banner.'_728' ) ?>";
google_ad_width = 728;
google_ad_height = 90;
} else <?php } ?> if ( adWidth >= 468 ) {
google_ad_slot = "<?php echo tie_get_option( $banner.'_468' ) ?>";
google_ad_width = 468;
google_ad_height = 60;
}else {
google_ad_slot = "<?php echo tie_get_option( $banner.'_300' ) ?>";
google_ad_width = 300;
google_ad_height = 250;
}
</script>
<script type="text/javascript" src="<?php echo $protocol ?>://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<?php elseif(tie_get_option( $banner.'_adsense' )): ?>
<?php echo do_shortcode(htmlspecialchars_decode(tie_get_option( $banner.'_adsense' ))) ?>
<?php
endif;
?>
<?php
echo $after;
endif;
}
/*-----------------------------------------------------------------------------------*/
# Get All Categories IDs
/*-----------------------------------------------------------------------------------*/
function tie_get_all_category_ids(){
$categories = array();
$get_cats = get_terms( 'category' );
if ( ! empty( $get_cats ) && ! is_wp_error( $get_cats ) ){
foreach ( $get_cats as $cat )
$categories[] = $cat->term_id;
}
return $categories;
}
/*-----------------------------------------------------------------------------------*/
# WOOCOMMERCE
/*-----------------------------------------------------------------------------------*/
add_action('woocommerce_before_main_content', 'tie_woocommerce_wrapper_start', 22);
function tie_woocommerce_wrapper_start() {
echo '<div class="post-listing"><div class="post-inner">';
}
add_action('woocommerce_after_main_content', 'tie_woocommerce_wrapper_start2', 11);
function tie_woocommerce_wrapper_start2() {
echo '</div></div>';
}
add_action('woocommerce_before_shop_loop', 'tie_woocommerce_wrapper_start3', 33);
function tie_woocommerce_wrapper_start3() {
echo '<div class="clear"></div>';
}
add_action('woocommerce_before_shop_loop_item_title', 'tie_woocommerce_wrapper_product_img_start', 9);
function tie_woocommerce_wrapper_product_img_start() {
echo '<div class="product-img">';
}
add_action('woocommerce_before_shop_loop_item_title', 'tie_woocommerce_wrapper_product_img_end', 11);
function tie_woocommerce_wrapper_product_img_end() {
echo '</div>';
}
add_filter('woocommerce_single_product_image_html', 'tie_woocommerce_single_product_image_html', 99, 1);
add_filter('woocommerce_single_product_image_thumbnail_html', 'tie_woocommerce_single_product_image_html', 99, 1);
function tie_woocommerce_single_product_image_html($html) {
$html = str_replace('data-rel="prettyPhoto', 'rel="lightbox-enabled', $html);
return $html;
}
/*-----------------------------------------------------------------------------------*/
# Remove Query Strings From Static Resources
/*-----------------------------------------------------------------------------------*/
function tie_remove_query_strings_1( $src ){
$rqs = explode( '?ver', $src );
return $rqs[0];
}
function tie_remove_query_strings_2( $src ){
$rqs = explode( '&ver', $src );
return $rqs[0];
}
if ( !is_admin() ) {
add_filter( 'script_loader_src', 'tie_remove_query_strings_1', 15, 1 );
add_filter( 'style_loader_src', 'tie_remove_query_strings_1', 15, 1 );
add_filter( 'script_loader_src', 'tie_remove_query_strings_2', 15, 1 );
add_filter( 'style_loader_src', 'tie_remove_query_strings_2', 15, 1 );
}
/*-----------------------------------------------------------------------------------*/
# WooCommerce Cart
/*-----------------------------------------------------------------------------------*/
add_filter('add_to_cart_fragments', 'tie_woocommerce_header_add_to_cart_fragment');
function tie_woocommerce_header_add_to_cart_fragment( $fragments ) {
global $woocommerce;
ob_start();
?>
<span class="shooping-count-outer"><?php if( isset( $woocommerce->cart->cart_contents_count ) && ( $woocommerce->cart->cart_contents_count != 0 ) ){ ?><span class="shooping-count"><?php echo $woocommerce->cart->cart_contents_count ?></span><?php } ?><i class="fa fa-shopping-cart"></i></span>
<?php
$fragments['.shooping-count-outer'] = ob_get_clean();
return $fragments;
}
/*-----------------------------------------------------------------------------------*/
# Titles for WordPress before 4.1
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( '_wp_render_title_tag' ) ) :
function tie_slug_render_title() {
?>
<title><?php wp_title( '|', true, 'right' ); ?></title>
<?php
}
add_action( 'wp_head', 'tie_slug_render_title' );
endif;
/*-----------------------------------------------------------------------------------*/
# Sanitizes a title, replacing whitespace and a few other characters with dashes.
/*-----------------------------------------------------------------------------------*/
function tie_sanitize_title( $title ){
$title = strip_tags($title);
$title = preg_replace('/&.+?;/', '', $title);
$title = str_replace('.', '-', $title);
$title = strtolower($title);
$title = preg_replace('/[^%a-z0-9 :-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
/*-----------------------------------------------------------------------------------*/
# Compatibility With Taqyeem Plugin | Change the custom fields names
/*-----------------------------------------------------------------------------------*/
add_action( 'load-post.php', 'tie_update_reviews_info' );
function tie_update_reviews_info( ){
global $post;
$post_id = false ;
if( !empty( $post->ID ) ) $post_id = $post->ID;
elseif( !empty($_GET['post']) ) $post_id = $_GET['post'];
if( !empty( $post_id ) ){
$current_post_data = get_post_meta($post_id);
if( !empty( $current_post_data ) && is_array($current_post_data) )
extract($current_post_data);
// There is no title feature in the theme so we check if one of other fields exists to execute the code one time
if( !empty( $tie_review_position[0] ) && empty( $taq_review_title[0] ) ){
$update_new_title = update_post_meta($post_id, 'taq_review_title' , __( "Review Overview" , "tie" ) );
}
if( !empty( $tie_review_position[0] ) && empty( $taq_review_position[0] ) ){
if( $tie_review_position[0] == 'both' ){
$update_new_position = update_post_meta($post_id, 'taq_review_position' , 'top' );
}else{
$update_new_position = update_post_meta($post_id, 'taq_review_position' , $tie_review_position[0] );
}
if( $update_new_position ) delete_post_meta($post_id, 'tie_review_position');
}
if( !empty( $tie_review_style[0] ) && empty( $taq_review_style[0] ) ){
$update_new_style = update_post_meta($post_id, 'taq_review_style' , $tie_review_style[0] );
if( $update_new_style ) delete_post_meta($post_id, 'tie_review_style');
}
if( !empty( $tie_review_summary[0] ) && empty( $taq_review_summary[0] ) ){
$update_new_summary = update_post_meta($post_id, 'taq_review_summary' , $tie_review_summary[0] );
if( $update_new_summary ) delete_post_meta($post_id, 'tie_review_summary');
}
if( !empty( $tie_review_total[0] ) && empty( $taq_review_total[0] ) ){
$update_new_total = update_post_meta($post_id, 'taq_review_total' , $tie_review_total[0] );
if( $update_new_total ) delete_post_meta($post_id, 'tie_review_total');
}
if( !empty( $tie_review_criteria[0] ) && empty( $taq_review_criteria[0] ) ){
$update_new_criteria = update_post_meta($post_id, 'taq_review_criteria' , unserialize ( $tie_review_criteria[0] ) );
if( $update_new_criteria ) delete_post_meta($post_id, 'tie_review_criteria');
}
if( !empty( $tie_review_score[0] ) && empty( $taq_review_score[0] ) ){
$update_new_score = update_post_meta($post_id, 'taq_review_score' , $tie_review_score[0] );
if( $update_new_score ) delete_post_meta($post_id, 'tie_review_score');
}
}
}
/* Old Review Shortcode */
add_shortcode('review', 'taqyeem_shortcode_review');
?>
|
gpl-2.0
|
unconstruct/bandwidth
|
wp-content/plugins/nextgen-facebook/lib/notices.php
|
4085
|
<?php
/*
License: GPLv3
License URI: http://surniaulula.com/wp-content/plugins/nextgen-facebook/license/gpl.txt
Copyright 2012-2013 - Jean-Sebastien Morisset - http://surniaulula.com/
*/
if ( ! defined( 'ABSPATH' ) )
die( 'Sorry, you cannot call this webpage directly.' );
if ( ! class_exists( 'ngfbNotices' ) ) {
class ngfbNotices {
private $ngfb; // ngfbPlugin
private $log = array(
'err' => array(),
'inf' => array(),
'nag' => array(),
);
public function __construct( &$ngfb_plugin ) {
$this->ngfb =& $ngfb_plugin;
$this->ngfb->debug->mark();
add_action( 'admin_notices', array( &$this, 'admin_notices' ) );
}
public function nag( $msg = '', $store = false, $user = true ) { $this->log( 'nag', $msg, $store, $user ); }
public function err( $msg = '', $store = false, $user = true ) { $this->log( 'err', $msg, $store, $user ); }
public function inf( $msg = '', $store = false, $user = true ) { $this->log( 'inf', $msg, $store, $user ); }
public function log( $type, $msg = '', $store = false, $user = true ) {
if ( empty( $msg ) )
return;
if ( $store == true ) {
$user_id = get_current_user_id(); // since wp 3.0
$msg_opt = $this->ngfb->acronym . '_notices_' . $type;
if ( $user == true )
$msg_arr = get_user_option( $msg_opt, $user_id );
else $msg_arr = get_option( $msg_opt );
if ( $msg_arr === false )
$msg_arr = array();
if ( ! in_array( $msg, $msg_arr ) )
$msg_arr[] = $msg;
if ( $user == true )
update_user_option( $user_id, $msg_opt, $msg_arr );
else update_option( $msg_opt, $msg_arr );
} elseif ( ! in_array( $msg, $this->log[$type] ) )
$this->log[$type][] = $msg;
}
public function trunc( $type ) {
$user_id = get_current_user_id(); // since wp 3.0
$msg_opt = $this->ngfb->acronym . '_notices_' . $type;
// delete doesn't always work, so set an empty value first
if ( get_option( $msg_opt ) ) {
update_option( $msg_opt, array() );
delete_option( $msg_opt );
}
if ( get_user_option( $msg_opt, $user_id ) ) {
update_user_option( $user_id, $msg_opt, array() );
delete_user_option( $user_id, $msg_opt );
}
$this->log[$type] = array();
}
public function admin_notices() {
foreach ( array( 'nag', 'err', 'inf' ) as $type ) {
$user_id = get_current_user_id(); // since wp 3.0
$msg_opt = $this->ngfb->acronym . '_notices_' . $type;
$msg_arr = array_merge(
(array) get_option( $msg_opt ),
(array) get_user_option( $msg_opt, $user_id ),
$this->log[$type]
);
$this->trunc( $type );
if ( ! empty( $msg_arr ) ) {
if ( $type == 'nag' ) {
echo '
<style type="text/css">
.ngfb-update-nag {
color:#333;
background:#eeeeff;
background-image: -webkit-gradient(linear, left bottom, left top, color-stop(7%, #eeeeff), color-stop(77%, #ddddff));
background-image: -webkit-linear-gradient(bottom, #eeeeff 7%, #ddddff 77%);
background-image: -moz-linear-gradient(bottom, #eeeeff 7%, #ddddff 77%);
background-image: -o-linear-gradient(bottom, #eeeeff 7%, #ddddff 77%);
background-image: linear-gradient(to top, #eeeeff 7%, #ddddff 77%);
border:1px dashed #ccc;
padding:10px 40px 10px 40px;
overflow:hidden;
line-height:1.4em;
}
.ngfb-update-nag p {
margin:10px 0 10px 0;
}
</style>';
}
foreach ( $msg_arr as $msg ) {
if ( ! empty( $msg ) )
switch ( $type ) {
case 'nag' :
echo '<div class="update-nag ngfb-update-nag">', $msg, '</div>', "\n";
break;
case 'err' :
echo '<div class="error"><div style="float:left;"><p><b>',
$this->ngfb->acronym_uc, ' Warning</b> :</p></div><p>', $msg, '</p></div>', "\n";
break;
case 'inf' :
echo '<div class="updated fade"><div style="float:left;"><p><b>',
$this->ngfb->acronym_uc, ' Info</b> :</p></div><p>', $msg, '</p></div>', "\n";
break;
}
}
}
}
}
}
}
?>
|
gpl-2.0
|
h3xstream/Benchmark
|
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01968.java
|
3010
|
/**
* OWASP Benchmark Project v1.2
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>.
*
* The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Nick Sanidas
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(value="/sqli-04/BenchmarkTest01968")
public class BenchmarkTest01968 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String param = "";
if (request.getHeader("BenchmarkTest01968") != null) {
param = request.getHeader("BenchmarkTest01968");
}
// URL Decode the header value since req.getHeader() doesn't. Unlike req.getParameter().
param = java.net.URLDecoder.decode(param, "UTF-8");
String bar = doSomething(request, param);
try {
String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='" + bar + "'";
org.owasp.benchmark.helpers.DatabaseHelper.JDBCtemplate.batchUpdate(sql);
response.getWriter().println(
"No results can be displayed for query: " + org.owasp.esapi.ESAPI.encoder().encodeForHTML(sql) + "<br>"
+ " because the Spring batchUpdate method doesn't return results."
);
} catch (org.springframework.dao.DataAccessException e) {
if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
response.getWriter().println(
"Error processing request."
);
}
else throw new ServletException(e);
}
} // end doPost
private static String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {
String bar = "alsosafe";
if (param != null) {
java.util.List<String> valuesList = new java.util.ArrayList<String>( );
valuesList.add("safe");
valuesList.add( param );
valuesList.add( "moresafe" );
valuesList.remove(0); // remove the 1st safe value
bar = valuesList.get(1); // get the last 'safe' value
}
return bar;
}
}
|
gpl-2.0
|
jcortes/workportal-inbox
|
inbox.js
|
2154
|
viewsModule.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'InboxCtrl',
templateUrl: 'inbox.html'
});
});
viewsModule.controller('InboxCtrl', function($rootScope, $scope, $modal, $location, $firebase, Activities, fbURL, workingDays) {
// Definicion de Variables
$scope.alerts = []; // array of alert message objects.
$scope.activities = Activities;
// Cierra el mensaje de alerta
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
// Modal: se llama con edit(activityId)
$scope.open = function(activityId) {
var activity = this.activity;
var modalInstance = $modal.open({
templateUrl: 'activity-template.html',
controller: $scope.model,
resolve: {
id: function() {
return activityId;
},
days: function(){
return workingDays(new Date(activity.beginDate), new Date(activity.endDate));
}
}
});
};
$scope.model = function($scope, $firebase, fbURL, $modalInstance, Activities, id, days) {
$scope.activity = {};
// array de mensajes de alerta
$scope.alerts = [];
$scope.designations = [
{name:'Aprobada', value:'A'},
{name:'Rechazada', value:'R'},
{name:'', value:'R'}
];
// Si se hace click en editar entonces el id viene desde $scope.modal->activityId
if (angular.isDefined(id)) {
var activityUrl = fbURL + id;
$scope.activity = $firebase(new Firebase(activityUrl));
$scope.activity.activityId = id;
$scope.days = days;
}
// Se cierra la ventana modal
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
// Guarda la actividad editada
$scope.save = function() {
$scope.activity.$save();
$modalInstance.dismiss('cancel');
};
};
});
|
gpl-2.0
|
carlcnx/EnClass
|
src/CodeGenerator/Settings.Designer.cs
|
6334
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EnClass.CodeGenerator {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("4")]
public int IndentSize {
get {
return ((int)(this["IndentSize"]));
}
set {
this["IndentSize"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool UseTabsForIndents {
get {
return ((bool)(this["UseTabsForIndents"]));
}
set {
this["UseTabsForIndents"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute(@"<?xml version=""1.0"" encoding=""utf-16""?>
<ArrayOfString xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<string>System</string>
<string>System.Collections.Generic</string>
<string>System.Text</string>
</ArrayOfString>")]
public global::System.Collections.Specialized.StringCollection CSharpImportList {
get {
return ((global::System.Collections.Specialized.StringCollection)(this["CSharpImportList"]));
}
set {
this["CSharpImportList"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<ArrayOfString xmlns:xsi=\"http://www.w3." +
"org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <s" +
"tring>java.io.*</string>\r\n <string>java.util.*</string>\r\n</ArrayOfString>")]
public global::System.Collections.Specialized.StringCollection JavaImportList {
get {
return ((global::System.Collections.Specialized.StringCollection)(this["JavaImportList"]));
}
set {
this["JavaImportList"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("VisualStudio2008")]
public global::EnClass.CodeGenerator.SolutionType SolutionType {
get {
return ((global::EnClass.CodeGenerator.SolutionType)(this["SolutionType"]));
}
set {
this["SolutionType"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string DestinationPath {
get {
return ((string)(this["DestinationPath"]));
}
set {
this["DestinationPath"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool UseNotImplementedExceptions {
get {
return ((bool)(this["UseNotImplementedExceptions"]));
}
set {
this["UseNotImplementedExceptions"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("Copyright (c) 2014 All Rights Reserved")]
public string CopyrightHeader {
get {
return ((string)(this["CopyrightHeader"]));
}
set {
this["CopyrightHeader"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string CompagnyName {
get {
return ((string)(this["CompagnyName"]));
}
set {
this["CompagnyName"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string Author {
get {
return ((string)(this["Author"]));
}
set {
this["Author"] = value;
}
}
}
}
|
gpl-2.0
|
openjdk/jdk8u
|
jdk/src/share/classes/sun/nio/ch/AsynchronousServerSocketChannelImpl.java
|
8448
|
/*
* Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.nio.ch;
import java.nio.channels.*;
import java.net.SocketAddress;
import java.net.SocketOption;
import java.net.StandardSocketOptions;
import java.net.InetSocketAddress;
import java.io.FileDescriptor;
import java.io.IOException;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import sun.net.NetHooks;
import sun.net.ExtendedOptionsHelper;
/**
* Base implementation of AsynchronousServerSocketChannel.
*/
abstract class AsynchronousServerSocketChannelImpl
extends AsynchronousServerSocketChannel
implements Cancellable, Groupable
{
protected final FileDescriptor fd;
// the local address to which the channel's socket is bound
protected volatile InetSocketAddress localAddress = null;
// need this lock to set local address
private final Object stateLock = new Object();
// close support
private ReadWriteLock closeLock = new ReentrantReadWriteLock();
private volatile boolean open = true;
// set true when accept operation is cancelled
private volatile boolean acceptKilled;
// set true when exclusive binding is on and SO_REUSEADDR is emulated
private boolean isReuseAddress;
AsynchronousServerSocketChannelImpl(AsynchronousChannelGroupImpl group) {
super(group.provider());
this.fd = Net.serverSocket(true);
}
@Override
public final boolean isOpen() {
return open;
}
/**
* Marks beginning of access to file descriptor/handle
*/
final void begin() throws IOException {
closeLock.readLock().lock();
if (!isOpen())
throw new ClosedChannelException();
}
/**
* Marks end of access to file descriptor/handle
*/
final void end() {
closeLock.readLock().unlock();
}
/**
* Invoked to close file descriptor/handle.
*/
abstract void implClose() throws IOException;
@Override
public final void close() throws IOException {
// synchronize with any threads using file descriptor/handle
closeLock.writeLock().lock();
try {
if (!open)
return; // already closed
open = false;
} finally {
closeLock.writeLock().unlock();
}
implClose();
}
/**
* Invoked by accept to accept connection
*/
abstract Future<AsynchronousSocketChannel>
implAccept(Object attachment,
CompletionHandler<AsynchronousSocketChannel,Object> handler);
@Override
public final Future<AsynchronousSocketChannel> accept() {
return implAccept(null, null);
}
@Override
@SuppressWarnings("unchecked")
public final <A> void accept(A attachment,
CompletionHandler<AsynchronousSocketChannel,? super A> handler)
{
if (handler == null)
throw new NullPointerException("'handler' is null");
implAccept(attachment, (CompletionHandler<AsynchronousSocketChannel,Object>)handler);
}
final boolean isAcceptKilled() {
return acceptKilled;
}
@Override
public final void onCancel(PendingFuture<?,?> task) {
acceptKilled = true;
}
@Override
public final AsynchronousServerSocketChannel bind(SocketAddress local, int backlog)
throws IOException
{
InetSocketAddress isa = (local == null) ? new InetSocketAddress(0) :
Net.checkAddress(local);
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkListen(isa.getPort());
try {
begin();
synchronized (stateLock) {
if (localAddress != null)
throw new AlreadyBoundException();
NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort());
Net.bind(fd, isa.getAddress(), isa.getPort());
Net.listen(fd, backlog < 1 ? 50 : backlog);
localAddress = Net.localAddress(fd);
}
} finally {
end();
}
return this;
}
@Override
public final SocketAddress getLocalAddress() throws IOException {
if (!isOpen())
throw new ClosedChannelException();
return Net.getRevealedLocalAddress(localAddress);
}
@Override
public final <T> AsynchronousServerSocketChannel setOption(SocketOption<T> name,
T value)
throws IOException
{
if (name == null)
throw new NullPointerException();
if (!supportedOptions().contains(name))
throw new UnsupportedOperationException("'" + name + "' not supported");
try {
begin();
if (name == StandardSocketOptions.SO_REUSEADDR &&
Net.useExclusiveBind())
{
// SO_REUSEADDR emulated when using exclusive bind
isReuseAddress = (Boolean)value;
} else {
Net.setSocketOption(fd, Net.UNSPEC, name, value);
}
return this;
} finally {
end();
}
}
@Override
@SuppressWarnings("unchecked")
public final <T> T getOption(SocketOption<T> name) throws IOException {
if (name == null)
throw new NullPointerException();
if (!supportedOptions().contains(name))
throw new UnsupportedOperationException("'" + name + "' not supported");
try {
begin();
if (name == StandardSocketOptions.SO_REUSEADDR &&
Net.useExclusiveBind())
{
// SO_REUSEADDR emulated when using exclusive bind
return (T)Boolean.valueOf(isReuseAddress);
}
return (T) Net.getSocketOption(fd, Net.UNSPEC, name);
} finally {
end();
}
}
private static class DefaultOptionsHolder {
static final Set<SocketOption<?>> defaultOptions = defaultOptions();
private static Set<SocketOption<?>> defaultOptions() {
HashSet<SocketOption<?>> set = new HashSet<SocketOption<?>>(2);
set.add(StandardSocketOptions.SO_RCVBUF);
set.add(StandardSocketOptions.SO_REUSEADDR);
set.addAll(ExtendedOptionsHelper.keepAliveOptions());
return Collections.unmodifiableSet(set);
}
}
@Override
public final Set<SocketOption<?>> supportedOptions() {
return DefaultOptionsHolder.defaultOptions;
}
@Override
public final String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.getClass().getName());
sb.append('[');
if (!isOpen())
sb.append("closed");
else {
if (localAddress == null) {
sb.append("unbound");
} else {
sb.append(Net.getRevealedLocalAddressAsString(localAddress));
}
}
sb.append(']');
return sb.toString();
}
}
|
gpl-2.0
|
avalutions/Avaya-PDS-Silverlight-API
|
Common/Field.cs
|
272
|
using System;
namespace Dialer.Communication.Common
{
public abstract class Field
{
public String Name { get; set; }
public Int32 X { get; set; }
public Int32 Y { get; set; }
public Int32 Width { get; set; }
}
}
|
gpl-2.0
|
solbirn/pyActiveSync
|
pyActiveSync/client/GetItemEstimate.py
|
4933
|
########################################################################
# Copyright (C) 2013 Sol Birnbaum
#
# 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.
########################################################################
from utils.wapxml import wapxmltree, wapxmlnode
class GetItemEstimate:
class getitemestimate_response:
def __init__(self):
self.Status = None
self.CollectionId = None
self.Estimate = None
@staticmethod
def build(synckeys, collection_ids, options):
getitemestimate_xmldoc_req = wapxmltree()
xmlrootgetitemestimatenode = wapxmlnode("GetItemEstimate")
getitemestimate_xmldoc_req.set_root(xmlrootgetitemestimatenode, "getitemestimate")
xmlcollectionsnode = wapxmlnode("Collections", xmlrootgetitemestimatenode)
for collection_id in collection_ids:
xml_Collection_node = wapxmlnode("Collection", xmlcollectionsnode)
try:
xml_gie_airsyncSyncKey_node = wapxmlnode("airsync:SyncKey", xml_Collection_node, synckeys[collection_id])
except KeyError:
xml_gie_airsyncSyncKey_node = wapxmlnode("airsync:SyncKey", xml_Collection_node, "0")
xml_gie_CollectionId_node = wapxmlnode("CollectionId", xml_Collection_node, collection_id)#?
if options[collection_id].has_key("ConversationMode"):
xml_gie_ConverationMode_node = wapxmlnode("airsync:ConversationMode", xml_Collection_node, options[collection_id]["ConversationMode"])#?
xml_gie_airsyncOptions_node = wapxmlnode("airsync:Options", xml_Collection_node)
xml_gie_airsyncClass_node = wapxmlnode("airsync:Class", xml_gie_airsyncOptions_node, options[collection_id]["Class"]) #STR #http://msdn.microsoft.com/en-us/library/gg675489(v=exchg.80).aspx
if options[collection_id].has_key("FilterType"):
xml_gie_airsyncFilterType_node = wapxmlnode("airsync:FilterType", xml_gie_airsyncOptions_node, options[collection_id]["FilterType"]) #INT #http://msdn.microsoft.com/en-us/library/gg663562(v=exchg.80).aspx
if options[collection_id].has_key("MaxItems"):
xml_gie_airsyncMaxItems_node = wapxmlnode("airsync:MaxItems", xml_gie_airsyncMaxItems_node, options[collection_id]["MaxItems"]) #OPTIONAL #INT #http://msdn.microsoft.com/en-us/library/gg675531(v=exchg.80).aspx
return getitemestimate_xmldoc_req
@staticmethod
def parse(wapxml):
namespace = "getitemestimate"
root_tag = "GetItemEstimate"
root_element = wapxml.get_root()
if root_element.get_xmlns() != namespace:
raise AttributeError("Xmlns '%s' submitted to '%s' parser. Should be '%s'." % (root_element.get_xmlns(), root_tag, namespace))
if root_element.tag != root_tag:
raise AttributeError("Root tag '%s' submitted to '%s' parser. Should be '%s'." % (root_element.tag, root_tag, root_tag))
getitemestimate_getitemestimate_children = root_element.get_children()
#getitemestimate_responses = getitemestimate_getitemestimate_children.get_children()
responses = []
for getitemestimate_response_child in getitemestimate_getitemestimate_children:
response = GetItemEstimate.getitemestimate_response()
if getitemestimate_response_child.tag is "Status":
response.Status = getitemestimate_response_child.text
for element in getitemestimate_response_child:
if element.tag is "Status":
response.Status = element.text
elif element.tag == "Collection":
getitemestimate_collection_children = element.get_children()
collection_id = 0
estimate = 0
for collection_child in getitemestimate_collection_children:
if collection_child.tag == "CollectionId":
response.CollectionId = collection_child.text
elif collection_child.tag == "Estimate":
response.Estimate = collection_child.text
responses.append(response)
return responses
|
gpl-2.0
|
gadawg81/NodeJS-Project
|
MySite/app.js
|
583
|
/*
* Module dependencies
*/
var express = require('express')
, stylus = require('stylus')
, nib = require('nib')
var app = express()
function compile(str, path) {
return stylus(str)
.set('filename', path)
.use(nib())
}
app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.logger('dev'))
app.use(stylus.middleware(
{ src: __dirname + '/public'
, compile: compile
}
))
app.use(express.static(__dirname + '/public'))
app.get('/', function (req, res) {
res.end('Hi there!')
})
app.listen(3000)
|
gpl-2.0
|
kunj1988/Magento2
|
app/code/Magento/Sales/Model/ResourceModel/Metadata.php
|
1307
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Model\ResourceModel;
/**
* Class Metadata
*/
class Metadata
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
/**
* @var string
*/
protected $resourceClassName;
/**
* @var string
*/
protected $modelClassName;
/**
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @param string $resourceClassName
* @param string $modelClassName
*/
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
$resourceClassName,
$modelClassName
) {
$this->objectManager = $objectManager;
$this->resourceClassName = $resourceClassName;
$this->modelClassName = $modelClassName;
}
/**
* @return \Magento\Framework\Model\ResourceModel\Db\AbstractDb
*/
public function getMapper()
{
return $this->objectManager->get($this->resourceClassName);
}
/**
* @return \Magento\Framework\Api\ExtensibleDataInterface
*/
public function getNewInstance()
{
return $this->objectManager->create($this->modelClassName);
}
}
|
gpl-2.0
|
melchor629/Java-GLEngine
|
src/main/java/org/melchor629/engine/loaders/collada/Polylist.java
|
2586
|
package org.melchor629.engine.loaders.collada;
import java.util.ArrayList;
import org.w3c.dom.Element;
/**
*
* @author melchor9000
*/
public class Polylist {
public String material;
public int count;
public java.nio.IntBuffer vcount, p;
public ArrayList<Input> inputs;
public Polylist(Element pl) {
material = pl.getAttribute("material");
count = Integer.parseInt(pl.getAttribute("count"));
inputs = new ArrayList<>();
org.w3c.dom.NodeList nl = pl.getElementsByTagName("input");
for(int i = 0; i < nl.getLength(); i++) {
Element input = (Element) nl.item(i);
Input in = new Input(input);
inputs.add(in);
}
vcount = org.melchor629.engine.utils.BufferUtils.createIntBuffer(count);
String t = pl.getElementsByTagName("vcount").item(0).getTextContent();
int pos = 0, newPos, pCount = 0;
for(int i = 0; i < count; i++) {
newPos = t.indexOf(' ', pos + 1);
int val;
if(newPos != -1)
val = Integer.parseInt(t.substring(pos, newPos), 10);
else
val = Integer.parseInt(t.substring(pos), 10);
vcount.put(val);
pCount += val;
pos = newPos + 1;
}
pCount *= inputs.size(); //(vcount[0] -> m caras) * n inputs
p = org.melchor629.engine.utils.BufferUtils.createIntBuffer(pCount);
t = pl.getElementsByTagName("p").item(0).getTextContent();
pos = 0;
for(int i = 0; i < pCount; i++) {
newPos = t.indexOf(' ', pos + 1);
int val;
if(newPos != -1)
val = Integer.parseInt(t.substring(pos, newPos), 10);
else
val = Integer.parseInt(t.substring(pos), 10);
p.put(val);
pos = newPos + 1;
}
vcount.flip();
p.flip();
}
public Input getInput(String semantic) {
for(Input input : inputs)
if(input.semantic.toLowerCase().equals(semantic.toLowerCase()))
return input;
return null;
}
public static class Input {
public String semantic;
public String source;
public int offset;
public Input(Element input) {
semantic = input.getAttribute("semantic");
source = input.getAttribute("source");
String offset_s = input.getAttribute("offset");
offset = offset_s.equals("") ? 0 : Integer.parseInt(offset_s);
}
}
}
|
gpl-2.0
|
tushar-jaiswal/LeetCode
|
Algorithms/24. Swap Nodes in Pairs/SwapNodesInPairs.cs
|
1021
|
//Author: Tushar Jaiswal
//Creation Date: 06/12/2016
/*Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.*/
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode SwapPairs(ListNode head) {
if(head == null || head.next == null)
{ return head; }
ListNode result = head.next;
ListNode curr = head;
ListNode prev = new ListNode(0);
while(curr != null && curr.next != null)
{
ListNode second = curr.next;
curr.next = second.next;
second.next = curr;
prev.next = second;
prev = curr;
curr = curr.next;
}
return result;
}
}
|
gpl-2.0
|
zhwolf/myproject
|
wxm_stock/tor_web.py
|
4867
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#http://qinxuye.me/article/ways-to-continual-sync-browser-and-server/
import os
import random, time
import logging
import Queue
import re,urllib2
from BeautifulSoup import BeautifulSoup
# import Jinja2
from jinja2 import Environment, FileSystemLoader,TemplateNotFound
# import Tornado
import tornado.ioloop
import tornado.web
import tornado.websocket
settings = {
'template_path': 'templates',
"static_path": os.path.join(os.path.dirname(__file__), "static"),
'debug' : True,
#"cookie_secret": "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
#"login_url": "/login",
"xsrf_cookies": False,
}
### global
# Load template file templates/site.html
class TemplateRendering:
"""
A simple class to hold methods for rendering templates.
"""
def render_template(self, template_name, **kwargs):
template_dirs = ["templates"]
if self.settings.get('template_path', ''):
template_dirs.append(
self.settings["template_path"]
)
env = Environment(loader=FileSystemLoader(template_dirs))
try:
template = env.get_template(template_name)
except TemplateNotFound:
raise TemplateNotFound(template_name)
content = template.render(kwargs)
return content
class BaseHandler(tornado.web.RequestHandler, TemplateRendering):
"""
RequestHandler already has a `render()` method. I'm writing another
method `render2()` and keeping the API almost same.
"""
def render2(self, template_name, **kwargs):
"""
This is for making some extra context variables available to
the template
"""
kwargs.update({
#'settings': self.settings,
#'STATIC_URL': self.settings.get('static_url_prefix', '/static/'),
'request': self.request,
'xsrf_token': self.xsrf_token,
'xsrf_form_html': self.xsrf_form_html,
})
content = self.render_template(template_name, **kwargs)
self.write(content)
class index(BaseHandler):
def get(self):
return self.render2("index.html")
class edit(BaseHandler):
def get(self):
return self.render2("edit.html")
class record(BaseHandler):
def get(self):
return self.render2("record.html")
class history(BaseHandler):
def get(self):
return self.render2("history.html")
class LongPolling(BaseHandler):
@tornado.web.asynchronous
def post(self):
self.num = 0
self.get_data(callback=self.on_finish)
def get_data(self, callback):
if self.request.connection.stream.closed():
return
#num = random.randint(1, 100)
self.num = self.num +1
tornado.ioloop.IOLoop.instance().add_timeout(
time.time()+3,
lambda: callback(self.num)
) # 间隔3秒调用回调函数
def on_finish(self, data):
self.write("Server says: %d" % data)
self.finish() # 使用finish方法断开连接
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
for i in xrange(10):
num = random.randint(1, 100)
self.write_message(str(num))
time.sleep(2)
def on_message(self, message):
logging.info("getting message %s", message)
self.write_message("You say:" + message)
def check_origin(self, origin):
return True
class StockStatus(tornado.websocket.WebSocketHandler):
def open(self):
pass
def on_message(self, message):
logging.info("getting message %s", message)
self.write_message("You say:" + message)
def check_origin(self, origin):
return True
def getStatus(self, stocks):
def worker():
while not q.empty():
item = q.get()
q.task_done()
logging.INFO("Thread quit for queue is empty")
q = Queue.Queue()
for item in stocks:
q.put(item)
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
q.join() # block until all tasks are done
# Assign handler to the server root (127.0.0.1:PORT/)
application = tornado.web.Application(
[
("//*", index),
("/edit/*", edit),
("/record/*", record),
("/history/*", history),
("/LongPolling/*", LongPolling),
("/websocket/*", WebSocketHandler),
("/stock/status*", StockStatus),
],
**settings)
if __name__ == "__main__":
application.listen(8080)
tornado.ioloop.IOLoop.instance().start()
|
gpl-2.0
|
koo5/manaplus
|
src/gui/widgets/emoteshortcutcontainer.cpp
|
7354
|
/*
* Extended support for activating emotes
* Copyright (C) 2009 Aethyra Development Team
* Copyright (C) 2011-2013 The ManaPlus Developers
*
* This file is part of The ManaPlus Client.
*
* 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
* 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 "gui/widgets/emoteshortcutcontainer.h"
#include "animatedsprite.h"
#include "client.h"
#include "configuration.h"
#include "emoteshortcut.h"
#include "inputmanager.h"
#include "inventory.h"
#include "item.h"
#include "itemshortcut.h"
#include "keyboardconfig.h"
#include "localplayer.h"
#include "gui/textpopup.h"
#include "gui/viewport.h"
#include "resources/image.h"
#include "utils/dtor.h"
#include <guichan/font.hpp>
#include "debug.h"
static const int MAX_ITEMS = 48;
EmoteShortcutContainer::EmoteShortcutContainer():
ShortcutContainer(),
mEmoteImg(),
mEmotePopup(new TextPopup),
mForegroundColor2(getThemeColor(Theme::TEXT_OUTLINE)),
mEmoteClicked(false),
mEmoteMoved(0)
{
addMouseListener(this);
addWidgetListener(this);
mBackgroundImg = Theme::getImageFromThemeXml(
"item_shortcut_background.xml", "background.xml");
if (mBackgroundImg)
mBackgroundImg->setAlpha(Client::getGuiAlpha());
// Setup emote sprites
for (int i = 0; i <= EmoteDB::getLast(); i++)
{
const EmoteSprite *const sprite = EmoteDB::getSprite(i, true);
if (sprite && sprite->sprite)
mEmoteImg.push_back(sprite);
}
mMaxItems = MAX_ITEMS;
if (mBackgroundImg)
{
mBoxHeight = mBackgroundImg->getHeight();
mBoxWidth = mBackgroundImg->getWidth();
}
else
{
mBoxHeight = 1;
mBoxWidth = 1;
}
mForegroundColor = getThemeColor(Theme::TEXT);
}
EmoteShortcutContainer::~EmoteShortcutContainer()
{
delete mEmotePopup;
if (mBackgroundImg)
{
mBackgroundImg->decRef();
mBackgroundImg = nullptr;
}
}
void EmoteShortcutContainer::setWidget2(const Widget2 *const widget)
{
Widget2::setWidget2(widget);
mForegroundColor = getThemeColor(Theme::TEXT);
mForegroundColor2 = getThemeColor(Theme::TEXT_OUTLINE);
}
void EmoteShortcutContainer::draw(gcn::Graphics *graphics)
{
if (!emoteShortcut)
return;
BLOCK_START("EmoteShortcutContainer::draw")
mAlpha = Client::getGuiAlpha();
if (Client::getGuiAlpha() != mAlpha && mBackgroundImg)
mBackgroundImg->setAlpha(mAlpha);
Graphics *const g = static_cast<Graphics *const>(graphics);
gcn::Font *const font = getFont();
drawBackground(g);
g->setColorAll(mForegroundColor, mForegroundColor2);
for (unsigned i = 0; i < mMaxItems; i++)
{
const int emoteX = (i % mGridWidth) * mBoxWidth;
const int emoteY = (i / mGridWidth) * mBoxHeight;
// Draw emote keyboard shortcut.
const std::string key = inputManager.getKeyValueString(
Input::KEY_EMOTE_1 + i);
font->drawString(g, key, emoteX + 2, emoteY + 2);
}
const unsigned sz = static_cast<unsigned>(mEmoteImg.size());
for (unsigned i = 0; i < mMaxItems; i++)
{
if (i < sz && mEmoteImg[i] && mEmoteImg[i]->sprite)
{
mEmoteImg[i]->sprite->draw(g, (i % mGridWidth) * mBoxWidth + 2,
(i / mGridWidth) * mBoxHeight + 10);
}
}
if (mEmoteMoved && mEmoteMoved < static_cast<unsigned>(sz) + 1
&& mEmoteMoved > 0)
{
// Draw the emote image being dragged by the cursor.
const EmoteSprite *const sprite = mEmoteImg[mEmoteMoved - 1];
if (sprite && sprite->sprite)
{
const AnimatedSprite *const spr = sprite->sprite;
const int tPosX = mCursorPosX - (spr->getWidth() / 2);
const int tPosY = mCursorPosY - (spr->getHeight() / 2);
spr->draw(g, tPosX, tPosY);
}
}
BLOCK_END("EmoteShortcutContainer::draw")
}
void EmoteShortcutContainer::mouseDragged(gcn::MouseEvent &event A_UNUSED)
{
/*
if (!emoteShortcut)
return;
if (event.getButton() == gcn::MouseEvent::LEFT)
{
if (!mEmoteMoved && mEmoteClicked)
{
const int index = getIndexFromGrid(event.getX(), event.getY());
if (index == -1)
return;
// const unsigned char emoteId = emoteShortcut->getEmote(index);
const unsigned char emoteId
= static_cast<unsigned char>(index + 1);
if (emoteId)
{
mEmoteMoved = emoteId;
emoteShortcut->removeEmote(index);
}
}
if (mEmoteMoved)
{
mCursorPosX = event.getX();
mCursorPosY = event.getY();
}
}
*/
}
void EmoteShortcutContainer::mousePressed(gcn::MouseEvent &event)
{
if (!emoteShortcut)
return;
const int index = getIndexFromGrid(event.getX(), event.getY());
if (index == -1)
return;
// Stores the selected emote if there is one.
if (emoteShortcut->isEmoteSelected())
{
emoteShortcut->setEmote(index);
emoteShortcut->setEmoteSelected(0);
}
else if (emoteShortcut->getEmote(index))
{
mEmoteClicked = true;
}
}
void EmoteShortcutContainer::mouseReleased(gcn::MouseEvent &event)
{
if (!emoteShortcut)
return;
if (event.getButton() == gcn::MouseEvent::LEFT)
{
const int index = getIndexFromGrid(event.getX(), event.getY());
if (emoteShortcut->isEmoteSelected())
emoteShortcut->setEmoteSelected(0);
if (index == -1)
{
mEmoteMoved = 0;
return;
}
if (mEmoteMoved)
{
emoteShortcut->setEmotes(index, mEmoteMoved);
mEmoteMoved = 0;
}
else if (emoteShortcut->getEmote(index) && mEmoteClicked)
{
emoteShortcut->useEmote(index + 1);
}
if (mEmoteClicked)
mEmoteClicked = false;
}
}
void EmoteShortcutContainer::mouseMoved(gcn::MouseEvent &event)
{
if (!emoteShortcut || !mEmotePopup)
return;
const int index = getIndexFromGrid(event.getX(), event.getY());
if (index == -1)
return;
mEmotePopup->setVisible(false);
if (static_cast<unsigned>(index) < mEmoteImg.size() && mEmoteImg[index])
{
mEmotePopup->show(viewport->getMouseX(), viewport->getMouseY(),
mEmoteImg[index]->name);
}
}
void EmoteShortcutContainer::mouseExited(gcn::MouseEvent &event A_UNUSED)
{
if (mEmotePopup)
mEmotePopup->setVisible(false);
}
void EmoteShortcutContainer::widgetHidden(const gcn::Event &event A_UNUSED)
{
if (mEmotePopup)
mEmotePopup->setVisible(false);
}
|
gpl-2.0
|
Distrotech/Transmission
|
qt/tracker-model.cc
|
4101
|
/*
* This file Copyright (C) Mnemosyne LLC
*
* 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.
*
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* $Id$
*/
#include <algorithm> // std::sort()
#include <QUrl>
#include "app.h" // MyApp
#include "tracker-model.h"
int
TrackerModel :: rowCount (const QModelIndex& parent) const
{
Q_UNUSED (parent);
return parent.isValid() ? 0 : myRows.size();
}
QVariant
TrackerModel :: data (const QModelIndex& index, int role) const
{
QVariant var;
const int row = index.row ();
if ((0<=row) && (row<myRows.size()))
{
const TrackerInfo& trackerInfo = myRows.at (row);
switch (role)
{
case Qt::DisplayRole:
var = QString (trackerInfo.st.announce);
break;
case Qt::DecorationRole:
var = trackerInfo.st.getFavicon ();
break;
case TrackerRole:
var = qVariantFromValue (trackerInfo);
break;
default:
break;
}
}
return var;
}
/***
****
***/
struct CompareTrackers
{
bool operator() (const TrackerInfo& a, const TrackerInfo& b) const
{
if (a.torrentId != b.torrentId )
return a.torrentId < b.torrentId;
if (a.st.tier != b.st.tier)
return a.st.tier < b.st.tier;
if (a.st.isBackup != b.st.isBackup)
return !a.st.isBackup;
return a.st.announce < b.st.announce;
}
};
void
TrackerModel :: refresh (const TorrentModel& torrentModel, const QSet<int>& ids)
{
// build a list of the TrackerInfos
QVector<TrackerInfo> trackers;
foreach (int id, ids)
{
const Torrent * tor = torrentModel.getTorrentFromId (id);
if (tor != 0)
{
const TrackerStatsList trackerList = tor->trackerStats ();
foreach (const TrackerStat& st, trackerList)
{
TrackerInfo trackerInfo;
trackerInfo.st = st;
trackerInfo.torrentId = id;
trackers.append (trackerInfo);
}
}
}
// sort 'em
CompareTrackers comp;
std::sort (trackers.begin(), trackers.end(), comp);
// merge 'em with the existing list
int old_index = 0;
int new_index = 0;
while ((old_index < myRows.size()) || (new_index < trackers.size()))
{
if (old_index == myRows.size())
{
// add this new row
beginInsertRows (QModelIndex (), old_index, old_index);
myRows.insert (old_index, trackers.at (new_index));
endInsertRows ();
++old_index;
++new_index;
}
else if (new_index == trackers.size())
{
// remove this old row
beginRemoveRows (QModelIndex (), old_index, old_index);
myRows.remove (old_index);
endRemoveRows ();
}
else if (comp (myRows.at(old_index), trackers.at(new_index)))
{
// remove this old row
beginRemoveRows (QModelIndex (), old_index, old_index);
myRows.remove (old_index);
endRemoveRows ();
}
else if (comp (trackers.at(new_index), myRows.at(old_index)))
{
// add this new row
beginInsertRows (QModelIndex (), old_index, old_index);
myRows.insert (old_index, trackers.at (new_index));
endInsertRows ();
++old_index;
++new_index;
}
else // update existing row
{
myRows[old_index].st = trackers.at(new_index).st;
QModelIndex topLeft;
QModelIndex bottomRight;
dataChanged (index(old_index,0), index(old_index,0));
++old_index;
++new_index;
}
}
}
int
TrackerModel :: find (int torrentId, const QString& url) const
{
for (int i=0, n=myRows.size(); i<n; ++i)
{
const TrackerInfo& inf = myRows.at(i);
if ((inf.torrentId == torrentId) && (url == inf.st.announce))
return i;
}
return -1;
}
|
gpl-2.0
|
visi0nary/android_device_blackview_alifep1pro
|
GoodixNewFpSetting/src/com/goodix/fpsetting/TouchIDActivity.java
|
25892
|
/************************************************************************
* <p>Title: TouchIDActivity.java</p>
* <p>Description: </p>
* <p>Copyright (C), 1997-2014, Shenzhen Goodix Technology Co.,Ltd.</p>
* <p>Company: Goodix</p>
* @author peng.hu
* @date 2014-9-23
* @version 1.0
************************************************************************/
package com.goodix.fpsetting;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.gxFP.IVerifyCallback;
import com.goodix.application.FpApplication;
import com.goodix.device.MessageType;
import com.goodix.service.FingerprintHandleService;
import com.goodix.service.FingerprintHandleService.ServiceBinder;
import android.gxFP.FingerprintManager.VerifySession;
import com.goodix.util.AlgoResult;
import com.goodix.util.Fingerprint;
import com.goodix.util.L;
import com.goodix.util.Preferences;
/**
* <p>
* Title: TouchIDActivity
* </p>
* <p>
* Description:
* </p>
*/
public class TouchIDActivity extends Activity {
public static final String TAG = "TouchIDActivity";
public static final String FRINGERPRINT_URI = "fp_uri";
public static final String FRINGERPRINT_INDEX = "fp_uri_index";
/* remote service connected */
private static final int MSG_SERVICE_CONNECTED = 1;
/* fingerprint data is ready */
private static final int MSG_DATA_IS_READY = 2;
/* verify success */
private static final int MSG_VERIFY_SUCCESS = 3;
/* verify failed */
private static final int MSG_VERIFY_FAILED = 4;
private static final int MSG_DEBUG_INFO = 5;
/* fingerprint manager */
//private FingerprintManager mFpManagerService;
/* root container of fingerprint items */
private ViewGroup mContainer = null;
/* Database service */
private FingerprintHandleService mFingerPrintHandleService;
/* is in edit model */
private boolean bEditFingerprint = false;
/* flag that fingerprint item been edited. */
private int mEditorIndex = -1;
/* Message handler */
private MyHandler mHandler;
/* The list of fingerprint */
private ArrayList<Fingerprint> mDataList = null;
private LayoutInflater mInflater;
private HolderEditor mEditorHolder = null;
//private FpManagerServiceConnection mServiceConn;
private FpHandleServiceConnection mHandleServiceConn;
/* fingerprint mananger service session */
private VerifySession mSession = null;
/* Control that showing description or not */
private CheckBox mShowDescription = null;
/* Edit fingerprint information */
private ViewGroup mEditorPanel = null;
/* Add new fingerprint , start register activity */
private Button mInsertButton = null;
/* All fingerprint item views */
private CheckBox mShowMessage = null;
private ArrayList<View> mListViews;
public static TouchIDActivity instance = null;
private LinearLayout mAlgoLog;
private TextView mTopView;
private TextView mBehandView;
private ImageView mImageOne;
private ToggleButton mSwitchLockScreen;
private ViewGroup mInsertPanel = null;
private ViewGroup mTouchIDListPanel = null;
private boolean mIsEnableShow = false;
/*
* private static TextView mLeftLogView; private static TextView
* mRightLogView;
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_touchid);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
instance = this;
mHandler = new MyHandler(this);
updateView();
mListViews = new ArrayList<View>();
Intent intent = new Intent(TouchIDActivity.this,FingerprintHandleService.class);
mHandleServiceConn = new FpHandleServiceConnection();
getApplicationContext().bindService(intent, mHandleServiceConn,Context.BIND_AUTO_CREATE);
this.mInflater = LayoutInflater.from(this);
}
private void updateView() {
TextView titleText = (TextView) findViewById(R.id.fp_description);
titleText.setText(R.string.fingerprint_manager);
Button titleBackBtn = (Button) findViewById(R.id.title_back);
titleBackBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
mAlgoLog = (LinearLayout) findViewById(R.id.touchid_info);
if (Preferences.getEnableEM() == true) {
mAlgoLog.setVisibility(View.VISIBLE);
} else {
mAlgoLog.setVisibility(View.GONE);
}
mTopView = (TextView) findViewById(R.id.top_textview);
mBehandView = (TextView) findViewById(R.id.behand_textview);
mImageOne = (ImageView) findViewById(R.id.image_one);
/* Vanzo:zhangjingzhi on: Wed, 05 Aug 2015 18:34:22 +0800
* SystemUI:cm systemui support
boolean enable = Preferences.getIsEnableFpUnlockscreen(this);
mSwitchLockScreen = (ToggleButton) findViewById(R.id.switch_lockscreen);
mSwitchLockScreen.setChecked(enable);
mSwitchLockScreen.setVisibility(View.GONE);
mSwitchLockScreen
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Preferences.setIsEnableFpUnlockscreen(
TouchIDActivity.this, isChecked);
}
});
*/
// End of Vanzo: zhangjingzhi
mTouchIDListPanel = (ViewGroup) findViewById(R.id.fp_list_space);
mShowDescription = (CheckBox) findViewById(R.id.enable_des);
mShowDescription
.setOnCheckedChangeListener(new OnEnableDesCheckedChangeListener());
boolean bEnable = Preferences.getIsEnableDescription(this);
mShowDescription.setChecked(bEnable);
mShowMessage = (CheckBox)findViewById(R.id.enable_show_mes);
mShowMessage.setOnCheckedChangeListener(new OnEnableDesCheckedChangeListener());
mIsEnableShow = Preferences.getIsEnableShowMessage(this);
mShowMessage.setChecked(bEnable);
}
private class OnEnableDesCheckedChangeListener implements OnCheckedChangeListener {
@Override
public void onCheckedChanged(CompoundButton checkBox, boolean enable) {
switch (checkBox.getId()) {
case R.id.enable_des:
L.d("mShowDescription changed");
Preferences.setIsEnableDescription(TouchIDActivity.this, enable);
// mTouchIDListController.showDescriptions(enable);
showDescriptions(enable);
break;
case R.id.enable_show_mes:
L.d("mShowMessage changed");
Preferences.setIsEnableShowMessage(TouchIDActivity.this, enable);
mIsEnableShow = enable;
showMatchedMessage(mIsEnableShow,0, 0);
break;
default:
break;
}
}
}
private int getFingerViewIndex(int index) {
if (mDataList == null) {
return -1;
}
for (int i = 0; i < this.mDataList.size(); i++) {
if (Integer.parseInt(this.mDataList.get(i).getUri()) == index) {
return i;
}
}
return -1;
}
public void showMatchedMessage(boolean enable,int index,int percent) {
TextView mHolder;
int viewIndex = getFingerViewIndex(index);
if (null != mListViews) {
for (int i = 0; i < mListViews.size(); i++) {
mHolder = (TextView) mListViews.get(i).findViewById(R.id.fp_show_message);
mHolder.setVisibility((enable && viewIndex == i)? View.VISIBLE : View.GONE);
mHolder.setText(String.valueOf(percent));
}
}
}
public void showDescriptions(boolean enable) {
View mHolder;
if (null != mListViews) {
for (int i = 0; i < mListViews.size(); i++) {
mHolder = (View) mListViews.get(i).findViewById(R.id.fp_description);
mHolder.setVisibility(enable ? View.VISIBLE : View.GONE);
}
}
}
@Override
protected void onPause() {
L.d("TouchiIdACTIVITY : onPause");
if(mSession!=null)
mSession.exit();
super.onPause();
}
@Override
protected void onResume() {
L.d("TouchiIdACTIVITY : onResume");
if(mSession!=null)
mSession.enter();
super.onResume();
}
@Override
protected void onRestart() {
L.d("TouchiIdACTIVITY : onRstart");
super.onRestart();
}
@Override
protected void onStop() {
L.d("TouchiIdACTIVITY : onStop");
super.onStop();
}
/**
* <p>
* Title: FpHandleServiceConnection
* </p>
* <p>
* Description:
* </p>
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK: {
return super.onKeyDown(keyCode, event);
}
default:
return super.onKeyDown(keyCode, event);
}
}
@Override
protected void onDestroy() {
Log.v(TAG, "TouchIDActivity : onDestroy");
L.d("TouchIDActivity : onDestroy");
super.onDestroy();
instance = null;
if (null != mSession) {
mSession.exit();
}
/* unbind */
getApplicationContext().unbindService(mHandleServiceConn);
/* start FingerprintHandlerService */
}
@Override
public void onActivityResult(int request_code, int resultcode, Intent intent) {
super.onActivityResult(request_code, resultcode, intent);
if (resultcode == RESULT_OK)
onCaptureActivityResult(request_code, resultcode, intent);
}
public void onCaptureActivityResult(int request_code, int resultcode,
Intent intent) {
if (resultcode == Activity.RESULT_OK) {
Time time = new Time();
time.setToNow();
String name, description, uri;
int mKey = getKey(mDataList);
name = getResources().getString(R.string.finger_name) + mKey;
description = getResources().getString(R.string.finger_description)+" (" + time.hour + ":" + time.minute + ":" + time.second + ")";
uri = intent.getStringExtra(TouchIDActivity.FRINGERPRINT_URI);
Fingerprint fp = new Fingerprint(mKey, name, description, uri);
if (this.mFingerPrintHandleService.insert(fp)) {
this.mDataList.add(fp);
// create view
View item = loadNormalItem(fp);
item.setOnClickListener(new OnFpItemOnClickListener(fp.getKey()));
if (false == Preferences.getIsEnableDescription(this)) {
item.findViewById(R.id.fp_description).setVisibility(
View.GONE);
}
mListViews.add(item);
this.mContainer.addView(item, mListViews.size() - 1);
if (this.mFingerPrintHandleService.getDatabaseSpace() <= 0) {
mInsertButton.setEnabled(false);
mInsertButton.setTextColor(this.getResources().getColor(
R.color.gray_level_three));
}
} else {
Toast.makeText(this,getResources().getString(R.string.addfinger_faied_toast),Toast.LENGTH_SHORT).show();
}
}
}
private class FpHandleServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName arg0, IBinder binder) {
TouchIDActivity.this.mFingerPrintHandleService = ((ServiceBinder) binder).getService();
Log.v(TAG, "FpHandleServiceConnection : onServiceConnected");
mHandler.sendMessage(Message.obtain(mHandler,MSG_SERVICE_CONNECTED, 0, 0));
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
}
}
/**
* @Title: getKey
* @Description:
* @param @return
* @return int
* @throws
*/
private int getKey(ArrayList<Fingerprint> dataList) {
int mKey = 0;
for (int i = 0; i < dataList.size(); i++)
mKey = Math.max(dataList.get(i).getKey(), mKey);
return ++mKey;
}
private void updateFingerprintItemsView() {
if (null == mDataList) {
return;
}
// create mContainer
mContainer = (ViewGroup) this.mInflater.inflate(
R.layout.fingerprint_list_container, null);
mContainer.setLongClickable(true);
mContainer.setLongClickable(true);
// mContainer.setOnTouchListener(new OnTouchContaierListner());
// create items
for (int i = 0; i < mDataList.size(); i++) {
View item = loadNormalItem(mDataList.get(i));
item.setOnClickListener(new OnFpItemOnClickListener(mDataList
.get(i).getKey()));
mListViews.add(item);
mContainer.addView(item);
}
// create add item.
this.mInsertPanel = (ViewGroup) this.mInflater.inflate(
R.layout.fingerprint_list_item_add, null);
mInsertButton = (Button) mInsertPanel.findViewById(R.id.btn_add);
mInsertButton.setOnClickListener(new OnAddBtnOnClickListener());
if (this.mFingerPrintHandleService.getDatabaseSpace() > 0) {
mInsertButton.setEnabled(true);
mInsertButton.setTextColor(getResources().getColor(R.color.apple_blue));
} else {
mInsertButton.setEnabled(false);
mInsertButton.setTextColor(getResources().getColor(R.color.gray_level_three));
}
mContainer.addView(mInsertPanel);
mTouchIDListPanel.addView(mContainer);
showDescriptions(Preferences.getIsEnableFpUnlockscreen(this));
}
private class OnAddBtnOnClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent(TouchIDActivity.this,RegisterActivity.class);
intent.putParcelableArrayListExtra(FRINGERPRINT_INDEX, mDataList);
startActivityForResult(intent, 3);
}
}
private View loadNormalItem(Fingerprint mFp) {
View item = this.mInflater.inflate(
R.layout.fingerprint_list_item_normal, null);
((TextView) item.findViewById(R.id.fp_name)).setText(mFp.getName());
((TextView) item.findViewById(R.id.fp_description)).setText(mFp
.getDescription());
return item;
}
private class OnFpItemOnClickListener implements View.OnClickListener {
int mKey = -1;
public OnFpItemOnClickListener(int key) {
mKey = key;
}
@Override
public void onClick(View v) {
int index = -1;
for (int i = 0; i < mDataList.size(); i++) {
if (mKey == mDataList.get(i).getKey()) {
index = i;
break;
}
}
if (-1 != index) {
editorItem(index);
}
}
}
private void cancelEdit() {
if (mEditorIndex != -1 && bEditFingerprint == true) {
mContainer.removeViewAt(mEditorIndex);
mContainer.addView(mListViews.get(mEditorIndex), mEditorIndex);
mEditorIndex = -1;
bEditFingerprint = false;
}
}
private class HolderEditor {
public EditText name;
public EditText description;
public Button delete;
public Button ok;
public Button cancel;
}
private void editorItem(int index) {
if (true == bEditFingerprint) {
cancelEdit();
return;
}
bEditFingerprint = true;
this.mEditorIndex = index;
if (mEditorPanel == null) {
mEditorPanel = (ViewGroup) this.mInflater.inflate(
R.layout.fingerprint_list_item_editor, null);
mEditorHolder = new HolderEditor();
mEditorHolder.name = (EditText) mEditorPanel
.findViewById(R.id.editor_name);
mEditorHolder.description = (EditText) mEditorPanel
.findViewById(R.id.edit_description);
mEditorHolder.delete = (Button) mEditorPanel
.findViewById(R.id.btn_delete);
mEditorHolder.delete
.setOnClickListener(new OnDeleteBtnOnClickListener());
mEditorHolder.cancel = (Button) mEditorPanel
.findViewById(R.id.btn_cancel);
mEditorHolder.cancel
.setOnClickListener(new OnCancelBtnOnClickListener());
mEditorHolder.ok = (Button) mEditorPanel.findViewById(R.id.btn_ok);
mEditorHolder.ok.setOnClickListener(new OnOkBtnOnClickListener());
// add listener
}
mEditorHolder.name.setText(mDataList.get(index).getName());
mEditorHolder.description
.setText(mDataList.get(index).getDescription());
mContainer.removeViewAt(mEditorIndex);
mContainer.addView(mEditorPanel, mEditorIndex);
startEditAnimation();
}
private void startEditAnimation() {
AlphaAnimation animation = new AlphaAnimation(0, 1);
animation.setDuration(500);
mEditorPanel.startAnimation(animation);
}
private class OnCancelBtnOnClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
cancelEdit();
}
}
private class OnOkBtnOnClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
mDataList.get(mEditorIndex).setName(
mEditorHolder.name.getText().toString());
mDataList.get(mEditorIndex).setDescription(
mEditorHolder.description.getText().toString());
mFingerPrintHandleService.update(mDataList.get(mEditorIndex));
TextView name = (TextView) mListViews.get(mEditorIndex)
.findViewById(R.id.fp_name);
TextView des = (TextView) mListViews.get(mEditorIndex)
.findViewById(R.id.fp_description);
name.setText(mDataList.get(mEditorIndex).getName());
des.setText(mDataList.get(mEditorIndex).getDescription());
mContainer.removeViewAt(mEditorIndex);
mContainer.addView(mListViews.get(mEditorIndex), mEditorIndex);
mEditorIndex = -1;
bEditFingerprint = false;
}
}
private class OnDeleteBtnOnClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
mListViews.remove(mEditorIndex);
mContainer.removeViewAt(mEditorIndex);
mFingerPrintHandleService.delete(mDataList.get(mEditorIndex)
.getKey());
try {
int index = Integer.parseInt(mDataList.get(mEditorIndex)
.getUri());
FpApplication.getInstance().getFpServiceManager().delete(index);
} catch (Exception e) {
e.printStackTrace();
}
mDataList.remove(mEditorIndex);
mInsertButton.setEnabled(true);
mInsertButton.setTextColor(getResources().getColor(
R.color.apple_blue));
mEditorIndex = -1;
bEditFingerprint = false;
}
}
private ArrayList<Fingerprint> loadData(ArrayList<Fingerprint> dataList,
int fpFlag) {
if (null == dataList || (fpFlag >> 16) <= 0) {
return null;
}
ArrayList<Fingerprint> tempList = new ArrayList<Fingerprint>();
int mKey = getKey(dataList);
int count = (fpFlag >> 16 & 0xFFFF);
boolean[] bRegister = new boolean[count];
for (int i = 0; i < count; i++) {
bRegister[i] = (((fpFlag >> i) & 0x1) > 0) ? true : false;
if (bRegister[i] == true) {
boolean bFind = false;
for (int j = 0; j < dataList.size(); j++) {
if (Integer.parseInt(dataList.get(j).getUri()) == i + 1) {
Fingerprint fp = dataList.remove(j);
tempList.add(fp);
bFind = true;
break;
}
}
if (bFind == false) {
Fingerprint fp = new Fingerprint(mKey, "unknown",
"unknown", Integer.toString(i + 1));
mKey++;
tempList.add(fp);
this.mFingerPrintHandleService.insert(fp);
}
}
}
for (int i = 0; i < dataList.size(); i++) {
this.mFingerPrintHandleService.delete(dataList.get(i).getKey());
}
return tempList;
}
private void startInitFingerprintThread() {
//relevant: step 2
new InitFingerprintThread().start();
}
private class InitFingerprintThread extends Thread {
public void run() {
//relevant: step 3
if (null != mFingerPrintHandleService && null != FpApplication.getInstance().getFpServiceManager()) {
int flag = FpApplication.getInstance().getFpServiceManager().query();
ArrayList<Fingerprint> dataList = loadData(mFingerPrintHandleService.query(), flag);
mHandler.sendMessage(Message.obtain(mHandler,MSG_DATA_IS_READY, 0, 0, dataList));
}
}
}
private IVerifyCallback mVerifyCallBack = new IVerifyCallback.Stub() {
@Override
public void handleMessage(int msg, int arg0, int arg1, byte[] data)
throws RemoteException {
Log.v(TAG,String.format("%s , arg0 = %d , arg1 = %d",MessageType.getString(msg), arg0, arg1));
switch (msg) {
case MessageType.MSG_TYPE_RECONGNIZE_SUCCESS:
mHandler.sendMessage(mHandler.obtainMessage(MSG_VERIFY_SUCCESS,
arg0, arg1, data));
break;
case MessageType.MSG_TYPE_RECONGNIZE_FAILED:
mHandler.sendMessage(mHandler.obtainMessage(MSG_VERIFY_FAILED,
arg0, arg1, data));
break;
case MessageType.MSG_TYPE_COMMON_NOTIFY_INFO:
mHandler.sendMessage(mHandler.obtainMessage(MSG_DEBUG_INFO,
arg0, arg1, data));
break;
default:
break;
}
// return false;
}
};
private void unmatchAnimation(View v) {
ScaleAnimation anim;
anim = new ScaleAnimation(1f, 0.995f, 1f, 0.995f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
anim.setRepeatCount(1);
anim.setDuration(300);
anim.setAnimationListener(new unMatchedAnimationListener(v));
v.startAnimation(anim);
}
private class unMatchedAnimationListener implements AnimationListener {
View view = null;
unMatchedAnimationListener(View v) {
this.view = v;
}
@Override
public void onAnimationEnd(Animation animation) {
view.setBackgroundResource(R.drawable.setting_button_left_padding);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
view.setBackgroundResource(R.drawable.touchid_worning_bg);
}
}
private class MatchedAnimationListener implements AnimationListener {
View view = null;
MatchedAnimationListener(View v) {
this.view = v;
}
@Override
public void onAnimationEnd(Animation animation) {
view.setBackgroundColor(0xFFFFFFFF);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
view.setBackgroundColor(0xFFDDDDDD);
}
}
private void showAnimation(View v) {
ScaleAnimation anim_time;
anim_time = new ScaleAnimation(1f, 0.99f, 1f, 0.99f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
// anim_time.setFillAfter(true);
anim_time.setRepeatCount(2);
anim_time.setDuration(300);
anim_time.setAnimationListener(new MatchedAnimationListener(v));
v.startAnimation(anim_time);
}
public void showMatchedAnimation(int index) {
for (int i = 0; i < this.mDataList.size(); i++) {
if (Integer.parseInt(this.mDataList.get(i).getUri()) == index) {
showAnimation(mListViews.get(i));
break;
}
}
}
private int getViewCount() {
if (mListViews != null) {
return mListViews.size();
}
return 0;
}
private static class MyHandler extends Handler {
private WeakReference<TouchIDActivity> mActivityRef;
public MyHandler(TouchIDActivity activity) {
mActivityRef = new WeakReference<TouchIDActivity>(activity);
}
public void handleMessage(Message msg) {
if (mActivityRef.get() == null)
return;
TouchIDActivity activity = (TouchIDActivity) mActivityRef.get();
if (null == activity) {
return;
}
switch (msg.what) {
case MSG_SERVICE_CONNECTED:
if (null != activity.mFingerPrintHandleService
/*&& null != activity.mFpManagerService*/) {
//relevant: step 1
activity.startInitFingerprintThread();
}
break;
case MSG_DATA_IS_READY: {
if (msg.obj instanceof ArrayList) {
activity.mDataList = (ArrayList<Fingerprint>) msg.obj;
/* update view */
activity.updateFingerprintItemsView();
if (null == activity.mSession) {
activity.mSession = FpApplication.getInstance().getFpServiceManager().newVerifySession(activity.mVerifyCallBack);
//relevant: step 4
activity.mSession.enter();
}
}
}
break;
case MSG_VERIFY_SUCCESS:
activity.showMatchedMessage(activity.mIsEnableShow,msg.arg2, msg.arg1);
if (msg.arg2 > 0) {
activity.showMatchedAnimation(msg.arg2);
} else {
activity.unmatchAnimation(activity.mTouchIDListPanel);
}
break;
case MSG_VERIFY_FAILED:
activity.showMatchedMessage(activity.mIsEnableShow,msg.arg2, msg.arg1);
activity.unmatchAnimation(activity.mTouchIDListPanel);
break;
case MSG_DEBUG_INFO:
byte[] data = (byte[]) msg.obj;
if (data != null) {
String str = new String(data);
if (AlgoResult.isFilePath(str)) {
activity.mTopView.setText(AlgoResult.bulidLog(activity,str, AlgoResult.FILTER_RECOGNIZE,activity.getViewCount()));
}
activity.mBehandView.setText(AlgoResult.bulidLog(activity,str, AlgoResult.FILTER_RECOGNIZE,activity.getViewCount()));
int index = str.indexOf("=");
if (-1 != index) {
String fileName = null;
fileName = str.substring(index + 1, str.length() - 1);
File file = new File(fileName);
try {
InputStream in = new FileInputStream(file);
Bitmap map = BitmapFactory.decodeStream(in);
activity.mImageOne.setImageBitmap(map);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
default:
break;
}
}
}
}
|
gpl-2.0
|
ivan-uskov/C-labs
|
lw5/lw5-1/body_hierarchy/stdafx.cpp
|
293
|
// stdafx.cpp : source file that includes just the standard includes
// body_hierarchy.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
|
gpl-2.0
|
drlucaswilkins/newtonfractal
|
NewtonFractal/src/main/scala/com/lucaswilkins/newtonfractals/image.scala
|
3080
|
package com.lucaswilkins.newtonfractals
import java.awt.Component
import java.awt.image.BufferedImage
import java.io.File
import java.util.prefs.Preferences
import javax.imageio.ImageIO
import javax.swing.{JOptionPane, JFileChooser}
import javax.swing.filechooser.FileNameExtensionFilter
/**
* This handles the file dialog and the saving of the image
*/
object image {
val directoryKey = "DefaultSaveDirectory"
/*
* This part is to fairly safely handle setting a default directory
*/
val prefs = Preferences.userRoot.node(getClass().getName)
var _currentDirectory: File = {
val putativeDirectory = prefs.get(directoryKey, System.getProperty("user.home"))
val putativeFile = new File(putativeDirectory)
val existingFile =
if(putativeFile.exists()) {
putativeFile
} else {
new File(System.getProperty("user.home"))
}
if(existingFile.isDirectory) {
existingFile
} else {
existingFile.getParentFile()
}
}
def currentDirectory = _currentDirectory
def currentDirectory_=(file: File): Unit = if(file.exists) {
_currentDirectory = if(file.isDirectory) file else file.getParentFile
prefs.put(directoryKey, file.getAbsolutePath)
}
/*
* File chooser stuff
*/
val fileChooser = new JFileChooser
val filters = (("PNG Image", "png" :: Nil) ::
("JPEG Image", "jpg" :: "jpeg" :: Nil) ::
("Windows Bitmap", "bmp" :: Nil) :: Nil)
.map(x ⇒ new FileNameExtensionFilter(x._1, x._2:_*))
filters.map(fileChooser addChoosableFileFilter _)
fileChooser.setCurrentDirectory(currentDirectory)
/**
* Save a buffered image to file
*
* @param im the buffered image
* @param parent parent window for the file chooser
*/
def saveBufferedImage(im: BufferedImage, parent: Component): Unit = {
var retry = true
case class RetryException(msg: String) extends Exception(msg)
while (retry){
retry = false
val returnValue = fileChooser.showSaveDialog(parent)
if (returnValue == JFileChooser.APPROVE_OPTION) {
val selectedFile = fileChooser.getSelectedFile
currentDirectory = selectedFile
try {
val imType =
filters
.find(_.accept(selectedFile))
.getOrElse(throw RetryException("Unknown image file type."))
.getExtensions
.toList
.apply(0)
writeBufferedImage(im, selectedFile, imType)
} catch {
case msg: Throwable ⇒ {
JOptionPane.showMessageDialog(
parent,
"Write Failed: " + msg.getMessage(),
"Write Failed!",
JOptionPane.ERROR_MESSAGE)
msg match {
case RetryException(_) ⇒ retry = true
case _ ⇒
}
}
}
}
}
}
/*
* Actual writing to file
*/
def writeBufferedImage(im: BufferedImage, file: File, imType: String): Unit = {
ImageIO.write(im, imType, file)
}
}
|
gpl-2.0
|
wpgaijin/practical-project-wrangler
|
includes/classes/class-ppw-project-ajax-search.php
|
4751
|
<?php
/**
* Project AJAX Search
*
* @package PPW
* @subpackage PPW/Includes/Classes
* @since 0.0.1
*/
if( !class_exists( 'PPW_Project_AJAX_Search' ) ) {
class PPW_Project_AJAX_Search {
/**
* Initialize the class
*
* @since 0.0.1
* @uses add_action() wp-includes/plugin.php
*/
public function __construct() {
add_action( 'wp_ajax_ppw_project_search', array( $this, 'search' ) );
add_action( 'wp_ajax_nopriv_ppw_project_search', array( $this, 'search' ) );
} // end __construct
/**
* Results
*
* Return the AJAX results
*
* @since 0.0.1
* @uses add_action() wp-includes/pluggable.php
* @uses get_option() wp-includes/option.php
* @uses get_posts() wp-includes/post.php
* @uses get_post_meta() wp-includes/post.php
* @uses json_encode() wp-includes/compat.php
* @uses the_permalink() wp-includes/link-template.php
* @global obj $wp_query the wordpress query obj
* @return void
*/
public function search() {
global $wpdb;
$projects_group_title = apply_filters( 'ppw_projects_group_title', 'ppw__Listing-group--title' );
$projects_block = apply_filters( 'ppw_projects_block', 'ppw__projects-block' );
$projects_block_title = apply_filters( 'ppw_projects_block_title', 'ppw__project-block--title' );
$projects_block_categories = apply_filters( 'ppw_projects_block_categories', 'ppw__projects-block--categories' );
$projects_block_description = apply_filters( 'ppw_projects_block_description', 'ppw__projects-block--description' );
$projects_block_avatars = apply_filters( 'ppw_projects_block_avatars', 'ppw__projects-block--avatars' );
$projects_block_link = apply_filters( 'ppw_projects_block_link', 'ppw__projects-block--link' );
if( wp_verify_nonce( $_POST['ppw_search_nonce'], 'ppw_project_search_nonce') ) {
$search_query = trim( $_POST['search_string'] );
$options = get_option( PPW_PREFIX . '_options' );
$excerpt_length = $options[PPW_PREFIX . '_options_project_excertp_length'];
if( $search_query ) {
$found_projects = get_posts( array(
'posts_per_page' => 9999,
'post_type' => 'ppw_projects',
's' => $search_query
) );
foreach( $found_projects as $project ) {
$project_description = get_post_meta( $project->ID, PPW_PREFIX . '_projects_desc', true );
$project_category = get_post_meta( $project->ID, PPW_PREFIX . '_projects_category', true );
$project_clients = get_post_meta( $project->ID, PPW_PREFIX . '_projects_client', true );
$project_assigned = get_post_meta( $project->ID, PPW_PREFIX . '_assigned', true );
$this_letter = strtoupper( substr( $project->post_title, 0, 1) );
$curr_letter = '';
$html = 'a';
if( $this_letter != $curr_letter ) {
$curr_letter = $this_letter;
$html .= '<div ' . ppw_get_attribute( 'class', esc_attr( $projects_group_title ) ) . '><h2>' . $this_letter . '</h2></div>';
}
$html .= '<div ' . ppw_get_attribute( 'class', esc_attr( $projects_block ) ) . '> <h2 ' . ppw_get_attribute( 'class', esc_attr( $projects_block_title ) ) . '>';
$html .= $project->post_title;
$html .= '</h2>';
$html .= '<div ' . ppw_get_attribute( 'class', esc_attr( $projects_block_categories ) ) . '>';
$html .= ppw_get_product_categories($project->ID);
$html .= '</div>';
$html .= '<div ' . ppw_get_attribute( 'class', esc_attr( $projects_block_description ) ) . '>';
$html .= wp_trim_words( $project_description, $excerpt_length );
$html .= '</div>';
$html .= '<div ' . ppw_get_attribute( 'class', esc_attr( $projects_block_avatars ) ) . '>';
$html .= ppw_get_project_user_avatar( $project_clients, $project_assigned );
$html .= '</div>';
$html .= '<a href="<?php echo the_permalink(); ?>" ' . ppw_get_attribute( 'class', esc_attr( $projects_block_link ) ) . '></a>';
$html .= '</div>';
}
echo json_encode( array( 'search_results' => $html, 'search_id' => 'found' ) );
} else {
echo json_encode( array( 'search_msg' => __('No Projects Found', PPW_TEXTDOMAIN ), 'search_results' => 'none', 'search_id' => 'fail' ) );
}
}
die();
} // end search
}
} // end PPW_Project_AJAX_Search
|
gpl-2.0
|
st0ne/gr-OE2AIP
|
lib/dstar_header_decoder.cc
|
8862
|
#include "dstar_header_decoder.h"
#include <string.h>
void headerDecode(unsigned char raw_header[660], bool hardDecition, header_t *decodedHeader)
{
/*for ( int i = 0; i < 660; i++){
//cout << hex << (int)raw_header[i] << ", ";
raw_header[i] = raw_header_data[i];
}*/
// Descrambling der empfangenen Symbole
char sr = 0x7f;
for (short i=0; i<660; ++i) {
if ( ((sr>>3)&0x1) ^ (sr&0x1) ){
sr >>= 1;
sr |= 64;
raw_header[i] ^= 1;
} else {
sr >>= 1;
}
}
// Das ist Array fuer die deinterleavte Symbole
char symbole2[660];
for (short i = 0; i < 12; ++i) {
for (short j=0; j < 28; ++j) {
symbole2[i + j*24] = raw_header[i*28 + j];
}
}
for (short i = 12; i < 24; ++i) {
for (short j=0; j < 27; ++j) {
symbole2[i + j*24] = raw_header[i*27 + j + 12];
}
}
if (hardDecition)
{
// Taeusche eine "Soft-Decision"-Dekodierung vor,
// indem "0" --> "0" bzw. "1" --> "31" ersetzt wird.
for (short i=0; i<660; ++i)
symbole2[i] *= 31;
}
// ===============================================================================
// ================ ============================
// ================ Viterbi-Decodierung nach DL3OCK ============================
// ================ ============================
// ===============================================================================
// Eine feinere Quantisierung als mit 5Bit bringt keine nenneswerte
// Verbesserung der Korrekturfaehigkeit des Dekoders.
// Analoge Werte fuer die Referenzsymbole
const char High = 31; // fuer die "5Bit-Quantisierung".
const char Low = 0;
const short KillerMetrik = 400;
// Zustanduebergangsmatrix. Sie wird in der
// vorliegenden Implementierung nicht benoetigt!
// char T[4][2] = {{0, 1},
// {2, 3},
// {0, 1},
// {2, 3}};
// inverse Zustanduebergangsmatrix
char invT[4][3] = {{0, 2, 0},
{0, 2, 1},
{1, 3, 0},
{1, 3, 1}};
// Ausgabematrix fuer den ersten Bit als analoger Wert
char A1[4][2] = {{Low, High},
{High, Low},
{High, Low},
{Low, High}};
// Ausgabematrix fuer den zweiten Bit als analoger Wert
char A2[4][2] = {{Low, High},
{Low, High},
{High, Low},
{High, Low}};
// Metrik
int Metrik[4];
int tempMetrik[4];
// Alternierende Speicherfelder fuer die dekodierten Daten
char Datenfolge_plus [4][330];
char Datenfolge_minus[4][330];
short datenbuffer = 1;
int Metrik_A, Metrik_B;
short j0 = 0;
// Initialisiere die Anfangsmetriken
Metrik[0] = 0;
Metrik[1] = KillerMetrik;
Metrik[2] = KillerMetrik;
Metrik[3] = KillerMetrik;
for (short k=0; k<330; ++k){
register char Symbol1 = symbole2[2*k];
register char Symbol2 = symbole2[2*k+1];
register short temp1, temp2;
for (char S=0; S<4; ++S){
temp1 = Symbol1-A1[ invT[S][0] ][ invT[S][2] ];
temp2 = Symbol2-A2[ invT[S][0] ][ invT[S][2] ];
Metrik_A = Metrik[invT[S][0]] + temp1*temp1 + temp2*temp2;
temp1 = Symbol1-A1[ invT[S][1] ][ invT[S][2] ];
temp2 = Symbol2-A2[ invT[S][1] ][ invT[S][2] ];
Metrik_B = Metrik[invT[S][1]] + temp1*temp1 + temp2*temp2;
if (Metrik_A < Metrik_B){
tempMetrik[S] = Metrik_A;
if (datenbuffer>0) {
for (short j=j0; j<k; ++j){
Datenfolge_plus[S][j] = Datenfolge_minus[invT[S][0]][j];
}
Datenfolge_plus[S][k] = invT[S][2];
} else {
for (short j=j0; j<k; ++j){
Datenfolge_minus[S][j] = Datenfolge_plus[invT[S][0]][j];
}
Datenfolge_minus[S][k] = invT[S][2];
}
} else {
tempMetrik[S] = Metrik_B;
if (datenbuffer>0) {
for (short j=j0; j<k; ++j){
Datenfolge_plus[S][j] = Datenfolge_minus[invT[S][1]][j];
}
Datenfolge_plus[S][k] = invT[S][2];
} else {
for (short j=j0; j<k; ++j){
Datenfolge_minus[S][j] = Datenfolge_plus[invT[S][1]][j];
}
Datenfolge_minus[S][k] = invT[S][2];
}
}
}
// kopiere die temp-Metriken zurueck
for (char i=0; i<4; ++i){
Metrik[i] = tempMetrik[i];
}
// Erfahrungsgemaess stimmen alle Pfade bis auf den letzen relativ
// kurzen Stueck ueberein (s.g. Einschwingphaenomen). Deshalb reicht
// es auch aus, nur die aktuelsten (hier ca. 20) Elemente umzukopieren.
// Mit 30, basierend auf meinen Beobachtungen, ist man auf jeden Fall auf
// der sicheren Seite.
if (k>29){
j0 = k-30;
}
datenbuffer *= -1;
}
// Array fuer Header in Byte-Format
char header[41];
// Konvertiere die Bits in Bytes und speichere die
// empfangene 41 Header-Bytes ab.
for (char i=0; i<41; ++i){
register char zeichen = 0;
if ( Datenfolge_minus[0][i*8 ] ) zeichen += (1<<0);
if ( Datenfolge_minus[0][i*8+1] ) zeichen += (1<<1);
if ( Datenfolge_minus[0][i*8+2] ) zeichen += (1<<2);
if ( Datenfolge_minus[0][i*8+3] ) zeichen += (1<<3);
if ( Datenfolge_minus[0][i*8+4] ) zeichen += (1<<4);
if ( Datenfolge_minus[0][i*8+5] ) zeichen += (1<<5);
if ( Datenfolge_minus[0][i*8+6] ) zeichen += (1<<6);
if ( Datenfolge_minus[0][i*8+7] ) zeichen += (1<<7);
header[i] = zeichen;
}
if ( header[0] & (1<<7) )
decodedHeader->isData = true;
else
decodedHeader->isData = false;
if ( header[0] & (1<<6) )
decodedHeader->viaRepeater = true;
else
decodedHeader->viaRepeater = false;
if ( header[0] & (1<<5) )
decodedHeader->interruption = true;
else
decodedHeader->interruption = false;
if ( header[0] & (1<<4) )
decodedHeader->isControlSignal = true;
else
decodedHeader->isControlSignal = false;
if ( header[0] & (1<<3) )
decodedHeader->emergency = true;
else
decodedHeader->emergency = false;
// Copy Flag1
memcpy(&decodedHeader->flag1, &header[0], 1);
// Copy Flag2
memcpy(&decodedHeader->flag2, &header[1], 1);
// Copy Flag3
memcpy(&decodedHeader->flag3, &header[2], 1);
// Copy RPT2
memcpy(&decodedHeader->destinationRepeater, &header[3], 8);
// Copy RPT1
memcpy(&decodedHeader->departureRepeater, &header[11], 8);
// Copy companion Callsign
memcpy(&decodedHeader->companionCallsign, &header[19], 8);
// Copy own Callsign
memcpy(&decodedHeader->ownCallsign, &header[27], 8);
// Copy own Callsign suffix
memcpy(&decodedHeader->ownCallsignSuffix, &header[35], 4);
// Copy CRC
memcpy(&decodedHeader->checksum, &header[39], 2);
// Berechne CRC vom ganzen Header
//
// Generatorpolynom G(x) = x^16 + x^12 + x^5 + 1
// ohne die fuehrende 1 UND in umgekehrter Reihenfolge
const unsigned short genpoly = 0x8408;
unsigned short crc = 0xffff;
for (char i=0; i<39; ++i){
crc ^= header[i];
for (char j=0; j<8; ++j){
if ( crc & 0x1 ) {
crc >>= 1;
crc ^= genpoly;
} else {
crc >>= 1;
}
}
}
// Beachte die Reihenfolge der CRC-Bytes!!!
// Zunaechst kommt Low- und dann High-Byte
// in "LSB first" Reihenfolge.
crc ^= 0xffff; // invertiere das Ergebnis
decodedHeader->calculatedChecksum = crc;
/*
if ( (0xffff&(header[40]<<8))+(header[39]&0xff) == crc )
cout << "OK" << endl;
else
cout << "NOK" << endl;
*/
}
|
gpl-2.0
|
thangbn/Direct-File-Downloader
|
src/src/com/aelitis/azureus/ui/common/table/impl/TableColumnInfoImpl.java
|
2459
|
/**
* Created on Jan 5, 2009
*
* Copyright 2008 Vuze, Inc. All rights reserved.
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License only.
*
* 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 com.aelitis.azureus.ui.common.table.impl;
import com.aelitis.azureus.ui.common.table.TableColumnCore;
import org.gudy.azureus2.plugins.ui.tables.TableColumnInfo;
/**
* @author TuxPaper
* @created Jan 5, 2009
*
*/
public class TableColumnInfoImpl
implements TableColumnInfo
{
String[] categories;
byte proficiency = TableColumnInfo.PROFICIENCY_INTERMEDIATE;
private final TableColumnCore column;
/**
* @param column
*/
public TableColumnInfoImpl(TableColumnCore column) {
this.column = column;
}
public TableColumnCore getColumn() {
return column;
}
// @see org.gudy.azureus2.ui.swt.views.table.utils.TableColumnInfo#getCategories()
public String[] getCategories() {
return categories;
}
// @see org.gudy.azureus2.ui.swt.views.table.utils.TableColumnInfo#setCategories(java.lang.String[])
public void addCategories(String[] categories) {
if (categories == null || categories.length == 0) {
return;
}
int pos;
String[] newCategories;
if (this.categories == null) {
newCategories = new String[categories.length];
pos = 0;
} else {
newCategories = new String[categories.length + this.categories.length];
pos = this.categories.length;
System.arraycopy(this.categories, 0, newCategories, 0, pos);
}
System.arraycopy(categories, pos, newCategories, 0, categories.length);
this.categories = newCategories;
}
// @see org.gudy.azureus2.ui.swt.views.table.utils.TableColumnInfo#getProficiency()
public byte getProficiency() {
return proficiency;
}
// @see org.gudy.azureus2.ui.swt.views.table.utils.TableColumnInfo#setProficiency(int)
public void setProficiency(byte proficiency) {
this.proficiency = proficiency;
}
}
|
gpl-2.0
|
bvcms/bvcms
|
CmsWeb/Areas/OnlineReg/Models/OnlineReg/ReadWriteXml.cs
|
3800
|
using System;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using CmsData.API;
using CmsWeb.Controllers;
using UtilityExtensions;
namespace CmsWeb.Areas.OnlineReg.Models
{
public partial class OnlineRegModel
{
public void ReadXml(XmlReader reader)
{
var s = reader.ReadOuterXml();
var x = XDocument.Parse(s);
if (x.Root == null) return;
foreach (var e in x.Root.Elements())
{
var name = e.Name.ToString();
switch (name)
{
case "List":
foreach (var ee in e.Elements())
{
OnlineRegPersonModel personModel = Util.DeSerialize<OnlineRegPersonModel>(ee.ToString());
personModel.CurrentDatabase = CurrentDatabase;
List.Add(personModel);
}
break;
case "EventId":
EventId = e.Value.ToInt();
break;
case "History":
foreach (var ee in e.Elements())
_history.Add(ee.Value);
break;
case "CurrentDatabase":
break;
default:
Util.SetPropertyFromText(this, name, e.Value);
break;
}
}
}
public void WriteXml(XmlWriter writer)
{
var w = new APIWriter(writer);
writer.WriteComment(Util.Now.ToString());
foreach (var pi in typeof(OnlineRegModel).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(vv => vv.CanRead && vv.CanWrite))
{
var name = pi.Name;
switch (name)
{
case "List":
w.Start("List");
foreach (var i in List)
Util.Serialize(i, writer);
w.End();
break;
case "History":
w.Start("History");
foreach (var i in History)
w.Add("item", i);
w.End();
break;
case "password":
break;
case "testing":
if (testing == true)
w.Add(pi.Name, testing);
break;
case "FromMobile":
if (FromMobile.HasValue())
w.Add(pi.Name, FromMobile);
else if (MobileAppMenuController.Source.HasValue())
w.Add(pi.Name, MobileAppMenuController.Source);
break;
case "prospect":
if (prospect)
w.Add(pi.Name, prospect);
break;
case "CurrentDatabase":
case "Datum":
break;
case "TranId":
if (TranId.HasValue)
w.Add(pi.Name, TranId);
break;
default:
w.Add(pi.Name, pi.GetValue(this, null));
break;
}
}
}
public XmlSchema GetSchema()
{
throw new NotImplementedException();
}
}
}
|
gpl-2.0
|
davidhalter-archive/ardour
|
libs/ardour/midi_playlist_source.cc
|
5148
|
/*
Copyright (C) 2011 Paul Davis
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifdef WAF_BUILD
#include "libardour-config.h"
#endif
#include <vector>
#include <cstdio>
#include <glibmm/fileutils.h>
#include <glibmm/miscutils.h>
#include "pbd/error.h"
#include "pbd/convert.h"
#include "pbd/enumwriter.h"
#include "ardour/midi_playlist.h"
#include "ardour/midi_playlist_source.h"
#include "ardour/midi_region.h"
#include "ardour/debug.h"
#include "ardour/filename_extensions.h"
#include "ardour/session.h"
#include "ardour/session_directory.h"
#include "ardour/session_playlists.h"
#include "ardour/source_factory.h"
#include "i18n.h"
using namespace std;
using namespace ARDOUR;
using namespace PBD;
/*******************************************************************************
As of May 2011, it appears too complex to support compound regions for MIDI
because of the need to be able to edit the data represented by the region. It
seems that it would be a better idea to render the consituent regions into a
new MIDI file and create a new region based on that, an operation we have been
calling "consolidate"
This code has been in place as a stub in case anyone gets any brilliant ideas
on other ways to approach this issue.
********************************************************************************/
MidiPlaylistSource::MidiPlaylistSource (Session& s, const ID& orig, const std::string& name, boost::shared_ptr<MidiPlaylist> p,
uint32_t chn, frameoffset_t begin, framecnt_t len, Source::Flag flags)
: Source (s, DataType::MIDI, name)
, MidiSource (s, name, flags)
, PlaylistSource (s, orig, name, p, DataType::MIDI, begin, len, flags)
{
}
MidiPlaylistSource::MidiPlaylistSource (Session& s, const XMLNode& node)
: Source (s, node)
, MidiSource (s, node)
, PlaylistSource (s, node)
{
/* PlaylistSources are never writable, renameable, removable or destructive */
_flags = Flag (_flags & ~(Writable|CanRename|Removable|RemovableIfEmpty|RemoveAtDestroy|Destructive));
/* ancestors have already called ::set_state() in their XML-based
constructors.
*/
if (set_state (node, Stateful::loading_state_version, false)) {
throw failed_constructor ();
}
}
MidiPlaylistSource::~MidiPlaylistSource ()
{
}
XMLNode&
MidiPlaylistSource::get_state ()
{
XMLNode& node (MidiSource::get_state ());
/* merge PlaylistSource state */
PlaylistSource::add_state (node);
return node;
}
int
MidiPlaylistSource::set_state (const XMLNode& node, int version)
{
return set_state (node, version, true);
}
int
MidiPlaylistSource::set_state (const XMLNode& node, int version, bool with_descendants)
{
if (with_descendants) {
if (Source::set_state (node, version) ||
MidiSource::set_state (node, version) ||
PlaylistSource::set_state (node, version)) {
return -1;
}
}
return 0;
}
framecnt_t
MidiPlaylistSource::length (framepos_t) const
{
pair<framepos_t,framepos_t> extent = _playlist->get_extent();
return extent.second - extent.first;
}
framepos_t
MidiPlaylistSource::read_unlocked (Evoral::EventSink<framepos_t>& dst,
framepos_t position,
framepos_t start, framecnt_t cnt,
MidiStateTracker* tracker) const
{
boost::shared_ptr<MidiPlaylist> mp = boost::dynamic_pointer_cast<MidiPlaylist> (_playlist);
if (!mp) {
return 0;
}
return mp->read (dst, start, cnt);
}
framepos_t
MidiPlaylistSource::write_unlocked (MidiRingBuffer<framepos_t>& dst,
framepos_t position,
framecnt_t cnt)
{
fatal << string_compose (_("programming error: %1"), "MidiPlaylistSource::write_unlocked() called - should be impossible") << endmsg;
/*NOTREACHED*/
return 0;
}
void
MidiPlaylistSource::append_event_unlocked_beats(const Evoral::Event<Evoral::MusicalTime>& /*ev*/)
{
fatal << string_compose (_("programming error: %1"), "MidiPlaylistSource::append_event_unlocked_beats() called - should be impossible") << endmsg;
/*NOTREACHED*/
}
void
MidiPlaylistSource::append_event_unlocked_frames(const Evoral::Event<framepos_t>& ev, framepos_t source_start)
{
fatal << string_compose (_("programming error: %1"), "MidiPlaylistSource::append_event_unlocked_frames() called - should be impossible") << endmsg;
/*NOTREACHED*/
}
void
MidiPlaylistSource::load_model (bool, bool)
{
/* nothing to do */
}
void
MidiPlaylistSource::destroy_model ()
{
/* nothing to do */
}
void
MidiPlaylistSource::flush_midi ()
{
}
bool
MidiPlaylistSource::empty () const
{
return !_playlist || _playlist->empty();
}
|
gpl-2.0
|
vanilla/vanilla
|
tests/APIv2/ConversationsTest.php
|
10437
|
<?php
/**
* @author Alexandre (DaazKu) Chouinard <alexandre.c@vanillaforums.com>
* @copyright 2009-2019 Vanilla Forums Inc.
* @license GPL-2.0-only
*/
namespace VanillaTests\APIv2;
use Garden\Web\Exception\ForbiddenException;
/**
* Test the /api/v2/conversations endpoints.
*/
class ConversationsTest extends AbstractAPIv2Test {
protected static $userCounter = 0;
protected static $userIDs = [];
protected $baseUrl = '/conversations';
protected $pk = 'conversationID';
/**
* @var bool
*/
protected $moderationAllowed = false;
/**
* {@inheritdoc}
*/
public static function setupBeforeClass(): void {
parent::setupBeforeClass();
self::$userIDs = [];
// Disable flood control checks on the model and make sure that the specific instance is injected into the controllers.
$conversationModel = self::container()->get(\ConversationModel::class)->setFloodControlEnabled(false);
self::container()->setInstance(\ConversationModel::class, $conversationModel);
/**
* @var \Gdn_Session $session
*/
$session = self::container()->get(\Gdn_Session::class);
$session->start(self::$siteInfo['adminUserID'], false, false);
/** @var \UsersApiController $usersAPIController */
$usersAPIController = static::container()->get('UsersAPIController');
for ($i = self::$userCounter; $i < self::$userCounter + 4; $i++) {
$user = $usersAPIController->post([
'name' => "ConversationsUser$i",
'email' => "ConversationsUser$i@example.com",
'password' => "$%#$&ADSFBNYI*&WBV$i",
]);
self::$userIDs[] = $user['userID'];
}
// Disable email sending.
/** @var \Gdn_Configuration $config */
$config = static::container()->get('Config');
$config->set('Garden.Email.Disabled', true, true, false);
$session->end();
}
/**
* Test setup.
*/
public function setUp(): void {
parent::setUp();
$this->moderationAllowed = false;
}
/**
* Test GET /conversations/<id>.
*
* @return array
*/
public function testGet() {
$this->expectModerationException();
$postedConversation = $this->testPost();
$result = $this->api()->get(
"{$this->baseUrl}/{$postedConversation[$this->pk]}"
);
$this->assertEquals(200, $result->getStatusCode());
$conversation = $result->getBody();
// The current model assign dateUpdated as dateLastViewed which makes the test fail.
unset($postedConversation['dateLastViewed'], $conversation['dateLastViewed']);
$name1 = $postedConversation['name'];
$name2 = $conversation['name'];
unset($postedConversation['name'], $conversation['name']);
$this->assertStringEndsWith($name1, $name2);
// Sort participants because they can ge re-ordered, but the results are still correct.
$fn = function ($a, $b) {
return strnatcmp($a['userID'], $b['userID']);
};
usort($postedConversation['participants'], $fn);
usort($conversation['participants'], $fn);
$this->assertRowsEqual($postedConversation, $conversation);
$this->assertCamelCase($result->getBody());
return $result->getBody();
}
/**
* Test GET /conversations/<id>/participants.
*/
public function testGetParticipants() {
$this->expectModerationException();
$conversation = $this->testPostParticipants();
$result = $this->api()->get(
"{$this->baseUrl}/{$conversation[$this->pk]}/participants"
);
$expectedCountParticipant = count(self::$userIDs);
$expectedFirstParticipant = [
'userID' => self::$userIDs[0],
'deleted' => false,
];
$this->assertEquals(200, $result->getStatusCode());
$participants = $result->getBody();
$this->assertTrue(is_array($participants));
$this->assertEquals($expectedCountParticipant, count($participants));
$this->assertRowsEqual($expectedFirstParticipant, $participants[0]);
}
/**
* Test GET /conversations.
*/
public function testIndex() {
$this->expectModerationException();
$nbsInsert = 3;
// Insert a few rows.
$rows = [];
for ($i = 0; $i < $nbsInsert; $i++) {
$rows[] = $this->testPost();
}
// Switch up to the regular member to get the conversations, then switch back to the admin.
$originalUserID = $this->api()->getUserID();
$this->api()->setUserID(self::$userIDs[0]);
$result = $this->api()->get($this->baseUrl, ['insertUserID' => self::$userIDs[0]]);
$this->api()->setUserID($originalUserID);
$this->assertEquals(200, $result->getStatusCode());
$rows = $result->getBody();
// The index should be a proper indexed array.
for ($i = 0; $i < count($rows); $i++) {
$this->assertArrayHasKey($i, $rows);
}
// Now that we're not a user in the conversations, and moderation is disabled, we should see an exception is thrown.
$this->api()->get($this->baseUrl, ['insertUserID' => self::$userIDs[0]]);
}
/**
* @requires function ConversationAPIController::delete
*/
public function testDelete() {
$this->fail(__METHOD__.' needs to be implemented');
}
/**
* Test DELETE /conversations/<id>/leave.
*/
public function testDeleteLeave() {
$conversation = $this->testPost();
// Leave the conversation as the user that created it
$this->api()->getUserID();
$this->api()->setUserID(self::$userIDs[0]);
$result = $this->api()->delete(
"{$this->baseUrl}/{$conversation[$this->pk]}/leave"
);
$this->assertEquals(204, $result->getStatusCode());
// Get the participant count as another user that is part of the conversation.
$this->api()->setUserID(self::$userIDs[1]);
$participantsResult = $this->api()->get(
"{$this->baseUrl}/{$conversation[$this->pk]}/participants",
['status' => 'all']
);
$this->assertEquals(200, $participantsResult->getStatusCode());
$expectedFirstParticipant = [
'userID' => self::$userIDs[0],
'status' => 'deleted',
];
$participants = $participantsResult->getBody();
$this->assertTrue(is_array($participants));
$this->assertRowsEqual($expectedFirstParticipant, $participants[0]);
}
/**
* Test POST /conversations.
*
* @throws \Exception
*
* @return array The conversation.
*/
public function testPost() {
$postData = [
'participantUserIDs' => array_slice(self::$userIDs, 1, 2)
];
$expectedResult = [
'insertUserID' => self::$userIDs[0],
'countParticipants' => 3,
'countMessages' => 0,
'countReadMessages' => 0,
'dateLastViewed' => null,
];
// Create the conversation as the first test user.
$currentUserID = $this->api()->getUserID();
$this->api()->setUserID(self::$userIDs[0]);
$result = $this->api()->post(
$this->baseUrl,
$postData
);
$this->api()->setUserID($currentUserID);
$this->assertEquals(201, $result->getStatusCode());
$body = $result->getBody();
$this->assertTrue(is_int($body[$this->pk]));
$this->assertTrue($body[$this->pk] > 0);
$this->assertRowsEqual($expectedResult, $body);
return $body;
}
/**
* Test POST /conversations/<id>/participants.
*
* @return array The conversation.
*/
public function testPostParticipants() {
$this->expectModerationException();
$conversation = $this->testPost();
$postData = [
'participantUserIDs' => array_slice(self::$userIDs, 3)
];
$result = $this->api()->post(
"{$this->baseUrl}/{$conversation[$this->pk]}/participants",
$postData
);
$this->assertEquals(201, $result->getStatusCode());
$newParticipants = $result->getBody();
$this->assertEquals(count($postData['participantUserIDs']), count($newParticipants));
$updatedConversation = $this->api()->get("{$this->baseUrl}/{$conversation[$this->pk]}")->getBody();
$this->assertEquals(
$conversation['countParticipants'] + count($postData['participantUserIDs']),
$updatedConversation['countParticipants']
);
return $updatedConversation;
}
/**
* Test that output of "body" field is sanitized when user posts a conversation message containing an XSS vector.
*/
public function testXssBodySanitized(): void {
$xssVector = '"><<iframe/><iframe src=javascript:alert(document.domain)></iframe>';
// Create a conversation.
$conversation = $this->testPost();
$this->api()->setUserID($conversation["participants"][0]["userID"]);
// Post a message with XSS in the body.
$this->api()->post("/messages", [
"body" => '"><<iframe/><iframe src=javascript:alert(document.domain)></iframe>',
"conversationID" => $conversation["conversationID"],
"format" => "markdown",
]);
// Retrieve the conversation.
$this->api()->setUserID($conversation["participants"][1]["userID"]);
$updatedConversation = $this->api()->get($this->baseUrl)->getBody()[0];
// Make sure the body has been formatted to remove the XSS.
$this->assertStringContainsString("\"><", $updatedConversation["body"]);
$this->assertStringNotContainsString($updatedConversation["body"], $xssVector);
}
/**
* Expect exceptions if conversation moderation isn't allowed.
*/
private function expectModerationException(): void {
if (!$this->moderationAllowed) {
$this->expectException(\Exception::class);
$this->expectExceptionCode(403);
$this->expectExceptionMessage('The site is not configured for moderating conversations.');
}
}
}
|
gpl-2.0
|
Fat-Zer/tdelibs
|
tdeui/kdetrayproxy/kdetrayproxy.cpp
|
7019
|
/*
* Copyright (C) 2004 Lubos Lunak <l.lunak@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; 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 "kdetrayproxy.h"
#include <tdeapplication.h>
#include <kdebug.h>
#include <netwm.h>
#include <X11/Xlib.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
KDETrayProxy::KDETrayProxy()
: selection( makeSelectionAtom())
{
connect( &selection, TQT_SIGNAL( newOwner( Window )), TQT_SLOT( newOwner( Window )));
connect( &module, TQT_SIGNAL( windowAdded( WId )), TQT_SLOT( windowAdded( WId )));
selection.owner();
for( TQValueList< WId >::ConstIterator it = module.windows().begin();
it != module.windows().end();
++it )
windowAdded( *it );
kapp->installX11EventFilter( this ); // XSelectInput( StructureNotifyMask ) on windows is done by KWinModule
// kdDebug() << "Init done" << endl;
}
Atom KDETrayProxy::makeSelectionAtom()
{
return XInternAtom( tqt_xdisplay(), "_NET_SYSTEM_TRAY_S" + TQCString().setNum( tqt_xscreen()), False );
}
void KDETrayProxy::windowAdded( WId w )
{
NETWinInfo ni( tqt_xdisplay(), w, tqt_xrootwin(), NET::WMKDESystemTrayWinFor );
WId trayWinFor = ni.kdeSystemTrayWinFor();
if ( !trayWinFor ) // not a KDE tray window
return;
// kdDebug() << "New tray window:" << w << endl;
if( !tray_windows.contains( w ))
tray_windows.append( w );
withdrawWindow( w );
// window will be removed from pending_windows when after docked
if( !pending_windows.contains( w ))
pending_windows.append( w );
docked_windows.remove( w );
Window owner = selection.owner();
if( owner == None ) // no tray owner, sorry
{
// kdDebug() << "No owner, left in pending" << endl;
return;
}
dockWindow( w, owner );
}
void KDETrayProxy::newOwner( Window owner )
{
// kdDebug() << "New owner:" << owner << endl;
for( TQValueList< Window >::ConstIterator it = pending_windows.begin();
it != pending_windows.end();
++it )
dockWindow( *it, owner );
// remove from pending_windows only in windowRemoved(), after it's really docked
}
bool KDETrayProxy::x11Event( XEvent* e )
{
if( tray_windows.isEmpty())
return false;
if( e->type == DestroyNotify && tray_windows.contains( e->xdestroywindow.window ))
{
tray_windows.remove( e->xdestroywindow.window );
pending_windows.remove( e->xdestroywindow.window );
docked_windows.remove( e->xdestroywindow.window );
}
if( e->type == ReparentNotify && tray_windows.contains( e->xreparent.window ))
{
if( e->xreparent.parent == tqt_xrootwin())
{
if( !docked_windows.contains( e->xreparent.window ) || e->xreparent.serial >= docked_windows[ e->xreparent.window ] )
{
// kdDebug() << "Window released:" << e->xreparent.window << endl;
docked_windows.remove( e->xreparent.window );
if( !pending_windows.contains( e->xreparent.window ))
pending_windows.append( e->xreparent.window );
}
}
else
{
// kdDebug() << "Window away:" << e->xreparent.window << ":" << e->xreparent.parent << endl;
pending_windows.remove( e->xreparent.window );
}
}
if( e->type == UnmapNotify && tray_windows.contains( e->xunmap.window ))
{
if( docked_windows.contains( e->xunmap.window ) && e->xunmap.serial >= docked_windows[ e->xunmap.window ] )
{
// kdDebug() << "Window unmapped:" << e->xunmap.window << endl;
XReparentWindow( tqt_xdisplay(), e->xunmap.window, tqt_xrootwin(), 0, 0 );
// ReparentNotify will take care of the rest
}
}
return false;
}
void KDETrayProxy::dockWindow( Window w, Window owner )
{
// kdDebug() << "Docking " << w << " into " << owner << endl;
docked_windows[ w ] = XNextRequest( tqt_xdisplay());
static Atom prop = XInternAtom( tqt_xdisplay(), "_XEMBED_INFO", False );
long data[ 2 ] = { 0, 1 };
XChangeProperty( tqt_xdisplay(), w, prop, prop, 32, PropModeReplace, (unsigned char*)data, 2 );
XSizeHints hints;
hints.flags = PMinSize | PMaxSize;
hints.min_width = 24;
hints.max_width = 24;
hints.min_height = 24;
hints.max_height = 24;
XSetWMNormalHints( tqt_xdisplay(), w, &hints );
// kxerrorhandler ?
XEvent ev;
memset(&ev, 0, sizeof( ev ));
static Atom atom = XInternAtom( tqt_xdisplay(), "_NET_SYSTEM_TRAY_OPCODE", False );
ev.xclient.type = ClientMessage;
ev.xclient.window = owner;
ev.xclient.message_type = atom;
ev.xclient.format = 32;
ev.xclient.data.l[ 0 ] = GET_QT_X_TIME();
ev.xclient.data.l[ 1 ] = 0; // SYSTEM_TRAY_REQUEST_DOCK
ev.xclient.data.l[ 2 ] = w;
ev.xclient.data.l[ 3 ] = 0; // unused
ev.xclient.data.l[ 4 ] = 0; // unused
XSendEvent( tqt_xdisplay(), owner, False, NoEventMask, &ev );
}
void KDETrayProxy::withdrawWindow( Window w )
{
XWithdrawWindow( tqt_xdisplay(), w, tqt_xscreen());
static Atom wm_state = XInternAtom( tqt_xdisplay(), "WM_STATE", False );
for(;;)
{
Atom type;
int format;
unsigned long length, after;
unsigned char *data;
int r = XGetWindowProperty( tqt_xdisplay(), w, wm_state, 0, 2,
False, AnyPropertyType, &type, &format,
&length, &after, &data );
bool withdrawn = true;
if ( r == Success && data && format == 32 )
{
withdrawn = ( *( long* )data == WithdrawnState );
XFree( (char *)data );
}
if( withdrawn )
return; // --->
struct timeval tm;
tm.tv_sec = 0;
tm.tv_usec = 10 * 1000; // 10ms
select(0, NULL, NULL, NULL, &tm);
}
}
#include "kdetrayproxy.moc"
#if 0
#include <tdecmdlineargs.h>
int main( int argc, char* argv[] )
{
TDECmdLineArgs::init( argc, argv, "a", "b", "c", "d" );
TDEApplication app( false ); // no styles
app.disableSessionManagement();
KDETrayProxy proxy;
return app.exec();
}
#endif
|
gpl-2.0
|
QuyICDAC/icdacgov
|
modules/mod_janews_featured/tmpl/telineii/blog.php
|
2715
|
<?php
/**
* ------------------------------------------------------------------------
* JA News Featured Module for J25 & J32
* ------------------------------------------------------------------------
* Copyright (C) 2004-2011 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
* @license - GNU/GPL, http://www.gnu.org/licenses/gpl.html
* Author: J.O.O.M Solutions Co., Ltd
* Websites: http://www.joomlart.com - http://www.joomlancers.com
* ------------------------------------------------------------------------
*/
defined('_JEXEC') or die('Restricted access');
/* This template for headline (frontpage): first news with big image and next news with smaller images*/
$showhlreadmore = intval (trim( $helper->get( 'showhlreadmore', 0 ) ));
$bigitems = intval (trim( $helper->get( 'bigitems', 1) ));
$bigmaxchar = $helper->get ( 'bigmaxchars', 200 );
$bigshowimage = $helper->get ( 'bigshowimage', 1 );
$smallmaxchar = $helper->get ( 'smallmaxchars', 100 );
$smallshowimage = $helper->get ( 'smallshowimage', 1 );
$i = 0;
?>
<?php if(count($rows) > 0) : ?>
<div id="jazin-hlwrap-<?php echo $module->id?>" class="<?php echo $theme?>">
<div id="ja-zinfp-<?php echo $module->id?>" class="clearfix">
<div class="ja-zinfp-featured column clearfix">
<?php foreach ($rows as $news) :
$pos = ($i==0 || $i==$bigitems)?'first':(($i==count($rows)-1 || $i==$bigitems-1)?'last':'');
if($i<$bigitems) : //First new?>
<div class="ja-zincontent inner clearfix <?php echo $pos;?>">
<?php if($bigshowimage) echo $news->bigimage?>
<h4 class="ja-zintitle">
<a href="<?php echo $news->link;?>" title="<?php echo strip_tags($news->title); ?>">
<?php echo $news->title;?>
</a>
</h4>
<?php echo $bigmaxchar > strlen($news->bigintrotext)?$news->introtext:$news->bigintrotext?>
<?php if ($showhlreadmore) {?>
<a href="<?php echo $news->link?>" class="readon" title="<?php echo JText::_('JAFP_READ_MORE');?>"><span><?php echo JText::_('JAFP_READ_MORE');?></span></a>
<?php } ?>
</div>
<?php if($i==$bigitems-1):?>
</div>
<div class="ja-zinfp-normal column clearfix">
<?php endif;?>
<?php else: ?>
<div class="ja-zincontent inner clearfix <?php echo $pos;?>">
<?php if($smallshowimage) echo $news->smallimage?>
<h4 class="jazin-title">
<a href="<?php echo $news->link;?>" title="<?php echo strip_tags($news->title); ?>">
<?php echo $news->title;?>
</a>
</h4>
<?php echo $smallmaxchar > strlen($news->smallintrotext)?$news->introtext:$news->smallintrotext?>
</div>
<?php
endif;
++$i;
endforeach;
?>
</div>
</div>
</div>
<?php endif; ?>
|
gpl-2.0
|
luffy22/Astro
|
components/com_freepaypal/views/topdonors/view.html.php
|
8514
|
<?php
/**
* Topdonors View for FreePayPal Component
*
* @package Joomla.Tutorials
* @subpackage Components
* @link http://docs.joomla.org/Category:Development
* @license GNU/GPL
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.view');
jimport('joomla.environment.uri');
/**
* HTML View class for the FreePayPal Component
*
* @package Joomla.Tutorials
* @subpackage Components
*/
class FreePayPalViewTopdonors extends JView {
function display($tpl = null) {
//$model =& $this->getModel();
//$greeting = $model->getGreeting();
//$this->assignRef( 'greeting', $greeting );
//parent::display($tpl);
$params1 = JComponentHelper::getParams('com_freepaypal')->toArray();
$db = JFactory::getDBO();
FreePayPalViewTopdonors::HTML_topDonors($db, $params1);
}
function getRecords($db, $params) {
$debug = $params['debug'];
$viewoption = $params['top_donors_viewoption'];
$numdonors = $params['top_donors_num_donors'];
$interval_type = $params['top_donors_timeinterval_type'];
switch ($interval_type) {
case 1: // weekly
// start of the week
$first_day_of_week = date('d') - date('w');
$last_day_of_week = date('d') - date('w') + 7;
$sql = "SELECT *, SUM(mc_gross) AS sum_mc_gross FROM #__freepaypal_transactions WHERE published = 1 AND YEAR(payment_date_mysql) = '" . date('Y') . "' AND MONTH(payment_date_mysql) = '" . date('m') . "' AND DAY(payment_date_mysql) BETWEEN " . $first_day_of_week . " AND " . $last_day_of_week . " GROUP BY payer_id ORDER BY sum_mc_gross";
if ($debug == 1) {
echo "Start of Week: " . date('Y-m-d', mktime(1, 0, 0, date('m'), date('d') - date('w'), date('Y'))) . ' 00:00:00';
echo "End of Week: " . date('Y-m-d', mktime(1, 0, 0, date('m'), date('d') - date('w') + 7, date('Y'))) . ' 00:00:00';
echo "SQL Query: " . $sql;
}
break;
case 2: // monthly
$sql = "SELECT *, SUM(mc_gross) AS sum_mc_gross FROM #__freepaypal_transactions WHERE published = 1 AND YEAR(payment_date_mysql) = '" . date('Y') . "' AND MONTH(payment_date_mysql) = '" . date('m') . "' GROUP BY payer_id ORDER BY sum_mc_gross";
if ($debug == 1) {
echo "Start of Month: " . date('Y-m-d', mktime(1, 0, 0, date('m'), 1, date('Y'))) . ' 00:00:00';
echo "End of Month: " . date('Y-m-d', mktime(1, 0, 0, date('m') + 1, 1, date('Y'))) . ' 00:00:00';
echo "SQL Query: " . $sql;
}
break;
case 3: // annual
$sql = "SELECT *, SUM(mc_gross) AS sum_mc_gross FROM #__freepaypal_transactions WHERE published = 1 AND YEAR(payment_date_mysql) = '" . date('Y') . "' GROUP BY payer_id ORDER BY sum_mc_gross";
if ($debug == 1) {
echo "Start of Year: " . date('Y-m-d', mktime(1, 0, 0, 1, 1, date('Y'))) . ' 00:00:00';
echo "End of Year: " . date('Y-m-d', mktime(1, 0, 0, 1, 1, date('Y') + 1)) . ' 00:00:00';
echo "SQL Query: " . $sql;
}
break;
case 4: // all
$sql = "SELECT *, SUM(mc_gross) AS sum_mc_gross FROM #__freepaypal_transactions WHERE published = 1 GROUP BY payer_id ORDER BY sum_mc_gross";
if ($debug == 1) {
echo "SQL Query: " . $sql;
}
}
$db->setQuery($sql);
$rows = $db->loadObjectList();
return $rows;
}
function HTML_topDonors($db, $params) {
$viewoption = $params['top_donors_viewoption'];
$numdonors = $params['top_donors_num_donors'];
$timeinterval = $params['top_donors_timeinterval_type'];
$titles_csv = $params['top_donors_table_titles'];
$fields_csv = $params['top_donors_table_fields'];
if ($viewoption == 3) {
echo JText::_("FreePayPal::List Top Donors view not available. The configuration must be changed to enable this view.");
return;
}
$rows = FreePayPalViewTopdonors::getRecords($db, $params);
$config = new JConfig();
echo "<script type=\"text/javascript\" src=\"" . JURI::root() . "components/com_freepaypal/views/listdonations/sorttable.js\"></script>";
if ($params['debug'] == 1) {
echo '<ul>';
echo '<li>top_donors_viewoption = ' . $params['top_donors_viewoption'] . '</li>';
echo '<li>top_donors_num_donors = ' . $params['top_donors_num_donors'] . '</li>';
echo '<li>top_donors_timeinterval_type = ' . $params['top_donors_timeinterval_type'] . '</li>';
echo '</ul>';
}
$numrows = count($rows);
$rows_shown = ($numrows < $numdonors) ? $numrows : $numdonors;
echo '<ul>';
echo '<li>' . JText::_('Top') . ' ' . $rows_shown . ' ' . JText::_('donors for') . ' ';
if ($timeinterval == 1)
echo JText::_('this week') . '.</li>';
else if ($timeinterval == 2)
echo JText::_('this month') . '.</li>';
else if ($timeinterval == 3)
echo JText::_('this year') . '.</li>';
else
echo JText::_('all time') . '.</li>';
echo '</ul>';
$colnames = explode(',', $titles_csv);
$fieldnames = explode(',', $fields_csv);
//echo "<div id=\"test\" class=\"module\">";
//echo "<table class=\"sortable\" border=\"1\">\n";
if (count($colnames) > 0) {
echo "<table class=\"moduletable\" >\n";
echo "<thead><tr>";
/* echo "<th>Date</th>";
echo "<th>Amount</th>";
echo "<th>Currency</th>";
echo "<th>Name</th>";
echo "<th>" . $rows[0]->option_name1 . "</th>";
echo "<th>" . $rows[1]->option_name2 . "</th>"; */
foreach ($colnames as $colname) {
echo "<th>" . trim($colname) . "</th>";
}
echo "</tr></thead>";
if (count($rows) > 0 && count($fieldnames) > 0) {
echo "<tbody>";
$i = 0;
$rows = array_reverse($rows);
foreach ($rows as $row) {
echo '<tr>';
foreach ($fieldnames as $fieldname) {
$fields = explode(' ', $fieldname);
$j = 0;
foreach ($fields as $field) {
$field = trim($field);
if (strlen($field) > 0) {
if (substr($field, 0, 1) == '$') {
$field = substr($field, 1);
if ($j == 0)
$phpstr = '$row->' . $field;
else
$phpstr .= " .' '. " . '$row->' . $field;
}
else {
if ($j == 0)
$phpstr = "\"" . $field . "\"";
else
$phpstr .= " .\" \". " . "\"" . $field . "\"";
}
$j++;
}
}
$phpstr_eval = "echo \"<td>\" . " . $phpstr . " . \"</td>\";";
if ($params['debug'] == 1) {
$phpstr_evaldbg = "echo \"td\" . " . $phpstr . " .\"/td \" ;";
//echo '<li>phpcommand = <code>' . $phpstr_eval . ' ' . print_r($field) . '</code></li>';
echo '<li>phpcommand = </li><pre>' . $phpstr_evaldbg . '</pre>';
}
eval($phpstr_eval);
}
echo '</tr>';
$i++;
if ($i >= $numdonors && $numdonors > 0)
break;
}
echo "</tbody>";
}
else {
echo '<tbody><tr><td></td></tr></tbody>';
}
echo '</table>';
}
}
}
|
gpl-2.0
|
gaoxiaojun/dync
|
src/share/vm/ci/ciInstanceKlass.hpp
|
8633
|
/*
* Copyright (c) 1999, 2015, 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.
*
*/
#ifndef SHARE_VM_CI_CIINSTANCEKLASS_HPP
#define SHARE_VM_CI_CIINSTANCEKLASS_HPP
#include "ci/ciConstantPoolCache.hpp"
#include "ci/ciFlags.hpp"
#include "ci/ciKlass.hpp"
#include "ci/ciSymbol.hpp"
// ciInstanceKlass
//
// This class represents a Klass* in the HotSpot virtual machine
// whose Klass part is an InstanceKlass. It may or may not
// be loaded.
class ciInstanceKlass : public ciKlass {
CI_PACKAGE_ACCESS
friend class ciBytecodeStream;
friend class ciEnv;
friend class ciExceptionHandler;
friend class ciMethod;
friend class ciField;
private:
jobject _loader;
jobject _protection_domain;
InstanceKlass::ClassState _init_state; // state of class
bool _is_shared;
bool _has_finalizer;
bool _has_subklass;
bool _has_nonstatic_fields;
bool _has_default_methods;
bool _is_anonymous;
ciFlags _flags;
jint _nonstatic_field_size;
jint _nonstatic_oop_map_size;
// Lazy fields get filled in only upon request.
ciInstanceKlass* _super;
ciInstance* _java_mirror;
ciConstantPoolCache* _field_cache; // cached map index->field
GrowableArray<ciField*>* _nonstatic_fields;
int _has_injected_fields; // any non static injected fields? lazily initialized.
// The possible values of the _implementor fall into following three cases:
// NULL: no implementor.
// A ciInstanceKlass that's not itself: one implementor.
// Itsef: more than one implementors.
ciInstanceKlass* _implementor;
void compute_injected_fields();
bool compute_injected_fields_helper();
protected:
ciInstanceKlass(KlassHandle h_k);
ciInstanceKlass(ciSymbol* name, jobject loader, jobject protection_domain);
InstanceKlass* get_instanceKlass() const {
return InstanceKlass::cast(get_Klass());
}
oop loader();
jobject loader_handle();
oop protection_domain();
jobject protection_domain_handle();
const char* type_string() { return "ciInstanceKlass"; }
bool is_in_package_impl(const char* packagename, int len);
void print_impl(outputStream* st);
ciConstantPoolCache* field_cache();
bool is_shared() { return _is_shared; }
void compute_shared_init_state();
bool compute_shared_has_subklass();
int compute_nonstatic_fields();
GrowableArray<ciField*>* compute_nonstatic_fields_impl(GrowableArray<ciField*>* super_fields);
// Update the init_state for shared klasses
void update_if_shared(InstanceKlass::ClassState expected) {
if (_is_shared && _init_state != expected) {
if (is_loaded()) compute_shared_init_state();
}
}
public:
// Has this klass been initialized?
bool is_initialized() {
update_if_shared(InstanceKlass::fully_initialized);
return _init_state == InstanceKlass::fully_initialized;
}
// Is this klass being initialized?
bool is_being_initialized() {
update_if_shared(InstanceKlass::being_initialized);
return _init_state == InstanceKlass::being_initialized;
}
// Has this klass been linked?
bool is_linked() {
update_if_shared(InstanceKlass::linked);
return _init_state >= InstanceKlass::linked;
}
// General klass information.
ciFlags flags() {
assert(is_loaded(), "must be loaded");
return _flags;
}
bool has_finalizer() {
assert(is_loaded(), "must be loaded");
return _has_finalizer; }
bool has_subklass() {
assert(is_loaded(), "must be loaded");
if (_is_shared && !_has_subklass) {
if (flags().is_final()) {
return false;
} else {
return compute_shared_has_subklass();
}
}
return _has_subklass;
}
jint size_helper() {
return (Klass::layout_helper_size_in_bytes(layout_helper())
>> LogHeapWordSize);
}
jint nonstatic_field_size() {
assert(is_loaded(), "must be loaded");
return _nonstatic_field_size; }
jint has_nonstatic_fields() {
assert(is_loaded(), "must be loaded");
return _has_nonstatic_fields; }
jint nonstatic_oop_map_size() {
assert(is_loaded(), "must be loaded");
return _nonstatic_oop_map_size; }
ciInstanceKlass* super();
jint nof_implementors() {
ciInstanceKlass* impl;
assert(is_loaded(), "must be loaded");
impl = implementor();
if (impl == NULL) {
return 0;
} else if (impl != this) {
return 1;
} else {
return 2;
}
}
bool has_default_methods() {
assert(is_loaded(), "must be loaded");
return _has_default_methods;
}
bool is_anonymous() {
return _is_anonymous;
}
ciInstanceKlass* get_canonical_holder(int offset);
ciField* get_field_by_offset(int field_offset, bool is_static);
ciField* get_field_by_name(ciSymbol* name, ciSymbol* signature, bool is_static);
// total number of nonstatic fields (including inherited):
int nof_nonstatic_fields() {
if (_nonstatic_fields == NULL)
return compute_nonstatic_fields();
else
return _nonstatic_fields->length();
}
bool has_injected_fields() {
if (_has_injected_fields == -1) {
compute_injected_fields();
}
return _has_injected_fields > 0 ? true : false;
}
// nth nonstatic field (presented by ascending address)
ciField* nonstatic_field_at(int i) {
assert(_nonstatic_fields != NULL, "");
return _nonstatic_fields->at(i);
}
ciInstanceKlass* unique_concrete_subklass();
bool has_finalizable_subclass();
bool contains_field_offset(int offset) {
return instanceOopDesc::contains_field_offset(offset, nonstatic_field_size());
}
// Get the instance of java.lang.Class corresponding to
// this klass. This instance is used for locking of
// synchronized static methods of this klass.
ciInstance* java_mirror();
// Java access flags
bool is_public () { return flags().is_public(); }
bool is_final () { return flags().is_final(); }
bool is_super () { return flags().is_super(); }
bool is_interface () { return flags().is_interface(); }
bool is_abstract () { return flags().is_abstract(); }
ciMethod* find_method(ciSymbol* name, ciSymbol* signature);
// Note: To find a method from name and type strings, use ciSymbol::make,
// but consider adding to vmSymbols.hpp instead.
bool is_leaf_type();
ciInstanceKlass* implementor();
// Is the defining class loader of this class the default loader?
bool uses_default_loader() const;
bool is_java_lang_Object() const;
BasicType box_klass_type() const;
bool is_box_klass() const;
bool is_boxed_value_offset(int offset) const;
// Is this klass in the given package?
bool is_in_package(const char* packagename) {
return is_in_package(packagename, (int) strlen(packagename));
}
bool is_in_package(const char* packagename, int len);
// What kind of ciObject is this?
bool is_instance_klass() const { return true; }
bool is_java_klass() const { return true; }
virtual ciKlass* exact_klass() {
if (is_loaded() && is_final() && !is_interface()) {
return this;
}
return NULL;
}
// Dump the current state of this klass for compilation replay.
virtual void dump_replay_data(outputStream* out);
};
#endif // SHARE_VM_CI_CIINSTANCEKLASS_HPP
|
gpl-2.0
|
elitelinux/glpi-smartcities
|
plugins/ocsinventoryng/hook.php
|
93789
|
<?php
/*
* @version $Id: HEADER 15930 2012-12-15 11:10:55Z tsmr $
-------------------------------------------------------------------------
Ocsinventoryng plugin for GLPI
Copyright (C) 2012-2013 by the ocsinventoryng plugin Development Team.
https://forge.indepnet.net/projects/ocsinventoryng
-------------------------------------------------------------------------
LICENSE
This file is part of ocsinventoryng.
Ocsinventoryng plugin 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.
Ocsinventoryng plugin 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 ocsinventoryng. If not, see <http://www.gnu.org/licenses/>.
-------------------------------------------------------------------------- */
function plugin_ocsinventoryng_install() {
global $DB;
include_once (GLPI_ROOT."/plugins/ocsinventoryng/inc/profile.class.php");
$migration = new Migration(110);
if (!TableExists("glpi_plugin_ocsinventoryng_ocsservers_profiles")
&& !TableExists("glpi_plugin_ocsinventoryng_ocsservers")) {
$install = true;
$DB->runFile(GLPI_ROOT ."/plugins/ocsinventoryng/install/mysql/1.1.0-empty.sql");
$migration->createRule(array('sub_type' => 'RuleImportEntity',
'entities_id' => 0,
'is_recursive' => 1,
'is_active' => 1,
'match' => 'AND',
'name' => 'RootOcs'),
array(array('criteria' => 'TAG',
'condition' => Rule::PATTERN_IS,
'pattern' => '*'),
array('criteria' => 'OCS_SERVER',
'condition' => Rule::PATTERN_IS,
'pattern' => 1)),
array(array('field' => 'entities_id',
'action_type' => 'assign',
'value' => 0)));
} else if (!TableExists("glpi_plugin_ocsinventoryng_ocsservers")
&& !TableExists("ocs_glpi_ocsservers")) {
CronTask::Register('PluginOcsinventoryngOcsServer', 'ocsng', MINUTE_TIMESTAMP*5);
$migration->createRule(array('sub_type' => 'RuleImportEntity',
'entities_id' => 0,
'is_recursive' => 1,
'is_active' => 1,
'match' => 'AND',
'name' => 'RootOcs'),
array(array('criteria' => 'TAG',
'condition' => Rule::PATTERN_IS,
'pattern' => '*'),
array('criteria' => 'OCS_SERVER',
'condition' => Rule::PATTERN_IS,
'pattern' => 1)),
array(array('field' => 'entities_id',
'action_type' => 'assign',
'value' => 0)));
} else if (!TableExists("glpi_plugin_ocsinventoryng_ocsservers")
&& TableExists("ocs_glpi_ocsservers")) {
$update = true;
$DB->runFile(GLPI_ROOT ."/plugins/ocsinventoryng/install/mysql/1.0.0-update.sql");
// recuperation des droits du core
// creation de la table glpi_plugin_ocsinventoryng_profiles vide
If (TableExists("ocs_glpi_profiles")
&& (TableExists('ocs_glpi_ocsservers')
&& countElementsInTable('ocs_glpi_ocsservers') > 0)) {
$query = "INSERT INTO `glpi_plugin_ocsinventoryng_profiles`
(`profiles_id`, `ocsng`, `sync_ocsng`, `view_ocsng`, `clean_ocsng`,
`rule_ocs`)
SELECT `id`, `ocsng`, `sync_ocsng`, `view_ocsng`, `clean_ocsng`,
`rule_ocs`
FROM `ocs_glpi_profiles`";
$DB->queryOrDie($query, "1.0.0 insert profiles for OCS in plugin");
}
// recuperation des paramètres du core
If (TableExists("ocs_glpi_crontasks")) {
$query = "INSERT INTO `glpi_crontasks`
SELECT *
FROM `ocs_glpi_crontasks`
WHERE `itemtype` = 'OcsServer'";
$DB->queryOrDie($query, "1.0.0 insert crontasks for plugin ocsinventoryng");
$query = "UPDATE `glpi_crontasks`
SET `itemtype` = 'PluginOcsinventoryngOcsServer'
WHERE `itemtype` = 'OcsServer'";
$DB->queryOrDie($query, "1.0.0 update ocsinventoryng crontask");
}
If (TableExists("ocs_glpi_displaypreferences")) {
$query = "INSERT INTO `glpi_displaypreferences`
SELECT *
FROM `ocs_glpi_displaypreferences`
WHERE `itemtype` = 'OcsServer'";
$DB->queryOrDie($query, "1.0.0 insert displaypreferences for plugin ocsinventoryng");
$query = "UPDATE `glpi_displaypreferences`
SET `itemtype` = 'PluginOcsinventoryngOcsServer'
WHERE `itemtype` = 'OcsServer'";
$DB->queryOrDie($query, "1.0.0 update ocsinventoryng displaypreferences");
}
plugin_ocsinventoryng_migrateComputerLocks($migration);
}
//Update 1.0.3
If (TableExists("glpi_plugin_ocsinventoryng_networkports")
&& !FieldExists('glpi_plugin_ocsinventoryng_networkports', 'speed')) {
$query = "ALTER TABLE `glpi_plugin_ocsinventoryng_networkports`
ADD `speed` varchar(255) COLLATE utf8_unicode_ci DEFAULT '10mb/s';";
$DB->queryOrDie($query, "1.0.3 update table glpi_plugin_ocsinventoryng_networkports");
}
// Update 1.0.4
if (TableExists("glpi_plugin_ocsinventoryng_ocsservers")
&& !FieldExists('glpi_plugin_ocsinventoryng_ocsservers', 'conn_type')) {
$query = "ALTER TABLE `glpi_plugin_ocsinventoryng_ocsservers`
ADD `conn_type` tinyint(1) NOT NULL DEFAULT '0';";
$DB->queryOrDie($query, "1.0.4 update table glpi_plugin_ocsinventoryng_ocsservers");
}
//Update 1.1.0
if (!TableExists("glpi_plugin_ocsinventoryng_ocsservers_profiles")) {
$query = "CREATE TABLE `glpi_plugin_ocsinventoryng_ocsservers_profiles` (
`id` int(11) NOT NULL auto_increment,
`plugin_ocsinventoryng_ocsservers_id` int(11) NOT NULL default '0',
`profiles_id` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `plugin_ocsinventoryng_ocsservers_id` (`plugin_ocsinventoryng_ocsservers_id`),
KEY `profiles_id` (`profiles_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
$DB->queryOrDie($query,
'Creating glpi_plugin_ocsinventoryng_ocsservers_profiles'."<br>".$DB->error());
}
if (TableExists("glpi_plugin_ocsinventoryng_ocslinks")
&& !FieldExists('glpi_plugin_ocsinventoryng_ocslinks', 'last_ocs_conn')) {
$query = "ALTER TABLE `glpi_plugin_ocsinventoryng_ocslinks`
ADD `last_ocs_conn` datetime default NULL;";
$DB->queryOrDie($query, "1.1.0 update table glpi_plugin_ocsinventoryng_ocslinks");
}
if (TableExists("glpi_plugin_ocsinventoryng_ocslinks")
&& !FieldExists('glpi_plugin_ocsinventoryng_ocslinks', 'ip_src')) {
$query = "ALTER TABLE `glpi_plugin_ocsinventoryng_ocslinks`
ADD `ip_src` varchar(255) collate utf8_unicode_ci default NULL;";
$DB->queryOrDie($query, "1.1.0 update table glpi_plugin_ocsinventoryng_ocslinks");
}
if (TableExists("glpi_plugin_ocsinventoryng_ocsservers")
&& !FieldExists('glpi_plugin_ocsinventoryng_ocsservers', 'import_device_bios')) {
$query = "ALTER TABLE `glpi_plugin_ocsinventoryng_ocsservers`
ADD `import_device_bios` tinyint(1) NOT NULL DEFAULT '1';";
$DB->queryOrDie($query, "1.1.0 update table glpi_plugin_ocsinventoryng_ocsservers");
}
if (!TableExists("glpi_plugin_ocsinventoryng_devicebiosdatas")) {
$query = "CREATE TABLE `glpi_plugin_ocsinventoryng_devicebiosdatas` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`designation` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`comment` text COLLATE utf8_unicode_ci,
`date` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`assettag` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`manufacturers_id` int(11) NOT NULL DEFAULT '0',
`entities_id` int(11) NOT NULL DEFAULT '0',
`is_recursive` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `manufacturers_id` (`manufacturers_id`),
KEY `entities_id` (`entities_id`),
KEY `is_recursive` (`is_recursive`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
$DB->queryOrDie($query, "1.1.0 add table glpi_plugin_ocsinventoryng_devicebiosdatas");
}
if (!TableExists("glpi_plugin_ocsinventoryng_items_devicebiosdatas")) {
$query = "CREATE TABLE `glpi_plugin_ocsinventoryng_items_devicebiosdatas` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`items_id` int(11) NOT NULL DEFAULT '0',
`itemtype` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`plugin_ocsinventoryng_devicebiosdatas_id` int(11) NOT NULL DEFAULT '0',
`is_deleted` tinyint(1) NOT NULL DEFAULT '0',
`is_dynamic` tinyint(1) NOT NULL DEFAULT '0',
`entities_id` int(11) NOT NULL DEFAULT '0',
`is_recursive` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `computers_id` (`items_id`),
KEY `plugin_ocsinventoryng_devicebiosdatas_id` (`plugin_ocsinventoryng_devicebiosdatas_id`),
KEY `is_deleted` (`is_deleted`),
KEY `is_dynamic` (`is_dynamic`),
KEY `entities_id` (`entities_id`),
KEY `is_recursive` (`is_recursive`),
KEY `item` (`itemtype`,`items_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
$DB->queryOrDie($query, "1.1.0 add table glpi_plugin_ocsinventoryng_items_devicebiosdatas");
}
PluginOcsinventoryngProfile::initProfile();
PluginOcsinventoryngProfile::createFirstAccess($_SESSION['glpiactiveprofile']['id']);
if (TableExists("glpi_plugin_ocsinventoryng_ocsservers")
&& TableExists("glpi_plugin_ocsinventoryng_profiles")
&& (countElementsInTable("glpi_plugin_ocsinventoryng_ocsservers", "`is_active` = 1") == 1)) {
foreach ($DB->request("glpi_plugin_ocsinventoryng_ocsservers") as $server) {
foreach ($DB->request("glpi_plugin_ocsinventoryng_profiles",
"`ocsng` IS NOT NULL") as $rights) {
$query = "INSERT INTO `glpi_plugin_ocsinventoryng_ocsservers_profiles`
SET `profiles_id` = '".$rights['profiles_id']."',
`plugin_ocsinventoryng_ocsservers_id` = '".$server['id']."'";
$DB->queryOrDie($query, "insert into glpi_plugin_ocsinventoryng_ocsservers_profiles");
}
}
}
$migration = new Migration("1.1.0");
$migration->dropTable('glpi_plugin_ocsinventoryng_profiles');
// Si massocsimport import est installe, on verifie qu'il soit bien dans la dernière version
if (TableExists("glpi_plugin_mass_ocs_import")) { //1.1 ou 1.2
if (!FieldExists('glpi_plugin_mass_ocs_import_config','warn_if_not_imported')) { //1.1
plugin_ocsinventoryng_upgrademassocsimport11to12();
}
}
if (TableExists("glpi_plugin_mass_ocs_import")) { //1.2 because if before
plugin_ocsinventoryng_upgrademassocsimport121to13();
}
if (TableExists("glpi_plugin_massocsimport")) { //1.3 ou 1.4
if (FieldExists('glpi_plugin_massocsimport','ID')) { //1.3
plugin_ocsinventoryng_upgrademassocsimport13to14();
}
}
if (TableExists('glpi_plugin_massocsimport_threads')
&& !FieldExists('glpi_plugin_massocsimport_threads','not_unique_machines_number')) {
plugin_ocsinventoryng_upgrademassocsimport14to15();
}
//Tables from massocsimport
if (!TableExists('glpi_plugin_ocsinventoryng_threads')
&& !TableExists('glpi_plugin_massocsimport_threads')) { //not installed
$query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_ocsinventoryng_threads` (
`id` int(11) NOT NULL auto_increment,
`threadid` int(11) NOT NULL default '0',
`start_time` datetime default NULL,
`end_time` datetime default NULL,
`status` int(11) NOT NULL default '0',
`error_msg` text NOT NULL,
`imported_machines_number` int(11) NOT NULL default '0',
`synchronized_machines_number` int(11) NOT NULL default '0',
`failed_rules_machines_number` int(11) NOT NULL default '0',
`linked_machines_number` int(11) NOT NULL default '0',
`notupdated_machines_number` int(11) NOT NULL default '0',
`not_unique_machines_number` int(11) NOT NULL default '0',
`link_refused_machines_number` int(11) NOT NULL default '0',
`total_number_machines` int(11) NOT NULL default '0',
`plugin_ocsinventoryng_ocsservers_id` int(11) NOT NULL default '1',
`processid` int(11) NOT NULL default '0',
`entities_id` int(11) NOT NULL DEFAULT 0,
`rules_id` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `end_time` (`end_time`),
KEY `process_thread` (`processid`,`threadid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ";
$DB->queryOrDie($query, $DB->error());
$query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_ocsinventoryng_configs` (
`id` int(11) NOT NULL auto_increment,
`thread_log_frequency` int(11) NOT NULL default '10',
`is_displayempty` int(1) NOT NULL default '1',
`import_limit` int(11) NOT NULL default '0',
`delay_refresh` int(11) NOT NULL default '0',
`allow_ocs_update` tinyint(1) NOT NULL default '0',
`comment` text,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ";
$DB->queryOrDie($query, $DB->error());
$query = "INSERT INTO `glpi_plugin_ocsinventoryng_configs`
(`id`,`thread_log_frequency`,`is_displayempty`,`import_limit`)
VALUES (1, 2, 1, 0);";
$DB->queryOrDie($query, $DB->error());
$query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_ocsinventoryng_details` (
`id` int(11) NOT NULL auto_increment,
`entities_id` int(11) NOT NULL default '0',
`plugin_ocsinventoryng_threads_id` int(11) NOT NULL default '0',
`rules_id` TEXT,
`threadid` int(11) NOT NULL default '0',
`ocsid` int(11) NOT NULL default '0',
`computers_id` int(11) NOT NULL default '0',
`action` int(11) NOT NULL default '0',
`process_time` datetime DEFAULT NULL,
`plugin_ocsinventoryng_ocsservers_id` int(11) NOT NULL default '1',
PRIMARY KEY (`id`),
KEY `end_time` (`process_time`),
KEY `process_thread` (`plugin_ocsinventoryng_threads_id`,`threadid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
$DB->queryOrDie($query, $DB->error());
$query = "INSERT INTO `glpi_displaypreferences` (`itemtype`, `num`, `rank`, `users_id`)
VALUES ('PluginOcsinventoryngNotimportedcomputer', 2, 1, 0),
('PluginOcsinventoryngNotimportedcomputer', 3, 2, 0),
('PluginOcsinventoryngNotimportedcomputer', 4, 3, 0),
('PluginOcsinventoryngNotimportedcomputer', 5, 4, 0),
('PluginOcsinventoryngNotimportedcomputer', 6, 5, 0),
('PluginOcsinventoryngNotimportedcomputer', 7, 6, 0),
('PluginOcsinventoryngNotimportedcomputer', 8, 7, 0),
('PluginOcsinventoryngNotimportedcomputer', 9, 8, 0),
('PluginOcsinventoryngNotimportedcomputer', 10, 9, 0),
('PluginOcsinventoryngDetail', 5, 1, 0),
('PluginOcsinventoryngDetail', 2, 2, 0),
('PluginOcsinventoryngDetail', 3, 3, 0),
('PluginOcsinventoryngDetail', 4, 4, 0),
('PluginOcsinventoryngDetail', 6, 5, 0),
('PluginOcsinventoryngDetail', 80, 6, 0)";
$DB->queryOrDie($query, $DB->error());
$query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_ocsinventoryng_notimportedcomputers` (
`id` INT( 11 ) NOT NULL auto_increment,
`entities_id` int(11) NOT NULL default '0',
`rules_id` TEXT,
`comment` text NULL,
`ocsid` INT( 11 ) NOT NULL DEFAULT '0',
`plugin_ocsinventoryng_ocsservers_id` INT( 11 ) NOT NULL ,
`ocs_deviceid` VARCHAR( 255 ) NOT NULL ,
`useragent` VARCHAR( 255 ) NOT NULL ,
`tag` VARCHAR( 255 ) NOT NULL ,
`serial` VARCHAR( 255 ) NOT NULL ,
`name` VARCHAR( 255 ) NOT NULL ,
`ipaddr` VARCHAR( 255 ) NOT NULL ,
`domain` VARCHAR( 255 ) NOT NULL ,
`last_inventory` DATETIME ,
`reason` INT( 11 ) NOT NULL ,
PRIMARY KEY ( `id` ),
UNIQUE KEY `ocs_id` (`plugin_ocsinventoryng_ocsservers_id`,`ocsid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ";
$DB->queryOrDie($query, $DB->error());
$query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_ocsinventoryng_servers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`plugin_ocsinventoryng_ocsservers_id` int(11) NOT NULL DEFAULT '0',
`max_ocsid` int(11) DEFAULT NULL,
`max_glpidate` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `plugin_ocsinventoryng_ocsservers_id` (`plugin_ocsinventoryng_ocsservers_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ";
$DB->queryOrDie($query, $DB->error());
} else if (!TableExists('glpi_plugin_ocsinventoryng_threads')
&& TableExists('glpi_plugin_massocsimport_threads')) {
if (TableExists('glpi_plugin_massocsimport_threads')
&& !FieldExists('glpi_plugin_massocsimport_threads','not_unique_machines_number')) {
plugin_ocsinventoryng_upgrademassocsimport14to15();
}
$query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_ocsinventoryng_threads` (
`id` int(11) NOT NULL auto_increment,
`threadid` int(11) NOT NULL default '0',
`start_time` datetime default NULL,
`end_time` datetime default NULL,
`status` int(11) NOT NULL default '0',
`error_msg` text NOT NULL,
`imported_machines_number` int(11) NOT NULL default '0',
`synchronized_machines_number` int(11) NOT NULL default '0',
`failed_rules_machines_number` int(11) NOT NULL default '0',
`linked_machines_number` int(11) NOT NULL default '0',
`notupdated_machines_number` int(11) NOT NULL default '0',
`not_unique_machines_number` int(11) NOT NULL default '0',
`link_refused_machines_number` int(11) NOT NULL default '0',
`total_number_machines` int(11) NOT NULL default '0',
`ocsservers_id` int(11) NOT NULL default '1',
`processid` int(11) NOT NULL default '0',
`entities_id` int(11) NOT NULL DEFAULT 0,
`rules_id` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `end_time` (`end_time`),
KEY `process_thread` (`processid`,`threadid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ";
$DB->queryOrDie($query, $DB->error());
//error of massocsimport 1.5.0 installaton
$migration->addField("glpi_plugin_massocsimport_threads", "entities_id", 'integer');
$migration->addField("glpi_plugin_massocsimport_threads", "rules_id", 'integer');
foreach (getAllDatasFromTable('glpi_plugin_massocsimport_threads') as $thread) {
if (is_null($thread['rules_id']) || $thread['rules_id'] == '') {
$rules_id = 0;
} else {
$rules_id = $thread['rules_id'];
}
$query = "INSERT INTO `glpi_plugin_ocsinventoryng_threads`
VALUES ('".$thread['id']."',
'".$thread['threadid']."',
'".$thread['start_time']."',
'".$thread['end_time']."',
'".$thread['status']."',
'".$thread['error_msg']."',
'".$thread['imported_machines_number']."',
'".$thread['synchronized_machines_number']."',
'".$thread['failed_rules_machines_number']."',
'".$thread['linked_machines_number']."',
'".$thread['notupdated_machines_number']."',
'".$thread['not_unique_machines_number']."',
'".$thread['link_refused_machines_number']."',
'".$thread['total_number_machines']."',
'".$thread['ocsservers_id']."',
'".$thread['processid']."',
'".$thread['entities_id']."',
'".$rules_id."');";
$DB->queryOrDie($query, $DB->error());
}
$migration->renameTable("glpi_plugin_massocsimport_threads",
"backup_glpi_plugin_massocsimport_threads");
$migration->changeField("glpi_plugin_ocsinventoryng_threads", "ocsservers_id",
"plugin_ocsinventoryng_ocsservers_id", 'integer');
$query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_ocsinventoryng_configs` (
`id` int(11) NOT NULL auto_increment,
`thread_log_frequency` int(11) NOT NULL default '10',
`is_displayempty` int(1) NOT NULL default '1',
`import_limit` int(11) NOT NULL default '0',
`ocsservers_id` int(11) NOT NULL default '-1',
`delay_refresh` int(11) NOT NULL default '0',
`allow_ocs_update` tinyint(1) NOT NULL default '0',
`comment` text,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ";
$DB->query($query) or die($DB->error());
foreach (getAllDatasFromTable('glpi_plugin_massocsimport_configs') as $thread) {
$query = "INSERT INTO `glpi_plugin_ocsinventoryng_configs`
VALUES('".$thread['id']."',
'".$thread['thread_log_frequency']."',
'".$thread['is_displayempty']."',
'".$thread['import_limit']."',
'".$thread['ocsservers_id']."',
'".$thread['delay_refresh']."',
'".$thread['allow_ocs_update']."',
'".$thread['comment']."');";
$DB->queryOrDie($query, $DB->error());
}
$migration->renameTable("glpi_plugin_massocsimport_configs",
"backup_glpi_plugin_massocsimport_configs");
$migration->dropField("glpi_plugin_ocsinventoryng_configs", "ocsservers_id");
$query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_ocsinventoryng_details` (
`id` int(11) NOT NULL auto_increment,
`entities_id` int(11) NOT NULL default '0',
`plugin_massocsimport_threads_id` int(11) NOT NULL default '0',
`rules_id` TEXT,
`threadid` int(11) NOT NULL default '0',
`ocsid` int(11) NOT NULL default '0',
`computers_id` int(11) NOT NULL default '0',
`action` int(11) NOT NULL default '0',
`process_time` datetime DEFAULT NULL,
`ocsservers_id` int(11) NOT NULL default '1',
PRIMARY KEY (`id`),
KEY `end_time` (`process_time`),
KEY `process_thread` (`ocsservers_id`,`threadid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
$DB->queryOrDie($query, $DB->error());
foreach (getAllDatasFromTable('glpi_plugin_massocsimport_details') as $thread) {
$query = "INSERT INTO `glpi_plugin_ocsinventoryng_details`
VALUES ('".$thread['id']."',
'".$thread['entities_id']."',
'".$thread['plugin_massocsimport_threads_id']."',
'".$thread['rules_id']."',
'".$thread['threadid']."',
'".$thread['ocsid']."',
'".$thread['computers_id']."',
'".$thread['action']."',
'".$thread['process_time']."',
'".$thread['ocsservers_id']."');";
$DB->query($query) or die($DB->error());
}
$migration->renameTable("glpi_plugin_massocsimport_details",
"backup_glpi_plugin_massocsimport_details");
$migration->changeField("glpi_plugin_ocsinventoryng_details",
"plugin_massocsimport_threads_id", "plugin_ocsinventoryng_threads_id",
'integer');
$migration->changeField("glpi_plugin_ocsinventoryng_details", "ocsservers_id",
"plugin_ocsinventoryng_ocsservers_id", 'integer');
$query = "UPDATE `glpi_displaypreferences`
SET `itemtype` = 'PluginOcsinventoryngNotimportedcomputer'
WHERE `itemtype` = 'PluginMassocsimportNotimported'";
$DB->queryOrDie($query, $DB->error());
$query = "UPDATE `glpi_displaypreferences`
SET `itemtype` = 'PluginOcsinventoryngDetail'
WHERE `itemtype` = 'PluginMassocsimportDetail';";
$DB->queryOrDie($query, $DB->error());
$query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_ocsinventoryng_notimportedcomputers` (
`id` INT( 11 ) NOT NULL auto_increment,
`entities_id` int(11) NOT NULL default '0',
`rules_id` TEXT,
`comment` text NULL,
`ocsid` INT( 11 ) NOT NULL DEFAULT '0',
`ocsservers_id` INT( 11 ) NOT NULL ,
`ocs_deviceid` VARCHAR( 255 ) NOT NULL ,
`useragent` VARCHAR( 255 ) NOT NULL ,
`tag` VARCHAR( 255 ) NOT NULL ,
`serial` VARCHAR( 255 ) NOT NULL ,
`name` VARCHAR( 255 ) NOT NULL ,
`ipaddr` VARCHAR( 255 ) NOT NULL ,
`domain` VARCHAR( 255 ) NOT NULL ,
`last_inventory` DATETIME ,
`reason` INT( 11 ) NOT NULL ,
PRIMARY KEY ( `id` ),
UNIQUE KEY `ocs_id` (`ocsservers_id`,`ocsid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ";
$DB->queryOrDie($query, $DB->error());
if (TableExists("glpi_plugin_massocsimport_notimported")) {
foreach (getAllDatasFromTable('glpi_plugin_massocsimport_notimported') as $thread) {
$query = "INSERT INTO `glpi_plugin_ocsinventoryng_notimportedcomputers`
VALUES ('".$thread['id']."', '".$thread['entities_id']."',
'".$thread['rules_id']."', '".$thread['comment']."',
'".$thread['ocsid']."', '".$thread['ocsservers_id']."',
'".$thread['ocs_deviceid']."', '".$thread['useragent']."',
'".$thread['tag']."', '".$thread['serial']."', '".$thread['name']."',
'".$thread['ipaddr']."', '".$thread['domain']."',
'".$thread['last_inventory']."', '".$thread['reason']."')";
$DB->queryOrDie($query, $DB->error());
}
$migration->renameTable("glpi_plugin_massocsimport_notimported",
"backup_glpi_plugin_massocsimport_notimported");
}
$migration->changeField("glpi_plugin_ocsinventoryng_notimportedcomputers", "ocsservers_id",
"plugin_ocsinventoryng_ocsservers_id", 'integer');
$query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_ocsinventoryng_servers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ocsservers_id` int(11) NOT NULL DEFAULT '0',
`max_ocsid` int(11) DEFAULT NULL,
`max_glpidate` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ocsservers_id` (`ocsservers_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ";
$DB->query($query) or die($DB->error());
foreach (getAllDatasFromTable('glpi_plugin_massocsimport_servers') as $thread) {
$query = "INSERT INTO `glpi_plugin_ocsinventoryng_servers`
(`id` ,`ocsservers_id` ,`max_ocsid` ,`max_glpidate`)
VALUES ('".$thread['id']."',
'".$thread['ocsservers_id']."',
'".$thread['max_ocsid']."',
'".$thread['max_glpidate']."');";
$DB->queryOrDie($query, $DB->error());
}
$migration->renameTable("glpi_plugin_massocsimport_servers",
"backup_glpi_plugin_massocsimport_servers");
$migration->changeField("glpi_plugin_ocsinventoryng_servers", "ocsservers_id",
"plugin_ocsinventoryng_ocsservers_id", 'integer');
$query = "UPDATE `glpi_notificationtemplates`
SET `itemtype` = 'PluginOcsinventoryngNotimportedcomputer'
WHERE `itemtype` = 'PluginMassocsimportNotimported'";
$DB->queryOrDie($query, $DB->error());
$query = "UPDATE `glpi_notifications`
SET `itemtype` = 'PluginOcsinventoryngNotimportedcomputer'
WHERE `itemtype` = 'PluginMassocsimportNotimported'";
$DB->queryOrDie($query, $DB->error());
$query = "UPDATE `glpi_crontasks`
SET `itemtype` = 'PluginOcsinventoryngThread'
WHERE `itemtype` = 'PluginMassocsimportThread';";
$DB->queryOrDie($query, $DB->error());
$query = "UPDATE `glpi_alerts`
SET `itemtype` = 'PluginOcsinventoryngNotimportedcomputer'
WHERE `itemtype` IN ('PluginMassocsimportNotimported')";
$DB->queryOrDie($query, $DB->error());
}
$migration->executeMigration();
$query = "SELECT `id`
FROM `glpi_notificationtemplates`
WHERE `itemtype` = 'PluginOcsinventoryngNotimportedcomputer'";
$result = $DB->query($query);
if (!$DB->numrows($result)) {
//Add template
$query = "INSERT INTO `glpi_notificationtemplates`
VALUES (NULL, 'Computers not imported', 'PluginOcsinventoryngNotimportedcomputer',
NOW(), '', NULL);";
$DB->queryOrDie($query, $DB->error());
$templates_id = $DB->insert_id();
$query = "INSERT INTO `glpi_notificationtemplatetranslations`
VALUES (NULL, $templates_id, '',
'##lang.notimported.action## : ##notimported.entity##',
'\r\n\n##lang.notimported.action## : ##notimported.entity##\n\n" .
"##FOREACHnotimported## \n##lang.notimported.reason## : ##notimported.reason##\n" .
"##lang.notimported.name## : ##notimported.name##\n" .
"##lang.notimported.deviceid## : ##notimported.deviceid##\n" .
"##lang.notimported.tag## : ##notimported.tag##\n##lang.notimported.serial## : ##notimported.serial## \r\n\n" .
" ##notimported.url## \n##ENDFOREACHnotimported## \r\n', '<p>##lang.notimported.action## : ##notimported.entity##<br /><br />" .
"##FOREACHnotimported## <br />##lang.notimported.reason## : ##notimported.reason##<br />" .
"##lang.notimported.name## : ##notimported.name##<br />" .
"##lang.notimported.deviceid## : ##notimported.deviceid##<br />" .
"##lang.notimported.tag## : ##notimported.tag##<br />" .
"##lang.notimported.serial## : ##notimported.serial##</p>\r\n<p><a href=\"##notimported.url##\">" .
"##notimported.url##</a><br />##ENDFOREACHnotimported##</p>');";
$DB->queryOrDie($query, $DB->error());
$query = "INSERT INTO `glpi_notifications`
VALUES (NULL, 'Computers not imported', 0, 'PluginOcsinventoryngNotimportedcomputer',
'not_imported', 'mail',".$templates_id.", '', 1, 1, NOW());";
$DB->queryOrDie($query, $DB->error());
}
$cron = new CronTask();
if (!$cron->getFromDBbyName('PluginOcsinventoryngThread','CleanOldThreads')) {
CronTask::Register('PluginOcsinventoryngThread', 'CleanOldThreads', HOUR_TIMESTAMP,
array('param' => 24));
}
if (!$cron->getFromDBbyName('PluginOcsinventoryngNotimportedcomputer','SendAlerts')) {
// creation du cron - param = duree de conservation
CronTask::Register('PluginOcsinventoryngNotimportedcomputer', 'SendAlerts', 10 * MINUTE_TIMESTAMP,
array('param' => 24));
}
return true;
}
function plugin_ocsinventoryng_upgrademassocsimport11to12() {
global $DB;
$migration= new Migration(12);
if (!TableExists("glpi_plugin_mass_ocs_import_config")) {
$query = "CREATE TABLE `glpi_plugin_mass_ocs_import_config` (
`ID` int(11) NOT NULL,
`enable_logging` int(1) NOT NULL default '1',
`thread_log_frequency` int(4) NOT NULL default '10',
`display_empty` int(1) NOT NULL default '1',
`delete_frequency` int(4) NOT NULL default '0',
`import_limit` int(11) NOT NULL default '0',
`default_ocs_server` int(11) NOT NULL default '-1',
`delay_refresh` varchar(4) NOT NULL default '0',
`delete_empty_frequency` int(4) NOT NULL default '0',
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ";
$DB->queryOrDie($query, "1.1 to 1.2 ".$DB->error());
$query = "INSERT INTO `glpi_plugin_mass_ocs_import_config`
(`ID`, `enable_logging`, `thread_log_frequency`, `display_empty`,
`delete_frequency`, `delete_empty_frequency`, `import_limit`,
`default_ocs_server` )
VALUES (1, 1, 5, 1, 2, 2, 0,-1)";
$DB->queryOrDie($query, "1.1 to 1.2 ".$DB->error());
}
$migration->addField("glpi_plugin_mass_ocs_import_config", "warn_if_not_imported", 'integer');
$migration->addField("glpi_plugin_mass_ocs_import_config", "not_imported_threshold", 'integer');
$migration->executeMigration();
}
function plugin_ocsinventoryng_upgrademassocsimport121to13() {
global $DB;
$migration = new Migration(13);
if (TableExists("glpi_plugin_mass_ocs_import_config")) {
$tables = array("glpi_plugin_massocsimport_servers" => "glpi_plugin_mass_ocs_import_servers",
"glpi_plugin_massocsimport" => "glpi_plugin_mass_ocs_import",
"glpi_plugin_massocsimport_config" => "glpi_plugin_mass_ocs_import_config",
"glpi_plugin_massocsimport_not_imported"
=> "glpi_plugin_mass_ocs_import_not_imported");
foreach ($tables as $new => $old) {
$migration->renameTable($old, $new);
}
$migration->changeField("glpi_plugin_massocsimport", "process_id", "process_id",
"BIGINT(20) NOT NULL DEFAULT '0'");
$migration->addField("glpi_plugin_massocsimport_config", "comments", 'text');
$migration->addField("glpi_plugin_massocsimport", "noupdate_machines_number", 'integer');
if (!TableExists("glpi_plugin_massocsimport_details")) {
$query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_massocsimport_details` (
`ID` int(11) NOT NULL auto_increment,
`process_id` bigint(10) NOT NULL default '0',
`thread_id` int(4) NOT NULL default '0',
`ocs_id` int(11) NOT NULL default '0',
`glpi_id` int(11) NOT NULL default '0',
`action` int(11) NOT NULL default '0',
`process_time` datetime DEFAULT NULL,
`ocs_server_id` int(4) NOT NULL default '1',
PRIMARY KEY (`ID`),
KEY `end_time` (`process_time`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
$DB->queryOrDie($query, "1.2.1 to 1.3 ".$DB->error());
}
//Add fields to the default view
$query = "INSERT INTO `glpi_displayprefs` (`itemtype`, `num`, `rank`, `users_id`)
VALUES (" . PLUGIN_MASSOCSIMPORT_NOTIMPORTED . ", 2, 1, 0),
(" . PLUGIN_MASSOCSIMPORT_NOTIMPORTED . ", 3, 2, 0),
(" . PLUGIN_MASSOCSIMPORT_NOTIMPORTED . ", 4, 3, 0),
(" . PLUGIN_MASSOCSIMPORT_NOTIMPORTED . ", 5, 4, 0),
(" . PLUGIN_MASSOCSIMPORT_NOTIMPORTED . ", 6, 5, 0),
(" . PLUGIN_MASSOCSIMPORT_NOTIMPORTED . ", 7, 6, 0),
(" . PLUGIN_MASSOCSIMPORT_NOTIMPORTED . ", 8, 7, 0),
(" . PLUGIN_MASSOCSIMPORT_NOTIMPORTED . ", 8, 7, 0),
(" . PLUGIN_MASSOCSIMPORT_NOTIMPORTED . ", 10, 9, 0),
(" . PLUGIN_MASSOCSIMPORT_DETAIL . ", 5, 1, 0),
(" . PLUGIN_MASSOCSIMPORT_DETAIL . ", 2, 2, 0),
(" . PLUGIN_MASSOCSIMPORT_DETAIL . ", 3, 3, 0),
(" . PLUGIN_MASSOCSIMPORT_DETAIL . ", 4, 4, 0),
(" . PLUGIN_MASSOCSIMPORT_DETAIL . ", 6, 5, 0)";
$DB->query($query);// or die($DB->error());
$drop_fields = array (//Was not used, debug only...
"glpi_plugin_massocsimport_config" => "warn_if_not_imported",
"glpi_plugin_massocsimport_config" => "not_imported_threshold",
//Logging must always be enable !
"glpi_plugin_massocsimport_config" => "enable_logging",
"glpi_plugin_massocsimport_config" => "delete_empty_frequency");
foreach ($drop_fields as $table => $field) {
$migration->dropField($table, $field);
}
}
$migration->executeMigration();
}
function plugin_ocsinventoryng_upgrademassocsimport13to14() {
global $DB;
$migration = new Migration(14);
$migration->renameTable("glpi_plugin_massocsimport", "glpi_plugin_massocsimport_threads");
$migration->changeField("glpi_plugin_massocsimport_threads", "ID", "id", 'autoincrement');
$migration->changeField("glpi_plugin_massocsimport_threads", "thread_id", "threadid", 'integer');
$migration->changeField("glpi_plugin_massocsimport_threads", "status", "status", 'integer');
$migration->changeField("glpi_plugin_massocsimport_threads", "ocs_server_id", "ocsservers_id",
'integer', array('value' => 1));
$migration->changeField("glpi_plugin_massocsimport_threads", "process_id", "processid",
'integer');
$migration->changeField("glpi_plugin_massocsimport_threads", "noupdate_machines_number",
"notupdated_machines_number", 'integer');
$migration->migrationOneTable("glpi_plugin_massocsimport_threads");
$migration->addKey("glpi_plugin_massocsimport_threads", array("processid", "threadid"),
"process_thread");
$migration->renameTable("glpi_plugin_massocsimport_config", "glpi_plugin_massocsimport_configs");
$migration->dropField("glpi_plugin_massocsimport_configs", "delete_frequency");
$migration->dropField("glpi_plugin_massocsimport_configs", "enable_logging");
$migration->dropField("glpi_plugin_massocsimport_configs", "delete_empty_frequency");
$migration->dropField("glpi_plugin_massocsimport_configs", "warn_if_not_imported");
$migration->dropField("glpi_plugin_massocsimport_configs", "not_imported_threshold");
$migration->changeField("glpi_plugin_massocsimport_configs", "ID", "id", 'autoincrement');
$migration->changeField("glpi_plugin_massocsimport_configs", "thread_log_frequency",
"thread_log_frequency", 'integer', array('value' => 10));
$migration->changeField("glpi_plugin_massocsimport_configs", "display_empty", "is_displayempty",
'int(1) NOT NULL default 1');
$migration->changeField("glpi_plugin_massocsimport_configs", "default_ocs_server",
"ocsservers_id", 'integer', array('value' => -1));
$migration->changeField("glpi_plugin_massocsimport_configs", "delay_refresh", "delay_refresh",
'integer');
$migration->changeField("glpi_plugin_massocsimport_configs", "comments", "comment", 'text');
$migration->changeField("glpi_plugin_massocsimport_details", "ID", "id", 'autoincrement');
$migration->changeField("glpi_plugin_massocsimport_details", "process_id",
"plugin_massocsimport_threads_id", 'integer');
$migration->changeField("glpi_plugin_massocsimport_details", "thread_id", "threadid", 'integer');
$migration->changeField("glpi_plugin_massocsimport_details", "ocs_id", "ocsid", 'integer');
$migration->changeField("glpi_plugin_massocsimport_details", "glpi_id", "computers_id",
'integer');
$migration->changeField("glpi_plugin_massocsimport_details", "ocs_server_id",
"ocsservers_id", 'integer', array('value' => 1));
$migration->migrationOneTable('glpi_plugin_massocsimport_details');
$migration->addKey("glpi_plugin_massocsimport_details",
array("plugin_massocsimport_threads_id", "threadid"), "process_thread");
$migration->renameTable("glpi_plugin_massocsimport_not_imported",
"glpi_plugin_massocsimport_notimported");
$migration->changeField("glpi_plugin_massocsimport_notimported", "ID", "id", 'autoincrement');
$migration->changeField("glpi_plugin_massocsimport_notimported", "ocs_id", "ocsid", 'integer');
$migration->changeField("glpi_plugin_massocsimport_notimported", "ocs_server_id", "ocsservers_id",
'integer');
$migration->changeField("glpi_plugin_massocsimport_notimported", "deviceid", "ocs_deviceid",
'string');
$migration->changeField("glpi_plugin_massocsimport_servers", "ID", "id", 'autoincrement');
$migration->changeField("glpi_plugin_massocsimport_servers", "ocs_server_id", "ocsservers_id",
'integer');
$migration->changeField("glpi_plugin_massocsimport_servers", "max_ocs_id", "max_ocsid",
'int(11) DEFAULT NULL');
$migration->changeField("glpi_plugin_massocsimport_servers", "max_glpi_date", "max_glpidate",
'datetime DEFAULT NULL');
$migration->executeMigration();
}
function plugin_ocsinventoryng_upgrademassocsimport14to15() {
global $DB;
$migration = new Migration(15);
$migration->addField("glpi_plugin_massocsimport_threads", "not_unique_machines_number",
'integer');
$migration->addField("glpi_plugin_massocsimport_threads", "link_refused_machines_number",
'integer');
$migration->addField("glpi_plugin_massocsimport_threads", "entities_id", 'integer');
$migration->addField("glpi_plugin_massocsimport_threads", "rules_id", 'text');
$migration->addField("glpi_plugin_massocsimport_configs", "allow_ocs_update", 'bool');
$migration->addField("glpi_plugin_massocsimport_notimported", "reason", 'integer');
if (!countElementsInTable('glpi_displaypreferences',
"`itemtype`='PluginMassocsimportNotimported'
AND `num`='10' AND `users_id`='0'")) {
$query = "INSERT INTO `glpi_displaypreferences`
(`itemtype`, `num`, `rank`, `users_id`)
VALUES ('PluginMassocsimportNotimported', 10, 9, 0)";
$DB->queryOrDie($query, "1.5 insert into glpi_displaypreferences " .$DB->error());
}
$migration->addField("glpi_plugin_massocsimport_notimported", "serial", 'string',
array('value' => ''));
$migration->addField("glpi_plugin_massocsimport_notimported", "comment", "TEXT NOT NULL");
$migration->addField("glpi_plugin_massocsimport_notimported", "rules_id", 'text');
$migration->addField("glpi_plugin_massocsimport_notimported", "entities_id", 'integer');
$migration->addField("glpi_plugin_massocsimport_details", "entities_id", 'integer');
$migration->addField("glpi_plugin_massocsimport_details", "rules_id", 'text');
$query = "SELECT id " .
"FROM `glpi_notificationtemplates` " .
"WHERE `itemtype`='PluginMassocsimportNotimported'";
$result = $DB->query($query);
if (!$DB->numrows($result)) {
//Add template
$query = "INSERT INTO `glpi_notificationtemplates` " .
"VALUES (NULL, 'Computers not imported', 'PluginMassocsimportNotimported',
NOW(), '', '');";
$DB->queryOrDie($query, $DB->error());
$templates_id = $DB->insert_id();
$query = "INSERT INTO `glpi_notificationtemplatetranslations` " .
"VALUES(NULL, $templates_id, '', '##lang.notimported.action## : ##notimported.entity##'," .
" '\r\n\n##lang.notimported.action## : ##notimported.entity##\n\n" .
"##FOREACHnotimported## \n##lang.notimported.reason## : ##notimported.reason##\n" .
"##lang.notimported.name## : ##notimported.name##\n" .
"##lang.notimported.deviceid## : ##notimported.deviceid##\n" .
"##lang.notimported.tag## : ##notimported.tag##\n##lang.notimported.serial## : ##notimported.serial## \r\n\n" .
" ##notimported.url## \n##ENDFOREACHnotimported## \r\n', '<p>##lang.notimported.action## : ##notimported.entity##<br /><br />" .
"##FOREACHnotimported## <br />##lang.notimported.reason## : ##notimported.reason##<br />" .
"##lang.notimported.name## : ##notimported.name##<br />" .
"##lang.notimported.deviceid## : ##notimported.deviceid##<br />" .
"##lang.notimported.tag## : ##notimported.tag##<br />" .
"##lang.notimported.serial## : ##notimported.serial##</p>\r\n<p><a href=\"##infocom.url##\">" .
"##notimported.url##</a><br />##ENDFOREACHnotimported##</p>');";
$DB->queryOrDie($query, $DB->error());
$query = "INSERT INTO `glpi_notifications`
VALUES (NULL, 'Computers not imported', 0, 'PluginMassocsimportNotimported',
'not_imported', 'mail',".$templates_id.", '', 1, 1, NOW());";
$DB->queryOrDie($query, $DB->error());
}
$migration->executeMigration();
}
function plugin_ocsinventoryng_uninstall() {
global $DB;
include_once (GLPI_ROOT."/plugins/ocsinventoryng/inc/profile.class.php");
include_once (GLPI_ROOT."/plugins/ocsinventoryng/inc/menu.class.php");
$tables = array("glpi_plugin_ocsinventoryng_ocsservers",
"glpi_plugin_ocsinventoryng_ocslinks",
"glpi_plugin_ocsinventoryng_ocsadmininfoslinks",
"glpi_plugin_ocsinventoryng_profiles",
"glpi_plugin_ocsinventoryng_threads",
"glpi_plugin_ocsinventoryng_servers",
"glpi_plugin_ocsinventoryng_configs",
"glpi_plugin_ocsinventoryng_notimportedcomputers",
"glpi_plugin_ocsinventoryng_details",
"glpi_plugin_ocsinventoryng_registrykeys",
"glpi_plugin_ocsinventoryng_networkports",
"glpi_plugin_ocsinventoryng_networkporttypes",
"glpi_plugin_ocsinventoryng_ocsservers_profiles");
foreach ($tables as $table) {
$DB->query("DROP TABLE IF EXISTS `$table`;");
}
$tables_glpi = array("glpi_bookmarks", "glpi_displaypreferences",
"glpi_documents_items", "glpi_logs", "glpi_tickets");
foreach ($tables_glpi as $table_glpi) {
$DB->query("DELETE
FROM `".$table_glpi."`
WHERE `itemtype` IN ('PluginMassocsimportNotimported',
'PluginMassocsimportDetail',
'PluginOcsinventoryngOcsServer',
'PluginOcsinventoryngNotimportedcomputer',
'PluginOcsinventoryngDetail')");
}
$tables_ocs = array("ocs_glpi_crontasks", "ocs_glpi_displaypreferences",
"ocs_glpi_ocsadmininfoslinks", "ocs_glpi_ocslinks",
"ocs_glpi_ocsservers", "ocs_glpi_registrykeys", "ocs_glpi_profiles");
foreach ($tables_ocs as $table_ocs) {
$DB->query("DROP TABLE IF EXISTS `$table_ocs`;");
}
$tables_mass = array("backup_glpi_plugin_massocsimport_configs", "backup_glpi_plugin_massocsimport_details",
"backup_glpi_plugin_massocsimport_notimported", "backup_glpi_plugin_massocsimport_servers",
"backup_glpi_plugin_massocsimport_threads");
foreach ($tables_mass as $table_mass) {
$DB->query("DROP TABLE IF EXISTS `$table_mass`;");
}
$query = "DELETE
FROM `glpi_alerts`
WHERE `itemtype` IN ('PluginMassocsimportNotimported',
'PluginOcsinventoryngNotimportedcomputer')";
$DB->queryOrDie($query, $DB->error());
// clean rules
$rule = new RuleImportEntity();
foreach ($DB->request("glpi_rules", array('sub_type' => 'RuleImportEntity')) AS $data) {
$rule->delete($data);
}
$rule = new RuleImportComputer();
foreach ($DB->request("glpi_rules", array('sub_type' => 'RuleImportComputer')) AS $data) {
$rule->delete($data);
}
$notification = new Notification();
foreach (getAllDatasFromTable($notification->getTable(),
"`itemtype` IN ('PluginMassocsimportNotimported',
'PluginOcsinventoryngNotimportedcomputer')") as $data) {
$notification->delete($data);
}
$template = new NotificationTemplate();
foreach (getAllDatasFromTable($template->getTable(),
"`itemtype` IN ('PluginMassocsimportNotimported',
'PluginOcsinventoryngNotimportedcomputer')") as $data) {
$template->delete($data);
}
$cron = new CronTask;
if ($cron->getFromDBbyName('PluginMassocsimportThread', 'CleanOldThreads')) {
CronTask::Unregister('massocsimport');
}
if ($cron->getFromDBbyName('PluginOcsinventoryngThread', 'CleanOldThreads')) {
CronTask::Unregister('ocsinventoryng');
}
//Delete rights associated with the plugin
$profileRight = new ProfileRight();
foreach (PluginOcsinventoryngProfile::getAllRights() as $right) {
$profileRight->deleteByCriteria(array('name' => $right['field']));
}
PluginOcsinventoryngMenu::removeRightsFromSession();
PluginOcsinventoryngProfile::removeRightsFromSession();
return true;
}
function plugin_ocsinventoryng_getDropdown() {
// Table => Name
return array('PluginOcsinventoryngNetworkPortType' => PluginOcsinventoryngNetworkPortType::getTypeName(2),
'PluginOcsinventoryngNetworkPort' => PluginOcsinventoryngNetworkPort::getTypeName(2));
}
/**
* Define dropdown relations
**/
function plugin_ocsinventoryng_getDatabaseRelations() {
$plugin = new Plugin();
if ($plugin->isActivated("ocsinventoryng")) {
return array("glpi_plugin_ocsinventoryng_ocsservers"
=> array("glpi_plugin_ocsinventoryng_ocslinks"
=> "plugin_ocsinventoryng_ocsservers_id",
"glpi_plugin_ocsinventoryng_ocsadmininfoslinks"
=> "plugin_ocsinventoryng_ocsservers_id"),
"glpi_entities"
=> array("glpi_plugin_ocsinventoryng_ocslinks" => "entities_id"),
"glpi_computers"
=> array("glpi_plugin_ocsinventoryng_ocslinks" => "computers_id",
"glpi_plugin_ocsinventoryng_registrykeys" => "computers_id"),
"glpi_states"
=> array("glpi_plugin_ocsinventoryng_ocsservers" => "states_id_default"),
"glpi_plugin_ocsinventoryng_devicebiosdatas"
=> array("glpi_plugin_ocsinventoryng_items_devicebiosdatas" => "plugin_ocsinventoryng_devicebiosdatas_id"),
"glpi_manufacturers"
=> array("glpi_plugin_ocsinventoryng_devicebiosdatas" => "manufacturers_id"));
}
return array ();
}
function plugin_ocsinventoryng_postinit() {
global $CFG_GLPI, $PLUGIN_HOOKS;
$PLUGIN_HOOKS['pre_item_add']['ocsinventoryng'] = array();
$PLUGIN_HOOKS['item_update']['ocsinventoryng'] = array();
$PLUGIN_HOOKS['pre_item_add']['ocsinventoryng']
= array('Computer_Item' => array('PluginOcsinventoryngOcslink', 'addComputer_Item'));
$PLUGIN_HOOKS['item_update']['ocsinventoryng']
= array('Computer' => array('PluginOcsinventoryngOcslink', 'updateComputer'));
$PLUGIN_HOOKS['pre_item_purge']['ocsinventoryng']
= array('Computer' => array('PluginOcsinventoryngOcslink', 'purgeComputer'),
'Computer_Item' => array('PluginOcsinventoryngOcslink', 'purgeComputer_Item'));
foreach (PluginOcsinventoryngOcsServer::getTypes(true) as $type) {
CommonGLPI::registerStandardTab($type, 'PluginOcsinventoryngOcsServer');
}
}
/**
* @param $type
**/
//TODO && use right for rules
function plugin_ocsinventoryng_MassiveActions($type) {
switch ($type) {
case 'PluginOcsinventoryngNotimportedcomputer' :
$actions = array ();
$actions['PluginOcsinventoryngNotimportedcomputer'.MassiveAction::CLASS_ACTION_SEPARATOR."plugin_ocsinventoryng_replayrules"] = __("Restart import", 'ocsinventoryng');
$actions['PluginOcsinventoryngNotimportedcomputer'.MassiveAction::CLASS_ACTION_SEPARATOR."plugin_ocsinventoryng_import"] = __("Import in the entity",
'ocsinventoryng');
$plugin = new Plugin;
if ($plugin->isActivated("uninstall")) {
$actions['PluginOcsinventoryngNotimportedcomputer'.MassiveAction::CLASS_ACTION_SEPARATOR."plugin_ocsinventoryng_delete"] = __('Delete computer in OCSNG',
'ocsinventoryng');
}
return $actions;
case 'Computer' :
if (Session::haveRight("plugin_ocsinventoryng", UPDATE)
|| Session::haveRight("plugin_ocsinventoryng_sync", UPDATE)) {
return array(// Specific one
'PluginOcsinventoryngOcsServer'.MassiveAction::CLASS_ACTION_SEPARATOR."plugin_ocsinventoryng_force_ocsng_update"
=> __('Force synchronization OCSNG',
'ocsinventoryng'),
'PluginOcsinventoryngOcsServer'.MassiveAction::CLASS_ACTION_SEPARATOR."plugin_ocsinventoryng_lock_ocsng_field" => __('Lock fields',
'ocsinventoryng'),
'PluginOcsinventoryngOcsServer'.MassiveAction::CLASS_ACTION_SEPARATOR."plugin_ocsinventoryng_unlock_ocsng_field" => __('Unlock fields',
'ocsinventoryng'));
}
break;
case 'NetworkPort':
if (Session::haveRight("plugin_ocsinventoryng", UPDATE)
&& Session::haveRight('networking',UPDATE)) {
return array('PluginOcsinventoryngNetworkPort'.MassiveAction::CLASS_ACTION_SEPARATOR.'plugin_ocsinventoryng_update_networkport_type'
=> __('Update networkport types',
'ocsinventoryng'));
}
}
return array ();
}
/**
* @param $itemtype
**/
function plugin_ocsinventoryng_getAddSearchOptions($itemtype) {
$sopt = array();
if ($itemtype == 'Computer') {
if (Session::haveRight("plugin_ocsinventoryng_view", READ)) {
$sopt[10002]['table'] = 'glpi_plugin_ocsinventoryng_ocslinks';
$sopt[10002]['field'] = 'last_update';
$sopt[10002]['name'] = __('GLPI import date', 'ocsinventoryng');
$sopt[10002]['datatype'] = 'datetime';
$sopt[10002]['massiveaction'] = false;
$sopt[10002]['joinparams'] = array('jointype' => 'child');
$sopt[10003]['table'] = 'glpi_plugin_ocsinventoryng_ocslinks';
$sopt[10003]['field'] = 'last_ocs_update';
$sopt[10003]['name'] = __('Last OCSNG inventory date', 'ocsinventoryng');
$sopt[10003]['datatype'] = 'datetime';
$sopt[10003]['massiveaction'] = false;
$sopt[10003]['joinparams'] = array('jointype' => 'child');
$sopt[10001]['table'] = 'glpi_plugin_ocsinventoryng_ocslinks';
$sopt[10001]['field'] = 'use_auto_update';
$sopt[10001]['linkfield'] = '_auto_update_ocs'; // update through compter update process
$sopt[10001]['name'] = __('Automatic update OCSNG', 'ocsinventoryng');
$sopt[10001]['datatype'] = 'bool';
$sopt[10001]['joinparams'] = array('jointype' => 'child');
$sopt[10004]['table'] = 'glpi_plugin_ocsinventoryng_ocslinks';
$sopt[10004]['field'] = 'ocs_agent_version';
$sopt[10004]['name'] = __('Inventory agent', 'ocsinventoryng');
$sopt[10004]['massiveaction'] = false;
$sopt[10004]['joinparams'] = array('jointype' => 'child');
$sopt[10005]['table'] = 'glpi_plugin_ocsinventoryng_ocslinks';
$sopt[10005]['field'] = 'tag';
$sopt[10005]['name'] = __('OCSNG TAG', 'ocsinventoryng');
$sopt[10005]['datatype'] = 'string';
$sopt[10005]['massiveaction'] = false;
$sopt[10005]['joinparams'] = array('jointype' => 'child');
$sopt[10006]['table'] = 'glpi_plugin_ocsinventoryng_ocslinks';
$sopt[10006]['field'] = 'ocsid';
$sopt[10006]['name'] = __('OCSNG ID', 'ocsinventoryng');
$sopt[10006]['datatype'] = 'number';
$sopt[10006]['massiveaction'] = false;
$sopt[10006]['joinparams'] = array('jointype' => 'child');
$sopt[10007]['table'] = 'glpi_plugin_ocsinventoryng_ocslinks';
$sopt[10007]['field'] = 'last_ocs_conn';
$sopt[10007]['name'] = __('Last OCSNG connection date', 'ocsinventoryng');
$sopt[10007]['datatype'] = 'date';
$sopt[10007]['massiveaction'] = false;
$sopt[10007]['joinparams'] = array('jointype' => 'child');
$sopt[10008]['table'] = 'glpi_plugin_ocsinventoryng_ocslinks';
$sopt[10008]['field'] = 'ip_src';
$sopt[10008]['name'] = __('IP Source', 'ocsinventoryng');
$sopt[10008]['datatype'] = 'string';
$sopt[10008]['massiveaction'] = false;
$sopt[10008]['joinparams'] = array('jointype' => 'child');
//$sopt['registry'] = __('Registry', 'ocsinventoryng');
$sopt[10010]['table'] = 'glpi_plugin_ocsinventoryng_registrykeys';
$sopt[10010]['field'] = 'value';
$sopt[10010]['name'] = sprintf(__('%1$s: %2$s'), __('Registry',
'ocsinventoryng'), __('Key/Value',
'ocsinventoryng'));
$sopt[10010]['forcegroupby'] = true;
$sopt[10010]['massiveaction'] = false;
$sopt[10010]['joinparams'] = array('jointype' => 'child');
$sopt[10011]['table'] = 'glpi_plugin_ocsinventoryng_registrykeys';
$sopt[10011]['field'] = 'ocs_name';
$sopt[10011]['name'] = sprintf(__('%1$s: %2$s'), __('Registry',
'ocsinventoryng'), __('OCSNG name',
'ocsinventoryng'));
$sopt[10011]['forcegroupby'] = true;
$sopt[10011]['massiveaction'] = false;
$sopt[10011]['joinparams'] = array('jointype' => 'child');
}
}
return $sopt;
}
/**
* @param $type
* @param $ID
* @param $data
* @param $num
**/
function plugin_ocsinventoryng_displayConfigItem($type, $ID, $data, $num) {
$searchopt = &Search::getOptions($type);
$table = $searchopt[$ID]["table"];
$field = $searchopt[$ID]["field"];
switch ($table.'.'.$field) {
case "glpi_plugin_ocsinventoryng_ocslinks.last_update" :
case "glpi_plugin_ocsinventoryng_ocslinks.last_ocs_update" :
return " class='center'";
}
return "";
}
/**
* @param $type
* @param $id
* @param $num
**/
function plugin_ocsinventoryng_addSelect($type, $id, $num) {
$searchopt = &Search::getOptions($type);
$table = $searchopt[$id]["table"];
$field = $searchopt[$id]["field"];
$out = "`$table`.`$field` AS ITEM_$num,
`$table`.`ocsid` AS ocsid,
`$table`.`plugin_ocsinventoryng_ocsservers_id` AS plugin_ocsinventoryng_ocsservers_id, ";
if ($num == 0) {
switch ($type) {
case 'PluginOcsinventoryngNotimportedcomputer' :
return $out;
case 'PluginOcsinventoryngDetail' :
$out .= "`$table`.`plugin_ocsinventoryng_threads_id`,
`$table`.`threadid`, ";
return $out;
}
return "";
}
}
/**
* @param $link
* @param $nott
* @param $type
* @param $ID
* @param $val
**/
function plugin_ocsinventoryng_addWhere($link, $nott, $type, $ID, $val) {
$searchopt = &Search::getOptions($type);
$table = $searchopt[$ID]["table"];
$field = $searchopt[$ID]["field"];
$SEARCH = Search::makeTextSearch($val,$nott);
switch ($table.".".$field) {
case "glpi_plugin_ocsinventoryng_details.action" :
return $link." `$table`.`$field` = '$val' ";
}
return "";
}
/**
* @param $type
* @param $id
* @param $data
* @param $num
**/
function plugin_ocsinventoryng_giveItem($type, $id, $data, $num) {
global $CFG_GLPI, $DB;
$searchopt = &Search::getOptions($type);
$table = $searchopt[$id]["table"];
$field = $searchopt[$id]["field"];
switch ("$table.$field") {
case "glpi_plugin_ocsinventoryng_details.action" :
$detail = new PluginOcsinventoryngDetail();
return $detail->giveActionNameByActionID($data[$num][0]['name']);
case "glpi_plugin_ocsinventoryng_details.computers_id" :
$comp = new Computer();
$comp->getFromDB($data[$num][0]['name']);
return "<a href='".Toolbox::getItemTypeFormURL('Computer')."?id=".$data[$num][0]['name']."'>".
$comp->getName()."</a>";
case "glpi_plugin_ocsinventoryng_details.plugin_ocsinventoryng_ocsservers_id" :
$ocs = new PluginOcsinventoryngOcsServer();
$ocs->getFromDB($data[$num][0]['name']);
return "<a href='".Toolbox::getItemTypeFormURL('PluginOcsinventoryngOcsServer')."?id=".
$data[$num][0]['name']."'>".$ocs->getName()."</a>";
case "glpi_plugin_ocsinventoryng_details.rules_id" :
$detail = new PluginOcsinventoryngDetail();
$detail->getFromDB($data['id']);
return PluginOcsinventoryngNotimportedcomputer::getRuleMatchedMessage($detail->fields['rules_id']);
case "glpi_plugin_ocsinventoryng_notimportedcomputers.reason" :
return PluginOcsinventoryngNotimportedcomputer::getReason($data[$num][0]['name']);
}
return '';
}
/**
* @param $params array
**/
function plugin_ocsinventoryng_searchOptionsValues($params=array()) {
switch($params['searchoption']['field']) {
case "action":
PluginOcsinventoryngDetail::showActions($params['name'],$params['value']);
return true;
}
return false;
}
/**
*
* Criteria for rules
* @since 0.84
* @param $params input data
* @return an array of criteria
*/
function plugin_ocsinventoryng_getRuleCriteria($params) {
$criteria = array();
switch ($params['rule_itemtype']) {
case 'RuleImportEntity':
$criteria['TAG']['table'] = 'accountinfo';
$criteria['TAG']['field'] = 'TAG';
$criteria['TAG']['name'] = __('OCSNG TAG', 'ocsinventoryng');
$criteria['TAG']['linkfield'] = 'HARDWARE_ID';
$criteria['DOMAIN']['table'] = 'hardware';
$criteria['DOMAIN']['field'] = 'WORKGROUP';
$criteria['DOMAIN']['name'] = __('Domain');
$criteria['DOMAIN']['linkfield'] = '';
$criteria['OCS_SERVER']['table'] = 'glpi_plugin_ocsinventoryng_ocsservers';
$criteria['OCS_SERVER']['field'] = 'name';
$criteria['OCS_SERVER']['name'] = _n('OCSNG server', 'OCSNG servers', 1,
'ocsinventoryng');
$criteria['OCS_SERVER']['linkfield'] = '';
$criteria['OCS_SERVER']['type'] = 'dropdown';
$criteria['OCS_SERVER']['virtual'] = true;
$criteria['OCS_SERVER']['id'] = 'ocs_server';
$criteria['IPSUBNET']['table'] = 'networks';
$criteria['IPSUBNET']['field'] = 'IPSUBNET';
$criteria['IPSUBNET']['name'] = __('Subnet');
$criteria['IPSUBNET']['linkfield'] = 'HARDWARE_ID';
$criteria['IPADDRESS']['table'] = 'networks';
$criteria['IPADDRESS']['field'] = 'IPADDRESS';
$criteria['IPADDRESS']['name'] = __('IP address');
$criteria['IPADDRESS']['linkfield'] = 'HARDWARE_ID';
$criteria['MACHINE_NAME']['table'] = 'hardware';
$criteria['MACHINE_NAME']['field'] = 'NAME';
$criteria['MACHINE_NAME']['name'] = __("Computer's name");
$criteria['MACHINE_NAME']['linkfield'] = '';
$criteria['DESCRIPTION']['table'] = 'hardware';
$criteria['DESCRIPTION']['field'] = 'DESCRIPTION';
$criteria['DESCRIPTION']['name'] = __('Description');
$criteria['DESCRIPTION']['linkfield'] = '';
$criteria['SSN']['table'] = 'bios';
$criteria['SSN']['field'] = 'SSN';
$criteria['SSN']['name'] = __('Serial number');
$criteria['SSN']['linkfield'] = 'HARDWARE_ID';
break;
case 'RuleImportComputer':
$criteria['ocsservers_id']['table'] = 'glpi_plugin_ocsinventoryng_ocsservers';
$criteria['ocsservers_id']['field'] = 'name';
$criteria['ocsservers_id']['name'] = _n('OCSNG server', 'OCSNG servers', 1,
'ocsinventoryng');
$criteria['ocsservers_id']['linkfield'] = '';
$criteria['ocsservers_id']['type'] = 'dropdown';
$criteria['TAG']['name'] = __('OCSNG TAG', 'ocsinventoryng');
break;
}
return $criteria;
}
/**
*
* Actions for rules
* @since 0.84
* @param $params input data
* @return an array of actions
*/
function plugin_ocsinventoryng_getRuleActions($params) {
//
$actions = array();
switch ($params['rule_itemtype']) {
case 'RuleImportEntity':
$actions['_affect_entity_by_tag']['name'] = __('Entity from TAG');
$actions['_affect_entity_by_tag']['type'] = 'text';
$actions['_affect_entity_by_tag']['force_actions'] = array('regex_result');
break;
case 'RuleImportComputer':
$actions['_fusion']['name'] = _n('OCSNG link', 'OCSNG links', 1, 'ocsinventoryng');
$actions['_fusion']['type'] = 'fusion_type';
break;
}
return $actions;
}
/**
* @see inc/RuleCollection::prepareInputDataForProcess()
* @since 0.84
* @param $params input data
* @return an array of criteria value to add for processing
**/
function plugin_ocsinventoryng_ruleCollectionPrepareInputDataForProcess($params) {
switch ($params['rule_itemtype']) {
case 'RuleImportEntity':
case 'RuleImportComputer':
if ($params['rule_itemtype'] == 'RuleImportEntity') {
$ocsservers_id = $params['values']['input']['ocsservers_id'];
} else {
$ocsservers_id = $params['values']['params']['plugin_ocsinventoryng_ocsservers_id'];
}
$rule_parameters = array(
'ocsservers_id' => $ocsservers_id,
'OCS_SERVER' => $ocsservers_id
);
if (isset($params['values']['params']['ocsid'])) {
$ocsid = $params['values']['params']['ocsid'];
} else if ($params['values']['input']['id']) {
$ocsid = $params['values']['input']['id'];
}
$ocsClient = PluginOcsinventoryngOcsServer::getDBocs($ocsservers_id);
$tables = array_keys(plugin_ocsinventoryng_getTablesForQuery());
$fields = plugin_ocsinventoryng_getFieldsForQuery();
$ocsComputer = $ocsClient->getComputer($ocsid, array(
'DISPLAY' => array(
'CHECKSUM' => $ocsClient->getChecksumForTables($tables) | PluginOcsinventoryngOcsClient::CHECKSUM_NETWORK_ADAPTERS,
'WANTED' => $ocsClient->getWantedForTables($tables),
)
));
if (!is_null($ocsComputer)) {
if (isset($ocsComputer['NETWORKS'])) {
$networks = $ocsComputer['NETWORKS'];
$ipblacklist = Blacklist::getIPs();
$macblacklist = Blacklist::getMACs();
foreach ($networks as $data) {
if (isset($data['IPSUBNET'])) {
$rule_parameters['IPSUBNET'][] = $data['IPSUBNET'];
}
if (isset($data['MACADDR']) && !in_array($data['MACADDR'], $macblacklist)) {
$rule_parameters['MACADDRESS'][] = $data['MACADDR'];
}
if (isset($data['IPADDRESS']) && !in_array($data['IPADDRESS'], $ipblacklist)) {
$rule_parameters['IPADDRESS'][] = $data['IPADDRESS'];
}
}
$ocs_data = array();
foreach ($fields as $field) {
// TODO cleaner way of getting fields
$field = explode('.', $field);
if (count($field) < 2) {
continue;
}
$table = strtoupper($field[0]);
$fieldSql = explode(' ', $field[1]);
$ocsField = $fieldSql[0];
$glpiField = $fieldSql[count($fieldSql) -1];
$section = array();
if (isset($ocsComputer[$table])) {
$section = $ocsComputer[$table];
}
if (array_key_exists($ocsField, $section)) {
// Not multi
$ocs_data[$glpiField][] = $section[$ocsField];
} else {
foreach ($section as $sectionLine) {
$ocs_data[$glpiField][] = $sectionLine[$ocsField];
}
}
}
//This case should never happend but...
//Sometimes OCS can't find network ports but fill the right ip in hardware table...
//So let's use the ip to proceed rules (if IP is a criteria of course)
if (in_array("IPADDRESS",$fields) && !isset($ocs_data['IPADDRESS'])) {
$ocs_data['IPADDRESS']
= PluginOcsinventoryngOcsServer::getGeneralIpAddress($ocsservers_id, $ocsid);
}
return array_merge($rule_parameters, $ocs_data);
}
}
}
return array();
}
/**
*
* Actions for rules
* @since 0.84
* @param $params input data
* @return an array of actions
*/
function plugin_ocsinventoryng_executeActions($params) {
$action = $params['action'];
$output = $params['output'];
switch ($params['params']['rule_itemtype']) {
case 'RuleImportComputer':
if ($action->fields['field'] == '_fusion') {
if ($action->fields["value"] == RuleImportComputer::RULE_ACTION_LINK_OR_IMPORT) {
if (isset($params['params']['criterias_results']['found_computers'])) {
$output['found_computers'] = $params['params']['criterias_results']['found_computers'];
$output['action'] = PluginOcsinventoryngOcsServer::LINK_RESULT_LINK;
} else {
$output['action'] = PluginOcsinventoryngOcsServer::LINK_RESULT_IMPORT;
}
} else if ($action->fields["value"] == RuleImportComputer::RULE_ACTION_LINK_OR_NO_IMPORT) {
if (isset($params['params']['criterias_results']['found_computers'])) {
$output['found_computers'] = $params['params']['criterias_results']['found_computers'];;
$output['action'] = PluginOcsinventoryngOcsServer::LINK_RESULT_LINK;
} else {
$output['action'] = PluginOcsinventoryngOcsServer::LINK_RESULT_NO_IMPORT;
}
}
} else {
$output['action'] = PluginOcsinventoryngOcsServer::LINK_RESULT_NO_IMPORT;
}
break;
}
return $output;
}
/**
*
* Preview for test a Rule
* @since 0.84
* @param $params input data
* @return $output array
*/
function plugin_ocsinventoryng_preProcessRulePreviewResults($params){
$output = $params['output'];
switch ($params['params']['rule_itemtype']) {
case 'RuleImportComputer':
//If ticket is assign to an object, display this information first
if (isset($output["action"])){
echo "<tr class='tab_bg_2'>";
echo "<td>".__('Action type')."</td>";
echo "<td>";
switch ($output["action"]){
case PluginOcsinventoryngOcsServer::LINK_RESULT_LINK:
_e('Link possible', 'ocsinventoryng');
break;
case PluginOcsinventoryngOcsServer::LINK_RESULT_NO_IMPORT:
_e('Import refused', 'ocsinventoryng');
break;
case PluginOcsinventoryngOcsServer::LINK_RESULT_IMPORT:
_e('New computer created in GLPI', 'ocsinventoryng');
break;
}
echo "</td>";
echo "</tr>";
if ($output["action"] != PluginOcsinventoryngOcsServer::LINK_RESULT_NO_IMPORT
&& isset($output["found_computers"])){
echo "<tr class='tab_bg_2'>";
$item = new Computer;
if ($item->getFromDB($output["found_computers"][0])){
echo "<td>".__('Link with computer', 'ocsinventoryng')."</td>";
echo "<td>".$item->getLink(array('comments' => true))."</td>";
}
echo "</tr>";
}
}
break;
}
return $output;
}
/**
*
* Preview for test a RuleCoolection
* @since 0.84
* @param $params input data
* @return $output array
*/
function plugin_ocsinventoryng_preProcessRuleCollectionPreviewResults($params){
return plugin_ocsinventoryng_preProcessRulePreviewResults($params);
}
/**
* Get the list of all tables to include in the query
*
* @return an array of table names
**/
function plugin_ocsinventoryng_getTablesForQuery() {
$tables = array();
$crits = plugin_ocsinventoryng_getRuleCriteria(array('rule_itemtype' => 'RuleImportEntity'));
foreach ($crits as $criteria) {
if ((!isset($criteria['virtual'])
|| !$criteria['virtual'])
&& $criteria['table'] != ''
&& !isset($tables[$criteria["table"]])) {
$tables[$criteria['table']] = $criteria['linkfield'];
}
}
return $tables;
}
/**
* * Get fields needed to process criterias
*
* @param $withouttable fields without tablename ? (default 0)
*
* @return an array of needed fields
**/
function plugin_ocsinventoryng_getFieldsForQuery($withouttable=0) {
$fields = array();
foreach (plugin_ocsinventoryng_getRuleCriteria(array('rule_itemtype' => 'RuleImportEntity')) as $key => $criteria) {
if ($withouttable) {
if (strcasecmp($key,$criteria['field']) != 0) {
$fields[] = $key;
} else {
$fields[] = $criteria['field'];
}
} else {
//If the field is different from the key
if (strcasecmp($key,$criteria['field']) != 0) {
$as = " AS ".$key;
} else {
$as = "";
}
//If the field name is not null AND a table name is provided
if (($criteria['field'] != ''
&& (!isset($criteria['virtual']) || !$criteria['virtual']))) {
if ( $criteria['table'] != '') {
$fields[] = $criteria['table'].".".$criteria['field'].$as;
} else {
$fields[] = $criteria['field'].$as;
}
} else {
$fields[] = $criteria['id'];
}
}
}
return $fields;
}
/**
* Get foreign fields needed to process criterias
*
* @return an array of needed fields
**/
function plugin_ocsinventoryng_getFKFieldsForQuery() {
$fields = array();
foreach (plugin_ocsinventoryng_getRuleCriteria(array('rule_itemtype'
=> 'RuleImportEntity')) as $criteria) {
//If the field name is not null AND a table name is provided
if ((!isset($criteria['virtual']) || !$criteria['virtual'])
&& $criteria['linkfield'] != '') {
$fields[] = $criteria['table'].".".$criteria['linkfield'];
}
}
return $fields;
}
/**
*
* Add global criteria for ruleImportComputer rules engine
* @since 1.0
* @param $global_criteria an array of global criteria for this rule engine
* @return the array including plugin's criteria
*/
function plugin_ocsinventoryng_ruleImportComputer_addGlobalCriteria($global_criteria) {
return array_merge($global_criteria, array('IPADDRESS', 'IPSUBNET', 'MACADDRESS'));
}
/**
*
* Get SQL restriction for ruleImportComputer
* @param params necessary parameters to build SQL restrict requests
* @return an array with SQL restrict resquests
* @since 1.0
*/
function plugin_ocsinventoryng_ruleImportComputer_getSqlRestriction($params = array()) {
// Search computer, in entity, not already linked
//resolve The rule result no preview : Drop this restriction `glpi_plugin_ocsinventoryng_ocslinks`.`computers_id` IS NULL
$params['sql_where'] .= " AND `glpi_computers`.`is_template` = '0' ";
$params['sql_where'] .= " AND `glpi_computers`.`entities_id` IN (".$params['where_entity'].")";
$params['sql_from'] = "`glpi_computers`
LEFT JOIN `glpi_plugin_ocsinventoryng_ocslinks`
ON (`glpi_computers`.`id` = `glpi_plugin_ocsinventoryng_ocslinks`.`computers_id`)";
$needport = false;
$needip = false;
foreach ($params['criteria'] as $criteria) {
switch ($criteria->fields['criteria']) {
case 'IPADDRESS' :
$ips =$params['input']["IPADDRESS"];
if (!is_array($ips)) {
$ips = array($params['input']["IPADDRESS"]);
}
if (count($ips)) {
$needport = true;
$needip = true;
$params['sql_where'] .= " AND `glpi_ipaddresses`.`name` IN ('";
$params['sql_where'] .= implode("','", $ips);
$params['sql_where'] .= "')";
} else {
$params['sql_where'] = " AND 0 ";
}
break;
case 'MACADDRESS' :
$macs =$params['input']["MACADDRESS"];
if (!is_array($macs)) {
$macs = array($params['input']["MACADDRESS"]);
}
if (count($macs)) {
$needport = true;
$params['sql_where'] .= " AND `glpi_networkports`.`mac` IN ('";
$params['sql_where'] .= implode("','",$macs);
$params['sql_where'] .= "')";
} else {
$params['sql_where'] = " AND 0 ";
}
break;
}
}
if ($needport) {
$params['sql_from'] .= " LEFT JOIN `glpi_networkports`
ON (`glpi_computers`.`id` = `glpi_networkports`.`items_id`
AND `glpi_networkports`.`itemtype` = 'Computer') ";
}
if ($needip) {
$params['sql_from'] .= " LEFT JOIN `glpi_networknames`
ON (`glpi_networkports`.`id` = `glpi_networknames`.`items_id`
AND `glpi_networknames`.`itemtype`='NetworkPort')
LEFT JOIN `glpi_ipaddresses`
ON (`glpi_ipaddresses`.`items_id` = `glpi_networknames`.`id`)";
}
return $params;
}
/**
*
* Display plugin's entries in unlock fields form
* @since 1.0
* @param $params an array which contains the item and the header boolean
* @return an array
*/
function plugin_ocsinventoryng_showLocksForItem($params = array()) {
global $DB;
$comp = $params['item'];
$header = $params['header'];
$ID = $comp->getID();
if (!Session::haveRight("computer", UPDATE)) {
return $params;
}
//First of all let's look it the computer is managed by OCS Inventory
$query = "SELECT *
FROM `glpi_plugin_ocsinventoryng_ocslinks`
WHERE `computers_id` = '$ID'";
$result = $DB->query($query);
if ($DB->numrows($result) == 1) {
$data = $DB->fetch_assoc($result);
// Print lock fields for OCSNG
$lockable_fields = PluginOcsinventoryngOcsServer::getLockableFields();
$locked = importArrayFromDB($data["computer_update"]);
if (!in_array(PluginOcsinventoryngOcsServer::IMPORT_TAG_078, $locked)) {
$locked = PluginOcsinventoryngOcsServer::migrateComputerUpdates($ID, $locked);
}
if (count($locked) > 0) {
foreach ($locked as $key => $val) {
if (!isset($lockable_fields[$val])) {
unset($locked[$key]);
}
}
}
if (count($locked)) {
$header = true;
echo "<tr><th colspan='2'>". _n('Locked field', 'Locked fields', 2, 'ocsinventoryng').
"</th></tr>\n";
foreach ($locked as $key => $val) {
echo "<tr class='tab_bg_1'>";
echo "<td class='center' width='10'>";
echo "<input type='checkbox' name='lockfield[" . $key . "]'></td>";
echo "<td class='left' width='95%'>" . $lockable_fields[$val] . "</td>";
echo "</tr>\n";
}
}
}
$params['header'] = $header;
return $params;
}
/**
*
* Unlock fields managed by the plugin
* @since 1.0
* @param $_POST array
*/
function plugin_ocsinventoryng_unlockFields($params = array()) {
$computer = new Computer();
$computer->check($_POST['id'], UPDATE);
if (isset($_POST["lockfield"]) && count($_POST["lockfield"])) {
foreach ($_POST["lockfield"] as $key => $val) {
PluginOcsinventoryngOcsServer::deleteInOcsArray($_POST["id"], $key, "computer_update");
}
}
}
/**
* Update plugin with new computers_id and new entities_id
*
* @param $options array of possible options
* - itemtype
* - ID old ID
* - newID new ID
* - entities_id new entities_id
**/
function plugin_ocsinventoryng_item_transfer($options=array()) {
global $DB;
if ($options['type'] == 'Computer') {
$query = "UPDATE glpi_plugin_ocsinventoryng_ocslinks
SET `computers_id` = '".$options['newID']."',
`entities_id` = '".$options['entities_id']."'
WHERE `computers_id` = '".$options['id']."'";
$DB->query($query);
Session::addMessageAfterRedirect("Transfer Computer Hook ". $options['type']." " .
$options['id']."->".$options['newID']);
return false;
}
}
//------------------- Locks migration -------------------
/**
* Move locks from ocslink.import_* to is_dynamic in related tables
*
* @param $migration
**/
function plugin_ocsinventoryng_migrateComputerLocks(Migration $migration) {
global $DB,$CFG_GLPI;
$import = array('import_printer' => 'Printer',
'import_monitor' => 'Monitor',
'import_peripheral' => 'Peripheral');
foreach ($import as $field => $itemtype) {
foreach ($DB->request('ocs_glpi_ocslinks', '', array('computers_id', $field)) as $data) {
if (FieldExists('ocs_glpi_ocslinks', $field)) {
$import_field = importArrayFromDB($data[$field]);
//If array is not empty
if (!empty($import_field)) {
$query_update = "UPDATE `glpi_computers_items`
SET `is_dynamic`='1'
WHERE `id` IN (".implode(',',array_keys($import_field)).")
AND `itemtype`='$itemtype'";
$DB->query($query_update);
}
}
}
$migration->dropField('ocs_glpi_ocslinks', $field);
}
//Migration disks and vms
$import = array('import_disk' => 'glpi_computerdisks',
'import_vm' => 'glpi_computervirtualmachines',
'import_software' => 'glpi_computers_softwareversions',
'import_ip' => 'glpi_networkports');
foreach ($import as $field => $table) {
if (FieldExists('ocs_glpi_ocslinks', $field)) {
foreach ($DB->request('ocs_glpi_ocslinks', '', array('computers_id', $field)) as $data) {
$import_field = importArrayFromDB($data[$field]);
//If array is not empty
if (!empty($import_field)) {
$in_where = "(".implode(',',array_keys($import_field)).")";
$query_update = "UPDATE `$table`
SET `is_dynamic`='1'
WHERE `id` IN $in_where";
$DB->query($query_update);
if ($table == 'glpi_networkports') {
$query_update = "UPDATE `glpi_networkports` AS PORT,
`glpi_networknames` AS NAME
SET NAME.`is_dynamic` = 1
WHERE PORT.`id` IN $in_where
AND NAME.`itemtype` = 'NetworkPort'
AND NAME.`items_id` = PORT.`id`";
$DB->query($query_update);
$query_update = "UPDATE `glpi_networkports` AS PORT,
`glpi_networknames` AS NAME,
`glpi_ipaddresses` AS ADDR
SET ADDR.`is_dynamic` = 1
WHERE PORT.`id` IN $in_where
AND NAME.`itemtype` = 'NetworkPort'
AND NAME.`items_id` = PORT.`id`
AND ADDR.`itemtype` = 'NetworkName'
AND ADDR.`items_id` = NAME.`id`";
$DB->query($query_update);
}
}
}
$migration->dropField('ocs_glpi_ocslinks', $field);
}
}
if (FieldExists('ocs_glpi_ocslinks', 'import_device')) {
foreach ($DB->request('ocs_glpi_ocslinks', '', array('computers_id', 'import_device'))
as $data) {
$import_device = importArrayFromDB($data['import_device']);
if (!in_array('_version_078_', $import_device)) {
$import_device = plugin_ocsinventoryng_migrateImportDevice($import_device);
}
$devices = array();
$types = $CFG_GLPI['ocsinventoryng_devices_index'];
foreach ($import_device as $key => $val) {
if (!$key) { // OcsServer::IMPORT_TAG_078
continue;
}
list($type, $nomdev) = explode('$$$$$', $val);
list($type, $iddev) = explode('$$$$$', $key);
if (!isset($types[$type])) { // should never happen
continue;
}
$devices[$types[$type]][] = $iddev;
}
foreach ($devices as $type => $data) {
//If array is not empty
$query_update = "UPDATE `".getTableForItemType($type)."`
SET `is_dynamic`='1'
WHERE `id` IN (".implode(',',$data).")";
$DB->query($query_update);
}
}
$migration->dropField('ocs_glpi_ocslinks', 'import_device');
}
$migration->migrationOneTable('ocs_glpi_ocslinks');
}
/**
* Migration import_device field if GLPI version is not 0.78
*
* @param $import_device array
*
* @return import_device array migrated in post 0.78 scheme
**/
function plugin_ocsinventoryng_migrateImportDevice($import_device=array()) {
$new_import_device = array('_version_078_');
if (count($import_device)) {
foreach ($import_device as $key=>$val) {
$tmp = explode('$$$$$', $val);
if (isset($tmp[1])) { // Except for old IMPORT_TAG
$tmp2 = explode('$$$$$', $key);
// Index Could be 1330395 (from glpi 0.72)
// Index Could be 5$$$$$5$$$$$5$$$$$5$$$$$5$$$$$1330395 (glpi 0.78 bug)
// So take the last part of the index
$key2 = $tmp[0].'$$$$$'.array_pop($tmp2);
$new_import_device[$key2] = $val;
}
}
}
return $new_import_device;
}
?>
|
gpl-2.0
|
peterhj/wgs-assembler
|
kmer/meryl/maskMers.C
|
16596
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "bio++.H"
#include "seqStream.H"
#include "libmeryl.H"
#include <algorithm>
#define MAX_COVERAGE 51
class mateRescueData {
public:
mateRescueData() {
_mean = 0;
_stddev = 0;
_coverage = 0;
_normal = 0L;
_normalZero = 0;
};
void init(int32 mean_, int32 stddev_, uint32 coverage_) {
_mean = mean_;
_stddev = stddev_;
_coverage = coverage_;
assert(_mean > 3 * _stddev);
double a = 1.0 / (_stddev * sqrt(2 * M_PI));
double c = 2 * _stddev * _stddev;
int32 b1l = (int32)floor(-3 * _stddev);
int32 b1h = (int32)ceil ( 3 * _stddev);
_normal = new double [b1h - b1l + 1];
_normalZero = -b1l;
for (int32 l=0; l<b1h - b1l + 1; l++)
_normal[l] = 0.0;
for (int32 l=b1l; l<b1h; l++)
_normal[l + _normalZero] = a * exp(- l*l / c);
};
~mateRescueData() {
};
int32 mean(void) { return(_mean); };
int32 stddev(void) { return(_stddev); };
uint32 coverage(void) { return(_coverage); };
double normal(int32 p) { return(_normal[p + _normalZero]); };
private:
int32 _mean;
int32 _stddev;
uint32 _coverage;
double *_normal;
int32 _normalZero;
};
class merMaskedSequence {
public:
merMaskedSequence(char *fastaName_, char *merylName_, uint32 onlySeqIID_=~uint32ZERO) {
_numSeq = 0;
_seqLen = 0L;
_masking = 0L;
_repeatID = 0L;
_merSize = 0;
strcpy(_fastaName, fastaName_);
strcpy(_merylName, merylName_);
strcpy(_maskMersName, _merylName);
strcat(_maskMersName, ".maskMers");
if (fileExists(_maskMersName))
loadMasking(onlySeqIID_);
else
buildMasking();
};
~merMaskedSequence() {
delete [] _seqLen;
for (uint32 i=0; i<_numSeq; i++) {
delete [] _masking[i];
delete [] _repeatID[i];
}
delete [] _masking;
delete [] _repeatID;
};
public:
uint32 numSeq(void) { return(_numSeq); };
int32 seqLen(uint32 i) { return(_seqLen[i]); };
char masking(uint32 s, uint32 p) { return(_masking[s][p]); };
uint32 repeatID(uint32 s, uint32 p) { return(_repeatID[s][p]); };
uint32 merSize(void) { return(_merSize); };
private:
void loadMasking(uint32 onlySeqIID_=~uint32ZERO); // Read the masking from the saved file
void saveMasking(void); // Write the masking to a file
void buildMasking(void); // Read the mers to build the masking
uint32 _numSeq;
int32 *_seqLen; // signed just for convenience later (positions are signed for same reason)
char **_masking;
uint32 **_repeatID;
uint32 _merSize;
char _fastaName[FILENAME_MAX];
char _merylName[FILENAME_MAX];
char _maskMersName[FILENAME_MAX];
};
void
merMaskedSequence::loadMasking(uint32 onlySeqIID_) {
FILE *maskMersFile = fopen(_maskMersName, "r");
fread(&_numSeq, sizeof(uint32), 1, maskMersFile);
fread(&_merSize, sizeof(uint32), 1, maskMersFile);
_seqLen = new int32 [_numSeq];
_masking = new char * [_numSeq];
_repeatID = new uint32 * [_numSeq];
fprintf(stderr, uint32FMT" sequences in '%s'\n", _numSeq, _fastaName);
fread( _seqLen, sizeof(uint32), _numSeq, maskMersFile);
for (uint32 i=0; i<_numSeq; i++) {
_masking[i] = 0L;
_repeatID[i] = 0L;
if ((onlySeqIID_ >= _numSeq) || (onlySeqIID_ == i)) {
fprintf(stderr, "Loading sequence "uint32FMT" of length "uint32FMT"\n", i, _seqLen[i]);
_masking[i] = new char [_seqLen[i]];
_repeatID[i] = new uint32 [_seqLen[i]];
//memset(_masking[i], 'g', sizeof(char) * _seqLen[i]);
//memset(_repeatID[i], 0, sizeof(uint32) * _seqLen[i]);
fread(_masking[i], sizeof(char), _seqLen[i], maskMersFile);
fread(_repeatID[i], sizeof(uint32), _seqLen[i], maskMersFile);
} else {
fseek(maskMersFile, sizeof(char) * _seqLen[i], SEEK_CUR);
fseek(maskMersFile, sizeof(uint32) * _seqLen[i], SEEK_CUR);
_seqLen[i] = 0;
}
}
fclose(maskMersFile);
}
void
merMaskedSequence::saveMasking(void) {
FILE *maskMersFile = fopen(_maskMersName, "w");
fwrite(&_numSeq, sizeof(uint32), 1, maskMersFile);
fwrite(&_merSize, sizeof(uint32), 1, maskMersFile);
fwrite( _seqLen, sizeof(uint32), _numSeq, maskMersFile);
for (uint32 i=0; i<_numSeq; i++) {
fwrite(_masking[i], sizeof(char), _seqLen[i], maskMersFile);
fwrite(_repeatID[i], sizeof(uint32), _seqLen[i], maskMersFile);
}
fclose(maskMersFile);
}
void
merMaskedSequence::buildMasking(void) {
seqStream *STR = new seqStream(_fastaName);
_numSeq = STR->numberOfSequences();
_seqLen = new int32 [_numSeq];
_masking = new char * [_numSeq];
_repeatID = new uint32 * [_numSeq];
_merSize = 0;
fprintf(stderr, uint32FMT" sequences in '%s'\n", _numSeq, _fastaName);
for (uint32 i=0; i<_numSeq; i++) {
_seqLen[i] = STR->lengthOf(i);
_masking[i] = new char [_seqLen[i]];
_repeatID[i] = new uint32 [_seqLen[i]];
memset(_masking[i], 'g', sizeof(char) * _seqLen[i]);
memset(_repeatID[i], 0, sizeof(uint32) * _seqLen[i]);
}
// g -> gap in sequence
// u -> unique mer
// r -> repeat mer
//
// For all the r's we also need to remember the other locations
// that repeat is at. We annotate the map with a repeat id, set if
// another copy of the repeat is nearby.
merylStreamReader *MS = new merylStreamReader(_merylName);
speedCounter *CT = new speedCounter(" Masking mers in sequence: %7.2f Mmers -- %5.2f Mmers/second\r", 1000000.0, 0x1fffff, true);
uint32 rid = 0;
_merSize = MS->merSize();
while (MS->nextMer()) {
//fprintf(stderr, "mer count="uint64FMT" pos="uint32FMT"\n", MS->theCount(), MS->getPosition(0));
if (MS->theCount() == 1) {
uint32 p = MS->getPosition(0);
uint32 s = STR->sequenceNumberOfPosition(p);
p -= STR->startOf(s);
_masking[s][p] = 'u';
} else {
std::sort(MS->thePositions(), MS->thePositions() + MS->theCount());
uint32 lastS = ~uint32ZERO;
uint32 lastP = 0;
rid++;
for (uint32 i=0; i<MS->theCount(); i++) {
uint32 p = MS->getPosition(i);
uint32 s = STR->sequenceNumberOfPosition(p);
p -= STR->startOf(s);
// Always set the masking.
_masking[s][p] = 'r';
// If there is a repeat close by, set the repeat ID.
if ((s == lastS) && (lastP + 40000 > p)) {
_repeatID[s][lastP] = rid;
_repeatID[s][p] = rid;
}
lastS = s;
lastP = p;
}
}
CT->tick();
}
delete CT;
delete MS;
delete STR;
saveMasking();
}
void
computeDensity(merMaskedSequence *S, char *outputPrefix) {
char outputName[FILENAME_MAX];
FILE *outputFile;
uint32 windowSizeMax = 10000;
for (uint32 s=0; s<S->numSeq(); s++) {
// seqLen == 0 iff that sequence is not loaded.
if (S->seqLen(s) == 0)
continue;
sprintf(outputName, "%s.density.seq"uint32FMTW(02), outputPrefix, s);
outputFile = fopen(outputName, "w");
fprintf(stderr, "Starting '%s'\n", outputName);
fprintf(outputFile, "#window\tunique\trepeat\tgaps\n");
// Not the most efficient, but good enough for us right now.
for (int32 p=0; p<S->seqLen(s); ) {
uint32 windowSize = 0;
uint32 uniqueSum = 0;
uint32 repeatSum = 0;
uint32 gapSum = 0;
while ((windowSize < windowSizeMax) &&
(p < S->seqLen(s))) {
char m = S->masking(s, p);
if (m == 'u') uniqueSum++;
if (m == 'g') gapSum++;
if (m == 'r') repeatSum++;
windowSize++;
p++;
}
fprintf(outputFile, uint32FMT"\t%f\t%f\t%f\n",
p - windowSize,
(double)uniqueSum / windowSize,
(double)repeatSum / windowSize,
(double)gapSum / windowSize);
}
fclose(outputFile);
}
}
// For each 'r' mer, compute the number of 'u' mers
// that are within some mean +- stddev range.
//
// We count for two blocks:
//
// | <- mean -> | <- mean -> |
// ---[block1]---------------mer---------------[block2]---
//
// Once we know that, we can compute the probability that
// a repeat mer can be rescued.
//
// p1 = uniq/total -- for 1 X coverage
// pn = 1 - (1-p1)^n -- for n X coverage
void
computeMateRescue(merMaskedSequence *S, char *outputPrefix, mateRescueData *lib, uint32 libLen) {
char outputName[FILENAME_MAX];
FILE *outputFile;
FILE *outputData;
uint32 closeRepeatsLen = 0;
uint32 closeRepeatsMax = 80000;
int32 *closeRepeats = new int32 [closeRepeatsMax];
speedCounter *CT = new speedCounter(" Examining repeats: %7.2f Kbases -- %5.2f Kbases/second\r", 1000.0, 0x1ffff, true);
uint32 totalDepth = 0;
for (uint32 l=0; l<libLen; l++)
totalDepth += lib[l].coverage();
for (uint32 s=0; s<S->numSeq(); s++) {
// seqLen == 0 iff that sequence is not loaded.
if (S->seqLen(s) == 0)
continue;
fprintf(stderr, "Starting sequence "uint32FMT"\n", s);
sprintf(outputName, "%s.mateRescue.seq"uint32FMTW(02)".out", outputPrefix, s);
outputFile = fopen(outputName, "w");
sprintf(outputName, "%s.mateRescue.seq"uint32FMTW(02)".dat", outputPrefix, s);
outputData = fopen(outputName, "w");
double numRR[MAX_COVERAGE] = {0}; // num repeats rescued (expected) for [] X coverage
double numNR[MAX_COVERAGE] = {0}; // num repeats nonrescuable (expected) for [] X coverage
uint32 numRT = 0; // num repeats total
for (int32 p=0; p<S->seqLen(s); p++) {
CT->tick();
double pRtot = 0.0;
double pFtot = 0.0;
if ((S->masking(s, p) != 'g') &&
(S->masking(s, p) != 'u') &&
(S->masking(s, p) != 'r'))
fprintf(stderr, "INVALID MASKING - got %d = %c\n", S->masking(s, p), S->masking(s, p));
if (S->masking(s, p) == 'r') {
numRT++;
// Index over x-coverage in libraries. MUST BE 1.
uint32 ridx = 1;
for (uint32 l=0; l<libLen; l++) {
int32 mean = lib[l].mean();
int32 stddev = lib[l].stddev();
// Build a list of the same repeat close to this guy.
closeRepeatsLen = 0;
if (S->repeatID(s, p) > 0) {
int32 pl = (int32)floor(p - 3 * stddev);
int32 ph = (int32)ceil (p + 3 * stddev);
if (pl < 0) pl = 0;
if (ph > S->seqLen(s)) ph = S->seqLen(s);
for (int32 pi=pl; pi<ph; pi++)
if ((S->repeatID(s, pi) == S->repeatID(s, p)) && (pi != p))
closeRepeats[closeRepeatsLen++] = pi;
}
int32 b1l = (int32)floor(p - mean - 3 * stddev);
int32 b1h = (int32)ceil (p - mean + 3 * stddev);
int32 b2l = (int32)floor(p + mean - 3 * stddev);
int32 b2h = (int32)ceil (p + mean + 3 * stddev);
if (b1l < 0) b1l = 0;
if (b1h < 0) b1h = 0;
if (b1h > S->seqLen(s)) b1h = S->seqLen(s);
if (b2l < 0) b2l = 0;
if (b2h > S->seqLen(s)) b2h = S->seqLen(s);
if (b2l > S->seqLen(s)) b2l = S->seqLen(s);
//fprintf(stderr, "b1: %d-%d b2:%d-%d\n", b1l, b1h, b2l, b2h);
// probability we can rescue this repeat with this mate pair
double pRescue = 0.0;
double pFailed = 0.0;
if (closeRepeatsLen == 0) {
// No close repeats, use the fast method.
for (int32 b=b1l; b<b1h; b++) {
if (S->masking(s, b) == 'u')
pRescue += lib[l].normal(b - p + mean);
}
for (int32 b=b2l; b<b2h; b++) {
if (S->masking(s, b) == 'u')
pRescue += lib[l].normal(b - p - mean);
}
} else {
// Close repeats, gotta be slow.
for (int32 b=b1l; b<b1h; b++) {
if (S->masking(s, b) == 'u') {
int32 mrl = b + mean - 3 * stddev;
int32 mrh = b + mean + 3 * stddev;
bool rescuable = true;
for (uint32 cri=0; rescuable && cri<closeRepeatsLen; cri++)
if ((mrl <= closeRepeats[cri]) && (closeRepeats[cri] <= mrh))
rescuable = false;
if (rescuable)
pRescue += lib[l].normal(b - p + mean);
else
pFailed += lib[l].normal(b - p + mean);
}
}
for (int32 b=b2l; b<b2h; b++) {
if (S->masking(s, b) == 'u') {
int32 mrl = b - mean - 3 * stddev;
int32 mrh = b - mean + 3 * stddev;
bool rescuable = true;
for (uint32 cri=0; rescuable && cri<closeRepeatsLen; cri++)
if ((mrl <= closeRepeats[cri]) && (closeRepeats[cri] <= mrh))
rescuable = false;
if (rescuable)
pRescue += lib[l].normal(b - p - mean);
else
pFailed += lib[l].normal(b - p - mean);
}
}
}
// We're summing over two distributions.
pRescue /= 2.0;
pFailed /= 2.0;
// Compute probability of rescuing with libraries we've
// seen already, and the expected number of repeats
// rescued.
//
// We keep track of the probability we rescue this repeat
// with additional coverage of libraries. First 1x of the
// first lib, then 2x of the first, etc, etc.
//
{
double pR = 1.0;
double pF = 1.0;
for (uint32 x=0; x<lib[l].coverage(); x++) {
// Makes it here. pRescue != 1.0
pR *= (1.0 - pRescue);
numRR[ridx] += 1 - pR;
pRtot += 1 - pR;
pF *= (1.0 - pFailed);
numNR[ridx] += 1 - pF;
pFtot += 1 - pF;
ridx++;
}
}
} // over all libs
fprintf(outputData, int32FMT"\t%f\t%f\n", p, pRtot / totalDepth, pFtot / totalDepth);
} // if masking is r
} // over all positions
fprintf(outputFile, "seqIID\tmerSize\ttRepeat\teRescue\teFailed\tXcov\tmean\tstddev\n");
for (uint32 x=1, l=0, n=0; l<libLen; x++) {
fprintf(outputFile, uint32FMT"\t"uint32FMT"\t"uint32FMT"\t%.0f\t%.0f\t"uint32FMT"\t"int32FMT"\t"int32FMT"\n",
s, S->merSize(), numRT, numRR[x], numNR[x], x, lib[l].mean(), lib[l].stddev());
n++;
if (n >= lib[l].coverage()) {
l++;
n = 0;
}
}
fclose(outputFile);
fclose(outputData);
}
delete CT;
}
int
main(int argc, char **argv) {
char *merylName = 0L;
char *fastaName = 0L;
char *outputPrefix = 0L;
uint32 onlySeqIID = ~uint32ZERO;
bool doDensity = false;
bool doRescue = false;
mateRescueData lib[MAX_COVERAGE];
uint32 libLen = 0;
int arg=1;
int err=0;
while (arg < argc) {
if (strcmp(argv[arg], "-mers") == 0) {
merylName = argv[++arg];
} else if (strcmp(argv[arg], "-seq") == 0) {
fastaName = argv[++arg];
} else if (strcmp(argv[arg], "-only") == 0) {
onlySeqIID = atoi(argv[++arg]);
} else if (strcmp(argv[arg], "-output") == 0) {
outputPrefix = argv[++arg];
} else if (strcmp(argv[arg], "-d") == 0) {
doDensity = true;
} else if (strcmp(argv[arg], "-r") == 0) {
if (atoi(argv[arg+3]) > 0) {
doRescue = true;
lib[libLen++].init(atoi(argv[arg+1]), atoi(argv[arg+2]), atoi(argv[arg+3]));
}
arg += 3;
} else {
fprintf(stderr, "unknown option '%s'\n", argv[arg]);
err++;
}
arg++;
}
if ((err) || (merylName == 0L) || (fastaName == 0L) || (outputPrefix == 0L)) {
fprintf(stderr, "usage: %s -mers mers -seq fasta -output prefix [-d] [-r mean stddev coverage]\n", argv[0]);
exit(1);
}
merMaskedSequence *S = new merMaskedSequence(fastaName, merylName, onlySeqIID);
if (doDensity)
computeDensity(S, outputPrefix);
if (doRescue)
computeMateRescue(S, outputPrefix, lib, libLen);
return(0);
}
|
gpl-2.0
|
CoolerVoid/email_audit
|
src/imap_control.cpp
|
6863
|
/*
# Copyright (C) 2016 imap_control authors(Antonio Costa, Cooler_),
#
# This file is part of spam_detect_PoC
#
# libtext_bayes is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# libtext_bayes is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <curl/curl.h>
#include <float.h>
#include <math.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include "imap_control.h"
#include <string.h>
#include <vector>
std::vector<std::string> ImapControl::split(const std::string &text, char sep)
{
std::vector<std::string> tokens;
std::size_t start = 0, end = 0;
while ((end = text.find(sep, start)) != std::string::npos)
{
tokens.push_back(text.substr(start, end - start));
start = end + 1;
}
tokens.push_back(text.substr(start));
return tokens;
}
size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)data;
mem->memory = (char *)realloc(mem->memory, mem->size + realsize + 1);
if( mem->memory )
{
memcpy(&(mem->memory[mem->size]), ptr, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
}
return realsize;
}
void ImapControl::Auth(std::string login_in, std::string password_in)
{
memset(login,0,127);
strncpy(login,login_in.c_str(),127);
memset(password,0,127);
strncpy(password,password_in.c_str(),127);
}
void ImapControl::Server(std::string server_in)
{
memset(server,0,127);
strncpy(server,server_in.c_str(),127);
}
std::vector<std::string> ImapControl::list_all()
{
CURL *curl_handle;
CURLcode res;
struct MemoryStruct chunk;
chunk.memory =(char *) malloc(1);
chunk.size = 0;
curl_global_init(CURL_GLOBAL_ALL);
curl_handle = curl_easy_init();
char target[256];
memset(target,0,255);
strcpy(target,server);
strcat(target,"/INBOX/");
curl_easy_setopt(curl_handle, CURLOPT_USERNAME, login);
curl_easy_setopt(curl_handle, CURLOPT_PASSWORD, password);
curl_easy_setopt(curl_handle, CURLOPT_URL, target);
curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, "search all");
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 10L);
// run SSL or TLS
curl_easy_setopt(curl_handle, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
#ifdef SKIP_PEER_VERIFICATION
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0L);
#endif
#ifdef SKIP_HOSTNAME_VERIFICATION
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0L);
#endif
res = curl_easy_perform(curl_handle);
if(res != CURLE_OK)
{
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
std::string tmp(chunk.memory);
std::vector<std::string> result=split(tmp,' ');
result.erase(result.begin(), result.begin()+2);
curl_easy_cleanup(curl_handle);
if(chunk.memory!=NULL)
free(chunk.memory);
curl_global_cleanup();
return result;
}
void ImapControl::view_msg(char *uid)
{
CURL *curl_handle;
CURLcode res;
struct MemoryStruct chunk;
chunk.memory =(char *) malloc(1);
chunk.size = 0;
curl_global_init(CURL_GLOBAL_ALL);
curl_handle = curl_easy_init();
char path[256];
memset(path,0,255);
char target[256];
memset(target,0,255);
strcpy(target,server);
snprintf(path,255,"%s/INBOX/;UID=%s",server,uid);
curl_easy_setopt(curl_handle, CURLOPT_USERNAME, login);
curl_easy_setopt(curl_handle, CURLOPT_PASSWORD, password);
curl_easy_setopt(curl_handle, CURLOPT_URL, path);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 3L);
//run ssl or tls
curl_easy_setopt(curl_handle, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
#ifdef SKIP_PEER_VERIFICATION
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0L);
#endif
#ifdef SKIP_HOSTNAME_VERIFICATION
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0L);
#endif
res = curl_easy_perform(curl_handle);
if(res != CURLE_OK)
{
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
curl_easy_cleanup(curl_handle);
if(chunk.memory!=NULL)
free(chunk.memory);
curl_global_cleanup();
printf("%s\n",chunk.memory);
}
void ImapControl::remove_msg(char *uid)
{
CURL *curl_handle;
CURLcode res;
struct MemoryStruct chunk;
chunk.memory = (char *)malloc(1);
chunk.size = 0;
curl_global_init(CURL_GLOBAL_ALL);
curl_handle = curl_easy_init();
char cmd[64];
memset(cmd,0,63);
char target[256];
memset(target,0,255);
strcpy(target,server);
strcat(target,"/INBOX/");
snprintf(cmd,63,"STORE %s +Flags \\Deleted",uid);
//imaps://imap.gmail.com:993
curl_easy_setopt(curl_handle, CURLOPT_USERNAME, login);
curl_easy_setopt(curl_handle, CURLOPT_PASSWORD, password);
curl_easy_setopt(curl_handle, CURLOPT_URL, target);
curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, cmd);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 2L);
//SSL or TLS
curl_easy_setopt(curl_handle, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
#ifdef SKIP_PEER_VERIFICATION
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0L);
#endif
#ifdef SKIP_HOSTNAME_VERIFICATION
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0L);
#endif
res = curl_easy_perform(curl_handle);
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
else {
curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, "EXPUNGE");
res = curl_easy_perform(curl_handle);
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
}
if(chunk.memory!=NULL)
free(chunk.memory);
curl_global_cleanup();
printf("%s\n",chunk.memory);
}
|
gpl-2.0
|
PragmaticMates/django-invoicing
|
invoicing/urls.py
|
222
|
from django.conf.urls import url
from invoicing.views import InvoiceDetailView
app_name = 'invoicing'
urlpatterns = [
url(r'^invoice/detail/(?P<pk>[-\d]+)/$', InvoiceDetailView.as_view(), name='invoice_detail'),
]
|
gpl-2.0
|
kunj1988/Magento2
|
app/code/Magento/Config/Controller/Adminhtml/System/Config/AbstractScopeConfig.php
|
1627
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Config\Controller\Adminhtml\System\Config;
use Magento\Config\Controller\Adminhtml\System\ConfigSectionChecker;
/**
* @api
* @since 100.0.2
*/
abstract class AbstractScopeConfig extends \Magento\Config\Controller\Adminhtml\System\AbstractConfig
{
/**
* @var \Magento\Config\Model\Config
*/
protected $_backendConfig;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Config\Model\Config\Structure $configStructure
* @param ConfigSectionChecker $sectionChecker
* @param \Magento\Config\Model\Config $backendConfig
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Config\Model\Config\Structure $configStructure,
ConfigSectionChecker $sectionChecker,
\Magento\Config\Model\Config $backendConfig
) {
$this->_backendConfig = $backendConfig;
parent::__construct($context, $configStructure, $sectionChecker);
}
/**
* Sets scope for backend config
*
* @param string $sectionId
* @return bool
*/
protected function isSectionAllowed($sectionId)
{
$website = $this->getRequest()->getParam('website');
$store = $this->getRequest()->getParam('store');
if ($store) {
$this->_backendConfig->setStore($store);
} elseif ($website) {
$this->_backendConfig->setWebsite($website);
}
return parent::isSectionAllowed($sectionId);
}
}
|
gpl-2.0
|
caxenie/nstbot
|
nstbot/connection.py
|
2112
|
import socket
class Serial(object):
def __init__(self, port, baud):
import serial
self.conn = serial.Serial(port, baudrate=baud, rtscts=True, timeout=0)
def send(self, message):
self.conn.write(message)
def receive(self):
return self.conn.read(1024)
def close(self):
self.conn.close()
class Socket(object):
cache = {}
def __init__(self, address, port=56000):
self.socket = Socket.get_socket(address, port)
@classmethod
def get_socket(cls, address, port):
key = (address, port)
s = cls.cache.get(key, None)
if s is None:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((address, port))
s.settimeout(0)
cls.cache[key] = s
return s
def send(self, message):
self.socket.send(message)
def receive(self):
try:
return self.socket.recv(1024)
except socket.error:
return ''
def close(self):
self.socket.close()
class SocketList(object):
cache = {}
def __init__(self, adress_list):
self.socket_list={}
for name, value in adress_list.iteritems():
address = value[0]
port = value[1]
self.socket_list[name] = SocketList.get_socket(address, port)
@classmethod
def get_socket(cls, address, port):
key = (address, port)
s = cls.cache.get(key, None)
if s is None:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((address, port))
s.settimeout(0)
cls.cache[key] = s
return s
def get_socket_keys(self):
return self.socket_list.keys()
def send(self, name, message):
self.socket_list[name].send(message)
def receive(self, name):
try:
return self.socket_list[name].recv(1024)
except socket.error:
return ''
def close(self):
for name, socket in self.socket_list.iteritems():
self.socket_list[name].close()
|
gpl-2.0
|
project-cabal/cabal
|
engines/fullpipe/modal.cpp
|
37840
|
/* Cabal - Legacy Game Implementations
*
* Cabal is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* 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.
*
*/
// Based on the ScummVM (GPLv2+) file of the same name
#include "fullpipe/fullpipe.h"
#include "fullpipe/messages.h"
#include "fullpipe/constants.h"
#include "fullpipe/motion.h"
#include "fullpipe/scenes.h"
#include "fullpipe/gameloader.h"
#include "fullpipe/statics.h"
#include "fullpipe/modal.h"
#include "fullpipe/constants.h"
#include "graphics/palette.h"
#include "video/avi_decoder.h"
#include "engines/savestate.h"
namespace Fullpipe {
ModalIntro::ModalIntro() {
_field_8 = 0;
_countDown = 0;
_stillRunning = 0;
if (g_vars->sceneIntro_skipIntro) {
_introFlags = 4;
} else {
_introFlags = 33;
_countDown = 150;
PictureObject *pict = g_fp->accessScene(SC_INTRO1)->getPictureObjectById(PIC_IN1_PIPETITLE, 0);
pict->setFlags(pict->_flags & 0xFFFB);
}
g_vars->sceneIntro_skipIntro = false;
_sfxVolume = g_fp->_sfxVolume;
}
ModalIntro::~ModalIntro() {
g_fp->stopAllSounds();
g_fp->_sfxVolume = _sfxVolume;
}
bool ModalIntro::handleMessage(ExCommand *message) {
if (message->_messageKind != 17)
return false;
if (message->_messageNum != 36)
return false;
if (message->_keyCode != 13 && message->_keyCode != 27 && message->_keyCode != 32)
return false;
if (_stillRunning) {
if (!(_introFlags & 0x10)) {
_countDown = 0;
g_vars->sceneIntro_needBlackout = true;
return true;
}
g_vars->sceneIntro_playing = false;
g_vars->sceneIntro_needBlackout = true;
}
return true;
}
bool ModalIntro::init(int counterdiff) {
if (!g_vars->sceneIntro_playing) {
if (!_stillRunning) {
finish();
return false;
}
if (_introFlags & 0x10)
g_fp->_gameLoader->updateSystems(42);
_introFlags |= 2;
return true;
}
if (_introFlags & 4) {
ModalVideoPlayer *player = new ModalVideoPlayer();
g_fp->_modalObject = player;
player->_parentObj = this;
player->play("intro.avi");
_countDown--;
if (_countDown > 0 )
return true;
if (_stillRunning <= 0) {
_countDown = 0;
_stillRunning = 0;
_introFlags = (_introFlags & 0xfb) | 0x40;
return true;
}
_introFlags |= 2;
return true;
}
if (_introFlags & 0x40) {
ModalVideoPlayer *player = new ModalVideoPlayer();
g_fp->_modalObject = player;
player->_parentObj = this;
player->play("intro2.avi");
_countDown--;
if (_countDown > 0)
return true;
if (_stillRunning <= 0) {
_countDown = 50;
_stillRunning = 0;
_introFlags = (_introFlags & 0xbf) | 9;
return true;
}
_introFlags |= 2;
return true;
}
if (_introFlags & 8) {
_countDown--;
if (_countDown > 0 )
return true;
if (_stillRunning > 0) {
_introFlags |= 2;
return true;
}
_countDown = 150;
_introFlags = (_introFlags & 0xf7) | 0x21;
g_fp->accessScene(SC_INTRO1)->getPictureObjectById(PIC_IN1_PIPETITLE, 0)->_flags &= 0xfffb;
}
if (!(_introFlags & 0x20)) {
if (_introFlags & 0x10) {
if (!_stillRunning) {
_introFlags |= 1;
g_fp->accessScene(SC_INTRO1)->getPictureObjectById(PIC_IN1_PIPETITLE, 0)->_flags &= 0xfffb;
g_fp->accessScene(SC_INTRO1)->getPictureObjectById(PIC_IN1_GAMETITLE, 0)->_flags &= 0xfffb;
chainQueue(QU_INTR_STARTINTRO, 1);
}
g_fp->_gameLoader->updateSystems(42);
}
return true;
}
_countDown--;
if (_countDown <= 0) {
if (_stillRunning > 0) {
_introFlags |= 2;
return true;
}
_introFlags = (_introFlags & 0xdf) | 0x10;
g_fp->accessScene(SC_INTRO1)->getPictureObjectById(PIC_IN1_GAMETITLE, 0)->_flags &= 0xfffb;
_stillRunning = 0;
}
return true;
}
void ModalIntro::update() {
if (g_fp->_currentScene) {
if (_introFlags & 1) {
g_fp->sceneFade(g_fp->_currentScene, true);
_stillRunning = 255;
_introFlags &= 0xfe;
if (_introFlags & 0x20)
g_fp->playSound(SND_INTR_019, 0);
} else if (_introFlags & 2) {
if (g_vars->sceneIntro_needBlackout) {
g_fp->drawAlphaRectangle(0, 0, 800, 600, 0);
g_vars->sceneIntro_needBlackout = 0;
_stillRunning = 0;
_introFlags &= 0xfd;
} else {
g_fp->sceneFade(g_fp->_currentScene, false);
_stillRunning = 0;
_introFlags &= 0xfd;
}
} else if (_stillRunning) {
g_fp->_currentScene->draw();
}
}
}
void ModalIntro::finish() {
g_fp->_gameLoader->unloadScene(SC_INTRO2);
g_fp->_currentScene = g_fp->accessScene(SC_INTRO1);
g_fp->_gameLoader->preloadScene(SC_INTRO1, TrubaDown);
if (g_fp->_currentScene)
g_fp->_gameLoader->updateSystems(42);
}
void ModalVideoPlayer::play(const char *filename) {
// TODO: Videos are encoded using Intel Indeo 5 (IV50), which isn't supported yet
Video::AVIDecoder *aviDecoder = new Video::AVIDecoder();
if (!aviDecoder->loadFile(filename))
return;
uint16 x = (g_system->getWidth() - aviDecoder->getWidth()) / 2;
uint16 y = (g_system->getHeight() - aviDecoder->getHeight()) / 2;
bool skipVideo = false;
aviDecoder->start();
while (!g_fp->shouldQuit() && !aviDecoder->endOfVideo() && !skipVideo) {
if (aviDecoder->needsUpdate()) {
const Graphics::Surface *frame = aviDecoder->decodeNextFrame();
if (frame) {
g_fp->_system->copyRectToScreen(frame->getPixels(), frame->getPitch(), x, y, frame->getWidth(), frame->getHeight());
if (aviDecoder->hasDirtyPalette())
g_fp->_system->getPaletteManager()->setPalette(aviDecoder->getPalette(), 0, 256);
g_fp->_system->updateScreen();
}
}
Common::Event event;
while (g_fp->_system->getEventManager()->pollEvent(event)) {
if ((event.type == Common::EVENT_KEYDOWN && (event.kbd.keycode == Common::KEYCODE_ESCAPE ||
event.kbd.keycode == Common::KEYCODE_RETURN ||
event.kbd.keycode == Common::KEYCODE_SPACE))
|| event.type == Common::EVENT_LBUTTONUP)
skipVideo = true;
}
g_fp->_system->delayMillis(aviDecoder->getTimeToNextFrame());
}
}
ModalMap::ModalMap() {
_mapScene = 0;
_pic = 0;
_isRunning = false;
_rect1 = g_fp->_sceneRect;
_x = g_fp->_currentScene->_x;
_y = g_fp->_currentScene->_y;
_flag = 0;
_mouseX = 0;
_mouseY = 0;
_field_38 = 0;
_field_3C = 0;
_field_40 = 12;
_rect2.top = 0;
_rect2.left = 0;
_rect2.bottom = 600;
_rect2.right = 800;
}
ModalMap::~ModalMap() {
g_fp->_gameLoader->unloadScene(SC_MAP);
g_fp->_sceneRect = _rect1;
g_fp->_currentScene->_x = _x;
g_fp->_currentScene->_y = _y;
}
bool ModalMap::init(int counterdiff) {
g_fp->setCursor(PIC_CSR_ITN);
if (_flag) {
_rect2.left = _mouseX + _field_38 - g_fp->_mouseScreenPos.x;
_rect2.top = _mouseY + _field_3C - g_fp->_mouseScreenPos.y;
_rect2.right = _rect2.left + 800;
_rect2.bottom = _rect2.top + 600;
g_fp->_sceneRect =_rect2;
_mapScene->updateScrolling2();
_rect2 = g_fp->_sceneRect;
}
_field_40--;
if (_field_40 <= 0) {
_field_40 = 12;
if (_pic)
_pic->_flags ^= 4;
}
return _isRunning;
}
void ModalMap::update() {
g_fp->_sceneRect = _rect2;
_mapScene->draw();
g_fp->drawArcadeOverlay(1);
}
bool ModalMap::handleMessage(ExCommand *cmd) {
if (cmd->_messageKind != 17)
return false;
switch (cmd->_messageNum) {
case 29:
_flag = 1;
_mouseX = g_fp->_mouseScreenPos.x;
_mouseY = g_fp->_mouseScreenPos.x;
_field_3C = _rect2.top;
_field_38 = _rect2.left;
break;
case 30:
_flag = 0;
break;
case 36:
if (cmd->_keyCode != 9 && cmd->_keyCode != 27 )
return false;
break;
case 107:
break;
default:
return false;
}
_isRunning = 0;
return true;
}
void ModalMap::initMap() {
_isRunning = 1;
_mapScene = g_fp->accessScene(SC_MAP);
if (!_mapScene)
error("ModalMap::initMap(): error accessing scene SC_MAP");
PictureObject *pic;
for (int i = 0; i < 200; i++) {
if (!(g_fp->_mapTable[i] >> 16))
break;
pic = _mapScene->getPictureObjectById(g_fp->_mapTable[i] >> 16, 0);
if ((g_fp->_mapTable[i] & 0xffff) == 1)
pic->_flags |= 4;
else
pic->_flags &= 0xfffb;
}
pic = getScenePicture();
Common::Point point;
Common::Point point2;
if (pic) {
pic->getDimensions(&point);
_rect2.left = point.x / 2 + pic->_ox - 400;
_rect2.top = point.y / 2 + pic->_oy - 300;
_rect2.right = _rect2.left + 800;
_rect2.bottom = _rect2.top + 600;
_mapScene->updateScrolling2();
_pic = _mapScene->getPictureObjectById(PIC_MAP_I02, 0);
_pic->getDimensions(&point2);
_pic->setOXY(pic->_ox + point.x / 2 - point2.x / 2, point.y - point2.y / 2 + pic->_oy - 24);
_pic->_flags |= 4;
_pic = _mapScene->getPictureObjectById(PIC_MAP_I01, 0);
_pic->getDimensions(&point2);
_pic->setOXY(pic->_ox + point.x / 2 - point2.x / 2, point.y - point2.y / 2 + pic->_oy - 25);
_pic->_flags |= 4;
}
g_fp->setArcadeOverlay(PIC_CSR_MAP);
}
PictureObject *ModalMap::getScenePicture() {
int picId = 0;
switch (g_fp->_currentScene->_sceneId) {
case SC_1:
picId = PIC_MAP_S01;
break;
case SC_2:
picId = PIC_MAP_S02;
break;
case SC_3:
picId = PIC_MAP_S03;
break;
case SC_4:
picId = PIC_MAP_S04;
break;
case SC_5:
picId = PIC_MAP_S05;
break;
case SC_6:
picId = PIC_MAP_S06;
break;
case SC_7:
picId = PIC_MAP_S07;
break;
case SC_8:
picId = PIC_MAP_S08;
break;
case SC_9:
picId = PIC_MAP_S09;
break;
case SC_10:
picId = PIC_MAP_S10;
break;
case SC_11:
picId = PIC_MAP_S11;
break;
case SC_12:
picId = PIC_MAP_S12;
break;
case SC_13:
picId = PIC_MAP_S13;
break;
case SC_14:
picId = PIC_MAP_S14;
break;
case SC_15:
picId = PIC_MAP_S15;
break;
case SC_16:
picId = PIC_MAP_S16;
break;
case SC_17:
picId = PIC_MAP_S17;
break;
case SC_18:
case SC_19:
picId = PIC_MAP_S1819;
break;
case SC_20:
picId = PIC_MAP_S20;
break;
case SC_21:
picId = PIC_MAP_S21;
break;
case SC_22:
picId = PIC_MAP_S22;
break;
case SC_23:
picId = PIC_MAP_S23_1;
break;
case SC_24:
picId = PIC_MAP_S24;
break;
case SC_25:
picId = PIC_MAP_S25;
break;
case SC_26:
picId = PIC_MAP_S26;
break;
case SC_27:
picId = PIC_MAP_S27;
break;
case SC_28:
picId = PIC_MAP_S28;
break;
case SC_29:
picId = PIC_MAP_S29;
break;
case SC_30:
picId = PIC_MAP_S30;
break;
case SC_31:
picId = PIC_MAP_S31_1;
break;
case SC_32:
picId = PIC_MAP_S32_1;
break;
case SC_33:
picId = PIC_MAP_S33;
break;
case SC_34:
picId = PIC_MAP_S34;
break;
case SC_35:
picId = PIC_MAP_S35;
break;
case SC_36:
picId = PIC_MAP_S36;
break;
case SC_37:
picId = PIC_MAP_S37;
break;
case SC_38:
picId = PIC_MAP_S38;
break;
case SC_FINAL1:
picId = PIC_MAP_S38;
break;
}
if (picId)
return _mapScene->getPictureObjectById(picId, 0);
error("ModalMap::getScenePicture(): Unknown scene id: %d", g_fp->_currentScene->_sceneId);
}
void FullpipeEngine::openMap() {
if (!_modalObject) {
ModalMap *map = new ModalMap;
_modalObject = map;
map->initMap();
}
}
ModalFinal::ModalFinal() {
_flags = 0;
_counter = 255;
_sfxVolume = g_fp->_sfxVolume;
}
ModalFinal::~ModalFinal() {
if (g_vars->sceneFinal_var01) {
g_fp->_gameLoader->unloadScene(SC_FINAL2);
g_fp->_gameLoader->unloadScene(SC_FINAL3);
g_fp->_gameLoader->unloadScene(SC_FINAL4);
g_fp->_currentScene = g_fp->accessScene(SC_FINAL1);
g_fp->stopAllSounds();
g_vars->sceneFinal_var01 = 0;
}
g_fp->_sfxVolume = _sfxVolume;
}
bool ModalFinal::init(int counterdiff) {
if (g_vars->sceneFinal_var01) {
g_fp->_gameLoader->updateSystems(42);
return true;
}
if (_counter > 0) {
_flags |= 2u;
g_fp->_gameLoader->updateSystems(42);
return true;
}
unloadScenes();
g_fp->_modalObject = new ModalCredits();
return true;
}
void ModalFinal::unloadScenes() {
g_fp->_gameLoader->unloadScene(SC_FINAL2);
g_fp->_gameLoader->unloadScene(SC_FINAL3);
g_fp->_gameLoader->unloadScene(SC_FINAL4);
g_fp->_currentScene = g_fp->accessScene(SC_FINAL1);
g_fp->stopAllSounds();
}
bool ModalFinal::handleMessage(ExCommand *cmd) {
if (cmd->_messageKind == 17 && cmd->_messageNum == 36 && cmd->_keyCode == 27) {
g_fp->_modalObject = new ModalMainMenu();
g_fp->_modalObject->_parentObj = this;
return true;
}
return false;
}
void ModalFinal::update() {
if (g_fp->_currentScene) {
g_fp->_currentScene->draw();
if (_flags & 1) {
g_fp->drawAlphaRectangle(0, 0, 800, 600, 0xff - _counter);
_counter += 10;
if (_counter >= 255) {
_counter = 255;
_flags &= 0xfe;
}
} else {
if (!(_flags & 2))
return;
g_fp->drawAlphaRectangle(0, 0, 800, 600, 0xff - _counter);
_counter -= 10;
if (_counter <= 0) {
_counter = 0;
_flags &= 0xFD;
}
}
g_fp->_sfxVolume = _counter * (_sfxVolume + 3000) / 255 - 3000;
g_fp->updateSoundVolume();
}
}
ModalCredits::ModalCredits() {
Common::Point point;
_sceneTitles = g_fp->accessScene(SC_TITLES);
_creditsPic = _sceneTitles->getPictureObjectById(PIC_TTL_CREDITS, 0);
_creditsPic->_flags |= 4;
_fadeIn = true;
_fadeOut = false;
_creditsPic->getDimensions(&point);
_countdown = point.y / 2 + 470;
_sfxVolume = g_fp->_sfxVolume;
_currY = 630;
_maxY = -1000 - point.y;
_currX = 400 - point.x / 2;
_creditsPic->setOXY(_currX, _currY);
}
ModalCredits::~ModalCredits() {
g_fp->_gameLoader->unloadScene(SC_TITLES);
g_fp->_sfxVolume = _sfxVolume;
}
bool ModalCredits::handleMessage(ExCommand *cmd) {
if (cmd->_messageKind == 17 && cmd->_messageNum == 36 && cmd->_keyCode == 27) {
_fadeIn = false;
return true;
}
return false;
}
bool ModalCredits::init(int counterdiff) {
if (_fadeIn || _fadeOut) {
_countdown--;
if (_countdown < 0)
_fadeIn = false;
_creditsPic->setOXY(_currX, _currY);
if (_currY > _maxY)
_currY -= 2;
} else {
if (_parentObj)
return 0;
ModalMainMenu *menu = new ModalMainMenu;
g_fp->_modalObject = menu;
menu->_mfield_34 = 1;
}
return true;
}
void ModalCredits::update() {
if (_fadeOut) {
if (_fadeIn) {
_sceneTitles->draw();
return;
}
} else if (_fadeIn) {
g_fp->sceneFade(_sceneTitles, true);
_fadeOut = 1;
return;
}
if (_fadeOut) {
g_fp->sceneFade(_sceneTitles, false);
_fadeOut = 0;
return;
}
_sceneTitles->draw();
}
ModalMainMenu::ModalMainMenu() {
_areas.clear();
_lastArea = 0;
_hoverAreaId = 0;
_mfield_34 = 0;
_scene = g_fp->accessScene(SC_MAINMENU);
_debugKeyCount = 0;
_sliderOffset = 0;
_screct.left = g_fp->_sceneRect.left;
_screct.top = g_fp->_sceneRect.top;
_screct.right = g_fp->_sceneRect.right;
_screct.bottom = g_fp->_sceneRect.bottom;
if (g_fp->_currentScene) {
_bgX = g_fp->_currentScene->_x;
_bgY = g_fp->_currentScene->_y;
} else {
_bgX = 0;
_bgY = 0;
}
g_fp->_sceneRect.top = 0;
g_fp->_sceneRect.left = 0;
g_fp->_sceneRect.right = 800;
g_fp->_sceneRect.bottom = 600;
MenuArea *area;
area = new MenuArea();
area->picIdL = PIC_MNU_EXIT_L;
area->picObjD = 0;
area->picObjL = _scene->getPictureObjectById(area->picIdL, 0);
area->picObjL->_flags &= 0xFFFB;
_areas.push_back(area);
area = new MenuArea();
area->picIdL = PIC_MNU_CONTINUE_L;
area->picObjD = 0;
area->picObjL = _scene->getPictureObjectById(area->picIdL, 0);
area->picObjL->_flags &= 0xFFFB;
_areas.push_back(area);
if (isSaveAllowed()) {
area = new MenuArea();
area->picIdL = PIC_MNU_SAVE_L;
area->picObjD = 0;
area->picObjL = _scene->getPictureObjectById(area->picIdL, 0);
area->picObjL->_flags &= 0xFFFB;
_areas.push_back(area);
}
area = new MenuArea();
area->picIdL = PIC_MNU_LOAD_L;
area->picObjD = 0;
area->picObjL = _scene->getPictureObjectById(area->picIdL, 0);
area->picObjL->_flags &= 0xFFFB;
_areas.push_back(area);
area = new MenuArea();
area->picIdL = PIC_MNU_RESTART_L;
area->picObjD = 0;
area->picObjL = _scene->getPictureObjectById(area->picIdL, 0);
area->picObjL->_flags &= 0xFFFB;
_areas.push_back(area);
area = new MenuArea();
area->picIdL = PIC_MNU_AUTHORS_L;
area->picObjD = 0;
area->picObjL = _scene->getPictureObjectById(area->picIdL, 0);
area->picObjL->_flags &= 0xFFFB;
_areas.push_back(area);
area = new MenuArea();
area->picIdL = PIC_MNU_SLIDER_L;
area->picObjD = _scene->getPictureObjectById(PIC_MNU_SLIDER_D, 0);
area->picObjD->_flags |= 4;
area->picObjL = _scene->getPictureObjectById(area->picIdL, 0);
area->picObjL->_flags &= 0xFFFB;
_areas.push_back(area);
_menuSliderIdx = _areas.size() - 1;
area = new MenuArea();
area->picIdL = PIC_MNU_MUSICSLIDER_L;
area->picObjD = _scene->getPictureObjectById(PIC_MNU_MUSICSLIDER_D, 0);
area->picObjD->_flags |= 4;
area->picObjL = _scene->getPictureObjectById(area->picIdL, 0);
area->picObjL->_flags &= 0xFFFB;
_areas.push_back(area);
_musicSliderIdx = _areas.size() - 1;
if (g_fp->_mainMenu_debugEnabled)
enableDebugMenuButton();
setSliderPos();
}
void ModalMainMenu::update() {
_scene->draw();
}
bool ModalMainMenu::handleMessage(ExCommand *message) {
if (message->_messageKind != 17)
return false;
Common::Point point;
if (message->_messageNum == 29) {
point.x = message->_x;
point.y = message->_y;
int numarea = checkHover(point);
if (numarea >= 0) {
if (numarea == _menuSliderIdx) {
_lastArea = _areas[_menuSliderIdx];
_sliderOffset = _lastArea->picObjL->_ox - point.x;
return false;
}
if (numarea == _musicSliderIdx) {
_lastArea = _areas[_musicSliderIdx];
_sliderOffset = _lastArea->picObjL->_ox - point.x;
return false;
}
_hoverAreaId = _areas[numarea]->picIdL;
}
return false;
}
if (message->_messageNum == 30) {
if (_lastArea)
_lastArea = 0;
return false;
}
if (message->_messageNum != 36)
return false;
if (message->_keyCode == 27)
_hoverAreaId = PIC_MNU_CONTINUE_L;
else
enableDebugMenu(message->_keyCode);
return false;
}
bool ModalMainMenu::init(int counterdiff) {
switch (_hoverAreaId) {
case PIC_MNU_RESTART_L:
g_fp->restartGame();
if (this == g_fp->_modalObject)
return false;
delete this;
break;
case PIC_MNU_EXIT_L:
{
ModalQuery *mq = new ModalQuery();
g_fp->_modalObject = mq;
mq->_parentObj = this;
mq->create(_scene, _scene, PIC_MEX_BGR);
_hoverAreaId = 0;
return true;
}
case PIC_MNU_DEBUG_L:
g_fp->_gameLoader->unloadScene(SC_MAINMENU);
g_fp->_sceneRect = _screct;
if (!g_fp->_currentScene)
error("ModalMainMenu::init: Bad state");
g_fp->_currentScene->_x = _bgX;
g_fp->_currentScene->_y = _bgY;
g_fp->_gameLoader->preloadScene(g_fp->_currentScene->_sceneId, SC_DBGMENU);
return false;
case PIC_MNU_CONTINUE_L:
if (!_mfield_34) {
g_fp->_gameLoader->unloadScene(SC_MAINMENU);
g_fp->_sceneRect = _screct;
if (g_fp->_currentScene) {
g_fp->_currentScene->_x = _bgX;
g_fp->_currentScene->_y = _bgY;
}
return false;
}
g_fp->restartGame();
if (this == g_fp->_modalObject)
return false;
delete this;
break;
case PIC_MNU_AUTHORS_L:
g_fp->_modalObject = new ModalCredits();
g_fp->_modalObject->_parentObj = this;
_hoverAreaId = 0;
return true;
case PIC_MNU_SAVE_L:
case PIC_MNU_LOAD_L:
{
ModalSaveGame *sg = new ModalSaveGame();
g_fp->_modalObject = sg;
g_fp->_modalObject->_parentObj = _parentObj;
int mode = 0;
if (_hoverAreaId == PIC_MNU_SAVE_L)
mode = 1;
sg->setup(g_fp->accessScene(SC_MAINMENU), mode);
sg->setScene(g_fp->accessScene(SC_MAINMENU));
sg->_rect = _screct;
sg->_oldBgX = _bgX;
sg->_oldBgY = _bgY;
delete this;
}
break;
default:
if (_lastArea) {
updateSliderPos();
} else {
g_fp->_cursorId = PIC_CSR_DEFAULT;
int idx = checkHover(g_fp->_mouseScreenPos);
if (idx < 0)
goto LABEL_40;
g_fp->_cursorId = PIC_CSR_DEFAULT;
if (idx != this->_menuSliderIdx && idx != this->_musicSliderIdx )
goto LABEL_40;
}
g_fp->_cursorId = PIC_CSR_LIFT;
LABEL_40:
g_fp->setCursor(g_fp->_cursorId);
updateVolume();
return true;
}
return true;
}
void ModalMainMenu::updateVolume() {
if (g_fp->_soundEnabled ) {
for (int s = 0; s < g_fp->_currSoundListCount; s++)
for (int i = 0; i < g_fp->_currSoundList1[s]->getCount(); i++) {
updateSoundVolume(g_fp->_currSoundList1[s]->getSoundByIndex(i));
}
}
}
void ModalMainMenu::updateSoundVolume(Sound *snd) {
if (!snd->_objectId)
return;
StaticANIObject *ani = g_fp->_currentScene->getStaticANIObject1ById(snd->_objectId, -1);
if (!ani)
return;
int a, b;
if (ani->_ox >= _screct.left) {
int par, pan;
if (ani->_ox <= _screct.right) {
int dx;
if (ani->_oy <= _screct.bottom) {
if (ani->_oy >= _screct.top) {
snd->setPanAndVolume(g_fp->_sfxVolume, 0);
return;
}
dx = _screct.top - ani->_oy;
} else {
dx = ani->_oy - _screct.bottom;
}
par = 0;
if (dx > 800) {
snd->setPanAndVolume(-3500, 0);
return;
}
pan = -3500;
a = g_fp->_sfxVolume - (-3500);
b = 800 - dx;
} else {
int dx = ani->_ox - _screct.right;
if (dx > 800) {
snd->setPanAndVolume(-3500, 0);
return;
}
pan = -3500;
par = dx * (-3500) / -800;
a = g_fp->_sfxVolume - (-3500);
b = 800 - dx;
}
int32 pp = b * a;
snd->setPanAndVolume(pan + pp / 800, par);
return;
}
int dx = _screct.left - ani->_ox;
if (dx <= 800) {
int32 s = (800 - dx) * (g_fp->_sfxVolume - (-3500));
int32 p = -3500 + s / 800;
if (p > g_fp->_sfxVolume)
p = g_fp->_sfxVolume;
snd->setPanAndVolume(p, dx * (-3500) / 800);
} else {
snd->setPanAndVolume(-3500, 0);
}
}
void ModalMainMenu::updateSliderPos() {
if (_lastArea->picIdL == PIC_MNU_SLIDER_L) {
int x = g_fp->_mouseScreenPos.x + _sliderOffset;
if (x >= 65) {
if (x > 238)
x = 238;
} else {
x = 65;
}
_lastArea->picObjD->setOXY(x, _lastArea->picObjD->_oy);
_lastArea->picObjL->setOXY(x, _lastArea->picObjD->_oy);
int vol = 1000 * (3 * x - 195);
g_fp->_sfxVolume = vol / 173 - 3000;
if (!(vol / 173))
g_fp->_sfxVolume = -10000;
g_fp->updateSoundVolume();
} else if (_lastArea->picIdL == PIC_MNU_MUSICSLIDER_L) {
int x = g_fp->_mouseScreenPos.x + _sliderOffset;
if (x >= 65) {
if (x > 238)
x = 238;
} else {
x = 65;
}
_lastArea->picObjD->setOXY(x, _lastArea->picObjD->_oy);
_lastArea->picObjL->setOXY(x, _lastArea->picObjD->_oy);
g_fp->setMusicVolume(255 * (x - 65) / 173);
}
}
int ModalMainMenu::checkHover(Common::Point &point) {
for (uint i = 0; i < _areas.size(); i++) {
if (_areas[i]->picObjL->isPixelHitAtPos(point.x, point.y)) {
_areas[i]->picObjL->_flags |= 4;
return i;
} else {
_areas[i]->picObjL->_flags &= 0xFFFB;
}
}
if (isOverArea(_areas[_menuSliderIdx]->picObjL, &point)) {
_areas[_menuSliderIdx]->picObjL->_flags |= 4;
return _menuSliderIdx;
}
if (isOverArea(_areas[_musicSliderIdx]->picObjL, &point)) {
_areas[_musicSliderIdx]->picObjL->_flags |= 4;
return _musicSliderIdx;
}
return -1;
}
bool ModalMainMenu::isOverArea(PictureObject *obj, Common::Point *point) {
Common::Point p;
obj->getDimensions(&p);
int left = point->x - 8;
int right = point->x + 12;
int down = point->y - 11;
int up = point->y + 9;
if (left >= obj->_ox && right < obj->_ox + p.x && down >= obj->_oy && up < obj->_oy + p.y)
return true;
return false;
}
bool ModalMainMenu::isSaveAllowed() {
if (!g_fp->_isSaveAllowed)
return false;
if (g_fp->_aniMan->_flags & 0x100)
return false;
for (Common::Array<MessageQueue *>::iterator s = g_fp->_globalMessageQueueList->begin(); s != g_fp->_globalMessageQueueList->end(); ++s) {
if (!(*s)->_isFinished && ((*s)->getFlags() & 1))
return false;
}
return true;
}
void ModalMainMenu::enableDebugMenu(char c) {
const char deb[] = "DEBUGER";
if (c == deb[_debugKeyCount]) {
_debugKeyCount++;
if (deb[_debugKeyCount] )
return;
enableDebugMenuButton();
}
_debugKeyCount = 0;
}
void ModalMainMenu::enableDebugMenuButton() {
MenuArea *area;
for (uint i = 0; i < _areas.size(); i++)
if (_areas[i]->picIdL == PIC_MNU_DEBUG_L)
return;
area = new MenuArea();
area->picIdL = PIC_MNU_DEBUG_L;
area->picObjD = 0;
area->picObjL = _scene->getPictureObjectById(area->picIdL, 0);
area->picObjL->_flags &= 0xFFFB;
_areas.push_back(area);
}
void ModalMainMenu::setSliderPos() {
int x = 173 * (g_fp->_sfxVolume + 3000) / 3000 + 65;
PictureObject *obj = _areas[_menuSliderIdx]->picObjD;
if (x >= 65) {
if (x > 238)
x = 238;
} else {
x = 65;
}
obj->setOXY(x, obj->_oy);
_areas[_menuSliderIdx]->picObjL->setOXY(x, obj->_oy);
x = 173 * g_fp->_musicVolume / 255 + 65;
obj = _areas[_musicSliderIdx]->picObjD;
if (x >= 65) {
if (x > 238)
x = 238;
} else {
x = 65;
}
obj->setOXY(x, obj->_oy);
_areas[_musicSliderIdx]->picObjL->setOXY(x, obj->_oy);
}
ModalHelp::ModalHelp() {
_mainMenuScene = 0;
_bg = 0;
_isRunning = false;
_rect = g_fp->_sceneRect;
_hx = g_fp->_currentScene->_x;
_hy = g_fp->_currentScene->_y;
g_fp->_sceneRect.left = 0;
g_fp->_sceneRect.bottom = 600;
g_fp->_sceneRect.top = 0;
g_fp->_sceneRect.right = 800;
}
ModalHelp::~ModalHelp() {
g_fp->_gameLoader->unloadScene(SC_MAINMENU);
g_fp->_sceneRect = _rect;
g_fp->_currentScene->_x = _hx;
g_fp->_currentScene->_y = _hy;
}
bool ModalHelp::handleMessage(ExCommand *cmd) {
if (cmd->_messageKind == 17) {
int msg = cmd->_messageNum;
if (msg == 29 || msg == 36 || msg == 107) {
_isRunning = 0;
return true;
}
}
return false;
}
bool ModalHelp::init(int counterdiff) {
g_fp->setCursor(PIC_CSR_DEFAULT);
return _isRunning;
}
void ModalHelp::update() {
g_fp->_sceneRect.left = 0;
g_fp->_sceneRect.top = 0;
g_fp->_sceneRect.right = 800;
g_fp->_sceneRect.bottom = 600;
_bg->draw(0, 0, 0, 0);
}
void ModalHelp::launch() {
_mainMenuScene = g_fp->accessScene(SC_MAINMENU);
if (_mainMenuScene) {
_bg = _mainMenuScene->getPictureObjectById(PIC_HLP_BGR, 0)->_picture;
_isRunning = 1;
}
}
ModalQuery::ModalQuery() {
_bgScene = 0;
_bg = 0;
_okBtn = 0;
_cancelBtn = 0;
_queryResult = -1;
}
ModalQuery::~ModalQuery() {
_bg->_flags &= 0xFFFB;
_cancelBtn->_flags &= 0xFFFB;
_okBtn->_flags &= 0xFFFB;
}
bool ModalQuery::create(Scene *sc, Scene *bgScene, int id) {
if (id == PIC_MEX_BGR) {
_bg = sc->getPictureObjectById(PIC_MEX_BGR, 0);
if (!_bg)
return false;
_okBtn = sc->getPictureObjectById(PIC_MEX_OK, 0);
if (!_okBtn)
return false;
_cancelBtn = sc->getPictureObjectById(PIC_MEX_CANCEL, 0);
if (!_cancelBtn)
return 0;
} else {
if (id != PIC_MOV_BGR)
return false;
_bg = sc->getPictureObjectById(PIC_MOV_BGR, 0);
if (!_bg)
return false;
_okBtn = sc->getPictureObjectById(PIC_MOV_OK, 0);
if (!_okBtn)
return false;
_cancelBtn = sc->getPictureObjectById(PIC_MOV_CANCEL, 0);
if (!_cancelBtn)
return false;
}
_queryResult = -1;
_bgScene = bgScene;
return true;
}
void ModalQuery::update() {
if (_bgScene)
_bgScene->draw();
_bg->draw();
if (_okBtn->_flags & 4)
_okBtn->draw();
if (_cancelBtn->_flags & 4)
_cancelBtn->draw();
}
bool ModalQuery::handleMessage(ExCommand *cmd) {
if (cmd->_messageKind == 17) {
if (cmd->_messageNum == 29) {
if (_okBtn->isPointInside(g_fp->_mouseScreenPos.x, g_fp->_mouseScreenPos.y)) {
_queryResult = 1;
return false;
}
if (_cancelBtn->isPointInside(g_fp->_mouseScreenPos.x, g_fp->_mouseScreenPos.y))
_queryResult = 0;
} else if (cmd->_messageNum == 36 && cmd->_keyCode == 27) {
_queryResult = 0;
return false;
}
}
return false;
}
bool ModalQuery::init(int counterdiff) {
if (_okBtn->isPointInside(g_fp->_mouseScreenPos.x, g_fp->_mouseScreenPos.y))
_okBtn->_flags |= 4;
else
_okBtn->_flags &= 0xFFFB;
if (_cancelBtn->isPointInside(g_fp->_mouseScreenPos.x, g_fp->_mouseScreenPos.y))
_cancelBtn->_flags |= 4;
else
_cancelBtn->_flags &= 0xFFFB;
if (_queryResult == -1) {
return true;
} else {
if (_bg->_id == PIC_MEX_BGR) {
_cancelBtn->_flags &= 0xFFFB;
_okBtn->_flags &= 0xFFFB;
if (_queryResult == 1) {
if (_bgScene)
g_fp->sceneFade(_bgScene, false);
warning("STUB: ModalQuery::init()");
// Quit game
//if (inputArFlag) {
// g_needRestart = 1;
// return 0;
//}
//SendMessageA(hwndCallback, WM_DESTROY, 0, 0);
}
}
}
return false;
}
ModalSaveGame::ModalSaveGame() {
_oldBgX = 0;
_oldBgY = 0;
_bgr = 0;
_okD = 0;
_okL = 0;
_cancelD = 0;
_cancelL = 0;
_emptyD = 0;
_emptyL = 0;
_fullD = 0;
_fullL = 0;
_menuScene = 0;
_queryRes = -1;
_rect = g_fp->_sceneRect;
_queryDlg = 0;
_mode = 1;
_objtype = kObjTypeModalSaveGame;
}
ModalSaveGame::~ModalSaveGame() {
g_fp->_sceneRect = _rect;
_arrayD.clear();
_arrayL.clear();
for (uint i = 0; i < _files.size(); i++)
free(_files[i]);
_files.clear();
}
void ModalSaveGame::setScene(Scene *sc) {
_queryRes = -1;
_menuScene = sc;
}
void ModalSaveGame::processKey(int key) {
if (key == 27)
_queryRes = 0;
}
bool ModalSaveGame::init(int counterdiff) {
if (_queryDlg) {
if (!_queryDlg->init(counterdiff)) {
if (!_queryDlg->getQueryResult())
_queryRes = -1;
delete _queryDlg;
_queryDlg = 0;
}
return true;
}
if (_queryRes == -1)
return true;
g_fp->_sceneRect = _rect;
if (g_fp->_currentScene) {
g_fp->_currentScene->_x = _oldBgX;
g_fp->_currentScene->_y = _oldBgY;
}
if (!_queryRes) {
ModalMainMenu *m = new ModalMainMenu;
g_fp->_modalObject = m;
m->_parentObj = _parentObj;
m->_screct = _rect;
m->_bgX = _oldBgX;
m->_bgY = _oldBgY;
delete this;
return true;
}
return false;
}
void ModalSaveGame::setup(Scene *sc, int mode) {
_files.clear();
_arrayL.clear();
_arrayD.clear();
_mode = mode;
if (mode) {
_bgr = sc->getPictureObjectById(PIC_MSV_BGR, 0);
_cancelD = sc->getPictureObjectById(PIC_MSV_CANCEL_D, 0);
_cancelL = sc->getPictureObjectById(PIC_MSV_CANCEL_L, 0);
_okD = sc->getPictureObjectById(PIC_MSV_OK_D, 0);
_okL = sc->getPictureObjectById(PIC_MSV_OK_L, 0);
_emptyD = sc->getPictureObjectById(PIC_MSV_EMPTY_D, 0);
_emptyL = sc->getPictureObjectById(PIC_MSV_EMPTY_L, 0);
} else {
_bgr = sc->getPictureObjectById(PIC_MLD_BGR, 0);
_cancelD = sc->getPictureObjectById(PIC_MLD_CANCEL_D, 0);
_cancelL = sc->getPictureObjectById(PIC_MLD_CANCEL_L, 0);
_okD = sc->getPictureObjectById(PIC_MLD_OK_D, 0);
_okL = sc->getPictureObjectById(PIC_MLD_OK_L, 0);
_emptyD = sc->getPictureObjectById(PIC_MSV_EMPTY_D, 0);
_emptyL = sc->getPictureObjectById(PIC_MSV_EMPTY_D, 0);
}
_fullD = sc->getPictureObjectById(PIC_MSV_FULL_D, 0);
_fullL = sc->getPictureObjectById(PIC_MSV_FULL_L, 0);
_queryRes = -1;
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_0_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_0_L, 0));
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_1_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_1_L, 0));
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_2_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_2_L, 0));
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_3_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_3_L, 0));
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_4_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_4_L, 0));
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_5_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_5_L, 0));
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_6_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_6_L, 0));
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_7_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_7_L, 0));
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_8_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_8_L, 0));
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_9_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_9_L, 0));
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_DOTS_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_DOTS_L, 0));
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_DOT_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_DOT_L, 0));
_arrayL.push_back(sc->getPictureObjectById(PIC_MSV_SPACE_D, 0));
_arrayD.push_back(sc->getPictureObjectById(PIC_MSV_SPACE_L, 0));
Common::Point point;
int x = _bgr->_ox + _bgr->getDimensions(&point)->x / 2;
int y = _bgr->_oy + 90;
int w;
FileInfo *fileinfo;
for (int i = 0; i < 7; i++) {
fileinfo = new FileInfo;
memset(fileinfo, 0, sizeof(FileInfo));
Common::strlcpy(fileinfo->filename, getSavegameFile(i), 160);
if (!getFileInfo(i, fileinfo)) {
fileinfo->empty = true;
w = _emptyD->getDimensions(&point)->x;
} else {
w = 0;
for (int j = 0; j < 16; j++) {
_arrayL[j]->getDimensions(&point);
w += point.x + 2;
}
}
fileinfo->fx1 = x - w / 2;
fileinfo->fx2 = x + w / 2;
fileinfo->fy1 = y;
fileinfo->fy2 = y + _emptyD->getDimensions(&point)->y;
_files.push_back(fileinfo);
y = fileinfo->fy2 + 3;
}
}
char *ModalSaveGame::getSaveName() {
if (_queryRes < 0)
return 0;
return _files[_queryRes]->filename;
}
bool ModalSaveGame::getFileInfo(int slot, FileInfo *fileinfo) {
Common::InSaveFile *f = g_system->getSavefileManager()->openForLoading(
Fullpipe::getSavegameFile(slot));
if (!f)
return false;
Fullpipe::FullpipeSavegameHeader header;
Fullpipe::readSavegameHeader(f, header);
delete f;
// Create the return descriptor
SaveStateDescriptor desc(slot, header.saveName);
char res[17];
snprintf(res, 17, "%s %s", desc.getSaveDate().c_str(), desc.getSaveTime().c_str());
for (int i = 0; i < 16; i++) {
switch(res[i]) {
case '.':
fileinfo->date[i] = 11;
break;
case ' ':
fileinfo->date[i] = 12;
break;
case ':':
fileinfo->date[i] = 10;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
fileinfo->date[i] = res[i] - '0';
break;
default:
error("Incorrect date format: %s", res);
}
}
return true;
}
void ModalSaveGame::update() {
if (_menuScene)
_menuScene->draw();
_bgr->draw();
if (_queryDlg) {
_queryDlg->update();
return;
}
g_fp->_cursorId = PIC_CSR_DEFAULT;
g_fp->setCursor(g_fp->_cursorId);
Common::Point point;
for (uint i = 0; i < _files.size(); i++) {
if (g_fp->_mouseScreenPos.x < _files[i]->fx1 || g_fp->_mouseScreenPos.x > _files[i]->fx2 ||
g_fp->_mouseScreenPos.y < _files[i]->fy1 || g_fp->_mouseScreenPos.y > _files[i]->fy2 ) {
if (_files[i]->empty) {
_emptyD->setOXY(_files[i]->fx1, _files[i]->fy1);
_emptyD->draw();
} else {
int x = _files[i]->fx1;
for (int j = 0; j < 16; j++) {
_arrayL[_files[i]->date[j]]->setOXY(x + 1, _files[i]->fy1);
_arrayL[_files[i]->date[j]]->draw();
x += _arrayL[_files[i]->date[j]]->getDimensions(&point)->x + 2;
}
}
} else {
if (_files[i]->empty) {
_emptyL->setOXY(_files[i]->fx1, _files[i]->fy1);
_emptyL->draw();
} else {
int x = _files[i]->fx1;
for (int j = 0; j < 16; j++) {
_arrayD[_files[i]->date[j]]->setOXY(x + 1, _files[i]->fy1);
_arrayD[_files[i]->date[j]]->draw();
x += _arrayD[_files[i]->date[j]]->getDimensions(&point)->x + 2;
}
}
}
}
if (_cancelL->isPixelHitAtPos(g_fp->_mouseScreenPos.x, g_fp->_mouseScreenPos.y))
_cancelL->draw();
else if (_okL->isPixelHitAtPos(g_fp->_mouseScreenPos.x, g_fp->_mouseScreenPos.y))
_okL->draw();
}
bool ModalSaveGame::handleMessage(ExCommand *cmd) {
if (_queryDlg)
return _queryDlg->handleMessage(cmd);
if (cmd->_messageNum == 29)
processMouse(cmd->_x, cmd->_y);
else if (cmd->_messageNum == 36)
processKey(cmd->_keyCode);
return false;
}
void ModalSaveGame::processMouse(int x, int y) {
for (uint i = 0; i < _files.size(); i++) {
if (x >= _files[i]->fx1 && x <= _files[i]->fx2 && y >= _files[i]->fy1 && y <= _files[i]->fy2) {
_queryRes = i + 1;
if (_mode) {
if (!_files[i]->empty) {
_queryDlg = new ModalQuery;
_queryDlg->create(_menuScene, 0, PIC_MOV_BGR);
}
}
return;
}
}
if (_cancelL->isPixelHitAtPos(x, y))
_queryRes = 0;
}
void ModalSaveGame::saveload() {
if (_objtype != kObjTypeModalSaveGame)
return;
if (_mode) {
if (getSaveName()) {
bool allowed = true;
for (Common::Array<MessageQueue *>::iterator s = g_fp->_globalMessageQueueList->begin(); s != g_fp->_globalMessageQueueList->end(); ++s) {
if (!(*s)->_isFinished && ((*s)->getFlags() & 1))
allowed = false;
}
if (g_fp->_isSaveAllowed && allowed)
g_fp->_gameLoader->writeSavegame(g_fp->_currentScene, getSaveName());
}
} else {
if (getSaveName()) {
if (_parentObj) {
delete _parentObj;
_parentObj = 0;
}
g_fp->stopAllSoundStreams();
g_fp->stopSoundStream2();
g_fp->_gameLoader->readSavegame(getSaveName());
}
}
}
void FullpipeEngine::openHelp() {
if (!_modalObject) {
ModalHelp *help = new ModalHelp;
_modalObject = help;
help->launch();
}
}
void FullpipeEngine::openMainMenu() {
ModalMainMenu *menu = new ModalMainMenu;
menu->_parentObj = g_fp->_modalObject;
g_fp->_modalObject = menu;
}
} // End of namespace Fullpipe
|
gpl-2.0
|
webtsys/phango2
|
config_sample.php
|
4112
|
<?php
/*********************
# Example config for Web-T-syS Phango 1.0
Well, I think that variables don't need explain but...
**********************/
//Db config variables
//Host database. You have to write the domain name for the mysql server, normally localhost.
PhangoVar::$host_db['default'] = 'localhost';
//Database name. The database that phango use.
PhangoVar::$db['default'] = 'phango';
//Username for database
PhangoVar::$login_db['default'] = 'root';
//Password for database
PhangoVar::$pass_db['default'] = '';
//Type database server, for now, mysql or derivated
define('TYPE_DB','mysql');
//Use standard connection db?
define('USE_DB',0);
#Path variables
//Cookie_path, path of cookie, Example,if your domain is http://www.example.com/mysite, the content in content_path will be '/mysite/'. If your domain is http://www.example.com, you don't need change default $cookie_path
PhangoVar::$cookie_path = '/';
//The name of session...
define('COOKIE_NAME', 'webtsys_id');
//base url, without last slash. Put here tipically, the url of home page of your site.
PhangoVar::$base_url = 'http://www.example.com';
//base url for media, if you want put this on other server, without last slash. Put here tipically, the same value thar $base_url.
PhangoVar::$media_url = PhangoVar::$base_url;
//base path, the REAL PATH in the server.
PhangoVar::$base_path = '/var/www/htdocs/phango/';
//media path, the REAL PATH in the server media. Normally you can mount with nfs or other methods the media disk if is on other server.
PhangoVar::$media_path = PhangoVar::$base_path;
//addons path, if use composer, you can find your modules installed here for load manually.
PhangoVar::$addons_composer_path = PhangoVar::$base_path.'vendor/';
//Path where the index.php alive.
PhangoVar::$application_path = PhangoVar::$base_path.'application/';
//DEBUG, if you active DEBUG, phango send messages with error to stdout
define('DEBUG', '0');
#Language variables
//Language, define display language, you can create many new languages using check_language.php, for the code, use the l10n standard.
PhangoVar::$language = 'en-US';
//Avaliables languages, you can append a new language in the array.
PhangoVar::$arr_i18n = array('es-ES','en-US');
//Timezone, define timezone, you can choose timezones from this list: http://php.net/manual/es/timezones.php
define('MY_TIMEZONE', 'America/New_York');
//App index.Here you can say to phango what module want that is showed in home page.
PhangoVar::$app_index = 'welcome';
//In this array you can append the modules that you want execute. Delete media when your app goes to production.
PhangoVar::$activated_modules = array('welcome', 'media', 'lang');
//Constant for development, delete if you want to go to production.
PhangoVar::$THEME_MODULE=1;
//Constant for the admin section
define('ADMIN_FOLDER', 'admin');
//Theme used by default.
PhangoVar::$dir_theme = 'default';
//If the theme is on a module, use this variable. Example: PhangoVar::$module_theme = 'modules/descuentos/';
PhangoVar::$module_theme = '';
//Default portal name
PhangoVar::$portal_name='My Web';
//Default portal_email
PhangoVar::$portal_email='example@example.com';
//Default date format on php format. More examples: http://php.net/manual/es/function.date.php
PhangoVar::$date_format='d-m-Y';
PhangoVar::$time_format='7200';
//Timezone, define timezone, you can choose timezones from this list: http://php.net/manual/es/timezones.php
PhangoVar::$timezone=MY_TIMEZONE;
//Default time format on php format. More examples: http://php.net/manual/es/function.date.php
PhangoVar::$ampm='H:i:s';
// Default editor used for textareas on TextBBForm
PhangoVar::$textbb_type='ckeditor';
//Captcha type used on many places for clases how login class.
PhangoVar::$captcha_type='';
//Mailer type used for send emails by send_mail function.
PhangoVar::$mailer_type='';
//A key for use in different encryption methods..., change for other, a trick is make a sha1sum with a random file.
PhangoVar::$prefix_key = 'bc24ffaf6dd55be07423bf37bdc24d65d5f7b275';
?>
|
gpl-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.