repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
herzcthu/Laravel-HS
|
resources/views/backend/includes/sidebar.blade.php
|
3540
|
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel (optional) -->
<div class="user-panel">
<div class="pull-left image">
<img src="{!! (!empty(access()->user()->avatar)? access()->user()->avatar: asset('img/backend/user2-160x160.png')) !!}" class="img-circle" alt="User Image" />
</div>
<div class="pull-left info">
<p>{{ access()->user()->name }}</p>
<!-- Status -->
<a href="#"><i class="fa fa-circle text-success"></i> Online</a>
</div>
</div>
<!-- search form (Optional) -->
<!--form action="#" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search..."/>
<span class="input-group-btn">
<button type='submit' name='search' id='search-btn' class="btn btn-flat"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
<!-- /.search form -->
<!-- Sidebar Menu -->
<ul class="sidebar-menu">
<!-- Optionally, you can add icons to the links -->
@permission('view_backend')
<li class="{{ Active::pattern('admin/dashboard') }}"><a href="{!!route('backend.dashboard')!!}"><span>{!! _t('Dashboard') !!}</span></a></li>
@endpermission
@if(!access()->user()->can('view_backend'))
<li class="{{ Active::pattern('dashboard') }}"><a href="{!!route('frontend.dashboard')!!}"><span>{!! _t('Dashboard') !!}</span></a></li>
@endif
@permission('editall_users')
<li class="{{ Active::pattern('admin/access/*') }}"><a href="{!! route('admin.access.users.index')!!}"><span>{!! _t('User Management') !!}</span></a></li>
@endpermission
@permission('manage_media')
<li class="{{ Active::pattern('admin/media/*') }}"><a href="{!! route('admin.media.index')!!}"><span>{!! _t('Media Library') !!}</span></a></li>
@endpermission
@permission('manage_location')
<li class="{{ Active::pattern('admin/locations/*') }}"><a href="{!! route('admin.locations.index')!!}"><span>{!! _t('Locations') !!}</span></a></li>
@endpermission
@permission('manage_participant')
<li class="{{ Active::pattern('admin/participants/*') }}"><a href="{!! route('admin.participants.index')!!}"><span>{!! _t('Participants') !!}</span></a></li>
@endpermission
@permission('manage_project')
<li class="{{ Active::pattern('admin/projects/*') }}"><a href="{!! route('admin.projects.index')!!}"><span>{!! _t('Projects') !!}</span></a></li>
@endpermission
@permission('manage_project')
<li class="{{ Active::pattern('admin/language/*') }}"><a href="{!! route('admin.language.index')!!}"><span>{!! _t('Translation') !!}</span></a></li>
@endpermission
</ul><!-- /.sidebar-menu -->
</section>
<!-- /.sidebar -->
</aside>
|
gpl-2.0
|
jiasilu/Adamour
|
modules/mod_s5_image_and_content_fader/mod_s5_image_and_content_fader.php
|
9361
|
<?php
/**
@version 1.0: mod_s5_image_and_content_fader
Author: Shape 5 - Professional Template Community
Available for download at www.shape5.com
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
$jslibrary = $params->get( 'jslibrary' );
$s5_dropdowntext = $params->get( 's5_dropdowntext' );
$s5_hidecar = $params->get( 's5_hidecar' );
$s5_hidebut = $params->get( 's5_hidebut' );
$s5_hidetext = $params->get( 's5_hidetext' );
$s5_delay = $params->get( 's5_delay' );
if ($s5_hidecar == "falsee") {$s5_hidecar = "false";}
if ($s5_hidecar == "truee") {$s5_hidecar = "true";}
if ($s5_hidebut == "falsee") {$s5_hidebut = "false";}
if ($s5_hidebut == "truee") {$s5_hidebut = "true";}
if ($s5_hidetext == "falsee") {$s5_hidetext = "false";}
if ($s5_hidetext == "truee") {$s5_hidetext = "true";}
$jseffect = $params->get( 'jseffect' );
$background_s5_iacf = $params->get( 'background' );
$pretext_s5_iacf = $params->get( 'pretext' );
$tween_time_s5_iacf = "0.5";
$height_s5_iacf = $params->get( 'height' );
$width_s5_iacf = $params->get( 'width' );
$picture1_s5_iacf = $params->get( 'picture1' );
$picture1link_s5_iacf = $params->get( 'picture1link' );
$picture1target_s5_iacf = $params->get( 'picturetarget' );
$picture2_s5_iacf = $params->get( 'picture2' );
$picture2link_s5_iacf = $params->get( 'picture2link' );
$picture2target_s5_iacf = $params->get( 'picturetarget' );
$picture3_s5_iacf = $params->get( 'picture3' );
$picture3link_s5_iacf = $params->get( 'picture3link' );
$picture3target_s5_iacf = $params->get( 'picturetarget' );
$picture4_s5_iacf = $params->get( 'picture4' );
$picture4link_s5_iacf = $params->get( 'picture4link' );
$picture4target_s5_iacf = $params->get( 'picturetarget' );
$picture5_s5_iacf = $params->get( 'picture5' );
$picture5link_s5_iacf = $params->get( 'picture5link' );
$picture5target_s5_iacf = $params->get( 'picturetarget' );
$picture6_s5_iacf = $params->get( 'picture6' );
$picture6link_s5_iacf = $params->get( 'picture6link' );
$picture6target_s5_iacf = $params->get( 'picturetarget' );
$picture7_s5_iacf = $params->get( 'picture7' );
$picture7link_s5_iacf = $params->get( 'picture7link' );
$picture7target_s5_iacf = $params->get( 'picturetarget' );
$picture8_s5_iacf = $params->get( 'picture8' );
$picture8link_s5_iacf = $params->get( 'picture8link' );
$picture8target_s5_iacf = $params->get( 'picturetarget' );
$picture9_s5_iacf = $params->get( 'picture9' );
$picture9link_s5_iacf = $params->get( 'picture9link' );
$picture9target_s5_iacf = $params->get( 'picturetarget' );
$picture10_s5_iacf = $params->get( 'picture10' );
$picture10link_s5_iacf = $params->get( 'picture10link' );
$picture10target_s5_iacf = $params->get( 'picturetarget' );
$display_time_s5_iacf = "10";
$s5stretchimage = $params->get( 's5stretchimage' );
$s5pixelwidth = $params->get( 's5pixelwidth' );
$title1 = $params->get( 'title1' );
$title2 = $params->get( 'title2' );
$title3 = $params->get( 'title3' );
$title4 = $params->get( 'title4' );
$title5 = $params->get( 'title5' );
$title6 = $params->get( 'title6' );
$title7 = $params->get( 'title7' );
$title8 = $params->get( 'title8' );
$title9 = $params->get( 'title9' );
$title10 = $params->get( 'title10' );
$picture1text_s5_iacf = $params->get( 'picture1text' );
$picture1spacing_s5_iacf = "12px";
$picture1textsize_s5_iacf = $params->get( 'picture1textsize' );
$picture1textcolor_s5_iacf = "ffffff";
$picture1textbg_s5_iacf = "333333";
$picture2text_s5_iacf = $params->get( 'picture2text' );
$picture2spacing_s5_iacf = "12px";
$picture2textsize_s5_iacf = $params->get( 'picture2textsize' );
$picture2textcolor_s5_iacf = "ffffff";
$picture2textbg_s5_iacf = "333333";
$picture3text_s5_iacf = $params->get( 'picture3text' );
$picture3spacing_s5_iacf = "12px";
$picture3textsize_s5_iacf = $params->get( 'picture3textsize' );
$picture3textcolor_s5_iacf = "ffffff";
$picture3textbg_s5_iacf = "333333";
$picture4text_s5_iacf = $params->get( 'picture4text' );
$picture4spacing_s5_iacf = "12px";
$picture4textsize_s5_iacf = $params->get( 'picture4textsize' );
$picture4textcolor_s5_iacf = "ffffff";
$picture4textbg_s5_iacf = "333333";
$picture5text_s5_iacf = $params->get( 'picture5text' );
$picture5spacing_s5_iacf = "12px";
$picture5textsize_s5_iacf = $params->get( 'picture5textsize' );
$picture5textcolor_s5_iacf = "ffffff";
$picture5textbg_s5_iacf = "333333";
$picture6text_s5_iacf = $params->get( 'picture6text' );
$picture6spacing_s5_iacf = "12px";
$picture6textsize_s5_iacf = $params->get( 'picture6textsize' );
$picture6textcolor_s5_iacf = "ffffff";
$picture6textbg_s5_iacf = "333333";
$picture7text_s5_iacf = $params->get( 'picture7text' );
$picture7spacing_s5_iacf = "12px";
$picture7textsize_s5_iacf = $params->get( 'picture7textsize' );
$picture7textcolor_s5_iacf = "ffffff";
$picture7textbg_s5_iacf = "333333";
$picture8text_s5_iacf = $params->get( 'picture8text' );
$picture8spacing_s5_iacf = "12px";
$picture8textsize_s5_iacf = $params->get( 'picture8textsize' );
$picture8textcolor_s5_iacf = "ffffff";
$picture8textbg_s5_iacf = "333333";
$picture9text_s5_iacf = $params->get( 'picture9text' );
$picture9spacing_s5_iacf = "12px";
$picture9textsize_s5_iacf = $params->get( 'picture9textsize' );
$picture9textcolor_s5_iacf = "ffffff";
$picture9textbg_s5_iacf = "333333";
$picture10text_s5_iacf = $params->get( 'picture10text' );
$picture10spacing_s5_iacf = "12px";
$picture10textsize_s5_iacf = $params->get( 'picture10textsize' );
$picture10textcolor_s5_iacf = "ffffff";
$picture10textbg_s5_iacf = "333333";
$picture1textweight_s5_iacf = "normal";
$picture2textweight_s5_iacf = "normal";
$picture3textweight_s5_iacf = "normal";
$picture4textweight_s5_iacf = "normal";
$picture5textweight_s5_iacf = "normal";
$picture6textweight_s5_iacf = "normal";
$picture7textweight_s5_iacf = "normal";
$picture8textweight_s5_iacf = "normal";
$picture9textweight_s5_iacf = "normal";
$picture10textweight_s5_iacf = "normal";
$picture1textopac_s5_iacf = "25";
$picture2textopac_s5_iacf = "25";
$picture3textopac_s5_iacf = "25";
$picture4textopac_s5_iacf = "25";
$picture5textopac_s5_iacf = "25";
$picture6textopac_s5_iacf = "25";
$picture7textopac_s5_iacf = "25";
$picture8textopac_s5_iacf = "25";
$picture9textopac_s5_iacf = "25";
$picture10textopac_s5_iacf = "25";
$non_ie_picture1textopac_s5_iacf = 55/ 100;
$non_ie_picture2textopac_s5_iacf = 55 / 100;
$non_ie_picture3textopac_s5_iacf = 55 / 100;
$non_ie_picture4textopac_s5_iacf = 55 / 100;
$non_ie_picture5textopac_s5_iacf = 55 / 100;
$non_ie_picture6textopac_s5_iacf = 55 / 100;
$non_ie_picture7textopac_s5_iacf = 55 / 100;
$non_ie_picture8textopac_s5_iacf = 55 / 100;
$non_ie_picture9textopac_s5_iacf = 55 / 100;
$non_ie_picture10textopac_s5_iacf = 55 / 100;
$tween_time_s5_iacf = $tween_time_s5_iacf*1000;
$display_time_s5_iacf = $display_time_s5_iacf*1000;
$text_display_effect = $tween_time_s5_iacf * 0.75;
$text_display_time_s5_iacf = $display_time_s5_iacf - $text_display_effect;
if ($picture1target_s5_iacf == "1") {
$picture1target_s5_iacf = "_blank"; }
if ($picture1target_s5_iacf == "0") {
$picture1target_s5_iacf = "_top"; }
if ($picture2target_s5_iacf == "1") {
$picture2target_s5_iacf = "_blank"; }
if ($picture2target_s5_iacf == "0") {
$picture2target_s5_iacf = "_top"; }
if ($picture3target_s5_iacf == "1") {
$picture3target_s5_iacf = "_blank"; }
if ($picture3target_s5_iacf == "0") {
$picture3target_s5_iacf = "_top"; }
if ($picture4target_s5_iacf == "1") {
$picture4target_s5_iacf = "_blank"; }
if ($picture4target_s5_iacf == "0") {
$picture4target_s5_iacf = "_top"; }
if ($picture5target_s5_iacf == "1") {
$picture5target_s5_iacf = "_blank"; }
if ($picture5target_s5_iacf == "0") {
$picture5target_s5_iacf = "_top"; }
if ($picture6target_s5_iacf == "1") {
$picture6target_s5_iacf = "_blank"; }
if ($picture6target_s5_iacf == "0") {
$picture6target_s5_iacf = "_top"; }
if ($picture7target_s5_iacf == "1") {
$picture7target_s5_iacf = "_blank"; }
if ($picture7target_s5_iacf == "0") {
$picture7target_s5_iacf = "_top"; }
if ($picture8target_s5_iacf == "1") {
$picture8target_s5_iacf = "_blank"; }
if ($picture8target_s5_iacf == "0") {
$picture8target_s5_iacf = "_top"; }
if ($picture9target_s5_iacf == "1") {
$picture9target_s5_iacf = "_blank"; }
if ($picture9target_s5_iacf == "0") {
$picture9target_s5_iacf = "_top"; }
if ($picture10target_s5_iacf == "1") {
$picture10target_s5_iacf = "_blank"; }
if ($picture10target_s5_iacf == "0") {
$picture10target_s5_iacf = "_top"; }
if ($s5stretchimage == "") {
$s5stretchimage = "actualsize";}
if ($s5pixelwidth == "") {
$s5pixelwidth = "null";}
JHTML::_('behavior.mootools');
require(JModuleHelper::getLayoutPath('mod_s5_image_and_content_fader'));
?>
<?php if ($s5stretchimage == "stretch") { ?>
<script type="text/javascript">//<![CDATA[
document.write('<style>.jdGallery .slideElement {background-size:100% auto;}<?php if ($s5pixelwidth != "") { ?>@media screen and (max-width: <?php echo $s5pixelwidth; ?>) {#myGallery { height:<?php echo $height_s5_iacf ?> !important; } .jdGallery .slideElement {background-size:auto auto !important;}}<?php } ?></style>');
//]]></script>
<?php } ?>
|
gpl-2.0
|
jankei/dominus
|
game/leftPanels/chatrooms/client/chatroom_list.js
|
1132
|
Template.chatroom_list.helpers({
selectedChatroom: function() {
return Session.get('selectedChatroomId') == Template.currentData()._id
},
numPeople: function() {
return Template.currentData().members.length
},
showNewNotification: function() {
if (Session.get('windowHasFocus') && Session.get('selectedChatroomId') == this._id) {
return false
}
var recent = Recentchats.findOne({room_id:Template.currentData()._id})
if (recent) {
var latest_open = Cookie.get('room_'+this._id+'_open')
if (latest_open) {
if (moment(new Date(recent.updated_at)).isAfter(moment(new Date(latest_open)))) {
return true
}
} else {
return true
}
}
return false
}
})
Template.chatroom_list.events({
'click .openChatroomButton': function(event, template) {
if (Session.get('selectedChatroomId') == template.data._id) {
Session.set('selectedChatroomId', null)
} else {
Session.set('selectedChatroomId', template.data._id)
var date = new Date(TimeSync.serverTime(null, 5000))
Cookie.set('room_'+template.data._id+'_open', moment(date).add(1, 's').toDate(), {years: 10});
}
},
})
|
gpl-2.0
|
VladimirMB/catsproducts
|
index.php
|
2121
|
<?php include 'data/products.php';?>
<?php include 'data/dodaci_tipovi.php';?>
<!DOCTYPE html>
<html lang="sr">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Test</title>
<script type="text/javascript" src="js/jquery-1.7.1.min.js" ></script>
<script type="text/javascript" src="js/js.js"></script>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="wrapper">
<div id="content">
<ul id='main_menu'>
<?php
foreach ($categories as $k=>$category) {
if ($k == 0) {
echo '<li><a class="active" href="#'.$category['category_id_name'].'">'.$category["category_name"].'</a></li>';
} else {
echo '<li><a href="#'.$category['category_id_name'].'">'.$category["category_name"].'</a></li>';
}
}
?>
</ul>
<?php
foreach ($categories as $k=>$category) {
$build = '';
foreach ($products as $product) {
if ($category['category_id'] == $product['category_id']) {
$dodaci_tip = 'dodaci_tip'.$product['dodatak_type'];
$build = $build."
<li data-catid='{$product['category_id']}' data-id='{$product['product_id']}' class='mitem' >
<div class='mitem-image' style='background: url(products/{$product['product_id']}.jpg) center no-repeat; background-size: auto 140px;'></div>
<div class='mitem-title'>
<a href='#' class='name'>{$product['product_name']}</a>
<span>{$product['product_desc']}</span>
${$dodaci_tip}
</div>
<div class='mitem-price'>
<div class='mitem-price-text price'><span class='price'>{$product['product_price']}</span> RSD</div>
</div>
<div class='clear'></div>
</li>
";
}
}
if ($k != 0) {
echo "<ul data-Cid='{$category['category_id']}' id='{$category['category_id_name']}' class='product-content hide' >{$build}</ul>";
} else {
echo "<ul data-Cid='{$category['category_id']}' id='{$category['category_id_name']}' class='product-content' >{$build}</ul>";
}
}
?>
<div class="clear"></div>
</div>
</div>
</body>
</html>
|
gpl-2.0
|
JarnoVgr/ZombieSurvival
|
gamemodes/zombiesurvival/gamemode/zombieclasses/bloated_zombie.lua
|
4928
|
CLASS.Name = "Bloated Zombie"
CLASS.TranslationName = "class_bloated_zombie"
CLASS.Description = "description_bloated_zombie"
CLASS.Help = "controls_bloated_zombie"
CLASS.Wave = 3 / 6
CLASS.Health = 325
CLASS.Speed = 150
CLASS.JumpPower = 150
CLASS.Mass = DEFAULT_MASS * 2
CLASS.CanTaunt = false
CLASS.Points = 6
CLASS.SWEP = "weapon_zs_bloatedzombie"
CLASS.Model = Model("models/player/fatty/fatty.mdl")
CLASS.DeathSounds = {"npc/ichthyosaur/water_growl5.wav"}
CLASS.VoicePitch = 0.6
CLASS.CanFeignDeath = true
sound.Add({
name = "fatty.footstep",
channel = CHAN_BODY,
volume = 0.8,
soundlevel = 65,
pitchstart = 75,
pitchend = 75,
sound = {"npc/zombie/foot1.wav", "npc/zombie/foot2.wav", "npc/zombie/foot3.wav"}
})
sound.Add({
name = "fatty.footscuff",
channel = CHAN_BODY,
volume = 0.8,
soundlevel = 65,
pitchstart = 75,
pitchend = 75,
sound = {"npc/zombie/foot_slide1.wav", "npc/zombie/foot_slide2.wav", "npc/zombie/foot_slide3.wav"}
})
local DIR_BACK = DIR_BACK
local ACT_HL2MP_ZOMBIE_SLUMP_RISE = ACT_HL2MP_ZOMBIE_SLUMP_RISE
local ACT_HL2MP_SWIM_PISTOL = ACT_HL2MP_SWIM_PISTOL
local ACT_HL2MP_IDLE_CROUCH_ZOMBIE = ACT_HL2MP_IDLE_CROUCH_ZOMBIE
local ACT_HL2MP_WALK_CROUCH_ZOMBIE_01 = ACT_HL2MP_WALK_CROUCH_ZOMBIE_01
local ACT_HL2MP_RUN_ZOMBIE = ACT_HL2MP_RUN_ZOMBIE
function CLASS:PlayPainSound(pl)
pl:EmitSound("npc/zombie_poison/pz_idle"..math.random(2, 3)..".wav", 72, math.Rand(75, 85))
return true
end
local mathrandom = math.random
local StepSounds = {
"npc/zombie/foot1.wav",
"npc/zombie/foot2.wav",
"npc/zombie/foot3.wav"
}
local ScuffSounds = {
"npc/zombie/foot_slide1.wav",
"npc/zombie/foot_slide2.wav",
"npc/zombie/foot_slide3.wav"
}
function CLASS:PlayerFootstep(pl, vFootPos, iFoot, strSoundName, fVolume, pFilter)
if mathrandom() < 0.15 then
pl:EmitSound(ScuffSounds[mathrandom(#ScuffSounds)], 70, 75)
else
pl:EmitSound(StepSounds[mathrandom(#StepSounds)], 70, 75)
end
return true
end
function CLASS:CalcMainActivity(pl, velocity)
local feign = pl.FeignDeath
if feign and feign:IsValid() then
if feign:GetDirection() == DIR_BACK then
pl.CalcSeqOverride = pl:LookupSequence("zombie_slump_rise_02_fast")
else
pl.CalcIdeal = ACT_HL2MP_ZOMBIE_SLUMP_RISE
end
return true
end
if pl:WaterLevel() >= 3 then
pl.CalcIdeal = ACT_HL2MP_SWIM_PISTOL
elseif pl:Crouching() then
if velocity:Length2D() <= 0.5 then
pl.CalcIdeal = ACT_HL2MP_IDLE_CROUCH_ZOMBIE
else
pl.CalcIdeal = ACT_HL2MP_WALK_CROUCH_ZOMBIE_01 - 1 + math.ceil((CurTime() / 4 + pl:EntIndex()) % 3)
end
else
pl.CalcIdeal = ACT_HL2MP_RUN_ZOMBIE
end
return true
end
function CLASS:UpdateAnimation(pl, velocity, maxseqgroundspeed)
local feign = pl.FeignDeath
if feign and feign:IsValid() then
if feign:GetState() == 1 then
pl:SetCycle(1 - math.max(feign:GetStateEndTime() - CurTime(), 0) * 0.666)
else
pl:SetCycle(math.max(feign:GetStateEndTime() - CurTime(), 0) * 0.666)
end
pl:SetPlaybackRate(0)
return true
end
local len2d = velocity:Length2D()
if len2d > 0.5 then
pl:SetPlaybackRate(math.min(len2d / maxseqgroundspeed, 3))
else
pl:SetPlaybackRate(1)
end
return true
end
function CLASS:DoAnimationEvent(pl, event, data)
if event == PLAYERANIMEVENT_ATTACK_PRIMARY then
pl:AnimRestartGesture(GESTURE_SLOT_ATTACK_AND_RELOAD, ACT_GMOD_GESTURE_RANGE_ZOMBIE, true)
return ACT_INVALID
end
end
function CLASS:DoesntGiveFear(pl)
return pl.FeignDeath and pl.FeignDeath:IsValid()
end
if SERVER then
function CLASS:AltUse(pl)
pl:StartFeignDeath()
end
local function Bomb(pl, pos, dir)
if not IsValid(pl) then return end
dir:RotateAroundAxis(dir:Right(), 30)
local effectdata = EffectData()
effectdata:SetOrigin(pos)
effectdata:SetNormal(dir:Forward())
util.Effect("fatexplosion", effectdata, true)
for i=1, 6 do
local ang = Angle()
ang:Set(dir)
ang:RotateAroundAxis(ang:Up(), math.Rand(-30, 30))
ang:RotateAroundAxis(ang:Right(), math.Rand(-30, 30))
local heading = ang:Forward()
local ent = ents.CreateLimited("projectile_poisonflesh")
if ent:IsValid() then
ent:SetPos(pos)
ent:SetOwner(pl)
ent:Spawn()
ent:SetTeamID(TEAM_UNDEAD)
local phys = ent:GetPhysicsObject()
if phys:IsValid() then
phys:Wake()
phys:SetVelocityInstantaneous(heading * math.Rand(120, 250))
end
end
end
end
function CLASS:OnKilled(pl, attacker, inflictor, suicide, headshot, dmginfo, assister)
if attacker ~= pl and not suicide then
local pos = pl:LocalToWorld(pl:OBBCenter())
local ang = pl:SyncAngles()
timer.Simple(0, function() Bomb(pl, pos, ang) end)
end
end
end
if CLIENT then
CLASS.Icon = "zombiesurvival/classmenu/zombine2"
end
|
gpl-2.0
|
smarr/Truffle
|
tools/src/org.graalvm.tools.lsp/src/org/graalvm/tools/lsp/server/types/MessageActionItem.java
|
2539
|
/*
* Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.tools.lsp.server.types;
import com.oracle.truffle.tools.utils.json.JSONObject;
import java.util.Objects;
public class MessageActionItem extends JSONBase {
MessageActionItem(JSONObject jsonData) {
super(jsonData);
}
/**
* A short title like 'Retry', 'Open Log' etc.
*/
public String getTitle() {
return jsonData.getString("title");
}
public MessageActionItem setTitle(String title) {
jsonData.put("title", title);
return this;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
MessageActionItem other = (MessageActionItem) obj;
if (!Objects.equals(this.getTitle(), other.getTitle())) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 41 * hash + Objects.hashCode(this.getTitle());
return hash;
}
public static MessageActionItem create(String title) {
final JSONObject json = new JSONObject();
json.put("title", title);
return new MessageActionItem(json);
}
}
|
gpl-2.0
|
sdl/Sdl-Community
|
MT Enhanced Provider/Sdl.Community.MtEnhancedProvider/GoogleApi/MtTranslationProviderGTApiConnecter.cs
|
9487
|
/* Copyright 2015 Patrick Porter
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;
using NLog;
using Sdl.Community.MtEnhancedProvider.Service;
using Sdl.LanguagePlatform.Core;
namespace Sdl.Community.MtEnhancedProvider.GoogleApi
{
public class MtTranslationProviderGTApiConnecter
{
//holds supported languages so we don't have to keep pinging google once the lang has been checked
//the structure is <targetLang, List<sourceLangs>>
public static Dictionary<string, List<string>> DictSupportedLangs;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly HtmlUtil _htmlUtil;
public MtTranslationProviderGTApiConnecter(string key, HtmlUtil htmlUtil)
{
ApiKey = key;
_htmlUtil = htmlUtil;
}
public string ApiKey { get; set; }//for when this is already instantiated but key is changed in dialog
private void UpdateSupportedLangs(string target)
{
var list = GetSourceLangsList(target);
if (list == null) //returns null if error
{
var message = PluginResources.LangPairAuthErrorMsg1 + Environment.NewLine + PluginResources.LangPairAuthErrorMsg2;
throw new Exception(message); //b/c list will come back null if key is bad
}
if (!DictSupportedLangs.ContainsKey(target))
{
DictSupportedLangs.Add(target, list);
}
}
public bool IsSupportedLangPair(CultureInfo sourceCulture, CultureInfo targetCulture)
{
var sourceLang = GetLanguageCode(sourceCulture);
var targetLang = GetLanguageCode(targetCulture);
if (DictSupportedLangs == null)
{
DictSupportedLangs = new Dictionary<string, List<string>>();
}
if (!DictSupportedLangs.ContainsKey(targetLang))
{
UpdateSupportedLangs(targetLang);
}
return DictSupportedLangs[targetLang].Any(source => source == sourceLang);
}
/// <summary>
/// Used to translate plain text only.
/// </summary>
public string Translate(LanguagePair langPair, string text) //this is called for just plain text
{
text = HttpUtility.HtmlEncode(text); //we want to HtmlEncode a plain text segment
var result = DoTranslate(langPair, text, "html");
return result;
}
/// <summary>
/// Used to translate as html to allow for tag markup
/// </summary>
public string Translate(LanguagePair langPair, string text, string format) //this is called for segments with tags
{
//here we do not HtmlEncode b/c the tagplacer will do that later..selectively
var result = DoTranslate(langPair, text, format);
return result;
}
//Credentials are validated only then we try to translate something
//Translate a dummy text in order to show the error on the UI when user try to close the window.
public void ValidateCredentials()
{
var langPair = new LanguagePair
{
SourceCulture = new CultureInfo("en-us"),
TargetCulture = new CultureInfo("de-de")
};
Translate(langPair, string.Empty);
}
private string DoTranslate(LanguagePair langPair, string text, string format)
{
try
{
if (string.IsNullOrEmpty(ApiKey))
{
throw new Exception(PluginResources.ApiConnectionGoogleNoKeyErrorMessage);
}
var targetLang = langPair.TargetCulture.Name.Equals("fr-HT") ? "ht" : GetLanguageCode(langPair.TargetCulture);
text = EncodeSpecialChars(text); //all strings should get this final check for characters that seem to break GT api
//create the url for the translate request
var url = $"https://translation.googleapis.com/language/translate/v2?key={ApiKey}&q={text}&target={targetLang}";
if (format != "") //add format if provided
{
url += $"&format={format}";
}
string result; //this will take the result from the webclient
using (var webClient = new WebClient())
{
webClient.Encoding = Encoding.UTF8;
try
{
result = webClient.DownloadString(url); //gets us the json data indicating supported source languages for this target
}
catch (WebException e) //will come back 400 bad request if there is a problem
{
_logger.Error($"{MethodBase.GetCurrentMethod().Name} {e.Message}\n { e.StackTrace}");
var eReason = GetExceptionReason(e);
//get our localized error message from the resources file
throw new Exception(eReason);
}
}
//need to parse results and find key "translatedText" - there should be only one
var returnedResult = GetTranslation(result);
var decodedResult = _htmlUtil.HtmlDecode(returnedResult); //google seems to send back html codes at times
//for some reason, GT is sometimes adding zero-width spaces, aka "bom", aka char(8203)
//so we need to remove it
decodedResult = GtRemoveBoms(decodedResult);
return decodedResult;
}
catch (Exception ex)
{
_logger.Error($"{MethodBase.GetCurrentMethod().Name} {ex.Message}\n { ex.StackTrace}");
throw new Exception(ex.Message);
}
}
private string GtRemoveBoms(string input)
{
//this is to deal with google putting in zero-width spaces for some reason, i.e. char(8203)
//convert returned text to char array
var chars = input.ToCharArray();
//remove all char8203 using linq
chars = chars.Where(val => val != (char)8203).ToArray();
//convert back to a string
return new string(chars);
}
private string GetLanguageCode(CultureInfo ci)
{
if (ci.Name == "zh-TW" || ci.Name == "zh-CN") { return ci.Name; } //just get the name for zh-TW which Google can process..google can also process simplified when specifying target as zh-CN but it breaks when you specify that as source??
if (ci.Name.Equals("nb-NO") || ci.Name.Equals("nn-NO")) return "no";
if (ci.TwoLetterISOLanguageName.Equals("sr") && ci.DisplayName.ToLower().Contains("latin")) return "sr-Latn";
var strReturn = ci.TwoLetterISOLanguageName; //if not chinese trad or norweigian get 2 letter code
//convert tagalog and hebrew for Google
if (strReturn == "fil") { strReturn = "tl"; }
if (strReturn == "he") { strReturn = "iw"; }
return strReturn;
}
private string EncodeSpecialChars(string strInput)
{
//google can't handle some url encoded characters
//but if we UrlEncodeUnicode all of them
//it screws up non-latin alphabet languages
//...workaround:
strInput = strInput.Replace("#", "%23");
strInput = strInput.Replace("&", "%26");
strInput = strInput.Replace(";", "%3b");
return strInput;
}
public List<string> GetSourceLangsList(string targetLang)
{
var list = new List<string>();
try
{
var url = $"https://www.googleapis.com/language/translate/v2/languages?key={ApiKey}&target={targetLang}";
var result = ""; //this will take the result from the webclient
using (var webClient = new WebClient{Encoding = Encoding.UTF8})
{
try
{
result = webClient.DownloadString(url); //gets us the json data indicating supported source languages for this target
}
catch (WebException e) //will come back 400 invalid value if target lang not supported
{
_logger.Error($"{MethodBase.GetCurrentMethod().Name} {e.Message}\n { e.StackTrace}");
var eReason = GetExceptionReason(e);
return eReason == "Bad Request" ? null : new List<string> {"unsupported"};
//otherwise, if it is b/c of a non-supported targetLang, eReason will be "Invalid Value"
}
}
list = GetLanguageCodes(result);
}
catch (Exception ex)
{
_logger.Error($"{MethodBase.GetCurrentMethod().Name} {ex.Message}\n { ex.StackTrace}");
}
return list;
}
private string ParseReturnedError(string input)
{
//this is different from successful response parses
var ser = new JavaScriptSerializer();
var message = string.Empty;
var dict = ser.Deserialize<Dictionary<string, Dictionary<string, object>>>(input);
foreach (var strKey in dict.Keys) //this structure gets it out
{
object o = dict[strKey];
var dict2 = (Dictionary<string, object>)o;
message = dict2["message"].ToString();
}
return message;
}
private List<string> GetLanguageCodes(string input)
{
var jsonObject = JObject.Parse(input)["data"]["languages"].ToArray();
return jsonObject.Select(language => language["language"].ToString()).ToList();
}
private string GetTranslation(string input)
{
var jsonObject = JObject.Parse(input)["data"]["translations"];
return jsonObject[0]["translatedText"].ToString();
}
private string GetExceptionReason(WebException exception)
{
var myStream = exception.Response.GetResponseStream();
if (myStream == null) return string.Empty;
var x = new System.IO.StreamReader(myStream);
var contents = x.ReadToEnd();
var reason = ParseReturnedError(contents);
return reason;
}
}
}
|
gpl-2.0
|
miguelinux/vbox
|
src/VBox/Runtime/r3/win/vcc100-kernel32-fakes.cpp
|
12649
|
/* $Id: vcc100-kernel32-fakes.cpp $ */
/** @file
* IPRT - Tricks to make the Visual C++ 2010 CRT work on NT4, W2K and XP.
*/
/*
* Copyright (C) 2012-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#include <iprt/cdefs.h>
#include <iprt/types.h>
#include <iprt/asm.h>
#include <iprt/string.h>
#ifndef RT_ARCH_X86
# error "This code is X86 only"
#endif
#define DecodePointer Ignore_DecodePointer
#define EncodePointer Ignore_EncodePointer
#define InitializeCriticalSectionAndSpinCount Ignore_InitializeCriticalSectionAndSpinCount
#define HeapSetInformation Ignore_HeapSetInformation
#define HeapQueryInformation Ignore_HeapQueryInformation
#define CreateTimerQueue Ignore_CreateTimerQueue
#define CreateTimerQueueTimer Ignore_CreateTimerQueueTimer
#define DeleteTimerQueueTimer Ignore_DeleteTimerQueueTimer
#define InitializeSListHead Ignore_InitializeSListHead
#define InterlockedFlushSList Ignore_InterlockedFlushSList
#define InterlockedPopEntrySList Ignore_InterlockedPopEntrySList
#define InterlockedPushEntrySList Ignore_InterlockedPushEntrySList
#define QueryDepthSList Ignore_QueryDepthSList
#define VerifyVersionInfoA Ignore_VerifyVersionInfoA
#define VerSetConditionMask Ignore_VerSetConditionMask
#include <Windows.h>
#undef DecodePointer
#undef EncodePointer
#undef InitializeCriticalSectionAndSpinCount
#undef HeapSetInformation
#undef HeapQueryInformation
#undef CreateTimerQueue
#undef CreateTimerQueueTimer
#undef DeleteTimerQueueTimer
#undef InitializeSListHead
#undef InterlockedFlushSList
#undef InterlockedPopEntrySList
#undef InterlockedPushEntrySList
#undef QueryDepthSList
#undef VerifyVersionInfoA
#undef VerSetConditionMask
#ifndef HEAP_STANDARD
# define HEAP_STANDARD 0
#endif
/** Dynamically resolves an kernel32 API. */
#define RESOLVE_ME(ApiNm) \
static bool volatile s_fInitialized = false; \
static decltype(ApiNm) *s_pfnApi = NULL; \
decltype(ApiNm) *pfnApi; \
if (!s_fInitialized) \
pfnApi = s_pfnApi; \
else \
{ \
pfnApi = (decltype(pfnApi))GetProcAddress(GetModuleHandleW(L"kernel32"), #ApiNm); \
s_pfnApi = pfnApi; \
s_fInitialized = true; \
} do {} while (0) \
extern "C"
__declspec(dllexport) PVOID WINAPI
DecodePointer(PVOID pvEncoded)
{
RESOLVE_ME(DecodePointer);
if (pfnApi)
return pfnApi(pvEncoded);
/*
* Fallback code.
*/
return pvEncoded;
}
extern "C"
__declspec(dllexport) PVOID WINAPI
EncodePointer(PVOID pvNative)
{
RESOLVE_ME(EncodePointer);
if (pfnApi)
return pfnApi(pvNative);
/*
* Fallback code.
*/
return pvNative;
}
extern "C"
__declspec(dllexport) BOOL WINAPI
InitializeCriticalSectionAndSpinCount(LPCRITICAL_SECTION pCritSect, DWORD cSpin)
{
RESOLVE_ME(InitializeCriticalSectionAndSpinCount);
if (pfnApi)
return pfnApi(pCritSect, cSpin);
/*
* Fallback code.
*/
InitializeCriticalSection(pCritSect);
return TRUE;
}
extern "C"
__declspec(dllexport) BOOL WINAPI
HeapSetInformation(HANDLE hHeap, HEAP_INFORMATION_CLASS enmInfoClass, PVOID pvBuf, SIZE_T cbBuf)
{
RESOLVE_ME(HeapSetInformation);
if (pfnApi)
return pfnApi(hHeap, enmInfoClass, pvBuf, cbBuf);
/*
* Fallback code.
*/
if (enmInfoClass == HeapCompatibilityInformation)
{
if ( cbBuf != sizeof(ULONG)
|| !pvBuf
|| *(PULONG)pvBuf == HEAP_STANDARD
)
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
return TRUE;
}
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
extern "C"
__declspec(dllexport) BOOL WINAPI
HeapQueryInformation(HANDLE hHeap, HEAP_INFORMATION_CLASS enmInfoClass, PVOID pvBuf, SIZE_T cbBuf, PSIZE_T pcbRet)
{
RESOLVE_ME(HeapQueryInformation);
if (pfnApi)
return pfnApi(hHeap, enmInfoClass, pvBuf, cbBuf, pcbRet);
/*
* Fallback code.
*/
if (enmInfoClass == HeapCompatibilityInformation)
{
*pcbRet = sizeof(ULONG);
if (cbBuf < sizeof(ULONG) || !pvBuf)
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
*(PULONG)pvBuf = HEAP_STANDARD;
return TRUE;
}
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
/* These are used by INTEL\mt_obj\Timer.obj: */
extern "C"
__declspec(dllexport)
HANDLE WINAPI CreateTimerQueue(void)
{
RESOLVE_ME(CreateTimerQueue);
if (pfnApi)
return pfnApi();
SetLastError(ERROR_NOT_SUPPORTED);
return NULL;
}
extern "C"
__declspec(dllexport)
BOOL WINAPI CreateTimerQueueTimer(PHANDLE phTimer, HANDLE hTimerQueue, WAITORTIMERCALLBACK pfnCallback, PVOID pvUser,
DWORD msDueTime, DWORD msPeriod, ULONG fFlags)
{
RESOLVE_ME(CreateTimerQueueTimer);
if (pfnApi)
return pfnApi(phTimer, hTimerQueue, pfnCallback, pvUser, msDueTime, msPeriod, fFlags);
SetLastError(ERROR_NOT_SUPPORTED);
return FALSE;
}
extern "C"
__declspec(dllexport)
BOOL WINAPI DeleteTimerQueueTimer(HANDLE hTimerQueue, HANDLE hTimer, HANDLE hEvtCompletion)
{
RESOLVE_ME(DeleteTimerQueueTimer);
if (pfnApi)
return pfnApi(hTimerQueue, hTimer, hEvtCompletion);
SetLastError(ERROR_NOT_SUPPORTED);
return FALSE;
}
/* This is used by several APIs. */
extern "C"
__declspec(dllexport)
VOID WINAPI InitializeSListHead(PSLIST_HEADER pHead)
{
RESOLVE_ME(InitializeSListHead);
if (pfnApi)
pfnApi(pHead);
else /* fallback: */
pHead->Alignment = 0;
}
extern "C"
__declspec(dllexport)
PSLIST_ENTRY WINAPI InterlockedFlushSList(PSLIST_HEADER pHead)
{
RESOLVE_ME(InterlockedFlushSList);
if (pfnApi)
return pfnApi(pHead);
/* fallback: */
PSLIST_ENTRY pRet = NULL;
if (pHead->Next.Next)
{
for (;;)
{
SLIST_HEADER OldHead = *pHead;
SLIST_HEADER NewHead;
NewHead.Alignment = 0;
NewHead.Sequence = OldHead.Sequence + 1;
if (ASMAtomicCmpXchgU64(&pHead->Alignment, NewHead.Alignment, OldHead.Alignment))
{
pRet = OldHead.Next.Next;
break;
}
}
}
return pRet;
}
extern "C"
__declspec(dllexport)
PSLIST_ENTRY WINAPI InterlockedPopEntrySList(PSLIST_HEADER pHead)
{
RESOLVE_ME(InterlockedPopEntrySList);
if (pfnApi)
return pfnApi(pHead);
/* fallback: */
PSLIST_ENTRY pRet = NULL;
for (;;)
{
SLIST_HEADER OldHead = *pHead;
pRet = OldHead.Next.Next;
if (pRet)
{
SLIST_HEADER NewHead;
__try
{
NewHead.Next.Next = pRet->Next;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
continue;
}
NewHead.Depth = OldHead.Depth - 1;
NewHead.Sequence = OldHead.Sequence + 1;
if (ASMAtomicCmpXchgU64(&pHead->Alignment, NewHead.Alignment, OldHead.Alignment))
break;
}
else
break;
}
return pRet;
}
extern "C"
__declspec(dllexport)
PSLIST_ENTRY WINAPI InterlockedPushEntrySList(PSLIST_HEADER pHead, PSLIST_ENTRY pEntry)
{
RESOLVE_ME(InterlockedPushEntrySList);
if (pfnApi)
return pfnApi(pHead, pEntry);
/* fallback: */
PSLIST_ENTRY pRet = NULL;
for (;;)
{
SLIST_HEADER OldHead = *pHead;
pRet = OldHead.Next.Next;
pEntry->Next = pRet;
SLIST_HEADER NewHead;
NewHead.Next.Next = pEntry;
NewHead.Depth = OldHead.Depth + 1;
NewHead.Sequence = OldHead.Sequence + 1;
if (ASMAtomicCmpXchgU64(&pHead->Alignment, NewHead.Alignment, OldHead.Alignment))
break;
}
return pRet;
}
extern "C"
__declspec(dllexport)
WORD WINAPI QueryDepthSList(PSLIST_HEADER pHead)
{
RESOLVE_ME(QueryDepthSList);
if (pfnApi)
return pfnApi(pHead);
return pHead->Depth;
}
/* curl drags these in: */
extern "C"
__declspec(dllexport)
BOOL WINAPI VerifyVersionInfoA(LPOSVERSIONINFOEXA pInfo, DWORD fTypeMask, DWORDLONG fConditionMask)
{
RESOLVE_ME(VerifyVersionInfoA);
if (pfnApi)
return pfnApi(pInfo, fTypeMask, fConditionMask);
/* fallback to make curl happy: */
OSVERSIONINFOEXA VerInfo;
RT_ZERO(VerInfo);
VerInfo.dwOSVersionInfoSize = sizeof(VerInfo);
if (!GetVersionEx((OSVERSIONINFO *)&VerInfo))
{
RT_ZERO(VerInfo);
VerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
AssertReturn(GetVersionEx((OSVERSIONINFO *)&VerInfo), FALSE);
}
BOOL fRet = TRUE;
for (unsigned i = 0; i < 8 && fRet; i++)
if (fTypeMask & RT_BIT_32(i))
{
uint32_t uLeft, uRight;
switch (RT_BIT_32(i))
{
#define MY_CASE(a_Num, a_Member) case a_Num: uLeft = VerInfo.a_Member; uRight = pInfo->a_Member; break
MY_CASE(VER_MINORVERSION, dwMinorVersion);
MY_CASE(VER_MAJORVERSION, dwMajorVersion);
MY_CASE(VER_BUILDNUMBER, dwBuildNumber);
MY_CASE(VER_PLATFORMID, dwPlatformId);
MY_CASE(VER_SERVICEPACKMINOR, wServicePackMinor);
MY_CASE(VER_SERVICEPACKMAJOR, wServicePackMinor);
MY_CASE(VER_SUITENAME, wSuiteMask);
MY_CASE(VER_PRODUCT_TYPE, wProductType);
#undef MY_CASE
default: uLeft = uRight = 0; AssertFailed();
}
switch ((uint8_t)(fConditionMask >> (i*8)))
{
case VER_EQUAL: fRet = uLeft == uRight; break;
case VER_GREATER: fRet = uLeft > uRight; break;
case VER_GREATER_EQUAL: fRet = uLeft >= uRight; break;
case VER_LESS: fRet = uLeft < uRight; break;
case VER_LESS_EQUAL: fRet = uLeft <= uRight; break;
case VER_AND: fRet = (uLeft & uRight) == uRight; break;
case VER_OR: fRet = (uLeft & uRight) != 0; break;
default: fRet = FALSE; AssertFailed(); break;
}
}
return fRet;
}
extern "C"
__declspec(dllexport)
ULONGLONG WINAPI VerSetConditionMask(ULONGLONG fConditionMask, DWORD fTypeMask, BYTE bOperator)
{
RESOLVE_ME(VerSetConditionMask);
if (pfnApi)
return pfnApi(fConditionMask, fTypeMask, bOperator);
/* fallback: */
for (unsigned i = 0; i < 8; i++)
if (fTypeMask & RT_BIT_32(i))
{
uint64_t fMask = UINT64_C(0xff) << (i*8);
fConditionMask &= ~fMask;
fConditionMask |= (uint64_t)bOperator << (i*8);
}
return fConditionMask;
}
/* Dummy to force dragging in this object in the link, so the linker
won't accidentally use the symbols from kernel32. */
extern "C" int vcc100_kernel32_fakes_cpp(void)
{
return 42;
}
|
gpl-2.0
|
podonoghue/usbdm-eclipse-makefiles-build
|
PackageFiles/Stationery/Packages/180.ARM_Peripherals/Snippets/spi-2-config-example.cpp
|
3805
|
/*
==============================================================================
* @file spi-2-config-example.cpp (180.ARM_Peripherals/Snippets)
* @brief C++ demo using SPI interface
*
* This example sets up two hardware configurations and switches between them.
* This has low overhead but is limited by the hardware.
* - Two configurations (assuming 2 SPI CTARs)
* - These configurations may be used with multiple devices (limited by PCSs)
*
* Created on: 10/12/2021
* Author: podonoghue
==============================================================================
*/
/*
* This example requires a loop-back between SPI_MOSI and SPI_MISO.
* It may be necessary to adjust the peripheral selection to an available pin.
*
* The SPI signals used must be mapped to pins in Configure.usbdmProject
* - SPI0_SCK
* - SPI0_SIN
* - SPI0_SOUT
* - SPI0_PCS0
* - SPI0_PCS1
*/
#include <string.h>
#include "hardware.h"
#include "spi.h"
using namespace USBDM;
static const SpiConfigurations configurations {
// Speed Mode Bit Order Frame Size
/* Configuration 0 (CTAR0) */ { 1'000'000, SpiMode_0, SpiOrder_MsbFirst, SpiFrameSize_8},
/* Configuration 1 (CTAR1) */ {10'000'000, SpiMode_0, SpiOrder_MsbFirst, SpiFrameSize_12},
/* PCS idle levels */ SpiPeripheralSelect_None, // All PCSs idle low
};
int main() {
Spi0 spi{};
// Configure two configurations (CTARs) and the idle levels for PCSs
spi.setConfigurations(configurations);
for(;;) {
{
/*
* Odd transmission
*
* Transmit with configuration 0
* 8-bit transfers @ 1 MHz using PCS0
*/
static const uint8_t txDataA[] = { 0xA1,0xB2,0xC3,0xD4,0x55, };
uint8_t rxData1[sizeof(txDataA)/sizeof(txDataA[0])] = {0};
uint8_t rxData2[sizeof(txDataA)/sizeof(txDataA[0])] = {0};
uint8_t rxData3 = 0;
uint8_t rxData4 = 0;
spi.startTransaction(SpiPeripheralSelect_0, SpiCtarSelect_0);
spi.txRx(txDataA, rxData1); // 5 bytes tx-rx
spi.txRx(txDataA, rxData2); // 5 bytes tx-rx
rxData3 = spi.txRx(txDataA[0]); // 1 byte tx-rx
rxData4 = spi.txRx(txDataA[1]); // 1 byte tx-rx
spi.endTransaction();
if ((memcmp(txDataA, rxData1, sizeof(txDataA)/sizeof(txDataA[0])) != 0) ||
(memcmp(txDataA, rxData2, sizeof(txDataA)/sizeof(txDataA[0])) != 0) ||
(rxData3 != txDataA[0]) ||
(rxData4 != txDataA[1])) {
console.writeln("Failed read-back");
__asm__("bkpt");
}
}
{
/*
* Even transmission
*
* Transmit with configuration 1
* 12-bit transfers @ 10 MHz using PCS2
*/
static const uint16_t txDataB[] = { 0xA01,0xB02,0xC03,0xD04,0x555, };
uint16_t rxData1[sizeof(txDataB)/sizeof(txDataB[0])] = {0};
uint16_t rxData2[sizeof(txDataB)/sizeof(txDataB[0])] = {0};
uint16_t rxData3 = 0;;
uint16_t rxData4 = 0;
spi.startTransaction(SpiPeripheralSelect_1, SpiCtarSelect_1);
spi.txRx(txDataB, rxData1); // 5 bytes tx-rx
spi.txRx(txDataB, rxData2); // 5 bytes tx-rx
rxData3 = spi.txRx(txDataB[0]); // 1 byte tx-rx
rxData4 = spi.txRx(txDataB[1]); // 1 byte tx-rx
spi.endTransaction();
if ((memcmp(txDataB, rxData1, sizeof(txDataB)/sizeof(txDataB[0])) != 0) ||
(memcmp(txDataB, rxData2, sizeof(txDataB)/sizeof(txDataB[0])) != 0) ||
(rxData3 != txDataB[0]) ||
(rxData4 != txDataB[1])) {
console.writeln("Failed read-back");
__asm__("bkpt");
}
}
wait(10_ms);
}
}
|
gpl-2.0
|
Electrolysm/Electrolysm-Chemistry
|
java/chemistry/electrolysm/chemicals/ChemicalCompression.java
|
1674
|
package chemistry.electrolysm.chemicals;
import electrolysm.api.items.RecipeStack;
import chemistry.electrolysm.chemicals.Values.ChemicalValue;
import chemistry.electrolysm.chemicals.Values.MultiChemical;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* Created by Clarky158 on 07/09/2014.
*/
public class ChemicalCompression {
public static HashMap<List<RecipeStack>, RecipeStack> map = new HashMap<List<RecipeStack>, RecipeStack>();
public ChemicalCompression(){
MultiChemical.elements e = new MultiChemical.elements();
}
private void register(List<ItemStack> inputChem, ItemStack result) {
List<RecipeStack> list = new ArrayList<RecipeStack>();
for (int i = 0; i < inputChem.size(); i++) {
list.add(i, new RecipeStack(inputChem.get(i)));
}
map.put(list, new RecipeStack(result));
}
private void registerChem(List<MultiChemical> values, ItemStack result){
List<RecipeStack> list = new ArrayList<RecipeStack>();
for (int i = 0; i < values.size(); i++) {
list.add(new RecipeStack(ChemicalSeparation.createItemStack(values.get(i), 1)));
}
map.put(list, new RecipeStack(result));
}
public ItemStack getProduct(ItemStack[] stacks) {
List<ItemStack> list = new ArrayList<ItemStack>();
for (int i = 0; i < stacks.length; i++) {
list.add(stacks[i]);
}
if(map.get(list) != null) {
return map.get(list).getStackValue();
}
return null;
}
}
|
gpl-2.0
|
AmandaMoen/AmandaMoen
|
notes/resources/UW_IntroClass/class10/code/Solutions/python_literal.py
|
863
|
#!/usr/bin/env python
"""
Example of how to save data as python literals in a py file
"""
outfilename = "add_book_data.pyliteral"
# get the data from the py file
from add_book_data import AddressBook
# save it as python literals:
outfile = open(outfilename, 'w')
outfile.write(str(AddressBook))
outfile.close()
## see if we can re-load it
data = open(outfilename, 'r').read()
AddressBook2 = eval(data)
if AddressBook2 == AddressBook:
print "they are the same"
## try again with the pretty print version:
import pprint
outfilename = "add_book_data.pyliteral_pretty"
outfile = open(outfilename, 'w')
outfile.write(pprint.pformat(AddressBook))
outfile.close()
## see if we can re-load it
data = open(outfilename, 'r').read()
AddressBook2 = eval(data)
if AddressBook2 == AddressBook:
print "pretty printed version is the same as well"
|
gpl-2.0
|
ticketscad/TicketsCAD-Stable-Releases
|
upgrade.php
|
3405
|
<?php
/*
3/18/09 added direcs
3/22/09 remove terrain, add version settings update
7/28/10 Added inclusion of startup.inc.php for checking of network status and setting of file name variables to support no-maps versions of scripts.
3/15/11 changed stylesheet.php to stylesheet.php
*/
error_reporting(E_ALL); // 10/1/08
@session_start();
require_once($_SESSION['fip']); //7/28/10
$old_version = get_variable('_version');
$from_version = "2.10 D beta";
//$from_version = "2.10 D betaZ";
$this_version = "2.10 E beta";
if (!(trim($old_version)==trim($from_version) )) {
die ("This script upgrades *only* version '{$from_version}' - but has detected version '{$old_version}' in database '{$mysql_db}'.\n<br />\n<br />Please correct.");
}
// 3/18/09
$query = "ALTER TABLE `$GLOBALS[mysql_prefix]responder` ADD `direcs` TINYINT( 2 ) NOT NULL DEFAULT '1' COMMENT '0=>no directions, 1=> yes' AFTER `mobile` ;";
$result = mysql_query($query) or do_error($query,'mysql_query() failed',mysql_error(), basename( __FILE__), __LINE__);
$query = "ALTER TABLE `$GLOBALS[mysql_prefix]responder` ADD `instam` TINYINT( 2 ) NOT NULL DEFAULT '0' COMMENT 'instamapper' AFTER `aprs` ;";
$result = mysql_query($query) or do_error($query,'mysql_query() failed',mysql_error(), basename( __FILE__), __LINE__);
$query = "UPDATE `$GLOBALS[mysql_prefix]settings` SET `name` = 'auto_poll' WHERE `settings`.`name` ='aprs_poll' LIMIT 1 ;";
$result = mysql_query($query) or do_error($query,'mysql_query() failed',mysql_error(), basename( __FILE__), __LINE__);
$query = "UPDATE `$GLOBALS[mysql_prefix]settings` SET `value` = '{$this_version}' WHERE `settings`.`name` ='_version' LIMIT 1 ;"; // 3/22/09
$result = mysql_query($query) or do_error($query,'mysql_query() failed',mysql_error(), basename( __FILE__), __LINE__);
$query = "ALTER TABLE `$GLOBALS[mysql_prefix]tracks_hh` ADD `utc_stamp` BIGINT( 12 ) NOT NULL DEFAULT '0' COMMENT 'Position timestamp in UTC' AFTER `altitude` ;";
$result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename( __FILE__), __LINE__);
$query = "INSERT INTO `$GLOBALS[mysql_prefix]settings` (`id`, `name`, `value`) VALUES
(NULL, 'quick', '1'),
(NULL, 'msg_text_1', ''),
(NULL, 'msg_text_2', ''),
(NULL, 'msg_text_3', ''),
(NULL, 'situ_refr', '120'),
(NULL, 'instamapper', '0');";
$result = mysql_query($query) or do_error($query,'mysql_query() failed',mysql_error(), basename( __FILE__), __LINE__);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<META NAME="Author" CONTENT="A. Shore">
<META NAME="Description" CONTENT="Tickets Version Upgrade Script - <?php print $old_version; ?> to <?php print $this_version; ?>">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<META HTTP-EQUIV="Expires" CONTENT="0">
<META HTTP-EQUIV="Cache-Control" CONTENT="NO-CACHE">
<META HTTP-EQUIV="Pragma" CONTENT="NO-CACHE">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
<LINK REL=StyleSheet HREF="stylesheet.php?version=<?php print time();?>" TYPE="text/css"> <!-- 3/15/11 -->
</HEAD>
<BODY>
<BR /><BR /><BR /><CENTER>
<H3>Tickets Version Upgrade: '<?php print $old_version; ?>' to '<?php print $this_version; ?>' with database '<?php print $mysql_db; ?>' completed.
<BR /><BR />
<SPAN onClick = "location.href='index.php'"><U>Start</U></SPAN></H3>
</CENTER>
</BODY>
</HTML>
|
gpl-2.0
|
mkdee/d8rules
|
DateServer/src/DateLibrary/grammar/DateExpressionLexer.cs
|
363
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Antlr.Runtime;
namespace drules.dates.library.grammar
{
public partial class DateExpressionLexer
{
// ReSharper disable InconsistentNaming
public const int HIDDEN = BaseRecognizer.Hidden;
// ReSharper restore InconsistentNaming
}
}
|
gpl-2.0
|
jeka5555/rengine
|
core/.assets/js/jquery/jquery.rightClick.js
|
1334
|
if(jQuery) (function(){
$.extend($.fn, {
rightClick: function(handler) {
$(this).each( function() {
$(this).mousedown( function(e) {
var evt = e;
$(this).mouseup( function() {
$(this).unbind('mouseup');
if( evt.button == 2 ) {
handler.call( $(this), evt );
return false;
} else {
return true;
}
});
});
$(this)[0].oncontextmenu = function() {
return false;
}
});
return $(this);
},
rightMouseDown: function(handler) {
$(this).each( function() {
$(this).mousedown( function(e) {
if( e.button == 2 ) {
handler.call( $(this), e );
return false;
} else {
return true;
}
});
$(this)[0].oncontextmenu = function() {
return false;
}
});
return $(this);
},
rightMouseUp: function(handler) {
$(this).each( function() {
$(this).mouseup( function(e) {
if( e.button == 2 ) {
handler.call( $(this), e );
return false;
} else {
return true;
}
});
$(this)[0].oncontextmenu = function() {
return false;
}
});
return $(this);
},
noContext: function() {
$(this).each( function() {
$(this)[0].oncontextmenu = function() {
return false;
}
});
return $(this);
}
});
})(jQuery);
|
gpl-2.0
|
BigBoss424/boyer
|
boyer/wp-content/themes/cannyon/cfg/widgets/mythemes.post_meta.class.php
|
4205
|
<?php
if( !class_exists( 'mythemes_post_meta' ) ){
class mythemes_post_meta extends WP_Widget
{
function __construct()
{
parent::__construct( 'mythemes_post_meta', __( 'Post Meta' , 'cannyon' ) . ' [' . mythemes_core::author( 'name' ) . ']', array(
'classname' => 'widget_post_meta',
'description' => __( 'Use only for single template' , 'cannyon' )
));
}
function widget( $args, $instance )
{
global $post;
/* PRINT THE WIDGET */
extract( $args , EXTR_SKIP );
$instance = wp_parse_args( (array) $instance, array(
'title' => ''
));
$title = $instance[ 'title' ];
if( !is_single() ){
return;
}
echo $before_widget;
if( !empty( $title ) ) {
echo $before_title;
echo apply_filters( 'widget_title', esc_attr( $title ), $instance, $this -> id_base );
echo $after_title;
}
$y = esc_attr( get_post_time( 'Y', false, $post -> ID ) );
$m = esc_attr( get_post_time( 'm', false, $post -> ID ) );
$d = esc_attr( get_post_time( 'd', false, $post -> ID ) );
$name = get_the_author_meta( 'display_name' , $post -> post_author );
$dtime = get_post_time( 'Y-m-d', false, $post -> ID );
$ptime = get_post_time( esc_attr( get_option( 'date_format' ) ), false , $post -> ID, true );
echo '<div class="large-icons">';
echo '<ul>';
edit_post_link( '<i class="icon-pencil"></i>' . __( 'Edit' , 'cannyon' ) , '<li>', '</li>' );
echo '<li><a href="' . esc_url( get_day_link( $y , $m , $d ) ) . '">';
echo '<time datetime="' . esc_attr( $dtime ) . '"><i class="icon-calendar"></i>' . esc_html( $ptime ) . '</time></a></li>';
echo '<li><a href="' . esc_url( get_author_posts_url( $post -> post_author ) ) . '" title="' . sprintf( __( 'Writed by %s' , 'cannyon' ), esc_attr( $name ) ) . '"><i class="icon-user-5"></i>' . esc_html( $name ) . '</a></li>';
if( $post -> comment_status == 'open' ) {
$nr = get_comments_number( $post -> ID );
echo '<li>';
echo '<a href="' . esc_url( get_comments_link( $post -> ID ) ) . '">';
echo '<i class="icon-comment"></i>';
echo sprintf( _nx( '%s Comment' , '%s Comments' , absint( $nr ) , 'Number of comment(s) from widget "myThemes: Meta Details"' , 'cannyon' ), number_format_i18n( absint( $nr ) ) );
echo '</a></li>';
}
if( function_exists( 'stats_get_csv' ) ) {
$args = array(
'days' => -1,
'post_id' => $post -> ID,
);
$result = stats_get_csv( 'postviews' , $args );
$views = $result[ 0 ][ 'views' ];
echo '<li><i class="icon-eye-2"></i> ' . sprintf( _n( '%s view' , '%s views' , absint( $views ) , 'cannyon' ) , number_format_i18n( absint( $views ) ) ) . '</li>';
}
echo '</ul>';
echo '</div>';
echo $after_widget;
}
function update( $new_instance, $old_instance )
{
/* UPATE THE WIDGET OPTIONS */
$instance = $old_instance;
$instance[ 'title' ] = esc_attr( strip_tags( $new_instance[ 'title' ] ) );
return $instance;
}
function form( $instance )
{
/* PRINT WIDGET FORM */
$instance = wp_parse_args( (array) $instance, array(
'title' => ''
));
$title = $instance[ 'title' ];
echo '<p>';
echo '<label for="' . $this -> get_field_id( 'title' ) . '">' . __( 'Title' , 'cannyon' );
echo '<input type="text" class="widefat" id="' . $this -> get_field_id( 'title' ) . '" name="' . $this -> get_field_name( 'title' ) . '" value="' . esc_attr( $title ) . '" />';
echo '</label>';
echo '</p>';
}
}
register_widget( 'mythemes_post_meta' );
} /* END IF CLASS EXISTS */
?>
|
gpl-2.0
|
imadkaf/lsdoEZ4
|
extension/ezodf/modules/ezodf/authenticate.php
|
3443
|
<?php
//
// ## BEGIN COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
// SOFTWARE NAME: eZ Publish Community Project
// SOFTWARE RELEASE: 4.2011
// COPYRIGHT NOTICE: Copyright (C) 1999-2011 eZ Systems AS
// SOFTWARE LICENSE: GNU General Public License v2.0
// NOTICE: >
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2.0 of the GNU General
// Public License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of version 2.0 of the GNU General
// Public License along with this program; if not, write to the Free
// Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
// ## END COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
//
include_once ('lib/ezutils/classes/ezfunctionhandler.php');
include_once ('lib/ezutils/classes/ezsys.php');
include_once( 'kernel/common/template.php' );
include_once( 'kernel/classes/datatypes/ezuser/ezuser.php' );
include_once( "lib/ezutils/classes/ezhttptool.php" );
$tpl = templateInit();
$http = eZHTTPTool::instance();
if ( $http->hasPostVariable( 'Username' ) );
$username = $http->postVariable( 'Username' );
if ( $http->hasPostVariable( 'Password' ) );
$password = $http->postVariable( 'Password' );
if ( $http->hasPostVariable( 'NodeID' ) );
$parentNodeID = $http->postVariable( 'NodeID' );
// User authentication
$user = eZUser::loginUser( $username, $password );
if ( $user == false )
{
print( 'problem:Authentication failed' );
eZExecution::cleanExit();
}
else
{
// Print the list of ID nodes..
//Structure : name, type, ID
$nodes = eZFunctionHandler::execute( 'content','list', array( 'parent_node_id' => $parentNodeID ) );
$array = array();
foreach( $nodes as $node )
{
$tpl->setVariable( 'node', $node );
$nodeID = $node->attribute( 'node_id' );
$name = $node->attribute( 'name' );
$className = $node->attribute( 'class_name' );
$object =& $node->object();
$contentClass = $object->contentClass();
$isContainer = $contentClass->attribute( 'is_container' );
preg_match( '/\/+[a-z0-9\-\._]+\/?[a-z0-9_\.\-\?\+\/~=&#;,]*[a-z0-9\/]{1}/si', $tpl->fetch( 'design:ezodf/icon.tpl' ), $matches );
$iconPath = 'http://'. eZSys::hostname(). ':' . eZSys::serverPort() . $matches[0];
$array[] = array( $nodeID, $name, $className, $isContainer, $iconPath );
}
//Test if not empty
if ( empty( $array ) )
{
print( 'problem:No Items' );
eZExecution::cleanExit();
}
//Convert the array into a string and display it
$display = '';
foreach( $array as $line )
{
foreach( $line as $element )
{
$display .= $element . ';';
}
$display .= chr( 13 );
}
print( $display );
// Don't display eZ Publish page structure
eZExecution::cleanExit();
}
?>
|
gpl-2.0
|
mekolat/ManaPlus
|
src/gui/windows/okdialog.cpp
|
3078
|
/*
* The ManaPlus Client
* Copyright (C) 2004-2009 The Mana World Development Team
* Copyright (C) 2009-2010 The Mana Developers
* Copyright (C) 2011-2018 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/windows/okdialog.h"
#include "soundmanager.h"
#include "const/sound.h"
#include "gui/widgets/button.h"
#include "gui/widgets/textbox.h"
#include "gui/fonts/font.h"
#include "debug.h"
OkDialog::OkDialog(const std::string &restrict title,
const std::string &restrict msg,
const std::string &restrict button,
const DialogTypeT soundEvent,
const Modal modal,
const ShowCenter showCenter,
Window *const parent,
const int minWidth) :
Window(title, modal, parent, "ok.xml"),
ActionListener(),
mTextBox(new TextBox(this))
{
mTextBox->setEditable(false);
mTextBox->setOpaque(Opaque_false);
mTextBox->setTextWrapped(msg, minWidth);
// TRANSLATORS: ok dialog button
Button *const okButton = new Button(this,
button,
"ok",
BUTTON_SKIN,
this);
int width = getFont()->getWidth(title);
if (width < mTextBox->getMinWidth())
width = mTextBox->getMinWidth();
if (width < okButton->getWidth())
width = okButton->getWidth();
if (mTextBox->getWidth() > width)
width = mTextBox->getWidth();
if (okButton->getWidth() > width)
width = okButton->getWidth();
setContentSize(width, mTextBox->getHeight() + okButton->getHeight()
+ getOption("buttonPadding", 8));
mTextBox->setPosition((width - mTextBox->getWidth()) / 2, 0);
okButton->setPosition((width - okButton->getWidth()) / 2,
mTextBox->getHeight() + getOption("buttonPadding", 8));
// +++ virtual method call
add(mTextBox);
add(okButton);
if (showCenter == ShowCenter_true)
center();
else
centerHorisontally();
// +++ virtual method call
setVisible(Visible_true);
okButton->requestFocus();
if (soundEvent == DialogType::OK)
soundManager.playGuiSound(SOUND_INFO);
else if (soundEvent == DialogType::ERROR)
soundManager.playGuiSound(SOUND_ERROR);
}
void OkDialog::action(const ActionEvent &event)
{
setActionEventId(event.getId());
distributeActionEvent();
scheduleDelete();
}
|
gpl-2.0
|
ForAEdesWeb/AEW1
|
administrator/components/com_acymailing/classes/listsub.php
|
4796
|
<?php
/**
* @package AcyMailing for Joomla!
* @version 4.9.4
* @author acyba.com
* @copyright (C) 2009-2015 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><?php
class listsubClass extends acymailingClass{
var $type = 'list';
var $gid;
var $checkAccess = true;
var $sendNotif = true;
var $sendConf = true;
var $forceConf = false;
var $survey = '';
var $campaigndelay = 0;
var $skipedfollowups = 0;
function updateSubscription($subid,$lists){
$result = true;
$time = time();
$listHelper = acymailing_get('helper.list');
$listHelper->sendNotif = $this->sendNotif;
$listHelper->sendConf = $this->sendConf;
$listHelper->forceConf = $this->forceConf;
$listHelper->survey = $this->survey;
$listHelper->campaigndelay = $this->campaigndelay;
foreach($lists as $status => $listids){
if(empty($listids)) continue;
JArrayHelper::toInteger($listids);
if($status == '-1') $column = 'unsubdate';
else $column = 'subdate';
$query = 'UPDATE '.acymailing_table('listsub').' SET `status` = '.intval($status).','.$column.'='.$time.' WHERE subid = '.intval($subid).' AND listid IN ('.implode(',',$listids).')';
$this->database->setQuery($query);
$result = $this->database->query() && $result;
if($status == 1){
$listHelper->subscribe($subid,$listids);
}elseif($status == -1){
$listHelper->unsubscribe($subid,$listids);
}
}
return $result;
}
function removeSubscription($subid,$listids){
JArrayHelper::toInteger($listids);
$query = 'DELETE FROM '.acymailing_table('listsub').' WHERE subid = '.intval($subid).' AND listid IN ('.implode(',',$listids).')';
$this->database->setQuery($query);
$this->database->query();
$listHelper = acymailing_get('helper.list');
$listHelper->sendNotif = $this->sendNotif;
$listHelper->sendConf = $this->sendConf;
$listHelper->forceConf = $this->forceConf;
$listHelper->unsubscribe($subid,$listids);
return true;
}
function addSubscription($subid,$lists){
$app = JFactory::getApplication();
$my = JFactory::getUser();
$result = true;
$time = time();
$subid = intval($subid);
$listHelper = acymailing_get('helper.list');
$listHelper->campaigndelay = $this->campaigndelay;
$listHelper->skipedfollowups = $this->skipedfollowups;
$listHelper->sendNotif = $this->sendNotif;
$listHelper->sendConf = $this->sendConf;
$listHelper->forceConf = $this->forceConf;
foreach($lists as $status => $listids){
$status = intval($status);
JArrayHelper::toInteger($listids);
$this->database->setQuery('SELECT `listid`,`access_sub` FROM '.acymailing_table('list').' WHERE `listid` IN ('.implode(',',$listids).') AND `type` = \'list\'');
$allResults = $this->database->loadObjectList('listid');
$listids = array_keys($allResults);
if($status == '-1') $column = 'unsubdate';
else $column = 'subdate';
$values = array();
foreach($listids as $listid){
if(empty($listid)) continue;
if($status > 0 && acymailing_level(3)){
if((!$app->isAdmin() || !empty($this->gid)) && $this->checkAccess && $allResults[$listid]->access_sub != 'all'){
if(!acymailing_isAllowed($allResults[$listid]->access_sub,$this->gid)) continue;
}
}
$values[] = intval($listid).','.$subid.','.$status.','.$time;
}
if(empty($values)) continue;
$query = 'INSERT IGNORE INTO '.acymailing_table('listsub').' (listid,subid,`status`,'.$column.') VALUES ('.implode('),(',$values).')';
$this->database->setQuery($query);
$result = $this->database->query() && $result;
if($status == 1){
$listHelper->subscribe($subid,$listids);
}
}
return $result;
}
function getSubscription($subid){
$query = 'SELECT * FROM '.acymailing_table('listsub').' as a LEFT JOIN '.acymailing_table('list').' as b on a.listid = b.listid WHERE a.subid = '.intval($subid).' AND b.type = \''.$this->type.'\' ORDER BY b.ordering ASC';
$this->database->setQuery($query);
return $this->database->loadObjectList('listid');
}
function getSubscriptionString($subid){
$usersubscription = $this->getSubscription($subid);
$subscriptionString = '';
if(!empty($usersubscription)){
$subscriptionString = '<ul>';
foreach($usersubscription as $onesub){
$status = ($onesub->status == 1) ? JText::_('SUBSCRIBED') : (($onesub->status == -1) ? JText::_('UNSUBSCRIBED') : JText::_('PENDING_SUBSCRIPTION'));
$subscriptionString .= '<li>['.$onesub->listid.'] '.$onesub->name.' : '.$status.'</li>';
}
$subscriptionString .= '</ul>';
}
return $subscriptionString;
}
}
|
gpl-2.0
|
trisyoungs/duq
|
src/gui/uchroma/gui/editviewlayout_funcs.cpp
|
9079
|
/*
*** Edit ViewLayout Dialog
*** src/gui/uchroma/gui/editviewlayout_funcs.cpp
Copyright T. Youngs 2013-2018
This file is part of uChroma.
uChroma is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
uChroma 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 uChroma. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gui/uchroma/gui/editviewlayout.h"
#include "gui/uchroma/uchromabase.h"
#include "gui/uchroma/gui/selecttarget.h"
#include "templates/variantpointer.h"
/*
* Window Functions
*/
// Constructor
EditViewLayoutDialog::EditViewLayoutDialog(UChromaBase& uChromaBase, QWidget* parent) : QDialog(parent), uChromaBase_(uChromaBase), layout_(uChromaBase)
{
ui.setupUi(this);
currentPane_ = NULL;
refreshing_ = true;
// Set items in PaneViewTypeCombo
for (int n=0; n<ViewPane::nViewTypes; ++n) ui.PaneViewTypeCombo->addItem(ViewPane::viewType((ViewPane::ViewType) n));
// Set items in PaneRoleCombo
for (int n=0; n<ViewPane::nPaneRoles; ++n) ui.PaneRoleCombo->addItem(ViewPane::paneRole((ViewPane::PaneRole) n));
// Set items in axis scaling combos
for (int n=0; n<Axes::nAutoScaleMethods; ++n)
{
ui.PaneAutoScaleXCombo->addItem(Axes::autoScaleMethod((Axes::AutoScaleMethod) n));
ui.PaneAutoScaleYCombo->addItem(Axes::autoScaleMethod((Axes::AutoScaleMethod) n));
ui.PaneAutoScaleZCombo->addItem(Axes::autoScaleMethod((Axes::AutoScaleMethod) n));
}
refreshing_ = false;
}
// Destructor
EditViewLayoutDialog::~EditViewLayoutDialog()
{
}
// Window close event
void EditViewLayoutDialog::closeEvent(QCloseEvent* event)
{
reject();
}
void EditViewLayoutDialog::reject()
{
setResult(QDialog::Rejected);
hide();
}
void EditViewLayoutDialog::on_OKButton_clicked(bool checked)
{
accept();
}
void EditViewLayoutDialog::on_CancelButton_clicked(bool checked)
{
reject();
}
// Call dialog to edit specified ViewLayout
bool EditViewLayoutDialog::call(ViewLayout target)
{
// Copy supplied data
layout_ = target;
// Tell the Organiser widget which layout it's editing
ui.Organiser->setViewLayout(&layout_);
updateControls();
// Call the dialog
if (exec()) return true;
else return false;
}
// Return ViewLayout stored in dialog
ViewLayout& EditViewLayoutDialog::viewLayout()
{
return layout_;
}
/*
* Convenience Functions
*/
/*
* Slots - Main Layout
*/
void EditViewLayoutDialog::on_GridNColumnsSpin_valueChanged(int value)
{
if (refreshing_) return;
layout_.setGrid(value, ui.GridNRowsSpin->value());
updateControls();
}
void EditViewLayoutDialog::on_GridNRowsSpin_valueChanged(int value)
{
if (refreshing_) return;
layout_.setGrid(ui.GridNColumnsSpin->value(), value);
updateControls();
}
void EditViewLayoutDialog::on_PaneAddButton_clicked(bool checked)
{
if (refreshing_) return;
currentPane_ = layout_.addPane("New Pane");
updateControls();
}
void EditViewLayoutDialog::on_PaneRemoveButton_clicked(bool checked)
{
if (refreshing_) return;
layout_.removePane(currentPane_);
updateControls();
}
void EditViewLayoutDialog::on_PaneBringToFrontButton_clicked(bool checked)
{
layout_.bringPaneToFront(currentPane_);
}
void EditViewLayoutDialog::on_PaneSendToBackButton_clicked(bool checked)
{
layout_.sendPaneToBack(currentPane_);
}
void EditViewLayoutDialog::on_Organiser_currentPaneChanged(int gridX, int gridY)
{
if (refreshing_) return;
// Get pane at the specified grid coordinates
currentPane_ = layout_.paneAtGrid(gridX, gridY);
updateControls();
}
/*
* Slots - Current Pane
*/
void EditViewLayoutDialog::on_PaneNameEdit_textChanged(QString text)
{
if (refreshing_) return;
if (currentPane_) currentPane_->setName(qPrintable(text));
ui.Organiser->update();
}
void EditViewLayoutDialog::on_PaneRoleCombo_currentIndexChanged(int index)
{
if (refreshing_) return;
if (currentPane_) currentPane_->setRole((ViewPane::PaneRole) index);
updateControls();
}
void EditViewLayoutDialog::on_PaneNextButton_clicked(bool checked)
{
if (refreshing_) return;
if (currentPane_) currentPane_ = currentPane_->next;
if (!currentPane_) currentPane_ = layout_.panes();
updateControls();
}
void EditViewLayoutDialog::on_PanePreviousButton_clicked(bool checked)
{
if (refreshing_) return;
if (currentPane_) currentPane_ = currentPane_->prev;
if (!currentPane_) currentPane_ = layout_.lastPane();
updateControls();
}
/*
* Slots - Pane View Style
*/
void EditViewLayoutDialog::on_PaneViewTypeCombo_currentIndexChanged(int index)
{
if (refreshing_) return;
if (currentPane_) currentPane_->setViewType( (ViewPane::ViewType) index );
}
/*
* Slots - Axis Scaling
*/
void EditViewLayoutDialog::on_PaneAutoScaleXCombo_currentIndexChanged(int index)
{
if (refreshing_) return;
if (currentPane_) currentPane_->axes().setAutoScale(0, (Axes::AutoScaleMethod) index);
}
void EditViewLayoutDialog::on_PaneAutoScaleYCombo_currentIndexChanged(int index)
{
if (refreshing_) return;
if (currentPane_) currentPane_->axes().setAutoScale(1, (Axes::AutoScaleMethod) index);
}
void EditViewLayoutDialog::on_PaneAutoScaleZCombo_currentIndexChanged(int index)
{
if (refreshing_) return;
if (currentPane_) currentPane_->axes().setAutoScale(2, (Axes::AutoScaleMethod) index);
}
/*
* Slots - Pane Targets
*/
void EditViewLayoutDialog::on_PaneTargetsList_currentRowChanged(int index)
{
ui.PaneRemoveTargetButton->setEnabled(index != -1);
}
void EditViewLayoutDialog::on_PaneAddTargetButton_clicked(bool checked)
{
SelectTargetDialog targetDialog(this);
targetDialog.populateLists(currentPane_, layout_.panes(), uChromaBase_.collections());
if (targetDialog.exec())
{
// Get lists of panes and collections, and add them to the targets list
RefList<ViewPane,bool> panes = targetDialog.selectedPanes();
for (RefListItem<ViewPane,bool>* ri = panes.first(); ri != NULL; ri = ri->next) currentPane_->addPaneTarget(ri->item);
RefList<Collection,bool> collections = targetDialog.selectedCollections();
for (RefListItem<Collection,bool>* rj = collections.first(); rj != NULL; rj = rj->next) currentPane_->addCollectionTarget(rj->item);
}
updateControls();
}
void EditViewLayoutDialog::on_PaneRemoveTargetButton_clicked(bool checked)
{
// Get list of current items
QList<QListWidgetItem*> items = ui.PaneTargetsList->selectedItems();
for (int n=0; n<items.count(); ++n)
{
if (items[n]->text().startsWith("(C)")) currentPane_->removeCollectionTarget(VariantPointer<Collection>(items[n]->data(Qt::UserRole)));
else if (items[n]->text().startsWith("(P)")) currentPane_->removePaneTarget(VariantPointer<ViewPane>(items[n]->data(Qt::UserRole)));
}
updateControls();
}
/*
* Slots - Pane Role Options
*/
/*
* Update
*/
// Update controls
void EditViewLayoutDialog::updateControls()
{
refreshing_ = true;
// Make a check on the currentPane_ to see if it still exists in the layout...
if (currentPane_ && (!layout_.containsPane(currentPane_))) currentPane_ = layout_.panes();
ui.Organiser->update();
ui.GridNColumnsSpin->setValue(layout_.nColumns());
ui.GridNRowsSpin->setValue(layout_.nRows());
// Check that a valid pane is selected in the organiser
ui.PaneNameEdit->setEnabled(currentPane_);
ui.PaneRoleCombo->setEnabled(currentPane_);
ui.PaneRemoveButton->setEnabled(currentPane_);
if (currentPane_)
{
ui.PaneNameEdit->setText(currentPane_->name());
ui.PaneRoleCombo->setCurrentIndex(currentPane_->role());
ui.PaneViewTypeCombo->setCurrentIndex(currentPane_->viewType());
// Axis Scaling
ui.PaneAutoScaleXCombo->setCurrentIndex(currentPane_->axes().autoScale(0));
ui.PaneAutoScaleYCombo->setCurrentIndex(currentPane_->axes().autoScale(1));
ui.PaneAutoScaleZCombo->setCurrentIndex(currentPane_->axes().autoScale(2));
// Update targets list
ui.PaneTargetsList->clear();
QListWidgetItem* item;
for (RefListItem<ViewPane,bool>* ri = currentPane_->paneTargets(); ri != NULL; ri = ri->next)
{
item = new QListWidgetItem(ui.PaneTargetsList);
item->setText(QString("(P) ") + ri->item->name());
item->setData(Qt::UserRole, VariantPointer<ViewPane>(ri->item));
}
for (TargetData* target = currentPane_->collectionTargets(); target != NULL; target = target->next)
{
if (!Collection::objectValid(target->collection(), "collection in EditViewLayoutDialog::updateControls")) continue;
item = new QListWidgetItem(ui.PaneTargetsList);
item->setText(QString("(C) ") + target->collection()->name());
item->setData(Qt::UserRole, VariantPointer<Collection>(target->collection()));
}
// Set the correct stack page for the selected role
ui.PaneRoleStack->setCurrentIndex(currentPane_->role());
// -- Set stack page controls
// ui.
}
refreshing_ = false;
}
|
gpl-2.0
|
ProfessorX/Config
|
.PyCharm30/system/python_stubs/-1247972723/PyKDE4/khtml.py
|
30475
|
# encoding: utf-8
# module PyKDE4.khtml
# from /usr/lib/python2.7/dist-packages/PyKDE4/khtml.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kparts as __PyKDE4_kparts
import PyQt4.QtGui as __PyQt4_QtGui
# no functions
# classes
class DOM(): # skipped bases: <type 'sip.wrapper'>
# no doc
def strcasecmp(self, *args, **kwargs): # real signature unknown
pass
def strcmp(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
AbstractView = None # (!) real value is ''
Attr = None # (!) real value is ''
CDATASection = None # (!) real value is ''
CharacterData = None # (!) real value is ''
Comment = None # (!) real value is ''
Counter = None # (!) real value is ''
CSSCharsetRule = None # (!) real value is ''
CSSException = None # (!) real value is ''
CSSFontFaceRule = None # (!) real value is ''
CSSImportRule = None # (!) real value is ''
CSSMediaRule = None # (!) real value is ''
CSSNamespaceRule = None # (!) real value is ''
CSSPageRule = None # (!) real value is ''
CSSPrimitiveValue = None # (!) real value is ''
CSSRule = None # (!) real value is ''
CSSRuleList = None # (!) real value is ''
CSSStyleDeclaration = None # (!) real value is ''
CSSStyleRule = None # (!) real value is ''
CSSStyleSheet = None # (!) real value is ''
CSSUnknownRule = None # (!) real value is ''
CSSValue = None # (!) real value is ''
CSSValueList = None # (!) real value is ''
CustomNodeFilter = None # (!) real value is ''
Document = None # (!) real value is ''
DocumentFragment = None # (!) real value is ''
DocumentStyle = None # (!) real value is ''
DocumentType = None # (!) real value is ''
DOMException = None # (!) real value is ''
DOMImplementation = None # (!) real value is ''
DomShared = None # (!) real value is ''
DOMString = None # (!) real value is ''
Element = None # (!) real value is ''
Entity = None # (!) real value is ''
EntityReference = None # (!) real value is ''
Event = None # (!) real value is ''
EventException = None # (!) real value is ''
EventListener = None # (!) real value is ''
HTMLAnchorElement = None # (!) real value is ''
HTMLAppletElement = None # (!) real value is ''
HTMLAreaElement = None # (!) real value is ''
HTMLBaseElement = None # (!) real value is ''
HTMLBaseFontElement = None # (!) real value is ''
HTMLBlockquoteElement = None # (!) real value is ''
HTMLBodyElement = None # (!) real value is ''
HTMLBRElement = None # (!) real value is ''
HTMLButtonElement = None # (!) real value is ''
HTMLCollection = None # (!) real value is ''
HTMLDirectoryElement = None # (!) real value is ''
HTMLDivElement = None # (!) real value is ''
HTMLDListElement = None # (!) real value is ''
HTMLDocument = None # (!) real value is ''
HTMLElement = None # (!) real value is ''
HTMLFieldSetElement = None # (!) real value is ''
HTMLFontElement = None # (!) real value is ''
HTMLFormElement = None # (!) real value is ''
HTMLFrameElement = None # (!) real value is ''
HTMLFrameSetElement = None # (!) real value is ''
HTMLHeadElement = None # (!) real value is ''
HTMLHeadingElement = None # (!) real value is ''
HTMLHRElement = None # (!) real value is ''
HTMLHtmlElement = None # (!) real value is ''
HTMLIFrameElement = None # (!) real value is ''
HTMLImageElement = None # (!) real value is ''
HTMLInputElement = None # (!) real value is ''
HTMLIsIndexElement = None # (!) real value is ''
HTMLLabelElement = None # (!) real value is ''
HTMLLayerElement = None # (!) real value is ''
HTMLLegendElement = None # (!) real value is ''
HTMLLIElement = None # (!) real value is ''
HTMLLinkElement = None # (!) real value is ''
HTMLMapElement = None # (!) real value is ''
HTMLMenuElement = None # (!) real value is ''
HTMLMetaElement = None # (!) real value is ''
HTMLModElement = None # (!) real value is ''
HTMLObjectElement = None # (!) real value is ''
HTMLOListElement = None # (!) real value is ''
HTMLOptGroupElement = None # (!) real value is ''
HTMLOptionElement = None # (!) real value is ''
HTMLParagraphElement = None # (!) real value is ''
HTMLParamElement = None # (!) real value is ''
HTMLPreElement = None # (!) real value is ''
HTMLQuoteElement = None # (!) real value is ''
HTMLScriptElement = None # (!) real value is ''
HTMLSelectElement = None # (!) real value is ''
HTMLStyleElement = None # (!) real value is ''
HTMLTableCaptionElement = None # (!) real value is ''
HTMLTableCellElement = None # (!) real value is ''
HTMLTableColElement = None # (!) real value is ''
HTMLTableElement = None # (!) real value is ''
HTMLTableRowElement = None # (!) real value is ''
HTMLTableSectionElement = None # (!) real value is ''
HTMLTextAreaElement = None # (!) real value is ''
HTMLTitleElement = None # (!) real value is ''
HTMLUListElement = None # (!) real value is ''
KeyboardEvent = None # (!) real value is ''
LinkStyle = None # (!) real value is ''
MediaList = None # (!) real value is ''
MouseEvent = None # (!) real value is ''
MutationEvent = None # (!) real value is ''
NamedNodeMap = None # (!) real value is ''
Node = None # (!) real value is ''
NodeFilter = None # (!) real value is ''
NodeIterator = None # (!) real value is ''
NodeList = None # (!) real value is ''
Notation = None # (!) real value is ''
ProcessingInstruction = None # (!) real value is ''
Range = None # (!) real value is ''
RangeException = None # (!) real value is ''
Rect = None # (!) real value is ''
RGBColor = None # (!) real value is ''
StyleSheet = None # (!) real value is ''
StyleSheetList = None # (!) real value is ''
Text = None # (!) real value is ''
TextEvent = None # (!) real value is ''
TreeWalker = None # (!) real value is ''
UIEvent = None # (!) real value is ''
class KHTMLPart(__PyKDE4_kparts.ReadOnlyPart):
# no doc
def activeNode(self, *args, **kwargs): # real signature unknown
pass
def autoloadImages(self, *args, **kwargs): # real signature unknown
pass
def backgroundURL(self, *args, **kwargs): # real signature unknown
pass
def baseURL(self, *args, **kwargs): # real signature unknown
pass
def begin(self, *args, **kwargs): # real signature unknown
pass
def browserExtension(self, *args, **kwargs): # real signature unknown
pass
def browserHostExtension(self, *args, **kwargs): # real signature unknown
pass
def caretDisplayPolicyNonFocused(self, *args, **kwargs): # real signature unknown
pass
def caretPositionChanged(self, *args, **kwargs): # real signature unknown
pass
def closeUrl(self, *args, **kwargs): # real signature unknown
pass
def completeURL(self, *args, **kwargs): # real signature unknown
pass
def configurationChanged(self, *args, **kwargs): # real signature unknown
pass
def createPart(self, *args, **kwargs): # real signature unknown
pass
def currentFrame(self, *args, **kwargs): # real signature unknown
pass
def customEvent(self, *args, **kwargs): # real signature unknown
pass
def dndEnabled(self, *args, **kwargs): # real signature unknown
pass
def dnsPrefetch(self, *args, **kwargs): # real signature unknown
pass
def docCreated(self, *args, **kwargs): # real signature unknown
pass
def doCloseStream(self, *args, **kwargs): # real signature unknown
pass
def document(self, *args, **kwargs): # real signature unknown
pass
def documentSource(self, *args, **kwargs): # real signature unknown
pass
def doOpenStream(self, *args, **kwargs): # real signature unknown
pass
def doWriteStream(self, *args, **kwargs): # real signature unknown
pass
def encoding(self, *args, **kwargs): # real signature unknown
pass
def end(self, *args, **kwargs): # real signature unknown
pass
def executeScript(self, *args, **kwargs): # real signature unknown
pass
def findFrame(self, *args, **kwargs): # real signature unknown
pass
def findFramePart(self, *args, **kwargs): # real signature unknown
pass
def findText(self, *args, **kwargs): # real signature unknown
pass
def findTextBegin(self, *args, **kwargs): # real signature unknown
pass
def findTextNext(self, *args, **kwargs): # real signature unknown
pass
def fontScaleFactor(self, *args, **kwargs): # real signature unknown
pass
def forcePermitLocalImages(self, *args, **kwargs): # real signature unknown
pass
def formNotification(self, *args, **kwargs): # real signature unknown
pass
def formSubmitNotification(self, *args, **kwargs): # real signature unknown
pass
def frameExists(self, *args, **kwargs): # real signature unknown
pass
def frameNames(self, *args, **kwargs): # real signature unknown
pass
def frames(self, *args, **kwargs): # real signature unknown
pass
def gotoAnchor(self, *args, **kwargs): # real signature unknown
pass
def guiActivateEvent(self, *args, **kwargs): # real signature unknown
pass
def hasSelection(self, *args, **kwargs): # real signature unknown
pass
def hide(self, *args, **kwargs): # real signature unknown
pass
def htmlDocument(self, *args, **kwargs): # real signature unknown
pass
def htmlError(self, *args, **kwargs): # real signature unknown
pass
def inProgress(self, *args, **kwargs): # real signature unknown
pass
def isCaretMode(self, *args, **kwargs): # real signature unknown
pass
def isEditable(self, *args, **kwargs): # real signature unknown
pass
def isModified(self, *args, **kwargs): # real signature unknown
pass
def isPointInsideSelection(self, *args, **kwargs): # real signature unknown
pass
def javaEnabled(self, *args, **kwargs): # real signature unknown
pass
def jScriptEnabled(self, *args, **kwargs): # real signature unknown
pass
def jsDefaultStatusBarText(self, *args, **kwargs): # real signature unknown
pass
def jsStatusBarText(self, *args, **kwargs): # real signature unknown
pass
def lastModified(self, *args, **kwargs): # real signature unknown
pass
def mayPrefetchHostname(self, *args, **kwargs): # real signature unknown
pass
def metaRefreshEnabled(self, *args, **kwargs): # real signature unknown
pass
def nextAnchor(self, *args, **kwargs): # real signature unknown
pass
def nodeActivated(self, *args, **kwargs): # real signature unknown
pass
def nodeUnderMouse(self, *args, **kwargs): # real signature unknown
pass
def nonSharedNodeUnderMouse(self, *args, **kwargs): # real signature unknown
pass
def onlyLocalReferences(self, *args, **kwargs): # real signature unknown
pass
def onURL(self, *args, **kwargs): # real signature unknown
pass
def openFile(self, *args, **kwargs): # real signature unknown
pass
def openUrl(self, *args, **kwargs): # real signature unknown
pass
def pageReferrer(self, *args, **kwargs): # real signature unknown
pass
def paint(self, *args, **kwargs): # real signature unknown
pass
def parentPart(self, *args, **kwargs): # real signature unknown
pass
def partManager(self, *args, **kwargs): # real signature unknown
pass
def pluginPageQuestionAsked(self, *args, **kwargs): # real signature unknown
pass
def pluginsEnabled(self, *args, **kwargs): # real signature unknown
pass
def popupMenu(self, *args, **kwargs): # real signature unknown
pass
def preloadScript(self, *args, **kwargs): # real signature unknown
pass
def preloadStyleSheet(self, *args, **kwargs): # real signature unknown
pass
def prevAnchor(self, *args, **kwargs): # real signature unknown
pass
def referrer(self, *args, **kwargs): # real signature unknown
pass
def restored(self, *args, **kwargs): # real signature unknown
pass
def restoreState(self, *args, **kwargs): # real signature unknown
pass
def saveState(self, *args, **kwargs): # real signature unknown
pass
def scheduleRedirection(self, *args, **kwargs): # real signature unknown
pass
def selectAll(self, *args, **kwargs): # real signature unknown
pass
def selectedText(self, *args, **kwargs): # real signature unknown
pass
def selectedTextAsHTML(self, *args, **kwargs): # real signature unknown
pass
def selection(self, *args, **kwargs): # real signature unknown
pass
def selectionChanged(self, *args, **kwargs): # real signature unknown
pass
def setActiveNode(self, *args, **kwargs): # real signature unknown
pass
def setAlwaysHonourDoctype(self, *args, **kwargs): # real signature unknown
pass
def setAutoloadImages(self, *args, **kwargs): # real signature unknown
pass
def setCaretDisplayPolicyNonFocused(self, *args, **kwargs): # real signature unknown
pass
def setCaretMode(self, *args, **kwargs): # real signature unknown
pass
def setCaretPosition(self, *args, **kwargs): # real signature unknown
pass
def setCaretVisible(self, *args, **kwargs): # real signature unknown
pass
def setDNDEnabled(self, *args, **kwargs): # real signature unknown
pass
def setDNSPrefetch(self, *args, **kwargs): # real signature unknown
pass
def setEditable(self, *args, **kwargs): # real signature unknown
pass
def setEncoding(self, *args, **kwargs): # real signature unknown
pass
def setFixedFont(self, *args, **kwargs): # real signature unknown
pass
def setFontScaleFactor(self, *args, **kwargs): # real signature unknown
pass
def setForcePermitLocalImages(self, *args, **kwargs): # real signature unknown
pass
def setFormNotification(self, *args, **kwargs): # real signature unknown
pass
def setJavaEnabled(self, *args, **kwargs): # real signature unknown
pass
def setJScriptEnabled(self, *args, **kwargs): # real signature unknown
pass
def setJSDefaultStatusBarText(self, *args, **kwargs): # real signature unknown
pass
def setJSStatusBarText(self, *args, **kwargs): # real signature unknown
pass
def setMetaRefreshEnabled(self, *args, **kwargs): # real signature unknown
pass
def setOnlyLocalReferences(self, *args, **kwargs): # real signature unknown
pass
def setPluginPageQuestionAsked(self, *args, **kwargs): # real signature unknown
pass
def setPluginsEnabled(self, *args, **kwargs): # real signature unknown
pass
def setSelection(self, *args, **kwargs): # real signature unknown
pass
def setStandardFont(self, *args, **kwargs): # real signature unknown
pass
def setStatusBarText(self, *args, **kwargs): # real signature unknown
pass
def setStatusMessagesEnabled(self, *args, **kwargs): # real signature unknown
pass
def setSuppressedPopupIndicator(self, *args, **kwargs): # real signature unknown
pass
def settings(self, *args, **kwargs): # real signature unknown
pass
def setURLCursor(self, *args, **kwargs): # real signature unknown
pass
def setUserStyleSheet(self, *args, **kwargs): # real signature unknown
pass
def setZoomFactor(self, *args, **kwargs): # real signature unknown
pass
def show(self, *args, **kwargs): # real signature unknown
pass
def showError(self, *args, **kwargs): # real signature unknown
pass
def slotFinished(self, *args, **kwargs): # real signature unknown
pass
def startingJob(self, *args, **kwargs): # real signature unknown
pass
def statusMessagesEnabled(self, *args, **kwargs): # real signature unknown
pass
def stopAnimations(self, *args, **kwargs): # real signature unknown
pass
def submitFormProxy(self, *args, **kwargs): # real signature unknown
pass
def timerEvent(self, *args, **kwargs): # real signature unknown
pass
def toplevelURL(self, *args, **kwargs): # real signature unknown
pass
def updateZoomFactor(self, *args, **kwargs): # real signature unknown
pass
def urlCursor(self, *args, **kwargs): # real signature unknown
pass
def urlSelected(self, *args, **kwargs): # real signature unknown
pass
def view(self, *args, **kwargs): # real signature unknown
pass
def write(self, *args, **kwargs): # real signature unknown
pass
def zoomFactor(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
Before = 1
BrowserViewGUI = 1
CaretBlink = 2
CaretDisplayPolicy = None # (!) real value is ''
CaretInvisible = 1
CaretVisible = 0
DefaultGUI = 0
DNSPrefetch = None # (!) real value is ''
DNSPrefetchDisabled = 0
DNSPrefetchEnabled = 1
DNSPrefetchOnlyWWWAndSLD = 2
Encrypted = 1
FindLinksOnly = 65536
FindNoPopups = 131072
FindOptions = None # (!) real value is ''
FormNotification = None # (!) real value is ''
GUIProfile = None # (!) real value is ''
Mixed = 2
NoNotification = 0
NotCrypted = 0
Only = 2
PageSecurity = None # (!) real value is ''
Unused = 255
class KHTMLSettings(): # skipped bases: <type 'sip.wrapper'>
# no doc
def accessKeysEnabled(self, *args, **kwargs): # real signature unknown
pass
def addAdFilter(self, *args, **kwargs): # real signature unknown
pass
def adFilteredBy(self, *args, **kwargs): # real signature unknown
pass
def adviceToStr(self, *args, **kwargs): # real signature unknown
pass
def allowTabulation(self, *args, **kwargs): # real signature unknown
pass
def autoLoadImages(self, *args, **kwargs): # real signature unknown
pass
def autoSpellCheck(self, *args, **kwargs): # real signature unknown
pass
def availableFamilies(self, *args, **kwargs): # real signature unknown
pass
def baseColor(self, *args, **kwargs): # real signature unknown
pass
def changeCursor(self, *args, **kwargs): # real signature unknown
pass
def cursiveFontName(self, *args, **kwargs): # real signature unknown
pass
def dnsPrefetch(self, *args, **kwargs): # real signature unknown
pass
def encoding(self, *args, **kwargs): # real signature unknown
pass
def fallbackAccessKeysAssignments(self, *args, **kwargs): # real signature unknown
pass
def fantasyFontName(self, *args, **kwargs): # real signature unknown
pass
def fixedFontName(self, *args, **kwargs): # real signature unknown
pass
def followSystemColors(self, *args, **kwargs): # real signature unknown
pass
def hoverLink(self, *args, **kwargs): # real signature unknown
pass
def init(self, *args, **kwargs): # real signature unknown
pass
def isAdFiltered(self, *args, **kwargs): # real signature unknown
pass
def isAdFilterEnabled(self, *args, **kwargs): # real signature unknown
pass
def isAutoDelayedActionsEnabled(self, *args, **kwargs): # real signature unknown
pass
def isBackRightClickEnabled(self, *args, **kwargs): # real signature unknown
pass
def isFormCompletionEnabled(self, *args, **kwargs): # real signature unknown
pass
def isHideAdsEnabled(self, *args, **kwargs): # real signature unknown
pass
def isJavaEnabled(self, *args, **kwargs): # real signature unknown
pass
def isJavaScriptDebugEnabled(self, *args, **kwargs): # real signature unknown
pass
def isJavaScriptEnabled(self, *args, **kwargs): # real signature unknown
pass
def isJavaScriptErrorReportingEnabled(self, *args, **kwargs): # real signature unknown
pass
def isOpenMiddleClickEnabled(self, *args, **kwargs): # real signature unknown
pass
def isPluginsEnabled(self, *args, **kwargs): # real signature unknown
pass
def jsErrorsEnabled(self, *args, **kwargs): # real signature unknown
pass
def jsPopupBlockerPassivePopup(self, *args, **kwargs): # real signature unknown
pass
def linkColor(self, *args, **kwargs): # real signature unknown
pass
def maxFormCompletionItems(self, *args, **kwargs): # real signature unknown
pass
def mediumFontSize(self, *args, **kwargs): # real signature unknown
pass
def minFontSize(self, *args, **kwargs): # real signature unknown
pass
def sansSerifFontName(self, *args, **kwargs): # real signature unknown
pass
def serifFontName(self, *args, **kwargs): # real signature unknown
pass
def setFixedFontName(self, *args, **kwargs): # real signature unknown
pass
def setJSErrorsEnabled(self, *args, **kwargs): # real signature unknown
pass
def setJSPopupBlockerPassivePopup(self, *args, **kwargs): # real signature unknown
pass
def setStdFontName(self, *args, **kwargs): # real signature unknown
pass
def settingsToCSS(self, *args, **kwargs): # real signature unknown
pass
def showAnimations(self, *args, **kwargs): # real signature unknown
pass
def smoothScrolling(self, *args, **kwargs): # real signature unknown
pass
def stdFontName(self, *args, **kwargs): # real signature unknown
pass
def strToAdvice(self, *args, **kwargs): # real signature unknown
pass
def textColor(self, *args, **kwargs): # real signature unknown
pass
def underlineLink(self, *args, **kwargs): # real signature unknown
pass
def unfinishedImageFrame(self, *args, **kwargs): # real signature unknown
pass
def userStyleSheet(self, *args, **kwargs): # real signature unknown
pass
def vLinkColor(self, *args, **kwargs): # real signature unknown
pass
def windowFocusPolicy(self, *args, **kwargs): # real signature unknown
pass
def windowMovePolicy(self, *args, **kwargs): # real signature unknown
pass
def windowOpenPolicy(self, *args, **kwargs): # real signature unknown
pass
def windowResizePolicy(self, *args, **kwargs): # real signature unknown
pass
def windowStatusPolicy(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
KAnimationAdvice = None # (!) real value is ''
KAnimationDisabled = 0
KAnimationEnabled = 2
KAnimationLoopOnce = 1
KDNSPrefetch = None # (!) real value is ''
KDNSPrefetchDisabled = 0
KDNSPrefetchEnabled = 2
KDNSPrefetchOnlyWWWAndSLD = 1
KJavaScriptAccept = 1
KJavaScriptAdvice = None # (!) real value is ''
KJavaScriptDunno = 0
KJavaScriptReject = 2
KJSWindowFocusAllow = 0
KJSWindowFocusIgnore = 1
KJSWindowFocusPolicy = None # (!) real value is ''
KJSWindowMoveAllow = 0
KJSWindowMoveIgnore = 1
KJSWindowMovePolicy = None # (!) real value is ''
KJSWindowOpenAllow = 0
KJSWindowOpenAsk = 1
KJSWindowOpenDeny = 2
KJSWindowOpenPolicy = None # (!) real value is ''
KJSWindowOpenSmart = 3
KJSWindowResizeAllow = 0
KJSWindowResizeIgnore = 1
KJSWindowResizePolicy = None # (!) real value is ''
KJSWindowStatusAllow = 0
KJSWindowStatusIgnore = 1
KJSWindowStatusPolicy = None # (!) real value is ''
KSmoothScrollingDisabled = 0
KSmoothScrollingEnabled = 2
KSmoothScrollingMode = None # (!) real value is ''
KSmoothScrollingWhenEfficient = 1
class KHTMLView(__PyQt4_QtGui.QScrollArea):
# no doc
def addChild(self, *args, **kwargs): # real signature unknown
pass
def clear(self, *args, **kwargs): # real signature unknown
pass
def cleared(self, *args, **kwargs): # real signature unknown
pass
def closeEvent(self, *args, **kwargs): # real signature unknown
pass
def contentsHeight(self, *args, **kwargs): # real signature unknown
pass
def contentsToViewport(self, *args, **kwargs): # real signature unknown
pass
def contentsWidth(self, *args, **kwargs): # real signature unknown
pass
def contentsX(self, *args, **kwargs): # real signature unknown
pass
def contentsY(self, *args, **kwargs): # real signature unknown
pass
def displayAccessKeys(self, *args, **kwargs): # real signature unknown
pass
def doAutoScroll(self, *args, **kwargs): # real signature unknown
pass
def dragEnterEvent(self, *args, **kwargs): # real signature unknown
pass
def dropEvent(self, *args, **kwargs): # real signature unknown
pass
def event(self, *args, **kwargs): # real signature unknown
pass
def eventFilter(self, *args, **kwargs): # real signature unknown
pass
def findAheadActive(self, *args, **kwargs): # real signature unknown
pass
def finishedLayout(self, *args, **kwargs): # real signature unknown
pass
def focusInEvent(self, *args, **kwargs): # real signature unknown
pass
def focusNextPrevChild(self, *args, **kwargs): # real signature unknown
pass
def focusOutEvent(self, *args, **kwargs): # real signature unknown
pass
def frameWidth(self, *args, **kwargs): # real signature unknown
pass
def hideAccessKeys(self, *args, **kwargs): # real signature unknown
pass
def hideEvent(self, *args, **kwargs): # real signature unknown
pass
def keyPressEvent(self, *args, **kwargs): # real signature unknown
pass
def keyReleaseEvent(self, *args, **kwargs): # real signature unknown
pass
def layout(self, *args, **kwargs): # real signature unknown
pass
def marginHeight(self, *args, **kwargs): # real signature unknown
pass
def marginWidth(self, *args, **kwargs): # real signature unknown
pass
def mouseDoubleClickEvent(self, *args, **kwargs): # real signature unknown
pass
def mouseMoveEvent(self, *args, **kwargs): # real signature unknown
pass
def mousePressEvent(self, *args, **kwargs): # real signature unknown
pass
def mouseReleaseEvent(self, *args, **kwargs): # real signature unknown
pass
def paintEvent(self, *args, **kwargs): # real signature unknown
pass
def part(self, *args, **kwargs): # real signature unknown
pass
def print_(self, *args, **kwargs): # real signature unknown
pass
def repaintAccessKeys(self, *args, **kwargs): # real signature unknown
pass
def repaintContents(self, *args, **kwargs): # real signature unknown
pass
def resizeContents(self, *args, **kwargs): # real signature unknown
pass
def resizeEvent(self, *args, **kwargs): # real signature unknown
pass
def scrollBy(self, *args, **kwargs): # real signature unknown
pass
def scrollContentsBy(self, *args, **kwargs): # real signature unknown
pass
def setContentsPos(self, *args, **kwargs): # real signature unknown
pass
def setHorizontalScrollBarPolicy(self, *args, **kwargs): # real signature unknown
pass
def setMarginHeight(self, *args, **kwargs): # real signature unknown
pass
def setMarginWidth(self, *args, **kwargs): # real signature unknown
pass
def setSmoothScrollingMode(self, *args, **kwargs): # real signature unknown
pass
def setSmoothScrollingModeDefault(self, *args, **kwargs): # real signature unknown
pass
def setVerticalScrollBarPolicy(self, *args, **kwargs): # real signature unknown
pass
def setZoomLevel(self, *args, **kwargs): # real signature unknown
pass
def showEvent(self, *args, **kwargs): # real signature unknown
pass
def slotPaletteChanged(self, *args, **kwargs): # real signature unknown
pass
def smoothScrollingMode(self, *args, **kwargs): # real signature unknown
pass
def timerEvent(self, *args, **kwargs): # real signature unknown
pass
def updateContents(self, *args, **kwargs): # real signature unknown
pass
def viewportEvent(self, *args, **kwargs): # real signature unknown
pass
def viewportToContents(self, *args, **kwargs): # real signature unknown
pass
def visibleHeight(self, *args, **kwargs): # real signature unknown
pass
def visibleWidth(self, *args, **kwargs): # real signature unknown
pass
def wheelEvent(self, *args, **kwargs): # real signature unknown
pass
def widgetEvent(self, *args, **kwargs): # real signature unknown
pass
def zoomLevel(self, *args, **kwargs): # real signature unknown
pass
def zoomView(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
SmoothScrollingMode = None # (!) real value is ''
SSMDisabled = 0
SSMEnabled = 2
SSMWhenEfficient = 1
|
gpl-2.0
|
instantsoft/icms2
|
system/controllers/images/backend/forms/form_preset.php
|
6265
|
<?php
class formImagesPreset extends cmsForm {
public function init($do) {
$fields = [
'basic' => [
'type' => 'fieldset',
'title' => LANG_CP_BASIC,
'childs' => [
new fieldString('name', [
'title' => LANG_SYSTEM_NAME,
'rules' => [
['required'],
['sysname'],
['max_length', 32],
$do == 'add' ? ['unique', 'images_presets', 'name'] : false
]
]),
new fieldString('title', [
'title' => LANG_IMAGES_PRESET,
'rules' => [
['required'],
['max_length', 128]
]
]),
]
],
'size' => [
'type' => 'fieldset',
'title' => LANG_OPTIONS,
'childs' => [
new fieldNumber('width', [
'title' => LANG_IMAGES_PRESET_SIZE_W,
'hint' => LANG_IMAGES_PRESET_SIZE_W_HINT,
'units' => 'px'
]),
new fieldNumber('height', [
'title' => LANG_IMAGES_PRESET_SIZE_H,
'hint' => LANG_IMAGES_PRESET_SIZE_H_HINT,
'units' => 'px'
]),
new fieldCheckbox('allow_enlarge', [
'title' => LANG_IMAGES_PRESET_ALLOW_ENLARGE
]),
new fieldCheckbox('is_square', [
'title' => LANG_IMAGES_PRESET_SQUARE
]),
new fieldList('crop_position', [
'title' => LANG_IMAGES_PRESET_CROP_POSITION,
'default' => cmsImages::CROPCENTER,
'items' => [
cmsImages::CROPTOP => LANG_CP_FIELD_LABEL_TOP,
cmsImages::CROPCENTER => LANG_IMAGES_PRESET_CCENTER,
cmsImages::CROPTOPCENTER => LANG_IMAGES_PRESET_TOP_CENTER,
cmsImages::CROPBOTTOM => LANG_IMAGES_PRESET_CBOTTOM,
cmsImages::CROPLEFT => LANG_CP_FIELD_LABEL_LEFT,
cmsImages::CROPRIGHT => LANG_IMAGES_PRESET_CRIGHT
],
'visible_depend' => ['is_square' => ['show' => ['1']]]
]),
new fieldCheckbox('gamma_correct', [
'title' => LANG_IMAGES_PRESET_GAMMA_CORRECT
]),
new fieldList('convert_format', [
'title' => LANG_IMAGES_PRESET_OUT_FORMAT,
'default' => '',
'items' => [
'' => LANG_IMAGES_PRESET_OUT_ASIS,
'jpg' => 'JPG',
'png' => 'PNG',
'webp' => 'WEBP'
]
]),
'gif_to_gif' => new fieldCheckbox('gif_to_gif', [
'title' => LANG_IMAGES_PRESET_GIF_TO_GIF,
'default' => 1,
'visible_depend' => ['convert_format' => ['hide' => ['']]]
]),
new fieldNumber('quality', [
'title' => LANG_IMAGES_PRESET_QUALITY,
'units' => '%',
'default' => '87',
'rules' => [
['required'],
['digits'],
['min', 1],
['max', 100]
]
])
]
],
'watermark' => [
'type' => 'fieldset',
'title' => LANG_IMAGES_PRESET_WM,
'childs' => [
new fieldCheckbox('is_watermark', [
'title' => LANG_IMAGES_PRESET_WM_ON
]),
new fieldImage('wm_image', [
'title' => LANG_IMAGES_PRESET_WM_IMG,
'options' => [
'sizes' => ['small', 'original']
],
'visible_depend' => ['is_watermark' => ['show' => ['1']]]
]),
new fieldList('wm_origin', [
'title' => LANG_IMAGES_PRESET_WM_ORIGIN,
'items' => [
'top-left' => LANG_IMAGES_PRESET_WM_ORIGIN_TL,
'top-center' => LANG_IMAGES_PRESET_WM_ORIGIN_T,
'top-right' => LANG_IMAGES_PRESET_WM_ORIGIN_TR,
'left' => LANG_IMAGES_PRESET_WM_ORIGIN_L,
'center' => LANG_IMAGES_PRESET_WM_ORIGIN_C,
'right' => LANG_IMAGES_PRESET_WM_ORIGIN_R,
'bottom-left' => LANG_IMAGES_PRESET_WM_ORIGIN_BL,
'bottom' => LANG_IMAGES_PRESET_WM_ORIGIN_B,
'bottom-right' => LANG_IMAGES_PRESET_WM_ORIGIN_BR
],
'visible_depend' => ['is_watermark' => ['show' => ['1']]]
]),
new fieldNumber('wm_margin', [
'title' => LANG_IMAGES_PRESET_WM_MARGIN,
'units' => 'px',
'rules' => [
['digits']
],
'visible_depend' => ['is_watermark' => ['show' => ['1']]]
])
]
]
];
if (!extension_loaded('imagick')) {
unset($fields['size']['childs']['gif_to_gif']);
}
return $fields;
}
}
|
gpl-2.0
|
PascalSteger/gravimage
|
programs/reducedata/grc_COM.py
|
5116
|
#!/usr/bin/env ipython3
##
# @file
# calculate approximative center of mass, assuming constant
# stellar mass 2D version
# (c) 2015 ETHZ Pascal S.P. Steger, pascal@steger.aero
import numpy as np
import pdb
#from pylab import *
#ion()
import gi_helper as gh
import gi_file as gf
from gi_helper import expDtofloat, floattoint
from gi_centering import com_shrinkcircle_v
def concat_pops(M1, M2, x1, x2, y1, y2, z1, z2, vx1, vx2, vy1, vy2, vz1, vz2, gp):
M0 = np.hstack([M1, M2])
x0 = np.hstack([x1, x2])
y0 = np.hstack([y1, y2])
z0 = np.hstack([z1, z2])
vx0 = np.hstack([vx1, vx2])
vy0 = np.hstack([vy1, vy2])
vz0 = np.hstack([vz1, vz2])
N1 = min(len(x1), gp.ntracer[1-1])
N2 = min(len(x2), gp.ntracer[2-1])
pm1 = np.hstack([np.ones(N1, dtype=bool), np.zeros(N2, dtype=bool)])
pm2 = np.hstack([np.zeros(N1, dtype=bool), np.ones(N2, dtype=bool)])
pm = pm1 + pm2
return M0, x0, y0, z0, vx0, vy0, vz0, pm1, pm2, pm
## \fn concat_pops(M1, M2, x1, x2, y1, y2, z1, z2, vx1, vx2, vy1, vy2, vz1, vz2, gp)
# concatenate all arrays for two populations
# @param M1
# @param M2
# @param x1
# @param x2
# @param y1
# @param y2
# @param z1
# @param z2
# @param vx1
# @param vx2
# @param vy1
# @param vy2
# @param vz1
# @param vz2
# @param gp
def select_pm(M, x, y, z, vx, vy, vz, comp, pm):
return M[pm], x[pm], y[pm], z[pm], vx[pm], vy[pm], vz[pm], comp[pm]
## \fn select_pm(M, x, y, z, vx, vy, vz, comp)
# extract only parts of the arrays given
# @param M
# @param x
# @param y
# @param z
# @param vx
# @param vy
# @param vz
# @param comp
# @param pm
def read_data(filename):
# M0 in Msun, x0, y0, z0 in pc, vx,vy,vz in km/s
# comp0 1,2 component (float in file, but really only int)
M0, x0,y0,z0,vx0,vy0,vz0,comp0 = np.genfromtxt(filename, skiprows = 1, unpack = True,\
usecols=(0, 1, 2, 3, 4, 5, 6, 7),\
dtype="d17",\
converters={0:expDtofloat,\
1:expDtofloat,\
2:expDtofloat,\
3:expDtofloat,\
4:expDtofloat,\
5:expDtofloat,\
6:expDtofloat,\
7:floattoint})
return M0, x0, y0, z0, vx0, vy0, vz0, comp0
## \fn read_data(filename)
# read and convert data
# @param filename string
def run(gp):
import gr_params
gpr = gr_params.grParams(gp)
print('input: ', gpr.fil)
M0,x0,y0,z0,vx0, vy0, vz0, comp0 = read_data(gpr.fil)
# [Msun], 3*[pc], 3*[km/s], [1]
# assign population
if gp.pops==2:
pm1 = (comp0 == 1) # will be overwritten below if gp.metalpop
pm2 = (comp0 == 2) # same same
elif gp.pops==1:
pm1 = (comp0 < 3)
pm2 = (comp0 == -1) # assign none, but of same length as comp0
# cut to subsets
ind1 = gh.draw_random_subset(x1, gp.ntracer[1-1])
M1, x1, y1, z1, vx1, vy1, vz1, comp1 = select_pm(M1, x1, y1, z1, vx1, vy1, vz1, comp1, ind1)
ind2 = gh.draw_random_subset(x2, gp.ntracer[2-1])
M2, x2, y2, z2, vx2, vy2, vz2, comp2 = select_pm(M2, x2, y2, z2, vx2, vy2, vz2, comp2, ind2)
# use vz for no contamination, or vb for with contamination
M0, x0, y0, z0, vx0, vy0, vz0 = concat_pops(M1, M2, x1, x2, y1, y2, z1, z2, vx1, vx2, vy1, vy2, vz1, vz2, gp)
com_x, com_y, com_z, com_vz = com_shrinkcircle_v(x0, y0, z0, vz0, pm0) # [pc]
print('COM [pc]: ', com_x, com_y, com_z) # [pc]
print('VOM [km/s]', com_vz) # [km/s]
# from now on, work with 2D data only; z0 was only used to get
# center in (x,y) better
x0 -= com_x # [pc]
y0 -= com_y # [pc]
vz0 -= com_vz # [km/s]
R0 = np.sqrt(x0**2+y0**2) # [pc]
Rhalf = np.median(R0) # [pc]
Rscale = Rhalf # [pc] from all tracer points
pop = -1
for pmn in [pm, pm1, pm2]:
pop = pop + 1 # population number
pmr = ( R0 < (gp.maxR*Rscale) ) # read max extension for data
#(rprior*Rscale) from
#gi_params
pmn = pmn*pmr # [1]
print("fraction of members = ", 1.0*sum(pmn)/len(pmn))
x, y, z, comp, vz, vb, Mg, PMN = select_pm(x0, y0, z0, comp0, vz0, vb0, Mg0, PM0, pmn)
R = np.sqrt(x*x+y*y) # [pc]
Rscalei = np.median(R)
gf.write_Xscale(gp.files.get_scale_file(pop), Rscalei)
gf.write_data_output(gp.files.get_com_file(pop), x/Rscalei, y/Rscalei, vz, Rscalei)
if gpr.showplots:
gpr.show_part_pos(x, y, pmn, Rscale)
if __name__=='__main__':
gpr.showplots = True
import gi_params
gp = gi_params.Params()
run(gp)
|
gpl-2.0
|
javiersantos/WhatsAppBetaUpdater.Xamarin
|
WhatsAppBetaUpdater/Receiver/AlarmReceiver.cs
|
1941
|
using Android.App;
using Android.Content;
using Android.Support.V4.App;
using Android.Graphics;
using System;
namespace WhatsAppBetaUpdater {
[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver {
public override void OnReceive (Context context, Intent intent) {
if (RetreiveLatestReceiver.IsAvailableVersion(context)) {
intent.PutExtra ("title", string.Format(context.Resources.GetString(Resource.String.notification_title), "WhatsApp " + RetreiveLatestReceiver.GetLatestVersion ()));
intent.PutExtra ("message", string.Format(context.Resources.GetString(Resource.String.notification_description), context.Resources.GetString(Resource.String.app_name)));
var message = intent.GetStringExtra ("message");
var title = intent.GetStringExtra ("title");
var notIntent = new Intent (context, typeof(MainActivity));
var contentIntent = PendingIntent.GetActivity (context, 0, notIntent, PendingIntentFlags.CancelCurrent);
var manager = NotificationManagerCompat.From (context);
var style = new NotificationCompat.BigTextStyle ().BigText (message);
int resourceId = Resource.Drawable.ic_launcher;
var wearableExtender = new NotificationCompat.WearableExtender ().SetBackground (BitmapFactory.DecodeResource (context.Resources, resourceId));
// Generate notification (short text and small icon)
var builder = new NotificationCompat.Builder (context);
builder.SetContentIntent (contentIntent);
builder.SetSmallIcon (Resource.Drawable.ic_launcher);
builder.SetContentTitle (title);
builder.SetContentText (message);
builder.SetStyle (style);
builder.SetWhen (Java.Lang.JavaSystem.CurrentTimeMillis ()); // When the AlarmManager will check changes?
builder.SetAutoCancel (true);
builder.Extend (wearableExtender); // Support Android Wear, yeah!
var notification = builder.Build ();
manager.Notify (0, notification);
}
}
}
}
|
gpl-2.0
|
Moujimouja/centreon
|
www/class/centreonServicecategories.class.php
|
4209
|
<?php
/**
* Copyright 2005-2015 Centreon
* Centreon is developped by : Julien Mathis and Romain Le Merlus under
* GPL Licence 2.0.
*
* 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.
*
* 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>.
*
* Linking this program statically or dynamically with other modules is making a
* combined work based on this program. Thus, the terms and conditions of the GNU
* General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this program give Centreon
* permission to link this program 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 Centreon choice, provided that
* Centreon 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 this program. If you modify this program, you may extend this
* exception to your version of the program, but you are not obliged to do so. If you
* do not wish to do so, delete this exception statement from your version.
*
* For more information : contact@centreon.com
*
*/
/**
*
* Enter description here ...
* @author jmathis
*
*/
class CentreonServicecategories
{
protected $db;
/*
* constructor
*/
public function __construct($pearDB)
{
$this->db = $pearDB;
}
/**
*
* @param integer $field
* @return array
*/
public static function getDefaultValuesParameters($field)
{
$parameters = array();
$parameters['currentObject']['table'] = 'service_categories';
$parameters['currentObject']['id'] = 'sc_id';
$parameters['currentObject']['name'] = 'sc_name';
$parameters['currentObject']['comparator'] = 'sc_id';
switch ($field) {
case 'sc_svcTpl':
$parameters['type'] = 'relation';
$parameters['externalObject']['object'] = 'centreonServicetemplates';
$parameters['relationObject']['table'] = 'service_categories_relation';
$parameters['relationObject']['field'] = 'service_service_id';
$parameters['relationObject']['comparator'] = 'sc_id';
break;
}
return $parameters;
}
/**
*
* @param array $values
* @return array
*/
public function getObjectForSelect2($values = array(), $options = array())
{
global $centreon;
$items = array();
# get list of authorized service categories
if (!$centreon->user->access->admin) {
$scAcl = $centreon->user->access->getServiceCategories();
}
$explodedValues = implode(',', $values);
if (empty($explodedValues)) {
$explodedValues = "''";
}
# get list of selected service categories
$query = "SELECT sc_id, sc_name "
. "FROM service_categories "
. "WHERE sc_id IN (" . $explodedValues . ") "
. "ORDER BY sc_name ";
$resRetrieval = $this->db->query($query);
while ($row = $resRetrieval->fetchRow()) {
# hide unauthorized service categories
$hide = false;
if (!$centreon->user->access->admin && count($scAcl) && !in_array($row['sc_id'], array_keys($scAcl))) {
$hide = true;
}
$items[] = array(
'id' => $row['sc_id'],
'text' => $row['sc_name'],
'hide' => $hide
);
}
return $items;
}
}
|
gpl-2.0
|
rinkun/link
|
wp-content/themes/xeory_base/lib/functions/setting.php
|
8629
|
<?php
// セッティング & 小物系
// WordPress標準の機能はこちらに記入しています。
// ナビ
// register_nav_menu('primary_nav', 'プライベートナビ(最上部に表示)');
register_nav_menu('global_nav', 'グローバルナビ(ヘッダー領域下に表示)');
register_nav_menu('footer_nav', 'フッターナビ(フッター領域に表示)');
/* ナビにclassを付ける */
add_filter( 'nav_menu_css_class', 'my_nav_menu_css_class', 10, 2 );
function my_nav_menu_css_class( $classes, $item ) {
if ( 'page' == $item->object ) {
$page = get_page_by_title( $item->title );
$classes[] = $page->post_name;
} else if ( 'category' == $item->object ) {
$cat = get_category( get_cat_ID ( $item->title ) );
$classes[] = $cat->slug;
}
return $classes;
}
// アイキャッチ
// add_theme_support( 'post-thumbnails', array( 'post', 'page', 'cta', 'lp' ) );
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 304, 214 ); // 通常の投稿サムネイル
add_image_size( 'post-thumbnail-2nd', 282, 260 ); // 個別投稿、個別の固定ページでのサムネイル
add_action( 'admin_init', 'my_admin_init' );
function my_admin_init() {
add_filter( 'gettext', 'my_gettext', 10, 3 );
}
function my_gettext( $translate_text, $text, $domain ) {
$translate_text = str_replace( 'アイキャッチ画像を設定', '画像をアップロードする', $translate_text );
$translate_text = str_replace( 'アイキャッチ画像を削除', 'メイン画像を削除する', $translate_text );
$translate_text = str_replace( 'アイキャッチ画像', 'メイン画像を設定', $translate_text );
return $translate_text;
}
// サイドバー
register_sidebar(array(
'name' => 'サイドバー',
'id' => 'sidebar',
'description' => 'サイドバーに入るウィジェットエリアです。',
'before_widget' => '<div id="%1$s" class="%2$s side-widget"><div class="side-widget-inner">',
'after_widget' => '</div></div>',
'before_title' => '<h4 class="side-title"><span class="side-title-inner">',
'after_title' => '</span></h4>'
));
//ここから
register_sidebar(array(
'name' => '投稿記事下',
'id' => 'under_post_area',
'description' => '',
'before_widget' => '<div>',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>'
));
/* more-linkのハッシュ消し
* ---------------------------------------- */
function remove_more_jump_link($link) {
$offset = strpos($link, '#more-');
if ($offset) {
$end = strpos($link, '"',$offset);
}
if ($end) {
$link = substr_replace($link, '', $offset, $end-$offset);
}
return $link;
}
add_filter('the_content_more_link', 'remove_more_jump_link');
// more-linkにnofollow
add_filter('the_content', 'bzb_nofollow_more_link');
function bzb_nofollow_more_link($content) {
return preg_replace("@class=\"more-link\"@", "class=\"more-link\" rel=\"nofollow\"", $content);
}
//user_setting
function my_user_meta($bzb_user_info)
{
//項目の削除
//unset($bzb_user_info['xxx']);
//項目の追加
$bzb_user_info['facebook'] = 'facebook';
$bzb_user_info['googleplus'] = 'google+';
return $bzb_user_info;
}
add_filter('user_contactmethods', 'my_user_meta', 10, 1);
function add_enctype_attr2user_edit_form_tag() {
echo ' enctype="multipart/form-data"';
}
add_action( 'user_edit_form_tag', 'add_enctype_attr2user_edit_form_tag' );
/* オリジナルアバター
* ---------------------------------------- */
function add_original_avatar_form( $bool ) {
global $profileuser;
if ( preg_match( '/^(profile\.php|user-edit\.php)/', basename( $_SERVER['REQUEST_URI'] ) ) ) {
?>
<script type="text/javascript">
jQuery('document').ready(function(){
jQuery('.media-upload').each(function(){
var rel = jQuery(this).attr("rel");
jQuery(this).click(function(){
window.send_to_editor = function(html) {
html = '<a>' + html + '</a>';
imgurl = jQuery('img', html).attr('src');
jQuery('#'+rel).val(imgurl);
tb_remove();
}
formfield = jQuery('#'+rel).attr('name');
tb_show(null, 'media-upload.php?post_id=0&type=image&TB_iframe=true');
return false;
});
});
});
</script>
<tr>
<th><label for="original_avatar">オリジナルアバター</label></th>
<td><input type="text" id="original_avatar" name="original_avatar" class="regular-text" value="<?php echo get_user_meta($profileuser->ID, 'original_avatar', true);?>" />
<a class="media-upload" href="JavaScript:void(0);" rel="original_avatar">
<input class="cmb_upload_button button" type="button" value="画像をアップロードする" /></a>
</td></tr>
<?php
}
return $bool;
}
add_action( 'show_password_fields', 'add_original_avatar_form' );
function update_original_avatar( $user_id, $old_user_data ) {
if ( isset( $_POST['original_avatar'] ) && $old_user_data->original_avatar != $_POST['original_avatar'] ) {
$original_avatar = sanitize_text_field( $_POST['original_avatar'] );
$original_avatar = wp_filter_kses( $original_avatar );
$original_avatar = _wp_specialchars( $original_avatar );
update_user_meta( $user_id, 'original_avatar', $original_avatar );
}
}
add_action( 'profile_update', 'update_original_avatar', 10, 2 );
add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');
function my_custom_dashboard_widgets() {
global $wp_meta_boxes;
wp_add_dashboard_widget('custom_help_widget', 'Xeoryからのお知らせ', 'dashboard_text');
}
function dashboard_text() {
echo '<iframe src="https://xeory.jp/if-news/" width="100%" height="300"></iframe><img src="https://xeory.jp/images/xeory.gif" alt="">';
}
if(!function_exists('pagination')){
function pagination($pages = '', $range = 4)
{
$showitems = ($range * 2)+1;
global $paged;
if(empty($paged)) $paged = 1;
if($pages == '')
{
global $wp_query;
$pages = $wp_query->max_num_pages;
if(!$pages)
{
$pages = 1;
}
}
if(1 != $pages)
{
echo "<div class=\"pagination\">";
if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'><i class='fa fa-angle-double-left'></i></a>";
if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'><i class='fa fa-angle-left'></i></a>";
for ($i=1; $i <= $pages; $i++)
{
if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
{
echo ($paged == $i)? "<span class=\"current\">".$i."</span>":"<a href='".get_pagenum_link($i)."' class=\"inactive\">".$i."</a>";
}
}
if ($paged < $pages && $showitems < $pages) echo "<a href=\"".get_pagenum_link($paged + 1)."\"><i class='fa fa-angle-right'></i></a>";
if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'><i class='fa fa-angle-double-right'></i></a>";
echo "</div>\n";
}
}
}
// 検索フォーム
function bzb_search_form( $form ) {
$form = '<form role="search" method="get" id="searchform" action="'.home_url( '/' ).'" >
<div>
<input type="text" value="' . get_search_query() . '" name="s" id="s" />
<button type="submit" id="searchsubmit"></button>
</div>
</form>';
return $form;
}
add_filter( 'get_search_form', 'bzb_search_form' );
/* メインクエリ
* ---------------------------------------- */
if(!function_exists('customize_main_query')){
function customize_main_query($query) {
if ( is_admin() || ! $query->is_main_query() )
return;
if ( $query->is_front_page () || $query->is_home() ) {
$query->set(
'meta_query',
array(
array( 'key'=>'show_toppage_flag',
'compare' => 'NOT EXISTS'
),
array( 'key'=>'show_toppage_flag',
'value'=>'none',
'compare'=>'!='
),
'relation'=>'OR'
)
);
$query->set('order','DESC');
}
if ( !is_admin() && $query->is_main_query() && $query->is_search() ) {
$query->set( 'post_type', 'post' );
}
}
}
add_action( 'pre_get_posts', 'customize_main_query' );
|
gpl-2.0
|
TheAirlineProject/TheAirlineProject_Web
|
scripts/importAirports.php
|
2033
|
<?php
$dir = "xml/airports/";
$files = scandir($dir);
while($files[0] == "." || $files[0] == "..") {
array_shift($files);
}
$i = 0;
$con = mysqli_connect("localhost","root","asdf","tap") or die("error connecting");
$xml = simplexml_load_file('xml/airports/super.xml');
foreach($xml->airport as $a) {
$i++;
$name = $a['name'];
$icao = $a['icao'];
$iata = $a['iata'];
$type = $a['type'];
$season = $a['season'];
$town = $a->town['town'];
$country = $a->town['country'];
$gmt = $a->town['GMT'];
$dst = $a->town['DST'];
$lat = $a->coordinates->latitude['value'];
$long = $a->coordinates->longitude['value'];
$size = $a->size['value'];
$pax = $a->size['pax'];
$cargo = $a->size['cargo'];
$cvol = $a->size['cargovolume'];
$terminals = ""; $runways = "";
foreach($a->terminals->terminal as $t) {
$terminals .= $t['name'] . "." . $t['gates'] . "..";
}
foreach($a->runways->runway as $r) {
$runways .= $r['name'] . "." . $r['length'] . "." . $r['surface'] . "..";
}
//echo "$name.$icao.$iata.$type.$season.$town.$country.$gmt.$dst.$lat.$long.$size.$pax.$cargo.$cvol.$terminals.$runways.'<br />'";
$sql1 = "INSERT INTO airports (name, icao, iata, type, season, town, country, gmt, dst, lat, lon, size, pax, cargo, cvolume,terminals,runways) ";
$sql2 = "VALUES(\"$name\",\"$icao\",\"$iata\",\"$type\",\"$season\",\"$town\",\"$country\",\"$gmt\",\"$dst\",\"$lat\",\"$long\",\"$size\",$pax,\"$cargo\",\"$cvol\",\"$terminals\",\"$runways\")";
$sql2 = str_replace('/','fslash',$sql2);
$sql = $sql1 . $sql2;
// $sql = "INSERT INTO airports (name"
// echo $sql;
mysqli_query($con,$sql) or die(' error:' . mysqli_error($con) . "<br />$sql");
//print_r($ret); //isn't printing anything
//echo($i . ":" . $name . $icao . $iata . $type . $season . $town . $country . $gmt . $dst . $lat . $long . $size . $pax . $cargo . $cvol . "terminals:" . $terminals . "runways:" . $runways . "<br />");
}
mysqli_close($con);
?>
|
gpl-2.0
|
3lywa/gcconnex
|
mod/custom_index_widgets/views/default/widgets/latest_generic_index/content.php
|
1480
|
<?php
$object_type = $vars["entity"]->widget_subtype;
if (!isset($object_type))
$object_type = 'ELGG_ENTITIES_ANY_VALUE';
$num_items = $vars['entity']->num_items;
if (!isset($num_items))
$num_items = 10;
$widget_group = $vars["entity"]->widget_group;
if (!isset($widget_group)) $widget_group = ELGG_ENTITIES_ANY_VALUE;
$site_categories = $vars['config']->site->categories;
$widget_categorie = $vars['entity']->widget_categorie;
$widget_context_mode = $vars['entity']->widget_context_mode;
if (!isset($widget_context_mode))
$widget_context_mode = 'search';
elgg_set_context($widget_context_mode);
if ($site_categories == NULL || $widget_categorie == NULL) {
$widget_datas = elgg_list_entities(array(
'type'=>'object',
'subtype'=>$object_type,
'container_guids' => $widget_group,
// 'offset' => 0, //GCChange - set to 0 in order to ignore pagination of activity index widget
'limit'=>$num_items,
'full_view' => false,
'view_type_toggle' => false,
'pagination' => false));
} else {
$widget_datas = elgg_list_entities_from_metadata(array(
'type'=>'object',
'subtype'=>$object_type,
'container_guids' => $widget_group,
// 'offset' => 0, //GCChange - set to 0 in order to ignore pagination of activity index widget
'limit'=>$num_items,
'full_view' => false,
'view_type_toggle' => false,
'pagination' => false,
'metadata_name' => 'universal_categories',
'metadata_value' => $widget_categorie,
));
}
echo $widget_datas;
?>
|
gpl-2.0
|
lupus-dev/lupus
|
core/classes/achievements/achievement.AtLeastKWins.php
|
1339
|
<?php
/**
* Lupus in Tabula
* ...un progetto di Edoardo Morassutto
* Contributors:
* - 2016 Edoardo Morassutto <edoardo.morassutto@gmail.com>
*/
class AtLeastKWins extends Achievement {
public static $enabled = false;
/**
* Numero minimo di partite da vincere per sbloccare l'obiettivo,
* viene overridato dalle classe derivate
* @var int
*/
protected $K = 0;
/**
* Verifica se l'utente può sbloccare l'obiettivo
* @param User $user Utente da controllare
* @return bool True se l'utente può sbloccare l'obiettivo, false altrimenti
*/
public function canObtain($user) {
$sql = "SELECT game.status, player.role
FROM player
JOIN game ON player.id_game = game.id_game
WHERE id_user=? AND game.status >= ? AND game.status < ?";
$res = Database::query($sql, [$user->id_user, GameStatus::Winy, GameStatus::Winy+100]);
if (!$res) return false;
$wins = 0;
foreach ($res as $game) {
$teamCode = $game['status'] - GameStatus::Winy;
$role = firstUpper($game['role']);
$roleTeam = firstUpper($role::$team_name);
if ($teamCode == $roleTeam::$team_code)
$wins++;
}
return $wins >= $this->K;
}
}
|
gpl-2.0
|
doublesword/commuse
|
Source/W201621/MemInjectWithFirstThread/InjectDllByCurThread.cpp
|
5566
|
#include "StdAfx.h"
#include <windows.h>
#include "InjectDllByCurThread.h"
#include <tlhelp32.h>
InjectDllByCurThread::InjectDllByCurThread(void)
{
}
InjectDllByCurThread::~InjectDllByCurThread(void)
{
}
DWORD InjectDllByCurThread::GetFirstThreadInProcessR(DWORD pid)
{
HANDLE hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hSnapshot == INVALID_HANDLE_VALUE)
return 0;
THREADENTRY32 te = { sizeof(te) };
if (!::Thread32First(hSnapshot, &te)) {
::CloseHandle(hSnapshot);
return 0;
}
DWORD tid = 0;
do {
if (te.th32OwnerProcessID == pid) {
tid = te.th32ThreadID;
break;
}
} while (::Thread32Next(hSnapshot, &te));
::CloseHandle(hSnapshot);
return tid;
}
bool InjectDllByCurThread::DoInjection(PCSTR dllPath , DWORD pid, DWORD tid )
{
#ifdef _WIN64
BYTE code[] = {
// sub rsp, 28h
0x48, 0x83, 0xec, 0x28,
// mov [rsp + 18], rax
0x48, 0x89, 0x44, 0x24, 0x18,
// mov [rsp + 10h], rcx
0x48, 0x89, 0x4c, 0x24, 0x10,
// mov rcx, 11111111111111111h
0x48, 0xb9, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
// mov rax, 22222222222222222h
0x48, 0xb8, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
// call rax
0xff, 0xd0,
// mov rcx, [rsp + 10h]
0x48, 0x8b, 0x4c, 0x24, 0x10,
// mov rax, [rsp + 18h]
0x48, 0x8b, 0x44, 0x24, 0x18,
// add rsp, 28h
0x48, 0x83, 0xc4, 0x28,
// mov r11, 333333333333333333h
0x49, 0xbb, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33,
// jmp r11
0x41, 0xff, 0xe3
};
#else
BYTE code[] = {
0x60,
0x68, 0x11, 0x11, 0x11, 0x11,
0xb8, 0x22, 0x22, 0x22, 0x22,
0xff, 0xd0,
0x61,
0x68, 0x33, 0x33, 0x33, 0x33,
0xc3
};
#endif
//-------------------------------------------------------------------------------
TOKEN_PRIVILEGES priv = {0};
HANDLE hToken = NULL;
HANDLE hProcess = NULL;
HANDLE hThread = NULL;
if( OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) )
{
priv.PrivilegeCount = 1;
priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if( LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &priv.Privileges[0].Luid ) )
AdjustTokenPrivileges( hToken, FALSE, &priv, 0, NULL, NULL );
CloseHandle( hToken );
}
hProcess = OpenProcess( PROCESS_VM_OPERATION | PROCESS_VM_WRITE, FALSE, pid );
if( !hProcess )
return false;
if (tid==0)
{
tid = GetFirstThreadInProcessR(pid);
}
if (tid>0)
{
hThread = ::OpenThread(THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT, FALSE, tid);
if (!hThread)
return false;
}else return false;
//-------------------------------------------------------------------------------
const auto page_size = 1 << 12;
bool bRet = false;
do
{
//
// allocate buffer in target process to hold DLL path and injected function code
//
char* buffer = static_cast<char*>(::VirtualAllocEx(hProcess, NULL, page_size,
MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE));
if (!buffer)
break;
printf("Buffer in remote process: %p\n", buffer);
//
// suspend the target thread and get its context
//
if (::SuspendThread(hThread) == -1)
break;
CONTEXT context;
context.ContextFlags = CONTEXT_FULL;
if (!::GetThreadContext(hThread, &context))
break;
FARPROC loadLibraryAddress = ::GetProcAddress(::GetModuleHandle(L"kernel32.dll"), "LoadLibraryA");
#ifdef _WIN64
// set dll path
*reinterpret_cast<PVOID*>(code + 0x10) = static_cast<void*>(buffer + page_size / 2);
// set LoadLibraryA address
*reinterpret_cast<PVOID*>(code + 0x1a) = static_cast<void*>(loadLibraryAddress);
// jump address (back to the original code)
*reinterpret_cast<unsigned long long*>(code + 0x34) = context.Rip;
#else
// set dll path
*reinterpret_cast<PVOID*>(code + 2) = static_cast<void*>(buffer + page_size / 2);
// set LoadLibraryA address
*reinterpret_cast<PVOID*>(code + 7) = static_cast<void*>(loadLibraryAddress);
// jump address (back to the original code)
*reinterpret_cast<unsigned*>(code + 0xf) = context.Eip;
#endif
//
// copy the injected function into the buffer
//
if (!::WriteProcessMemory(hProcess, buffer, code, sizeof(code), nullptr))
break;
//
// copy the DLL name into the buffer
//
if (!::WriteProcessMemory(hProcess, buffer + page_size / 2, dllPath, ::strlen(dllPath) + 1, NULL))
break;
//
// change thread context and let it go!
//
#ifdef _WIN64
context.Rip = reinterpret_cast<unsigned long long>(buffer);
#else
context.Eip = reinterpret_cast<DWORD>(buffer);
#endif
if (!::SetThreadContext(hThread, &context))
break;
::ResumeThread(hThread);
bRet = true;
} while (0);
if(hProcess) CloseHandle(hProcess);
if(hThread) CloseHandle(hThread);
return bRet;
}
|
gpl-2.0
|
LinEvil/PlayerSQL
|
src/main/java/com/mengcraft/playersql/LocalDataMgr.java
|
3911
|
package com.mengcraft.playersql;
import com.google.common.collect.Maps;
import com.mengcraft.playersql.lib.ItemUtil;
import com.mengcraft.simpleorm.EbeanHandler;
import lombok.SneakyThrows;
import lombok.val;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.StreamSupport;
import static java.util.stream.Collectors.toList;
public enum LocalDataMgr {
INSTANCE;
private final Map<UUID, LocalData> pool = Maps.newConcurrentMap();
EbeanHandler db;
ItemUtil itemUtil;
public static void pick(Player p) {
LocalData d = load(p);
List<String> list = (List<String>) JSONValue.parse(d.getInventory());
if (list.isEmpty()) {
return;
}
ItemStack[] all = list.stream().map(l -> conv(l)).toArray(ItemStack[]::new);
val out = p.getInventory().addItem(all).values();
d.setInventory(out.isEmpty() ? "[]" : JSONArray.toJSONString(out.stream().map(item -> conv(item)).collect(toList())));
PluginMain.runAsync(() -> INSTANCE.db.save(d));
PluginMain.getMessenger().send(p, "transfer_back_okay", ChatColor.GREEN + "Items have been added to the inventory");
if (!out.isEmpty()) {
PluginMain.getMessenger().send(p, "transfer_back_overflow", ChatColor.RED + "Some items are not received. Please clean up the inventory and try again.");
}
}
public static void transfer(Player p, boolean newbie) {// this method run async
if (!ready()) {
return;
}
LocalData d = load(p);
if (!(d.getInventory() == null)) {
return;
}
if (newbie) {
d.setInventory("[]");
} else {
List<String> list = StreamSupport.stream(p.getInventory().spliterator(), false)
.filter(item -> !(item == null) && !(item.getType() == Material.AIR))
.map(item -> conv(item))
.collect(toList());
d.setInventory(JSONArray.toJSONString(list));
if (!list.isEmpty()) {
PluginMain.getMessenger().send(p, "transfer_okay", "transfer_okay");
String notice = PluginMain.getPlugin().getConfig().getString("transfer.extra-notify-command", "");
if (!notice.isEmpty()) {
Arrays.stream(notice.split("\n")).forEach(origin -> {
if (origin.isEmpty()) {
return;
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), origin.replace("%player_name%", p.getName()));
});
}
}
p.getInventory().clear();
}
INSTANCE.db.save(d);
}
public static void transfer(Player p) {
transfer(p, false);
}
public static boolean ready() {
return Config.TRANSFER_ORIGIN && !(INSTANCE.db == null);
}
public static LocalData load(Player p) {
return INSTANCE.pool.computeIfAbsent(p.getUniqueId(), id -> {
LocalData d = INSTANCE.db.find(LocalData.class, id);
if (d == null) {
d = INSTANCE.db.bean(LocalData.class);
d.setId(p.getUniqueId());
}
return d;
});
}
@SneakyThrows
private static String conv(ItemStack item) {
return INSTANCE.itemUtil.convert(item);
}
public static void quit(Player p) {
INSTANCE.pool.remove(p.getUniqueId());
}
@SneakyThrows
private static ItemStack conv(String line) {
return INSTANCE.itemUtil.convert(line);
}
}
|
gpl-2.0
|
armstrongli/CaiddApp
|
src/cn/caidd/portal/Portal.java
|
2443
|
package cn.caidd.portal;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import cn.caidd.caiddapp.R;
import cn.caidd.constele.TxnCodeConst;
public class Portal extends Activity {
WebView portalWebView;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainview);
portalWebView = (WebView) findViewById(R.id.mainweb);
WebSettings webSettings = portalWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBlockNetworkImage(false);
portalWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url); // 在当前的webview中跳转到新的url
return true;
}
});
// register javascript interface for calling in web page.
portalWebView.addJavascriptInterface(new ApplyReqResp(), "ApplyReqResp");
portalWebView.addJavascriptInterface(new Object() {
@SuppressWarnings("unused")
public void loadPortal() {
loadUrl(TxnCodeConst.getPageUrl(TxnCodeConst.PORTAL_URL));
}
@SuppressWarnings("unused")
public void loadLogin() {
loadUrl(TxnCodeConst.getPageUrl(TxnCodeConst.LOGIN_URL));
}
@SuppressWarnings("unused")
public void loadProductDetail() {
loadUrl(TxnCodeConst.getPageUrl(TxnCodeConst.DETAIL_URL));
}
@SuppressWarnings("unused")
public void loadOrder() {
loadUrl(TxnCodeConst.getPageUrl(TxnCodeConst.ORDER_URL));
}
@SuppressWarnings("unused")
public void loadOrderDetail() {
loadUrl(TxnCodeConst.getPageUrl(TxnCodeConst.ORDER_DETAIL_URL));
}
@SuppressWarnings("unused")
public void loadCollect() {
loadUrl(TxnCodeConst.getPageUrl(TxnCodeConst.COLLECT_URL));
}
@SuppressWarnings("unused")
public void loadCollectDetail() {
loadUrl(TxnCodeConst.getPageUrl(TxnCodeConst.COLLECT_SHOW_URL));
}
}, "GoTo");
portalWebView.loadUrl("file:///android_asset/test.html");
}
private void loadUrl(final String localfileurl) {
portalWebView.post(new Runnable() {
@Override
public void run() {
portalWebView.loadUrl(localfileurl);
}
});
}
}
|
gpl-2.0
|
oat-sa/tao-core
|
views/js/e2e/resourceSelector/item/item.spec.js
|
3558
|
/**
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; under version 2
* of the License (non-upgradable).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright (c) 2019 (original work) Open Assessment Technologies SA ;
*/
import itemData from './itemData';
import { selectors } from '../resourceTree';
describe('Items', () => {
const newItemName = itemData.name;
/**
* - Set up the server & routes
* - Log in
* - Visit the page
*/
beforeEach(() => {
cy.setupServer();
cy.addTreeRoutes();
cy.login('admin');
cy.loadItemsPage();
});
/**
* Destroy everything we created, leaving the environment clean for next time.
*/
afterEach(() => {
if (Cypress.$(`[title="${newItemName}"]`).length > 0) {
cy.deleteItem(`[title="${newItemName}"]`);
}
});
/**
* Item tests
*/
describe('Item creation, edit and delete', () => {
it('items page loads', function() {
cy.get(selectors.resourceTree);
});
it('can create and rename a new item', function() {
cy.addItem(selectors.itemsRootClass);
cy.renameSelectedItem(newItemName);
cy.get(selectors.resourceTree)
.contains(newItemName)
.should('exist');
});
it('can delete previously created item', function() {
cy.addItem(selectors.itemsRootClass);
cy.renameSelectedItem(newItemName);
cy.get(selectors.actions.deleteItem).click();
cy.get('.modal-body [data-control="ok"]').click();
cy.wait('@deleteItem');
});
it('has correct action buttons when item is selected', function() {
cy.addItem(selectors.itemsRootClass);
cy.renameSelectedItem(newItemName);
cy.get(`[title="${newItemName}"]`)
.closest(selectors.treeNode)
.should('not.have.class', 'closed');
cy.get(selectors.actionsContainer).within(() => {
[
'newClass',
'deleteItem',
'import',
'export',
'moveTo',
'copyTo',
'duplicate',
'newItem'
].forEach((action) => {
cy.get(selectors.actions[action])
.should('exist')
.and('be.visible');
});
});
});
it('has correct action buttons when nothing is selected', function() {
// deselect selected list item
cy.get(selectors.resourceTree)
.find('.selected').first()
.click({ force: true });
cy.get(selectors.actionsContainer).within(() => {
cy.get(selectors.actionBtn)
.should('not.be.visible');
});
});
});
});
|
gpl-2.0
|
elim37/festival
|
wp-content/themes/itheme2/index.php
|
3839
|
<?php get_header(); ?>
<?php
/** Themify Default Variables
* @var object */
global $themify; ?>
<?php if(is_front_page() && !is_paged()){ get_template_part( 'includes/header-slider'); } ?>
<!-- layout-container -->
<div id="layout" class="clearfix">
<?php themify_content_before(); //hook ?>
<!-- content -->
<div id="content" class="clearfix">
<?php themify_content_start(); //hook ?>
<?php
/////////////////////////////////////////////
// Author Page
/////////////////////////////////////////////
?>
<?php if(is_author()) : ?>
<?php
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
$author_url = $curauth->user_url;
?>
<div class="author-bio clearfix">
<p class="author-avatar"><?php echo get_avatar( $curauth->user_email, $size = '48' ); ?></p>
<h2 class="author-name"><?php _e('About','themify'); ?> <?php echo $curauth->first_name; ?> <?php echo $curauth->last_name; ?></h2>
<?php if($author_url != ''): ?><p class="author-url"><a href="<?php echo $author_url; ?>"><?php echo $author_url; ?></a></p><?php endif; //author url ?>
<div class="author-description">
<?php echo $curauth->user_description; ?>
</div>
<!-- /.author-description -->
</div>
<!-- /.author bio -->
<h2 class="author-posts-by"><?php _e('Posts by','themify'); ?> <?php echo $curauth->first_name; ?> <?php echo $curauth->last_name; ?>:</h2>
<?php endif; ?>
<?php
/////////////////////////////////////////////
// Search Title
/////////////////////////////////////////////
?>
<?php if(is_search()): ?>
<h1 class="page-title"><?php _e('Search Results for:','themify'); ?> <em><?php echo get_search_query(); ?></em></h1>
<?php endif; ?>
<?php
/////////////////////////////////////////////
// Category Title
/////////////////////////////////////////////
?>
<?php if(is_category() || is_tag() || is_tax() ): ?>
<h1 class="page-title"><?php single_cat_title(); ?></h1>
<?php echo $themify->get_category_description(); ?>
<?php endif; ?>
<?php
/////////////////////////////////////////////
// Default query categories
/////////////////////////////////////////////
?>
<?php $query_cats = themify_get('setting-default_query_cats'); ?>
<?php if(($query_cats !="") && !is_search()): ?>
<?php query_posts(apply_filters('themify_query_posts_args', $query_string . '&cat='.$query_cats)); ?>
<?php endif; ?>
<?php
/////////////////////////////////////////////
// Loop
/////////////////////////////////////////////
?>
<?php if (have_posts()) : ?>
<!-- loops-wrapper -->
<div class="loops-wrapper">
<?php while (have_posts()) : the_post(); ?>
<?php if(is_search()): ?>
<?php get_template_part( 'includes/loop','search'); ?>
<?php else: ?>
<?php get_template_part( 'includes/loop','index'); ?>
<?php endif; ?>
<?php endwhile; ?>
</div>
<!-- /loops-wrapper -->
<?php get_template_part( 'includes/pagination'); ?>
<?php
/////////////////////////////////////////////
// Error - No Page Found
/////////////////////////////////////////////
?>
<?php else : ?>
<p><?php _e( 'Sorry, nothing found.', 'themify' ); ?></p>
<?php endif; ?>
</div>
<!--/content -->
<?php
/////////////////////////////////////////////
// Sidebar
/////////////////////////////////////////////
if ($themify->layout != "sidebar-none"): get_sidebar(); endif; ?>
<?php themify_content_end(); //hook ?>
</div>
<!-- layout-container -->
<?php themify_content_after() //hook; ?>
<?php get_footer(); ?>
|
gpl-2.0
|
ggovan/wherethis
|
lib/main.js
|
886
|
var self = require("sdk/self");
var contextMenu = require("sdk/context-menu");
var menuItem = contextMenu.Item({
label: "Where This?",
context: contextMenu.SelectionContext(),
contentScript: 'self.on("click", function () {' +
' var text = window.getSelection().toString();' +
' self.postMessage(text);' +
'});',
image: self.data.url("icon-16.png"),
accessKey: "w",
onMessage: function (selectionText) {
//We'll only use terms that begin with [A-z0-9-] and end with [A-z0-9]. strip everything else.
var re = /[^A-z0-9-]*([-A-z0-9].*[A-z0-9])[^A-z0-9]*/g ;
var trimmed = selectionText.replace(re, "$1");
var encoded = encodeURI(trimmed);
var panel = require("sdk/panel").Panel({
width: 600,
height: 400,
contentURL: "https://www.google.co.uk/maps/place/" + encoded
});
panel.show();
}
});
|
gpl-2.0
|
JulieKuehl/julie-jumpstart
|
wp-content/themes/jumpstart/framework/admin/plugins/plugins.php
|
6188
|
<?php
if ( !function_exists( 'themeblvd_plugins' ) ) :
/**
* Run TGM class to tell users just installing
* the current theme which plugins they should
* be using. However, if the user has already
* dismissed the message, we will not even include
* the class.
*
* remove_action( 'after_setup_theme', 'themeblvd_plugins' );
*
* @since 2.2.0
*/
function themeblvd_plugins() {
/* @todo - Will evaluate whether to include this or
not later on. This will save resources, however will
also remove the "Recommended Plugins" menu item once
dismissing the prompt, which could be confusing.
// Check if the user has already dismissed the prompt
if ( get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice', true ) )
return;
*/
// Include TGM_Plugin_Activation class
include_once( TB_FRAMEWORK_DIRECTORY . '/admin/plugins/class-tgm-plugin-activation.php' );
// Hook in TGM Class registration
add_action( 'tgmpa_register', 'themeblvd_tgm_register' );
}
endif;
if ( !function_exists( 'themeblvd_tgm_register' ) ) :
/**
* Register the required/recommnended plugins.
*
* This function is hooked into tgmpa_register, which
* is fired within the TGM_Plugin_Activation class
* constructor.
*
* @since 2.2.0
*/
function themeblvd_tgm_register() {
// Plugins to require/recommend
$plugins = array(
'builder' => array(
'name' => 'Theme Blvd Layout Builder',
'slug' => 'theme-blvd-layout-builder',
'required' => false
),
'sliders' => array(
'name' => 'Theme Blvd Sliders',
'slug' => 'theme-blvd-sliders',
'required' => false
),
'sidebars' => array(
'name' => 'Theme Blvd Widget Areas',
'slug' => 'theme-blvd-widget-areas',
'required' => false
),
'widgets' => array(
'name' => 'Theme Blvd Widget Pack',
'slug' => 'theme-blvd-widget-pack',
'required' => false
),
'shortcodes' => array(
'name' => 'Theme Blvd Shortcodes',
'slug' => 'theme-blvd-shortcodes',
'required' => false
)
);
$plugins = apply_filters( 'themeblvd_plugins', $plugins );
// TGM Class config
$config = array(
'domain' => 'themeblvd', // Text domain - likely want to be the same as your theme.
'default_path' => '', // Default absolute path to pre-packaged plugins
'parent_menu_slug' => 'themes.php', // Default parent menu slug
'parent_url_slug' => 'themes.php', // Default parent URL slug
'menu' => 'install-plugins', // Menu slug
'has_notices' => true, // Show admin notices or not
'is_automatic' => false, // Automatically activate plugins after installation or not
'message' => '', // Message to output right before the plugins table
'strings' => array(
'page_title' => __( 'Install Recommended Plugins', 'themeblvd' ),
'menu_title' => __( 'Theme Plugins', 'themeblvd' ),
'installing' => __( 'Installing Plugin: %s', 'themeblvd' ), // %1$s = plugin name
'oops' => __( 'Something went wrong with the plugin API.', 'themeblvd' ),
'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( 'Activate installed plugin', 'Activate installed plugins' ),
'return' => __( 'Return to Required Plugins Installer', 'themeblvd' ),
'plugin_activated' => __( 'Plugin activated successfully.', 'themeblvd' ),
'complete' => __( 'All plugins installed and activated successfully. %s', 'themeblvd' ), // %1$s = dashboard link
'nag_type' => 'updated' // Determines admin notice type - can only be 'updated' or 'error'
)
);
$config = apply_filters( 'themeblvd_tgm_config', $config );
// Run it.
tgmpa( $plugins, $config );
}
endif;
|
gpl-2.0
|
efess/AltConsole
|
src/AltConsole/WpfControlInput.cs
|
3257
|
using AltConsole.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace AltConsole
{
public class WpfControlInput : IInputProvider
{
public event EventHandler<InputKeyEventArgs> Input;
//public event EventHandler<InputEventArgs> Input;
public WpfControlInput(UIElement wpfControl)
{
wpfControl.KeyDown += wpfControl_KeyDown;
wpfControl.TextInput += wpfControl_TextInput;
}
private char? ToUnicode(Key keyDown, bool shift, bool alt)
{
char? newChar = null;
int virtualKey = KeyInterop.VirtualKeyFromKey(keyDown);
uint scanCode = Win32Input.MapVirtualKey((uint)virtualKey, Win32Input.MapType.MAPVK_VK_TO_VSC);
var buf = new StringBuilder(256);
var keyboardState = new byte[256];
//Win32Input.GetKeyboardState(keyboardState);
if (shift)
keyboardState[16] = 0xff;//(int)Keys.ShiftKey
if (alt)
{
keyboardState[17] = 0xff;//(int)Keys.ControlKey
keyboardState[18] = 0xff;//(int)Keys.Menu]
}
var result = Win32Input.ToUnicode((uint)virtualKey, scanCode, keyboardState, buf, 256, 0);
switch (result)
{
case -1:
break;
case 0:
break;
case 1:
newChar = buf[0];
break;
default:
newChar = buf[0];
break;
}
return newChar;
}
void wpfControl_TextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
//var lol = e.Text.ToCharArray();
//if(lol.Length > 1)
//{
// System.Diagnostics.Debug.Fail("Okay, TextInput contains more than one char...");
//}
//else if(lol.Length == 0)
//{
// System.Diagnostics.Debug.Fail("TextInput doesn't contain anything!");
//}
//var chr = lol[0];
//OnCharacterInput(chr);
}
void wpfControl_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
var keyEvent = new KeyDown
{
Character = ToUnicode(e.Key, Keyboard.Modifiers.HasFlag(ModifierKeys.Shift), Keyboard.Modifiers.HasFlag(ModifierKeys.Alt)) ?? '\0',
Key = e.Key,
IsAlt = Keyboard.Modifiers.HasFlag(ModifierKeys.Alt),
IsShift = Keyboard.Modifiers.HasFlag(ModifierKeys.Shift),
IsCtrl = Keyboard.Modifiers.HasFlag(ModifierKeys.Control),
IsWindows = Keyboard.Modifiers.HasFlag(ModifierKeys.Windows)
};
var evnt = Input;
if (evnt != null)
{
evnt(this, new InputKeyEventArgs(keyEvent));
}
}
protected virtual void OnCharacterInput(char inputCharacter)
{
return;
}
}
}
|
gpl-2.0
|
czchen/debian-ibus-libzhuyin
|
src/ZYConfig.cc
|
3716
|
/* vim:set et ts=4 sts=4:
*
* ibus-libzhuyin - New Zhuyin engine based on libzhuyin for IBus
*
* Copyright (c) 2008-2010 Peng Huang <shawn.p.huang@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 "ZYConfig.h"
#include "ZYTypes.h"
#include "ZYBus.h"
namespace ZY {
Config::Config (Bus & bus, const std::string & name)
: Object (ibus_bus_get_config (bus)),
m_section ("engine/" + name)
{
initDefaultValues ();
g_signal_connect (get<IBusConfig> (),
"value-changed",
G_CALLBACK (valueChangedCallback),
this);
}
Config::~Config (void)
{
}
void
Config::initDefaultValues (void)
{
m_page_size = 5;
m_keyboard_layout = CHEWING_DEFAULT;
m_init_chinese = TRUE;
m_init_full_english = FALSE;
m_init_full_punct = TRUE;
m_init_trad_chinese = TRUE;
m_always_input_numbers = FALSE;
m_easy_symbol = TRUE;
m_user_symbol = TRUE;
}
void
Config::readDefaultValues (void)
{
}
inline bool
Config::read (const gchar * name,
bool defval)
{
GVariant *value = NULL;
if ((value = ibus_config_get_value (get<IBusConfig> (), m_section.c_str (), name)) != NULL) {
if (g_variant_classify (value) == G_VARIANT_CLASS_BOOLEAN)
return g_variant_get_boolean (value);
}
// write default value to config
value = g_variant_new ("b", defval);
ibus_config_set_value (get<IBusConfig> (), m_section.c_str (), name, value);
return defval;
}
inline gint
Config::read (const gchar * name,
gint defval)
{
GVariant *value = NULL;
if ((value = ibus_config_get_value (get<IBusConfig> (), m_section.c_str (), name)) != NULL) {
if (g_variant_classify (value) == G_VARIANT_CLASS_INT32)
return g_variant_get_int32 (value);
}
// write default value to config
value = g_variant_new ("i", defval);
ibus_config_set_value (get<IBusConfig> (), m_section.c_str (), name, value);
return defval;
}
inline std::string
Config::read (const gchar * name,
const gchar * defval)
{
GVariant *value = NULL;
if ((value = ibus_config_get_value (get<IBusConfig> (), m_section.c_str (), name)) != NULL) {
if (g_variant_classify (value) == G_VARIANT_CLASS_STRING)
return g_variant_get_string (value, NULL);
}
// write default value to config
value = g_variant_new ("s", defval);
ibus_config_set_value (get<IBusConfig> (), m_section.c_str (), name, value);
return defval;
}
gboolean
Config::valueChanged (const std::string §ion,
const std::string &name,
GVariant *value)
{
return FALSE;
}
void
Config::valueChangedCallback (IBusConfig *config,
const gchar *section,
const gchar *name,
GVariant *value,
Config *self)
{
self->valueChanged (section, name, value);
}
};
|
gpl-2.0
|
ratschlab/ASP
|
examples/undocumented/python_modular/converter_kernellocaltangentspacealignment_modular.py
|
634
|
from tools.load import LoadMatrix
lm=LoadMatrix()
data = lm.load_numbers('../data/fm_train_real.dat')
parameter_list = [[data,10],[data,20]]
def converter_kernellocaltangentspacealignment_modular(data,k):
from shogun.Features import RealFeatures
from shogun.Converter import KernelLocalTangentSpaceAlignment
features = RealFeatures(data)
converter = KernelLocalTangentSpaceAlignment()
converter.set_target_dim(1)
converter.set_k(k)
converter.apply(features)
return features
if __name__=='__main__':
print('KernelLocalTangentSpaceAlignment')
converter_kernellocaltangentspacealignment_modular(*parameter_list[0])
|
gpl-2.0
|
hakonsbm/nest-simulator
|
pynest/examples/gif_population.py
|
5043
|
# -*- coding: utf-8 -*-
#
# gif_population.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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.
#
# NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>.
"""Population of GIF neuron model with oscillatory behavior
-------------------------------------------------------------
This script simulates a population of generalized integrate-and-fire (GIF)
model neurons driven by noise from a group of Poisson generators.
Due to spike-frequency adaptation, the GIF neurons tend to show oscillatory
behavior on the time scale comparable with the time constant of adaptation
elements (stc and sfa).
Population dynamics are visualized by raster plot and as average firing rate.
References
~~~~~~~~~~~
.. [1] Schwalger T, Degert M, Gerstner W (2017). Towards a theory of cortical columns: From spiking
neurons to interacting neural populations of finite size. PLoS Comput Biol.
https://doi.org/10.1371/journal.pcbi.1005507
.. [2] Mensi S, Naud R, Pozzorini C, Avermann M, Petersen CC and
Gerstner W (2012). Parameter extraction and classification of
three cortical neuron types reveals two distinct adaptation
mechanisms. Journal of Neurophysiology. 107(6), pp.1756-1775.
"""
###############################################################################
# Import all necessary modules for simulation and plotting.
import nest
import nest.raster_plot
import matplotlib.pyplot as plt
nest.ResetKernel()
###############################################################################
# Assigning the simulation parameters to variables.
dt = 0.1
simtime = 2000.0
###############################################################################
# Definition of neural parameters for the GIF model. These parameters are
# extracted by fitting the model to experimental data [2]_.
neuron_params = {"C_m": 83.1,
"g_L": 3.7,
"E_L": -67.0,
"Delta_V": 1.4,
"V_T_star": -39.6,
"t_ref": 4.0,
"V_reset": -36.7,
"lambda_0": 1.0,
"q_stc": [56.7, -6.9],
"tau_stc": [57.8, 218.2],
"q_sfa": [11.7, 1.8],
"tau_sfa": [53.8, 640.0],
"tau_syn_ex": 10.0,
}
###############################################################################
# Definition of the parameters for the population of GIF neurons.
N_ex = 100 # size of the population
p_ex = 0.3 # connection probability inside the population
w_ex = 30.0 # synaptic weights inside the population (pA)
###############################################################################
# Definition of the parameters for the Poisson group and its connection with
# GIF neurons population.
N_noise = 50 # size of Poisson group
rate_noise = 10.0 # firing rate of Poisson neurons (Hz)
w_noise = 20.0 # synaptic weights from Poisson to population neurons (pA)
###############################################################################
# Configuration of the simulation kernel with the previously defined time
# resolution.
nest.SetKernelStatus({"resolution": dt})
###############################################################################
# Building a population of GIF neurons, a group of Poisson neurons and a
# spike detector device for capturing spike times of the population.
population = nest.Create("gif_psc_exp", N_ex, params=neuron_params)
noise = nest.Create("poisson_generator", N_noise, params={'rate': rate_noise})
spike_det = nest.Create("spike_detector")
###############################################################################
# Build connections inside the population of GIF neurons population, between
# Poisson group and the population, and also connecting spike detector to
# the population.
nest.Connect(
population, population, {'rule': 'pairwise_bernoulli', 'p': p_ex},
syn_spec={"weight": w_ex}
)
nest.Connect(noise, population, 'all_to_all', syn_spec={"weight": w_noise})
nest.Connect(population, spike_det)
###############################################################################
# Simulation of the network.
nest.Simulate(simtime)
###############################################################################
# Plotting the results of simulation including raster plot and histogram of
# population activity.
nest.raster_plot.from_device(spike_det, hist=True)
plt.title('Population dynamics')
|
gpl-2.0
|
osigaud/ArmModelPython
|
MotorControlModel/Plot/plotFunctions.py
|
31733
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Author: Thomas Beucher
Module: plotFunctions
Description: some plotting functions
'''
import os
import random as rd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import animation
from matplotlib.mlab import griddata
plt.rc("figure", facecolor="white")
from Utils.FileReading import getStateData, getEstimatedStateData, getEstimatedXYHandData, getXYHandData, getXYEstimError, getXYEstimErrorOfSpeed, getXYElbowData, getCommandData, getNoiselessCommandData, getInitPos, getCostData, getTrajTimeData, getTrajTimeData, getLastXData
from Utils.ReadSetupFile import ReadSetupFile
from ArmModel.Arm import Arm, getDotQAndQFromStateVector
from GlobalVariables import BrentTrajectoriesFolder, pathDataFolder
#--------------------------- trajectory animations ---------------------------------------------------------------------------------------------
def trajectoriesAnimation(what, foldername = "None", targetSize = "0.05"):
rs = ReadSetupFile()
if what == "CMAES":
name = rs.CMAESpath + targetSize + "/" + foldername + "/Log/"
elif what == "Brent":
name = BrentTrajectoriesFolder
else:
name = rs.RBFNpath + foldername + "/Log/"
ec = getXYElbowData(name)
hc = getXYHandData(name)
posIni = np.loadtxt(pathDataFolder + rs.experimentFilePosIni)
xEl, yEl, xHa, yHa = [], [], [], []
for key, val in ec.items():
for el in val:
xEl.append(el[0])
yEl.append(el[1])
for elhc in hc[key]:
xHa.append(elhc[0])
yHa.append(elhc[1])
fig = plt.figure()
upperArm, = plt.plot([],[])
foreArm, = plt.plot([],[])
plt.xlim(-0.7, 0.7)
plt.ylim(-0.7,0.7)
plt.plot([-0.7,0.7], [rs.YTarget, rs.YTarget])
plt.scatter([-rs.sizeOfTarget[3]/2, rs.sizeOfTarget[3]/2], [rs.YTarget, rs.YTarget], c ='g', marker='o', s=50)
plt.scatter([el[0] for el in posIni],[el[1] for el in posIni], c='b')
def init():
upperArm.set_data([0], [0])
foreArm.set_data([xEl[0]], [yEl[0]])
return upperArm, foreArm
def animate(i):
xe = (0, xEl[i])
ye = (0, yEl[i])
xh = (xEl[i], xHa[i])
yh = (yEl[i], yHa[i])
upperArm.set_data(xe, ye)
foreArm.set_data(xh, yh)
return upperArm, foreArm
ani = animation.FuncAnimation(fig, animate, init_func=init, frames=len(xEl), blit=True, interval=20, repeat=True)
plt.show(block = True)
#----------------------------------------------------------------------------------------------------------------------------
#Functions related to plotting initial positions
def makeInitPlot(rs,filename):
x0 = []
y0 = []
#posIni = np.loadtxt(pathDataFolder + rs.experimentFilePosIni)
posIni = np.loadtxt(pathDataFolder + filename)
for el in posIni:
x0.append(el[0])
y0.append(el[1])
#print "distance to target: " + str(rs.getDistanceToTarget(el[0],el[1]))
#xy = getInitPos(BrentTrajectoriesFolder)
xy = getInitPos(pathDataFolder+"TrajRepository/")
x, y = [], []
aa, keyy = [], []
for key, el in xy.items():
x.append(el[0])
y.append(el[1])
plt.scatter(x, y, c = "b", marker=u'o', s=10, cmap=cm.get_cmap('RdYlBu'))
plt.scatter(rs.XTarget, rs.YTarget, c = "r", marker=u'*', s = 100)
plt.scatter(x0, y0, c = "r", marker=u'o', s=25)
def plotInitPos(filename):
'''
Plots the initial position of trajectories present in the Brent directory
'''
plt.figure()
rs = ReadSetupFile()
makeInitPlot(rs,filename)
plt.show(block = True)
#----------------------------------------------------------------------------------------------------------------------------
#Functions related to velocity profiles
def makeVelocityData(rs,arm,name,media):
state = getStateData(name)
factor = min(1, 100./len(state.items()))
for k,v in state.items():
index, speed = [], []
if rd.random()<factor:
handxy = arm.mgdEndEffector([v[0][2],v[0][3]])
distance = round(rs.getDistanceToTarget(handxy[0],handxy[1]),2)
for j in range(len(v)):
index.append(j*rs.dt)
speed.append(arm.cartesianSpeed(v[j]))
if distance<=0.15:
media.plot(index, speed, c ='blue')
elif distance<=0.28:
media.plot(index, speed, c ='green')
else:
media.plot(index, speed, c ='red')
def plotVelocityProfile(what, foldername = "None"):
rs = ReadSetupFile()
arm = Arm()
plt.figure(1, figsize=(16,9))
if what == "CMAES":
for i in range(4):
ax = plt.subplot2grid((2,2), (i/2,i%2))
name = rs.CMAESpath + str(rs.sizeOfTarget[i]) + "/" + foldername + "/Log/"
makeVelocityData(rs,arm,name,ax)
ax.set_xlabel("time (s)")
ax.set_ylabel("Instantaneous velocity (m/s)")
ax.set_title(str("Velocity profiles for target " + str(rs.sizeOfTarget[i])))
else:
if what == "Brent":
name = BrentTrajectoriesFolder
else:
name = rs.RBFNpath + foldername + "/Log/"
makeVelocityData(rs,arm,name,plt)
plt.xlabel("time (s)")
plt.ylabel("Instantaneous velocity (m/s)")
plt.title("Velocity profiles for " + what)
plt.savefig("ImageBank/"+what+'_velocity_profiles'+foldername+'.png', bbox_inches='tight')
plt.show(block = True)
# ------------------------- positions, trajectories ---------------------------------
# factor is used to plot no more than 100 trajectories. If there are more, they are drawn randomly
def plotPos(name, media, plotEstim):
states = getXYHandData(name)
factor = min(1, 100./len(states.items()))
for k,v in states.items():
if rd.random()<factor:
posX, posY = [], []
for j in range(len(v)):
posX.append(v[j][0])
posY.append(v[j][1])
media.plot(posX,posY, c ='b')
if plotEstim==True:
estimStates = getEstimatedXYHandData(name)
for k,v in estimStates.items():
if rd.random()<factor:
eX, eY = [], []
for j in range(len(v)):
eX.append(v[j][0])
eY.append(v[j][1])
media.plot(eX,eY, c ='r')
def plotEstimError(rs,name, media):
errors = getXYEstimError(name)
factor = min(1, 100./len(errors.items()))
for k,v in errors.items():
if rd.random()<factor:
index, er = [], []
for j in range(len(v)):
# for j in range(20):
# index.append(j*rs.dt)
index.append(j)
er.append(v[j])
media.plot(index,er, c ='b')
def plotEstimErrorOfSpeed(name, media):
errors = getXYEstimErrorOfSpeed(name)
factor = min(1, 100./len(errors.items()))
for k,v in errors.items():
if rd.random()<factor:
speed, er = [], []
for j in range(len(v)):
speed.append(v[j][0])
er.append(v[j][1])
media.plot(speed,er, c ='b')
def plotTrajsInRepo():
rs = ReadSetupFile()
plt.figure(1, figsize=(16,9))
plotPos(pathDataFolder+"TrajRepository/", plt, False)
plt.xlabel("X (m)")
plt.ylabel("Y (m)")
plt.title("XY Positions")
plt.savefig("ImageBank/TrajRepo.png", bbox_inches='tight')
#plt.savefig("ImageBank/"+what+'_trajectories.png')
plt.show(block = True)
def plotXYPositions(what, foldername = "None", targetSize = "All", plotEstim=False):
rs = ReadSetupFile()
plt.figure(1, figsize=(16,9))
if what == "CMAES" and targetSize == "All":
for i in range(len(rs.sizeOfTarget)):
ax = plt.subplot2grid((2,2), (i/2,i%2))
name = rs.CMAESpath + str(rs.sizeOfTarget[i]) + "/" + foldername + "/Log/"
plotPos(name, ax, plotEstim)
#makeInitPlot(rs)
ax.set_xlabel("X (m)")
ax.set_ylabel("Y (m)")
ax.set_title("XY Positions for target " + str(rs.sizeOfTarget[i]))
else:
if what == "CMAES":
name = rs.CMAESpath + targetSize + "/" + foldername + "/Log/"
elif what == "Brent":
name = BrentTrajectoriesFolder
else:
name = rs.RBFNpath + foldername + "/Log/"
plotPos(name, plt, plotEstim)
#makeInitPlot(rs)
plt.xlabel("X (m)")
plt.ylabel("Y (m)")
plt.title("XY Positions for " + what)
plt.savefig("ImageBank/"+what+'_trajectories'+foldername+'.png', bbox_inches='tight')
plt.show(block = True)
def plotXYEstimError(what, foldername = "None", targetSize = "All"):
rs = ReadSetupFile()
plt.figure(1, figsize=(16,9))
if what == "CMAES" and targetSize == "All":
for i in range(len(rs.sizeOfTarget)):
ax = plt.subplot2grid((2,2), (i/2,i%2))
name = rs.CMAESpath + str(rs.sizeOfTarget[i]) + "/" + foldername + "/Log/"
plotEstimError(rs,name, ax)
#makeInitPlot(rs)
ax.set_xlabel("Time (s)")
ax.set_ylabel("Estimation error (m)")
ax.set_title("Estimation error for target " + str(rs.sizeOfTarget[i]))
else:
if what == "CMAES":
name = rs.CMAESpath + targetSize + "/" + foldername + "/Log/"
elif what == "Brent":
name = BrentTrajectoriesFolder
else:
name = rs.RBFNpath + foldername + "/Log/"
plotEstimError(rs,name, plt)
#makeInitPlot(rs)
plt.xlabel("Time (s)")
plt.ylabel("Estimation error (m)")
plt.title("Estimation error Positions for " + what)
plt.savefig("ImageBank/"+what+'_estimError'+foldername+'.png', bbox_inches='tight')
plt.show(block = True)
def plotXYEstimErrorOfSpeed(what, foldername = "None", targetSize = "All"):
rs = ReadSetupFile()
plt.figure(1, figsize=(16,9))
if what == "CMAES" and targetSize == "All":
for i in range(len(rs.sizeOfTarget)):
ax = plt.subplot2grid((2,2), (i/2,i%2))
name = rs.CMAESpath + str(rs.sizeOfTarget[i]) + "/" + foldername + "/Log/"
plotEstimErrorOfSpeed(name, ax)
#makeInitPlot(rs)
ax.set_xlabel("Velocity (m/s)")
ax.set_ylabel("Estimation error (m)")
ax.set_title("Estimation error function of velocity for target " + str(rs.sizeOfTarget[i]))
else:
if what == "CMAES":
name = rs.CMAESpath + targetSize + "/" + foldername + "/Log/"
elif what == "Brent":
name = BrentTrajectoriesFolder
else:
name = rs.RBFNpath + foldername + "/Log/"
plotEstimErrorOfSpeed(name, plt)
#makeInitPlot(rs)
plt.xlabel("Velocity (m/s)")
plt.ylabel("Estimation error (m)")
plt.title("Estimation error function of velocity for " + what)
plt.savefig("ImageBank/"+what+'_estimError'+foldername+'.png', bbox_inches='tight')
plt.show(block = True)
def plotArticularPositions(what, foldername = "None", targetSize = "0.05"):
rs = ReadSetupFile()
if what == "CMAES":
name = rs.CMAESpath + targetSize + "/" + foldername + "/Log/"
elif what == "Brent":
name = BrentTrajectoriesFolder
else:
name = rs.RBFNpath + foldername + "/Log/"
state = getStateData(name)
plt.figure(1, figsize=(16,9))
for k,v in state.items():
if rd.random()<0.06 or what != "Brent":
Q1, Q2 = [], []
for j in range(len(v)):
Q1.append(v[j][2])
Q2.append(v[j][3])
plt.plot(Q1,Q2, c ='b')
plt.xlabel("Q1 (rad)")
plt.ylabel("Q2 (rad)")
plt.title("Articular positions for " + what)
plt.savefig("ImageBank/"+what+'_articular'+foldername+'.png', bbox_inches='tight')
plt.show(block = True)
#------------------ muscular activations --------------------------------
def plotMuscularActivations(what, foldername = "None", targetSize = "0.05"):
'''
plots the muscular activations from a folder
input: -foldername: the folder where the data lies
-what: get from Brent, rbfn or from cmaes controllers
'''
rs = ReadSetupFile()
if what == "CMAES":
name = rs.CMAESpath + targetSize + "/" + foldername + "/Log/"
elif what == "Brent":
name = BrentTrajectoriesFolder
else:
name = rs.RBFNpath + foldername + "/Log/"
U = getNoiselessCommandData(name)
for key, el1 in U.items():
t = []
u1, u2, u3, u4, u5, u6 = [], [], [], [], [], []
if rd.random()<0.01 or what != "Brent":
for i in range(len(el1)):
t.append(i)
u1.append(el1[i][0])
u2.append(el1[i][1])
u3.append(el1[i][2])
u4.append(el1[i][3])
u5.append(el1[i][4])
u6.append(el1[i][5])
plt.figure()
plt.plot(t, u1, label = "U1")
plt.plot(t, u2, label = "U2")
plt.plot(t, u3, label = "U3")
plt.plot(t, u4, label = "U4")
plt.plot(t, u5, label = "U5")
plt.plot(t, u6, label = "U6")
plt.legend(loc = 0)
plt.xlabel("time")
plt.ylabel("U")
plt.title("Muscular Activations for " + what)
plt.savefig("ImageBank/"+what+"_muscu" + key +foldername + ".png", bbox_inches='tight')
print key
val = raw_input('1 to see data, anything otherwise: ')
val = int(val)
if val == 1:
print el1
#plt.clf()
plt.show(block = True)
#-------------------------- cost maps ----------------------------------------------
def plotCostColorMap(what, foldername = "None", targetSize = "All"):
'''
Cette fonction permet d'afficher le profil de cout des trajectoires
Entrees: -what: choix des donnees a afficher
'''
rs = ReadSetupFile()
fig = plt.figure(1, figsize=(16,9))
if what == "CMAES" and targetSize == "All":
for i in range(len(rs.sizeOfTarget)):
ax = plt.subplot2grid((2,2), (i/2,i%2))
name = rs.CMAESpath + str(rs.sizeOfTarget[i]) + "/" + foldername + "/Cost/"
costs = getCostData(name)
x0 = []
y0 = []
cost = []
for k, v in costs.items():
for j in range(len(v)):
x0.append(v[j][0])
y0.append(v[j][1])
cost.append(v[j][2])
xi = np.linspace(-0.4,0.4,100)
yi = np.linspace(0.12,0.58,100)
zi = griddata(x0, y0, cost, xi, yi)
t1 = ax.scatter(x0, y0, c=cost, marker=u'o', s=5, cmap=cm.get_cmap('RdYlBu'))
ax.scatter(rs.XTarget, rs.YTarget, c ='g', marker='v', s=200)
CS = ax.contourf(xi, yi, zi, 15, cmap=cm.get_cmap('RdYlBu'))
fig.colorbar(t1, shrink=0.5, aspect=5)
t1 = ax.scatter(x0, y0, c='b', marker=u'o', s=20)
ax.set_xlabel("X (m)")
ax.set_ylabel("Y (m)")
ax.set_title(str("Cost map for target " + str(rs.sizeOfTarget[i])))
else:
if what == "CMAES":
name = rs.CMAESpath + targetSize + "/" + foldername + "/Cost/"
elif what == "Brent":
name = BrentTrajectoriesFolder
else:
name = rs.RBFNpath + foldername + "/Cost/"
costs = getCostData(name)
x0 = []
y0 = []
cost = []
for k, v in costs.items():
for j in range(len(v)):
x0.append(v[j][0])
y0.append(v[j][1])
cost.append(v[j][2])
xi = np.linspace(-0.4,0.4,100)
yi = np.linspace(0.12,0.58,100)
zi = griddata(x0, y0, cost, xi, yi)
t1 = plt.scatter(x0, y0, c=cost, marker=u'o', s=5, cmap=cm.get_cmap('RdYlBu'))
plt.scatter(rs.XTarget, rs.YTarget, c ='g', marker='v', s=200)
CS = plt.contourf(xi, yi, zi, 15, cmap=cm.get_cmap('RdYlBu'))
fig.colorbar(t1, shrink=0.5, aspect=5)
t1 = plt.scatter(x0, y0, c='b', marker=u'o', s=20)
plt.xlabel("X (m)")
plt.ylabel("Y (m)")
plt.title("Cost map for " + what)
plt.savefig("ImageBank/"+what+'_costmap'+foldername+'.png', bbox_inches='tight')
plt.show(block = True)
#-------------------------- time maps ----------------------------------------------
def plotTimeColorMap(what, foldername = "None", targetSize = "All"):
'''
Cette fonction permet d'afficher le profil de temps des trajectoires
Entrees: -what: choix des donnees a afficher
'''
rs = ReadSetupFile()
fig = plt.figure(1, figsize=(16,9))
if what == "CMAES" and targetSize == "All":
for i in range(len(rs.sizeOfTarget)):
ax = plt.subplot2grid((2,2), (i/2,i%2))
name = rs.CMAESpath + str(rs.sizeOfTarget[i]) + "/" + foldername + "/TrajTime/"
times = getTrajTimeData(name)
x0 = []
y0 = []
time = []
for k, v in times.items():
for j in range(len(v)):
x0.append(v[j][0])
y0.append(v[j][1])
time.append(v[j][2])
xi = np.linspace(-0.4,0.4,100)
yi = np.linspace(0.12,0.58,100)
zi = griddata(x0, y0, time, xi, yi)
t1 = ax.scatter(x0, y0, c=time, marker=u'o', s=50, cmap=cm.get_cmap('RdYlBu'))
ax.scatter(rs.XTarget, rs.YTarget, c ='g', marker='v', s=200)
CS = ax.contourf(xi, yi, zi, 15, cmap=cm.get_cmap('RdYlBu'))
ax.set_xlabel("X (m)")
ax.set_ylabel("Y (m)")
ax.set_title(str("Time map for target " + str(rs.sizeOfTarget[i])))
fig.colorbar(t1, shrink=0.5, aspect=5)
t1 = ax.scatter(x0, y0, c='b', marker=u'o', s=20)
else:
if what == "CMAES":
name = rs.CMAESpath + targetSize + "/" + foldername + "/TrajTime/"
elif what == "Brent":
name = BrentTrajectoriesFolder
else:
name = rs.RBFNpath + foldername + "/TrajTime/"
times = getTrajTimeData(name)
x0 = []
y0 = []
time = []
for k, v in times.items():
for j in range(len(v)):
x0.append(v[j][0])
y0.append(v[j][1])
time.append(v[j][2])
xi = np.linspace(-0.4,0.4,100)
yi = np.linspace(0.12,0.58,100)
zi = griddata(x0, y0, time, xi, yi)
t1 = plt.scatter(x0, y0, c=time, marker=u'o', s=50, cmap=cm.get_cmap('RdYlBu'))
plt.scatter(rs.XTarget, rs.YTarget, c ='g', marker='v', s=200)
CS = plt.contourf(xi, yi, zi, 15, cmap=cm.get_cmap('RdYlBu'))
fig.colorbar(t1, shrink=0.5, aspect=5)
plt.scatter(x0, y0, c='b', marker=u'o', s=20)
plt.xlabel("X (m)")
plt.ylabel("Y (m)")
plt.savefig("ImageBank/"+what+'_timemap'+foldername+'.png', bbox_inches='tight')
plt.show(block = True)
#-----------------------------------------------------------------------------------------------------------
def plotTimeDistanceTarget(foldername):
rs = ReadSetupFile()
dicoTime = {}
for i in range(len(rs.sizeOfTarget)):
name = rs.CMAESpath + str(rs.sizeOfTarget[i]) + "/" + foldername + "/TrajTime/"
trajTimes = getTrajTimeData(name)
for k, v in trajTimes.items():
for j in range(len(v)):
distance = round(rs.getDistanceToTarget(v[j][0],v[j][1]),2)
if not distance in dicoTime.keys():
dicoTime[distance] = {}
if not rs.sizeOfTarget[i] in dicoTime[distance].keys():
dicoTime[distance][rs.sizeOfTarget[i]] = []
dicoTime[distance][rs.sizeOfTarget[i]].append(v[j][2])
plotTab = []
fig = plt.figure(1, figsize=(16,9))
plt.ylabel("time (s)")
plt.xlabel("Target size (mm)")
for key in sorted(dicoTime.keys()):
plotTab.append(plt.plot([i for i in sorted(dicoTime[key].keys())], [np.mean(dicoTime[key][i]) for i in sorted(dicoTime[key].keys())], label = str("Distance: " + str(key))))
plt.legend(loc = 0)
plt.savefig("ImageBank/timedist"+foldername+'.png', bbox_inches='tight')
plt.show(block = True)
#-----------------------------------------------------------------------------------------------------------
def plotPerfSizeDist(foldername):
rs = ReadSetupFile()
dicoCost = {}
for i in range(len(rs.sizeOfTarget)):
name = rs.CMAESpath + str(rs.sizeOfTarget[i]) + "/" + foldername + "/Cost/"
costs = getCostData(name)
for k, v in costs.items():
for j in range(len(v)):
distance = round(rs.getDistanceToTarget(v[j][0],v[j][1]),2)
if not distance in dicoCost.keys():
dicoCost[distance] = {}
if not rs.sizeOfTarget[i] in dicoCost[distance].keys():
dicoCost[distance][rs.sizeOfTarget[i]] = []
dicoCost[distance][rs.sizeOfTarget[i]].append(v[j][2])
plotTab = []
fig = plt.figure(1, figsize=(16,9))
plt.ylabel("performance")
plt.xlabel("Target size (mm)")
for key in sorted(dicoCost.keys()):
plotTab.append(plt.plot([i for i in sorted(dicoCost[key].keys())], [np.mean(dicoCost[key][i]) for i in sorted(dicoCost[key].keys())], label = str("Distance: " + str(key))))
plt.legend(loc = 0)
plt.savefig("ImageBank/perfdist"+foldername+".png", bbox_inches='tight')
plt.show(block = True)
#-----------------------------------------------------------------------------------------------------------
def plotFittsLaw(foldername, rbfn = False):
rs = ReadSetupFile()
timeDistWidth = []
for i in range(len(rs.sizeOfTarget)):
name = rs.CMAESpath + str(rs.sizeOfTarget[i]) + "/" + foldername + "/TrajTime/"
trajTimes = getTrajTimeData(name)
for k, v in trajTimes.items():
for j in range(len(v)):
distance = rs.getDistanceToTarget(v[j][0],v[j][1])
trajtime = v[j][2]
size = rs.sizeOfTarget[i]
timeDistWidth.append((distance, size, trajtime))
MT, DI = [], []
for el in timeDistWidth:
MT.append(el[2])
DI.append(np.log2(el[0]/el[1]))
slope, intercept, r_value, p_value, std_err = stats.linregress(DI,MT)
yLR = slope * np.asarray(DI) + intercept
plt.figure()
for el in timeDistWidth:
if el[0]<=0.15:
plt.scatter(np.log2(el[0]/el[1]), el[2], c ='blue')
elif el[0]<=0.28:
plt.scatter(np.log2(el[0]/el[1]), el[2], c ='green')
else:
plt.scatter(np.log2(el[0]/el[1]), el[2], c ='red')
plt.plot(DI, yLR)
plt.title("a = " + str(slope) + " b = " + str(intercept) + " r^2 = " + str(r_value**2))
plt.xlabel("log(D/W)/log(2)")
plt.ylabel("Movement time (s)")
plt.savefig("ImageBank/fitts"+foldername+".png", bbox_inches='tight')
plt.show(block = True)
# ---------------- hit dispersion ---------------------------------------
def plotHitDispersion(foldername,sizeT):
rs = ReadSetupFile()
name = rs.CMAESpath + sizeT + "/" + foldername + "/finalX/"
data = getLastXData(name)
tabx, taby = [], []
for el in data.values():
for j in range(len(el)):
tabx.append(el[j])
taby.append(rs.YTarget)
fig = plt.figure(1, figsize=(16,9))
plt.plot([-rs.sizeOfTarget[0]/2, rs.sizeOfTarget[0]/2], [rs.YTarget, rs.YTarget], c = 'r')
plt.scatter([-rs.sizeOfTarget[0]/2, rs.sizeOfTarget[0]/2], [rs.YTarget, rs.YTarget], marker=u'|', s = 100)
plt.scatter(tabx, taby, c = 'b')
plt.xlabel("X (m)")
plt.ylabel("Y (m)")
plt.savefig("ImageBank/hit" + str(sizeT) +foldername + ".png", bbox_inches='tight')
plt.show(block = True)
def plotScattergram(what,foldername):
rs = ReadSetupFile()
data = {}
if what=="CMAES":
for i in range(len(rs.sizeOfTarget)):
name = rs.CMAESpath + str(rs.sizeOfTarget[i]) + "/" + foldername + "/finalX/"
tmp = getLastXData(name)
tabx = []
for el in tmp.values():
for j in range(len(el)):
tabx.append(el[j])
data[rs.sizeOfTarget[i]] = tabx
plt.figure(1, figsize=(16,9))
for i in range(len(rs.sizeOfTarget)):
ax = plt.subplot2grid((2,2), (i/2,i%2))
ax.hist(data[rs.sizeOfTarget[i]], 20)
ax.plot([-rs.sizeOfTarget[i]/2, -rs.sizeOfTarget[i]/2], [0, 500], c = 'r', linewidth = 3)
ax.plot([rs.sizeOfTarget[i]/2, rs.sizeOfTarget[i]/2], [0, 500], c = 'r', linewidth = 3)
ax.set_title(str("Hit Dispersion for Target " + str(rs.sizeOfTarget[i])))
elif what=="RBFN":
name = rs.RBFNpath + foldername + "/finalX/"
tmp = getLastXData(name)
tabx = []
for el in tmp.values():
for j in range(len(el)):
tabx.append(el[j])
plt.hist(tabx, 20)
for i in range(len(rs.sizeOfTarget)):
plt.plot([-rs.sizeOfTarget[i]/2, -rs.sizeOfTarget[i]]/2, [0, 20], c = 'r', linewidth = 3)
plt.plot([rs.sizeOfTarget[i]/2, rs.sizeOfTarget[i]]/2, [0, 20], c = 'r', linewidth = 3)
plt.xlabel("X (m)")
plt.ylabel("Y (m)")
plt.title("Hit Dispersion for RBFN")
plt.savefig("ImageBank/"+what+"_hitdisp"+foldername+".png", bbox_inches='tight')
plt.show(block = True)
# ---------------- end of hit dispersion ---------------------------------------
def plotCMAESProgress():
plotCMAESCostProgress()
plotCMAESTimeProgress()
def plotCMAESCostProgress():
rs = ReadSetupFile()
fig = plt.figure(1, figsize=(16,9))
for i in range(len(rs.sizeOfTarget)):
ax = plt.subplot2grid((2,2), (i/2,i%2))
name = rs.CMAESpath + str(rs.sizeOfTarget[i]) + "/Cost/cmaesCost.log"
data = np.loadtxt(name)
x,w,m,b = [],[],[],[]
for j in range(len(data)):
x.append(j)
w.append(data[j][0])
m.append(data[j][1])
b.append(data[j][2])
ax.plot(x, w, c = 'b')
ax.plot(x, m, c = 'g')
ax.plot(x, b, c = 'r')
ax.set_title(str("Cost Target " + str(rs.sizeOfTarget[i])))
plt.savefig("ImageBank/costProgress.png")
plt.show(block = True)
def plotCMAESTimeProgress():
rs = ReadSetupFile()
fig = plt.figure(1, figsize=(16,9))
for i in range(len(rs.sizeOfTarget)):
ax = plt.subplot2grid((2,2), (i/2,i%2))
name = rs.CMAESpath + str(rs.sizeOfTarget[i]) + "/Cost/cmaesTime.log"
data = np.loadtxt(name)
x,w,m,b = [],[],[],[]
for j in range(len(data)):
x.append(j)
w.append(data[j][0])
m.append(data[j][1])
b.append(data[j][2])
ax.plot(x, w, c = 'b')
ax.plot(x, m, c = 'g')
ax.plot(x, b, c = 'r')
ax.set_title(str("Time Target " + str(rs.sizeOfTarget[i])))
plt.savefig("ImageBank/timeProgress.png")
plt.show(block = True)
def plotExperimentSetup():
rs = ReadSetupFile()
fig = plt.figure(1, figsize=(16,9))
arm = Arm()
q1 = np.linspace(-0.6, 2.6, 100, True)
q2 = np.linspace(-0.2, 3, 100, True)
posIni = np.loadtxt(pathDataFolder + rs.experimentFilePosIni)
xi, yi = [], []
xb, yb = [0], [0]
t = 0
for el in posIni:
if el[1] == np.min(posIni, axis = 0)[1] and t == 0:
t += 1
a, b = arm.mgi(el[0], el[1])
a1, b1 = arm.mgdFull(np.array([[a], [b]]))
xb.append(a1[0])
xb.append(b1[0])
yb.append(a1[1])
yb.append(b1[1])
xi.append(el[0])
yi.append(el[1])
pos = []
for i in range(len(q1)):
for j in range(len(q2)):
coordHa = arm.mgdEndEffector(np.array([[q1[i]], [q2[j]]]))
pos.append(coordHa)
x, y = [], []
for el in pos:
x.append(el[0])
y.append(el[1])
plt.scatter(x, y)
plt.scatter(xi, yi, c = 'r')
plt.scatter(0, 0.6175, c = "r", marker=u'*', s = 200)
plt.plot(xb, yb, c = 'r')
plt.plot([-0.3,0.3], [0.6175, 0.6175], c = 'g')
plt.savefig("ImageBank/setup.png", bbox_inches='tight')
plt.show(block = True)
#TODO: both functions below can be much improved
def plotManipulability():
rs = ReadSetupFile()
fig = plt.figure(1, figsize=(16,9))
arm = Arm()
q1 = np.linspace(-0.6, 2.6, 100, True)
q2 = np.linspace(-0.2, 3, 100, True)
target = [rs.XTarget, rs.YTarget]
pos = []
for i in range(len(q1)):
for j in range(len(q2)):
config = np.array([q1[i], q2[j]])
coordHa = arm.mgdEndEffector(config)
pos.append(coordHa)
x, y, cost = [], [], []
for el in pos:
x.append(el[0])
y.append(el[1])
config = arm.mgi(el[0],el[1])
manip = arm.directionalManipulability(config,target)
cost.append(manip)
xi = np.linspace(-0.7,0.8,100)
yi = np.linspace(-0.5,0.8,100)
zi = griddata(x, y, cost, xi, yi)
#t1 = plt.scatter(x, y, c=cost, marker=u'o', s=5, cmap=cm.get_cmap('RdYlBu'))
#CS = plt.contourf(xi, xi, zi, 15, cmap=cm.get_cmap('RdYlBu'))
t1 = plt.scatter(x, y, c=cost, s=5, cmap=cm.get_cmap('RdYlBu'))
CS = plt.contourf(xi, yi, zi, 15, cmap=cm.get_cmap('RdYlBu'))
fig.colorbar(t1, shrink=0.5, aspect=5)
plt.scatter(rs.XTarget, rs.YTarget, c = "g", marker=u'*', s = 200)
#plt.plot([-0.3,0.3], [rs.YTarget, rs.YTarget], c = 'g')
plt.xlabel("X (m)")
plt.ylabel("Y (m)")
plt.title(str("Manipulability map"))
plt.savefig("ImageBank/manipulability.png", bbox_inches='tight')
plt.show(block = True)
def plotManipulability2():
rs = ReadSetupFile()
fig = plt.figure(1, figsize=(16,9))
arm = Arm()
q1 = np.linspace(-0.6, 2.6, 100, True)
q2 = np.linspace(-0.2, 3, 100, True)
target = [rs.XTarget, rs.YTarget]
pos = []
for i in range(len(q1)):
for j in range(len(q2)):
config = np.array([q1[i], q2[j]])
coordHa = arm.mgdEndEffector(config)
pos.append(coordHa)
x, y, cost = [], [], []
for el in pos:
x.append(el[0])
y.append(el[1])
config = arm.mgi(el[0],el[1])
manip = arm.manipulability(config,target)
cost.append(manip)
xi = np.linspace(-0.7,0.8,100)
yi = np.linspace(-0.5,0.8,100)
zi = griddata(x, y, cost, xi, yi)
#t1 = plt.scatter(x, y, c=cost, marker=u'o', s=5, cmap=cm.get_cmap('RdYlBu'))
#CS = plt.contourf(xi, xi, zi, 15, cmap=cm.get_cmap('RdYlBu'))
t1 = plt.scatter(x, y, c=cost, s=5, cmap=cm.get_cmap('RdYlBu'))
CS = plt.contourf(xi, yi, zi, 15, cmap=cm.get_cmap('RdYlBu'))
fig.colorbar(t1, shrink=0.5, aspect=5)
plt.scatter(rs.XTarget, rs.YTarget, c = "g", marker=u'*', s = 200)
#plt.plot([-0.3,0.3], [rs.YTarget, rs.YTarget], c = 'g')
plt.xlabel("X (m)")
plt.ylabel("Y (m)")
plt.title(str("Manipulability map"))
plt.savefig("ImageBank/manipulability2.png", bbox_inches='tight')
plt.show(block = True)
|
gpl-2.0
|
KevinNZ83/Social-Aggregator
|
Social.Aggregator.Web/App_Start/Startup.Auth.cs
|
3470
|
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using Social.Aggregator.Models;
namespace Social.Aggregator
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
}
}
|
gpl-2.0
|
rohitwebdevta/machinelearningtoolbox
|
min1.py
|
694
|
threshold = 0.5
learning_rate = 0.1
weights = [0, 0, 0]
training_set = [((1, 0, 0), 1), ((1, 0, 1), 1), ((1, 1, 0), 1), ((1, 1, 1), 0)]
def dot_product(values, weights):
return sum(value * weight for value, weight in zip(values, weights))
while True:
print('-' * 60)
error_count = 0
for input_vector, desired_output in training_set:
print(weights)
result = dot_product(input_vector, weights) > threshold
error = desired_output - result
if error != 0:
error_count += 1
for index, value in enumerate(input_vector):
weights[index] += learning_rate * error * value
if error_count == 0:
break
|
gpl-2.0
|
kosmosby/medicine-prof
|
administrator/components/com_extman/views/extensions/html.php
|
1445
|
<?php
/**
* @package EXTman
* @copyright Copyright (C) 2011 - 2014 Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.joomlatools.com
*/
class ComExtmanViewExtensionsHtml extends ComKoowaViewHtml
{
/**
* Initializes the config for the object
*
* Called from {@link __construct()} as a first step of object instantiation.
*
* @param KObjectConfig $config Configuration options
* @return void
*/
protected function _initialize(KObjectConfig $config)
{
$config->append(array(
'template_functions' => array(
'translateComponentName' => array($this, 'translateComponentName'),
),
));
parent::_initialize($config);
}
public function translateComponentName($component)
{
$language = JFactory::getLanguage();
$language->load($component.'.sys', JPATH_BASE, null, false, false)
|| $language->load($component.'.sys', JPATH_ADMINISTRATOR.'/components/'.$component, null, false, false)
|| $language->load($component.'.sys', JPATH_BASE, $language->getDefault(), false, false)
|| $language->load($component.'.sys', JPATH_ADMINISTRATOR.'/components/'.$component, $language->getDefault(), false, false);
return $language->hasKey($component) ? JText::_($component) : $component;
}
}
|
gpl-2.0
|
ahuarte47/SOS
|
coding/json/src/main/java/org/n52/sos/decode/json/impl/GetObservationByIdRequestDecoder.java
|
2740
|
/**
* Copyright (C) 2012-2016 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* License version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*/
package org.n52.sos.decode.json.impl;
import java.util.List;
import org.n52.sos.coding.json.JSONConstants;
import org.n52.sos.coding.json.SchemaConstants;
import org.n52.sos.decode.json.AbstractSosRequestDecoder;
import org.n52.sos.ogc.ows.OwsExceptionReport;
import org.n52.sos.ogc.sos.Sos2Constants;
import org.n52.sos.ogc.sos.SosConstants;
import org.n52.sos.request.GetObservationByIdRequest;
import com.fasterxml.jackson.databind.JsonNode;
/**
* TODO JavaDoc
*
* @author Christian Autermann <c.autermann@52north.org>
*
* @since 4.0.0
*/
public class GetObservationByIdRequestDecoder extends AbstractSosRequestDecoder<GetObservationByIdRequest> {
public GetObservationByIdRequestDecoder() {
super(GetObservationByIdRequest.class, SosConstants.SOS, Sos2Constants.SERVICEVERSION,
SosConstants.Operations.GetObservationById);
}
@Override
protected String getSchemaURI() {
return SchemaConstants.Request.GET_OBSERVATION_BY_ID;
}
@Override
protected GetObservationByIdRequest decodeRequest(JsonNode node) throws OwsExceptionReport {
GetObservationByIdRequest req = new GetObservationByIdRequest();
req.setObservationIdentifier(parseObservationIdentifiers(node));
return req;
}
private List<String> parseObservationIdentifiers(JsonNode node) {
return parseStringOrStringList(node.path(JSONConstants.OBSERVATION));
}
}
|
gpl-2.0
|
zencart/zencart
|
includes/functions/functions_files.php
|
12065
|
<?php
/**
* File functions
*
* @copyright Copyright 2003-2020 Zen Cart Development Team
* @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
* @version $Id: $
*/
/**
* build a list of directories in a specified parent folder
* (formatted in id/text pairs for SELECT boxes)
*
* @param string $parent_folder
* @param string $default_text
* @return array (id/text pairs)
*
* @todo convert to a directory-iterator instead
*/
function zen_build_subdirectories_array($parent_folder = '', $default_text = 'Main Directory')
{
if ($parent_folder == '') $parent_folder = DIR_FS_CATALOG_IMAGES;
$dir_info = [];
$dir_info[] = ['id' => '', 'text' => $default_text];
$dir = @dir($parent_folder);
if ($dir == null) return [];
while ($file = $dir->read()) {
if (is_dir($parent_folder . $file) && $file != "." && $file != "..") {
$dir_info[] = ['id' => $file . '/', 'text' => $file];
}
}
$dir->close();
sort($dir_info);
return $dir_info;
}
/**
* find template or default file
* @param string $check_directory
* @param string $check_file
* @param bool $dir_only
* @return string
*/
function zen_get_file_directory($check_directory, $check_file, $dir_only = false)
{
global $template_dir;
$zv_filename = $check_file;
if (strpos($zv_filename, '.php') === false) $zv_filename .= '.php';
if (file_exists($check_directory . $template_dir . '/' . $zv_filename)) {
$zv_directory = $check_directory . $template_dir . '/';
} else {
$zv_directory = $check_directory;
}
if ($dir_only === true) {
return $zv_directory;
}
return $zv_directory . $zv_filename;
}
function zen_include_language_file($file, $folder, $page)
{
global $messageStack, $languageLoader;
if (IS_ADMIN_FLAG === true) {
$lang_file = zen_get_file_directory(DIR_FS_CATALOG . DIR_WS_LANGUAGES . $_SESSION['language'] . $folder, $file, 'false');
$module_file = DIR_FS_CATALOG . $module_file;
} else {
$lang_file = zen_get_file_directory(DIR_WS_LANGUAGES . $_SESSION['language'] . $folder, $file, 'false');
}
if ($languageLoader->hasLanguageFile(DIR_FS_CATALOG . DIR_WS_LANGUAGES, $_SESSION['language'], $file, $folder)) {
$languageLoader->loadExtraLanguageFiles(DIR_FS_CATALOG . DIR_WS_LANGUAGES, $_SESSION['language'], $file, $folder);
} else {
if ($page === 'inline') {
?>
<div class="messageStackCaution">
<?php echo WARNING_COULD_NOT_LOCATE_LANG_FILE . $lang_file; ?>
</div>
<?php
} else {
if (is_object($messageStack)) {
if (IS_ADMIN_FLAG === false) {
$messageStack->add($page, WARNING_COULD_NOT_LOCATE_LANG_FILE . $lang_file, 'caution');
} else {
$messageStack->add_session(WARNING_COULD_NOT_LOCATE_LANG_FILE . $lang_file, 'caution');
}
}
}
return false;
}
return true;
}
/**
* find module directory
* include template specific immediate /modules files
* new_products, products_new_listing, featured_products, featured_products_listing, product_listing, specials_index, upcoming,
* products_all_listing, products_discount_prices, also_purchased_products
* @param string $check_file
* @param bool $dir_only
* @return string
*/
function zen_get_module_directory($check_file, $dir_only = false)
{
global $template_dir;
$zv_filename = $check_file;
if (strpos($zv_filename, '.php') === false) $zv_filename .= '.php';
if (file_exists(DIR_WS_MODULES . $template_dir . '/' . $zv_filename)) {
$template_dir_select = $template_dir . '/';
} else {
$template_dir_select = '';
}
if ($dir_only === true || $dir_only == 'true') {
return $template_dir_select;
}
return $template_dir_select . $zv_filename;
}
/**
* @param string $check_file
* @return string
*/
function zen_get_module_sidebox_directory($check_file)
{
global $template_dir;
$zv_filename = $check_file;
if (strpos($zv_filename, '.php') === false) $zv_filename .= '.php';
if (file_exists(DIR_WS_MODULES . 'sideboxes/' . $template_dir . '/' . $zv_filename)) {
$template_dir_select = 'sideboxes/' . $template_dir . '/';
} else {
$template_dir_select = 'sideboxes/';
}
return $template_dir_select . $zv_filename;
}
/**
* Find index_filters directory
* suitable for including template-specific immediate /modules files, such as:
* new_products, products_new_listing, featured_products, featured_products_listing, product_listing, specials_index, upcoming,
* products_all_listing, products_discount_prices, also_purchased_products
* @param $check_file
* @param bool $dir_only
* @return false|mixed|string
*/
function zen_get_index_filters_directory($check_file, $dir_only = false)
{
global $template_dir;
$zv_filename = $check_file;
if (strpos($zv_filename, '.php') === false) $zv_filename .= '.php';
$checkArray = [];
$checkArray[] = DIR_WS_INCLUDES . 'index_filters/' . $template_dir . '/' . $zv_filename;
$checkArray[] = DIR_WS_INCLUDES . 'index_filters/' . $zv_filename;
$checkArray[] = DIR_WS_INCLUDES . 'index_filters/' . $template_dir . '/' . 'default_filter.php';
foreach ($checkArray as $key => $val) {
if (file_exists($val)) {
return ($dir_only === true || $dir_only == 'true') ? $val = substr($val, 0, strpos($val, '/')) : $val;
}
}
return DIR_WS_INCLUDES . 'index_filters/' . 'default_filter.php';
}
/** @deprecated not used anywhere in core code */
function zen_get_file_permissions($mode)
{
// determine type
if (($mode & 0xC000) == 0xC000) { // unix domain socket
$type = 's';
} elseif (($mode & 0x4000) == 0x4000) { // directory
$type = 'd';
} elseif (($mode & 0xA000) == 0xA000) { // symbolic link
$type = 'l';
} elseif (($mode & 0x8000) == 0x8000) { // regular file
$type = '-';
} elseif (($mode & 0x6000) == 0x6000) { //bBlock special file
$type = 'b';
} elseif (($mode & 0x2000) == 0x2000) { // character special file
$type = 'c';
} elseif (($mode & 0x1000) == 0x1000) { // named pipe
$type = 'p';
} else { // unknown
$type = '?';
}
// determine permissions
$owner['read'] = ($mode & 00400) ? 'r' : '-';
$owner['write'] = ($mode & 00200) ? 'w' : '-';
$owner['execute'] = ($mode & 00100) ? 'x' : '-';
$group['read'] = ($mode & 00040) ? 'r' : '-';
$group['write'] = ($mode & 00020) ? 'w' : '-';
$group['execute'] = ($mode & 00010) ? 'x' : '-';
$world['read'] = ($mode & 00004) ? 'r' : '-';
$world['write'] = ($mode & 00002) ? 'w' : '-';
$world['execute'] = ($mode & 00001) ? 'x' : '-';
// adjust for SUID, SGID and sticky bit
if ($mode & 0x800) $owner['execute'] = ($owner['execute'] == 'x') ? 's' : 'S';
if ($mode & 0x400) $group['execute'] = ($group['execute'] == 'x') ? 's' : 'S';
if ($mode & 0x200) $world['execute'] = ($world['execute'] == 'x') ? 't' : 'T';
return $type .
$owner['read'] . $owner['write'] . $owner['execute'] .
$group['read'] . $group['write'] . $group['execute'] .
$world['read'] . $world['write'] . $world['execute'];
}
/**
* delete a file
*
* @TODO - refactor to bypass the use of the global $zen_remove_error and use a return value instead
* @TODO - and give it a more meaningful name at the same time
*
* @param string $source
*/
function zen_remove($source)
{
global $messageStack, $zen_remove_error;
$zen_remove_error = false;
if (is_dir($source)) {
$dir = dir($source);
while ($file = $dir->read()) {
if (($file != '.') && ($file != '..')) {
if (is_writeable($source . '/' . $file)) {
zen_remove($source . '/' . $file);
} else {
$messageStack->add(sprintf(ERROR_FILE_NOT_REMOVEABLE, $source . '/' . $file), 'error');
$zen_remove_error = true;
}
}
}
$dir->close();
if (is_writeable($source)) {
rmdir($source);
zen_record_admin_activity('Removed directory from server: [' . $source . ']', 'notice');
} else {
$messageStack->add(sprintf(ERROR_DIRECTORY_NOT_REMOVEABLE, $source), 'error');
$zen_remove_error = true;
}
} else {
if (is_writeable($source)) {
unlink($source);
zen_record_admin_activity('Deleted file from server: [' . $source . ']', 'notice');
} else {
$messageStack->add(sprintf(ERROR_FILE_NOT_REMOVEABLE, $source), 'error');
$zen_remove_error = true;
}
}
}
/**
* attempt to make the specified file read-only
*
* @return boolean
* @var string
*/
function set_unwritable($filepath)
{
return @chmod($filepath, 0444);
}
/**
* function to override PHP's is_writable() which can occasionally be unreliable due to O/S and F/S differences
* attempts to open the specified file for writing. Returns true if successful, false if not.
* if a directory is specified, uses PHP's is_writable() anyway
*
* @param string $filepath
* @param bool $make_unwritable
* @return boolean
*/
function is__writeable($filepath, $make_unwritable = true)
{
if (is_dir($filepath)) return is_writable($filepath);
$fp = @fopen($filepath, 'a');
if ($fp) {
@fclose($fp);
if ($make_unwritable) set_unwritable($filepath);
$fp = @fopen($filepath, 'a');
if ($fp) {
@fclose($fp);
return true;
}
}
return false;
}
/**
* @TODO - refactor where this is used, to find a better way of displaying whatever is needed
* @param string $filename
* @return string
*/
function zen_get_uploaded_file(string $filename)
{
$parts = explode(". ", $filename, 2);
$filenum = $parts[0];
$filename = $parts[1];
$file_parts = explode(".", $filename, 2);
$filetype = $file_parts[count($file_parts) - 1];
return $filenum . "." . $filetype;
}
/**
* Obtain a list of .log/.xml files from the /logs/ folder
* (and also /cache/ folder for backward compatibility of older modules which store logs there)
*
* If $maxToList == 'count' then it returns the total number of files found
* If an integer is passed, then an array of files is returned, including paths, filenames, and datetime details
*
* @param string|int $maxToList (integer or 'count')
* @return array|int
*
* inspired by log checking suggestion from Steve Sherratt (torvista)
*/
function get_logs_data($maxToList = 'count')
{
if (!defined('DIR_FS_LOGS')) define('DIR_FS_LOGS', DIR_FS_CATALOG . 'logs');
if (!defined('DIR_FS_SQL_CACHE')) define('DIR_FS_SQL_CACHE', DIR_FS_CATALOG . 'cache');
$logs = array();
$file = array();
$i = 0;
foreach (array(DIR_FS_LOGS, DIR_FS_SQL_CACHE) as $purgeFolder) {
$purgeFolder = rtrim($purgeFolder, '/');
if (!file_exists($purgeFolder) || !is_dir($purgeFolder)) continue;
$dir = dir($purgeFolder);
while ($logfile = $dir->read()) {
if (substr($logfile, 0, 1) == '.') continue;
if (!preg_match('/.*(\.log|\.xml)$/', $logfile)) continue; // xml allows for usps debug
if ($maxToList != 'count') {
$filename = $purgeFolder . '/' . $logfile;
$logs[$i]['path'] = $purgeFolder . "/";
$logs[$i]['filename'] = $logfile;
$logs[$i]['filesize'] = @filesize($filename);
$logs[$i]['unixtime'] = @filemtime($filename);
$logs[$i]['datetime'] = strftime(DATE_TIME_FORMAT, $logs[$i]['unixtime']);
}
$i++;
if ($maxToList != 'count' && $i >= $maxToList) break;
}
$dir->close();
unset($dir);
}
if ($maxToList == 'count') return $i;
$logs = zen_sort_array($logs, 'unixtime', SORT_DESC);
return $logs;
}
|
gpl-2.0
|
cwaclawik/moodle
|
user/profile/index.php
|
9152
|
<?php //$Id$
require('../../config.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->dirroot.'/user/profile/lib.php');
require_once($CFG->dirroot.'/user/profile/definelib.php');
admin_externalpage_setup('profilefields');
$action = optional_param('action', '', PARAM_ALPHA);
$redirect = $CFG->wwwroot.'/user/profile/index.php';
$strchangessaved = get_string('changessaved');
$strcancelled = get_string('cancelled');
$strdefaultcategory = get_string('profiledefaultcategory', 'admin');
$strnofields = get_string('profilenofieldsdefined', 'admin');
$strcreatefield = get_string('profilecreatefield', 'admin');
/// Do we have any actions to perform before printing the header
switch ($action) {
case 'movecategory':
$id = required_param('id', PARAM_INT);
$dir = required_param('dir', PARAM_ALPHA);
if (confirm_sesskey()) {
profile_move_category($id, $dir);
}
redirect($redirect);
break;
case 'movefield':
$id = required_param('id', PARAM_INT);
$dir = required_param('dir', PARAM_ALPHA);
if (confirm_sesskey()) {
profile_move_field($id, $dir);
}
redirect($redirect);
break;
case 'deletecategory':
$id = required_param('id', PARAM_INT);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
if (data_submitted() and $confirm and confirm_sesskey()) {
profile_delete_category($id);
redirect($redirect);
}
//ask for confirmation
$fieldcount = $DB->count_records('user_info_field', array('categoryid'=>$id));
$optionsyes = array ('id'=>$id, 'confirm'=>1, 'action'=>'deletecategory', 'sesskey'=>sesskey());
admin_externalpage_print_header();
print_heading('profiledeletecategory', 'admin');
notice_yesno(get_string('profileconfirmcategorydeletion', 'admin', $fieldcount), $redirect, $redirect, $optionsyes, null, 'post', 'get');
admin_externalpage_print_footer();
die;
break;
case 'deletefield':
$id = required_param('id', PARAM_INT);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
if (data_submitted() and $confirm and confirm_sesskey()) {
profile_delete_field($id);
redirect($redirect);
}
//ask for confirmation
$datacount = $DB->count_records('user_info_data', array('fieldid'=>$id));
$optionsyes = array ('id'=>$id, 'confirm'=>1, 'action'=>'deletefield', 'sesskey'=>sesskey());
admin_externalpage_print_header();
print_heading('profiledeletefield', 'admin');
notice_yesno(get_string('profileconfirmfielddeletion', 'admin', $datacount), $redirect, $redirect, $optionsyes, null, 'post', 'get');
admin_externalpage_print_footer();
die;
break;
case 'editfield':
$id = optional_param('id', 0, PARAM_INT);
$datatype = optional_param('datatype', '', PARAM_ALPHA);
profile_edit_field($id, $datatype, $redirect);
die;
break;
case 'editcategory':
$id = optional_param('id', 0, PARAM_INT);
profile_edit_category($id, $redirect);
die;
break;
default:
//normal form
}
/// Print the header
admin_externalpage_print_header();
print_heading(get_string('profilefields', 'admin'));
/// Check that we have at least one category defined
if ($DB->count_records('user_info_category') == 0) {
$defaultcategory = new object();
$defaultcategory->name = $strdefaultcategory;
$defaultcategory->sortorder = 1;
$DB->insert_record('user_info_category', $defaultcategory);
redirect($redirect);
}
/// Show all categories
$categories = $DB->get_records('user_info_category', null, 'sortorder ASC');
foreach ($categories as $category) {
$table = new object();
$table->head = array(get_string('profilefield', 'admin'), get_string('edit'));
$table->align = array('left', 'right');
$table->width = '95%';
$table->class = 'generaltable profilefield';
$table->data = array();
if ($fields = $DB->get_records('user_info_field', array('categoryid'=>$category->id), 'sortorder ASC')) {
foreach ($fields as $field) {
$table->data[] = array($field->name, profile_field_icons($field));
}
}
print_heading(format_string($category->name) .' '.profile_category_icons($category));
if (count($table->data)) {
print_table($table);
} else {
notify($strnofields);
}
} /// End of $categories foreach
echo '<hr />';
echo '<div class="profileeditor">';
/// Create a new field link
$options = profile_list_datatypes();
popup_form($CFG->wwwroot.'/user/profile/index.php?id=0&action=editfield&datatype=', $options, 'newfieldform','','choose','','',false,'self',$strcreatefield);
/// Create a new category link
$options = array('action'=>'editcategory');
print_single_button('index.php', $options, get_string('profilecreatecategory', 'admin'));
echo '</div>';
admin_externalpage_print_footer();
die;
/***** Some functions relevant to this script *****/
/**
* Create a string containing the editing icons for the user profile categories
* @param object the category object
* @return string the icon string
*/
function profile_category_icons ($category) {
global $CFG, $USER, $DB;
$strdelete = get_string('delete');
$strmoveup = get_string('moveup');
$strmovedown = get_string('movedown');
$stredit = get_string('edit');
$categorycount = $DB->count_records('user_info_category');
$fieldcount = $DB->count_records('user_info_field', array('categoryid'=>$category->id));
/// Edit
$editstr = '<a title="'.$stredit.'" href="index.php?id='.$category->id.'&action=editcategory"><img src="'.$CFG->pixpath.'/t/edit.gif" alt="'.$stredit.'" class="iconsmall" /></a> ';
/// Delete
/// Can only delete the last category if there are no fields in it
if ( ($categorycount > 1) or ($fieldcount == 0) ) {
$editstr .= '<a title="'.$strdelete.'" href="index.php?id='.$category->id.'&action=deletecategory';
$editstr .= '"><img src="'.$CFG->pixpath.'/t/delete.gif" alt="'.$strdelete.'" class="iconsmall" /></a> ';
} else {
$editstr .= '<img src="'.$CFG->pixpath.'/spacer.gif" alt="" class="iconsmall" /> ';
}
/// Move up
if ($category->sortorder > 1) {
$editstr .= '<a title="'.$strmoveup.'" href="index.php?id='.$category->id.'&action=movecategory&dir=up&sesskey='.sesskey().'"><img src="'.$CFG->pixpath.'/t/up.gif" alt="'.$strmoveup.'" class="iconsmall" /></a> ';
} else {
$editstr .= '<img src="'.$CFG->pixpath.'/spacer.gif" alt="" class="iconsmall" /> ';
}
/// Move down
if ($category->sortorder < $categorycount) {
$editstr .= '<a title="'.$strmovedown.'" href="index.php?id='.$category->id.'&action=movecategory&dir=down&sesskey='.sesskey().'"><img src="'.$CFG->pixpath.'/t/down.gif" alt="'.$strmovedown.'" class="iconsmall" /></a> ';
} else {
$editstr .= '<img src="'.$CFG->pixpath.'/spacer.gif" alt="" class="iconsmall" /> ';
}
return $editstr;
}
/**
* Create a string containing the editing icons for the user profile fields
* @param object the field object
* @return string the icon string
*/
function profile_field_icons($field) {
global $CFG, $USER, $DB;
if (empty($str)) {
$strdelete = get_string('delete');
$strmoveup = get_string('moveup');
$strmovedown = get_string('movedown');
$stredit = get_string('edit');
}
$fieldcount = $DB->count_records('user_info_field', array('categoryid'=>$field->categoryid));
$datacount = $DB->count_records('user_info_data', array('fieldid'=>$field->id));
/// Edit
$editstr = '<a title="'.$stredit.'" href="index.php?id='.$field->id.'&action=editfield"><img src="'.$CFG->pixpath.'/t/edit.gif" alt="'.$stredit.'" class="iconsmall" /></a> ';
/// Delete
$editstr .= '<a title="'.$strdelete.'" href="index.php?id='.$field->id.'&action=deletefield';
$editstr .= '"><img src="'.$CFG->pixpath.'/t/delete.gif" alt="'.$strdelete.'" class="iconsmall" /></a> ';
/// Move up
if ($field->sortorder > 1) {
$editstr .= '<a title="'.$strmoveup.'" href="index.php?id='.$field->id.'&action=movefield&dir=up&sesskey='.sesskey().'"><img src="'.$CFG->pixpath.'/t/up.gif" alt="'.$strmoveup.'" class="iconsmall" /></a> ';
} else {
$editstr .= '<img src="'.$CFG->pixpath.'/spacer.gif" alt="" class="iconsmall" /> ';
}
/// Move down
if ($field->sortorder < $fieldcount) {
$editstr .= '<a title="'.$strmovedown.'" href="index.php?id='.$field->id.'&action=movefield&dir=down&sesskey='.sesskey().'"><img src="'.$CFG->pixpath.'/t/down.gif" alt="'.$strmovedown.'" class="iconsmall" /></a> ';
} else {
$editstr .= '<img src="'.$CFG->pixpath.'/spacer.gif" alt="" class="iconsmall" /> ';
}
return $editstr;
}
?>
|
gpl-2.0
|
EchanHe/trimesh2
|
libsrc/TriMesh_normals.cc
|
4674
|
/*
Szymon Rusinkiewicz
Princeton University
TriMesh_normals.cc
Compute per-vertex normals for TriMeshes
For meshes, uses average of per-face normals, weighted according to:
Max, N.
"Weights for Computing Vertex Normals from Facet Normals,"
Journal of Graphics Tools, Vol. 4, No. 2, 1999.
For raw point clouds, fits plane to k nearest neighbors.
*/
#include "TriMesh.h"
#include "KDtree.h"
#include "lineqn.h"
using namespace std;
namespace trimesh {
// Compute per-vertex normals
void TriMesh::need_normals()
{
// Nothing to do if we already have normals
int nv = vertices.size();
if (int(normals.size()) == nv) {
#pragma omp parallel for
for (int i = 0; i < nv; i++)
normalize(normals[i]);
return;
}
dprintf("Computing normals... ");
normals.clear();
normals.resize(nv);
// TODO: direct handling of grids
if (!tstrips.empty()) {
// Compute from tstrips
const int *t = &tstrips[0], *end = t + tstrips.size();
while (likely(t < end)) {
int striplen = *t - 2;
t += 3;
bool flip = false;
for (int i = 0; i < striplen; i++, t++, flip = !flip) {
const point &p0 = vertices[*(t-2)];
const point &p1 = vertices[*(t-1)];
const point &p2 = vertices[* t ];
vec a = p0-p1, b = p1-p2, c = p2-p0;
float l2a = len2(a), l2b = len2(b), l2c = len2(c);
if (!l2a || !l2b || !l2c)
continue;
vec facenormal = flip ? (b CROSS a) : (a CROSS b);
normals[*(t-2)] += facenormal * (1.0f / (l2a * l2c));
normals[*(t-1)] += facenormal * (1.0f / (l2b * l2a));
normals[* t ] += facenormal * (1.0f / (l2c * l2b));
}
}
} else if (need_faces(), !faces.empty()) {
// Compute from faces
int nf = faces.size();
#pragma omp parallel for
for (int i = 0; i < nf; i++) {
const point &p0 = vertices[faces[i][0]];
const point &p1 = vertices[faces[i][1]];
const point &p2 = vertices[faces[i][2]];
vec a = p0-p1, b = p1-p2, c = p2-p0;
float l2a = len2(a), l2b = len2(b), l2c = len2(c);
if (!l2a || !l2b || !l2c)
continue;
vec facenormal = a CROSS b;
normals[faces[i][0]] += facenormal * (1.0f / (l2a * l2c));
normals[faces[i][1]] += facenormal * (1.0f / (l2b * l2a));
normals[faces[i][2]] += facenormal * (1.0f / (l2c * l2b));
}
} else {
// Find normals of a point cloud
const int k = 6;
const vec ref(0, 0, 1);
KDtree kd(vertices);
#pragma omp parallel for
for (int i = 0; i < nv; i++) {
vector<const float *> knn;
kd.find_k_closest_to_pt(knn, k, vertices[i]);
int actual_k = knn.size();
if (actual_k < 3) {
dprintf("Warning: not enough points for vertex %d\n", i);
normals[i] = ref;
continue;
}
// Compute covariance
float C[3][3] = { {0,0,0}, {0,0,0}, {0,0,0} };
// The below loop starts at 1, since element 0
// is just vertices[i] itself
for (int j = 1; j < actual_k; j++) {
vec d = point(knn[j]) - vertices[i];
for (int l = 0; l < 3; l++)
for (int m = 0; m < 3; m++)
C[l][m] += d[l] * d[m];
}
float e[3];
eigdc<float,3>(C, e);
normals[i] = vec(C[0][0], C[1][0], C[2][0]);
if ((normals[i] DOT ref) < 0.0f)
normals[i] = -normals[i];
}
}
// Make them all unit-length
#pragma omp parallel for
for (int i = 0; i < nv; i++)
normalize(normals[i]);
dprintf("Done.\n");
}
void TriMesh::need_inwardNormals() {
need_normals();
int nv = vertices.size();
if (int(inwardNormals.size()) == nv)
return;
//initial inward normals
inwardNormals.clear();
inwardNormals.resize(nv);
for (int i = 0; i < nv; i++) {
inwardNormals[i] = -normals[i];
normalize(inwardNormals[i]);
}
}
void TriMesh::need_faceNormals() {
need_normals();
int nv = vertices.size();
int nf = faces.size();
if (int(faceNormals.size()) == nf)
return;
faceNormals.resize(nf);
for (int i=0 ; i<nf ; i++){
faceNormals[i] = normalize(trinorm(i));
//vec e[3] = { vertices[faces[i][2]] - vertices[faces[i][1]],
// vertices[faces[i][0]] - vertices[faces[i][2]],
// vertices[faces[i][1]] - vertices[faces[i][0]] };
//faceNormals[i] = -e[0] CROSS e[1];
//if (len((e[0] CROSS -e[2])- (e[1] CROSS -e[0]))>0.00001)
// std::cout << "larger";
}
}
void TriMesh::need_faceMidPts() {
int nf = faces.size();
if (faceMidPts.size() == nf)
return;
faceMidPts.resize(nf);
for (int i = 0; i < nf; i++) {
float aveX = (vertices[faces[i][0]][0] + vertices[faces[i][1]][0] + vertices[faces[i][2]][0]) / 3;
float aveY = (vertices[faces[i][0]][1] + vertices[faces[i][1]][1] + vertices[faces[i][2]][1]) / 3;
float aveZ = (vertices[faces[i][0]][2] + vertices[faces[i][1]][2] + vertices[faces[i][2]][2]) / 3;
faceMidPts[i] = vec(aveX, aveY, aveZ);
}
}
}; // namespace trimesh
|
gpl-2.0
|
CAndRyan/HL7_Analyst_CCS
|
HL7Lib/Base/Extensions.cs
|
23804
|
/***************************************************************
* Copyright (C) 2011 Jeremy Reagan, All Rights Reserved.
* I may be reached via email at: jeremy.reagan@live.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; under 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.
****************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace HL7Lib.Base
{
/// <summary>
/// Extension Methods
/// </summary>
public static class Extensions
{
/// <summary>
/// Pulls a specified segment from a list of segments by name.
/// </summary>
/// <param name="s">The list of segments to search.</param>
/// <param name="SegmentName">The segment name to pull.</param>
/// <returns>Returns the specified segment if it exists, else returns null.</returns>
public static List<Segment> Get(this List<Segment> s, string SegmentName)
{
List<Segment> returnSegment = s.FindAll(delegate(Segment seg) { return seg.Name.ToUpper() == SegmentName.ToUpper(); });
return returnSegment;
}
/// <summary>
/// Pulls a specified Field from a list of Fields by Name
/// </summary>
/// <param name="fList">The list of fields to search</param>
/// <param name="FieldName">The field name to pull</param>
/// <returns>Returns the specified field if it exists, else returns null.</returns>
public static Field Get(this List<Field> fList, string FieldName)
{
Field field = fList.Find(delegate(Field f) { return f.Name == FieldName; });
return field;
}
/// <summary>
/// Pulls a specified Component from a list of Components by Name
/// </summary>
/// <param name="cList">The list of components to search</param>
/// <param name="ComponentName">The component name to pull</param>
/// <returns>Returns the specified component if it exists, else returns null</returns>
public static Component Get(this List<Component> cList, string ComponentName)
{
Component component = cList.Find(delegate(Component c) { return c.Name == ComponentName; });
return component;
}
/// <summary>
/// Pulls a specified Component from a list of Components byID
/// </summary>
/// <param name="cList">The list of components to search</param>
/// <param name="ComponentID">The component ID to pull</param>
/// <returns>Returns the specified component if it exists, else returns null</returns>
public static Component GetByID(this List<Component> cList, string ComponentID)
{
Component component = cList.Find(delegate(Component c) { return c.ID == ComponentID; });
return component;
}
/// <summary>
/// Gets the specified component from a segment by the component ID
/// </summary>
/// <param name="s">The segment</param>
/// <param name="ComponentID">The component ID</param>
/// <returns>Returns the specified component if it exists, else returns null</returns>
public static Component GetByID(this Segment s, string ComponentID)
{
var item = (from field in s.Fields where field.Components.GetByID(ComponentID) != null select field.Components.GetByID(ComponentID)).FirstOrDefault();
return (HL7Lib.Base.Component)item;
}
/// <summary>
/// Takes a standard Component ID and converts it to a ComponentID object
/// </summary>
/// <param name="ComID">The Component ID string to convert</param>
/// <returns></returns>
public static ComponentID ConvertID(this string ComID)
{
ComponentID cid = new Base.ComponentID();
string[] parts = ComID.Split('-');
string[] idParts = parts.GetValue(1).ToString().Split('.');
cid.SegmentName = parts.GetValue(0).ToString();
cid.FieldIndex = Convert.ToInt32(idParts.GetValue(0).ToString());
cid.ComponentIndex = Convert.ToInt32(idParts.GetValue(1).ToString()) - 1;
return cid;
}
/// <summary>
/// Gets a list of components from a single message by ID
/// </summary>
/// <param name="m">The message to search</param>
/// <param name="ID">The ID of the component to pull</param>
/// <returns>Returns the list of components</returns>
public static List<Component> GetByID(this Message m, string ID)
{
if (!String.IsNullOrEmpty(ID))
{
ComponentID cid = ID.ConvertID();
List<Component> returnValue = new List<Component>();
var items = from com in m.Segments.Get(cid.SegmentName) where com.GetByID(ID) != null select com.GetByID(ID);
foreach (Component c in items)
returnValue.Add(c);
return returnValue;
}
else
{
return null;
}
}
/// <summary>
/// Pulls a list of components from a list of messages based on the ID passed in
/// </summary>
/// <param name="msgs">The messages to pull from</param>
/// <param name="ID">The component ID to pull</param>
/// <returns>A list of components matching the ID passed in</returns>
public static List<Component> GetByID(this List<Message> msgs, string ID)
{
var items = from com in msgs where com.GetByID(ID) != null select com.GetByID(ID);
List<Component> coms = new List<Component>();
foreach (List<Component> cs in items)
foreach (Component c in cs)
coms.Add(c);
return coms;
}
/// <summary>
/// Gets a single component from a single message by ID and with the specified value
/// </summary>
/// <param name="m">The message to search</param>
/// <param name="ID">The ID of the component to pull</param>
/// <param name="ValueString">The value of the component to search for</param>
/// <returns>The component returned</returns>
public static Component GetByID(this Message m, string ID, string ValueString)
{
Component returnValue = new Component();
if (!String.IsNullOrEmpty(ID))
{
ComponentID cid = ID.ConvertID();
List<Segment> segments = m.Segments.Get(cid.SegmentName);
foreach (Segment s in segments)
{
Component c = s.GetByID(ID);
if (ValueString.ToUpper() == "NULL")
{
if (c != null && String.IsNullOrEmpty(c.Value))
returnValue = c;
}
else if (ValueString.ToUpper() == "!NULL")
{
if (c != null && !String.IsNullOrEmpty(c.Value))
returnValue = c;
}
else
{
if (c != null && c.Value != null)
if (c.Value.ToUpper() == ValueString.ToUpper())
returnValue = c;
}
}
}
return returnValue;
}
///// <summary>
///// Removes patient identifying information from message and replaces it with made up patient data.
///// </summary>
///// <param name="m">The message to de-identify.</param>
///// <returns>Returns the original message without identifying information.</returns>
//public static Message DeIdentify(this Message m)
//{
// Message msg = m;
// if (msg.Segments.Get("PID") != null)
// {
// string mrn = Helper.RandomMRN();
// string sex = msg.Segments.Get("PID")[0].Fields[8].Components[0].Value;
// msg.Segments.Get("PID")[0].Fields[2].Components[0].Value = mrn;
// msg.Segments.Get("PID")[0].Fields[3].Components[0].Value = mrn;
// msg.Segments.Get("PID")[0].Fields[4].Components[0].Value = mrn;
// msg.Segments.Get("PID")[0].Fields[5].Components[0].Value = Helper.RandomLastName();
// msg.Segments.Get("PID")[0].Fields[5].Components[1].Value = Helper.RandomFirstName(sex);
// msg.Segments.Get("PID")[0].Fields[6].Components[0].Value = Helper.RandomLastName();
// msg.Segments.Get("PID")[0].Fields[6].Components[1].Value = Helper.RandomFirstName("FEMALE");
// msg.Segments.Get("PID")[0].Fields[9].Components[0].Value = "";
// msg.Segments.Get("PID")[0].Fields[9].Components[1].Value = "";
// msg.Segments.Get("PID")[0].Fields[11].Components[0].Value = Helper.RandomAddress();
// msg.Segments.Get("PID")[0].Fields[13].Components[0].Value = "";
// msg.Segments.Get("PID")[0].Fields[13].Components[11].Value = "";
// msg.Segments.Get("PID")[0].Fields[14].Components[0].Value = "";
// msg.Segments.Get("PID")[0].Fields[14].Components[11].Value = "";
// msg.Segments.Get("PID")[0].Fields[18].Components[0].Value = mrn;
// msg.Segments.Get("PID")[0].Fields[19].Components[0].Value = "999999999";
// }
// return msg;
//}
/// <summary>
/// Removes patient identifying information from message and replaces it with made up patient data.
/// </summary>
/// <param name="m">The message to de-identify.</param>
/// <returns>Returns the original message without identifying information.</returns>
public static Message DeIdentify(this Message m, ILogWriter logger) {
List<Segment> segments = m.Segments.Get("PID");
if (segments.Count == 1) {
Segment s = segments[0];
List<EditItem> items = new List<EditItem>();
foreach (ConfigItem item in Configuration.LoadPHI()) {
Component phi = s.GetByID(item.Id);
if (!String.IsNullOrEmpty(phi == null ? null : phi.Value)) {
//foreach (Replacement pre in item.PreReplace) {
// if (pre.ExactMatch && phi.Value.ToLower() == pre.Match) {
// phi.Value = phi.Value.ToLower();
// phi.Value = phi.Value.Replace(pre.Match, pre.Replace);
// }
// else { //fixme - update for regex and upper/lower case
// //
// }
//}
items.Add(new EditItem(phi.ID, phi.Value, item));
}
}
//HL7Lib.Base.Component last = s.GetByID("PID-5.1");
//HL7Lib.Base.Component first = s.GetByID("PID-5.2");
//HL7Lib.Base.Component sex = s.GetByID("PID-8.1");
//HL7Lib.Base.Component address = s.GetByID("PID-11.1");
//HL7Lib.Base.Component mrn = s.GetByID("PID-18.1");
//HL7Lib.Base.Component ssn = s.GetByID("PID-19.1");
//List<EditItem> items = new List<EditItem>();
//if (!String.IsNullOrEmpty(last.Value))
// items.Add(new EditItem(last.ID, last.Value, HL7Lib.Base.Helper.RandomLastName()));
//if (!String.IsNullOrEmpty(first.Value))
// items.Add(new EditItem(first.ID, first.Value, HL7Lib.Base.Helper.RandomFirstName(sex.Value)));
//if (!String.IsNullOrEmpty(address.Value))
// items.Add(new EditItem(address.ID, address.Value, HL7Lib.Base.Helper.RandomAddress()));
//if (!String.IsNullOrEmpty(mrn.Value))
// items.Add(new EditItem(mrn.ID, mrn.Value, HL7Lib.Base.Helper.RandomMRN()));
//if (!String.IsNullOrEmpty(ssn.Value))
// items.Add(new EditItem(ssn.ID, ssn.Value, "999-99-9999"));
return EditValues(m, items, logger);
}
else {
return null;
}
}
/// <summary>
/// Removes patient identifying information from message and replaces it with made up patient data, providing a default ILogWriter
/// </summary>
/// <param name="m">The message to de-identify.</param>
/// <returns>Returns the original message without identifying information.</returns>
public static Message DeIdentify(this Message m) {
return DeIdentify(m, LogWriter.Instance);
}
/// <summary>
/// Return this message with the same fields but with random values
/// </summary>
/// <param name="m"></param>
/// <param name="logger"></param>
/// <returns></returns>
public static Message GenerateFrom(this Message m, ILogWriter logger) {
m.Segments = m.Segments.Select(s => s.GenerateFrom(logger)).ToList();
return m;
}
/// <summary>
/// Return this message with the same fields but with random values, providing a default ILogWriter
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
public static Message GenerateFrom(this Message m) {
return GenerateFrom(m, LogWriter.Instance);
}
/// <summary>
/// Modify the Fields of this Segment
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private static Segment GenerateFrom(this Segment s, ILogWriter logger) {
if (s.Name == "MSH") { // Modify the MSH segment separately
List<Field> uFields = new List<Field>(new Field[] { s.Fields[0], s.Fields[1], s.Fields[2] });
uFields.AddRange(s.Fields.GetRange(3, (s.Fields.Count - 4)).Select(f => f.GenerateFrom(logger)));
s.Fields = uFields;
}
else {
List<Field> uFields = new List<Field>(new Field[] { s.Fields[0], s.Fields[1] });
uFields.AddRange(s.Fields.GetRange(2, (s.Fields.Count - 3)).Select(f => f.GenerateFrom(logger)));
s.Fields = uFields;
}
return s;
}
/// <summary>
/// Modify the Components of this Field
/// </summary>
/// <param name="f"></param>
/// <param name="logger"></param>
/// <returns></returns>
private static Field GenerateFrom(this Field f, ILogWriter logger) {
f.Components = f.Components.Select(c => c.GenerateFrom(logger)).ToList();
return f;
}
/// <summary>
/// Modify the value of this Component
/// </summary>
/// <param name="c"></param>
/// <param name="logger"></param>
/// <returns></returns>
private static Component GenerateFrom(this Component c, ILogWriter logger) {
c.Value = String.IsNullOrEmpty(c.Value) ? c.Value : "XaaX";
return c;
}
/// <summary>
/// Edits the message string
/// </summary>
/// <param name="m">The message to edit</param>
/// <param name="items">The items to edit in the message</param>
/// <returns>The new message after editing</returns>
public static Message EditValues(this Message m, List<EditItem> items, ILogWriter logger) {
try {
string returnMsg = m.InputString;
List<EditItem> finalList = new List<EditItem>();
foreach (EditItem item in items) {
List<HL7Lib.Base.Component> com = m.GetByID(item.ComponentID);
foreach (HL7Lib.Base.Component c in com) {
//fixme - commented(2/10/17) since this method will not work without a more complex relacement method
//if (item.Config != null) { //fixme - consider updating this pre-processing within the new EditItem itself
// foreach (Replacement pre in item.Config.PreReplace) {
// if (pre.ExactMatch && c.Value.ToLower() == pre.Match) {
// c.Value = c.Value.ToLower().Replace(pre.Match, pre.Replace);
// }
// else { //fixme - update for regex and upper/lower case
// //
// }
// }
//}
//fixme - commented(2/10/17) since this method will not work without a more complex relacement method
finalList.Add(new EditItem(c.ID, c.Value, item.NewValue));
}
}
finalList.Sort((x, y) => x.OldValue.Length.CompareTo(y.OldValue.Length)); // Sort so shortest oldvalue comes first - fixme
for (int j = 0; j < finalList.Count; j++) {
if (!String.IsNullOrEmpty(finalList[j].OldValue)) {
//returnMsg = returnMsg.Replace(finalList[j].OldValue, finalList[j].NewValue);
returnMsg = Regex.Replace(returnMsg, finalList[j].OldValue, finalList[j].NewValue, RegexOptions.IgnoreCase);
// Update each other EditItem as well - fixme
for (int i = (j + 1); i < finalList.Count; i++) {
//finalList[i].OldValue = finalList[i].OldValue.Replace(finalList[j].OldValue, finalList[j].NewValue);
finalList[i].OldValue = Regex.Replace(finalList[i].OldValue, finalList[j].OldValue, finalList[j].NewValue, RegexOptions.IgnoreCase);
}
}
}
return new Message(returnMsg);
}
catch (Exception ex) {
logger.LogException(ex).Report();
return null;
}
}
/// <summary>
/// Edits the message string, providing a default ILogWriter for exception handling
/// </summary>
/// <param name="m">The message to edit</param>
/// <param name="items">The items to edit in the message</param>
/// <returns>The new message after editing</returns>
public static Message EditValues(this Message m, List<EditItem> items) {
return EditValues(m, items, LogWriter.Instance);
}
/// <summary>
/// Converts a regular date into an HL7 date string.
/// </summary>
/// <param name="d">The date to convert.</param>
/// <returns>Returns the HL7 date string.</returns>
public static string ToHL7Date(this DateTime d)
{
return d.ToString("yyyyMMddHHmmss");
}
/// <summary>
/// Converts an HL7 date string into a .Net date.
/// </summary>
/// <param name="HL7Date">The HL7 date string to convert.</param>
/// <returns>Returns the date after conversion.</returns>
public static Nullable<DateTime> FromHL7Date(this string HL7Date)
{
try
{
int y = 0;
int M = 0;
int d = 0;
int H = 0;
int m = 0;
int s = 0;
switch (HL7Date.Trim().Length)
{
case 8:
y = Convert.ToInt32(HL7Date.Trim().Substring(0, 4));
M = Convert.ToInt32(HL7Date.Trim().Substring(4, 2));
d = Convert.ToInt32(HL7Date.Trim().Substring(6, 2));
break;
case 12:
y = Convert.ToInt32(HL7Date.Trim().Substring(0, 4));
M = Convert.ToInt32(HL7Date.Trim().Substring(4, 2));
d = Convert.ToInt32(HL7Date.Trim().Substring(6, 2));
H = Convert.ToInt32(HL7Date.Trim().Substring(8, 2));
m = Convert.ToInt32(HL7Date.Trim().Substring(10, 2));
break;
case 14:
case 15:
case 16:
case 17:
case 18:
y = Convert.ToInt32(HL7Date.Trim().Substring(0, 4));
M = Convert.ToInt32(HL7Date.Trim().Substring(4, 2));
d = Convert.ToInt32(HL7Date.Trim().Substring(6, 2));
H = Convert.ToInt32(HL7Date.Trim().Substring(8, 2));
m = Convert.ToInt32(HL7Date.Trim().Substring(10, 2));
s = Convert.ToInt32(HL7Date.Trim().Substring(12, 2));
break;
}
return new DateTime(y, M, d, H, m, s);
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Gets the index of the specified field within the field list
/// </summary>
/// <param name="fList">The field list to pull</param>
/// <param name="f">The field to get the index for</param>
/// <returns>Returns the index of the specified field</returns>
public static int GetIndex(this List<Field> fList, Field f)
{
int i = fList.FindIndex(delegate(Field field) { return field.Name == f.Name; });
return i;
}
/// <summary>
/// Gets the index of the specified component within the component list
/// </summary>
/// <param name="cList">The component list to pull</param>
/// <param name="c">The component to get the index for</param>
/// <returns>Returns the index of the specified component</returns>
public static int GetIndex(this List<Component> cList, Component c)
{
int i = cList.FindIndex(delegate(Component component) { return component.Name == c.Name; });
return i;
}
/// <summary>
/// Unescapes escape sequences in the HL7 segment
/// </summary>
/// <param name="msg">The string to unescape</param>
/// <param name="EscapeCharacter">The escape character being used</param>
/// <returns>The unescaped string</returns>
public static string UnEscape(this string msg, string EscapeCharacter)
{
string returnStr = msg;
returnStr = returnStr.Replace(String.Format("{0}T{0}", EscapeCharacter), "&");
returnStr = returnStr.Replace(String.Format("{0}S{0}", EscapeCharacter), "^");
returnStr = returnStr.Replace(String.Format("{0}F{0}", EscapeCharacter), "|");
returnStr = returnStr.Replace(String.Format("{0}R{0}", EscapeCharacter), "~");
returnStr = returnStr.Replace(String.Format("{0}E{0}", EscapeCharacter), "\\");
return returnStr;
}
}
}
|
gpl-2.0
|
bylu/Test
|
wulu/2015.11.23/qipai/member/inc/config_pay_cbpayment.php
|
1517
|
<?php
require_once(DEDEMEMBER."/paycenter/cbpayment/cbpayment_config.php");
if($payment_exp[3] < 0) $payment_exp[3] = 0;
$piice_ex = $price*$payment_exp[3];
$v_oid = trim($buyid); //¶©µ¥ºÅ
if($piice_ex > 0) $price = $price+$piice_ex;
$v_amount = sprintf("%01.2f", $price); //Ö§¸¶½ð¶î
$text = $v_amount.$v_moneytype.$v_oid.$v_mid.$v_url.$key; //md5¼ÓÃÜÆ´´Õ´®,×¢Òâ˳Ðò²»Äܱä
$v_md5info = strtoupper(md5($text)); //md5º¯Êý¼ÓÃܲ¢×ª»¯³É´óд×Öĸ
$remark1 = trim($ptype);//±¸×¢×Ö¶Î1
$remark2 = trim($pname);//±¸×¢×Ö¶Î2
$v_rcvname = 'Õ¾³¤'; // ÊÕ»õÈË
$v_rcvaddr = 'ÉîÛÚ'; // ÊÕ»õµØÖ·
$v_rcvtel = '0755-83791960'; // ÊÕ»õÈ˵绰
$v_rcvpost = '100080'; // ÊÕ»õÈËÓʱà
$v_rcvmobile = '13838384381'; // ÊÕ»õÈËÊÖ»úºÅ
$v_ordername = $cfg_ml->M_UserName; // ¶©»õÈËÐÕÃû
$v_orderaddr = 'ÉîÛÚ'; // ¶©»õÈ˵ØÖ·
$v_ordertel = '0755-83791960'; // ¶©»õÈ˵绰
$v_orderpost = 518000; // ¶©»õÈËÓʱà
$v_orderemail = 'service@nps.cn'; // ¶©»õÈËÓʼþ
$v_ordermobile = 13838384581; // ¶©»õÈËÊÖ»úºÅ
$strRequestUrl = $v_post_url.'?v_mid='.$v_mid.'&v_oid='.$v_oid.'&v_amount='.$v_amount.'&v_moneytype='.$v_moneytype
.'&v_url='.$v_url.'&v_md5info='.$v_md5info.'&remark1='.$remark1.'&remark2='.$remark2;
echo '<html>
<head>
<title>תµ½ÍøÒøÔÚÏßÖ§¸¶Ò³Ãæ</title>
</head>
<body onload="document.cbpayment.submit();">
<form name="cbpayment" action="'.$strRequestUrl.'" method="post">
</form>
</body>
</html>';
exit;
|
gpl-2.0
|
em4pixeleen/Trsvideolooper
|
Trs_Video_Looper/usb_drive.py
|
1497
|
# Author: Daniel Verde
# License: GNU GPLv2, see LICENSE.txt
import glob
from usb_drive_mounter import USBDriveMounter
class USBDriveReader(object):
def __init__(self, config):
"""Create an instance of a file reader that uses the USB drive mounter
service to keep track of attached USB drives and automatically mount
them for reading videos.
"""
self._load_config(config)
self._mounter = USBDriveMounter(root=self._mount_path,
readonly=self._readonly)
self._mounter.start_monitor()
def _load_config(self, config):
self._mount_path = config.get('usb_drive', 'mount_path')
self._readonly = config.getboolean('usb_drive', 'readonly')
def search_paths(self):
"""Return a list of paths to search for files. Will return a list of all
mounted USB drives.
"""
self._mounter.mount_all()
return glob.glob(self._mount_path + '*')
def is_changed(self):
"""Return true if the file search paths have changed, like when a new
USB drive is inserted.
"""
return self._mounter.poll_changes()
def idle_message(self):
"""Return a message to display when idle and no files are found."""
return 'Inserta una unidad de almacenamiento con videos compatibles.'
def create_file_reader(config):
"""Create new file reader based on mounting USB drives."""
return USBDriveReader(config)
|
gpl-2.0
|
mineo/picard
|
picard/util/icontheme.py
|
2350
|
# -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2006 Lukáš Lalinský
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os.path
import sys
from PyQt5 import QtGui
if sys.platform == 'win32':
_search_paths = []
else:
_search_paths = [
os.path.expanduser('~/.icons'),
os.path.join(os.environ.get('XDG_DATA_DIRS', '/usr/share'), 'icons'),
'/usr/share/pixmaps',
]
_current_theme = None
if 'XDG_CURRENT_DESKTOP' in os.environ:
desktop = os.environ['XDG_CURRENT_DESKTOP'].lower()
if desktop in ('gnome', 'unity'):
_current_theme = (os.popen('gsettings get org.gnome.desktop.interface icon-theme').read().strip()[1:-1]
or None)
elif os.environ.get('KDE_FULL_SESSION'):
_current_theme = (os.popen("kreadconfig --file kdeglobals --group Icons --key Theme --default crystalsvg").read().strip()
or None)
ICON_SIZE_MENU = ('16x16',)
ICON_SIZE_TOOLBAR = ('22x22',)
ICON_SIZE_ALL = ('22x22', '16x16')
def lookup(name, size=ICON_SIZE_ALL):
icon = QtGui.QIcon()
if _current_theme:
for path in _search_paths:
for subdir in ('actions', 'places', 'devices'):
fullpath = os.path.join(path, _current_theme, size[0], subdir, name)
if os.path.exists(fullpath + '.png'):
icon.addFile(fullpath + '.png')
for s in size[1:]:
icon.addFile(os.path.join(path, _current_theme, s, subdir, name) + '.png')
return icon
for s in size:
icon.addFile('/'.join([':', 'images', s, name]) + '.png')
return icon
|
gpl-2.0
|
tahivan/php_prj
|
modules/shops/admin/payport.php
|
7910
|
<?php
/**
* @Project NUKEVIET 3.x
* @Author VINADES.,JSC (contact@vinades.vn)
* @Copyright (C) 2010 VINADES.,JSC. All rights reserved
* @Createdate 2-9-2010 14:43
*/
if( ! defined( 'NV_IS_FILE_ADMIN' ) ) die( 'Stop!!!' );
$page_title = $lang_module['setup_payment'];
$array_setting_payment = array();
// Load config template payment port in data
$sql = "SELECT * FROM `" . $db_config['prefix'] . "_" . $module_data . "_payment` ORDER BY `weight` ASC";
$result = $db->sql_query( $sql );
$all_page = $db->sql_numrows( $result );
while( $row = $db->sql_fetchrow( $result ) )
{
$array_setting_payment[$row['payment']] = $row;
}
// Load config template payment port in file
$check_config_payment = "/^([a-zA-Z0-9\-\_]+)\.config\.ini$/";
$payment_funcs = nv_scandir( NV_ROOTDIR . '/modules/' . $module_file . '/payment', $check_config_payment );
if( ! empty( $payment_funcs ) )
{
$payment_funcs = preg_replace( $check_config_payment, "\\1", $payment_funcs );
}
$array_setting_payment_key = array_keys( $array_setting_payment );
$array_payment_other = array();
foreach( $payment_funcs as $payment )
{
$xml = simplexml_load_file( NV_ROOTDIR . '/modules/' . $module_file . '/payment/' . $payment . '.config.ini' );
if( $xml !== false )
{
$xmlconfig = $xml->xpath( 'config' );
$config = $xmlconfig[0];
$array_config = array();
$array_config_title = array();
foreach( $config as $key => $value )
{
$config_lang = $value->attributes();
if( isset( $config_lang[NV_LANG_INTERFACE] ) )
{
$lang = ( string )$config_lang[NV_LANG_INTERFACE];
}
else
{
$lang = $key;
}
$array_config[$key] = trim( $value );
$array_config_title[$key] = $lang;
}
$array_payment_other[$payment] = array(
'payment' => $payment,
'paymentname' => trim( $xml->name ),
'domain' => trim( $xml->domain ),
'images_button' => trim( $xml->images_button ),
'config' => $array_config,
'titlekey' => $array_config_title
);
unset( $config, $xmlconfig, $xml );
}
}
$data_pay = array();
$payment = $nv_Request->get_string( 'payment', 'get', '' );
if( ! empty( $payment ) )
{
// Get data have not in database
if( ! in_array( $payment, $array_setting_payment_key ) )
{
if( ! empty( $array_payment_other[$payment] ) )
{
list( $weight ) = $db->sql_fetchrow( $db->sql_query( "SELECT max(`weight`) FROM `" . $db_config['prefix'] . "_" . $module_data . "_payment`" ) );
$weight = intval( $weight ) + 1;
$sql = "REPLACE INTO `" . $db_config['prefix'] . "_" . $module_data . "_payment` (`payment`, `paymentname`, `domain`, `active`, `weight`, `config`,`images_button`) VALUES (" . $db->dbescape_string( $payment ) . ", " . $db->dbescape_string( $array_payment_other[$payment]['paymentname'] ) . ", " . $db->dbescape_string( $array_payment_other[$payment]['domain'] ) . ", '0', '" . $weight . "', '" . nv_base64_encode( serialize( $array_payment_other[$payment]['config'] ) ) . "', " . $db->dbescape_string( $array_payment_other[$payment]['images_button'] ) . ")";
$db->sql_query( $sql );
$data_pay = $array_payment_other[$payment];
}
}
// Get data have in database
$sql = "SELECT * FROM `" . $db_config['prefix'] . "_" . $module_data . "_payment` WHERE payment=" . $db->dbescape( $payment );
$result = $db->sql_query( $sql );
$data_pay = $db->sql_fetchrow( $result );
}
if( $nv_Request->isset_request( 'saveconfigpaymentedit', 'post' ) )
{
$payment = filter_text_input( 'payment', 'post', '', 0 );
$paymentname = filter_text_input( 'paymentname', 'post', '', 0 );
$domain = filter_text_input( 'domain', 'post', '', 0 );
$images_button = filter_text_input( 'images_button', 'post', '', 0 );
$active = $nv_Request->get_int( 'active', 'post', 0 );
$array_config = $nv_Request->get_array( 'config', 'post', array() );
if( ! nv_is_url( $images_button ) and file_exists( NV_DOCUMENT_ROOT . $images_button ) )
{
$lu = strlen( NV_BASE_SITEURL . NV_UPLOADS_DIR . "/" . $module_name . "/" );
$images_button = substr( $images_button, $lu );
}
elseif( ! nv_is_url( $images_button ) )
{
$images_button = "";
}
$sql = "UPDATE `" . $db_config['prefix'] . "_" . $module_data . "_payment` SET `paymentname` = " . $db->dbescape_string( $paymentname ) . ", `domain` = " . $db->dbescape_string( $domain ) . ", `active`=" . $active . ", `config` = '" . nv_base64_encode( serialize( $array_config ) ) . "',`images_button`=" . $db->dbescape_string( $images_button ) . " WHERE `payment` = " . $db->dbescape_string( $payment ) . " LIMIT 1";
$db->sql_query( $sql );
nv_insert_logs( NV_LANG_DATA, $module_name, 'log_edit_product', "edit " . $paymentname, $admin_info['userid'] );
nv_del_moduleCache( $module_name );
Header( "Location: " . NV_BASE_ADMINURL . "index.php?" . NV_NAME_VARIABLE . "=" . $module_name . "&" . NV_OP_VARIABLE . "=" . $op );
}
$xtpl = new XTemplate( "payport.tpl", NV_ROOTDIR . "/themes/" . $global_config['module_theme'] . "/modules/" . $module_file );
$xtpl->assign( 'LANG', $lang_module );
$a = 0;
if( ! empty( $array_setting_payment ) and empty( $data_pay ) )
{
foreach( $array_setting_payment as $value )
{
$value['link_edit'] = NV_BASE_ADMINURL . "index.php?" . NV_NAME_VARIABLE . "=" . $module_name . "&" . NV_OP_VARIABLE . "=" . $op . "&payment=" . $value['payment'];
$value['class'] = ( $a % 2 == 0 ) ? ' class="second"' : '';
$value['active'] = ( $value['active'] == "1" ) ? "checked=\"checked\"" : "";
$value['slect_weight'] = drawselect_number( $value['payment'], 1, $all_page + 1, $value['weight'], "nv_chang_pays('" . $value['payment'] . "',this,url_change_weight,url_back);" );
$xtpl->assign( 'DATA_PM', $value );
$xtpl->parse( 'main.listpay.paymentloop' );
$a ++;
}
$xtpl->assign( 'url_back', NV_BASE_ADMINURL . "index.php?" . NV_NAME_VARIABLE . "=" . $module_name . "&" . NV_OP_VARIABLE . "=" . $op );
$xtpl->assign( 'url_change', NV_BASE_ADMINURL . "index.php?" . NV_NAME_VARIABLE . "=" . $module_name . "&" . NV_OP_VARIABLE . "=changepay" );
$xtpl->assign( 'url_active', NV_BASE_ADMINURL . "index.php?" . NV_NAME_VARIABLE . "=" . $module_name . "&" . NV_OP_VARIABLE . "=actpay" );
$xtpl->parse( 'main.listpay' );
}
if( ! empty( $array_payment_other ) && empty( $data_pay ) )
{
$a = 1;
foreach( $array_payment_other as $pay => $value )
{
if( ! in_array( $pay, $array_setting_payment_key ) )
{
$value['link_edit'] = NV_BASE_ADMINURL . "index.php?" . NV_NAME_VARIABLE . "=" . $module_name . "&" . NV_OP_VARIABLE . "=" . $op . "&payment=" . $value['payment'];
$value['class'] = ( $a % 2 == 0 ) ? ' class="second"' : '';
$value['STT'] = $a;
$xtpl->assign( 'ODATA_PM', $value );
$xtpl->parse( 'main.olistpay.opaymentloop' );
$a ++;
}
}
if( $a > 1 ) $xtpl->parse( 'main.olistpay' );
}
if( ! empty( $data_pay ) )
{
$xtpl->assign( 'EDITPAYMENT', sprintf( $lang_module['editpayment'], $data_pay['payment'] ) );
$array_config = unserialize( nv_base64_decode( $data_pay['config'] ) );
$arkey_title = array();
if( ! empty( $array_payment_other[$data_pay['payment']]['titlekey'] ) )
{
$arkey_title = $array_payment_other[$data_pay['payment']]['titlekey'];
}
foreach( $array_config as $key => $value )
{
if( isset( $arkey_title[$key] ) )
{
$lang = ( string )$arkey_title[$key];
}
else
{
$lang = $key;
}
$value = $array_config[$key];
$xtpl->assign( 'CONFIG_LANG', $lang );
$xtpl->assign( 'CONFIG_NAME', $key );
$xtpl->assign( 'CONFIG_VALUE', $value );
$xtpl->parse( 'main.paymentedit.config' );
}
$data_pay['active'] = ( $data_pay['active'] == "1" ) ? "checked=\"checked\"" : "";
$xtpl->assign( 'DATA', $data_pay );
$xtpl->parse( 'main.paymentedit' );
}
$xtpl->parse( 'main' );
$contents = $xtpl->text( 'main' );
include ( NV_ROOTDIR . "/includes/header.php" );
echo nv_admin_theme( $contents );
include ( NV_ROOTDIR . "/includes/footer.php" );
?>
|
gpl-2.0
|
pastewka/lammps
|
lib/kokkos/core/src/eti/Serial/Kokkos_Serial_ViewCopyETIInst_int_int_LayoutLeft_Rank5.cpp
|
2482
|
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Kokkos is licensed under 3-clause BSD terms of use:
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NTESS OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
#define KOKKOS_IMPL_COMPILING_LIBRARY true
#include <Kokkos_Core.hpp>
namespace Kokkos {
namespace Impl {
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int*****, LayoutLeft, LayoutRight, Serial, int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int*****, LayoutLeft, LayoutLeft, Serial, int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int*****, LayoutLeft, LayoutStride, Serial, int)
KOKKOS_IMPL_VIEWFILL_ETI_INST(int*****, LayoutLeft, Serial, int)
} // namespace Impl
} // namespace Kokkos
|
gpl-2.0
|
bmajoros/GeneZilla
|
crf.H
|
577
|
/****************************************************************
crf.H
Copyright (C)2015 William H. Majoros (martiandna@gmail.com).
This is OPEN SOURCE SOFTWARE governed by the Gnu General Public
License (GPL) version 3, as described at www.opensource.org.
****************************************************************/
#ifndef INCL_crf_H
#define INCL_crf_H
#include "BOOM/String.H"
#include "BOOM/Sequence.H"
#include "BOOM/Set.H"
#include "BOOM/SmartPointer.H"
#include "SignalType.H"
#include "ContentType.H"
#include "Labeling.H"
#include "LabelMatrix.H"
#endif
|
gpl-2.0
|
FredericFernandes/RP_Project
|
src/Core/Population.java
|
21876
|
package Core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import loader.LoaderSimulation;
public class Population {
private int numOfCenters;
private boolean pMedian = false;
private ArrayList<String[]> listOfLines;
private int initialPopSize;
private HashMap<Integer, ArrayList<Integer>> myPop;
private int numOfCities;
// double[] popFitness;
public HashMap<Integer, ArrayList<Integer>> getMyPop() {
return myPop;
}
Population(Population pOther)
{
this.pMedian = pOther.pMedian;
this.initialPopSize = pOther.initialPopSize;
this.numOfCenters = pOther.numOfCenters;
this.listOfLines = pOther.listOfLines;
this.myPop = new HashMap<Integer, ArrayList<Integer>>();
this.numOfCities=pOther.numOfCities;
}
public Population (int numOfCities, int numOfCenters, int popSize, ArrayList<String[]> listOfLines){
/* In this constructor, we RANDOMLY generate a population.
* Each individual (a line of the population matrix) is an affectation of centers to a set of cities.
* The case index in the vector is the number of the city.
*/
this.listOfLines = listOfLines;
this.numOfCenters = numOfCenters;
this.initialPopSize = popSize;
this.numOfCities=numOfCities;
Random r = new Random ();
myPop = new HashMap<Integer, ArrayList<Integer>>();
for (int i=0 ; i<popSize; i++)
myPop.put(i, new ArrayList<Integer>(numOfCities));
if (numOfCenters == -1){
for (int i=0;i<myPop.size();i++){
for(int j=0;j<numOfCities;j++){
myPop.get(i).add(r.nextInt(2));
}
}
}else{
// Here you treat the case where a certain number of center is required
pMedian = true;
for (int i=0;i<myPop.size();i++){
for(int j=0;j<numOfCities;j++){
myPop.get(i).add(0);
}
}
for (int i=0;i<myPop.size();i++){
int j=0;int var = 0;
//for(int j=0;j<numOfCenters;j++){
while(j<numOfCenters){
var = r.nextInt(numOfCities);
if(myPop.get(i).get(var) !=1){
myPop.get(i).set(var,1);
j++;
}
}
//}
// If there are less than p centers, the missing centers must be added
}
}
}
public Population (){
myPop = new HashMap<Integer, ArrayList<Integer>>();
}
// public void printPop (){
// System.out.println("MODE p-median " + pMedian);
// for (int i=0;i<this.myPop.size();i++){
// System.out.print("[" + i + "] : [ ");
// //System.out.println(this.myPop[i].toString());
// for (int j=0;j<this.myPop.get(i).size()-1;j++)
// System.out.print(this.myPop.get(i).get(j) + " | ");
//
// System.out.println(this.myPop.get(i).get(this.myPop.get(i).size()-1) +" ]");
// }
// }
public Population getSolution(){
HashMap<Integer, HashMap<Integer, ArrayList<Couple>>> mMAP = this.affectCitiesInPop();
Population nextIterationPop = this.arrangePop(mMAP);
System.out.println("BEST SOLUTION FOUND = " + nextIterationPop.myPop.get(0));
return nextIterationPop;
}
public ArrayList<Integer> getAffectationCenters()
{
HashMap<Integer, HashMap<Integer, ArrayList<Couple>>> mMAP = this.affectCitiesInPop();
Population nextIterationPop = this.arrangePop(mMAP);
System.out.println("BEST SOL = " + nextIterationPop.myPop.get(0));
return (nextIterationPop.myPop.get(0));
}
public HashMap<Integer, ArrayList<Couple>> getOtherAffectation()
{
HashMap<Integer, HashMap<Integer, ArrayList<Couple>>> mMAP = this.affectCitiesInPop();
//Population nextIterationPop = this.arrangePop(mMAP);
HashMap<Integer, ArrayList<Integer>> arrangedPop = new HashMap<Integer, ArrayList<Integer>>();
Population pp = new Population(this);
ArrayList<Double> fitnessList = this.getFitnessList(mMAP);
ArrayList<Double> sortedFitnessList = new ArrayList<Double>(fitnessList);
Collections.sort(sortedFitnessList);
//System.out.println(" INITIAL Fitness List : " + fitnessList);
//System.out.println(" SORTED Fitness List : " + sortedFitnessList);
int[] indexes = new int[sortedFitnessList.size()];
for (int i = 0; i < this.initialPopSize; i++){
indexes[i] = fitnessList.indexOf(sortedFitnessList.get(i));
arrangedPop.put(i, this.myPop.get(indexes[i]));
}
//System.out.println("Index list = " + Arrays.toString(indexes));
for (int i = 0; i < arrangedPop.size(); i++){
pp.myPop.put(i, arrangedPop.get(i));
}
System.out.println("THE OTHER PART OF THE SOLUTION = " + mMAP.get(indexes[0]));
return mMAP.get(indexes[0]);
}
public ArrayList<Double> getFitnessList (HashMap<Integer, HashMap<Integer, ArrayList<Couple>>> mMAP){
double fit = 0;
ArrayList<Double> fitnessList = new ArrayList<Double>();
ArrayList<Double> costsList =getCostsList();
// - delete the parameter befoire uncommenting this : HashMap<Integer, HashMap<Integer, ArrayList<Couple>>> mMAP = this.affectCitiesInPop(fl, listOfLines);
Set mMAPKeySet = mMAP.keySet();
for(int i=0; i<this.myPop.size(); i++){
for(int j=0 ; j<this.myPop.get(i).size() ; j++){
fit += myPop.get(i).get(j) * costsList.get(j);
}
// System.out.println("\n======================================================================================\n");
// System.out.println("First part of the fitness fot " +i + " is :"+ fit);
// First part is correctecly calculated
Iterator it = mMAPKeySet.iterator();
for (int j=0; j<mMAP.size(); j++){
while(it.hasNext()){
int indivIndex = (int) it.next();
if(indivIndex == i){
//System.out.println("Checking for managing costs in the individual " + indivIndex);
Set insideKeySet = mMAP.get(indivIndex).keySet();
Iterator it1 = insideKeySet.iterator();
while(it1.hasNext()){
int managingCity = (int) it1.next();
//System.out.println(managingCity + " can manage up to " + mMAP.get(indivIndex).get(managingCity).size() + " in the individual " + indivIndex);
for(int k=0;k<mMAP.get(indivIndex).get(managingCity).size();k++){
//System.out.println("Individual "+ i +": ADD " + mMAP.get(indivIndex).get(managingCity).get(k).getR());
fit += mMAP.get(indivIndex).get(managingCity).get(k).getR();
}
}
}
}
}
fitnessList.add(fit);
fit = 0;
}
//this.printPop();
return fitnessList;
}
public HashMap<Integer, HashMap<Integer, ArrayList<Couple>>> affectCitiesInPop(){
HashMap<Integer, HashMap<Integer, ArrayList<Couple>>> mMAP = new HashMap<Integer, HashMap<Integer, ArrayList<Couple>>>();
mMAP = new HashMap<Integer, HashMap<Integer, ArrayList<Couple>>>();
// mMAP = management Map in All Population
ArrayList<Integer> obligatoryCities = new ArrayList<Integer>();
HashMap<Integer, ArrayList<Couple>> affectationMap = getAffectationMap();
Set affectationMapKeySet = affectationMap.keySet(); // a Set of cities who can manage ; we use them to access the general affectation Map
for(int i = 0;i<myPop.get(0).size();i++){
if(!affectationMap.containsKey(i)){
obligatoryCities.add(i);
}
}
//System.out.println(" Affect cities in Population of size = " +myPop.size());
//System.out.println("Obligatory Cities are : " + obligatoryCities);
// System.out.println("Population before affecting == it shouldn't have a problem");
// this.printPop();
if(pMedian){
if(numOfCenters < obligatoryCities.size()){
System.out.println("It is Impossible to solve this problem with only " + numOfCenters + "!");
}else{
for(int i=0;i<myPop.size();i++){ // for every indivdual in the population ; fix obligatoryCities
for(int j=0; j<myPop.get(i).size(); j++){
if(obligatoryCities.contains(j))
myPop.get(i).set(j,1);
}
}
for(int i=0;i<this.myPop.size();i++){ // for every indivdual in the population
HashMap<Integer, ArrayList<Couple>> mMAPValue = new HashMap<Integer, ArrayList<Couple>>(); // the value part in mMAP
int nCI = 0;
if(!mMAP.containsKey(i)){
mMAP.put(i, mMAPValue);
}
for(int j=0; j<this.myPop.get(i).size(); j++){
if(obligatoryCities.contains(j) && myPop.get(i).get(j) == 0){
myPop.get(i).set(j, 1);
}
if(myPop.get(i).get(j) == 1)
nCI++;
}
if(nCI>numOfCenters){ // This individual has too many centers
for(int k=numOfCenters; k<nCI; k++){
boolean ok = false;
for(int j=0; j<myPop.get(i).size(); j++){ // for every city in the vector of the individual "i"
if(!ok && myPop.get(i).get(j) == 1 && !obligatoryCities.contains(j)){
myPop.get(i).set(j, 0);
ok = true;
}
}
}
}
if(nCI<numOfCenters){ // This individuals doesn't have enough centers
for(int k=nCI; k<numOfCenters; k++){
boolean ok = false;
for(int j=0; j<myPop.get(i).size(); j++){ // for every city in the vector of the individual "i"
if(!ok && myPop.get(i).get(j) == 0){
myPop.get(i).set(j, 1);
ok = true;
}
}
}
}
}
}
}
for(int i=0;i<this.myPop.size();i++){ // for every indivdual in the population
HashMap<Integer, ArrayList<Couple>> mMAPValue = new HashMap<Integer, ArrayList<Couple>>(); // the value part in mMAP
int nCI = 0;
for(int j=0; j<this.myPop.get(i).size(); j++){
if(myPop.get(i).get(j) == 1)
nCI++;
}
//System.out.println("======================================= " + i +" ===============================================");
if(!mMAP.containsKey(i)){
mMAP.put(i, mMAPValue);
}
double minCost = -1;
int managingCity = -1;
for(int j=0; j<this.myPop.get(i).size(); j++){ // for every city in the vector of the individual "i"
if(this.myPop.get(i).get(j) == 0){ // only cities with no center
//System.out.println("The city " + j + " doesn't have a center !");
Iterator it = affectationMapKeySet.iterator(); // iterate on the list of cities that can manage other cities
while(it.hasNext()){
int cc = (int) it.next(); // the city in the affectation Map that can manage
if(cc != j){
if(this.myPop.get(i).get(cc) == 1){ // only cities with a center can manage another center
//System.out.println("Checking if " + cc + " can manage " + j);
for (int k=0; k<affectationMap.get(cc).size(); k++){ // check in the affectationMap for the city with the lowest management cost for the city "j"
if (affectationMap.get(cc).get(k).getL() == j){
//System.out.println(cc + " can manage " + j + " with a cost of " + affectationMap.get(cc).get(k).getR());
if(managingCity == -1){
minCost = affectationMap.get(cc).get(k).getR();
managingCity = cc;
}else{
if(affectationMap.get(cc).get(k).getR() < minCost){
minCost = affectationMap.get(cc).get(k).getR();
managingCity = cc;
}
}
}
}
}
}
}
if(managingCity == -1){
//System.out.println(j + " can't be managed by none of the existing cities ==> " + "must affect a center to it !");
this.myPop.get(i).set(j, 1);
nCI++;
//System.out.println(" the city (" + j + ") has a center now === PROOF: its valut in the Pop is " + this.myPop.get(i) );
//this.printPop();
}else{
//System.out.println("The minimum cost for managing " + j + " is " + minCost + " by " + managingCity);
Couple couple = new Couple(j,minCost);
if(!mMAP.get(i).containsKey(managingCity)){
mMAP.get(i).put(managingCity, new ArrayList<Couple>());}
mMAP.get(i).get(managingCity).add(couple);
minCost = -1;
managingCity = -1;
}
}
}
//System.out.println("The hashMap for the individual " + i + " : "+ mMAP.get(i));
}
//this.printPop();
return mMAP;
}
public Population arrangePop( HashMap<Integer, HashMap<Integer, ArrayList<Couple>>> mMAP){
HashMap<Integer, ArrayList<Integer>> arrangedPop = new HashMap<Integer, ArrayList<Integer>>();
Population pp = new Population(this);
//System.out.println("ARRANGE POP_____SIZE : " + this.myPop.size());
ArrayList<Double> fitnessList = this.getFitnessList(mMAP);
ArrayList<Double> sortedFitnessList = new ArrayList<Double>(fitnessList);
Collections.sort(sortedFitnessList);
//System.out.println(" INITIAL Fitness List : " + fitnessList);
//System.out.println(" SORTED Fitness List : " + sortedFitnessList);
int[] indexes = new int[sortedFitnessList.size()];
for (int i = 0; i < this.initialPopSize; i++){
indexes[i] = fitnessList.indexOf(sortedFitnessList.get(i));
arrangedPop.put(i, this.myPop.get(indexes[i]));
}
//System.out.println("Index list = " + Arrays.toString(indexes));
for (int i = 0; i < arrangedPop.size(); i++){
pp.myPop.put(i, arrangedPop.get(i));
}
//System.out.println("BEST SOL (individual " + indexes[0] + ") = " + pp.myPop.get(0) + " With a cost of : " + sortedFitnessList.get(0));
//System.out.println("THE OTHER PART OF THE SOLUTION = " + mMAP.get(indexes[0]));
//pp.printPop();
//System.out.println("After arange Pop : size = "+pp.myPop.size() + "== initialPopSize = " + this.initialPopSize);
return pp;
}
public Population selectionBest (double percentage, ArrayList<Double> fitnessList){
Population selectedPop = new Population(this);
ArrayList<Double> sortedFitnessList = new ArrayList<Double>(fitnessList);
Collections.sort(sortedFitnessList);
//System.out.println("Fitness list : " + fitnessList);
//System.out.println("Sorted fitness list : " + sortedFitnessList);
int[] indexes = new int[(int) Math.round (sortedFitnessList.size()*percentage)];
for (int i = 0; i < indexes.length; i++){
indexes[i] = fitnessList.indexOf(sortedFitnessList.get(i));
selectedPop.myPop.put(i, this.myPop.get(indexes[i]));
}
//System.out.println("Indexes are : " + Arrays.toString(indexes) + "\n");
// for (int i = 0; i < indexes.length ; i++)
// System.out.println(fitnessList.get(indexes[i]));
//System.out.println("Selected Pop contains " + selectedPop.myPop.size() + " individuals from initial " + this.myPop.size());
return selectedPop;
}
public Population crossOver (int crossOverIndex){
if(crossOverIndex < 1 || (crossOverIndex > (myPop.get(0).size()-2)))
System.out.println("Corssover Impossible ===> position out of Bound");
int index = myPop.size();
//System.out.println(" size before crossover " + index);
Population offSprings = new Population(this);
HashMap<Integer, ArrayList<Integer>> offSpringsMap = new HashMap<Integer, ArrayList<Integer>>();
ArrayList<Integer> p1 = new ArrayList<Integer>();
ArrayList<Integer> p2 = new ArrayList<Integer>();
ArrayList<Integer> c1;
ArrayList<Integer> c2;
if(myPop.size() % 2 == 0){
for (int i = 0; i < myPop.size()-1; i=i+2){
c1 = new ArrayList<Integer>();
c2 = new ArrayList<Integer>();
p1 = myPop.get(i);
p2 = myPop.get(i+1);
for (int j = 0; j<crossOverIndex; j++){
c1.add(p1.get(j));
c2.add(p2.get(j));
}
for (int j = crossOverIndex; j<p1.size(); j++){
c2.add(p1.get(j));
c1.add(p2.get(j));
}
offSpringsMap.put(index+i, c1);
offSpringsMap.put(index+i+1, c2);
// System.out.println((index+i) + " "+ offSpringsMap.get(index+i));
// System.out.println((index+i+1) + " "+ offSpringsMap.get(index+i+1));
}
}else{
for (int i = 0; i < myPop.size()-2; i++){
c1 = new ArrayList<Integer>();
c2 = new ArrayList<Integer>();
p1 = myPop.get(i);
p2 = myPop.get(i+1);
for (int j = 0; j<crossOverIndex; j++){
c1.add(p1.get(j));
c2.add(p2.get(j));
}
for (int j = crossOverIndex; j<p1.size(); j++){
c2.add(p1.get(j));
c1.add(p2.get(j));
}
offSpringsMap.put(index, c1);
offSpringsMap.put(index+1, c2);
}
}
if(pMedian){
for(int i=0;i<offSpringsMap.size(); i++){
ArrayList<Integer> a = new ArrayList<Integer>();
for(int j=0; j<offSpringsMap.get(index+i).size();j++){
if(offSpringsMap.get(index+i).get(j) == 1)
a.add(j);
}
if(a.size()>this.numOfCenters){
// adapt the number of centers in this individual to "p"
//System.out.println("The individual : " + (index+i) + offSpringsMap.get(index+i) + a.size() +" ==>"+ "has too many Centers");
for(int j=numOfCenters;j<a.size();j++){
Random r = new Random();
int k = r.nextInt(a.size());
while(offSpringsMap.get(index+i).get(a.get(k)) ==0){
k = r.nextInt(a.size());
}
offSpringsMap.get(index+i).set(a.get(k), 0);
}
//System.out.println("The individual : " + (index+i) + offSpringsMap.get(index+i) + " Fixed");
}
//System.out.println((index+i) + " number of ones = " + a.size());
if(a.size()<this.numOfCenters){
// adapt the number of centers in this individual to "p"
//System.out.println("The individual " +(index+i) + offSpringsMap.get(index+i) + a.size() + " has less Centers");
for(int j=a.size();j<this.numOfCenters;j++){
Random r = new Random();
int k = r.nextInt(offSpringsMap.get(index+i).size());
while(offSpringsMap.get(index+i).get(k) ==1){
k = r.nextInt(offSpringsMap.get(index+i).size());
}
offSpringsMap.get(index+i).set(k, 1);
}
//System.out.println("The individual " + (index+i) + offSpringsMap.get(index+i) + " after fixing ");
}
}
}
offSprings.myPop.putAll(myPop);
offSprings.myPop.putAll(offSpringsMap);
//System.out.println("OffSprings Size : " + offSprings.myPop.size());
return offSprings;
}
public Population randomMutation (double prob){
// probability is between 0 and 1
//System.out.println(" Mutation procces may occur on " + this.myPop.size() + " individuals ");
Population newPop = new Population(this);
for (int i = 0; i < this.myPop.size(); i++){
newPop.myPop.put(i, myPop.get(i));
Random r = new Random();
double pb = r.nextInt(100)/100;
if (pb<=prob){
r = new Random();
//System.out.println(newPop.myPop.get(i).size());
int mutationIndex = (int) r.nextInt(newPop.myPop.get(i).size());
if(mutationIndex<0)
mutationIndex = 0;
if(mutationIndex>=newPop.myPop.get(i).size())
mutationIndex = newPop.myPop.get(i).size();
//System.out.println("About to do a flip on the " + mutationIndex + "position of the individual number " + i + " " + newPop.myPop.get(i));
newPop.myPop.get(i).set(mutationIndex, 1 - newPop.myPop.get(i).get(mutationIndex));
//System.out.println("After Mutation : " + newPop.myPop.get(i));
}
}
if(this.pMedian){
for(int i=0;i<newPop.myPop.size(); i++){
ArrayList<Integer> a = new ArrayList<Integer>();
for(int j=0; j<newPop.myPop.get(i).size();j++){
if(newPop.myPop.get(i).get(j) == 1)
a.add(j);
}
if(a.size()>this.numOfCenters){
// adapt the number of centers in this individual to "p"
//System.out.println("The individual : " + (i) + newPop.myPop.get(i) + a.size() +" ==>"+ "has too many Centers" + "delete" + (a.size()-numOfCenters));
for(int j=numOfCenters;j<a.size();j++){
Random r = new Random();
int k = r.nextInt(a.size());
while(newPop.myPop.get(i).get(a.get(k)) ==0){
k = r.nextInt(a.size());
}
newPop.myPop.get(i).set(a.get(k), 0);
}
//System.out.println("The individual : " + (i) + newPop.myPop.get(i) + " Fixed");
}
//System.out.println((i) + " number of ones = " + a.size());
if(a.size()<this.numOfCenters){
// adapt the number of centers in this individual to "p"
//System.out.println("The individual " +(i) + newPop.myPop.get(i) + a.size() + " has less Centers");
for(int j=a.size();j<this.numOfCenters;j++){
Random r = new Random();
int k = r.nextInt(newPop.myPop.get(i).size());
while(newPop.myPop.get(i).get(k) ==1){
k = r.nextInt(newPop.myPop.get(i).size());
}
newPop.myPop.get(i).set(k, 1);
}
//System.out.println("The individual " + (i) + newPop.myPop.get(i) + " after fixing ");
}
}
}
//System.out.println("New Pop after mutation : size = " + newPop.myPop.size());
return newPop;
}
public int size()
{
return myPop.size();
}
public HashMap<Integer, ArrayList<Couple>> getAffectationMap (){
// The couple in this case is : This city that can BE MANAGED by the city in the key argument and the cost of this management
HashMap<Integer, ArrayList<Couple>> affectationMap = new HashMap<Integer, ArrayList<Couple>>();
int numOfCities = Integer.valueOf(listOfLines.get(0)[0]);
int startingIndex = numOfCities + 1;
Couple couple;
for(int i=startingIndex; i<listOfLines.size()-1; i++){
// System.out.print(myList.get(i)[0] + " ");
// System.out.print(myList.get(i)[1] + " ");
// System.out.print(myList.get(i)[2] + "\n");
if(!affectationMap.containsKey(Integer.valueOf(listOfLines.get(i)[0])) && Integer.valueOf(listOfLines.get(i)[0]) != -1 ){
affectationMap.put(Integer.valueOf(listOfLines.get(i)[0]), new ArrayList<Couple>());
}
couple = new Couple(Integer.valueOf(listOfLines.get(i)[1]), Double.valueOf(listOfLines.get(i)[2]));
affectationMap.get(Integer.valueOf(listOfLines.get(i)[0])).add(couple);
}
return affectationMap;
}
public ArrayList<Double> getCostsList(){
ArrayList<Double> installationCostsList = new ArrayList<Double>();
for(int i=1; i<=numOfCities; i++){
installationCostsList.add(Double.valueOf(listOfLines.get(i)[2]));
}
return installationCostsList;
}
public double getResult()
{
HashMap<Integer, HashMap<Integer, ArrayList<Couple>>> mMAP = this.affectCitiesInPop();
ArrayList<Double> fitnessList = this.getFitnessList(mMAP);
ArrayList<Double> sortedFitnessList = new ArrayList<Double>(fitnessList);
Collections.sort(sortedFitnessList);
return sortedFitnessList.get(0);
}
}
|
gpl-2.0
|
AStoker/requiredLabel
|
requiredLabel.js
|
2994
|
define(['jquery', 'knockout'],
function ($, ko) {
ko.bindingHandlers.requiredLabel = {
init: function (element, valueAccessor) {
// Initially create the required element next to the label
var valUnwraped = ko.unwrap(valueAccessor()),
isRequired = ko.unwrap(valUnwraped.isRequired),
requiredColor = ko.unwrap(valUnwraped.color) || 'red',
$requiredStateElem = $("<span title='Required' data-requiredLabel='iconState' style='display: none; color: "+requiredColor+"; margin-left: 4px; font-weight: bold; height: .8em; width: .8em;'>*</span>").data('requiredLabelOriginator', $(element)),
$wrappedLabelText = $("<span>"+$(element).html().trim()+"</span>");
$(element).html($wrappedLabelText[0])
.append($requiredStateElem);
},
update: function (element, valueAccessor) {
// Whenever the value subsequently changes (including on first render/after init)
var valUnwraped = ko.unwrap(valueAccessor()),
isRequired = ko.unwrap(valUnwraped.isRequired),
completedState = ko.unwrap(valUnwraped.completed),
completedColor = ko.unwrap(valUnwraped.completedColor) || 'green',
$elementState = $(element).find("[data-requiredLabel='iconState']"),
visibilityTransitionFunc = valUnwraped.visibilityTransition;
if (!completedState) {
$elementState.html("*");
} else {
$elementState.html("<svg style='fill: green; width: 100%; height: 100%;' viewBox='0 0 500 500'>"+
"<path fill='"+completedColor+"' d='M249.5,1C112,1,1,112,1,249.5S112,498,249.5,498S498,387,498,249.5S386.4,1,249.5,1z M385,136.5"+
"c-33.2,47.8-113,170.8-146.2,218.6c-5.3,8-12,9.3-19.9,3.3c-34.6-23.3-68.4-47.2-101.7-70.4c-8.6-6-9.3-12-3.3-20.6"+
"c4-6,8-11.3,12-17.3c6-8,12-9.3,20.6-3.3c21.9,15.3,43.2,29.9,64.5,45.2c2,1.3,4,2.7,6.6,4.7c2-2.7,3.3-4.7,4.7-6.6"+
"c24.6-34.6,95-144.8,119.6-180.1c8-11.3,13.3-12,23.9-4c5.3,3.3,10,7.3,15.3,10.6C389.7,121.9,391,127.9,385,136.5z' />"+
"</svg>");
}
if(isRequired == null || isRequired == true){ //If null or true
if($.isFunction(visibilityTransitionFunc)){
visibilityTransitionFunc($elementState[0]);
}
$elementState.css({"display": "inline-block"});
} else { //if false
if($.isFunction(visibilityTransitionFunc)){
visibilityTransitionFunc($elementState[0]);
}
$elementState.css({"display": "none"});
}
}
};
});
|
gpl-2.0
|
reibach/phpReibach
|
config/edit_company.php
|
7739
|
<?php
/*
edit_company.php
phpRechnung - is easy-to-use Web-based multilingual accounting software.
Copyright (C) 2001 - 2015 Edy Corak < edy at loenshotel dot de >
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
require_once("../include/phprechnung.inc.php");
require_once("../include/smarty.inc.php");
CheckUser();
CheckAdminGroup1();
CheckSession();
$ArrayValue = CheckArrayValue($_REQUEST);
foreach($ArrayValue as $key => $val)
{
$$key = $val;
$smarty->assign("$key",$val);
}
if(!is_numeric($settingID) || $settingID <= 0 )
{
die(header("Location: $web"));
}
$smarty->assign("Title","$a[settings] - $a[edit] - $a[company_settings]");
$smarty->assign("Basic_Settings","$a[basic_settings]");
$smarty->assign("Company_Settings","$a[company_settings]");
$smarty->assign("PDF_Settings","$a[pdf_settings]");
$smarty->assign("Company_Name","$a[company_name]");
$smarty->assign("Company_Address","$a[company_address]");
$smarty->assign("Company_Postal","$a[company_postal]");
$smarty->assign("Company_City","$a[company_city]");
$smarty->assign("Company_Country","$a[company_country]");
$smarty->assign("Company_Phone","$a[company_phone]");
$smarty->assign("Company_Fax","$a[company_fax]");
$smarty->assign("Company_Email","$a[company_email]");
$smarty->assign("Company_URL","$a[company_url]");
$smarty->assign("Company_Mobile","$a[company_mobile]");
$smarty->assign("Company_Currency","$a[company_currency]");
$smarty->assign("Company_Tax_Free","$a[company_tax_free]");
$smarty->assign("Sales_Prices","$a[sales_prices]");
$smarty->assign("Company_Taxnr","$a[company_taxnr]");
$smarty->assign("Business_Taxnr","$a[business_taxnr]");
$smarty->assign("Bank_Name","$a[bank_name]");
$smarty->assign("Bank_Account","$a[bank_account]");
$smarty->assign("Bank_Number","$a[bank_number]");
$smarty->assign("Bank_IBAN","$a[bank_iban]");
$smarty->assign("Bank_BIC","$a[bank_bic]");
// Database connection
//
DBConnect();
// Get company related entrys from setting table
//
$query = $db->Execute("SELECT DATE_FORMAT(COMPANY_DATE,'%d.%m.%Y') AS COMPANY_DATE, COMPANY_NAME, COMPANY_ADDRESS, COMPANY_POSTAL, COMPANY_CITY, COMPANY_COUNTRY, COMPANY_PHONE,
COMPANY_FAX, COMPANY_EMAIL, COMPANY_URL, COMPANY_MOBILE, COMPANY_TAXNR, COMPANY_BUSINESS_TAXNR, COMPANY_BANKNAME, COMPANY_BANKACCOUNT, COMPANY_BANKNUMBER, COMPANY_BANKIBAN, COMPANY_BANKBIC, COMPANY_CURRENCY,
COMPANY_SALESPRICE, TAX_FREE, SETTINGID FROM setting WHERE SETTINGID=$settingID");
$i = 0;
$str = "";
foreach ($query as $f) {
$str = $str.$f['COMPANY_MOBILE']."-----".$i."<p></p>";
echo $str;
$i++;
foreach ($f as $key => $value) {
//echo "Schlüssel: $key; Wert: $value<br />\n";
}
foreach ($f as $v2) {
//echo "$v2\n";
}
}
//print_r $query;
if (!$query)
print($db->ErrorMsg());
else
foreach($query as $f)
{
//$test = var_dump ($f);
//print_r $f;
echo $f['COMPANY_SALESPRICE'];
$sp = $f['COMPANY_SALESPRICE'];
//var_dump ($sp);
//exit;
if (empty($D_Company_Date))
{
$smarty->assign("D_Company_Date",$f['COMPANY_DATE']);
}
else
{
$smarty->assign("D_Company_Date","$D_Company_Date");
}
if (empty($D_Company_Name))
{
$smarty->assign("D_Company_Name",$f['COMPANY_NAME']);
}
else
{
$smarty->assign("D_Company_Name","$D_Company_Name");
}
if (empty($D_Company_Address))
{
$smarty->assign("D_Company_Address",$f['COMPANY_ADDRESS']);
}
else
{
$smarty->assign("D_Company_Address","$D_Company_Address");
}
if (empty($D_Company_Postal))
{
$smarty->assign("D_Company_Postal",$f['COMPANY_POSTAL']);
}
else
{
$smarty->assign("D_Company_Postal","$D_Company_Postal");
}
if (empty($D_Company_City))
{
$smarty->assign("D_Company_City",$f['COMPANY_CITY']);
}
else
{
$smarty->assign("D_Company_City","$D_Company_City");
}
if (empty($D_Company_Country))
{
$smarty->assign("D_Company_Country",$f['COMPANY_COUNTRY']);
}
else
{
$smarty->assign("D_Company_Country","$D_Company_Country");
}
if (empty($D_Company_Phone))
{
$smarty->assign("D_Company_Phone",$f['COMPANY_PHONE']);
}
else
{
$smarty->assign("D_Company_Phone","$D_Company_Phone");
}
if (empty($D_Company_Fax))
{
$smarty->assign("D_Company_Fax",$f['COMPANY_FAX']);
}
else
{
$smarty->assign("D_Company_Fax","$D_Company_Fax");
}
if (empty($D_Company_Email))
{
$smarty->assign("D_Company_Email",$f['COMPANY_EMAIL']);
}
else
{
$smarty->assign("D_Company_Email","$D_Company_Email");
}
if (empty($D_Company_URL))
{
$smarty->assign("D_Company_URL",$f['COMPANY_URL']);
}
else
{
$smarty->assign("D_Company_URL","$D_Company_URL");
}
if (empty($D_Company_Mobile))
{
$smarty->assign("D_Company_Mobile",$f['COMPANY_MOBILE']);
//$smarty->assign("D_Company_Mobile","TESTME");
}
else
{
$smarty->assign("D_Company_Mobile","$D_Company_Mobile");
//$smarty->assign("D_Company_Mobile","TEST");
}
if (empty($D_Company_Currency))
{
$smarty->assign("D_Company_Currency",$f['COMPANY_CURRENCY']);
}
else
{
$smarty->assign("D_Company_Currency","$D_Company_Currency");
}
if (empty($D_Company_Tax_Free))
{
$smarty->assign("D_Company_Tax_Free",$f['TAX_FREE']);
}
else
{
$smarty->assign("D_Company_Tax_Free","$D_Company_Tax_Free");
}
if (empty($D_Sales_Prices))
{
$smarty->assign("D_Sales_Prices",$f['COMPANY_SALESPRICE']);
}
else
{
$smarty->assign("D_Sales_Prices","$D_Sales_Prices");
}
if (empty($D_Company_Taxnr))
{
$smarty->assign("D_Company_Taxnr",$f['COMPANY_TAXNR']);
}
else
{
$smarty->assign("D_Company_Taxnr","$D_Company_Taxnr");
}
if (empty($D_Business_Taxnr))
{
$smarty->assign("D_Business_Taxnr",$f['COMPANY_BUSINESS_TAXNR']);
}
else
{
$smarty->assign("D_Business_Taxnr","$D_Business_Taxnr");
}
if (empty($D_Bank_Name))
{
$smarty->assign("D_Bank_Name",$f['COMPANY_BANKNAME']);
}
else
{
$smarty->assign("D_Bank_Name","$D_Bank_Name");
}
if (empty($D_Bank_Account))
{
$smarty->assign("D_Bank_Account",$f['COMPANY_BANKACCOUNT']);
}
else
{
$smarty->assign("D_Bank_Account","$D_Bank_Account");
}
if (empty($D_Bank_Number))
{
$smarty->assign("D_Bank_Number",$f['COMPANY_BANKNUMBER']);
}
else
{
$smarty->assign("D_Bank_Number","$D_Bank_Number");
}
if (empty($D_Bank_IBAN))
{
$smarty->assign("D_Bank_IBAN",$f['COMPANY_BANKIBAN']);
}
else
{
$smarty->assign("D_Bank_IBAN","$D_Bank_IBAN");
}
if (empty($D_Bank_BIC))
{
$smarty->assign("D_Bank_BIC",$f['COMPANY_BANKBIC']);
}
else
{
$smarty->assign("D_Bank_BIC","$D_Bank_BIC");
}
}
// Check if there are any saved invoices
//
$query1 = $db->Execute("SELECT INVOICEID FROM invoice");
$numrows1 = $query1->RowCount();
if ($numrows1)
{
$smarty->assign("InvoiceAvailable","1");
$smarty->assign("DisplaySalesPrice","$sales_price[$sp]");
}
// Save options in $net_gross_values
//
$smarty->assign("sales_price_values",array($sales_price));
$smarty->assign("choice_yes_no",array($choice_yes_no));
$smarty->display('config/edit_company.tpl');
?>
|
gpl-2.0
|
tuliolages/OpenRedu
|
app/controllers/plans_controller.rb
|
2671
|
# -*- encoding : utf-8 -*-
class PlansController < BaseController
before_filter :find_course_environment, :except => [:index, :create]
load_and_authorize_resource :plan, :only => [:options], :through => :user
def create
@user = load_and_authorize_if_param(User, params[:user_id])
@partner = load_and_authorize_if_param(Partner, params[:partner_id])
if client_id = params[:client_id]
@client = @partner.partner_environment_associations.find(client_id)
end
@environment = Environment.find(params[:environment_id])
if params[:course_id]
@course = @environment.courses.find_by_path(params[:course_id])
end
@plan = @course.try(:plan) || @environment.try(:plan)
authorize! :migrate, @plan
@new_plan = Plan.from_preset(params[:new_plan].to_sym, params[:type])
@plan.migrate_to @new_plan
flash[:notice] = "O novo plano foi assinado, você pode ver a fatura abaixo."
respond_to do |format|
if @client
format.html do
redirect_to partner_client_plan_invoices_path(@partner, @client,
@new_plan)
end
else
format.html do
redirect_to plan_invoices_path(@new_plan)
end
end
end
end
def index
@user = load_and_authorize_if_param(User, params[:user_id])
@plans = @user.plans.current.includes(:billable)
respond_to do |format|
format.html { render :layout => 'new_application' }
end
end
def options
@partner = load_and_authorize_if_param(Partner, params[:partner_id])
authorize! :migrate, @plan
@user = @plan.user
if params[:client_id]
@client = @partner.partner_environment_associations.find(params[:client_id])
end
@billable_url = if @plan.billable.is_a? Environment
environment_url(@plan.billable)
elsif @plan.billable.is_a? Course
environment_course_url(@plan.billable.environment,
@plan.billable)
end
respond_to do |format|
if @client
format.html { render "partner_environment_associations/plans/options" }
else
format.html { render :layout => 'new_application' }
end
end
end
protected
def find_course_environment
@plan = Plan.find(params[:id])
if @plan.billable_type == 'Course'
@course = @plan.billable
@environment = @course.environment
end
end
def load_and_authorize_if_param(klass, id)
if id
instance = klass.find(id)
authorize! :manage, instance
instance
end
end
end
|
gpl-2.0
|
UniversityOfAlberta/GrandForum
|
Classes/CCCVTK/common-cv.lib.php
|
34886
|
<?php
/*
CCCVTK, the Canadian Common CV Toolkit
Copyright (C) 2013-2014 Sylvain Hallé
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// We load the (huge) list of constants associated to the CV
require_once("constants.lib.php");
/**
* Basic class to handle data from the Canadian Common CV (CCV). Basically,
* this class loads the XML data from an instance of CCV, parses and
* processes it, and offers information from the most common sections
* (publications, funding, students supervised, etc.) as a set of
* associative arrays that can be easily queried by a PHP script. Any
* user-defined script can then use these arrays to build a document with
* an arbitrary format (e.g. LaTeX, HTML, plain-text, etc.).
*
* This script works in conjunction with a large array containing all the
* predefined constants used in the documentation of the CCV.
*/
class CommonCV // {{{
{
// The DOM object holding the CV's contents
private $m_dom;
// An object to perform XPath queries on the CV's content. It is made
// public so that one can query the CV in custom ways if needed
public $m_xpath;
public static $constants;
/**
* Default constructor. Reads a CV from a given filename
* @param filename The filename to read from
*/
public function CommonCV($filename) // {{{
{
global $CCV_CONST;
$this->constants = $CCV_CONST;
$this->loadFromFile($filename);
} // }}}
/**
* Loads a CV from an XML file. This wipes any CV that was already
* loaded into the object.
* @param filename The filename to read from
*/
private function loadFromFile($filename) // {{{
{
$file_contents = file_get_contents($filename);
$this->m_dom = new DOMDocument();
$this->m_dom->formatOutput = true;
$this->m_dom->loadXML($file_contents);
$this->m_xpath = new DOMXpath($this->m_dom);
} // }}}
/**
* Parses the list of conference papers and returns (some of its) data
* as an associative array for convenience
*/
public function getConferencePapers() // {{{
{
global $CCV_CONST;
$records = array();
$elements = $this->m_xpath->query("//section[@id='4b9f909503cd4c8aa8d826c87d6d874d']");
for ($i = 0; !is_null($elements) && $i < $elements->length; $i++)
{
$record = array();
$id = $this->get_xpath("@recordId", $elements->item($i));
$record["title"] = $this->get_xpath("field[@id='8e6ee535c95e42ec866b777c7472bafb']/value", $elements->item($i));
$record["publisher"] = $this->get_xpath("field[@id='0c357193a93f4137a87394401ac81958']/value", $elements->item($i));
$record["authors"] = $this->get_xpath("field[@id='3cc54d9bb92d421da46548979048396f']/value", $elements->item($i));
$record["editors"] = $this->get_xpath("field[@id='018e656a0f824b1f91a6a2cb33ac61dd']/value", $elements->item($i));
$record["pages"] = $this->get_xpath("field[@id='684ccb1fcdd7421f89b304ff5c40579d']/value", $elements->item($i));
$record["url"] = $this->get_xpath("field[@id='61690b466fb748d99ed29b340c0ee60b']/value", $elements->item($i));
$record["status"] = $this->get_xpath("field[@id='080301b1f1c0464bba7fcfa1fa8fe182']/lov/@id", $elements->item($i));
$pr = $this->get_xpath("field[@id='560a2ce08e14497ba575af760eb12ba9']/lov/@id", $elements->item($i));
if ($pr === $CCV_CONST["Yes-No"]["Yes"])
$record["peer_reviewed"] = true;
elseif ($pr === $CCV_CONST["Yes-No"]["No"])
$record["peer_reviewed"] = false;
$record["conf_name"] = $this->get_xpath("field[@id='b3c8a60c053a405597b92899d95765a3']/value", $elements->item($i));
$record["published_in"] = $this->get_xpath("field[@id='1a1b39e861054ee59d270e66271a4ead']/value", $elements->item($i));
$record["city"] = $this->get_xpath("field[@id='c2efd9725588489b8df73467c5597c32']/value", $elements->item($i));
$date = $this->get_xpath("field[@id='0318d139f3e0479083188ff8319a97b2']/value", $elements->item($i));
@list($date_year, $date_month) = explode("/", $date);
$record["date_year"] = $date_year;
$record["date_month"] = $date_month;
if($date_year == "" || $date_month == ""){
// Check Conference Date field instead
$confDate = $this->get_xpath("field[@id='99b57db653a841ccbd5f8e52079745c0']/value", $elements->item($i));
@list($date_year, $date_month) = explode("/", $confDate);
if($date_year != ""){
$record["date_year"] = $date_year;
}
if($date_month != ""){
$record["date_month"] = str_pad($date_month, 2, "0", STR_PAD_LEFT);
}
}
$records[$id] = $record;
}
return $records;
} // }}}
/**
* Parses the list of journal papers and returns (some of its) data
* as an associative array for convenience
*/
public function getJournalPapers() // {{{
{
global $CCV_CONST;
$records = array();
$elements = $this->m_xpath->query("//section[@id='9a34d6b273914f18b2273e8de7c48fd6']");
for ($i = 0; !is_null($elements) && $i < $elements->length; $i++)
{
$id = $this->get_xpath("@recordId", $elements->item($i));
$record = array();
$record["title"] = $this->get_xpath("field[@id='f3fd4878d47c4e83aef6959620ba4870']/value", $elements->item($i));
$record["authors"] = $this->get_xpath("field[@id='bc3b428d99384b04bb749311bb804e1d']/value", $elements->item($i));
$record["editors"] = $this->get_xpath("field[@id='707a6e0ca58341a5a82fb923b2842530']/value", $elements->item($i));
$record["pages"] = $this->get_xpath("field[@id='00ba1799ece344dc8d0779a3f05a4df8']/value", $elements->item($i));
$record["url"] = $this->get_xpath("field[@id='478545acac5340c0a73b7e0d2a4bee06']/value", $elements->item($i));
$record["publisher"] = $this->get_xpath("field[@id='4ad593960aba4a21bf154fa8daf37f9f']/value", $elements->item($i));
$record["volume"] = $this->get_xpath("field[@id='0a826c656ff34e579dfcbfb373771260']/value", $elements->item($i));
$record["number"] = $this->get_xpath("field[@id='cc1d9e14945b4e8496641dbe22b3448a']/value", $elements->item($i));
$record["status"] = $this->get_xpath("field[@id='3b56e4362d6a495aa5d22a1de5914741']/lov/@id", $elements->item($i));
$pr = $this->get_xpath("field[@id='2089ff1a86844b6c9a10fc63469f9a9d']/lov/@id", $elements->item($i));
if ($pr === $CCV_CONST["Yes-No"]["Yes"])
$record["peer_reviewed"] = true;
elseif ($pr === $CCV_CONST["Yes-No"]["No"])
$record["peer_reviewed"] = false;
$record["journal"] = $this->get_xpath("field[@id='5c04ea4dae464499807d0b40b4cad049']/value", $elements->item($i));
$date = $this->get_xpath("field[@id='6fafe258e19e49a7884428cb49d75424']/value", $elements->item($i));
@list($date_year, $date_month) = explode("/", $date);
$record["date_year"] = $date_year;
$record["date_month"] = ($date_month != "") ? str_pad($date_month, 2, "0", STR_PAD_LEFT) : "01";
$records[$id] = $record;
}
return $records;
} // }}}
/**
* Parses the list of book chapters and returns (some of its) data
* as an associative array for convenience
*/
public function getBookChapters() // {{{
{
global $CCV_CONST;
$records = array();
$elements = $this->m_xpath->query("//section[@id='fd8f2ffe3f5c43db8b5c3f72d8ffd994']");
for ($i = 0; !is_null($elements) && $i < $elements->length; $i++)
{
$id = $this->get_xpath("@recordId", $elements->item($i));
$record = array();
$record["booktitle"] = $this->get_xpath("field[@id='b864a9512e89482487f83ed22c454e9d']/value", $elements->item($i));
$record["title"] = $this->get_xpath("field[@id='52a699a6b0fe42a4851a7d5ae355360b']/value", $elements->item($i));
$record["authors"] = $this->get_xpath("field[@id='5bc7b0b361f843d296e0e035b4b87176']/value", $elements->item($i));
$record["editors"] = $this->get_xpath("field[@id='dcb27492e1554fc9838992ba7c70f416']/value", $elements->item($i));
$record["pages"] = $this->get_xpath("field[@id='45b9d02a4bb04ec782357741b53dc135']/value", $elements->item($i));
$record["url"] = $this->get_xpath("field[@id='6f1c66fc402d4b0db3d9987e2c5d49e8']/value", $elements->item($i));
$record["publisher"] = $this->get_xpath("field[@id='51a088349c1442238d5d0331d95f3205']/value", $elements->item($i));
$record["status"] = $this->get_xpath("field[@id='cf36bbd2e16c45cba9768a84ac2d6729']/lov/@id", $elements->item($i));
$pr = $this->get_xpath("field[@id='51bd72e89f85442a9ae199e75fe5e765']/lov/@id", $elements->item($i));
if ($pr === $CCV_CONST["Yes-No"]["Yes"])
$record["peer_reviewed"] = true;
elseif ($pr === $CCV_CONST["Yes-No"]["No"])
$record["peer_reviewed"] = false;
$record["journal"] = $this->get_xpath("field[@id='5c04ea4dae464499807d0b40b4cad049']/value", $elements->item($i));
$date = $this->get_xpath("field[@id='c114eabcd4674f3c9467b2bf6820cbd6']/value", $elements->item($i));
@list($date_year, $date_month) = explode("/", $date);
$record["date_year"] = $date_year;
$record["date_month"] = ($date_month != "") ? str_pad($date_month, 2, "0", STR_PAD_LEFT) : "01";
$records[$id] = $record;
}
return $records;
} // }}}
/**
* Parses the list of supervised students and returns (some of its) data
* as an associative array for convenience
*/
public function getStudentsSupervised() // {{{
{
global $CCV_CONST;
$records = array();
$elements = $this->m_xpath->query("//section[@id='4b36fa1eef2549f6ab3a3df7c1c81e0b']");
for ($i = 0; !is_null($elements) && $i < $elements->length; $i++)
{
$record = array();
$id = $this->get_xpath("@recordId", $elements->item($i));
// Supervision Dates
$date = $this->get_xpath("field[@id='19964df0a8524f2bb44d5eb53729f9cc']/value", $elements->item($i));
@list($record["start_year"], $record["start_month"]) = explode("/", $date);
$date = $this->get_xpath("field[@id='bd3619f7970441dc83ada1d2fdbf0780']/value", $elements->item($i));
@list($record["end_year"], $record["end_month"]) = explode("/", $date);
// Degree Dates
$date = $this->get_xpath("field[@id='3cf3d0de12f44222b941fdbf57ad51a6']/value", $elements->item($i));
@list($record["degree_start_year"], $record["degree_start_month"]) = explode("/", $date);
$date = $this->get_xpath("field[@id='ab1293e2fee8472481457d4f8493c7f1']/value", $elements->item($i));
@list($record["degree_expected_year"], $record["degree_expected_month"]) = explode("/", $date);
$date = $this->get_xpath("field[@id='8284dbdd03aa4277b7fca7662bd1758c']/value", $elements->item($i));
@list($record["degree_end_year"], $record["degree_end_month"]) = explode("/", $date);
$record["name"] = $this->get_xpath("field[@id='3c504aafda28418ea439d8f92c28aef0']/value", $elements->item($i));
$record["institution"] = $this->get_xpath("field[@id='e36ccf9a00a241dc942e608df32c8c84']/value", $elements->item($i));
$record["diploma"] = $this->get_xpath("field[@id='5b8638e8646448dcb8edef2c21e01c87']/lov/@id", $elements->item($i));
$record["status"] = $this->get_xpath("field[@id='e5d331dca0fc4000992e43b695b2db21']/lov/@id", $elements->item($i));
$record["title"] = $this->get_xpath("field[@id='420e5bbd57104c3c9823b5e6850ee6f8']/value", $elements->item($i));
$records[$id] = $record;
}
return $records;
} // }}}
/**
* Parses the list of funding sources and returns (some of its) data
* as an associative array for convenience
*/
public function getFunding() // {{{
{
global $CCV_CONST;
$records = array();
$elements = $this->m_xpath->query("//section[@id='aaedc5454412483d9131f7619d10279e']");
for ($i = 0; !is_null($elements) && $i < $elements->length; $i++)
{
$record = array();
$id = $this->get_xpath("@recordId", $elements->item($i));
$date = $this->get_xpath("field[@id='9c1db4674334436ca891b7b8a9e114bd']/value", $elements->item($i));
list($record["start_year"], $record["start_month"]) = explode("/", $date);
$date = $this->get_xpath("field[@id='b63179ab0f0e4c9eaa7e9a8130d60ee3']/value", $elements->item($i));
@list($record["end_year"], $record["end_month"]) = explode("/", $date);
$record["funding_title"] = $this->get_xpath("field[@id='735545eb499e4cc6a949b4b375a804e8']/value", $elements->item($i));
$record["funding_type"] = $this->get_xpath("field[@id='931b92a5ffed4e5aa9c7b3a0afd5f8ba']/lov/@id", $elements->item($i));
$record["funding_program"] = $this->get_xpath("section[@id='376b8991609f46059a3d66028f005360']/field[@id='97231512141a452a82151cc162e9a59c']/value", $elements->item($i));
$record["funder"] = $this->get_xpath("section[@id='376b8991609f46059a3d66028f005360']/field[@id='67e083b070954e91bcbb1cc70131145a']/lov/@id", $elements->item($i));
$record["otherfunder"] = $this->get_xpath("section[@id='376b8991609f46059a3d66028f005360']/field[@id='1bdead14642545f3971a59997d82da67']/value", $elements->item($i));
$record["total_amount"] = $this->get_xpath("section[@id='376b8991609f46059a3d66028f005360']/field[@id='dfe6a0b34347486aaa677f07306a141e']/value", $elements->item($i));
$record["received_amount"] = $this->get_xpath("section[@id='376b8991609f46059a3d66028f005360']/field[@id='882a94c7548744ca992e2647346d2e14']/value", $elements->item($i));
$record["role"] = $this->get_xpath("field[@id='13806a6772d248158619261afaab2fe0']/lov/@id", $elements->item($i));
$co_holders = array();
$co_els = $this->m_xpath->query("section[@id='c7c473d1237b432fb7f2abd831130fb7']", $elements->item($i));
for ($j = 0; !is_null($co_els) && $j < $co_els->length; $j++)
{
$co_holder = array();
$ch_id = $this->get_xpath("@recordId", $co_els->item($j));
$co_holder["name"] = $this->get_xpath("field[@id='ddd551dfb26344fbb17f07afcffc94ed']/value", $co_els->item($j));
$co_holders[$ch_id] = $co_holder;
}
$record["co_holders"] = $co_holders;
$comp = $this->get_xpath("section[@id='376b8991609f46059a3d66028f005360']/field[@id='00efdc7e790a48ac8675696c66afc3ad']/lov/@id", $elements->item($i));
if ($comp === $CCV_CONST["Yes-No"]["Yes"])
$record["competitive"] = true;
elseif ($comp === $CCV_CONST["Yes-No"]["No"])
$record["competitive"] = false;
$records[$id] = $record;
}
return $records;
} // }}}
/**
* Parses the list of personal info and returns (some of its) data
* as an associative array for convenience
*/
public function getPersonalInfo() // {{{
{
global $CCV_CONST;
$records = array();
$elements = $this->m_xpath->query("//section[@id='2687e70e5d45487c93a8a02626543f64']");
if ($elements->length > 0)
{
$i = 0;
$records["greeting"] = $this->get_xpath("field[@id='ee8beaea41f049d8bcfadfbfa89ac09e']/lov/@id", $elements->item($i));
$records["last_name"] = $this->get_xpath("field[@id='5c6f17e8a67241e19667815a9e95d9d0']/value", $elements->item($i));
$records["first_name"] = $this->get_xpath("field[@id='98ad36fee26a4d6b8953ea764f4fed04']/value", $elements->item($i));
$records["middle_name"] = $this->get_xpath("field[@id='4ca83c1aaa6a42a78eac0290368e70f3']/value", $elements->item($i));
$records["prev_first_name"] = $this->get_xpath("field[@id='0fb359a7d809457d9392bb1ca577f1b3']/value", $elements->item($i));
$records["prev_last_name"] = $this->get_xpath("field[@id='84e9fa08f7334db79ed5310e5f7a961b']/value", $elements->item($i));
$records["sex"] = $this->get_xpath("field[@id='3d258d8ceb174d3eb2ae1258a780d91b']/lov/@id", $elements->item($i));
$records["correspondence_language"] = $this->get_xpath("field[@id='2b72a344523c467da0c896656b5290c0']/lov/@id", $elements->item($i));
// Get Address Info
$co_holders = array();
$co_els = $this->m_xpath->query("//section[@id='b92721f0510a4ef4b0d1cf7f5ea3f01e']");
for ($j = 0; !is_null($co_els) && $j < $co_els->length; $j++)
{
$co_holder = array();
$ch_id = $this->get_xpath("@recordId", $co_els->item($j));
$co_holder["primary_indicator"] = ($this->get_xpath("@primaryIndicator", $co_els->item($j)) == "true");
$co_holder["type"] = $this->get_xpath("field[@id='35c302c36fe9479287206171087fb185']/lov/@id", $co_els->item($j));
$co_holder["line1"] = $this->get_xpath("field[@id='2de0fe4994f546c695a060d68e8e03ca']/value", $co_els->item($j));
$co_holder["line2"] = $this->get_xpath("field[@id='dafdb980e181416abc5e26c0770df662']/value", $co_els->item($j));
$co_holder["line3"] = $this->get_xpath("field[@id='fc390eae1fbc45c89789f2ecbb5bed8e']/value", $co_els->item($j));
$co_holder["line4"] = $this->get_xpath("field[@id='d51e2de9122744489ac2231d85995617']/value", $co_els->item($j));
$co_holder["line5"] = $this->get_xpath("field[@id='5365d87b9ff145d3a8d0d4fc21af57bb']/value", $co_els->item($j));
$co_holder["city"] = $this->get_xpath("field[@id='499d69637b4148d0a49463a2881e9d09']/value", $co_els->item($j));
$co_holder["postal_code"] = $this->get_xpath("field[@id='a41f1e118e61482eb3cdde4aaeb783e8']/value", $co_els->item($j));
$co_holder["location_country"] = $this->get_xpath("field[@id='b1071063df03484ebec65cd1a3464438']/refTable/linkedWith[@label='Country']/@value", $co_els->item($j));
$co_holder["location_subdivision"] = $this->get_xpath("field[@id='b1071063df03484ebec65cd1a3464438']/refTable/linkedWith[@label='Subdivision']/@value", $co_els->item($j));
$date = $this->get_xpath("field[@id='b77ff4a2c49247e0af668be52704da91']/value", $co_els->item($j));
@list($co_holder["start_year"], $co_holder["start_month"], $co_holder["start_day"]) = explode("-", $date);
$date = $this->get_xpath("field[@id='4ab2497d7a0f471ebc6a50e32dd4f22d']/value", $co_els->item($j));
@list($co_holder["end_year"], $co_holder["end_month"], $co_holder["end_day"]) = explode("-", $date);
$co_holder["start_year"] = ($co_holder["start_year"] == null) ? "" : $co_holder["start_year"];
$co_holder["start_month"] = ($co_holder["start_month"] == null) ? "" : $co_holder["start_month"];
$co_holder["start_day"] = ($co_holder["start_day"] == null) ? "" : $co_holder["start_day"];
$co_holder["end_year"] = ($co_holder["end_year"] == null) ? "" : $co_holder["end_year"];
$co_holder["end_month"] = ($co_holder["end_month"] == null) ? "" : $co_holder["end_month"];
$co_holder["end_day"] = ($co_holder["end_day"] == null) ? "" : $co_holder["end_day"];
$co_holders[$ch_id] = $co_holder;
}
$records["addresses"] = $co_holders;
// Get Language Skills Info
$languages = array();
$lang_els = $this->m_xpath->query("//section[@id='c1f614961342429c86397e81cd6f50f5']");
for ($j = 0; !is_null($lang_els) && $j < $lang_els->length; $j++)
{
$language = array();
$l_id = $this->get_xpath("@recordId", $lang_els->item($j));
$language["language"] = $this->get_xpath("field[@id='ee161805b4f941e48f05e050e364e585']/lov/@id", $lang_els->item($j));
$read = $this->get_xpath("field[@id='a9d0f0666e5b47dcb9acb30bd5cab407']/lov/@id", $lang_els->item($j));
$write = $this->get_xpath("field[@id='12173f36422446479799578ba07d96c8']/lov/@id", $lang_els->item($j));
$speak = $this->get_xpath("field[@id='e670ac0f2c3e48a3b13d487e66ea7889']/lov/@id", $lang_els->item($j));
$understand = $this->get_xpath("field[@id='aa02c54f1e5b4672a0b96def14e5b02e']/lov/@id", $lang_els->item($j));
$peer_review = $this->get_xpath("field[@id='fc6ac63e9ec04129aec7b26e5a729920']/lov/@id", $lang_els->item($j));
$language["read"] = ($read == $CCV_CONST["Yes-No"]["Yes"]) ? true : false;
$language["write"] = ($write == $CCV_CONST["Yes-No"]["Yes"]) ? true : false;
$language["speak"] = ($speak == $CCV_CONST["Yes-No"]["Yes"]) ? true : false;
$language["understand"] = ($understand == $CCV_CONST["Yes-No"]["Yes"]) ? true : false;
$language["peer_review"] = ($peer_review == $CCV_CONST["Yes-No"]["Yes"]) ? true : false;
$languages[$l_id] = $language;
}
$records["languages"] = $languages;
// Get Telephone Info
$telephone = array();
$phone_els = $this->m_xpath->query("//section[@id='2a3366209cf8477f82556b045188f131']");
for ($j = 0; !is_null($phone_els) && $j < $phone_els->length; $j++)
{
$phone = array();
$t_id = $this->get_xpath("@recordId", $phone_els->item($j));
$phone["primary_indicator"] = ($this->get_xpath("@primaryIndicator", $phone_els->item($j)) == "true");
$phone["type"] = $this->get_xpath("field[@id='ccef121ae875427f829024aabb39fa8c']/lov/@id", $phone_els->item($j));
$phone["country_code"] = $this->get_xpath("field[@id='63dedd46a5204cda8257227bbb3b6675']/value", $phone_els->item($j));
$phone["area_code"] = $this->get_xpath("field[@id='13cdf3a5e13643f5bc74566bf075253c']/value", $phone_els->item($j));
$phone["number"] = $this->get_xpath("field[@id='1ca756fe70964371a2b9f57bdf567a5d']/value", $phone_els->item($j));
$phone["extension"] = $this->get_xpath("field[@id='afe0657785084098bb718345280eb840']/value", $phone_els->item($j));
$date = $this->get_xpath("field[@id='69c67fae5d4849d08f4f9799ae0a2335']/value", $phone_els->item($j));
@list($phone["start_year"], $phone["start_month"], $phone["start_day"]) = explode("-", $date);
$date = $this->get_xpath("field[@id='a90e95e1d278467eaf1847464f09f39f']/value", $phone_els->item($j));
@list($phone["end_year"], $phone["end_month"], $phone["end_day"]) = explode("-", $date);
$phone["start_year"] = ($phone["start_year"] == null) ? "" : $phone["start_year"];
$phone["start_month"] = ($phone["start_month"] == null) ? "" : $phone["start_month"];
$phone["start_day"] = ($phone["start_day"] == null) ? "" : $phone["start_day"];
$phone["end_year"] = ($phone["end_year"] == null) ? "" : $phone["end_year"];
$phone["end_month"] = ($phone["end_month"] == null) ? "" : $phone["end_month"];
$phone["end_day"] = ($phone["end_day"] == null) ? "" : $phone["end_day"];
$telephone[$t_id] = $phone;
}
$records["telephone"] = $telephone;
}
return $records;
} // }}}
/**
* Parses the list of employment and returns (some of its) data
* as an associative array for convenience
*/
public function getEmployment() // {{{
{
global $CCV_CONST;
$records = array();
$elements = $this->m_xpath->query("//section[@id='b857f61b33484cb093068bd2da764f99']");
for ($i = 0; !is_null($elements) && $i < $elements->length; $i++)
{
$record = array();
$id = $this->get_xpath("@recordId", $elements->item($i));
$record['type'] = $this->get_xpath("field[@id='9510a03a308f43ceb8cd046aeffa9499']/lov/@id", $elements->item($i));
$record['title'] = $this->get_xpath("field[@id='886807b87b624978bc8ca9045ff56e47']/value", $elements->item($i));
$record['status'] = $this->get_xpath("field[@id='ef7bd6fa8dd040449fa181f0ca4530e4']/lov/@id", $elements->item($i));
$record['rank'] = $this->get_xpath("field[@id='500e1360abd14972bc1ef844a8b98087']/lov/@id", $elements->item($i));
$date = $this->get_xpath("field[@id='c7e85d10d10249c68b28c71fc80ec570']/value", $elements->item($i));
@list($record["start_year"], $record["start_month"]) = explode("/", $date);
$date = $this->get_xpath("field[@id='b4681f52d85440829faa3160ba3bb31f']/value", $elements->item($i));
@list($record["end_year"], $record["end_month"]) = explode("/", $date);
$record["end_year"] = ($record["end_year"] == null) ? "" : $record["end_year"];
$record["end_month"] = ($record["end_month"] == null) ? "" : $record["end_month"];
$record['organization_country'] = $this->get_xpath("field[@id='5dd34f14c1ea47c09e8ddcd202653814']/refTable/linkedWith[@label='Country']/@value", $elements->item($i));
$record['organization_subdivision'] = $this->get_xpath("field[@id='5dd34f14c1ea47c09e8ddcd202653814']/refTable/linkedWith[@label='Subdivision']/@value", $elements->item($i));
$record['organization_type'] = $this->get_xpath("field[@id='5dd34f14c1ea47c09e8ddcd202653814']/refTable/linkedWith[@label='Organization Type']/@value", $elements->item($i));
$record['organization_name'] = $this->get_xpath("field[@id='5dd34f14c1ea47c09e8ddcd202653814']/refTable/linkedWith[@label='Organization']/@value", $elements->item($i));
$record['department'] = $this->get_xpath("field[@id='cd6e5e97994e42f893bd5c9e7212c94b']/value", $elements->item($i));
$record['faculty'] = $this->get_xpath("field[@id='58cf7001d283421b91f5da21f0ef2188']/value", $elements->item($i));
$record['tenure'] = $this->get_xpath("field[@id='b0eca39ad77346648180dec948d13432']/lov/@id", $elements->item($i));
$records[$id] = $record;
}
return $records;
} // }}}
/**
* Parses the list of courses taught info and returns (some of its) data
* as an associative array for convenience
*/
public function getCoursesTaught() // {{{
{
global $CCV_CONST;
$records = array();
$elements = $this->m_xpath->query("//section[@id='9dc74140d0ff4b26a2d4a559bc9b5a2b']");
for ($i = 0; !is_null($elements) && $i < $elements->length; $i++)
{
$record = array();
$id = $this->get_xpath("@recordId", $elements->item($i));
$record["role"] = $this->get_xpath("field[@id='cefdb78ecd9e43fb8554d21e7d454132']/value", $elements->item($i));
$record["department"] = $this->get_xpath("field[@id='b532bb9be90e4a93a879f23e79cfd652']/value", $elements->item($i));
$record["semester"] = $this->get_xpath("field[@id='bab7abad3efb404897984bee6ed33692']/value", $elements->item($i));
$record["code"] = $this->get_xpath("field[@id='d62dd205bef0463a8a23436c75f83f41']/value", $elements->item($i));
$record["title"] = $this->get_xpath("field[@id='95728285a48242a896b5727c98a7c0c5']/value", $elements->item($i));
$record["level"] = $this->get_xpath("field[@id='6db7aff8daf74420abcca56f8e6d6cc3']/lov/@id", $elements->item($i));
$date = $this->get_xpath("field[@id='76f08a7bda38475bb15660d4fc57745f']/value", $elements->item($i));
@list($record["start_date_year"], $record["start_date_month"], $record["start_date_day"]) = explode("-", $date);
$date = $this->get_xpath("field[@id='c87587a998c04d3bbb23e853516d2f94']/value", $elements->item($i));
@list($record["end_date_year"], $record["end_date_month"], $record["end_date_day"]) = explode("-", $date);
$record["nb_students"] = $this->get_xpath("field[@id='c2b79aa4e9e0431db8f3c4e2c32db3b0']/value", $elements->item($i));
$record["nb_credits"] = $this->get_xpath("field[@id='c2b79aa4e9e0431db8f3c4e2c32db3b0']/value", $elements->item($i));
$record["nb_credits"] = $this->get_xpath("section[@id='05b1c7c941194144b786690d89ba7c8c']/field[@id='97231512141a452a82151cc162e9a59c']/value", $elements->item($i));
$records[$id] = $record;
}
return $records;
} // }}}
/**
* Parses the list of Research Specialization Keywords and returns (some of its) data
* as an associative array for convenience
*/
public function getResearchSpecializationKeywords() // {{{
{
global $CCV_CONST;
$records = array();
$elements = $this->m_xpath->query("//section[@id='53099556bdac4ac8813be6fd62a356b1']");
for ($i = 0; !is_null($elements) && $i < $elements->length; $i++)
{
$record = array();
$id = $this->get_xpath("@recordId", $elements->item($i));
$record["keyword"] = $this->get_xpath("field[@id='6351fbc0f45f4266b29f292fd521c67a']/value", $elements->item($i));
$records[$id] = $record;
}
return $records;
} // }}}
/**
* Parses the list of reviewed journal papers and returns (some of its)
* data as an associative array for convenience
*/
public function getReviewedJournalPapers() // {{{
{
global $CCV_CONST;
$records = array();
$elements = $this->m_xpath->query("//section[@id='3f4e029fb3a141958126bcbc9d086acd']");
for ($i = 0; !is_null($elements) && $i < $elements->length; $i++)
{
$record = array();
$id = $this->get_xpath("@recordId", $elements->item($i));
$record["journal"] = $this->get_xpath("field[@id='e206eee3330a41c6ada624c29265fde7']/value", $elements->item($i));
$record["publisher"] = $this->get_xpath("field[@id='9b9aaa304dcf4bd78e20c211ba3b0bee']/value", $elements->item($i));
$record["numpapers"] = $this->get_xpath("field[@id='0c8f14842ab04c8daa4749b864f46a6c']/value", $elements->item($i));
$record["blindtype"] = $this->get_xpath("field[@id='59990065210f4bc084270ef862602cc4']/lov/@id", $elements->item($i));
$records[$id] = $record;
}
return $records;
} // }}}
/**
* Parses the list of reviewed conference papers and returns (some of its)
* data as an associative array for convenience
*/
public function getReviewedConferencePapers() // {{{
{
global $CCV_CONST;
$records = array();
$elements = $this->m_xpath->query("//section[@id='7cc778c33e64469987c55e2078be60d3']");
for ($i = 0; !is_null($elements) && $i < $elements->length; $i++)
{
$record = array();
$id = $this->get_xpath("@recordId", $elements->item($i));
$record["conference"] = $this->get_xpath("field[@id='9cdaafaa865246bc9637444cb90ae9a6']/value", $elements->item($i));
$record["numpapers"] = $this->get_xpath("field[@id='7189023217b44dba9d4ac5c76ffe6c10']/value", $elements->item($i));
$record["blindtype"] = $this->get_xpath("field[@id='b5f58c56b4544a969ac6013d1d7de0fa']/lov/@id", $elements->item($i));
$records[$id] = $record;
}
return $records;
} // }}}
/**
* Parses the list of committees and returns (some of its)
* data as an associative array for convenience
*/
public function getCommittees() // {{{
{
global $CCV_CONST;
$records = array();
$elements = $this->m_xpath->query("//section[@id='6c3b449732a84ac9af45d6935b8323d9']");
for ($i = 0; !is_null($elements) && $i < $elements->length; $i++)
{
$record = array();
$id = $this->get_xpath("@recordId", $elements->item($i));
$record["organization_name"] = $this->get_xpath("field[@id='e1f84da9b6df40fe9db972af2f85e5eb']/refTable/linkedWith[@label='Organisation']/@value", $elements->item($i));
$record["organization_country"] = $this->get_xpath("field[@id='e1f84da9b6df40fe9db972af2f85e5eb']/refTable/linkedWith[@label='Pays']/@value", $elements->item($i));
$record["name"] = $this->get_xpath("field[@id='b3c21a20aeee49cea5c1c33029da4c4c']/value", $elements->item($i));
$role = $this->get_xpath("field[@id='da89e8800c6641be91b0b21a61118c09']/lov/@id", $elements->item($i));
$record["role"] = $this->getCaptionFromValue($role);
$start_date = $this->get_xpath("field[@id='4c1a9700923d4bf9b541e479f4f32a66']/value", $elements->item($i));
@list($record["start_year"], $record["start_month"]) = explode("/", $start_date);
$end_date = $this->get_xpath("field[@id='1db804cbb6f04c64b57e60c306557d91']/value", $elements->item($i));
@list($record["end_year"], $record["end_month"]) = explode("/", $end_date);
$records[$id] = $record;
}
return $records;
} // }}}
/**
* Reverses the first/last names of authors in the list; e.g. takes
* "Doe J, Klein C, Einstein A" and returns "J. Doe, C. Klein,
* A. Einstein"
* @param $s The string to process
* @param $dots Optional; if set to false, will not add periods after
* the initials
*/
public static function reverseAuthors($s, $dots = true) // {{{
{
$out = "";
$authors = explode(",", $s);
$rec_no = 0;
foreach ($authors as $author)
{
if ($rec_no++ > 0)
$out .= ", ";
$p = strrpos($author, " ");
if ($p === false)
$out .= "$author";
else
{
$last_names = trim(substr($author, 0, $p));
$first_names = trim(substr($author, $p));
if ($dots)
$first_names = preg_replace("/(\\w)/", "$1.", $first_names);
$out .= "$first_names $last_names";
}
}
return trim($out);
} // }}}
/**
* Reverse a single author, i.e. takes "Einstein, Albert" and returns
* "Albert Einstein".
* @param $s The string to process
* @param $dots Optional; if set to false, will not add periods after
* the first name part
*/
public static function reverseAuthor($s, $dots = true) // {{{
{
$out = "";
@list($last, $first) = explode(",", $s);
$out .= $first;
if ($dots)
$out .= ".";
$out .= " ".$last;
return $out;
} // }}}
/**
* Returns the (English) caption associated to a particular constant,
* according to the online documentation of the CCV
* @param $value The value to look for
* @param $key Optional. If specified, the function will only look
* for the value in a particular subsection of the list (e.g.
* "Funding Organization")
* @return The caption associated to that value
*/
public static function getCaptionFromValue($value, $key = null) // {{{
{
global $CCV_CONST;
if ($key === null)
{
$to_iterate = array_values($CCV_CONST);
foreach ($to_iterate as $entry)
{
foreach ($entry as $caption => $val)
{
if ($val === $value)
return $caption;
}
}
}
else
{
$to_iterate = $CCV_CONST[$key];
foreach ($to_iterate as $caption => $val)
{
if ($val === $value)
return $caption;
}
}
return "?";
} // }}}
/**
* Returns the first value of the query
*/
private function get_xpath($query, $ref_element) // {{{
{
$els = $this->m_xpath->query($query, $ref_element);
if ($els && $els->length > 0)
return trim($els->item(0)->nodeValue);
return "";
} // }}}
} // }}}
/* :folding=explicit:wrap=none: */
?>
|
gpl-2.0
|
pashen/icms
|
cache/%%E4^E46^E4632459%%mod_respect.tpl.php
|
2296
|
<?php /* Smarty version 2.6.19, created on 2012-10-17 13:03:40
compiled from mod_respect.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('function', 'profile_url', 'mod_respect.tpl', 9, false),array('modifier', 'escape', 'mod_respect.tpl', 9, false),)), $this); ?>
<?php if ($this->_tpl_vars['users']): ?>
<table width="100%" border="0" cellpadding="2" cellspacing="1">
<?php $_from = $this->_tpl_vars['users']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)):
foreach ($_from as $this->_tpl_vars['id'] => $this->_tpl_vars['user']):
?>
<tr>
<td width="30"><img src="<?php echo $this->_tpl_vars['user']['avatar']; ?>
" border="0" /></td>
<td>
<div style="margin-left:15px;">
<a style="font-size:16px;font-weight:bold;" href="<?php echo cmsSmartyProfileURL(array('login' => $this->_tpl_vars['user']['login']), $this);?>
#upr_awards" title="<?php echo ((is_array($_tmp=$this->_tpl_vars['user']['nickname'])) ? $this->_run_mod_handler('escape', true, $_tmp, 'html') : smarty_modifier_escape($_tmp, 'html')); ?>
"><?php echo $this->_tpl_vars['user']['nickname']; ?>
</a>
<?php if ($this->_tpl_vars['cfg']['show_awards']): ?>
<div style="margin-top:6px">
<?php $_from = $this->_tpl_vars['user']['awards']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)):
foreach ($_from as $this->_tpl_vars['id'] => $this->_tpl_vars['award']):
?>
<img src="/images/icons/award.gif" border="0" title="<?php echo ((is_array($_tmp=$this->_tpl_vars['award']['title'])) ? $this->_run_mod_handler('escape', true, $_tmp, 'html') : smarty_modifier_escape($_tmp, 'html')); ?>
" />
<?php endforeach; endif; unset($_from); ?>
</div>
<?php endif; ?>
</div>
</td>
</tr>
<?php endforeach; endif; unset($_from); ?>
</table>
<?php else: ?>
<p>Íåò äîñòîéíûõ.</p>
<?php endif; ?>
|
gpl-2.0
|
vincenzo/deeson-dev-challenge
|
sites/all/themes/ddc_theme/templates/node/article/node--article--teaser.tpl.php
|
593
|
<?php
/**
* @file
* Template file for article teasers.
*/
?>
<div class="contextual-links-region">
<?php print render($title_suffix); ?>
<article>
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<div class="media">
<div class="pull-left">
<?php print render($content['field_image']); ?>
</div>
<div class="media-body">
<h1><?php print $linked_title; ?></h1>
<?php print render($content['body']); ?>
</div>
</div>
</div>
</article>
</div>
|
gpl-2.0
|
NoviumDesign/polefitness
|
wp-content/plugins/woocommerce-gateway-klarna/classes/class-klarna-checkout.php
|
86274
|
<?php
/**
* Klarna checkout class
*
* @link http://www.woothemes.com/products/klarna/
* @since 1.0.0
*
* @package WC_Gateway_Klarna
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
class WC_Gateway_Klarna_Checkout extends WC_Gateway_Klarna {
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
global $woocommerce;
parent::__construct();
$this->id = 'klarna_checkout';
$this->method_title = __( 'Klarna Checkout', 'woocommerce-gateway-klarna' );
$this->has_fields = false;
// Load the form fields.
$this->init_form_fields();
// Load the settings.
$this->init_settings();
// Define user set variables
include( KLARNA_DIR . 'includes/variables-checkout.php' );
// Helper class
include_once( KLARNA_DIR . 'classes/class-klarna-helper.php' );
$this->klarna_helper = new WC_Gateway_Klarna_Helper( $this );
// Test mode or Live mode
if ( $this->testmode == 'yes' ) {
// Disable SSL if in testmode
$this->klarna_ssl = 'false';
$this->klarna_mode = Klarna::BETA;
} else {
// Set SSL if used in webshop
if ( is_ssl() ) {
$this->klarna_ssl = 'true';
} else {
$this->klarna_ssl = 'false';
}
$this->klarna_mode = Klarna::LIVE;
}
// Actions
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array(
$this,
'process_admin_options'
) );
// Push listener
add_action( 'woocommerce_api_wc_gateway_klarna_checkout', array( $this, 'check_checkout_listener' ) );
// Validate listener
add_action( 'woocommerce_api_wc_gateway_klarna_order_validate', array( 'WC_Gateway_Klarna_Order_Validate', 'validate_checkout_listener' ) );
// We execute the woocommerce_thankyou hook when the KCO Thank You page is rendered,
// because other plugins use this, but we don't want to display the actual WC Order
// details table in KCO Thank You page. This action is removed here, but only when
// in Klarna Thank You page.
if ( is_page() ) {
global $post;
$klarna_checkout_page_id = url_to_postid( $this->klarna_checkout_thanks_url );
if ( $post->ID == $klarna_checkout_page_id ) {
remove_action( 'woocommerce_thankyou', 'woocommerce_order_details_table', 10 );
}
}
// Subscription support
$this->supports = array(
'products',
'refunds',
'subscriptions',
'subscription_cancellation',
'subscription_suspension',
'subscription_reactivation',
'subscription_amount_changes',
'subscription_date_changes',
'subscription_payment_method_change',
'multiple_subscriptions'
);
// Add link to KCO page in standard checkout
/**
* Checkout page AJAX
*/
// Add coupon
add_action( 'wp_ajax_klarna_checkout_coupons_callback', array( $this, 'klarna_checkout_coupons_callback' ) );
add_action( 'wp_ajax_nopriv_klarna_checkout_coupons_callback', array(
$this,
'klarna_checkout_coupons_callback'
) );
// Remove coupon
add_action( 'wp_ajax_klarna_checkout_remove_coupon_callback', array(
$this,
'klarna_checkout_remove_coupon_callback'
) );
add_action( 'wp_ajax_nopriv_klarna_checkout_remove_coupon_callback', array(
$this,
'klarna_checkout_remove_coupon_callback'
) );
// Cart quantity
add_action( 'wp_ajax_klarna_checkout_cart_callback_update', array(
$this,
'klarna_checkout_cart_callback_update'
) );
add_action( 'wp_ajax_nopriv_klarna_checkout_cart_callback_update', array(
$this,
'klarna_checkout_cart_callback_update'
) );
// Cart remove
add_action( 'wp_ajax_klarna_checkout_cart_callback_remove', array(
$this,
'klarna_checkout_cart_callback_remove'
) );
add_action( 'wp_ajax_nopriv_klarna_checkout_cart_callback_remove', array(
$this,
'klarna_checkout_cart_callback_remove'
) );
// Shipping method selector
add_action( 'wp_ajax_klarna_checkout_shipping_callback', array( $this, 'klarna_checkout_shipping_callback' ) );
add_action( 'wp_ajax_nopriv_klarna_checkout_shipping_callback', array(
$this,
'klarna_checkout_shipping_callback'
) );
// Shipping option inside KCO iframe
add_action( 'wp_ajax_kco_iframe_shipping_option_change_cb', array(
$this,
'kco_iframe_shipping_option_change_cb'
) );
add_action( 'wp_ajax_nopriv_kco_iframe_shipping_option_change_cb', array(
$this,
'kco_iframe_shipping_option_change_cb'
) );
// Country selector
add_action( 'wp_ajax_klarna_checkout_country_callback', array( $this, 'klarna_checkout_country_callback' ) );
add_action( 'wp_ajax_nopriv_klarna_checkout_country_callback', array(
$this,
'klarna_checkout_country_callback'
) );
// Order note
add_action( 'wp_ajax_klarna_checkout_order_note_callback', array(
$this,
'klarna_checkout_order_note_callback'
) );
add_action( 'wp_ajax_nopriv_klarna_checkout_order_note_callback', array(
$this,
'klarna_checkout_order_note_callback'
) );
// KCO iframe JS event callbacks
// V2
add_action( 'wp_ajax_kco_iframe_change_cb', array( $this, 'kco_iframe_change_cb' ) );
add_action( 'wp_ajax_nopriv_kco_iframe_change_cb', array( $this, 'kco_iframe_change_cb' ) );
// V3
add_action( 'wp_ajax_kco_iframe_shipping_address_change_cb', array(
$this,
'kco_iframe_shipping_address_change_cb'
) );
add_action( 'wp_ajax_nopriv_kco_iframe_shipping_address_change_cb', array(
$this,
'kco_iframe_shipping_address_change_cb'
) );
if ( class_exists( 'WC_Subscriptions_Order' ) ) {
// Process subscription payment
// add_action( 'woocommerce_scheduled_subscription_renewal_klarna_checkout', array( $this, 'scheduled_subscription_payment' ), 10, 2 );
add_action( 'woocommerce_scheduled_subscription_payment_klarna_checkout', array(
$this,
'scheduled_subscription_payment'
), 10, 2 );
// Do not copy invoice number to recurring orders
// add_filter( 'woocommerce_subscriptions_renewal_order_meta_query', array( $this, 'kco_recurring_do_not_copy_meta_data' ), 10, 4 );
}
// Purge kco_incomplete orders hourly
add_action( 'wp', array( $this, 'register_purge_cron_job' ) );
add_action( 'klarna_purge_cron_job_hook', array( $this, 'purge_kco_incomplete' ) );
// Add activate settings field for recurring orders
add_filter( 'klarna_checkout_form_fields', array( $this, 'add_activate_recurring_option' ) );
// Register new order status
add_action( 'init', array( $this, 'register_klarna_incomplete_order_status' ) );
add_filter( 'wc_order_statuses', array( $this, 'add_kco_incomplete_to_order_statuses' ) );
add_filter( 'woocommerce_valid_order_statuses_for_payment_complete', array(
$this,
'kco_incomplete_payment_complete'
) );
add_filter( 'woocommerce_valid_order_statuses_for_payment', array( $this, 'kco_incomplete_payment_complete' ) );
// Hide "Refunded" and "KCO Incomplete" statuses for KCO orders
add_filter( 'wc_order_statuses', array( $this, 'remove_refunded_and_kco_incomplete' ), 1000 );
// Hide "Manual Refund" button for KCO orders
add_action( 'admin_head', array( $this, 'remove_refund_manually' ) );
// Cancel unpaid orders for KCO orders too
add_filter( 'woocommerce_cancel_unpaid_order', array( $this, 'cancel_unpaid_kco' ), 10, 2 );
}
/**
* Cancel unpaid KCO orders if the option is enabled
*
* @param $cancel boolean Cancel or not
* @param $order Object WooCommerce order object
*
* @return boolean
* @since 2.0
**/
function cancel_unpaid_kco( $cancel, $order ) {
if ( 'klarna_checkout' == get_post_meta( $order->id, '_created_via', true ) ) {
$cancel = true;
}
return $cancel;
}
/**
* Remove "Refunded" and "KCO Incomplete" statuses from the dropdown for KCO orders
*
* @since 2.0
**/
function remove_refunded_and_kco_incomplete( $order_statuses ) {
if ( is_admin() && function_exists( 'get_current_screen' ) ) {
$screen = get_current_screen();
if ( is_object( $screen ) && 'shop_order' == $screen->id ) {
if ( isset( $_GET['post'] ) && absint( $_GET['post'] ) == $_GET['post'] ) {
$order_id = $_GET['post'];
$order = wc_get_order( $order_id );
if ( false != $order && 'refunded' != $order->get_status() && 'klarna_checkout' == get_post_meta( $order_id, '_created_via', true ) ) {
unset( $order_statuses['wc-refunded'] );
}
// NEVER make it possible to change status to KCO Incomplete
if ( false != $order ) {
unset( $order_statuses['wc-kco-incomplete'] );
}
}
}
}
return $order_statuses;
}
/**
* Hide "Refund x Manually" for KCO orders
*
* @since 2.0
**/
function remove_refund_manually() {
$screen = get_current_screen();
if ( 'shop_order' == $screen->id ) {
if ( absint( $_GET['post'] ) == $_GET['post'] ) {
$order_id = $_GET['post'];
$order = wc_get_order( $order_id );
if ( false != $order && 'klarna_checkout' == get_post_meta( $order_id, '_created_via', true ) ) {
echo '<style>.do-manual-refund{display:none !important;}</style>';
}
}
}
}
/**
* Register purge KCO Incomplete orders cronjob
*
* @since 2.0
**/
function register_purge_cron_job() {
if ( ! wp_next_scheduled( 'klarna_purge_cron_job_hook' ) ) {
wp_schedule_event( current_time( 'timestamp' ), 'daily', 'klarna_purge_cron_job_hook' );
}
}
/**
* Purge KCO Incomplete orders
*
* Deletes KCO Incomplete orders that are older than one day and have KCO Incomplete email
* set to guest_checkout@klarna.com indicating customer email was never captured before
* checkout was abandoned and all KCO incomplete orders older than 2 weeks.
*
* @since 2.0
**/
function purge_kco_incomplete() {
// Get KCO Incomplete orders that are older than a day and don't have a real customer email captured.
$kco_incomplete_args = array(
'post_type' => 'shop_order',
'post_status' => 'wc-kco-incomplete',
'posts_per_page' => - 1,
'date_query' => array(
array(
'before' => '1 day ago'
)
)
);
$kco_incomplete_query = new WP_Query( $kco_incomplete_args );
if ( $kco_incomplete_query->have_posts() ) {
while ( $kco_incomplete_query->have_posts() ) {
$kco_incomplete_query->the_post();
global $post;
if ( 'guest_checkout@klarna.com' == get_post_meta( $post->ID, '_kco_incomplete_customer_email', true ) ) {
wp_delete_post( $post->ID, true );
}
}
}
wp_reset_postdata();
// Get all KCO Incomplete orders older than 2 weeks.
$kco_incomplete_args_1 = array(
'post_type' => 'shop_order',
'post_status' => 'wc-kco-incomplete',
'posts_per_page' => - 1,
'date_query' => array(
array(
'before' => '2 weeks ago'
)
)
);
$kco_incomplete_query_1 = new WP_Query( $kco_incomplete_args_1 );
if ( $kco_incomplete_query_1->have_posts() ) {
while ( $kco_incomplete_query_1->have_posts() ) {
$kco_incomplete_query_1->the_post();
global $post;
wp_delete_post( $post->ID, true );
}
}
wp_reset_postdata();
}
/**
* Register KCO Incomplete order status
*
* @since 2.0
**/
function register_klarna_incomplete_order_status() {
if ( 'yes' == $this->debug ) {
$show_in_admin_status_list = true;
} else {
$show_in_admin_status_list = false;
}
register_post_status( 'wc-kco-incomplete', array(
'label' => 'KCO incomplete',
'public' => false,
'exclude_from_search' => false,
'show_in_admin_all_list' => false,
'show_in_admin_status_list' => $show_in_admin_status_list,
'label_count' => _n_noop( 'KCO incomplete <span class="count">(%s)</span>', 'KCO incomplete <span class="count">(%s)</span>' ),
) );
}
/**
* Add KCO Incomplete to list of order status
*
* @since 2.0
**/
function add_kco_incomplete_to_order_statuses( $order_statuses ) {
// Add this status only if not in account page (so it doesn't show in My Account list of orders)
if ( ! is_account_page() ) {
$order_statuses['wc-kco-incomplete'] = 'Incomplete Klarna Checkout';
}
return $order_statuses;
}
/**
* Allows $order->payment_complete to work for KCO incomplete orders
*
* @since 2.0
**/
function kco_incomplete_payment_complete( $order_statuses ) {
$order_statuses[] = 'kco-incomplete';
return $order_statuses;
}
/**
* Add options for recurring order activation.
*
* @since 2.0
**/
function add_activate_recurring_option( $settings ) {
if ( class_exists( 'WC_Subscriptions_Manager' ) ) {
$settings['activate_recurring_title'] = array(
'title' => __( 'Recurring orders', 'woocommerce-gateway-klarna' ),
'type' => 'title',
);
$settings['activate_recurring'] = array(
'title' => __( 'Automatically activate recurring orders', 'woocommerce-gateway-klarna' ),
'type' => 'checkbox',
'label' => __( 'If this option is checked recurring orders will be activated automatically', 'woocommerce-gateway-klarna' ),
'default' => 'yes'
);
}
return $settings;
}
/**
* Scheduled subscription payment.
*
* @since 2.0
**/
function scheduled_subscription_payment( $amount_to_charge, $order ) {
// Check if order was created using this method
if ( $this->id == get_post_meta( $order->id, '_payment_method', true ) ) {
// Prevent hook from firing twice
if ( ! get_post_meta( $order->id, '_schedule_klarna_subscription_payment', true ) ) {
$result = $this->process_subscription_payment( $amount_to_charge, $order );
if ( false == $result ) {
WC_Subscriptions_Manager::process_subscription_payment_failure_on_order( $order );
} else {
WC_Subscriptions_Manager::process_subscription_payments_on_order( $order );
$order->payment_complete(); // Need to mark new order complete, so Subscription is marked as Active again
}
add_post_meta( $order->id, '_schedule_klarna_subscription_payment', 'no', true );
} else {
delete_post_meta( $order->id, '_schedule_klarna_subscription_payment', 'no' );
}
}
}
/**
* Process subscription payment.
*
* @since 2.0
**/
function process_subscription_payment( $amount_to_charge, $order ) {
if ( 0 == $amount_to_charge ) {
// Payment complete
$order->payment_complete();
return true;
}
$klarna_recurring_token = get_post_meta( $order->id, '_klarna_recurring_token', true );
$klarna_currency = get_post_meta( $order->id, '_order_currency', true );
$klarna_country = get_post_meta( $order->id, '_billing_country', true );
$klarna_locale = get_post_meta( $order->id, '_klarna_locale', true );
$klarna_eid = $this->klarna_eid;
$klarna_secret = $this->klarna_secret;
$klarna_billing = array(
'postal_code' => get_post_meta( $order->id, '_billing_postcode', true ),
'email' => get_post_meta( $order->id, '_billing_email', true ),
'country' => get_post_meta( $order->id, '_billing_country', true ),
'city' => get_post_meta( $order->id, '_billing_city', true ),
'family_name' => get_post_meta( $order->id, '_billing_last_name', true ),
'given_name' => get_post_meta( $order->id, '_billing_first_name', true ),
'street_address' => get_post_meta( $order->id, '_billing_address_1', true ),
'phone' => get_post_meta( $order->id, '_billing_phone', true )
);
$shipping_email = get_post_meta( $order->id, '_shipping_email', true ) ? get_post_meta( $order->id, '_shipping_email', true ) : get_post_meta( $order->id, '_billing_email', true );
$shipping_phone = get_post_meta( $order->id, '_shipping_phone', true ) ? get_post_meta( $order->id, '_shipping_phone', true ) : get_post_meta( $order->id, '_billing_phone', true );
$klarna_shipping = array(
'postal_code' => get_post_meta( $order->id, '_shipping_postcode', true ),
'email' => $shipping_email,
'country' => get_post_meta( $order->id, '_shipping_country', true ),
'city' => get_post_meta( $order->id, '_shipping_city', true ),
'family_name' => get_post_meta( $order->id, '_shipping_last_name', true ),
'given_name' => get_post_meta( $order->id, '_shipping_first_name', true ),
'street_address' => get_post_meta( $order->id, '_shipping_address_1', true ),
'phone' => $shipping_phone
);
// Products in subscription
$cart = array();
if ( sizeof( $order->get_items() ) > 0 ) {
foreach ( $order->get_items() as $item_key => $item ) {
$_product = $order->get_product_from_item( $item );
if ( $_product->exists() && $item['qty'] ) {
// Get SKU or product id
$reference = '';
if ( $_product->get_sku() ) {
$reference = $_product->get_sku();
} elseif ( $_product->variation_id ) {
$reference = $_product->variation_id;
} else {
$reference = $_product->id;
}
$recurring_price = $order->get_item_total( $item, true ) * 100;
$recurring_tax_rate = ( $item['line_tax'] / $item['line_total'] ) * 10000;
$cart[] = array(
'reference' => strval( $reference ),
'name' => utf8_decode( $item['name'] ),
'quantity' => (int) $item['qty'],
'unit_price' => (int) $recurring_price,
'discount_rate' => 0,
'tax_rate' => (int) $recurring_tax_rate
);
}
}
}
// Shipping
if ( $order->get_total_shipping() > 0 ) {
$shipping_price = ( $order->get_total_shipping() + $order->get_shipping_tax() ) * 100;
$shipping_tax_rate = ( $order->get_shipping_tax() / $order->get_total_shipping() ) * 10000;
$cart[] = array(
'type' => 'shipping_fee',
'reference' => 'SHIPPING',
'name' => __( 'Shipping Fee', 'woocommerce-gateway-klarna' ),
'quantity' => 1,
'unit_price' => (int) $shipping_price,
'tax_rate' => (int) $shipping_tax_rate
);
}
$create = array();
if ( 'yes' == $this->activate_recurring ) {
$create['activate'] = true;
} else {
$create['activate'] = false;
}
$create['purchase_currency'] = $klarna_currency;
$create['purchase_country'] = $klarna_country;
$create['locale'] = $klarna_locale;
$create['merchant']['id'] = $klarna_eid;
$create['billing_address'] = $klarna_billing;
$create['shipping_address'] = $klarna_shipping;
$create['merchant_reference'] = array(
'orderid1' => ltrim( $order->get_order_number(), '#' )
);
$create['cart'] = array();
foreach ( $cart as $item ) {
$create['cart']['items'][] = $item;
}
$connector = Klarna_Checkout_Connector::create( $klarna_secret, $this->klarna_server );
$klarna_order = new Klarna_Checkout_RecurringOrder( $connector, $klarna_recurring_token );
try {
$klarna_order->create( $create );
if ( isset( $klarna_order['invoice'] ) ) {
add_post_meta( $order->id, '_klarna_order_invoice_recurring', $klarna_order['invoice'], true );
$order->add_order_note( __( 'Klarna subscription payment invoice number: ', 'woocommerce-gateway-klarna' ) . $klarna_order['invoice'] );
} elseif ( isset( $klarna_order['reservation'] ) ) {
add_post_meta( $order->id, '_klarna_order_reservation_recurring', $klarna_order['reservation'], true );
$order->add_order_note( __( 'Klarna subscription payment reservation number: ', 'woocommerce-gateway-klarna' ) . $klarna_order['reservation'] );
}
return true;
} catch ( Klarna_Checkout_ApiErrorException $e ) {
$order->add_order_note( sprintf( __( 'Klarna subscription payment failed. Error code %s. Error message %s', 'woocommerce-gateway-klarna' ), $e->getCode(), utf8_encode( $e->getMessage() ) ) );
// error_log( var_export( $e, true ) );
return false;
}
}
/**
* Do not copy Klarna invoice number from completed subscription order to its renewal orders.
*
* @since 2.0
**/
function kco_recurring_do_not_copy_meta_data( $order_meta_query, $original_order_id, $renewal_order_id, $new_order_role ) {
$order_meta_query .= " AND `meta_key` NOT IN ('_klarna_invoice_number')";
return $order_meta_query;
}
//
// AJAX callbacks
//
/**
* Klarna Checkout cart AJAX callback.
*
* @since 2.0
**/
function klarna_checkout_cart_callback_update() {
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'klarna_checkout_nonce' ) ) {
exit( 'Nonce can not be verified.' );
}
global $woocommerce;
$updated_item_key = $_REQUEST['cart_item_key'];
$new_quantity = $_REQUEST['new_quantity'];
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
$cart_items = $woocommerce->cart->get_cart();
$updated_item = $cart_items[ $updated_item_key ];
$updated_product = wc_get_product( $updated_item['product_id'] );
// Update WooCommerce cart and transient order item
$klarna_sid = $woocommerce->session->get( 'klarna_sid' );
$woocommerce->cart->set_quantity( $updated_item_key, $new_quantity );
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
$this->update_or_create_local_order();
$data['widget_html'] = $this->klarna_checkout_get_kco_widget_html();
if ( WC()->session->get( 'klarna_checkout' ) ) {
$this->ajax_update_klarna_order();
}
wp_send_json_success( $data );
wp_die();
}
/**
* Klarna Checkout cart AJAX callback.
*
* @since 2.0
**/
function klarna_checkout_cart_callback_remove() {
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'klarna_checkout_nonce' ) ) {
exit( 'Nonce can not be verified.' );
}
global $woocommerce;
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
$cart_items = $woocommerce->cart->get_cart();
// Remove line item row
$removed_item_key = esc_attr( $_REQUEST['cart_item_key_remove'] );
$woocommerce->cart->remove_cart_item( $removed_item_key );
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
$this->update_or_create_local_order();
} else {
if ( $woocommerce->session->get( 'ongoing_klarna_order' ) ) {
wp_delete_post( $woocommerce->session->get( 'ongoing_klarna_order' ) );
$woocommerce->session->__unset( 'ongoing_klarna_order' );
}
}
// This needs to be sent back to JS, so cart widget can be updated
$data['item_count'] = $woocommerce->cart->get_cart_contents_count();
$data['cart_url'] = $woocommerce->cart->get_cart_url();
$data['widget_html'] = $this->klarna_checkout_get_kco_widget_html();
// Update ongoing Klarna order
if ( WC()->session->get( 'klarna_checkout' ) ) {
$this->ajax_update_klarna_order();
}
wp_send_json_success( $data );
wp_die();
}
/**
* Klarna Checkout coupons AJAX callback.
*
* @since 2.0
**/
function klarna_checkout_coupons_callback() {
global $woocommerce;
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'klarna_checkout_nonce' ) ) {
exit( 'Nonce can not be verified.' );
}
$data = array();
// Adding coupon
if ( ! empty( $_REQUEST['coupon'] ) && is_string( $_REQUEST['coupon'] ) ) {
$coupon = $_REQUEST['coupon'];
$coupon_success = $woocommerce->cart->add_discount( $coupon );
$applied_coupons = $woocommerce->cart->applied_coupons;
$woocommerce->session->set( 'applied_coupons', $applied_coupons );
$woocommerce->cart->calculate_totals();
wc_clear_notices(); // This notice handled by Klarna plugin
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
$this->update_or_create_local_order();
$coupon_object = new WC_Coupon( $coupon );
$amount = wc_price( $woocommerce->cart->get_coupon_discount_amount( $coupon, $woocommerce->cart->display_cart_ex_tax ) );
$data['amount'] = $amount;
$data['coupon_success'] = $coupon_success;
$data['coupon'] = $coupon;
$data['widget_html'] = $this->klarna_checkout_get_kco_widget_html();
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
if ( WC()->session->get( 'klarna_checkout' ) ) {
$this->ajax_update_klarna_order();
}
}
wp_send_json_success( $data );
wp_die();
}
/**
* Klarna Checkout coupons AJAX callback.
*
* @since 2.0
**/
function klarna_checkout_remove_coupon_callback() {
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'klarna_checkout_nonce' ) ) {
exit( 'Nonce can not be verified.' );
}
global $woocommerce;
$data = array();
// Removing coupon
if ( isset( $_REQUEST['remove_coupon'] ) ) {
$remove_coupon = $_REQUEST['remove_coupon'];
$woocommerce->cart->remove_coupon( $remove_coupon );
$applied_coupons = $woocommerce->cart->applied_coupons;
$woocommerce->session->set( 'applied_coupons', $applied_coupons );
$woocommerce->cart->calculate_totals();
wc_clear_notices(); // This notice handled by Klarna plugin
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
$this->update_or_create_local_order();
$data['widget_html'] = $this->klarna_checkout_get_kco_widget_html();
if ( WC()->session->get( 'klarna_checkout' ) ) {
$this->ajax_update_klarna_order();
}
}
wp_send_json_success( $data );
wp_die();
}
/**
* Klarna Checkout shipping AJAX callback.
*
* @since 2.0
**/
function klarna_checkout_shipping_callback() {
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'klarna_checkout_nonce' ) ) {
exit( 'Nonce can not be verified.' );
}
global $woocommerce;
$new_method = $_REQUEST['new_method'];
$chosen_shipping_methods[] = wc_clean( $new_method );
$woocommerce->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
$this->update_or_create_local_order();
$data['new_method'] = $new_method;
$data['widget_html'] = $this->klarna_checkout_get_kco_widget_html();
if ( WC()->session->get( 'klarna_checkout' ) ) {
$this->ajax_update_klarna_order();
}
wp_send_json_success( $data );
wp_die();
}
/**
* Klarna Checkout coupons AJAX callback.
*
* @since 2.0
**/
function klarna_checkout_order_note_callback() {
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'klarna_checkout_nonce' ) ) {
exit( 'Nonce can not be verified.' );
}
global $woocommerce;
$data = array();
// Adding coupon
if ( isset( $_REQUEST['order_note'] ) && is_string( $_REQUEST['order_note'] ) ) {
$order_note = sanitize_text_field( $_REQUEST['order_note'] );
$data['order_note'] = $order_note;
if ( WC()->session->get( 'klarna_checkout' ) ) {
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
$orderid = $this->update_or_create_local_order();
$order_details = array(
'ID' => $orderid,
'post_excerpt' => $order_note
);
$order_update = wp_update_post( $order_details );
if ( $this->debug == 'yes' ) {
$this->log->add( 'klarna', 'ORDERID: ' . $orderid );
}
$this->ajax_update_klarna_order();
WC()->session->set( 'klarna_order_note', $order_note );
}
}
wp_send_json_success( $data );
wp_die();
}
/**
* Klarna Checkout country selector AJAX callback.
*
* @since 2.0
**/
function klarna_checkout_country_callback() {
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'klarna_checkout_nonce' ) ) {
exit( 'Nonce can not be verified.' );
}
$data = array();
if ( isset( $_REQUEST['new_country'] ) && is_string( $_REQUEST['new_country'] ) ) {
$new_country = sanitize_text_field( $_REQUEST['new_country'] );
// Reset session
$klarna_order = null;
WC()->session->__unset( 'klarna_checkout' );
WC()->session->__unset( 'klarna_checkout_country' );
// Store new country as WC session value
WC()->session->set( 'klarna_euro_country', $new_country );
}
wp_send_json_success( $data );
wp_die();
}
/**
* Pushes Klarna order update in AJAX calls.
*
* Used to capture customer address, recalculate tax and shipping for order and user session
*
* @since 2.0
**/
function kco_iframe_change_cb() {
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'klarna_checkout_nonce' ) ) {
exit( 'Nonce can not be verified.' );
}
global $woocommerce;
$data = array();
// Check stock
if ( is_wp_error( $woocommerce->cart->check_cart_item_stock() ) ) {
wp_send_json_error();
wp_die();
}
// Capture email
if ( isset( $_REQUEST['email'] ) && is_string( $_REQUEST['email'] ) && ! is_user_logged_in() ) {
$this->update_or_create_local_order( $_REQUEST['email'] );
$orderid = $woocommerce->session->get( 'ongoing_klarna_order' );
$data['orderid'] = $orderid;
$connector = Klarna_Checkout_Connector::create( $this->klarna_secret, $this->klarna_server );
$klarna_order = new Klarna_Checkout_Order( $connector, WC()->session->get( 'klarna_checkout' ) );
$klarna_order->fetch();
$update['merchant']['push_uri'] = add_query_arg( array(
'sid' => $orderid
), $klarna_order['merchant']['push_uri'] );
$update['merchant']['confirmation_uri'] = add_query_arg( array(
'sid' => $orderid,
'order-received' => $orderid
), $klarna_order['merchant']['confirmation_uri'] );
$klarna_order->update( $update );
}
// Capture postal code
if ( isset( $_REQUEST['postal_code'] ) && is_string( $_REQUEST['postal_code'] ) && WC_Validation::is_postcode( $_REQUEST['postal_code'], $this->klarna_country ) ) {
$woocommerce->customer->set_shipping_postcode( $_REQUEST['postal_code'] );
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
// Update user session
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
// Update ongoing WooCommerce order
$this->update_or_create_local_order();
$data['widget_html'] = $this->klarna_checkout_get_kco_widget_html();
if ( WC()->session->get( 'klarna_checkout' ) ) {
$this->ajax_update_klarna_order();
}
}
wp_send_json_success( $data );
wp_die();
}
/**
* Klarna order shipping address change callback function.
*
* @since 2.0
**/
function kco_iframe_shipping_address_change_cb() {
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'klarna_checkout_nonce' ) ) {
exit( 'Nonce can not be verified.' );
}
global $woocommerce;
$data = array();
// Capture postal code
if ( isset( $_REQUEST['postal_code'] ) && is_string( $_REQUEST['postal_code'] ) ) {
$woocommerce->customer->set_postcode( $_REQUEST['postal_code'] );
$woocommerce->customer->set_shipping_postcode( $_REQUEST['postal_code'] );
}
if ( isset( $_REQUEST['region'] ) && is_string( $_REQUEST['region'] ) ) {
$woocommerce->customer->set_state( $_REQUEST['region'] );
$woocommerce->customer->set_shipping_state( $_REQUEST['region'] );
}
if ( isset( $_REQUEST['country'] ) && is_string( $_REQUEST['country'] ) ) {
$woocommerce->customer->set_country( 'US' );
$woocommerce->customer->set_shipping_country( 'US' );
}
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
$this->update_or_create_local_order();
$data['widget_html'] = $this->klarna_checkout_get_kco_widget_html();
if ( WC()->session->get( 'klarna_checkout' ) ) {
$this->ajax_update_klarna_order();
}
wp_send_json_success( $data );
wp_die();
}
/**
* Klarna order shipping option change callback function.
*
* @since 2.0
**/
function kco_iframe_shipping_option_change_cb() {
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'klarna_checkout_nonce' ) ) {
exit( 'Nonce can not be verified.' );
}
global $woocommerce;
$new_method = $_REQUEST['new_method'];
$chosen_shipping_methods[] = wc_clean( $new_method );
$woocommerce->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
$this->update_or_create_local_order();
$data['new_method'] = $new_method;
$data['widget_html'] = $this->klarna_checkout_get_kco_widget_html();
if ( WC()->session->get( 'klarna_checkout' ) ) {
$this->ajax_update_klarna_order();
}
wp_send_json_success( $data );
wp_die();
}
/**
* Pushes Klarna order update in AJAX calls.
*
* @since 2.0
**/
function ajax_update_klarna_order() {
global $woocommerce;
// Check if Euro is selected, get correct country
if ( 'EUR' == get_woocommerce_currency() && WC()->session->get( 'klarna_euro_country' ) ) {
$klarna_c = strtolower( WC()->session->get( 'klarna_euro_country' ) );
$eid = $this->settings["eid_$klarna_c"];
$sharedSecret = $this->settings["secret_$klarna_c"];
} else {
$eid = $this->klarna_eid;
$sharedSecret = $this->klarna_secret;
}
if ( $this->is_rest() ) {
if ( $this->testmode == 'yes' ) {
if ( 'gb' == $this->klarna_country ) {
$klarna_server_url = Klarna\Rest\Transport\ConnectorInterface::EU_TEST_BASE_URL;
} elseif ( 'us' == $this->klarna_country ) {
$klarna_server_url = Klarna\Rest\Transport\ConnectorInterface::NA_TEST_BASE_URL;
}
} else {
if ( 'gb' == $this->klarna_country ) {
$klarna_server_url = Klarna\Rest\Transport\ConnectorInterface::EU_BASE_URL;
} elseif ( 'us' == $this->klarna_country ) {
$klarna_server_url = Klarna\Rest\Transport\ConnectorInterface::NA_BASE_URL;
}
}
$connector = Klarna\Rest\Transport\Connector::create( $eid, $sharedSecret, $klarna_server_url );
$klarna_order = new \Klarna\Rest\Checkout\Order( $connector, WC()->session->get( 'klarna_checkout' ) );
} else {
$connector = Klarna_Checkout_Connector::create( $sharedSecret, $this->klarna_server );
$klarna_order = new Klarna_Checkout_Order( $connector, WC()->session->get( 'klarna_checkout' ) );
$klarna_order->fetch();
}
// Process cart contents and prepare them for Klarna
include_once( KLARNA_DIR . 'classes/class-wc-to-klarna.php' );
$wc_to_klarna = new WC_Gateway_Klarna_WC2K( $this->is_rest(), $this->klarna_country );
$cart = $wc_to_klarna->process_cart_contents();
if ( 0 == count( $cart ) ) {
$klarna_order = null;
} else {
// Reset cart
if ( $this->is_rest() ) {
$update['order_lines'] = array();
$klarna_order_total = 0;
$klarna_tax_total = 0;
foreach ( $cart as $item ) {
$update['order_lines'][] = $item;
$klarna_order_total += $item['total_amount'];
// Process sales_tax item differently
if ( array_key_exists( 'type', $item ) && 'sales_tax' == $item['type'] ) {
$klarna_tax_total += $item['total_amount'];
} else {
$klarna_tax_total += $item['total_tax_amount'];
}
}
$update['order_amount'] = $klarna_order_total;
$update['order_tax_amount'] = $klarna_tax_total;
} else {
$update['cart']['items'] = array();
foreach ( $cart as $item ) {
$update['cart']['items'][] = $item;
}
}
try {
$klarna_order->update( apply_filters( 'kco_update_order', $update ) );
} catch ( Exception $e ) {
if ( $this->debug == 'yes' ) {
$this->log->add( 'klarna', 'KCO ERROR: ' . var_export( $e, true ) );
error_log( 'ERROR: ' . var_export( $e, true ) );
}
}
}
}
//
//
//
/**
* Gets Klarna checkout widget HTML.
* Used in KCO widget.
*
* @param $atts Array
*
* @return String shortcode output
*
* @since 2.0
**/
function klarna_checkout_get_kco_widget_html( $atts = null ) {
global $woocommerce;
ob_start();
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
?>
<!-- Coupons -->
<?php woocommerce_checkout_coupon_form(); ?>
<!-- Cart items -->
<?php echo $this->klarna_checkout_get_cart_contents_html( $atts ); ?>
<!-- Totals -->
<div>
<table id="kco-totals">
<tbody>
<tr id="kco-page-subtotal">
<td class="kco-col-desc"><?php _e( 'Subtotal', 'woocommerce-gateway-klarna' ); ?></td>
<td id="kco-page-subtotal-amount" class="kco-col-number kco-rightalign"><span
class="amount"><?php echo $woocommerce->cart->get_cart_subtotal(); ?></span></td>
</tr>
<?php echo $this->klarna_checkout_get_shipping_options_row_html(); // Shipping options ?>
<?php echo $this->klarna_checkout_get_fees_row_html(); // Fees ?>
<?php echo $this->klarna_checkout_get_coupon_rows_html(); // Coupons ?>
<?php echo $this->klarna_checkout_get_taxes_rows_html(); // Taxes ?>
<?php /* Cart total */ ?>
<tr id="kco-page-total">
<td class="kco-bold"><?php _e( 'Total', 'woocommerce-gateway-klarna' ); ?></a></td>
<td id="kco-page-total-amount" class="kco-rightalign kco-bold"><span
class="amount"><?php echo $woocommerce->cart->get_total(); ?></span></td>
</tr>
<?php /* Cart total */ ?>
</tbody>
</table>
</div>
<!-- Order note -->
<?php if ( 'false' != $atts['order_note'] ) { ?>
<div>
<form>
<?php
if ( WC()->session->get( 'klarna_order_note' ) ) {
$order_note = WC()->session->get( 'klarna_order_note' );
} else {
$order_note = '';
}
?>
<textarea id="klarna-checkout-order-note" class="input-text" name="klarna-checkout-order-note"
placeholder="<?php _e( 'Notes about your order, e.g. special notes for delivery.', 'woocommerce-gateway-klarna' ); ?>"><?php echo $order_note; ?></textarea>
</form>
</div>
<?php }
return ob_get_clean();
}
/**
* Gets cart contents as formatted HTML.
* Used in KCO widget.
*
* @since 2.0
**/
function klarna_checkout_get_cart_contents_html( $atts ) {
global $woocommerce;
ob_start();
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
$hide_columns = array();
if ( '' != $atts['hide_columns'] ) {
$hide_columns = explode( ',', $atts['hide_columns'] );
}
?>
<div>
<table id="klarna-checkout-cart">
<tbody>
<tr>
<?php if ( ! in_array( 'remove', $hide_columns ) ) { ?>
<th class="product-remove kco-leftalign"></th>
<?php } ?>
<th class="product-name kco-leftalign"><?php _e( 'Product', 'woocommerce-gateway-klarna' ); ?></th>
<?php if ( ! in_array( 'price', $hide_columns ) ) { ?>
<th class="product-price kco-centeralign"><?php _e( 'Price', 'woocommerce-gateway-klarna' ); ?></th>
<?php } ?>
<th class="product-quantity kco-centeralign"><?php _e( 'Quantity', 'woocommerce-gateway-klarna' ); ?></th>
<th class="product-total kco-rightalign"><?php _e( 'Total', 'woocommerce-gateway-klarna' ); ?></th>
</tr>
<?php
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = $cart_item['data'];
$cart_item_product = wc_get_product( $cart_item['product_id'] );
echo '<tr>';
if ( ! in_array( 'remove', $hide_columns ) ) {
echo '<td class="kco-product-remove kco-leftalign"><a href="#">x</a></td>';
}
echo '<td class="product-name kco-leftalign">';
if ( ! $_product->is_visible() ) {
echo apply_filters( 'woocommerce_cart_item_name', $_product->get_title(), $cart_item, $cart_item_key ) . ' ';
} else {
echo apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s </a>', $_product->get_permalink( $cart_item ), $_product->get_title() ), $cart_item, $cart_item_key );
}
// Meta data
echo $woocommerce->cart->get_item_data( $cart_item );
echo '</td>';
if ( ! in_array( 'price', $hide_columns ) ) {
echo '<td class="product-price kco-centeralign"><span class="amount">';
echo $woocommerce->cart->get_product_price( $_product );
echo '</span></td>';
}
echo '<td class="product-quantity kco-centeralign" data-cart_item_key="' . $cart_item_key . '">';
if ( $_product->is_sold_individually() ) {
$product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', esc_attr( $cart_item_key ) );
} else {
$product_quantity = woocommerce_quantity_input( array(
'input_name' => "cart[{$cart_item_key}][qty]",
'input_value' => $cart_item['quantity'],
'max_value' => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(),
'min_value' => '1'
), $_product, false );
}
echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key );
echo '</td>';
echo '<td class="product-total kco-rightalign"><span class="amount">';
echo apply_filters( 'woocommerce_cart_item_subtotal', $woocommerce->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key );
echo '</span></td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
<?php
return ob_get_clean();
}
/**
* Gets shipping options as formatted HTML.
*
* @since 2.0
**/
function klarna_checkout_get_shipping_options_row_html() {
global $woocommerce;
ob_start();
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
?>
<tr id="kco-page-shipping">
<?php
// if ( WC()->session->get( 'klarna_is_rest', false ) ) { // Just show shipping cost for Rest
// Temporarily commented out while Klarna works on this feaure and replaced by the check below
// that always returns true.
?>
<?php if ( 1 > 2 ) { // Just show shipping cost for Rest ?>
<td>
<?php _e( 'Shipping', 'woocommerce-gateway-klarna' ); ?>
</td>
<td id="kco-page-shipping-total" class="kco-rightalign">
<?php echo $woocommerce->cart->get_cart_shipping_total(); ?>
</td>
<?php } else { ?>
<td>
<?php
$woocommerce->cart->calculate_shipping();
$packages = $woocommerce->shipping->get_packages();
foreach ( $packages as $i => $package ) {
$chosen_method = isset( $woocommerce->session->chosen_shipping_methods[ $i ] ) ? $woocommerce->session->chosen_shipping_methods[ $i ] : '';
$available_methods = $package['rates'];
$show_package_details = sizeof( $packages ) > 1;
$index = $i;
?>
<?php if ( ! empty( $available_methods ) ) { ?>
<?php if ( 1 === count( $available_methods ) ) {
$method = current( $available_methods );
echo wp_kses_post( wc_cart_totals_shipping_method_label( $method ) ); ?>
<input type="hidden" name="shipping_method[<?php echo esc_attr( $index ); ?>]"
data-index="<?php echo esc_attr( $index ); ?>"
id="shipping_method_<?php echo esc_attr( $index ); ?>"
value="<?php echo esc_attr( $method->id ); ?>" class="shipping_method"/>
<?php } else { ?>
<p style="margin: 0 0 0.5em !important; padding: 0 !important;"><?php _e( 'Shipping', 'woocommerce-gateway-klarna' ); ?></p>
<ul id="shipping_method">
<?php foreach ( $available_methods as $method ) : ?>
<li>
<input style="margin-left:3px" type="radio"
name="shipping_method[<?php echo esc_attr( $index ); ?>]"
data-index="<?php echo esc_attr( $index ); ?>"
id="shipping_method_<?php echo esc_attr( $index ); ?>_<?php echo esc_attr( sanitize_title( $method->id ) ); ?>"
value="<?php echo esc_attr( $method->id ); ?>" <?php checked( $method->id, $chosen_method ); ?>
class="shipping_method"/>
<label
for="shipping_method_<?php echo esc_attr( $index ); ?>_<?php echo esc_attr( sanitize_title( $method->id ) ); ?>"><?php echo wp_kses_post( wc_cart_totals_shipping_method_label( $method ) ); ?></label>
</li>
<?php endforeach; ?>
</ul>
<?php } ?>
<?php } ?>
<?php
}
?>
</td>
<td id="kco-page-shipping-total" class="kco-rightalign">
<?php echo $woocommerce->cart->get_cart_shipping_total(); ?>
</td>
<?php } ?>
</tr>
<?php
return ob_get_clean();
}
/**
* Gets shipping options as formatted HTML.
*
* @since 2.0
**/
function klarna_checkout_get_fees_row_html() {
global $woocommerce;
ob_start();
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_fees();
$woocommerce->cart->calculate_totals();
// Fees
foreach ( $woocommerce->cart->get_fees() as $cart_fee ) {
echo '<tr class="kco-fee">';
echo '<td class="kco-col-desc">';
echo strip_tags( $cart_fee->name );
echo '</td>';
echo '<td class="kco-col-number kco-rightalign"><span class="amount">';
// echo wc_price( $cart_fee->amount + $cart_fee->tax );
echo wc_cart_totals_fee_html( $cart_fee );
echo '</span></td>';
echo '</tr>';
}
return ob_get_clean();
}
/**
* Gets coupons as formatted HTML.
*
* @since 2.0
**/
function klarna_checkout_get_coupon_rows_html() {
global $woocommerce;
ob_start();
foreach ( $woocommerce->cart->get_applied_coupons() as $coupon ) { ?>
<tr class="kco-applied-coupon">
<td>
<?php _e( 'Coupon: ', 'woocommerce-gateway-klarna' ); ?><?php echo $coupon; ?>
<a class="kco-remove-coupon" data-coupon="<?php echo $coupon; ?>" href="#">(remove)</a>
</td>
<td class="kco-rightalign">
-<?php echo wc_price( $woocommerce->cart->get_coupon_discount_amount( $coupon, $woocommerce->cart->display_cart_ex_tax ) ); ?></td>
</tr>
<?php }
return ob_get_clean();
}
/**
* Gets coupons as formatted HTML.
*
* @since 2.0
**/
function klarna_checkout_get_taxes_rows_html() {
ob_start();
if ( wc_tax_enabled() && 'excl' === WC()->cart->tax_display_cart ) {
if ( 'itemized' === get_option( 'woocommerce_tax_total_display' ) ) {
foreach ( WC()->cart->get_tax_totals() as $code => $tax ) { ?>
<tr class="kco-tax-rate kco-tax-rate-<?php echo sanitize_title( $code ); ?>">
<td><?php echo esc_html( $tax->label ); ?></td>
<td class="kco-rightalign"
data-title="<?php echo esc_html( $tax->label ); ?>"><?php echo wp_kses_post( $tax->formatted_amount ); ?></td>
</tr>
<?php }
} else { ?>
<tr class="tax-total">
<td><?php echo esc_html( WC()->countries->tax_or_vat() ); ?></td>
<td class="kco-rightalign" data-title="<?php echo esc_html( WC()->countries->tax_or_vat() );
?>"><?php wc_cart_totals_taxes_total_html(); ?></td>
</tr>
<?php }
}
return ob_get_clean();
}
/**
* WooCommerce cart to Klarna cart items.
*
* Helper functions that format WooCommerce cart items for Klarna order items.
*
* @since 2.0
**/
function cart_to_klarna() {
global $woocommerce;
$woocommerce->cart->calculate_shipping();
$woocommerce->cart->calculate_totals();
/**
* Process cart contents
*/
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item ) {
if ( $cart_item['quantity'] ) {
$_product = wc_get_product( $cart_item['product_id'] );
// We manually calculate the tax percentage here
if ( $_product->is_taxable() && $cart_item['line_subtotal_tax'] > 0 ) {
// Calculate tax percentage
$item_tax_percentage = round( $cart_item['line_subtotal_tax'] / $cart_item['line_subtotal'], 2 ) * 100;
} else {
$item_tax_percentage = 00;
}
$cart_item_data = $cart_item['data'];
$cart_item_name = $cart_item_data->post->post_title;
if ( isset( $cart_item['item_meta'] ) ) {
$item_meta = new WC_Order_Item_Meta( $cart_item['item_meta'] );
if ( $meta = $item_meta->display( true, true ) ) {
$item_name .= ' ( ' . $meta . ' )';
}
}
// apply_filters to item price so we can filter this if needed
$klarna_item_price_including_tax = $cart_item['line_subtotal'] + $cart_item['line_subtotal_tax'];
$item_price = apply_filters( 'klarna_item_price_including_tax', $klarna_item_price_including_tax );
// Get SKU or product id
$reference = '';
if ( $_product->get_sku() ) {
$reference = $_product->get_sku();
} elseif ( $_product->variation_id ) {
$reference = $_product->variation_id;
} else {
$reference = $_product->id;
}
$total_amount = (int) ( $cart_item['line_total'] + $cart_item['line_tax'] ) * 100;
$item_price = number_format( $item_price * 100, 0, '', '' ) / $cart_item['quantity'];
// Check if there's a discount applied
if ( $cart_item['line_subtotal'] > $cart_item['line_total'] ) {
$item_discount_rate = round( 1 - ( $cart_item['line_total'] / $cart_item['line_subtotal'] ), 2 ) * 10000;
$item_discount = ( $item_price * $cart_item['quantity'] - $total_amount );
} else {
$item_discount_rate = 0;
$item_discount = 0;
}
if ( $this->is_rest() ) {
$klarna_item = array(
'reference' => strval( $reference ),
'name' => strip_tags( $cart_item_name ),
'quantity' => (int) $cart_item['quantity'],
'unit_price' => (int) $item_price,
'tax_rate' => intval( $item_tax_percentage . '00' ),
'total_amount' => $total_amount,
'total_tax_amount' => $cart_item['line_subtotal_tax'] * 100,
'total_discount_amount' => $item_discount
);
} else {
$klarna_item = array(
'reference' => strval( $reference ),
'name' => strip_tags( $cart_item_name ),
'quantity' => (int) $cart_item['quantity'],
'unit_price' => (int) $item_price,
'tax_rate' => intval( $item_tax_percentage . '00' ),
'discount_rate' => $item_discount_rate
);
}
$cart[] = $klarna_item;
} // End if qty
} // End foreach
} // End if sizeof get_items()
/**
* Process shipping
*/
if ( $woocommerce->cart->shipping_total > 0 ) {
// We manually calculate the tax percentage here
if ( $woocommerce->cart->shipping_tax_total > 0 ) {
// Calculate tax percentage
$shipping_tax_percentage = round( $woocommerce->cart->shipping_tax_total / $woocommerce->cart->shipping_total, 2 ) * 100;
} else {
$shipping_tax_percentage = 00;
}
$shipping_price = number_format( ( $woocommerce->cart->shipping_total + $woocommerce->cart->shipping_tax_total ) * 100, 0, '', '' );
// Get shipping method name
$shipping_packages = $woocommerce->shipping->get_packages();
foreach ( $shipping_packages as $i => $package ) {
$chosen_method = isset( $woocommerce->session->chosen_shipping_methods[ $i ] ) ? $woocommerce->session->chosen_shipping_methods[ $i ] : '';
if ( '' != $chosen_method ) {
$package_rates = $package['rates'];
foreach ( $package_rates as $rate_key => $rate_value ) {
if ( $rate_key == $chosen_method ) {
$klarna_shipping_method = $rate_value->label;
}
}
}
}
if ( ! isset( $klarna_shipping_method ) ) {
$klarna_shipping_method = __( 'Shipping', 'woocommerce-gateway-klarna' );
}
$shipping = array(
'type' => 'shipping_fee',
'reference' => 'SHIPPING',
'name' => $klarna_shipping_method,
'quantity' => 1,
'unit_price' => (int) $shipping_price,
'tax_rate' => intval( $shipping_tax_percentage . '00' )
);
if ( $this->is_rest() ) {
$shipping['total_amount'] = (int) $shipping_price;
$shipping['total_tax_amount'] = $woocommerce->cart->shipping_tax_total * 100;
}
$cart[] = $shipping;
}
return $cart;
}
/**
* Initialise Gateway Settings Form Fields
*
* @since 1.0.0
*/
function init_form_fields() {
$this->form_fields = include( KLARNA_DIR . 'includes/settings-checkout.php' );
}
/**
* Admin Panel Options
*
* @since 1.0.0
*/
public function admin_options() { ?>
<h3><?php _e( 'Klarna Checkout', 'woocommerce-gateway-klarna' ); ?></h3>
<p>
<?php printf( __( 'With Klarna Checkout your customers can pay by invoice or credit card. Klarna Checkout works by replacing the standard WooCommerce checkout form. Documentation <a href="%s" target="_blank">can be found here</a>.', 'woocommerce-gateway-klarna' ), 'https://docs.woothemes.com/document/klarna/' ); ?>
</p>
<?php
// If the WooCommerce terms page isn't set, do nothing.
$klarna_terms_page = get_option( 'woocommerce_terms_page_id' );
if ( empty( $klarna_terms_page ) && empty( $this->terms_url ) ) {
echo '<strong>' . __( 'You need to specify a Terms Page in the WooCommerce settings or in the Klarna Checkout settings in order to enable the Klarna Checkout payment method.', 'woocommerce-gateway-klarna' ) . '</strong>';
}
?>
<table class="form-table">
<?php $this->generate_settings_html(); ?>
</table><!--/.form-table-->
<?php }
/**
* Disabled KCO on regular checkout page
*
* @since 1.0.0
*/
function is_available() {
if ( defined( 'WOOCOMMERCE_KLARNA_AVAILABLE' ) || ! is_checkout() ) {
return true;
}
return false;
}
/**
* Set up Klarna configuration.
*
* @since 2.0
**/
function configure_klarna( $klarna, $country ) {
// Country and language
switch ( $country ) {
case 'NO' :
case 'NB' :
$klarna_country = 'NO';
$klarna_language = 'nb-no';
$klarna_currency = 'NOK';
$klarna_eid = $this->eid_no;
$klarna_secret = $this->secret_no;
break;
case 'FI' :
$klarna_country = 'FI';
// Check if WPML is used and determine if Finnish or Swedish is used as language
if ( class_exists( 'woocommerce_wpml' ) && defined( 'ICL_LANGUAGE_CODE' ) && strtoupper( ICL_LANGUAGE_CODE ) == 'SV' ) {
$klarna_language = 'sv-fi'; // Swedish
} else {
$klarna_language = 'fi-fi'; // Finnish
}
$klarna_currency = 'EUR';
$klarna_eid = $this->eid_fi;
$klarna_secret = $this->secret_fi;
break;
case 'SE' :
case 'SV' :
$klarna_country = 'SE';
$klarna_language = 'sv-se';
$klarna_currency = 'SEK';
$klarna_eid = $this->eid_se;
$klarna_secret = $this->secret_se;
break;
case 'DE' :
$klarna_country = 'DE';
$klarna_language = 'de-de';
$klarna_currency = 'EUR';
$klarna_eid = $this->eid_de;
$klarna_secret = $this->secret_de;
break;
case 'AT' :
$klarna_country = 'AT';
$klarna_language = 'de-at';
$klarna_currency = 'EUR';
$klarna_eid = $this->eid_at;
$klarna_secret = $this->secret_at;
break;
case 'GB' :
$klarna_country = 'gb';
$klarna_language = 'en-gb';
$klarna_currency = 'gbp';
$klarna_eid = $this->eid_uk;
$klarna_secret = $this->secret_uk;
break;
default:
$klarna_country = '';
$klarna_language = '';
$klarna_currency = '';
$klarna_eid = '';
$klarna_secret = '';
}
$klarna->config( $eid = $klarna_eid, $secret = $klarna_secret, $country = $country, $language = $klarna_language, $currency = $klarna_currency, $mode = $this->klarna_mode, $pcStorage = 'json', $pcURI = '/srv/pclasses.json', $ssl = $this->klarna_ssl, $candice = false );
}
/**
* Render checkout page
*
* @since 1.0.0
*/
function get_klarna_checkout_page() {
global $woocommerce;
global $current_user;
get_currentuserinfo();
// Debug
if ( $this->debug == 'yes' ) {
$this->log->add( 'klarna', 'KCO page about to render...' );
}
// Check if Klarna order exists, if it does display thank you page
// otherwise display checkout page
if ( isset( $_GET['klarna_order'] ) ) { // Display Order response/thank you page via iframe from Klarna
ob_start();
include( KLARNA_DIR . 'includes/checkout/thank-you.php' );
return ob_get_clean();
} else { // Display Checkout page
ob_start();
include( KLARNA_DIR . 'includes/checkout/checkout.php' );
return ob_get_clean();
} // End if isset($_GET['klarna_order'])
} // End Function
/**
* Creates a WooCommerce order, or updates if already created
*
* @since 1.0.0
*/
function update_or_create_local_order( $customer_email = '' ) {
if ( is_user_logged_in() ) {
global $current_user;
$customer_email = $current_user->user_email;
}
if ( '' == $customer_email ) {
$customer_email = 'guest_checkout@klarna.com';
}
if ( ! is_email( $customer_email ) ) {
return;
}
// Check quantities
global $woocommerce;
$result = $woocommerce->cart->check_cart_item_stock();
if ( is_wp_error( $result ) ) {
return $result->get_error_message();
}
// Update the local order
include_once( KLARNA_DIR . 'classes/class-klarna-to-wc.php' );
$klarna_to_wc = new WC_Gateway_Klarna_K2WC();
$klarna_to_wc->set_rest( $this->is_rest() );
$klarna_to_wc->set_eid( $this->klarna_eid );
$klarna_to_wc->set_secret( $this->klarna_secret );
$klarna_to_wc->set_klarna_log( $this->log );
$klarna_to_wc->set_klarna_debug( $this->debug );
$klarna_to_wc->set_klarna_test_mode( $this->testmode );
$klarna_to_wc->set_klarna_server( $this->klarna_server );
if ( $customer_email ) {
$orderid = $klarna_to_wc->prepare_wc_order( $customer_email );
} else {
$orderid = $klarna_to_wc->prepare_wc_order();
}
return $orderid;
}
/**
* Order confirmation via IPN
*
* @since 1.0.0
*/
function check_checkout_listener() {
$this->log->add( 'klarna', 'Checkout listener hit.' );
if ( isset( $_GET['validate'] ) ) {
exit;
}
switch ( $_GET['scountry'] ) {
case 'SE':
$klarna_secret = $this->secret_se;
$klarna_eid = $this->eid_se;
break;
case 'FI' :
$klarna_secret = $this->secret_fi;
$klarna_eid = $this->eid_se;
break;
case 'NO' :
$klarna_secret = $this->secret_no;
$klarna_eid = $this->eid_no;
break;
case 'DE' :
$klarna_secret = $this->secret_de;
$klarna_eid = $this->eid_de;
break;
case 'AT' :
$klarna_secret = $this->secret_at;
$klarna_eid = $this->eid_at;
break;
case 'gb' :
$klarna_secret = $this->secret_uk;
$klarna_eid = $this->eid_uk;
break;
case 'us' :
$klarna_secret = $this->secret_us;
$klarna_eid = $this->eid_us;
break;
default:
$klarna_secret = '';
}
// Process cart contents and prepare them for Klarna
if ( isset( $_GET['klarna_order'] ) ) {
include_once( KLARNA_DIR . 'classes/class-klarna-to-wc.php' );
$klarna_to_wc = new WC_Gateway_Klarna_K2WC();
$klarna_to_wc->set_rest( $this->is_rest() );
$klarna_to_wc->set_eid( $klarna_eid );
$klarna_to_wc->set_secret( $klarna_secret );
$klarna_to_wc->set_klarna_order_uri( $_GET['klarna_order'] );
$klarna_to_wc->set_klarna_log( $this->log );
$klarna_to_wc->set_klarna_test_mode( $this->testmode );
$klarna_to_wc->set_klarna_debug( $this->debug );
$klarna_to_wc->set_klarna_server( $this->klarna_server );
$klarna_to_wc->listener();
}
} // End function check_checkout_listener
/**
* Helper function get_enabled
*
* @since 1.0.0
*/
function get_enabled() {
return $this->enabled;
}
/**
* Helper function get_modify_standard_checkout_url
*
* @since 1.0.0
*/
function get_modify_standard_checkout_url() {
return $this->modify_standard_checkout_url;
}
/**
* Helper function get_klarna_checkout_page
*
* @since 1.0.0
*/
function get_klarna_checkout_url() {
return $this->klarna_checkout_url;
}
/**
* Helper function get_klarna_country
*
* @since 1.0.0
*/
function get_klarna_country() {
return $this->klarna_country;
}
/**
* Helper function - get correct currency for selected country
*
* @since 1.0.0
*/
function get_currency_for_country( $country ) {
switch ( $country ) {
case 'DK':
$currency = 'DKK';
break;
case 'DE' :
$currency = 'EUR';
break;
case 'NL' :
$currency = 'EUR';
break;
case 'NO' :
$currency = 'NOK';
break;
case 'FI' :
$currency = 'EUR';
break;
case 'SE' :
$currency = 'SEK';
break;
case 'AT' :
$currency = 'EUR';
break;
default:
$currency = '';
}
return $currency;
}
/**
* Helper function - get Account Signup Text
*
* @since 1.0.0
*/
public function get_account_signup_text() {
return $this->account_signup_text;
}
/**
* Helper function - get Account Login Text
*
* @since 1.0.0
*/
public function get_account_login_text() {
return $this->account_login_text;
}
/**
* Helper function - get Subscription Product ID
*
* @since 2.0.0
*/
public function get_subscription_product_id() {
global $woocommerce;
$subscription_product_id = false;
if ( ! empty( $woocommerce->cart->cart_contents ) ) {
foreach ( $woocommerce->cart->cart_contents as $cart_item ) {
if ( WC_Subscriptions_Product::is_subscription( $cart_item['product_id'] ) ) {
$subscription_product_id = $cart_item['product_id'];
break;
}
}
}
return $subscription_product_id;
}
/**
* Can the order be refunded via Klarna?
*
* @param WC_Order $order
*
* @return bool
* @since 2.0.0
*/
public function can_refund_order( $order ) {
if ( get_post_meta( $order->id, '_klarna_invoice_number', true ) ) {
return true;
}
return false;
}
/**
* Refund order in Klarna system
*
* @param integer $orderid
* @param integer $amount
* @param string $reason
*
* @return bool
* @since 2.0.0
*/
public function process_refund( $orderid, $amount = null, $reason = '' ) {
// Check if order was created using this method
if ( $this->id == get_post_meta( $orderid, '_payment_method', true ) ) {
$order = wc_get_order( $orderid );
if ( ! $this->can_refund_order( $order ) ) {
if ( $this->debug == 'yes' ) {
$this->log->add( 'klarna', 'Refund Failed: No Klarna invoice ID.' );
}
$order->add_order_note( __( 'This order cannot be refunded. Please make sure it is activated.', 'woocommerce-gateway-klarna' ) );
return false;
}
if ( 'v2' == get_post_meta( $order->id, '_klarna_api', true ) ) {
$country = get_post_meta( $orderid, '_billing_country', true );
$klarna = new Klarna();
$this->configure_klarna( $klarna, $country );
$invNo = get_post_meta( $order->id, '_klarna_invoice_number', true );
$klarna_order = new WC_Gateway_Klarna_Order( $order, $klarna );
$refund_order = $klarna_order->refund_order( $amount, $reason, $invNo );
} elseif ( 'rest' == get_post_meta( $order->id, '_klarna_api', true ) ) {
$country = get_post_meta( $orderid, '_billing_country', true );
/**
* Need to send local order to constructor and Klarna order to method
*/
if ( $this->testmode == 'yes' ) {
if ( 'gb' == strtolower( $country ) ) {
$klarna_server_url = Klarna\Rest\Transport\ConnectorInterface::EU_TEST_BASE_URL;
} elseif ( 'us' == strtolower( $country ) ) {
$klarna_server_url = Klarna\Rest\Transport\ConnectorInterface::NA_TEST_BASE_URL;
}
} else {
if ( 'gb' == strtolower( $country ) ) {
$klarna_server_url = Klarna\Rest\Transport\ConnectorInterface::EU_BASE_URL;
} elseif ( 'us' == strtolower( $country ) ) {
$klarna_server_url = Klarna\Rest\Transport\ConnectorInterface::NA_BASE_URL;
}
}
if ( 'gb' == strtolower( $country ) ) {
$connector = Klarna\Rest\Transport\Connector::create( $this->eid_uk, $this->secret_uk, $klarna_server_url );
} elseif ( 'us' == strtolower( $country ) ) {
$connector = Klarna\Rest\Transport\Connector::create( $this->eid_us, $this->secret_us, $klarna_server_url );
}
$klarna_order_id = get_post_meta( $orderid, '_klarna_order_id', true );
$k_order = new Klarna\Rest\OrderManagement\Order( $connector, $klarna_order_id );
$k_order->fetch();
$klarna_order = new WC_Gateway_Klarna_Order( $order );
$refund_order = $klarna_order->refund_order_rest( $amount, $reason, $k_order );
}
if ( $refund_order ) {
return true;
}
}
return false;
}
/**
* Determines which version of Klarna API should be used
*
* @return boolean
* @since 2.0.0
*/
function is_rest() {
if ( 'GB' == $this->klarna_country || 'gb' == $this->klarna_country || 'US' == $this->klarna_country || 'us' == $this->klarna_country ) {
// Set it in session as well, to be used in Shortcodes class
WC()->session->set( 'klarna_is_rest', true );
return true;
}
// Set it in session as well, to be used in Shortcodes class
WC()->session->set( 'klarna_is_rest', false );
return false;
}
/**
* Determines if KCO checkout page should be displayed.
*
* @return boolean
* @since 2.0.0
*/
function show_kco() {
// Don't render the Klarna Checkout form if the payment gateway isn't enabled.
if ( $this->enabled != 'yes' ) {
// Set it in session as well, to be used in Shortcodes class
WC()->session->set( 'klarna_show_kco', false );
return false;
}
// If checkout registration is disabled and not logged in, the user cannot checkout
global $woocommerce;
$checkout = $woocommerce->checkout();
if ( ! $checkout->enable_guest_checkout && ! is_user_logged_in() ) {
echo apply_filters( 'klarna_checkout_must_be_logged_in_message', sprintf( __( 'You must be logged in to checkout. %s or %s.', 'woocommerce' ), '<a href="' . wp_login_url() . '" title="Login">Login</a>', '<a href="' . wp_registration_url() . '" title="Create an account">create an account</a>' ) );
WC()->session->set( 'klarna_show_kco', false );
return false;
}
// If no Klarna country is set - return.
if ( empty( $this->klarna_country ) ) {
echo apply_filters( 'klarna_checkout_wrong_country_message', sprintf( __( 'Sorry, you can not buy via Klarna Checkout from your country or currency. Please <a href="%s">use another payment method</a>. ', 'woocommerce-gateway-klarna' ), get_permalink( get_option( 'woocommerce_checkout_page_id' ) ) ) );
WC()->session->set( 'klarna_show_kco', false );
return false;
}
// If the WooCommerce terms page or the Klarna Checkout settings field
// Terms Page isn't set, do nothing.
if ( empty( $this->terms_url ) ) {
WC()->session->set( 'klarna_show_kco', false );
return false;
}
WC()->session->set( 'klarna_show_kco', true );
return true;
}
/**
* Get a link to the transaction on the 3rd party gateway size (if applicable).
*
* @param WC_Order $order the order object.
*
* @return string transaction URL, or empty string.
*/
public function get_transaction_url( $order ) {
// Check if order is completed
if ( get_post_meta( $order->id, '_klarna_order_activated', true ) ) {
if ( $this->testmode == 'yes' ) {
$this->view_transaction_url = 'https://testdrive.klarna.com/invoices/%s.pdf';
} else {
$this->view_transaction_url = 'https://online.klarna.com/invoices/%s.pdf';
}
}
return parent::get_transaction_url( $order );
}
} // End class WC_Gateway_Klarna_Checkout
// Extra Class for Klarna Checkout
class WC_Gateway_Klarna_Checkout_Extra {
public function __construct() {
add_action( 'init', array( $this, 'start_session' ), 1 );
add_action( 'before_woocommerce_init', array( $this, 'prevent_caching' ) );
add_filter( 'woocommerce_get_checkout_url', array( $this, 'change_checkout_url' ), 20 );
add_action( 'woocommerce_register_form_start', array( $this, 'add_account_signup_text' ) );
add_action( 'woocommerce_login_form_start', array( $this, 'add_account_login_text' ) );
add_action( 'woocommerce_checkout_after_order_review', array( $this, 'klarna_add_link_to_kco_page' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'klarna_checkout_enqueuer' ) );
// Filter Checkout page ID, so WooCommerce Google Analytics integration can
// output Ecommerce tracking code on Klarna Thank You page
add_filter( 'woocommerce_get_checkout_page_id', array( $this, 'change_checkout_page_id' ) );
// Change is_checkout to true on KCO page
add_filter( 'woocommerce_is_checkout', array( $this, 'change_is_checkout_value' ) );
// Address update listener
add_action( 'template_redirect', array( $this, 'address_update_listener' ) );
}
/**
* Prevent caching in KCO and KCO thank you pages
*
* @since 1.9.8.2
*/
function prevent_caching() {
$checkout_settings = get_option( 'woocommerce_klarna_checkout_settings' );
$checkout_pages = array();
$thank_you_pages = array();
// Clean request URI to remove all parameters
$clean_req_uri = explode( '?', $_SERVER['REQUEST_URI'] );
$clean_req_uri = $clean_req_uri[0];
$clean_req_uri = trailingslashit( $clean_req_uri );
$length = strlen( $clean_req_uri );
// Get arrays of checkout and thank you pages for all countries
if ( is_array( $checkout_settings ) ) {
foreach ( $checkout_settings as $cs_key => $cs_value ) {
if ( strpos( $cs_key, 'klarna_checkout_url_' ) !== false ) {
$checkout_pages[ $cs_key ] = substr( $cs_value, 0 - $length );
}
if ( strpos( $cs_key, 'klarna_checkout_thanks_url_' ) !== false ) {
$thank_you_pages[ $cs_key ] = substr( $cs_value, 0 - $length );
}
}
}
// Check if string is longer than 1 character, to avoid homepage caching
if ( strlen( $clean_req_uri ) > 1 ) {
if ( in_array( $clean_req_uri, $checkout_pages ) || in_array( $clean_req_uri, $thank_you_pages ) ) {
// Prevent caching
if ( ! defined( 'DONOTCACHEPAGE' ) ) {
define( "DONOTCACHEPAGE", "true" );
}
if ( ! defined( 'DONOTCACHEOBJECT' ) ) {
define( "DONOTCACHEOBJECT", "true" );
}
if ( ! defined( 'DONOTCACHEDB' ) ) {
define( "DONOTCACHEDB", "true" );
}
nocache_headers();
}
}
}
/**
* Add link to KCO page from standard checkout page.
* Initiated here because KCO class is instantiated multiple times
* making the hook fire multiple times as well.
*
* @since 2.0
*/
function klarna_add_link_to_kco_page() {
global $klarna_checkout_url;
$checkout_settings = get_option( 'woocommerce_klarna_checkout_settings' );
if ( 'yes' == $checkout_settings['enabled'] && '' != $checkout_settings['klarna_checkout_button_label'] && 'yes' == $checkout_settings['add_klarna_checkout_button'] ) {
echo '<div class="woocommerce"><a style="margin-top:1em" href="' . $klarna_checkout_url . '" class="button std-checkout-button">' . $checkout_settings['klarna_checkout_button_label'] . '</a></div>';
}
}
// Set session
function start_session() {
$data = new WC_Gateway_Klarna_Checkout; // Still need to initiate it here, otherwise shortcode won't work
// if ( ! is_admin() || defined( 'DOING_AJAX' ) ) {
$checkout_settings = get_option( 'woocommerce_klarna_checkout_settings' );
$is_enabled = ( isset( $checkout_settings['enabled'] ) ) ? $checkout_settings['enabled'] : '';
$checkout_pages = array();
$thank_you_pages = array();
// Clean request URI to remove all parameters
$clean_req_uri = explode( '?', $_SERVER['REQUEST_URI'] );
$clean_req_uri = $clean_req_uri[0];
$clean_req_uri = trailingslashit( $clean_req_uri );
$length = strlen( $clean_req_uri );
// Get arrays of checkout and thank you pages for all countries
if ( is_array( $checkout_settings ) ) {
foreach ( $checkout_settings as $cs_key => $cs_value ) {
if ( strpos( $cs_key, 'klarna_checkout_url_' ) !== false ) {
$checkout_pages[ $cs_key ] = substr( $cs_value, 0 - $length );
}
if ( strpos( $cs_key, 'klarna_checkout_thanks_url_' ) !== false ) {
$thank_you_pages[ $cs_key ] = substr( $cs_value, 0 - $length );
}
}
}
// Start session if on a KCO or KCO Thank You page and KCO enabled
if ( ( in_array( $clean_req_uri, $checkout_pages ) || in_array( $clean_req_uri, $thank_you_pages ) ) && 'yes' == $is_enabled ) {
session_start();
}
// }
}
function klarna_checkout_css() {
global $post;
global $klarna_checkout_url;
$checkout_page_id = url_to_postid( $klarna_checkout_url );
$checkout_settings = get_option( 'woocommerce_klarna_checkout_settings' );
if ( $post->ID == $checkout_page_id ) {
if ( '' != $checkout_settings['color_button'] || '' != $checkout_settings['color_button_text'] ) { ?>
<style>
a.std-checkout-button,
.klarna_checkout_coupon input[type="submit"] {
background: <?php echo $checkout_settings['color_button']; ?> !important;
border: none !important;
color: <?php echo $checkout_settings['color_button_text']; ?> !important;
}
</style>
<?php }
}
}
/**
* Change Checkout URL
*
* Triggered from the 'woocommerce_get_checkout_url' action.
* Alter the checkout url to the custom Klarna Checkout Checkout page.
*
**/
function change_checkout_url( $url ) {
global $woocommerce;
global $klarna_checkout_url;
$checkout_settings = get_option( 'woocommerce_klarna_checkout_settings' );
$enabled = $checkout_settings['enabled'];
$modify_standard_checkout_url = $checkout_settings['modify_standard_checkout_url'];
$klarna_country = WC()->session->get( 'klarna_country' );
$available_countries = $this->get_authorized_countries();
// Change the Checkout URL if this is enabled in the settings
if ( $modify_standard_checkout_url == 'yes' && $enabled == 'yes' && ! empty( $klarna_checkout_url ) && in_array( strtoupper( $klarna_country ), $available_countries ) && array_key_exists( strtoupper( $klarna_country ), WC()->countries->get_allowed_countries() ) ) {
if ( class_exists( 'WC_Subscriptions_Cart' ) && WC_Subscriptions_Cart::cart_contains_subscription() ) {
if ( in_array( strtoupper( $klarna_country ), array( 'SE', 'FI', 'NO' ) ) ) {
$url = $klarna_checkout_url;
} else {
return $url;
}
} else {
$url = $klarna_checkout_url;
}
}
return $url;
}
/**
* Function Add Account signup text
*
* @since version 1.8.9
* Add text above the Account Registration Form.
* Useful for legal text for German stores. See documentation for more information. Leave blank to disable.
*
**/
public function add_account_signup_text() {
$checkout_settings = get_option( 'woocommerce_klarna_checkout_settings' );
$account_signup_text = ( isset( $checkout_settings['account_signup_text'] ) ) ? $checkout_settings['account_signup_text'] : '';
// Change the Checkout URL if this is enabled in the settings
if ( ! empty( $account_signup_text ) ) {
echo $account_signup_text;
}
}
/**
* Function Add Account login text
*
* @since version 1.8.9
* Add text above the Account Login Form.
* Useful for legal text for German stores. See documentation for more information. Leave blank to disable.
**/
public function add_account_login_text() {
$checkout_settings = get_option( 'woocommerce_klarna_checkout_settings' );
$account_login_text = ( isset( $checkout_settings['account_login_text'] ) ) ? $checkout_settings['account_login_text'] : '';
// Change the Checkout URL if this is enabled in the settings
if ( ! empty( $account_login_text ) ) {
echo $account_login_text;
}
}
/**
* Change checkout page ID to Klarna Thank You page, when in Klarna Thank You page only
*/
public function change_checkout_page_id( $checkout_page_id ) {
global $post;
global $klarna_checkout_thanks_url;
if ( is_page() ) {
$current_page_url = get_permalink( $post->ID );
// Compare Klarna Thank You page URL to current page URL
if ( esc_url( trailingslashit( $klarna_checkout_thanks_url ) ) == esc_url( trailingslashit( $current_page_url ) ) ) {
$checkout_page_id = $post->ID;
}
}
return $checkout_page_id;
}
/**
* Set is_checkout to true on KCO page
*/
function change_is_checkout_value( $bool ) {
global $post;
global $klarna_checkout_url;
if ( is_page() ) {
$current_page_url = get_permalink( $post->ID );
// Compare Klarna Checkout page URL to current page URL
if ( esc_url( trailingslashit( $klarna_checkout_url ) ) == esc_url( trailingslashit( $current_page_url ) ) ) {
return true;
}
}
return false;
}
/**
* Enqueue Klarna Checkout javascript.
*
* @since 2.0
**/
function klarna_checkout_enqueuer() {
global $woocommerce;
$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
$assets_path = str_replace( array( 'http:', 'https:' ), '', WC()->plugin_url() ) . '/assets/';
$frontend_script_path = $assets_path . 'js/frontend/';
if ( true == $this->is_rest() ) {
$version = 'v3';
} else {
$version = 'v2';
}
wp_register_script( 'klarna_checkout', KLARNA_URL . 'assets/js/klarna-checkout.js', array(), false, true );
wp_localize_script( 'klarna_checkout', 'kcoAjax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'klarna_checkout_nonce' => wp_create_nonce( 'klarna_checkout_nonce' ),
'version' => $version
) );
wp_register_style( 'klarna_checkout', KLARNA_URL . 'assets/css/klarna-checkout.css' );
if ( is_page() ) {
global $post;
$checkout_settings = get_option( 'woocommerce_klarna_checkout_settings' );
$checkout_pages = array();
$thank_you_pages = array();
// Clean request URI to remove all parameters
$clean_req_uri = explode( '?', $_SERVER['REQUEST_URI'] );
$clean_req_uri = $clean_req_uri[0];
$clean_req_uri = trailingslashit( $clean_req_uri );
$length = strlen( $clean_req_uri );
// Get arrays of checkout and thank you pages for all countries
if ( is_array( $checkout_settings ) ) {
foreach ( $checkout_settings as $cs_key => $cs_value ) {
if ( strpos( $cs_key, 'klarna_checkout_url_' ) !== false ) {
$checkout_pages[ $cs_key ] = substr( $cs_value, 0 - $length );
}
if ( strpos( $cs_key, 'klarna_checkout_thanks_url_' ) !== false ) {
$thank_you_pages[ $cs_key ] = substr( $cs_value, 0 - $length );
}
}
}
// Start session if on a KCO or KCO Thank You page and KCO enabled
if ( in_array( $clean_req_uri, $checkout_pages ) || in_array( $clean_req_uri, $thank_you_pages ) ) {
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'wc-checkout', $frontend_script_path . 'checkout' . $suffix . '.js', array(
'jquery',
'woocommerce',
'wc-country-select',
'wc-address-i18n'
) );
wp_enqueue_script( 'klarna_checkout' );
wp_enqueue_style( 'klarna_checkout' );
}
}
}
/**
* Get authorized KCO Countries.
*
* @since 2.0
**/
public function get_authorized_countries() {
$checkout_settings = get_option( 'woocommerce_klarna_checkout_settings' );
$this->eid_se = ( isset( $checkout_settings['eid_se'] ) ) ? $checkout_settings['eid_se'] : '';
$this->eid_no = ( isset( $checkout_settings['eid_no'] ) ) ? $checkout_settings['eid_no'] : '';
$this->eid_fi = ( isset( $checkout_settings['eid_fi'] ) ) ? $checkout_settings['eid_fi'] : '';
$this->eid_de = ( isset( $checkout_settings['eid_de'] ) ) ? $checkout_settings['eid_de'] : '';
$this->eid_at = ( isset( $checkout_settings['eid_at'] ) ) ? $checkout_settings['eid_at'] : '';
$this->eid_uk = ( isset( $checkout_settings['eid_uk'] ) ) ? $checkout_settings['eid_uk'] : '';
$this->eid_us = ( isset( $checkout_settings['eid_us'] ) ) ? $checkout_settings['eid_us'] : '';
$this->authorized_countries = array();
if ( ! empty( $this->eid_se ) ) {
$this->authorized_countries[] = 'SE';
}
if ( ! empty( $this->eid_no ) ) {
$this->authorized_countries[] = 'NO';
}
if ( ! empty( $this->eid_fi ) ) {
$this->authorized_countries[] = 'FI';
}
if ( ! empty( $this->eid_de ) ) {
$this->authorized_countries[] = 'DE';
}
if ( ! empty( $this->eid_at ) ) {
$this->authorized_countries[] = 'AT';
}
if ( ! empty( $this->eid_uk ) ) {
$this->authorized_countries[] = 'GB';
}
if ( ! empty( $this->eid_us ) ) {
$this->authorized_countries[] = 'US';
}
return $this->authorized_countries;
}
/**
* Determines which version of Klarna API should be used
*
* @todo remove or move this function to a separate class. This function exist in the WC_Gateway_Klarna_Checkout class as well.
* We needed to move it here because the is_rest function in the WC_Gateway_Klarna_Checkout class was probably called after the klarna_checkout_enqueuer function in this class.
* This caused is_rest to be false on first pageload of the checkout even if the Klarna country was UK or US.
*
*/
function is_rest() {
$this->klarna_country = WC()->session->get( 'klarna_country' );
if ( 'GB' == $this->klarna_country || 'gb' == $this->klarna_country || 'US' == $this->klarna_country || 'us' == $this->klarna_country ) {
// Set it in session as well, to be used in Shortcodes class
WC()->session->set( 'klarna_is_rest', true );
return true;
}
// Set it in session as well, to be used in Shortcodes class
WC()->session->set( 'klarna_is_rest', false );
return false;
}
/**
* Change the template for address_update callback
*
* Can't use WC_API here because we need output on the page.
* Checks if KCO shortcode is used and query parameter exists.
*
* Output JSON and die()
*
* @since 2.0
**/
function address_update_listener() {
global $post;
// Check if page has Klarna Checkout shortcode in it and address_update query parameter
if ( has_shortcode( $post->post_content, 'woocommerce_klarna_checkout' ) && isset( $_GET['address_update'] ) && 'yes' == $_GET['address_update'] ) {
// Read the post body
$post_body = file_get_contents( 'php://input' );
// Convert post body into native object
$data = json_decode( $post_body, true );
$order_id = $_GET['sid'];
// Capture address from Klarna
$order = wc_get_order( $order_id );
$billing_address = array(
'country' => strtoupper( $data['billing_address']['country'] ),
'first_name' => $data['billing_address']['given_name'],
'last_name' => $data['billing_address']['family_name'],
// 'company' => $data['billing_address']['company'],
'address_1' => $data['billing_address']['street_address'],
'address_2' => $data['billing_address']['street_address2'],
'postcode' => $data['billing_address']['postal_code'],
'city' => $data['billing_address']['city'],
'state' => $data['billing_address']['region'],
'email' => $data['billing_address']['email'],
'phone' => $data['billing_address']['phone'],
);
$shipping_address = array(
'country' => strtoupper( $data['shipping_address']['country'] ),
'first_name' => $data['shipping_address']['given_name'],
'last_name' => $data['shipping_address']['family_name'],
// 'company' => $data['shipping_address']['company'],
'address_1' => $data['shipping_address']['street_address'],
'address_2' => $data['shipping_address']['street_address2'],
'postcode' => $data['shipping_address']['postal_code'],
'city' => $data['shipping_address']['city'],
'state' => $data['shipping_address']['region'],
'email' => $data['shipping_address']['email'],
'phone' => $data['shipping_address']['phone'],
);
$order->set_address( $billing_address, 'billing' );
$order->set_address( $shipping_address, 'shipping' );
$order->calculate_taxes();
$sales_tax = round( ( $order->get_cart_tax() + $order->get_shipping_tax() ) * 100 );
if ( 'us' == strtolower( $data['billing_address']['country'] ) ) {
/**
* Update order total by removing old tax value and then adding the
* new one and set new order_tax_amount to $sales_tax value.
*/
$data['order_amount'] = $data['order_amount'] - $data['order_tax_amount'];
$data['order_amount'] = $data['order_amount'] + $sales_tax;
$data['order_tax_amount'] = $sales_tax;
/**
* Loop through $data['order_lines'], then create new array only with
* elements where 'type' is not equal to 'sales_tax'. Then add new
* sales_tax element to this new array, json_encode the array and send
* it back to Klarna.
*/
foreach ( $data['order_lines'] as $order_line_key => $order_line ) {
if ( 'sales_tax' == $order_line['type'] ) {
unset( $data['order_lines'][ $order_line_key ] );
}
}
// Add sales tax line item
$data['order_lines'][] = array(
'type' => 'sales_tax',
'reference' => __( 'Sales Tax', 'woocommerce-gateway-klarna' ),
'name' => __( 'Sales Tax', 'woocommerce-gateway-klarna' ),
'quantity' => 1,
'unit_price' => $sales_tax,
'tax_rate' => 0,
'total_amount' => $sales_tax,
'total_discount_amount' => 0,
'total_tax_amount' => 0
);
}
// Remove array indexing for order lines
$data['order_lines'] = array_values( $data['order_lines'] );
$response = json_encode( $data );
echo $response;
die();
}
}
} // End class WC_Gateway_Klarna_Checkout_Extra
$wc_klarna_checkout_extra = new WC_Gateway_Klarna_Checkout_Extra;
|
gpl-2.0
|
nekrozar/ygopro-scripts
|
c35498188.lua
|
2604
|
--アクションマジック-ダブル・バンキング
function c35498188.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(c35498188.condition)
e1:SetCost(c35498188.cost)
e1:SetTarget(c35498188.target)
e1:SetOperation(c35498188.activate)
c:RegisterEffect(e1)
--set
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(35498188,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCondition(aux.exccon)
e2:SetCost(c35498188.setcost)
e2:SetTarget(c35498188.settg)
e2:SetOperation(c35498188.setop)
c:RegisterEffect(e2)
end
function c35498188.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsAbleToEnterBP() or (Duel.GetCurrentPhase()>=PHASE_BATTLE_START and Duel.GetCurrentPhase()<=PHASE_BATTLE)
end
function c35498188.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,e:GetHandler()) end
Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD)
end
function c35498188.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsFaceup,tp,LOCATION_MZONE,0,1,nil) end
end
function c35498188.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(Card.IsFaceup,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_BATTLE_DESTROYING)
e1:SetCondition(c35498188.atkcon)
e1:SetOperation(c35498188.atkop)
e1:SetReset(RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
end
function c35498188.atkcon(e,tp,eg,ep,ev,re,r,rp)
return aux.bdocon(e,tp,eg,ep,ev,re,r,rp) and e:GetHandler():IsChainAttackable()
end
function c35498188.atkop(e,tp,eg,ep,ev,re,r,rp)
if Duel.SelectEffectYesNo(tp,e:GetHandler(),aux.Stringid(35498188,1)) then
Duel.ChainAttack()
end
end
function c35498188.costfilter(c)
return c:IsType(TYPE_SPELL) and c:IsDiscardable()
end
function c35498188.setcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c35498188.costfilter,tp,LOCATION_HAND,0,1,nil) end
Duel.DiscardHand(tp,c35498188.costfilter,1,1,REASON_COST+REASON_DISCARD)
end
function c35498188.settg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsSSetable() end
Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,e:GetHandler(),1,0,0)
end
function c35498188.setop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SSet(tp,c)
end
end
|
gpl-2.0
|
anhtuan8591/shop
|
modules/mod_kunenalatest/mod_kunenalatest.php
|
814
|
<?php
/**
* Kunena Latest Module
* @package Kunena.mod_kunenalatest
*
* @copyright (C) 2008 - 2012 Kunena Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link http://www.kunena.org
**/
defined ( '_JEXEC' ) or die ();
// Kunena detection and version check
$minKunenaVersion = '2.0';
if (!class_exists('KunenaForum') || !KunenaForum::isCompatible($minKunenaVersion)) {
echo JText::sprintf ('MOD_KUNENALATEST_KUNENA_NOT_INSTALLED', $minKunenaVersion);
return;
}
// Kunena online check
if (!KunenaForum::enabled()) {
echo JText::_('MOD_KUNENALATEST_KUNENA_OFFLINE');
return;
}
require_once (dirname ( __FILE__ ) . '/class.php');
$params = ( object ) $params;
$module = ( object ) $module;
$instance = new modKunenaLatest ( $module, $params );
$instance->display();
|
gpl-2.0
|
elieux/Cygwin
|
winsup/cygwin/fhandler_console.cc
|
76946
|
/* fhandler_console.cc
This file is part of Cygwin.
This software is a copyrighted work licensed under the terms of the
Cygwin license. Please consult the file "CYGWIN_LICENSE" for
details. */
#include "winsup.h"
#include "miscfuncs.h"
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <ctype.h>
#include <sys/param.h>
#include <sys/cygwin.h>
#include <cygwin/kd.h>
#include "cygerrno.h"
#include "security.h"
#include "path.h"
#include "fhandler.h"
#include "dtable.h"
#include "cygheap.h"
#include "sigproc.h"
#include "pinfo.h"
#include "shared_info.h"
#include "cygtls.h"
#include "tls_pbuf.h"
#include "registry.h"
#include <asm/socket.h>
#include "sync.h"
#include "child_info.h"
#include "cygwait.h"
/* Don't make this bigger than NT_MAX_PATH as long as the temporary buffer
is allocated using tmp_pathbuf!!! */
#define CONVERT_LIMIT NT_MAX_PATH
#define ALT_PRESSED (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)
#define CTRL_PRESSED (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)
#define con (shared_console_info->con)
#define srTop (con.b.srWindow.Top + con.scroll_region.Top)
#define srBottom ((con.scroll_region.Bottom < 0) ? con.b.srWindow.Bottom : con.b.srWindow.Top + con.scroll_region.Bottom)
const unsigned fhandler_console::MAX_WRITE_CHARS = 16384;
fhandler_console::console_state NO_COPY *fhandler_console::shared_console_info;
bool NO_COPY fhandler_console::invisible_console;
static void
beep ()
{
const WCHAR ding[] = L"\\media\\ding.wav";
reg_key r (HKEY_CURRENT_USER, KEY_ALL_ACCESS, L"AppEvents", L"Schemes",
L"Apps", L".Default", L".Default", L".Current", NULL);
if (r.created ())
{
PWCHAR buf = NULL;
UINT len = GetSystemWindowsDirectoryW (buf, 0) * sizeof (WCHAR);
buf = (PWCHAR) alloca (len += sizeof (ding));
UINT res = GetSystemWindowsDirectoryW (buf, len);
if (res && res <= len)
r.set_string (L"", wcscat (buf, ding));
}
MessageBeep (MB_OK);
}
fhandler_console::console_state *
fhandler_console::open_shared_console (HWND hw, HANDLE& h, bool& create)
{
wchar_t namebuf[(sizeof "XXXXXXXXXXXXXXXXXX-consNNNNNNNNNN")];
__small_swprintf (namebuf, L"%S-cons%p", &cygheap->installation_key, hw);
shared_locations m = create ? SH_SHARED_CONSOLE : SH_JUSTOPEN;
console_state *res = (console_state *)
open_shared (namebuf, 0, h, sizeof (*shared_console_info), &m);
create = m != SH_JUSTOPEN;
return res;
}
class console_unit
{
int n;
unsigned long bitmask;
HWND me;
public:
operator int () const {return n;}
console_unit (HWND);
friend BOOL CALLBACK enum_windows (HWND, LPARAM);
};
BOOL CALLBACK
enum_windows (HWND hw, LPARAM lp)
{
console_unit *this1 = (console_unit *) lp;
if (hw == this1->me)
return TRUE;
HANDLE h = NULL;
fhandler_console::console_state *cs;
if ((cs = fhandler_console::open_shared_console (hw, h)))
{
this1->bitmask ^= 1 << cs->tty_min_state.getntty ();
UnmapViewOfFile ((void *) cs);
CloseHandle (h);
}
return TRUE;
}
console_unit::console_unit (HWND me0):
bitmask (0xffffffff), me (me0)
{
EnumWindows (enum_windows, (LPARAM) this);
n = (_minor_t) ffs (bitmask) - 1;
if (n < 0)
api_fatal ("console device allocation failure - too many consoles in use, max consoles is 32");
}
bool
fhandler_console::set_unit ()
{
bool created;
fh_devices devset;
lock_ttys here;
HWND me;
fh_devices this_unit = dev ();
bool generic_console = this_unit == FH_CONIN || this_unit == FH_CONOUT;
if (shared_console_info)
{
fh_devices shared_unit =
(fh_devices) shared_console_info->tty_min_state.getntty ();
devset = (shared_unit == this_unit || this_unit == FH_CONSOLE
|| generic_console
|| this_unit == FH_TTY) ?
shared_unit : FH_ERROR;
created = false;
}
else if ((!generic_console && (myself->ctty != -1 && !iscons_dev (myself->ctty)))
|| !(me = GetConsoleWindow ()))
devset = FH_ERROR;
else
{
created = true;
shared_console_info = open_shared_console (me, cygheap->console_h, created);
ProtectHandleINH (cygheap->console_h);
if (created)
shared_console_info->tty_min_state.setntty (DEV_CONS_MAJOR, console_unit (me));
devset = (fh_devices) shared_console_info->tty_min_state.getntty ();
}
dev ().parse (devset);
if (devset != FH_ERROR)
pc.file_attributes (FILE_ATTRIBUTE_NORMAL);
else
{
set_io_handle (NULL);
set_output_handle (NULL);
created = false;
}
return created;
}
/* Allocate and initialize the shared record for the current console. */
void
fhandler_console::setup ()
{
if (set_unit ())
{
con.scroll_region.Bottom = -1;
con.dwLastCursorPosition.X = -1;
con.dwLastCursorPosition.Y = -1;
con.dwLastMousePosition.X = -1;
con.dwLastMousePosition.Y = -1;
con.dwLastButtonState = 0; /* none pressed */
con.last_button_code = 3; /* released */
con.underline_color = FOREGROUND_GREEN | FOREGROUND_BLUE;
con.dim_color = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
con.meta_mask = LEFT_ALT_PRESSED;
/* Set the mask that determines if an input keystroke is modified by
META. We set this based on the keyboard layout language loaded
for the current thread. The left <ALT> key always generates
META, but the right <ALT> key only generates META if we are using
an English keyboard because many "international" keyboards
replace common shell symbols ('[', '{', etc.) with accented
language-specific characters (umlaut, accent grave, etc.). On
these keyboards right <ALT> (called AltGr) is used to produce the
shell symbols and should not be interpreted as META. */
if (PRIMARYLANGID (LOWORD (GetKeyboardLayout (0))) == LANG_ENGLISH)
con.meta_mask |= RIGHT_ALT_PRESSED;
con.set_default_attr ();
con.backspace_keycode = CERASE;
con.cons_rapoi = NULL;
shared_console_info->tty_min_state.is_console = true;
}
}
/* Return the tty structure associated with a given tty number. If the
tty number is < 0, just return a dummy record. */
tty_min *
tty_list::get_cttyp ()
{
dev_t n = myself->ctty;
if (iscons_dev (n))
return fhandler_console::shared_console_info ?
&fhandler_console::shared_console_info->tty_min_state : NULL;
else if (istty_slave_dev (n))
return &ttys[device::minor (n)];
else
return NULL;
}
inline DWORD
dev_console::con_to_str (char *d, int dlen, WCHAR w)
{
return sys_wcstombs (d, dlen, &w, 1);
}
inline UINT
dev_console::get_console_cp ()
{
/* The alternate charset is always 437, just as in the Linux console. */
return alternate_charset_active ? 437 : 0;
}
inline DWORD
dev_console::str_to_con (mbtowc_p f_mbtowc, const char *charset,
PWCHAR d, const char *s, DWORD sz)
{
return sys_cp_mbstowcs (f_mbtowc, charset, d, CONVERT_LIMIT, s, sz);
}
bool
fhandler_console::set_raw_win32_keyboard_mode (bool new_mode)
{
bool old_mode = con.raw_win32_keyboard_mode;
con.raw_win32_keyboard_mode = new_mode;
syscall_printf ("raw keyboard mode %sabled", con.raw_win32_keyboard_mode ? "en" : "dis");
return old_mode;
};
void
fhandler_console::set_cursor_maybe ()
{
con.fillin (get_output_handle ());
if (con.dwLastCursorPosition.X != con.b.dwCursorPosition.X ||
con.dwLastCursorPosition.Y != con.b.dwCursorPosition.Y)
{
SetConsoleCursorPosition (get_output_handle (), con.b.dwCursorPosition);
con.dwLastCursorPosition = con.b.dwCursorPosition;
}
}
void
fhandler_console::send_winch_maybe ()
{
SHORT y = con.dwWinSize.Y;
SHORT x = con.dwWinSize.X;
con.fillin (get_output_handle ());
if (y != con.dwWinSize.Y || x != con.dwWinSize.X)
{
con.scroll_region.Top = 0;
con.scroll_region.Bottom = -1;
get_ttyp ()->kill_pgrp (SIGWINCH);
}
}
/* Check whether a mouse event is to be reported as an escape sequence */
bool
fhandler_console::mouse_aware (MOUSE_EVENT_RECORD& mouse_event)
{
if (!con.use_mouse)
return 0;
/* Adjust mouse position by window scroll buffer offset
and remember adjusted position in state for use by read() */
CONSOLE_SCREEN_BUFFER_INFO now;
if (!GetConsoleScreenBufferInfo (get_output_handle (), &now))
/* Cannot adjust position by window scroll buffer offset */
return 0;
con.dwMousePosition.X = mouse_event.dwMousePosition.X - now.srWindow.Left;
con.dwMousePosition.Y = mouse_event.dwMousePosition.Y - now.srWindow.Top;
return ((mouse_event.dwEventFlags == 0 || mouse_event.dwEventFlags == DOUBLE_CLICK)
&& mouse_event.dwButtonState != con.dwLastButtonState)
|| mouse_event.dwEventFlags == MOUSE_WHEELED
|| (mouse_event.dwEventFlags == MOUSE_MOVED
&& (con.dwMousePosition.X != con.dwLastMousePosition.X
|| con.dwMousePosition.Y != con.dwLastMousePosition.Y)
&& ((con.use_mouse >= 2 && mouse_event.dwButtonState)
|| con.use_mouse >= 3));
}
void __reg3
fhandler_console::read (void *pv, size_t& buflen)
{
push_process_state process_state (PID_TTYIN);
HANDLE h = get_io_handle ();
#define buf ((char *) pv)
int ch;
set_input_state ();
/* Check console read-ahead buffer filled from terminal requests */
if (con.cons_rapoi && *con.cons_rapoi)
{
*buf = *con.cons_rapoi++;
buflen = 1;
return;
}
int copied_chars = get_readahead_into_buffer (buf, buflen);
if (copied_chars)
{
buflen = copied_chars;
return;
}
DWORD timeout = is_nonblocking () ? 0 : INFINITE;
char tmp[60];
termios ti = get_ttyp ()->ti;
for (;;)
{
int bgres;
if ((bgres = bg_check (SIGTTIN)) <= bg_eof)
{
buflen = bgres;
return;
}
set_cursor_maybe (); /* to make cursor appear on the screen immediately */
switch (cygwait (h, timeout))
{
case WAIT_OBJECT_0:
break;
case WAIT_SIGNALED:
goto sig_exit;
case WAIT_CANCELED:
process_state.pop ();
pthread::static_cancel_self ();
/*NOTREACHED*/
case WAIT_TIMEOUT:
set_sig_errno (EAGAIN);
buflen = (size_t) -1;
return;
default:
goto err;
}
DWORD nread;
INPUT_RECORD input_rec;
const char *toadd = NULL;
if (!ReadConsoleInputW (h, &input_rec, 1, &nread))
{
syscall_printf ("ReadConsoleInput failed, %E");
goto err; /* seems to be failure */
}
/* check the event that occurred */
switch (input_rec.EventType)
{
case KEY_EVENT:
#define virtual_key_code (input_rec.Event.KeyEvent.wVirtualKeyCode)
#define control_key_state (input_rec.Event.KeyEvent.dwControlKeyState)
con.nModifiers = 0;
#ifdef DEBUGGING
/* allow manual switching to/from raw mode via ctrl-alt-scrolllock */
if (input_rec.Event.KeyEvent.bKeyDown &&
virtual_key_code == VK_SCROLL &&
((control_key_state & (LEFT_ALT_PRESSED | LEFT_CTRL_PRESSED)) == (LEFT_ALT_PRESSED | LEFT_CTRL_PRESSED))
)
{
set_raw_win32_keyboard_mode (!con.raw_win32_keyboard_mode);
continue;
}
#endif
if (con.raw_win32_keyboard_mode)
{
__small_sprintf (tmp, "\033{%u;%u;%u;%u;%u;%luK",
input_rec.Event.KeyEvent.bKeyDown,
input_rec.Event.KeyEvent.wRepeatCount,
input_rec.Event.KeyEvent.wVirtualKeyCode,
input_rec.Event.KeyEvent.wVirtualScanCode,
input_rec.Event.KeyEvent.uChar.UnicodeChar,
input_rec.Event.KeyEvent.dwControlKeyState);
toadd = tmp;
nread = strlen (toadd);
break;
}
#define ich (input_rec.Event.KeyEvent.uChar.AsciiChar)
#define wch (input_rec.Event.KeyEvent.uChar.UnicodeChar)
/* Ignore key up events, except for left alt events with non-zero character
*/
if (!input_rec.Event.KeyEvent.bKeyDown &&
/*
Event for left alt, with a non-zero character, comes from
"alt + numerics" key sequence.
e.g. <left-alt> 0233 => é
*/
!(wch != 0
// ?? experimentally determined on an XP system
&& virtual_key_code == VK_MENU
// left alt -- see http://www.microsoft.com/hwdev/tech/input/Scancode.asp
&& input_rec.Event.KeyEvent.wVirtualScanCode == 0x38))
continue;
if (control_key_state & SHIFT_PRESSED)
con.nModifiers |= 1;
if (control_key_state & RIGHT_ALT_PRESSED)
con.nModifiers |= 2;
if (control_key_state & CTRL_PRESSED)
con.nModifiers |= 4;
if (control_key_state & LEFT_ALT_PRESSED)
con.nModifiers |= 8;
/* Allow Backspace to emit ^? and escape sequences. */
if (input_rec.Event.KeyEvent.wVirtualKeyCode == VK_BACK)
{
char c = con.backspace_keycode;
nread = 0;
if (control_key_state & ALT_PRESSED)
{
if (con.metabit)
c |= 0x80;
else
tmp[nread++] = '\e';
}
tmp[nread++] = c;
tmp[nread] = 0;
toadd = tmp;
}
/* Allow Ctrl-Space to emit ^@ */
else if (input_rec.Event.KeyEvent.wVirtualKeyCode == VK_SPACE
&& (control_key_state & CTRL_PRESSED)
&& !(control_key_state & ALT_PRESSED))
toadd = "";
else if (wch == 0
/* arrow/function keys */
|| (input_rec.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY))
{
toadd = get_nonascii_key (input_rec, tmp);
if (!toadd)
{
con.nModifiers = 0;
continue;
}
nread = strlen (toadd);
}
else
{
nread = con.con_to_str (tmp + 1, 59, wch);
/* Determine if the keystroke is modified by META. The tricky
part is to distinguish whether the right Alt key should be
recognized as Alt, or as AltGr. */
bool meta =
/* Alt but not AltGr (= left ctrl + right alt)? */
(control_key_state & ALT_PRESSED) != 0
&& ((control_key_state & CTRL_PRESSED) == 0
/* but also allow Alt-AltGr: */
|| (control_key_state & ALT_PRESSED) == ALT_PRESSED
|| (wch <= 0x1f || wch == 0x7f));
if (!meta)
{
/* Determine if the character is in the current multibyte
charset. The test is easy. If the multibyte sequence
is > 1 and the first byte is ASCII CAN, the character
has been translated into the ASCII CAN + UTF-8 replacement
sequence. If so, just ignore the keypress.
FIXME: Is there a better solution? */
if (nread > 1 && tmp[1] == 0x18)
beep ();
else
toadd = tmp + 1;
}
else if (con.metabit)
{
tmp[1] |= 0x80;
toadd = tmp + 1;
}
else
{
tmp[0] = '\033';
tmp[1] = cyg_tolower (tmp[1]);
toadd = tmp;
nread++;
con.nModifiers &= ~4;
}
}
#undef ich
#undef wch
break;
case MOUSE_EVENT:
send_winch_maybe ();
{
MOUSE_EVENT_RECORD& mouse_event = input_rec.Event.MouseEvent;
/* As a unique guard for mouse report generation,
call mouse_aware() which is common with select(), so the result
of select() and the actual read() will be consistent on the
issue of whether input (i.e. a mouse escape sequence) will
be available or not */
if (mouse_aware (mouse_event))
{
/* Note: Reported mouse position was already retrieved by
mouse_aware() and adjusted by window scroll buffer offset */
/* Treat the double-click event like a regular button press */
if (mouse_event.dwEventFlags == DOUBLE_CLICK)
{
syscall_printf ("mouse: double-click -> click");
mouse_event.dwEventFlags = 0;
}
/* This code assumes Windows never reports multiple button
events at the same time. */
int b = 0;
char sz[32];
char mode6_term = 'M';
if (mouse_event.dwEventFlags == MOUSE_WHEELED)
{
if (mouse_event.dwButtonState & 0xFF800000)
{
b = 0x41;
strcpy (sz, "wheel down");
}
else
{
b = 0x40;
strcpy (sz, "wheel up");
}
}
else
{
/* Ignore unimportant mouse buttons */
mouse_event.dwButtonState &= 0x7;
if (mouse_event.dwEventFlags == MOUSE_MOVED)
{
b = con.last_button_code;
}
else if (mouse_event.dwButtonState < con.dwLastButtonState && !con.ext_mouse_mode6)
{
b = 3;
strcpy (sz, "btn up");
}
else if ((mouse_event.dwButtonState & 1) != (con.dwLastButtonState & 1))
{
b = 0;
strcpy (sz, "btn1 down");
}
else if ((mouse_event.dwButtonState & 2) != (con.dwLastButtonState & 2))
{
b = 2;
strcpy (sz, "btn2 down");
}
else if ((mouse_event.dwButtonState & 4) != (con.dwLastButtonState & 4))
{
b = 1;
strcpy (sz, "btn3 down");
}
if (con.ext_mouse_mode6 /* distinguish release */
&& mouse_event.dwButtonState < con.dwLastButtonState)
mode6_term = 'm';
con.last_button_code = b;
if (mouse_event.dwEventFlags == MOUSE_MOVED)
{
b += 32;
strcpy (sz, "move");
}
else
{
/* Remember the modified button state */
con.dwLastButtonState = mouse_event.dwButtonState;
}
}
/* Remember mouse position */
con.dwLastMousePosition.X = con.dwMousePosition.X;
con.dwLastMousePosition.Y = con.dwMousePosition.Y;
/* Remember the modifiers */
con.nModifiers = 0;
if (mouse_event.dwControlKeyState & SHIFT_PRESSED)
con.nModifiers |= 0x4;
if (mouse_event.dwControlKeyState & ALT_PRESSED)
con.nModifiers |= 0x8;
if (mouse_event.dwControlKeyState & CTRL_PRESSED)
con.nModifiers |= 0x10;
/* Indicate the modifiers */
b |= con.nModifiers;
/* We can now create the code. */
if (con.ext_mouse_mode6)
{
__small_sprintf (tmp, "\033[<%d;%d;%d%c", b,
con.dwMousePosition.X + 1,
con.dwMousePosition.Y + 1,
mode6_term);
nread = strlen (tmp);
}
else if (con.ext_mouse_mode15)
{
__small_sprintf (tmp, "\033[%d;%d;%dM", b + 32,
con.dwMousePosition.X + 1,
con.dwMousePosition.Y + 1);
nread = strlen (tmp);
}
else if (con.ext_mouse_mode5)
{
unsigned int xcode = con.dwMousePosition.X + ' ' + 1;
unsigned int ycode = con.dwMousePosition.Y + ' ' + 1;
__small_sprintf (tmp, "\033[M%c", b + ' ');
nread = 4;
/* the neat nested encoding function of mintty
does not compile in g++, so let's unfold it: */
if (xcode < 0x80)
tmp [nread++] = xcode;
else if (xcode < 0x800)
{
tmp [nread++] = 0xC0 + (xcode >> 6);
tmp [nread++] = 0x80 + (xcode & 0x3F);
}
else
tmp [nread++] = 0;
if (ycode < 0x80)
tmp [nread++] = ycode;
else if (ycode < 0x800)
{
tmp [nread++] = 0xC0 + (ycode >> 6);
tmp [nread++] = 0x80 + (ycode & 0x3F);
}
else
tmp [nread++] = 0;
}
else
{
unsigned int xcode = con.dwMousePosition.X + ' ' + 1;
unsigned int ycode = con.dwMousePosition.Y + ' ' + 1;
if (xcode >= 256)
xcode = 0;
if (ycode >= 256)
ycode = 0;
__small_sprintf (tmp, "\033[M%c%c%c", b + ' ',
xcode, ycode);
nread = 6; /* tmp may contain NUL bytes */
}
syscall_printf ("mouse: %s at (%d,%d)", sz,
con.dwMousePosition.X,
con.dwMousePosition.Y);
toadd = tmp;
}
}
break;
case FOCUS_EVENT:
if (con.use_focus)
{
if (input_rec.Event.FocusEvent.bSetFocus)
__small_sprintf (tmp, "\033[I");
else
__small_sprintf (tmp, "\033[O");
toadd = tmp;
nread = 3;
}
break;
case WINDOW_BUFFER_SIZE_EVENT:
send_winch_maybe ();
/* fall through */
default:
continue;
}
if (toadd)
{
line_edit_status res = line_edit (toadd, nread, ti);
if (res == line_edit_signalled)
goto sig_exit;
else if (res == line_edit_input_done)
break;
}
}
while (buflen)
if ((ch = get_readahead ()) < 0)
break;
else
{
buf[copied_chars++] = (unsigned char)(ch & 0xff);
buflen--;
}
#undef buf
buflen = copied_chars;
return;
err:
__seterrno ();
buflen = (size_t) -1;
return;
sig_exit:
set_sig_errno (EINTR);
buflen = (size_t) -1;
}
void
fhandler_console::set_input_state ()
{
if (get_ttyp ()->rstcons ())
input_tcsetattr (0, &get_ttyp ()->ti);
}
bool
dev_console::fillin (HANDLE h)
{
bool ret;
if ((ret = GetConsoleScreenBufferInfo (h, &b)))
{
dwWinSize.Y = 1 + b.srWindow.Bottom - b.srWindow.Top;
dwWinSize.X = 1 + b.srWindow.Right - b.srWindow.Left;
if (b.dwCursorPosition.Y > dwEnd.Y
|| (b.dwCursorPosition.Y >= dwEnd.Y && b.dwCursorPosition.X > dwEnd.X))
dwEnd = b.dwCursorPosition;
}
else
{
memset (&b, 0, sizeof (b));
dwWinSize.Y = 25;
dwWinSize.X = 80;
b.srWindow.Bottom = 24;
b.srWindow.Right = 79;
}
return ret;
}
void __reg3
dev_console::scroll_buffer (HANDLE h, int x1, int y1, int x2, int y2, int xn, int yn)
{
/* Scroll the screen context.
x1, y1 - ul corner
x2, y2 - dr corner
xn, yn - new ul corner
Negative values represents current screen dimensions
*/
SMALL_RECT sr1, sr2;
CHAR_INFO fill;
COORD dest;
fill.Char.AsciiChar = ' ';
fill.Attributes = current_win32_attr;
fillin (h);
sr1.Left = x1 >= 0 ? x1 : dwWinSize.X - 1;
sr1.Top = y1 >= 0 ? y1 : b.srWindow.Bottom;
sr1.Right = x2 >= 0 ? x2 : dwWinSize.X - 1;
sr1.Bottom = y2 >= 0 ? y2 : b.srWindow.Bottom;
sr2.Top = b.srWindow.Top + scroll_region.Top;
sr2.Left = 0;
sr2.Bottom = (scroll_region.Bottom < 0) ? b.srWindow.Bottom : b.srWindow.Top + scroll_region.Bottom;
sr2.Right = dwWinSize.X - 1;
if (sr1.Bottom > sr2.Bottom && sr1.Top <= sr2.Bottom)
sr1.Bottom = sr2.Bottom;
dest.X = xn >= 0 ? xn : dwWinSize.X - 1;
dest.Y = yn >= 0 ? yn : b.srWindow.Bottom;
ScrollConsoleScreenBuffer (h, &sr1, &sr2, dest, &fill);
}
inline void
fhandler_console::scroll_buffer (int x1, int y1, int x2, int y2, int xn, int yn)
{
con.scroll_buffer (get_output_handle (), x1, y1, x2, y2, xn, yn);
}
inline void
fhandler_console::scroll_buffer_screen (int x1, int y1, int x2, int y2, int xn, int yn)
{
if (y1 >= 0)
y1 += con.b.srWindow.Top;
if (y2 >= 0)
y1 += con.b.srWindow.Top;
if (yn >= 0)
yn += con.b.srWindow.Top;
con.scroll_buffer (get_output_handle (), x1, y1, x2, y2, xn, yn);
}
int
fhandler_console::dup (fhandler_base *child, int flags)
{
/* See comments in fhandler_pty_slave::dup */
if (myself->ctty != -2)
myself->set_ctty (this, flags);
return 0;
}
int
fhandler_console::open (int flags, mode_t)
{
HANDLE h;
if (dev () == FH_ERROR)
{
set_errno (EPERM); /* constructor found an error */
return 0;
}
tcinit (false);
set_io_handle (NULL);
set_output_handle (NULL);
/* Open the input handle as handle_ */
h = CreateFile ("CONIN$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, &sec_none,
OPEN_EXISTING, 0, 0);
if (h == INVALID_HANDLE_VALUE)
{
__seterrno ();
return 0;
}
set_io_handle (h);
h = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, &sec_none,
OPEN_EXISTING, 0, 0);
if (h == INVALID_HANDLE_VALUE)
{
__seterrno ();
return 0;
}
set_output_handle (h);
if (con.fillin (get_output_handle ()))
{
con.current_win32_attr = con.b.wAttributes;
if (!con.default_color)
con.default_color = con.b.wAttributes;
con.set_default_attr ();
}
get_ttyp ()->rstcons (false);
set_open_status ();
DWORD cflags;
if (GetConsoleMode (get_io_handle (), &cflags))
SetConsoleMode (get_io_handle (),
ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT | cflags);
debug_printf ("opened conin$ %p, conout$ %p", get_io_handle (),
get_output_handle ());
return 1;
}
void
fhandler_console::open_setup (int flags)
{
set_flags ((flags & ~O_TEXT) | O_BINARY);
if (myself->set_ctty (this, flags) && !myself->cygstarted)
init_console_handler (true);
fhandler_base::open_setup (flags);
}
int
fhandler_console::close ()
{
CloseHandle (get_io_handle ());
CloseHandle (get_output_handle ());
if (!have_execed)
free_console ();
return 0;
}
int
fhandler_console::ioctl (unsigned int cmd, void *arg)
{
int res = fhandler_termios::ioctl (cmd, arg);
if (res <= 0)
return res;
switch (cmd)
{
case TIOCGWINSZ:
int st;
st = con.fillin (get_output_handle ());
if (st)
{
/* *not* the buffer size, the actual screen size... */
/* based on Left Top Right Bottom of srWindow */
((struct winsize *) arg)->ws_row = con.dwWinSize.Y;
((struct winsize *) arg)->ws_col = con.dwWinSize.X;
syscall_printf ("WINSZ: (row=%d,col=%d)",
((struct winsize *) arg)->ws_row,
((struct winsize *) arg)->ws_col);
return 0;
}
else
{
syscall_printf ("WINSZ failed");
__seterrno ();
return -1;
}
return 0;
case TIOCSWINSZ:
bg_check (SIGTTOU);
return 0;
case KDGKBMETA:
*(int *) arg = (con.metabit) ? K_METABIT : K_ESCPREFIX;
return 0;
case KDSKBMETA:
if ((intptr_t) arg == K_METABIT)
con.metabit = TRUE;
else if ((intptr_t) arg == K_ESCPREFIX)
con.metabit = FALSE;
else
{
set_errno (EINVAL);
return -1;
}
return 0;
case TIOCLINUX:
if (*(unsigned char *) arg == 6)
{
*(unsigned char *) arg = (unsigned char) con.nModifiers;
return 0;
}
set_errno (EINVAL);
return -1;
case FIONREAD:
{
/* Per MSDN, max size of buffer required is below 64K. */
#define INREC_SIZE (65536 / sizeof (INPUT_RECORD))
DWORD n;
int ret = 0;
INPUT_RECORD inp[INREC_SIZE];
if (!PeekConsoleInputW (get_io_handle (), inp, INREC_SIZE, &n))
{
set_errno (EINVAL);
return -1;
}
while (n-- > 0)
if (inp[n].EventType == KEY_EVENT && inp[n].Event.KeyEvent.bKeyDown)
++ret;
*(int *) arg = ret;
return 0;
}
break;
}
return fhandler_base::ioctl (cmd, arg);
}
int
fhandler_console::tcflush (int queue)
{
int res = 0;
if (queue == TCIFLUSH
|| queue == TCIOFLUSH)
{
if (!FlushConsoleInputBuffer (get_io_handle ()))
{
__seterrno ();
res = -1;
}
}
return res;
}
int
fhandler_console::output_tcsetattr (int, struct termios const *t)
{
/* All the output bits we can ignore */
DWORD flags = ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT;
int res = SetConsoleMode (get_output_handle (), flags) ? 0 : -1;
if (res)
__seterrno_from_win_error (GetLastError ());
syscall_printf ("%d = tcsetattr(,%p) (ENABLE FLAGS %y) (lflag %y oflag %y)",
res, t, flags, t->c_lflag, t->c_oflag);
return res;
}
int
fhandler_console::input_tcsetattr (int, struct termios const *t)
{
/* Ignore the optional_actions stuff, since all output is emitted
instantly */
DWORD oflags;
if (!GetConsoleMode (get_io_handle (), &oflags))
oflags = 0;
DWORD flags = 0;
#if 0
/* Enable/disable LF -> CRLF conversions */
rbinary ((t->c_iflag & INLCR) ? false : true);
#endif
/* There's some disparity between what we need and what's
available. We've got ECHO and ICANON, they've
got ENABLE_ECHO_INPUT and ENABLE_LINE_INPUT. */
termios_printf ("this %p, get_ttyp () %p, t %p", this, get_ttyp (), t);
get_ttyp ()->ti = *t;
if (t->c_lflag & ECHO)
{
flags |= ENABLE_ECHO_INPUT;
}
if (t->c_lflag & ICANON)
{
flags |= ENABLE_LINE_INPUT;
}
if (flags & ENABLE_ECHO_INPUT
&& !(flags & ENABLE_LINE_INPUT))
{
/* This is illegal, so turn off the echo here, and fake it
when we read the characters */
flags &= ~ENABLE_ECHO_INPUT;
}
if ((t->c_lflag & ISIG) && !(t->c_iflag & IGNBRK))
{
flags |= ENABLE_PROCESSED_INPUT;
}
flags |= ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;
int res;
if (flags == oflags)
res = 0;
else
{
res = SetConsoleMode (get_io_handle (), flags) ? 0 : -1;
if (res < 0)
__seterrno ();
syscall_printf ("%d = tcsetattr(,%p) enable flags %y, c_lflag %y iflag %y",
res, t, flags, t->c_lflag, t->c_iflag);
}
get_ttyp ()->rstcons (false);
return res;
}
int
fhandler_console::tcsetattr (int a, struct termios const *t)
{
int res = output_tcsetattr (a, t);
if (res != 0)
return res;
return input_tcsetattr (a, t);
}
int
fhandler_console::tcgetattr (struct termios *t)
{
int res;
*t = get_ttyp ()->ti;
t->c_cflag |= CS8;
DWORD flags;
if (!GetConsoleMode (get_io_handle (), &flags))
{
__seterrno ();
res = -1;
}
else
{
if (flags & ENABLE_ECHO_INPUT)
t->c_lflag |= ECHO;
if (flags & ENABLE_LINE_INPUT)
t->c_lflag |= ICANON;
if (flags & ENABLE_PROCESSED_INPUT)
t->c_lflag |= ISIG;
else
t->c_iflag |= IGNBRK;
/* What about ENABLE_WINDOW_INPUT
and ENABLE_MOUSE_INPUT ? */
/* All the output bits we can ignore */
res = 0;
}
syscall_printf ("%d = tcgetattr(%p) enable flags %y, t->lflag %y, t->iflag %y",
res, t, flags, t->c_lflag, t->c_iflag);
return res;
}
fhandler_console::fhandler_console (fh_devices unit) :
fhandler_termios ()
{
if (unit > 0)
dev ().parse (unit);
setup ();
trunc_buf.len = 0;
_tc = &(shared_console_info->tty_min_state);
}
void
dev_console::set_color (HANDLE h)
{
WORD win_fg = fg;
WORD win_bg = bg;
if (reverse)
{
WORD save_fg = win_fg;
win_fg = (win_bg & BACKGROUND_RED ? FOREGROUND_RED : 0) |
(win_bg & BACKGROUND_GREEN ? FOREGROUND_GREEN : 0) |
(win_bg & BACKGROUND_BLUE ? FOREGROUND_BLUE : 0) |
(win_bg & BACKGROUND_INTENSITY ? FOREGROUND_INTENSITY : 0);
win_bg = (save_fg & FOREGROUND_RED ? BACKGROUND_RED : 0) |
(save_fg & FOREGROUND_GREEN ? BACKGROUND_GREEN : 0) |
(save_fg & FOREGROUND_BLUE ? BACKGROUND_BLUE : 0) |
(save_fg & FOREGROUND_INTENSITY ? BACKGROUND_INTENSITY : 0);
}
/* apply attributes */
if (underline)
win_fg = underline_color;
/* emulate blink with bright background */
if (blink)
win_bg |= BACKGROUND_INTENSITY;
if (intensity == INTENSITY_INVISIBLE)
win_fg = win_bg;
else if (intensity != INTENSITY_BOLD)
/* nothing to do */;
/* apply foreground intensity only in non-reverse mode! */
else if (reverse)
win_bg |= BACKGROUND_INTENSITY;
else
win_fg |= FOREGROUND_INTENSITY;
current_win32_attr = win_fg | win_bg;
if (h)
SetConsoleTextAttribute (h, current_win32_attr);
}
#define FOREGROUND_ATTR_MASK (FOREGROUND_RED | FOREGROUND_GREEN | \
FOREGROUND_BLUE | FOREGROUND_INTENSITY)
#define BACKGROUND_ATTR_MASK (BACKGROUND_RED | BACKGROUND_GREEN | \
BACKGROUND_BLUE | BACKGROUND_INTENSITY)
void
dev_console::set_default_attr ()
{
blink = underline = reverse = false;
intensity = INTENSITY_NORMAL;
fg = default_color & FOREGROUND_ATTR_MASK;
bg = default_color & BACKGROUND_ATTR_MASK;
set_color (NULL);
}
int
dev_console::set_cl_x (cltype x)
{
if (x == cl_disp_beg || x == cl_buf_beg)
return 0;
if (x == cl_disp_end)
return dwWinSize.X - 1;
if (x == cl_buf_end)
return b.dwSize.X - 1;
return b.dwCursorPosition.X;
}
int
dev_console::set_cl_y (cltype y)
{
if (y == cl_buf_beg)
return 0;
if (y == cl_disp_beg)
return b.srWindow.Top;
if (y == cl_disp_end)
return b.srWindow.Bottom;
if (y == cl_buf_end)
return b.dwSize.Y - 1;
return b.dwCursorPosition.Y;
}
bool
dev_console::scroll_window (HANDLE h, int x1, int y1, int x2, int y2)
{
if (save_buf || x1 != 0 || x2 != dwWinSize.X - 1 || y1 != b.srWindow.Top
|| y2 != b.srWindow.Bottom || b.dwSize.Y <= dwWinSize.Y)
return false;
SMALL_RECT sr;
int toscroll = dwEnd.Y - b.srWindow.Top + 1;
sr.Left = sr.Right = dwEnd.X = 0;
if (b.srWindow.Bottom + toscroll >= b.dwSize.Y)
{
/* So we're at the end of the buffer and scrolling the console window
would move us beyond the buffer. What we do here is to scroll the
console buffer upward by just as much so that the current last line
becomes the last line just prior to the first window line. That
keeps the end of the console buffer intact, as desired. */
SMALL_RECT br;
COORD dest;
CHAR_INFO fill;
br.Left = 0;
br.Top = (b.srWindow.Bottom - b.srWindow.Top) + 1
- (b.dwSize.Y - dwEnd.Y - 1);
br.Right = b.dwSize.X - 1;
br.Bottom = b.dwSize.Y - 1;
dest.X = dest.Y = 0;
fill.Char.AsciiChar = ' ';
fill.Attributes = current_win32_attr;
ScrollConsoleScreenBuffer (h, &br, NULL, dest, &fill);
/* Since we're moving the console buffer under the console window
we only have to move the console window if the user scrolled the
window upwards. The number of lines is the distance to the
buffer bottom. */
toscroll = b.dwSize.Y - b.srWindow.Bottom - 1;
/* Fix dwEnd to reflect the new cursor line. Take the above scrolling
into account and subtract 1 to account for the increment below. */
dwEnd.Y = b.dwCursorPosition.Y + toscroll - 1;
}
if (toscroll)
{
/* FIXME: For some reason SetConsoleWindowInfo does not correctly
set the scrollbars. Calling SetConsoleCursorPosition here is
just a workaround which doesn't cover all cases. In some scenarios
the scrollbars are still off by one console window size. */
/* The reminder of the console buffer is big enough to simply move
the console window. We have to set the cursor first, otherwise
the scroll bars will not be corrected. */
SetConsoleCursorPosition (h, dwEnd);
/* If the user scolled manually, setting the cursor position might scroll
the console window so that the cursor is not at the top. Correct
the action by moving the window down again so the cursor is one line
above the new window position. */
GetConsoleScreenBufferInfo (h, &b);
if (b.dwCursorPosition.Y >= b.srWindow.Top)
toscroll = b.dwCursorPosition.Y - b.srWindow.Top + 1;
/* Move the window accordingly. */
sr.Top = sr.Bottom = toscroll;
SetConsoleWindowInfo (h, FALSE, &sr);
}
/* Eventually set cursor to new end position at the top of the window. */
dwEnd.Y++;
SetConsoleCursorPosition (h, dwEnd);
/* Fix up console buffer info. */
fillin (h);
return true;
}
/*
* Clear the screen context from x1/y1 to x2/y2 cell.
* Negative values represents current screen dimensions
*/
void __reg3
fhandler_console::clear_screen (cltype xc1, cltype yc1, cltype xc2, cltype yc2)
{
HANDLE h = get_output_handle ();
SHORT oldEndY = con.dwEnd.Y;
con.fillin (h);
int x1 = con.set_cl_x (xc1);
int y1 = con.set_cl_y (yc1);
int x2 = con.set_cl_x (xc2);
int y2 = con.set_cl_y (yc2);
/* Make correction for the following situation: The console buffer
is only partially used and the user scrolled down into the as yet
unused area so far that the cursor is outside the window buffer. */
if (oldEndY < con.dwEnd.Y && oldEndY < con.b.srWindow.Top)
{
con.dwEnd.Y = con.b.dwCursorPosition.Y = oldEndY;
y1 = con.b.srWindow.Top;
}
/* Detect special case - scroll the screen if we have a buffer in order to
preserve the buffer. */
if (!con.scroll_window (h, x1, y1, x2, y2))
con.clear_screen (h, x1, y1, x2, y2);
}
void __reg3
dev_console::clear_screen (HANDLE h, int x1, int y1, int x2, int y2)
{
COORD tlc;
DWORD done;
int num;
num = abs (y1 - y2) * b.dwSize.X + abs (x1 - x2) + 1;
if ((y2 * b.dwSize.X + x2) > (y1 * b.dwSize.X + x1))
{
tlc.X = x1;
tlc.Y = y1;
}
else
{
tlc.X = x2;
tlc.Y = y2;
}
FillConsoleOutputCharacterA (h, ' ', num, tlc, &done);
FillConsoleOutputAttribute (h, current_win32_attr, num, tlc, &done);
}
void __reg3
fhandler_console::cursor_set (bool rel_to_top, int x, int y)
{
COORD pos;
con.fillin (get_output_handle ());
#if 0
/* Setting y to the current b.srWindow.Bottom here is the reason that the window
isn't scrolled back to the current cursor position like it's done in
any other terminal. Rather, the curser is forced to the bottom of the
currently scrolled region. This breaks the console buffer content if
output is generated while the user had the window scrolled back. This
behaviour is very old, it has no matching ChangeLog entry.
Just disable for now but keep the code in for future reference. */
if (y > con.b.srWindow.Bottom)
y = con.b.srWindow.Bottom;
else
#endif
if (y < 0)
y = 0;
else if (rel_to_top)
y += con.b.srWindow.Top;
if (x > con.dwWinSize.X)
x = con.dwWinSize.X - 1;
else if (x < 0)
x = 0;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition (get_output_handle (), pos);
}
void __reg3
fhandler_console::cursor_rel (int x, int y)
{
con.fillin (get_output_handle ());
x += con.b.dwCursorPosition.X;
y += con.b.dwCursorPosition.Y;
cursor_set (false, x, y);
}
void __reg3
fhandler_console::cursor_get (int *x, int *y)
{
con.fillin (get_output_handle ());
*y = con.b.dwCursorPosition.Y;
*x = con.b.dwCursorPosition.X;
}
/* VT100 line drawing graphics mode maps `abcdefghijklmnopqrstuvwxyz{|}~ to
graphical characters */
static const wchar_t __vt100_conv[31] = {
0x25C6, /* Black Diamond */
0x2592, /* Medium Shade */
0x2409, /* Symbol for Horizontal Tabulation */
0x240C, /* Symbol for Form Feed */
0x240D, /* Symbol for Carriage Return */
0x240A, /* Symbol for Line Feed */
0x00B0, /* Degree Sign */
0x00B1, /* Plus-Minus Sign */
0x2424, /* Symbol for Newline */
0x240B, /* Symbol for Vertical Tabulation */
0x2518, /* Box Drawings Light Up And Left */
0x2510, /* Box Drawings Light Down And Left */
0x250C, /* Box Drawings Light Down And Right */
0x2514, /* Box Drawings Light Up And Right */
0x253C, /* Box Drawings Light Vertical And Horizontal */
0x23BA, /* Horizontal Scan Line-1 */
0x23BB, /* Horizontal Scan Line-3 */
0x2500, /* Box Drawings Light Horizontal */
0x23BC, /* Horizontal Scan Line-7 */
0x23BD, /* Horizontal Scan Line-9 */
0x251C, /* Box Drawings Light Vertical And Right */
0x2524, /* Box Drawings Light Vertical And Left */
0x2534, /* Box Drawings Light Up And Horizontal */
0x252C, /* Box Drawings Light Down And Horizontal */
0x2502, /* Box Drawings Light Vertical */
0x2264, /* Less-Than Or Equal To */
0x2265, /* Greater-Than Or Equal To */
0x03C0, /* Greek Small Letter Pi */
0x2260, /* Not Equal To */
0x00A3, /* Pound Sign */
0x00B7, /* Middle Dot */
};
inline
bool fhandler_console::write_console (PWCHAR buf, DWORD len, DWORD& done)
{
if (con.iso_2022_G1
? con.vt100_graphics_mode_G1
: con.vt100_graphics_mode_G0)
for (DWORD i = 0; i < len; i ++)
if (buf[i] >= (unsigned char) '`' && buf[i] <= (unsigned char) '~')
buf[i] = __vt100_conv[buf[i] - (unsigned char) '`'];
while (len > 0)
{
DWORD nbytes = len > MAX_WRITE_CHARS ? MAX_WRITE_CHARS : len;
if (!WriteConsoleW (get_output_handle (), buf, nbytes, &done, 0))
{
__seterrno ();
return false;
}
len -= done;
buf += done;
}
return true;
}
/* The following three functions were adapted (i.e., mildly modified) from
http://stackoverflow.com/questions/14699043/replacement-to-systemcolor */
/* Split a rectangular region into two smaller rectangles based on the
largest dimension. */
static void
region_split (PCHAR_INFO& buf, COORD& bufsiz, SMALL_RECT& region,
PCHAR_INFO& buf_b, COORD& bufsiz_b, SMALL_RECT& region_b)
{
region_b = region;
bufsiz_b = bufsiz;
SHORT half = (1 + region.Bottom - region.Top) / 2;
region_b.Top += half;
region.Bottom = (bufsiz.Y = region_b.Top) - 1;
buf_b = buf + (half * (1 + region.Right));
bufsiz_b.Y = region_b.Bottom - region_b.Top;
}
/* Utility function to figure out the distance between two points. */
static SHORT
delta (SHORT first, SHORT second)
{
return (second >= first) ? (second - first + 1) : 0;
}
/* Subdivide the ReadConsoleInput operation into smaller and smaller chunks as
needed until it succeeds in reading the entire screen buffer. */
static BOOL
ReadConsoleOutputWrapper (HANDLE h, PCHAR_INFO buf, COORD bufsiz,
SMALL_RECT region)
{
COORD coord = {};
SHORT width = delta (region.Left, region.Right);
SHORT height = delta (region.Top, region.Bottom);
if ((width == 0) || (height == 0))
return TRUE;
BOOL success = ReadConsoleOutputW (h, buf, bufsiz, coord, ®ion);
if (success)
/* it worked */;
else if (GetLastError () == ERROR_NOT_ENOUGH_MEMORY && (width * height) > 1)
{
PCHAR_INFO buf_b;
COORD bufsiz_b;
SMALL_RECT region_b;
region_split (buf, bufsiz, region, buf_b, bufsiz_b, region_b);
success = ReadConsoleOutputWrapper (h, buf, bufsiz, region)
&& ReadConsoleOutputWrapper (h, buf_b, bufsiz_b, region_b);
}
return success;
}
void
dev_console::save_restore (HANDLE h, char c)
{
if (c == 'h') /* save */
{
fillin (h);
save_bufsize.X = b.dwSize.X;
if ((save_bufsize.Y = dwEnd.Y + 1) > b.dwSize.Y)
save_bufsize.X = b.dwSize.Y;
if (save_buf)
cfree (save_buf);
size_t screen_size = sizeof (CHAR_INFO) * save_bufsize.X * save_bufsize.Y;
save_buf = (PCHAR_INFO) cmalloc_abort (HEAP_1_BUF, screen_size);
save_cursor = b.dwCursorPosition; /* Remember where we were. */
save_top = b.srWindow.Top;
SMALL_RECT now = {}; /* Read the whole buffer */
now.Bottom = save_bufsize.Y - 1;
now.Right = save_bufsize.X - 1;
if (!ReadConsoleOutputWrapper (h, save_buf, save_bufsize, now))
debug_printf ("ReadConsoleOutputWrapper(h, ...) failed during save, %E");
/* Position at top of buffer */
COORD cob = {};
if (!SetConsoleCursorPosition (h, cob))
debug_printf ("SetConsoleCursorInfo(%p, ...) failed during save, %E", h);
/* Clear entire buffer */
clear_screen (h, 0, 0, now.Right, now.Bottom);
b.dwCursorPosition.X = b.dwCursorPosition.Y = dwEnd.X = dwEnd.Y = 0;
}
else if (save_buf)
{
COORD cob = {};
SMALL_RECT now = {};
now.Bottom = save_bufsize.Y - 1;
now.Right = save_bufsize.X - 1;
/* Restore whole buffer */
clear_screen (h, 0, 0, b.dwSize.X - 1, b.dwSize.Y - 1);
BOOL res = WriteConsoleOutputW (h, save_buf, save_bufsize, cob, &now);
if (!res)
debug_printf ("WriteConsoleOutputW failed, %E");
cfree (save_buf);
save_buf = NULL;
cob.X = 0;
cob.Y = save_top;
/* CGF: NOOP? Doesn't seem to position screen as expected */
/* Temporarily position at top of screen */
if (!SetConsoleCursorPosition (h, cob))
debug_printf ("SetConsoleCursorInfo(%p, cob) failed during restore, %E", h);
/* Position where we were previously */
if (!SetConsoleCursorPosition (h, save_cursor))
debug_printf ("SetConsoleCursorInfo(%p, save_cursor) failed during restore, %E", h);
/* Get back correct version of buffer information */
dwEnd.X = dwEnd.Y = 0;
fillin (h);
}
}
#define BAK 1
#define ESC 2
#define NOR 0
#define IGN 4
#if 1
#define ERR 5
#else
#define ERR NOR
#endif
#define DWN 6
#define BEL 7
#define TAB 8 /* We should't let the console deal with these */
#define CR 13
#define LF 10
#define SO 14
#define SI 15
static const char base_chars[256] =
{
/*00 01 02 03 04 05 06 07 */ IGN, ERR, ERR, NOR, NOR, NOR, NOR, BEL,
/*08 09 0A 0B 0C 0D 0E 0F */ BAK, TAB, DWN, ERR, ERR, CR, SO, SI,
/*10 11 12 13 14 15 16 17 */ NOR, NOR, ERR, ERR, ERR, ERR, ERR, ERR,
/*18 19 1A 1B 1C 1D 1E 1F */ NOR, NOR, ERR, ESC, ERR, ERR, ERR, ERR,
/* ! " # $ % & ' */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*( ) * + , - . / */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*0 1 2 3 4 5 6 7 */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*8 9 : ; < = > ? */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*@ A B C D E F G */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*H I J K L M N O */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*P Q R S T U V W */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*X Y Z [ \ ] ^ _ */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*` a b c d e f g */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*h i j k l m n o */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*p q r s t u v w */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*x y z { | } ~ 7F */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*80 81 82 83 84 85 86 87 */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*88 89 8A 8B 8C 8D 8E 8F */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*90 91 92 93 94 95 96 97 */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*98 99 9A 9B 9C 9D 9E 9F */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*A0 A1 A2 A3 A4 A5 A6 A7 */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*A8 A9 AA AB AC AD AE AF */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*B0 B1 B2 B3 B4 B5 B6 B7 */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*B8 B9 BA BB BC BD BE BF */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*C0 C1 C2 C3 C4 C5 C6 C7 */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*C8 C9 CA CB CC CD CE CF */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*D0 D1 D2 D3 D4 D5 D6 D7 */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*D8 D9 DA DB DC DD DE DF */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*E0 E1 E2 E3 E4 E5 E6 E7 */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*E8 E9 EA EB EC ED EE EF */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*F0 F1 F2 F3 F4 F5 F6 F7 */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR,
/*F8 F9 FA FB FC FD FE FF */ NOR, NOR, NOR, NOR, NOR, NOR, NOR, NOR };
void
fhandler_console::char_command (char c)
{
int x, y, n;
char buf[40];
switch (c)
{
case 'm': /* Set Graphics Rendition */
for (int i = 0; i <= con.nargs; i++)
switch (con.args[i])
{
case 0: /* normal color */
con.set_default_attr ();
break;
case 1: /* bold */
con.intensity = INTENSITY_BOLD;
break;
case 2: /* dim */
con.intensity = INTENSITY_DIM;
break;
case 4: /* underlined */
con.underline = 1;
break;
case 5: /* blink mode */
con.blink = true;
break;
case 7: /* reverse */
con.reverse = true;
break;
case 8: /* invisible */
con.intensity = INTENSITY_INVISIBLE;
break;
case 10: /* end alternate charset */
con.alternate_charset_active = false;
break;
case 11: /* start alternate charset */
con.alternate_charset_active = true;
break;
case 22:
case 28:
con.intensity = INTENSITY_NORMAL;
break;
case 24:
con.underline = false;
break;
case 25:
con.blink = false;
break;
case 27:
con.reverse = false;
break;
case 30: /* BLACK foreground */
con.fg = 0;
break;
case 31: /* RED foreground */
con.fg = FOREGROUND_RED;
break;
case 32: /* GREEN foreground */
con.fg = FOREGROUND_GREEN;
break;
case 33: /* YELLOW foreground */
con.fg = FOREGROUND_RED | FOREGROUND_GREEN;
break;
case 34: /* BLUE foreground */
con.fg = FOREGROUND_BLUE;
break;
case 35: /* MAGENTA foreground */
con.fg = FOREGROUND_RED | FOREGROUND_BLUE;
break;
case 36: /* CYAN foreground */
con.fg = FOREGROUND_BLUE | FOREGROUND_GREEN;
break;
case 37: /* WHITE foreg */
con.fg = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
break;
case 39:
con.fg = con.default_color & FOREGROUND_ATTR_MASK;
break;
case 40: /* BLACK background */
con.bg = 0;
break;
case 41: /* RED background */
con.bg = BACKGROUND_RED;
break;
case 42: /* GREEN background */
con.bg = BACKGROUND_GREEN;
break;
case 43: /* YELLOW background */
con.bg = BACKGROUND_RED | BACKGROUND_GREEN;
break;
case 44: /* BLUE background */
con.bg = BACKGROUND_BLUE;
break;
case 45: /* MAGENTA background */
con.bg = BACKGROUND_RED | BACKGROUND_BLUE;
break;
case 46: /* CYAN background */
con.bg = BACKGROUND_BLUE | BACKGROUND_GREEN;
break;
case 47: /* WHITE background */
con.bg = BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
break;
case 49:
con.bg = con.default_color & BACKGROUND_ATTR_MASK;
break;
}
con.set_color (get_output_handle ());
break;
case 'q': /* Set cursor style (DECSCUSR) */
if (con.saw_space)
{
CONSOLE_CURSOR_INFO console_cursor_info;
GetConsoleCursorInfo (get_output_handle (), &console_cursor_info);
switch (con.args[0])
{
case 0: /* blinking block */
case 1: /* blinking block (default) */
case 2: /* steady block */
console_cursor_info.dwSize = 100;
SetConsoleCursorInfo (get_output_handle (), &console_cursor_info);
break;
case 3: /* blinking underline */
case 4: /* steady underline */
console_cursor_info.dwSize = 10; /* or Windows default 25? */
SetConsoleCursorInfo (get_output_handle (), &console_cursor_info);
break;
default: /* use value as percentage */
console_cursor_info.dwSize = con.args[0];
SetConsoleCursorInfo (get_output_handle (), &console_cursor_info);
break;
}
}
break;
case 'h':
case 'l':
if (!con.saw_question_mark)
{
switch (con.args[0])
{
case 4: /* Insert mode */
con.insert_mode = (c == 'h') ? true : false;
syscall_printf ("insert mode %sabled", con.insert_mode ? "en" : "dis");
break;
}
break;
}
switch (con.args[0])
{
case 25: /* Show/Hide Cursor (DECTCEM) */
{
CONSOLE_CURSOR_INFO console_cursor_info;
GetConsoleCursorInfo (get_output_handle (), & console_cursor_info);
if (c == 'h')
console_cursor_info.bVisible = TRUE;
else
console_cursor_info.bVisible = FALSE;
SetConsoleCursorInfo (get_output_handle (), & console_cursor_info);
break;
}
case 47: /* Save/Restore screen */
con.save_restore (get_output_handle (), c);
break;
case 67: /* DECBKM ("DEC Backarrow Key Mode") */
con.backspace_keycode = (c == 'h' ? CTRL('H') : CERASE);
break;
case 1000: /* Mouse tracking */
con.use_mouse = (c == 'h') ? 1 : 0;
break;
case 1002: /* Mouse button event tracking */
con.use_mouse = (c == 'h') ? 2 : 0;
break;
case 1003: /* Mouse any event tracking */
con.use_mouse = (c == 'h') ? 3 : 0;
break;
case 1004: /* Focus in/out event reporting */
con.use_focus = (c == 'h') ? true : false;
break;
case 1005: /* Extended mouse mode */
con.ext_mouse_mode5 = c == 'h';
break;
case 1006: /* SGR extended mouse mode */
con.ext_mouse_mode6 = c == 'h';
break;
case 1015: /* Urxvt extended mouse mode */
con.ext_mouse_mode15 = c == 'h';
break;
case 2000: /* Raw keyboard mode */
set_raw_win32_keyboard_mode ((c == 'h') ? true : false);
break;
default: /* Ignore */
syscall_printf ("unknown h/l command: %d", con.args[0]);
break;
}
break;
case 'J':
switch (con.args[0])
{
case 0: /* Clear to end of screen */
clear_screen (cl_curr_pos, cl_curr_pos, cl_disp_end, cl_disp_end);
break;
case 1: /* Clear from beginning of screen to cursor */
clear_screen (cl_disp_beg, cl_disp_beg, cl_curr_pos, cl_curr_pos);
break;
case 2: /* Clear screen */
cursor_get (&x, &y);
clear_screen (cl_disp_beg, cl_disp_beg, cl_disp_end, cl_disp_end);
cursor_set (false, x, y);
break;
default:
goto bad_escape;
}
break;
case 'A':
cursor_rel (0, -(con.args[0] ?: 1));
break;
case 'B':
cursor_rel (0, con.args[0] ?: 1);
break;
case 'C':
cursor_rel (con.args[0] ?: 1, 0);
break;
case 'D':
cursor_rel (-(con.args[0] ?: 1),0);
break;
case 'K':
switch (con.args[0])
{
case 0: /* Clear to end of line */
clear_screen (cl_curr_pos, cl_curr_pos, cl_disp_end, cl_curr_pos);
break;
case 2: /* Clear line */
clear_screen (cl_disp_beg, cl_curr_pos, cl_disp_end, cl_curr_pos);
break;
case 1: /* Clear from bol to cursor */
clear_screen (cl_disp_beg, cl_curr_pos, cl_curr_pos, cl_curr_pos);
break;
default:
goto bad_escape;
}
break;
case 'H':
case 'f':
cursor_set (true, (con.args[1] ?: 1) - 1,
(con.args[0] ?: 1) - 1);
break;
case 'G': /* hpa - position cursor at column n - 1 */
cursor_get (&x, &y);
cursor_set (false, (con.args[0] ? con.args[0] - 1 : 0), y);
break;
case 'd': /* vpa - position cursor at line n */
cursor_get (&x, &y);
cursor_set (true, x, (con.args[0] ? con.args[0] - 1 : 0));
break;
case 's': /* Save cursor position */
cursor_get (&con.savex, &con.savey);
con.savey -= con.b.srWindow.Top;
break;
case 'u': /* Restore cursor position */
cursor_set (true, con.savex, con.savey);
break;
case 'I': /* TAB */
cursor_get (&x, &y);
cursor_set (false, 8 * (x / 8 + 1), y);
break;
case 'L': /* AL - insert blank lines */
n = con.args[0] ?: 1;
cursor_get (&x, &y);
scroll_buffer (0, y, -1, -1, 0, y + n);
break;
case 'M': /* DL - delete lines */
n = con.args[0] ?: 1;
cursor_get (&x, &y);
scroll_buffer (0, y + n, -1, -1, 0, y);
break;
case '@': /* IC - insert chars */
n = con.args[0] ?: 1;
cursor_get (&x, &y);
scroll_buffer (x, y, -1, y, x + n, y);
break;
case 'P': /* DC - delete chars */
n = con.args[0] ?: 1;
cursor_get (&x, &y);
scroll_buffer (x + n, y, -1, y, x, y);
break;
case 'S': /* SF - Scroll forward */
n = con.args[0] ?: 1;
scroll_buffer_screen (0, n, -1, -1, 0, 0);
break;
case 'T': /* SR - Scroll down */
con.fillin (get_output_handle ());
n = con.b.srWindow.Top + con.args[0] ?: 1;
scroll_buffer_screen (0, 0, -1, -1, 0, n);
break;
case 'X': /* ec - erase chars */
n = con.args[0] ?: 1;
cursor_get (&x, &y);
scroll_buffer (x + n, y, -1, y, x, y);
scroll_buffer (x, y, -1, y, x + n, y);
break;
case 'Z': /* Back tab */
cursor_get (&x, &y);
cursor_set (false, ((8 * (x / 8 + 1)) - 8), y);
break;
case 'b': /* Repeat char #1 #2 times */
if (con.insert_mode)
{
cursor_get (&x, &y);
scroll_buffer (x, y, -1, y, x + con.args[1], y);
}
while (con.args[1]--)
WriteFile (get_output_handle (), &con.args[0], 1, (DWORD *) &x, 0);
break;
case 'c': /* u9 - Terminal enquire string */
if (con.saw_greater_than_sign)
/* Generate Secondary Device Attribute report, using 67 = ASCII 'C'
to indicate Cygwin (convention used by Rxvt, Urxvt, Screen, Mintty),
and cygwin version for terminal version. */
__small_sprintf (buf, "\033[>67;%d%02d;0c", CYGWIN_VERSION_DLL_MAJOR, CYGWIN_VERSION_DLL_MINOR);
else
strcpy (buf, "\033[?6c");
/* The generated report needs to be injected for read-ahead into the
fhandler_console object associated with standard input.
So puts_readahead does not work.
Use a common console read-ahead buffer instead. */
con.cons_rapoi = NULL;
strcpy (con.cons_rabuf, buf);
con.cons_rapoi = con.cons_rabuf;
break;
case 'n':
switch (con.args[0])
{
case 6: /* u7 - Cursor position request */
cursor_get (&x, &y);
y -= con.b.srWindow.Top;
/* x -= con.b.srWindow.Left; // not available yet */
__small_sprintf (buf, "\033[%d;%dR", y + 1, x + 1);
con.cons_rapoi = NULL;
strcpy (con.cons_rabuf, buf);
con.cons_rapoi = con.cons_rabuf;
break;
default:
goto bad_escape;
}
break;
case 'r': /* Set Scroll region */
con.scroll_region.Top = con.args[0] ? con.args[0] - 1 : 0;
con.scroll_region.Bottom = con.args[1] ? con.args[1] - 1 : -1;
cursor_set (true, 0, 0);
break;
case 'g': /* TAB set/clear */
break;
default:
bad_escape:
break;
}
}
/* This gets called when we found an invalid input character. We just
print a half filled square (UTF 0x2592). We have no chance to figure
out the "meaning" of the input char anyway. */
inline void
fhandler_console::write_replacement_char ()
{
static const wchar_t replacement_char = 0x2592; /* Half filled square */
DWORD done;
WriteConsoleW (get_output_handle (), &replacement_char, 1, &done, 0);
}
const unsigned char *
fhandler_console::write_normal (const unsigned char *src,
const unsigned char *end)
{
/* Scan forward to see what a char which needs special treatment */
DWORD done;
DWORD buf_len;
const unsigned char *found = src;
size_t ret;
mbstate_t ps;
UINT cp = con.get_console_cp ();
const char *charset;
mbtowc_p f_mbtowc;
if (cp)
{
/* The alternate charset is always 437, just as in the Linux console. */
f_mbtowc = __cp_mbtowc;
charset = "CP437";
}
else
{
f_mbtowc = cygheap->locale.mbtowc;
charset = cygheap->locale.charset;
}
/* First check if we have cached lead bytes of a former try to write
a truncated multibyte sequence. If so, process it. */
if (trunc_buf.len)
{
const unsigned char *nfound;
int cp_len = MIN (end - src, 4 - trunc_buf.len);
memcpy (trunc_buf.buf + trunc_buf.len, src, cp_len);
memset (&ps, 0, sizeof ps);
switch (ret = f_mbtowc (_REENT, NULL, (const char *) trunc_buf.buf,
trunc_buf.len + cp_len, charset, &ps))
{
case -2:
/* Still truncated multibyte sequence? Keep in trunc_buf. */
trunc_buf.len += cp_len;
return end;
case -1:
/* Give up, print replacement chars for trunc_buf... */
for (int i = 0; i < trunc_buf.len; ++i)
write_replacement_char ();
/* ... mark trunc_buf as unused... */
trunc_buf.len = 0;
/* ... and proceed. */
nfound = NULL;
break;
case 0:
nfound = trunc_buf.buf + 1;
break;
default:
nfound = trunc_buf.buf + ret;
break;
}
/* Valid multibyte sequence? Process. */
if (nfound)
{
buf_len = con.str_to_con (f_mbtowc, charset, write_buf,
(const char *) trunc_buf.buf,
nfound - trunc_buf.buf);
if (!write_console (write_buf, buf_len, done))
{
debug_printf ("multibyte sequence write failed, handle %p", get_output_handle ());
return 0;
}
found = src + (nfound - trunc_buf.buf - trunc_buf.len);
trunc_buf.len = 0;
return found;
}
}
/* Loop over src buffer as long as we have just simple characters. Stop
as soon as we reach the conversion limit, or if we encounter a control
character or a truncated or invalid mutibyte sequence. */
memset (&ps, 0, sizeof ps);
while (found < end
&& found - src < CONVERT_LIMIT
&& base_chars[*found] == NOR)
{
switch (ret = f_mbtowc (_REENT, NULL, (const char *) found,
end - found, charset, &ps))
{
case -2: /* Truncated multibyte sequence. Store for next write. */
trunc_buf.len = end - found;
memcpy (trunc_buf.buf, found, trunc_buf.len);
goto do_print;
case -1: /* Invalid multibyte sequence. Handled below. */
goto do_print;
case 0:
found++;
break;
default:
found += ret;
break;
}
}
do_print:
/* Print all the base characters out */
if (found != src)
{
DWORD len = found - src;
buf_len = con.str_to_con (f_mbtowc, charset, write_buf,
(const char *) src, len);
if (!buf_len)
{
debug_printf ("conversion error, handle %p",
get_output_handle ());
__seterrno ();
return 0;
}
if (con.insert_mode)
{
int x, y;
cursor_get (&x, &y);
scroll_buffer (x, y, -1, y, x + buf_len, y);
}
if (!write_console (write_buf, buf_len, done))
{
debug_printf ("write failed, handle %p", get_output_handle ());
return 0;
}
/* Stop here if we reached the conversion limit. */
if (len >= CONVERT_LIMIT)
return found + trunc_buf.len;
}
/* If there's still something in the src buffer, but it's not a truncated
multibyte sequence, then we stumbled over a control character or an
invalid multibyte sequence. Print it. */
if (found < end && trunc_buf.len == 0)
{
int x, y;
switch (base_chars[*found])
{
case SO: /* Shift Out: Invoke G1 character set (ISO 2022) */
con.iso_2022_G1 = true;
break;
case SI: /* Shift In: Invoke G0 character set (ISO 2022) */
con.iso_2022_G1 = false;
break;
case BEL:
beep ();
break;
case ESC:
con.state = gotesc;
break;
case DWN:
cursor_get (&x, &y);
if (y >= srBottom)
{
if (y >= con.b.srWindow.Bottom && !con.scroll_region.Top)
WriteConsoleW (get_output_handle (), L"\n", 1, &done, 0);
else
{
scroll_buffer (0, srTop + 1, -1, srBottom, 0, srTop);
y--;
}
}
cursor_set (false, ((get_ttyp ()->ti.c_oflag & ONLCR) ? 0 : x), y + 1);
break;
case BAK:
cursor_rel (-1, 0);
break;
case IGN:
cursor_rel (1, 0);
break;
case CR:
cursor_get (&x, &y);
cursor_set (false, 0, y);
break;
case ERR:
/* Don't print chars marked as ERR chars, except for a ASCII CAN
sequence which is printed as singlebyte chars from the UTF
Basic Latin and Latin 1 Supplement plains. */
if (*found == 0x18)
{
write_replacement_char ();
if (found + 1 < end)
{
ret = __utf8_mbtowc (_REENT, NULL, (const char *) found + 1,
end - found - 1, NULL, &ps);
if (ret != (size_t) -1)
while (ret-- > 0)
{
WCHAR w = *(found + 1);
WriteConsoleW (get_output_handle (), &w, 1, &done, 0);
found++;
}
}
}
break;
case TAB:
cursor_get (&x, &y);
cursor_set (false, 8 * (x / 8 + 1), y);
break;
case NOR:
write_replacement_char ();
break;
}
found++;
}
return found + trunc_buf.len;
}
ssize_t __stdcall
fhandler_console::write (const void *vsrc, size_t len)
{
bg_check_types bg = bg_check (SIGTTOU);
if (bg <= bg_eof)
return (ssize_t) bg;
push_process_state process_state (PID_TTYOU);
/* Run and check for ansi sequences */
unsigned const char *src = (unsigned char *) vsrc;
unsigned const char *end = src + len;
/* This might look a bit far fetched, but using the TLS path buffer allows
to allocate a big buffer without using the stack too much. Doing it here
in write instead of in write_normal should be faster, too. */
tmp_pathbuf tp;
write_buf = tp.w_get ();
debug_printf ("%p, %ld", vsrc, len);
while (src < end)
{
paranoid_printf ("char %0c state is %d", *src, con.state);
switch (con.state)
{
case normal:
src = write_normal (src, end);
if (!src) /* write_normal failed */
return -1;
break;
case gotesc:
if (*src == '[') /* CSI Control Sequence Introducer */
{
con.state = gotsquare;
con.saw_question_mark = false;
con.saw_greater_than_sign = false;
con.saw_space = false;
for (con.nargs = 0; con.nargs < MAXARGS; con.nargs++)
con.args[con.nargs] = 0;
con.nargs = 0;
}
else if (*src == ']') /* OSC Operating System Command */
{
con.rarg = 0;
con.my_title_buf[0] = '\0';
con.state = gotrsquare;
}
else if (*src == '(') /* Designate G0 character set */
{
con.state = gotparen;
}
else if (*src == ')') /* Designate G1 character set */
{
con.state = gotrparen;
}
else if (*src == 'M') /* Reverse Index (scroll down) */
{
con.fillin (get_output_handle ());
scroll_buffer_screen (0, 0, -1, -1, 0, 1);
con.state = normal;
}
else if (*src == 'c') /* RIS Full Reset */
{
con.set_default_attr ();
con.vt100_graphics_mode_G0 = false;
con.vt100_graphics_mode_G1 = false;
con.iso_2022_G1 = false;
cursor_set (false, 0, 0);
clear_screen (cl_buf_beg, cl_buf_beg, cl_buf_end, cl_buf_end);
con.state = normal;
}
else if (*src == '8') /* DECRC Restore cursor position */
{
cursor_set (false, con.savex, con.savey);
con.state = normal;
}
else if (*src == '7') /* DECSC Save cursor position */
{
cursor_get (&con.savex, &con.savey);
con.state = normal;
}
else if (*src == 'R') /* ? */
con.state = normal;
else
{
con.state = normal;
}
src++;
break;
case gotarg1:
if (isdigit (*src))
{
con.args[con.nargs] = con.args[con.nargs] * 10 + *src - '0';
src++;
}
else if (*src == ';')
{
src++;
con.nargs++;
if (con.nargs >= MAXARGS)
con.nargs--;
}
else if (*src == ' ')
{
src++;
con.saw_space = true;
con.state = gotcommand;
}
else
con.state = gotcommand;
break;
case gotcommand:
char_command (*src++);
con.state = normal;
break;
case gotrsquare:
if (isdigit (*src))
con.rarg = con.rarg * 10 + (*src - '0');
else if (*src == ';' && (con.rarg == 2 || con.rarg == 0))
con.state = gettitle;
else
con.state = eattitle;
src++;
break;
case eattitle:
case gettitle:
{
int n = strlen (con.my_title_buf);
if (*src < ' ')
{
if (*src == '\007' && con.state == gettitle)
set_console_title (con.my_title_buf);
con.state = normal;
}
else if (n < TITLESIZE)
{
con.my_title_buf[n++] = *src;
con.my_title_buf[n] = '\0';
}
src++;
break;
}
case gotsquare:
if (*src == ';')
{
con.state = gotarg1;
con.nargs++;
src++;
}
else if (isalpha (*src))
con.state = gotcommand;
else if (*src != '@' && !isalpha (*src) && !isdigit (*src))
{
if (*src == '?')
con.saw_question_mark = true;
else if (*src == '>')
con.saw_greater_than_sign = true;
/* ignore any extra chars between [ and first arg or command */
src++;
}
else
con.state = gotarg1;
break;
case gotparen: /* Designate G0 Character Set (ISO 2022) */
if (*src == '0')
con.vt100_graphics_mode_G0 = true;
else
con.vt100_graphics_mode_G0 = false;
con.state = normal;
src++;
break;
case gotrparen: /* Designate G1 Character Set (ISO 2022) */
if (*src == '0')
con.vt100_graphics_mode_G1 = true;
else
con.vt100_graphics_mode_G1 = false;
con.state = normal;
src++;
break;
}
}
syscall_printf ("%ld = fhandler_console::write(...)", len);
return len;
}
static const struct {
int vk;
const char *val[4];
} keytable[] = {
/* NORMAL */ /* SHIFT */ /* CTRL */ /* CTRL-SHIFT */
/* Unmodified and Alt-modified keypad keys comply with linux console
SHIFT, CTRL, CTRL-SHIFT modifiers comply with xterm modifier usage */
{VK_NUMPAD5, {"\033[G", "\033[1;2G", "\033[1;5G", "\033[1;6G"}},
{VK_CLEAR, {"\033[G", "\033[1;2G", "\033[1;5G", "\033[1;6G"}},
{VK_LEFT, {"\033[D", "\033[1;2D", "\033[1;5D", "\033[1;6D"}},
{VK_RIGHT, {"\033[C", "\033[1;2C", "\033[1;5C", "\033[1;6C"}},
{VK_UP, {"\033[A", "\033[1;2A", "\033[1;5A", "\033[1;6A"}},
{VK_DOWN, {"\033[B", "\033[1;2B", "\033[1;5B", "\033[1;6B"}},
{VK_PRIOR, {"\033[5~", "\033[5;2~", "\033[5;5~", "\033[5;6~"}},
{VK_NEXT, {"\033[6~", "\033[6;2~", "\033[6;5~", "\033[6;6~"}},
{VK_HOME, {"\033[1~", "\033[1;2~", "\033[1;5~", "\033[1;6~"}},
{VK_END, {"\033[4~", "\033[4;2~", "\033[4;5~", "\033[4;6~"}},
{VK_INSERT, {"\033[2~", "\033[2;2~", "\033[2;5~", "\033[2;6~"}},
{VK_DELETE, {"\033[3~", "\033[3;2~", "\033[3;5~", "\033[3;6~"}},
/* F1...F12, SHIFT-F1...SHIFT-F10 comply with linux console
F6...F12, and all modified F-keys comply with rxvt (compatible extension) */
{VK_F1, {"\033[[A", "\033[23~", "\033[11^", "\033[23^"}},
{VK_F2, {"\033[[B", "\033[24~", "\033[12^", "\033[24^"}},
{VK_F3, {"\033[[C", "\033[25~", "\033[13^", "\033[25^"}},
{VK_F4, {"\033[[D", "\033[26~", "\033[14^", "\033[26^"}},
{VK_F5, {"\033[[E", "\033[28~", "\033[15^", "\033[28^"}},
{VK_F6, {"\033[17~", "\033[29~", "\033[17^", "\033[29^"}},
{VK_F7, {"\033[18~", "\033[31~", "\033[18^", "\033[31^"}},
{VK_F8, {"\033[19~", "\033[32~", "\033[19^", "\033[32^"}},
{VK_F9, {"\033[20~", "\033[33~", "\033[20^", "\033[33^"}},
{VK_F10, {"\033[21~", "\033[34~", "\033[21^", "\033[34^"}},
{VK_F11, {"\033[23~", "\033[23$", "\033[23^", "\033[23@"}},
{VK_F12, {"\033[24~", "\033[24$", "\033[24^", "\033[24@"}},
/* CTRL-6 complies with Windows cmd console but should be fixed */
{'6', {NULL, NULL, "\036", NULL}},
/* Table end marker */
{0}
};
const char *
fhandler_console::get_nonascii_key (INPUT_RECORD& input_rec, char *tmp)
{
#define NORMAL 0
#define SHIFT 1
#define CONTROL 2
/*#define CONTROLSHIFT 3*/
int modifier_index = NORMAL;
if (input_rec.Event.KeyEvent.dwControlKeyState & SHIFT_PRESSED)
modifier_index = SHIFT;
if (input_rec.Event.KeyEvent.dwControlKeyState & CTRL_PRESSED)
modifier_index += CONTROL;
for (int i = 0; keytable[i].vk; i++)
if (input_rec.Event.KeyEvent.wVirtualKeyCode == keytable[i].vk)
{
if ((input_rec.Event.KeyEvent.dwControlKeyState & ALT_PRESSED)
&& keytable[i].val[modifier_index] != NULL)
{ /* Generic ESC prefixing if Alt is pressed */
tmp[0] = '\033';
strcpy (tmp + 1, keytable[i].val[modifier_index]);
return tmp;
}
else
return keytable[i].val[modifier_index];
}
if (input_rec.Event.KeyEvent.uChar.AsciiChar)
{
tmp[0] = input_rec.Event.KeyEvent.uChar.AsciiChar;
tmp[1] = '\0';
return tmp;
}
return NULL;
}
int
fhandler_console::init (HANDLE h, DWORD a, mode_t bin)
{
// this->fhandler_termios::init (h, mode, bin);
/* Ensure both input and output console handles are open */
int flags = 0;
a &= GENERIC_READ | GENERIC_WRITE;
if (a == GENERIC_READ)
flags = O_RDONLY;
if (a == GENERIC_WRITE)
flags = O_WRONLY;
if (a == (GENERIC_READ | GENERIC_WRITE))
flags = O_RDWR;
open_with_arch (flags | O_BINARY | (h ? 0 : O_NOCTTY));
return !tcsetattr (0, &get_ttyp ()->ti);
}
int
fhandler_console::igncr_enabled ()
{
return get_ttyp ()->ti.c_iflag & IGNCR;
}
void
fhandler_console::set_close_on_exec (bool val)
{
close_on_exec (val);
}
void __stdcall
set_console_title (char *title)
{
wchar_t buf[TITLESIZE + 1];
sys_mbstowcs (buf, TITLESIZE + 1, title);
lock_ttys here (15000);
SetConsoleTitleW (buf);
debug_printf ("title '%W'", buf);
}
void
fhandler_console::fixup_after_fork_exec (bool execing)
{
set_unit ();
}
// #define WINSTA_ACCESS (WINSTA_READATTRIBUTES | STANDARD_RIGHTS_READ | STANDARD_RIGHTS_WRITE | WINSTA_CREATEDESKTOP | WINSTA_EXITWINDOWS)
#define WINSTA_ACCESS WINSTA_ALL_ACCESS
/* Create a console in an invisible window station. This should work
in all versions of Windows NT except Windows 7 (so far). */
bool
fhandler_console::create_invisible_console (HWINSTA horig)
{
HWINSTA h = CreateWindowStationW (NULL, 0, WINSTA_ACCESS, NULL);
termios_printf ("%p = CreateWindowStation(NULL), %E", h);
BOOL b;
if (h)
{
b = SetProcessWindowStation (h);
termios_printf ("SetProcessWindowStation %d, %E", b);
}
b = AllocConsole (); /* will cause flashing if CreateWindowStation
failed */
if (!h)
SetParent (GetConsoleWindow (), HWND_MESSAGE);
if (horig && h && h != horig && SetProcessWindowStation (horig))
CloseWindowStation (h);
termios_printf ("%d = AllocConsole (), %E", b);
invisible_console = true;
return b;
}
/* Ugly workaround for Windows 7 and later.
First try to just attach to any console which may have started this
app. If that works use this as our "invisible console".
This will fail if not started from the command prompt. In that case, start
a dummy console application in a hidden state so that we can use its console
as our invisible console. This probably works everywhere but process
creation is slow and to be avoided if possible so the window station method
is vastly preferred.
FIXME: This is not completely thread-safe since it creates two inheritable
handles which are known only to this function. If another thread starts
a process the new process will inherit these handles. However, since this
function is currently only called at startup and during exec, it shouldn't
be a big deal. */
bool
fhandler_console::create_invisible_console_workaround ()
{
if (!AttachConsole (-1))
{
bool taskbar;
DWORD err = GetLastError ();
path_conv helper ("/bin/cygwin-console-helper.exe");
HANDLE hello = NULL;
HANDLE goodbye = NULL;
/* If err == ERROR_PROC_FOUND then this method won't work. But that's
ok. The window station method should work ok when AttachConsole doesn't
work.
If the helper doesn't exist or we can't create event handles then we
can't use this method. */
if (err == ERROR_PROC_NOT_FOUND || !helper.exists ()
|| !(hello = CreateEvent (&sec_none, true, false, NULL))
|| !(goodbye = CreateEvent (&sec_none, true, false, NULL)))
{
AllocConsole (); /* This is just sanity check code. We should
never actually hit here unless we're running
in an environment which lacks the helper
app. */
taskbar = true;
}
else
{
STARTUPINFOW si = {};
PROCESS_INFORMATION pi;
size_t len = helper.get_wide_win32_path_len ();
WCHAR cmd[len + (2 * strlen (" 0xffffffff")) + 1];
WCHAR title[] = L"invisible cygwin console";
helper.get_wide_win32_path (cmd);
__small_swprintf (cmd + len, L" %p %p", hello, goodbye);
si.cb = sizeof (si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.lpTitle = title;
/* Create a new hidden process. Use the two event handles as
argv[1] and argv[2]. */
BOOL x = CreateProcessW (NULL, cmd, &sec_none_nih, &sec_none_nih, true,
CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
if (x)
{
CloseHandle (pi.hProcess); /* Don't need */
CloseHandle (pi.hThread); /* these. */
}
taskbar = false;
/* Wait for subprocess to indicate that it is live. This may not
actually be needed but it's hard to say since it is possible that
there will be no console for a brief time after the process
returns and there is no easy way to determine if/when this happens
in Windows. So play it safe. */
if (!x || (WaitForSingleObject (hello, 10000) != WAIT_OBJECT_0)
|| !AttachConsole (pi.dwProcessId))
AllocConsole (); /* Oh well. Watch the flash. */
}
if (!taskbar)
/* Setting the owner of the console window to HWND_MESSAGE seems to
hide it from the taskbar. Don't know if this method is faster than
calling ShowWindowAsync but it should guarantee no taskbar presence
for the hidden console. */
SetParent (GetConsoleWindow (), HWND_MESSAGE);
if (hello)
CloseHandle (hello);
if (goodbye)
{
SetEvent (goodbye); /* Tell helper process it's ok to exit. */
CloseHandle (goodbye);
}
}
return invisible_console = true;
}
void
fhandler_console::free_console ()
{
BOOL res = FreeConsole ();
debug_printf ("freed console, res %d", res);
init_console_handler (false);
}
bool
fhandler_console::need_invisible ()
{
BOOL b = false;
if (exists ())
invisible_console = false;
else
{
HWINSTA h;
/* The intent here is to allocate an "invisible" console if we have no
controlling tty or to reuse the existing console if we already have
a tty. So, first get the old window station. If there is no controlling
terminal, create a new window station and then set it as the current
window station. The subsequent AllocConsole will then be allocated
invisibly. But, after doing that we have to restore any existing windows
station or, strangely, characters will not be displayed in any windows
drawn on the current screen. We only do this if we have changed to
a new window station and if we had an existing windows station previously.
We also close the previously opened window station even though AllocConsole
is now "using" it. This doesn't seem to cause any problems.
Things to watch out for if you make changes in this code:
- Flashing, black consoles showing up when you start, e.g., ssh in
an xterm.
- Non-displaying of characters in rxvt or xemacs if you start a
process using setsid: bash -lc "setsid rxvt". */
h = GetProcessWindowStation ();
USEROBJECTFLAGS oi;
DWORD len;
if (!h
|| !GetUserObjectInformationW (h, UOI_FLAGS, &oi, sizeof (oi), &len)
|| !(oi.dwFlags & WSF_VISIBLE))
{
b = true;
debug_printf ("window station is not visible");
AllocConsole ();
invisible_console = true;
}
else if (wincap.has_broken_alloc_console ())
b = create_invisible_console_workaround ();
else
b = create_invisible_console (h);
}
debug_printf ("invisible_console %d", invisible_console);
return b;
}
|
gpl-2.0
|
manhhung86it/builder-site
|
wp-content/plugins/a3-portfolio-edited/templates/navbar/main-navbar.php
|
1561
|
<?php
/**
* The template for displaying the main nav bar on main page or archive page
*
* Override this template by copying it to yourtheme/portfolio/navbar/main-navbar.php
*
* @author A3 Rev
* @version 1.0.0
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly
}
?>
<div style="clear:both"></div>
<div class="a3-portfolio-navigation-mobile">
<i class="a3-portfolio-navigation-mobile-icon a3-portfolio-icon-list"></i>
<span><?php echo a3_portfolio_ei_ict_t__('Mobile Navigation', __('Navigation', 'a3_portfolios')); ?></span>
</div>
<div style="clear:both"></div>
<div class="a3-portfolio-menus-container">
<div style="clear:both"></div>
<ul class="filter">
<li>
<a rel="*" href="#" class="filter-m active"><?php echo a3_portfolio_ei_ict_t__('All Filter', __('All', 'a3_portfolios')); ?></a>
</li>
<?php
if (is_array($menus) && count($menus) > 0) :
foreach ($menus as $menu_slug => $menu_name):
?>
<li class="_<?php echo $menu_slug; ?>">
<a rel="<?php echo $menu_slug; ?>" class="filter-m" href="#"><?php echo $menu_name; ?></a>
</li>
<?php
endforeach;
endif;
?>
<li style="display: none" class="_uncategorized">
<a rel="uncategorized" class="filter-m" href="#"><?php echo __('Uncategorized', 'a3_portfolios'); ?></a>
</li>
</ul>
<div style="clear:both"></div>
</div>
<div style="clear:both"></div>
|
gpl-2.0
|
SunriseSoftVN/hayhayblog
|
parser/app/vn/myfeed/parser/processor/DistanceBaseFilter.scala
|
1007
|
package vn.myfeed.parser.processor
import vn.myfeed.parser.model.{LinkElement, ArticleElement, Article}
/**
* This class base on distance of two potential element to find another potential element.
*
* @param maxDistance distance between two elements
*
* @author Nguyen Duc Dung
* @since 12/24/12 7:26 AM
*
*/
class DistanceBaseFilter(maxDistance: Int = 2) extends Processor {
def process(implicit article: Article) {
var lastPotentialElement: Option[ArticleElement] = None
article.elements.foreach(element => {
if (element.isPotential) {
lastPotentialElement.map(lastElement => {
val distance = element.index - lastElement.index
if (1 < distance && distance <= maxDistance) {
for (i <- lastElement.index to element.index) {
val el = article.elements(i)
if(!el.isInstanceOf[LinkElement]) el.isPotential = true
}
}
})
lastPotentialElement = Some(element)
}
})
}
}
|
gpl-2.0
|
alongosz/ezpublish-kernel
|
eZ/Publish/API/Repository/Tests/ContentServiceTest.php
|
242464
|
<?php
/**
* File containing the ContentServiceTest class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
namespace eZ\Publish\API\Repository\Tests;
use eZ\Publish\API\Repository\Exceptions\BadStateException;
use eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException;
use eZ\Publish\API\Repository\Exceptions\InvalidArgumentException as APIInvalidArgumentException;
use eZ\Publish\API\Repository\Values\Content\Content;
use eZ\Publish\API\Repository\Exceptions\UnauthorizedException;
use eZ\Publish\API\Repository\Values\Content\ContentCreateStruct;
use eZ\Publish\API\Repository\Values\Content\ContentInfo;
use eZ\Publish\API\Repository\Values\Content\ContentMetadataUpdateStruct;
use eZ\Publish\API\Repository\Values\Content\Field;
use eZ\Publish\API\Repository\Values\Content\Location;
use eZ\Publish\API\Repository\Values\Content\DraftList\Item\UnauthorizedContentDraftListItem;
use eZ\Publish\API\Repository\Values\Content\URLAlias;
use eZ\Publish\API\Repository\Values\Content\Relation;
use eZ\Publish\API\Repository\Values\Content\VersionInfo;
use eZ\Publish\API\Repository\Values\User\Limitation\SectionLimitation;
use eZ\Publish\API\Repository\Values\User\Limitation\LocationLimitation;
use eZ\Publish\API\Repository\Values\User\Limitation\ContentTypeLimitation;
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
use Exception;
use eZ\Publish\API\Repository\Values\User\User;
use eZ\Publish\Core\Base\Exceptions\UnauthorizedException as CoreUnauthorizedException;
use eZ\Publish\Core\Repository\Values\Content\ContentUpdateStruct;
use InvalidArgumentException;
/**
* Test case for operations in the ContentService using in memory storage.
*
* @see \eZ\Publish\API\Repository\ContentService
* @group content
*/
class ContentServiceTest extends BaseContentServiceTest
{
private const ADMINISTRATORS_USER_GROUP_NAME = 'Administrators';
private const ADMINISTRATORS_USER_GROUP_ID = 12;
private const ADMINISTRATORS_USER_GROUP_LOCATION_ID = 13;
private const WRITERS_USER_GROUP_NAME = 'Writers';
private const MEMBERS_USER_GROUP_ID = 11;
private const MEDIA_CONTENT_ID = 41;
private const MEDIA_REMOTE_ID = 'a6e35cbcb7cd6ae4b691f3eee30cd262';
private const DEMO_DESIGN_REMOTE_ID = '8b8b22fe3c6061ed500fbd2b377b885f';
private const FORUM_IDENTIFIER = 'forum';
private const ENG_US = 'eng-US';
private const GER_DE = 'ger-DE';
private const ENG_GB = 'eng-GB';
/** @var \eZ\Publish\API\Repository\PermissionResolver */
private $permissionResolver;
/** @var \eZ\Publish\API\Repository\ContentService */
private $contentService;
/** @var \eZ\Publish\API\Repository\LocationService */
private $locationService;
public function setUp(): void
{
parent::setUp();
$repository = $this->getRepository();
$this->permissionResolver = $repository->getPermissionResolver();
$this->contentService = $repository->getContentService();
$this->locationService = $repository->getLocationService();
}
/**
* Test for the newContentCreateStruct() method.
*
* @see \eZ\Publish\API\Repository\ContentService::newContentCreateStruct()
* @depends eZ\Publish\API\Repository\Tests\ContentTypeServiceTest::testLoadContentTypeByIdentifier
* @group user
* @group field-type
*/
public function testNewContentCreateStruct()
{
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier(self::FORUM_IDENTIFIER);
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$this->assertInstanceOf(ContentCreateStruct::class, $contentCreate);
}
/**
* Test for the createContent() method.
*
* @return \eZ\Publish\API\Repository\Values\Content\Content
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testNewContentCreateStruct
* @group user
* @group field-type
*/
public function testCreateContent()
{
if ($this->isVersion4()) {
$this->markTestSkipped('This test requires eZ Publish 5');
}
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier(self::FORUM_IDENTIFIER);
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate->setField('name', 'My awesome forum');
$contentCreate->remoteId = 'abcdef0123456789abcdef0123456789';
$contentCreate->alwaysAvailable = true;
$content = $this->contentService->createContent($contentCreate);
$this->assertInstanceOf(Content::class, $content);
return $content;
}
/**
* Test for the createContent() method.
*
* Tests made for issue #EZP-20955 where Anonymous user is granted access to create content
* and should have access to do that.
*
* @return \eZ\Publish\API\Repository\Values\Content\Content
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testNewContentCreateStruct
* @group user
* @group field-type
*/
public function testCreateContentAndPublishWithPrivilegedAnonymousUser()
{
if ($this->isVersion4()) {
$this->markTestSkipped('This test requires eZ Publish 5');
}
$anonymousUserId = $this->generateId('user', 10);
$repository = $this->getRepository();
$contentTypeService = $this->getRepository()->getContentTypeService();
$roleService = $repository->getRoleService();
// Give Anonymous user role additional rights
$role = $roleService->loadRoleByIdentifier('Anonymous');
$roleDraft = $roleService->createRoleDraft($role);
$policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'create');
$policyCreateStruct->addLimitation(new SectionLimitation(['limitationValues' => [1]]));
$policyCreateStruct->addLimitation(new LocationLimitation(['limitationValues' => [2]]));
$policyCreateStruct->addLimitation(new ContentTypeLimitation(['limitationValues' => [1]]));
$roleDraft = $roleService->addPolicyByRoleDraft($roleDraft, $policyCreateStruct);
$policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'publish');
$policyCreateStruct->addLimitation(new SectionLimitation(['limitationValues' => [1]]));
$policyCreateStruct->addLimitation(new LocationLimitation(['limitationValues' => [2]]));
$policyCreateStruct->addLimitation(new ContentTypeLimitation(['limitationValues' => [1]]));
$roleDraft = $roleService->addPolicyByRoleDraft($roleDraft, $policyCreateStruct);
$roleService->publishRoleDraft($roleDraft);
// Set Anonymous user as current
$repository->getPermissionResolver()->setCurrentUserReference($repository->getUserService()->loadUser($anonymousUserId));
// Create a new content object:
$contentCreate = $this->contentService->newContentCreateStruct(
$contentTypeService->loadContentTypeByIdentifier('folder'),
self::ENG_GB
);
$contentCreate->setField('name', 'Folder 1');
$content = $this->contentService->createContent(
$contentCreate,
[$this->locationService->newLocationCreateStruct(2)]
);
$this->contentService->publishVersion(
$content->getVersionInfo()
);
}
/**
* Test for the createContent() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $content
*
* @return \eZ\Publish\API\Repository\Values\Content\Content
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
*/
public function testCreateContentSetsContentInfo($content)
{
$this->assertInstanceOf(ContentInfo::class, $content->contentInfo);
return $content;
}
/**
* Test for the createContent() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $content
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentSetsContentInfo
*/
public function testCreateContentSetsExpectedContentInfo($content)
{
$permissionResolver = $this->getRepository()->getPermissionResolver();
$this->assertEquals(
[
$content->id,
28, // id of content type "forum"
true,
1,
'abcdef0123456789abcdef0123456789',
self::ENG_US,
$permissionResolver->getCurrentUserReference()->getUserId(),
false,
null,
// Main Location id for unpublished Content should be null
null,
],
[
$content->contentInfo->id,
$content->contentInfo->contentTypeId,
$content->contentInfo->alwaysAvailable,
$content->contentInfo->currentVersionNo,
$content->contentInfo->remoteId,
$content->contentInfo->mainLanguageCode,
$content->contentInfo->ownerId,
$content->contentInfo->published,
$content->contentInfo->publishedDate,
$content->contentInfo->mainLocationId,
]
);
}
/**
* Test for the createContent() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $content
*
* @return \eZ\Publish\API\Repository\Values\Content\Content
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
*/
public function testCreateContentSetsVersionInfo($content)
{
$this->assertInstanceOf(VersionInfo::class, $content->getVersionInfo());
return $content;
}
/**
* Test for the createContent() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $content
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentSetsVersionInfo
*/
public function testCreateContentSetsExpectedVersionInfo($content)
{
$currentUserReference = $this->getRepository()->getPermissionResolver()->getCurrentUserReference();
$this->assertEquals(
[
'status' => VersionInfo::STATUS_DRAFT,
'versionNo' => 1,
'creatorId' => $currentUserReference->getUserId(),
'initialLanguageCode' => self::ENG_US,
],
[
'status' => $content->getVersionInfo()->status,
'versionNo' => $content->getVersionInfo()->versionNo,
'creatorId' => $content->getVersionInfo()->creatorId,
'initialLanguageCode' => $content->getVersionInfo()->initialLanguageCode,
]
);
$this->assertTrue($content->getVersionInfo()->isDraft());
$this->assertFalse($content->getVersionInfo()->isPublished());
$this->assertFalse($content->getVersionInfo()->isArchived());
}
/**
* Test for the createContent() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $content
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends testCreateContent
*/
public function testCreateContentSetsExpectedContentType($content)
{
$contentType = $content->getContentType();
$this->assertEquals(
[
$contentType->id,
// Won't match as it's set to true in createContentDraftVersion1()
//$contentType->defaultAlwaysAvailable,
//$contentType->defaultSortField,
//$contentType->defaultSortOrder,
],
[
$content->contentInfo->contentTypeId,
//$content->contentInfo->alwaysAvailable,
//$location->sortField,
//$location->sortOrder,
]
);
}
/**
* Test for the createContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
*/
public function testCreateContentThrowsInvalidArgumentException()
{
if ($this->isVersion4()) {
$this->markTestSkipped('This test requires eZ Publish 5');
}
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier(self::FORUM_IDENTIFIER);
$contentCreate1 = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate1->setField('name', 'An awesome Sidelfingen forum');
$contentCreate1->remoteId = 'abcdef0123456789abcdef0123456789';
$contentCreate1->alwaysAvailable = true;
$draft = $this->contentService->createContent($contentCreate1);
$this->contentService->publishVersion($draft->versionInfo);
$contentCreate2 = $this->contentService->newContentCreateStruct($contentType, self::ENG_GB);
$contentCreate2->setField('name', 'An awesome Bielefeld forum');
$contentCreate2->remoteId = 'abcdef0123456789abcdef0123456789';
$contentCreate2->alwaysAvailable = false;
$this->expectException(APIInvalidArgumentException::class);
$this->contentService->createContent($contentCreate2);
}
/**
* Test for the createContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
*/
public function testCreateContentThrowsInvalidArgumentExceptionOnFieldTypeNotAccept()
{
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier(self::FORUM_IDENTIFIER);
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
// The name field does only accept strings and null as its values
$contentCreate->setField('name', new \stdClass());
$this->expectException(APIInvalidArgumentException::class);
$this->contentService->createContent($contentCreate);
}
/**
* Test for the createContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
*/
public function testCreateContentThrowsContentFieldValidationException()
{
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier('folder');
$contentCreate1 = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate1->setField('name', 'An awesome Sidelfingen folder');
// Violates string length constraint
$contentCreate1->setField('short_name', str_repeat('a', 200));
$this->expectException(ContentFieldValidationException::class);
// Throws ContentFieldValidationException, since short_name does not pass validation of the string length validator
$this->contentService->createContent($contentCreate1);
}
/**
* Test for the createContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
*/
public function testCreateContentRequiredFieldMissing()
{
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier(self::FORUM_IDENTIFIER);
$contentCreate1 = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
// Required field "name" is not set
$this->expectException(ContentFieldValidationException::class);
// Throws a ContentFieldValidationException, since a required field is missing
$this->contentService->createContent($contentCreate1);
}
/**
* Test for the createContent() method.
*
* NOTE: We have bidirectional dependencies between the ContentService and
* the LocationService, so that we cannot use PHPUnit's test dependencies
* here.
*
* @see \eZ\Publish\API\Repository\ContentService::createContent($contentCreateStruct, $locationCreateStructs)
* @depend(s) eZ\Publish\API\Repository\Tests\LocationServiceTest::testCreateLocation
* @depend(s) eZ\Publish\API\Repository\Tests\LocationServiceTest::testLoadLocationByRemoteId
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
* @group user
*/
public function testCreateContentWithLocationCreateParameterDoesNotCreateLocationImmediately()
{
$this->createContentDraftVersion1();
$this->expectException(NotFoundException::class);
// The location will not have been created, yet, so this throws an exception
$this->locationService->loadLocationByRemoteId('0123456789abcdef0123456789abcdef');
}
/**
* Test for the createContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContent($contentCreateStruct, $locationCreateStructs)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentWithLocationCreateParameterDoesNotCreateLocationImmediately
*/
public function testCreateContentThrowsInvalidArgumentExceptionWithLocationCreateParameter()
{
$parentLocationId = $this->generateId('location', 56);
// $parentLocationId is a valid location ID
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier(self::FORUM_IDENTIFIER);
// Configure new locations
$locationCreate1 = $this->locationService->newLocationCreateStruct($parentLocationId);
$locationCreate1->priority = 23;
$locationCreate1->hidden = true;
$locationCreate1->remoteId = '0123456789abcdef0123456789aaaaaa';
$locationCreate1->sortField = Location::SORT_FIELD_NODE_ID;
$locationCreate1->sortOrder = Location::SORT_ORDER_DESC;
$locationCreate2 = $this->locationService->newLocationCreateStruct($parentLocationId);
$locationCreate2->priority = 42;
$locationCreate2->hidden = true;
$locationCreate2->remoteId = '0123456789abcdef0123456789bbbbbb';
$locationCreate2->sortField = Location::SORT_FIELD_NODE_ID;
$locationCreate2->sortOrder = Location::SORT_ORDER_DESC;
// Configure new content object
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate->setField('name', 'A awesome Sindelfingen forum');
$contentCreate->remoteId = 'abcdef0123456789abcdef0123456789';
$contentCreate->alwaysAvailable = true;
// Create new content object under the specified location
$draft = $this->contentService->createContent(
$contentCreate,
[$locationCreate1]
);
$this->contentService->publishVersion($draft->versionInfo);
$this->expectException(APIInvalidArgumentException::class);
// Content remoteId already exists,
$this->contentService->createContent(
$contentCreate,
[$locationCreate2]
);
}
/**
* Test for the loadContentInfo() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentInfo()
* @group user
*/
public function testLoadContentInfo()
{
$mediaFolderId = $this->generateId('object', self::MEDIA_CONTENT_ID);
// Load the ContentInfo for "Media" folder
$contentInfo = $this->contentService->loadContentInfo($mediaFolderId);
$this->assertInstanceOf(ContentInfo::class, $contentInfo);
return $contentInfo;
}
/**
* Test for the returned value of the loadContentInfo() method.
*
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
* @covers \eZ\Publish\API\Repository\ContentService::loadContentInfo
*
* @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
*/
public function testLoadContentInfoSetsExpectedContentInfo(ContentInfo $contentInfo)
{
$this->assertPropertiesCorrectUnsorted(
$this->getExpectedMediaContentInfoProperties(),
$contentInfo
);
}
/**
* Test for the loadContentInfo() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentInfo()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
*/
public function testLoadContentInfoThrowsNotFoundException()
{
$nonExistentContentId = $this->generateId('object', self::DB_INT_MAX);
$this->expectException(NotFoundException::class);
$this->contentService->loadContentInfo($nonExistentContentId);
}
/**
* Test for the loadContentInfoList() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentInfoList()
*/
public function testLoadContentInfoList()
{
$mediaFolderId = $this->generateId('object', self::MEDIA_CONTENT_ID);
$list = $this->contentService->loadContentInfoList([$mediaFolderId]);
$this->assertCount(1, $list);
$this->assertEquals([$mediaFolderId], array_keys($list), 'Array key was not content id');
$this->assertInstanceOf(
ContentInfo::class,
$list[$mediaFolderId]
);
}
/**
* Test for the loadContentInfoList() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentInfoList()
* @depends testLoadContentInfoList
*/
public function testLoadContentInfoListSkipsNotFoundItems()
{
$nonExistentContentId = $this->generateId('object', self::DB_INT_MAX);
$list = $this->contentService->loadContentInfoList([$nonExistentContentId]);
$this->assertCount(0, $list);
}
/**
* Test for the loadContentInfoByRemoteId() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentInfoByRemoteId()
*/
public function testLoadContentInfoByRemoteId()
{
// Load the ContentInfo for "Media" folder
$contentInfo = $this->contentService->loadContentInfoByRemoteId('faaeb9be3bd98ed09f606fc16d144eca');
$this->assertInstanceOf(ContentInfo::class, $contentInfo);
return $contentInfo;
}
/**
* Test for the returned value of the loadContentInfoByRemoteId() method.
*
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfoByRemoteId
* @covers \eZ\Publish\API\Repository\ContentService::loadContentInfoByRemoteId
*
* @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
*/
public function testLoadContentInfoByRemoteIdSetsExpectedContentInfo(ContentInfo $contentInfo)
{
$this->assertPropertiesCorrectUnsorted(
[
'id' => 10,
'contentTypeId' => 4,
'name' => 'Anonymous User',
'sectionId' => 2,
'currentVersionNo' => 2,
'published' => true,
'ownerId' => 14,
'modificationDate' => $this->createDateTime(1072180405),
'publishedDate' => $this->createDateTime(1033920665),
'alwaysAvailable' => 1,
'remoteId' => 'faaeb9be3bd98ed09f606fc16d144eca',
'mainLanguageCode' => self::ENG_US,
'mainLocationId' => 45,
],
$contentInfo
);
}
/**
* Test for the loadContentInfoByRemoteId() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentInfoByRemoteId()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfoByRemoteId
*/
public function testLoadContentInfoByRemoteIdThrowsNotFoundException()
{
$this->expectException(NotFoundException::class);
$this->contentService->loadContentInfoByRemoteId('abcdefghijklmnopqrstuvwxyz0123456789');
}
/**
* Test for the loadVersionInfo() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadVersionInfo()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
* @group user
*/
public function testLoadVersionInfo()
{
$mediaFolderId = $this->generateId('object', self::MEDIA_CONTENT_ID);
// $mediaFolderId contains the ID of the "Media" folder
// Load the ContentInfo for "Media" folder
$contentInfo = $this->contentService->loadContentInfo($mediaFolderId);
// Now load the current version info of the "Media" folder
$versionInfo = $this->contentService->loadVersionInfo($contentInfo);
$this->assertInstanceOf(
VersionInfo::class,
$versionInfo
);
}
/**
* Test for the loadVersionInfoById() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadVersionInfoById()
*/
public function testLoadVersionInfoById()
{
$mediaFolderId = $this->generateId('object', self::MEDIA_CONTENT_ID);
// $mediaFolderId contains the ID of the "Media" folder
// Load the VersionInfo for "Media" folder
$versionInfo = $this->contentService->loadVersionInfoById($mediaFolderId);
$this->assertInstanceOf(
VersionInfo::class,
$versionInfo
);
return $versionInfo;
}
/**
* Test for the returned value of the loadVersionInfoById() method.
*
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadVersionInfoById
* @covers \eZ\Publish\Core\Repository\ContentService::loadVersionInfoById
*
* @param \eZ\Publish\API\Repository\Values\Content\VersionInfo $versionInfo
*/
public function testLoadVersionInfoByIdSetsExpectedVersionInfo(VersionInfo $versionInfo)
{
$this->assertPropertiesCorrect(
[
'names' => [
self::ENG_US => 'Media',
],
'contentInfo' => new ContentInfo($this->getExpectedMediaContentInfoProperties()),
'id' => 472,
'versionNo' => 1,
'modificationDate' => $this->createDateTime(1060695457),
'creatorId' => 14,
'creationDate' => $this->createDateTime(1060695450),
'status' => VersionInfo::STATUS_PUBLISHED,
'initialLanguageCode' => self::ENG_US,
'languageCodes' => [
self::ENG_US,
],
],
$versionInfo
);
$this->assertTrue($versionInfo->isPublished());
$this->assertFalse($versionInfo->isDraft());
$this->assertFalse($versionInfo->isArchived());
}
/**
* Test for the loadVersionInfoById() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadVersionInfoById()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadVersionInfoById
*/
public function testLoadVersionInfoByIdThrowsNotFoundException()
{
$nonExistentContentId = $this->generateId('object', self::DB_INT_MAX);
$this->expectException(NotFoundException::class);
$this->contentService->loadVersionInfoById($nonExistentContentId);
}
/**
* Test for the loadContentByContentInfo() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentByContentInfo()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
*/
public function testLoadContentByContentInfo()
{
$mediaFolderId = $this->generateId('object', self::MEDIA_CONTENT_ID);
// $mediaFolderId contains the ID of the "Media" folder
// Load the ContentInfo for "Media" folder
$contentInfo = $this->contentService->loadContentInfo($mediaFolderId);
// Now load the current content version for the info instance
$content = $this->contentService->loadContentByContentInfo($contentInfo);
$this->assertInstanceOf(
Content::class,
$content
);
}
/**
* Test for the loadContentByVersionInfo() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentByVersionInfo()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadVersionInfo
*/
public function testLoadContentByVersionInfo()
{
$mediaFolderId = $this->generateId('object', self::MEDIA_CONTENT_ID);
// $mediaFolderId contains the ID of the "Media" folder
// Load the ContentInfo for "Media" folder
$contentInfo = $this->contentService->loadContentInfo($mediaFolderId);
// Load the current VersionInfo
$versionInfo = $this->contentService->loadVersionInfo($contentInfo);
// Now load the current content version for the info instance
$content = $this->contentService->loadContentByVersionInfo($versionInfo);
$this->assertInstanceOf(
Content::class,
$content
);
}
/**
* Test for the loadContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContent()
* @group user
* @group field-type
*/
public function testLoadContent()
{
$mediaFolderId = $this->generateId('object', self::MEDIA_CONTENT_ID);
// $mediaFolderId contains the ID of the "Media" folder
// Load the Content for "Media" folder, any language and current version
$content = $this->contentService->loadContent($mediaFolderId);
$this->assertInstanceOf(
Content::class,
$content
);
}
/**
* Test for the loadContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
*/
public function testLoadContentThrowsNotFoundException()
{
$nonExistentContentId = $this->generateId('object', self::DB_INT_MAX);
$this->expectException(NotFoundException::class);
$this->contentService->loadContent($nonExistentContentId);
}
/**
* Data provider for testLoadContentByRemoteId().
*
* @return array
*/
public function contentRemoteIdVersionLanguageProvider()
{
return [
['f5c88a2209584891056f987fd965b0ba', null, null],
['f5c88a2209584891056f987fd965b0ba', [self::ENG_US], null],
['f5c88a2209584891056f987fd965b0ba', null, 1],
['f5c88a2209584891056f987fd965b0ba', [self::ENG_US], 1],
[self::MEDIA_REMOTE_ID, null, null],
[self::MEDIA_REMOTE_ID, [self::ENG_US], null],
[self::MEDIA_REMOTE_ID, null, 1],
[self::MEDIA_REMOTE_ID, [self::ENG_US], 1],
];
}
/**
* Test for the loadContentByRemoteId() method.
*
* @covers \eZ\Publish\API\Repository\ContentService::loadContentByRemoteId
* @dataProvider contentRemoteIdVersionLanguageProvider
*
* @param string $remoteId
* @param array|null $languages
* @param int $versionNo
*/
public function testLoadContentByRemoteId($remoteId, $languages, $versionNo)
{
$content = $this->contentService->loadContentByRemoteId($remoteId, $languages, $versionNo);
$this->assertInstanceOf(
Content::class,
$content
);
$this->assertEquals($remoteId, $content->contentInfo->remoteId);
if ($languages !== null) {
$this->assertEquals($languages, $content->getVersionInfo()->languageCodes);
}
$this->assertEquals($versionNo ?: 1, $content->getVersionInfo()->versionNo);
}
/**
* Test for the loadContentByRemoteId() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentByRemoteId()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentByRemoteId
*/
public function testLoadContentByRemoteIdThrowsNotFoundException()
{
$this->expectException(NotFoundException::class);
// This call will fail with a "NotFoundException", because no content object exists for the given remoteId
$this->contentService->loadContentByRemoteId('a1b1c1d1e1f1a2b2c2d2e2f2a3b3c3d3');
}
/**
* Test for the publishVersion() method.
*
* @return \eZ\Publish\API\Repository\Values\Content\Content
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadVersionInfo
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentWithLocationCreateParameterDoesNotCreateLocationImmediately
* @group user
* @group field-type
*/
public function testPublishVersion()
{
$time = time();
$content = $this->createContentVersion1();
$this->assertInstanceOf(Content::class, $content);
$this->assertTrue($content->contentInfo->published);
$this->assertEquals(VersionInfo::STATUS_PUBLISHED, $content->versionInfo->status);
$this->assertGreaterThanOrEqual($time, $content->contentInfo->publishedDate->getTimestamp());
$this->assertGreaterThanOrEqual($time, $content->contentInfo->modificationDate->getTimestamp());
$this->assertTrue($content->versionInfo->isPublished());
$this->assertFalse($content->versionInfo->isDraft());
$this->assertFalse($content->versionInfo->isArchived());
return $content;
}
/**
* Test for the publishVersion() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $content
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
*/
public function testPublishVersionSetsExpectedContentInfo($content)
{
$userReference = $this->getRepository()->getPermissionResolver()->getCurrentUserReference();
$this->assertEquals(
[
$content->id,
true,
1,
'abcdef0123456789abcdef0123456789',
self::ENG_US,
$userReference->getUserId(),
true,
],
[
$content->contentInfo->id,
$content->contentInfo->alwaysAvailable,
$content->contentInfo->currentVersionNo,
$content->contentInfo->remoteId,
$content->contentInfo->mainLanguageCode,
$content->contentInfo->ownerId,
$content->contentInfo->published,
]
);
$this->assertNotNull($content->contentInfo->mainLocationId);
$date = new \DateTime('1984/01/01');
$this->assertGreaterThan(
$date->getTimestamp(),
$content->contentInfo->publishedDate->getTimestamp()
);
}
/**
* Test for the publishVersion() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $content
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
*/
public function testPublishVersionSetsExpectedVersionInfo($content)
{
$currentUserReference = $this->getRepository()->getPermissionResolver()->getCurrentUserReference();
$this->assertEquals(
[
$currentUserReference->getUserId(),
self::ENG_US,
VersionInfo::STATUS_PUBLISHED,
1,
],
[
$content->getVersionInfo()->creatorId,
$content->getVersionInfo()->initialLanguageCode,
$content->getVersionInfo()->status,
$content->getVersionInfo()->versionNo,
]
);
$date = new \DateTime('1984/01/01');
$this->assertGreaterThan(
$date->getTimestamp(),
$content->getVersionInfo()->modificationDate->getTimestamp()
);
$this->assertNotNull($content->getVersionInfo()->modificationDate);
$this->assertTrue($content->getVersionInfo()->isPublished());
$this->assertFalse($content->getVersionInfo()->isDraft());
$this->assertFalse($content->getVersionInfo()->isArchived());
}
/**
* Test for the publishVersion() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $content
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends testPublishVersion
*/
public function testPublishVersionSetsExpectedContentType($content)
{
$contentType = $content->getContentType();
$this->assertEquals(
[
$contentType->id,
// won't be a match as it's set to true in createContentDraftVersion1()
//$contentType->defaultAlwaysAvailable,
//$contentType->defaultSortField,
//$contentType->defaultSortOrder,
],
[
$content->contentInfo->contentTypeId,
//$content->contentInfo->alwaysAvailable,
//$location->sortField,
//$location->sortOrder,
]
);
}
/**
* Test for the publishVersion() method.
*
* @return \eZ\Publish\API\Repository\Values\Content\Content
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentWithLocationCreateParameterDoesNotCreateLocationImmediately
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
*/
public function testPublishVersionCreatesLocationsDefinedOnCreate()
{
$content = $this->createContentVersion1();
$location = $this->locationService->loadLocationByRemoteId(
'0123456789abcdef0123456789abcdef'
);
$this->assertEquals(
$location->getContentInfo(),
$content->getVersionInfo()->getContentInfo()
);
return [$content, $location];
}
/**
* Test for the publishVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionCreatesLocationsDefinedOnCreate
*/
public function testCreateContentWithLocationCreateParameterCreatesExpectedLocation(array $testData)
{
/** @var \eZ\Publish\API\Repository\Values\Content\Content $content */
/** @var \eZ\Publish\API\Repository\Values\Content\Location $location */
list($content, $location) = $testData;
$parentLocationId = $this->generateId('location', 56);
$parentLocation = $this->getRepository()->getLocationService()->loadLocation($parentLocationId);
$mainLocationId = $content->getVersionInfo()->getContentInfo()->mainLocationId;
$this->assertPropertiesCorrect(
[
'id' => $mainLocationId,
'priority' => 23,
'hidden' => true,
'invisible' => true,
'remoteId' => '0123456789abcdef0123456789abcdef',
'parentLocationId' => $parentLocationId,
'pathString' => $parentLocation->pathString . $mainLocationId . '/',
'depth' => $parentLocation->depth + 1,
'sortField' => Location::SORT_FIELD_NODE_ID,
'sortOrder' => Location::SORT_ORDER_DESC,
],
$location
);
}
/**
* Test for the publishVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
*/
public function testPublishVersionThrowsBadStateException()
{
$draft = $this->createContentDraftVersion1();
// Publish the content draft
$this->contentService->publishVersion($draft->getVersionInfo());
$this->expectException(BadStateException::class);
// This call will fail with a "BadStateException", because the version is already published.
$this->contentService->publishVersion($draft->getVersionInfo());
}
/**
* Test that publishVersion() does not affect publishedDate (assuming previous version exists).
*
* @covers \eZ\Publish\API\Repository\ContentService::publishVersion
*/
public function testPublishVersionDoesNotChangePublishedDate()
{
$publishedContent = $this->createContentVersion1();
// force timestamps to differ
sleep(1);
$contentDraft = $this->contentService->createContentDraft($publishedContent->contentInfo);
$contentUpdateStruct = $this->contentService->newContentUpdateStruct();
$contentUpdateStruct->setField('name', 'New name');
$contentDraft = $this->contentService->updateContent($contentDraft->versionInfo, $contentUpdateStruct);
$republishedContent = $this->contentService->publishVersion($contentDraft->versionInfo);
$this->assertEquals(
$publishedContent->contentInfo->publishedDate->getTimestamp(),
$republishedContent->contentInfo->publishedDate->getTimestamp()
);
$this->assertGreaterThan(
$publishedContent->contentInfo->modificationDate->getTimestamp(),
$republishedContent->contentInfo->modificationDate->getTimestamp()
);
}
/**
* Test for the createContentDraft() method.
*
* @return \eZ\Publish\API\Repository\Values\Content\Content
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
* @group user
*/
public function testCreateContentDraft()
{
$content = $this->createContentVersion1();
// Now we create a new draft from the published content
$draftedContent = $this->contentService->createContentDraft($content->contentInfo);
$this->assertInstanceOf(
Content::class,
$draftedContent
);
return $draftedContent;
}
/**
* Test for the createContentDraft() method.
*
* Test that editor has access to edit own draft.
* Note: Editors have access to version_read, which is needed to load content drafts.
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
* @group user
*/
public function testCreateContentDraftAndLoadAccess()
{
$user = $this->createUserVersion1();
// Set new editor as user
$this->permissionResolver->setCurrentUserReference($user);
// Create draft
$draft = $this->createContentDraftVersion1(2, 'folder');
// Try to load the draft
$loadedDraft = $this->contentService->loadContent($draft->id);
$this->assertEquals($draft->id, $loadedDraft->id);
}
/**
* Test for the createContentDraft() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $draft
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
*/
public function testCreateContentDraftSetsExpectedProperties($draft)
{
$this->assertEquals(
[
'fieldCount' => 1,
'relationCount' => 0,
],
[
'fieldCount' => count($draft->getFields()),
'relationCount' => count($this->getRepository()->getContentService()->loadRelations($draft->getVersionInfo())),
]
);
}
/**
* Test for the createContentDraft() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $draft
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
*/
public function testCreateContentDraftSetsContentInfo($draft)
{
$contentInfo = $draft->contentInfo;
$currentUserReference = $this->getRepository()->getPermissionResolver()->getCurrentUserReference();
$this->assertEquals(
[
$draft->id,
true,
1,
self::ENG_US,
$currentUserReference->getUserId(),
'abcdef0123456789abcdef0123456789',
1,
],
[
$contentInfo->id,
$contentInfo->alwaysAvailable,
$contentInfo->currentVersionNo,
$contentInfo->mainLanguageCode,
$contentInfo->ownerId,
$contentInfo->remoteId,
$contentInfo->sectionId,
]
);
}
/**
* Test for the createContentDraft() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $draft
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
*/
public function testCreateContentDraftSetsVersionInfo($draft)
{
$versionInfo = $draft->getVersionInfo();
$currentUserReference = $this->getRepository()->getPermissionResolver()->getCurrentUserReference();
$this->assertEquals(
[
'creatorId' => $currentUserReference->getUserId(),
'initialLanguageCode' => self::ENG_US,
'languageCodes' => [0 => self::ENG_US],
'status' => VersionInfo::STATUS_DRAFT,
'versionNo' => 2,
],
[
'creatorId' => $versionInfo->creatorId,
'initialLanguageCode' => $versionInfo->initialLanguageCode,
'languageCodes' => $versionInfo->languageCodes,
'status' => $versionInfo->status,
'versionNo' => $versionInfo->versionNo,
]
);
$this->assertTrue($versionInfo->isDraft());
$this->assertFalse($versionInfo->isPublished());
$this->assertFalse($versionInfo->isArchived());
}
/**
* Test for the createContentDraft() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $draft
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadVersionInfo
*/
public function testCreateContentDraftLoadVersionInfoStillLoadsPublishedVersion($draft)
{
$content = $this->createContentVersion1();
// Now we create a new draft from the published content
$this->contentService->createContentDraft($content->contentInfo);
// This call will still load the published version
$versionInfoPublished = $this->contentService->loadVersionInfo($content->contentInfo);
$this->assertEquals(1, $versionInfoPublished->versionNo);
}
/**
* Test for the createContentDraft() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
*/
public function testCreateContentDraftLoadContentStillLoadsPublishedVersion()
{
$content = $this->createContentVersion1();
// Now we create a new draft from the published content
$this->contentService->createContentDraft($content->contentInfo);
// This call will still load the published content version
$contentPublished = $this->contentService->loadContent($content->id);
$this->assertEquals(1, $contentPublished->getVersionInfo()->versionNo);
}
/**
* Test for the createContentDraft() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentByRemoteId
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
*/
public function testCreateContentDraftLoadContentByRemoteIdStillLoadsPublishedVersion()
{
$content = $this->createContentVersion1();
// Now we create a new draft from the published content
$this->contentService->createContentDraft($content->contentInfo);
// This call will still load the published content version
$contentPublished = $this->contentService->loadContentByRemoteId('abcdef0123456789abcdef0123456789');
$this->assertEquals(1, $contentPublished->getVersionInfo()->versionNo);
}
/**
* Test for the createContentDraft() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentByContentInfo
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
*/
public function testCreateContentDraftLoadContentByContentInfoStillLoadsPublishedVersion()
{
$content = $this->createContentVersion1();
// Now we create a new draft from the published content
$this->contentService->createContentDraft($content->contentInfo);
// This call will still load the published content version
$contentPublished = $this->contentService->loadContentByContentInfo($content->contentInfo);
$this->assertEquals(1, $contentPublished->getVersionInfo()->versionNo);
}
/**
* Test for the newContentUpdateStruct() method.
*
* @covers \eZ\Publish\API\Repository\ContentService::newContentUpdateStruct
* @group user
*/
public function testNewContentUpdateStruct()
{
$updateStruct = $this->contentService->newContentUpdateStruct();
$this->assertInstanceOf(
ContentUpdateStruct::class,
$updateStruct
);
$this->assertPropertiesCorrect(
[
'initialLanguageCode' => null,
'fields' => [],
],
$updateStruct
);
}
/**
* Test for the updateContent() method.
*
* @return \eZ\Publish\API\Repository\Values\Content\Content
*
* @see \eZ\Publish\API\Repository\ContentService::updateContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testNewContentUpdateStruct
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
* @group user
* @group field-type
*/
public function testUpdateContent()
{
$draftVersion2 = $this->createUpdatedDraftVersion2();
$this->assertInstanceOf(
Content::class,
$draftVersion2
);
$this->assertEquals(
$this->generateId('user', 10),
$draftVersion2->versionInfo->creatorId,
'creatorId is not properly set on new Version'
);
return $draftVersion2;
}
/**
* Test for the updateContent_WithDifferentUser() method.
*
* @return \eZ\Publish\API\Repository\Values\Content\Content
*
* @see \eZ\Publish\API\Repository\ContentService::updateContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testNewContentUpdateStruct
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
* @group user
* @group field-type
*/
public function testUpdateContentWithDifferentUser()
{
$arrayWithDraftVersion2 = $this->createUpdatedDraftVersion2NotAdmin();
$this->assertInstanceOf(
Content::class,
$arrayWithDraftVersion2[0]
);
$this->assertEquals(
$this->generateId('user', $arrayWithDraftVersion2[1]),
$arrayWithDraftVersion2[0]->versionInfo->creatorId,
'creatorId is not properly set on new Version'
);
return $arrayWithDraftVersion2[0];
}
/**
* Test for the updateContent() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $content
*
* @see \eZ\Publish\API\Repository\ContentService::updateContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContent
*/
public function testUpdateContentSetsExpectedFields($content)
{
$actual = $this->normalizeFields($content->getFields());
$expected = [
new Field(
[
'id' => 0,
'value' => true,
'languageCode' => self::ENG_GB,
'fieldDefIdentifier' => 'name',
'fieldTypeIdentifier' => 'ezstring',
]
),
new Field(
[
'id' => 0,
'value' => true,
'languageCode' => self::ENG_US,
'fieldDefIdentifier' => 'name',
'fieldTypeIdentifier' => 'ezstring',
]
),
];
$this->assertEquals($expected, $actual);
}
/**
* Test for the updateContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::updateContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContent
*/
public function testUpdateContentThrowsBadStateException()
{
$content = $this->createContentVersion1();
// Now create an update struct and modify some fields
$contentUpdateStruct = $this->contentService->newContentUpdateStruct();
$contentUpdateStruct->setField('title', 'An awesome² story about ezp.');
$contentUpdateStruct->setField('title', 'An awesome²³ story about ezp.', self::ENG_GB);
$contentUpdateStruct->initialLanguageCode = self::ENG_US;
$this->expectException(BadStateException::class);
// This call will fail with a "BadStateException", because $publishedContent is not a draft.
$this->contentService->updateContent(
$content->getVersionInfo(),
$contentUpdateStruct
);
}
/**
* Test for the updateContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::updateContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContent
*/
public function testUpdateContentThrowsInvalidArgumentExceptionWhenFieldTypeDoesNotAccept()
{
$draft = $this->createContentDraftVersion1();
// Now create an update struct and modify some fields
$contentUpdateStruct = $this->contentService->newContentUpdateStruct();
// The name field does not accept a stdClass object as its input
$contentUpdateStruct->setField('name', new \stdClass(), self::ENG_US);
$this->expectException(APIInvalidArgumentException::class);
// is not accepted
$this->contentService->updateContent(
$draft->getVersionInfo(),
$contentUpdateStruct
);
}
/**
* Test for the updateContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::updateContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContent
*/
public function testUpdateContentWhenMandatoryFieldIsEmpty()
{
$draft = $this->createContentDraftVersion1();
// Now create an update struct and set a mandatory field to null
$contentUpdateStruct = $this->contentService->newContentUpdateStruct();
$contentUpdateStruct->setField('name', null);
// Don't set this, then the above call without languageCode will fail
$contentUpdateStruct->initialLanguageCode = self::ENG_US;
$this->expectException(ContentFieldValidationException::class);
// This call will fail with a "ContentFieldValidationException", because the mandatory "name" field is empty.
$this->contentService->updateContent(
$draft->getVersionInfo(),
$contentUpdateStruct
);
}
/**
* Test for the updateContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::updateContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContent
*/
public function testUpdateContentThrowsContentFieldValidationException()
{
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier('folder');
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate->setField('name', 'An awesome Sidelfingen folder');
$draft = $this->contentService->createContent($contentCreate);
$contentUpdate = $this->contentService->newContentUpdateStruct();
// Violates string length constraint
$contentUpdate->setField('short_name', str_repeat('a', 200), self::ENG_US);
$this->expectException(ContentFieldValidationException::class);
// Throws ContentFieldValidationException because the string length validation of the field "short_name" fails
$this->contentService->updateContent($draft->getVersionInfo(), $contentUpdate);
}
/**
* Test for the updateContent() method.
*
* @covers \eZ\Publish\API\Repository\ContentService::updateContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContent
*/
public function testUpdateContentValidatorIgnoresRequiredFieldsOfNotUpdatedLanguages()
{
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier('folder');
// Create multilangual content
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate->setField('name', 'An awesome Sidelfingen folder', self::ENG_US);
$contentCreate->setField('name', 'An awesome Sidelfingen folder', self::ENG_GB);
$contentDraft = $this->contentService->createContent($contentCreate);
// 2. Update content type definition
$contentTypeDraft = $contentTypeService->createContentTypeDraft($contentType);
$fieldDefinition = $contentType->getFieldDefinition('short_name');
$fieldDefinitionUpdate = $contentTypeService->newFieldDefinitionUpdateStruct();
$fieldDefinitionUpdate->identifier = 'short_name';
$fieldDefinitionUpdate->isRequired = true;
$contentTypeService->updateFieldDefinition(
$contentTypeDraft,
$fieldDefinition,
$fieldDefinitionUpdate
);
$contentTypeService->publishContentTypeDraft($contentTypeDraft);
// 3. Update only eng-US translation
$contentUpdate = $this->contentService->newContentUpdateStruct();
$contentUpdate->setField('name', 'An awesome Sidelfingen folder (updated)', self::ENG_US);
$contentUpdate->setField('short_name', 'Lorem ipsum dolor');
$this->contentService->updateContent($contentDraft->getVersionInfo(), $contentUpdate);
}
/**
* Test for the updateContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::updateContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContent
*/
public function testUpdateContentWithNotUpdatingMandatoryField()
{
$draft = $this->createContentDraftVersion1();
// Now create an update struct which does not overwrite mandatory
// fields
$contentUpdateStruct = $this->contentService->newContentUpdateStruct();
// Don't set this, then the above call without languageCode will fail
$contentUpdateStruct->initialLanguageCode = self::ENG_US;
// This will only update the "description" field in the "eng-US" language
$updatedDraft = $this->contentService->updateContent(
$draft->getVersionInfo(),
$contentUpdateStruct
);
foreach ($updatedDraft->getFields() as $field) {
if ($field->languageCode === self::ENG_US && $field->fieldDefIdentifier === 'name' && $field->value !== null) {
// Found field
return;
}
}
$this->fail(
'Field with identifier "name" in language "eng-US" could not be found or has empty value.'
);
}
/**
* Test for the createContentDraft() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft($contentInfo, $versionInfo)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContent
*/
public function testCreateContentDraftWithSecondParameter()
{
$contentVersion2 = $this->createContentVersion2();
// Now we create a new draft from the initial version
$draftedContentReloaded = $this->contentService->createContentDraft(
$contentVersion2->contentInfo,
$contentVersion2->getVersionInfo()
);
$this->assertEquals(3, $draftedContentReloaded->getVersionInfo()->versionNo);
}
/**
* Test for the createContentDraft() method with third parameter.
*
* @covers \eZ\Publish\Core\Repository\ContentService::createContentDraft
*/
public function testCreateContentDraftWithThirdParameter()
{
$content = $this->contentService->loadContent(4);
$user = $this->createUserVersion1();
$draftContent = $this->contentService->createContentDraft(
$content->contentInfo,
$content->getVersionInfo(),
$user
);
$this->assertInstanceOf(
Content::class,
$draftContent
);
}
/**
* Test for the publishVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContent
*/
public function testPublishVersionFromContentDraft()
{
$contentVersion2 = $this->createContentVersion2();
$versionInfo = $this->contentService->loadVersionInfo($contentVersion2->contentInfo);
$this->assertEquals(
[
'status' => VersionInfo::STATUS_PUBLISHED,
'versionNo' => 2,
],
[
'status' => $versionInfo->status,
'versionNo' => $versionInfo->versionNo,
]
);
$this->assertTrue($versionInfo->isPublished());
$this->assertFalse($versionInfo->isDraft());
$this->assertFalse($versionInfo->isArchived());
}
/**
* Test for the publishVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
*/
public function testPublishVersionFromContentDraftArchivesOldVersion()
{
$contentVersion2 = $this->createContentVersion2();
$versionInfo = $this->contentService->loadVersionInfo($contentVersion2->contentInfo, 1);
$this->assertEquals(
[
'status' => VersionInfo::STATUS_ARCHIVED,
'versionNo' => 1,
],
[
'status' => $versionInfo->status,
'versionNo' => $versionInfo->versionNo,
]
);
$this->assertTrue($versionInfo->isArchived());
$this->assertFalse($versionInfo->isDraft());
$this->assertFalse($versionInfo->isPublished());
}
/**
* Test for the publishVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
*/
public function testPublishVersionFromContentDraftUpdatesContentInfoCurrentVersion()
{
$contentVersion2 = $this->createContentVersion2();
$this->assertEquals(2, $contentVersion2->contentInfo->currentVersionNo);
}
/**
* Test for the publishVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
*/
public function testPublishVersionFromOldContentDraftArchivesNewerVersionNo()
{
$content = $this->createContentVersion1();
// Create a new draft with versionNo = 2
$draftedContentVersion2 = $this->contentService->createContentDraft($content->contentInfo);
// Create another new draft with versionNo = 3
$draftedContentVersion3 = $this->contentService->createContentDraft($content->contentInfo);
// Publish draft with versionNo = 3
$this->contentService->publishVersion($draftedContentVersion3->getVersionInfo());
// Publish the first draft with versionNo = 2
// currentVersionNo is now 2, versionNo 3 will be archived
$publishedDraft = $this->contentService->publishVersion($draftedContentVersion2->getVersionInfo());
$this->assertEquals(2, $publishedDraft->contentInfo->currentVersionNo);
}
/**
* Test for the publishVersion() method, and that it creates limited archives.
*
* @todo Adapt this when per content type archive limited is added on repository Content Type model.
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
*/
public function testPublishVersionNotCreatingUnlimitedArchives()
{
$content = $this->createContentVersion1();
// load first to make sure list gets updated also (cache)
$versionInfoList = $this->contentService->loadVersions($content->contentInfo);
$this->assertCount(1, $versionInfoList);
$this->assertEquals(1, $versionInfoList[0]->versionNo);
// Create a new draft with versionNo = 2
$draftedContentVersion = $this->contentService->createContentDraft($content->contentInfo);
$this->contentService->publishVersion($draftedContentVersion->getVersionInfo());
// Create a new draft with versionNo = 3
$draftedContentVersion = $this->contentService->createContentDraft($content->contentInfo);
$this->contentService->publishVersion($draftedContentVersion->getVersionInfo());
// Create a new draft with versionNo = 4
$draftedContentVersion = $this->contentService->createContentDraft($content->contentInfo);
$this->contentService->publishVersion($draftedContentVersion->getVersionInfo());
// Create a new draft with versionNo = 5
$draftedContentVersion = $this->contentService->createContentDraft($content->contentInfo);
$this->contentService->publishVersion($draftedContentVersion->getVersionInfo());
// Create a new draft with versionNo = 6
$draftedContentVersion = $this->contentService->createContentDraft($content->contentInfo);
$this->contentService->publishVersion($draftedContentVersion->getVersionInfo());
// Create a new draft with versionNo = 7
$draftedContentVersion = $this->contentService->createContentDraft($content->contentInfo);
$this->contentService->publishVersion($draftedContentVersion->getVersionInfo());
$versionInfoList = $this->contentService->loadVersions($content->contentInfo);
$this->assertCount(6, $versionInfoList);
$this->assertEquals(2, $versionInfoList[0]->versionNo);
$this->assertEquals(7, $versionInfoList[5]->versionNo);
$this->assertEquals(
[
VersionInfo::STATUS_ARCHIVED,
VersionInfo::STATUS_ARCHIVED,
VersionInfo::STATUS_ARCHIVED,
VersionInfo::STATUS_ARCHIVED,
VersionInfo::STATUS_ARCHIVED,
VersionInfo::STATUS_PUBLISHED,
],
[
$versionInfoList[0]->status,
$versionInfoList[1]->status,
$versionInfoList[2]->status,
$versionInfoList[3]->status,
$versionInfoList[4]->status,
$versionInfoList[5]->status,
]
);
}
/**
* Test for the newContentMetadataUpdateStruct() method.
*
* @covers \eZ\Publish\API\Repository\ContentService::newContentMetadataUpdateStruct
* @group user
*/
public function testNewContentMetadataUpdateStruct()
{
// Creates a new metadata update struct
$metadataUpdate = $this->contentService->newContentMetadataUpdateStruct();
foreach ($metadataUpdate as $propertyName => $propertyValue) {
$this->assertNull($propertyValue, "Property '{$propertyName}' initial value should be null'");
}
$metadataUpdate->remoteId = 'aaaabbbbccccddddeeeeffff11112222';
$metadataUpdate->mainLanguageCode = self::ENG_GB;
$metadataUpdate->alwaysAvailable = false;
$this->assertInstanceOf(
ContentMetadataUpdateStruct::class,
$metadataUpdate
);
}
/**
* Test for the updateContentMetadata() method.
*
* @return \eZ\Publish\API\Repository\Values\Content\Content
*
* @see \eZ\Publish\API\Repository\ContentService::updateContentMetadata()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testNewContentMetadataUpdateStruct
* @group user
*/
public function testUpdateContentMetadata()
{
$content = $this->createContentVersion1();
// Creates a metadata update struct
$metadataUpdate = $this->contentService->newContentMetadataUpdateStruct();
$metadataUpdate->remoteId = 'aaaabbbbccccddddeeeeffff11112222';
$metadataUpdate->mainLanguageCode = self::ENG_GB;
$metadataUpdate->alwaysAvailable = false;
$metadataUpdate->publishedDate = $this->createDateTime(441759600); // 1984/01/01
$metadataUpdate->modificationDate = $this->createDateTime(441759600); // 1984/01/01
// Update the metadata of the published content object
$content = $this->contentService->updateContentMetadata(
$content->contentInfo,
$metadataUpdate
);
$this->assertInstanceOf(
Content::class,
$content
);
return $content;
}
/**
* Test for the updateContentMetadata() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $content
*
* @see \eZ\Publish\API\Repository\ContentService::updateContentMetadata()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContentMetadata
*/
public function testUpdateContentMetadataSetsExpectedProperties($content)
{
$contentInfo = $content->contentInfo;
$currentUserReference = $this->getRepository()->getPermissionResolver()->getCurrentUserReference();
$this->assertEquals(
[
'remoteId' => 'aaaabbbbccccddddeeeeffff11112222',
'sectionId' => $this->generateId('section', 1),
'alwaysAvailable' => false,
'currentVersionNo' => 1,
'mainLanguageCode' => self::ENG_GB,
'modificationDate' => $this->createDateTime(441759600),
'ownerId' => $currentUserReference->getUserId(),
'published' => true,
'publishedDate' => $this->createDateTime(441759600),
],
[
'remoteId' => $contentInfo->remoteId,
'sectionId' => $contentInfo->sectionId,
'alwaysAvailable' => $contentInfo->alwaysAvailable,
'currentVersionNo' => $contentInfo->currentVersionNo,
'mainLanguageCode' => $contentInfo->mainLanguageCode,
'modificationDate' => $contentInfo->modificationDate,
'ownerId' => $contentInfo->ownerId,
'published' => $contentInfo->published,
'publishedDate' => $contentInfo->publishedDate,
]
);
}
/**
* Test for the updateContentMetadata() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $content
*
* @see \eZ\Publish\API\Repository\ContentService::updateContentMetadata()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContentMetadata
*/
public function testUpdateContentMetadataNotUpdatesContentVersion($content)
{
$this->assertEquals(1, $content->getVersionInfo()->versionNo);
}
/**
* Test for the updateContentMetadata() method.
*
* @covers \eZ\Publish\API\Repository\ContentService::updateContentMetadata()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContentMetadata
*/
public function testUpdateContentMetadataThrowsInvalidArgumentExceptionOnDuplicateRemoteId()
{
$content = $this->createContentVersion1();
// Creates a metadata update struct
$metadataUpdate = $this->contentService->newContentMetadataUpdateStruct();
$metadataUpdate->remoteId = self::MEDIA_REMOTE_ID;
$this->expectException(APIInvalidArgumentException::class);
// specified remoteId is already used by the "Media" page.
$this->contentService->updateContentMetadata(
$content->contentInfo,
$metadataUpdate
);
}
/**
* Test for the updateContentMetadata() method.
*
* @covers \eZ\Publish\Core\Repository\ContentService::updateContentMetadata
*/
public function testUpdateContentMetadataThrowsInvalidArgumentExceptionOnNoMetadataPropertiesSet()
{
$contentInfo = $this->contentService->loadContentInfo(4);
$contentMetadataUpdateStruct = $this->contentService->newContentMetadataUpdateStruct();
$this->expectException(APIInvalidArgumentException::class);
$this->contentService->updateContentMetadata($contentInfo, $contentMetadataUpdateStruct);
}
/**
* Test for the deleteContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::deleteContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
*/
public function testDeleteContent()
{
$contentVersion2 = $this->createContentVersion2();
// Load the locations for this content object
$locations = $this->locationService->loadLocations($contentVersion2->contentInfo);
// This will delete the content, all versions and the associated locations
$this->contentService->deleteContent($contentVersion2->contentInfo);
$this->expectException(NotFoundException::class);
foreach ($locations as $location) {
$this->locationService->loadLocation($location->id);
}
}
/**
* Test for the deleteContent() method.
*
* Test for issue EZP-21057:
* "contentService: Unable to delete a content with an empty file attribute"
*
* @see \eZ\Publish\API\Repository\ContentService::deleteContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
*/
public function testDeleteContentWithEmptyBinaryField()
{
$contentVersion = $this->createContentVersion1EmptyBinaryField();
// Load the locations for this content object
$locations = $this->locationService->loadLocations($contentVersion->contentInfo);
// This will delete the content, all versions and the associated locations
$this->contentService->deleteContent($contentVersion->contentInfo);
$this->expectException(NotFoundException::class);
foreach ($locations as $location) {
$this->locationService->loadLocation($location->id);
}
}
public function testCountContentDraftsReturnsZeroByDefault(): void
{
$this->assertSame(0, $this->contentService->countContentDrafts());
}
public function testCountContentDrafts(): void
{
// Create 5 drafts
$this->createContentDrafts(5);
$this->assertSame(5, $this->contentService->countContentDrafts());
}
public function testCountContentDraftsForUsers(): void
{
$newUser = $this->createUserWithPolicies(
'new_user',
[
['module' => 'content', 'function' => 'create'],
['module' => 'content', 'function' => 'read'],
['module' => 'content', 'function' => 'publish'],
['module' => 'content', 'function' => 'edit'],
]
);
$previousUser = $this->permissionResolver->getCurrentUserReference();
// Set new editor as user
$this->permissionResolver->setCurrentUserReference($newUser);
// Create a content draft as newUser
$publishedContent = $this->createContentVersion1();
$this->contentService->createContentDraft($publishedContent->contentInfo);
// Reset to previous current user
$this->permissionResolver->setCurrentUserReference($previousUser);
// Now $contentDrafts for the previous current user and the new user
$newUserDrafts = $this->contentService->countContentDrafts($newUser);
$previousUserDrafts = $this->contentService->countContentDrafts();
$this->assertSame(1, $newUserDrafts);
$this->assertSame(0, $previousUserDrafts);
}
/**
* Test for the loadContentDrafts() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentDrafts()
*/
public function testLoadContentDraftsReturnsEmptyArrayByDefault()
{
$contentDrafts = $this->contentService->loadContentDrafts();
$this->assertSame([], $contentDrafts);
}
/**
* Test for the loadContentDrafts() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentDrafts()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
*/
public function testLoadContentDrafts()
{
// "Media" content object
$mediaContentInfo = $this->contentService->loadContentInfoByRemoteId(self::MEDIA_REMOTE_ID);
// "eZ Publish Demo Design ..." content object
$demoDesignContentInfo = $this->contentService->loadContentInfoByRemoteId(self::DEMO_DESIGN_REMOTE_ID);
// Create some drafts
$this->contentService->createContentDraft($mediaContentInfo);
$this->contentService->createContentDraft($demoDesignContentInfo);
// Now $contentDrafts should contain two drafted versions
$draftedVersions = $this->contentService->loadContentDrafts();
$actual = [
$draftedVersions[0]->status,
$draftedVersions[0]->getContentInfo()->remoteId,
$draftedVersions[1]->status,
$draftedVersions[1]->getContentInfo()->remoteId,
];
sort($actual, SORT_STRING);
$this->assertEquals(
[
VersionInfo::STATUS_DRAFT,
VersionInfo::STATUS_DRAFT,
self::DEMO_DESIGN_REMOTE_ID,
self::MEDIA_REMOTE_ID,
],
$actual
);
}
/**
* Test for the loadContentDrafts() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentDrafts($user)
*/
public function testLoadContentDraftsWithFirstParameter()
{
$user = $this->createUserVersion1();
// Get current user
$oldCurrentUser = $this->permissionResolver->getCurrentUserReference();
// Set new editor as user
$this->permissionResolver->setCurrentUserReference($user);
// "Media" content object
$mediaContentInfo = $this->contentService->loadContentInfoByRemoteId(self::MEDIA_REMOTE_ID);
// Create a content draft
$this->contentService->createContentDraft($mediaContentInfo);
// Reset to previous current user
$this->permissionResolver->setCurrentUserReference($oldCurrentUser);
// Now $contentDrafts for the previous current user and the new user
$newCurrentUserDrafts = $this->contentService->loadContentDrafts($user);
$oldCurrentUserDrafts = $this->contentService->loadContentDrafts();
$this->assertSame([], $oldCurrentUserDrafts);
$this->assertEquals(
[
VersionInfo::STATUS_DRAFT,
self::MEDIA_REMOTE_ID,
],
[
$newCurrentUserDrafts[0]->status,
$newCurrentUserDrafts[0]->getContentInfo()->remoteId,
]
);
$this->assertTrue($newCurrentUserDrafts[0]->isDraft());
$this->assertFalse($newCurrentUserDrafts[0]->isArchived());
$this->assertFalse($newCurrentUserDrafts[0]->isPublished());
}
/**
* Test for the loadContentDraftList() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentDrafts()
*/
public function testLoadContentDraftListWithPaginationParameters()
{
// Create some drafts
$publishedContent = $this->createContentVersion1();
$draftContentA = $this->contentService->createContentDraft($publishedContent->contentInfo);
$draftContentB = $this->contentService->createContentDraft($draftContentA->contentInfo);
$draftContentC = $this->contentService->createContentDraft($draftContentB->contentInfo);
$draftContentD = $this->contentService->createContentDraft($draftContentC->contentInfo);
$draftContentE = $this->contentService->createContentDraft($draftContentD->contentInfo);
$draftsOnPage1 = $this->contentService->loadContentDraftList(null, 0, 2);
$draftsOnPage2 = $this->contentService->loadContentDraftList(null, 2, 2);
$this->assertSame(5, $draftsOnPage1->totalCount);
$this->assertSame(5, $draftsOnPage2->totalCount);
$this->assertEquals($draftContentE->getVersionInfo(), $draftsOnPage1->items[0]->getVersionInfo());
$this->assertEquals($draftContentD->getVersionInfo(), $draftsOnPage1->items[1]->getVersionInfo());
$this->assertEquals($draftContentC->getVersionInfo(), $draftsOnPage2->items[0]->getVersionInfo());
$this->assertEquals($draftContentB->getVersionInfo(), $draftsOnPage2->items[1]->getVersionInfo());
}
/**
* Test for the loadContentDraftList() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentDrafts($user)
*/
public function testLoadContentDraftListWithForUserWithLimitation()
{
$oldUser = $this->permissionResolver->getCurrentUserReference();
$parentContent = $this->createFolder(['eng-US' => 'parentFolder'], 2);
$content = $this->createFolder(['eng-US' => 'parentFolder'], $parentContent->contentInfo->mainLocationId);
// User has limitation to read versions only for `$content`, not for `$parentContent`
$newUser = $this->createUserWithVersionReadLimitations([$content->contentInfo->mainLocationId]);
$this->permissionResolver->setCurrentUserReference($newUser);
$contentDraftUnauthorized = $this->contentService->createContentDraft($parentContent->contentInfo);
$contentDraftA = $this->contentService->createContentDraft($content->contentInfo);
$contentDraftB = $this->contentService->createContentDraft($content->contentInfo);
$newUserDraftList = $this->contentService->loadContentDraftList($newUser, 0);
$this->assertSame(3, $newUserDraftList->totalCount);
$this->assertEquals($contentDraftB->getVersionInfo(), $newUserDraftList->items[0]->getVersionInfo());
$this->assertEquals($contentDraftA->getVersionInfo(), $newUserDraftList->items[1]->getVersionInfo());
$this->assertEquals(
new UnauthorizedContentDraftListItem('content', 'versionread', ['contentId' => $contentDraftUnauthorized->id]),
$newUserDraftList->items[2]
);
// Reset to previous user
$this->permissionResolver->setCurrentUserReference($oldUser);
$oldUserDraftList = $this->contentService->loadContentDraftList();
$this->assertSame(0, $oldUserDraftList->totalCount);
$this->assertSame([], $oldUserDraftList->items);
}
/**
* Test for the loadContentDraftList() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentDrafts()
*/
public function testLoadAllContentDrafts()
{
// Create more drafts then default pagination limit
$this->createContentDrafts(12);
$this->assertCount(12, $this->contentService->loadContentDraftList());
}
/**
* Test for the loadVersionInfo() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadVersionInfo($contentInfo, $versionNo)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
*/
public function testLoadVersionInfoWithSecondParameter()
{
$publishedContent = $this->createContentVersion1();
$this->contentService->createContentDraft($publishedContent->contentInfo);
// Will return the VersionInfo of the $draftContent
$versionInfo = $this->contentService->loadVersionInfoById($publishedContent->id, 2);
$this->assertEquals(2, $versionInfo->versionNo);
// Check that ContentInfo contained in VersionInfo has correct main Location id set
$this->assertEquals(
$publishedContent->getVersionInfo()->getContentInfo()->mainLocationId,
$versionInfo->getContentInfo()->mainLocationId
);
}
/**
* Test for the loadVersionInfo() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadVersionInfo($contentInfo, $versionNo)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadVersionInfoWithSecondParameter
*/
public function testLoadVersionInfoThrowsNotFoundExceptionWithSecondParameter()
{
$draft = $this->createContentDraftVersion1();
$this->expectException(NotFoundException::class);
// This call will fail with a "NotFoundException", because not versionNo 2 exists for this content object.
$this->contentService->loadVersionInfo($draft->contentInfo, 2);
}
/**
* Test for the loadVersionInfoById() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadVersionInfoById($contentId, $versionNo)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadVersionInfoWithSecondParameter
*/
public function testLoadVersionInfoByIdWithSecondParameter()
{
$publishedContent = $this->createContentVersion1();
$draftContent = $this->contentService->createContentDraft($publishedContent->contentInfo);
// Will return the VersionInfo of the $draftContent
$versionInfo = $this->contentService->loadVersionInfoById($publishedContent->id, 2);
$this->assertEquals(2, $versionInfo->versionNo);
// Check that ContentInfo contained in VersionInfo has correct main Location id set
$this->assertEquals(
$publishedContent->getVersionInfo()->getContentInfo()->mainLocationId,
$versionInfo->getContentInfo()->mainLocationId
);
return [
'versionInfo' => $versionInfo,
'draftContent' => $draftContent,
];
}
/**
* Test for the returned value of the loadVersionInfoById() method.
*
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadVersionInfoByIdWithSecondParameter
* @covers \eZ\Publish\API\Repository\ContentService::loadVersionInfoById
*
* @param array $data
*/
public function testLoadVersionInfoByIdWithSecondParameterSetsExpectedVersionInfo(array $data)
{
/** @var VersionInfo $versionInfo */
$versionInfo = $data['versionInfo'];
/** @var \eZ\Publish\API\Repository\Values\Content\Content $draftContent */
$draftContent = $data['draftContent'];
$this->assertPropertiesCorrect(
[
'names' => [
self::ENG_US => 'An awesome forum',
],
'contentInfo' => new ContentInfo([
'id' => $draftContent->contentInfo->id,
'contentTypeId' => 28,
'name' => 'An awesome forum',
'sectionId' => 1,
'currentVersionNo' => 1,
'published' => true,
'ownerId' => 14,
// this Content Object is created at the test runtime
'modificationDate' => $versionInfo->contentInfo->modificationDate,
'publishedDate' => $versionInfo->contentInfo->publishedDate,
'alwaysAvailable' => 1,
'remoteId' => 'abcdef0123456789abcdef0123456789',
'mainLanguageCode' => self::ENG_US,
'mainLocationId' => $draftContent->contentInfo->mainLocationId,
'status' => ContentInfo::STATUS_PUBLISHED,
]),
'id' => $draftContent->versionInfo->id,
'versionNo' => 2,
'creatorId' => 14,
'status' => 0,
'initialLanguageCode' => self::ENG_US,
'languageCodes' => [
self::ENG_US,
],
],
$versionInfo
);
}
/**
* Test for the loadVersionInfoById() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadVersionInfoById($contentId, $versionNo)
*/
public function testLoadVersionInfoByIdThrowsNotFoundExceptionWithSecondParameter()
{
$content = $this->createContentVersion1();
$this->expectException(NotFoundException::class);
// This call will fail with a "NotFoundException", because not versionNo 2 exists for this content object.
$this->contentService->loadVersionInfoById($content->id, 2);
}
/**
* Test for the loadContentByVersionInfo() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentByVersionInfo($versionInfo, $languages)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentByVersionInfo
*/
public function testLoadContentByVersionInfoWithSecondParameter()
{
$sectionId = $this->generateId('section', 1);
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier(self::FORUM_IDENTIFIER);
$contentCreateStruct = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreateStruct->setField('name', 'Sindelfingen forum²');
$contentCreateStruct->setField('name', 'Sindelfingen forum²³', self::ENG_GB);
$contentCreateStruct->remoteId = 'abcdef0123456789abcdef0123456789';
// $sectionId contains the ID of section 1
$contentCreateStruct->sectionId = $sectionId;
$contentCreateStruct->alwaysAvailable = true;
// Create a new content draft
$content = $this->contentService->createContent($contentCreateStruct);
// Now publish this draft
$publishedContent = $this->contentService->publishVersion($content->getVersionInfo());
// Will return a content instance with fields in "eng-US"
$reloadedContent = $this->contentService->loadContentByVersionInfo(
$publishedContent->getVersionInfo(),
[
self::ENG_GB,
],
false
);
$actual = [];
foreach ($reloadedContent->getFields() as $field) {
$actual[] = new Field(
[
'id' => 0,
'value' => $field->value !== null, // Actual value tested by FieldType integration tests
'languageCode' => $field->languageCode,
'fieldDefIdentifier' => $field->fieldDefIdentifier,
]
);
}
usort(
$actual,
function ($field1, $field2) {
if (0 === ($return = strcasecmp($field1->fieldDefIdentifier, $field2->fieldDefIdentifier))) {
return strcasecmp($field1->languageCode, $field2->languageCode);
}
return $return;
}
);
$expected = [
new Field(
[
'id' => 0,
'value' => true,
'languageCode' => self::ENG_GB,
'fieldDefIdentifier' => 'name',
]
),
];
$this->assertEquals($expected, $actual);
}
/**
* Test for the loadContentByContentInfo() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentByContentInfo($contentInfo, $languages)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentByContentInfo
*/
public function testLoadContentByContentInfoWithLanguageParameters()
{
$sectionId = $this->generateId('section', 1);
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier(self::FORUM_IDENTIFIER);
$contentCreateStruct = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreateStruct->setField('name', 'Sindelfingen forum²');
$contentCreateStruct->setField('name', 'Sindelfingen forum²³', self::ENG_GB);
$contentCreateStruct->remoteId = 'abcdef0123456789abcdef0123456789';
// $sectionId contains the ID of section 1
$contentCreateStruct->sectionId = $sectionId;
$contentCreateStruct->alwaysAvailable = true;
// Create a new content draft
$content = $this->contentService->createContent($contentCreateStruct);
// Now publish this draft
$publishedContent = $this->contentService->publishVersion($content->getVersionInfo());
// Will return a content instance with fields in "eng-US"
$reloadedContent = $this->contentService->loadContentByContentInfo(
$publishedContent->contentInfo,
[
self::ENG_US,
],
null,
false
);
$actual = $this->normalizeFields($reloadedContent->getFields());
$expected = [
new Field(
[
'id' => 0,
'value' => true,
'languageCode' => self::ENG_US,
'fieldDefIdentifier' => 'name',
'fieldTypeIdentifier' => 'ezstring',
]
),
];
$this->assertEquals($expected, $actual);
// Will return a content instance with fields in "eng-GB" (versions prior to 6.0.0-beta9 returned "eng-US" also)
$reloadedContent = $this->contentService->loadContentByContentInfo(
$publishedContent->contentInfo,
[
self::ENG_GB,
],
null,
true
);
$actual = $this->normalizeFields($reloadedContent->getFields());
$expected = [
new Field(
[
'id' => 0,
'value' => true,
'languageCode' => self::ENG_GB,
'fieldDefIdentifier' => 'name',
'fieldTypeIdentifier' => 'ezstring',
]
),
];
$this->assertEquals($expected, $actual);
// Will return a content instance with fields in main language "eng-US", as "fre-FR" does not exists
$reloadedContent = $this->contentService->loadContentByContentInfo(
$publishedContent->contentInfo,
[
'fre-FR',
],
null,
true
);
$actual = $this->normalizeFields($reloadedContent->getFields());
$expected = [
new Field(
[
'id' => 0,
'value' => true,
'languageCode' => self::ENG_US,
'fieldDefIdentifier' => 'name',
'fieldTypeIdentifier' => 'ezstring',
]
),
];
$this->assertEquals($expected, $actual);
}
/**
* Test for the loadContentByContentInfo() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentByContentInfo($contentInfo, $languages, $versionNo)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentByContentInfo
*/
public function testLoadContentByContentInfoWithVersionNumberParameter()
{
$publishedContent = $this->createContentVersion1();
$this->contentService->createContentDraft($publishedContent->contentInfo);
// This content instance is identical to $draftContent
$draftContentReloaded = $this->contentService->loadContentByContentInfo(
$publishedContent->contentInfo,
null,
2
);
$this->assertEquals(
2,
$draftContentReloaded->getVersionInfo()->versionNo
);
// Check that ContentInfo contained in reloaded draft Content has correct main Location id set
$this->assertEquals(
$publishedContent->versionInfo->contentInfo->mainLocationId,
$draftContentReloaded->versionInfo->contentInfo->mainLocationId
);
}
/**
* Test for the loadContentByContentInfo() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentByContentInfo($contentInfo, $languages, $versionNo)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentByContentInfoWithVersionNumberParameter
*/
public function testLoadContentByContentInfoThrowsNotFoundExceptionWithVersionNumberParameter()
{
$content = $this->createContentVersion1();
$this->expectException(NotFoundException::class);
// This call will fail with a "NotFoundException", because no content with versionNo = 2 exists.
$this->contentService->loadContentByContentInfo($content->contentInfo, null, 2);
}
/**
* Test for the loadContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContent($contentId, $languages)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
*/
public function testLoadContentWithSecondParameter()
{
$draft = $this->createMultipleLanguageDraftVersion1();
// This draft contains those fields localized with "eng-GB"
$draftLocalized = $this->contentService->loadContent($draft->id, [self::ENG_GB], null, false);
$this->assertLocaleFieldsEquals($draftLocalized->getFields(), self::ENG_GB);
return $draft;
}
/**
* Test for the loadContent() method using undefined translation.
*
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentWithSecondParameter
*
* @param \eZ\Publish\API\Repository\Values\Content\Content $contentDraft
*/
public function testLoadContentWithSecondParameterThrowsNotFoundException(Content $contentDraft)
{
$this->expectException(NotFoundException::class);
$this->contentService->loadContent($contentDraft->id, [self::GER_DE], null, false);
}
/**
* Test for the loadContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContent($contentId, $languages, $versionNo)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
*/
public function testLoadContentWithThirdParameter()
{
$publishedContent = $this->createContentVersion1();
$this->contentService->createContentDraft($publishedContent->contentInfo);
// This content instance is identical to $draftContent
$draftContentReloaded = $this->contentService->loadContent($publishedContent->id, null, 2);
$this->assertEquals(2, $draftContentReloaded->getVersionInfo()->versionNo);
// Check that ContentInfo contained in reloaded draft Content has correct main Location id set
$this->assertEquals(
$publishedContent->versionInfo->contentInfo->mainLocationId,
$draftContentReloaded->versionInfo->contentInfo->mainLocationId
);
}
/**
* Test for the loadContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContent($contentId, $languages, $versionNo)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentWithThirdParameter
*/
public function testLoadContentThrowsNotFoundExceptionWithThirdParameter()
{
$content = $this->createContentVersion1();
$this->expectException(NotFoundException::class);
// This call will fail with a "NotFoundException", because for this content object no versionNo=2 exists.
$this->contentService->loadContent($content->id, null, 2);
}
/**
* Test for the loadContentByRemoteId() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentByRemoteId($remoteId, $languages)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
*/
public function testLoadContentByRemoteIdWithSecondParameter()
{
$draft = $this->createMultipleLanguageDraftVersion1();
$this->contentService->publishVersion($draft->versionInfo);
// This draft contains those fields localized with "eng-GB"
$draftLocalized = $this->contentService->loadContentByRemoteId(
$draft->contentInfo->remoteId,
[self::ENG_GB],
null,
false
);
$this->assertLocaleFieldsEquals($draftLocalized->getFields(), self::ENG_GB);
}
/**
* Test for the loadContentByRemoteId() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentByRemoteId($remoteId, $languages, $versionNo)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
*/
public function testLoadContentByRemoteIdWithThirdParameter()
{
$publishedContent = $this->createContentVersion1();
$this->contentService->createContentDraft($publishedContent->contentInfo);
// This content instance is identical to $draftContent
$draftContentReloaded = $this->contentService->loadContentByRemoteId(
$publishedContent->contentInfo->remoteId,
null,
2
);
$this->assertEquals(2, $draftContentReloaded->getVersionInfo()->versionNo);
// Check that ContentInfo contained in reloaded draft Content has correct main Location id set
$this->assertEquals(
$publishedContent->versionInfo->contentInfo->mainLocationId,
$draftContentReloaded->versionInfo->contentInfo->mainLocationId
);
}
/**
* Test for the loadContentByRemoteId() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadContentByRemoteId($remoteId, $languages, $versionNo)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentByRemoteIdWithThirdParameter
*/
public function testLoadContentByRemoteIdThrowsNotFoundExceptionWithThirdParameter()
{
$content = $this->createContentVersion1();
$this->expectException(NotFoundException::class);
// This call will fail with a "NotFoundException", because for this content object no versionNo=2 exists.
$this->contentService->loadContentByRemoteId(
$content->contentInfo->remoteId,
null,
2
);
}
/**
* Test that retrieval of translated name field respects prioritized language list.
*
* @dataProvider getPrioritizedLanguageList
* @param string[]|null $languageCodes
*/
public function testLoadContentWithPrioritizedLanguagesList($languageCodes)
{
$content = $this->createContentVersion2();
$content = $this->contentService->loadContent($content->id, $languageCodes);
$expectedName = $content->getVersionInfo()->getName(
isset($languageCodes[0]) ? $languageCodes[0] : null
);
$nameValue = $content->getFieldValue('name');
/** @var \eZ\Publish\Core\FieldType\TextLine\Value $nameValue */
self::assertEquals($expectedName, $nameValue->text);
self::assertEquals($expectedName, $content->getVersionInfo()->getName());
// Also check value on shortcut method on content
self::assertEquals($expectedName, $content->getName());
}
/**
* @return array
*/
public function getPrioritizedLanguageList()
{
return [
[[self::ENG_US]],
[[self::ENG_GB]],
[[self::ENG_GB, self::ENG_US]],
[[self::ENG_US, self::ENG_GB]],
];
}
/**
* Test for the deleteVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::deleteVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
*/
public function testDeleteVersion()
{
$content = $this->createContentVersion1();
// Create new draft, because published or last version of the Content can't be deleted
$draft = $this->contentService->createContentDraft(
$content->getVersionInfo()->getContentInfo()
);
// Delete the previously created draft
$this->contentService->deleteVersion($draft->getVersionInfo());
$versions = $this->contentService->loadVersions($content->getVersionInfo()->getContentInfo());
$this->assertCount(1, $versions);
$this->assertEquals(
$content->getVersionInfo()->id,
$versions[0]->id
);
}
/**
* Test for the deleteVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::deleteVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
*/
public function testDeleteVersionThrowsBadStateExceptionOnPublishedVersion()
{
$content = $this->createContentVersion1();
$this->expectException(BadStateException::class);
// This call will fail with a "BadStateException", because the content version is currently published.
$this->contentService->deleteVersion($content->getVersionInfo());
}
/**
* Test for the deleteVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::deleteVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
*/
public function testDeleteVersionWorksIfOnlyVersionIsDraft()
{
$draft = $this->createContentDraftVersion1();
$this->contentService->deleteVersion($draft->getVersionInfo());
$this->expectException(NotFoundException::class);
// This call will fail with a "NotFound", because we allow to delete content if remaining version is draft.
// Can normally only happen if there where always only a draft to begin with, simplifies UI edit API usage.
$this->contentService->loadContent($draft->id);
}
/**
* Test for the loadVersions() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadVersions()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
*
* @return VersionInfo[]
*/
public function testLoadVersions()
{
$contentVersion2 = $this->createContentVersion2();
// Load versions of this ContentInfo instance
$versions = $this->contentService->loadVersions($contentVersion2->contentInfo);
$expectedVersionsOrder = [
$this->contentService->loadVersionInfo($contentVersion2->contentInfo, 1),
$this->contentService->loadVersionInfo($contentVersion2->contentInfo, 2),
];
$this->assertEquals($expectedVersionsOrder, $versions);
return $versions;
}
/**
* Test for the loadVersions() method.
*
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadVersions
* @covers \eZ\Publish\Core\Repository\ContentService::loadVersions
*
* @param \eZ\Publish\API\Repository\Values\Content\VersionInfo[] $versions
*/
public function testLoadVersionsSetsExpectedVersionInfo(array $versions)
{
$this->assertCount(2, $versions);
$expectedVersions = [
[
'versionNo' => 1,
'creatorId' => 14,
'status' => VersionInfo::STATUS_ARCHIVED,
'initialLanguageCode' => self::ENG_US,
'languageCodes' => [self::ENG_US],
],
[
'versionNo' => 2,
'creatorId' => 10,
'status' => VersionInfo::STATUS_PUBLISHED,
'initialLanguageCode' => self::ENG_US,
'languageCodes' => [self::ENG_US, self::ENG_GB],
],
];
$this->assertPropertiesCorrect($expectedVersions[0], $versions[0]);
$this->assertPropertiesCorrect($expectedVersions[1], $versions[1]);
$this->assertEqualsWithDelta(
$versions[0]->creationDate->getTimestamp(),
$versions[1]->creationDate->getTimestamp(),
2,
'Creation time did not match within delta of 2 seconds',
);
$this->assertEqualsWithDelta(
$versions[0]->modificationDate->getTimestamp(),
$versions[1]->modificationDate->getTimestamp(),
2,
'Creation time did not match within delta of 2 seconds',
);
$this->assertTrue($versions[0]->isArchived());
$this->assertFalse($versions[0]->isDraft());
$this->assertFalse($versions[0]->isPublished());
$this->assertTrue($versions[1]->isPublished());
$this->assertFalse($versions[1]->isDraft());
$this->assertFalse($versions[1]->isArchived());
}
/**
* Test for the copyContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::copyContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
* @group field-type
*/
public function testCopyContent()
{
$parentLocationId = $this->generateId('location', 56);
$contentVersion2 = $this->createMultipleLanguageContentVersion2();
// Configure new target location
$targetLocationCreate = $this->locationService->newLocationCreateStruct($parentLocationId);
$targetLocationCreate->priority = 42;
$targetLocationCreate->hidden = true;
$targetLocationCreate->remoteId = '01234abcdef5678901234abcdef56789';
$targetLocationCreate->sortField = Location::SORT_FIELD_NODE_ID;
$targetLocationCreate->sortOrder = Location::SORT_ORDER_DESC;
// Copy content with all versions and drafts
$contentCopied = $this->contentService->copyContent(
$contentVersion2->contentInfo,
$targetLocationCreate
);
$this->assertInstanceOf(
Content::class,
$contentCopied
);
$this->assertNotEquals(
$contentVersion2->contentInfo->remoteId,
$contentCopied->contentInfo->remoteId
);
$this->assertNotEquals(
$contentVersion2->id,
$contentCopied->id
);
$this->assertCount(
2,
$this->contentService->loadVersions($contentCopied->contentInfo)
);
$this->assertEquals(2, $contentCopied->getVersionInfo()->versionNo);
$this->assertAllFieldsEquals($contentCopied->getFields());
$this->assertDefaultContentStates($contentCopied->contentInfo);
$this->assertNotNull(
$contentCopied->contentInfo->mainLocationId,
'Expected main location to be set given we provided a LocationCreateStruct'
);
}
/**
* Test for the copyContent() method with ezsettings.default.content.retain_owner_on_copy set to false
* See settings/test/integration_legacy.yml for service override.
*
* @see \eZ\Publish\API\Repository\ContentService::copyContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
* @group field-type
*/
public function testCopyContentWithNewOwner()
{
$parentLocationId = $this->generateId('location', 56);
$userService = $this->getRepository()->getUserService();
$newOwner = $this->createUser('new_owner', 'foo', 'bar');
/** @var \eZ\Publish\API\Repository\Values\Content\Content $contentVersion2 */
$contentVersion2 = $this->createContentDraftVersion1(
$parentLocationId,
self::FORUM_IDENTIFIER,
'name',
$newOwner
);
// Configure new target location
$targetLocationCreate = $this->locationService->newLocationCreateStruct($parentLocationId);
$targetLocationCreate->priority = 42;
$targetLocationCreate->hidden = true;
$targetLocationCreate->remoteId = '01234abcdef5678901234abcdef56789';
$targetLocationCreate->sortField = Location::SORT_FIELD_NODE_ID;
$targetLocationCreate->sortOrder = Location::SORT_ORDER_DESC;
// Copy content with all versions and drafts
$contentCopied = $this->contentService->copyContent(
$contentVersion2->contentInfo,
$targetLocationCreate
);
$this->assertEquals(
$newOwner->id,
$contentVersion2->contentInfo->ownerId
);
$this->assertEquals(
$userService->loadUserByLogin('admin')->getUserId(),
$contentCopied->contentInfo->ownerId
);
}
/**
* Test for the copyContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::copyContent($contentInfo, $destinationLocationCreateStruct, $versionInfo)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCopyContent
*/
public function testCopyContentWithGivenVersion()
{
$parentLocationId = $this->generateId('location', 56);
$contentVersion2 = $this->createContentVersion2();
// Configure new target location
$targetLocationCreate = $this->locationService->newLocationCreateStruct($parentLocationId);
$targetLocationCreate->priority = 42;
$targetLocationCreate->hidden = true;
$targetLocationCreate->remoteId = '01234abcdef5678901234abcdef56789';
$targetLocationCreate->sortField = Location::SORT_FIELD_NODE_ID;
$targetLocationCreate->sortOrder = Location::SORT_ORDER_DESC;
// Copy only the initial version
$contentCopied = $this->contentService->copyContent(
$contentVersion2->contentInfo,
$targetLocationCreate,
$this->contentService->loadVersionInfo($contentVersion2->contentInfo, 1)
);
$this->assertInstanceOf(
Content::class,
$contentCopied
);
$this->assertNotEquals(
$contentVersion2->contentInfo->remoteId,
$contentCopied->contentInfo->remoteId
);
$this->assertNotEquals(
$contentVersion2->id,
$contentCopied->id
);
$this->assertCount(
1,
$this->contentService->loadVersions($contentCopied->contentInfo)
);
$this->assertEquals(1, $contentCopied->getVersionInfo()->versionNo);
$this->assertNotNull(
$contentCopied->contentInfo->mainLocationId,
'Expected main location to be set given we provided a LocationCreateStruct'
);
}
/**
* Test for the addRelation() method.
*
* @return \eZ\Publish\API\Repository\Values\Content\Content
*
* @see \eZ\Publish\API\Repository\ContentService::addRelation()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersionFromContentDraft
*/
public function testAddRelation()
{
$draft = $this->createContentDraftVersion1();
$media = $this->contentService->loadContentInfoByRemoteId(self::MEDIA_REMOTE_ID);
// Create relation between new content object and "Media" page
$relation = $this->contentService->addRelation(
$draft->getVersionInfo(),
$media
);
$this->assertInstanceOf(
'\\eZ\\Publish\\API\\Repository\\Values\\Content\\Relation',
$relation
);
return $this->contentService->loadRelations($draft->getVersionInfo());
}
/**
* Test for the addRelation() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Relation[] $relations
*
* @see \eZ\Publish\API\Repository\ContentService::addRelation()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testAddRelation
*/
public function testAddRelationAddsRelationToContent($relations)
{
$this->assertCount(
1,
$relations
);
}
/**
* @param \eZ\Publish\API\Repository\Values\Content\Relation[] $relations
*/
protected function assertExpectedRelations($relations)
{
$this->assertEquals(
[
'type' => Relation::COMMON,
'sourceFieldDefinitionIdentifier' => null,
'sourceContentInfo' => 'abcdef0123456789abcdef0123456789',
'destinationContentInfo' => self::MEDIA_REMOTE_ID,
],
[
'type' => $relations[0]->type,
'sourceFieldDefinitionIdentifier' => $relations[0]->sourceFieldDefinitionIdentifier,
'sourceContentInfo' => $relations[0]->sourceContentInfo->remoteId,
'destinationContentInfo' => $relations[0]->destinationContentInfo->remoteId,
]
);
}
/**
* Test for the addRelation() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Relation[] $relations
*
* @see \eZ\Publish\API\Repository\ContentService::addRelation()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testAddRelation
*/
public function testAddRelationSetsExpectedRelations($relations)
{
$this->assertExpectedRelations($relations);
}
/**
* Test for the createContentDraft() method.
*
* @return \eZ\Publish\API\Repository\Values\Content\Relation[]
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testAddRelationSetsExpectedRelations
*/
public function testCreateContentDraftWithRelations()
{
$draft = $this->createContentDraftVersion1();
$media = $this->contentService->loadContentInfoByRemoteId(self::MEDIA_REMOTE_ID);
// Create relation between new content object and "Media" page
$this->contentService->addRelation(
$draft->getVersionInfo(),
$media
);
$content = $this->contentService->publishVersion($draft->versionInfo);
$newDraft = $this->contentService->createContentDraft($content->contentInfo);
return $this->contentService->loadRelations($newDraft->getVersionInfo());
}
/**
* Test for the createContentDraft() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Relation[] $relations
*
* @return \eZ\Publish\API\Repository\Values\Content\Relation[]
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraftWithRelations
*/
public function testCreateContentDraftWithRelationsCreatesRelations($relations)
{
$this->assertCount(
1,
$relations
);
return $relations;
}
/**
* Test for the createContentDraft() method.
*
* @param \eZ\Publish\API\Repository\Values\Content\Relation[] $relations
*
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraftWithRelationsCreatesRelations
*/
public function testCreateContentDraftWithRelationsCreatesExpectedRelations($relations)
{
$this->assertExpectedRelations($relations);
}
/**
* Test for the addRelation() method.
*
* @see \eZ\Publish\API\Repository\ContentService::addRelation()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testAddRelation
*/
public function testAddRelationThrowsBadStateException()
{
$content = $this->createContentVersion1();
$media = $this->contentService->loadContentInfoByRemoteId(self::MEDIA_REMOTE_ID);
$this->expectException(BadStateException::class);
// This call will fail with a "BadStateException", because content is published and not a draft.
$this->contentService->addRelation(
$content->getVersionInfo(),
$media
);
}
/**
* Test for the loadRelations() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadRelations()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testAddRelation
*/
public function testLoadRelations()
{
$draft = $this->createContentDraftVersion1();
$media = $this->contentService->loadContentInfoByRemoteId(self::MEDIA_REMOTE_ID);
$demoDesign = $this->contentService->loadContentInfoByRemoteId(self::DEMO_DESIGN_REMOTE_ID);
// Create relation between new content object and "Media" page
$this->contentService->addRelation(
$draft->getVersionInfo(),
$media
);
// Create another relation with the "Demo Design" page
$this->contentService->addRelation(
$draft->getVersionInfo(),
$demoDesign
);
$relations = $this->contentService->loadRelations($draft->getVersionInfo());
usort(
$relations,
function ($rel1, $rel2) {
return strcasecmp(
$rel2->getDestinationContentInfo()->remoteId,
$rel1->getDestinationContentInfo()->remoteId
);
}
);
$this->assertEquals(
[
[
'sourceContentInfo' => 'abcdef0123456789abcdef0123456789',
'destinationContentInfo' => self::MEDIA_REMOTE_ID,
],
[
'sourceContentInfo' => 'abcdef0123456789abcdef0123456789',
'destinationContentInfo' => self::DEMO_DESIGN_REMOTE_ID,
],
],
[
[
'sourceContentInfo' => $relations[0]->sourceContentInfo->remoteId,
'destinationContentInfo' => $relations[0]->destinationContentInfo->remoteId,
],
[
'sourceContentInfo' => $relations[1]->sourceContentInfo->remoteId,
'destinationContentInfo' => $relations[1]->destinationContentInfo->remoteId,
],
]
);
}
/**
* Test for the loadRelations() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadRelations()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testAddRelation
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadRelations
*/
public function testLoadRelationsSkipsArchivedContent()
{
$trashService = $this->getRepository()->getTrashService();
$draft = $this->createContentDraftVersion1();
// Load other content objects
$media = $this->contentService->loadContentInfoByRemoteId(self::MEDIA_REMOTE_ID);
$demoDesign = $this->contentService->loadContentInfoByRemoteId(self::DEMO_DESIGN_REMOTE_ID);
// Create relation between new content object and "Media" page
$this->contentService->addRelation(
$draft->getVersionInfo(),
$media
);
// Create another relation with the "Demo Design" page
$this->contentService->addRelation(
$draft->getVersionInfo(),
$demoDesign
);
$demoDesignLocation = $this->locationService->loadLocation($demoDesign->mainLocationId);
// Trashing Content's last Location will change its status to archived,
// in this case relation towards it will not be loaded.
$trashService->trash($demoDesignLocation);
// Load all relations
$relations = $this->contentService->loadRelations($draft->getVersionInfo());
$this->assertCount(1, $relations);
$this->assertEquals(
[
[
'sourceContentInfo' => 'abcdef0123456789abcdef0123456789',
'destinationContentInfo' => self::MEDIA_REMOTE_ID,
],
],
[
[
'sourceContentInfo' => $relations[0]->sourceContentInfo->remoteId,
'destinationContentInfo' => $relations[0]->destinationContentInfo->remoteId,
],
]
);
}
/**
* Test for the loadRelations() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadRelations()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testAddRelation
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadRelations
*/
public function testLoadRelationsSkipsDraftContent()
{
$draft = $this->createContentDraftVersion1();
// Load other content objects
$media = $this->contentService->loadContentByRemoteId(self::MEDIA_REMOTE_ID);
$demoDesign = $this->contentService->loadContentInfoByRemoteId(self::DEMO_DESIGN_REMOTE_ID);
// Create draft of "Media" page
$mediaDraft = $this->contentService->createContentDraft($media->contentInfo);
// Create relation between "Media" page and new content object draft.
// This relation will not be loaded before the draft is published.
$this->contentService->addRelation(
$mediaDraft->getVersionInfo(),
$draft->getVersionInfo()->getContentInfo()
);
// Create another relation with the "Demo Design" page
$this->contentService->addRelation(
$mediaDraft->getVersionInfo(),
$demoDesign
);
$relations = $this->contentService->loadRelations($mediaDraft->getVersionInfo());
$this->assertCount(1, $relations);
$this->assertEquals(
[
[
'sourceContentInfo' => self::MEDIA_REMOTE_ID,
'destinationContentInfo' => self::DEMO_DESIGN_REMOTE_ID,
],
],
[
[
'sourceContentInfo' => $relations[0]->sourceContentInfo->remoteId,
'destinationContentInfo' => $relations[0]->destinationContentInfo->remoteId,
],
]
);
}
/**
* Test for the countReverseRelations() method.
*
* @covers \eZ\Publish\API\Repository\ContentService::countReverseRelations
*/
public function testCountReverseRelations(): void
{
$contentWithReverseRelations = $this->createContentWithReverseRelations([
$this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Foo'], 2)->contentInfo
),
$this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Bar'], 2)->contentInfo
),
]);
$contentInfo = $contentWithReverseRelations->content->getVersionInfo()->getContentInfo();
$this->assertEquals(2, $this->contentService->countReverseRelations($contentInfo));
}
/**
* Test for the countReverseRelations() method.
*
* @covers \eZ\Publish\API\Repository\ContentService::countReverseRelations
*/
public function testCountReverseRelationsReturnsZeroByDefault(): void
{
$draft = $this->createContentDraftVersion1();
$this->assertSame(0, $this->contentService->countReverseRelations($draft->getVersionInfo()->getContentInfo()));
}
/**
* Test for the countReverseRelations() method.
*
* @covers \eZ\Publish\API\Repository\ContentService::countReverseRelations
*/
public function testCountReverseRelationsForUnauthorizedUser(): void
{
$contentWithReverseRelations = $this->createContentWithReverseRelations([
$this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Foo'], 2)->contentInfo
),
]);
$mediaUser = $this->createMediaUserVersion1();
$this->permissionResolver->setCurrentUserReference($mediaUser);
$contentInfo = $contentWithReverseRelations->content->contentInfo;
$this->assertSame(0, $this->contentService->countReverseRelations($contentInfo));
}
/**
* Test for the loadReverseRelations() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadReverseRelations()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testAddRelation
*/
public function testLoadReverseRelations()
{
$versionInfo = $this->createContentVersion1()->getVersionInfo();
$contentInfo = $versionInfo->getContentInfo();
// Create some drafts
$mediaDraft = $this->contentService->createContentDraft(
$this->contentService->loadContentInfoByRemoteId(self::MEDIA_REMOTE_ID)
);
$demoDesignDraft = $this->contentService->createContentDraft(
$this->contentService->loadContentInfoByRemoteId(self::DEMO_DESIGN_REMOTE_ID)
);
// Create relation between new content object and "Media" page
$relation1 = $this->contentService->addRelation(
$mediaDraft->getVersionInfo(),
$contentInfo
);
// Create another relation with the "Demo Design" page
$relation2 = $this->contentService->addRelation(
$demoDesignDraft->getVersionInfo(),
$contentInfo
);
// Publish drafts, so relations become active
$this->contentService->publishVersion($mediaDraft->getVersionInfo());
$this->contentService->publishVersion($demoDesignDraft->getVersionInfo());
$relations = $this->contentService->loadRelations($versionInfo);
$reverseRelations = $this->contentService->loadReverseRelations($contentInfo);
$this->assertEquals($contentInfo->id, $relation1->getDestinationContentInfo()->id);
$this->assertEquals($mediaDraft->id, $relation1->getSourceContentInfo()->id);
$this->assertEquals($contentInfo->id, $relation2->getDestinationContentInfo()->id);
$this->assertEquals($demoDesignDraft->id, $relation2->getSourceContentInfo()->id);
$this->assertCount(0, $relations);
$this->assertCount(2, $reverseRelations);
usort(
$reverseRelations,
function ($rel1, $rel2) {
return strcasecmp(
$rel2->getSourceContentInfo()->remoteId,
$rel1->getSourceContentInfo()->remoteId
);
}
);
$this->assertEquals(
[
[
'sourceContentInfo' => self::MEDIA_REMOTE_ID,
'destinationContentInfo' => 'abcdef0123456789abcdef0123456789',
],
[
'sourceContentInfo' => self::DEMO_DESIGN_REMOTE_ID,
'destinationContentInfo' => 'abcdef0123456789abcdef0123456789',
],
],
[
[
'sourceContentInfo' => $reverseRelations[0]->sourceContentInfo->remoteId,
'destinationContentInfo' => $reverseRelations[0]->destinationContentInfo->remoteId,
],
[
'sourceContentInfo' => $reverseRelations[1]->sourceContentInfo->remoteId,
'destinationContentInfo' => $reverseRelations[1]->destinationContentInfo->remoteId,
],
]
);
}
/**
* Test for the loadReverseRelations() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadReverseRelations()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testAddRelation
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadReverseRelations
*/
public function testLoadReverseRelationsSkipsArchivedContent()
{
$trashService = $this->getRepository()->getTrashService();
$versionInfo = $this->createContentVersion1()->getVersionInfo();
$contentInfo = $versionInfo->getContentInfo();
// Create some drafts
$mediaDraft = $this->contentService->createContentDraft(
$this->contentService->loadContentInfoByRemoteId(self::MEDIA_REMOTE_ID)
);
$demoDesignDraft = $this->contentService->createContentDraft(
$this->contentService->loadContentInfoByRemoteId(self::DEMO_DESIGN_REMOTE_ID)
);
// Create relation between new content object and "Media" page
$relation1 = $this->contentService->addRelation(
$mediaDraft->getVersionInfo(),
$contentInfo
);
// Create another relation with the "Demo Design" page
$relation2 = $this->contentService->addRelation(
$demoDesignDraft->getVersionInfo(),
$contentInfo
);
// Publish drafts, so relations become active
$this->contentService->publishVersion($mediaDraft->getVersionInfo());
$this->contentService->publishVersion($demoDesignDraft->getVersionInfo());
$demoDesignLocation = $this->locationService->loadLocation($demoDesignDraft->contentInfo->mainLocationId);
// Trashing Content's last Location will change its status to archived,
// in this case relation from it will not be loaded.
$trashService->trash($demoDesignLocation);
// Load all relations
$relations = $this->contentService->loadRelations($versionInfo);
$reverseRelations = $this->contentService->loadReverseRelations($contentInfo);
$this->assertEquals($contentInfo->id, $relation1->getDestinationContentInfo()->id);
$this->assertEquals($mediaDraft->id, $relation1->getSourceContentInfo()->id);
$this->assertEquals($contentInfo->id, $relation2->getDestinationContentInfo()->id);
$this->assertEquals($demoDesignDraft->id, $relation2->getSourceContentInfo()->id);
$this->assertCount(0, $relations);
$this->assertCount(1, $reverseRelations);
$this->assertEquals(
[
[
'sourceContentInfo' => self::MEDIA_REMOTE_ID,
'destinationContentInfo' => 'abcdef0123456789abcdef0123456789',
],
],
[
[
'sourceContentInfo' => $reverseRelations[0]->sourceContentInfo->remoteId,
'destinationContentInfo' => $reverseRelations[0]->destinationContentInfo->remoteId,
],
]
);
}
/**
* Test for the loadReverseRelations() method.
*
* @see \eZ\Publish\API\Repository\ContentService::loadReverseRelations()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testAddRelation
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadReverseRelations
*/
public function testLoadReverseRelationsSkipsDraftContent()
{
// Load "Media" page Content
$media = $this->contentService->loadContentByRemoteId(self::MEDIA_REMOTE_ID);
// Create some drafts
$newDraftVersionInfo = $this->createContentDraftVersion1()->getVersionInfo();
$demoDesignDraft = $this->contentService->createContentDraft(
$this->contentService->loadContentInfoByRemoteId(self::DEMO_DESIGN_REMOTE_ID)
);
// Create relation between "Media" page and new content object
$relation1 = $this->contentService->addRelation(
$newDraftVersionInfo,
$media->contentInfo
);
// Create another relation with the "Demo Design" page
$relation2 = $this->contentService->addRelation(
$demoDesignDraft->getVersionInfo(),
$media->contentInfo
);
// Publish drafts, so relations become active
$this->contentService->publishVersion($demoDesignDraft->getVersionInfo());
// We will not publish new Content draft, therefore relation from it
// will not be loaded as reverse relation for "Media" page
$relations = $this->contentService->loadRelations($media->versionInfo);
$reverseRelations = $this->contentService->loadReverseRelations($media->contentInfo);
$this->assertEquals($media->contentInfo->id, $relation1->getDestinationContentInfo()->id);
$this->assertEquals($newDraftVersionInfo->contentInfo->id, $relation1->getSourceContentInfo()->id);
$this->assertEquals($media->contentInfo->id, $relation2->getDestinationContentInfo()->id);
$this->assertEquals($demoDesignDraft->id, $relation2->getSourceContentInfo()->id);
$this->assertCount(0, $relations);
$this->assertCount(1, $reverseRelations);
$this->assertEquals(
[
[
'sourceContentInfo' => self::DEMO_DESIGN_REMOTE_ID,
'destinationContentInfo' => self::MEDIA_REMOTE_ID,
],
],
[
[
'sourceContentInfo' => $reverseRelations[0]->sourceContentInfo->remoteId,
'destinationContentInfo' => $reverseRelations[0]->destinationContentInfo->remoteId,
],
]
);
}
/**
* @covers \eZ\Publish\API\Repository\ContentService::loadReverseRelationList
*/
public function testLoadReverseRelationList(): void
{
$draft1 = $this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Foo'], 2)->contentInfo
);
$draft2 = $this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Bar'], 2)->contentInfo
);
$draft3 = $this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Baz'], 2)->contentInfo
);
$contentWithReverseRelations = $this->createContentWithReverseRelations([
$draft1,
$draft2,
$draft3,
]);
$contentInfo = $contentWithReverseRelations->content->contentInfo;
$reverseRelationList = $this->contentService->loadReverseRelationList($contentInfo);
$this->assertSame(3, $reverseRelationList->totalCount);
$this->assertEquals(
$contentWithReverseRelations->reverseRelations[2]->contentInfo,
$reverseRelationList->items[0]->getRelation()->sourceContentInfo
);
$this->assertEquals(
$contentWithReverseRelations->reverseRelations[1]->contentInfo,
$reverseRelationList->items[1]->getRelation()->sourceContentInfo
);
$this->assertEquals(
$contentWithReverseRelations->reverseRelations[0]->contentInfo,
$reverseRelationList->items[2]->getRelation()->sourceContentInfo
);
}
/**
* @covers \eZ\Publish\API\Repository\ContentService::loadReverseRelationList
*/
public function testLoadReverseRelationListWithPagination(): void
{
$draft1 = $this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Foo'], 2)->contentInfo
);
$draft2 = $this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Bar'], 2)->contentInfo
);
$draft3 = $this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Baz'], 2)->contentInfo
);
$contentWithReverseRelations = $this->createContentWithReverseRelations([
$draft1,
$draft2,
$draft3,
]);
$contentInfo = $contentWithReverseRelations->content->contentInfo;
$reverseRelationPage1 = $this->contentService->loadReverseRelationList($contentInfo, 0, 2);
$reverseRelationPage2 = $this->contentService->loadReverseRelationList($contentInfo, 2, 2);
$this->assertSame(3, $reverseRelationPage1->totalCount);
$this->assertSame(3, $reverseRelationPage2->totalCount);
$this->assertEquals(
$contentWithReverseRelations->reverseRelations[2]->contentInfo,
$reverseRelationPage1->items[0]->getRelation()->sourceContentInfo
);
$this->assertEquals(
$contentWithReverseRelations->reverseRelations[1]->contentInfo,
$reverseRelationPage1->items[1]->getRelation()->sourceContentInfo
);
$this->assertEquals(
$contentWithReverseRelations->reverseRelations[0]->contentInfo,
$reverseRelationPage2->items[0]->getRelation()->sourceContentInfo
);
}
/**
* @covers \eZ\Publish\API\Repository\ContentService::loadReverseRelationList
*/
public function testLoadReverseRelationListSkipsArchivedContent(): void
{
$trashService = $this->getRepository()->getTrashService();
$draft1 = $this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Foo'], 2)->contentInfo
);
$draft2 = $this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Bar'], 2)->contentInfo
);
$draft3 = $this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Baz'], 2)->contentInfo
);
$contentWithReverseRelations = $this->createContentWithReverseRelations([
$draft1,
$draft2,
$draft3,
]);
$locationToTrash = $this->locationService->loadLocation($draft3->contentInfo->mainLocationId);
// Trashing Content's last Location will change its status to archived, in this case relation from it will not be loaded.
$trashService->trash($locationToTrash);
$contentInfo = $contentWithReverseRelations->content->contentInfo;
$reverseRelationList = $this->contentService->loadReverseRelationList($contentInfo);
$this->assertSame(2, $reverseRelationList->totalCount);
$this->assertEquals(
$contentWithReverseRelations->reverseRelations[1]->contentInfo,
$reverseRelationList->items[0]->getRelation()->sourceContentInfo
);
$this->assertEquals(
$contentWithReverseRelations->reverseRelations[0]->contentInfo,
$reverseRelationList->items[1]->getRelation()->sourceContentInfo
);
}
/**
* @covers \eZ\Publish\API\Repository\ContentService::loadReverseRelationList
*/
public function testLoadReverseRelationListSkipsDraftContent()
{
$draft1 = $this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Foo'], 2)->contentInfo
);
$contentWithReverseRelations = $this->createContentWithReverseRelations([$draft1]);
$contentInfo = $contentWithReverseRelations->content->contentInfo;
// create a relation, but without publishing it
$draft2 = $this->contentService->createContentDraft(
$this->createFolder([self::ENG_GB => 'Bar'], 2)->contentInfo
);
$this->contentService->addRelation(
$draft2->getVersionInfo(),
$contentInfo
);
$reverseRelationList = $this->contentService->loadReverseRelationList($contentInfo);
$this->assertSame(1, $reverseRelationList->totalCount);
$this->assertEquals(
$contentWithReverseRelations->reverseRelations[0]->contentInfo,
$reverseRelationList->items[0]->getRelation()->sourceContentInfo
);
}
/**
* Test for the deleteRelation() method.
*
* @see \eZ\Publish\API\Repository\ContentService::deleteRelation()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadRelations
*/
public function testDeleteRelation()
{
$draft = $this->createContentDraftVersion1();
$media = $this->contentService->loadContentInfoByRemoteId(self::MEDIA_REMOTE_ID);
$demoDesign = $this->contentService->loadContentInfoByRemoteId(self::DEMO_DESIGN_REMOTE_ID);
// Establish some relations
$this->contentService->addRelation($draft->getVersionInfo(), $media);
$this->contentService->addRelation($draft->getVersionInfo(), $demoDesign);
// Delete one of the currently created relations
$this->contentService->deleteRelation($draft->getVersionInfo(), $media);
// The relations array now contains only one element
$relations = $this->contentService->loadRelations($draft->getVersionInfo());
$this->assertCount(1, $relations);
}
/**
* Test for the deleteRelation() method.
*
* @see \eZ\Publish\API\Repository\ContentService::deleteRelation()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testDeleteRelation
*/
public function testDeleteRelationThrowsBadStateException()
{
$content = $this->createContentVersion1();
// Load the destination object
$media = $this->contentService->loadContentInfoByRemoteId(self::MEDIA_REMOTE_ID);
// Create a new draft
$draftVersion2 = $this->contentService->createContentDraft($content->contentInfo);
// Add a relation
$this->contentService->addRelation($draftVersion2->getVersionInfo(), $media);
// Publish new version
$contentVersion2 = $this->contentService->publishVersion(
$draftVersion2->getVersionInfo()
);
$this->expectException(BadStateException::class);
// This call will fail with a "BadStateException", because content is published and not a draft.
$this->contentService->deleteRelation(
$contentVersion2->getVersionInfo(),
$media
);
}
/**
* Test for the deleteRelation() method.
*
* @see \eZ\Publish\API\Repository\ContentService::deleteRelation()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testDeleteRelation
*/
public function testDeleteRelationThrowsInvalidArgumentException()
{
$draft = $this->createContentDraftVersion1();
// Load the destination object
$media = $this->contentService->loadContentInfoByRemoteId(self::MEDIA_REMOTE_ID);
// This call will fail with a "InvalidArgumentException", because no relation exists between $draft and $media.
$this->expectException(APIInvalidArgumentException::class);
$this->contentService->deleteRelation(
$draft->getVersionInfo(),
$media
);
}
/**
* Test for the createContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
*/
public function testCreateContentInTransactionWithRollback()
{
if ($this->isVersion4()) {
$this->markTestSkipped('This test requires eZ Publish 5');
}
$repository = $this->getRepository();
$contentTypeService = $this->getRepository()->getContentTypeService();
// Start a transaction
$repository->beginTransaction();
try {
$contentType = $contentTypeService->loadContentTypeByIdentifier(self::FORUM_IDENTIFIER);
// Get a content create struct and set mandatory properties
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate->setField('name', 'Sindelfingen forum');
$contentCreate->remoteId = 'abcdef0123456789abcdef0123456789';
$contentCreate->alwaysAvailable = true;
// Create a new content object
$contentId = $this->contentService->createContent($contentCreate)->id;
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Rollback all changes
$repository->rollback();
try {
// This call will fail with a "NotFoundException"
$this->contentService->loadContent($contentId);
} catch (NotFoundException $e) {
// This is expected
return;
}
$this->fail('Content object still exists after rollback.');
}
/**
* Test for the createContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
*/
public function testCreateContentInTransactionWithCommit()
{
if ($this->isVersion4()) {
$this->markTestSkipped('This test requires eZ Publish 5');
}
$repository = $this->getRepository();
$contentTypeService = $repository->getContentTypeService();
// Start a transaction
$repository->beginTransaction();
try {
$contentType = $contentTypeService->loadContentTypeByIdentifier(self::FORUM_IDENTIFIER);
// Get a content create struct and set mandatory properties
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate->setField('name', 'Sindelfingen forum');
$contentCreate->remoteId = 'abcdef0123456789abcdef0123456789';
$contentCreate->alwaysAvailable = true;
// Create a new content object
$contentId = $this->contentService->createContent($contentCreate)->id;
// Commit changes
$repository->commit();
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Load the new content object
$content = $this->contentService->loadContent($contentId);
$this->assertEquals($contentId, $content->id);
}
/**
* Test for the createContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContent($contentCreateStruct, $locationCreateStructs)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentWithLocationCreateParameterDoesNotCreateLocationImmediately
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentThrowsNotFoundException
*/
public function testCreateContentWithLocationCreateParameterInTransactionWithRollback()
{
$repository = $this->getRepository();
// Start a transaction
$repository->beginTransaction();
try {
$draft = $this->createContentDraftVersion1();
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
$contentId = $draft->id;
// Roleback the transaction
$repository->rollback();
try {
// This call will fail with a "NotFoundException"
$this->contentService->loadContent($contentId);
} catch (NotFoundException $e) {
return;
}
$this->fail('Can still load content object after rollback.');
}
/**
* Test for the createContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContent($contentCreateStruct, $locationCreateStructs)
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentWithLocationCreateParameterDoesNotCreateLocationImmediately
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentThrowsNotFoundException
*/
public function testCreateContentWithLocationCreateParameterInTransactionWithCommit()
{
$repository = $this->getRepository();
// Start a transaction
$repository->beginTransaction();
try {
$draft = $this->createContentDraftVersion1();
$contentId = $draft->id;
// Roleback the transaction
$repository->commit();
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Load the new content object
$content = $this->contentService->loadContent($contentId);
$this->assertEquals($contentId, $content->id);
}
/**
* Test for the createContentDraft() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
*/
public function testCreateContentDraftInTransactionWithRollback()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::ADMINISTRATORS_USER_GROUP_ID);
// Load the user group content object
$content = $this->contentService->loadContent($contentId);
// Start a new transaction
$repository->beginTransaction();
try {
// Create a new draft
$drafted = $this->contentService->createContentDraft($content->contentInfo);
// Store version number for later reuse
$versionNo = $drafted->versionInfo->versionNo;
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Rollback
$repository->rollback();
try {
// This call will fail with a "NotFoundException"
$this->contentService->loadContent($contentId, null, $versionNo);
} catch (NotFoundException $e) {
return;
}
$this->fail('Can still load content draft after rollback');
}
/**
* Test for the createContentDraft() method.
*
* @see \eZ\Publish\API\Repository\ContentService::createContentDraft()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContentDraft
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
*/
public function testCreateContentDraftInTransactionWithCommit()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::ADMINISTRATORS_USER_GROUP_ID);
// Load the user group content object
$content = $this->contentService->loadContent($contentId);
// Start a new transaction
$repository->beginTransaction();
try {
// Create a new draft
$drafted = $this->contentService->createContentDraft($content->contentInfo);
// Store version number for later reuse
$versionNo = $drafted->versionInfo->versionNo;
// Commit all changes
$repository->commit();
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
$content = $this->contentService->loadContent($contentId, null, $versionNo);
$this->assertEquals(
$versionNo,
$content->getVersionInfo()->versionNo
);
}
/**
* Test for the publishVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
*/
public function testPublishVersionInTransactionWithRollback()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::ADMINISTRATORS_USER_GROUP_ID);
// Load the user group content object
$content = $this->contentService->loadContent($contentId);
// Start a new transaction
$repository->beginTransaction();
try {
$draftVersion = $this->contentService->createContentDraft($content->contentInfo)->getVersionInfo();
// Publish a new version
$content = $this->contentService->publishVersion($draftVersion);
// Store version number for later reuse
$versionNo = $content->versionInfo->versionNo;
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Rollback
$repository->rollback();
try {
// This call will fail with a "NotFoundException"
$this->contentService->loadContent($contentId, null, $versionNo);
} catch (NotFoundException $e) {
return;
}
$this->fail('Can still load content draft after rollback');
}
/**
* Test for the publishVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::publishVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testPublishVersion
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadVersionInfo
*/
public function testPublishVersionInTransactionWithCommit()
{
$repository = $this->getRepository();
// Load the user group content object
$template = $this->contentService->loadContent(self::ADMINISTRATORS_USER_GROUP_ID);
// Start a new transaction
$repository->beginTransaction();
try {
// Publish a new version
$content = $this->contentService->publishVersion(
$this->contentService->createContentDraft($template->contentInfo)->getVersionInfo()
);
// Store version number for later reuse
$versionNo = $content->versionInfo->versionNo;
// Commit all changes
$repository->commit();
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Load current version info
$versionInfo = $this->contentService->loadVersionInfo($content->contentInfo);
$this->assertEquals($versionNo, $versionInfo->versionNo);
}
/**
* Test for the updateContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::updateContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
*/
public function testUpdateContentInTransactionWithRollback()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::ADMINISTRATORS_USER_GROUP_ID);
// Create a new user group draft
$draft = $this->contentService->createContentDraft(
$this->contentService->loadContentInfo($contentId)
);
// Get an update struct and change the group name
$contentUpdate = $this->contentService->newContentUpdateStruct();
$contentUpdate->setField('name', self::ADMINISTRATORS_USER_GROUP_NAME, self::ENG_US);
// Start a transaction
$repository->beginTransaction();
try {
// Update the group name
$draft = $this->contentService->updateContent(
$draft->getVersionInfo(),
$contentUpdate
);
// Publish updated version
$this->contentService->publishVersion($draft->getVersionInfo());
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Rollback all changes.
$repository->rollback();
// Name will still be "Administrator users"
$name = $this->contentService->loadContent($contentId)->getFieldValue('name');
$this->assertEquals('Administrator users', $name);
}
/**
* Test for the updateContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::updateContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
*/
public function testUpdateContentInTransactionWithCommit()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::ADMINISTRATORS_USER_GROUP_ID);
// Create a new user group draft
$draft = $this->contentService->createContentDraft(
$this->contentService->loadContentInfo($contentId)
);
// Get an update struct and change the group name
$contentUpdate = $this->contentService->newContentUpdateStruct();
$contentUpdate->setField('name', self::ADMINISTRATORS_USER_GROUP_NAME, self::ENG_US);
// Start a transaction
$repository->beginTransaction();
try {
// Update the group name
$draft = $this->contentService->updateContent(
$draft->getVersionInfo(),
$contentUpdate
);
// Publish updated version
$this->contentService->publishVersion($draft->getVersionInfo());
// Commit all changes.
$repository->commit();
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Name is now "Administrators"
$name = $this->contentService->loadContent($contentId)->getFieldValue('name', self::ENG_US);
$this->assertEquals(self::ADMINISTRATORS_USER_GROUP_NAME, $name);
}
/**
* Test for the updateContentMetadata() method.
*
* @see \eZ\Publish\API\Repository\ContentService::updateContentMetadata()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContentMetadata
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
*/
public function testUpdateContentMetadataInTransactionWithRollback()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::ADMINISTRATORS_USER_GROUP_ID);
// Load a ContentInfo object
$contentInfo = $this->contentService->loadContentInfo($contentId);
// Store remoteId for later testing
$remoteId = $contentInfo->remoteId;
// Start a transaction
$repository->beginTransaction();
try {
// Get metadata update struct and change remoteId
$metadataUpdate = $this->contentService->newContentMetadataUpdateStruct();
$metadataUpdate->remoteId = md5(microtime(true));
// Update the metadata of the published content object
$this->contentService->updateContentMetadata(
$contentInfo,
$metadataUpdate
);
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Rollback all changes.
$repository->rollback();
// Load current remoteId
$remoteIdReloaded = $this->contentService->loadContentInfo($contentId)->remoteId;
$this->assertEquals($remoteId, $remoteIdReloaded);
}
/**
* Test for the updateContentMetadata() method.
*
* @see \eZ\Publish\API\Repository\ContentService::updateContentMetadata()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testUpdateContentMetadata
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
*/
public function testUpdateContentMetadataInTransactionWithCommit()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::ADMINISTRATORS_USER_GROUP_ID);
// Load a ContentInfo object
$contentInfo = $this->contentService->loadContentInfo($contentId);
// Store remoteId for later testing
$remoteId = $contentInfo->remoteId;
// Start a transaction
$repository->beginTransaction();
try {
// Get metadata update struct and change remoteId
$metadataUpdate = $this->contentService->newContentMetadataUpdateStruct();
$metadataUpdate->remoteId = md5(microtime(true));
// Update the metadata of the published content object
$this->contentService->updateContentMetadata(
$contentInfo,
$metadataUpdate
);
// Commit all changes.
$repository->commit();
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Load current remoteId
$remoteIdReloaded = $this->contentService->loadContentInfo($contentId)->remoteId;
$this->assertNotEquals($remoteId, $remoteIdReloaded);
}
/**
* Test for the updateContentMetadata() method, and how cache + transactions play together.
*
* @see \eZ\Publish\API\Repository\ContentService::updateContentMetadata()
* @depends testUpdateContentMetadata
* @depends testLoadContentInfo
*/
public function testUpdateContentMetadataCheckWithinTransaction()
{
$repository = $this->getRepository();
$contentService = $repository->getContentService();
$contentId = $this->generateId('object', 12);
// Load a ContentInfo object, and warmup cache
$contentInfo = $contentService->loadContentInfo($contentId);
// Store remoteId for later testing
$remoteId = $contentInfo->remoteId;
// Start a transaction
$repository->beginTransaction();
try {
// Get metadata update struct and change remoteId
$metadataUpdate = $contentService->newContentMetadataUpdateStruct();
$metadataUpdate->remoteId = md5(microtime(true));
// Update the metadata of the published content object
$contentService->updateContentMetadata(
$contentInfo,
$metadataUpdate
);
// Check that it's been updated
$remoteIdReloaded = $contentService->loadContentInfo($contentId)->remoteId;
$this->assertNotEquals($remoteId, $remoteIdReloaded);
// Commit all changes.
$repository->commit();
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
}
/**
* Test for the deleteVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::deleteVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentDrafts
*/
public function testDeleteVersionInTransactionWithRollback()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::ADMINISTRATORS_USER_GROUP_ID);
// Start a new transaction
$repository->beginTransaction();
try {
// Create a new draft
$draft = $this->contentService->createContentDraft(
$this->contentService->loadContentInfo($contentId)
);
$this->contentService->deleteVersion($draft->getVersionInfo());
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Rollback all changes.
$repository->rollback();
// This array will be empty
$drafts = $this->contentService->loadContentDrafts();
$this->assertSame([], $drafts);
}
/**
* Test for the deleteVersion() method.
*
* @see \eZ\Publish\API\Repository\ContentService::deleteVersion()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCreateContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentDrafts
*/
public function testDeleteVersionInTransactionWithCommit()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::ADMINISTRATORS_USER_GROUP_ID);
// Start a new transaction
$repository->beginTransaction();
try {
// Create a new draft
$draft = $this->contentService->createContentDraft(
$this->contentService->loadContentInfo($contentId)
);
$this->contentService->deleteVersion($draft->getVersionInfo());
// Commit all changes.
$repository->commit();
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// This array will contain no element
$drafts = $this->contentService->loadContentDrafts();
$this->assertSame([], $drafts);
}
/**
* Test for the deleteContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::deleteContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testDeleteContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
*/
public function testDeleteContentInTransactionWithRollback()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::MEMBERS_USER_GROUP_ID);
// Load a ContentInfo instance
$contentInfo = $this->contentService->loadContentInfo($contentId);
// Start a new transaction
$repository->beginTransaction();
try {
// Delete content object
$this->contentService->deleteContent($contentInfo);
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Rollback all changes
$repository->rollback();
// This call will return the original content object
$contentInfo = $this->contentService->loadContentInfo($contentId);
$this->assertEquals($contentId, $contentInfo->id);
}
/**
* Test for the deleteContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::deleteContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testDeleteContent
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testLoadContentInfo
*/
public function testDeleteContentInTransactionWithCommit()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::MEMBERS_USER_GROUP_ID);
// Load a ContentInfo instance
$contentInfo = $this->contentService->loadContentInfo($contentId);
// Start a new transaction
$repository->beginTransaction();
try {
// Delete content object
$this->contentService->deleteContent($contentInfo);
// Commit all changes
$repository->commit();
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Deleted content info is not found anymore
try {
$this->contentService->loadContentInfo($contentId);
} catch (NotFoundException $e) {
return;
}
$this->fail('Can still load ContentInfo after commit.');
}
/**
* Test for the copyContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::copyContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCopyContent
* @depend(s) eZ\Publish\API\Repository\Tests\LocationServiceTest::testNewLocationCreateStruct
* @depend(s) eZ\Publish\API\Repository\Tests\LocationServiceTest::testLoadLocationChildren
* @depend(s) eZ\Publish\API\Repository\Tests\LocationServiceTest::testLoadLocation
*/
public function testCopyContentInTransactionWithRollback()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::MEMBERS_USER_GROUP_ID);
$locationId = $this->generateId('location', self::ADMINISTRATORS_USER_GROUP_LOCATION_ID);
// Load content object to copy
$content = $this->contentService->loadContent($contentId);
// Create new target location
$locationCreate = $this->locationService->newLocationCreateStruct($locationId);
// Start a new transaction
$repository->beginTransaction();
try {
// Copy content with all versions and drafts
$this->contentService->copyContent(
$content->contentInfo,
$locationCreate
);
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
// Rollback all changes
$repository->rollback();
$this->refreshSearch($repository);
// This array will only contain a single admin user object
$locations = $this->locationService->loadLocationChildren(
$this->locationService->loadLocation($locationId)
)->locations;
$this->assertCount(1, $locations);
}
/**
* Test for the copyContent() method.
*
* @see \eZ\Publish\API\Repository\ContentService::copyContent()
* @depends eZ\Publish\API\Repository\Tests\ContentServiceTest::testCopyContent
* @depend(s) eZ\Publish\API\Repository\Tests\LocationServiceTest::testNewLocationCreateStruct
* @depend(s) eZ\Publish\API\Repository\Tests\LocationServiceTest::testLoadLocationChildren
* @depend(s) eZ\Publish\API\Repository\Tests\LocationServiceTest::testLoadLocation
*/
public function testCopyContentInTransactionWithCommit()
{
$repository = $this->getRepository();
$contentId = $this->generateId('object', self::MEMBERS_USER_GROUP_ID);
$locationId = $this->generateId('location', self::ADMINISTRATORS_USER_GROUP_LOCATION_ID);
// Load content object to copy
$content = $this->contentService->loadContent($contentId);
// Create new target location
$locationCreate = $this->locationService->newLocationCreateStruct($locationId);
// Start a new transaction
$repository->beginTransaction();
try {
// Copy content with all versions and drafts
$this->contentService->copyContent(
$content->contentInfo,
$locationCreate
);
// Commit all changes
$repository->commit();
} catch (Exception $e) {
// Cleanup hanging transaction on error
$repository->rollback();
throw $e;
}
$this->refreshSearch($repository);
// This will contain the admin user and the new child location
$locations = $this->locationService->loadLocationChildren(
$this->locationService->loadLocation($locationId)
)->locations;
$this->assertCount(2, $locations);
}
public function testURLAliasesCreatedForNewContent()
{
$urlAliasService = $this->getRepository()->getURLAliasService();
$draft = $this->createContentDraftVersion1();
// Automatically creates a new URLAlias for the content
$liveContent = $this->contentService->publishVersion($draft->getVersionInfo());
$location = $this->locationService->loadLocation(
$liveContent->getVersionInfo()->getContentInfo()->mainLocationId
);
$aliases = $urlAliasService->listLocationAliases($location, false);
$this->assertAliasesCorrect(
[
'/Design/Plain-site/An-awesome-forum' => [
'type' => URLAlias::LOCATION,
'destination' => $location->id,
'path' => '/Design/Plain-site/An-awesome-forum',
'languageCodes' => [self::ENG_US],
'isHistory' => false,
'isCustom' => false,
'forward' => false,
],
],
$aliases
);
}
public function testURLAliasesCreatedForUpdatedContent()
{
$urlAliasService = $this->getRepository()->getURLAliasService();
$draft = $this->createUpdatedDraftVersion2();
$location = $this->locationService->loadLocation(
$draft->getVersionInfo()->getContentInfo()->mainLocationId
);
// Load and assert URL aliases before publishing updated Content, so that
// SPI cache is warmed up and cache invalidation is also tested.
$aliases = $urlAliasService->listLocationAliases($location, false);
$this->assertAliasesCorrect(
[
'/Design/Plain-site/An-awesome-forum' => [
'type' => URLAlias::LOCATION,
'destination' => $location->id,
'path' => '/Design/Plain-site/An-awesome-forum',
'languageCodes' => [self::ENG_US],
'alwaysAvailable' => true,
'isHistory' => false,
'isCustom' => false,
'forward' => false,
],
],
$aliases
);
// Automatically marks old aliases for the content as history
// and creates new aliases, based on the changes
$liveContent = $this->contentService->publishVersion($draft->getVersionInfo());
$location = $this->locationService->loadLocation(
$liveContent->getVersionInfo()->getContentInfo()->mainLocationId
);
$aliases = $urlAliasService->listLocationAliases($location, false);
$this->assertAliasesCorrect(
[
'/Design/Plain-site/An-awesome-forum2' => [
'type' => URLAlias::LOCATION,
'destination' => $location->id,
'path' => '/Design/Plain-site/An-awesome-forum2',
'languageCodes' => [self::ENG_US],
'alwaysAvailable' => true,
'isHistory' => false,
'isCustom' => false,
'forward' => false,
],
'/Design/Plain-site/An-awesome-forum23' => [
'type' => URLAlias::LOCATION,
'destination' => $location->id,
'path' => '/Design/Plain-site/An-awesome-forum23',
'languageCodes' => [self::ENG_GB],
'alwaysAvailable' => true,
'isHistory' => false,
'isCustom' => false,
'forward' => false,
],
],
$aliases
);
}
public function testCustomURLAliasesNotHistorizedOnUpdatedContent()
{
$urlAliasService = $this->getRepository()->getURLAliasService();
$content = $this->createContentVersion1();
// Create a custom URL alias
$urlAliasService->createUrlAlias(
$this->locationService->loadLocation(
$content->getVersionInfo()->getContentInfo()->mainLocationId
),
'/my/fancy/story-about-ez-publish',
self::ENG_US
);
$draftVersion2 = $this->contentService->createContentDraft($content->contentInfo);
$contentUpdate = $this->contentService->newContentUpdateStruct();
$contentUpdate->initialLanguageCode = self::ENG_US;
$contentUpdate->setField('name', 'Amazing Bielefeld forum');
$draftVersion2 = $this->contentService->updateContent(
$draftVersion2->getVersionInfo(),
$contentUpdate
);
// Only marks auto-generated aliases as history
// the custom one is left untouched
$liveContent = $this->contentService->publishVersion($draftVersion2->getVersionInfo());
$location = $this->locationService->loadLocation(
$liveContent->getVersionInfo()->getContentInfo()->mainLocationId
);
$aliases = $urlAliasService->listLocationAliases($location);
$this->assertAliasesCorrect(
[
'/my/fancy/story-about-ez-publish' => [
'type' => URLAlias::LOCATION,
'destination' => $location->id,
'path' => '/my/fancy/story-about-ez-publish',
'languageCodes' => [self::ENG_US],
'isHistory' => false,
'isCustom' => true,
'forward' => false,
'alwaysAvailable' => false,
],
],
$aliases
);
}
/**
* Test to ensure that old versions are not affected by updates to newer
* drafts.
*/
public function testUpdatingDraftDoesNotUpdateOldVersions()
{
$contentVersion2 = $this->createContentVersion2();
$loadedContent1 = $this->contentService->loadContent($contentVersion2->id, null, 1);
$loadedContent2 = $this->contentService->loadContent($contentVersion2->id, null, 2);
$this->assertNotEquals(
$loadedContent1->getFieldValue('name', self::ENG_US),
$loadedContent2->getFieldValue('name', self::ENG_US)
);
}
/**
* Test scenario with writer and publisher users.
* Writer can only create content. Publisher can publish this content.
*/
public function testPublishWorkflow()
{
$this->createRoleWithPolicies('Publisher', [
['module' => 'content', 'function' => 'read'],
['module' => 'content', 'function' => 'create'],
['module' => 'content', 'function' => 'publish'],
]);
$this->createRoleWithPolicies('Writer', [
['module' => 'content', 'function' => 'read'],
['module' => 'content', 'function' => 'create'],
]);
$writerUser = $this->createCustomUserWithLogin(
'writer',
'writer@example.com',
self::WRITERS_USER_GROUP_NAME,
'Writer'
);
$publisherUser = $this->createCustomUserWithLogin(
'publisher',
'publisher@example.com',
'Publishers',
'Publisher'
);
$this->permissionResolver->setCurrentUserReference($writerUser);
$draft = $this->createContentDraftVersion1();
$this->permissionResolver->setCurrentUserReference($publisherUser);
$content = $this->contentService->publishVersion($draft->versionInfo);
$this->contentService->loadContent($content->id);
}
/**
* Test publish / content policy is required to be able to publish content.
*/
public function testPublishContentWithoutPublishPolicyThrowsException()
{
$this->createRoleWithPolicies('Writer', [
['module' => 'content', 'function' => 'read'],
['module' => 'content', 'function' => 'create'],
['module' => 'content', 'function' => 'edit'],
]);
$writerUser = $this->createCustomUserWithLogin(
'writer',
'writer@example.com',
self::WRITERS_USER_GROUP_NAME,
'Writer'
);
$this->permissionResolver->setCurrentUserReference($writerUser);
$this->expectException(CoreUnauthorizedException::class);
$this->expectExceptionMessageRegExp('/User does not have access to \'publish\' \'content\'/');
$this->createContentVersion1();
}
/**
* Test removal of the specific translation from all the Versions of a Content Object.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslation
*/
public function testDeleteTranslation()
{
$content = $this->createContentVersion2();
// create multiple versions to exceed archive limit
for ($i = 0; $i < 5; ++$i) {
$contentDraft = $this->contentService->createContentDraft($content->contentInfo);
$contentUpdateStruct = $this->contentService->newContentUpdateStruct();
$contentDraft = $this->contentService->updateContent(
$contentDraft->versionInfo,
$contentUpdateStruct
);
$this->contentService->publishVersion($contentDraft->versionInfo);
}
$this->contentService->deleteTranslation($content->contentInfo, self::ENG_GB);
$this->assertTranslationDoesNotExist(self::ENG_GB, $content->id);
}
/**
* Test deleting a Translation which is initial for some Version, updates initialLanguageCode
* with mainLanguageCode (assuming they are different).
*/
public function testDeleteTranslationUpdatesInitialLanguageCodeVersion()
{
$content = $this->createContentVersion2();
// create another, copied, version
$contentDraft = $this->contentService->updateContent(
$this->contentService->createContentDraft($content->contentInfo)->versionInfo,
$this->contentService->newContentUpdateStruct()
);
$publishedContent = $this->contentService->publishVersion($contentDraft->versionInfo);
// remove first version with only one translation as it is not the subject of this test
$this->contentService->deleteVersion(
$this->contentService->loadVersionInfo($publishedContent->contentInfo, 1)
);
// sanity check
self::assertEquals(self::ENG_US, $content->contentInfo->mainLanguageCode);
self::assertEquals(self::ENG_US, $content->versionInfo->initialLanguageCode);
// update mainLanguageCode so it is different than initialLanguageCode for Version
$contentMetadataUpdateStruct = $this->contentService->newContentMetadataUpdateStruct();
$contentMetadataUpdateStruct->mainLanguageCode = self::ENG_GB;
$content = $this->contentService->updateContentMetadata($publishedContent->contentInfo, $contentMetadataUpdateStruct);
$this->contentService->deleteTranslation($content->contentInfo, self::ENG_US);
$this->assertTranslationDoesNotExist(self::ENG_US, $content->id);
}
/**
* Test removal of the specific translation properly updates languages of the URL alias.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslation
*/
public function testDeleteTranslationUpdatesUrlAlias()
{
$urlAliasService = $this->getRepository()->getURLAliasService();
$content = $this->createContentVersion2();
$mainLocation = $this->locationService->loadLocation($content->contentInfo->mainLocationId);
// create custom URL alias for Content main Location
$urlAliasService->createUrlAlias($mainLocation, '/my-custom-url', self::ENG_GB);
// create secondary Location for Content
$secondaryLocation = $this->locationService->createLocation(
$content->contentInfo,
$this->locationService->newLocationCreateStruct(2)
);
// create custom URL alias for Content secondary Location
$urlAliasService->createUrlAlias($secondaryLocation, '/my-secondary-url', self::ENG_GB);
// delete Translation
$this->contentService->deleteTranslation($content->contentInfo, self::ENG_GB);
foreach ([$mainLocation, $secondaryLocation] as $location) {
// check auto-generated URL aliases
foreach ($urlAliasService->listLocationAliases($location, false) as $alias) {
self::assertNotContains(self::ENG_GB, $alias->languageCodes);
}
// check custom URL aliases
foreach ($urlAliasService->listLocationAliases($location) as $alias) {
self::assertNotContains(self::ENG_GB, $alias->languageCodes);
}
}
}
/**
* Test removal of a main translation throws BadStateException.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslation
*/
public function testDeleteTranslationMainLanguageThrowsBadStateException()
{
$content = $this->createContentVersion2();
// delete first version which has only one translation
$this->contentService->deleteVersion($this->contentService->loadVersionInfo($content->contentInfo, 1));
// try to delete main translation
$this->expectException(BadStateException::class);
$this->expectExceptionMessage('Specified translation is the main translation of the Content Object');
$this->contentService->deleteTranslation($content->contentInfo, $content->contentInfo->mainLanguageCode);
}
/**
* Test removal of a Translation is possible when some archived Versions have only this Translation.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslation
*/
public function testDeleteTranslationDeletesSingleTranslationVersions()
{
// content created by the createContentVersion1 method has eng-US translation only.
$content = $this->createContentVersion1();
// create new version and add eng-GB translation
$contentDraft = $this->contentService->createContentDraft($content->contentInfo);
$contentUpdateStruct = $this->contentService->newContentUpdateStruct();
$contentUpdateStruct->setField('name', 'Awesome Board', self::ENG_GB);
$contentDraft = $this->contentService->updateContent($contentDraft->versionInfo, $contentUpdateStruct);
$publishedContent = $this->contentService->publishVersion($contentDraft->versionInfo);
// update mainLanguageCode to avoid exception related to that
$contentMetadataUpdateStruct = $this->contentService->newContentMetadataUpdateStruct();
$contentMetadataUpdateStruct->mainLanguageCode = self::ENG_GB;
$content = $this->contentService->updateContentMetadata($publishedContent->contentInfo, $contentMetadataUpdateStruct);
$this->contentService->deleteTranslation($content->contentInfo, self::ENG_US);
$this->assertTranslationDoesNotExist(self::ENG_US, $content->id);
}
/**
* Test removal of the translation by the user who is not allowed to delete a content
* throws UnauthorizedException.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslation
*/
public function testDeleteTranslationThrowsUnauthorizedException()
{
$content = $this->createContentVersion2();
// create user that can read/create/edit but cannot delete content
$this->createRoleWithPolicies('Writer', [
['module' => 'content', 'function' => 'read'],
['module' => 'content', 'function' => 'versionread'],
['module' => 'content', 'function' => 'create'],
['module' => 'content', 'function' => 'edit'],
]);
$writerUser = $this->createCustomUserWithLogin(
'writer',
'writer@example.com',
self::WRITERS_USER_GROUP_NAME,
'Writer'
);
$this->permissionResolver->setCurrentUserReference($writerUser);
$this->expectException(UnauthorizedException::class);
$this->expectExceptionMessage('User does not have access to \'remove\' \'content\'');
$this->contentService->deleteTranslation($content->contentInfo, self::ENG_GB);
}
/**
* Test removal of a non-existent translation throws InvalidArgumentException.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslation
*/
public function testDeleteTranslationThrowsInvalidArgumentException()
{
// content created by the createContentVersion1 method has eng-US translation only.
$content = $this->createContentVersion1();
$this->expectException(APIInvalidArgumentException::class);
$this->expectExceptionMessage('Argument \'$languageCode\' is invalid: ger-DE does not exist in the Content item');
$this->contentService->deleteTranslation($content->contentInfo, self::GER_DE);
}
/**
* Test deleting a Translation from Draft.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslationFromDraft
*/
public function testDeleteTranslationFromDraft()
{
$languageCode = self::ENG_GB;
$content = $this->createMultipleLanguageContentVersion2();
$draft = $this->contentService->createContentDraft($content->contentInfo);
$draft = $this->contentService->deleteTranslationFromDraft($draft->versionInfo, $languageCode);
$content = $this->contentService->publishVersion($draft->versionInfo);
$loadedContent = $this->contentService->loadContent($content->id);
self::assertNotContains($languageCode, $loadedContent->versionInfo->languageCodes);
self::assertEmpty($loadedContent->getFieldsByLanguage($languageCode));
}
/**
* Get values for multilingual field.
*
* @return array
*/
public function providerForDeleteTranslationFromDraftRemovesUrlAliasOnPublishing()
{
return [
[
[self::ENG_US => 'US Name', self::ENG_GB => 'GB Name'],
],
[
[self::ENG_US => 'Same Name', self::ENG_GB => 'Same Name'],
],
];
}
/**
* Test deleting a Translation from Draft removes previously stored URL aliases for published Content.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslationFromDraft
*
* @dataProvider providerForDeleteTranslationFromDraftRemovesUrlAliasOnPublishing
*
* @param string[] $fieldValues translated field values
*
* @throws \eZ\Publish\API\Repository\Exceptions\BadStateException
* @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
* @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
* @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
*/
public function testDeleteTranslationFromDraftRemovesUrlAliasOnPublishing(array $fieldValues)
{
$urlAliasService = $this->getRepository()->getURLAliasService();
// set language code to be removed
$languageCode = self::ENG_GB;
$draft = $this->createMultilingualContentDraft(
'folder',
2,
self::ENG_US,
[
'name' => [
self::ENG_GB => $fieldValues[self::ENG_GB],
self::ENG_US => $fieldValues[self::ENG_US],
],
]
);
$content = $this->contentService->publishVersion($draft->versionInfo);
// create secondary location
$this->locationService->createLocation(
$content->contentInfo,
$this->locationService->newLocationCreateStruct(5)
);
// sanity check
$locations = $this->locationService->loadLocations($content->contentInfo);
self::assertCount(2, $locations, 'Sanity check: Expected to find 2 Locations');
foreach ($locations as $location) {
$urlAliasService->createUrlAlias($location, '/us-custom_' . $location->id, self::ENG_US);
$urlAliasService->createUrlAlias($location, '/gb-custom_' . $location->id, self::ENG_GB);
// check default URL aliases
$aliases = $urlAliasService->listLocationAliases($location, false, $languageCode);
self::assertNotEmpty($aliases, 'Sanity check: URL alias for the translation does not exist');
// check custom URL aliases
$aliases = $urlAliasService->listLocationAliases($location, true, $languageCode);
self::assertNotEmpty($aliases, 'Sanity check: Custom URL alias for the translation does not exist');
}
// delete translation and publish new version
$draft = $this->contentService->createContentDraft($content->contentInfo);
$draft = $this->contentService->deleteTranslationFromDraft($draft->versionInfo, $languageCode);
$this->contentService->publishVersion($draft->versionInfo);
// check that aliases does not exist
foreach ($locations as $location) {
// check default URL aliases
$aliases = $urlAliasService->listLocationAliases($location, false, $languageCode);
self::assertEmpty($aliases, 'URL alias for the deleted translation still exists');
// check custom URL aliases
$aliases = $urlAliasService->listLocationAliases($location, true, $languageCode);
self::assertEmpty($aliases, 'Custom URL alias for the deleted translation still exists');
}
}
/**
* Test that URL aliases for deleted Translations are properly archived.
*/
public function testDeleteTranslationFromDraftArchivesUrlAliasOnPublishing()
{
$urlAliasService = $this->getRepository()->getURLAliasService();
$content = $this->contentService->publishVersion(
$this->createMultilingualContentDraft(
'folder',
2,
self::ENG_US,
[
'name' => [
self::ENG_GB => 'BritishEnglishContent',
self::ENG_US => 'AmericanEnglishContent',
],
]
)->versionInfo
);
$unrelatedContent = $this->contentService->publishVersion(
$this->createMultilingualContentDraft(
'folder',
2,
self::ENG_US,
[
'name' => [
self::ENG_GB => 'AnotherBritishContent',
self::ENG_US => 'AnotherAmericanContent',
],
]
)->versionInfo
);
$urlAlias = $urlAliasService->lookup('/BritishEnglishContent');
self::assertFalse($urlAlias->isHistory);
self::assertEquals($urlAlias->path, '/BritishEnglishContent');
self::assertEquals($urlAlias->destination, $content->contentInfo->mainLocationId);
$draft = $this->contentService->deleteTranslationFromDraft(
$this->contentService->createContentDraft($content->contentInfo)->versionInfo,
self::ENG_GB
);
$content = $this->contentService->publishVersion($draft->versionInfo);
$urlAlias = $urlAliasService->lookup('/BritishEnglishContent');
self::assertTrue($urlAlias->isHistory);
self::assertEquals($urlAlias->path, '/BritishEnglishContent');
self::assertEquals($urlAlias->destination, $content->contentInfo->mainLocationId);
$unrelatedUrlAlias = $urlAliasService->lookup('/AnotherBritishContent');
self::assertFalse($unrelatedUrlAlias->isHistory);
self::assertEquals($unrelatedUrlAlias->path, '/AnotherBritishContent');
self::assertEquals($unrelatedUrlAlias->destination, $unrelatedContent->contentInfo->mainLocationId);
}
/**
* Test deleting a Translation from Draft which has single Translation throws BadStateException.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslationFromDraft
*/
public function testDeleteTranslationFromDraftThrowsBadStateExceptionOnSingleTranslation()
{
// create Content with single Translation
$publishedContent = $this->contentService->publishVersion(
$this->createContentDraft(
self::FORUM_IDENTIFIER,
2,
['name' => 'Eng-US Version name']
)->versionInfo
);
// update mainLanguageCode to avoid exception related to trying to delete main Translation
$contentMetadataUpdateStruct = $this->contentService->newContentMetadataUpdateStruct();
$contentMetadataUpdateStruct->mainLanguageCode = self::ENG_GB;
$publishedContent = $this->contentService->updateContentMetadata(
$publishedContent->contentInfo,
$contentMetadataUpdateStruct
);
// create single Translation Version from the first one
$draft = $this->contentService->createContentDraft(
$publishedContent->contentInfo,
$publishedContent->versionInfo
);
$this->expectException(BadStateException::class);
$this->expectExceptionMessage('Specified Translation is the only one Content Object Version has');
// attempt to delete Translation
$this->contentService->deleteTranslationFromDraft($draft->versionInfo, self::ENG_US);
}
/**
* Test deleting the Main Translation from Draft throws BadStateException.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslationFromDraft
*/
public function testDeleteTranslationFromDraftThrowsBadStateExceptionOnMainTranslation()
{
$mainLanguageCode = self::ENG_US;
$draft = $this->createMultilingualContentDraft(
self::FORUM_IDENTIFIER,
2,
$mainLanguageCode,
[
'name' => [
self::ENG_US => 'An awesome eng-US forum',
self::ENG_GB => 'An awesome eng-GB forum',
],
]
);
$this->expectException(BadStateException::class);
$this->expectExceptionMessage('Specified Translation is the main Translation of the Content Object');
$this->contentService->deleteTranslationFromDraft($draft->versionInfo, $mainLanguageCode);
}
/**
* Test deleting the Translation from Published Version throws BadStateException.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslationFromDraft
*/
public function testDeleteTranslationFromDraftThrowsBadStateExceptionOnPublishedVersion()
{
$languageCode = self::ENG_US;
$content = $this->createMultipleLanguageContentVersion2();
$draft = $this->contentService->createContentDraft($content->contentInfo);
$publishedContent = $this->contentService->publishVersion($draft->versionInfo);
$this->expectException(BadStateException::class);
$this->expectExceptionMessage('Version is not a draft');
$this->contentService->deleteTranslationFromDraft($publishedContent->versionInfo, $languageCode);
}
/**
* Test deleting a Translation from Draft throws UnauthorizedException if user cannot edit Content.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslationFromDraft
*/
public function testDeleteTranslationFromDraftThrowsUnauthorizedException()
{
$languageCode = self::ENG_GB;
$content = $this->createMultipleLanguageContentVersion2();
$draft = $this->contentService->createContentDraft($content->contentInfo);
// create user that can read/create/delete but cannot edit or content
$this->createRoleWithPolicies('Writer', [
['module' => 'content', 'function' => 'read'],
['module' => 'content', 'function' => 'versionread'],
['module' => 'content', 'function' => 'create'],
['module' => 'content', 'function' => 'delete'],
]);
$writerUser = $this->createCustomUserWithLogin(
'user',
'user@example.com',
self::WRITERS_USER_GROUP_NAME,
'Writer'
);
$this->permissionResolver->setCurrentUserReference($writerUser);
$this->expectException(UnauthorizedException::class);
$this->expectExceptionMessage('User does not have access to \'edit\' \'content\'');
$this->contentService->deleteTranslationFromDraft($draft->versionInfo, $languageCode);
}
/**
* Test deleting a non-existent Translation from Draft throws InvalidArgumentException.
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteTranslationFromDraft
*/
public function testDeleteTranslationFromDraftThrowsInvalidArgumentException()
{
$languageCode = self::GER_DE;
$content = $this->createMultipleLanguageContentVersion2();
$draft = $this->contentService->createContentDraft($content->contentInfo);
$this->expectException(APIInvalidArgumentException::class);
$this->expectExceptionMessageRegExp('/The Version \(ContentId=\d+, VersionNo=\d+\) is not translated into ger-DE/');
$this->contentService->deleteTranslationFromDraft($draft->versionInfo, $languageCode);
}
/**
* Test loading list of Content items.
*/
public function testLoadContentListByContentInfo()
{
$allLocationsCount = $this->locationService->getAllLocationsCount();
$contentInfoList = array_map(
function (Location $location) {
return $location->contentInfo;
},
$this->locationService->loadAllLocations(0, $allLocationsCount)
);
$contentList = $this->contentService->loadContentListByContentInfo($contentInfoList);
self::assertCount(count($contentInfoList), $contentList);
foreach ($contentList as $content) {
try {
$loadedContent = $this->contentService->loadContent($content->id);
self::assertEquals($loadedContent, $content, "Failed to properly bulk-load Content {$content->id}");
} catch (NotFoundException $e) {
self::fail("Failed to load Content {$content->id}: {$e->getMessage()}");
} catch (UnauthorizedException $e) {
self::fail("Failed to load Content {$content->id}: {$e->getMessage()}");
}
}
}
/**
* Test loading content versions after removing exactly two drafts.
*
* @see https://jira.ez.no/browse/EZP-30271
*
* @covers \eZ\Publish\Core\Repository\ContentService::deleteVersion
*/
public function testLoadVersionsAfterDeletingTwoDrafts()
{
$content = $this->createFolder([self::ENG_GB => 'Foo'], 2);
// First update and publish
$modifiedContent = $this->updateFolder($content, [self::ENG_GB => 'Foo1']);
$content = $this->contentService->publishVersion($modifiedContent->versionInfo);
// Second update and publish
$modifiedContent = $this->updateFolder($content, [self::ENG_GB => 'Foo2']);
$content = $this->contentService->publishVersion($modifiedContent->versionInfo);
// Create drafts
$this->updateFolder($content, [self::ENG_GB => 'Foo3']);
$this->updateFolder($content, [self::ENG_GB => 'Foo4']);
$versions = $this->contentService->loadVersions($content->contentInfo);
foreach ($versions as $key => $version) {
if ($version->isDraft()) {
$this->contentService->deleteVersion($version);
unset($versions[$key]);
}
}
$this->assertEquals($versions, $this->contentService->loadVersions($content->contentInfo));
}
/**
* Tests loading list of content versions of status draft.
*/
public function testLoadVersionsOfStatusDraft()
{
$content = $this->createContentVersion1();
$this->contentService->createContentDraft($content->contentInfo);
$this->contentService->createContentDraft($content->contentInfo);
$this->contentService->createContentDraft($content->contentInfo);
$versions = $this->contentService->loadVersions($content->contentInfo, VersionInfo::STATUS_DRAFT);
$this->assertSame(\count($versions), 3);
}
/**
* Tests loading list of content versions of status archived.
*/
public function testLoadVersionsOfStatusArchived()
{
$content = $this->createContentVersion1();
$draft1 = $this->contentService->createContentDraft($content->contentInfo);
$this->contentService->publishVersion($draft1->versionInfo);
$draft2 = $this->contentService->createContentDraft($content->contentInfo);
$this->contentService->publishVersion($draft2->versionInfo);
$versions = $this->contentService->loadVersions($content->contentInfo, VersionInfo::STATUS_ARCHIVED);
$this->assertSame(\count($versions), 2);
}
/**
* Asserts that all aliases defined in $expectedAliasProperties with the
* given properties are available in $actualAliases and not more.
*
* @param array $expectedAliasProperties
* @param array $actualAliases
*/
private function assertAliasesCorrect(array $expectedAliasProperties, array $actualAliases)
{
foreach ($actualAliases as $actualAlias) {
if (!isset($expectedAliasProperties[$actualAlias->path])) {
$this->fail(
sprintf(
'Alias with path "%s" in languages "%s" not expected.',
$actualAlias->path,
implode(', ', $actualAlias->languageCodes)
)
);
}
foreach ($expectedAliasProperties[$actualAlias->path] as $propertyName => $propertyValue) {
$this->assertEquals(
$propertyValue,
$actualAlias->$propertyName,
sprintf(
'Property $%s incorrect on alias with path "%s" in languages "%s".',
$propertyName,
$actualAlias->path,
implode(', ', $actualAlias->languageCodes)
)
);
}
unset($expectedAliasProperties[$actualAlias->path]);
}
if (!empty($expectedAliasProperties)) {
$this->fail(
sprintf(
'Missing expected aliases with paths "%s".',
implode('", "', array_keys($expectedAliasProperties))
)
);
}
}
/**
* Asserts that the given fields are equal to the default fields fixture.
*
* @param \eZ\Publish\API\Repository\Values\Content\Field[] $fields
*/
private function assertAllFieldsEquals(array $fields)
{
$actual = $this->normalizeFields($fields);
$expected = $this->normalizeFields($this->createFieldsFixture());
$this->assertEquals($expected, $actual);
}
/**
* Asserts that the given fields are equal to a language filtered set of the
* default fields fixture.
*
* @param \eZ\Publish\API\Repository\Values\Content\Field[] $fields
* @param string $languageCode
*/
private function assertLocaleFieldsEquals(array $fields, $languageCode)
{
$actual = $this->normalizeFields($fields);
$expected = [];
foreach ($this->normalizeFields($this->createFieldsFixture()) as $field) {
if ($field->languageCode !== $languageCode) {
continue;
}
$expected[] = $field;
}
$this->assertEquals($expected, $actual);
}
/**
* This method normalizes a set of fields and returns a normalized set.
*
* Normalization means it resets the storage specific field id to zero and
* it sorts the field by their identifier and their language code. In
* addition, the field value is removed, since this one depends on the
* specific FieldType, which is tested in a dedicated integration test.
*
* @param \eZ\Publish\API\Repository\Values\Content\Field[] $fields
*
* @return \eZ\Publish\API\Repository\Values\Content\Field[]
*/
private function normalizeFields(array $fields)
{
$normalized = [];
foreach ($fields as $field) {
$normalized[] = new Field(
[
'id' => 0,
'value' => $field->value !== null,
'languageCode' => $field->languageCode,
'fieldDefIdentifier' => $field->fieldDefIdentifier,
'fieldTypeIdentifier' => $field->fieldTypeIdentifier,
]
);
}
usort(
$normalized,
function ($field1, $field2) {
if (0 === ($return = strcasecmp($field1->fieldDefIdentifier, $field2->fieldDefIdentifier))) {
return strcasecmp($field1->languageCode, $field2->languageCode);
}
return $return;
}
);
return $normalized;
}
/**
* Asserts that given Content has default ContentStates.
*
* @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
*/
private function assertDefaultContentStates(ContentInfo $contentInfo)
{
$objectStateService = $this->getRepository()->getObjectStateService();
$objectStateGroups = $objectStateService->loadObjectStateGroups();
foreach ($objectStateGroups as $objectStateGroup) {
$contentState = $objectStateService->getContentState($contentInfo, $objectStateGroup);
foreach ($objectStateService->loadObjectStates($objectStateGroup) as $objectState) {
// Only check the first object state which is the default one.
$this->assertEquals(
$objectState,
$contentState
);
break;
}
}
}
/**
* Assert that given Content has no references to a translation specified by the $languageCode.
*
* @param string $languageCode
* @param int $contentId
*/
private function assertTranslationDoesNotExist($languageCode, $contentId)
{
$content = $this->contentService->loadContent($contentId);
foreach ($content->fields as $field) {
/** @var array $field */
self::assertArrayNotHasKey($languageCode, $field);
self::assertNotEquals($languageCode, $content->contentInfo->mainLanguageCode);
self::assertArrayNotHasKey($languageCode, $content->versionInfo->getNames());
self::assertNotEquals($languageCode, $content->versionInfo->initialLanguageCode);
self::assertNotContains($languageCode, $content->versionInfo->languageCodes);
}
foreach ($this->contentService->loadVersions($content->contentInfo) as $versionInfo) {
self::assertArrayNotHasKey($languageCode, $versionInfo->getNames());
self::assertNotEquals($languageCode, $versionInfo->contentInfo->mainLanguageCode);
self::assertNotEquals($languageCode, $versionInfo->initialLanguageCode);
self::assertNotContains($languageCode, $versionInfo->languageCodes);
}
}
/**
* Returns the default fixture of fields used in most tests.
*
* @return \eZ\Publish\API\Repository\Values\Content\Field[]
*/
private function createFieldsFixture()
{
return [
new Field(
[
'id' => 0,
'value' => 'An awesome multi-lang forum²',
'languageCode' => self::ENG_US,
'fieldDefIdentifier' => 'name',
'fieldTypeIdentifier' => 'ezstring',
]
),
new Field(
[
'id' => 0,
'value' => 'An awesome multi-lang forum²³',
'languageCode' => self::ENG_GB,
'fieldDefIdentifier' => 'name',
'fieldTypeIdentifier' => 'ezstring',
]
),
];
}
/**
* Gets expected property values for the "Media" ContentInfo ValueObject.
*
* @return array
*/
private function getExpectedMediaContentInfoProperties()
{
return [
'id' => self::MEDIA_CONTENT_ID,
'contentTypeId' => 1,
'name' => 'Media',
'sectionId' => 3,
'currentVersionNo' => 1,
'published' => true,
'ownerId' => 14,
'modificationDate' => $this->createDateTime(1060695457),
'publishedDate' => $this->createDateTime(1060695457),
'alwaysAvailable' => 1,
'remoteId' => self::MEDIA_REMOTE_ID,
'mainLanguageCode' => self::ENG_US,
'mainLocationId' => 43,
'status' => ContentInfo::STATUS_PUBLISHED,
];
}
/**
* @covers \eZ\Publish\API\Repository\ContentService::hideContent
*
* @throws \eZ\Publish\API\Repository\Exceptions\BadStateException
* @throws \eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException
* @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException
* @throws \eZ\Publish\API\Repository\Exceptions\ForbiddenException
* @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
* @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
* @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
*/
public function testHideContent(): void
{
$contentTypeService = $this->getRepository()->getContentTypeService();
$locationCreateStructs = array_map(
function (Location $parentLocation) {
return $this->locationService->newLocationCreateStruct($parentLocation->id);
},
$this->createParentLocationsForHideReveal(2)
);
$contentType = $contentTypeService->loadContentTypeByIdentifier('folder');
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate->setField('name', 'Folder to hide');
$content = $this->contentService->createContent(
$contentCreate,
$locationCreateStructs
);
$publishedContent = $this->contentService->publishVersion($content->versionInfo);
$locations = $this->locationService->loadLocations($publishedContent->contentInfo);
// Sanity check
$this->assertCount(3, $locations);
$this->assertCount(0, $this->filterHiddenLocations($locations));
$this->contentService->hideContent($publishedContent->contentInfo);
$locations = $this->locationService->loadLocations($publishedContent->contentInfo);
$this->assertCount(3, $locations);
$this->assertCount(3, $this->filterHiddenLocations($locations));
}
/**
* @covers \eZ\Publish\API\Repository\ContentService::revealContent
*
* @throws \eZ\Publish\API\Repository\Exceptions\ForbiddenException
* @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
* @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
*/
public function testRevealContent()
{
$contentTypeService = $this->getRepository()->getContentTypeService();
$locationCreateStructs = array_map(
function (Location $parentLocation) {
return $this->locationService->newLocationCreateStruct($parentLocation->id);
},
$this->createParentLocationsForHideReveal(2)
);
$contentType = $contentTypeService->loadContentTypeByIdentifier('folder');
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate->setField('name', 'Folder to hide');
$locationCreateStructs[0]->hidden = true;
$content = $this->contentService->createContent(
$contentCreate,
$locationCreateStructs
);
$publishedContent = $this->contentService->publishVersion($content->versionInfo);
$locations = $this->locationService->loadLocations($publishedContent->contentInfo);
// Sanity check
$hiddenLocations = $this->filterHiddenLocations($locations);
$this->assertCount(3, $locations);
$this->assertCount(1, $hiddenLocations);
$this->contentService->hideContent($publishedContent->contentInfo);
$this->assertCount(
3,
$this->filterHiddenLocations(
$this->locationService->loadLocations($publishedContent->contentInfo)
)
);
$this->contentService->revealContent($publishedContent->contentInfo);
$locations = $this->locationService->loadLocations($publishedContent->contentInfo);
$hiddenLocationsAfterReveal = $this->filterHiddenLocations($locations);
$this->assertCount(3, $locations);
$this->assertCount(1, $hiddenLocationsAfterReveal);
$this->assertEquals($hiddenLocations, $hiddenLocationsAfterReveal);
}
/**
* @depends testRevealContent
*/
public function testRevealContentWithHiddenParent()
{
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier('folder');
$contentNames = [
'Parent Content',
'Child (Nesting 1)',
'Child (Nesting 2)',
'Child (Nesting 3)',
'Child (Nesting 4)',
];
$parentLocation = $this->locationService->newLocationCreateStruct(
$this->generateId('location', 2)
);
/** @var Content[] $contents */
$contents = [];
foreach ($contentNames as $contentName) {
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate->setField('name', $contentName);
$content = $this->contentService->createContent($contentCreate, [$parentLocation]);
$contents[] = $publishedContent = $this->contentService->publishVersion($content->versionInfo);
$parentLocation = $this->locationService->newLocationCreateStruct(
$this->generateId('location', $publishedContent->contentInfo->mainLocationId)
);
}
$this->contentService->hideContent($contents[0]->contentInfo);
$this->contentService->hideContent($contents[2]->contentInfo);
$this->contentService->revealContent($contents[2]->contentInfo);
$parentContent = $this->contentService->loadContent($contents[0]->id);
$parentLocation = $this->locationService->loadLocation($parentContent->contentInfo->mainLocationId);
$parentSublocations = $this->locationService->loadLocationList([
$contents[1]->contentInfo->mainLocationId,
$contents[2]->contentInfo->mainLocationId,
$contents[3]->contentInfo->mainLocationId,
$contents[4]->contentInfo->mainLocationId,
]);
// Parent remains invisible
self::assertTrue($parentLocation->invisible);
// All parent sublocations remain invisible as well
foreach ($parentSublocations as $parentSublocation) {
self::assertTrue($parentSublocation->invisible);
}
}
/**
* @depends testRevealContent
*/
public function testRevealContentWithHiddenChildren()
{
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier('folder');
$contentNames = [
'Parent Content',
'Child (Nesting 1)',
'Child (Nesting 2)',
'Child (Nesting 3)',
'Child (Nesting 4)',
];
$parentLocation = $this->locationService->newLocationCreateStruct(
$this->generateId('location', 2)
);
/** @var Content[] $contents */
$contents = [];
foreach ($contentNames as $contentName) {
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate->setField('name', $contentName);
$content = $this->contentService->createContent($contentCreate, [$parentLocation]);
$contents[] = $publishedContent = $this->contentService->publishVersion($content->versionInfo);
$parentLocation = $this->locationService->newLocationCreateStruct(
$this->generateId('location', $publishedContent->contentInfo->mainLocationId)
);
}
$this->contentService->hideContent($contents[0]->contentInfo);
$this->contentService->hideContent($contents[2]->contentInfo);
$this->contentService->revealContent($contents[0]->contentInfo);
$directChildContent = $this->contentService->loadContent($contents[1]->id);
$directChildLocation = $this->locationService->loadLocation($directChildContent->contentInfo->mainLocationId);
$childContent = $this->contentService->loadContent($contents[2]->id);
$childLocation = $this->locationService->loadLocation($childContent->contentInfo->mainLocationId);
$childSublocations = $this->locationService->loadLocationList([
$contents[3]->contentInfo->mainLocationId,
$contents[4]->contentInfo->mainLocationId,
]);
// Direct child content is not hidden
self::assertFalse($directChildContent->contentInfo->isHidden);
// Direct child content location is still invisible
self::assertFalse($directChildLocation->invisible);
// Child content is still hidden
self::assertTrue($childContent->contentInfo->isHidden);
// Child content location is still invisible
self::assertTrue($childLocation->invisible);
// All childs sublocations remain invisible as well
foreach ($childSublocations as $childSublocation) {
self::assertTrue($childSublocation->invisible);
}
}
public function testHideContentWithParentLocation()
{
$contentTypeService = $this->getRepository()->getContentTypeService();
$contentType = $contentTypeService->loadContentTypeByIdentifier('folder');
$contentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$contentCreate->setField('name', 'Parent');
$content = $this->contentService->createContent(
$contentCreate,
[
$this->locationService->newLocationCreateStruct(
$this->generateId('location', 2)
),
]
);
$publishedContent = $this->contentService->publishVersion($content->versionInfo);
$this->contentService->hideContent($publishedContent->contentInfo);
$locations = $this->locationService->loadLocations($publishedContent->contentInfo);
$childContentCreate = $this->contentService->newContentCreateStruct($contentType, self::ENG_US);
$childContentCreate->setField('name', 'Child');
$childContent = $this->contentService->createContent(
$childContentCreate,
[
$this->locationService->newLocationCreateStruct(
$locations[0]->id
),
]
);
$publishedChildContent = $this->contentService->publishVersion($childContent->versionInfo);
$childLocations = $this->locationService->loadLocations($publishedChildContent->contentInfo);
$this->assertTrue($locations[0]->hidden);
$this->assertTrue($locations[0]->invisible);
$this->assertFalse($childLocations[0]->hidden);
$this->assertTrue($childLocations[0]->invisible);
}
public function testChangeContentName()
{
$contentDraft = $this->createContentDraft(
'folder',
$this->generateId('location', 2),
[
'name' => 'Marco',
]
);
$publishedContent = $this->contentService->publishVersion($contentDraft->versionInfo);
$contentMetadataUpdateStruct = new ContentMetadataUpdateStruct([
'name' => 'Polo',
]);
$this->contentService->updateContentMetadata($publishedContent->contentInfo, $contentMetadataUpdateStruct);
$updatedContent = $this->contentService->loadContent($publishedContent->id);
$this->assertEquals('Marco', $publishedContent->contentInfo->name);
$this->assertEquals('Polo', $updatedContent->contentInfo->name);
}
public function testCopyTranslationsFromPublishedToDraft()
{
$contentDraft = $this->createContentDraft(
'folder',
$this->generateId('location', 2),
[
'name' => 'Folder US',
]
);
$publishedContent = $this->contentService->publishVersion($contentDraft->versionInfo);
$deDraft = $this->contentService->createContentDraft($publishedContent->contentInfo);
$contentUpdateStruct = new ContentUpdateStruct([
'initialLanguageCode' => self::GER_DE,
'fields' => $contentDraft->getFields(),
]);
$contentUpdateStruct->setField('name', 'Folder GER', self::GER_DE);
$deContent = $this->contentService->updateContent($deDraft->versionInfo, $contentUpdateStruct);
$updatedContent = $this->contentService->loadContent($deContent->id, null, $deContent->versionInfo->versionNo);
$this->assertEquals(
[
self::ENG_US => 'Folder US',
self::GER_DE => 'Folder GER',
],
$updatedContent->fields['name']
);
$gbDraft = $this->contentService->createContentDraft($publishedContent->contentInfo);
$contentUpdateStruct = new ContentUpdateStruct([
'initialLanguageCode' => self::ENG_GB,
'fields' => $contentDraft->getFields(),
]);
$contentUpdateStruct->setField('name', 'Folder GB', self::ENG_GB);
$gbContent = $this->contentService->updateContent($gbDraft->versionInfo, $contentUpdateStruct);
$this->contentService->publishVersion($gbDraft->versionInfo);
$updatedContent = $this->contentService->loadContent($gbContent->id, null, $gbContent->versionInfo->versionNo);
$this->assertEquals(
[
self::ENG_US => 'Folder US',
self::ENG_GB => 'Folder GB',
],
$updatedContent->fields['name']
);
$dePublished = $this->contentService->publishVersion($deDraft->versionInfo);
$this->assertEquals(
[
self::ENG_US => 'Folder US',
self::GER_DE => 'Folder GER',
self::ENG_GB => 'Folder GB',
],
$dePublished->fields['name']
);
}
/**
* Create structure of parent folders with Locations to be used for Content hide/reveal tests.
*
* @param int $parentLocationId
*
* @return \eZ\Publish\API\Repository\Values\Content\Location[] A list of Locations aimed to be parents
*
* @throws \eZ\Publish\API\Repository\Exceptions\ForbiddenException
* @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
* @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
*/
private function createParentLocationsForHideReveal(int $parentLocationId): array
{
$parentFoldersLocationsIds = [
$this->createFolder([self::ENG_US => 'P1'], $parentLocationId)->contentInfo->mainLocationId,
$this->createFolder([self::ENG_US => 'P2'], $parentLocationId)->contentInfo->mainLocationId,
$this->createFolder([self::ENG_US => 'P3'], $parentLocationId)->contentInfo->mainLocationId,
];
return array_values($this->locationService->loadLocationList($parentFoldersLocationsIds));
}
/**
* Filter Locations list by hidden only.
*
* @param \eZ\Publish\API\Repository\Values\Content\Location[] $locations
*
* @return array
*/
private function filterHiddenLocations(array $locations): array
{
return array_values(
array_filter(
$locations,
function (Location $location) {
return $location->hidden;
}
)
);
}
public function testPublishVersionWithSelectedLanguages()
{
$publishedContent = $this->createFolder(
[
self::ENG_US => 'Published US',
self::GER_DE => 'Published DE',
],
$this->generateId('location', 2)
);
$draft = $this->contentService->createContentDraft($publishedContent->contentInfo);
$contentUpdateStruct = new ContentUpdateStruct([
'initialLanguageCode' => self::ENG_US,
]);
$contentUpdateStruct->setField('name', 'Draft 1 US', self::ENG_US);
$contentUpdateStruct->setField('name', 'Draft 1 DE', self::GER_DE);
$this->contentService->updateContent($draft->versionInfo, $contentUpdateStruct);
$this->contentService->publishVersion($draft->versionInfo, ['ger-DE']);
$content = $this->contentService->loadContent($draft->contentInfo->id);
$this->assertEquals(
[
self::ENG_US => 'Published US',
self::GER_DE => 'Draft 1 DE',
],
$content->fields['name']
);
}
public function testCreateContentWithRomanianSpecialCharsInTitle()
{
$baseName = 'ȘșțȚdfdf';
$expectedPath = '/SstTdfdf';
$this->createFolder([self::ENG_US => $baseName], 2);
$urlAliasService = $this->getRepository()->getURLAliasService();
$urlAlias = $urlAliasService->lookup($expectedPath);
$this->assertSame($expectedPath, $urlAlias->path);
}
/**
* @param int $amountOfDrafts
*
* @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
*/
private function createContentDrafts(int $amountOfDrafts): void
{
if (0 >= $amountOfDrafts) {
throw new InvalidArgumentException('$amountOfDrafts', 'Must be greater then 0');
}
$publishedContent = $this->createContentVersion1();
for ($i = 1; $i <= $amountOfDrafts; ++$i) {
$this->contentService->createContentDraft($publishedContent->contentInfo);
}
}
/**
* @param array $limitationValues
*
* @return \eZ\Publish\API\Repository\Values\User\User
*
* @throws \eZ\Publish\API\Repository\Exceptions\ForbiddenException
* @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
* @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
*/
private function createUserWithVersionReadLimitations(array $limitationValues = []): User
{
$limitations = [
new LocationLimitation(['limitationValues' => $limitationValues]),
];
return $this->createUserWithPolicies(
'user',
[
['module' => 'content', 'function' => 'versionread', 'limitations' => $limitations],
['module' => 'content', 'function' => 'create'],
['module' => 'content', 'function' => 'read'],
['module' => 'content', 'function' => 'edit'],
]
);
}
/**
* @param \eZ\Publish\API\Repository\Values\Content\Content[] $drafts
*
* @throws \eZ\Publish\API\Repository\Exceptions\BadStateException
* @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
*
* @return object
*/
private function createContentWithReverseRelations(array $drafts)
{
$contentWithReverseRelations = new class() {
/** @var \eZ\Publish\API\Repository\Values\Content\Content */
public $content;
/** @var \eZ\Publish\API\Repository\Values\Content\Content[] */
public $reverseRelations;
};
$content = $this->createContentVersion1();
$versionInfo = $content->getVersionInfo();
$contentInfo = $versionInfo->getContentInfo();
$contentWithReverseRelations->content = $content;
/** @var \eZ\Publish\API\Repository\Values\Content\Content $draft */
foreach ($drafts as $draft) {
$this->contentService->addRelation(
$draft->getVersionInfo(),
$contentInfo
);
$contentWithReverseRelations->reverseRelations[] = $this->contentService->publishVersion($draft->getVersionInfo());
}
return $contentWithReverseRelations;
}
}
|
gpl-2.0
|
hexbinary/landing
|
src/main/java/org/oscarehr/PMmodule/dao/OcanSubmissionLogDao.java
|
2279
|
/**
*
* Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* 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.
*
* This software was written for
* Centre for Research on Inner City Health, St. Michael's Hospital,
* Toronto, Ontario, Canada
*/
package org.oscarehr.PMmodule.dao;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import org.oscarehr.PMmodule.model.OcanSubmissionLog;
import org.oscarehr.PMmodule.model.OcanSubmissionRecordLog;
import org.oscarehr.common.dao.AbstractDao;
import org.springframework.stereotype.Repository;
@Repository
public class OcanSubmissionLogDao extends AbstractDao<OcanSubmissionLog> {
public OcanSubmissionLogDao() {
super(OcanSubmissionLog.class);
}
public void persistRecord(OcanSubmissionRecordLog rec) {
entityManager.persist(rec);
}
public List<OcanSubmissionLog> findAll() {
Query query = entityManager.createQuery("select l from OcanSubmissionLog l order by l.submitDateTime DESC");
@SuppressWarnings("unchecked")
List<OcanSubmissionLog> results = query.getResultList();
return results;
}
public List<OcanSubmissionLog> findBySubmissionDate(Date submissionDate) {
Query query = entityManager.createQuery("select l from OcanSubmissionLog l where date(l.submitDateTime)=? order by l.submitDateTime DESC");
query.setParameter(1, submissionDate);
@SuppressWarnings("unchecked")
List<OcanSubmissionLog> results = query.getResultList();
return results;
}
}
|
gpl-2.0
|
gensmusic/test
|
third_party/phantomjs/listen-dom-changed/monitor-with-jquery-watch.js
|
2891
|
"use strict";
var page = require('webpage').create();
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onCallback = function(data) {
console.log('onCallback:' + data.type);
};
var url = 'http://127.0.0.1:3333/';
page.open(url, function(status) {
if (status === 'success') {
console.log('open success ...');
if (page.injectJs('./scripts/jquery-watch.js')) {
console.log('injectJS successfully');
} else {
console.log('injectJS failed');
phantom.exit();
}
// set listener with jquery-watch!!!
page.evaluate(function() {
$('#change-css h4').watch({
properties: 'color',
callback: function(data, i) {
var propChanged = data.props[i];
var newValue = data.vals[i];
console.log('propChanged:' + propChanged + ', newValue:' + newValue);
}
});
$('#ele-change').watch({
properties: 'prop_innerHTML',
watchChildren: true,
callback: function(data, i, mutations) {
var propChanged = data.props[i];
var newValue = data.vals[i];
// console.log('propChanged:' + propChanged + ', newValue:' + newValue);
mutations.forEach(function(m) {
window.callPhantom({'type' : m.type});
switch (m.type) {
case 'attributes':
console.log('attributes:' + m.attributeName + ' changed: oldValue [' + m.oldValue + ']');
break;
case 'characterData':
console.log('characterData:' + 'changed');
break;
case 'childList':
console.log('childList:' + 'changed');
break;
default:
console.log('unkown type:' + m.type);
}
});
}
});
});
// change css
var changeCSS = function() {
page.evaluate(function() {
$('#change-css #color').click();
});
};
var addDom = function() {
page.evaluate(function() {
$('#ele-change #add').click();
})
};
var deleteDom = function() {
page.evaluate(function() {
$('#ele-change #del').click();
});
};
setInterval(changeCSS, 1000);
setInterval(addDom, 2000);
setInterval(deleteDom, 4000);
} else {
console.log('failed to open')
}
});
|
gpl-2.0
|
EderRoger/design_pattern
|
src/factory/Gralic.java
|
98
|
package factory;
/**
* Created by eder on 09/10/15.
*/
public class Gralic extends Veggies {
}
|
gpl-2.0
|
Jessekevon/specht-architects
|
wp-content/plugins/gravityforms-develop/includes/addon/class-gf-addon.php
|
147940
|
<?php
if ( ! class_exists( 'GFForms' ) ) {
die();
}
/**
* Handles all tasks mostly common to any Gravity Forms Add-On, including third party ones
*
*
* @package GFAddOn
* @author Rocketgenius
*/
abstract class GFAddOn {
/**
* @var string Version number of the Add-On
*/
protected $_version;
/**
* @var string Gravity Forms minimum version requirement
*/
protected $_min_gravityforms_version;
/**
* @var string URL-friendly identifier used for form settings, add-on settings, text domain localization...
*/
protected $_slug;
/**
* @var string Relative path to the plugin from the plugins folder. Example "gravityforms/gravityforms.php"
*/
protected $_path;
/**
* @var string Full path the the plugin. Example: __FILE__
*/
protected $_full_path;
/**
* @var string URL to the Gravity Forms website. Example: 'http://www.gravityforms.com' OR affiliate link.
*/
protected $_url;
/**
* @var string Title of the plugin to be used on the settings page, form settings and plugins page. Example: 'Gravity Forms MailChimp Add-On'
*/
protected $_title;
/**
* @var string Short version of the plugin title to be used on menus and other places where a less verbose string is useful. Example: 'MailChimp'
*/
protected $_short_title;
/**
* @var array Members plugin integration. List of capabilities to add to roles.
*/
protected $_capabilities = array();
/**
* @var string The hook suffix for the app menu
*/
public $app_hook_suffix;
private $_saved_settings = array();
private $_previous_settings = array();
/**
* @var array Stores a copy of setting fields that failed validation; only populated after validate_settings() has been called.
*/
private $_setting_field_errors = array();
// ------------ Permissions -----------
/**
* @var string|array A string or an array of capabilities or roles that have access to the settings page
*/
protected $_capabilities_settings_page = array();
/**
* @var string|array A string or an array of capabilities or roles that have access to the form settings
*/
protected $_capabilities_form_settings = array();
/**
* @var string|array A string or an array of capabilities or roles that have access to the plugin page
*/
protected $_capabilities_plugin_page = array();
/**
* @var string|array A string or an array of capabilities or roles that have access to the app menu
*/
protected $_capabilities_app_menu = array();
/**
* @var string|array A string or an array of capabilities or roles that have access to the app settings page
*/
protected $_capabilities_app_settings = array();
/**
* @var string|array A string or an array of capabilities or roles that can uninstall the plugin
*/
protected $_capabilities_uninstall = array();
// ------------ RG Autoupgrade -----------
/**
* @var bool Used by Rocketgenius plugins to activate auto-upgrade.
* @ignore
*/
protected $_enable_rg_autoupgrade = false;
// ------------ Private -----------
private $_no_conflict_scripts = array();
private $_no_conflict_styles = array();
private $_preview_styles = array();
private $_print_styles = array();
private static $_registered_addons = array( 'active' => array(), 'inactive' => array() );
/**
* Class constructor which hooks the instance into the WordPress init action
*/
function __construct() {
add_action( 'init', array( $this, 'init' ) );
if ( $this->_enable_rg_autoupgrade ) {
require_once( 'class-gf-auto-upgrade.php' );
$is_gravityforms_supported = $this->is_gravityforms_supported( $this->_min_gravityforms_version );
new GFAutoUpgrade( $this->_slug, $this->_version, $this->_min_gravityforms_version, $this->_title, $this->_full_path, $this->_path, $this->_url, $is_gravityforms_supported );
}
$this->pre_init();
}
/**
* Registers an addon so that it gets initialized appropriately
*
* @param string $class - The class name
* @param string $overrides - Specify the class to replace/override
*/
public static function register( $class, $overrides = null ) {
//Ignore classes that have been marked as inactive
if ( in_array( $class, self::$_registered_addons['inactive'] ) ) {
return;
}
//Mark classes as active. Override existing active classes if they are supposed to be overridden
$index = array_search( $overrides, self::$_registered_addons['active'] );
if ( $index !== false ) {
self::$_registered_addons['active'][ $index ] = $class;
} else {
self::$_registered_addons['active'][] = $class;
}
//Mark overridden classes as inactive.
if ( ! empty( $overrides ) ) {
self::$_registered_addons['inactive'][] = $overrides;
}
}
public static function get_registered_addons() {
return self::$_registered_addons['active'];
}
/**
* Initializes all addons.
*/
public static function init_addons() {
//Removing duplicate add-ons
$active_addons = array_unique( self::$_registered_addons['active'] );
foreach ( $active_addons as $addon ) {
call_user_func( array( $addon, 'get_instance' ) );
}
}
/**
* Gets executed before all init functions. Override this function to perform initialization tasks that must be done prior to init
*/
public function pre_init() {
if ( $this->is_gravityforms_supported() ) {
//Entry meta
if ( $this->method_is_overridden( 'get_entry_meta' ) ) {
add_filter( 'gform_entry_meta', array( $this, 'get_entry_meta' ), 10, 2 );
}
}
}
/**
* Plugin starting point. Handles hooks and loading of language files.
*/
public function init() {
// Initializing translations. Translation files in the WP_LANG_DIR folder have a higher priority.
$locale = apply_filters( 'plugin_locale', get_locale(), $this->_slug );
load_textdomain( $this->_slug, WP_LANG_DIR . '/gravityforms/' . $this->_slug . '-' . $locale . '.mo' );
load_plugin_textdomain( $this->_slug, false, $this->_slug . '/languages' );
add_filter( 'gform_logging_supported', array( $this, 'set_logging_supported' ) );
if ( RG_CURRENT_PAGE == 'admin-ajax.php' ) {
//If gravity forms is supported, initialize AJAX
if ( $this->is_gravityforms_supported() ) {
$this->init_ajax();
}
} elseif ( is_admin() ) {
$this->init_admin();
} else {
if ( $this->is_gravityforms_supported() ) {
$this->init_frontend();
}
}
}
/**
* Override this function to add initialization code (i.e. hooks) for the admin site (WP dashboard)
*/
protected function init_admin() {
// enqueues admin scripts
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ), 10, 0 );
// message enforcing min version of Gravity Forms
if ( isset( $this->_min_gravityforms_version ) && RG_CURRENT_PAGE == 'plugins.php' && false === $this->_enable_rg_autoupgrade ) {
add_action( 'after_plugin_row_' . $this->_path, array( $this, 'plugin_row' ) );
}
// STOP HERE IF GRAVITY FORMS IS NOT SUPPORTED
if ( isset( $this->_min_gravityforms_version ) && ! $this->is_gravityforms_supported( $this->_min_gravityforms_version ) ) {
return;
}
$this->setup();
// Add form settings only when there are form settings fields configured or form_settings() method is implemented
if ( self::has_form_settings_page() ) {
$this->form_settings_init();
}
// Add plugin page when there is a plugin page configured or plugin_page() method is implemented
if ( self::has_plugin_page() ) {
$this->plugin_page_init();
}
// Add addon settings page only when there are addon settings fields configured or settings_page() method is implemented
if ( self::has_plugin_settings_page() ) {
if ( $this->current_user_can_any( $this->_capabilities_settings_page ) ) {
$this->plugin_settings_init();
}
}
// creates the top level app left menu
if ( self::has_app_menu() ) {
if ( $this->current_user_can_any( $this->_capabilities_app_menu ) ) {
add_action( 'admin_menu', array( $this, 'create_app_menu' ) );
}
}
// Members plugin integration
if ( self::has_members_plugin() ) {
add_filter( 'members_get_capabilities', array( $this, 'members_get_capabilities' ) );
}
// Results page
if ( $this->method_is_overridden( 'get_results_page_config' ) ) {
$results_page_config = $this->get_results_page_config();
$results_capabilities = rgar( $results_page_config, 'capabilities' );
if ( $results_page_config && $this->current_user_can_any( $results_capabilities ) ) {
$this->results_page_init( $results_page_config );
}
}
// Locking
if ( $this->method_is_overridden( 'get_locking_config' ) ) {
require_once( GFCommon::get_base_path() . '/includes/locking/class-gf-locking.php' );
require_once( 'class-gf-addon-locking.php' );
$config = $this->get_locking_config();
new GFAddonLocking( $config, $this );
}
// No conflict scripts
add_filter( 'gform_noconflict_scripts', array( $this, 'register_noconflict_scripts' ) );
add_filter( 'gform_noconflict_styles', array( $this, 'register_noconflict_styles' ) );
}
/**
* Override this function to add initialization code (i.e. hooks) for the public (customer facing) site
*/
protected function init_frontend() {
$this->setup();
add_filter( 'gform_preview_styles', array( $this, 'enqueue_preview_styles' ), 10, 2 );
add_filter( 'gform_print_styles', array( $this, 'enqueue_print_styles' ), 10, 2 );
add_action( 'gform_enqueue_scripts', array( $this, 'enqueue_scripts' ), 10, 2 );
}
/**
* Override this function to add AJAX hooks or to add initialization code when an AJAX request is being performed
*/
protected function init_ajax() {
if ( rgpost( 'view' ) == 'gf_results_' . $this->_slug ) {
require_once( GFCommon::get_base_path() . '/tooltips.php' );
require_once( 'class-gf-results.php' );
$gf_results = new GFResults( $this->_slug, $this->get_results_page_config() );
add_action( 'wp_ajax_gresults_get_results_gf_results_' . $this->_slug, array( $gf_results, 'ajax_get_results' ) );
add_action( 'wp_ajax_gresults_get_more_results_gf_results_' . $this->_slug, array( $gf_results, 'ajax_get_more_results' ) );
} elseif ( $this->method_is_overridden( 'get_locking_config' ) ) {
require_once( GFCommon::get_base_path() . '/includes/locking/class-gf-locking.php' );
require_once( 'class-gf-addon-locking.php' );
$config = $this->get_locking_config();
new GFAddonLocking( $config, $this );
}
}
//-------------- Setup ---------------
/**
* Performs upgrade tasks when the version of the Add-On changes. To add additional upgrade tasks, override the upgrade() function, which will only get executed when the plugin version has changed.
*/
protected function setup() {
//Upgrading add-on
$installed_version = get_option( 'gravityformsaddon_' . $this->_slug . '_version' );
//Making sure version has really changed. Gets around aggressive caching issue on some sites that cause setup to run multiple times.
if ( $installed_version != $this->_version ) {
$installed_version = GFForms::get_wp_option( 'gravityformsaddon_' . $this->_slug . '_version' );
}
//Upgrade if version has changed
if ( $installed_version != $this->_version ) {
$this->upgrade( $installed_version );
update_option( 'gravityformsaddon_' . $this->_slug . '_version', $this->_version );
}
}
/**
* Override this function to add to add database update scripts or any other code to be executed when the Add-On version changes
*/
protected function upgrade( $previous_version ) {
return;
}
//-------------- Script enqueuing ---------------
/**
* Override this function to provide a list of styles to be enqueued.
* When overriding this function, be sure to call parent::styles() to ensure the base class scripts are enqueued.
* See scripts() for an example of the format expected to be returned.
*/
protected function styles() {
$min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG || isset( $_GET['gform_debug'] ) ? '' : '.min';
return array(
array(
'handle' => 'gaddon_form_settings_css',
'src' => GFAddOn::get_gfaddon_base_url() . "/css/gaddon_settings{$min}.css",
'version' => GFCommon::$version,
'enqueue' => array(
array( 'admin_page' => array( 'form_settings', 'plugin_settings', 'plugin_page', 'app_settings' ) ),
)
),
array(
'handle' => 'gaddon_results_css',
'src' => GFAddOn::get_gfaddon_base_url() . "/css/gaddon_results{$min}.css",
'version' => GFCommon::$version,
'enqueue' => array(
array( 'admin_page' => array( 'results' ) ),
)
),
);
}
/**
* Override this function to provide a list of scripts to be enqueued.
* When overriding this function, be sure to call parent::scripts() to ensure the base class scripts are enqueued.
* Following is an example of the array that is expected to be returned by this function:
*<pre>
* <code>
*
* array(
* array( "handle" => 'maskedinput',
* "src" => GFCommon::get_base_url() . '/js/jquery.maskedinput-1.3.min.js',
* "version" => GFCommon::$version,
* "deps" => array("jquery"),
* "in_footer" => false,
*
* //Determines where the script will be enqueued. The script will be enqueued if any of the conditions match
* "enqueue" => array(
* //admin_page - Specified one or more pages (known pages) where the script is supposed to be enqueued.
* //To enqueue scripts in the front end (public website), simply don't define this setting
* array("admin_page" => array("form_settings", 'plugin_settings') ),
*
* //tab - Specifies a form settings or plugin settings tab in which the script is supposed to be enqueued. If none is specified, the script will be enqueued in any of the form settings or plugin_settings page
* array("tab" => 'signature'),
*
* //query - Specifies a set of query string ($_GET) values. If all specified query string values match the current requested page, the script will be enqueued
* array("query" => 'page=gf_edit_forms&view=settings&id=_notempty_')
*
* //post - Specifies a set of post ($_POST) values. If all specified posted values match the current request, the script will be enqueued
* array("post" => 'posted_field=val')
*
* )
* ),
* array(
* "handle" => 'super_signature_script',
* "src" => $this->get_base_url() . '/super_signature/ss.js',
* "version" => $this->_version,
* "deps" => array("jquery"),
* "callback" => array($this, 'localize_scripts'),
* "strings" => array(
* // Accessible in JavaScript using the global variable "[script handle]_strings"
* "stringKey1" => __("The string", 'gravityforms'),
* "stringKey2" => __("Another string.", 'gravityforms')
* )
* "enqueue" => array(
* //field_types - Specifies one or more field types that requires this script. The script will only be enqueued if the current form has a field of any of the specified field types. Only applies when a current form is available.
* array("field_types" => array("signature"))
* )
* )
* );
*
* </code>
* </pre>
*/
protected function scripts() {
$min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG || isset( $_GET['gform_debug'] ) ? '' : '.min';
return array(
array(
'handle' => 'gform_form_admin',
'enqueue' => array( array( 'admin_page' => array( 'form_settings' ) ) )
),
array(
'handle' => 'gform_gravityforms',
'enqueue' => array( array( 'admin_page' => array( 'form_settings' ) ) )
),
array(
'handle' => 'google_charts',
'src' => 'https://www.google.com/jsapi',
'version' => GFCommon::$version,
'enqueue' => array(
array( 'admin_page' => array( 'results' ) ),
)
),
array(
'handle' => 'gaddon_results_js',
'src' => GFAddOn::get_gfaddon_base_url() . "/js/gaddon_results{$min}.js",
'version' => GFCommon::$version,
'deps' => array( 'jquery', 'sack', 'jquery-ui-resizable', 'jquery-ui-datepicker', 'google_charts', 'gform_field_filter' ),
'callback' => array( 'GFResults', 'localize_results_scripts' ),
'enqueue' => array(
array( 'admin_page' => array( 'results' ) ),
)
),
array(
'handle' => 'gaddon_repeater',
'src' => GFAddOn::get_gfaddon_base_url() . "/js/repeater{$min}.js",
'version' => GFCommon::$version,
'deps' => array( 'jquery' ),
'enqueue' => array(
array(
'admin_page' => array( 'form_settings' ),
),
),
),
array(
'handle' => 'gaddon_fieldmap_js',
'src' => GFAddOn::get_gfaddon_base_url() . "/js/gaddon_fieldmap{$min}.js",
'version' => GFCommon::$version,
'deps' => array( 'jquery', 'gaddon_repeater' ),
'enqueue' => array(
array( 'admin_page' => array( 'form_settings' ) ),
)
),
array(
'handle' => 'gaddon_selectcustom_js',
'src' => GFAddOn::get_gfaddon_base_url() . "/js/gaddon_selectcustom{$min}.js",
'version' => GFCommon::$version,
'deps' => array( 'jquery' ),
'enqueue' => array(
array( 'admin_page' => array( 'form_settings' ) ),
)
),
);
}
/**
* Target of admin_enqueue_scripts and gform_enqueue_scripts hooks.
* Not intended to be overridden by child classes.
* In order to enqueue scripts and styles, override the scripts() and styles() functions
*
* @ignore
*/
public function enqueue_scripts( $form = '', $is_ajax = false ) {
if ( empty( $form ) ) {
$form = $this->get_current_form();
}
//Enqueueing scripts
$scripts = $this->scripts();
foreach ( $scripts as $script ) {
$src = isset( $script['src'] ) ? $script['src'] : false;
$deps = isset( $script['deps'] ) ? $script['deps'] : array();
$version = isset( $script['version'] ) ? $script['version'] : false;
$in_footer = isset( $script['in_footer'] ) ? $script['in_footer'] : false;
wp_register_script( $script['handle'], $src, $deps, $version, $in_footer );
if ( isset( $script['enqueue'] ) && $this->_can_enqueue_script( $script['enqueue'], $form, $is_ajax ) ) {
$this->add_no_conflict_scripts( array( $script['handle'] ) );
wp_enqueue_script( $script['handle'] );
if ( isset( $script['strings'] ) ) {
wp_localize_script( $script['handle'], $script['handle'] . '_strings', $script['strings'] );
}
if ( isset( $script['callback'] ) && is_callable( $script['callback'] ) ) {
$args = compact( 'form', 'is_ajax' );
call_user_func_array( $script['callback'], $args );
}
}
}
//Enqueueing styles
$styles = $this->styles();
foreach ( $styles as $style ) {
$src = isset( $style['src'] ) ? $style['src'] : false;
$deps = isset( $style['deps'] ) ? $style['deps'] : array();
$version = isset( $style['version'] ) ? $style['version'] : false;
$media = isset( $style['media'] ) ? $style['media'] : 'all';
wp_register_style( $style['handle'], $src, $deps, $version, $media );
if ( $this->_can_enqueue_script( $style['enqueue'], $form, $is_ajax ) ) {
$this->add_no_conflict_styles( array( $style['handle'] ) );
if ( $this->is_preview() ) {
$this->_preview_styles[] = $style['handle'];
} elseif ( $this->is_print() ) {
$this->_print_styles[] = $style['handle'];
} else {
wp_enqueue_style( $style['handle'] );
}
}
}
}
/**
* Target of gform_preview_styles. Enqueue styles to the preview page.
* Not intended to be overridden by child classes
*
* @ignore
*/
public function enqueue_preview_styles( $preview_styles, $form ) {
return array_merge( $preview_styles, $this->_preview_styles );
}
/**
* Target of gform_print_styles. Enqueue styles to the print entry page.
* Not intended to be overridden by child classes
*
* @ignore
*/
public function enqueue_print_styles( $print_styles, $form ) {
if ( false === $print_styles ) {
$print_styles = array();
}
$styles = $this->styles();
foreach ( $styles as $style ) {
if ( $this->_can_enqueue_script( $style['enqueue'], $form, false ) ) {
$this->add_no_conflict_styles( array( $style['handle'] ) );
$src = isset( $style['src'] ) ? $style['src'] : false;
$deps = isset( $style['deps'] ) ? $style['deps'] : array();
$version = isset( $style['version'] ) ? $style['version'] : false;
$media = isset( $style['media'] ) ? $style['media'] : 'all';
wp_register_style( $style['handle'], $src, $deps, $version, $media );
$print_styles[] = $style['handle'];
}
}
return array_merge( $print_styles, $this->_print_styles );
}
/**
* Adds scripts to the list of white-listed no conflict scripts.
*
* @param $scripts
*/
private function add_no_conflict_scripts( $scripts ) {
$this->_no_conflict_scripts = array_merge( $scripts, $this->_no_conflict_scripts );
}
/**
* Adds styles to the list of white-listed no conflict styles.
*
* @param $styles
*/
private function add_no_conflict_styles( $styles ) {
$this->_no_conflict_styles = array_merge( $styles, $this->_no_conflict_styles );
}
private function _can_enqueue_script( $enqueue_conditions, $form, $is_ajax ) {
if ( empty( $enqueue_conditions ) ) {
return false;
}
foreach ( $enqueue_conditions as $condition ) {
if ( is_callable( $condition ) ) {
return call_user_func( $condition, $form, $is_ajax );
} else {
$query_matches = isset( $condition['query'] ) ? $this->_request_condition_matches( $_GET, $condition['query'] ) : true;
$post_matches = isset( $condition['post'] ) ? $this->_request_condition_matches( $_POST, $condition['query'] ) : true;
$admin_page_matches = isset( $condition['admin_page'] ) ? $this->_page_condition_matches( $condition['admin_page'], rgar( $condition, 'tab' ) ) : true;
$field_type_matches = isset( $condition['field_types'] ) ? $this->_field_condition_matches( $condition['field_types'], $form ) : true;
if ( $query_matches && $post_matches && $admin_page_matches && $field_type_matches ) {
return true;
}
}
}
return false;
}
private function _request_condition_matches( $request, $query ) {
parse_str( $query, $query_array );
foreach ( $query_array as $key => $value ) {
switch ( $value ) {
case '_notempty_' :
if ( rgempty( $key, $request ) ) {
return false;
}
break;
case '_empty_' :
if ( ! rgempty( $key, $request ) ) {
return false;
}
break;
default :
if ( rgar( $request, $key ) != $value ) {
return false;
}
break;
}
}
return true;
}
private function _page_condition_matches( $pages, $tab ) {
if ( ! is_array( $pages ) ) {
$pages = array( $pages );
}
foreach ( $pages as $page ) {
switch ( $page ) {
case 'form_editor' :
if ( $this->is_form_editor() ) {
return true;
}
break;
case 'form_settings' :
if ( $this->is_form_settings( $tab ) ) {
return true;
}
break;
case 'plugin_settings' :
if ( $this->is_plugin_settings( $tab ) ) {
return true;
}
break;
case 'app_settings' :
if ( $this->is_app_settings( $tab ) ) {
return true;
}
break;
case 'plugin_page' :
if ( $this->is_plugin_page() ) {
return true;
}
break;
case 'entry_view' :
if ( $this->is_entry_view() ) {
return true;
}
break;
case 'entry_edit' :
if ( $this->is_entry_edit() ) {
return true;
}
break;
case 'results' :
if ( $this->is_results() ) {
return true;
}
break;
}
}
return false;
}
private function _field_condition_matches( $field_types, $form ) {
if ( ! is_array( $field_types ) ) {
$field_types = array( $field_types );
}
$fields = GFAPI::get_fields_by_type( $form, $field_types );
if ( count( $fields ) > 0 ) {
return true;
}
return false;
}
/**
* Target for the gform_noconflict_scripts filter. Adds scripts to the list of white-listed no conflict scripts.
*
* Not intended to be overridden or called directed by Add-Ons.
*
* @ignore
*
* @param array $scripts Array of scripts to be white-listed
*
* @return array
*/
public function register_noconflict_scripts( $scripts ) {
//registering scripts with Gravity Forms so that they get enqueued when running in no-conflict mode
return array_merge( $scripts, $this->_no_conflict_scripts );
}
/**
* Target for the gform_noconflict_styles filter. Adds styles to the list of white-listed no conflict scripts.
*
* Not intended to be overridden or called directed by Add-Ons.
*
* @ignore
*
* @param array $styles Array of styles to be white-listed
*
* @return array
*/
public function register_noconflict_styles( $styles ) {
//registering styles with Gravity Forms so that they get enqueued when running in no-conflict mode
return array_merge( $styles, $this->_no_conflict_styles );
}
//-------------- Entry meta --------------------------------------
/**
* Override this method to activate and configure entry meta.
*
*
* @param array $entry_meta An array of entry meta already registered with the gform_entry_meta filter.
* @param int $form_id The form id
*
* @return array The filtered entry meta array.
*/
protected function get_entry_meta( $entry_meta, $form_id ) {
return $entry_meta;
}
//-------------- Results page --------------------------------------
/**
* Returns the configuration for the results page. By default this is not activated.
* To activate the results page override this function and return an array with the configuration data.
*
* Example:
* public function get_results_page_config() {
* return array(
* "title" => 'Quiz Results',
* "capabilities" => array("gravityforms_quiz_results"),
* "callbacks" => array(
* "fields" => array($this, 'results_fields'),
* "calculation" => array($this, 'results_calculation'),
* "markup" => array($this, 'results_markup'),
* )
* );
* }
*
*/
public function get_results_page_config() {
return false;
}
/**
* Initializes the result page functionality. To activate result page functionality, override the get_results_page_config() function.
*
* @param $results_page_config - configuration returned by get_results_page_config()
*/
protected function results_page_init( $results_page_config ) {
require_once( 'class-gf-results.php' );
if ( isset( $results_page_config['callbacks']['filters'] ) ) {
add_filter( 'gform_filters_pre_results', $results_page_config['callbacks']['filters'], 10, 2 );
}
if ( isset( $results_page_config['callbacks']['filter_ui'] ) ) {
add_filter( 'gform_filter_ui', $results_page_config['callbacks']['filter_ui'], 10, 5 );
}
$gf_results = new GFResults( $this->_slug, $results_page_config );
$gf_results->init();
}
//-------------- Logging integration --------------------------------------
public function set_logging_supported( $plugins ) {
$plugins[ $this->_slug ] = $this->_title;
return $plugins;
}
//-------------- Members plugin integration --------------------------------------
/**
* Checks whether the Members plugin is installed and activated.
*
* Not intended to be overridden or called directly by Add-Ons.
*
* @ignore
*
* @return bool
*/
protected function has_members_plugin() {
return function_exists( 'members_get_capabilities' );
}
/**
* Not intended to be overridden or called directly by Add-Ons.
*
* @ignore
*
* @param $caps
*
* @return array
*/
public function members_get_capabilities( $caps ) {
return array_merge( $caps, $this->_capabilities );
}
//-------------- Permissions: Capabilities and Roles ----------------------------
/**
* Checks whether the current user is assigned to a capability or role.
*
* @param string|array $caps An string or array of capabilities to check
*
* @return bool Returns true if the current user is assigned to any of the capabilities.
*/
protected function current_user_can_any( $caps ) {
return GFCommon::current_user_can_any( $caps );
}
//------- Settings Helper Methods (Common to all settings pages) -------------------
/***
* Renders the UI of all settings page based on the specified configuration array $sections
*
* @param array $sections - Configuration array containing all fields to be rendered grouped into sections
*/
protected function render_settings( $sections ) {
if ( ! $this->has_setting_field_type( 'save', $sections ) ) {
$sections = $this->add_default_save_button( $sections );
}
?>
<form id="gform-settings" action="" method="post">
<?php $this->settings( $sections ); ?>
</form>
<?php
}
/***
* Renders settings fields based on the specified configuration array $sections
*
* @param array $sections - Configuration array containing all fields to be rendered grouped into sections
*/
protected function settings( $sections ) {
$is_first = true;
foreach ( $sections as $section ) {
if ( $this->setting_dependency_met( rgar( $section, 'dependency' ) ) ) {
$this->single_section( $section, $is_first );
}
$is_first = false;
}
}
/***
* Displays the UI for a field section
*
* @param array $section - The section to be displayed
* @param bool $is_first - true for the first section in the list, false for all others
*/
protected function single_section( $section, $is_first = false ) {
extract(
wp_parse_args(
$section, array(
'title' => false,
'description' => false,
'id' => '',
'class' => false,
'style' => '',
'tooltip' => false,
'tooltip_class' => ''
)
)
);
$classes = array( 'gaddon-section' );
if ( $is_first ) {
$classes[] = 'gaddon-first-section';
}
if ( $class )
$classes[] = $class;
?>
<div
id="<?php echo $id; ?>"
class="<?php echo implode( ' ', $classes ); ?>"
style="<?php echo $style; ?>"
>
<?php if ( $title ): ?>
<h4 class="gaddon-section-title gf_settings_subgroup_title">
<?php echo $title; ?>
<?php if( $tooltip ): ?>
<?php gform_tooltip( $tooltip, $tooltip_class ); ?>
<?php endif; ?>
</h4>
<?php endif; ?>
<?php if ( $description ): ?>
<div class="gaddon-section-description"><?php echo $description; ?></div>
<?php endif; ?>
<table class="form-table gforms_form_settings">
<?php
foreach ( $section['fields'] as $field ) {
if ( ! $this->setting_dependency_met( rgar( $field, 'dependency' ) ) )
continue;
if ( is_callable( array( $this, "single_setting_row_{$field['type']}" ) ) ) {
call_user_func( array( $this, "single_setting_row_{$field['type']}" ), $field );
} else {
$this->single_setting_row( $field );
}
}
?>
</table>
</div>
<?php
}
/***
* Displays the UI for the field container row
*
* @param array $field - The field to be displayed
*/
protected function single_setting_row( $field ) {
$display = rgar( $field, 'hidden' ) || rgar( $field, 'type' ) == 'hidden' ? 'style="display:none;"' : '';
?>
<tr id="gaddon-setting-row-<?php echo $field['name'] ?>" <?php echo $display; ?>>
<th>
<?php $this->single_setting_label( $field ); ?>
</th>
<td>
<?php $this->single_setting( $field ); ?>
</td>
</tr>
<?php
}
protected function single_setting_label( $field ) {
echo $field['label'];
if ( isset( $field['tooltip'] ) ) {
echo ' ' . gform_tooltip( $field['tooltip'], rgar( $field, 'tooltip_class' ), true );
}
if ( rgar( $field, 'required' ) ) {
echo ' ' . $this->get_required_indicator( $field );
}
}
protected function single_setting_row_save( $field ) {
?>
<tr>
<td colspan="2">
<?php $this->single_setting( $field ); ?>
</td>
</tr>
<?php
}
/***
* Calls the appropriate field function to handle rendering of each specific field type
*
* @param array $field - The field to be rendered
*/
protected function single_setting( $field ) {
if ( is_callable( rgar( $field, 'callback' ) ) ) {
call_user_func( $field['callback'], $field );
} elseif ( is_callable( array( $this, "settings_{$field['type']}" ) ) ) {
call_user_func( array( $this, "settings_{$field['type']}" ), $field );
} else {
printf( esc_html__( "Field type '%s' has not been implemented", 'gravityforms' ), esc_html( $field['type'] ) );
}
}
/***
* Sets the current saved settings to a class variable so that it can be accessed by lower level functions in order to initialize inputs with the appropriate values
*
* @param array $settings : Settings to be saved
*/
protected function set_settings( $settings ) {
$this->_saved_settings = $settings;
}
/***
* Sets the previous settings to a class variable so that it can be accessed by lower level functions providing support for
* verifying whether a value was changed before executing an action
*
* @param array $settings : Settings to be stored
*/
protected function set_previous_settings( $settings ) {
$this->_previous_settings = $settings;
}
protected function get_previous_settings() {
return $this->_previous_settings;
}
/***
* Gets settings from $_POST variable, returning a name/value collection of setting name and setting value
*/
protected function get_posted_settings() {
global $_gaddon_posted_settings;
if ( isset( $_gaddon_posted_settings ) ) {
return $_gaddon_posted_settings;
}
$_gaddon_posted_settings = array();
if ( count( $_POST ) > 0 ) {
foreach ( $_POST as $key => $value ) {
if ( preg_match( '|_gaddon_setting_(.*)|', $key, $matches ) ) {
$_gaddon_posted_settings[ $matches[1] ] = self::maybe_decode_json( stripslashes_deep( $value ) );
}
}
}
return $_gaddon_posted_settings;
}
protected static function maybe_decode_json( $value ) {
if ( self::is_json( $value ) ) {
return json_decode( $value, ARRAY_A );
}
return $value;
}
protected static function is_json( $value ) {
if ( is_string( $value ) && in_array( substr( $value, 0, 1 ), array( '{', '[' ) ) && is_array( json_decode( $value, ARRAY_A ) ) ) {
return true;
}
return false;
}
/***
* Gets the "current" settings, which are settings from $_POST variables if this is a postback request, or the current saved settings for a get request.
*/
protected function get_current_settings() {
//try getting settings from post
$settings = $this->get_posted_settings();
//if nothing has been posted, get current saved settings
if ( empty( $settings ) ) {
$settings = $this->_saved_settings;
}
return $settings;
}
/***
* Retrieves the setting for a specific field/input
*
* @param string $setting_name The field or input name
* @param string $default_value Optional. The default value
* @param bool|array $settings Optional. THe settings array
*
* @return string|array
*/
protected function get_setting( $setting_name, $default_value = '', $settings = false ) {
if ( ! $settings ) {
$settings = $this->get_current_settings();
}
if ( false === $settings ) {
return $default_value;
}
if ( strpos( $setting_name, '[' ) !== false ) {
$path_parts = explode( '[', $setting_name );
foreach ( $path_parts as $part ) {
$part = trim( $part, ']' );
if ( $part != '0'){
if ( empty( $part ) ) {
return $settings;
}
}
if ( false === isset( $settings[ $part ] ) ) {
return $default_value;
}
$settings = rgar( $settings, $part );
}
$setting = $settings;
} else {
if ( false === isset( $settings[ $setting_name ] ) ) {
return $default_value;
}
$setting = $settings[ $setting_name ];
}
return $setting;
}
/***
* Determines if a dependent field has been populated.
*
* @param string $dependency - Field or input name of the "parent" field.
*
* @return bool - true if the "parent" field has been filled out and false if it has not.
*
*/
protected function setting_dependency_met( $dependency ) {
// if no dependency, always return true
if ( ! $dependency ) {
return true;
}
//use a callback if one is specified in the configuration
if ( is_callable( $dependency ) ) {
return call_user_func( $dependency );
}
if ( is_array( $dependency ) ) {
//supports: 'dependency' => array("field" => 'myfield', 'values' => array("val1", 'val2'))
$dependency_field = $dependency['field'];
$dependency_value = $dependency['values'];
} else {
//supports: 'dependency' => 'myfield'
$dependency_field = $dependency;
$dependency_value = '_notempty_';
}
if ( ! is_array( $dependency_value ) ) {
$dependency_value = array( $dependency_value );
}
$current_value = $this->get_setting( $dependency_field );
foreach ( $dependency_value as $val ) {
if ( $current_value == $val ) {
return true;
}
if ( $val == '_notempty_' && ! rgblank( $current_value ) ) {
return true;
}
}
return false;
}
protected function has_setting_field_type( $type, $fields ) {
if ( ! empty( $fields ) ) {
foreach ( $fields as &$section ) {
foreach ( $section['fields'] as $field ) {
if ( rgar( $field, 'type' ) == $type ) {
return true;
}
}
}
}
return false;
}
protected function add_default_save_button( $sections ) {
$sections[ count( $sections ) - 1 ]['fields'][] = array( 'type' => 'save' );
return $sections;
}
protected function get_save_success_message( $sections ) {
$save_button = $this->get_save_button( $sections );
return isset( $save_button['messages']['success'] ) ? $save_button['messages']['success'] : esc_html__( 'Settings updated', 'gravityforms' );
}
protected function get_save_error_message( $sections ) {
$save_button = $this->get_save_button( $sections );
return isset( $save_button['messages']['error'] ) ? $save_button['messages']['error'] : esc_html__( 'There was an error while saving your settings', 'gravityforms' );
}
protected function get_save_button( $sections ) {
$fields = $sections[ count( $sections ) - 1 ]['fields'];
foreach ( $fields as $field ) {
if ( $field['type'] == 'save' )
return $field;
}
return false;
}
//------------- Field Types ------------------------------------------------------
/***
* Renders and initializes a text field based on the $field array
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
protected function settings_text( $field, $echo = true ) {
$field['type'] = 'text'; //making sure type is set to text
$attributes = $this->get_field_attributes( $field );
$default_value = rgar( $field, 'value' ) ? rgar( $field, 'value' ) : rgar( $field, 'default_value' );
$value = $this->get_setting( $field['name'], $default_value );
$name = esc_attr( $field['name'] );
$tooltip = isset( $choice['tooltip'] ) ? gform_tooltip( $choice['tooltip'], rgar( $choice, 'tooltip_class' ), true ) : '';
$html = '';
$html .= '<input
type="text"
name="_gaddon_setting_' . esc_attr( $field['name'] ) . '"
value="' . esc_attr( $value ) . '" ' .
implode( ' ', $attributes ) .
' />';
$feedback_callback = rgar( $field, 'feedback_callback' );
if ( is_callable( $feedback_callback ) ) {
$is_valid = call_user_func_array( $feedback_callback, array( $value, $field ) );
$icon = '';
if ( $is_valid === true ) {
$icon = 'icon-check fa-check gf_valid'; // check icon
} elseif ( $is_valid === false ) {
$icon = 'icon-remove fa-times gf_invalid'; // x icon
}
if ( ! empty( $icon ) ) {
$html .= " <i class=\"fa {$icon}\"></i>";
}
}
if ( $this->field_failed_validation( $field ) ) {
$html .= $this->get_error_icon( $field );
}
if ( $echo ) {
echo $html;
}
return $html;
}
/***
* Renders and initializes a textarea field based on the $field array
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
protected function settings_textarea( $field, $echo = true ) {
$field['type'] = 'textarea'; //making sure type is set to textarea
$attributes = $this->get_field_attributes( $field );
$default_value = rgar( $field, 'value' ) ? rgar( $field, 'value' ) : rgar( $field, 'default_value' );
$value = $this->get_setting( $field['name'], $default_value );
$name = '' . esc_attr( $field['name'] );
$tooltip = isset( $choice['tooltip'] ) ? gform_tooltip( $choice['tooltip'], rgar( $choice, 'tooltip_class' ), true ) : '';
$html = '';
if ( rgar( $field, 'use_editor' ) && GFCommon::is_wp_version( '3.3' ) ) {
$html .= '<span class="mt-gaddon-editor mt-_gaddon_setting_'. $field['name'] .'"></span>';
ob_start();
wp_editor( $value, '_gaddon_setting_'. $field['name'], array( 'autop' => false, 'editor_class' => 'merge-tag-support mt-wp_editor mt-manual_position mt-position-right' ) );
$html .= ob_get_contents();
ob_end_clean();
} else {
$html .= '<textarea
name="_gaddon_setting_' . $name . '" ' .
implode( ' ', $attributes ) .
'>' .
esc_html( $value ) .
'</textarea>';
}
if ( $this->field_failed_validation( $field ) ) {
$html .= $this->get_error_icon( $field );
}
if ( $echo ) {
echo $html;
}
return $html;
}
/***
* Renders and initializes a hidden field based on the $field array
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
protected function settings_hidden( $field, $echo = true ) {
$field['type'] = 'hidden'; //making sure type is set to hidden
$attributes = $this->get_field_attributes( $field );
$default_value = rgar( $field, 'value' ) ? rgar( $field, 'value' ) : rgar( $field, 'default_value' );
$value = $this->get_setting( $field['name'], $default_value );
if ( is_array( $value ) ) {
$value = json_encode( $value );
}
$html = '<input
type="hidden"
name="_gaddon_setting_' . esc_attr( $field['name'] ) . '"
value=\'' . esc_attr( $value ) . '\' ' .
implode( ' ', $attributes ) .
' />';
if ( $echo ) {
echo $html;
}
return $html;
}
/***
* Renders and initializes a checkbox field or a collection of checkbox fields based on the $field array
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
protected function settings_checkbox( $field, $echo = true ) {
$field['type'] = 'checkbox'; //making sure type is set to checkbox
$field_attributes = $this->get_field_attributes( $field, array() );
$horizontal = rgar( $field, 'horizontal' ) ? ' gaddon-setting-inline' : '';
$html = '';
$default_choice_attributes = array( 'onclick' => 'jQuery(this).siblings("input[type=hidden]").val(jQuery(this).prop("checked") ? 1 : 0);' );
if ( is_array( $field['choices'] ) ) {
foreach ( $field['choices'] as $choice ) {
$choice['id'] = sanitize_title( $choice['name'] );
$choice_attributes = $this->get_choice_attributes( $choice, $field_attributes, $default_choice_attributes );
$value = $this->get_setting( $choice['name'], rgar( $choice, 'default_value' ) );
$tooltip = isset( $choice['tooltip'] ) ? gform_tooltip( $choice['tooltip'], rgar( $choice, 'tooltip_class' ), true ) : '';
$html .= $this->checkbox_item( $choice, $horizontal, $choice_attributes, $value, $tooltip );
}
}
if ( $this->field_failed_validation( $field ) ) {
$html .= $this->get_error_icon( $field );
}
if ( $echo ) {
echo $html;
}
return $html;
}
/**
* Returns the markup for an individual checkbox item give the parameters
*
* @param $choice - Choice array with all configured properties
* @param $horizontal_class - CSS class to style checkbox items horizontally
* @param $attributes - String containing all the attributes for the input tag.
* @param $value - Currently selection (1 if field has been checked. 0 or null otherwise)
* @param $tooltip - String containing a tooltip for this checkbox item.
*
* @return string - The markup of an individual checkbox item
*/
protected function checkbox_item( $choice, $horizontal_class, $attributes, $value, $tooltip ) {
$hidden_field_value = $value == '1' ? '1' : '0';
$checkbox_item = '
<div id="gaddon-setting-checkbox-choice-' . $choice['id'] . '" class="gaddon-setting-checkbox' . $horizontal_class . '">
<input type=hidden name="_gaddon_setting_' . esc_attr( $choice['name'] ) . '" value="' . $hidden_field_value . '" />';
if ( is_callable( array( $this, "checkbox_input_{$choice['name']}" ) ) ) {
$markup = call_user_func( array( $this, "checkbox_input_{$choice['name']}" ), $choice, $attributes, $value, $tooltip );
} else {
$markup = $this->checkbox_input( $choice, $attributes, $value, $tooltip );
}
$checkbox_item .= $markup . '</div>';
return $checkbox_item;
}
/**
* Returns the markup for an individual checkbox input and its associated label
*
* @param $choice - Choice array with all configured properties
* @param $attributes - String containing all the attributes for the input tag.
* @param $value - Currently selection (1 if field has been checked. 0 or null otherwise)
* @param $tooltip - String containing a tooltip for this checkbox item.
*
* @return string - The markup of an individual checkbox input and its associated label
*/
protected function checkbox_input( $choice, $attributes, $value, $tooltip ) {
$markup = '<input type = "checkbox" ' .
implode( ' ', $attributes ) . ' ' .
checked( $value, '1', false ) .
' />
<label for="' . esc_attr( $choice['id'] ) . '">' . esc_html( $choice['label'] ) . ' ' . $tooltip . '</label>';
return $markup;
}
/***
* Renders and initializes a radio field or a collection of radio fields based on the $field array
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string Returns the markup for the radio buttons
*
*/
protected function settings_radio( $field, $echo = true ) {
$field['type'] = 'radio'; //making sure type is set to radio
$selected_value = $this->get_setting( $field['name'], rgar( $field, 'default_value' ) );
$field_attributes = $this->get_field_attributes( $field );
$horizontal = rgar( $field, 'horizontal' ) ? ' gaddon-setting-inline' : '';
$html = '';
if ( is_array( $field['choices'] ) ) {
foreach ( $field['choices'] as $i => $choice ) {
$choice['id'] = $field['name'] . $i;
$choice_attributes = $this->get_choice_attributes( $choice, $field_attributes );
$tooltip = isset( $choice['tooltip'] ) ? gform_tooltip( $choice['tooltip'], rgar( $choice, 'tooltip_class' ), true ) : '';
$radio_value = isset( $choice['value'] ) ? $choice['value'] : $choice['label'];
$checked = checked( $selected_value, $radio_value, false );
$html .= '
<div id="gaddon-setting-radio-choice-' . $choice['id'] . '" class="gaddon-setting-radio' . $horizontal . '">
<label for="' . esc_attr( $choice['id'] ) . '">
<input
id = "' . esc_attr( $choice['id'] ) . '"
type = "radio" ' .
'name="_gaddon_setting_' . esc_attr( $field['name'] ) . '" ' .
'value="' . $radio_value . '" ' .
implode( ' ', $choice_attributes ) . ' ' .
$checked .
' /><span>' . esc_html( $choice['label'] ) . ' ' . $tooltip . '</span>
</label>
</div>
';
}
}
if ( $this->field_failed_validation( $field ) ) {
$html .= $this->get_error_icon( $field );
}
if ( $echo ) {
echo $html;
}
return $html;
}
/***
* Renders and initializes a drop down field based on the $field array
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
protected function settings_select( $field, $echo = true ) {
$field['type'] = 'select'; // making sure type is set to select
$attributes = $this->get_field_attributes( $field );
$value = $this->get_setting( $field['name'], rgar( $field, 'default_value' ) );
$name = '' . esc_attr( $field['name'] );
$html = sprintf(
'<select name="%1$s" %2$s>%3$s</select>',
'_gaddon_setting_' . $name, implode( ' ', $attributes ), $this->get_select_options( $field['choices'], $value )
);
if ( $this->field_failed_validation( $field ) ) {
$html .= $this->get_error_icon( $field );
}
if ( $echo ) {
echo $html;
}
return $html;
}
/**
* Renders and initializes a drop down field with a input field for custom input based on the $field array.
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
protected function settings_select_custom( $field, $echo = true ) {
/* Prepare select field */
$select_field = $field;
$select_field_value = $this->get_setting( $select_field['name'], rgar( $select_field, 'default_value' ) );
$select_field['onchange'] = '';
$select_field['class'] = ( isset( $select_field['class'] ) ) ? $select_field['class'] . 'gaddon-setting-select-custom' : 'gaddon-setting-select-custom';
/* Prepare input field */
$input_field = $field;
$input_field['name'] .= '_custom';
$input_field_display = '';
/* If select value is "gf_custom", hide the select field and display the input field. */
if ( $select_field_value == 'gf_custom' ) {
$select_field['style'] = 'display:none;';
} else {
$input_field_display = ' style="display:none;"';
}
/* Loop through select choices and make sure option for custom exists */
$has_gf_custom = false;
foreach ( $select_field['choices'] as $choice ) {
if ( rgar( $choice, 'name' ) == 'gf_custom' || rgar( $choice, 'value' ) == 'gf_custom' ) {
$has_gf_custom = true;
}
}
if ( ! $has_gf_custom ) {
$select_field['choices'][] = array(
'label' => esc_html__( 'Add Custom', 'gravityforms' ) .' ' . $select_field['label'],
'value' => 'gf_custom'
);
}
/* Add select field */
$html = $this->settings_select( $select_field, false );
/* Add input field */
$html .= '<div class="gaddon-setting-select-custom-container"'. $input_field_display .'>
<a href="#" class="select-custom-reset">Reset</a>'.
$this->settings_text( $input_field, false ) .'
</div>';
/* Add validation display */
if ( $this->field_failed_validation( $field ) ) {
$html .= $this->get_error_icon( $field );
}
if ( $echo ) {
echo $html;
}
return $html;
}
public function get_select_options( $choices, $selected_value ) {
$options = '';
foreach ( $choices as $choice ) {
if ( isset( $choice['choices'] ) ) {
$options .= sprintf( '<optgroup label="%1$s">%2$s</optgroup>', esc_attr( $choice['label'] ), $this->get_select_options( $choice['choices'], $selected_value ) );
} else {
if ( ! isset( $choice['value'] ) ) {
$choice['value'] = $choice['label'];
}
$options .= $this->get_select_option( $choice, $selected_value );
}
}
return $options;
}
protected function get_select_option( $choice, $selected_value ) {
if ( is_array( $selected_value ) ) {
$selected = in_array( $choice['value'], $selected_value ) ? "selected='selected'" : '';
} else {
$selected = selected( $selected_value, $choice['value'], false );
}
return sprintf( '<option value="%1$s" %2$s>%3$s</option>', esc_attr( $choice['value'] ), $selected, $choice['label'] );
}
//------------- Field Map Field Type --------------------------
public function settings_field_map( $field, $echo = true ) {
$html = '';
$field_map = rgar( $field, 'field_map' );
if ( empty( $field_map ) ) {
return $html;
}
$form_id = rgget( 'id' );
$html .= '<table class="settings-field-map-table" cellspacing="0" cellpadding="0">' .
$this->field_map_table_header() .
'<tbody>';
foreach ( $field['field_map'] as $child_field ) {
if ( ! $this->setting_dependency_met( rgar( $child_field, 'dependency' ) ) ) {
continue;
}
$child_field['name'] = $this->get_mapped_field_name( $field, $child_field['name'] );
$required = rgar( $child_field, 'required' ) ? $this->get_required_indicator( $child_field ) : '';
$html .= '
<tr>
<td>
<label for="' . $child_field['name'] . '">' . $child_field['label'] . ' ' . $required . '<label>
</td>
<td>' .
$this->settings_field_map_select( $child_field, $form_id ) .
'</td>
</tr>';
}
$html .= '
</tbody>
</table>';
if ( $echo ) {
echo $html;
}
return $html;
}
public function field_map_table_header() {
return '<thead>
<tr>
<th>' . $this->field_map_title() . '</th>
<th>' . esc_html__( 'Form Field', 'gravityforms' ) . '</th>
</tr>
</thead>';
}
public function settings_field_map_select( $field, $form_id ) {
$field_type = ( isset( $field['field_type'] ) ) ? $field['field_type'] : null;
$exclude_field_types = ( isset( $field['exclude_field_types'] ) ? $field['exclude_field_types'] : null );
$field['choices'] = $this->get_field_map_choices( $form_id, $field_type, $exclude_field_types );
return $this->settings_select( $field, false );
}
protected function field_map_title() {
return esc_html__( 'Field', 'gravityforms' );
}
public static function get_field_map_choices( $form_id, $field_type = null, $exclude_field_types = null ) {
$form = RGFormsModel::get_form_meta( $form_id );
$fields = array();
$fields[] = array( 'value' => '', 'label' => '' );
// Adding default fields
if ( is_null( $field_type ) ) {
$fields[] = array( 'value' => 'date_created', 'label' => esc_html__( 'Entry Date', 'gravityforms' ) );
$fields[] = array( 'value' => 'ip', 'label' => esc_html__( 'User IP', 'gravityforms' ) );
$fields[] = array( 'value' => 'source_url', 'label' => esc_html__( 'Source Url', 'gravityforms' ) );
$fields[] = array( 'value' => 'form_title', 'label' => esc_html__( 'Form Title', 'gravityforms' ) );
}
// Populate entry meta
$entry_meta = GFFormsModel::get_entry_meta( $form['id'] );
foreach ( $entry_meta as $meta_key => $meta ) {
$fields[] = array( 'value' => $meta_key, 'label' => rgars( $entry_meta, "{$meta_key}/label" ) );
}
// Populate form fields
if ( is_array( $form['fields'] ) ) {
foreach ( $form['fields'] as $field ) {
$input_type = $field->get_input_type();
$inputs = $field->get_entry_inputs();
$field_is_valid_type = ( is_null( $field_type ) || ( is_array( $field_type ) && in_array( $input_type, $field_type ) ) || ( ! is_null( $field_type ) && $input_type == $field_type ) );
if ( is_null( $exclude_field_types ) ) {
$exclude_field = false;
} elseif ( is_array( $exclude_field_types ) ) {
if ( in_array( $input_type, $exclude_field_types ) ) {
$exclude_field = true;
} else {
$exclude_field = false;
}
} else {
//not array, so should be single string
if ( $input_type == $exclude_field_types ) {
$exclude_field = true;
} else {
$exclude_field = false;
}
}
if ( is_array( $inputs ) && $field_is_valid_type && ! $exclude_field ) {
//If this is an address field, add full name to the list
if ( $input_type == 'address' ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Full', 'gravityforms' ) . ')'
);
}
//If this is a name field, add full name to the list
if ( $input_type == 'name' ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Full', 'gravityforms' ) . ')'
);
}
//If this is a checkbox field, add to the list
if ( $input_type == 'checkbox' ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Selected', 'gravityforms' ) . ')'
);
}
foreach ( $inputs as $input ) {
$fields[] = array(
'value' => $input['id'],
'label' => GFCommon::get_label( $field, $input['id'] )
);
}
} elseif ( $input_type == 'list' && $field->enableColumns && $field_is_valid_type && ! $exclude_field ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Full', 'gravityforms' ) . ')'
);
$col_index = 0;
foreach ( $field->choices as $column ) {
$fields[] = array(
'value' => $field->id . '.' . $col_index,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html( rgar( $column, 'text' ) ) . ')',
);
$col_index ++;
}
} elseif ( ! rgar( $field, 'displayOnly' ) && $field_is_valid_type && ! $exclude_field ) {
$fields[] = array( 'value' => $field->id, 'label' => GFCommon::get_label( $field ) );
}
}
}
return $fields;
}
public function get_mapped_field_name( $parent_field, $field_name ) {
return "{$parent_field['name']}_{$field_name}";
}
public static function get_field_map_fields( $feed, $field_name ) {
$fields = array();
$prefix = "{$field_name}_";
foreach ( $feed['meta'] as $name => $value ) {
if ( strpos( $name, $prefix ) === 0 ) {
$name = str_replace( $prefix, '', $name );
$fields[ $name ] = $value;
}
}
return $fields;
}
public static function get_dynamic_field_map_fields( $feed, $field_name ) {
$fields = array();
$dynamic_fields = $feed['meta'][$field_name];
if ( ! empty( $dynamic_fields ) ) {
foreach ( $dynamic_fields as $dynamic_field ) {
$field_key = ( $dynamic_field['key'] == 'gf_custom' ) ? $dynamic_field['custom_key'] : $dynamic_field['key'];
$fields[$field_key] = $dynamic_field['value'];
}
}
return $fields;
}
//----------------------------------------------------------------
public function settings_dynamic_field_map( $field, $echo = true ) {
$html = '';
$value_field = $key_field = $custom_key_field = $field;
$form = $this->get_current_form();
/* Setup key field drop down */
$key_field['choices'] = ( isset( $field['field_map'] ) ) ? $field['field_map'] : null;
$key_field['name'] .= '_key';
$key_field['class'] = 'key key_{i}';
$key_field['style'] = 'width:200px;';
/* Setup custom key text field */
$custom_key_field['name'] .= '_custom_key_{i}';
$custom_key_field['class'] = 'custom_key custom_key_{i}';
$custom_key_field['style'] = 'width:200px;max-width:90%;';
$custom_key_field['value'] = '{custom_key}';
/* Setup value drop down */
$value_field['name'] .= '_custom_value';
$value_field['class'] = 'value value_{i}';
/* Remove unneeded values */
unset( $field['field_map'] );
unset( $value_field['field_map'] );
unset( $key_field['field_map'] );
unset( $custom_key_field['field_map'] );
//add on errors set when validation fails
if ( $this->field_failed_validation( $field ) ) {
$html .= $this->get_error_icon( $field );
}
/* Build key cell based on available field map choices */
if ( empty( $key_field['choices'] ) ) {
/* Set key field value to "gf_custom" so custom key is used. */
$key_field['value'] = 'gf_custom';
/* Build HTML string */
$key_field_html = '<td>' .
$this->settings_hidden( $key_field, false ) . '
<div class="custom-key-container">
' . $this->settings_text( $custom_key_field, false ) . '
</div>
</td>';
} else {
/* Ensure field map array has a custom key option. */
$has_gf_custom = false;
foreach ( $key_field['choices'] as $choice ) {
if ( rgar( $choice, 'name' ) == 'gf_custom' || rgar( $choice, 'value' ) == 'gf_custom' ) {
$has_gf_custom = true;
}
if ( rgar( $choice, 'choices' ) ) {
foreach ( $choice['choices'] as $subchoice ) {
if ( rgar( $subchoice, 'name' ) == 'gf_custom' || rgar( $subchoice, 'value' ) == 'gf_custom' ) {
$has_gf_custom = true;
}
}
}
}
if ( ! $has_gf_custom && ! rgar( $field, 'disable_custom' ) ) {
$key_field['choices'][] = array(
'label' => esc_html__( 'Add Custom Key', 'gravityforms' ),
'value' => 'gf_custom'
);
}
/* Build HTML string */
$key_field_html = '<th>' .
$this->settings_select( $key_field, false ) . '
<div class="custom-key-container">
<a href="#" class="custom-key-reset">Reset</a>' .
$this->settings_text( $custom_key_field, false ) . '
</div>
</th>';
}
$html .= '
<table class="settings-field-map-table" cellspacing="0" cellpadding="0">
<tbody class="repeater">
<tr>
'. $key_field_html .'
<td>' .
$this->settings_field_map_select( $value_field, $form['id'] ) . '
</td>
<td>
{buttons}
</td>
</tr>
</tbody>
</table>';
$html .= $this->settings_hidden( $field, false );
$limit = empty( $field['limit'] ) ? 0 : $field['limit'];
$html .= "
<script type=\"text/javascript\">
var dynamicFieldMap". esc_attr( $field['name'] ) ." = new gfieldmap({
'baseURL': '". GFCommon::get_base_url() ."',
'fieldId': '". esc_attr( $field['name'] ) ."',
'fieldName': '". $field['name'] ."',
'keyFieldName': '". $key_field['name'] ."',
'limit': '". $limit . "'
});
</script>";
if ( $echo ) {
echo $html;
}
return $html;
}
public function settings_field_select( $field, $echo = true ) {
$args = is_array( rgar( $field, 'args' ) ) ? rgar( $field, 'args' ) : array( rgar( $field, 'args' ) );
$args = wp_parse_args(
$args, array(
'append_choices' => array(),
'disable_first_choice' => false,
)
);
$field['choices'] = array();
if ( ! $args['disable_first_choice'] ) {
$field['choices'][] = array( 'value' => '', 'label' => '' );
}
$field['choices'] = array_merge( $field['choices'], $this->get_form_fields_as_choices( $this->get_current_form(), $args ) );
if ( ! empty( $args['append_choices'] ) ) {
$field['choices'] = array_merge( $field['choices'], $args['append_choices'] );
}
$html = $this->settings_select( $field, false );
if ( $echo ) {
echo $html;
}
return $html;
}
public function get_form_fields_as_choices( $form, $args = array() ) {
$fields = array();
if ( ! is_array( $form['fields'] ) ) {
return $fields;
}
$args = wp_parse_args(
$args, array(
'field_types' => array(),
'input_types' => array(),
'callback' => false
)
);
foreach ( $form['fields'] as $field ) {
$input_type = GFFormsModel::get_input_type( $field );
$is_applicable_input_type = empty( $args['input_types'] ) || in_array( $input_type, $args['input_types'] );
if ( is_callable( $args['callback'] ) ) {
$is_applicable_input_type = call_user_func( $args['callback'], $is_applicable_input_type, $field, $form );
}
if ( ! $is_applicable_input_type ) {
continue;
}
if ( ! empty( $args['property'] ) && ( ! isset( $field->$args['property'] ) || $field->$args['property'] != $args['property_value'] ) ) {
continue;
}
$inputs = $field->get_entry_inputs();
if ( is_array( $inputs ) ) {
// if this is an address field, add full name to the list
if ( $input_type == 'address' ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Full', 'gravityforms' ) . ')'
);
}
// if this is a name field, add full name to the list
if ( $input_type == 'name' ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Full', 'gravityforms' ) . ')'
);
}
// if this is a checkbox field, add to the list
if ( $input_type == 'checkbox' ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Selected', 'gravityforms' ) . ')'
);
}
foreach ( $inputs as $input ) {
$fields[] = array(
'value' => $input['id'],
'label' => GFCommon::get_label( $field, $input['id'] )
);
}
} elseif ( $input_type == 'list' && $field->enableColumns ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Full', 'gravityforms' ) . ')'
);
$col_index = 0;
foreach ( $field->choices as $column ) {
$fields[] = array(
'value' => $field->id . '.' . $col_index,
'label' => GFCommon::get_label( $field ) . ' (' . rgar( $column, 'text' ) . ')',
);
$col_index ++;
}
} elseif ( ! rgar( $field, 'displayOnly' ) ) {
$fields[] = array( 'value' => $field->id, 'label' => GFCommon::get_label( $field ) );
} else {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field )
);
}
}
return $fields;
}
public function settings_checkbox_and_select( $field, $echo = true ) {
// prepare checkbox
$checkbox_input = rgars( $field, 'checkbox' );
$checkbox_field = array(
'type' => 'checkbox',
'name' => $field['name'] . 'Enable',
'label' => esc_html__( 'Enable', 'gravityforms' ),
'horizontal' => true,
'value' => '1',
'choices' => false,
'tooltip' => false
);
$checkbox_field = wp_parse_args( $checkbox_input, $checkbox_field );
// prepare select
$select_input = rgars( $field, 'select' );
$is_enabled = $this->get_setting( $checkbox_field['name'] );
$select_field = array(
'name' => $field['name'] . 'Value',
'type' => 'select',
'class' => '',
'tooltip' => false
);
$select_field['class'] .= ' ' . $select_field['name'];
$select_field = wp_parse_args( $select_input, $select_field );
// a little more with the checkbox
if( empty( $checkbox_field['choices'] ) ) {
$checkbox_field['choices'] = array(
array(
'name' => $checkbox_field['name'],
'label' => $checkbox_field['label'],
'onchange' => sprintf( "( function( $, elem ) {
$( elem ).parents( 'td' ).css( 'position', 'relative' );
if( $( elem ).prop( 'checked' ) ) {
$( '%1\$s' ).fadeIn();
} else {
$( '%1\$s' ).fadeOut();
}
} )( jQuery, this );",
"#{$select_field['name']}Span" )
)
);
}
// get markup
$html = sprintf(
'%s <span id="%s" class="%s">%s %s</span>',
$this->settings_checkbox( $checkbox_field, false ),
$select_field['name'] . 'Span',
$is_enabled ? '' : 'hidden',
$this->settings_select( $select_field, false ),
$select_field['tooltip'] ? gform_tooltip( $select_field['tooltip'], rgar( $select_field, 'tooltip_class' ) . ' tooltip ' . $select_field['name'], true ) : ''
);
if ( $echo ) {
echo $html;
}
return $html;
}
/***
* Renders the save button for settings pages
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML
*/
protected function settings_save( $field, $echo = true ) {
$field['type'] = 'submit';
$field['name'] = 'gform-settings-save';
$field['class'] = 'button-primary gfbutton';
if ( ! rgar( $field, 'value' ) ) {
$field['value'] = esc_html__( 'Update Settings', 'gravityforms' );
}
$attributes = $this->get_field_attributes( $field );
$html = '<input
type="' . esc_attr( $field['type'] ) . '"
name="' . esc_attr( $field['name'] ) . '"
value="' . esc_attr( $field['value'] ) . '" ' . implode( ' ', $attributes ) . ' />';
if ( $echo ) {
echo $html;
}
return $html;
}
/**
* Helper to create a simple conditional logic set of fields. It creates one row of conditional logic with Field/Operator/Value inputs.
*
* @param mixed $setting_name_root - The root name to be used for inputs. It will be used as a prefix to the inputs that make up the conditional logic fields.
*
* @return string The HTML
*/
protected function simple_condition( $setting_name_root ) {
$conditional_fields = $this->get_conditional_logic_fields();
$value_input = esc_js( '_gaddon_setting_' . esc_attr( $setting_name_root ) . '_value' );
$object_type = esc_js( "simple_condition_{$setting_name_root}" );
$str = $this->settings_select( array(
'name' => "{$setting_name_root}_field_id",
'type' => 'select',
'choices' => $conditional_fields,
'class' => 'optin_select',
'onchange' => "jQuery('#" . esc_js( $setting_name_root ) . "_container').html(GetRuleValues('{$object_type}', 0, jQuery(this).val(), '', '{$value_input}'));"
), false );
$str .= $this->settings_select( array(
'name' => "{$setting_name_root}_operator",
'type' => 'select',
'onchange' => "SetRuleProperty('{$object_type}', 0, 'operator', jQuery(this).val()); jQuery('#" . esc_js( $setting_name_root ) . "_container').html(GetRuleValues('{$object_type}', 0, jQuery('#{$setting_name_root}_field_id').val(), '', '{$value_input}'));",
'choices' => array(
array(
'value' => 'is',
'label' => esc_html__( 'is', 'gravityforms' ),
),
array(
'value' => 'isnot',
'label' => esc_html__( 'is not', 'gravityforms' ),
),
array(
'value' => '>',
'label' => esc_html__( 'greater than', 'gravityforms' ),
),
array(
'value' => '<',
'label' => esc_html__( 'less than', 'gravityforms' ),
),
array(
'value' => 'contains',
'label' => esc_html__( 'contains', 'gravityforms' ),
),
array(
'value' => 'starts_with',
'label' => esc_html__( 'starts with', 'gravityforms' ),
),
array(
'value' => 'ends_with',
'label' => esc_html__( 'ends with', 'gravityforms' ),
),
),
), false );
$str .= sprintf( "<span id='%s_container'></span>", esc_attr( $setting_name_root ) );
$field_id = $this->get_setting( "{$setting_name_root}_field_id" );
$value = $this->get_setting( "{$setting_name_root}_value" );
$operator = $this->get_setting( "{$setting_name_root}_operator" );
if ( empty( $operator ) ){
$operator = 'is';
}
$field_id_attribute = ! empty( $field_id ) ? $field_id : 'jQuery("#' . esc_attr( $setting_name_root ) . '_field_id").val()';
$str .= "<script type='text/javascript'>
var " . esc_attr( $setting_name_root ) . "_object = {'conditionalLogic':{'rules':[{'fieldId':'{$field_id}','operator':'{$operator}','value':'" . esc_attr( $value ) . "'}]}};
jQuery(document).ready(
function(){
gform.addFilter( 'gform_conditional_object', 'SimpleConditionObject' );
jQuery('#" . esc_attr( $setting_name_root ) . "_container').html(
GetRuleValues('{$object_type}', 0, {$field_id_attribute}, '" . esc_attr( $value ) . "', '_gaddon_setting_" . esc_attr( $setting_name_root ) . "_value'));
}
);
</script>";
return $str;
}
/**
* Parses the properties of the $field meta array and returns a set of HTML attributes to be added to the HTML element.
*
* @param array $field - current field meta to be parsed.
* @param array $default - default set of properties. Will be appended to the properties specified in the $field array
*
* @return array - resulting HTML attributes ready to be included in the HTML element.
*/
protected function get_field_attributes( $field, $default = array() ) {
// each nonstandard property will be extracted from the $props array so it is not auto-output in the field HTML
$no_output_props = apply_filters(
'gaddon_no_output_field_properties',
array(
'default_value', 'label', 'choices', 'feedback_callback', 'checked', 'checkbox_label', 'value', 'type',
'validation_callback', 'required', 'hidden', 'tooltip', 'dependency', 'messages', 'name', 'args', 'exclude_field_types',
'field_type'
), $field
);
$default_props = array(
'class' => '', // will default to gaddon-setting
'default_value' => '', // default value that should be selected or entered for the field
);
// Property switch case
switch ( $field['type'] ) {
case 'select':
$default_props['choices'] = array();
break;
case 'checkbox':
$default_props['checked'] = false;
$default_props['checkbox_label'] = '';
$default_props['choices'] = array();
break;
case 'text':
default:
break;
}
$props = wp_parse_args( $field, $default_props );
$props['id'] = rgempty( 'id', $props ) ? rgar( $props, 'name' ) : rgar( $props, 'id' );
$props['class'] = trim( "{$props['class']} gaddon-setting gaddon-{$props['type']}" );
// extract no-output properties from $props array so they are not auto-output in the field HTML
foreach ( $no_output_props as $prop ) {
if ( isset( $props[ $prop ] ) ) {
${$prop} = $props[ $prop ];
unset( $props[ $prop ] );
}
}
//adding default attributes
foreach ( $default as $key => $value ) {
if ( isset( $props[ $key ] ) ) {
$props[ $key ] = $value . $props[ $key ];
} else {
$props[ $key ] = $value;
}
}
// get an array of property strings, example: name='myFieldName'
$prop_strings = array();
foreach ( $props as $prop => $value ) {
$prop_strings[ $prop ] = "{$prop}='" . esc_attr( $value ) . "'";
}
return $prop_strings;
}
/**
* Parses the properties of the $choice meta array and returns a set of HTML attributes to be added to the HTML element.
*
* @param array $choice - current choice meta to be parsed.
* @param array $field_attributes - current field's attributes.
*
* @return array - resulting HTML attributes ready to be included in the HTML element.
*/
protected function get_choice_attributes( $choice, $field_attributes, $default_choice_attributes = array() ) {
$choice_attributes = $field_attributes;
foreach ( $choice as $prop => $val ) {
$no_output_choice_attributes = array(
'default_value', 'label', 'checked', 'value', 'type',
'validation_callback', 'required', 'tooltip',
);
if ( in_array( $prop, $no_output_choice_attributes ) || is_array( $val ) ) {
unset( $choice_attributes[ $prop ] );
} else {
$choice_attributes[ $prop ] = "{$prop}='" . esc_attr( $val ) . "'";
}
}
//Adding default attributes. Either creating a new attribute or pre-pending to an existing one.
foreach ( $default_choice_attributes as $default_attr_name => $default_attr_value ) {
if ( isset( $choice_attributes[ $default_attr_name ] ) ) {
$choice_attributes[ $default_attr_name ] = $this->prepend_attribute( $default_attr_name, $default_attr_value, $choice_attributes[ $default_attr_name ] );
}
else {
$choice_attributes[ $default_attr_name ] = "{$default_attr_name}='" . esc_attr( $default_attr_value ) . "'";
}
}
return $choice_attributes;
}
/***
* @param $name - The name of the attribute to be added
* @param $attribute - The attribute value to be added
* @param $current_attribute - The full string containing the current attribute value
* @return mixed - The new attribute string with the new value added to the beginning of the list
*/
protected function prepend_attribute( $name, $attribute, $current_attribute ) {
return str_replace( "{$name}='", "{$name}='{$attribute}", $current_attribute );
}
/**
* Validates settings fields.
* Validates that all fields are valid. Fields can be invalid when they are blank and marked as required or if it fails a custom validation check.
* To specify a custom validation, use the 'validation_callback' field meta property and implement the validation function with the custom logic.
*
* @param $fields - A list of all fields from the field meta configuration
* @param $settings - A list of submitted settings values
*
* @return bool - Returns true if all fields have passed validation, and false otherwise.
*/
protected function validate_settings( $fields, $settings ) {
foreach ( $fields as $section ) {
if ( ! $this->setting_dependency_met( rgar( $section, 'dependency' ) ) ) {
continue;
}
foreach ( $section['fields'] as $field ) {
if ( ! $this->setting_dependency_met( rgar( $field, 'dependency' ) ) ) {
continue;
}
$field_setting = rgar( $settings, rgar( $field, 'name' ) );
if ( is_callable( rgar( $field, 'validation_callback' ) ) ) {
call_user_func( rgar( $field, 'validation_callback' ), $field, $field_setting );
continue;
}
switch ( $field['type'] ) {
case 'field_map' :
$this->validate_field_map_settings( $field, $settings );
break;
case 'checkbox' :
$this->validate_checkbox_settings( $field, $settings );
break;
default :
if ( rgar( $field, 'required' ) && rgblank( $field_setting ) ) {
$this->set_field_error( $field, rgar( $field, 'error_message' ) );
}
break;
}
}
}
$field_errors = $this->get_field_errors();
$is_valid = empty( $field_errors );
return $is_valid;
}
protected function validate_checkbox_settings( $field, $settings ) {
if ( ! rgar( $field, 'required' ) ) {
return;
}
if ( ! is_array( rgar( $field, 'choices' ) ) ) {
return;
}
foreach ( $field['choices'] as $choice ) {
$choice_setting = rgar( $settings, rgar( $choice, 'name' ) );
if ( ! empty( $choice_setting ) ) {
return;
}
}
$this->set_field_error( $field, rgar( $field, 'error_message' ) );
}
protected function validate_field_map_settings( $field, $settings ) {
$field_map = rgar( $field, 'field_map' );
if ( empty( $field_map ) ) {
return;
}
foreach ( $field_map as $child_field ) {
if ( ! $this->setting_dependency_met( rgar( $child_field, 'dependency' ) ) ) {
continue;
}
$child_field['name'] = $this->get_mapped_field_name( $field, $child_field['name'] );
$setting_value = rgar( $settings, $child_field['name'] );
if ( rgar( $child_field, 'required' ) && rgblank( $setting_value ) ) {
$this->set_field_error( $child_field );
} elseif ( rgar( $child_field, 'validation_callback' ) && is_callable( rgar( $child_field, 'validation_callback' ) ) ) {
call_user_func( rgar( $child_field, 'validation_callback' ), $child_field, $field );
}
}
}
/**
* Sets the validation error message
* Sets the error message to be displayed when a field fails validation.
* When implementing a custom validation callback function, use this function to specify the error message to be displayed.
*
* @param array $field - The current field meta
* @param string $error_message - The error message to be displayed
*/
protected function set_field_error( $field, $error_message = '' ) {
// set default error message if none passed
if ( ! $error_message ) {
$error_message = esc_html__( 'This field is required.', 'gravityforms' );
}
$this->_setting_field_errors[ $field['name'] ] = $error_message;
}
/**
* Gets the validation errors for a field.
* Returns validation errors associated with the specified field or a list of all validation messages (if a field isn't specified)
*
* @param array|boolean $field - Optional. The field meta. When specified, errors for this field will be returned
*
* @return mixed - If a field is specified, a string containing the error message will be returned. Otherwise, an array of all errors will be returned
*/
protected function get_field_errors( $field = false ) {
if ( ! $field ) {
return $this->_setting_field_errors;
}
return isset( $this->_setting_field_errors[ $field['name'] ] ) ? $this->_setting_field_errors[ $field['name'] ] : array();
}
/**
* Gets the invalid field icon
* Returns the markup for an alert icon to indicate and highlight invalid fields.
*
* @param array $field - The field meta.
*
* @return string - The full markup for the icon
*/
protected function get_error_icon( $field ) {
$error = $this->get_field_errors( $field );
return '<span
class="gf_tooltip tooltip"
title="<h6>' . esc_html__( 'Validation Error', 'gravityforms' ) . '</h6>' . $error . '"
style="display:inline-block;position:relative;right:-3px;top:1px;font-size:14px;">
<i class="fa fa-exclamation-circle icon-exclamation-sign gf_invalid"></i>
</span>';
}
/**
* Gets the required indicator
* Gets the markup of the required indicator symbol to highlight fields that are required
*
* @param $field - The field meta.
*
* @return string - Returns markup of the required indicator symbol
*/
protected function get_required_indicator( $field ) {
return '<span class="required">*</span>';
}
/**
* Checks if the specified field failed validation
*
* @param $field - The field meta to be checked
*
* @return bool|mixed - Returns a validation error string if the field has failed validation. Otherwise returns false
*/
protected function field_failed_validation( $field ) {
$field_error = $this->get_field_errors( $field );
return ! empty( $field_error ) ? $field_error : false;
}
/**
* Filter settings fields.
* Runs through each field and applies the 'save_callback', if set, before saving the settings.
* To specify a custom save filter, use the 'save_callback' field meta property and implement the save filter function with the custom logic.
*
* @param $fields - A list of all fields from the field meta configuration
* @param $settings - A list of submitted settings values
*
* @return $settings - The updated settings values.
*/
public function filter_settings( $fields, $settings ) {
foreach ( $fields as $section ) {
if ( ! $this->setting_dependency_met( rgar( $section, 'dependency' ) ) ) {
continue;
}
foreach ( $section['fields'] as $field ) {
if ( ! $this->setting_dependency_met( rgar( $field, 'dependency' ) ) ) {
continue;
}
$field_setting = rgar( $settings, rgar( $field, 'name' ) );
if ( is_callable( rgar( $field, 'save_callback' ) ) ) {
$settings[ $field['name'] ] = call_user_func( rgar( $field, 'save_callback' ), $field, $field_setting );
continue;
}
}
}
return $settings;
}
protected function add_field_before( $name, $fields, $settings ) {
return $this->add_field( $name, $fields, $settings, 'before' );
}
protected function add_field_after( $name, $fields, $settings ) {
return $this->add_field( $name, $fields, $settings, 'after' );
}
protected function add_field( $name, $fields, $settings, $pos ) {
if ( rgar( $fields, 'name' ) ) {
$fields = array( $fields );
}
$pos_mod = $pos == 'before' ? 0 : 1;
foreach ( $settings as &$section ) {
for ( $i = 0; $i < count( $section['fields'] ); $i ++ ) {
if ( $section['fields'][ $i ]['name'] == $name ) {
array_splice( $section['fields'], $i + $pos_mod, 0, $fields );
break 2;
}
}
}
return $settings;
}
protected function remove_field( $name, $settings ) {
foreach ( $settings as &$section ) {
for ( $i = 0; $i < count( $section['fields'] ); $i ++ ) {
if ( $section['fields'][ $i ]['name'] == $name ) {
array_splice( $section['fields'], $i, 1 );
break 2;
}
}
}
return $settings;
}
protected function replace_field( $name, $fields, $settings ) {
if ( rgar( $fields, 'name' ) ) {
$fields = array( $fields );
}
foreach ( $settings as &$section ) {
for ( $i = 0; $i < count( $section['fields'] ); $i ++ ) {
if ( $section['fields'][ $i ]['name'] == $name ) {
array_splice( $section['fields'], $i, 1, $fields );
break 2;
}
}
}
return $settings;
}
protected function get_field( $name, $settings ) {
foreach ( $settings as $section ) {
for ( $i = 0; $i < count( $section['fields'] ); $i ++ ) {
if ( $section['fields'][ $i ]['name'] == $name ) {
return $section['fields'][ $i ];
}
}
}
return false;
}
public function build_choices( $key_value_pairs ) {
$choices = array();
if ( ! is_array( $key_value_pairs ) ) {
return $choices;
}
$first_key = key( $key_value_pairs );
$is_numeric = is_int( $first_key ) && $first_key === 0;
foreach ( $key_value_pairs as $value => $label ) {
if ( $is_numeric ) {
$value = $label;
}
$choices[] = array( 'value' => $value, 'label' => $label );
}
return $choices;
}
//-------------- Form settings ---------------------------------------------------
/**
* Initializes form settings page
* Hooks up the required scripts and actions for the Form Settings page
*/
protected function form_settings_init() {
$view = rgget( 'view' );
$subview = rgget( 'subview' );
if ( $this->current_user_can_any( $this->_capabilities_form_settings ) ) {
add_action( 'gform_form_settings_menu', array( $this, 'add_form_settings_menu' ), 10, 2 );
}
if ( rgget( 'page' ) == 'gf_edit_forms' && $view == 'settings' && $subview == $this->_slug && $this->current_user_can_any( $this->_capabilities_form_settings ) ) {
require_once( GFCommon::get_base_path() . '/tooltips.php' );
add_action( 'gform_form_settings_page_' . $this->_slug, array( $this, 'form_settings_page' ) );
}
}
/**
* Initializes plugin settings page
* Hooks up the required scripts and actions for the Plugin Settings page
*/
protected function plugin_page_init() {
if ( $this->current_user_can_any( $this->_capabilities_plugin_page ) ) {
//creates the subnav left menu
add_filter( 'gform_addon_navigation', array( $this, 'create_plugin_page_menu' ) );
}
}
/**
* Creates plugin page menu item
* Target of gform_addon_navigation filter. Creates a menu item in the left nav, linking to the plugin page
*
* @param $menus - Current list of menu items
*
* @return array - Returns a new list of menu items
*/
public function create_plugin_page_menu( $menus ) {
$menus[] = array( 'name' => $this->_slug, 'label' => $this->get_short_title(), 'callback' => array( $this, 'plugin_page_container' ), 'permission' => $this->_capabilities_plugin_page );
return $menus;
}
/**
* Renders the form settings page.
*
* Not intended to be overridden or called directly by Add-Ons.
* Sets up the form settings page.
*
* @ignore
*/
public function form_settings_page() {
GFFormSettings::page_header( $this->_title );
?>
<div class="gform_panel gform_panel_form_settings" id="form_settings">
<?php
$form = $this->get_current_form();
$form_id = $form['id'];
$form = apply_filters( "gform_admin_pre_render_{$form_id}", apply_filters( 'gform_admin_pre_render', $form ) );
if ( $this->method_is_overridden( 'form_settings' ) ) {
//enables plugins to override settings page by implementing a form_settings() function
$this->form_settings( $form );
} else {
//saves form settings if save button was pressed
$this->maybe_save_form_settings( $form );
//reads current form settings
$settings = $this->get_form_settings( $form );
$this->set_settings( $settings );
//reading addon fields
$sections = $this->form_settings_fields( $form );
GFCommon::display_admin_message();
$page_title = $this->form_settings_page_title();
if ( empty( $page_title ) ) {
$page_title = rgar( $sections[0], 'title' );
//using first section title as page title, so disable section title
$sections[0]['title'] = false;
}
$icon = $this->form_settings_icon();
if ( empty( $icon ) ) {
$icon = '<i class="fa fa-cogs"></i>';
}
?>
<h3><span><?php echo $icon ?> <?php echo $page_title ?></span></h3>
<?php
//rendering settings based on fields and current settings
$this->render_settings( $sections );
}
?>
<script type="text/javascript">
var form = <?php echo json_encode( $this->get_current_form() ) ?>;
</script>
</div>
<?php
GFFormSettings::page_footer();
}
/***
* Saves form settings if the submit button was pressed
*
* @param array $form The form object
*
* @return null|true|false True on success, false on error, null on no action
*/
public function maybe_save_form_settings( $form ) {
if ( $this->is_save_postback() ) {
// store a copy of the previous settings for cases where action would only happen if value has changed
$this->set_previous_settings( $this->get_form_settings( $form ) );
$settings = $this->get_posted_settings();
$sections = $this->form_settings_fields( $form );
$is_valid = $this->validate_settings( $sections, $settings );
$result = false;
if ( $is_valid ) {
$settings = $this->filter_settings( $sections, $settings );
$result = $this->save_form_settings( $form, $settings );
}
if ( $result ) {
GFCommon::add_message( $this->get_save_success_message( $sections ) );
} else {
GFCommon::add_error_message( $this->get_save_error_message( $sections ) );
}
return $result;
}
}
/***
* Saves form settings to form object
*
* @param array $form
* @param array $settings
*
* @return true|false True on success or false on error
*/
public function save_form_settings( $form, $settings ) {
$form[ $this->_slug ] = $settings;
$result = GFFormsModel::update_form_meta( $form['id'], $form );
return ! ( false === $result );
}
/**
* Checks whether the current Add-On has a form settings page.
*
* @return bool
*/
private function has_form_settings_page() {
return $this->method_is_overridden( 'form_settings_fields' ) || $this->method_is_overridden( 'form_settings' );
}
/**
* Custom form settings page
* Override this function to implement a complete custom form settings page.
* Before overriding this function, consider using the form_settings_fields() and specifying your field meta.
*/
protected function form_settings( $form ) {
}
/**
* Custom form settings title
* Override this function to display a custom title on the Form Settings Page.
* By default, the first section in the configuration done in form_settings_fields() will be used as the page title.
* Use this function to override that behavior and add a custom page title.
*/
protected function form_settings_page_title() {
return '';
}
/**
* Override this function to customize the form settings icon
*/
protected function form_settings_icon() {
return '';
}
/**
* Checks whether the current Add-On has a plugin page.
*
* @return bool
*/
private function has_plugin_page() {
return $this->method_is_overridden( 'plugin_page' );
}
/**
* Override this function to create a custom plugin page
*/
protected function plugin_page() {
}
/**
* Override this function to customize the plugin page icon
*/
protected function plugin_page_icon() {
return '';
}
/**
* Override this function to customize the plugin page title
*/
protected function plugin_page_title() {
return $this->_title;
}
/**
* Plugin page container
* Target of the plugin menu left nav icon. Displays the outer plugin page markup and calls plugin_page() to render the actual page.
* Override plugin_page() in order to provide a custom plugin page
*/
public function plugin_page_container() {
?>
<div class="wrap">
<?php
$icon = $this->plugin_page_icon();
if ( ! empty( $icon ) ) {
?>
<img alt="<?php echo $this->get_short_title() ?>" style="margin: 15px 7px 0pt 0pt; float: left;" src="<?php echo $icon ?>" />
<?php
}
?>
<h2 class="gf_admin_page_title"><?php echo $this->plugin_page_title() ?></h2>
<?php
$this->plugin_page();
?>
</div>
<?php
}
/**
* Checks whether the current Add-On has a top level app menu.
*
* @return bool
*/
public function has_app_menu() {
return $this->has_app_settings() || $this->method_is_overridden( 'get_app_menu_items' );
}
/**
* Creates a top level app menu. Adds the app settings page automatically if it's configured.
* Target of the WordPress admin_menu action.
* Not intended to be overridden or called directly by add-ons.
*/
public function create_app_menu() {
$has_full_access = current_user_can( 'gform_full_access' );
$min_cap = GFCommon::current_user_can_which( $this->_capabilities_app_menu );
if ( empty( $min_cap ) ) {
$min_cap = 'gform_full_access';
}
$menu_items = $this->get_app_menu_items();
$addon_menus = array();
$addon_menus = apply_filters( 'gform_addon_app_navigation_' . $this->_slug, $addon_menus );
$parent_menu = self::get_parent_menu( $menu_items, $addon_menus );
if ( empty( $parent_menu ) ) {
return;
}
// Add a top-level left nav
$callback = isset( $parent_menu['callback'] ) ? $parent_menu['callback'] : array( $this, 'app_tab_page' );
global $menu;
$number = 10;
$menu_position = '16.' . $number;
while ( isset( $menu[$menu_position] ) ) {
$number += 10;
$menu_position = '16.' . $number;
}
$menu_position = apply_filters( 'gform_app_menu_position_' . $this->_slug, $menu_position );
$this->app_hook_suffix = add_menu_page( $this->get_short_title(), $this->get_short_title(), $has_full_access ? 'gform_full_access' : $min_cap, $parent_menu['name'], $callback, $this->get_app_menu_icon(), $menu_position );
add_action( "load-$this->app_hook_suffix", array( $this, 'load_screen_options' ) );
// Adding submenu pages
foreach ( $menu_items as $menu_item ) {
$callback = isset( $menu_item['callback'] ) ? $menu_item['callback'] : array( $this, 'app_tab_page' );
add_submenu_page( $parent_menu['name'], $menu_item['label'], $menu_item['label'], $has_full_access || empty( $menu_item['permission'] ) ? 'gform_full_access' : $menu_item['permission'], $menu_item['name'], $callback );
}
if ( is_array( $addon_menus ) ) {
foreach ( $addon_menus as $addon_menu ) {
add_submenu_page( $parent_menu['name'], $addon_menu['label'], $addon_menu['label'], $has_full_access ? 'gform_full_access' : $addon_menu['permission'], $addon_menu['name'], $addon_menu['callback'] );
}
}
if ( $this->has_app_settings() ) {
add_submenu_page( $parent_menu['name'], esc_html__( 'Settings', 'gravityforms' ), esc_html__( 'Settings', 'gravityforms' ), $has_full_access ? 'gform_full_access' : $this->_capabilities_app_settings, $this->_slug . '_settings', array( $this, 'app_tab_page' ) );
}
}
/**
* Returns the parent menu item
*
* @param $menu_items
* @param $addon_menus
*
* @return array|bool The parent menu araray or false if none
*/
private function get_parent_menu( $menu_items, $addon_menus ) {
$parent = false;
if ( GFCommon::current_user_can_any( $this->_capabilities_app_menu ) ) {
foreach ( $menu_items as $menu_item ) {
if ( $this->current_user_can_any( $menu_item['permission'] ) ) {
$parent = $menu_item;
break;
}
}
} elseif ( is_array( $addon_menus ) && sizeof( $addon_menus ) > 0 ) {
foreach ( $addon_menus as $addon_menu ) {
if ( $this->current_user_can_any( $addon_menu['permission'] ) ) {
$parent = array( 'name' => $addon_menu['name'], 'callback' => $addon_menu['callback'] );
break;
}
}
} elseif ( $this->has_app_settings() && $this->current_user_can_any( $this->_capabilities_app_settings ) ) {
$parent = array( 'name' => $this->_slug . '_settings', 'callback' => array( $this, 'app_settings' ) );
}
return $parent;
}
/**
* Override this function to create a top level app menu.
*
* e.g.
* $menu_item['name'] = 'gravitycontacts';
* $menu_item['label'] = __("Contacts", 'gravitycontacts');
* $menu_item['permission'] = 'gravitycontacts_view_contacts';
* $menu_item['callback'] = array($this, 'app_menu');
*
* @return array The array of menu items
*/
protected function get_app_menu_items() {
return array();
}
/**
* Override this function to specify a custom icon for the top level app menu.
* Accepts a dashicon class or a URL.
*
* @return string
*/
protected function get_app_menu_icon() {
return '';
}
/**
* Override this function to load custom screen options.
*
* e.g.
* $screen = get_current_screen();
* if(!is_object($screen) || $screen->id != $this->app_hook_suffix)
* return;
*
* if($this->is_contact_list_page()){
* $args = array(
* 'label' => __('Contacts per page', 'gravitycontacts'),
* 'default' => 20,
* 'option' => 'gcontacts_per_page'
* );
* add_screen_option( 'per_page', $args );
*/
protected function load_screen_options() {
}
/**
* Handles the rendering of app menu items that implement the tabs UI.
*
* Not intended to be overridden or called directly by add-ons.
*/
public function app_tab_page() {
$page = rgget( 'page' );
$current_tab = rgget( 'view' );
if ( $page == $this->_slug . '_settings' ) {
$tabs = $this->get_app_settings_tabs();
} else {
$menu_items = $this->get_app_menu_items();
$current_menu_item = false;
foreach ( $menu_items as $menu_item ) {
if ( $menu_item['name'] == $page ) {
$current_menu_item = $menu_item;
break;
}
}
if ( empty( $current_menu_item ) ) {
return;
}
if ( empty( $current_menu_item['tabs'] ) ) {
return;
}
$tabs = $current_menu_item['tabs'];
}
if ( empty( $current_tab ) ) {
foreach ( $tabs as $tab ) {
if ( ! isset( $tab['permission'] ) || $this->current_user_can_any( $tab['permission'] ) ) {
$current_tab = $tab['name'];
break;
}
}
}
if ( empty( $current_tab ) ) {
wp_die( esc_html__( "You don't have adequate permission to view this page", 'gravityforms' ) );
}
foreach ( $tabs as $tab ) {
if ( $tab['name'] == $current_tab && isset( $tab['callback'] ) && is_callable( $tab['callback'] ) ) {
if ( isset( $tab['permission'] ) && ! $this->current_user_can_any( $tab['permission'] ) ) {
wp_die( esc_html__( "You don't have adequate permission to view this page", 'gravityforms' ) );
}
$title = isset( $tab['label'] ) ? $tab['label'] : $tab['name'];
$this->app_tab_page_header( $tabs, $current_tab, $title, '' );
call_user_func( $tab['callback'] );
$this->app_tab_page_footer();
return;
}
}
$this->app_tab_page_header( $tabs, $current_tab, $current_tab, '' );
$action_hook = 'gform_addon_app_' . $page . '_' . str_replace( ' ', '_', $current_tab );
do_action( $action_hook );
$this->app_tab_page_footer();
}
/**
* Returns the form settings for the Add-On
*
* @param $form
*
* @return string
*/
protected function get_form_settings( $form ) {
return rgar( $form, $this->_slug );
}
/**
* Add the form settings tab.
*
* Override this function to add the tab conditionally.
*
*
* @param $tabs
* @param $form_id
*
* @return array
*/
public function add_form_settings_menu( $tabs, $form_id ) {
$tabs[] = array( 'name' => $this->_slug, 'label' => $this->get_short_title(), 'query' => array( 'fid' => null ) );
return $tabs;
}
/**
* Override this function to specify the settings fields to be rendered on the form settings page
*/
protected function form_settings_fields( $form ) {
// should return an array of sections, each section contains a title, description and an array of fields
return array();
}
//-------------- Plugin Settings ---------------------------------------------------
protected function plugin_settings_init() {
$subview = rgget( 'subview' );
RGForms::add_settings_page(
array(
'name' => $this->_slug,
'tab_label' => $this->get_short_title(),
'title' => $this->plugin_settings_title(),
'handler' => array( $this, 'plugin_settings_page' ),
)
);
if ( rgget( 'page' ) == 'gf_settings' && $subview == $this->_slug && $this->current_user_can_any( $this->_capabilities_settings_page ) ) {
require_once( GFCommon::get_base_path() . '/tooltips.php' );
}
add_filter( 'plugin_action_links', array( $this, 'plugin_settings_link' ), 10, 2 );
}
public function plugin_settings_link( $links, $file ) {
if ( $file != $this->_path ) {
return $links;
}
array_unshift( $links, '<a href="' . admin_url( 'admin.php' ) . '?page=gf_settings&subview=' . $this->_slug . '">' . esc_html__( 'Settings', 'gravityforms' ) . '</a>' );
return $links;
}
/**
* Plugin settings page
*/
public function plugin_settings_page() {
$icon = $this->plugin_settings_icon();
if ( empty( $icon ) ) {
$icon = '<i class="fa fa-cogs"></i>';
}
?>
<h3><span><?php echo $icon ?> <?php echo $this->plugin_settings_title() ?></span></h3>
<?php if ( $this->has_deprecated_elements() ) : ?>
<div class="push-alert-red" style="border-left: 1px solid #E6DB55; border-right: 1px solid #E6DB55;">
<?php esc_html_e( 'This add-on needs to be updated. Please contact the developer.', 'gravityforms' ); ?>
</div>
<?php endif; ?>
<?php
if ( $this->method_is_overridden( 'plugin_settings' ) ) {
//enables plugins to override settings page by implementing a plugin_settings() function
$this->plugin_settings();
} elseif ( $this->maybe_uninstall() ) {
?>
<div class="push-alert-gold" style="border-left: 1px solid #E6DB55; border-right: 1px solid #E6DB55;">
<?php printf( esc_html__( '%s has been successfully uninstalled. It can be re-activated from the %splugins page%s.', 'gravityforms'), $this->_title, "<a href='plugins.php'>", '</a>' ); ?>
</div>
<?php
} else {
//saves settings page if save button was pressed
$this->maybe_save_plugin_settings();
//reads main addon settings
$settings = $this->get_plugin_settings();
$this->set_settings( $settings );
//reading addon fields
$sections = $this->plugin_settings_fields();
GFCommon::display_admin_message();
//rendering settings based on fields and current settings
$this->render_settings( $sections, $settings );
//renders uninstall section
$this->render_uninstall();
}
}
public function plugin_settings_title() {
return sprintf( esc_html__( "%s Settings", "gravityforms" ), $this->get_short_title() );
}
protected function plugin_settings_icon() {
return '';
}
/**
* Override this function to add a custom settings page.
*/
protected function plugin_settings() {
}
/**
* Checks whether the current Add-On has a settings page.
*
* @return bool
*/
public function has_plugin_settings_page() {
return $this->method_is_overridden( 'plugin_settings_fields' ) || $this->method_is_overridden( 'plugin_settings' );
}
/**
* Returns the currently saved plugin settings
* @return mixed
*/
protected function get_plugin_settings() {
return get_option( 'gravityformsaddon_' . $this->_slug . '_settings' );
}
/**
* Get plugin setting
* Returns the plugin setting specified by the $setting_name parameter
*
* @param string $setting_name - Plugin setting to be returned
*
* @return mixed - Returns the specified plugin setting or null if the setting doesn't exist
*/
protected function get_plugin_setting( $setting_name ) {
$settings = $this->get_plugin_settings();
return isset( $settings[ $setting_name ] ) ? $settings[ $setting_name ] : null;
}
/**
* Updates plugin settings with the provided settings
*
* @param array $settings - Plugin settings to be saved
*/
protected function update_plugin_settings( $settings ) {
update_option( 'gravityformsaddon_' . $this->_slug . '_settings', $settings );
}
/**
* Saves the plugin settings if the submit button was pressed
*
*/
protected function maybe_save_plugin_settings() {
if ( $this->is_save_postback() ) {
// store a copy of the previous settings for cases where action whould only happen if value has changed
$this->set_previous_settings( $this->get_plugin_settings() );
$settings = $this->get_posted_settings();
$sections = $this->plugin_settings_fields();
$is_valid = $this->validate_settings( $sections, $settings );
if ( $is_valid ) {
$settings = $this->filter_settings( $sections, $settings );
$this->update_plugin_settings( $settings );
GFCommon::add_message( $this->get_save_success_message( $sections ) );
} else {
GFCommon::add_error_message( $this->get_save_error_message( $sections ) );
}
}
}
/**
* Override this function to specify the settings fields to be rendered on the plugin settings page
* @return array
*/
public function plugin_settings_fields() {
// should return an array of sections, each section contains a title, description and an array of fields
return array();
}
//-------------- App Settings ---------------------------------------------------
/**
* Returns the tabs for the settings app menu item
*
* Not intended to be overridden or called directly by add-ons.
*
* @return array|mixed|void
*/
public function get_app_settings_tabs() {
//build left side options, always have app Settings first and Uninstall last, put add-ons in the middle
$setting_tabs = array( array( 'name' => 'settings', 'label' => esc_html__( 'Settings', 'gravityforms' ), 'callback' => array( $this, 'app_settings_tab' ) ) );
$setting_tabs = apply_filters( 'gform_addon_app_settings_menu_' . $this->_slug, $setting_tabs );
if ( $this->current_user_can_any( $this->_capabilities_uninstall ) ) {
$setting_tabs[] = array( 'name' => 'uninstall', 'label' => esc_html__( 'Uninstall', 'gravityforms' ), 'callback' => array( $this, 'app_settings_uninstall_tab' ) );
}
ksort( $setting_tabs, SORT_NUMERIC );
return $setting_tabs;
}
/**
* Renders the app settings uninstall tab.
*
* Not intended to be overridden or called directly by add-ons.
*/
protected function app_settings_uninstall_tab() {
if ( $this->maybe_uninstall() ) {
?>
<div class="push-alert-gold" style="border-left: 1px solid #E6DB55; border-right: 1px solid #E6DB55;">
<?php sprintf( esc_html__( '%s has been successfully uninstalled. It can be re-activated from the %splugins page%s.', 'gravityforms' ), esc_html( $this->_title ), "<a href='plugins.php'>", '</a>' ); ?>
</div>
<?php
} else {
if ( $this->current_user_can_any( $this->_capabilities_uninstall ) && ( ! function_exists( 'is_multisite' ) || ! is_multisite() || is_super_admin() ) ) {
?>
<form action="" method="post">
<?php wp_nonce_field( 'uninstall', 'gf_addon_uninstall' ) ?>
<?php ?>
<h3>
<span><i class="fa fa-times"></i> <?php printf( esc_html__( 'Uninstall %s', 'gravityforms' ), $this->get_short_title() ); ?></span>
</h3>
<div class="delete-alert alert_red">
<h3>
<i class="fa fa-exclamation-triangle gf_invalid"></i> <?php esc_html_e( 'Warning', 'gravityforms' ); ?>
</h3>
<div class="gf_delete_notice">
<?php echo $this->uninstall_warning_message() ?>
</div>
<?php
$uninstall_button = '<input type="submit" name="uninstall" value="' . sprintf( esc_html__( 'Uninstall %s', 'gravityforms' ), $this->get_short_title() ) . '" class="button" onclick="return confirm(\'' . $this->uninstall_confirm_message() . '\');"/>';
echo $uninstall_button;
?>
</div>
</form>
<?php
}
}
}
/**
* Renders the header for the tabs UI.
*
* @param $tabs
* @param $current_tab
* @param $title
* @param string $message
*/
protected function app_tab_page_header( $tabs, $current_tab, $title, $message = '' ) {
$min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG || isset( $_GET['gform_debug'] ) ? '' : '.min';
// register admin styles
wp_register_style( 'gform_admin', GFCommon::get_base_url() . "/css/admin{$min}.css" );
wp_print_styles( array( 'jquery-ui-styles', 'gform_admin' ) );
?>
<div class="wrap <?php echo GFCommon::get_browser_class() ?>">
<?php if ( $message ) { ?>
<div id="message" class="updated"><p><?php echo $message; ?></p></div>
<?php } ?>
<h2><?php echo esc_html( $title ) ?></h2>
<div id="gform_tab_group" class="gform_tab_group vertical_tabs">
<ul id="gform_tabs" class="gform_tabs">
<?php
foreach ( $tabs as $tab ) {
if ( isset( $tab['permission'] ) && ! $this->current_user_can_any( $tab['permission'] ) ) {
continue;
}
$label = isset( $tab['label'] ) ? $tab['label'] : $tab['name'];
?>
<li <?php echo urlencode( $current_tab ) == $tab['name'] ? "class='active'" : '' ?>>
<a href="<?php echo esc_url( add_query_arg( array( 'view' => $tab['name'] ) ) ); ?>"><?php echo esc_html( $label ) ?></a>
</li>
<?php
}
?>
</ul>
<div id="gform_tab_container" class="gform_tab_container">
<div class="gform_tab_content" id="tab_<?php echo $current_tab ?>">
<?php
}
/**
* Renders the footer for the tabs UI.
*
*/
protected function app_tab_page_footer() {
?>
</div> <!-- / gform_tab_content -->
</div> <!-- / gform_tab_container -->
</div> <!-- / gform_tab_group -->
<br class="clear" style="clear: both;" />
</div> <!-- / wrap -->
<script type="text/javascript">
// JS fix for keep content contained on tabs with less content
jQuery(document).ready(function ($) {
$('#gform_tab_container').css('minHeight', jQuery('#gform_tabs').height() + 100);
});
</script>
<?php
}
public function app_settings_tab() {
require_once( GFCommon::get_base_path() . '/tooltips.php' );
$icon = $this->app_settings_icon();
if ( empty( $icon ) ) {
$icon = '<i class="fa fa-cogs"></i>';
}
?>
<h3><span><?php echo $icon ?> <?php echo $this->app_settings_title() ?></span></h3>
<?php
if ( $this->method_is_overridden( 'app_settings' ) ) {
//enables plugins to override settings page by implementing a plugin_settings() function
$this->app_settings();
} elseif ( $this->maybe_uninstall() ) {
?>
<div class="push-alert-gold" style="border-left: 1px solid #E6DB55; border-right: 1px solid #E6DB55;">
<?php printf( esc_html__( '%s has been successfully uninstalled. It can be re-activated from the %splugins page%s.', 'gravityforms' ), esc_html( $this->_title ), "<a href='plugins.php'>", '</a>' ); ?>
</div>
<?php
} else {
//saves settings page if save button was pressed
$this->maybe_save_app_settings();
//reads main addon settings
$settings = $this->get_app_settings();
$this->set_settings( $settings );
//reading addon fields
$sections = $this->app_settings_fields();
GFCommon::display_admin_message();
//rendering settings based on fields and current settings
$this->render_settings( $sections, $settings );
}
}
/**
* Override this function to specific a custom app settings title
*
* @return string
*/
protected function app_settings_title() {
return sprintf( esc_html__( '%s Settings', 'gravityforms' ), $this->get_short_title() );
}
/**
* Override this function to specific a custom app settings icon
*
* @return string
*/
protected function app_settings_icon() {
return '';
}
/**
* Checks whether the current Add-On has a settings page.
*
* @return bool
*/
public function has_app_settings() {
return $this->method_is_overridden( 'app_settings_fields' ) || $this->method_is_overridden( 'app_settings' );
}
/**
* Override this function to add a custom app settings page.
*/
protected function app_settings() {
}
/**
* Returns the currently saved plugin settings
* @return mixed
*/
protected function get_app_settings() {
return get_option( 'gravityformsaddon_' . $this->_slug . '_app_settings' );
}
/**
* Get app setting
* Returns the app setting specified by the $setting_name parameter
*
* @param string $setting_name - Plugin setting to be returned
*
* @return mixed - Returns the specified plugin setting or null if the setting doesn't exist
*/
protected function get_app_setting( $setting_name ) {
$settings = $this->get_app_settings();
return isset( $settings[ $setting_name ] ) ? $settings[ $setting_name ] : null;
}
/**
* Updates app settings with the provided settings
*
* @param array $settings - App settings to be saved
*/
protected function update_app_settings( $settings ) {
update_option( 'gravityformsaddon_' . $this->_slug . '_app_settings', $settings );
}
/**
* Saves the plugin settings if the submit button was pressed
*
*/
protected function maybe_save_app_settings() {
if ( $this->is_save_postback() ) {
// store a copy of the previous settings for cases where action whould only happen if value has changed
$this->set_previous_settings( $this->get_app_settings() );
$settings = $this->get_posted_settings();
$sections = $this->app_settings_fields();
$is_valid = $this->validate_settings( $sections, $settings );
if ( $is_valid ) {
$settings = $this->filter_settings( $sections, $settings );
$this->update_app_settings( $settings );
GFCommon::add_message( $this->get_save_success_message( $sections ) );
} else {
GFCommon::add_error_message( $this->get_save_error_message( $sections ) );
}
}
}
/**
* Override this function to specify the settings fields to be rendered on the plugin settings page
* @return array
*/
public function app_settings_fields() {
// should return an array of sections, each section contains a title, description and an array of fields
return array();
}
/**
* Returns an flattened array of field settings for the specified settings type ignoring sections.
*
* @param string $settings_type The settings type. e.g. 'plugin'
*
* @return array
*/
protected function settings_fields_only( $settings_type = 'plugin' ) {
$fields = array();
if ( ! is_callable( array( $this, "{$settings_type}_settings_fields" ) ) ) {
return $fields;
}
$sections = call_user_func( array( $this, "{$settings_type}_settings_fields" ) );
foreach ( $sections as $section ) {
foreach ( $section['fields'] as $field ) {
$fields[] = $field;
}
}
return $fields;
}
//-------------- Uninstall ---------------
/**
* Override this function to customize the markup for the uninstall section on the plugin settings page
*/
public function render_uninstall() {
?>
<form action="" method="post">
<?php wp_nonce_field( 'uninstall', 'gf_addon_uninstall' ) ?>
<?php if ( $this->current_user_can_any( $this->_capabilities_uninstall ) ) { ?>
<div class="hr-divider"></div>
<h3><span><i class="fa fa-times"></i> <?php printf( esc_html__( 'Uninstall %s Add-On', 'gravityforms' ), $this->get_short_title() ) ?></span></h3>
<div class="delete-alert alert_red">
<h3><i class="fa fa-exclamation-triangle gf_invalid"></i> Warning</h3>
<div class="gf_delete_notice">
<?php echo $this->uninstall_warning_message() ?>
</div>
<input type="submit" name="uninstall" value="<?php esc_attr_e( 'Uninstall Add-On', 'gravityforms' ) ?>" class="button" onclick="return confirm('<?php echo esc_js( $this->uninstall_confirm_message() ); ?>');">
</div>
<?php
}
?>
</form>
<?php
}
protected function uninstall_warning_message() {
return sprintf( esc_html__( '%sThis operation deletes ALL %s settings%s. If you continue, you will NOT be able to retrieve these settings.', 'gravityforms' ), '<strong>', esc_html( $this->get_short_title() ), '</strong>' );
}
protected function uninstall_confirm_message() {
return sprintf( esc_html__( "Warning! ALL %s settings will be deleted. This cannot be undone. 'OK' to delete, 'Cancel' to stop", 'gravityforms' ), esc_html( $this->get_short_title() ) );
}
/**
* Not intended to be overridden or called directly by Add-Ons.
*
* @ignore
*/
public function maybe_uninstall() {
if ( rgpost( 'uninstall' ) ) {
check_admin_referer( 'uninstall', 'gf_addon_uninstall' );
return $this->uninstall_addon();
}
return false;
}
/**
* Removes all settings and deactivates the Add-On.
*
* Not intended to be overridden or called directly by Add-Ons.
*
* @ignore
*/
public function uninstall_addon() {
if ( ! $this->current_user_can_any( $this->_capabilities_uninstall ) ) {
die( esc_html__( "You don't have adequate permission to uninstall this addon: " . $this->_title, 'gravityforms' ) );
}
$continue = $this->uninstall();
if ( false === $continue ) {
return false;
}
global $wpdb;
$lead_meta_table = GFFormsModel::get_lead_meta_table_name();
$forms = GFFormsModel::get_forms();
$all_form_ids = array();
// remove entry meta
foreach ( $forms as $form ) {
$all_form_ids[] = $form->id;
$entry_meta = $this->get_entry_meta( array(), $form->id );
if ( is_array( $entry_meta ) ) {
foreach ( array_keys( $entry_meta ) as $meta_key ) {
$sql = $wpdb->prepare( "DELETE from $lead_meta_table WHERE meta_key=%s", $meta_key );
$wpdb->query( $sql );
}
}
}
//remove form settings
if ( ! empty( $all_form_ids ) ) {
$form_metas = GFFormsModel::get_form_meta_by_id( $all_form_ids );
require_once( GFCommon::get_base_path() . '/form_detail.php' );
foreach ( $form_metas as $form_meta ) {
if ( isset( $form_meta[ $this->_slug ] ) ) {
unset( $form_meta[ $this->_slug ] );
$form_json = json_encode( $form_meta );
GFFormDetail::save_form_info( $form_meta['id'], addslashes( $form_json ) );
}
}
}
//removing options
delete_option( 'gravityformsaddon_' . $this->_slug . '_settings' );
delete_option( 'gravityformsaddon_' . $this->_slug . '_app_settings' );
delete_option( 'gravityformsaddon_' . $this->_slug . '_version' );
//Deactivating plugin
deactivate_plugins( $this->_path );
update_option( 'recently_activated', array( $this->_path => time() ) + (array) get_option( 'recently_activated' ) );
return true;
}
/**
* Called when the user chooses to uninstall the Add-On - after permissions have been checked and before removing
* all Add-On settings and Form settings.
*
* Override this method to perform additional functions such as dropping database tables.
*
*
* Return false to cancel the uninstall request.
*/
protected function uninstall() {
return true;
}
//-------------- Enforce minimum GF version ---------------------------------------------------
/**
* Target for the after_plugin_row action hook. Checks whether the current version of Gravity Forms
* is supported and outputs a message just below the plugin info on the plugins page.
*
* Not intended to be overridden or called directly by Add-Ons.
*
* @ignore
*/
public function plugin_row() {
if ( ! self::is_gravityforms_supported( $this->_min_gravityforms_version ) ) {
$message = $this->plugin_message();
self::display_plugin_message( $message, true );
}
}
/**
* Returns the message that will be displayed if the current version of Gravity Forms is not supported.
*
* Override this method to display a custom message.
*/
public function plugin_message() {
$message = sprintf( esc_html__( 'Gravity Forms %s is required. Activate it now or %spurchase it today!%s', 'gravityforms' ), $this->_min_gravityforms_version, "<a href='http://www.gravityforms.com'>", '</a>' );
return $message;
}
/**
* Formats and outs a message for the plugin row.
*
* Not intended to be overridden or called directly by Add-Ons.
*
* @ignore
*
* @param $message
* @param bool $is_error
*/
public static function display_plugin_message( $message, $is_error = false ) {
$style = $is_error ? 'style="background-color: #ffebe8;"' : '';
echo '</tr><tr class="plugin-update-tr"><td colspan="5" class="plugin-update"><div class="update-message" ' . $style . '>' . $message . '</div></td>';
}
//--------------- Logging -------------------------------------------------------------
/**
* Writes an error message to the Gravity Forms log. Requires the Gravity Forms logging Add-On.
*
* Not intended to be overridden by Add-Ons.
*
* @ignore
*/
public function log_error( $message ) {
if ( class_exists( 'GFLogging' ) ) {
GFLogging::include_logger();
GFLogging::log_message( $this->_slug, $message, KLogger::ERROR );
}
}
/**
* Writes an error message to the Gravity Forms log. Requires the Gravity Forms logging Add-On.
*
* Not intended to be overridden by Add-Ons.
*
* @ignore
*/
public function log_debug( $message ) {
if ( class_exists( 'GFLogging' ) ) {
GFLogging::include_logger();
GFLogging::log_message( $this->_slug, $message, KLogger::DEBUG );
}
}
//--------------- Locking ------------------------------------------------------------
/**
* Returns the configuration for locking
*
* e.g.
*
* array(
* "object_type" => 'contact',
* "capabilities" => array("gravityforms_contacts_edit_contacts"),
* "redirect_url" => admin_url("admin.php?page=gf_contacts"),
* "edit_url" => admin_url(sprintf("admin.php?page=gf_contacts&id=%d", $contact_id)),
* "strings" => $strings
* );
*
* Override this method to implement locking
*/
public function get_locking_config() {
return array();
}
/**
* Returns TRUE if the current page is the edit page. Otherwise, returns FALSE
*
* Override this method to implement locking on the edit page.
*/
public function is_locking_edit_page() {
return false;
}
/**
* Returns TRUE if the current page is the list page. Otherwise, returns FALSE
*
* Override this method to display locking info on the list page.
*/
public function is_locking_list_page() {
return false;
}
/**
* Returns TRUE if the current page is the view page. Otherwise, returns FALSE
*
* Override this method to display locking info on the view page.
*/
public function is_locking_view_page() {
return false;
}
/**
* Returns the ID of the object to be locked. E.g. Form ID
*
* Override this method to implement locking
*/
public function get_locking_object_id() {
return 0;
}
/**
* Outputs information about the user currently editing the specified object
*
* @param int $object_id The Object ID
* @param bool $echo Whether to echo
*
* @return string The markup for the lock info
*/
public function lock_info( $object_id, $echo = true ) {
$gf_locking = new GFAddonLocking( $this->get_locking_config(), $this );
$lock_info = $gf_locking->lock_info( $object_id, false );
if ( $echo ) {
echo $lock_info;
}
return $lock_info;
}
/**
* Outputs class for the row for the specified Object ID on the list page.
*
* @param int $object_id The object ID
* @param bool $echo Whether to echo
*
* @return string The markup for the class
*/
public function list_row_class( $object_id, $echo = true ) {
$gf_locking = new GFAddonLocking( $this->get_locking_config(), $this );
$class = $gf_locking->list_row_class( $object_id, false );
if ( $echo ) {
echo $class;
}
return $class;
}
/**
* Checked whether an object is locked
*
* @param int|mixed $object_id The object ID
*
* @return bool
*/
public function is_object_locked( $object_id ) {
$gf_locking = new GFAddonLocking( $this->get_locking_config(), $this );
return $gf_locking->is_locked( $object_id );
}
//------------- Field Value Retrieval -------------------------------------------------
/**
* Returns the value of the mapped field.
*
* @param string $setting_name
* @param array $form
* @param array $entry
* @param mixed $settings
*
* @return string
*/
protected function get_mapped_field_value( $setting_name, $form, $entry, $settings = false ) {
$field_id = $this->get_setting( $setting_name, '', $settings );
return $this->get_field_value( $form, $entry, $field_id );
}
/**
* Returns the value of the selected field.
*
* @access private
*
* @param array $form
* @param array $entry
* @param string $field_id
*
* @return string field value
*/
public function get_field_value( $form, $entry, $field_id ) {
$field_value = '';
switch ( strtolower( $field_id ) ) {
case 'form_title':
$field_value = rgar( $form, 'title' );
break;
case 'date_created':
$date_created = rgar( $entry, strtolower( $field_id ) );
if ( empty( $date_created ) ) {
//the date created may not yet be populated if this function is called during the validation phase and the entry is not yet created
$field_value = gmdate( 'Y-m-d H:i:s' );
} else {
$field_value = $date_created;
}
break;
case 'ip':
case 'source_url':
$field_value = rgar( $entry, strtolower( $field_id ) );
break;
default:
$field = GFFormsModel::get_field( $form, $field_id );
$is_integer = $field_id == intval( $field_id );
$input_type = GFFormsModel::get_input_type( $field );
if ( $is_integer && $input_type == 'address' ) {
$field_value = $this->get_full_address( $entry, $field_id );
} elseif ( $is_integer && $input_type == 'name' ) {
$field_value = $this->get_full_name( $entry, $field_id );
} elseif ( $is_integer && $input_type == 'checkbox' ) {
$selected = array();
foreach ( $field->inputs as $input ) {
$index = (string) $input['id'];
if ( ! rgempty( $index, $entry ) ) {
$selected[] = rgar( $entry, $index );
}
}
$field_value = implode( ', ', $selected );
} elseif ( $input_type == 'list' ) {
$field_value = $this->get_list_field_value( $entry, $field_id, $field );
} else {
$field_value = rgar( $entry, $field_id );
}
}
return $this->maybe_override_field_value( $field_value, $form, $entry, $field_id );
}
/**
* Enables use of the gform_SLUG_field_value filter to override the field value. Override this function to prevent the filter being used or to implement a custom filter.
*
* @param string $field_value
* @param array $form
* @param array $entry
* @param string $field_id
*
* @return string
*/
public function maybe_override_field_value( $field_value, $form, $entry, $field_id ) {
/* Get Add-On slug */
$slug = str_replace( 'gravityforms', '', $this->_slug );
return gf_apply_filters( "gform_{$slug}_field_value", array(
$form['id'],
$field_id
), $field_value, $form, $entry, $field_id );
}
/**
* Returns the combined value of the specified Address field.
*
* @param array $entry
* @param string $field_id
*
* @return string
*/
protected function get_full_address( $entry, $field_id ) {
$street_value = str_replace( ' ', ' ', trim( rgar( $entry, $field_id . '.1' ) ) );
$street2_value = str_replace( ' ', ' ', trim( rgar( $entry, $field_id . '.2' ) ) );
$city_value = str_replace( ' ', ' ', trim( rgar( $entry, $field_id . '.3' ) ) );
$state_value = str_replace( ' ', ' ', trim( rgar( $entry, $field_id . '.4' ) ) );
$zip_value = trim( rgar( $entry, $field_id . '.5' ) );
$country_value = GF_Fields::get( 'address' )->get_country_code( trim( rgar( $entry, $field_id . '.6' ) ) );
$address = $street_value;
$address .= ! empty( $address ) && ! empty( $street2_value ) ? " $street2_value" : $street2_value;
$address .= ! empty( $address ) && ( ! empty( $city_value ) || ! empty( $state_value ) ) ? ", $city_value," : $city_value;
$address .= ! empty( $address ) && ! empty( $city_value ) && ! empty( $state_value ) ? " $state_value" : $state_value;
$address .= ! empty( $address ) && ! empty( $zip_value ) ? " $zip_value," : $zip_value;
$address .= ! empty( $address ) && ! empty( $country_value ) ? " $country_value" : $country_value;
return $address;
}
/**
* Returns the combined value of the specified Name field.
*
* @param array $entry
* @param string $field_id
*
* @return string
*/
protected function get_full_name( $entry, $field_id ) {
//If field is simple (one input), simply return full content
$name = rgar( $entry, $field_id );
if ( ! empty( $name ) ) {
return $name;
}
//Complex field (multiple inputs). Join all pieces and create name
$prefix = trim( rgar( $entry, $field_id . '.2' ) );
$first = trim( rgar( $entry, $field_id . '.3' ) );
$middle = trim( rgar( $entry, $field_id . '.4' ) );
$last = trim( rgar( $entry, $field_id . '.6' ) );
$suffix = trim( rgar( $entry, $field_id . '.8' ) );
$name = $prefix;
$name .= ! empty( $name ) && ! empty( $first ) ? ' ' . $first : $first;
$name .= ! empty( $name ) && ! empty( $middle ) ? ' ' . $middle : $middle;
$name .= ! empty( $name ) && ! empty( $last ) ? ' ' . $last : $last;
$name .= ! empty( $name ) && ! empty( $suffix ) ? ' ' . $suffix : $suffix;
return $name;
}
/**
* Returns the value of the specified List field.
*
* @param array $entry
* @param string $field_id
* @param object $field
*
* @return string
*/
protected function get_list_field_value( $entry, $field_id, $field ) {
if ( ! ctype_digit( $field_id ) ) {
$field_id_array = explode( '.', $field_id );
$field_id = rgar( $field_id_array, 0 );
$column_num = rgar( $field_id_array, 1 );
}
$value = rgar( $entry, $field_id );
if ( empty( $value ) ) {
return '';
}
$list_values = $column_values = unserialize( $value );
if ( ! empty( $column_num ) && $field->enableColumns ) {
$column = rgars( $field->choices, "{$column_num}/text" );
$column_values = array();
foreach ( $list_values as $value ) {
$column_values[] = rgar( $value, $column );
}
} elseif ( $field->enableColumns ) {
return $value;
}
return GFCommon::implode_non_blank( ', ', $column_values );
}
/**
* Returns the field ID of the first field of the desired type.
*
* @access public
* @param string $field_type
* @param int $subfield_id (default: null)
* @param int $form_id (default: null)
* @return string
*/
public function get_first_field_by_type( $field_type, $subfield_id = null, $form_id = null, $return_first_only = true ) {
/* Get the current form ID. */
if ( rgblank( $form_id ) ) {
$form_id = rgget( 'id' );
}
/* Get the form. */
$form = GFAPI::get_form( $form_id );
/* Get the request field type for the form. */
$fields = GFAPI::get_fields_by_type( $form, array( $field_type ) );
if ( count( $fields ) == 0 || ( count( $fields ) > 1 && $return_first_only ) ) {
return null;
} else {
if ( rgblank( $subfield_id ) ) {
return $fields[0]->id;
} else {
return $fields[0]->id . '.' . $subfield_id;
}
}
}
//-------------- Helper functions ---------------------------------------------------
protected final function method_is_overridden( $method_name, $base_class = 'GFAddOn' ) {
$reflector = new ReflectionMethod( $this, $method_name );
$name = $reflector->getDeclaringClass()->getName();
return $name !== $base_class;
}
/**
* Returns the url of the root folder of the current Add-On.
*
* @param string $full_path Optional. The full path the the plugin file.
*
* @return string
*/
public function get_base_url( $full_path = '' ) {
if ( empty( $full_path ) ) {
$full_path = $this->_full_path;
}
return plugins_url( null, $full_path );
}
/**
* Returns the url of the Add-On Framework root folder.
*
* @return string
*/
final public static function get_gfaddon_base_url() {
return plugins_url( null, __FILE__ );
}
/**
* Returns the physical path of the Add-On Framework root folder.
*
* @return string
*/
final public static function get_gfaddon_base_path() {
return self::_get_base_path();
}
/**
* Returns the physical path of the plugins root folder.
*
* @param string $full_path
*
* @return string
*/
public function get_base_path( $full_path = '' ) {
if ( empty( $full_path ) ) {
$full_path = $this->_full_path;
}
$folder = basename( dirname( $full_path ) );
return WP_PLUGIN_DIR . '/' . $folder;
}
/**
* Returns the physical path of the Add-On Framework root folder
*
* @return string
*/
private static function _get_base_path() {
$folder = basename( dirname( __FILE__ ) );
return GFCommon::get_base_path() . '/includes/' . $folder;
}
/**
* Returns the URL of the Add-On Framework root folder
*
* @return string
*/
private static function _get_base_url() {
$folder = basename( dirname( __FILE__ ) );
return GFCommon::get_base_url() . '/includes/' . $folder;
}
/**
* Checks whether the Gravity Forms is installed.
*
* @return bool
*/
public function is_gravityforms_installed() {
return class_exists( 'GFForms' );
}
public function table_exists( $table_name ) {
global $wpdb;
$count = $wpdb->get_var( "SHOW TABLES LIKE '{$table_name}'" );
return ! empty( $count );
}
/**
* Checks whether the current version of Gravity Forms is supported
*
* @param $min_gravityforms_version
*
* @return bool|mixed
*/
public function is_gravityforms_supported( $min_gravityforms_version = '' ) {
if ( isset( $this->_min_gravityforms_version ) && empty( $min_gravityforms_version ) ) {
$min_gravityforms_version = $this->_min_gravityforms_version;
}
if ( empty( $min_gravityforms_version ) ) {
return true;
}
if ( class_exists( 'GFCommon' ) ) {
$is_correct_version = version_compare( GFCommon::$version, $min_gravityforms_version, '>=' );
return $is_correct_version;
} else {
return false;
}
}
/**
* Returns this plugin's short title. Used to display the plugin title in small areas such as tabs
*/
protected function get_short_title() {
return isset( $this->_short_title ) ? $this->_short_title : $this->_title;
}
/**
* Returns the unescaped URL for the plugin settings tab associated with this plugin
*
*/
protected function get_plugin_settings_url() {
return add_query_arg( array( 'page' => 'gf_settings', 'subview' => $this->_slug ), admin_url( 'admin.php' ) );
}
/**
* Returns the current form object based on the id query var. Otherwise returns false
*/
protected function get_current_form() {
return rgempty( 'id', $_GET ) ? false : GFFormsModel::get_form_meta( rgget( 'id' ) );
}
/**
* Returns TRUE if the current request is a postback, otherwise returns FALSE
*/
protected function is_postback() {
return is_array( $_POST ) && count( $_POST ) > 0;
}
/**
* Returns TRUE if the settings "Save" button was pressed
*/
protected function is_save_postback() {
return ! rgempty( 'gform-settings-save' );
}
/**
* Returns TRUE if the current page is the form editor page. Otherwise, returns FALSE
*/
protected function is_form_editor() {
if ( rgget( 'page' ) == 'gf_edit_forms' && ! rgempty( 'id', $_GET ) && rgempty( 'view', $_GET ) ) {
return true;
}
return false;
}
/**
* Returns TRUE if the current page is the form settings page, or a specific form settings tab (specified by the $tab parameter). Otherwise returns FALSE
*
* @param string $tab - Specifies a specific form setting page/tab
*
* @return bool
*/
protected function is_form_settings( $tab = null ) {
$is_form_settings = rgget( 'page' ) == 'gf_edit_forms' && rgget( 'view' ) == 'settings';
$is_tab = $this->_tab_matches( $tab );
if ( $is_form_settings && $is_tab ) {
return true;
} else {
return false;
}
}
private function _tab_matches( $tabs ) {
if ( $tabs == null ) {
return true;
}
if ( ! is_array( $tabs ) ) {
$tabs = array( $tabs );
}
$current_tab = rgempty( 'subview', $_GET ) ? 'settings' : rgget( 'subview' );
foreach ( $tabs as $tab ) {
if ( strtolower( $tab ) == strtolower( $current_tab ) ) {
return true;
}
}
}
/**
* Returns TRUE if the current page is the plugin settings main page, or a specific plugin settings tab (specified by the $tab parameter). Otherwise returns FALSE
*
* @param string $tab - Specifies a specific plugin setting page/tab.
*
* @return bool
*/
protected function is_plugin_settings( $tab = '' ) {
$is_plugin_settings = rgget( 'page' ) == 'gf_settings';
$is_tab = $this->_tab_matches( $tab );
if ( $is_plugin_settings && $is_tab ) {
return true;
} else {
return false;
}
}
/**
* Returns TRUE if the current page is the app settings main page, or a specific apps settings tab (specified by the $tab parameter). Otherwise returns FALSE
*
* @param string $tab - Specifies a specific app setting page/tab.
*
* @return bool
*/
protected function is_app_settings( $tab = '' ) {
$is_app_settings = rgget( 'page' ) == $this->_slug . '_settings';
$is_tab = $this->_tab_matches( $tab );
if ( $is_app_settings && $is_tab ) {
return true;
} else {
return false;
}
}
/**
* Returns TRUE if the current page is the plugin page. Otherwise returns FALSE
* @return bool
*/
protected function is_plugin_page() {
return strtolower( rgget( 'page' ) ) == strtolower( $this->_slug );
}
/**
* Returns TRUE if the current page is the entry view page. Otherwise, returns FALSE
* @return bool
*/
protected function is_entry_view() {
if ( rgget( 'page' ) == 'gf_entries' && rgget( 'view' ) == 'entry' && ( ! isset( $_POST['screen_mode'] ) || rgpost( 'screen_mode' ) == 'view' ) ) {
return true;
}
return false;
}
/**
* Returns TRUE if the current page is the entry edit page. Otherwise, returns FALSE
* @return bool
*/
protected function is_entry_edit() {
if ( rgget( 'page' ) == 'gf_entries' && rgget( 'view' ) == 'entry' && rgpost( 'screen_mode' ) == 'edit' ) {
return true;
}
return false;
}
protected function is_entry_list() {
if ( rgget( 'page' ) == 'gf_entries' && rgempty( 'view', $_GET ) ) {
return true;
}
return false;
}
/**
* Returns TRUE if the current page is the results page. Otherwise, returns FALSE
*/
protected function is_results() {
if ( rgget( 'page' ) == 'gf_entries' && rgget( 'view' ) == 'gf_results_' . $this->_slug ) {
return true;
}
return false;
}
/**
* Returns TRUE if the current page is the print page. Otherwise, returns FALSE
*/
protected function is_print() {
if ( rgget( 'gf_page' ) == 'print-entry' ) {
return true;
}
return false;
}
/**
* Returns TRUE if the current page is the preview page. Otherwise, returns FALSE
*/
protected function is_preview() {
if ( rgget( 'gf_page' ) == 'preview' ) {
return true;
}
return false;
}
public function has_deprecated_elements() {
$deprecated = GFAddOn::get_all_deprecated_protected_methods( get_class( $this ) );
if ( ! empty( $deprecated ) ) {
return true;
}
return false;
}
public static function get_all_deprecated_protected_methods($add_on_class_name = ''){
$deprecated = array();
$deprecated = array_merge( $deprecated, self::get_deprecated_protected_methods_for_base_class( 'GFAddOn', $add_on_class_name )) ;
$deprecated = array_merge( $deprecated, self::get_deprecated_protected_methods_for_base_class( 'GFFeedAddOn', $add_on_class_name ) ) ;
$deprecated = array_merge( $deprecated, self::get_deprecated_protected_methods_for_base_class( 'GFPaymentAddOn', $add_on_class_name ) ) ;
return $deprecated;
}
public static function get_deprecated_protected_methods_for_base_class( $base_class_name, $add_on_class_name = '' ) {
$deprecated = array();
if ( ! class_exists( $base_class_name ) ) {
return $deprecated;
}
$base_class_names = array(
'GFAddOn',
'GFFeedAddOn',
'GFPaymentAddOn'
);
$base_class = new ReflectionClass( $base_class_name );
$classes = empty($add_on_class_name) ? get_declared_classes() : array( $add_on_class_name );
foreach ( $classes as $class ) {
if ( ! is_subclass_of( $class, $base_class_name ) || in_array( $class, $base_class_names ) ) {
continue;
}
$add_on_class = new ReflectionClass( $class );
$add_on_methods = $add_on_class->getMethods( ReflectionMethod::IS_PROTECTED );
foreach ( $add_on_methods as $method ) {
$method_name = $method->getName();
$base_has_method = $base_class->hasMethod( $method_name );
$is_declared_by_base_class = $base_has_method && $base_class->getMethod( $method_name )->getDeclaringClass()->getName() == $base_class_name;
$is_overridden = $method->getDeclaringClass()->getName() == $class;
if ( $is_declared_by_base_class && $is_overridden ) {
$deprecated[] = $class . '::' . $method_name;
}
}
}
return $deprecated;
}
}
|
gpl-2.0
|
metaraine/iccs-planar-theme
|
page.php
|
360
|
<?php
/**
* @package Planar
*/
get_header(); ?>
<?php get_template_part( 'template-parts/page', 'header' ); ?>
<?php
if ( !is_front_page() ) :
get_template_part( 'template-parts/page', 'default-content' );
endif;
if ( is_front_page() ) :
get_template_part( 'template-parts/page', 'front-content' );
endif;
?>
<?php get_footer(); ?>
|
gpl-2.0
|
3013216027/acm
|
hdu/3496.cpp
|
1099
|
/* **********************************************
File Name: 3496.cpp
Auther: zhengdongjian@tju.edu.cn
Created Time: 2015/9/9 星期三 下午 8:14:35
*********************************************** */
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
/*
* dp[i][j][k] = min{dp[i - 1][j][k], dp[i - 1][j - 1][k - a[i]] + b[i]}
*/
const int INF = INT_MAX;
const int MAX = 101;
const int MAX_L = 1001;
ll dp[MAX][MAX_L];
ll a[MAX], b[MAX];
#ifdef ONLINE_JUDGE
#define lld I64d
#endif
int main() {
int T;
scanf(" %d", &T);
while (T--) {
int n, m, l;
scanf(" %d %d %d", &n, &m, &l);
for (int i = 1; i <= n; ++i) {
scanf(" %lld %lld", a + i, b + i);
}
memset(dp[0], 0, sizeof(ll) * MAX_L);
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= l; ++j) {
dp[i][j] = -INF;
}
}
for (int i = 1; i <= n; ++i) {
for (int k = l; k >= a[i]; --k) {
for (int j = 1; j <= m; ++j) {
dp[j][k] = max(dp[j][k], dp[j - 1][k - a[i]] + b[i]);
}
}
}
printf("%lld\n", max(dp[m][l], 0LL));
}
return 0;
}
|
gpl-2.0
|
jcbrocca/PFM
|
k-pax-master/src/main/java/uoc/edu/svrKpax/business/GameBOImp.java
|
7873
|
package uoc.edu.svrKpax.business;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import uoc.edu.svrKpax.dao.CategoryDao;
import uoc.edu.svrKpax.dao.GameDao;
import uoc.edu.svrKpax.dao.GameViewDao;
import uoc.edu.svrKpax.util.IntegerWrapper;
import uoc.edu.svrKpax.util.Security;
import uoc.edu.svrKpax.vo.Game;
import uoc.edu.svrKpax.vo.GameView;
import uoc.edu.svrKpax.vo.GamePagination;
public class GameBOImp implements GameBO {
private SessionBO sBo;
private GameDao gDao;
private GameViewDao gvDao;
private CategoryDao cDao;
@Override
public List<Game> listGames(String campusSession) {
if (sBo.validateSession(campusSession) != null) {
return gDao.getAllGames();
}
return null;
}
@Override
public List<Game> listUserGames(String username,String campusSession) {
if (sBo.validateSession(campusSession) != null) {
return gDao.getUserGames(username);
}
List<Game> list = new ArrayList<Game>();
Game game = new Game();
game.setIdGame(1);
list.add(game);
return list;
}
@Override
public Boolean addGame(String campusSession, String nameGame, int idGame) {
try {
if (sBo.validateSession(campusSession) != null) {
Game objGame = new Game();
objGame.setIdGame(idGame);
objGame.setName(nameGame);
objGame.setPublicAcces(0);
objGame.setSecretGame(Security.getIdGame());
objGame.setPrivateKey(Security.getIdSession());
gDao.addGame(objGame);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public List<Game> listGames(String campusSession, int idOrderer, int idFilterer, List<String> fields, List<String> values) {
if (sBo.validateSession(campusSession) != null) {
//Transform fields and values into Map
if(fields.size() != values.size())
return null;
Map <String, String> fields_values = new HashMap <String, String>();
for(int i = 0; i < fields.size(); i++)
{
String field = fields.get(i);
if(field != null && !field.trim().equals(""))
{
fields_values.put(field, values.get(i)); //No duplicated fields validation. Will be overwritten.
}
}
/*---- Validating fields and values -----*/
try
{
switch (idFilterer)
{
case 1: // By category.
if(!fields_values.containsKey("idCategory") ||
fields_values.get("idCategory").trim().equals(""))
{
return null;
}
Integer.parseInt(fields_values.get("idCategory"));
break;
case 2: // By game name.
if(!fields_values.containsKey("name") ||
fields_values.get("name").trim().equals(""))
{
return null;
}
break;
case 3: // By similar games.
if(!fields_values.containsKey("idGame") ||
fields_values.get("idGame").trim().equals(""))
{
return null;
}
Integer.parseInt(fields_values.get("idGame"));
break;
}
}
catch(NumberFormatException e)
{
return null;
}
//Getting the list
List<GameView> gamesView = gvDao.getAllGameViews(idFilterer, idOrderer, fields_values);
if(gamesView == null)
return null;
//Transform GameView list into GameList for returning
List<Game> games = new ArrayList <Game>();
for(GameView gameView: gamesView)
{
games.add(GameView.getGame(gameView));
}
return games;
}
return null;
}
@Override
public Boolean addGame(
String campusSession,
String nameGame,
int idGame,
int idCategory,
Date creationDate,
String developer,
int idPlatform,
int idSkill
) {
try {
//Add the game if user exists, game does not exists, there is a name, there is a creation date and category exists
Game objGame = gDao.getGame(idGame);
if (sBo.validateSession(campusSession) != null &&
objGame == null &&
cDao.getCategory(idCategory) != null &&
gDao.getGameByName(nameGame) == null &&
!nameGame.equals(""))
{
objGame = new Game();
objGame.setIdGame(idGame);
objGame.setName(nameGame);
objGame.setDeveloper(developer);
objGame.setPublicAcces(0);
objGame.setSecretGame(Security.getIdGame());
objGame.setPrivateKey(Security.getIdSession());
objGame.setIdCategory(idCategory);
objGame.setCreationDate(creationDate);
objGame.setIdPlatform(idPlatform);
objGame.setIdSkill(idSkill);
gDao.addGame(objGame);
}
else if(objGame != null){
objGame.setName(nameGame);
objGame.setIdCategory(idCategory);
//jcbrocca - ccamera
objGame.setIdPlatform(idPlatform);
objGame.setIdSkill(idSkill);
gDao.addGame(objGame);
}
else
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public Boolean delGame(String campusSession, int idGame) {
try {
if (sBo.validateSession(campusSession) != null) {
//TODO Delete all dependencies: comments, tags, likeGames, instances, records...
Game objGame = gDao.getGame(idGame);
gDao.delGame(objGame);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public Game getGame(String idGame,String campusSession) {
Game objGame = null;
try {
if (Security.isIdGame(idGame))
objGame = gDao.getGameUid(idGame);
else{
if(sBo.validateSession(campusSession)!=null){
objGame = gDao.getGame(Integer.parseInt(idGame));
}else{
return null;
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return objGame;
}
public void setgDao(GameDao gDao) {
this.gDao = gDao;
}
public GameDao getgDao() {
return gDao;
}
public SessionBO getsBo() {
return sBo;
}
public void setsBo(SessionBO sBo) {
this.sBo = sBo;
}
public GameViewDao getGvDao() {
return gvDao;
}
public void setGvDao(GameViewDao gvDao) {
this.gvDao = gvDao;
}
public CategoryDao getcDao() {
return cDao;
}
public void setcDao(CategoryDao cDao) {
this.cDao = cDao;
}
@Override
public List<Game> listDeveloperGames(String campusSession, String developer) {
if (sBo.validateSession(campusSession) != null) {
if(!developer.equals(""))
{
return gDao.getDeveloperGame(developer);
}
}
return null;
}
@Override
public List<Game> listNotDeveloperGames(String campusSession, String developer) {
if (sBo.validateSession(campusSession) != null) {
if(!developer.equals(""))
{
return gDao.getNotDeveloperGame(developer);
}
}
return null;
}
@Override
public List<Game> listUnauthorizedGames(String campusSession){
if (sBo.validateSession(campusSession) != null) {
return gDao.getUnauthorizedGame();
}
return null;
}
@Override
public boolean authorizeGame(String campusSession, int idGame){
try {
if (sBo.validateSession(campusSession) != null) {
Game objGame = gDao.getGame(idGame);
objGame.setPublicAcces(1);
gDao.addGame(objGame);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/*Corral*/
@Override
public GamePagination listGamesSearch(
String campusSession,
String text,
Integer offset,
Integer limit) {
if (sBo.validateSession(campusSession) != null) {
GamePagination gamepagination = new GamePagination();
IntegerWrapper total = new IntegerWrapper();
gamepagination.setGames(
gDao.getGamesSearch(
text,
offset,
limit,
total
)
);
gamepagination.setOffset(offset);
gamepagination.setLimit(limit);
gamepagination.setTotal(total);
return gamepagination;
}
return null;
}
@Override
public List<Game> listSimilarGames(String campusSession, String idGame){
if (sBo.validateSession(campusSession) != null) {
return gDao.getSimilarGames(idGame);
}
return null;
}
}
|
gpl-2.0
|
GTNewHorizons/Yamcl
|
src/main/java/eu/usrv/yamcore/auxiliary/TabText.java
|
8889
|
package eu.usrv.yamcore.auxiliary;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* <pre>
* TabText: class to write column formatted text in minecraft chat area
*
* - it splits each field and trims or fill with spaces to adjust tabs
*
* general usage example:
*
* - create a multiline string similar to csv format and create a TabText object with it
* - use line feed "\n" (ascii 10) as line separator and grave accent "`" (ascii 96) as field separator
* - you can use some format codes, see http://minecraft.gamepedia.com/Formatting_codes
* - DO NOT USE LOWERCASE CODES OR BOLD FORMAT BECAUSE IT CAN BREAK SPACING
*
* - // example
* - multilineString = "PLAYER------`RATE------`RANK------\n";
* - multilineString += "§EJohn`10.01`1§R\n";
* - multilineString += "Doe`-9.30`2";
*
* - TabText tt = new TabText(multilineString);
* - int numPages = tt.setPageHeight(pageHeight); // set page height and get number of pages
* - tt.setTabs(10, 18, ...); // horizontal tabs positions
* - tt.sortByFields(-2, 1); // sort by second column descending, then by first
* - printedText = tt.getPage(desiredPage, (boolean) monospace); // get your formatted page, for console or chat area
*
* see each method javadoc for additional details
*
* @version 5
* @author atesin#gmail,com
* </pre>
*/
public class TabText
{
private int chatHeight;
private int[] tabs;
private int numPages;
private String[] lines;
private Map<Integer, String> charList = new HashMap<Integer, String>(){
{
put( -6, "§" );
put( 2, "!.,:;i|" );
put( 3, "'`l" );
put( 4, " I[]t" );
put( 5, "\"()*<>fk{}" );
put( 7, "@~" );
}
};
// CONSTRUCTOR METHOD
public TabText( String multilineString )
{
setText( multilineString );
}
// SETTER METHODS
/** can reuse the object to save resources by calling this method */
public void setText( String multilineString )
{
lines = multilineString.split( "\n", -1 );
}
/**
* set page height and get number of pages according to it, for later use with getPage()
*
* @param chatHeight lines you want for each page, no more than 10 recommended
* @return number of pages your text will have
*/
public int setPageHeight( int chatHeight )
{
this.chatHeight = chatHeight;
numPages = (int) Math.ceil( (double) lines.length / (double) chatHeight );
return numPages;
}
/**
* set horizontal positions of "`" separators, considering 6px chars and 53 chars max
*
* @param tabs an integer list with desired tab column positions
*/
public void setTabs( int... tabs )
{
int[] tabs2 = new int[tabs.length + 1];
tabs2[0] = tabs[0];
for( int i = 1; i < tabs.length; ++i )
tabs2[i] = tabs[i] - tabs[i - 1];
tabs2[tabs.length] = 53 - tabs[tabs.length - 1];
this.tabs = tabs2;
}
// REGULAR METHODS
/**
* append chars with its width to be checked too, default width = 6 so you may only use for width != 6 chars
*
* @param chars a string with the chars to be added (careful with unicode or ansi chars, do some tests before)
* @param charsWidth horizontal space in pixels each char occupies
*/
public void addChars( String charsList, int charsWidth )
{
if( charsWidth == 6 )
return;
if( !charList.containsKey( charsWidth ) )
charList.put( charsWidth, "" );
charList.get( charsWidth ).concat( charsList );
}
/**
* get your formatted page, for chat area or console
*
* @param page desired page number (0 = all in one), considering preconfigured page height
* @param monospace true if fonts are fixed width (for server console) or false if variable with (for chat area)
* @return desired formatted, tabbed page
*/
public String getPage( int page, boolean monospace )
{
// get bounds if user wants pages
int fromLine = ( --page ) * chatHeight;
int toLine = ( fromLine + chatHeight > lines.length ) ? lines.length : fromLine + chatHeight;
if( page < 0 )
{
fromLine = 0;
toLine = lines.length;
}
// prepare lines iteration
int tab;
String line;
String lines2 = "";
String fields[];
Object[] field;
int lineLen;
int lineLen2;
// iterate each line
for( int linePos = fromLine; linePos < toLine; ++linePos )
{
fields = lines[linePos].split( "`", -1 );
line = "";
lineLen = 0;
lineLen2 = 0;
// start iterating each field
for( int fieldPos = 0; fieldPos < fields.length; ++fieldPos )
{
// add spaces to adjust horizontal position before if needed
if( !monospace && lineLen % 4 > 1 )
{
line += '.';
lineLen += 2;
}
// add spaces to fill width needed width too
while( lineLen < lineLen2 )
{
line += ' ';
lineLen += ( monospace ) ? 1 : 4;
}
// get field and set line properties
tab = ( monospace ) ? tabs[fieldPos] : tabs[fieldPos] * 6;
field = pxSubstring( fields[fieldPos], tab, monospace );
line += (String) field[0];
lineLen += (int) field[1];
lineLen2 += tab;
}
lines2 += ( lines2.length() < 1 ) ? line : '\n' + line;
}
return lines2;
}
// PIXEL WIDTH CALCULATION METHODS
/**
* returns substring, in chars or pixels, considering format codes
*
* @param str input string
* @param len desired string length
* @param mono true if lenght will be in chars (for console) or false if will be in pixels (for chat area)
* @return object array with stripped string [0] and integer length in pixels or chars depending of mono
*/
private Object[] pxSubstring( String str, int len, boolean mono )
{
int len2 = 0;
int len3 = 0;
int len4 = 0;
for( char ch : str.toCharArray() )
{
len3 += pxLen( ch, mono );
if( len3 > len )
break;
++len4;
len2 = len3;
}
return new Object[] { str.substring( 0, len4 ), len2 };
}
/**
* returns character total width, considering format codes, internal use
*
* @param ch the character to check
* @param mono true for result in chars or false for result in pixels
* @return character width depending of "mono"
*/
private int pxLen( char ch, boolean mono )
{
if( mono )
return ( ch == '§' ) ? -1 : 1;
// character list iteration, 6 = default
int l = 6;
for( int px : charList.keySet() )
{
if( charList.get( px ).indexOf( ch ) >= 0 )
{
l = px;
break;
}
}
return l;
}
/**
* sort lines by column values, string or numeric, IF SORT BY DECIMALS IT MUST HAVE SAME DECIMAL POSITIONS
*
* @param keys a list of column numbers criteria where 1 represents first columnn and so, negative numbers means
* descending order
*/
public void sortByFields( int... keys )
{
// get indexes and sort orders first
boolean[] desc = new boolean[keys.length];
for( int i = 0; i < keys.length; ++i )
{
// get field and direction
desc[i] = ( keys[i] < 0 );
keys[i] = Math.abs( keys[i] ) - 1;
}
// iterate lines
String[] fields;
String line;
String field;
String field2;
double num;
boolean desc2;
String[] lines2 = new String[lines.length];
for( int i = 0; i < lines.length; ++i )
{
// iterate fields
fields = lines[i].replaceAll( "§.", "" ).split( "`", -1 );
line = "";
for( int j = 0; j < keys.length; ++j )
{
// probe if field looks like a number
field = fields[keys[j]];
field2 = "~";
try
{
num = Double.parseDouble( field );
for( int k = field.length(); k < 53; ++k )
field2 += " ";
field2 += field;
// reverse order if negative number
desc2 = ( num < 0 ) ? ( desc[j] == false ) : desc[j];
}
catch( NumberFormatException e )
{
field2 += field;
for( int k = field.length(); k < 53; ++k )
field2 += " ";
desc2 = desc[j];
}
// reverse field char values if reverse order (like in rot13)
if( desc2 )
{
field = "";
for( char c : field2.toCharArray() )
field += (char) ( 158 - c );
field2 = field;
}
// add field to line
line += field2;
}
// add line to lines
lines2[i] = line + "`" + i;
}
// sort lines
Arrays.sort( lines2 );
// rearrange and set lines
String[] lines3 = new String[lines.length];
for( int i = 0; i < lines.length; ++i )
{
fields = lines2[i].split( "`", -1 );
lines3[i] = lines[Integer.parseInt( fields[1] )];
}
lines = lines3;
}
}
|
gpl-2.0
|
Francesco149/lainbot
|
plugins/decode.lua
|
787
|
local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
local function dec(data)
data = string.gsub(data, '[^'..b..'=]', '')
return (data:gsub('.', function(x)
if (x == '=') then return '' end
local r,f='',(b:find(x)-1)
for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
return r;
end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
if (#x ~= 8) then return '' end
local c=0
for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
return string.char(c)
end))
end
local function run(msg, matches)
return dec(matches[1])
end
return {
description = "Simplest plugin ever!",
usage = "!dec [whatever]: decodes base64 string",
patterns = {
"^!dec (.*)$"
},
run = run
}
|
gpl-2.0
|
nrgaway/qubes-gui-daemon
|
qubesguidaemon/mic.py
|
4765
|
# -*- encoding: utf-8 -*-
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2017 Marek Marczykowski-Górecki
# <marmarek@invisiblethingslab.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, see <http://www.gnu.org/licenses/>.
'''Microphone control extension'''
import asyncio
import subprocess
import qubes.devices
import qubes.ext
import qubes.vm.adminvm
class MicDevice(qubes.devices.DeviceInfo):
'''Microphone device info class'''
pass
class MicDeviceExtension(qubes.ext.Extension):
'''Extension to control microphone access
'''
def __init__(self):
super(MicDeviceExtension, self).__init__()
def get_device(self, app):
return MicDevice(app.domains[0], 'mic', 'Microphone')
@qubes.ext.handler('device-list:mic')
def on_device_list_mic(self, vm, event):
'''List microphone device
Currently this assume audio being handled in dom0. When adding support
for GUI domain, this needs to be changed
'''
return self.on_device_get_mic(vm, event, 'mic')
@qubes.ext.handler('device-get:mic')
def on_device_get_mic(self, vm, event, ident):
'''Get microphone device
Currently this assume audio being handled in dom0. When adding support
for GUI domain, this needs to be changed
'''
# pylint: disable=unused-argument,no-self-use
if not isinstance(vm, qubes.vm.adminvm.AdminVM):
return
if ident != 'mic':
return
yield self.get_device(vm.app)
@qubes.ext.handler('device-list-attached:mic')
def on_device_list_attached_mic(self, vm, event, persistent=None):
'''List attached microphone to the VM'''
if persistent is True:
return
audiovm = getattr(vm, 'audiovm', None)
if audiovm is None or not audiovm.is_running():
return
untrusted_audio_input = audiovm.untrusted_qdb.read(
'/audio-input/{}'.format(vm.name))
if untrusted_audio_input == b'1':
# (device, options)
yield (self.get_device(vm.app), {})
@qubes.ext.handler('device-pre-attach:mic')
@asyncio.coroutine
def on_device_pre_attach_mic(self, vm, event, device, options):
'''Attach microphone to the VM'''
# there is only one microphone
assert device == self.get_device(vm.app)
if options:
raise qubes.exc.QubesException(
'mic device does not support options')
audiovm = getattr(vm, 'audiovm', None)
if audiovm is None:
raise qubes.exc.QubesException(
"VM {} has no AudioVM set".format(vm))
if not audiovm.is_running():
raise qubes.exc.QubesVMNotRunningError(audiovm,
"Audio VM {} isn't running".format(audiovm))
try:
yield from audiovm.run_service_for_stdio(
'qubes.AudioInputEnable+{}'.format(vm.name))
except subprocess.CalledProcessError as e:
raise qubes.exc.QubesVMError(vm,
'Failed to attach audio input from {!s} to {!s}: '
'pulseaudio agent not running'.format(audiovm, vm))
@qubes.ext.handler('device-pre-detach:mic')
@asyncio.coroutine
def on_device_pre_detach_mic(self, vm, event, device):
'''Detach microphone from the VM'''
# there is only one microphone
assert device == self.get_device(vm.app)
audiovm = getattr(vm, 'audiovm', None)
if audiovm is None:
raise qubes.exc.QubesException(
"VM {} has no AudioVM set".format(vm))
if not audiovm.is_running():
raise qubes.exc.QubesVMNotRunningError(audiovm,
"Audio VM {} isn't running".format(audiovm))
try:
yield from audiovm.run_service_for_stdio(
'qubes.AudioInputDisable+{}'.format(vm.name))
except subprocess.CalledProcessError as e:
raise qubes.exc.QubesVMError(vm,
'Failed to detach audio input from {!s} to {!s}: '
'pulseaudio agent not running'.format(audiovm, vm))
|
gpl-2.0
|
ByeDream/HappyValley
|
Source/Framework/Modules/Timer/Platform/Windows/TimerWin.cpp
|
644
|
/************************************************************************/
/* The Timer Windows Implementation
/*
/* ByeDream
/* Dec-25-2015
/************************************************************************/
#include "stdafx.h"
#include "Framework/Utility/Utility.h"
#include "TimerWin.h"
HV::TimerWin::TimerWin(Application *app)
: Timer(app)
{
}
INT64 HV::TimerWin::getTimeUnitCount() const
{
INT64 count = 0;
QueryPerformanceCounter((LARGE_INTEGER*)&count);
return count;
}
INT64 HV::TimerWin::getTimeUnitFrequency() const
{
INT64 frequency = 0;
QueryPerformanceFrequency((LARGE_INTEGER*)&frequency);
return frequency;
}
|
gpl-2.0
|
njustesen/bloodai
|
src/game/GameMaster.java
|
5580
|
package game;
import java.util.HashMap;
import game.process.BlockProcess;
import game.process.CoinTossProcess;
import game.process.EndPhaseProcess;
import game.process.EndPlayerTurnProcess;
import game.process.EndSetupProcess;
import game.process.FollowUpProcess;
import game.process.FoulProcess;
import game.process.GameStartProcess;
import game.process.GameProcess;
import game.process.HandOffProcess;
import game.process.InterceptionProcess;
import game.process.KickBallProcess;
import game.process.MovePlayerProcess;
import game.process.PassProcess;
import game.process.PlaceBallOnPlayerProcess;
import game.process.PlaceBallProcess;
import game.process.PlacePlayerInReservesProcess;
import game.process.PlacePlayerProcess;
import game.process.PushProcess;
import game.process.RerollProcess;
import game.process.SelectActionProcess;
import game.process.SelectDieProcess;
import game.process.StandUpProcess;
import game.rulebooks.RuleBook;
import ai.AIAgent;
import ai.actions.Action;
import ai.actions.BlockPlayerAction;
import ai.actions.EndPhaseAction;
import ai.actions.EndPlayerTurnAction;
import ai.actions.EndSetupAction;
import ai.actions.FollowUpAction;
import ai.actions.FoulPlayerAction;
import ai.actions.HandOffPlayerAction;
import ai.actions.IllegalActionException;
import ai.actions.KickBallAction;
import ai.actions.PlacePlayerInReservesAction;
import ai.actions.SelectInterceptionAction;
import ai.actions.MovePlayerAction;
import ai.actions.PassPlayerAction;
import ai.actions.PlaceBallAction;
import ai.actions.PlaceBallOnPlayerAction;
import ai.actions.PlacePlayerAction;
import ai.actions.RerollAction;
import ai.actions.SelectCoinSideAction;
import ai.actions.SelectCoinTossEffectAction;
import ai.actions.SelectDieAction;
import ai.actions.SelectPlayerTurnAction;
import ai.actions.SelectPushSquareAction;
import ai.actions.StandPlayerUpAction;
import ai.actions.StartGameAction;
import ai.util.GameStateCloner;
import models.GameStage;
import models.GameState;
import models.Turn;
public class GameMaster {
private GameState state;
private RuleBook rulebook;
private AIAgent homeAgent;
private AIAgent awayAgent;
private HashMap<Class<? extends Action>, GameProcess> processes;
public GameMaster(GameState gameState, RuleBook rulebook, AIAgent homeAgent, AIAgent awayAgent) {
super();
this.state = gameState;
this.rulebook = rulebook;
this.homeAgent = homeAgent;
this.awayAgent = awayAgent;
init();
}
private void init() {
processes = new HashMap<Class<? extends Action>, GameProcess>();
processes.put(StartGameAction.class, new GameStartProcess());
processes.put(RerollAction.class, new RerollProcess());
processes.put(SelectDieAction.class, new SelectDieProcess());
processes.put(PlacePlayerAction.class, new PlacePlayerProcess());
processes.put(PlacePlayerInReservesAction.class,new PlacePlayerInReservesProcess());
processes.put(SelectPlayerTurnAction.class, new SelectActionProcess());
processes.put(PlaceBallOnPlayerAction.class, new PlaceBallOnPlayerProcess());
processes.put(MovePlayerAction.class, new MovePlayerProcess());
processes.put(StandPlayerUpAction.class, new StandUpProcess());
processes.put(BlockPlayerAction.class, new BlockProcess());
processes.put(PassPlayerAction.class, new PassProcess());
processes.put(HandOffPlayerAction.class, new HandOffProcess());
processes.put(FoulPlayerAction.class, new FoulProcess());
processes.put(FollowUpAction.class, new FollowUpProcess());
processes.put(SelectPushSquareAction.class, new PushProcess());
processes.put(EndPlayerTurnAction.class, new EndPlayerTurnProcess());
processes.put(EndPhaseAction.class, new EndPhaseProcess());
processes.put(SelectInterceptionAction.class, new InterceptionProcess());
processes.put(KickBallAction.class, new KickBallProcess());
processes.put(SelectCoinSideAction.class, new CoinTossProcess());
processes.put(SelectCoinTossEffectAction.class, new CoinTossProcess());
processes.put(EndSetupAction.class, new EndSetupProcess());
processes.put(PlaceBallAction.class, new PlaceBallProcess());
}
/**
* Starts the blood bowl game.
*/
public void start(){
while(true)
update();
}
/**
* Updates the Blood Bowl game.
* Decide whether to:
* 1) await UI input or
* 2) call AI agent
*/
public void update(){
// Begin game if not started
/*
if (state.getGameStage() == GameStage.START_UP){
try {
GameStartProcess.getInstance().run(state, null, rulebook);
} catch (IllegalActionException e) {
e.printStackTrace();
}
return;
}
*/
// If game is ended
if (state.getGameStage() == GameStage.GAME_ENDED)
return;
boolean home = Turn.isHomeTurn(state);
Action action = null;
GameState clone = new GameStateCloner().clone(state);
// Call AI agent or await UI
if (home && homeAgent != null)
action = homeAgent.takeAction(this, clone);
else if (!home && awayAgent != null)
action = awayAgent.takeAction(this, clone);
if (action != null){
try {
act(action);
} catch (IllegalActionException e) {
e.printStackTrace();
}
}
}
public void act(Action action) throws IllegalActionException {
if (action == null)
throw new NullPointerException("Action is null!");
GameProcess process = processes.get(action.getClass());
if (process == null)
throw new IllegalActionException("Unsupported action type!");
process.run(state, action, rulebook);
}
public GameState getState() {
return state;
}
}
|
gpl-2.0
|
niloc132/mauve-gwt
|
src/main/java/gnu/testlet/java/lang/reflect/sub/OtherPkg.java
|
218
|
package gnu.testlet.java.lang.reflect.sub;
public class OtherPkg
{
static void g()
{
}
void h()
{
}
protected void i()
{
}
static char j = 'j';
char k = 'k';
protected char l = 'l';
}
|
gpl-2.0
|
LeDYoM/Zoper
|
haf/include/haf/filesystem/include/path.hpp
|
208
|
#pragma once
#ifndef HAF_FILESYSTEM_PATH_INCLUDE_HPP
#define HAF_FILESYSTEM_PATH_INCLUDE_HPP
#include <mtypes/include/str.hpp>
namespace haf::sys
{
using Path = mtps::str;
} // namespace haf::sys
#endif
|
gpl-2.0
|
Martazza/OpenNos
|
OpenNos.DAL.Interface/IInventoryDAO.cs
|
632
|
using OpenNos.Data;
using System.Collections.Generic;
namespace OpenNos.DAL.Interface
{
public interface IInventoryDAO
{
#region Methods
DeleteResult DeleteFromSlotAndType(long characterId, short slot, short type);
SaveResult InsertOrUpdate(ref InventoryDTO inventory);
IEnumerable<InventoryDTO> LoadByCharacterId(long characterId);
InventoryDTO LoadByInventoryItem(long InventoryItemId);
InventoryDTO LoadBySlotAndType(long characterId, short slot, short type);
IEnumerable<InventoryDTO> LoadByType(long characterId, short type);
#endregion
}
}
|
gpl-2.0
|
junqiang521/Test
|
dnvme/tnvme-master/GrpNVMReadCmd/createResources_r10b.cpp
|
5096
|
/*
* Copyright (c) 2011, Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "createResources_r10b.h"
#include "globals.h"
#include "grpDefs.h"
#include "../Queues/acq.h"
#include "../Queues/asq.h"
#include "../Queues/iocq.h"
#include "../Queues/iosq.h"
#include "../Utils/kernelAPI.h"
#include "../Utils/queues.h"
#include "../Utils/irq.h"
namespace GrpNVMReadCmd {
static uint32_t NumEntriesIOQ = 2;
CreateResources_r10b::CreateResources_r10b(
string grpName, string testName) :
Test(grpName, testName, SPECREV_10b)
{
// 63 chars allowed: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
mTestDesc.SetCompliance("revision 1.0b, section 5");
mTestDesc.SetShort( "Create resources needed by subsequent tests");
// No string size limit for the long description
mTestDesc.SetLong(
"Create resources with group lifetime which are needed by subsequent "
"tests");
}
CreateResources_r10b::~CreateResources_r10b()
{
///////////////////////////////////////////////////////////////////////////
// Allocations taken from the heap and not under the control of the
// RsrcMngr need to be freed/deleted here.
///////////////////////////////////////////////////////////////////////////
}
CreateResources_r10b::
CreateResources_r10b(const CreateResources_r10b &other) : Test(other)
{
///////////////////////////////////////////////////////////////////////////
// All pointers in this object must be NULL, never allow shallow or deep
// copies, see Test::Clone() header comment.
///////////////////////////////////////////////////////////////////////////
}
CreateResources_r10b &
CreateResources_r10b::operator=(const CreateResources_r10b &other)
{
///////////////////////////////////////////////////////////////////////////
// All pointers in this object must be NULL, never allow shallow or deep
// copies, see Test::Clone() header comment.
///////////////////////////////////////////////////////////////////////////
Test::operator=(other);
return *this;
}
Test::RunType
CreateResources_r10b::RunnableCoreTest(bool preserve)
{
///////////////////////////////////////////////////////////////////////////
// All code contained herein must never permanently modify the state or
// configuration of the DUT. Permanence is defined as state or configuration
// changes that will not be restored after a cold hard reset.
///////////////////////////////////////////////////////////////////////////
preserve = preserve; // Suppress compiler error/warning
return RUN_TRUE; // This test is never destructive
}
void
CreateResources_r10b::RunCoreTest()
{
/** \verbatim
* Assumptions:
* 1) This is the 1st within GrpBasicInit.
* \endverbatim
*/
if (gCtrlrConfig->SetState(ST_DISABLE_COMPLETELY) == false)
throw FrmwkEx(HERE);
SharedACQPtr acq = CAST_TO_ACQ(
gRsrcMngr->AllocObj(Trackable::OBJ_ACQ, ACQ_GROUP_ID))
acq->Init(5);
SharedASQPtr asq = CAST_TO_ASQ(
gRsrcMngr->AllocObj(Trackable::OBJ_ASQ, ASQ_GROUP_ID))
asq->Init(5);
// All queues will use identical IRQ vector
IRQ::SetAnySchemeSpecifyNum(1); // throws upon error
gCtrlrConfig->SetCSS(CtrlrConfig::CSS_NVM_CMDSET);
if (gCtrlrConfig->SetState(ST_ENABLE) == false)
throw FrmwkEx(HERE);
{
uint64_t maxIOQEntries;
// Determine the max IOQ entries supported
if (gRegisters->Read(CTLSPC_CAP, maxIOQEntries) == false)
throw FrmwkEx(HERE, "Unable to determine MQES");
maxIOQEntries &= CAP_MQES;
maxIOQEntries += 1; // convert to 1-based
if (maxIOQEntries < (uint64_t)NumEntriesIOQ) {
LOG_NRM("Changing number of Q elements from %d to %lld",
NumEntriesIOQ, (unsigned long long)maxIOQEntries);
NumEntriesIOQ = maxIOQEntries;
}
gCtrlrConfig->SetIOCQES(gInformative->GetIdentifyCmdCtrlr()->
GetValue(IDCTRLRCAP_CQES) & 0xf);
Queues::CreateIOCQContigToHdw(mGrpName, mTestName,
CALC_TIMEOUT_ms(1), asq, acq, IOQ_ID, NumEntriesIOQ, true,
IOCQ_GROUP_ID, true, 0);
gCtrlrConfig->SetIOSQES(gInformative->GetIdentifyCmdCtrlr()->
GetValue(IDCTRLRCAP_SQES) & 0xf);
Queues::CreateIOSQContigToHdw(mGrpName, mTestName,
CALC_TIMEOUT_ms(1), asq, acq, IOQ_ID, NumEntriesIOQ, true,
IOSQ_GROUP_ID, IOQ_ID, 0);
}
}
} // namespace
|
gpl-2.0
|
Huxellberger/AdventOfCode2015
|
day03/Part1.java
|
2479
|
// Class to deliver presents to the children
// Prints out the houses delivered to at least once at the end
// Created By Jake Huxell For Advent Of Code 2015
import java.util.*;
import java.io.*;
public class Part1
{
// Function to convert index to hash map key
public static String getKey (int index[])
{
String keyFirst = "";
String keySecond = "";
if (index[0] < 0)
keyFirst += "minus";
else
keyFirst += "positive";
if (index[1] < 0)
keySecond += "minus";
else
keySecond += "positive";
return keyFirst + index[0] + keySecond + index[1];
} // getKey function
// Function to update index based on char instruction
public static void updateIndex (int index[], char instruction)
{
if (instruction == '^')
index[1] += 1;
else if (instruction == 'v')
index[1] -= 1;
else if (instruction == '>')
index[0] += 1;
else if (instruction == '<')
index[0] -= 1;
else
{}
} // updateIndex function
// Main function
public static void main(String args[])
{
// Use a hashmap for the house locations
int[] index = {0, 0};
String key;
HashMap <String, House> town = new HashMap();
key = getKey(index);
town.put(key, new House(key));
int houseCount = 1;
// Put in try for possible IOException
try
{
File file = new File(args[0]);
if (!file.exists())
{
System.out.println("\nFile not valid you christmas leper.\n");
return;
} // if
FileInputStream fis = new FileInputStream(file);
char currentInstruction;
while (fis.available() > 0)
{
currentInstruction = (char) fis.read();
updateIndex(index, currentInstruction);
key = getKey(index);
House currentHouse = town.get(key);
if (currentHouse == null)
{
town.put(key, new House(key));
houseCount++;
} // if
} // while
System.out.println(houseCount);
} // try block
// Catch for IOExceptions
catch (IOException exception)
{
System.err.println("\nSomething went wrong with the file.\n" +
exception.getMessage());
} // catch
// Catch really bad exceptions
catch (Exception exception)
{
System.err.println("\nSomething has gone very wrong indeed.\n" +
exception.getMessage());
}// catch
} // main function
} // Part1 Class
|
gpl-2.0
|
VladislavMaslakov/seven
|
wp-content/themes/seven/index.php
|
2182
|
<?php get_header(); ?>
<!-- Start Container -->
<div id="container">
<!-- Content -->
<div class="content right news clearfix">
<div class="container-top"></div>
<section class="page-head">
<?php
$theme_blog_title = stripslashes(get_option('theme_blog_title'));
if(!empty($theme_blog_title))
{
?>
<h1>
<span><?php echo $theme_blog_title; ?></span>
</h1>
<?php
}
?>
</section>
<!-- Main -->
<div id="main-content">
<?php
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
get_template_part("template-parts/blog_post_for_list");
endwhile;
theme_pagination( $wp_query->max_num_pages);
else :
?>
<h2><?php _e('No Posts Found', 'framework'); ?></h2>
<?php
endif;
?>
</div><!-- End Main -->
<?php get_sidebar(); ?>
<div class="container-bottom"></div>
</div> <!-- End Content-->
</div><!-- End Container -->
<?php get_footer(); ?>
|
gpl-2.0
|
pawkoz/dyplom
|
blender/source/gameengine/Ketsji/KX_TouchEventManager.cpp
|
7839
|
/*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* 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.
*
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
* The Original Code is: all of this file.
*
* Contributor(s): none yet.
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file gameengine/Ketsji/KX_TouchEventManager.cpp
* \ingroup ketsji
*/
#include "KX_TouchEventManager.h"
#include "SCA_ISensor.h"
#include "KX_TouchSensor.h"
#include "KX_GameObject.h"
#include "PHY_IPhysicsEnvironment.h"
#include "PHY_IPhysicsController.h"
KX_TouchEventManager::KX_TouchEventManager(class SCA_LogicManager* logicmgr,
PHY_IPhysicsEnvironment* physEnv)
: SCA_EventManager(logicmgr, TOUCH_EVENTMGR),
m_physEnv(physEnv)
{
//notm_scene->addTouchCallback(STATIC_RESPONSE, KX_TouchEventManager::collisionResponse, this);
//m_scene->addTouchCallback(OBJECT_RESPONSE, KX_TouchEventManager::collisionResponse, this);
//m_scene->addTouchCallback(SENSOR_RESPONSE, KX_TouchEventManager::collisionResponse, this);
m_physEnv->AddTouchCallback(PHY_OBJECT_RESPONSE, KX_TouchEventManager::newCollisionResponse, this);
m_physEnv->AddTouchCallback(PHY_SENSOR_RESPONSE, KX_TouchEventManager::newCollisionResponse, this);
m_physEnv->AddTouchCallback(PHY_BROADPH_RESPONSE, KX_TouchEventManager::newBroadphaseResponse, this);
}
bool KX_TouchEventManager::NewHandleCollision(void* object1, void* object2, const PHY_CollData *coll_data)
{
PHY_IPhysicsController* obj1 = static_cast<PHY_IPhysicsController*>(object1);
PHY_IPhysicsController* obj2 = static_cast<PHY_IPhysicsController*>(object2);
m_newCollisions.insert(NewCollision(obj1, obj2, coll_data));
return false;
}
bool KX_TouchEventManager::newCollisionResponse(void *client_data,
void *object1,
void *object2,
const PHY_CollData *coll_data)
{
KX_TouchEventManager *touchmgr = (KX_TouchEventManager *) client_data;
touchmgr->NewHandleCollision(object1, object2, coll_data);
return false;
}
bool KX_TouchEventManager::newBroadphaseResponse(void *client_data,
void *object1,
void *object2,
const PHY_CollData *coll_data)
{
PHY_IPhysicsController* ctrl1 = static_cast<PHY_IPhysicsController*>(object1);
PHY_IPhysicsController* ctrl2 = static_cast<PHY_IPhysicsController*>(object2);
KX_ClientObjectInfo *info1 = (ctrl1) ? static_cast<KX_ClientObjectInfo*>(ctrl1->GetNewClientInfo()) : NULL;
KX_ClientObjectInfo *info2 = (ctrl2) ? static_cast<KX_ClientObjectInfo*>(ctrl2->GetNewClientInfo()) : NULL;
// This call back should only be called for controllers of Near and Radar sensor
if (!info1)
return true;
// Get KX_GameObjects for callbacks
KX_GameObject* gobj1 = info1->m_gameobject;
KX_GameObject* gobj2 = (info2) ? info2->m_gameobject : NULL;
bool has_py_callbacks = false;
#ifdef WITH_PYTHON
// Consider callbacks for broadphase inclusion if it's a sensor object type
if (gobj1 && gobj2)
has_py_callbacks = gobj1->m_collisionCallbacks || gobj2->m_collisionCallbacks;
#else
(void)gobj1;
(void)gobj2;
#endif
switch (info1->m_type)
{
case KX_ClientObjectInfo::SENSOR:
if (info1->m_sensors.size() == 1)
{
// only one sensor for this type of object
KX_TouchSensor* touchsensor = static_cast<KX_TouchSensor*>(*info1->m_sensors.begin());
return touchsensor->BroadPhaseFilterCollision(object1, object2);
}
break;
case KX_ClientObjectInfo::OBSENSOR:
case KX_ClientObjectInfo::OBACTORSENSOR:
// this object may have multiple collision sensors,
// check is any of them is interested in this object
for (std::list<SCA_ISensor*>::iterator it = info1->m_sensors.begin();
it != info1->m_sensors.end();
++it)
{
if ((*it)->GetSensorType() == SCA_ISensor::ST_TOUCH)
{
KX_TouchSensor* touchsensor = static_cast<KX_TouchSensor*>(*it);
if (touchsensor->BroadPhaseSensorFilterCollision(object1, object2))
return true;
}
}
return has_py_callbacks;
// quiet the compiler
case KX_ClientObjectInfo::STATIC:
case KX_ClientObjectInfo::ACTOR:
case KX_ClientObjectInfo::RESERVED1:
/* do nothing*/
break;
}
return true;
}
void KX_TouchEventManager::RegisterSensor(SCA_ISensor* sensor)
{
KX_TouchSensor* touchsensor = static_cast<KX_TouchSensor*>(sensor);
if (m_sensors.AddBack(touchsensor))
// the sensor was effectively inserted, register it
touchsensor->RegisterSumo(this);
}
void KX_TouchEventManager::RemoveSensor(SCA_ISensor* sensor)
{
KX_TouchSensor* touchsensor = static_cast<KX_TouchSensor*>(sensor);
if (touchsensor->Delink())
// the sensor was effectively removed, unregister it
touchsensor->UnregisterSumo(this);
}
void KX_TouchEventManager::EndFrame()
{
SG_DList::iterator<KX_TouchSensor> it(m_sensors);
for (it.begin();!it.end();++it)
{
(*it)->EndFrame();
}
}
void KX_TouchEventManager::NextFrame()
{
SG_DList::iterator<KX_TouchSensor> it(m_sensors);
for (it.begin();!it.end();++it)
(*it)->SynchronizeTransform();
for (std::set<NewCollision>::iterator cit = m_newCollisions.begin(); cit != m_newCollisions.end(); ++cit)
{
// Controllers
PHY_IPhysicsController* ctrl1 = (*cit).first;
PHY_IPhysicsController* ctrl2 = (*cit).second;
// Sensor iterator
list<SCA_ISensor*>::iterator sit;
// First client info
KX_ClientObjectInfo *client_info = static_cast<KX_ClientObjectInfo*>(ctrl1->GetNewClientInfo());
// First gameobject
KX_GameObject *kxObj1 = KX_GameObject::GetClientObject(client_info);
// Invoke sensor response for each object
if (client_info) {
for ( sit = client_info->m_sensors.begin(); sit != client_info->m_sensors.end(); ++sit) {
static_cast<KX_TouchSensor*>(*sit)->NewHandleCollision(ctrl1, ctrl2, NULL);
}
}
// Second client info
client_info = static_cast<KX_ClientObjectInfo *>(ctrl2->GetNewClientInfo());
// Second gameobject
KX_GameObject *kxObj2 = KX_GameObject::GetClientObject(client_info);
if (client_info) {
for ( sit = client_info->m_sensors.begin(); sit != client_info->m_sensors.end(); ++sit) {
static_cast<KX_TouchSensor*>(*sit)->NewHandleCollision(ctrl2, ctrl1, NULL);
}
}
// Run python callbacks
PHY_CollData *colldata = cit->colldata;
kxObj1->RunCollisionCallbacks(kxObj2, colldata->m_point1, colldata->m_normal);
kxObj2->RunCollisionCallbacks(kxObj1, colldata->m_point2, -colldata->m_normal);
delete cit->colldata;
}
m_newCollisions.clear();
for (it.begin();!it.end();++it)
(*it)->Activate(m_logicmgr);
}
KX_TouchEventManager::NewCollision::NewCollision(PHY_IPhysicsController *first,
PHY_IPhysicsController *second,
const PHY_CollData *colldata)
: first(first), second(second), colldata(new PHY_CollData(*colldata))
{}
KX_TouchEventManager::NewCollision::NewCollision(const NewCollision &to_copy)
: first(to_copy.first), second(to_copy.second), colldata(to_copy.colldata)
{}
bool KX_TouchEventManager::NewCollision::operator<(const NewCollision &other) const
{
return first < other.first || second < other.second || colldata < other.colldata;
}
|
gpl-2.0
|
davidrousse/ezpuplish
|
app/ezpublish_legacy/var/ezwebin_site/cache/template/compiled/popup_sub_editclass_menu-ab659e251d18f3679eaedab5dec2ce7f.php
|
1973
|
<?php
// URI: design/admin/templates/popupmenu/popup_sub_editclass_menu.tpl
// Filename: design/admin/templates/popupmenu/popup_sub_editclass_menu.tpl
// Timestamp: 1349721948 (Mon Oct 8 18:45:48 UTC 2012)
$oldSetArray_2182f5ca506447c10badf9b3e3a46b92 = isset( $setArray ) ? $setArray : array();
$setArray = array();
$tpl->Level++;
if ( $tpl->Level > 40 )
{
$text = $tpl->MaxLevelWarning;$tpl->Level--;
return;
}
$eZTemplateCompilerCodeDate = 1074699607;
if ( !defined( 'EZ_TEMPLATE_COMPILER_COMMON_CODE' ) )
include_once( 'var/ezwebin_site/cache/template/compiled/common.php' );
$text .= '<!-- Edit class submenu -->
<script type="text/javascript">
menuArray[\'EditClassSubmenu\'] = { \'depth\': 1 };
menuArray[\'EditClassSubmenu\'][\'elements\'] = {};
menuArray[\'EditClassSubmenu\'][\'elements\'][\'edit-class-languages\'] = { \'variable\': \'%languages%\' };
menuArray[\'EditClassSubmenu\'][\'elements\'][\'edit-class-languages\'][\'content\'] = \'<a href="/ezpublish/app/ezpublish_legacy/index.php/ezwebin_site_admin/class/edit/%classID%/(language)/%locale%" onmouseover="ezpopmenu_mouseOver( \\\'EditClassSubmenu\\\' )">%name%<\\/a>\';
menuArray[\'EditClassSubmenu\'][\'elements\'][\'edit-class-another-language\'] = { \'url\': "/ezpublish/app/ezpublish_legacy/index.php/ezwebin_site_admin/class/edit/%classID%" };
menuArray[\'EditClassSubmenu\'][\'elements\'][\'edit-class-another-language\'][\'disabled_class\'] = \'menu-item-disabled\';
</script>
<div class="popupmenu" id="EditClassSubmenu">
<div id="edit-class-languages"></div>
<hr />
<!-- <a id="edit-class-another-language" href="#" onmouseover="ezpopmenu_mouseOver( \'EditClassSubmenu\' )">Autre langue</a> -->
<!-- <div id="edit-class-another-language"></div> -->
<a id="edit-class-another-language" href="#" onmouseover="ezpopmenu_mouseOver( \'EditClassSubmenu\' )">Nouvelle traduction</a>
</div>';
$setArray = $oldSetArray_2182f5ca506447c10badf9b3e3a46b92;
$tpl->Level--;
?>
|
gpl-2.0
|
avramishin/makerswp
|
wp-content/themes/makers/page-companies.php
|
3115
|
<?php
/**
* Template Name: Companies
* @package WordPress
*/
global $post;
$members = array();
$customList = array('website', 'type', 'description');
$args = array('numberposts' => 100, 'category_name' => 'companies');
$posts = get_posts($args);
$categoriesAll = array();
$firstCategory = null;
foreach ($posts as $post) {
$custom = get_post_custom($post->ID);
$featuredImageId = get_post_thumbnail_id($post->ID);
$image = wp_get_attachment_image_src($featuredImageId, array(261, 191));
$members[$post->ID] = array(
'id' => $post->ID,
'name' => $post->post_title,
'desc' => $post->post_content,
'image' => isset($image[0]) ? $image[0] : ''
);
foreach ($customList as $cfield) {
$members[$post->ID][$cfield] = isset($custom[$cfield][0]) ? $custom[$cfield][0] : "";
}
if (!empty($members[$post->ID]['type'])) {
$categories = explode(' ', $members[$post->ID]['type']);
foreach ($categories as $c) {
$c = trim($c);
if (!$c) continue;
if (empty($categoriesAll)) {
$firstCategory = $c;
}
$categoriesAll[$c] = $c;
}
}
}
get_header(); ?>
<main>
<div class="container intro">
<article>
<header>
<h2>What we have built so far</h2>
<p>We at Makers most often invest in web/mobile applications with clear monetization models. These are some of the companies we have built so far.</p>
</header>
<section class="page-companies">
<ul class="company-type">
<li class="active" data-filter="All" ><a href="javascript: void(0)" title="All">All</a></li>
<?php foreach ($categoriesAll as $filter=>$title): ?>
<li class="" data-filter="<?php echo htmlspecialchars($filter);?>">
<a href="javascript: void(0)" title="<?php echo htmlspecialchars(str_replace('-', ' ', $filter));?>"><?php echo htmlspecialchars(str_replace('-', ' ', $filter));?></a>
</li>
<?php endforeach; ?>
</ul>
<ul class="companies-grid list-3">
<?php foreach ($members as $m): ?>
<li class="All <?php echo $m['type'];?>">
<div class="table">
<div class="table-cell">
<a href="<?php echo $m['website'];?>" title="<?php echo $m['name'];?>" target="_blank">
<img width="261" height="191" src="<?php echo $m['image']; ?>" class="attachment-company-logo wp-post-image" alt="<?php echo $m['name'];?>" />
<p><?php echo $m['description']; ?></p>
</a>
</div>
</div>
</li>
<?php endforeach; ?>
</ul>
</section>
</article>
</div>
</main>
<script>
$(function() {
$('ul.company-type > li').click(function() {
var el = this;
$('ul.company-type > li').removeClass('active');
$(el).addClass('active');
$('ul.companies-grid > li').addClass('hidden');
var filter = $(el).attr('data-filter');
$('ul.companies-grid li.' + filter).removeClass('hidden');
});
});
</script>
<?php get_footer(); ?>
|
gpl-2.0
|
mehrmoudi/FA-Drawer
|
src/GUI/FAFrame.java
|
6876
|
package GUI;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import Core.FA;
import Core.DFA.DFABuilder;
import Core.NFA.NFA;
import Core.NFA.NFABuilder;
/**
*
* This class is the main frame of the application. You just need to initialize
* it with it's constructor and boom... You're ready to go!
*
* @author Mehran Mahmoudi
*
*
*/
public class FAFrame extends JFrame {
private static final long serialVersionUID = -6559694410472964579L;
public FAFrame() {
super("Mehran Mahmoudi's FA Drawer");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
setPreferredSize(new Dimension(900, 600));
pack();
setExtendedState(JFrame.MAXIMIZED_BOTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
init();
setVisible(true);
}
/**
* Initializes components of the JFrame.
*
* @author Mehran Mahmoudi
*/
private void init() {
final JPanel leftPane = new JPanel();
JPanel regPan = new JPanel();
regPan.setBorder(BorderFactory.createTitledBorder("Regular Expression"));
JLabel enterAlphas = new JLabel("Enter language alphabets, seprated with commas:");
final JTextField alphaText = new JTextField("a,b");
alphaText.setPreferredSize(new Dimension(250, (int) alphaText.getPreferredSize()
.getHeight()));
JLabel enterRegex = new JLabel("Enter regular expression:");
final JTextField regexText = new JTextField("a*b*");
regexText.setPreferredSize(new Dimension(250, (int) regexText.getPreferredSize()
.getHeight()));
JPanel faTypePan = new JPanel();
faTypePan.setBorder(BorderFactory.createTitledBorder("FA Type"));
JLabel chooseFAType = new JLabel("Choose FA type:");
ButtonGroup gp = new ButtonGroup();
JRadioButton nfaButton = new JRadioButton("NFA");
nfaButton.setSelected(true);
final JRadioButton dfaButton = new JRadioButton("DFA");
final JRadioButton minidfaButton = new JRadioButton("Minimized DFA");
// minidfaButton.setEnabled(false);
gp.add(nfaButton);
gp.add(dfaButton);
gp.add(minidfaButton);
final JButton plotButton = new JButton("Plot!");
// plotButton.setEnabled(false);
final JPanel rightPane = new JPanel();
rightPane.setBorder(BorderFactory.createTitledBorder("Finite Automaton"));
final FAPanel faPanel = new FAPanel();
regPan.setLayout(new VerticalFlowLayout());
regPan.add(enterAlphas);
regPan.add(alphaText);
regPan.add(enterRegex);
regPan.add(regexText);
faTypePan.setLayout(new VerticalFlowLayout());
faTypePan.add(chooseFAType);
faTypePan.add(nfaButton);
faTypePan.add(dfaButton);
faTypePan.add(minidfaButton);
leftPane.setLayout(new VerticalFlowLayout());
leftPane.add(regPan);
leftPane.add(faTypePan);
leftPane.add(plotButton);
rightPane.setLayout(new FlowLayout());
rightPane.add(faPanel);
getContentPane().setLayout(new SpringLayout());
getContentPane().add(leftPane);
getContentPane().add(rightPane);
regexText.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent arg0) {
if (regexText.getText().trim().equals("") || alphaText.getText().trim().equals("")) {
plotButton.setEnabled(false);
} else
plotButton.setEnabled(true);
}
@Override
public void insertUpdate(DocumentEvent arg0) {
if (regexText.getText().trim().equals("")) {
plotButton.setEnabled(false);
} else
plotButton.setEnabled(true);
}
@Override
public void changedUpdate(DocumentEvent arg0) {
}
});
alphaText.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent arg0) {
if (regexText.getText().trim().equals("") || alphaText.getText().trim().equals("")) {
plotButton.setEnabled(false);
} else
plotButton.setEnabled(true);
}
@Override
public void insertUpdate(DocumentEvent arg0) {
if (regexText.getText().trim().equals("")) {
plotButton.setEnabled(false);
} else
plotButton.setEnabled(true);
}
@Override
public void changedUpdate(DocumentEvent arg0) {
}
});
getContentPane().addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {
// TODO Auto-generated method stub
}
@Override
public void componentResized(ComponentEvent e) {
rightPane.setSize(getContentPane().getWidth() - leftPane.getWidth() - 15,
getContentPane().getHeight() - 15);
rightPane.setPreferredSize(new Dimension(getContentPane().getWidth()
- leftPane.getWidth() - 15, getContentPane().getHeight() - 15));
rightPane.setLocation(leftPane.getWidth() + 5, getContentPane().getY() + 5);
faPanel.setSize(rightPane.getWidth() - 40, rightPane.getHeight() - 50);
faPanel.setPreferredSize(new Dimension(rightPane.getWidth() - 40, rightPane
.getHeight() - 50));
faPanel.setLocation(20, 30);
}
@Override
public void componentMoved(ComponentEvent e) {
// TODO Auto-generated method stub
}
@Override
public void componentHidden(ComponentEvent e) {
// TODO Auto-generated method stub
}
});
plotButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String alphabets = alphaText.getText();
String regex = regexText.getText();
String[] alphas = alphabets.split(",");
char[] realAlhpas = new char[alphas.length];
for (int i = 0; i < realAlhpas.length; i++) {
realAlhpas[i] = alphas[i].trim().charAt(0);
}
FA fa = null;
NFABuilder nfaBuilder = new NFABuilder(regex, realAlhpas);
fa = nfaBuilder.toNFA();
if (dfaButton.isSelected()) {
NFA nfa = (NFA) fa;
DFABuilder dfaBuilder = new DFABuilder(nfa);
fa = dfaBuilder.getDFAfromNFA();
}
if (minidfaButton.isSelected()) {
NFA nfa = (NFA) fa;
DFABuilder dfaBuilder = new DFABuilder(nfa);
DFABuilder minBuilder = new DFABuilder(dfaBuilder.getDFAfromNFA());
fa = minBuilder.getMinimizedDFAfromDFA();
}
faPanel.setFA(fa);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
}
|
gpl-2.0
|
Celludriel/L3DT_Filemanager
|
L3dtFileManager/L3dt/L3dtFile.cs
|
634
|
using L3dtFileManager.Amf;
using L3dtFileManager.Dmf;
using L3dtFileManager.Hff;
using L3dtFileManager.Hfz;
using L3dtFileManager.Wmf;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace L3dtFileManager.L3dt
{
public class L3dtFile
{
public enum HeightMapType { HFF, HFZ };
public HeightMapType heightMapType;
public HffFile HffFile;
public HfzFile HfzFile;
public WmfFile WmfFile;
public AmfFile AmfFile;
public DmfFile DmfFile;
public Hashtable ClimateTable = new Hashtable();
}
}
|
gpl-2.0
|
jsj2008/kdegames
|
ksirk/ksirk/iris/src/xmpp/sasl/digestmd5response.cpp
|
2602
|
/*
* Copyright (C) 2008 Remko Troncon
* See COPYING for license details.
*/
#include "xmpp/sasl/digestmd5response.h"
#include <QByteArray>
#include <QtCrypto>
#include <QtDebug>
#include "xmpp/sasl/digestmd5proplist.h"
#include "xmpp/base/randomnumbergenerator.h"
#include "xmpp/base64/base64.h"
namespace XMPP {
DIGESTMD5Response::DIGESTMD5Response(const QByteArray& challenge, const QString& service, const QString& host, const QString& arealm, const QString& user, const QString& authz, const QByteArray& password, const RandomNumberGenerator& rand) : isValid_(true)
{
QString realm = arealm;
// get props
DIGESTMD5PropList in;
if(!in.fromString(challenge)) {
isValid_ = false;
return;
}
//qDebug() << (QString("simplesasl.cpp: IN: %1").arg(QString(in.toString())));
// make a cnonce
QByteArray a;
a.resize(32);
for(int n = 0; n < (int)a.size(); ++n) {
a[n] = (char) rand.generateNumberBetween(0, 255);
}
QByteArray cnonce = Base64::encode(a).toLatin1();
// make other variables
if (realm.isEmpty()) {
realm = QString::fromUtf8(in.get("realm"));
}
QByteArray nonce = in.get("nonce");
QByteArray nc = "00000001";
QByteArray uri = service.toUtf8() + '/' + host.toUtf8();
QByteArray qop = "auth";
// build 'response'
QByteArray X = user.toUtf8() + ':' + realm.toUtf8() + ':' + password;
QByteArray Y = QCA::Hash("md5").hash(X).toByteArray();
QByteArray tmp = ':' + nonce + ':' + cnonce;
if (!authz.isEmpty())
tmp += ':' + authz.toUtf8();
//qDebug() << (QString(tmp));
QByteArray A1(Y + tmp);
QByteArray A2 = QByteArray("AUTHENTICATE:") + uri;
QByteArray HA1 = QCA::Hash("md5").hashToString(A1).toLatin1();
QByteArray HA2 = QCA::Hash("md5").hashToString(A2).toLatin1();
QByteArray KD = HA1 + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + HA2;
QByteArray Z = QCA::Hash("md5").hashToString(KD).toLatin1();
//qDebug() << (QString("simplesasl.cpp: A1 = %1").arg(QString(A1)).toAscii());
//qDebug() << (QString("simplesasl.cpp: A2 = %1").arg(QString(A2)).toAscii());
//qDebug() << (QString("simplesasl.cpp: KD = %1").arg(QString(KD)).toAscii());
// build output
DIGESTMD5PropList out;
out.set("username", user.toUtf8());
if (!realm.isEmpty())
out.set("realm", realm.toUtf8());
out.set("nonce", nonce);
out.set("cnonce", cnonce);
out.set("nc", nc);
//out.set("serv-type", service.toUtf8());
//out.set("host", host.toUtf8());
out.set("digest-uri", uri);
out.set("qop", qop);
out.set("response", Z);
out.set("charset", "utf-8");
if (!authz.isEmpty())
out.set("authzid", authz.toUtf8());
value_ = out.toString();
}
}
|
gpl-2.0
|
lsj5031/monthly_report_nz
|
main.py
|
4007
|
import csv
import operator
import click
@click.command()
@click.option('--file', prompt='exported csv file', help='Download from you bank website.')
def read_csv(file):
parse_anz(file)
def sum_rows(row_list):
return reduce(operator.__add__, [float(row[2]) for row in row_list], 0)
category_list = ["supermarket",
"transportation",
"clothes",
"tools",
"eating",
"bills",
"others"]
def parse_anz(csv_file):
with open(csv_file, 'rb') as report:
parsed_anz = csv.reader(report)
# row[0] Card Number
# row[1] (D)eposit or (C)redit
# row[2] Amount
# row[3] Merchant Name
# row[4] Date
# row[5] Process Date
result = {_: [] for _ in category_list}
for row in parsed_anz:
if row[1] == "C":
continue
s = row[3].lower()
if is_supermarket(s):
result["supermarket"].append(row)
continue
if is_transportation(s):
result["transportation"].append(row)
continue
if is_clothes(s):
result["clothes"].append(row)
continue
if is_eating(s):
result["eating"].append(row)
continue
if is_tools(s):
result["tools"].append(row)
continue
if is_bills(s):
result["bills"].append(row)
continue
result["others"].append(row)
for k, v in result.iteritems():
print "%s : %s" % (k, sum_rows(v))
for _ in v:
print _
def is_supermarket(s):
if "pak n save" in s:
if "fuel" not in s:
return True
if "fresh & save" in s:
return True
if "tai ping" in s:
return True
if "warehouse" in s:
return True
if "countdown" in s:
return True
if "reduced to clear" in s:
return True
if "d.h." in s:
return True
if "fresh choice" in s:
return True
if "four square" in s:
return True
return False
def is_bills(s):
if "myrepublic" in s:
return True
if "2degrees" in s:
return True
if "powershop" in s:
return True
if "orcon" in s:
return True
if "contact" in s:
return True
if "youi nz" in s:
return True
if "wheelibin" in s:
return True
return False
def is_transportation(s):
if "fuel" in s:
return True
if "bp oil" in s:
return True
if "bp 2 go" in s:
return True
if "at hop" in s:
return True
if "carpark" in s:
return True
if "nzta" in s:
return True
if "caltex" in s:
return True
if "auckland transport" in s:
return True
if "z " == s[:2]:
return True
if "mobil " == s[:6]:
return True
return False
def is_clothes(s):
if "cotton on" in s:
return True
if "glassons" in s:
return True
if "valleygirl" in s:
return True
if "bing harris" in s:
return True
if "hannahs" in s:
return True
if "scarf queen" in s:
return True
return False
def is_tools(s):
if "briscoes" in s:
return True
if "bunning" in s:
return True
if "mitre 10" in s:
return True
return False
def is_eating(s):
if "burger king" in s:
return True
if "dominos" in s:
return True
if "mcdonalds" in s:
return True
if "kfc" in s:
return True
if "pho viet" in s:
return True
if "industry 61" in s:
return True
if "espresso" in s:
return True
if "pizza hut" in s:
return True
if "carls jr" in s:
return True
return False
if __name__ == '__main__':
read_csv()
|
gpl-2.0
|
Bysmyyr/cpabe
|
jpbc/jpbc-benchmark/src/main/java/it/unisa/dia/gas/jpbc/benchmark/Benchmark.java
|
156
|
package it.unisa.dia.gas.jpbc.benchmark;
/**
* @author Angelo De Caro (angelo.decaro@gmail.com)
*/
public interface Benchmark {
String toHTML();
}
|
gpl-2.0
|
janoliver/pOT-Droid
|
src/main/java/com/mde/potdroid/helpers/ptr/SwipyRefreshLayout.java
|
48107
|
package com.mde.potdroid.helpers.ptr;
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Transformation;
import android.widget.AbsListView;
import com.mde.potdroid.R;
/**
* The SwipeRefreshLayout should be used whenever the user can refresh the
* contents of a view via a vertical swipe gesture. The activity that
* instantiates this view should add an OnRefreshListener to be notified
* whenever the swipe to refresh gesture is completed. The SwipeRefreshLayout
* will notify the listener each and every time the gesture is completed again;
* the listener is responsible for correctly determining when to actually
* initiate a refresh of its content. If the listener determines there should
* not be a refresh, it must call setRefreshing(false) to cancel any visual
* indication of a refresh. If an activity wishes to show just the progress
* animation, it should call setRefreshing(true). To disable the gesture and
* progress animation, call setEnabled(false) on the view.
* <p>
* This layout should be made the parent of the view that will be refreshed as a
* result of the gesture and can only support one direct child. This view will
* also be made the target of the gesture and will be forced to match both the
* width and the height supplied in this layout. The SwipeRefreshLayout does not
* provide accessibility events; instead, a menu item must be provided to allow
* refresh of the content wherever this gesture is used.
* </p>
*/
public class SwipyRefreshLayout extends ViewGroup {
public static final String TAG = "SwipyRefreshLayout";
private static final float MAX_SWIPE_DISTANCE_FACTOR = .4f;
private static final int REFRESH_TRIGGER_DISTANCE = 90;
// Maps to ProgressBar.Large style
public static final int LARGE = MaterialProgressDrawable.LARGE;
// Maps to ProgressBar default style
public static final int DEFAULT = MaterialProgressDrawable.DEFAULT;
private static final String LOG_TAG = SwipyRefreshLayout.class.getSimpleName();
private static final int MAX_ALPHA = 255;
private static final int STARTING_PROGRESS_ALPHA = (int) (.3f * MAX_ALPHA);
private static final int CIRCLE_DIAMETER = 40;
private static final int CIRCLE_DIAMETER_LARGE = 56;
private static final float DECELERATE_INTERPOLATION_FACTOR = 2f;
private static final int INVALID_POINTER = -1;
private static final float DRAG_RATE = .7f;
// Max amount of circle that can be filled by progress during swipe gesture,
// where 1.0 is a full circle
private static final float MAX_PROGRESS_ANGLE = .8f;
private static final int SCALE_DOWN_DURATION = 150;
private static final int ALPHA_ANIMATION_DURATION = 300;
private static final int ANIMATE_TO_TRIGGER_DURATION = 200;
private static final int ANIMATE_TO_START_DURATION = 200;
// Default background for the progress spinner
private static final int CIRCLE_BG_LIGHT = 0xFFFAFAFA;
// Default offset in dips from the top of the view to where the progress spinner should stop
private static final int DEFAULT_CIRCLE_TARGET = 64;
private View mTarget; // the target of the gesture
private View mChildContainer; // the target of the gesture
private SwipyRefreshLayoutDirection mDirection;
private boolean mBothDirection;
private OnRefreshListener mListener;
private boolean mRefreshing = false;
private int mTouchSlop;
private float mTotalDragDistance = -1;
private int mMediumAnimationDuration;
private int mCurrentTargetOffsetTop;
// Whether or not the starting offset has been determined.
private boolean mOriginalOffsetCalculated = false;
private float mInitialMotionY;
private float mInitialDownY;
private boolean mIsBeingDragged;
private int mActivePointerId = INVALID_POINTER;
// Whether this item is scaled up rather than clipped
private boolean mScale;
// Target is returning to its start offset because it was cancelled or a
// refresh was triggered.
private boolean mReturningToStart;
private final DecelerateInterpolator mDecelerateInterpolator;
private static final int[] LAYOUT_ATTRS = new int[]{
android.R.attr.enabled
};
private CircleImageView mCircleView;
private int mCircleViewIndex = -1;
protected int mFrom;
private float mStartingScale;
protected int mOriginalOffsetTop;
private MaterialProgressDrawable mProgress;
private Animation mScaleAnimation;
private Animation mScaleDownAnimation;
private Animation mAlphaStartAnimation;
private Animation mAlphaMaxAnimation;
private Animation mScaleDownToStartAnimation;
private float mSpinnerFinalOffset;
private boolean mNotify;
private int mCircleWidth;
private int mCircleHeight;
int mAdapterViewId;
// Whether the client has set a custom starting position;
private boolean mUsingCustomStart;
private AnimationListener mRefreshListener = new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (mRefreshing) {
// Make sure the progress view is fully visible
mProgress.setAlpha(MAX_ALPHA);
mProgress.start();
if (mNotify) {
if (mListener != null) {
mListener.onRefresh(mDirection);
}
}
} else {
mProgress.stop();
mCircleView.setVisibility(View.GONE);
setColorViewAlpha(MAX_ALPHA);
// Return the circle to its start position
if (mScale) {
setAnimationProgress(0 /* animation complete and view is hidden */);
} else {
setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCurrentTargetOffsetTop,
true /* requires update */);
}
}
mCurrentTargetOffsetTop = mCircleView.getTop();
}
};
private void setColorViewAlpha(int targetAlpha) {
mCircleView.getBackground().setAlpha(targetAlpha);
mProgress.setAlpha(targetAlpha);
}
/**
* The refresh indicator starting and resting position is always positioned
* near the top of the refreshing content. This position is a consistent
* location, but can be adjusted in either direction based on whether or not
* there is a toolbar or actionbar present.
*
* @param scale Set to true if there is no view at a higher z-order than
* where the progress spinner is set to appear.
* @param start The offset in pixels from the top of this view at which the
* progress spinner should appear.
* @param end The offset in pixels from the top of this view at which the
* progress spinner should come to rest after a successful swipe
* gesture.
*/
public void setProgressViewOffset(boolean scale, int start, int end) {
final DisplayMetrics metrics = getResources().getDisplayMetrics();
mScale = scale;
mCircleView.setVisibility(View.GONE);
/*switch (mDirection) {
case BOTTOM:
mCurrentTargetOffsetTop = mOriginalOffsetTop = getMeasuredHeight() - end;
break;
case TOP:
default:
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight() + start;
break;
}*/
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight() + start;
mSpinnerFinalOffset = DEFAULT_CIRCLE_TARGET * metrics.density + end;
mUsingCustomStart = true;
mCircleView.invalidate();
}
public void addProgressViewOffset(int start, int end) {
final DisplayMetrics metrics = getResources().getDisplayMetrics();
mCircleView.setVisibility(View.GONE);
/*switch (mDirection) {
case BOTTOM:
mCurrentTargetOffsetTop = mOriginalOffsetTop = getMeasuredHeight() - end;
break;
case TOP:
default:
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight() + start;
break;
}*/
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight() + start;
mSpinnerFinalOffset = DEFAULT_CIRCLE_TARGET * metrics.density + end;
mUsingCustomStart = true;
mCircleView.invalidate();
}
/**
* The refresh indicator resting position is always positioned near the top
* of the refreshing content. This position is a consistent location, but
* can be adjusted in either direction based on whether or not there is a
* toolbar or actionbar present.
*
* @param scale Set to true if there is no view at a higher z-order than
* where the progress spinner is set to appear.
* @param end The offset in pixels from the top of this view at which the
* progress spinner should come to rest after a successful swipe
* gesture.
*/
public void setProgressViewEndTarget(boolean scale, int end) {
mSpinnerFinalOffset = end;
mScale = scale;
mCircleView.invalidate();
}
/**
* One of DEFAULT, or LARGE.
*/
public void setSize(int size) {
if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) {
return;
}
final DisplayMetrics metrics = getResources().getDisplayMetrics();
if (size == MaterialProgressDrawable.LARGE) {
mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER_LARGE * metrics.density);
} else {
mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
}
// force the bounds of the progress circle inside the circle view to
// update by setting it to null before updating its size and then
// re-setting it
mCircleView.setImageDrawable(null);
mProgress.updateSizes(size);
mCircleView.setImageDrawable(mProgress);
}
/**
* Simple constructor to use when creating a SwipeRefreshLayout from code.
*
* @param context
*/
public SwipyRefreshLayout(Context context) {
this(context, null);
}
/**
* Constructor that is called when inflating SwipeRefreshLayout from XML.
*
* @param context
* @param attrs
*/
public SwipyRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mMediumAnimationDuration = getResources().getInteger(
android.R.integer.config_mediumAnimTime);
setWillNotDraw(false);
mDecelerateInterpolator = new DecelerateInterpolator(DECELERATE_INTERPOLATION_FACTOR);
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
setEnabled(a.getBoolean(0, true));
a.recycle();
final TypedArray a2 = context.obtainStyledAttributes(attrs, R.styleable.SwipyRefreshLayout);
mAdapterViewId = a2.getResourceId(R.styleable.SwipyRefreshLayout_adapter_view, -1);
SwipyRefreshLayoutDirection direction
= SwipyRefreshLayoutDirection.getFromInt(a2.getInt(R.styleable.SwipyRefreshLayout_srl_direction, 0));
if (direction != SwipyRefreshLayoutDirection.BOTH) {
mDirection = direction;
mBothDirection = false;
} else {
mDirection = SwipyRefreshLayoutDirection.TOP;
mBothDirection = true;
}
a2.recycle();
final DisplayMetrics metrics = getResources().getDisplayMetrics();
mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
mCircleHeight = (int) (CIRCLE_DIAMETER * metrics.density);
createProgressView();
ViewCompat.setChildrenDrawingOrderEnabled(this, true);
// the absolute offset has to take into account that the circle starts at an offset
mSpinnerFinalOffset = DEFAULT_CIRCLE_TARGET * metrics.density;
}
protected int getChildDrawingOrder(int childCount, int i) {
if (mCircleViewIndex < 0) {
return i;
} else if (i == childCount - 1) {
// Draw the selected child last
return mCircleViewIndex;
} else if (i >= mCircleViewIndex) {
// Move the children after the selected child earlier one
return i + 1;
} else {
// Keep the children before the selected child the same
return i;
}
}
private void createProgressView() {
mCircleView = new CircleImageView(getContext(), CIRCLE_BG_LIGHT, CIRCLE_DIAMETER / 2);
mProgress = new MaterialProgressDrawable(getContext(), this);
mProgress.setBackgroundColor(CIRCLE_BG_LIGHT);
mCircleView.setImageDrawable(mProgress);
mCircleView.setVisibility(View.GONE);
addView(mCircleView);
}
/**
* Set the listener to be notified when a refresh is triggered via the swipe
* gesture.
*/
public void setOnRefreshListener(OnRefreshListener listener) {
mListener = listener;
}
/**
* Pre API 11, alpha is used to make the progress circle appear instead of scale.
*/
private boolean isAlphaUsedForScale() {
return android.os.Build.VERSION.SDK_INT < 11;
}
/**
* Notify the widget that refresh state has changed. Do not call this when
* refresh is triggered by a swipe gesture.
*
* @param refreshing Whether or not the view should show refresh progress.
*/
public void setRefreshing(boolean refreshing) {
if (refreshing && mRefreshing != refreshing) {
// scale and show
mRefreshing = refreshing;
int endTarget = 0;
if (!mUsingCustomStart) {
/*switch (mDirection) {
case BOTTOM:
endTarget = getMeasuredHeight() - (int) (mSpinnerFinalOffset);
break;
case TOP:
default:
endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));
break;
}*/
endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));
} else {
endTarget = (int) mSpinnerFinalOffset;
}
setTargetOffsetTopAndBottom(endTarget - mCurrentTargetOffsetTop,
true /* requires update */);
mNotify = false;
startScaleUpAnimation(mRefreshListener);
} else {
setRefreshing(refreshing, false /* notify */);
}
}
private void startScaleUpAnimation(AnimationListener listener) {
mCircleView.setVisibility(View.VISIBLE);
if (android.os.Build.VERSION.SDK_INT >= 11) {
// Pre API 11, alpha is used in place of scale up to show the
// progress circle appearing.
// Don't adjust the alpha during appearance otherwise.
mProgress.setAlpha(MAX_ALPHA);
}
mScaleAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(interpolatedTime);
}
};
mScaleAnimation.setDuration(mMediumAnimationDuration);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleAnimation);
}
/**
* Pre API 11, this does an alpha animation.
*
* @param progress
*/
private void setAnimationProgress(float progress) {
if (isAlphaUsedForScale()) {
setColorViewAlpha((int) (progress * MAX_ALPHA));
} else {
ViewCompat.setScaleX(mCircleView, progress);
ViewCompat.setScaleY(mCircleView, progress);
}
}
private void setRefreshing(boolean refreshing, final boolean notify) {
if (mRefreshing != refreshing) {
mNotify = notify;
ensureTarget();
ensureChildContainer();
mRefreshing = refreshing;
if (mRefreshing) {
animateOffsetToCorrectPosition(mCurrentTargetOffsetTop, mRefreshListener);
} else {
startScaleDownAnimation(mRefreshListener);
}
}
}
private void startScaleDownAnimation(AnimationListener listener) {
mScaleDownAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(1 - interpolatedTime);
}
};
mScaleDownAnimation.setDuration(SCALE_DOWN_DURATION);
mCircleView.setAnimationListener(listener);
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleDownAnimation);
}
private void startProgressAlphaStartAnimation() {
mAlphaStartAnimation = startAlphaAnimation(mProgress.getAlpha(), STARTING_PROGRESS_ALPHA);
}
private void startProgressAlphaMaxAnimation() {
mAlphaMaxAnimation = startAlphaAnimation(mProgress.getAlpha(), MAX_ALPHA);
}
private Animation startAlphaAnimation(final int startingAlpha, final int endingAlpha) {
// Pre API 11, alpha is used in place of scale. Don't also use it to
// show the trigger point.
if (mScale && isAlphaUsedForScale()) {
return null;
}
Animation alpha = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
mProgress
.setAlpha((int) (startingAlpha + ((endingAlpha - startingAlpha)
* interpolatedTime)));
}
};
alpha.setDuration(ALPHA_ANIMATION_DURATION);
// Clear out the previous animation listeners.
mCircleView.setAnimationListener(null);
mCircleView.clearAnimation();
mCircleView.startAnimation(alpha);
return alpha;
}
/**
* Set the background color of the progress spinner disc.
*
* @param colorRes Resource id of the color.
*/
public void setProgressBackgroundColor(int colorRes) {
mCircleView.setBackgroundColor(colorRes);
mProgress.setBackgroundColor(getResources().getColor(colorRes));
}
/**
* @deprecated Use {@link #setColorSchemeResources(int...)}
*/
@Deprecated
public void setColorScheme(int... colors) {
setColorSchemeResources(colors);
}
/**
* Set the color resources used in the progress animation from color resources.
* The first color will also be the color of the bar that grows in response
* to a user swipe gesture.
*
* @param colorResIds
*/
public void setColorSchemeResources(int... colorResIds) {
final Resources res = getResources();
int[] colorRes = new int[colorResIds.length];
for (int i = 0; i < colorResIds.length; i++) {
colorRes[i] = res.getColor(colorResIds[i]);
}
setColorSchemeColors(colorRes);
}
/**
* Set the colors used in the progress animation. The first
* color will also be the color of the bar that grows in response to a user
* swipe gesture.
*
* @param colors
*/
public void setColorSchemeColors(int... colors) {
ensureTarget();
ensureChildContainer();
mProgress.setColorSchemeColors(colors);
}
/**
* @return Whether the SwipeRefreshWidget is actively showing refresh
* progress.
*/
public boolean isRefreshing() {
return mRefreshing;
}
private void ensureTarget() {
// Don't bother getting the parent height if the parent hasn't been laid
// out yet.
if (mTarget == null) {
mTarget = findViewById(mAdapterViewId);
if(mTarget == null) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (!child.equals(mCircleView)) {
mTarget = child;
break;
}
}
}
}
if (mTotalDragDistance == -1) {
if (getParent() != null && ((View) getParent()).getHeight() > 0) {
final DisplayMetrics metrics = getResources().getDisplayMetrics();
mTotalDragDistance = (int) Math.min(
((View) getParent()).getHeight() * MAX_SWIPE_DISTANCE_FACTOR,
REFRESH_TRIGGER_DISTANCE * metrics.density);
}
}
}
private void ensureChildContainer() {
// Don't bother getting the parent height if the parent hasn't been laid
// out yet.
if (mChildContainer == null) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (!child.equals(mCircleView)) {
mChildContainer = child;
break;
}
}
}
}
/**
* Set the distance to trigger a sync in dips
*
* @param distance
*/
public void setDistanceToTriggerSync(int distance) {
mTotalDragDistance = distance;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
final int width = getMeasuredWidth();
final int height = getMeasuredHeight();
if (getChildCount() == 0) {
return;
}
if (mTarget == null) {
ensureTarget();
}
if(mChildContainer == null) {
ensureChildContainer();
}
if (mTarget == null || mChildContainer == null) {
return;
}
final View child = mChildContainer;
final int childLeft = getPaddingLeft();
final int childTop = getPaddingTop();
final int childWidth = width - getPaddingLeft() - getPaddingRight();
final int childHeight = height - getPaddingTop() - getPaddingBottom();
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
int circleWidth = mCircleView.getMeasuredWidth();
int circleHeight = mCircleView.getMeasuredHeight();
mCircleView.layout((width / 2 - circleWidth / 2), mCurrentTargetOffsetTop,
(width / 2 + circleWidth / 2), mCurrentTargetOffsetTop + circleHeight);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mChildContainer == null) {
ensureTarget();
}
if (mChildContainer == null) {
return;
}
mChildContainer.measure(MeasureSpec.makeMeasureSpec(
getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(
getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY));
mCircleView.measure(MeasureSpec.makeMeasureSpec(mCircleWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(mCircleHeight, MeasureSpec.EXACTLY));
if (!mUsingCustomStart && !mOriginalOffsetCalculated) {
mOriginalOffsetCalculated = true;
switch (mDirection) {
case BOTTOM:
mCurrentTargetOffsetTop = mOriginalOffsetTop = getMeasuredHeight();
break;
case TOP:
default:
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();
break;
}
}
mCircleViewIndex = -1;
// Get the index of the circleview.
for (int index = 0; index < getChildCount(); index++) {
if (getChildAt(index) == mCircleView) {
mCircleViewIndex = index;
break;
}
}
}
/**
* @return Whether it is possible for the child view of this layout to
* scroll up. Override this if the child view is a custom view.
*/
public boolean canChildScrollUp() {
if (android.os.Build.VERSION.SDK_INT < 14) {
if (mTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mTarget;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return mTarget.getScrollY() > 0;
}
} else {
return ViewCompat.canScrollVertically(mTarget, -1);
}
}
// public boolean canChildScrollUp() {
// if (android.os.Build.VERSION.SDK_INT < 14) {
// if (mTarget instanceof AbsListView) {
// final AbsListView absListView = (AbsListView) mTarget;
// if (absListView.getLastVisiblePosition() + 1 == absListView.getCount()) {
// int lastIndex = absListView.getLastVisiblePosition() - absListView.getFirstVisiblePosition();
//
// boolean res = absListView.getChildAt(lastIndex).getBottom() == absListView.getPaddingBottom();
//
// return res;
// }
// return true;
// } else {
// return mTarget.getScrollY() > 0;
// }
// } else {
// return ViewCompat.canScrollVertically(mTarget, 1);
// }
// }
public boolean canChildScrollDown() {
if (android.os.Build.VERSION.SDK_INT < 14) {
if (mTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mTarget;
try {
if (absListView.getCount() > 0) {
if (absListView.getLastVisiblePosition() + 1 == absListView.getCount()) {
int lastIndex = absListView.getLastVisiblePosition() - absListView.getFirstVisiblePosition();
return absListView.getChildAt(lastIndex).getBottom() == absListView.getPaddingBottom();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
} else {
return true;
}
} else {
return ViewCompat.canScrollVertically(mTarget, 1);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
ensureTarget();
ensureChildContainer();
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
switch (mDirection) {
case BOTTOM:
if (!isEnabled() || mReturningToStart || (!mBothDirection && canChildScrollDown()) || mRefreshing) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
break;
case TOP:
default:
if (!isEnabled() || mReturningToStart || (!mBothDirection && canChildScrollUp()) || mRefreshing) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
break;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCircleView.getTop(), true);
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
final float initialDownY = getMotionEventY(ev, mActivePointerId);
if (initialDownY == -1) {
return false;
}
mInitialDownY = initialDownY;
case MotionEvent.ACTION_MOVE:
if (mActivePointerId == INVALID_POINTER) {
return false;
}
final float y = getMotionEventY(ev, mActivePointerId);
if (y == -1) {
return false;
}
if (mBothDirection) {
if (y > mInitialDownY) {
setRawDirection(SwipyRefreshLayoutDirection.TOP);
} else if (y < mInitialDownY) {
setRawDirection(SwipyRefreshLayoutDirection.BOTTOM);
}
if ((mDirection == SwipyRefreshLayoutDirection.BOTTOM && canChildScrollDown())
|| (mDirection == SwipyRefreshLayoutDirection.TOP && canChildScrollUp())) {
mInitialDownY = y;
return false;
}
}
float yDiff;
switch (mDirection) {
case BOTTOM:
yDiff = mInitialDownY - y;
break;
case TOP:
default:
yDiff = y - mInitialDownY;
break;
}
if (yDiff > mTouchSlop && !mIsBeingDragged) {
switch (mDirection) {
case BOTTOM:
mInitialMotionY = mInitialDownY - mTouchSlop;
break;
case TOP:
default:
mInitialMotionY = mInitialDownY + mTouchSlop;
break;
}
mIsBeingDragged = true;
mProgress.setAlpha(STARTING_PROGRESS_ALPHA);
}
break;
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIsBeingDragged = false;
mActivePointerId = INVALID_POINTER;
break;
}
return mIsBeingDragged;
}
private float getMotionEventY(MotionEvent ev, int activePointerId) {
final int index = MotionEventCompat.findPointerIndex(ev, activePointerId);
if (index < 0) {
return -1;
}
return MotionEventCompat.getY(ev, index);
}
@Override
public void requestDisallowInterceptTouchEvent(boolean b) {
// Nope.
}
private boolean isAnimationRunning(Animation animation) {
return animation != null && animation.hasStarted() && !animation.hasEnded();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
try {
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
switch (mDirection) {
case BOTTOM:
if (!isEnabled() || mReturningToStart || canChildScrollDown() || mRefreshing) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
break;
case TOP:
default:
if (!isEnabled() || mReturningToStart || canChildScrollUp() || mRefreshing) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
break;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
break;
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (pointerIndex < 0) {
return false;
}
final float y = MotionEventCompat.getY(ev, pointerIndex);
float overscrollTop;
switch (mDirection) {
case BOTTOM:
overscrollTop = (mInitialMotionY - y) * DRAG_RATE;
break;
case TOP:
default:
overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
break;
}
if (mIsBeingDragged) {
mProgress.showArrow(true);
float originalDragPercent = overscrollTop / mTotalDragDistance;
if (originalDragPercent < 0) {
return false;
}
float dragPercent = Math.min(1f, Math.abs(originalDragPercent));
float adjustedPercent = (float) Math.max(dragPercent - .4, 0) * 5 / 3;
float extraOS = Math.abs(overscrollTop) - mTotalDragDistance;
float slingshotDist = mUsingCustomStart ? mSpinnerFinalOffset
- mOriginalOffsetTop : mSpinnerFinalOffset;
float tensionSlingshotPercent = Math.max(0,
Math.min(extraOS, slingshotDist * 2) / slingshotDist);
float tensionPercent = (float) ((tensionSlingshotPercent / 4) - Math.pow(
(tensionSlingshotPercent / 4), 2)) * 2f;
float extraMove = (slingshotDist) * tensionPercent * 2;
int targetY = mOriginalOffsetTop + (int) ((slingshotDist * dragPercent) + extraMove);
/*int targetY;
if (mDirection == SwipyRefreshLayoutDirection.TOP) {
targetY = mOriginalOffsetTop + (int) ((slingshotDist * dragPercent) + extraMove);
} else {
targetY = mOriginalOffsetTop - (int) ((slingshotDist * dragPercent) + extraMove);
}*/
// where 1.0f is a full circle
if (mCircleView.getVisibility() != View.VISIBLE) {
mCircleView.setVisibility(View.VISIBLE);
}
if (!mScale) {
ViewCompat.setScaleX(mCircleView, 1f);
ViewCompat.setScaleY(mCircleView, 1f);
}
if (overscrollTop < mTotalDragDistance) {
if (mScale) {
setAnimationProgress(overscrollTop / mTotalDragDistance);
}
if (mProgress.getAlpha() > STARTING_PROGRESS_ALPHA
&& !isAnimationRunning(mAlphaStartAnimation)) {
// Animate the alpha
startProgressAlphaStartAnimation();
}
float strokeStart = (float) (adjustedPercent * .8f);
mProgress.setStartEndTrim(0f, Math.min(MAX_PROGRESS_ANGLE, strokeStart));
mProgress.setArrowScale(Math.min(1f, adjustedPercent));
} else {
if (mProgress.getAlpha() < MAX_ALPHA
&& !isAnimationRunning(mAlphaMaxAnimation)) {
// Animate the alpha
startProgressAlphaMaxAnimation();
}
}
float rotation = (-0.25f + .4f * adjustedPercent + tensionPercent * 2) * .5f;
mProgress.setProgressRotation(rotation);
setTargetOffsetTopAndBottom(targetY - mCurrentTargetOffsetTop,
true /* requires update */);
}
break;
}
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
if (mActivePointerId == INVALID_POINTER) {
if (action == MotionEvent.ACTION_UP) {
}
return false;
}
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float y = MotionEventCompat.getY(ev, pointerIndex);
float overscrollTop;
switch (mDirection) {
case BOTTOM:
overscrollTop = (mInitialMotionY - y) * DRAG_RATE;
break;
case TOP:
default:
overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
break;
}
mIsBeingDragged = false;
if (overscrollTop > mTotalDragDistance) {
setRefreshing(true, true /* notify */);
} else {
// cancel refresh
mRefreshing = false;
mProgress.setStartEndTrim(0f, 0f);
AnimationListener listener = null;
if (!mScale) {
listener = new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (!mScale) {
startScaleDownAnimation(null);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
};
}
animateOffsetToStartPosition(mCurrentTargetOffsetTop, listener);
mProgress.showArrow(false);
}
mActivePointerId = INVALID_POINTER;
return false;
}
}
} catch (Exception e) {
Log.e(TAG, "An exception occured during SwipyRefreshLayout onTouchEvent " + e.toString());
}
return true;
}
private void animateOffsetToCorrectPosition(int from, AnimationListener listener) {
mFrom = from;
mAnimateToCorrectPosition.reset();
mAnimateToCorrectPosition.setDuration(ANIMATE_TO_TRIGGER_DURATION);
mAnimateToCorrectPosition.setInterpolator(mDecelerateInterpolator);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mAnimateToCorrectPosition);
}
private void animateOffsetToStartPosition(int from, AnimationListener listener) {
if (mScale) {
// Scale the item back down
startScaleDownReturnToStartAnimation(from, listener);
} else {
mFrom = from;
mAnimateToStartPosition.reset();
mAnimateToStartPosition.setDuration(ANIMATE_TO_START_DURATION);
mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mAnimateToStartPosition);
}
}
private final Animation mAnimateToCorrectPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
int targetTop = 0;
int endTarget = 0;
if (!mUsingCustomStart) {
/*switch (mDirection) {
case BOTTOM:
endTarget = getMeasuredHeight() - (int) (mSpinnerFinalOffset);
break;
case TOP:
default:
endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));
break;
}*/
endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));
} else {
endTarget = (int) mSpinnerFinalOffset;
}
targetTop = (mFrom + (int) ((endTarget - mFrom) * interpolatedTime));
int offset = targetTop - mCircleView.getTop();
setTargetOffsetTopAndBottom(offset, false /* requires update */);
}
};
private void moveToStart(float interpolatedTime) {
int targetTop = 0;
targetTop = (mFrom + (int) ((mOriginalOffsetTop - mFrom) * interpolatedTime));
int offset = targetTop - mCircleView.getTop();
setTargetOffsetTopAndBottom(offset, false /* requires update */);
}
private final Animation mAnimateToStartPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
moveToStart(interpolatedTime);
}
};
private void startScaleDownReturnToStartAnimation(int from,
AnimationListener listener) {
mFrom = from;
if (isAlphaUsedForScale()) {
mStartingScale = mProgress.getAlpha();
} else {
mStartingScale = ViewCompat.getScaleX(mCircleView);
}
mScaleDownToStartAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
float targetScale = (mStartingScale + (-mStartingScale * interpolatedTime));
setAnimationProgress(targetScale);
moveToStart(interpolatedTime);
}
};
mScaleDownToStartAnimation.setDuration(SCALE_DOWN_DURATION);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleDownToStartAnimation);
}
private void setTargetOffsetTopAndBottom(int offset, boolean requiresUpdate) {
mCircleView.bringToFront();
mCircleView.offsetTopAndBottom(offset);
// switch (mDirection) {
// case BOTTOM:
// mCurrentTargetOffsetTop = getMeasuredHeight() - mCircleView.getMeasuredHeight();
// break;
// case TOP:
// default:
// mCurrentTargetOffsetTop = mCircleView.getTop();
// break;
// }
mCurrentTargetOffsetTop = mCircleView.getTop();
if (requiresUpdate && android.os.Build.VERSION.SDK_INT < 11) {
invalidate();
}
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
}
/**
* Classes that wish to be notified when the swipe gesture correctly
* triggers a refresh should implement this interface.
*/
public interface OnRefreshListener {
public void onRefresh(SwipyRefreshLayoutDirection direction);
}
public SwipyRefreshLayoutDirection getDirection() {
return mBothDirection ? SwipyRefreshLayoutDirection.BOTH : mDirection;
}
public void setDirection(SwipyRefreshLayoutDirection direction) {
if (direction == SwipyRefreshLayoutDirection.BOTH) {
mBothDirection = true;
} else {
mBothDirection = false;
mDirection = direction;
}
/*switch (mDirection) {
case BOTTOM:
mCurrentTargetOffsetTop = mOriginalOffsetTop = getMeasuredHeight();
break;
case TOP:
default:
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();
break;
}*/
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();
}
// only TOP or Bottom
private void setRawDirection(SwipyRefreshLayoutDirection direction) {
if (mDirection == direction) {
return;
}
mDirection = direction;
/*
switch (mDirection) {
case BOTTOM:
mCurrentTargetOffsetTop = mOriginalOffsetTop = getMeasuredHeight();
break;
case TOP:
default:
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();
break;
}*/
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();
}
public CircleImageView getCircleView() {
return mCircleView;
}
}
|
gpl-2.0
|
6WIND/scapy
|
scapy/route6.py
|
12655
|
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Philippe Biondi <phil@secdev.org>
# This program is published under a GPLv2 license
# Copyright (C) 2005 Guillaume Valadon <guedou@hongo.wide.ad.jp>
# Arnaud Ebalard <arnaud.ebalard@eads.net>
"""
Routing and network interface handling for IPv6.
"""
#############################################################################
# Routing/Interfaces stuff #
#############################################################################
from __future__ import absolute_import
import socket
from scapy.config import conf
from scapy.utils6 import in6_ptop, in6_cidr2mask, in6_and, \
in6_islladdr, in6_ismlladdr, in6_isincluded, in6_isgladdr, \
in6_isaddr6to4, in6_ismaddr, construct_source_candidate_set, \
get_source_addr_from_candidate_set
from scapy.arch import read_routes6, in6_getifaddr
from scapy.pton_ntop import inet_pton, inet_ntop
from scapy.error import warning, log_loading
import scapy.modules.six as six
from scapy.utils import pretty_list
class Route6:
def __init__(self):
self.resync()
self.invalidate_cache()
def invalidate_cache(self):
self.cache = {}
def flush(self):
self.invalidate_cache()
self.ipv6_ifaces = set()
self.routes = []
def resync(self):
# TODO : At the moment, resync will drop existing Teredo routes
# if any. Change that ...
self.invalidate_cache()
self.routes = read_routes6()
self.ipv6_ifaces = set()
for route in self.routes:
self.ipv6_ifaces.add(route[3])
if self.routes == []:
log_loading.info("No IPv6 support in kernel")
def __repr__(self):
rtlst = []
for net, msk, gw, iface, cset, metric in self.routes:
rtlst.append(('%s/%i' % (net, msk),
gw,
(iface if isinstance(iface, six.string_types)
else iface.description),
", ".join(cset) if len(cset) > 0 else "",
str(metric)))
return pretty_list(rtlst,
[('Destination', 'Next Hop', "Iface", "Src candidates", "Metric")], # noqa: E501
sortBy=1)
# Unlike Scapy's Route.make_route() function, we do not have 'host' and 'net' # noqa: E501
# parameters. We only have a 'dst' parameter that accepts 'prefix' and
# 'prefix/prefixlen' values.
def make_route(self, dst, gw=None, dev=None):
"""Internal function : create a route for 'dst' via 'gw'.
"""
prefix, plen = (dst.split("/") + ["128"])[:2]
plen = int(plen)
if gw is None:
gw = "::"
if dev is None:
dev, ifaddr, x = self.route(gw)
else:
lifaddr = in6_getifaddr()
devaddrs = [x for x in lifaddr if x[2] == dev]
ifaddr = construct_source_candidate_set(prefix, plen, devaddrs)
self.ipv6_ifaces.add(dev)
return (prefix, plen, gw, dev, ifaddr, 1)
def add(self, *args, **kargs):
"""Ex:
add(dst="2001:db8:cafe:f000::/56")
add(dst="2001:db8:cafe:f000::/56", gw="2001:db8:cafe::1")
add(dst="2001:db8:cafe:f000::/64", gw="2001:db8:cafe::1", dev="eth0")
"""
self.invalidate_cache()
self.routes.append(self.make_route(*args, **kargs))
def remove_ipv6_iface(self, iface):
"""
Remove the network interface 'iface' from the list of interfaces
supporting IPv6.
"""
if not all(r[3] == iface for r in conf.route6.routes):
try:
self.ipv6_ifaces.remove(iface)
except KeyError:
pass
def delt(self, dst, gw=None):
""" Ex:
delt(dst="::/0")
delt(dst="2001:db8:cafe:f000::/56")
delt(dst="2001:db8:cafe:f000::/56", gw="2001:db8:deca::1")
"""
tmp = dst + "/128"
dst, plen = tmp.split('/')[:2]
dst = in6_ptop(dst)
plen = int(plen)
to_del = [x for x in self.routes
if in6_ptop(x[0]) == dst and x[1] == plen]
if gw:
gw = in6_ptop(gw)
to_del = [x for x in self.routes if in6_ptop(x[2]) == gw]
if len(to_del) == 0:
warning("No matching route found")
elif len(to_del) > 1:
warning("Found more than one match. Aborting.")
else:
i = self.routes.index(to_del[0])
self.invalidate_cache()
self.remove_ipv6_iface(self.routes[i][3])
del(self.routes[i])
def ifchange(self, iff, addr):
the_addr, the_plen = (addr.split("/") + ["128"])[:2]
the_plen = int(the_plen)
naddr = inet_pton(socket.AF_INET6, the_addr)
nmask = in6_cidr2mask(the_plen)
the_net = inet_ntop(socket.AF_INET6, in6_and(nmask, naddr))
for i, route in enumerate(self.routes):
net, plen, gw, iface, addr, metric = route
if iface != iff:
continue
self.ipv6_ifaces.add(iface)
if gw == '::':
self.routes[i] = (the_net, the_plen, gw, iface, [the_addr], metric) # noqa: E501
else:
self.routes[i] = (net, plen, gw, iface, [the_addr], metric)
self.invalidate_cache()
conf.netcache.in6_neighbor.flush()
def ifdel(self, iff):
""" removes all route entries that uses 'iff' interface. """
new_routes = []
for rt in self.routes:
if rt[3] != iff:
new_routes.append(rt)
self.invalidate_cache()
self.routes = new_routes
self.remove_ipv6_iface(iff)
def ifadd(self, iff, addr):
"""
Add an interface 'iff' with provided address into routing table.
Ex: ifadd('eth0', '2001:bd8:cafe:1::1/64') will add following entry into # noqa: E501
Scapy6 internal routing table:
Destination Next Hop iface Def src @ Metric
2001:bd8:cafe:1::/64 :: eth0 2001:bd8:cafe:1::1 1
prefix length value can be omitted. In that case, a value of 128
will be used.
"""
addr, plen = (addr.split("/") + ["128"])[:2]
addr = in6_ptop(addr)
plen = int(plen)
naddr = inet_pton(socket.AF_INET6, addr)
nmask = in6_cidr2mask(plen)
prefix = inet_ntop(socket.AF_INET6, in6_and(nmask, naddr))
self.invalidate_cache()
self.routes.append((prefix, plen, '::', iff, [addr], 1))
self.ipv6_ifaces.add(iff)
def route(self, dst=None, dev=None, verbose=conf.verb):
"""
Provide best route to IPv6 destination address, based on Scapy
internal routing table content.
When a set of address is passed (e.g. ``2001:db8:cafe:*::1-5``) an
address of the set is used. Be aware of that behavior when using
wildcards in upper parts of addresses !
If 'dst' parameter is a FQDN, name resolution is performed and result
is used.
if optional 'dev' parameter is provided a specific interface, filtering
is performed to limit search to route associated to that interface.
"""
dst = dst or "::/0" # Enable route(None) to return default route
# Transform "2001:db8:cafe:*::1-5:0/120" to one IPv6 address of the set
dst = dst.split("/")[0]
savedst = dst # In case following inet_pton() fails
dst = dst.replace("*", "0")
idx = dst.find("-")
while idx >= 0:
m = (dst[idx:] + ":").find(":")
dst = dst[:idx] + dst[idx + m:]
idx = dst.find("-")
try:
inet_pton(socket.AF_INET6, dst)
except socket.error:
dst = socket.getaddrinfo(savedst, None, socket.AF_INET6)[0][-1][0]
# TODO : Check if name resolution went well
# Choose a valid IPv6 interface while dealing with link-local addresses
if dev is None and (in6_islladdr(dst) or in6_ismlladdr(dst)):
dev = conf.iface # default interface
# Check if the default interface supports IPv6!
if dev not in self.ipv6_ifaces and self.ipv6_ifaces:
tmp_routes = [route for route in self.routes
if route[3] != conf.iface]
default_routes = [route for route in tmp_routes
if (route[0], route[1]) == ("::", 0)]
ll_routes = [route for route in tmp_routes
if (route[0], route[1]) == ("fe80::", 64)]
if default_routes:
# Fallback #1 - the first IPv6 default route
dev = default_routes[0][3]
elif ll_routes:
# Fallback #2 - the first link-local prefix
dev = ll_routes[0][3]
else:
# Fallback #3 - the loopback
dev = conf.loopback_name
warning("The conf.iface interface (%s) does not support IPv6! "
"Using %s instead for routing!" % (conf.iface, dev))
# Deal with dev-specific request for cache search
k = dst
if dev is not None:
k = dst + "%%" + (dev if isinstance(dev, six.string_types) else dev.pcap_name) # noqa: E501
if k in self.cache:
return self.cache[k]
paths = []
# TODO : review all kinds of addresses (scope and *cast) to see
# if we are able to cope with everything possible. I'm convinced
# it's not the case.
# -- arnaud
for p, plen, gw, iface, cset, me in self.routes:
if dev is not None and iface != dev:
continue
if in6_isincluded(dst, p, plen):
paths.append((plen, me, (iface, cset, gw)))
elif (in6_ismlladdr(dst) and in6_islladdr(p) and in6_islladdr(cset[0])): # noqa: E501
paths.append((plen, me, (iface, cset, gw)))
if not paths:
if dst == "::1":
return (conf.loopback_name, "::1", "::")
else:
if verbose:
warning("No route found for IPv6 destination %s "
"(no default route?)", dst)
return (conf.loopback_name, "::", "::")
# Sort with longest prefix first then use metrics as a tie-breaker
paths.sort(key=lambda x: (-x[0], x[1]))
best_plen = (paths[0][0], paths[0][1])
paths = [x for x in paths if (x[0], x[1]) == best_plen]
res = []
for p in paths: # Here we select best source address for every route
tmp = p[2]
srcaddr = get_source_addr_from_candidate_set(dst, tmp[1])
if srcaddr is not None:
res.append((p[0], p[1], (tmp[0], srcaddr, tmp[2])))
if res == []:
warning("Found a route for IPv6 destination '%s', but no possible source address.", dst) # noqa: E501
return (conf.loopback_name, "::", "::")
# Symptom : 2 routes with same weight (our weight is plen)
# Solution :
# - dst is unicast global. Check if it is 6to4 and we have a source
# 6to4 address in those available
# - dst is link local (unicast or multicast) and multiple output
# interfaces are available. Take main one (conf.iface)
# - if none of the previous or ambiguity persists, be lazy and keep
# first one
if len(res) > 1:
tmp = []
if in6_isgladdr(dst) and in6_isaddr6to4(dst):
# TODO : see if taking the longest match between dst and
# every source addresses would provide better results
tmp = [x for x in res if in6_isaddr6to4(x[2][1])]
elif in6_ismaddr(dst) or in6_islladdr(dst):
# TODO : I'm sure we are not covering all addresses. Check that
tmp = [x for x in res if x[2][0] == conf.iface]
if tmp:
res = tmp
# Fill the cache (including dev-specific request)
k = dst
if dev is not None:
k = dst + "%%" + (dev if isinstance(dev, six.string_types) else dev.pcap_name) # noqa: E501
self.cache[k] = res[0][2]
return res[0][2]
conf.route6 = Route6()
|
gpl-2.0
|
eugcar/RSA_Algorithm
|
RSA_Algorithm/doc/vp_doc/content/tooltip.js
|
9202
|
var tooltip = {
hideTooltipTimeOut : 1000,
showTooltipTimeOut : 500,
xOffset : 20,
yOffset : 0,
area : Object,
shadowArea : Object,
tipLayer : Object,
tipConnectorLayer : Object,
tipPinLayer : Object,
hideTimeoutId : '',
showTimeoutId : '',
opacityId : '',
tooltipVisible : false,
init : function(){
tipLayer = document.createElement('div');
tipLayer.id = 'toolTip';
document.getElementsByTagName('body')[0].appendChild(tipLayer);
tipLayer.className="TableContent Documentation";
tipLayer.style.top = '0';
tipLayer.style.visibility = 'hidden';
tipLayer.style.zIndex=5;
tipLayer.onmouseover= function onmouseover(event) {
if (window.showTimeoutId) {
clearTimeout(showTimeoutId);
}
if (window.hideTimeoutId) {
clearTimeout(hideTimeoutId);
}
};
tipLayer.onmouseout= function onmouseout(event) {
tooltip.hide();
};
{
// tip connector
tipConnectorLayer = document.createElement('div');
tipConnectorLayer.id = 'toolTipConnector';
document.getElementsByTagName('body')[0].appendChild(tipConnectorLayer);
tipConnectorLayer.className="Documentation";
tipConnectorLayer.style.top = '0';
tipConnectorLayer.style.visibility = 'hidden';
tipConnectorLayer.style.zIndex=2; // index = 2, below indicator's index = 3
tipConnectorLayer.onmouseover = tipLayer.onmouseover;
tipConnectorLayer.onmouseout = tipLayer.onmouseout;
}
{
// tip pin
tipPinLayer = document.createElement('div');
tipPinLayer.id = 'toolTipPin';
document.getElementsByTagName('body')[0].appendChild(tipPinLayer);
tipPinLayer.className="Documentation";
tipPinLayer.style.top = '0';
tipPinLayer.style.visibility = 'hidden';
tipPinLayer.style.zIndex=2; // index = 2, below indicator's index = 3
tipPinLayer.onmouseover = tipLayer.onmouseover;
tipPinLayer.onmouseout = tipLayer.onmouseout;
}
shadowArea = document.createElement('div');
shadowArea.id = 'shadowArea';
shadowArea.onmouseover= tipLayer.onmouseover;
shadowArea.onmouseout = tipLayer.onmouseout;
document.getElementsByTagName('body')[0].appendChild(shadowArea);
},
show : function(area){
this.tooltipVisible = true;
if (window.hideTimeoutId) {
clearTimeout(hideTimeoutId);
}
if (window.opacityId) {
clearTimeout(opacityId);
}
this.area = area;
area.removeAttribute('title');
this.updateShadowArea(area);
tipLayer.style.visibility = 'visible';
tipLayer.style.opacity = '.1';
tipLayer.style.zIndex=5;
tipLayer.innerHTML = area.getAttribute('docContent')
.replace(/>/g, '>').replace(/</g, '<')
.replace(/&\u200blt;/g, '<').replace(/&\u200bgt;/g, '>') // replace the &{zero-length-space}lt; to <
.replace(/"/g, '"');
tipConnectorLayer.style.visibility = 'visible';
tipConnectorLayer.style.opacity = '.1';
tipConnectorLayer.style.zIndex=5;
tipPinLayer.style.visibility = 'visible';
tipPinLayer.style.opacity = '.1';
tipPinLayer.style.zIndex=5;
this.moveTo(area);
this.fade(10);
},
updateShadowArea : function(area){
var areaCoordinate = area.coords.split(",");
var topRightX = areaCoordinate[2]*1
var topRightY = areaCoordinate[1]*1
var width = this.xOffset;
var height = areaCoordinate[3]*1 - topRightY;
N = (document.all) ? 0 : 1;
var diagram = document.getElementById("diagram");
if (N) {
shadowArea.style.left = findPosX(diagram) + topRightX;
shadowArea.style.top = findPosY(diagram) + topRightY;
} else {
shadowArea.style.posLeft = findPosX(diagram) + topRightX;
shadowArea.style.posTop = findPosY(diagram) + topRightY;
}
shadowArea.style.width = width;
shadowArea.style.height = height;
},
fade : function(opac) {
var passed = parseInt(opac);
var newOpac = parseInt(passed+5);
if ( newOpac < 90 ) {
tipLayer.style.opacity = '.'+newOpac;
tipLayer.style.filter = "alpha(opacity:"+newOpac+")";
tipConnectorLayer.style.opacity = '.'+newOpac;
tipConnectorLayer.style.filter = "alpha(opacity:"+newOpac+")";
tipPinLayer.style.opacity = '.'+newOpac;
tipPinLayer.style.filter = "alpha(opacity:"+newOpac+")";
opacityId = window.setTimeout("tooltip.fade('"+newOpac+"')", 40);
}
else {
tipLayer.style.opacity = '.90';
tipLayer.style.filter = "alpha(opacity:90)";
tipConnectorLayer.style.opacity = '.90';
tipConnectorLayer.style.filter = "alpha(opacity:90)";
tipPinLayer.style.opacity = '.90';
tipPinLayer.style.filter = "alpha(opacity:90)";
}
},
moveTo : function(area) {
var diagram = document.getElementById("diagram");
var lDiagramX = findPosX(diagram)
var lDiagramY = findPosY(diagram)
var lTipLayerX = lDiagramX;
var lTipLayerY = lDiagramY + diagram.height;
lTipLayerX += getScrollLeft();
var lAreaCoordinate = area.coords.split(",");
// var lAreaTop = lAreaCoordinate[1]*1 + lDiagramY;
var lAreaBottom = lAreaCoordinate[3]*1 + lDiagramY;
var lAreaX1 = lAreaCoordinate[0]*1 + lDiagramX;
var lAreaX2 = lAreaCoordinate[2]*1 + lDiagramX
var lScreenBottom = getScrollTop()+getClientHeight() - tipLayer.offsetHeight; // no height is set in layer. Just try to - 300
if (lTipLayerY > lScreenBottom) {
if (lScreenBottom < lAreaBottom) {
// don't overlap with the area
lScreenBottom = lAreaBottom;
}
lTipLayerY = lScreenBottom;
}
N = (document.all) ? 0 : 1;
if (N) {
tipLayer.style.left = lTipLayerX;
tipLayer.style.top = lTipLayerY;
tipPinLayer.style.left = lAreaX1;
tipPinLayer.style.top = lAreaBottom;
tipConnectorLayer.style.left = lAreaX1+((lAreaX2-lAreaX1)/2); // -2 for connector's width/2
tipConnectorLayer.style.top = lAreaBottom+6; // +6 for pin's height+borderHeight
}
else {
tipLayer.style.posLeft = lTipLayerX;
tipLayer.style.posTop = lTipLayerY;
tipPinLayer.style.posLeft = lAreaX1;
tipPinLayer.style.posTop = lAreaBottom;
tipConnectorLayer.style.posLeft = lAreaX1+((lAreaX2-lAreaX1)/2); // -2 for connector's width/2
tipConnectorLayer.style.posTop = lAreaBottom+6; // +6 for pin's height+borderHeight
}
var lScreenWidth = getWidth(lTipLayerX);
tipLayer.style.width = lScreenWidth;
tipPinLayer.style.width = lAreaX2-lAreaX1;
if (lTipLayerY > lAreaBottom+6) {
tipConnectorLayer.style.height = lTipLayerY-lAreaBottom-6;
}
else {
tipPinLayer.style.visibility = 'hidden';
tipConnectorLayer.style.visibility = 'hidden';
}
},
hide : function() {
hideTimeoutId = window.setTimeout(function() {
this.tooltipVisible = false;
if (window.showTimeoutId) {
clearTimeout(showTimeoutId);
}
if (window.hideTimeoutId) {
clearTimeout(hideTimeoutId);
}
if (window.opacityId) {
clearTimeout(opacityId);
}
tipLayer.style.visibility = 'hidden';
tipConnectorLayer.style.visibility = 'hidden';
tipPinLayer.style.visibility = 'hidden';
}, this.hideTooltipTimeOut);
}
};
function initPage(){
tooltip.init();
}
function showTooltip(area) {
if (tooltip.tooltipVisible) {
if (window.showTimeoutId) {
clearTimeout(showTimeoutId);
}
if (window.hideTimeoutId) {
clearTimeout(hideTimeoutId);
}
showTimeoutId = window.setTimeout(function() {
if (window.showTimeoutId) {
clearTimeout(showTimeoutId);
}
tooltip.show(area);
}, tooltip.showTooltipTimeOut);
}
else {
tooltip.show(area);
}
}
function hideTooltip(){
tooltip.hide();
}
function getWidth(aLeft) {
var lWidth = getClientWidth() + getScrollLeft() - aLeft - 20;
return lWidth;
}
function getClientWidth() {
return filterResults (
window.innerWidth ? window.innerWidth : 0,
document.documentElement ? document.documentElement.clientWidth : 0,
document.body ? document.body.clientWidth : 0
);
}
function getClientHeight() {
return filterResults (
window.innerHeight ? window.innerHeight : 0,
document.documentElement ? document.documentElement.clientHeight : 0,
document.body ? document.body.clientHeight : 0
);
}
function getScrollLeft() {
return filterResults (
window.pageXOffset ? window.pageXOffset : 0,
document.documentElement ? document.documentElement.scrollLeft : 0,
document.body ? document.body.scrollLeft : 0
);
}
function getScrollTop() {
return filterResults (
window.pageYOffset ? window.pageYOffset : 0,
document.documentElement ? document.documentElement.scrollTop : 0,
document.body ? document.body.scrollTop : 0
);
}
function filterResults(aWin, aDoc, aBody) {
var aResult = aWin ? aWin : 0;
if (aDoc && (!aResult || (aResult > aDoc)))
aResult = aDoc;
return aBody && (!aResult || (aResult > aBody)) ? aBody : aResult;
}
|
gpl-2.0
|
kosmosby/medicine-prof
|
components/com_judownload/fields/core_language/core_language.php
|
3103
|
<?php
/**
* ------------------------------------------------------------------------
* JUDownload for Joomla 2.5, 3.x
* ------------------------------------------------------------------------
*
* @copyright Copyright (C) 2010-2015 JoomUltra Co., Ltd. All Rights Reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author JoomUltra Co., Ltd
* @website http://www.joomultra.com
* @----------------------------------------------------------------------@
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
class JUDownloadFieldCore_language extends JUDownloadFieldBase
{
protected $field_name = 'language';
public function getPredefinedValuesHtml()
{
$items = self::getLanguages();
return JHtml::_("select.genericlist", $items, "jform[predefined_values]", null, 'value', 'text', $this->value, $this->getId());
}
public function getInput($fieldValue = null)
{
if (!$this->isPublished())
{
return "";
}
$items = $this->getLanguages();
$value = !is_null($fieldValue) ? $fieldValue : $this->value;
$this->addAttribute("class", $this->getInputClass(), "input");
$this->setVariable('items', $items);
$this->setVariable('value', $value);
return $this->fetch('input.php', __CLASS__);
}
protected function getLanguages()
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('a.lang_code AS value, a.title AS text, a.title_native');
$query->from('#__languages AS a');
$query->where('a.published >= 0');
$query->order('a.title');
$db->setQuery($query);
$items = $db->loadObjectList();
array_unshift($items, new JObject(array('value' => '*', 'text' => JText::alt('JALL', 'language'))));
return $items;
}
public function getSearchInput($defaultValue = "")
{
if (!$this->isPublished())
{
return "";
}
$options = self::getLanguages();
$options[0]->value = '';
$options[0]->text = JText::_('COM_JUDOWNLOAD_SELECT_LANGUAGE');
$this->setVariable('defaultValue', $defaultValue);
$this->setVariable('options', $options);
return $this->fetch('searchinput.php', __CLASS__);
}
public function onSearch(&$query, &$where, $search)
{
if ($search !== "")
{
$db = JFactory::getDbo();
$app = JFactory::getApplication();
if ($app->isSite())
{
$tag = JFactory::getLanguage()->getTag();
$where[] = $this->fieldvalue_column . ' IN (' . $db->quote($search) . ',' . $db->quote($tag) . ',' . $db->quote('*') . ',"")';
}
else
{
$where[] = $this->fieldvalue_column . ' IN (' . $db->quote($search) . ',' . $db->quote('*') . ',"")';
}
}
}
public function getBackendOutput()
{
return $this->getOutput();
}
public function getOutput($options = array())
{
if (!$this->isPublished())
{
return "";
}
$value = $this->value;
$this->setVariable('value', $value);
return $this->fetch('output.php', __CLASS__);
}
}
?>
|
gpl-2.0
|
cuenka/Joomla
|
Modules/mod_latestonCategoryk2/tmpl/default.php
|
788
|
<?php // no direct access
defined('_JEXEC') or die;
JHtml::_('bootstrap.tooltip');
?>
<div class="row-striped">
<?php if (count($items)) : ?>
<?php foreach ($items as $item) : ?>
<div class="row-fluid">
<div class="span2">
<span class="big"><?php echo $item->id; ?></span>
</div>
<div class="span7">
<span class="big"><?php echo $item->title; ?></span>
</div>
<div class="span3">
<span class="small"><i
class="icon-calendar"></i> <?php echo JHtml::_('date', $item->publish_up, 'Y-m-d'); ?></span>
</div>
</div>
<?php endforeach; ?>
<?php else : ?>
<div class="row-fluid">
<div class="span12">
<div class="alert"><?php echo JText::_('MOD_LATEST_NO_MATCHING_RESULTS');?></div>
</div>
</div>
<?php endif; ?>
</div>
|
gpl-2.0
|
Raydicul/Zapinformatique
|
wp-content/themes/zapinformatique/header.php
|
2573
|
<?php
/**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="content">
*
* @package Simone
*/
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php wp_title( '|', true, 'right' ); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<?php wp_head(); ?>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body <?php body_class(); ?>>
<div id="page" class="hfeed site">
<header id="masthead" class="site-header" role="banner">
<a class="skip-link screen-reader-text" href="#content"><?php _e( 'Skip to content', 'simone' ); ?></a>
<?php if ( get_header_image() && ('blank' == get_header_textcolor()) ) { ?>
<figure class="header-image">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<img src="<?php header_image(); ?>" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="">
</a>
</figure>
<?php } // End header image check. ?>
<?php
if ( get_header_image() && !('blank' == get_header_textcolor()) ) {
echo '<div class="site-branding header-background-image" style="background-image: url(' . get_header_image() . ')">';
} else {
echo '<div class="site-branding">';
}
?>
<div class="title-box">
<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
<h2 class="site-description"><?php bloginfo( 'description' ); ?></h2>
</div>
</div>
<center>
<nav id="site-navigation" class="main-navigation clear" role="navigation">
<h1 class="menu-toggle"><a href="#"><?php _e( 'Menu', 'simone' ); ?></a></h1>
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
<?php simone_social_menu(); ?>
</nav><!-- #site-navigation -->
</center>
</header><!-- #masthead -->
<div id="content" class="site-content">
|
gpl-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.