code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
const Koa = require('koa') const screenshot = require('./screenshot') const app = new Koa() app.use(async ctx => { var url = ctx.query.url console.log('goto:', url) if (!/^https?:\/\/.+/.test(url)) { ctx.body = 'url 不合法' } else { if (!isNaN(ctx.query.wait)) { ctx.query.wait = ~~ctx.query.wait } let data = await screenshot(url, ctx.query.wait, ~~ctx.query.width) if (ctx.query.base64) { ctx.body = 'data:image/jpeg;base64,' + data } else { ctx.body = `<img src="data:image/jpeg;base64,${data}" />` } } }) app.listen(8000) console.log('server start success at 8000') // process.on('unCaughtException', function (err) { // console.log(err) // })
lwdgit/chrome-automator
examples/screenshot/index.js
JavaScript
mit
710
// Test get machiens var fs = require('fs'); try { fs.accessSync('testdb.json', fs.F_OK); fs.unlinkSync('testdb.json'); // Do something } catch (e) { // It isn't accessible console.log(e); } var server = require('../server.js').createServer(8000, 'testdb.json'); var addTestMachine = function(name) { var newMachine = {}; newMachine.name = name; newMachine.type = 'washer'; newMachine.queue = []; newMachine.operational = true; newMachine.problemMessage = ""; newMachine.activeJob = {}; server.db('machines').push(newMachine); } describe('ALL THE TESTS LOL', function() { it('should add a machine', function(done) { var options = { method: 'POST', url: '/machines', payload: { name: 'test1', type: 'washer' } } server.inject(options, function(response) { expect(response.statusCode).toBe(200); var p = JSON.parse(response.payload); expect(p.name).toBe(options.payload.name); expect(p.type).toBe(options.payload.type); done(); }) }); it('should get all machines', function(done) { var name = 'testMachine'; var name2 = 'anotherMachine'; addTestMachine(name); addTestMachine(name2); var options = { method: 'GET', url: '/machines', } server.inject(options, function(res) { expect(res.statusCode).toBe(200); var p = JSON.parse(res.payload); // check p has test and anotherMachine done(); }); }); it('should get one machine', function(done) { var name = 'sweetTestMachine'; addTestMachine(name); var options = { method: 'GET', url: '/machines/'+name }; server.inject(options, function(res) { expect(res.statusCode).toBe(200); var p = JSON.parse(res.payload); expect(p.name).toBe(name); done(); }); }); it('should add a job the queue then th queue should have the person', function(done) { addTestMachine('queueTest'); var addOptions = { method: 'POST', url: '/machines/queueTest/queue', payload: { user: 'test@mail.com', pin: 1234, minutes: 50 } }; server.inject(addOptions, function(res) { expect(res.statusCode).toBe(200); var p = JSON.parse(res.payload); expect(p.name).toBe('queueTest'); var getQueue = { method: 'GET', url: '/machines/queueTest/queue' }; server.inject(getQueue, function(newRes) { expect(newRes.statusCode).toBe(200); var q = JSON.parse(newRes.payload); console.log(q); expect(q.queue[0].user).toBe('test@mail.com'); expect(q.queue[0].pin).toBe(1234); done(); }) }) }); it('should delete a job from the queue', function(done) { addTestMachine('anotherQueue'); var addOptions = { method: 'POST', url: '/machines/anotherQueue/queue', payload: { user: 'test@mail.com', pin: 1235, minutes: 50 } }; server.inject(addOptions, function(res) { var deleteOptions = addOptions; deleteOptions.url = '/machines/anotherQueue/queue/delete'; deleteOptions.payload = { user: addOptions.payload.user, pin: addOptions.payload.pin } server.inject(deleteOptions, function(r) { expect(r.statusCode).toBe(200); console.log(JSON.parse(r.payload)); done(); }) }) }) it('should add a job to the active queue', function(done) { addTestMachine('activeQueue'); var addOptions = { method: 'POST', url: '/machines/activeQueue/queue', payload: { user: 'test@mail.com', pin: 1235, minutes: 50 } }; server.inject(addOptions, function(r) { var runJobOptions = { method: 'POST', url: '/machines/activeQueue/queue/start', payload: { command: 'next', pin: 1235, minutes: 0 } }; server.inject(runJobOptions, function(res) { expect(res.statusCode).toBe(200); done(); }) }) }); });
sdierauf/laundrytime
spec/getMachinesSpec.js
JavaScript
mit
4,145
require "administrate/field/base" class EnumField < Administrate::Field::Base def to_s data end end
MontrealNewTech/website
app/fields/enum_field.rb
Ruby
mit
109
require('./loader.jsx');
arjunmehta/react-frontend-template
src/index.js
JavaScript
mit
25
from __future__ import absolute_import from .base import WhiteNoise __version__ = '2.0.3' __all__ = ['WhiteNoise']
KnockSoftware/whitenoise
whitenoise/__init__.py
Python
mit
118
game.PlayerEntity = me.Entity.extend ({ //builds the player class init: function(x, y, settings){ this.setSuper(x, y); this.setPlayerTimer(); this.setAttributes(); this.type="PlayerEntity"; this.setFlags(); me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); //locks camera on the character this.addAnimation(); this.renderable.setCurrentAnimation("idle"); //sets the idle animation }, setSuper: function(x, y){ this._super(me.Entity, 'init', [x, y, {//._super reaches to the object entity image: "player",//uses the image player width: 64, //preserves the height and width for player height: 64, spritewidth: "64", //uses height and width for player spriteheight: "64", getShape: function(){ return(new me.Rect(0, 0, 64, 64)) . toPolygon(); //creates a little rectangle for what the player can walk into. } }]); }, setPlayerTimer: function(){ this.now = new Date().getTime(); //keeps track of what time it is this.lastHit = this.now; //same as this.now this.lastSpear = this.now; this.lastAttack = new Date().getTime(); }, setAttributes: function(){ this.health = game.data.playerHealth; this.body.setVelocity(game.data.playerMoveSpeed, 20); //sets velocity to 5 this.attack = game.data.playerAttack; }, setFlags: function(){ this.facing = "right"; //makes the character face right this.dead = false; this.attacking = false; }, addAnimation: function(){ this.renderable.addAnimation("idle", [78]); //idle animation this.renderable.addAnimation("walk", [143, 144, 145, 146, 147, 148, 149, 150, 151], 80); //walking animation this.renderable.addAnimation("attack", [195, 196, 197, 198, 199, 200], 80); //setting the attack animation }, update: function(delta){ this.now = new Date().getTime(); //everytime we call update it updates the time this.dead = this.checkIfDead(); this.checkKeyPressesAndMove(); this.checkAbilityKeys(); this.setAnimation(); me.collision.check(this, true, this.collideHandler.bind(this), true); this.body.update(delta); //delta is the change in time this._super(me.Entity, "update", [delta]); return true; }, checkIfDead: function(){ if (this.health <= 0){ return true; } }, checkKeyPressesAndMove: function(){ if(me.input.isKeyPressed("right")){ //checks to see if the right key is pressed this.moveRight(); } else if(me.input.isKeyPressed("left")){ //allows the player to move left this.moveLeft(); } else{ this.body.vel.x = 0; //stops the movement } if(me.input.isKeyPressed("jump") && !this.jumping && !this.falling){ //allows the player to jump without double jumping or falling and jumping this.jump(); } this.attacking = me.input.isKeyPressed("attack"); //attack key }, moveRight: function(){ this.body.vel.x += this.body.accel.x * me.timer.tick; //adds the velocity to the set velocity and mutiplies by the me.timer.tick and makes the movement smooth this.facing = "right"; //sets the character to face right this.flipX(false); }, moveLeft: function(){ this.body.vel.x -= this.body.accel.x * me.timer.tick; this.facing = "left"; this.flipX(true); }, jump: function(){ this.body.jumping = true; this.body.vel.y -= this.body.accel.y * me.timer.tick; }, checkAbilityKeys: function(){ if(me.input.isKeyPressed("skill1")){ // this.speedBurst(); }else if(me.input.isKeyPressed("skill2")){ // this.eatCreep(); }else if(me.input.isKeyPressed("skill3")){ this.throwSpear(); } }, throwSpear: function(){ if(this.now-this.lastSpear >= game.data.spearTimer*100 && game.data.ability3 > 0){ this.lastSpear = this.now; var spear = me.pool.pull("spear", this.pos.x, this.pos.y, {}, this.facing); me.game.world.addChild(spear, 10); } }, setAnimation: function(){ if(this.attacking){ if(!this.renderable.isCurrentAnimation("attack")){ this.renderable.setCurrentAnimation("attack", "idle"); this.renderable.setAnimationFrame(); } } else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){ //changes the animation from attack to walking if (!this.renderable.isCurrentAnimation("walk")) { //sets the current animation for walk this.renderable.setCurrentAnimation("walk"); }; } else if(!this.renderable.isCurrentAnimation("attack")){ //changes the animation from attack to idle this.renderable.setCurrentAnimation("idle"); //if the player is not walking it uses idle animation } }, loseHealth: function(damage){ this.health = this.health - damage; }, collideHandler: function(response){ if(response.b.type==='EnemyBaseEntity'){ //sees if the enemy base entitiy is near a player entity and if so it is solid from left and right and top this.collideWithEnemyBase(response); } else if(response.b.type==='EnemyCreep'){ this.collideWithEnemyCreep(response); } }, collideWithEnemyBase: function(response){ var ydif = this.pos.y - response.b.pos.y; var xdif = this.pos.x - response.b.pos.x; if(ydif<-40 && xdif<70 && xdif>-35){ this.body.falling=false; this.body.vel.y = -1; } if(xdif>-35 && this.facing==='right' && (xdif<0)){ this.body.vel.x = 0; //this.pos.x = this.pos.x -1; } else if(xdif<70 && this.facing==='left' && (xdif>0)){ this.body.vel.x=0; //this.pos.x = this.pos.x +1; } if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){ //if the animation is attack it will lose the base health and that it will check when the lasthit was this.lastHit = this.now; response.b.loseHealth(game.data.playerAttack); } }, collideWithEnemyCreep: function(response){ var xdif = this.pos.x - response.b.pos.x; var ydif = this.pos.y - response.b.pos.y; this.stopMovement(xdif); if(this.checkAttack(xdif, ydif)){ this.hitCreep(response); }; }, stopMovement: function(xdif){ if(xdif > 0){ //this.pos.x = this.pos.x + 1; if (this.facing === "left"){ this.body.vel.x = 0; } } else{ //this.pos.x = this.pos.x - 1; if(this.facing === "right"){ this.body.vel.x = 0; } } }, checkAttack: function(xdif, ydif){ if(this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= game.data.playerAttackTimer && (Math.abs(ydif) <=40) && ((xdif>0) && this.facing==="left") || (((xdif<0) && this.facing === "right"))){ this.lastHit = this.now; return true; } return false; }, hitCreep: function(response){ if(response.b.health <= game.data.playerAttack){ game.data.gold += 1; } response.b.loseHealth(game.data.playerAttack); } }); //intermeidiae challenge creating an ally creep game.MyCreep = me.Entity.extend({ init: function(x, y, settings){ this._super(me.Entity, 'init', [x, y, { image: "creep2", width: 100, height:85, spritewidth: "100", spriteheight: "85", getShape: function(){ return (new me.Rect(0, 0, 52, 100)).toPolygon(); } }]); this.health = game.data.allyCreepHealth; this.alwaysUpdate = true; // //this.attacking lets us know if the enemy is currently attacking this.attacking = false; // //keeps track of when our creep last attacked anyting this.lastAttacking = new Date().getTime(); this.lastHit = new Date().getTime(); this.now = new Date().getTime(); this.body.setVelocity(game.data.allyCreepMoveSpeed, 20); this.type = "MyCreep"; this.renderable.addAnimation("walk", [0, 1, 2, 3, 4], 80); this.renderable.setCurrentAnimation("walk"); }, update: function(delta) { // this.now = new Date().getTime(); this.body.vel.x += this.body.accel.x * me.timer.tick; this.flipX(true); me.collision.check(this, true, this.collideHandler.bind(this), true); this.body.update(delta); this._super(me.Entity, "update", [delta]); return true; }, collideHandler: function(response) { if(response.b.type==='EnemyBaseEntity'){ this.attacking = true; //this.lastAttacking = this.now; this.body.vel.x = 0; this.pos.x = this.pos.x +1; //checks that it has been at least 1 second since this creep hit a base if((this.now-this.lastHit <= game.data.allyCreepAttackTimer)){ //updates the last hit timer this.lastHit = this.now; //makes the player base call its loseHealth function and passes it a damage of 1 response.b.loseHealth(1); } } } });
romulus1/FinalAwesomauts
js/entities/entities.js
JavaScript
mit
8,421
package uk.gov.dvsa.ui.pages.vehicleinformation; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import uk.gov.dvsa.domain.model.vehicle.Make; import uk.gov.dvsa.domain.navigation.PageNavigator; import uk.gov.dvsa.framework.config.webdriver.MotAppDriver; import uk.gov.dvsa.helper.FormDataHelper; import uk.gov.dvsa.helper.PageInteractionHelper; import uk.gov.dvsa.ui.pages.Page; public class VehicleMakePage extends Page { private static final String PAGE_TITLE = "What is the vehicle's make?"; public static final String PATH = "/create-vehicle/make"; @FindBy(id = "vehicleMake") private WebElement vehicleMakeDropdown; @FindBy(className = "button") private WebElement continueButton; public VehicleMakePage(MotAppDriver driver) { super(driver); selfVerify(); } @Override protected boolean selfVerify() { return PageInteractionHelper.verifyTitle(this.getTitle(), PAGE_TITLE); } public VehicleMakePage selectMake(Make make){ FormDataHelper.selectFromDropDownByValue(vehicleMakeDropdown, make.getId().toString()); vehicleMakeDropdown.sendKeys(Keys.TAB); return this; } public VehicleModelPage continueToVehicleModelPage() { continueButton.click(); return new VehicleModelPage(driver); } public VehicleModelPage updateVehicleMake(Make make) { FormDataHelper.selectFromDropDownByValue(vehicleMakeDropdown, make.getId().toString()); vehicleMakeDropdown.sendKeys(Keys.TAB); return continueToVehicleModelPage(); } }
dvsa/mot
mot-selenium/src/main/java/uk/gov/dvsa/ui/pages/vehicleinformation/VehicleMakePage.java
Java
mit
1,635
<?php namespace Tecnokey\ShopBundle\Controller\Frontend\User; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Tecnokey\ShopBundle\Entity\Shop\Order; use Tecnokey\ShopBundle\Form\Shop\OrderType; /** * Shop\Order controller. * * @Route("/tienda/usuario/pedidos") */ class OrderController extends Controller { /** * Lists all Shop\Order entities. * * @Route("/", name="TKShopFrontendOrderIndex") * @Template() */ public function indexAction() { $em = $this->getDoctrine()->getEntityManager(); $entities = $em->getRepository('TecnokeyShopBundle:Shop\Order')->findAll(); return array('entities' => $entities); } /** * * * @Route("/realizados", name="TKShopFrontendOrdersShowDelivered") * @Template() */ public function showDeliveredAction() { $orderBy = $this->get('view.sort'); $orderBy->add('pedido', 'publicId', 'pedido') ->add('fecha', 'created_at', 'Fecha') ->add('cantidad', 'quantity', 'Cantidad') ->add('importe', 'totalPrice', 'Importe') ->add('estado', 'status', 'Estado') ->initialize(); $em = $this->getDoctrine()->getEntityManager(); $user = $this->get('userManager')->getCurrentUser(); $entities = $em->getRepository('TecnokeyShopBundle:Shop\\User')->findDeliveredOrders($user, $orderBy->getValues()); return array( 'entities' => $entities, 'orderBy' => $orderBy->switchMode(), ); } /** * * * @Route("/en_proceso", name="TKShopFrontendOrdersShowInProcess") * @Template() */ public function showInProcessAction() { $orderBy = $this->get('view.sort'); $orderBy->add('pedido', 'publicId', 'pedido') ->add('fecha', 'createdAt', 'Fecha') ->add('cantidad', 'quantity', 'Cantidad') ->add('importe', 'totalPrice', 'Importe') ->add('estado', 'status', 'Estado') ->initialize(); $em = $this->getDoctrine()->getEntityManager(); $user = $this->get('userManager')->getCurrentUser(); $entities = $em->getRepository('TecnokeyShopBundle:Shop\\User')->findInProcessOrders($user, $orderBy->getValues()); return array( 'entities' => $entities, 'orderBy' => $orderBy->switchMode(), ); } /** * Finds and displays a Shop\Order entity. * * @Route("/{publicId}/show", name="TKShopFrontendOrderShow") * @Template() */ public function showAction($publicId) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository('TecnokeyShopBundle:Shop\Order')->findByPublicId($publicId); if (!$entity) { throw $this->createNotFoundException('Unable to find Shop\Order entity.'); } return array( 'order' => $entity, ); } /** * Finds and displays a Shop\Order entity. * * @Route("/confirmar", name="TKShopFrontendOrderCreateFromShoppingCart") * @Template() */ public function createFromShoppingCartAction() { $confirmed = $this->confirmOrder(); if ($confirmed == true) { return $this->redirect($this->generateUrl('TKShopFrontendOrdersShowInProcess')); } else{ return $this->redirect($this->generateUrl('TKShopFrontendUserShoppingCartEdit')); } } // HELPER FUNCTIONS // /** * Redirects to home page if there is a problem with Oder * * @param type $msg * @param type $redirect * @return type */ protected function orderErrorHandler($msg = NULL, $redirect=NULL){ //TODO: Redirect to index $this->get('session')->setFlash('order_error',"Atencion: El usuario no puede tener pedidos, cree un usuario de tipo cliente"); return $this->redirect($this->generateUrl("TKShopFrontendIndex")); } /** * Get the Order from the logged user * * @return Order */ protected function getOrderFromCurrentUser(){ $user = $this->get('userManager')->getCurrentUser(); $shoppingCart = NULL; if($this->get('userManager')->isDBUser($user)){ return $user->getOrders(); } else{ return NULL; } } /** * * @param ShoppingCart $shoppingCart * @return boolean */ public function confirmOrder() { $sc = $this->getUserShoppingCart(); $items = $sc->getItems(); if (count($items) < 1) { return false; } try { $checkoutManager = $this->get('checkoutManager'); $sc = $checkoutManager->checkout($sc); // generate an order $order = $checkoutManager->shoppingCartToOrder($sc); $user = $this->get('userManager')->getCurrentUser(); $order->setUser($user); $em = $this->getDoctrine()->getEntityManager(); $em->persist($order); $em->flush(); //End generating an order // remove all cart items $this->get('shoppingCartManager')->removeAllItems($sc); $em->flush(); //End removing all cart items return true; } catch (Exception $e) { return false; } } /** * Get the ShoppingCart from the logged user * If the user does NOT have a shoppingCart then one is created and attached to user but not persisted to database * * @return ShoppingCart */ protected function getUserShoppingCart() { $user = $this->get('userManager')->getCurrentUser(); $shoppingCart = NULL; if ($this->get('userManager')->isDBUser($user)) { $shoppingCart = $user->getShoppingCart(); if ($shoppingCart == NULL) { $shoppingCart = new ShoppingCart(); $user->setShoppingCart($shoppingCart); } } return $shoppingCart; } }
mqmtech/Tecnokey
src/Tecnokey/ShopBundle/Controller/Frontend/User/OrderController.php
PHP
mit
6,501
import {Component, ViewChild} from '@angular/core'; import { Platform, MenuController, NavController} from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { HomeComponent } from './pages/home-page/home.component'; import {CityListPage} from './pages/city-list/city-list'; import {ClausePage} from './pages/clause/clause'; @Component({ templateUrl: './app.component.html' }) export class AppComponent { @ViewChild('content') content: NavController; // make HelloIonicPage the root (or first) page rootPage: any = HomeComponent; pages: Array<{title: string, component: any}>; // stroage: Storage; constructor( private platform: Platform, private menu: MenuController, private splashScreen: SplashScreen ) { this.initializeApp(); // set our app's pages this.pages = [ { title: '首页', component: HomeComponent }, { title: '城市', component: CityListPage }, { title: '许可条款', component: ClausePage } ]; } initializeApp() { this.platform.ready().then(() => { this.splashScreen.hide(); }); } ionViewDidLoad(){ } openPage(page) { // close the menu when clicking a link from the menu this.menu.close(); // navigate to the new page if it is not the current page this.content.setRoot(page.component); } }
zhuzhiqiang/tianyingqing
src/app/app.component.ts
TypeScript
mit
1,412
import { Log } from './log'; //import Url = require('./url'); import { Url } from './url'; import { HashString } from './lib'; /** * Делаем HTTP (Ajax) запрос. * * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). * @see {@link https://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings} */ export const Ajax = (opts: JQueryAjaxSettings) => { // обязательно добавить в запрос тип возвращаемых данных if (opts.dataType == 'json') { if (opts.data == null) { opts.data = { datatype: 'json' } } else if (typeof opts.data === "string") { // opts.data - строка let params: HashString = Url.SplitUrlParams(opts.data); params['datatype'] = 'json'; opts.data = Url.JoinUrlParams(params); } else { // opts.data - объект opts.data.datatype = 'json'; } } if (opts.xhrFields == null || opts.xhrFields == undefined) { opts.xhrFields = { withCredentials: true }; } if (opts.error == null || typeof opts.error !== 'function') { opts.error = function (jqXHR, textStatus, errorThrown) { Log('error:', textStatus, errorThrown); }; } else { let original = opts.error; opts.error = function (jqXHR, textStatus, errorThrown) { // никаких call, apply надо сохранить контекст вызова иногда это важно original(jqXHR, textStatus, errorThrown); Log('Ajax.error()', textStatus, errorThrown); }; } return $.ajax(opts); };
96467840/AspNetCore
src/AspNetCore/PublishOutput/wwwroot/lib/unobtrusive-typescript/dist/utils/ajax.ts
TypeScript
mit
1,767
<div class="all_levels_area_of_interest @if($from == "account") account_listing_skills @endif"> @if(count($firstBox_areaOfInterest) > 0) <div class="hierarchy_parent"> <select name="title" id="area_of_interest_firstbox" class="first_level hierarchy" size="5" data-number="1"> @foreach($firstBox_areaOfInterest as $area_of_interest_id=>$area_of_interest) <option value="{{$area_of_interest_id}}" data-type="{{$area_of_interest['type']}}">{{$area_of_interest['name']}}&nbsp;></option> @endforeach </select> @if($from == "site_admin") <div style="margin-left:10px;margin-top:5px;"> <a class="btn black-btn btn-xs add_category" data-pos="first" id="add_category_btn" style="padding:5px 10px 5px; text-decoration:none;"> <i class="fa fa-plus plus"></i> <span class="plus_text" style="left:-5px;">ADD</span> </a> </div> @endif </div> @endif </div> @if($from != "site_admin") <div class="row"> <div class="col-xs-12"> <div class="text-center"><h5>You have selected:<span class="selected_text_area">None</span></h5></div> </div> </div> @endif
javulorg/javul
resources/views/admin/partials/area_of_interest_browse.blade.php
PHP
mit
1,334
# frozen_string_literal: true describe ContactController, type: :controller do include AuthHelper let!(:ada) { create(:published_profile, email: "ada@mail.org", main_topic_en: 'math') } describe 'create action' do it 'when profile active' do get :create, params: { id: ada.id, message: { name: "Maxi"} } expect(response).to be_successful expect(response.response_code).to eq(200) end it 'when profile inactive' do ada.update!(inactive: true) get :create, params: { id: ada.id, message: { name: "Maxi"} } expect(response).not_to be_successful expect(response.response_code).to eq(302) expect(response).to redirect_to("/#{I18n.locale}/profiles") end it 'when unpublished profiles' do ada.update!(published: false) get :create, params: { id: ada.id, message: { name: "Maxi"} } expect(response).not_to be_successful expect(response.response_code).to eq(302) expect(response).to redirect_to("/#{I18n.locale}/profiles") end end end
rubymonsters/speakerinnen_liste
spec/controllers/contact_controller_spec.rb
Ruby
mit
1,042
<?php namespace LCoder\Bundle\BlogBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('l_coder_blog'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
latviancoder/blog
src/LCoder/Bundle/BlogBundle/DependencyInjection/Configuration.php
PHP
mit
885
package tsmt import ( "encoding/xml" "github.com/fgrid/iso20022" ) type Document01800105 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsmt.018.001.05 Document"` Message *FullPushThroughReportV05 `xml:"FullPushThrghRpt"` } func (d *Document01800105) AddMessage() *FullPushThroughReportV05 { d.Message = new(FullPushThroughReportV05) return d.Message } // Scope // The FullPushThroughReport message is sent by the matching application to a party involved in a transaction. // This message is used to pass on information that the matching application has received from the submitter. The forwarded information can originate from an InitialBaselineSubmission or BaselineReSubmission or BaselineAmendmentRequest message. // Usage // The FullPushThroughReport message can be sent by the matching application to a party to convey // - the details of an InitialBaselineSubmission message that it has obtained,or // - the details of a BaselineResubmission message that it has obtained,or // - the details of a BaselineAmendmentRequest message that it has obtained. type FullPushThroughReportV05 struct { // Identifies the report. ReportIdentification *iso20022.MessageIdentification1 `xml:"RptId"` // Unique identification assigned by the matching application to the transaction. // This identification is to be used in any communication between the parties. TransactionIdentification *iso20022.SimpleIdentificationInformation `xml:"TxId"` // Unique identification assigned by the matching application to the baseline when it is established. EstablishedBaselineIdentification *iso20022.DocumentIdentification3 `xml:"EstblishdBaselnId,omitempty"` // Identifies the status of the transaction by means of a code. TransactionStatus *iso20022.TransactionStatus4 `xml:"TxSts"` // Reference to the transaction for the financial institution which submitted the baseline. UserTransactionReference []*iso20022.DocumentIdentification5 `xml:"UsrTxRef,omitempty"` // Specifies the type of report. ReportPurpose *iso20022.ReportType1 `xml:"RptPurp"` // Specifies the commercial details of the underlying transaction. PushedThroughBaseline *iso20022.Baseline5 `xml:"PushdThrghBaseln"` // Person to be contacted in the organisation of the buyer. BuyerContactPerson []*iso20022.ContactIdentification1 `xml:"BuyrCtctPrsn,omitempty"` // Person to be contacted in the organisation of the seller. SellerContactPerson []*iso20022.ContactIdentification1 `xml:"SellrCtctPrsn,omitempty"` // Person to be contacted in the buyer's bank. BuyerBankContactPerson []*iso20022.ContactIdentification1 `xml:"BuyrBkCtctPrsn,omitempty"` // Person to be contacted in the seller's bank. SellerBankContactPerson []*iso20022.ContactIdentification1 `xml:"SellrBkCtctPrsn,omitempty"` // Person to be contacted in another bank than the seller or buyer's bank. OtherBankContactPerson []*iso20022.ContactIdentification3 `xml:"OthrBkCtctPrsn,omitempty"` // Information on the next processing step required. RequestForAction *iso20022.PendingActivity2 `xml:"ReqForActn,omitempty"` } func (f *FullPushThroughReportV05) AddReportIdentification() *iso20022.MessageIdentification1 { f.ReportIdentification = new(iso20022.MessageIdentification1) return f.ReportIdentification } func (f *FullPushThroughReportV05) AddTransactionIdentification() *iso20022.SimpleIdentificationInformation { f.TransactionIdentification = new(iso20022.SimpleIdentificationInformation) return f.TransactionIdentification } func (f *FullPushThroughReportV05) AddEstablishedBaselineIdentification() *iso20022.DocumentIdentification3 { f.EstablishedBaselineIdentification = new(iso20022.DocumentIdentification3) return f.EstablishedBaselineIdentification } func (f *FullPushThroughReportV05) AddTransactionStatus() *iso20022.TransactionStatus4 { f.TransactionStatus = new(iso20022.TransactionStatus4) return f.TransactionStatus } func (f *FullPushThroughReportV05) AddUserTransactionReference() *iso20022.DocumentIdentification5 { newValue := new(iso20022.DocumentIdentification5) f.UserTransactionReference = append(f.UserTransactionReference, newValue) return newValue } func (f *FullPushThroughReportV05) AddReportPurpose() *iso20022.ReportType1 { f.ReportPurpose = new(iso20022.ReportType1) return f.ReportPurpose } func (f *FullPushThroughReportV05) AddPushedThroughBaseline() *iso20022.Baseline5 { f.PushedThroughBaseline = new(iso20022.Baseline5) return f.PushedThroughBaseline } func (f *FullPushThroughReportV05) AddBuyerContactPerson() *iso20022.ContactIdentification1 { newValue := new(iso20022.ContactIdentification1) f.BuyerContactPerson = append(f.BuyerContactPerson, newValue) return newValue } func (f *FullPushThroughReportV05) AddSellerContactPerson() *iso20022.ContactIdentification1 { newValue := new(iso20022.ContactIdentification1) f.SellerContactPerson = append(f.SellerContactPerson, newValue) return newValue } func (f *FullPushThroughReportV05) AddBuyerBankContactPerson() *iso20022.ContactIdentification1 { newValue := new(iso20022.ContactIdentification1) f.BuyerBankContactPerson = append(f.BuyerBankContactPerson, newValue) return newValue } func (f *FullPushThroughReportV05) AddSellerBankContactPerson() *iso20022.ContactIdentification1 { newValue := new(iso20022.ContactIdentification1) f.SellerBankContactPerson = append(f.SellerBankContactPerson, newValue) return newValue } func (f *FullPushThroughReportV05) AddOtherBankContactPerson() *iso20022.ContactIdentification3 { newValue := new(iso20022.ContactIdentification3) f.OtherBankContactPerson = append(f.OtherBankContactPerson, newValue) return newValue } func (f *FullPushThroughReportV05) AddRequestForAction() *iso20022.PendingActivity2 { f.RequestForAction = new(iso20022.PendingActivity2) return f.RequestForAction }
fgrid/iso20022
tsmt/FullPushThroughReportV05.go
GO
mit
5,855
namespace Kondor.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class ExampleChangedEntityChanged : DbMigration { public override void Up() { AddColumn("dbo.Cards", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.CardStates", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.StringResources", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.ExampleViews", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.Examples", "ExampleUniqueId", c => c.Guid(nullable: false)); AddColumn("dbo.Examples", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.Media", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.Notifications", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.Responses", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.Settings", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.Updates", "RowStatus", c => c.Int(nullable: false)); } public override void Down() { DropColumn("dbo.Updates", "RowStatus"); DropColumn("dbo.Settings", "RowStatus"); DropColumn("dbo.Responses", "RowStatus"); DropColumn("dbo.Notifications", "RowStatus"); DropColumn("dbo.Media", "RowStatus"); DropColumn("dbo.Examples", "RowStatus"); DropColumn("dbo.Examples", "ExampleUniqueId"); DropColumn("dbo.ExampleViews", "RowStatus"); DropColumn("dbo.StringResources", "RowStatus"); DropColumn("dbo.CardStates", "RowStatus"); DropColumn("dbo.Cards", "RowStatus"); } } }
odises/kondor
src/Kondor.Data/Migrations/201610060535379_ExampleChangedEntityChanged.cs
C#
mit
1,810
# frozen_string_literal: true class Dummy::Ui::CardListCell < ApplicationCell def show render if model.present? end end
sinfin/folio
test/dummy/app/cells/dummy/ui/card_list_cell.rb
Ruby
mit
129
# frozen_string_literal: true # :nocov: class UniqueJobWithoutUniqueArgsParameter include Sidekiq::Worker sidekiq_options backtrace: true, lock: :until_executed, queue: :customqueue, retry: true, lock_args_method: :unique_args def perform(optional = true) # rubocop:disable Style/OptionalBooleanParameter optional # NO-OP end def self.unique_args; end end
mhenrixon/sidekiq-unique-jobs
spec/support/workers/unique_job_without_unique_args_parameter.rb
Ruby
mit
450
import struct ''' Refer to docs for all the exact formats. There are many so check them out before converting things yourself ''' ''' If there's a specific offset you want to do things from, use pack_into and unack_into from the docs ''' #Integer to string i1= 1234 print "Int to string as 8 byte little endian", repr(struct.pack("<Q",i1)) print "Int to string as 8 byte big endian", repr(struct.pack(">Q",i1)) #String to integer. Make sure size of destination matches the length of the string s1= '1234' print "String to 4 byte integer little endian", struct.unpack("<i", s1) print "String to 4 byte integer big endian", struct.unpack(">i", s1) ''' Whenever you want to convert to and from binary, think of binascii ''' import binascii h1= binascii.b2a_hex(s1) print "String to hex", h1 uh1= binascii.a2b_hex(h1) print "Hex to string, even a binary string", uh1
arvinddoraiswamy/LearnPython
17.py
Python
mit
867
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module MobileCenterApi module Models # # Model object. # # class Event # @return [String] attr_accessor :id # @return [String] attr_accessor :name # @return [Integer] attr_accessor :device_count # @return [Integer] the device count of previous time range of the event attr_accessor :previous_device_count # @return [Integer] attr_accessor :count # @return [Integer] the event count of previous time range of the event attr_accessor :previous_count # @return [Integer] attr_accessor :count_per_device # @return [Integer] attr_accessor :count_per_session # # Mapper for Event class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { required: false, serialized_name: 'Event', type: { name: 'Composite', class_name: 'Event', model_properties: { id: { required: false, serialized_name: 'id', type: { name: 'String' } }, name: { required: false, serialized_name: 'name', type: { name: 'String' } }, device_count: { required: false, serialized_name: 'deviceCount', type: { name: 'Number' } }, previous_device_count: { required: false, serialized_name: 'previous_device_count', type: { name: 'Number' } }, count: { required: false, serialized_name: 'count', type: { name: 'Number' } }, previous_count: { required: false, serialized_name: 'previous_count', type: { name: 'Number' } }, count_per_device: { required: false, serialized_name: 'count_per_device', type: { name: 'Number' } }, count_per_session: { required: false, serialized_name: 'count_per_session', type: { name: 'Number' } } } } } end end end end
ewgenius/fastlane-plugin-mobile_center
lib/generated/mobile_center_api/models/event.rb
Ruby
mit
2,868
require 'helper' class TestLicenseeMatcher < Minitest::Test should "match the license without raising an error" do assert_nil Licensee::Matcher.match(nil) end end
JuanitoFatas/licensee
test/test_licensee_matcher.rb
Ruby
mit
172
import Helper from '@ember/component/helper'; import { inject as service } from '@ember/service'; import { get } from '@ember/object'; export default class MediaHelper extends Helper { @service() media; constructor() { super(...arguments); this.media.on('mediaChanged', () => { this.recompute(); }); } compute([prop]) { return get(this, `media.${prop}`); } }
freshbooks/ember-responsive
addon/helpers/media.js
JavaScript
mit
395
Enum = { BarDrawDirect: { Horizontal: "Horizontal", Vertical: "Vertical" }, PowerType: { MP: 0, Angery: 1 }, EffectType: { StateChange: "StateChange", HpChange: "HpChange", Timing: "Timing", Control: "Control" }, EffectControlType: { Stun: "Stun", Silence: "Silence", Sleep: "Sleep" }, EffectCharacterType: { Passive: "Passive", Self: "Self", Column: "Column", Single: "Single", Row: "Row", All: "All" }, EffectRange: { Melee: "Melee", Range: "Range" }, StateChangeClass: { Plus: "Plus", Minus: "Minus" }, StateChangeType: { HitRate: "HitRate", DodgeRate: "DodgeRate" }, HpChangeClass: { Damage: "Damage", Heal: "Heal" }, HpChangeType: { Normal: "Normal", Critial: "Critial" }, BattleActionType: { Physical: "Physical", Magical: "Magical" }, EffectStyle: { Temp: "Temp", Static: "Static", UniqueTemp: "UniqueTemp" }, Align: { Left: "Left", Right: "Right", Center: "Center" } }
mt830813/code
Project/HTML5Test/Test1/Scripts/Customer/Setting/Enum.js
JavaScript
mit
1,263
package io.prajesh.config; import io.prajesh.domain.HelloWorld; import io.prajesh.service.HelloWorldService; import io.prajesh.service.HelloWorldServiceImpl; import io.prajesh.service.factory.HelloWorldFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; /** * @author Prajesh Ananthan * Created on 16/7/2017. */ @Configuration public class HelloConfig { @Bean public HelloWorldFactory helloWorldFactory() { return new HelloWorldFactory(); } @Bean public HelloWorldService helloWorldService() { return new HelloWorldServiceImpl(); } @Bean @Profile("English") public HelloWorld helloWorldEn(HelloWorldFactory factory) { return factory.getHelloWorldFactory("en"); } @Bean @Profile("Malay") public HelloWorld helloWorldMy(HelloWorldFactory factory) { return factory.getHelloWorldFactory("my"); } }
prajesh-ananthan/spring-playfield
spring-core/src/main/java/io/prajesh/config/HelloConfig.java
Java
mit
980
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2013 The PPCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "db.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include "kernel.h" #include "main.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <cstdlib> #include "GetNextTargetRequired.h" #include "GetProofOfStakeReward.h" #include "GetProofOfWorkReward.h" using namespace std; using namespace boost; // // Global state // CCriticalSection cs_setpwalletRegistered; set<CWallet*> setpwalletRegistered; CCriticalSection cs_main; CTxMemPool mempool; unsigned int nTransactionsUpdated = 0; map<uint256, CBlockIndex*> mapBlockIndex; set<pair<COutPoint, unsigned int> > setStakeSeen; CBlockIndex* pindexGenesisBlock = NULL; int nBestHeight = -1; CBigNum bnBestChainTrust = 0; CBigNum bnBestInvalidTrust = 0; uint256 hashBestChain = 0; CBlockIndex* pindexBest = NULL; int64 nTimeBestReceived = 0; CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have map<uint256, CBlock*> mapOrphanBlocks; multimap<uint256, CBlock*> mapOrphanBlocksByPrev; set<pair<COutPoint, unsigned int> > setStakeSeenOrphan; map<uint256, uint256> mapProofOfStake; map<uint256, CDataStream*> mapOrphanTransactions; map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev; // Constant stuff for coinbase transactions we create: CScript COINBASE_FLAGS; const string strMessageMagic = COIN_NAME " Signed Message:\n"; double dHashesPerSec; int64 nHPSTimerStart; // Settings int64 nTransactionFee = MIN_TX_FEES; ////////////////////////////////////////////////////////////////////////////// // // dispatching functions // // These functions dispatch to one or all registered wallets void RegisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.insert(pwalletIn); } } void UnregisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.erase(pwalletIn); } } // check whether the passed transaction is from us bool static IsFromMe(CTransaction& tx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) return true; return false; } // get the wallet transaction with the given hash (if it exists) bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->GetTransaction(hashTx,wtx)) return true; return false; } // erases transaction with the given hash from all wallets void static EraseFromWallets(uint256 hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->EraseFromWallet(hash); } // make sure all wallets know about the given transaction, in the given block void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect) { if (!fConnect) { // ppcoin: wallets need to refund inputs when disconnecting coinstake if (tx.IsCoinStake()) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) pwallet->DisableTransaction(tx); } return; } BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate); } // notify wallets about a new best chain void static SetBestChain(const CBlockLocator& loc) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->SetBestChain(loc); } // notify wallets about an updated transaction void static UpdatedTransaction(const uint256& hashTx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->UpdatedTransaction(hashTx); } // dump all wallets void static PrintWallets(const CBlock& block) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->PrintWallet(block); } // notify wallets about an incoming inventory (for request counts) void static Inventory(const uint256& hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->Inventory(hash); } // ask wallets to resend their transactions void static ResendWalletTransactions() { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->ResendWalletTransactions(); } ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // bool AddOrphanTx(const CDataStream& vMsg) { CTransaction tx; CDataStream(vMsg) >> tx; uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; CDataStream* pvMsg = new CDataStream(vMsg); // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: if (pvMsg->size() > 5000) { printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str()); delete pvMsg; return false; } mapOrphanTransactions[hash] = pvMsg; BOOST_FOREACH(const CTxIn& txin, tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg)); printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(), mapOrphanTransactions.size()); return true; } void static EraseOrphanTx(uint256 hash) { if (!mapOrphanTransactions.count(hash)) return; const CDataStream* pvMsg = mapOrphanTransactions[hash]; CTransaction tx; CDataStream(*pvMsg) >> tx; BOOST_FOREACH(const CTxIn& txin, tx.vin) { mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash); if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty()) mapOrphanTransactionsByPrev.erase(txin.prevout.hash); } delete pvMsg; mapOrphanTransactions.erase(hash); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) { unsigned int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } ////////////////////////////////////////////////////////////////////////////// // // CTransaction and CTxIndex // bool CTransaction::ReadFromDisk(CTxDB& txdb, const uint256& hash, CTxIndex& txindexRet) { SetNull(); if (!txdb.ReadTxIndex(hash, txindexRet)) return false; if (!ReadFromDisk(txindexRet.pos)) return false; return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet) { if (!ReadFromDisk(txdb, prevout.hash, txindexRet)) return false; if (prevout.n >= vout.size()) { SetNull(); return false; } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout) { CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::ReadFromDisk(COutPoint prevout) { CTxDB txdb("r"); CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::IsStandard() const { BOOST_FOREACH(const CTxIn& txin, vin) { // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG // pay-to-script-hash, which is 3 ~80-byte signatures, 3 // ~65-byte public keys, plus a few script ops. if (txin.scriptSig.size() > 500) return false; if (!txin.scriptSig.IsPushOnly()) return false; } unsigned int nDataOut = 0; txnouttype whichType; BOOST_FOREACH(const CTxOut& txout, vout) { if (!::IsStandard(txout.scriptPubKey, whichType)) { return false; } if (whichType == TX_NULL_DATA) nDataOut++; } // only one OP_RETURN txout is permitted if (nDataOut > 1) { return false; } return true; } // // Check transaction inputs, and make sure any // pay-to-script-hash transactions are evaluating IsStandard scripts // // Why bother? To avoid denial-of-service attacks; an attacker // can submit a standard HASH... OP_EQUAL transaction, // which will get accepted into blocks. The redemption // script can be anything; an attacker could use a very // expensive-to-check-upon-redemption script like: // DUP CHECKSIG DROP ... repeated 100 times... OP_1 // bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const { if (IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prev = GetOutputFor(vin[i], mapInputs); vector<vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig the // IsStandard() call returns false vector<vector<unsigned char> > stack; if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0)) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); vector<vector<unsigned char> > vSolutions2; txnouttype whichType2; if (!Solver(subscript, whichType2, vSolutions2)) return false; if (whichType2 == TX_SCRIPTHASH) return false; int tmpExpected; tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; } unsigned int CTransaction::GetLegacySigOpCount() const { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } int CMerkleTx::SetMerkleBranch(const CBlock* pblock) { if (fClient) { if (hashBlock == 0) return 0; } else { CBlock blockTmp; if (pblock == NULL) { // Load the block this tx is in CTxIndex txindex; if (!CTxDB("r").ReadTxIndex(GetHash(), txindex)) return 0; if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos)) return 0; pblock = &blockTmp; } // Update the tx's hashBlock hashBlock = pblock->GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++) if (pblock->vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)pblock->vtx.size()) { vMerkleBranch.clear(); nIndex = -1; printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = pblock->GetMerkleBranch(nIndex); } // Is the tx in a block that's in the main chain map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return pindexBest->nHeight - pindex->nHeight + 1; } bool CTransaction::IsRestrictedCoinStake() const { if (!IsCoinStake()) return false; int64 nValueIn = 0; CScript onlyAllowedScript; for (unsigned int i = 0; i < vin.size(); ++i) { const COutPoint& prevout = vin[i].prevout; CTxDB txdb("r"); CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, prevout, txindex)) return false; txdb.Close(); const CTxOut& prevtxo = txPrev.vout[prevout.n]; const CScript& prevScript = prevtxo.scriptPubKey; if (i == 0) { onlyAllowedScript = prevScript; if (onlyAllowedScript.empty()) { return false; } } else { if (prevScript != onlyAllowedScript) { return false; } } nValueIn += prevtxo.nValue; } int64 nValueOut = 0; for (unsigned int i = 1; i < vout.size(); ++i) { const CTxOut& txo = vout[i]; if (txo.nValue == 0) continue ; if (txo.scriptPubKey != onlyAllowedScript) return false; nValueOut += txo.nValue; } if (nValueOut < nValueIn) return false; return true; } bool CTransaction::CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); if (vout.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); // Time (prevent mempool memory exhaustion attack) if (nTime > GetAdjustedTime() + MAX_CLOCK_DRIFT) return DoS(10, error("CTransaction::CheckTransaction() : timestamp is too far into the future")); // Size limits if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64 nValueOut = 0; for (size_t i = 0; i < vout.size(); i++) { const CTxOut& txout = vout[i]; if (txout.IsEmpty() && (!IsCoinBase()) && (!IsCoinStake())) return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction")); // ppcoin: enforce minimum output amount if ((!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum (%d)", txout.nValue)); if (txout.nValue > MAX_MONEY_STACK) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high (%d)", txout.nValue)); nValueOut += txout.nValue; if (!IsValidAmount(nValueOut)) return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, vin) { if (vInOutPoints.count(txin.prevout)) return false; vInOutPoints.insert(txin.prevout); } if (IsCoinBase()) { if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size")); } else { BOOST_FOREACH(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); } return true; } bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs) { if (pfMissingInputs) *pfMissingInputs = false; if (!tx.CheckTransaction()) return error("CTxMemPool::accept() : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx")); // ppcoin: coinstake is also only valid in a block, not as a loose transaction if (tx.IsCoinStake()) return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx")); // To help v0.1.5 clients who would see it as a negative number if ((int64)tx.nLockTime > std::numeric_limits<int>::max()) return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet"); // Rather not work on nonstandard transactions if (!tx.IsStandard()) return error("CTxMemPool::accept() : nonstandard transaction type"); // Do we already have it? uint256 hash = tx.GetHash(); { LOCK(cs); if (mapTx.count(hash)) return false; } if (fCheckInputs) if (txdb.ContainsTx(hash)) return false; // Check for conflicts with in-memory transactions CTransaction* ptxOld = NULL; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; // Allow replacing with a newer version of the same transaction if (i != 0) return false; ptxOld = mapNextTx[outpoint].ptx; if (ptxOld->IsFinal()) return false; if (!tx.IsNewerThan(*ptxOld)) return false; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld) return false; } break; } } if (fCheckInputs) { MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { if (fInvalid) return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str()); if (pfMissingInputs) *pfMissingInputs = true; return error("CTxMemPool::accept() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str()); } // Check for non-standard pay-to-script-hash in inputs if (!tx.AreInputsStandard(mapInputs)) return error("CTxMemPool::accept() : nonstandard transaction input"); // Note: if you modify this code to accept non-standard transactions, then // you should add code here to check that the transaction does a // reasonable number of ECDSA signature verifications. int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Don't accept it if it can't get into a block if (nFees < tx.GetMinFee(1000, false, GMF_RELAY)) return error("CTxMemPool::accept() : not enough fees"); // Continuously rate-limit free transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make other's transactions take longer to confirm. if (nFees < MIN_RELAY_TX_FEES) { static CCriticalSection cs; static double dFreeCount; static int64 nLastTime; int64 nNow = GetTime(); { LOCK(cs); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx)) return error("CTxMemPool::accept() : free transaction rejected by rate limiter"); if (fDebug) printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } } // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false)) { return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str()); } } // Store transaction in memory { LOCK(cs); if (ptxOld) { printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); remove(*ptxOld); } addUnchecked(tx); } ///// are we sure this is ok when loading transactions or restoring block txes // If updated, erase old tx from wallet if (ptxOld) EraseFromWallets(ptxOld->GetHash()); printf("CTxMemPool::accept() : accepted %s\n", hash.ToString().substr(0,10).c_str()); return true; } bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs) { return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs); } bool CTxMemPool::addUnchecked(CTransaction &tx) { printf("addUnchecked(): size %lu\n", mapTx.size()); // Add to memory pool without checking anything. Don't call this directly, // call CTxMemPool::accept to properly check the transaction first. { LOCK(cs); uint256 hash = tx.GetHash(); mapTx[hash] = tx; for (unsigned int i = 0; i < tx.vin.size(); i++) mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i); nTransactionsUpdated++; } return true; } bool CTxMemPool::remove(CTransaction &tx) { // Remove transaction from memory pool { LOCK(cs); uint256 hash = tx.GetHash(); if (mapTx.count(hash)) { BOOST_FOREACH(const CTxIn& txin, tx.vin) mapNextTx.erase(txin.prevout); mapTx.erase(hash); nTransactionsUpdated++; } } return true; } void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) { vtxid.clear(); LOCK(cs); vtxid.reserve(mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) vtxid.push_back((*mi).first); } int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; // Find the block it claims to be in map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return pindexBest->nHeight - pindex->nHeight + 1; } int CMerkleTx::GetBlocksToMaturity() const { if (!(IsCoinBase() || IsCoinStake())) return 0; int depth = GetDepthInMainChain(); if (depth == 0) // Not in the blockchain return COINBASE_MATURITY; return max(0, COINBASE_MATURITY - (depth - 1)); } bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs) { if (fClient) { if (!IsInMainChain() && !ClientConnectInputs()) return false; return CTransaction::AcceptToMemoryPool(txdb, false); } else { return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs); } } bool CMerkleTx::AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); } bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs) { { LOCK(mempool.cs); // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!(tx.IsCoinBase() || tx.IsCoinStake())) { uint256 hash = tx.GetHash(); if (!mempool.exists(hash) && !txdb.ContainsTx(hash)) tx.AcceptToMemoryPool(txdb, fCheckInputs); } } return AcceptToMemoryPool(txdb, fCheckInputs); } return false; } bool CWalletTx::AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); } int CTxIndex::GetDepthInMainChain() const { // Read block header CBlock block; if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false)) return 0; // Find the block in the index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash()); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return 1 + nBestHeight - pindex->nHeight; } // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock) { { LOCK(cs_main); { LOCK(mempool.cs); if (mempool.exists(hash)) { tx = mempool.lookup(hash); return true; } } CTxDB txdb("r"); CTxIndex txindex; if (tx.ReadFromDisk(txdb, hash, txindex)) { CBlock block; if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) hashBlock = block.GetHash(); return true; } // look for transaction in disconnected blocks to find orphaned CoinBase and CoinStake transactions BOOST_FOREACH(PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) { CBlockIndex* pindex = item.second; if (pindex == pindexBest || pindex->pnext != 0) continue; CBlock block; if (!block.ReadFromDisk(pindex)) continue; BOOST_FOREACH(const CTransaction& txOrphan, block.vtx) { if (txOrphan.GetHash() == hash) { tx = txOrphan; return true; } } } } return false; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions) { if (!fReadTransactions) { *this = pindex->GetBlockHeader(); return true; } if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions)) return false; if (GetHash() != pindex->GetBlockHash()) return error("CBlock::ReadFromDisk() : GetHash() doesn't match index"); return true; } uint256 static GetOrphanRoot(const CBlock* pblock) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblock->hashPrevBlock)) pblock = mapOrphanBlocks[pblock->hashPrevBlock]; return pblock->GetHash(); } // ppcoin: find block wanted by given orphan block uint256 WantedByOrphan(const CBlock* pblockOrphan) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock)) pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock]; return pblockOrphan->hashPrevBlock; } // // minimum amount of work that could possibly be required nTime after // minimum work required was nBase // unsigned int ComputeMinWork(unsigned int nBase, int64 nTime) { CBigNum bnResult; bnResult.SetCompact(nBase); bnResult *= 2; while (nTime > 0 && bnResult < POW_MAX_TARGET) { // Maximum 200% adjustment per day... bnResult *= 2; nTime -= 24 * 60 * 60; } if (bnResult > POW_MAX_TARGET) bnResult = POW_MAX_TARGET; return bnResult.GetCompact(); } // ppcoin: find last block index up to pindex const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake) { while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake)) pindex = pindex->pprev; return pindex; } bool CheckProofOfWork(uint256 hash, unsigned int nBits, bool triggerErrors) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > POW_MAX_TARGET) return triggerErrors ? error("CheckProofOfWork() : nBits below minimum work") : false; // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return triggerErrors ? error("CheckProofOfWork() : hash doesn't match nBits") : false; return true; } // Return maximum amount of blocks that other nodes claim to have int GetNumBlocksOfPeers() { return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate()); } bool IsInitialBlockDownload() { if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate()) return true; static int64 nLastUpdate; static CBlockIndex* pindexLastBest; if (pindexBest != pindexLastBest) { pindexLastBest = pindexBest; nLastUpdate = GetTime(); } return (GetTime() - nLastUpdate < 10 && pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->bnChainTrust > bnBestInvalidTrust) { bnBestInvalidTrust = pindexNew->bnChainTrust; CTxDB().WriteBestInvalidTrust(bnBestInvalidTrust); MainFrameRepaint(); } printf("InvalidChainFound: invalid block=%s height=%d trust=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, CBigNum(pindexNew->bnChainTrust).ToString().c_str()); printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(bnBestChainTrust).ToString().c_str()); // ppcoin: should not enter safe mode for longer invalid chain } void CBlock::UpdateTime(const CBlockIndex* pindexPrev) { nTime = max(GetBlockTime(), GetAdjustedTime()); } bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers if (!IsCoinBase()) { BOOST_FOREACH(const CTxIn& txin, vin) { COutPoint prevout = txin.prevout; // Get prev txindex from disk CTxIndex txindex; if (!txdb.ReadTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : ReadTxIndex failed"); if (prevout.n >= txindex.vSpent.size()) return error("DisconnectInputs() : prevout.n out of range"); // Mark outpoint as not spent txindex.vSpent[prevout.n].SetNull(); // Write back if (!txdb.UpdateTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : UpdateTxIndex failed"); } } // Remove transaction from index // This can fail if a duplicate of this transaction was in a chain that got // reorganized away. This is only possible if this transaction was completely // spent, so erasing it would be a no-op anway. txdb.EraseTxIndex(*this); return true; } bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid) { // FetchInputs can return false either because we just haven't seen some inputs // (in which case the transaction should be stored as an orphan) // or because the transaction is malformed (in which case the transaction should // be dropped). If tx is definitely invalid, fInvalid will be set to true. fInvalid = false; if (IsCoinBase()) return true; // Coinbase transactions have no inputs to fetch. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; if (inputsRet.count(prevout.hash)) continue; // Got it already // Read txindex CTxIndex& txindex = inputsRet[prevout.hash].first; bool fFound = true; if ((fBlock || fMiner) && mapTestPool.count(prevout.hash)) { // Get txindex from current proposed changes txindex = mapTestPool.find(prevout.hash)->second; } else { // Read txindex from txdb fFound = txdb.ReadTxIndex(prevout.hash, txindex); } if (!fFound && (fBlock || fMiner)) return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); // Read txPrev CTransaction& txPrev = inputsRet[prevout.hash].second; if (!fFound || txindex.pos == CDiskTxPos(1,1,1)) { // Get prev tx from single transactions in memory { LOCK(mempool.cs); if (!mempool.exists(prevout.hash)) return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); txPrev = mempool.lookup(prevout.hash); } if (!fFound) txindex.vSpent.resize(txPrev.vout.size()); } else { // Get prev tx from disk if (!txPrev.ReadFromDisk(txindex.pos)) return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); } } // Make sure all prevout.n's are valid: for (unsigned int i = 0; i < vin.size(); i++) { const COutPoint prevout = vin[i].prevout; assert(inputsRet.count(prevout.hash) != 0); const CTxIndex& txindex = inputsRet[prevout.hash].first; const CTransaction& txPrev = inputsRet[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { // Revisit this if/when transaction replacement is implemented and allows // adding inputs: fInvalid = true; return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); } } return true; } const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const { MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash); if (mi == inputs.end()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found"); const CTransaction& txPrev = (mi->second).second; if (input.prevout.n >= txPrev.vout.size()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range"); return txPrev.vout[input.prevout.n]; } int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int64 nResult = 0; for (unsigned int i = 0; i < vin.size(); i++) { nResult += GetOutputFor(vin[i], inputs).nValue; } return nResult; } unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prevout = GetOutputFor(vin[i], inputs); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig); } return nSigOps; } bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain // fMiner is true when called from the internal bitcoin miner // ... both are false when called from CTransaction::AcceptToMemoryPool if (!IsCoinBase()) { int64 nValueIn = 0; int64 nFees = 0; for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); // If prev is coinbase/coinstake, check that it's matured if (txPrev.IsCoinBase() || txPrev.IsCoinStake()) for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev) if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile) return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight); // ppcoin: check transaction timestamp if (txPrev.nTime > nTime) return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction")); // Check for negative or overflow input values nValueIn += txPrev.vout[prevout.n].nValue; if (!IsValidAmount(txPrev.vout[prevout.n].nValue) || !IsValidAmount(nValueIn)) return DoS(100, error("ConnectInputs() : txin values out of range")); } // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; // Check for conflicts (double-spend) // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!txindex.vSpent[prevout.n].IsNull()) return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str()); // Skip ECDSA signature verification when connecting blocks (fBlock=true) // before the last blockchain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))) { // Verify signature if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0)) { // only during transition phase for P2SH: do not invoke anti-DoS code for // potentially old clients relaying bad P2SH transactions if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0)) return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str()); return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str())); } } // Mark outpoints as spent txindex.vSpent[prevout.n] = posThisTx; // Write back if (fBlock || fMiner) { mapTestPool[prevout.hash] = txindex; } } if (IsCoinStake()) { // ppcoin: coin stake tx earns reward instead of paying fee uint64 nCoinAge; if (!GetCoinAge(txdb, nCoinAge)) return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str()); int64 nStakeReward = GetValueOut() - nValueIn; if (nStakeReward > GetProofOfStakeReward(nCoinAge, pindexBlock->pprev->nHeight) - GetMinFee() + MIN_TX_FEES) return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str())); } else { if (nValueIn < GetValueOut()) return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str())); // Tally transaction fees int64 nTxFee = nValueIn - GetValueOut(); if (nTxFee < 0) return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str())); // ppcoin: enforce transaction fees for every block if (nTxFee < GetMinFee()) return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false; nFees += nTxFee; if (!IsValidAmount(nFees)) return DoS(100, error("ConnectInputs() : nFees out of range")); } } return true; } bool CTransaction::ClientConnectInputs() { if (IsCoinBase()) return false; // Take over previous transactions' spent pointers { LOCK(mempool.cs); int64 nValueIn = 0; for (unsigned int i = 0; i < vin.size(); i++) { // Get prev tx from single transactions in memory COutPoint prevout = vin[i].prevout; if (!mempool.exists(prevout.hash)) return false; CTransaction& txPrev = mempool.lookup(prevout.hash); if (prevout.n >= txPrev.vout.size()) return false; // Verify signature if (!VerifySignature(txPrev, *this, i, true, 0)) return error("ConnectInputs() : VerifySignature failed"); ///// this is redundant with the mempool.mapNextTx stuff, ///// not sure which I want to get rid of ///// this has to go away now that posNext is gone // // Check for conflicts // if (!txPrev.vout[prevout.n].posNext.IsNull()) // return error("ConnectInputs() : prev tx already used"); // // // Flag outpoints as used // txPrev.vout[prevout.n].posNext = posThisTx; nValueIn += txPrev.vout[prevout.n].nValue; if (!IsValidAmount(txPrev.vout[prevout.n].nValue) || !IsValidAmount(nValueIn)) { return error("ClientConnectInputs() : txin values out of range"); } } if (GetValueOut() > nValueIn) { return false; } } return true; } bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Disconnect in reverse order for (int i = vtx.size()-1; i >= 0; i--) if (!vtx[i].DisconnectInputs(txdb)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = 0; if (!txdb.WriteBlockIndex(blockindexPrev)) return error("DisconnectBlock() : WriteBlockIndex failed"); } // ppcoin: clean up wallet after disconnecting coinstake BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, false, false); return true; } bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Check it again in case a previous version let a bad block in if (!CheckBlock()) return false; // Check coinbase reward if (IsProofOfWork() && vtx[0].GetValueOut() > (IsProofOfWork() ? (GetProofOfWorkReward(pindex->pprev ? pindex->pprev->nHeight : -1) - vtx[0].GetMinFee() + MIN_TX_FEES) : 0)) return DoS(50, error("CheckBlock() : coinbase reward exceeded %s > %s", FormatMoney(vtx[0].GetValueOut()).c_str(), FormatMoney(IsProofOfWork() ? GetProofOfWorkReward(pindex->pprev ? pindex->pprev->nHeight : -1) : 0).c_str())); // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction id's entirely. BOOST_FOREACH(CTransaction& tx, vtx) { CTxIndex txindexOld; if (txdb.ReadTxIndex(tx.GetHash(), txindexOld)) { BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent) if (pos.IsNull()) return false; } } // BIP16 didn't become active until Apr 1 2012 int64 nBIP16SwitchTime = 1333238400; bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime); //// issue here: it doesn't know the version unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size()); map<uint256, CTxIndex> mapQueuedChanges; int64 nFees = 0; int64 nValueIn = 0; int64 nValueOut = 0; unsigned int nSigOps = 0; BOOST_FOREACH(CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos); nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); MapPrevTx mapInputs; if (tx.IsCoinBase()) nValueOut += tx.GetValueOut(); else { bool fInvalid; if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid)) return false; if (fStrictPayToScriptHash) { // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); } int64 nTxValueIn = tx.GetValueIn(mapInputs); int64 nTxValueOut = tx.GetValueOut(); nValueIn += nTxValueIn; nValueOut += nTxValueOut; if (!tx.IsCoinStake()) nFees += nTxValueIn - nTxValueOut; if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash)) return false; } mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size()); } // ppcoin: track money supply and mint amount info pindex->nMint = nValueOut - nValueIn + nFees; pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn; if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex))) return error("Connect() : WriteBlockIndex for pindex failed"); // Write queued txindex changes for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi) { if (!txdb.UpdateTxIndex((*mi).first, (*mi).second)) return error("ConnectBlock() : UpdateTxIndex failed"); } // ppcoin: fees are not collected by miners as in bitcoin // ppcoin: fees are destroyed to compensate the entire network if (fDebug && GetBoolArg("-printcreation")) printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees); // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = pindex->GetBlockHash(); if (!txdb.WriteBlockIndex(blockindexPrev)) return error("ConnectBlock() : WriteBlockIndex for blockindexPrev failed"); } // Watch for transactions paying to me BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, true); return true; } bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew) { printf("REORGANIZE\n"); // Find the fork CBlockIndex* pfork = pindexBest; CBlockIndex* plonger = pindexNew; while (pfork != plonger) { while (plonger->nHeight > pfork->nHeight) if (!(plonger = plonger->pprev)) return error("Reorganize() : plonger->pprev is null"); if (pfork == plonger) break; if (!(pfork = pfork->pprev)) return error("Reorganize() : pfork->pprev is null"); } // List of what to disconnect vector<CBlockIndex*> vDisconnect; for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev) vDisconnect.push_back(pindex); // List of what to connect vector<CBlockIndex*> vConnect; for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) vConnect.push_back(pindex); reverse(vConnect.begin(), vConnect.end()); printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str()); printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str()); // Disconnect shorter branch vector<CTransaction> vResurrect; BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for disconnect failed"); if (!block.DisconnectBlock(txdb, pindex)) return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); // Queue memory transactions to resurrect BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!(tx.IsCoinBase() || tx.IsCoinStake())) vResurrect.push_back(tx); } // Connect longer branch vector<CTransaction> vDelete; for (unsigned int i = 0; i < vConnect.size(); i++) { CBlockIndex* pindex = vConnect[i]; CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for connect failed"); if (!block.ConnectBlock(txdb, pindex)) { // Invalid block txdb.TxnAbort(); return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); } // Queue memory transactions to delete BOOST_FOREACH(const CTransaction& tx, block.vtx) vDelete.push_back(tx); } if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash())) return error("Reorganize() : WriteHashBestChain failed"); // Make sure it's successfully written to disk before changing memory structure if (!txdb.TxnCommit()) return error("Reorganize() : TxnCommit failed"); // Disconnect shorter branch BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) if (pindex->pprev) pindex->pprev->pnext = NULL; // Connect longer branch BOOST_FOREACH(CBlockIndex* pindex, vConnect) if (pindex->pprev) pindex->pprev->pnext = pindex; // Resurrect memory transactions that were in the disconnected branch BOOST_FOREACH(CTransaction& tx, vResurrect) tx.AcceptToMemoryPool(txdb, false); // Delete redundant memory transactions that are in the connected branch BOOST_FOREACH(CTransaction& tx, vDelete) mempool.remove(tx); printf("REORGANIZE: done\n"); return true; } // Called from inside SetBestChain: attaches a block to the new best chain being built bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew) { uint256 hash = GetHash(); // Adding to current best branch if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return false; } if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); // Add to current best branch pindexNew->pprev->pnext = pindexNew; // Delete redundant memory transactions BOOST_FOREACH(CTransaction& tx, vtx) mempool.remove(tx); return true; } bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew) { uint256 hash = GetHash(); if (!txdb.TxnBegin()) return error("SetBestChain() : TxnBegin failed"); if (pindexGenesisBlock == NULL && hash == GENESIS_HASH) { txdb.WriteHashBestChain(hash); if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); pindexGenesisBlock = pindexNew; } else if (hashPrevBlock == hashBestChain) { if (!SetBestChainInner(txdb, pindexNew)) return error("SetBestChain() : SetBestChainInner failed"); } else { // the first block in the new chain that will cause it to become the new best chain CBlockIndex *pindexIntermediate = pindexNew; // list of blocks that need to be connected afterwards std::vector<CBlockIndex*> vpindexSecondary; // Reorganize is costly in terms of db load, as it works in a single db transaction. // Try to limit how much needs to be done inside while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust) { vpindexSecondary.push_back(pindexIntermediate); pindexIntermediate = pindexIntermediate->pprev; } if (!vpindexSecondary.empty()) printf("Postponing %i reconnects\n", vpindexSecondary.size()); // Switch to new best branch if (!Reorganize(txdb, pindexIntermediate)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return error("SetBestChain() : Reorganize failed"); } // Connect futher blocks BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary) { CBlock block; if (!block.ReadFromDisk(pindex)) { printf("SetBestChain() : ReadFromDisk failed\n"); break; } if (!txdb.TxnBegin()) { printf("SetBestChain() : TxnBegin 2 failed\n"); break; } // errors now are not fatal, we still did a reorganisation to a new chain in a valid way if (!block.SetBestChainInner(txdb, pindex)) break; } } // Update best block in wallet (so we can detect restored wallets) bool fIsInitialDownload = IsInitialBlockDownload(); if (!fIsInitialDownload) { const CBlockLocator locator(pindexNew); ::SetBestChain(locator); } // New best block hashBestChain = hash; pindexBest = pindexNew; nBestHeight = pindexBest->nHeight; bnBestChainTrust = pindexNew->bnChainTrust; nTimeBestReceived = GetTime(); nTransactionsUpdated++; printf("SetBestChain: new best=%s height=%d trust=%s moneysupply=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(), FormatMoney(pindexBest->nMoneySupply).c_str()); std::string strCmd = GetArg("-blocknotify", ""); if (!fIsInitialDownload && !strCmd.empty()) { boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } return true; } // ppcoin: total coin age spent in transaction, in the unit of coin-days. // Only those coins meeting minimum age requirement counts. As those // transactions not in main chain are not currently indexed so we // might not find out about their coin age. Older transactions are // guaranteed to be in main chain by sync-checkpoint. This rule is // introduced to help nodes establish a consistent view of the coin // age (trust score) of competing branches. bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const { CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds nCoinAge = 0; if (IsCoinBase()) return true; BOOST_FOREACH(const CTxIn& txin, vin) { // First try finding the previous transaction in database CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) continue; // previous transaction not in main chain if (nTime < txPrev.nTime) return false; // Transaction timestamp violation // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return false; // unable to read block of previous transaction if (block.GetBlockTime() + STAKE_MIN_AGE > nTime) continue; // only count coins meeting min age requirement int64 nValueIn = txPrev.vout[txin.prevout.n].nValue; bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT; if (fDebug && GetBoolArg("-printcoinage")) { printf("coin age nValueIn=%-12"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str()); } } CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60); if (fDebug && GetBoolArg("-printcoinage")) printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str()); nCoinAge = bnCoinDay.getuint64(); return true; } // ppcoin: total coin age spent in block, in the unit of coin-days. bool CBlock::GetCoinAge(uint64& nCoinAge) const { nCoinAge = 0; CTxDB txdb("r"); BOOST_FOREACH(const CTransaction& tx, vtx) { uint64 nTxCoinAge; if (tx.GetCoinAge(txdb, nTxCoinAge)) nCoinAge += nTxCoinAge; else return false; } if (nCoinAge == 0) // block coin age minimum 1 coin-day nCoinAge = 1; if (fDebug && GetBoolArg("-printcoinage")) printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge); return true; } bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos) { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str()); // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this); if (!pindexNew) return error("AddToBlockIndex() : new CBlockIndex failed"); pindexNew->phashBlock = &hash; map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; } // ppcoin: compute chain trust score pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust(); // ppcoin: compute stake entropy bit for stake modifier if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit())) return error("AddToBlockIndex() : SetStakeEntropyBit() failed"); // ppcoin: record proof-of-stake hash value if (pindexNew->IsProofOfStake()) { if (!mapProofOfStake.count(hash)) return error("AddToBlockIndex() : hashProofOfStake not found in map"); pindexNew->hashProofOfStake = mapProofOfStake[hash]; } // ppcoin: compute stake modifier uint64 nStakeModifier = 0; bool fGeneratedStakeModifier = false; if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier)) return error("AddToBlockIndex() : ComputeNextStakeModifier() failed"); pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier); pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew); if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum)) return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x", checksum=0x%08x", pindexNew->nHeight, nStakeModifier, pindexNew->nStakeModifierChecksum); // Add to mapBlockIndex map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; if (pindexNew->IsProofOfStake()) setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime)); pindexNew->phashBlock = &((*mi).first); // Write to disk block index CTxDB txdb; if (!txdb.TxnBegin()) return false; txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew)); if (!txdb.TxnCommit()) return false; // New best if (pindexNew->bnChainTrust > bnBestChainTrust) if (!SetBestChain(txdb, pindexNew)) return false; txdb.Close(); if (pindexNew == pindexBest) { // Notify UI to display prev block's coinbase if it was ours static uint256 hashPrevBestCoinBase; UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = vtx[0].GetHash(); } MainFrameRepaint(); return true; } bool CBlock::CheckBlock() const { // These are checks that are independent of context // that can be verified before saving an orphan block. // Size limits if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CheckBlock() : size limits failed")); // Check proof of work matches claimed amount if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits)) return DoS(50, error("CheckBlock() : proof of work failed")); // Check timestamp if (GetBlockTime() > GetAdjustedTime() + MAX_CLOCK_DRIFT) return error("CheckBlock() : block timestamp too far in the future"); // First transaction must be coinbase, the rest must not be if (vtx.empty() || !vtx[0].IsCoinBase()) return DoS(100, error("CheckBlock() : first tx is not coinbase")); for (unsigned int i = 1; i < vtx.size(); i++) if (vtx[i].IsCoinBase()) return DoS(100, error("CheckBlock() : more than one coinbase")); // ppcoin: only the second transaction can be the optional coinstake for (size_t i = 2; i < vtx.size(); i++) if (vtx[i].IsCoinStake()) return DoS(100, error("CheckBlock() : coinstake in wrong position")); // ppcoin: coinbase output should be empty if proof-of-stake block if (IsProofOfStake() && (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())) return error("CheckBlock() : coinbase output not empty for proof-of-stake block"); // Check coinbase timestamp if (GetBlockTime() > (int64)vtx[0].nTime + MAX_CLOCK_DRIFT) return DoS(50, error("CheckBlock() : coinbase timestamp is too early (block: %d, vtx[0]: %d)", GetBlockTime(), vtx[0].nTime)); // Check coinstake timestamp if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime)) return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%u nTimeTx=%u", GetBlockTime(), vtx[1].nTime)); // Check coinbase reward // // Note: We're not doing the reward check here, because we need to know the block height. // Check inside ConnectBlock instead. // Check transactions BOOST_FOREACH(const CTransaction& tx, vtx) { if (!tx.CheckTransaction()) return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed")); // ppcoin: check transaction timestamp if (GetBlockTime() < (int64)tx.nTime) return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp")); } // Check for duplicate txids. This is caught by ConnectInputs(), // but catching it earlier avoids a potential DoS attack: set<uint256> uniqueTx; BOOST_FOREACH(const CTransaction& tx, vtx) { uniqueTx.insert(tx.GetHash()); } if (uniqueTx.size() != vtx.size()) return DoS(100, error("CheckBlock() : duplicate transaction")); unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); } if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); // Check merkleroot if (hashMerkleRoot != BuildMerkleTree()) return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); // ppcoin: check block signature if (!CheckBlockSignature()) return DoS(100, error("CheckBlock() : bad block signature")); return true; } bool CBlock::AcceptBlock() { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AcceptBlock() : block already in mapBlockIndex"); // Get prev block index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); if (mi == mapBlockIndex.end()) return DoS(10, error("AcceptBlock() : prev block not found")); CBlockIndex* pindexPrev = (*mi).second; int nHeight = pindexPrev->nHeight+1; // Check proof-of-work or proof-of-stake if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake())) return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake")); // Check timestamp against prev if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + MAX_CLOCK_DRIFT < pindexPrev->GetBlockTime()) return error("AcceptBlock() : block's timestamp is too early"); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.IsFinal(nHeight, GetBlockTime())) return DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a hardened checkpoint if (!Checkpoints::CheckHardened(nHeight, hash)) return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight)); // ppcoin: check that the block satisfies synchronized checkpoint if (!Checkpoints::CheckSync(hash, pindexPrev)) return error("AcceptBlock() : rejected by synchronized checkpoint"); // Write block to history file if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION))) return error("AcceptBlock() : out of disk space"); unsigned int nFile = -1; unsigned int nBlockPos = 0; if (!WriteToDisk(nFile, nBlockPos)) return error("AcceptBlock() : WriteToDisk failed"); if (!AddToBlockIndex(nFile, nBlockPos)) return error("AcceptBlock() : AddToBlockIndex failed"); // Relay inventory, but don't relay old inventory during initial block download int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); if (hashBestChain == hash) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); } // ppcoin: check pending sync-checkpoint Checkpoints::AcceptPendingSyncCheckpoint(); return true; } bool ProcessBlock(CNode* pfrom, CBlock* pblock) { // Check for duplicate uint256 hash = pblock->GetHash(); if (mapBlockIndex.count(hash)) return error("ProcessBlock() : already have block %d %s", mapBlockIndex.at(hash)->nHeight, hash.ToString().substr(0,20).c_str()); if (mapOrphanBlocks.count(hash)) return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str()); // ppcoin: check proof-of-stake if (pblock->IsProofOfStake()) { std::pair<COutPoint, unsigned int> proofOfStake = pblock->GetProofOfStake(); if (pindexBest->IsProofOfStake() && proofOfStake.first == pindexBest->prevoutStake) { if (!pblock->CheckBlockSignature()) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : invalid signature in a duplicate Proof-of-Stake kernel"); } RelayBlock(*pblock, hash); BlacklistProofOfStake(proofOfStake, hash); CTxDB txdb; CBlock bestPrevBlock; bestPrevBlock.ReadFromDisk(pindexBest->pprev); if (!bestPrevBlock.SetBestChain(txdb, pindexBest->pprev)) return error("ProcessBlock() : Proof-of-stake rollback failed"); return error("ProcessBlock() : duplicate Proof-of-Stake kernel (%s, %d) in block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str()); } else if (setStakeSeen.count(proofOfStake) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash)) { return error("ProcessBlock() : duplicate Proof-of-Stake kernel (%s, %d) in block %s", proofOfStake.first.ToString().c_str(), proofOfStake.second, hash.ToString().c_str()); } } // Preliminary checks if (!pblock->CheckBlock()) return error("ProcessBlock() : CheckBlock FAILED"); CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint(); if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash)) { // Extra checks to prevent "fill up memory by spamming with bogus blocks" int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; CBigNum bnNewBlock; bnNewBlock.SetCompact(pblock->nBits); CBigNum bnRequired; bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime)); if (bnNewBlock > bnRequired) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work"); } } // ppcoin: ask for pending sync-checkpoint if any if (!IsInitialBlockDownload()) Checkpoints::AskForPendingSyncCheckpoint(pfrom); // We remove the previous block from the blacklisted kernels, if needed CleanProofOfStakeBlacklist(pblock->hashPrevBlock); // Find the previous block std::map<uint256, CBlockIndex*>::iterator parentBlockIt = mapBlockIndex.find(pblock->hashPrevBlock); // If we don't already have it, shunt off the block to the holding area until we get its parent if (parentBlockIt == mapBlockIndex.end()) { printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str()); CBlock* pblock2 = new CBlock(*pblock); // ppcoin: check proof-of-stake if (pblock2->IsProofOfStake()) setStakeSeenOrphan.insert(pblock2->GetProofOfStake()); mapOrphanBlocks.insert(make_pair(hash, pblock2)); mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2)); // Ask this guy to fill in what we're missing if (pfrom) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2)); // ppcoin: getblocks may not obtain the ancestor block rejected // earlier by duplicate-stake check so we ask for it again directly if (!IsInitialBlockDownload()) { pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2))); } } return true; } // ppcoin: verify hash target and signature of coinstake tx if (pblock->IsProofOfStake()) { uint256 hashProofOfStake = 0; const CBlockIndex * pindexPrev = parentBlockIt->second; if (!CheckProofOfStake(pindexPrev, pblock->vtx[1], pblock->nBits, hashProofOfStake)) { printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str()); return false; // do not error here as we expect this during initial block download } if (!mapProofOfStake.count(hash)) // add to mapProofOfStake { mapProofOfStake.insert(make_pair(hash, hashProofOfStake)); } } // Store to disk if (!pblock->AcceptBlock()) return error("ProcessBlock() : AcceptBlock FAILED"); // Recursively process any orphan blocks that depended on this one vector<uint256> vWorkQueue; vWorkQueue.push_back(hash); for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; CBlockIndex* pindexPrev = mapBlockIndex.at(hashPrev); for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); ++mi) { bool validated = true; CBlock* pblockOrphan = (*mi).second; uint256 orphanHash = pblockOrphan->GetHash(); if (pblockOrphan->IsProofOfStake()) { uint256 hashProofOfStake = 0; if (CheckProofOfStake(pindexPrev, pblockOrphan->vtx[1], pblockOrphan->nBits, hashProofOfStake)) { if (!mapProofOfStake.count(orphanHash)) mapProofOfStake.insert(make_pair(orphanHash, hashProofOfStake)); validated = true; } else { validated = false; } } if (validated && pblockOrphan->AcceptBlock()) vWorkQueue.push_back(orphanHash); mapOrphanBlocks.erase(orphanHash); setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake()); delete pblockOrphan; } mapOrphanBlocksByPrev.erase(hashPrev); } printf("ProcessBlock: ACCEPTED\n"); // ppcoin: if responsible for sync-checkpoint send it if (pfrom && !CHECKPOINT_PRIVATE_KEY.empty()) Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint()); return true; } // ppcoin: sign block bool CBlock::SignBlock(const CKeyStore& keystore) { vector<valtype> vSolutions; txnouttype whichType; const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { // Sign const valtype& vchPubKey = vSolutions[0]; CKey key; if (!keystore.GetKey(Hash160(vchPubKey), key)) return false; if (key.GetPubKey() != vchPubKey) return false; return key.Sign(GetHash(), vchBlockSig); } else if (whichType == TX_SCRIPTHASH) { CScript subscript; if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript)) return false; if (!Solver(subscript, whichType, vSolutions)) return false; if (whichType != TX_COLDMINTING) return false; CKey key; if (!keystore.GetKey(uint160(vSolutions[0]), key)) return false; return key.Sign(GetHash(), vchBlockSig); } return false; } // ppcoin: check block signature bool CBlock::CheckBlockSignature() const { if (GetHash() == GENESIS_HASH) return vchBlockSig.empty(); vector<valtype> vSolutions; txnouttype whichType; const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { const valtype& vchPubKey = vSolutions[0]; CKey key; if (!key.SetPubKey(vchPubKey)) return false; if (vchBlockSig.empty()) return false; return key.Verify(GetHash(), vchBlockSig); } else if (whichType == TX_SCRIPTHASH) { // Output is a pay-to-script-hash // Only allowed with cold minting if (!IsProofOfStake()) return false; // CoinStake scriptSig should contain 3 pushes: the signature, the pubkey and the cold minting script CScript scriptSig = vtx[1].vin[0].scriptSig; if (!scriptSig.IsPushOnly()) return false; vector<vector<unsigned char> > stack; if (!EvalScript(stack, scriptSig, CTransaction(), 0, 0)) return false; if (stack.size() != 3) return false; // Verify the script is a cold minting script const valtype& scriptSerialized = stack.back(); CScript script(scriptSerialized.begin(), scriptSerialized.end()); if (!Solver(script, whichType, vSolutions)) return false; if (whichType != TX_COLDMINTING) return false; // Verify the scriptSig pubkey matches the minting key valtype& vchPubKey = stack[1]; if (Hash160(vchPubKey) != uint160(vSolutions[0])) return false; // Verify the block signature with the minting key CKey key; if (!key.SetPubKey(vchPubKey)) return false; if (vchBlockSig.empty()) return false; return key.Verify(GetHash(), vchBlockSig); } return false; } // ppcoin: entropy bit for stake modifier if chosen by modifier unsigned int CBlock::GetStakeEntropyBit() const { unsigned int nEntropyBit = 0; nEntropyBit = ((GetHash().Get64()) & 1llu); // last bit of block hash if (fDebug && GetBoolArg("-printstakemodifier")) printf("GetStakeEntropyBit(v0.4+): nTime=%u hashBlock=%s entropybit=%d\n", nTime, GetHash().ToString().c_str(), nEntropyBit); return nEntropyBit; } bool CheckDiskSpace(uint64 nAdditionalBytes) { uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available; // Check for 15MB because database could create another 10MB log file at any time if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes) { fShutdown = true; string strMessage = _("Warning: Disk space is low"); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); ThreadSafeMessageBox(strMessage, COIN_NAME, wxOK | wxICON_EXCLAMATION | wxMODAL); StartShutdown(); return false; } return true; } FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode) { if (nFile == static_cast<unsigned int>(-1)) return NULL; FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode); if (!file) return NULL; if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w')) { if (fseek(file, nBlockPos, SEEK_SET) != 0) { fclose(file); return NULL; } } return file; } static unsigned int nCurrentBlockFile = 1; FILE* AppendBlockFile(unsigned int& nFileRet) { nFileRet = 0; INFINITE_LOOP { FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab"); if (!file) return NULL; if (fseek(file, 0, SEEK_END) != 0) return NULL; // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB if (ftell(file) < 0x7F000000 - MAX_SIZE) { nFileRet = nCurrentBlockFile; return file; } fclose(file); nCurrentBlockFile++; } } bool LoadBlockIndex(bool fAllowNew) { // // Load block index // CTxDB txdb("cr"); if (!txdb.LoadBlockIndex()) return false; txdb.Close(); // // Init with genesis block // if (mapBlockIndex.empty()) { if (!fAllowNew) return false; // Genesis Block: // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) // vMerkleTree: 4a5e1e const char* pszTimestamp = GENESIS_IDENT; CTransaction txNew; txNew.nTime = GENESIS_TX_TIME; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].SetEmpty(); CBlock block; block.vtx.push_back(txNew); block.hashPrevBlock = 0; block.hashMerkleRoot = block.BuildMerkleTree(); block.nVersion = GENESIS_BLOCK_VERSION; block.nTime = GENESIS_BLOCK_TIME; block.nBits = POW_INITIAL_TARGET.GetCompact(); block.nNonce = GENESIS_BLOCK_NONCE; printf("target : %s\n", POW_INITIAL_TARGET.getuint256().ToString().c_str()); printf("nBits : %08X\n", block.nBits); printf("expected genesis hash : %s\n", GENESIS_HASH.ToString().c_str()); printf("true genesis hash : %s\n", block.GetHash().ToString().c_str()); // If genesis block hash does not match, then generate new genesis hash. if (block.GetHash() != GENESIS_HASH || !CheckProofOfWork(block.GetHash(), block.nBits, false)) { printf("\n"); printf("FATAL ERROR: The genesis block is invalid.\n"); printf("Please notify the coins maintainers at " COIN_BUGTRACKER ".\n"); printf("If you're working on an Altcoin, we suggest you to use the following parameters as new genesis (wait a bit):\n"); // This will figure out a valid hash and Nonce if you're // creating a different genesis block: while (!CheckProofOfWork(block.GetHash(), block.nBits, false)) { if ((block.nNonce & 0xFFF) == 0) printf("Trying nonce %08X and above...\n", block.nNonce); ++block.nNonce; if (block.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++block.nTime; } } printf("A matching block has been found, with the following parameters:\n"); printf(" - GENESIS_MERKLE_HASH : %s\n", block.hashMerkleRoot.ToString().c_str()); printf(" - GENESIS_HASH : %s\n", block.GetHash().ToString().c_str()); printf(" - GENESIS_TIME : %u\n", block.nTime); printf(" - GENESIS_NONCE : %u\n", block.nNonce); std::exit( 1 ); } //// debug print assert(block.hashMerkleRoot == GENESIS_MERKLE_HASH); assert(block.GetHash() == GENESIS_HASH); assert(block.CheckBlock()); // Start new block file unsigned int nFile; unsigned int nBlockPos; if (!block.WriteToDisk(nFile, nBlockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); if (!block.AddToBlockIndex(nFile, nBlockPos)) return error("LoadBlockIndex() : genesis block not accepted"); // ppcoin: initialize synchronized checkpoint if (!Checkpoints::WriteSyncCheckpoint(GENESIS_HASH)) { return error("LoadBlockIndex() : failed to init sync checkpoint"); } } // ppcoin: if checkpoint master key changed must reset sync-checkpoint { CTxDB txdb; string strPubKey = ""; if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CHECKPOINT_PUBLIC_KEY) { // write checkpoint master key to db txdb.TxnBegin(); if (!txdb.WriteCheckpointPubKey(CHECKPOINT_PUBLIC_KEY)) return error("LoadBlockIndex() : failed to write new checkpoint master key to db"); if (!txdb.TxnCommit()) return error("LoadBlockIndex() : failed to commit new checkpoint master key to db"); if (!Checkpoints::ResetSyncCheckpoint()) return error("LoadBlockIndex() : failed to reset sync-checkpoint"); } txdb.Close(); } return true; } void PrintBlockTree() { // precompute tree structure map<CBlockIndex*, vector<CBlockIndex*> > mapNext; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { CBlockIndex* pindex = (*mi).second; mapNext[pindex->pprev].push_back(pindex); // test //while (rand() % 3 == 0) // mapNext[pindex->pprev].push_back(pindex); } vector<pair<int, CBlockIndex*> > vStack; vStack.push_back(make_pair(0, pindexGenesisBlock)); int nPrevCol = 0; while (!vStack.empty()) { int nCol = vStack.back().first; CBlockIndex* pindex = vStack.back().second; vStack.pop_back(); // print split or gap if (nCol > nPrevCol) { for (int i = 0; i < nCol-1; i++) printf("| "); printf("|\\\n"); } else if (nCol < nPrevCol) { for (int i = 0; i < nCol; i++) printf("| "); printf("|\n"); } nPrevCol = nCol; // print columns for (int i = 0; i < nCol; i++) printf("| "); // print item CBlock block; block.ReadFromDisk(pindex); printf("%d (%u,%u) %s %08lx %s mint %7s tx %d", pindex->nHeight, pindex->nFile, pindex->nBlockPos, block.GetHash().ToString().c_str(), block.nBits, DateTimeStrFormat(block.GetBlockTime()).c_str(), FormatMoney(pindex->nMint).c_str(), block.vtx.size()); PrintWallets(block); // put the main timechain first vector<CBlockIndex*>& vNext = mapNext[pindex]; for (unsigned int i = 0; i < vNext.size(); i++) { if (vNext[i]->pnext) { swap(vNext[0], vNext[i]); break; } } // iterate children for (unsigned int i = 0; i < vNext.size(); i++) vStack.push_back(make_pair(nCol+i, vNext[i])); } } ////////////////////////////////////////////////////////////////////////////// // // CAlert // map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static string strMintMessage = _("Warning: Minting suspended due to locked wallet."); static string strMintWarning; string GetWarnings(string strFor) { int nPriority = 0; string strStatusBar; string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // ppcoin: wallet lock warning for minting if (strMintWarning != "") { nPriority = 0; strStatusBar = strMintWarning; } // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // ppcoin: if detected invalid checkpoint enter safe mode if (Checkpoints::hashInvalidCheckpoint != 0) { nPriority = 3000; strStatusBar = strRPC = "Warning: An invalid checkpoint has been found! Displayed transactions may not be correct! You may need to upgrade, and/or notify developers of the issue."; } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; if (nPriority > 1000) { strRPC = strStatusBar; // ppcoin: safe mode for high alert } } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } bool CAlert::ProcessAlert() { if (!CheckSignature()) return false; if (!IsInEffect()) return false; { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); MainFrameRepaint(); return true; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(CTxDB& txdb, const CInv& inv) { switch (inv.type) { case MSG_TX: { bool txInMap = false; { LOCK(mempool.cs); txInMap = (mempool.exists(inv.hash)); } return txInMap || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash); } case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); } // Don't know what it is, just say we already got one return true; } bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) { static map<CService, CPubKey> mapReuseKey; RandAddSeedPerfmon(); if (fDebug) { printf("%s ", DateTimeStrFormat(GetTime()).c_str()); printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size()); } if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { printf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->Misbehaving(1); return false; } int64 nTime; CAddress addrMe; CAddress addrFrom; uint64 nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < MIN_PROTO_VERSION) { // Since February 20, 2012, the protocol is initiated at version 209, // and earlier versions are no longer supported printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) vRecv >> pfrom->strSubVer; if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; return true; } // ppcoin: record my external IP reported by peer if (addrFrom.IsRoutable() && addrMe.IsRoutable()) addrSeenByPeer = addrMe; // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); AddTimeData(pfrom->addr, nTime); // Change version pfrom->PushMessage("verack"); pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() && !IsInitialBlockDownload()) { CAddress addr(addrLocalHost); addr.nTime = GetAdjustedTime(); pfrom->PushAddress(addr); } // Get recent addresses if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Ask the first connected node for block updates static int nAskedForBlocks = 0; if (!pfrom->fClient && (pfrom->nVersion < NOBLKS_VERSION_START || pfrom->nVersion >= NOBLKS_VERSION_END)) { nAskedForBlocks++; pfrom->PushGetBlocks(pindexBest, uint256(0)); } // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); } // ppcoin: relay sync-checkpoint { LOCK(Checkpoints::cs_hashSyncCheckpoint); if (!Checkpoints::checkpointMessage.IsNull()) Checkpoints::checkpointMessage.RelayTo(pfrom); } pfrom->fSuccessfullyConnected = true; printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight); cPeerBlockCounts.input(pfrom->nStartingHeight); // ppcoin: ask for pending sync-checkpoint if any if (!IsInitialBlockDownload()) Checkpoints::AskForPendingSyncCheckpoint(pfrom); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else pfrom->Misbehaving(1); return false; } else if (strCommand == "verack") { pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); } else if (strCommand == "addr") { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { pfrom->Misbehaving(20); return error("message addr size() = %d", vAddr.size()); } // Store the new addresses int64 nNow = GetAdjustedTime(); int64 nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { if (fShutdown) return true; // ignore IPv6 for now, since it isn't implemented anyway if (!addr.IsIPv4()) continue; if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); int64 hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = 2; for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } } addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; } else if (strCommand == "inv") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message inv size() = %d", vInv.size()); } // find last block in inv vector unsigned int nLastBlock = (unsigned int)(-1); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) { nLastBlock = vInv.size() - 1 - nInv; break; } } CTxDB txdb("r"); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; if (fShutdown) return true; pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(txdb, inv); if (fDebug) printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); if (!fAlreadyHave) { pfrom->AskFor(inv); } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); } else if (nInv == nLastBlock) { // In case we are on a very long side-chain, it is possible that we already have // the last block in an inv bundle sent in response to getblocks. Try to detect // this situation and push another getblocks to continue. std::vector<CInv> vGetData(1,inv); pfrom->PushGetBlocks(mapBlockIndex.at(inv.hash), uint256(0)); if (fDebug) { printf("force request: %s\n", inv.ToString().c_str()); } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getdata") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message getdata size() = %d", vInv.size()); } BOOST_FOREACH(const CInv& inv, vInv) { if (fShutdown) return true; printf("received getdata for: %s\n", inv.ToString().c_str()); if (inv.type == MSG_BLOCK) { // Send block from disk map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { CBlock block; block.ReadFromDisk((*mi).second); pfrom->PushMessage("block", block); // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. // ppcoin: send latest proof-of-work block to allow the // download node to accept as orphan (proof-of-stake // block might be rejected by stake connection check) vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash())); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory { LOCK(cs_mapRelay); map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) pfrom->PushMessage(inv.GetCommand(), (*mi).second); } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; // Find the last block the caller has in the main chain CBlockIndex* pindex = locator.GetBlockIndex(); // Send the rest of the chain if (pindex) pindex = pindex->pnext; int nLimit = 500 + locator.GetDistanceBack(); unsigned int nBytes = 0; printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit); for (; pindex; pindex = pindex->pnext) { if (pindex->GetBlockHash() == hashStop) { printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes); // ppcoin: tell downloading node about the latest block if it's // without risk being rejected due to stake connection check if (hashStop != hashBestChain && pindex->GetBlockTime() + STAKE_MIN_AGE > pindexBest->GetBlockTime()) pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain)); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); CBlock block; block.ReadFromDisk(pindex, true); nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION); if (--nLimit <= 0 || nBytes >= SendBufferSize()/2) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = locator.GetBlockIndex(); if (pindex) pindex = pindex->pnext; } vector<CBlock> vHeaders; int nLimit = 2000; printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str()); for (; pindex; pindex = pindex->pnext) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx") { vector<uint256> vWorkQueue; vector<uint256> vEraseQueue; CDataStream vMsg(vRecv); CTxDB txdb("r"); CTransaction tx; vRecv >> tx; CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); bool fMissingInputs = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs)) { SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); // Recursively process any orphan transactions that depended on this one for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin(); mi != mapOrphanTransactionsByPrev[hashPrev].end(); ++mi) { const CDataStream& vMsg = *((*mi).second); CTransaction tx; CDataStream(vMsg) >> tx; CInv inv(MSG_TX, tx.GetHash()); bool fMissingInputs2 = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2)) { printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); } else if (!fMissingInputs2) { // invalid orphan vEraseQueue.push_back(inv.hash); printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); } } } BOOST_FOREACH(uint256 hash, vEraseQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { AddOrphanTx(vMsg); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nEvicted = LimitOrphanTxSize(MAX_BLOCK_ORPHAN_TX); if (nEvicted > 0) printf("mapOrphan overflow, removed %u tx\n", nEvicted); } if (tx.nDoS) pfrom->Misbehaving(tx.nDoS); } else if (strCommand == "block") { CBlock block; vRecv >> block; printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str()); // block.print(); CInv inv(MSG_BLOCK, block.GetHash()); pfrom->AddInventoryKnown(inv); if (ProcessBlock(pfrom, &block)) mapAlreadyAskedFor.erase(inv); if (block.nDoS) pfrom->Misbehaving(block.nDoS); } else if (strCommand == "getaddr") { pfrom->vAddrToSend.clear(); vector<CAddress> vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) pfrom->PushAddress(addr); } else if (strCommand == "checkorder") { uint256 hashReply; vRecv >> hashReply; if (!GetBoolArg("-allowreceivebyip")) { pfrom->PushMessage("reply", hashReply, (int)2, string("")); return true; } CWalletTx order; vRecv >> order; /// we have a chance to check the order here // Keep giving the same key to the same ip until they use it if (!mapReuseKey.count(pfrom->addr)) pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true); // Send back approval of order and pubkey to use CScript scriptPubKey; scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG; pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey); } else if (strCommand == "reply") { uint256 hashReply; vRecv >> hashReply; CRequestTracker tracker; { LOCK(pfrom->cs_mapRequests); map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply); if (mi != pfrom->mapRequests.end()) { tracker = (*mi).second; pfrom->mapRequests.erase(mi); } } if (!tracker.IsNull()) tracker.fn(tracker.param1, vRecv); } else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) { uint64 nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); } } else if (strCommand == "alert") { CAlert alert; vRecv >> alert; if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alert.GetHash()); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } } else if (strCommand == "checkpoint") { CSyncCheckpoint checkpoint; vRecv >> checkpoint; if (checkpoint.ProcessSyncCheckpoint(pfrom)) { // Relay pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint; LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) checkpoint.RelayTo(pnode); } } else { // Ignore unknown commands for extensibility } // Update the last seen time for this node's address if (pfrom->fNetworkNode) if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") AddressCurrentlyConnected(pfrom->addr); return true; } bool ProcessMessages(CNode* pfrom) { CDataStream& vRecv = pfrom->vRecv; if (vRecv.empty()) return true; //if (fDebug) // printf("ProcessMessages(%u bytes)\n", vRecv.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // unsigned char pchMessageStart[4]; GetMessageStart(pchMessageStart); static int64 nTimeLastPrintMessageStart = 0; if (fDebug && GetBoolArg("-printmessagestart") && nTimeLastPrintMessageStart + 30 < GetAdjustedTime()) { string strMessageStart((const char *)pchMessageStart, sizeof(pchMessageStart)); vector<unsigned char> vchMessageStart(strMessageStart.begin(), strMessageStart.end()); printf("ProcessMessages : AdjustedTime=%"PRI64d" MessageStart=%s\n", GetAdjustedTime(), HexStr(vchMessageStart).c_str()); nTimeLastPrintMessageStart = GetAdjustedTime(); } INFINITE_LOOP { // Safe guards to prevent the node to ignore a requested shutdown // in case of long processing if (fRequestShutdown) { StartShutdown(); return true; } // Scan for message start CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart)); int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader()); if (vRecv.end() - pstart < nHeaderSize) { if ((int)vRecv.size() > nHeaderSize) { printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n"); vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize); } break; } if (pstart - vRecv.begin() > 0) printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin()); vRecv.erase(vRecv.begin(), pstart); // Read header vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize); CMessageHeader hdr; vRecv >> hdr; if (!hdr.IsValid()) { printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; if (nMessageSize > MAX_SIZE) { printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize); continue; } if (nMessageSize > vRecv.size()) { // Rewind and wait for rest of message vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end()); break; } // Checksum uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Copy message to its own buffer CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion); vRecv.ignore(nMessageSize); // Process message bool fRet = false; try { { LOCK(cs_main); fRet = ProcessMessage(pfrom, strCommand, vMsg); } if (fShutdown) return true; } catch (std::ios_base::failure& e) { if (strstr(e.what(), "end of data")) { // Allow exceptions from underlength message on vRecv printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from overlong size printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessages()"); } } catch (std::exception& e) { PrintExceptionContinue(&e, "ProcessMessages()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } if (!fRet) printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); } vRecv.Compact(); return true; } bool SendMessages(CNode* pto, bool fSendTrickle) { TRY_LOCK(cs_main, lockMain); if (lockMain) { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // Keep-alive ping. We send a nonce of zero because we don't use it anywhere // right now. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) { uint64 nonce = 0; if (pto->nVersion > BIP0031_VERSION) pto->PushMessage("ping", nonce); else pto->PushMessage("ping"); } // Resend wallet transactions that haven't gotten in a block yet ResendWalletTransactions(); // Address refresh broadcast static int64 nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable()) { CAddress addr(addrLocalHost); addr.nTime = GetAdjustedTime(); pnode->PushAddress(addr); } } } nLastRebroadcast = GetTime(); } // // Message: addr // if (fSendTrickle) { vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } // // Message: inventory // vector<CInv> vInv; vector<CInv> vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); // always trickle our own transactions if (!fTrickleWait) { CWalletTx wtx; if (GetTransaction(inv.hash, wtx)) if (wtx.fFromMe) fTrickleWait = true; } if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // // Message: getdata // vector<CInv> vGetData; int64 nNow = GetTime() * 1000000; CTxDB txdb("r"); while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(txdb, inv)) { printf("sending getdata: %s\n", inv.ToString().c_str()); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } } mapAlreadyAskedFor[inv] = nNow; pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; } ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // int static FormatHashBlocks(void* pbuffer, unsigned int len) { unsigned char* pdata = (unsigned char*)pbuffer; unsigned int blocks = 1 + ((len + 8) / 64); unsigned char* pend = pdata + 64 * blocks; memset(pdata + len, 0, 64 * blocks - len); pdata[len] = 0x80; unsigned int bits = len * 8; pend[-1] = (bits >> 0) & 0xff; pend[-2] = (bits >> 8) & 0xff; pend[-3] = (bits >> 16) & 0xff; pend[-4] = (bits >> 24) & 0xff; return blocks; } static const unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; void SHA256Transform(void* pstate, void* pinput, const void* pinit) { SHA256_CTX ctx; unsigned char data[64]; SHA256_Init(&ctx); for (int i = 0; i < 16; i++) ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); for (int i = 0; i < 8; i++) ctx.h[i] = ((uint32_t*)pinit)[i]; SHA256_Update(&ctx, data, sizeof(data)); for (int i = 0; i < 8; i++) ((uint32_t*)pstate)[i] = ctx.h[i]; } // Some explaining would be appreciated class COrphan { public: CTransaction* ptx; set<uint256> setDependsOn; double dPriority; COrphan(CTransaction* ptxIn) { ptx = ptxIn; dPriority = 0; } void print() const { printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority); BOOST_FOREACH(uint256 hash, setDependsOn) printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); } }; uint64 nLastBlockTx = 0; uint64 nLastBlockSize = 0; int64 nLastCoinStakeSearchInterval = 0; // CreateNewBlock: // fProofOfStake: try (best effort) to make a proof-of-stake block CBlock* CreateNewBlock(CReserveKey& reservekey, CWallet* pwallet, bool fProofOfStake) { // Create new block auto_ptr<CBlock> pblock(new CBlock()); if (!pblock.get()) return NULL; // Create coinbase tx CTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG; // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); // ppcoin: if coinstake available add coinstake tx static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup CBlockIndex* pindexPrev = pindexBest; if (fProofOfStake) // attemp to find a coinstake { pblock->nBits = GetNextTargetRequired(pindexPrev, true); CTransaction txCoinStake; int64 nSearchTime = txCoinStake.nTime; // search to current time if (nSearchTime > nLastCoinStakeSearchTime) { if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake)) { if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - MAX_CLOCK_DRIFT)) { // make sure coinstake would meet timestamp protocol // as it would be the same as the block timestamp pblock->vtx[0].vout[0].SetEmpty(); pblock->vtx[0].nTime = txCoinStake.nTime; pblock->vtx.push_back(txCoinStake); } } nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime; nLastCoinStakeSearchTime = nSearchTime; } } pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake()); // Collect memory pool transactions into the block int64 nFees = 0; { LOCK2(cs_main, mempool.cs); CTxDB txdb("r"); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; multimap<double, CTransaction*> mapPriority; for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { CTransaction& tx = (*mi).second; if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal()) continue; COrphan* porphan = NULL; double dPriority = 0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Read prev transaction CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) { // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); } mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); continue; } int64 nValueIn = txPrev.vout[txin.prevout.n].nValue; // Read block header int nConf = txindex.GetDepthInMainChain(); dPriority += (double)nValueIn * nConf; if (fDebug && GetBoolArg("-printpriority")) printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority); } // Priority is sum(valuein * age) / txsize dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (porphan) porphan->dPriority = dPriority; else mapPriority.insert(make_pair(-dPriority, &(*mi).second)); if (fDebug && GetBoolArg("-printpriority")) { printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str()); if (porphan) porphan->print(); printf("\n"); } } // Collect transactions into block map<uint256, CTxIndex> mapTestPool; uint64 nBlockSize = 1000; uint64 nBlockTx = 0; int nBlockSigOps = 100; while (!mapPriority.empty()) { // Take highest priority transaction off priority queue CTransaction& tx = *(*mapPriority.begin()).second; mapPriority.erase(mapPriority.begin()); // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) continue; // Legacy limits on sigOps: unsigned int nTxSigOps = tx.GetLegacySigOpCount(); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Timestamp limit if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime)) continue; // ppcoin: simplify transaction fee - allow free = false int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK); // Connecting shouldn't fail due to dependency on other memory pool transactions // because we're already processing them in order of dependency map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); MapPrevTx mapInputs; bool fInvalid; if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid)) continue; int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (nTxFees < nMinFee) continue; nTxSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true)) continue; mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size()); swap(mapTestPool, mapTestPoolTmp); // Added pblock->vtx.push_back(tx); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; // Add transactions that depend on this one to the priority queue uint256 hash = tx.GetHash(); if (mapDependers.count(hash)) { BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx)); } } } } nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; if (fDebug && GetBoolArg("-printpriority")) { printf("CreateNewBlock(): total size %lu\n", nBlockSize); } } if (pblock->IsProofOfWork()) pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pindexPrev->nHeight); // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); if (pblock->IsProofOfStake()) pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime()); pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - MAX_CLOCK_DRIFT); if (pblock->IsProofOfWork()) pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; return pblock.release(); } void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS; assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) { // // Prebuild hash buffers // struct { struct unnamed2 { int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; } block; unsigned char pchPadding0[64]; uint256 hash1; unsigned char pchPadding1[64]; } tmp; memset(&tmp, 0, sizeof(tmp)); tmp.block.nVersion = pblock->nVersion; tmp.block.hashPrevBlock = pblock->hashPrevBlock; tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; tmp.block.nTime = pblock->nTime; tmp.block.nBits = pblock->nBits; tmp.block.nNonce = pblock->nNonce; FormatHashBlocks(&tmp.block, sizeof(tmp.block)); FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); // Byte swap all the input buffer for (unsigned int i = 0; i < sizeof(tmp)/4; i++) ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); // Precalc the first half of the first hash, which stays constant SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); memcpy(pdata, &tmp.block, 128); memcpy(phash1, &tmp.hash1, 64); } bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) { uint256 hash = pblock->GetHash(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); printf("Hash: %s\nTarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); if (hash > hashTarget && pblock->IsProofOfWork()) return error("BitcoinMiner : proof-of-work not meeting target"); //// debug print printf("BitcoinMiner:\n"); printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); printf("%s ", DateTimeStrFormat(GetTime()).c_str()); printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("BitcoinMiner : generated block is stale"); // Remove key from key pool reservekey.KeepKey(); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[pblock->GetHash()] = 0; } // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock)) return error("BitcoinMiner : ProcessBlock, block not accepted"); } return true; } void static ThreadBitcoinMiner(void* parg); bool fStaking = true; static bool fGenerateBitcoins = false; static bool fLimitProcessors = false; static int nLimitProcessors = -1; bool BitcoinMiner(CWallet *pwallet, bool fProofOfStake, uint256 * minedBlock, uint64 nTimeout) { printf("CPUMiner started for proof-of-%s (%d)\n", fProofOfStake? "stake" : "work", vnThreadsRunning[fProofOfStake? THREAD_MINTER : THREAD_MINER]); SetThreadPriority(THREAD_PRIORITY_LOWEST); uint64 nStartTime = GetTime(); // Each thread has its own key and counter CReserveKey reservekey(pwallet); unsigned int nExtraNonce = 0; while (minedBlock || fGenerateBitcoins || fProofOfStake) { if (fShutdown || (fProofOfStake && !fStaking)) return false; if (nTimeout && (GetTime() - nStartTime > nTimeout)) return false; while (vNodes.empty() || IsInitialBlockDownload()) { Sleep(1000); if (fShutdown || (fProofOfStake && !fStaking)) return false; if (!minedBlock && (!fGenerateBitcoins && !fProofOfStake)) return false; } while (pwallet->IsLocked()) { strMintWarning = strMintMessage; Sleep(1000); } strMintWarning.clear(); // // Create new block // unsigned int nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrev = pindexBest; auto_ptr<CBlock> pblock(CreateNewBlock(reservekey, pwallet, fProofOfStake)); if (!pblock.get()) return false; IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce); if (fProofOfStake) { // ppcoin: if proof-of-stake block found then process block if (pblock->IsProofOfStake()) { if (!pblock->SignBlock(*pwalletMain)) { strMintWarning = strMintMessage; continue; } strMintWarning.clear(); printf("CPUMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str()); SetThreadPriority(THREAD_PRIORITY_NORMAL); bool fSucceeded = CheckWork(pblock.get(), *pwalletMain, reservekey); SetThreadPriority(THREAD_PRIORITY_LOWEST); if (fSucceeded && minedBlock) { *minedBlock = pblock->GetHash(); return true; } } Sleep(500); continue; } printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size()); // // Search // int64 nStart = GetTime(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); INFINITE_LOOP { unsigned int nHashesDone = 0; pblock->nNonce = 0; INFINITE_LOOP { if (pblock->GetHash() <= hashTarget) break; pblock->nNonce += 1; nHashesDone += 1; if ((pblock->nNonce & 0xFFFF) == 0) break; } // Check if something found if (pblock->GetHash() <= hashTarget) { if (!pblock->SignBlock(*pwalletMain)) { strMintWarning = strMintMessage; break; } else { strMintWarning = ""; } SetThreadPriority(THREAD_PRIORITY_NORMAL); bool fSucceeded = CheckWork(pblock.get(), *pwalletMain, reservekey); SetThreadPriority(THREAD_PRIORITY_LOWEST); if (fSucceeded && minedBlock) { *minedBlock = pblock->GetHash(); return true; } break; } // Meter hashes/sec static int64 nHashCounter; if (nHPSTimerStart == 0) { nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; } else { nHashCounter += nHashesDone; } if (GetTimeMillis() - nHPSTimerStart > 4000) { static CCriticalSection cs; { LOCK(cs); if (GetTimeMillis() - nHPSTimerStart > 4000) { dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart); nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; static int64 nLogTime; if (GetTime() - nLogTime > 30 * 60) { nLogTime = GetTime(); printf("%s ", DateTimeStrFormat(GetTime()).c_str()); printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0); } } } } // Check for stop or if block needs to be rebuilt if (fShutdown || (fProofOfStake && !fStaking)) return false; if (!minedBlock && !fGenerateBitcoins) return false; if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors) return false; if (vNodes.empty()) break; if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60) break; if (pindexPrev != pindexBest) break; // Update nTime every few seconds pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime()); pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - MAX_CLOCK_DRIFT); pblock->UpdateTime(pindexPrev); if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + MAX_CLOCK_DRIFT) { break; // need to update coinbase timestamp } } } return false; } void static ThreadBitcoinMiner(void* parg) { CWallet* pwallet = (CWallet*)parg; try { vnThreadsRunning[THREAD_MINER]++; BitcoinMiner(pwallet, false); vnThreadsRunning[THREAD_MINER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_MINER]--; PrintException(&e, "ThreadBitcoinMiner()"); } catch (...) { vnThreadsRunning[THREAD_MINER]--; PrintException(NULL, "ThreadBitcoinMiner()"); } nHPSTimerStart = 0; if (vnThreadsRunning[THREAD_MINER] == 0) dHashesPerSec = 0; printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]); } void GenerateBitcoins(bool fGenerate, CWallet* pwallet) { fGenerateBitcoins = fGenerate; nLimitProcessors = GetArg("-genproclimit", -1); if (nLimitProcessors == 0) fGenerateBitcoins = false; fLimitProcessors = (nLimitProcessors != -1); if (fGenerate) { int nProcessors = boost::thread::hardware_concurrency(); printf("%d processors\n", nProcessors); if (nProcessors < 1) nProcessors = 1; if (fLimitProcessors && nProcessors > nLimitProcessors) nProcessors = nLimitProcessors; int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER]; printf("Starting %d BitcoinMiner threads\n", nAddThreads); for (int i = 0; i < nAddThreads; i++) { if (!CreateThread(ThreadBitcoinMiner, pwallet)) printf("Error: CreateThread(ThreadBitcoinMiner) failed\n"); Sleep(10); } } }
Magicking/neucoin
src/main.cpp
C++
mit
146,265
'use strict'; console.log('TESTTTT'); var mean = require('meanio'); exports.render = function (req, res) { function isAdmin() { return req.user && req.user.roles.indexOf('admin') !== -1; } // Send some basic starting info to the view res.render('index', { user: req.user ? { name: req.user.name, _id: req.user._id, username: req.user.username, roles: req.user.roles } : {}, modules: 'ho', motti: 'motti is cool', isAdmin: 'motti', adminEnabled: isAdmin() && mean.moduleEnabled('mean-admin') }); };
mottihoresh/nodarium-web
packages/custom/nodarium/server/controllers/index.js
JavaScript
mit
627
/* concatenated from client/src/app/js/globals.js */ (function () { if (!window.console) { window.console = {}; } var m = [ "log", "info", "warn", "error", "debug", "trace", "dir", "group", "groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd", "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear" ]; for (var i = 0; i < m.length; i++) { if (!window.console[m[i]]) { window.console[m[i]] = function() {}; } } _.mixin({ compactObject: function(o) { _.each(o, function(v, k) { if(!v) { delete o[k]; } }); return o; } }); })(); /* concatenated from client/src/app/js/app.js */ const mainPages = { HOME: "/", WALKS: "/walks", SOCIAL: "/social", JOIN_US: "/join-us", CONTACT_US: "/contact-us", COMMITTEE: "/committee", ADMIN: "/admin", HOW_TO: "/how-to" }; angular.module("ekwgApp", [ "btford.markdown", "ngRoute", "ngSanitize", "ui.bootstrap", "angularModalService", "btford.markdown", "mongolabResourceHttp", "ngAnimate", "ngCookies", "ngFileUpload", "ngSanitize", "ui.bootstrap", "ui.select", "angular-logger", "ezfb", "ngCsv"]) .constant("MONGOLAB_CONFIG", { trimErrorMessage: false, baseUrl: "/databases/", database: "ekwg" }) .constant("AUDIT_CONFIG", { auditSave: true, }) .constant("PAGE_CONFIG", { mainPages: mainPages }) .config(["$compileProvider", function ($compileProvider) { $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|tel):/); }]) .constant("MAILCHIMP_APP_CONSTANTS", { allowSendCampaign: true, apiServer: "https://us3.admin.mailchimp.com" }) .config(["$locationProvider", function ($locationProvider) { $locationProvider.hashPrefix(""); }]) .config(["$routeProvider", "uiSelectConfig", "uibDatepickerConfig", "uibDatepickerPopupConfig", "logEnhancerProvider", function ($routeProvider, uiSelectConfig, uibDatepickerConfig, uibDatepickerPopupConfig, logEnhancerProvider) { uiSelectConfig.theme = "bootstrap"; uiSelectConfig.closeOnSelect = false; $routeProvider .when(mainPages.ADMIN + "/expenseId/:expenseId", { controller: "AdminController", templateUrl: "partials/admin/admin.html", title: "expenses" }) .when(mainPages.ADMIN + "/:area?", { controller: "AdminController", templateUrl: "partials/admin/admin.html", title: "admin" }) .when(mainPages.COMMITTEE + "/committeeFileId/:committeeFileId", { controller: "CommitteeController", templateUrl: "partials/committee/committee.html", title: "AGM and committee" }) .when(mainPages.COMMITTEE, { controller: "CommitteeController", templateUrl: "partials/committee/committee.html", title: "AGM and committee" }) .when(mainPages.HOW_TO, { controller: "HowToController", templateUrl: "partials/howTo/how-to.html", title: "How-to" }) .when("/image-editor/:imageSource", { controller: "ImageEditController", templateUrl: "partials/imageEditor/image-editor.html", title: "image editor" }) .when(mainPages.JOIN_US, { controller: "HomeController", templateUrl: "partials/joinUs/join-us.html", title: "join us" }) .when("/letterhead/:firstPart?/:secondPart", { controller: "LetterheadController", templateUrl: "partials/letterhead/letterhead.html", title: "letterhead" }) .when(mainPages.CONTACT_US, { controller: "ContactUsController", templateUrl: "partials/contactUs/contact-us.html", title: "contact us" }) .when("/links", {redirectTo: mainPages.CONTACT_US}) .when(mainPages.SOCIAL + "/socialEventId/:socialEventId", { controller: "SocialEventsController", templateUrl: "partials/socialEvents/social.html", title: "social" }) .when(mainPages.SOCIAL + "/:area?", { controller: "SocialEventsController", templateUrl: "partials/socialEvents/social.html", title: "social" }) .when(mainPages.WALKS + "/walkId/:walkId", { controller: "WalksController", templateUrl: "partials/walks/walks.html", title: "walks" }) .when(mainPages.WALKS + "/:area?", { controller: "WalksController", templateUrl: "partials/walks/walks.html", title: "walks" }) .when(mainPages.HOME, { controller: "HomeController", templateUrl: "partials/home/home.html", title: "home" }) .when("/set-password/:passwordResetId", { controller: "AuthenticationModalsController", templateUrl: "partials/home/home.html" }) .otherwise({ controller: "AuthenticationModalsController", templateUrl: "partials/home/home.html" }); uibDatepickerConfig.startingDay = 1; uibDatepickerConfig.showWeeks = false; uibDatepickerPopupConfig.datepickerPopup = "dd-MMM-yyyy"; uibDatepickerPopupConfig.formatDay = "dd"; logEnhancerProvider.datetimePattern = "hh:mm:ss"; logEnhancerProvider.prefixPattern = "%s - %s -"; }]) .run(["$log", "$rootScope", "$route", "URLService", "CommitteeConfig", "CommitteeReferenceData", function ($log, $rootScope, $route, URLService, CommitteeConfig, CommitteeReferenceData) { var logger = $log.getInstance("App.run"); $log.logLevels["App.run"] = $log.LEVEL.OFF; $rootScope.$on('$locationChangeStart', function (evt, absNewUrl, absOldUrl) { }); $rootScope.$on("$locationChangeSuccess", function (event, newUrl, absOldUrl) { if (!$rootScope.pageHistory) $rootScope.pageHistory = []; $rootScope.pageHistory.push(URLService.relativeUrl(newUrl)); logger.info("newUrl", newUrl, "$rootScope.pageHistory", $rootScope.pageHistory); }); $rootScope.$on("$routeChangeSuccess", function (currentRoute, previousRoute) { $rootScope.title = $route.current.title; }); CommitteeConfig.getConfig() .then(function (config) { angular.extend(CommitteeReferenceData, config.committee); $rootScope.$broadcast("CommitteeReferenceDataReady", CommitteeReferenceData); }); }]); /* concatenated from client/src/app/js/admin.js */ angular.module('ekwgApp') .controller('AdminController', ["$rootScope", "$scope", "LoggedInMemberService", function($rootScope, $scope, LoggedInMemberService) { function setViewPriveleges() { $scope.loggedIn = LoggedInMemberService.memberLoggedIn(); $scope.memberAdmin = LoggedInMemberService.allowMemberAdminEdits(); LoggedInMemberService.showLoginPromptWithRouteParameter('expenseId'); } setViewPriveleges(); $scope.$on('memberLoginComplete', function() { setViewPriveleges(); }); $scope.$on('memberLogoutComplete', function() { setViewPriveleges(); }); }] ); /* concatenated from client/src/app/js/authenticationModalsController.js */ angular.module('ekwgApp') .controller("AuthenticationModalsController", ["$log", "$scope", "URLService", "$location", "$routeParams", "AuthenticationModalsService", "LoggedInMemberService", function ($log, $scope, URLService, $location, $routeParams, AuthenticationModalsService, LoggedInMemberService) { var logger = $log.getInstance("AuthenticationModalsController"); $log.logLevels["AuthenticationModalsController"] = $log.LEVEL.OFF; var urlFirstSegment = URLService.relativeUrlFirstSegment(); logger.info("URLService.relativeUrl:", urlFirstSegment, "$routeParams:", $routeParams); switch (urlFirstSegment) { case "/login": return AuthenticationModalsService.showLoginDialog(); case "/logout": return LoggedInMemberService.logout(); case "/mailing-preferences": if (LoggedInMemberService.memberLoggedIn()) { return AuthenticationModalsService.showMailingPreferencesDialog(LoggedInMemberService.loggedInMember().memberId); } else { return URLService.setRoot(); } case "/forgot-password": return AuthenticationModalsService.showForgotPasswordModal(); case "/set-password": return LoggedInMemberService.getMemberByPasswordResetId($routeParams.passwordResetId) .then(function (member) { logger.info("for $routeParams.passwordResetId", $routeParams.passwordResetId, "member", member); if (_.isEmpty(member)) { return AuthenticationModalsService.showResetPasswordFailedDialog(); } else { return AuthenticationModalsService.showResetPasswordModal(member.userName) } }); default: logger.warn(URLService.relativeUrl(), "doesnt match any of the supported urls"); return URLService.setRoot(); } }] ); /* concatenated from client/src/app/js/authenticationModalsService.js */ angular.module('ekwgApp') .factory("AuthenticationModalsService", ["$log", "ModalService", "URLService", function ($log, ModalService, URLService) { var logger = $log.getInstance("AuthenticationModalsService"); $log.logLevels["AuthenticationModalsService"] = $log.LEVEL.OFF; function showForgotPasswordModal() { logger.info('called showForgotPasswordModal'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/forgotten-password-dialog.html", controller: "ForgotPasswordController", preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }).catch(function (error) { logger.warn("error happened:", error); }) } function showResetPasswordModal(userName, message) { logger.info('called showResetPasswordModal for userName', userName); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/reset-password-dialog.html", controller: "ResetPasswordController", inputs: {userName: userName, message: message}, preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('showResetPasswordModal close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }) } function showLoginDialog() { logger.info('called showLoginDialog'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/login-dialog.html", controller: "LoginController", preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('showLoginDialog close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }) } function showResetPasswordFailedDialog() { logger.info('called showResetPasswordFailedDialog'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/reset-password-failed-dialog.html", controller: "ResetPasswordFailedController", preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('showResetPasswordFailedDialog modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('showResetPasswordFailedDialog close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }) } function showMailingPreferencesDialog(memberId) { logger.info('called showMailingPreferencesDialog'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/mailing-preferences-dialog.html", controller: "MailingPreferencesController", inputs: {memberId: memberId}, preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('showMailingPreferencesDialog modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }) } return { showResetPasswordModal: showResetPasswordModal, showResetPasswordFailedDialog: showResetPasswordFailedDialog, showForgotPasswordModal: showForgotPasswordModal, showLoginDialog: showLoginDialog, showMailingPreferencesDialog: showMailingPreferencesDialog } }]); /* concatenated from client/src/app/js/awsServices.js */ angular.module('ekwgApp') .factory('AWSConfig', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) { function getConfig() { return $http.get('/aws/config').then(HTTPResponseService.returnResponse); } function awsPolicy(fileType, objectKey) { return $http.get('/aws/s3Policy?mimeType=' + fileType + '&objectKey=' + objectKey).then(HTTPResponseService.returnResponse); } return { getConfig: getConfig, awsPolicy: awsPolicy } }]) .factory('EKWGFileUpload', ["$log", "AWSConfig", "NumberUtils", "Upload", function ($log, AWSConfig, NumberUtils, Upload) { $log.logLevels['EKWGFileUpload'] = $log.LEVEL.OFF; var logger = $log.getInstance('EKWGFileUpload'); var awsConfig; AWSConfig.getConfig().then(function (config) { awsConfig = config; }); function onFileSelect(file, notify, objectKey) { logger.debug(file, objectKey); function generateFileNameData() { return { originalFileName: file.name, awsFileName: NumberUtils.generateUid() + '.' + _.last(file.name.split('.')) }; } var fileNameData = generateFileNameData(), fileUpload = file; fileUpload.progress = parseInt(0); logger.debug('uploading fileNameData', fileNameData); return AWSConfig.awsPolicy(file.type, objectKey) .then(function (response) { var s3Params = response; var url = 'https://' + awsConfig.bucket + '.s3.amazonaws.com/'; return Upload.upload({ url: url, method: 'POST', data: { 'key': objectKey + '/' + fileNameData.awsFileName, 'acl': 'public-read', 'Content-Type': file.type, 'AWSAccessKeyId': s3Params.AWSAccessKeyId, 'success_action_status': '201', 'Policy': s3Params.s3Policy, 'Signature': s3Params.s3Signature }, file: file }).then(function (response) { fileUpload.progress = parseInt(100); if (response.status === 201) { var data = xml2json.parser(response.data), parsedData; parsedData = { location: data.postresponse.location, bucket: data.postresponse.bucket, key: data.postresponse.key, etag: data.postresponse.etag }; logger.debug('parsedData', parsedData); return fileNameData; } else { notify.error('Upload Failed for file ' + fileNameData); } }, notify.error, function (evt) { fileUpload.progress = parseInt(100.0 * evt.loaded / evt.total); }); }); } return {onFileSelect: onFileSelect}; }]); /* concatenated from client/src/app/js/batchGeoServices.js */ angular.module('ekwgApp') .factory('BatchGeoExportService', ["StringUtils", "DateUtils", "$filter", function(StringUtils, DateUtils, $filter) { function exportWalksFileName() { return 'batch-geo-walks-export-' + DateUtils.asMoment().format('DD-MMMM-YYYY-HH-mm') + '.csv' } function exportableWalks(walks) { return _(walks).sortBy('walkDate'); } function exportWalks(walks) { return _.chain(walks) .filter(filterWalk) .sortBy('walkDate') .last(250) .map(walkToCsvRecord) .value(); } function filterWalk(walk) { return _.has(walk, 'briefDescriptionAndStartPoint') && (_.has(walk, 'gridReference') || _.has(walk, 'postcode')); } function exportColumnHeadings() { return [ "Walk Date", "Start Time", "Postcode", "Contact Name/Email", "Distance", "Description", "Longer Description", "Grid Ref" ]; } function walkToCsvRecord(walk) { return { "walkDate": walkDate(walk), "startTime": walkStartTime(walk), "postcode": walkPostcode(walk), "displayName": contactDisplayName(walk), "distance": walkDistanceMiles(walk), "description": walkTitle(walk), "longerDescription": walkDescription(walk), "gridRef": walkGridReference(walk) }; } function walkTitle(walk) { var walkDescription = []; if (walk.includeWalkDescriptionPrefix) walkDescription.push(walk.walkDescriptionPrefix); if (walk.briefDescriptionAndStartPoint) walkDescription.push(walk.briefDescriptionAndStartPoint); return _.chain(walkDescription).map(replaceSpecialCharacters).value().join('. '); } function walkDescription(walk) { return replaceSpecialCharacters(walk.longerDescription); } function asString(value) { return value ? value : ''; } function contactDisplayName(walk) { return walk.displayName ? replaceSpecialCharacters(_.first(walk.displayName.split(' '))) : ''; } function replaceSpecialCharacters(value) { return value ? StringUtils.stripLineBreaks(value .replace("’", "'") .replace("é", "e") .replace("’", "'") .replace('…', '…') .replace('–', '–') .replace('’', '’') .replace('“', '“')) : ''; } function walkDistanceMiles(walk) { return walk.distance ? String(parseFloat(walk.distance).toFixed(1)) : ''; } function walkStartTime(walk) { return walk.startTime ? DateUtils.asString(walk.startTime, 'HH mm', 'HH:mm') : ''; } function walkGridReference(walk) { return walk.gridReference ? walk.gridReference : ''; } function walkPostcode(walk) { return walk.postcode ? walk.postcode : ''; } function walkDate(walk) { return $filter('displayDate')(walk.walkDate); } return { exportWalksFileName: exportWalksFileName, exportWalks: exportWalks, exportableWalks: exportableWalks, exportColumnHeadings: exportColumnHeadings } }]); /* concatenated from client/src/app/js/bulkUploadServices.js */ angular.module('ekwgApp') .factory('MemberBulkUploadService', ["$log", "$q", "$filter", "MemberService", "MemberUpdateAuditService", "MemberBulkLoadAuditService", "ErrorMessageService", "EmailSubscriptionService", "DateUtils", "DbUtils", "MemberNamingService", function ($log, $q, $filter, MemberService, MemberUpdateAuditService, MemberBulkLoadAuditService, ErrorMessageService, EmailSubscriptionService, DateUtils, DbUtils, MemberNamingService) { var logger = $log.getInstance('MemberBulkUploadService'); var noLogger = $log.getInstance('NoLogger'); $log.logLevels['MemberBulkUploadService'] = $log.LEVEL.OFF; $log.logLevels['NoLogger'] = $log.LEVEL.OFF; var RESET_PASSWORD = 'changeme'; function processMembershipRecords(file, memberBulkLoadServerResponse, members, notify) { notify.setBusy(); var today = DateUtils.momentNowNoTime().valueOf(); var promises = []; var memberBulkLoadResponse = memberBulkLoadServerResponse.data; logger.debug('received', memberBulkLoadResponse); return DbUtils.auditedSaveOrUpdate(new MemberBulkLoadAuditService(memberBulkLoadResponse)) .then(function (auditResponse) { var uploadSessionId = auditResponse.$id(); return processBulkLoadResponses(promises, uploadSessionId); }); function updateGroupMembersPreBulkLoadProcessing(promises) { if (memberBulkLoadResponse.members && memberBulkLoadResponse.members.length > 1) { notify.progress('Processing ' + members.length + ' members ready for bulk load'); _.each(members, function (member) { if (member.receivedInLastBulkLoad) { member.receivedInLastBulkLoad = false; promises.push(DbUtils.auditedSaveOrUpdate(member, auditUpdateCallback(member), auditErrorCallback(member))); } }); return $q.all(promises).then(function () { notify.progress('Marked ' + promises.length + ' out of ' + members.length + ' in preparation for update'); return promises; }); } else { return $q.when(promises); } } function processBulkLoadResponses(promises, uploadSessionId) { return updateGroupMembersPreBulkLoadProcessing(promises).then(function (updatedPromises) { _.each(memberBulkLoadResponse.members, function (ramblersMember, recordIndex) { createOrUpdateMember(uploadSessionId, recordIndex, ramblersMember, updatedPromises); }); return $q.all(updatedPromises).then(function () { logger.debug('performed total of', updatedPromises.length, 'audit or member updates'); return updatedPromises; }); }); } function auditUpdateCallback(member) { return function (response) { logger.debug('auditUpdateCallback for member:', member, 'response', response); } } function auditErrorCallback(member, audit) { return function (response) { logger.warn('member save error for member:', member, 'response:', response); if (audit) { audit.auditErrorMessage = response; } } } function saveAndAuditMemberUpdate(promises, uploadSessionId, rowNumber, memberAction, changes, auditMessage, member) { var audit = new MemberUpdateAuditService({ uploadSessionId: uploadSessionId, updateTime: DateUtils.nowAsValue(), memberAction: memberAction, rowNumber: rowNumber, changes: changes, auditMessage: auditMessage }); var qualifier = 'for membership ' + member.membershipNumber; member.receivedInLastBulkLoad = true; member.lastBulkLoadDate = DateUtils.momentNow().valueOf(); return DbUtils.auditedSaveOrUpdate(member, auditUpdateCallback(member), auditErrorCallback(member, audit)) .then(function (savedMember) { if (savedMember) { audit.memberId = savedMember.$id(); notify.success({title: 'Bulk member load ' + qualifier + ' was successful', message: auditMessage}) } else { audit.member = member; audit.memberAction = 'error'; logger.warn('member was not saved, so saving it to audit:', audit); notify.warning({title: 'Bulk member load ' + qualifier + ' failed', message: auditMessage}) } logger.debug('saveAndAuditMemberUpdate:', audit); promises.push(audit.$save()); return promises; }); } function convertMembershipExpiryDate(ramblersMember) { var dataValue = ramblersMember.membershipExpiryDate ? DateUtils.asValueNoTime(ramblersMember.membershipExpiryDate, 'DD/MM/YYYY') : ramblersMember.membershipExpiryDate; logger.debug('ramblersMember', ramblersMember, 'membershipExpiryDate', ramblersMember.membershipExpiryDate, '->', DateUtils.displayDate(dataValue)); return dataValue; } function createOrUpdateMember(uploadSessionId, recordIndex, ramblersMember, promises) { var memberAction; ramblersMember.membershipExpiryDate = convertMembershipExpiryDate(ramblersMember); ramblersMember.groupMember = !ramblersMember.membershipExpiryDate || ramblersMember.membershipExpiryDate >= today; var member = _.find(members, function (member) { var existingUserName = MemberNamingService.createUserName(ramblersMember); var match = member.membershipNumber && member.membershipNumber.toString() === ramblersMember.membershipNumber; if (!match && member.userName) { match = member.userName === existingUserName; } noLogger.debug('match', !!(match), 'ramblersMember.membershipNumber', ramblersMember.membershipNumber, 'ramblersMember.userName', existingUserName, 'member.membershipNumber', member.membershipNumber, 'member.userName', member.userName); return match; }); if (member) { EmailSubscriptionService.resetUpdateStatusForMember(member); } else { memberAction = 'created'; member = new MemberService(); member.userName = MemberNamingService.createUniqueUserName(ramblersMember, members); member.displayName = MemberNamingService.createUniqueDisplayName(ramblersMember, members); member.password = RESET_PASSWORD; member.expiredPassword = true; EmailSubscriptionService.defaultMailchimpSettings(member, true); logger.debug('new member created:', member); } var updateAudit = {auditMessages: [], fieldsChanged: 0, fieldsSkipped: 0}; _.each([ {fieldName: 'membershipExpiryDate', writeDataIf: 'changed', type: 'date'}, {fieldName: 'membershipNumber', writeDataIf: 'changed', type: 'string'}, {fieldName: 'mobileNumber', writeDataIf: 'empty', type: 'string'}, {fieldName: 'email', writeDataIf: 'empty', type: 'string'}, {fieldName: 'firstName', writeDataIf: 'empty', type: 'string'}, {fieldName: 'lastName', writeDataIf: 'empty', type: 'string'}, {fieldName: 'postcode', writeDataIf: 'empty', type: 'string'}, {fieldName: 'groupMember', writeDataIf: 'not-revoked', type: 'boolean'}], function (field) { changeAndAuditMemberField(updateAudit, member, ramblersMember, field) }); DbUtils.removeEmptyFieldsIn(member); logger.debug('saveAndAuditMemberUpdate -> member:', member, 'updateAudit:', updateAudit); return saveAndAuditMemberUpdate(promises, uploadSessionId, recordIndex + 1, memberAction || (updateAudit.fieldsChanged > 0 ? 'updated' : 'skipped'), updateAudit.fieldsChanged, updateAudit.auditMessages.join(', '), member); } function changeAndAuditMemberField(updateAudit, member, ramblersMember, field) { function auditValueForType(field, source) { var dataValue = source[field.fieldName]; switch (field.type) { case 'date': return ($filter('displayDate')(dataValue) || '(none)'); case 'boolean': return dataValue || false; default: return dataValue || '(none)'; } } var fieldName = field.fieldName; var performMemberUpdate = false; var auditQualifier = ' not overwritten with '; var auditMessage; var oldValue = auditValueForType(field, member); var newValue = auditValueForType(field, ramblersMember); if (field.writeDataIf === 'changed') { performMemberUpdate = (oldValue !== newValue) && ramblersMember[fieldName]; } else if (field.writeDataIf === 'empty') { performMemberUpdate = !member[fieldName]; } else if (field.writeDataIf === 'not-revoked') { performMemberUpdate = newValue && (oldValue !== newValue) && !member.revoked; } else if (field.writeDataIf) { performMemberUpdate = newValue; } if (performMemberUpdate) { auditQualifier = ' updated to '; member[fieldName] = ramblersMember[fieldName]; updateAudit.fieldsChanged++; } if (oldValue !== newValue) { if (!performMemberUpdate) updateAudit.fieldsSkipped++; auditMessage = fieldName + ': ' + oldValue + auditQualifier + newValue; } if ((performMemberUpdate || (oldValue !== newValue)) && auditMessage) { updateAudit.auditMessages.push(auditMessage); } } } return { processMembershipRecords: processMembershipRecords, } }]); /* concatenated from client/src/app/js/clipboardService.js */ angular.module('ekwgApp') .factory('ClipboardService', ["$compile", "$rootScope", "$document", "$log", function ($compile, $rootScope, $document, $log) { return { copyToClipboard: function (element) { var logger = $log.getInstance("ClipboardService"); $log.logLevels['ClipboardService'] = $log.LEVEL.OFF; var copyElement = angular.element('<span id="clipboard-service-copy-id">' + element + '</span>'); var body = $document.find('body').eq(0); body.append($compile(copyElement)($rootScope)); var ClipboardServiceElement = angular.element(document.getElementById('clipboard-service-copy-id')); logger.debug(ClipboardServiceElement); var range = document.createRange(); range.selectNode(ClipboardServiceElement[0]); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; logger.debug('Copying text command was ' + msg); window.getSelection().removeAllRanges(); copyElement.remove(); } } }]); /* concatenated from client/src/app/js/comitteeNotifications.js */ angular.module('ekwgApp') .controller('CommitteeNotificationsController', ["$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MAILCHIMP_APP_CONSTANTS", "MailchimpConfig", "Notifier", "CommitteeReferenceData", "CommitteeQueryService", "committeeFile", "close", function ($window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService, MAILCHIMP_APP_CONSTANTS, MailchimpConfig, Notifier, CommitteeReferenceData, CommitteeQueryService, committeeFile, close) { var logger = $log.getInstance('CommitteeNotificationsController'); $log.logLevels['CommitteeNotificationsController'] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); $scope.members = []; $scope.committeeFile = committeeFile; $scope.roles = {signoff: CommitteeReferenceData.contactUsRolesAsArray(), replyTo: []}; $scope.committeeFileBaseUrl = ContentMetaDataService.baseUrl('committeeFiles'); function loggedOnRole() { var memberId = LoggedInMemberService.loggedInMember().memberId; var loggedOnRoleData = _(CommitteeReferenceData.contactUsRolesAsArray()).find(function (role) { return role.memberId === memberId }); logger.debug('loggedOnRole for', memberId, '->', loggedOnRoleData); return loggedOnRoleData || {}; } $scope.fromDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.fromDateCalendar.opened = true; } }; $scope.toDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.toDateCalendar.opened = true; } }; $scope.populateGroupEvents = function () { notify.setBusy(); populateGroupEvents().then(function () { notify.clearBusy(); return true; }) }; function populateGroupEvents() { return CommitteeQueryService.groupEvents($scope.userEdits.groupEvents) .then(function (events) { $scope.userEdits.groupEvents.events = events; logger.debug('groupEvents', events); return events; }); } $scope.changeGroupEventSelection = function (groupEvent) { groupEvent.selected = !groupEvent.selected; }; $scope.notification = { editable: { text: '', signoffText: 'If you have any questions about the above, please don\'t hesitate to contact me.\n\nBest regards,', }, destinationType: 'committee', includeSignoffText: true, addresseeType: 'Hi *|FNAME|*,', addingNewFile: false, recipients: [], groupEvents: function () { return _.filter($scope.userEdits.groupEvents.events, function (groupEvent) { logger.debug('notification.groupEvents ->', groupEvent); return groupEvent.selected; }); }, signoffAs: { include: true, value: loggedOnRole().type || 'secretary' }, includeDownloadInformation: $scope.committeeFile, title: 'Committee Notification', text: function () { return $filter('lineFeedsToBreaks')($scope.notification.editable.text); }, signoffText: function () { return $filter('lineFeedsToBreaks')($scope.notification.editable.signoffText); } }; if ($scope.committeeFile) { $scope.notification.title = $scope.committeeFile.fileType; $scope.notification.editable.text = 'This is just a quick note to let you know in case you are interested, that I\'ve uploaded a new file to the EKWG website. The file information is as follows:'; } logger.debug('initialised on open: committeeFile', $scope.committeeFile, ', roles', $scope.roles); logger.debug('initialised on open: notification ->', $scope.notification); $scope.userEdits = { sendInProgress: false, cancelled: false, groupEvents: { events: [], fromDate: DateUtils.momentNowNoTime().valueOf(), toDate: DateUtils.momentNowNoTime().add(2, 'weeks').valueOf(), includeContact: true, includeDescription: true, includeLocation: true, includeWalks: true, includeSocialEvents: true, includeCommitteeEvents: true }, allGeneralSubscribedList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.GENERAL_MEMBERS_SUBSCRIBED) .map(toSelectGeneralMember).value(); }, allWalksSubscribedList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.WALKS_MEMBERS_SUBSCRIBED) .map(toSelectWalksMember).value(); }, allSocialSubscribedList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.SOCIAL_MEMBERS_SUBSCRIBED) .map(toSelectSocialMember).value(); }, allCommitteeList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.COMMITTEE_MEMBERS) .map(toSelectGeneralMember).value(); }, replyToRole: function () { return _($scope.roles.replyTo).find(function (role) { return role.type === $scope.socialEvent.notification.items.replyTo.value; }); }, notReady: function () { return $scope.members.length === 0 || $scope.userEdits.sendInProgress || ($scope.notification.recipients.length === 0 && $scope.notification.destinationType === 'custom'); } }; function toSelectGeneralMember(member) { var memberGrouping; var order; if (member.groupMember && member.mailchimpLists.general.subscribed) { memberGrouping = 'Subscribed to general emails'; order = 0; } else if (member.groupMember && !member.mailchimpLists.general.subscribed) { memberGrouping = 'Not subscribed to general emails'; order = 1; } else if (!member.groupMember) { memberGrouping = 'Not a group member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } function toSelectWalksMember(member) { var memberGrouping; var order; if (member.groupMember && member.mailchimpLists.walks.subscribed) { memberGrouping = 'Subscribed to walks emails'; order = 0; } else if (member.groupMember && !member.mailchimpLists.walks.subscribed) { memberGrouping = 'Not subscribed to walks emails'; order = 1; } else if (!member.groupMember) { memberGrouping = 'Not a group member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } function toSelectSocialMember(member) { var memberGrouping; var order; if (member.groupMember && member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Subscribed to social emails'; order = 0; } else if (member.groupMember && !member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Not subscribed to social emails'; order = 1; } else if (!member.groupMember) { memberGrouping = 'Not a group member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } $scope.editAllEKWGRecipients = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('general'); $scope.notification.list = 'general'; $scope.notification.recipients = $scope.userEdits.allGeneralSubscribedList(); $scope.campaignIdChanged(); }; $scope.editAllWalksRecipients = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('walks'); $scope.notification.list = 'walks'; $scope.notification.recipients = $scope.userEdits.allWalksSubscribedList(); $scope.campaignIdChanged(); }; $scope.editAllSocialRecipients = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('socialEvents'); $scope.notification.list = 'socialEvents'; $scope.notification.recipients = $scope.userEdits.allSocialSubscribedList(); $scope.campaignIdChanged(); }; $scope.editCommitteeRecipients = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('committee'); $scope.notification.list = 'general'; $scope.notification.recipients = $scope.userEdits.allCommitteeList(); $scope.campaignIdChanged(); }; $scope.clearRecipientsForCampaignOfType = function (campaignType) { $scope.notification.customCampaignType = campaignType; $scope.notification.campaignId = campaignIdFor(campaignType); $scope.notification.list = 'general'; $scope.notification.recipients = []; $scope.campaignIdChanged(); }; $scope.fileUrl = function () { return $scope.committeeFile && $scope.committeeFile.fileNameData ? URLService.baseUrl() + $scope.committeeFileBaseUrl + '/' + $scope.committeeFile.fileNameData.awsFileName : ''; }; $scope.fileTitle = function () { return $scope.committeeFile ? DateUtils.asString($scope.committeeFile.eventDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + $scope.committeeFile.fileNameData.title : ''; }; function campaignIdFor(campaignType) { switch (campaignType) { case 'committee': return $scope.config.mailchimp.campaigns.committee.campaignId; case 'general': return $scope.config.mailchimp.campaigns.newsletter.campaignId; case 'socialEvents': return $scope.config.mailchimp.campaigns.socialEvents.campaignId; case 'walks': return $scope.config.mailchimp.campaigns.walkNotification.campaignId; default: return $scope.config.mailchimp.campaigns.committee.campaignId; } } function campaignInfoForCampaign(campaignId) { return _.chain($scope.config.mailchimp.campaigns) .map(function (data, campaignType) { var campaignData = _.extend({campaignType: campaignType}, data); logger.debug('campaignData for', campaignType, '->', campaignData); return campaignData; }).find({campaignId: campaignId}) .value(); } $scope.campaignIdChanged = function () { var infoForCampaign = campaignInfoForCampaign($scope.notification.campaignId); logger.debug('for campaignId', $scope.notification.campaignId, 'infoForCampaign', infoForCampaign); if (infoForCampaign) { $scope.notification.title = infoForCampaign.name; } }; $scope.confirmSendNotification = function (dontSend) { $scope.userEdits.sendInProgress = true; var campaignName = $scope.notification.title; notify.setBusy(); return $q.when(templateFor('partials/committee/committee-notification.html')) .then(renderTemplateContent) .then(populateContentSections) .then(sendEmailCampaign) .then(notifyEmailSendComplete) .catch(handleNotificationError); function templateFor(template) { return $templateRequest($sce.getTrustedResourceUrl(template)) } function handleNotificationError(errorResponse) { $scope.userEdits.sendInProgress = false; notify.clearBusy(); notify.error({ title: 'Your notification could not be sent', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '') }); } function renderTemplateContent(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction($scope); $timeout(function () { $scope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function populateContentSections(notificationText) { logger.debug('populateContentSections -> notificationText', notificationText); return { sections: { notification_text: notificationText } }; } function sendEmailCampaign(contentSections) { notify.progress(dontSend ? ('Preparing to complete ' + campaignName + ' in Mailchimp') : ('Sending ' + campaignName)); return MailchimpConfig.getConfig() .then(function (config) { var replyToRole = $scope.notification.signoffAs.value || 'secretary'; logger.debug('replyToRole', replyToRole); var members; var list = $scope.notification.list; var otherOptions = { from_name: CommitteeReferenceData.contactUsField(replyToRole, 'fullName'), from_email: CommitteeReferenceData.contactUsField(replyToRole, 'email'), list_id: config.mailchimp.lists[list] }; logger.debug('Sending ' + campaignName, 'with otherOptions', otherOptions); var segmentId = config.mailchimp.segments[list].committeeSegmentId; var campaignId = $scope.notification.campaignId; switch ($scope.notification.destinationType) { case 'custom': members = $scope.notification.recipients; break; case 'committee': members = $scope.userEdits.allCommitteeList(); break; default: members = []; break; } logger.debug('sendCommitteeNotification:notification->', $scope.notification); if (members.length === 0) { logger.debug('about to replicateAndSendWithOptions to', list, 'list with campaignName', campaignName, 'campaign Id', campaignId, 'dontSend', dontSend); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); } else { var segmentName = MailchimpSegmentService.formatSegmentName('Committee Notification Recipients'); return MailchimpSegmentService.saveSegment(list, {segmentId: segmentId}, members, segmentName, $scope.members) .then(function (segmentResponse) { logger.debug('segmentResponse following save segment of segmentName:', segmentName, '->', segmentResponse); logger.debug('about to replicateAndSendWithOptions to committee with campaignName', campaignName, 'campaign Id', campaignId, 'segmentId', segmentResponse.segment.id); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, segmentId: segmentResponse.segment.id, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); }); } }) } function openInMailchimpIf(dontSend) { return function (replicateCampaignResponse) { logger.debug('openInMailchimpIf:replicateCampaignResponse', replicateCampaignResponse, 'dontSend', dontSend); if (dontSend) { return $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/wizard/neapolitan?id=" + replicateCampaignResponse.web_id, '_blank'); } else { return true; } } } function notifyEmailSendComplete() { if (!$scope.userEdits.cancelled) { notify.success('Sending of ' + campaignName + ' was successful.', false); $scope.userEdits.sendInProgress = false; $scope.cancelSendNotification(); } notify.clearBusy(); } }; $scope.completeInMailchimp = function () { notify.warning({ title: 'Complete in Mailchimp', message: 'You can close this dialog now as the message was presumably completed and sent in Mailchimp' }); $scope.confirmSendNotification(true); }; $scope.cancelSendNotification = function () { if ($scope.userEdits.sendInProgress) { $scope.userEdits.sendInProgress = false; $scope.userEdits.cancelled = true; notify.error({ title: 'Cancelling during send', message: "Because notification sending was already in progress when you cancelled, campaign may have already been sent - check in Mailchimp if in doubt." }); } else { logger.debug('calling cancelSendNotification'); close(); } }; var promises = [ MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) { $scope.members = members; logger.debug('refreshMembers -> populated ->', $scope.members.length, 'members'); $scope.selectableRecipients = _.chain(members) .map(toSelectGeneralMember) .sortBy(function (member) { return member.order + member.text }) .value(); logger.debug('refreshMembers -> populated ->', $scope.selectableRecipients.length, 'selectableRecipients'); }), MailchimpConfig.getConfig() .then(function (config) { $scope.config = config; logger.debug('retrieved config', $scope.config); $scope.clearRecipientsForCampaignOfType('committee'); }), MailchimpCampaignService.list({ limit: 1000, concise: true, status: 'save', title: 'Master' }).then(function (response) { $scope.campaigns = response.data; logger.debug('response.data', response.data); })]; if (!$scope.committeeFile) promises.push(populateGroupEvents()); $q.all(promises).then(function () { logger.debug('performed total of', promises.length); notify.clearBusy(); }); }] ); /* concatenated from client/src/app/js/committee.js */ angular.module('ekwgApp') .controller('CommitteeController', ["$rootScope", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MAILCHIMP_APP_CONSTANTS", "MailchimpConfig", "Notifier", "EKWGFileUpload", "CommitteeQueryService", "CommitteeReferenceData", "ModalService", function ($rootScope, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService, MAILCHIMP_APP_CONSTANTS, MailchimpConfig, Notifier, EKWGFileUpload, CommitteeQueryService, CommitteeReferenceData, ModalService) { var logger = $log.getInstance('CommitteeController'); $log.logLevels['CommitteeController'] = $log.LEVEL.OFF; var notify = Notifier($scope); notify.setBusy(); $scope.emailingInProgress = false; $scope.committeeFileBaseUrl = ContentMetaDataService.baseUrl('committeeFiles'); $scope.destinationType = ''; $scope.members = []; $scope.committeeFiles = []; $scope.alertMessages = []; $scope.allowConfirmDelete = false; $scope.latestYearOpen = true; $scope.committeeReferenceData = CommitteeReferenceData; $scope.selected = { addingNewFile: false, committeeFiles: [] }; $rootScope.$on('CommitteeReferenceDataReady', function () { assignFileTypes(); }); function assignFileTypes() { $scope.fileTypes = CommitteeReferenceData.fileTypes; logger.debug('CommitteeReferenceDataReady -> fileTypes ->', $scope.fileTypes); } $scope.userEdits = { saveInProgress: false }; $scope.showAlertMessage = function () { return ($scope.alert.class === 'alert-danger') || $scope.emailingInProgress; }; $scope.latestYear = function () { return CommitteeQueryService.latestYear($scope.committeeFiles) }; $scope.committeeFilesForYear = function (year) { return CommitteeQueryService.committeeFilesForYear(year, $scope.committeeFiles) }; $scope.isActive = function (committeeFile) { return committeeFile === $scope.selected.committeeFile; }; $scope.eventDateCalendar = { open: function ($event) { $scope.eventDateCalendar.opened = true; } }; $scope.allowSend = function () { return LoggedInMemberService.allowFileAdmin(); }; $scope.allowAddCommitteeFile = function () { return $scope.fileTypes && LoggedInMemberService.allowFileAdmin(); }; $scope.allowEditCommitteeFile = function (committeeFile) { return $scope.allowAddCommitteeFile() && committeeFile && committeeFile.$id(); }; $scope.allowDeleteCommitteeFile = function (committeeFile) { return $scope.allowEditCommitteeFile(committeeFile); }; $scope.cancelFileChange = function () { $q.when($scope.hideCommitteeFileDialog()).then(refreshCommitteeFiles).then(notify.clearBusy); }; $scope.saveCommitteeFile = function () { $scope.userEdits.saveInProgress = true; $scope.selected.committeeFile.eventDate = DateUtils.asValueNoTime($scope.selected.committeeFile.eventDate); logger.debug('saveCommitteeFile ->', $scope.selected.committeeFile); return $scope.selected.committeeFile.$saveOrUpdate(notify.success, notify.success, notify.error, notify.error) .then($scope.hideCommitteeFileDialog) .then(refreshCommitteeFiles) .then(notify.clearBusy) .catch(handleError); function handleError(errorResponse) { $scope.userEdits.saveInProgress = false; notify.error({ title: 'Your changes could not be saved', message: (errorResponse && errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } }; var defaultCommitteeFile = function () { return _.clone({ "createdDate": DateUtils.nowAsValue(), "fileType": $scope.fileTypes && $scope.fileTypes[0].description, "fileNameData": {} }) }; function removeDeleteOrAddOrInProgressFlags() { $scope.allowConfirmDelete = false; $scope.selected.addingNewFile = false; $scope.userEdits.saveInProgress = false; } $scope.deleteCommitteeFile = function () { $scope.allowConfirmDelete = true; }; $scope.cancelDeleteCommitteeFile = function () { removeDeleteOrAddOrInProgressFlags(); }; $scope.confirmDeleteCommitteeFile = function () { $scope.userEdits.saveInProgress = true; function showCommitteeFileDeleted() { return notify.success('File was deleted successfully'); } $scope.selected.committeeFile.$remove(showCommitteeFileDeleted, showCommitteeFileDeleted, notify.error, notify.error) .then($scope.hideCommitteeFileDialog) .then(refreshCommitteeFiles) .then(removeDeleteOrAddOrInProgressFlags) .then(notify.clearBusy); }; $scope.selectCommitteeFile = function (committeeFile, committeeFiles) { if (!$scope.selected.addingNewFile) { $scope.selected.committeeFile = committeeFile; $scope.selected.committeeFiles = committeeFiles; } }; $scope.editCommitteeFile = function () { removeDeleteOrAddOrInProgressFlags(); delete $scope.uploadedFile; $('#file-detail-dialog').modal('show'); }; $scope.openMailchimp = function () { $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns", '_blank'); }; $scope.openSettings = function () { ModalService.showModal({ templateUrl: "partials/committee/notification-settings-dialog.html", controller: "CommitteeNotificationSettingsController", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; $scope.sendNotification = function (committeeFile) { ModalService.showModal({ templateUrl: "partials/committee/send-notification-dialog.html", controller: "CommitteeNotificationsController", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, inputs: { committeeFile: committeeFile } }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; $scope.cancelSendNotification = function () { $('#send-notification-dialog').modal('hide'); $scope.resubmit = false; }; $scope.addCommitteeFile = function ($event) { $event.stopPropagation(); $scope.selected.addingNewFile = true; var committeeFile = new CommitteeFileService(defaultCommitteeFile()); $scope.selected.committeeFiles.push(committeeFile); $scope.selected.committeeFile = committeeFile; logger.debug('addCommitteeFile:', committeeFile, 'of', $scope.selected.committeeFiles.length, 'files'); $scope.editCommitteeFile(); }; $scope.hideCommitteeFileDialog = function () { removeDeleteOrAddOrInProgressFlags(); $('#file-detail-dialog').modal('hide'); }; $scope.attachFile = function (file) { $scope.oldTitle = $scope.selected.committeeFile.fileNameData ? $scope.selected.committeeFile.fileNameData.title : file.name; logger.debug('then:attachFile:oldTitle', $scope.oldTitle); $('#hidden-input').click(); }; $scope.onFileSelect = function (file) { if (file) { $scope.userEdits.saveInProgress = true; logger.debug('onFileSelect:file:about to upload ->', file); $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, 'committeeFiles') .then(function (fileNameData) { logger.debug('onFileSelect:file:upload complete -> fileNameData', fileNameData); $scope.selected.committeeFile.fileNameData = fileNameData; $scope.selected.committeeFile.fileNameData.title = $scope.oldTitle || file.name; $scope.userEdits.saveInProgress = false; }); } }; $scope.attachmentTitle = function () { return ($scope.selected.committeeFile && _.isEmpty($scope.selected.committeeFile.fileNameData) ? 'Attach' : 'Replace') + ' File'; }; $scope.fileUrl = function (committeeFile) { return committeeFile && committeeFile.fileNameData ? URLService.baseUrl() + $scope.committeeFileBaseUrl + '/' + committeeFile.fileNameData.awsFileName : ''; }; $scope.fileTitle = function (committeeFile) { return committeeFile ? DateUtils.asString(committeeFile.eventDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + committeeFile.fileNameData.title : ''; }; $scope.iconFile = function (committeeFile) { if (!committeeFile.fileNameData) return undefined; function fileExtensionIs(fileName, extensions) { return _.contains(extensions, fileExtension(fileName)); } function fileExtension(fileName) { return fileName ? _.last(fileName.split('.')).toLowerCase() : ''; } if (fileExtensionIs(committeeFile.fileNameData.awsFileName, ['doc', 'docx', 'jpg', 'pdf', 'ppt', 'png', 'txt', 'xls', 'xlsx'])) { return 'icon-' + fileExtension(committeeFile.fileNameData.awsFileName).substring(0, 3) + '.jpg'; } else { return 'icon-default.jpg'; } }; $scope.$on('memberLoginComplete', function () { refreshAll(); }); $scope.$on('memberLogoutComplete', function () { refreshAll(); }); function refreshMembers() { function assignMembersToScope(members) { $scope.members = members; return $scope.members; } if (LoggedInMemberService.allowFileAdmin()) { return MemberService.all() .then(assignMembersToScope); } } function refreshCommitteeFiles() { CommitteeQueryService.committeeFiles(notify).then(function (files) { logger.debug('committeeFiles', files); if (URLService.hasRouteParameter('committeeFileId')) { $scope.committeeFiles = _.filter(files, function (file) { return file.$id() === $routeParams.committeeFileId; }); } else { $scope.committeeFiles = files; } $scope.committeeFileYears = CommitteeQueryService.committeeFileYears($scope.committeeFiles); }); } function refreshAll() { refreshCommitteeFiles(); refreshMembers(); } assignFileTypes(); refreshAll(); }]); /* concatenated from client/src/app/js/committeeData.js */ angular.module('ekwgApp') .factory('CommitteeConfig', ["Config", function (Config) { function getConfig() { return Config.getConfig('committee', { committee: { contactUs: { chairman: {description: 'Chairman', fullName: 'Claire Mansfield', email: 'chairman@ekwg.co.uk'}, secretary: {description: 'Secretary', fullName: 'Kerry O\'Grady', email: 'secretary@ekwg.co.uk'}, treasurer: {description: 'Treasurer', fullName: 'Marianne Christensen', email: 'treasurer@ekwg.co.uk'}, membership: {description: 'Membership', fullName: 'Desiree Nel', email: 'membership@ekwg.co.uk'}, social: {description: 'Social Co-ordinator', fullName: 'Suzanne Graham Beer', email: 'social@ekwg.co.uk'}, walks: {description: 'Walks Co-ordinator', fullName: 'Stuart Maisner', email: 'walks@ekwg.co.uk'}, support: {description: 'Technical Support', fullName: 'Nick Barrett', email: 'nick.barrett@ekwg.co.uk'} }, fileTypes: [ {description: "AGM Agenda", public: true}, {description: "AGM Minutes", public: true}, {description: "Committee Meeting Agenda"}, {description: "Committee Meeting Minutes"}, {description: "Financial Statements", public: true} ] } }) } function saveConfig(config, saveCallback, errorSaveCallback) { return Config.saveConfig('committee', config, saveCallback, errorSaveCallback); } return { getConfig: getConfig, saveConfig: saveConfig } }]) .factory('CommitteeFileService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('committeeFiles'); }]) .factory('CommitteeReferenceData', ["$rootScope", function ($rootScope) { var refData = { contactUsRoles: function () { var keys = _.keys(refData.contactUs); if (keys.length > 0) { return keys; } }, contactUsField: function (role, field) { return refData.contactUs && refData.contactUs[role][field] }, fileTypesField: function (type, field) { return refData.fileTypes && refData.fileTypes[type][field] }, toFileType: function (fileTypeDescription, fileTypes) { return _.find(fileTypes, {description: fileTypeDescription}); }, contactUsRolesAsArray: function () { return _.map(refData.contactUs, function (data, type) { return { type: type, fullName: data.fullName, memberId: data.memberId, description: data.description + ' (' + data.fullName + ')', email: data.email }; }); } }; $rootScope.$on('CommitteeReferenceDataReady', function () { refData.ready = true; }); return refData; }]) .factory('CommitteeQueryService', ["$q", "$log", "$filter", "$routeParams", "URLService", "CommitteeFileService", "CommitteeReferenceData", "DateUtils", "LoggedInMemberService", "WalksService", "SocialEventsService", function ($q, $log, $filter, $routeParams, URLService, CommitteeFileService, CommitteeReferenceData, DateUtils, LoggedInMemberService, WalksService, SocialEventsService) { var logger = $log.getInstance('CommitteeQueryService'); $log.logLevels['CommitteeQueryService'] = $log.LEVEL.OFF; function groupEvents(groupEvents) { logger.debug('groupEvents', groupEvents); var fromDate = DateUtils.convertDateField(groupEvents.fromDate); var toDate = DateUtils.convertDateField(groupEvents.toDate); logger.debug('groupEvents:fromDate', $filter('displayDate')(fromDate), 'toDate', $filter('displayDate')(toDate)); var events = []; var promises = []; if (groupEvents.includeWalks) promises.push( WalksService.query({walkDate: {$gte: fromDate, $lte: toDate}}) .then(function (walks) { return _.map(walks, function (walk) { return events.push({ id: walk.$id(), selected: true, eventType: 'Walk', area: 'walks', type: 'walk', eventDate: walk.walkDate, eventTime: walk.startTime, distance: walk.distance, postcode: walk.postcode, title: walk.briefDescriptionAndStartPoint || 'Awaiting walk details', description: walk.longerDescription, contactName: walk.displayName || 'Awaiting walk leader', contactPhone: walk.contactPhone, contactEmail: walk.contactEmail }); }) })); if (groupEvents.includeCommitteeEvents) promises.push( CommitteeFileService.query({eventDate: {$gte: fromDate, $lte: toDate}}) .then(function (committeeFiles) { return _.map(committeeFiles, function (committeeFile) { return events.push({ id: committeeFile.$id(), selected: true, eventType: 'AGM & Committee', area: 'committee', type: 'committeeFile', eventDate: committeeFile.eventDate, postcode: committeeFile.postcode, description: committeeFile.fileType, title: committeeFile.fileNameData.title }); }) })); if (groupEvents.includeSocialEvents) promises.push( SocialEventsService.query({eventDate: {$gte: fromDate, $lte: toDate}}) .then(function (socialEvents) { return _.map(socialEvents, function (socialEvent) { return events.push({ id: socialEvent.$id(), selected: true, eventType: 'Social Event', area: 'social', type: 'socialEvent', eventDate: socialEvent.eventDate, eventTime: socialEvent.eventTimeStart, postcode: socialEvent.postcode, title: socialEvent.briefDescription, description: socialEvent.longerDescription, contactName: socialEvent.displayName, contactPhone: socialEvent.contactPhone, contactEmail: socialEvent.contactEmail }); }) })); return $q.all(promises).then(function () { logger.debug('performed total of', promises.length, 'events of length', events.length); return _.chain(events) .sortBy('eventDate') .value(); }); } function committeeFilesLatestFirst(committeeFiles) { return _.chain(committeeFiles) .sortBy('eventDate') .reverse() .value(); } function latestYear(committeeFiles) { return _.first( _.chain(committeeFilesLatestFirst(committeeFiles)) .pluck('eventDate') .map(function (eventDate) { return parseInt(DateUtils.asString(eventDate, undefined, 'YYYY')); }) .value()); } function committeeFilesForYear(year, committeeFiles) { var latestYearValue = latestYear(committeeFiles); return _.filter(committeeFilesLatestFirst(committeeFiles), function (committeeFile) { var fileYear = extractYear(committeeFile); return (fileYear === year) || (!fileYear && (latestYearValue === year)); }); } function extractYear(committeeFile) { return parseInt(DateUtils.asString(committeeFile.eventDate, undefined, 'YYYY')); } function committeeFileYears(committeeFiles) { var latestYearValue = latestYear(committeeFiles); function addLatestYearFlag(committeeFileYear) { return {year: committeeFileYear, latestYear: latestYearValue === committeeFileYear}; } var years = _.chain(committeeFiles) .map(extractYear) .unique() .sort() .map(addLatestYearFlag) .reverse() .value(); logger.debug('committeeFileYears', years); return years.length === 0 ? [{year: latestYear(committeeFiles), latestYear: true}] : years; } function committeeFiles(notify) { notify.progress('Refreshing Committee files...'); function queryCommitteeFiles() { if (URLService.hasRouteParameter('committeeFileId')) { return CommitteeFileService.getById($routeParams.committeeFileId) .then(function (committeeFile) { if (!committeeFile) notify.error('Committee file could not be found. Try opening again from the link in the notification email'); return [committeeFile]; }); } else { return CommitteeFileService.all().then(function (files) { return filterCommitteeFiles(files); }); } } return queryCommitteeFiles() .then(function (committeeFiles) { notify.progress('Found ' + committeeFiles.length + ' committee file(s)'); notify.setReady(); return _.chain(committeeFiles) .sortBy('fileDate') .reverse() .sortBy('createdDate') .value(); }, notify.error); } function filterCommitteeFiles(files) { logger.debug('filterCommitteeFiles files ->', files); var filteredFiles = _.filter(files, function (file) { return CommitteeReferenceData.fileTypes && CommitteeReferenceData.toFileType(file.fileType, CommitteeReferenceData.fileTypes).public || LoggedInMemberService.allowCommittee() || LoggedInMemberService.allowFileAdmin(); }); logger.debug('filterCommitteeFiles in ->', files && files.length, 'out ->', filteredFiles.length, 'CommitteeReferenceData.fileTypes', CommitteeReferenceData.fileTypes); return filteredFiles } return { groupEvents: groupEvents, committeeFiles: committeeFiles, latestYear: latestYear, committeeFileYears: committeeFileYears, committeeFilesForYear: committeeFilesForYear } }] ); /* concatenated from client/src/app/js/committeeNotificationSettingsController.js */ angular.module('ekwgApp') .controller('CommitteeNotificationSettingsController', ["$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MAILCHIMP_APP_CONSTANTS", "MailchimpConfig", "Notifier", "close", function ($window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService, MAILCHIMP_APP_CONSTANTS, MailchimpConfig, Notifier, close) { var logger = $log.getInstance('CommitteeNotificationSettingsController'); $log.logLevels['CommitteeNotificationSettingsController'] = $log.LEVEL.OFF; $scope.notify = {}; $scope.campaigns = []; var notify = Notifier($scope.notify); var campaignSearchTerm = 'Master'; notify.setBusy(); notify.progress({ title: 'Mailchimp Campaigns', message: 'Getting campaign information matching "' + campaignSearchTerm + '"' }); $scope.notReady = function () { return $scope.campaigns.length === 0; }; MailchimpConfig.getConfig() .then(function (config) { $scope.config = config; logger.debug('retrieved config', $scope.config); }); MailchimpCampaignService.list({ limit: 1000, concise: true, status: 'save', title: campaignSearchTerm }).then(function (response) { $scope.campaigns = response.data; logger.debug('response.data', response.data); notify.success({ title: 'Mailchimp Campaigns', message: 'Found ' + $scope.campaigns.length + ' draft campaigns matching "' + campaignSearchTerm + '"' }); notify.clearBusy(); }); $scope.editCampaign = function (campaignId) { if (!campaignId) { notify.error({ title: 'Edit Mailchimp Campaign', message: 'Please select a campaign from the drop-down before choosing edit' }); } else { notify.hide(); var webId = _.find($scope.campaigns, function (campaign) { return campaign.id === campaignId; }).web_id; logger.debug('editCampaign:campaignId', campaignId, 'web_id', webId); $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/edit?id=" + webId, '_blank'); } }; $scope.save = function () { logger.debug('saving config', $scope.config); MailchimpConfig.saveConfig($scope.config).then(close).catch(notify.error); }; $scope.cancel = function () { close(); }; }] ); /* concatenated from client/src/app/js/contentMetaServices.js */ angular.module('ekwgApp') .factory('ContentMetaDataService', ["ContentMetaData", "$q", function (ContentMetaData, $q) { var baseUrl = function (metaDataPathSegment) { return '/aws/s3/' + metaDataPathSegment; }; var createNewMetaData = function (withDefaults) { if (withDefaults) { return {image: '/(select file)', text: '(Enter title here)'}; } else { return {}; } }; var getMetaData = function (contentMetaDataType) { var task = $q.defer(); ContentMetaData.query({contentMetaDataType: contentMetaDataType}, {limit: 1}) .then(function (results) { if (results && results.length > 0) { task.resolve(results[0]); } else { task.resolve(new ContentMetaData({ contentMetaDataType: contentMetaDataType, baseUrl: baseUrl(contentMetaDataType), files: [createNewMetaData(true)] })); } }, function (response) { task.reject('Query of contentMetaDataType for ' + contentMetaDataType + ' failed: ' + response); }); return task.promise; }; var saveMetaData = function (metaData, saveCallback, errorSaveCallback) { return metaData.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback, errorSaveCallback); }; return { baseUrl: baseUrl, getMetaData: getMetaData, createNewMetaData: createNewMetaData, saveMetaData: saveMetaData } }]) .factory('ContentMetaData', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('contentMetaData'); }]) .factory('ContentTextService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('contentText'); }]) .factory('ContentText', ["ContentTextService", function (ContentTextService) { function forName(name) { return ContentTextService.all().then(function (contentDocuments) { return _.findWhere(contentDocuments, {name: name}) || new ContentTextService({name: name}); }); } return {forName: forName} }]); /* concatenated from client/src/app/js/directives.js */ angular.module('ekwgApp') .directive('contactUs', ["$log", "$compile", "URLService", "CommitteeReferenceData", function ($log, $compile, URLService, CommitteeReferenceData) { var logger = $log.getInstance('contactUs'); $log.logLevels['contactUs'] = $log.LEVEL.OFF; function email(role) { return CommitteeReferenceData.contactUsField(role, 'email'); } function description(role) { return CommitteeReferenceData.contactUsField(role, 'description'); } function fullName(role) { return CommitteeReferenceData.contactUsField(role, 'fullName'); } function createHref(scope, role) { return '<a href="mailto:' + email(role) + '">' + (scope.text || email(role)) + '</a>'; } function createListItem(scope, role) { return '<li ' + 'style="' + 'font-weight: normal;' + 'padding: 4px 0px 4px 21px;' + 'list-style: none;' + 'background-image: url(' + URLService.baseUrl() + '/assets/images/ramblers/bull-green.png);' + 'background-position: 0px 9px;' + 'background-repeat: no-repeat no-repeat">' + fullName(role) + ' - ' + description(role) + ' - ' + '<a href="mailto:' + email(role) + '"' + 'style="' + 'background-color: transparent;' + 'color: rgb(120, 35, 39);' + 'text-decoration: none; ' + 'font-weight: bold; ' + 'background-position: initial; ' + 'background-repeat: initial;">' + (scope.text || email(role)) + '</a>' + '</li>'; } function expandRoles(scope) { var roles = scope.role ? scope.role.split(',') : CommitteeReferenceData.contactUsRoles(); logger.debug('role ->', scope.role, ' roles ->', roles); return _(roles).map(function (role) { if (scope.format === 'list') { return createListItem(scope, role); } else { return createHref(scope, role); } }).join('\n'); } function wrapInUL(scope) { if (scope.format === 'list') { return '<ul style="' + 'margin: 10px 0 0;' + 'padding: 0 0 10px 10px;' + 'font-weight: bold;' + 'background-image: url(' + URLService.baseUrl() + '/assets/images/ramblers/dot-darkgrey-hor.png);' + 'background-position: 0% 100%;' + 'background-repeat: repeat no-repeat;' + 'margin-bottom: 20px;"> ' + (scope.heading || '') + expandRoles(scope) + '</ul>'; } else { return expandRoles(scope); } } return { restrict: 'EA', replace: true, link: function (scope, element) { scope.$watch('name', function () { if (CommitteeReferenceData.ready) { var html = wrapInUL(scope); logger.debug('html before compile ->', html); element.html($compile(html)(scope)); } }); }, scope: { format: '@', text: '@', role: '@', heading: '@' } }; }]); /* concatenated from client/src/app/js/emailerService.js */ angular.module('ekwgApp') .factory('EmailSubscriptionService', ["$rootScope", "$log", "$http", "$q", "MemberService", "DateUtils", "MailchimpErrorParserService", function ($rootScope, $log, $http, $q, MemberService, DateUtils, MailchimpErrorParserService) { var logger = $log.getInstance('EmailSubscriptionService'); $log.logLevels['EmailSubscriptionService'] = $log.LEVEL.OFF; var resetAllBatchSubscriptions = function (members, subscribedState) { var deferredTask = $q.defer(); var savePromises = []; deferredTask.notify('Resetting Mailchimp subscriptions for ' + members.length + ' members'); _.each(members, function (member) { defaultMailchimpSettings(member, subscribedState); savePromises.push(member.$saveOrUpdate()); }); $q.all(savePromises).then(function () { deferredTask.notify('Reset of Mailchimp subscriptions completed. Next member save will resend all lists to Mailchimp'); MemberService.all().then(function (refreshedMembers) { deferredTask.resolve(refreshedMembers); }) }); }; function defaultMailchimpSettings(member, subscribedState) { member.mailchimpLists = { "walks": {"subscribed": subscribedState}, "socialEvents": {"subscribed": subscribedState}, "general": {"subscribed": subscribedState} } } function booleanToString(value) { return String(value || false); } function addMailchimpIdentifiersToRequest(member, listType, request) { var mailchimpIdentifiers = {email: {}}; mailchimpIdentifiers.email.email = member.email; if (member.mailchimpLists[listType].leid) { mailchimpIdentifiers.email.leid = member.mailchimpLists[listType].leid; } if (request) { return angular.extend(request, mailchimpIdentifiers); } else { return mailchimpIdentifiers.email; } } var createBatchSubscriptionForList = function (listType, members) { var deferredTask = $q.defer(); var progress = 'Sending ' + listType + ' member data to Mailchimp'; deferredTask.notify(progress); var batchedMembers = []; var subscriptionEntries = _.chain(members) .filter(function (member) { return includeMemberInSubscription(listType, member); }) .map(function (member) { batchedMembers.push(member); var request = { "merge_vars": { "FNAME": member.firstName, "LNAME": member.lastName, "MEMBER_NUM": member.membershipNumber, "MEMBER_EXP": DateUtils.displayDate(member.membershipExpiryDate), "USERNAME": member.userName, "PW_RESET": member.passwordResetId || '' } }; return addMailchimpIdentifiersToRequest(member, listType, request); }).value(); if (subscriptionEntries.length > 0) { var url = '/mailchimp/lists/' + listType + '/batchSubscribe'; logger.debug('sending', subscriptionEntries.length, listType, 'subscriptions to mailchimp', subscriptionEntries); $http({method: 'POST', url: url, data: subscriptionEntries}) .then(function (response) { var responseData = response.data; logger.debug('received response', responseData); var errorObject = MailchimpErrorParserService.extractError(responseData); if (errorObject.error) { var errorResponse = { message: 'Sending of ' + listType + ' list subscription to Mailchimp was not successful', error: errorObject.error }; deferredTask.reject(errorResponse); } else { var totalResponseCount = responseData.updates.concat(responseData.adds).concat(responseData.errors).length; deferredTask.notify('Send of ' + subscriptionEntries.length + ' ' + listType + ' members completed - processing ' + totalResponseCount + ' Mailchimp response(s)'); var savePromises = []; processValidResponses(listType, responseData.updates.concat(responseData.adds), batchedMembers, savePromises, deferredTask); processErrorResponses(listType, responseData.errors, batchedMembers, savePromises, deferredTask); $q.all(savePromises).then(function () { MemberService.all().then(function (refreshedMembers) { deferredTask.notify('Send of ' + subscriptionEntries.length + ' members to ' + listType + ' list completed with ' + responseData.add_count + ' member(s) added, ' + responseData.update_count + ' updated and ' + responseData.error_count + ' error(s)'); deferredTask.resolve(refreshedMembers); }) }); } }).catch(function (response) { var data = response.data; var errorMessage = 'Sending of ' + listType + ' member data to Mailchimp was not successful due to response: ' + data.trim(); logger.error(errorMessage); deferredTask.reject(errorMessage); }) } else { deferredTask.notify('No ' + listType + ' updates to send Mailchimp'); MemberService.all().then(function (refreshedMembers) { deferredTask.resolve(refreshedMembers); }); } return deferredTask.promise; }; function includeMemberInEmailList(listType, member) { if (member.email && member.mailchimpLists[listType].subscribed) { if (listType === 'socialEvents') { return member.groupMember && member.socialMember; } else { return member.groupMember; } } else { return false; } } function includeMemberInSubscription(listType, member) { return includeMemberInEmailList(listType, member) && !member.mailchimpLists[listType].updated; } function includeMemberInUnsubscription(listType, member) { if (!member || !member.groupMember) { return true; } else if (member.mailchimpLists) { if (listType === 'socialEvents') { return (!member.socialMember && member.mailchimpLists[listType].subscribed); } else { return (!member.mailchimpLists[listType].subscribed); } } else { return false; } } function includeSubscriberInUnsubscription(listType, allMembers, subscriber) { return includeMemberInUnsubscription(listType, responseToMember(listType, allMembers, subscriber)); } function resetUpdateStatusForMember(member) { // updated == false means not up to date with mail e.g. next list update will send this data to mailchimo member.mailchimpLists.walks.updated = false; member.mailchimpLists.socialEvents.updated = false; member.mailchimpLists.general.updated = false; } function responseToMember(listType, allMembers, mailchimpResponse) { return _(allMembers).find(function (member) { var matchedOnListSubscriberId = mailchimpResponse.leid && member.mailchimpLists[listType].leid && (mailchimpResponse.leid.toString() === member.mailchimpLists[listType].leid.toString()); var matchedOnLastReturnedEmail = member.mailchimpLists[listType].email && (mailchimpResponse.email.toLowerCase() === member.mailchimpLists[listType].email.toLowerCase()); var matchedOnCurrentEmail = member.email && mailchimpResponse.email.toLowerCase() === member.email.toLowerCase(); return (matchedOnListSubscriberId || matchedOnLastReturnedEmail || matchedOnCurrentEmail); }); } function findMemberAndMarkAsUpdated(listType, batchedMembers, response, deferredTask) { var member = responseToMember(listType, batchedMembers, response); if (member) { member.mailchimpLists[listType].leid = response.leid; member.mailchimpLists[listType].updated = true; // updated == true means up to date e.g. nothing to send to mailchimo member.mailchimpLists[listType].lastUpdated = DateUtils.nowAsValue(); member.mailchimpLists[listType].email = member.email; } else { deferredTask.notify('From ' + batchedMembers.length + ' members, could not find any member related to response ' + JSON.stringify(response)); } return member; } function processValidResponses(listType, validResponses, batchedMembers, savePromises, deferredTask) { _.each(validResponses, function (response) { var member = findMemberAndMarkAsUpdated(listType, batchedMembers, response, deferredTask); if (member) { delete member.mailchimpLists[listType].code; delete member.mailchimpLists[listType].error; deferredTask.notify('processing valid response for member ' + member.email); savePromises.push(member.$saveOrUpdate()); } }); } function processErrorResponses(listType, errorResponses, batchedMembers, savePromises, deferredTask) { _.each(errorResponses, function (response) { var member = findMemberAndMarkAsUpdated(listType, batchedMembers, response.email, deferredTask); if (member) { deferredTask.notify('processing error response for member ' + member.email); member.mailchimpLists[listType].code = response.code; member.mailchimpLists[listType].error = response.error; if (_.contains([210, 211, 212, 213, 214, 215, 220, 250], response.code)) member.mailchimpLists[listType].subscribed = false; savePromises.push(member.$saveOrUpdate()); } }); } return { responseToMember: responseToMember, defaultMailchimpSettings: defaultMailchimpSettings, createBatchSubscriptionForList: createBatchSubscriptionForList, resetAllBatchSubscriptions: resetAllBatchSubscriptions, resetUpdateStatusForMember: resetUpdateStatusForMember, addMailchimpIdentifiersToRequest: addMailchimpIdentifiersToRequest, includeMemberInSubscription: includeMemberInSubscription, includeMemberInEmailList: includeMemberInEmailList, includeSubscriberInUnsubscription: includeSubscriberInUnsubscription } }]); /* concatenated from client/src/app/js/expenses.js */ angular.module('ekwgApp') .controller('ExpensesController', ["$compile", "$log", "$timeout", "$sce", "$templateRequest", "$q", "$rootScope", "$location", "$routeParams", "$scope", "$filter", "DateUtils", "NumberUtils", "URLService", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "ExpenseClaimsService", "MailchimpSegmentService", "MailchimpCampaignService", "MailchimpConfig", "Notifier", "EKWGFileUpload", function ($compile, $log, $timeout, $sce, $templateRequest, $q, $rootScope, $location, $routeParams, $scope, $filter, DateUtils, NumberUtils, URLService, LoggedInMemberService, MemberService, ContentMetaDataService, ExpenseClaimsService, MailchimpSegmentService, MailchimpCampaignService, MailchimpConfig, Notifier, EKWGFileUpload) { var logger = $log.getInstance('ExpensesController'); var noLogger = $log.getInstance('ExpensesControllerNoLogger'); $log.logLevels['ExpensesControllerNoLogger'] = $log.LEVEL.OFF; $log.logLevels['ExpensesController'] = $log.LEVEL.OFF; const SELECTED_EXPENSE = 'Expense from last email link'; $scope.receiptBaseUrl = ContentMetaDataService.baseUrl('expenseClaims'); $scope.dataError = false; $scope.members = []; $scope.expenseClaims = []; $scope.unfilteredExpenseClaims = []; $scope.expensesOpen = URLService.hasRouteParameter('expenseId') || URLService.isArea('expenses'); $scope.alertMessages = []; $scope.filterTypes = [{ disabled: !$routeParams.expenseId, description: SELECTED_EXPENSE, filter: function (expenseClaim) { if ($routeParams.expenseId) { return expenseClaim && expenseClaim.$id() === $routeParams.expenseId; } else { return false; } } }, { description: 'Unpaid expenses', filter: function (expenseClaim) { return !$scope.expenseClaimStatus(expenseClaim).atEndpoint; } }, { description: 'Paid expenses', filter: function (expenseClaim) { return $scope.expenseClaimStatus(expenseClaim).atEndpoint; } }, { description: 'Expenses awaiting action from me', filter: function (expenseClaim) { return LoggedInMemberService.allowFinanceAdmin() ? editable(expenseClaim) : editableAndOwned(expenseClaim); } }, { description: 'All expenses', filter: function () { return true; } }]; $scope.selected = { showOnlyMine: !allowAdminFunctions(), saveInProgress: false, expenseClaimIndex: 0, expenseItemIndex: 0, expenseFilter: $scope.filterTypes[$routeParams.expenseId ? 0 : 1] }; $scope.itemAlert = {}; var notify = Notifier($scope); var notifyItem = Notifier($scope.itemAlert); notify.setBusy(); var notificationsBaseUrl = 'partials/expenses/notifications'; LoggedInMemberService.showLoginPromptWithRouteParameter('expenseId'); $scope.showArea = function (area) { URLService.navigateTo('admin', area) }; $scope.selected.expenseClaim = function () { try { return $scope.expenseClaims[$scope.selected.expenseClaimIndex]; } catch (e) { console.error(e); } }; $scope.isInactive = function (expenseClaim) { return expenseClaim !== $scope.selected.expenseClaim(); }; $scope.selected.expenseItem = function () { try { var expenseClaim = $scope.expenseClaims[$scope.selected.expenseClaimIndex]; return expenseClaim ? expenseClaim.expenseItems[$scope.selected.expenseItemIndex] : undefined; } catch (e) { console.error(e); } }; $scope.expenseTypes = [ {value: "travel-reccie", name: "Travel (walk reccie)", travel: true}, {value: "travel-committee", name: "Travel (attend committee meeting)", travel: true}, {value: "other", name: "Other"}]; var eventTypes = { created: {description: "Created", editable: true}, submitted: {description: "Submitted", actionable: true, notifyCreator: true, notifyApprover: true}, 'first-approval': {description: "First Approval", actionable: true, notifyApprover: true}, 'second-approval': { description: "Second Approval", actionable: true, notifyCreator: true, notifyApprover: true, notifyTreasurer: true }, returned: {description: "Returned", atEndpoint: false, editable: true, notifyCreator: true, notifyApprover: true}, paid: {description: "Paid", atEndpoint: true, notifyCreator: true, notifyApprover: true, notifyTreasurer: true} }; var defaultExpenseClaim = function () { return _.clone({ "cost": 0, "expenseItems": [], "expenseEvents": [] }) }; var defaultExpenseItem = function () { return _.clone({ expenseType: $scope.expenseTypes[0], "travel": { "costPerMile": 0.28, "miles": 0, "from": '', "to": '', "returnJourney": true } }); }; function editable(expenseClaim) { return memberCanEditClaim(expenseClaim) && $scope.expenseClaimStatus(expenseClaim).editable; } function editableAndOwned(expenseClaim) { return memberOwnsClaim(expenseClaim) && $scope.expenseClaimStatus(expenseClaim).editable; } $scope.editable = function () { return editable($scope.selected.expenseClaim()); }; $scope.allowClearError = function () { return URLService.hasRouteParameter('expenseId') && $scope.dataError; }; $scope.allowAddExpenseClaim = function () { return !$scope.dataError && !_.find($scope.unfilteredExpenseClaims, editableAndOwned); }; $scope.allowFinanceAdmin = function () { return LoggedInMemberService.allowFinanceAdmin(); }; $scope.allowEditExpenseItem = function () { return $scope.allowAddExpenseItem() && $scope.selected.expenseItem() && $scope.selected.expenseClaim().$id(); }; $scope.allowAddExpenseItem = function () { return $scope.editable(); }; $scope.allowDeleteExpenseItem = function () { return $scope.allowEditExpenseItem(); }; $scope.allowDeleteExpenseClaim = function () { return !$scope.allowDeleteExpenseItem() && $scope.allowAddExpenseItem(); }; $scope.allowSubmitExpenseClaim = function () { return $scope.allowEditExpenseItem() && !$scope.allowResubmitExpenseClaim(); }; function allowAdminFunctions() { return LoggedInMemberService.allowTreasuryAdmin() || LoggedInMemberService.allowFinanceAdmin(); } $scope.allowAdminFunctions = function () { return allowAdminFunctions(); }; $scope.allowReturnExpenseClaim = function () { return $scope.allowAdminFunctions() && $scope.selected.expenseClaim() && expenseClaimHasEventType($scope.selected.expenseClaim(), eventTypes.submitted) && !expenseClaimHasEventType($scope.selected.expenseClaim(), eventTypes.returned) && $scope.expenseClaimStatus($scope.selected.expenseClaim()).actionable; }; $scope.allowResubmitExpenseClaim = function () { return $scope.editable() && expenseClaimHasEventType($scope.selected.expenseClaim(), eventTypes.returned); }; $scope.allowPaidExpenseClaim = function () { return LoggedInMemberService.allowTreasuryAdmin() && _.contains( [eventTypes.submitted.description, eventTypes['second-approval'].description, eventTypes['first-approval'].description], $scope.expenseClaimLatestEvent().eventType.description); }; function activeEvents(optionalEvents) { var events = optionalEvents || $scope.selected.expenseClaim().expenseEvents; var latestReturnedEvent = _.find(events.reverse(), function (event) { return _.isEqual(event.eventType, $scope.expenseClaimStatus.returned); }); return latestReturnedEvent ? events.slice(events.indexOf(latestReturnedEvent + 1)) : events; } function expenseClaimHasEventType(expenseClaim, eventType) { if (!expenseClaim) return false; return eventForEventType(expenseClaim, eventType); } function eventForEventType(expenseClaim, eventType) { if (expenseClaim) return _.find(expenseClaim.expenseEvents, function (event) { return _.isEqual(event.eventType, eventType); }); } $scope.allowApproveExpenseClaim = function () { return false; }; $scope.lastApprovedByMe = function () { var approvalEvents = $scope.approvalEvents(); return approvalEvents.length > 0 && _.last(approvalEvents).memberId === LoggedInMemberService.loggedInMember().memberId; }; $scope.approvalEvents = function () { if (!$scope.selected.expenseClaim()) return []; return _.filter($scope.selected.expenseClaim().expenseEvents, function (event) { return _.isEqual(event.eventType, eventTypes['first-approval']) || _.isEqual(event.eventType, eventTypes['second-approval']); }); }; $scope.expenseClaimStatus = function (optionalExpenseClaim) { var expenseClaim = optionalExpenseClaim || $scope.selected.expenseClaim(); return $scope.expenseClaimLatestEvent(expenseClaim).eventType; }; $scope.expenseClaimLatestEvent = function (optionalExpenseClaim) { var expenseClaim = optionalExpenseClaim || $scope.selected.expenseClaim(); return expenseClaim ? _.last(expenseClaim.expenseEvents) : {}; }; $scope.nextApprovalStage = function () { var approvals = $scope.approvalEvents(); if (approvals.length === 0) { return 'First Approval'; } else if (approvals.length === 1) { return 'Second Approval' } else { return 'Already has ' + approvals.length + ' approvals!'; } }; $scope.confirmApproveExpenseClaim = function () { var approvals = $scope.approvalEvents(); notifyItem.hide(); if (approvals.length === 0) { createEventAndSendNotifications(eventTypes['first-approval']); } else if (approvals.length === 1) { createEventAndSendNotifications(eventTypes['second-approval']); } else { notify.error('This expense claim already has ' + approvals.length + ' approvals!'); } }; $scope.showAllExpenseClaims = function () { $scope.dataError = false; $location.path('/admin/expenses') }; $scope.addExpenseClaim = function () { $scope.expenseClaims.unshift(new ExpenseClaimsService(defaultExpenseClaim())); $scope.selectExpenseClaim(0); createEvent(eventTypes.created); $scope.addExpenseItem(); }; $scope.selectExpenseItem = function (index) { if ($scope.selected.saveInProgress) { noLogger.info('selectExpenseItem - selected.saveInProgress - not changing to index', index); } else { noLogger.info('selectExpenseItem:', index); $scope.selected.expenseItemIndex = index; } }; $scope.selectExpenseClaim = function (index) { if ($scope.selected.saveInProgress) { noLogger.info('selectExpenseClaim - selected.saveInProgress - not changing to index', index); } else { $scope.selected.expenseClaimIndex = index; var expenseClaim = $scope.selected.expenseClaim(); noLogger.info('selectExpenseClaim:', index, expenseClaim); } }; $scope.editExpenseItem = function () { $scope.removeConfirm(); delete $scope.uploadedFile; $('#expense-detail-dialog').modal('show'); }; $scope.hideExpenseClaim = function () { $scope.removeConfirm(); $('#expense-detail-dialog').modal('hide'); }; $scope.addReceipt = function () { $('#hidden-input').click(); }; $scope.removeReceipt = function () { delete $scope.selected.expenseItem().receipt; delete $scope.uploadedFile; }; $scope.receiptTitle = function (expenseItem) { return expenseItem && expenseItem.receipt ? (expenseItem.receipt.title || expenseItem.receipt.originalFileName) : ''; }; function baseUrl() { return _.first($location.absUrl().split('/#')); } $scope.receiptUrl = function (expenseItem) { return expenseItem && expenseItem.receipt ? baseUrl() + $scope.receiptBaseUrl + '/' + expenseItem.receipt.awsFileName : ''; }; $scope.onFileSelect = function (file) { if (file) { $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, 'expenseClaims') .then(function (fileNameData) { var expenseItem = $scope.selected.expenseItem(); var oldTitle = (expenseItem.receipt && expenseItem.receipt.title) ? receipt.title : undefined; expenseItem.receipt = fileNameData; expenseItem.receipt.title = oldTitle; }); } }; function createEvent(eventType, reason) { var expenseClaim = $scope.selected.expenseClaim(); if (!expenseClaim.expenseEvents) expenseClaim.expenseEvents = []; var event = { "date": DateUtils.nowAsValue(), "memberId": LoggedInMemberService.loggedInMember().memberId, "eventType": eventType }; if (reason) event.reason = reason; expenseClaim.expenseEvents.push(event); } $scope.addExpenseItem = function () { $scope.removeConfirm(); var newExpenseItem = defaultExpenseItem(); $scope.selected.expenseClaim().expenseItems.push(newExpenseItem); var index = $scope.selected.expenseClaim().expenseItems.indexOf(newExpenseItem); if (index > -1) { $scope.selectExpenseItem(index); $scope.editExpenseItem(); } else { showExpenseErrorAlert('Could not display new expense item') } }; $scope.expenseTypeChange = function () { logger.debug('$scope.selected.expenseItem().expenseType', $scope.selected.expenseItem().expenseType); if ($scope.selected.expenseItem().expenseType.travel) { if (!$scope.selected.expenseItem().travel) $scope.selected.expenseItem().travel = defaultExpenseItem().travel; } else { delete $scope.selected.expenseItem().travel; } $scope.setExpenseItemFields(); }; $scope.expenseDateCalendar = { open: function ($event) { $scope.expenseDateCalendar.opened = true; } }; function recalculateClaimCost() { $scope.selected.expenseClaim().cost = $filter('sumValues')($scope.selected.expenseClaim().expenseItems, 'cost'); } $scope.cancelExpenseChange = function () { $scope.refreshExpenses().then($scope.hideExpenseClaim).then(notify.clearBusy); }; function showExpenseErrorAlert(message) { var messageDefaulted = message || 'Please try this again.'; notify.error('Your expense claim could not be saved. ' + messageDefaulted); $scope.selected.saveInProgress = false; } function showExpenseEmailErrorAlert(message) { $scope.selected.saveInProgress = false; notify.error('Your expense claim email processing failed. ' + message); } function showExpenseProgressAlert(message, busy) { notify.progress(message, busy); } function showExpenseSuccessAlert(message, busy) { notify.success(message, busy); } $scope.saveExpenseClaim = function (optionalExpenseClaim) { $scope.selected.saveInProgress = true; function showExpenseSaved(data) { $scope.expenseClaims[$scope.selected.expenseClaimIndex] = data; $scope.selected.saveInProgress = false; return notify.success('Expense was saved successfully'); } showExpenseProgressAlert('Saving expense claim', true); $scope.setExpenseItemFields(); return (optionalExpenseClaim || $scope.selected.expenseClaim()).$saveOrUpdate(showExpenseSaved, showExpenseSaved, showExpenseErrorAlert, showExpenseErrorAlert) .then($scope.hideExpenseClaim) .then(notify.clearBusy); }; $scope.approveExpenseClaim = function () { $scope.confirmAction = {approve: true}; if ($scope.lastApprovedByMe()) notifyItem.warning({ title: 'Duplicate approval warning', message: 'You were the previous approver, therefore ' + $scope.nextApprovalStage() + ' ought to be carried out by someone else. Are you sure you want to do this?' }); }; $scope.deleteExpenseClaim = function () { $scope.confirmAction = {delete: true}; }; $scope.deleteExpenseItem = function () { $scope.confirmAction = {delete: true}; }; $scope.confirmDeleteExpenseItem = function () { $scope.selected.saveInProgress = true; showExpenseProgressAlert('Deleting expense item', true); var expenseItem = $scope.selected.expenseItem(); logger.debug('removing', expenseItem); var index = $scope.selected.expenseClaim().expenseItems.indexOf(expenseItem); if (index > -1) { $scope.selected.expenseClaim().expenseItems.splice(index, 1); } else { showExpenseErrorAlert('Could not delete expense item') } $scope.selectExpenseItem(0); recalculateClaimCost(); $scope.saveExpenseClaim() .then($scope.removeConfirm) .then(notify.clearBusy); }; $scope.removeConfirm = function () { delete $scope.confirmAction; showExpenseSuccessAlert(); }; $scope.confirmDeleteExpenseClaim = function () { showExpenseProgressAlert('Deleting expense claim', true); function showExpenseDeleted() { return showExpenseSuccessAlert('Expense was deleted successfully'); } $scope.selected.expenseClaim().$remove(showExpenseDeleted, showExpenseDeleted, showExpenseErrorAlert, showExpenseErrorAlert) .then($scope.hideExpenseClaim) .then(showExpenseDeleted) .then($scope.refreshExpenses) .then($scope.removeConfirm) .then(notify.clearBusy); }; $scope.submitExpenseClaim = function (state) { $scope.resubmit = state; $('#submit-dialog').modal('show'); }; function hideSubmitDialog() { $('#submit-dialog').modal('hide'); $scope.resubmit = false; } $scope.cancelSubmitExpenseClaim = function () { hideSubmitDialog(); }; $scope.returnExpenseClaim = function () { $('#return-dialog').modal('show'); }; $scope.confirmReturnExpenseClaim = function (reason) { hideReturnDialog(); return createEventAndSendNotifications(eventTypes.returned, reason); }; function hideReturnDialog() { $('#return-dialog').modal('hide'); } $scope.cancelReturnExpenseClaim = function () { hideReturnDialog(); }; $scope.paidExpenseClaim = function () { $('#paid-dialog').modal('show'); }; $scope.confirmPaidExpenseClaim = function () { createEventAndSendNotifications(eventTypes.paid) .then(hidePaidDialog); }; function hidePaidDialog() { $('#paid-dialog').modal('hide'); } $scope.cancelPaidExpenseClaim = function () { hidePaidDialog(); }; $scope.confirmSubmitExpenseClaim = function () { if ($scope.resubmit) $scope.selected.expenseClaim().expenseEvents = [eventForEventType($scope.selected.expenseClaim(), eventTypes.created)]; createEventAndSendNotifications(eventTypes.submitted); }; $scope.resubmitExpenseClaim = function () { $scope.submitExpenseClaim(true); }; $scope.expenseClaimCreatedEvent = function (optionalExpenseClaim) { return eventForEventType(optionalExpenseClaim || $scope.selected.expenseClaim(), eventTypes.created); }; function createEventAndSendNotifications(eventType, reason) { notify.setBusy(); $scope.selected.saveInProgress = true; var expenseClaim = $scope.selected.expenseClaim(); var expenseClaimCreatedEvent = $scope.expenseClaimCreatedEvent(expenseClaim); return $q.when(createEvent(eventType, reason)) .then(sendNotificationsToAllRoles, showExpenseEmailErrorAlert) .then($scope.saveExpenseClaim, showExpenseEmailErrorAlert, showExpenseProgressAlert); function renderTemplateContent(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction($scope); $timeout(function () { $scope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function sendNotificationsToAllRoles() { return LoggedInMemberService.getMemberForMemberId(expenseClaimCreatedEvent.memberId) .then(function (member) { logger.debug('sendNotification:', 'memberId', expenseClaimCreatedEvent.memberId, 'member', member); var memberFullName = $filter('fullNameWithAlias')(member); return $q.when(showExpenseProgressAlert('Preparing to email ' + memberFullName)) .then(hideSubmitDialog, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(sendCreatorNotifications, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(sendApproverNotifications, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(sendTreasurerNotifications, showExpenseEmailErrorAlert, showExpenseProgressAlert); function sendCreatorNotifications() { if (eventType.notifyCreator) return sendNotificationsTo({ templateUrl: templateForEvent('creator', eventType), memberIds: [expenseClaimCreatedEvent.memberId], segmentType: 'directMail', segmentNameSuffix: '', destination: 'creator' }); return false; } function sendApproverNotifications() { if (eventType.notifyApprover) return sendNotificationsTo({ templateUrl: templateForEvent('approver', eventType), memberIds: MemberService.allMemberIdsWithPrivilege('financeAdmin', $scope.members), segmentType: 'expenseApprover', segmentNameSuffix: 'approval ', destination: 'approvers' }); return false; } function sendTreasurerNotifications() { if (eventType.notifyTreasurer) return sendNotificationsTo({ templateUrl: templateForEvent('treasurer', eventType), memberIds: MemberService.allMemberIdsWithPrivilege('treasuryAdmin', $scope.members), segmentType: 'expenseTreasurer', segmentNameSuffix: 'payment ', destination: 'treasurer' }); return false; } function templateForEvent(role, eventType) { return notificationsBaseUrl + '/' + role + '/' + eventType.description.toLowerCase().replace(' ', '-') + '-notification.html'; } function sendNotificationsTo(templateAndNotificationMembers) { logger.debug('sendNotificationsTo:', templateAndNotificationMembers); var campaignName = 'Expense ' + eventType.description + ' notification (to ' + templateAndNotificationMembers.destination + ')'; var campaignNameAndMember = campaignName + ' (' + memberFullName + ')'; var segmentName = 'Expense notification ' + templateAndNotificationMembers.segmentNameSuffix + '(' + memberFullName + ')'; if (templateAndNotificationMembers.memberIds.length === 0) throw new Error('No members have been configured as ' + templateAndNotificationMembers.destination + ' therefore notifications for this step will fail!!'); return $templateRequest($sce.getTrustedResourceUrl(templateAndNotificationMembers.templateUrl)) .then(renderTemplateContent) .then(populateContentSections) .then(sendNotification(templateAndNotificationMembers)) .catch(showExpenseEmailErrorAlert); function populateContentSections(expenseNotificationText) { return { sections: { expense_id_url: 'Please click <a href="' + baseUrl() + '/#/admin/expenseId/' + expenseClaim.$id() + '" target="_blank">this link</a> to see the details of the above expense claim, or to make changes to it.', expense_notification_text: expenseNotificationText } }; } function sendNotification(templateAndNotificationMembers) { return function (contentSections) { return createOrSaveMailchimpSegment() .then(saveSegmentDataToMember, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(sendEmailCampaign, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(notifyEmailSendComplete, showExpenseEmailErrorAlert, showExpenseSuccessAlert); function createOrSaveMailchimpSegment() { return MailchimpSegmentService.saveSegment('general', {segmentId: MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType)}, templateAndNotificationMembers.memberIds, segmentName, $scope.members); } function saveSegmentDataToMember(segmentResponse) { MailchimpSegmentService.setMemberSegmentId(member, templateAndNotificationMembers.segmentType, segmentResponse.segment.id); return LoggedInMemberService.saveMember(member); } function sendEmailCampaign() { showExpenseProgressAlert('Sending ' + campaignNameAndMember); return MailchimpConfig.getConfig() .then(function (config) { var campaignId = config.mailchimp.campaigns.expenseNotification.campaignId; var segmentId = MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType); logger.debug('about to replicateAndSendWithOptions with campaignName', campaignNameAndMember, 'campaign Id', campaignId, 'segmentId', segmentId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignNameAndMember, contentSections: contentSections, segmentId: segmentId }); }) .then(function () { showExpenseProgressAlert('Sending of ' + campaignNameAndMember + ' was successful', true); }); } function notifyEmailSendComplete() { showExpenseSuccessAlert('Sending of ' + campaignName + ' was successful. Check your inbox for progress.'); } } } } }); } } $scope.setExpenseItemFields = function () { var expenseItem = $scope.selected.expenseItem(); if (expenseItem) { expenseItem.expenseDate = DateUtils.asValueNoTime(expenseItem.expenseDate); if (expenseItem.travel) expenseItem.travel.miles = NumberUtils.asNumber(expenseItem.travel.miles); expenseItem.description = expenseItemDescription(expenseItem); expenseItem.cost = expenseItemCost(expenseItem); } recalculateClaimCost(); }; $scope.prefixedExpenseItemDescription = function (expenseItem) { if (!expenseItem) return ''; var prefix = expenseItem.expenseType && expenseItem.expenseType.travel ? expenseItem.expenseType.name + ' - ' : ''; return prefix + expenseItem.description; }; function expenseItemDescription(expenseItem) { var description; if (!expenseItem) return ''; if (expenseItem.travel && expenseItem.expenseType.travel) { description = [ expenseItem.travel.from, 'to', expenseItem.travel.to, expenseItem.travel.returnJourney ? 'return trip' : 'single trip', '(' + expenseItem.travel.miles, 'miles', expenseItem.travel.returnJourney ? 'x 2' : '', 'x', parseInt(expenseItem.travel.costPerMile * 100) + 'p per mile)' ].join(' '); } else { description = expenseItem.description; } return description; } function expenseItemCost(expenseItem) { var cost; if (!expenseItem) return 0; if (expenseItem.travel && expenseItem.expenseType.travel) { cost = (NumberUtils.asNumber(expenseItem.travel.miles) * (expenseItem.travel.returnJourney ? 2 : 1) * NumberUtils.asNumber(expenseItem.travel.costPerMile)); } else { cost = expenseItem.cost; } noLogger.info(cost, 'from expenseItem=', expenseItem); return NumberUtils.asNumber(cost, 2); } function refreshMembers() { if (LoggedInMemberService.memberLoggedIn()) { notify.progress('Refreshing member data...'); return MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) { logger.debug('refreshMembers: found', members.length, 'members'); return $scope.members = members; }); } } function memberCanEditClaim(expenseClaim) { if (!expenseClaim) return false; return memberOwnsClaim(expenseClaim) || LoggedInMemberService.allowFinanceAdmin(); } function memberOwnsClaim(expenseClaim) { if (!expenseClaim) return false; return (LoggedInMemberService.loggedInMember().memberId === $scope.expenseClaimCreatedEvent(expenseClaim).memberId); } $scope.refreshExpenses = function () { $scope.dataError = false; logger.debug('refreshExpenses started'); notify.setBusy(); notify.progress('Filtering for ' + $scope.selected.expenseFilter.description + '...'); logger.debug('refreshing expenseFilter', $scope.selected.expenseFilter); let noExpenseFound = function () { $scope.dataError = true; return notify.warning({ title: 'Expense claim could not be found', message: 'Try opening again from the link in the notification email, or click Show All Expense Claims' }) }; function query() { if ($scope.selected.expenseFilter.description === SELECTED_EXPENSE && $routeParams.expenseId) { return ExpenseClaimsService.getById($routeParams.expenseId) .then(function (expense) { if (!expense) { return noExpenseFound(); } else { return [expense]; } }) .catch(noExpenseFound); } else { return ExpenseClaimsService.all(); } } return query() .then(function (expenseClaims) { $scope.unfilteredExpenseClaims = []; $scope.expenseClaims = _.chain(expenseClaims).filter(function (expenseClaim) { return $scope.allowAdminFunctions() ? ($scope.selected.showOnlyMine ? memberOwnsClaim(expenseClaim) : true) : memberCanEditClaim(expenseClaim); }).filter(function (expenseClaim) { $scope.unfilteredExpenseClaims.push(expenseClaim); return $scope.selected.expenseFilter.filter(expenseClaim); }).sortBy(function (expenseClaim) { var expenseClaimLatestEvent = $scope.expenseClaimLatestEvent(expenseClaim); return expenseClaimLatestEvent ? expenseClaimLatestEvent.date : true; }).reverse().value(); let outcome = 'Found ' + $scope.expenseClaims.length + ' expense claim(s)'; notify.progress(outcome); logger.debug('refreshExpenses finished', outcome); notify.clearBusy(); return $scope.expenseClaims; }, notify.error) .catch(notify.error); }; $q.when(refreshMembers()) .then($scope.refreshExpenses) .then(notify.setReady) .catch(notify.error); }] ); /* concatenated from client/src/app/js/filters.js */ angular.module('ekwgApp') .factory('FilterUtils', function () { return { nameFilter: function (alias) { return alias ? 'fullNameWithAlias' : 'fullName'; } }; }) .filter('keepLineFeeds', function () { return function (input) { if (!input) return input; return input .replace(/(\r\n|\r|\n)/g, '<br/>') .replace(/\t/g, '&nbsp;&nbsp;&nbsp;') .replace(/ /g, '&nbsp;'); } }) .filter('lineFeedsToBreaks', function () { return function (input) { if (!input) return input; return input .replace(/(\r\n|\r|\n)/g, '<br/>') } }) .filter('displayName', function () { return function (member) { return member === undefined ? null : (member.firstName + ' ' + (member.hideSurname ? '' : member.lastName)).trim(); } }) .filter('fullName', function () { return function (member, defaultValue) { return member === undefined ? defaultValue || '(deleted member)' : (member.firstName + ' ' + member.lastName).trim(); } }) .filter('fullNameWithAlias', ["$filter", function ($filter) { return function (member, defaultValue) { return member ? ($filter('fullName')(member, defaultValue)) + (member.nameAlias ? ' (' + member.nameAlias + ')' : '') : defaultValue; } }]) .filter('fullNameWithAliasOrMe', ["$filter", "LoggedInMemberService", function ($filter, LoggedInMemberService) { return function (member, defaultValue, memberId) { return member ? (LoggedInMemberService.loggedInMember().memberId === member.$id() && member.$id() === memberId ? "Me" : ($filter('fullName')(member, defaultValue)) + (member.nameAlias ? ' (' + member.nameAlias + ')' : '')) : defaultValue; } }]) .filter('firstName', ["$filter", function ($filter) { return function (member, defaultValue) { return s.words($filter('fullName')(member, defaultValue))[0]; } }]) .filter('memberIdsToFullNames', ["$filter", function ($filter) { return function (memberIds, members, defaultValue) { return _(memberIds).map(function (memberId) { return $filter('memberIdToFullName')(memberId, members, defaultValue); }).join(', '); } }]) .filter('memberIdToFullName', ["$filter", "MemberService", "FilterUtils", function ($filter, MemberService, FilterUtils) { return function (memberId, members, defaultValue, alias) { return $filter(FilterUtils.nameFilter(alias))(MemberService.toMember(memberId, members), defaultValue); } }]) .filter('memberIdToFirstName', ["$filter", "MemberService", function ($filter, MemberService) { return function (memberId, members, defaultValue) { return $filter('firstName')(MemberService.toMember(memberId, members), defaultValue); } }]) .filter('asMoney', ["NumberUtils", function (NumberUtils) { return function (number) { return isNaN(number) ? '' : '£' + NumberUtils.asNumber(number).toFixed(2); } }]) .filter('humanize', function () { return function (string) { return s.humanize(string); } }) .filter('sumValues', ["NumberUtils", function (NumberUtils) { return function (items, propertyName) { return NumberUtils.sumValues(items, propertyName); } }]) .filter('walkSummary', ["$filter", function ($filter) { return function (walk) { return walk === undefined ? null : $filter('displayDate')(walk.walkDate) + " led by " + (walk.displayName || walk.contactName || "unknown") + " (" + (walk.briefDescriptionAndStartPoint || 'no description') + ')'; } }]) .filter('meetupEventSummary', ["$filter", function ($filter) { return function (meetupEvent) { return meetupEvent ? $filter('displayDate')(meetupEvent.startTime) + " (" + meetupEvent.title + ')' : null; } }]) .filter('asWalkEventType', ["WalksReferenceService", function (WalksReferenceService) { return function (eventTypeString, field) { var eventType = WalksReferenceService.toEventType(eventTypeString); return eventType && field ? eventType[field] : eventType; } }]) .filter('asEventNote', function () { return function (event) { return _.compact([event.description, event.reason]).join(', '); } }) .filter('asChangedItemsTooltip', ["$filter", function ($filter) { return function (event, members) { return _(event.data).map(function (value, key) { return s.humanize(key) + ': ' + $filter('toAuditDeltaValue')(value, key, members); }).join(', '); } }]) .filter('valueOrDefault', function () { return function (value, defaultValue) { return value || defaultValue || '(none)'; } }) .filter('toAuditDeltaValue', ["$filter", function ($filter) { return function (value, fieldName, members, defaultValue) { switch (fieldName) { case 'walkDate': return $filter('displayDate')(value); case 'walkLeaderMemberId': return $filter('memberIdToFullName')(value, members, defaultValue); default: return $filter('valueOrDefault')(value, defaultValue); } } }]) .filter('toAuditDeltaChangedItems', function () { return function (dataAuditDeltaInfoItems) { return _(dataAuditDeltaInfoItems).pluck('fieldName').map(s.humanize).join(', '); } }) .filter('asWalkValidationsList', function () { return function (walkValidations) { var lastItem = _.last(walkValidations); var firstItems = _.without(walkValidations, lastItem); var joiner = firstItems.length > 0 ? ' and ' : ''; return firstItems.join(', ') + joiner + lastItem; } }) .filter('idFromRecord', function () { return function (mongoRecord) { return mongoRecord.$id; } }) .filter('eventTimes', function () { return function (socialEvent) { var eventTimes = socialEvent.eventTimeStart; if (socialEvent.eventTimeEnd) eventTimes += ' - ' + socialEvent.eventTimeEnd; return eventTimes; } }) .filter('displayDate', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDate(dateValue); } }]) .filter('displayDay', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDay(dateValue); } }]) .filter('displayDates', ["$filter", function ($filter) { return function (dateValues) { return _(dateValues).map(function (dateValue) { return $filter('displayDate')(dateValue); }).join(', '); } }]) .filter('displayDateAndTime', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDateAndTime(dateValue); } }]) .filter('fromExcelDate', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDate(dateValue); } }]) .filter('lastLoggedInDateDisplayed', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDateAndTime(dateValue); } }]) .filter('lastConfirmedDateDisplayed', ["DateUtils", function (DateUtils) { return function (member) { return member && member.profileSettingsConfirmedAt ? 'by ' + (member.profileSettingsConfirmedBy || 'member') + ' at ' + DateUtils.displayDateAndTime(member.profileSettingsConfirmedAt) : 'not confirmed yet'; } }]) .filter('createdAudit', ["StringUtils", function (StringUtils) { return function (resource, members) { return StringUtils.formatAudit(resource.createdBy, resource.createdDate, members) } }]) .filter('updatedAudit', ["StringUtils", function (StringUtils) { return function (resource, members) { return StringUtils.formatAudit(resource.updatedBy, resource.updatedDate, members) } }]); /* concatenated from client/src/app/js/forgotPasswordController.js */ angular.module("ekwgApp") .controller("ForgotPasswordController", ["$q", "$log", "$scope", "$rootScope", "$location", "$routeParams", "EmailSubscriptionService", "MemberService", "LoggedInMemberService", "URLService", "MailchimpConfig", "MailchimpSegmentService", "MailchimpCampaignService", "Notifier", "ValidationUtils", "close", function ($q, $log, $scope, $rootScope, $location, $routeParams, EmailSubscriptionService, MemberService, LoggedInMemberService, URLService, MailchimpConfig, MailchimpSegmentService, MailchimpCampaignService, Notifier, ValidationUtils, close) { var logger = $log.getInstance("ForgotPasswordController"); $log.logLevels["ForgotPasswordController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); $scope.showSubmit = true; $scope.FORGOTTEN_PASSWORD_SEGMENT = "Forgotten Password"; $scope.forgottenPasswordCredentials = {}; $scope.actions = { close: function () { close(); }, submittable: function () { var onePopulated = ValidationUtils.fieldPopulated($scope.forgottenPasswordCredentials, "credentialOne"); var twoPopulated = ValidationUtils.fieldPopulated($scope.forgottenPasswordCredentials, "credentialTwo"); logger.info("notSubmittable: onePopulated", onePopulated, "twoPopulated", twoPopulated); return twoPopulated && onePopulated; }, submit: function () { var userDetails = "User Name " + $scope.forgottenPasswordCredentials.credentialOne + " and Membership Number " + $scope.forgottenPasswordCredentials.credentialTwo; notify.setBusy(); $scope.showSubmit = false; notify.success("Checking our records for " + userDetails, true); if ($scope.forgottenPasswordCredentials.credentialOne.length === 0 || $scope.forgottenPasswordCredentials.credentialTwo.length === 0) { $scope.showSubmit = true; notify.error({ title: "Incorrect information entered", message: "Please enter both a User Name and a Membership Number" }); } else { var forgotPasswordData = {loginResponse: {memberLoggedIn: false}}; var message; LoggedInMemberService.getMemberForResetPassword($scope.forgottenPasswordCredentials.credentialOne, $scope.forgottenPasswordCredentials.credentialTwo) .then(function (member) { if (_.isEmpty(member)) { message = "No member was found with " + userDetails; forgotPasswordData.loginResponse.alertMessage = message; $scope.showSubmit = true; return { forgotPasswordData: forgotPasswordData, notifyObject: { title: "Incorrect information entered", message: message } }; } else if (!member.mailchimpLists.general.subscribed) { message = "Sorry, " + userDetails + " is not setup in our system to receive emails"; forgotPasswordData.member = member; forgotPasswordData.loginResponse.alertMessage = message; $scope.showSubmit = true; return { forgotPasswordData: forgotPasswordData, notifyObject: { title: "Message cannot be sent", message: message } }; } else { LoggedInMemberService.setPasswordResetId(member); EmailSubscriptionService.resetUpdateStatusForMember(member); logger.debug("saving member", member); $scope.forgottenPasswordMember = member; member.$saveOrUpdate(sendForgottenPasswordEmailToMember, sendForgottenPasswordEmailToMember, saveFailed, saveFailed); forgotPasswordData.member = member; forgotPasswordData.loginResponse.alertMessage = "New password requested from login screen"; return {forgotPasswordData: forgotPasswordData}; } }).then(function (response) { return LoggedInMemberService.auditMemberLogin($scope.forgottenPasswordCredentials.credentialOne, "", response.forgotPasswordData.member, response.forgotPasswordData.loginResponse) .then(function () { if (response.notifyObject) { notify.error(response.notifyObject) } }); }); } } }; function saveFailed(error) { notify.error({title: "The password reset failed", message: error}); } function getMailchimpConfig() { return MailchimpConfig.getConfig() .then(function (config) { $scope.mailchimpConfig = config.mailchimp; }); } function createOrSaveForgottenPasswordSegment() { return MailchimpSegmentService.saveSegment("general", {segmentId: $scope.mailchimpConfig.segments.general.forgottenPasswordSegmentId}, [{id: $scope.forgottenPasswordMember.$id()}], $scope.FORGOTTEN_PASSWORD_SEGMENT, [$scope.forgottenPasswordMember]); } function saveSegmentDataToMailchimpConfig(segmentResponse) { return MailchimpConfig.getConfig() .then(function (config) { config.mailchimp.segments.general.forgottenPasswordSegmentId = segmentResponse.segment.id; MailchimpConfig.saveConfig(config); }); } function sendForgottenPasswordCampaign() { var member = $scope.forgottenPasswordMember.firstName + " " + $scope.forgottenPasswordMember.lastName; return MailchimpConfig.getConfig() .then(function (config) { logger.debug("config.mailchimp.campaigns.forgottenPassword.campaignId", config.mailchimp.campaigns.forgottenPassword.campaignId); logger.debug("config.mailchimp.segments.general.forgottenPasswordSegmentId", config.mailchimp.segments.general.forgottenPasswordSegmentId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: config.mailchimp.campaigns.forgottenPassword.campaignId, campaignName: "EKWG website password reset instructions (" + member + ")", segmentId: config.mailchimp.segments.general.forgottenPasswordSegmentId }); }); } function updateGeneralList() { return EmailSubscriptionService.createBatchSubscriptionForList("general", [$scope.forgottenPasswordMember]); } function sendForgottenPasswordEmailToMember() { $q.when(notify.success("Sending forgotten password email")) .then(updateGeneralList) .then(getMailchimpConfig) .then(createOrSaveForgottenPasswordSegment) .then(saveSegmentDataToMailchimpConfig) .then(sendForgottenPasswordCampaign) .then(finalMessage) .then(notify.clearBusy) .catch(handleSendError); } function handleSendError(errorResponse) { notify.error({ title: "Your email could not be sent", message: (errorResponse.message || errorResponse) + (errorResponse.error ? (". Error was: " + ErrorMessageService.stringify(errorResponse.error)) : "") }); } function finalMessage() { return notify.success({ title: "Message sent", message: "We've sent a message to the email address we have for you. Please check your inbox and follow the instructions in the message." }) } }] ); /* concatenated from client/src/app/js/googleMapsServices.js */ angular.module('ekwgApp') .factory('GoogleMapsConfig', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) { function getConfig() { return $http.get('/googleMaps/config').then(function (response) { return HTTPResponseService.returnResponse(response); }); } return { getConfig: getConfig, } }]); /* concatenated from client/src/app/js/homeController.js */ angular.module('ekwgApp') .controller('HomeController', ["$log", "$scope", "$routeParams", "LoggedInMemberService", "ContentMetaDataService", "CommitteeReferenceData", "InstagramService", "SiteEditService", function ($log, $scope, $routeParams, LoggedInMemberService, ContentMetaDataService, CommitteeReferenceData, InstagramService, SiteEditService) { var logger = $log.getInstance('HomeController'); $log.logLevels['HomeController'] = $log.LEVEL.OFF; $scope.feeds = {instagram: {recentMedia: []}, facebook: {}}; ContentMetaDataService.getMetaData('imagesHome') .then(function (contentMetaData) { $scope.interval = 5000; $scope.slides = contentMetaData.files; }); InstagramService.recentMedia() .then(function (recentMediaResponse) { $scope.feeds.instagram.recentMedia = _.take(recentMediaResponse.instagram, 14); logger.debug("Refreshed social media", $scope.feeds.instagram.recentMedia, 'count =', $scope.feeds.instagram.recentMedia.length); }); $scope.mediaUrlFor = function (media) { logger.debug('mediaUrlFor:media', media); return (media && media.images) ? media.images.standard_resolution.url : ""; }; $scope.mediaCaptionFor = function (media) { logger.debug('mediaCaptionFor:media', media); return media ? media.caption.text : ""; }; $scope.allowEdits = function () { return SiteEditService.active() && LoggedInMemberService.allowContentEdits(); }; }]); /* concatenated from client/src/app/js/howTo.js */ angular.module('ekwgApp') .controller("HowToDialogController", ["$rootScope", "$log", "$q", "$scope", "$filter", "FileUtils", "DateUtils", "EKWGFileUpload", "DbUtils", "LoggedInMemberService", "ErrorMessageService", "MailchimpLinkService", "MailchimpCampaignService", "Notifier", "MemberResourcesReferenceData", "memberResource", "close", function ($rootScope, $log, $q, $scope, $filter, FileUtils, DateUtils, EKWGFileUpload, DbUtils, LoggedInMemberService, ErrorMessageService, MailchimpLinkService, MailchimpCampaignService, Notifier, MemberResourcesReferenceData, memberResource, close) { var logger = $log.getInstance("HowToDialogController"); $log.logLevels["HowToDialogController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); $scope.fileUtils = FileUtils; $scope.mailchimpLinkService = MailchimpLinkService; $scope.memberResourcesReferenceData = MemberResourcesReferenceData; $scope.memberResource = memberResource; logger.debug("memberResourcesReferenceData:", $scope.memberResourcesReferenceData, "memberResource:", memberResource); $scope.resourceDateCalendar = { open: function () { $scope.resourceDateCalendar.opened = true; } }; $scope.cancel = function () { close(); }; $scope.onSelect = function (file) { if (file) { logger.debug("onSelect:file:about to upload ->", file); $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, "memberResources") .then(function (fileNameData) { logger.debug("onSelect:file:upload complete -> fileNameData", fileNameData); $scope.memberResource.data.fileNameData = fileNameData; $scope.memberResource.data.fileNameData.title = $scope.oldTitle || file.name; }); } }; $scope.attach = function (file) { $("#hidden-input").click(); }; $scope.save = function () { notify.setBusy(); logger.debug("save ->", $scope.memberResource); return $scope.memberResource.$saveOrUpdate(notify.success, notify.success, notify.error, notify.error) .then($scope.hideDialog) .then(notify.clearBusy) .catch(handleError); function handleError(errorResponse) { notify.error({ title: "Your changes could not be saved", message: (errorResponse && errorResponse.error ? (". Error was: " + JSON.stringify(errorResponse.error)) : "") }); notify.clearBusy(); } }; $scope.cancelChange = function () { $q.when($scope.hideDialog()).then(notify.clearBusy); }; $scope.campaignDate = function (campaign) { return DateUtils.asValueNoTime(campaign.send_time || campaign.create_time); }; $scope.campaignTitle = function (campaign) { return campaign.title + " (" + $filter("displayDate")($scope.campaignDate(campaign)) + ")"; }; $scope.campaignChange = function () { logger.debug("campaignChange:memberResource.data.campaign", $scope.memberResource.data.campaign); if ($scope.memberResource.data.campaign) { $scope.memberResource.title = $scope.memberResource.data.campaign.title; $scope.memberResource.resourceDate = $scope.campaignDate($scope.memberResource.data.campaign); } }; $scope.performCampaignSearch = function (selectFirst) { var campaignSearchTerm = $scope.memberResource.data.campaignSearchTerm; if (campaignSearchTerm) { notify.setBusy(); notify.progress({ title: "Email search", message: "searching for campaigns matching '" + campaignSearchTerm + "'" }); var options = { limit: $scope.memberResource.data.campaignSearchLimit, concise: true, status: "sent", campaignSearchTerm: campaignSearchTerm }; options[$scope.memberResource.data.campaignSearchField] = campaignSearchTerm; return MailchimpCampaignService.list(options).then(function (response) { $scope.campaigns = response.data; if (selectFirst) { $scope.memberResource.data.campaign = _.first($scope.campaigns); $scope.campaignChange(); } else { logger.debug("$scope.memberResource.data.campaign", $scope.memberResource.data.campaign, "first campaign=", _.first($scope.campaigns)) } logger.debug("response.data", response.data); notify.success({ title: "Email search", message: "Found " + $scope.campaigns.length + " campaigns matching '" + campaignSearchTerm + "'" }); notify.clearBusy(); return true; }); } else { return $q.when(true); } }; $scope.hideDialog = function () { $rootScope.$broadcast("memberResourcesChanged"); close(); }; $scope.editMode = $scope.memberResource.$id() ? "Edit" : "Add"; logger.debug("editMode:", $scope.editMode); if ($scope.memberResource.resourceType === "email" && $scope.memberResource.$id()) { $scope.performCampaignSearch(false).then(notify.clearBusy) } else { notify.clearBusy(); } }]) .controller("HowToController", ["$rootScope", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "MailchimpLinkService", "FileUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "MailchimpSegmentService", "MailchimpCampaignService", "MemberResourcesReferenceData", "MailchimpConfig", "Notifier", "MemberResourcesService", "CommitteeReferenceData", "ModalService", "SiteEditService", function ($rootScope, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $scope, $filter, $routeParams, $location, URLService, DateUtils, MailchimpLinkService, FileUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, MailchimpSegmentService, MailchimpCampaignService, MemberResourcesReferenceData, MailchimpConfig, Notifier, MemberResourcesService, CommitteeReferenceData, ModalService, SiteEditService) { var logger = $log.getInstance("HowToController"); $log.logLevels["HowToController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); $scope.fileUtils = FileUtils; $scope.memberResourcesReferenceData = MemberResourcesReferenceData; $scope.mailchimpLinkService = MailchimpLinkService; $scope.destinationType = ""; $scope.members = []; $scope.memberResources = []; $scope.alertMessages = []; $scope.allowConfirmDelete = false; $scope.selected = { addingNew: false, }; $scope.isActive = function (memberResource) { var active = SiteEditService.active() && LoggedInMemberService.memberLoggedIn() && memberResource === $scope.selected.memberResource; logger.debug("isActive =", active, "with memberResource", memberResource); return active; }; $scope.allowAdd = function () { return SiteEditService.active() && LoggedInMemberService.allowFileAdmin(); }; $scope.allowEdit = function (memberResource) { return $scope.allowAdd() && memberResource && memberResource.$id(); }; $scope.allowDelete = function (memberResource) { return $scope.allowEdit(memberResource); }; var defaultMemberResource = function () { return new MemberResourcesService({ data: {campaignSearchLimit: "1000", campaignSearchField: "title"}, resourceType: "email", accessLevel: "hidden", createdDate: DateUtils.nowAsValue(), createdBy: LoggedInMemberService.loggedInMember().memberId }) }; function removeDeleteOrAddOrInProgressFlags() { $scope.allowConfirmDelete = false; $scope.selected.addingNew = false; } $scope.delete = function () { $scope.allowConfirmDelete = true; }; $scope.cancelDelete = function () { removeDeleteOrAddOrInProgressFlags(); }; $scope.confirmDelete = function () { notify.setBusy(); function showDeleted() { return notify.success("member resource was deleted successfully"); } $scope.selected.memberResource.$remove(showDeleted, showDeleted, notify.error, notify.error) .then($scope.hideDialog) .then(refreshMemberResources) .then(removeDeleteOrAddOrInProgressFlags) .then(notify.clearBusy); }; $scope.selectMemberResource = function (memberResource) { logger.debug("selectMemberResource with memberResource", memberResource, "$scope.selected.addingNew", $scope.selected.addingNew); if (!$scope.selected.addingNew) { $scope.selected.memberResource = memberResource; } }; $scope.edit = function () { ModalService.showModal({ templateUrl: "partials/howTo/how-to-dialog.html", controller: "HowToDialogController", preClose: function (modal) { logger.debug("preClose event with modal", modal); modal.element.modal("hide"); }, inputs: { memberResource: $scope.selected.memberResource } }).then(function (modal) { logger.debug("modal event with modal", modal); modal.element.modal(); modal.close.then(function (result) { logger.debug("close event with result", result); }); }) }; $scope.add = function () { $scope.selected.addingNew = true; var memberResource = defaultMemberResource(); $scope.selected.memberResource = memberResource; logger.debug("add:", memberResource); $scope.edit(); }; $scope.hideDialog = function () { removeDeleteOrAddOrInProgressFlags(); }; $scope.$on("memberResourcesChanged", function () { refreshAll(); }); $scope.$on("memberResourcesChanged", function () { refreshAll(); }); $scope.$on("memberLoginComplete", function () { refreshAll(); }); $scope.$on("memberLogoutComplete", function () { refreshAll(); }); $scope.$on("editSite", function (event, data) { logger.debug("editSite:", data); refreshAll(); }); function refreshMemberResources() { MemberResourcesService.all() .then(function (memberResources) { if (URLService.hasRouteParameter("memberResourceId")) { $scope.memberResources = _.filter(memberResources, function (memberResource) { return memberResource.$id() === $routeParams.memberResourceId; }); } else { $scope.memberResources = _.chain(memberResources) .filter(function (memberResource) { return $scope.memberResourcesReferenceData.accessLevelFor(memberResource.accessLevel).filter(); }).sortBy("resourceDate") .value() .reverse(); logger.debug(memberResources.length, "memberResources", $scope.memberResources.length, "filtered memberResources"); } }); } function refreshAll() { refreshMemberResources(); } refreshAll(); }]); /* concatenated from client/src/app/js/httpServices.js */ angular.module('ekwgApp') .factory('HTTPResponseService', ["$log", function ($log) { var logger = $log.getInstance('HTTPResponseService'); $log.logLevels['HTTPResponseService'] = $log.LEVEL.OFF; function returnResponse(response) { logger.debug('response.data=', response.data); var returnObject = (typeof response.data === 'object') || !response.data ? response.data : JSON.parse(response.data); logger.debug('returned ', typeof response.data, 'response status =', response.status, returnObject.length, 'response items:', returnObject); return returnObject; } return { returnResponse: returnResponse } }]); /* concatenated from client/src/app/js/imageEditor.js */ angular.module('ekwgApp') .controller('ImageEditController', ["$scope", "$location", "Upload", "$http", "$q", "$routeParams", "$window", "LoggedInMemberService", "ContentMetaDataService", "Notifier", "EKWGFileUpload", function($scope, $location, Upload, $http, $q, $routeParams, $window, LoggedInMemberService, ContentMetaDataService, Notifier, EKWGFileUpload) { var notify = Notifier($scope); $scope.imageSource = $routeParams.imageSource; applyAllowEdits(); $scope.onFileSelect = function(file) { if (file) { $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, $scope.imageSource).then(function(fileNameData) { $scope.currentImageMetaDataItem.image = $scope.imageMetaData.baseUrl + '/' + fileNameData.awsFileName; console.log(' $scope.currentImageMetaDataItem.image', $scope.currentImageMetaDataItem.image); }); } }; $scope.refreshImageMetaData = function(imageSource) { notify.setBusy(); $scope.imageSource = imageSource; ContentMetaDataService.getMetaData(imageSource).then(function(contentMetaData) { $scope.imageMetaData = contentMetaData; notify.clearBusy(); }, function(response) { notify.error(response); }); }; $scope.refreshImageMetaData($scope.imageSource); $scope.$on('memberLoginComplete', function() { applyAllowEdits(); }); $scope.$on('memberLogoutComplete', function() { applyAllowEdits(); }); $scope.exitBackToPreviousWindow = function() { $window.history.back(); }; $scope.reverseSortOrder = function() { $scope.imageMetaData.files = $scope.imageMetaData.files.reverse(); }; $scope.imageTitleLength = function() { if ($scope.imageSource === 'imagesHome') { return 50; } else { return 20 } }; $scope.replace = function(imageMetaDataItem) { $scope.files = []; $scope.currentImageMetaDataItem = imageMetaDataItem; $('#hidden-input').click(); }; $scope.moveUp = function(imageMetaDataItem) { var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem); if (currentIndex > 0) { $scope.delete(imageMetaDataItem); $scope.imageMetaData.files.splice(currentIndex - 1, 0, imageMetaDataItem); } }; $scope.moveDown = function(imageMetaDataItem) { var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem); if (currentIndex < $scope.imageMetaData.files.length) { $scope.delete(imageMetaDataItem); $scope.imageMetaData.files.splice(currentIndex + 1, 0, imageMetaDataItem); } }; $scope.delete = function(imageMetaDataItem) { $scope.imageMetaData.files = _.without($scope.imageMetaData.files, imageMetaDataItem); }; $scope.insertHere = function(imageMetaDataItem) { var insertedImageMetaDataItem = new ContentMetaDataService.createNewMetaData(true); var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem); $scope.imageMetaData.files.splice(currentIndex, 0, insertedImageMetaDataItem); $scope.replace(insertedImageMetaDataItem); }; $scope.currentImageMetaDataItemBeingUploaded = function(imageMetaDataItem) { return ($scope.currentImageMetaDataItem && $scope.currentImageMetaDataItem.$$hashKey === imageMetaDataItem.$$hashKey); }; $scope.saveAll = function() { ContentMetaDataService.saveMetaData($scope.imageMetaData, saveOrUpdateSuccessful, notify.error) .then(function(contentMetaData) { $scope.exitBackToPreviousWindow(); }, function(response) { notify.error(response); }); }; function applyAllowEdits() { $scope.allowEdits = LoggedInMemberService.allowContentEdits(); } function saveOrUpdateSuccessful() { notify.success('data for ' + $scope.imageMetaData.files.length + ' images was saved successfully.'); } }]); /* concatenated from client/src/app/js/indexController.js */ angular.module('ekwgApp') .controller("IndexController", ["$q", "$cookieStore", "$log", "$scope", "$rootScope", "URLService", "LoggedInMemberService", "ProfileConfirmationService", "AuthenticationModalsService", "Notifier", "DateUtils", function ($q, $cookieStore, $log, $scope, $rootScope, URLService, LoggedInMemberService, ProfileConfirmationService, AuthenticationModalsService, Notifier, DateUtils) { var logger = $log.getInstance("IndexController"); $log.logLevels["IndexController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); logger.info('called IndexController'); $scope.ready = false; $scope.year = DateUtils.asString(DateUtils.momentNow().valueOf(), undefined, "YYYY"); $scope.actions = { forgotPassword: function () { URLService.navigateTo("forgot-password"); }, loginOrLogout: function () { if (LoggedInMemberService.memberLoggedIn()) { LoggedInMemberService.logout(); } else { URLService.navigateTo("login"); } } }; $scope.memberLoggedIn = function () { return LoggedInMemberService.memberLoggedIn() }; $scope.memberLoginStatus = function () { if (LoggedInMemberService.memberLoggedIn()) { var loggedInMember = LoggedInMemberService.loggedInMember(); return "Logout " + loggedInMember.firstName + " " + loggedInMember.lastName; } else { return "Login to EWKG Site"; } }; $scope.allowEdits = function () { return LoggedInMemberService.allowContentEdits(); }; $scope.isHome = function () { return URLService.relativeUrlFirstSegment() === "/"; }; $scope.isOnPage = function (data) { var matchedUrl = s.endsWith(URLService.relativeUrlFirstSegment(), data); logger.debug("isOnPage", matchedUrl, "data=", data); return matchedUrl; }; $scope.isProfileOrAdmin = function () { return $scope.isOnPage("profile") || $scope.isOnPage("admin"); }; }]); /* concatenated from client/src/app/js/instagramServices.js */ angular.module('ekwgApp') .factory('InstagramService', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) { function recentMedia() { return $http.get('/instagram/recentMedia').then(HTTPResponseService.returnResponse); } return { recentMedia: recentMedia, } }]); /* concatenated from client/src/app/js/letterheadController.js */ angular.module('ekwgApp') .controller('LetterheadController', ["$scope", "$location", function ($scope, $location) { var pathParts = $location.path().replace('/letterhead/', '').split('/'); $scope.firstPart = _.first(pathParts); $scope.lastPart = _.last(pathParts); }]); /* concatenated from client/src/app/js/links.js */ angular.module('ekwgApp') .factory('ContactUsAmendService', ["$filter", "LoggedInMemberService", "DateUtils", function ($filter, LoggedInMemberService, DateUtils) { }]) .controller('ContactUsController', ["$log", "$rootScope", "$routeParams", "$scope", "CommitteeReferenceData", "LoggedInMemberService", function ($log, $rootScope, $routeParams, $scope, CommitteeReferenceData, LoggedInMemberService) { var logger = $log.getInstance('ContactUsController'); $log.logLevels['ContactUsController'] = $log.LEVEL.OFF; $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; $scope.allowEdits = function () { return LoggedInMemberService.allowMemberAdminEdits(); } }]); /* concatenated from client/src/app/js/loggedInMemberService.js */ angular.module('ekwgApp') .factory('LoggedInMemberService', ["$rootScope", "$q", "$routeParams", "$cookieStore", "URLService", "MemberService", "MemberAuditService", "DateUtils", "NumberUtils", "$log", function ($rootScope, $q, $routeParams, $cookieStore, URLService, MemberService, MemberAuditService, DateUtils, NumberUtils, $log) { var logger = $log.getInstance('LoggedInMemberService'); var noLogger = $log.getInstance('NoLogger'); $log.logLevels['NoLogger'] = $log.LEVEL.OFF; $log.logLevels['LoggedInMemberService'] = $log.LEVEL.OFF; function loggedInMember() { if (!getCookie('loggedInMember')) setCookie('loggedInMember', {}); return getCookie('loggedInMember'); } function loginResponse() { if (!getCookie('loginResponse')) setCookie('loginResponse', {memberLoggedIn: false}); return getCookie('loginResponse'); } function showResetPassword() { return getCookie('showResetPassword'); } function allowContentEdits() { return memberLoggedIn() ? loggedInMember().contentAdmin : false; } function allowMemberAdminEdits() { return loginResponse().memberLoggedIn ? loggedInMember().memberAdmin : false; } function allowFinanceAdmin() { return loginResponse().memberLoggedIn ? loggedInMember().financeAdmin : false; } function allowCommittee() { return loginResponse().memberLoggedIn ? loggedInMember().committee : false; } function allowTreasuryAdmin() { return loginResponse().memberLoggedIn ? loggedInMember().treasuryAdmin : false; } function allowFileAdmin() { return loginResponse().memberLoggedIn ? loggedInMember().fileAdmin : false; } function memberLoggedIn() { return !_.isEmpty(loggedInMember()) && loginResponse().memberLoggedIn; } function showLoginPromptWithRouteParameter(routeParameter) { if (URLService.hasRouteParameter(routeParameter) && !memberLoggedIn()) $('#login-dialog').modal(); } function allowWalkAdminEdits() { return memberLoggedIn() ? loggedInMember().walkAdmin : false; } function allowSocialAdminEdits() { return memberLoggedIn() ? loggedInMember().socialAdmin : false; } function allowSocialDetailView() { return memberLoggedIn() ? loggedInMember().socialMember : false; } function logout() { var member = loggedInMember(); var loginResponseValue = loginResponse(); if (!_.isEmpty(member)) { loginResponseValue.alertMessage = 'The member ' + member.userName + ' logged out successfully'; auditMemberLogin(member.userName, undefined, member, loginResponseValue) } removeCookie('loginResponse'); removeCookie('loggedInMember'); removeCookie('showResetPassword'); removeCookie('editSite'); $rootScope.$broadcast('memberLogoutComplete'); } function auditMemberLogin(userName, password, member, loginResponse) { var audit = new MemberAuditService({ userName: userName, password: password, loginTime: DateUtils.nowAsValue(), loginResponse: loginResponse }); if (!_.isEmpty(member)) audit.member = member; return audit.$save(); } function setCookie(key, value) { noLogger.debug('setting cookie ' + key + ' with value ', value); $cookieStore.put(key, value); } function removeCookie(key) { logger.info('removing cookie ' + key); $cookieStore.remove(key); } function getCookie(key) { var object = $cookieStore.get(key); noLogger.debug('getting cookie ' + key + ' with value', object); return object; } function login(userName, password) { return getMemberForUserName(userName) .then(function (member) { removeCookie('showResetPassword'); var loginResponse = {}; if (!_.isEmpty(member)) { loginResponse.memberLoggedIn = false; if (!member.groupMember) { loginResponse.alertMessage = 'Logins for member ' + userName + ' have been disabled. Please'; } else if (member.password !== password) { loginResponse.alertMessage = 'The password was incorrectly entered for ' + userName + '. Please try again or'; } else if (member.expiredPassword) { setCookie('showResetPassword', true); loginResponse.alertMessage = 'The password for ' + userName + ' has expired. You must enter a new password before continuing. Alternatively'; } else { loginResponse.memberLoggedIn = true; loginResponse.alertMessage = 'The member ' + userName + ' logged in successfully'; setLoggedInMemberCookie(member); } } else { removeCookie('loggedInMember'); loginResponse.alertMessage = 'The member ' + userName + ' was not recognised. Please try again or'; } return {loginResponse: loginResponse, member: member}; }) .then(function (loginData) { setCookie('loginResponse', loginData.loginResponse); return auditMemberLogin(userName, password, loginData.member, loginData.loginResponse) .then(function () { logger.debug('loginResponse =', loginData.loginResponse); return $rootScope.$broadcast('memberLoginComplete'); } ); }, function (response) { throw new Error('Something went wrong...' + response); }) } function setLoggedInMemberCookie(member) { var memberId = member.$id(); var cookie = getCookie('loggedInMember'); if (_.isEmpty(cookie) || (cookie.memberId === memberId)) { var newCookie = angular.extend(member, {memberId: memberId}); logger.debug('saving loggedInMember ->', newCookie); setCookie('loggedInMember', newCookie); } else { logger.debug('not saving member (' + memberId + ') to cookie as not currently logged in member (' + cookie.memberId + ')', member); } } function saveMember(memberToSave, saveCallback, errorSaveCallback) { memberToSave.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback, errorSaveCallback) .then(function () { setLoggedInMemberCookie(memberToSave); }) .then(function () { $rootScope.$broadcast('memberSaveComplete'); }); } function resetPassword(userName, newPassword, newPasswordConfirm) { return getMemberForUserName(userName) .then(validateNewPassword) .then(saveSuccessfulPasswordReset) .then(broadcastMemberLoginComplete) .then(auditPasswordChange); function validateNewPassword(member) { var loginResponse = {memberLoggedIn: false}; var showResetPassword = true; if (member.password === newPassword) { loginResponse.alertMessage = 'The new password was the same as the old one for ' + member.userName + '. Please try again or'; } else if (!newPassword || newPassword.length < 6) { loginResponse.alertMessage = 'The new password needs to be at least 6 characters long. Please try again or'; } else if (newPassword !== newPasswordConfirm) { loginResponse.alertMessage = 'The new password was not confirmed correctly for ' + member.userName + '. Please try again or'; } else { showResetPassword = false; logger.debug('Saving new password for ' + member.userName + ' and removing expired status'); delete member.expiredPassword; delete member.passwordResetId; member.password = newPassword; loginResponse.memberLoggedIn = true; loginResponse.alertMessage = 'The password for ' + member.userName + ' was changed successfully'; } return {loginResponse: loginResponse, member: member, showResetPassword: showResetPassword}; } function saveSuccessfulPasswordReset(resetPasswordData) { logger.debug('saveNewPassword.resetPasswordData:', resetPasswordData); setCookie('loginResponse', resetPasswordData.loginResponse); setCookie('showResetPassword', resetPasswordData.showResetPassword); if (!resetPasswordData.showResetPassword) { return resetPasswordData.member.$update().then(function () { setLoggedInMemberCookie(resetPasswordData.member); return resetPasswordData; }) } else { return resetPasswordData; } } function auditPasswordChange(resetPasswordData) { return auditMemberLogin(userName, resetPasswordData.member.password, resetPasswordData.member, resetPasswordData.loginResponse) } function broadcastMemberLoginComplete(resetPasswordData) { $rootScope.$broadcast('memberLoginComplete'); return resetPasswordData } } function getMemberForUserName(userName) { return MemberService.query({userName: userName.toLowerCase()}, {limit: 1}) .then(function (queryResults) { return (queryResults && queryResults.length > 0) ? queryResults[0] : {}; }); } function getMemberForResetPassword(credentialOne, credentialTwo) { var credentialOneCleaned = credentialOne.toLowerCase().trim(); var credentialTwoCleaned = credentialTwo.toUpperCase().trim(); var orOne = {$or: [{userName: {$eq: credentialOneCleaned}}, {email: {$eq: credentialOneCleaned}}]}; var orTwo = {$or: [{membershipNumber: {$eq: credentialTwoCleaned}}, {postcode: {$eq: credentialTwoCleaned}}]}; var criteria = {$and: [orOne, orTwo]}; logger.info("querying member using", criteria); return MemberService.query(criteria, {limit: 1}) .then(function (queryResults) { logger.info("queryResults:", queryResults); return (queryResults && queryResults.length > 0) ? queryResults[0] : {}; }); } function getMemberForMemberId(memberId) { return MemberService.getById(memberId) } function getMemberByPasswordResetId(passwordResetId) { return MemberService.query({passwordResetId: passwordResetId}, {limit: 1}) .then(function (queryResults) { return (queryResults && queryResults.length > 0) ? queryResults[0] : {}; }); } function setPasswordResetId(member) { member.passwordResetId = NumberUtils.generateUid(); logger.debug('member.userName', member.userName, 'member.passwordResetId', member.passwordResetId); return member; } return { auditMemberLogin: auditMemberLogin, setPasswordResetId: setPasswordResetId, getMemberByPasswordResetId: getMemberByPasswordResetId, getMemberForResetPassword: getMemberForResetPassword, getMemberForUserName: getMemberForUserName, getMemberForMemberId: getMemberForMemberId, loggedInMember: loggedInMember, loginResponse: loginResponse, logout: logout, login: login, saveMember: saveMember, resetPassword: resetPassword, memberLoggedIn: memberLoggedIn, allowContentEdits: allowContentEdits, allowMemberAdminEdits: allowMemberAdminEdits, allowWalkAdminEdits: allowWalkAdminEdits, allowSocialAdminEdits: allowSocialAdminEdits, allowSocialDetailView: allowSocialDetailView, allowCommittee: allowCommittee, allowFinanceAdmin: allowFinanceAdmin, allowTreasuryAdmin: allowTreasuryAdmin, allowFileAdmin: allowFileAdmin, showResetPassword: showResetPassword, showLoginPromptWithRouteParameter: showLoginPromptWithRouteParameter }; }] ); /* concatenated from client/src/app/js/loginController.js */ angular.module('ekwgApp') .controller('LoginController', ["$log", "$scope", "$routeParams", "LoggedInMemberService", "AuthenticationModalsService", "Notifier", "URLService", "ValidationUtils", "close", function ($log, $scope, $routeParams, LoggedInMemberService, AuthenticationModalsService, Notifier, URLService, ValidationUtils, close) { $scope.notify = {}; var logger = $log.getInstance('LoginController'); $log.logLevels['LoginController'] = $log.LEVEL.OFF; var notify = Notifier($scope.notify); LoggedInMemberService.logout(); $scope.actions = { submittable: function () { var userNamePopulated = ValidationUtils.fieldPopulated($scope.enteredMemberCredentials, "userName"); var passwordPopulated = ValidationUtils.fieldPopulated($scope.enteredMemberCredentials, "password"); logger.info("submittable: userNamePopulated", userNamePopulated, "passwordPopulated", passwordPopulated); return passwordPopulated && userNamePopulated; }, forgotPassword: function () { URLService.navigateTo("forgot-password"); }, close: function () { close() }, login: function () { notify.showContactUs(false); notify.setBusy(); notify.progress({ busy: true, title: "Logging in", message: "using credentials for " + $scope.enteredMemberCredentials.userName + " - please wait" }); LoggedInMemberService.login($scope.enteredMemberCredentials.userName, $scope.enteredMemberCredentials.password).then(function () { var loginResponse = LoggedInMemberService.loginResponse(); if (LoggedInMemberService.memberLoggedIn()) { close(); if (!LoggedInMemberService.loggedInMember().profileSettingsConfirmed) { return URLService.navigateTo("mailing-preferences"); } return true; } else if (LoggedInMemberService.showResetPassword()) { return AuthenticationModalsService.showResetPasswordModal($scope.enteredMemberCredentials.userName, "Your password has expired, therefore you need to reset it to a new one before continuing."); } else { notify.showContactUs(true); notify.error({ title: "Login failed", message: loginResponse.alertMessage }); } }); }, } }] ); /* concatenated from client/src/app/js/mailChimpServices.js */ angular.module('ekwgApp') .factory('MailchimpConfig', ["Config", function (Config) { function getConfig() { return Config.getConfig('mailchimp', { mailchimp: { interestGroups: { walks: {interestGroupingId: undefined}, socialEvents: {interestGroupingId: undefined}, general: {interestGroupingId: undefined} }, segments: { walks: {segmentId: undefined}, socialEvents: {segmentId: undefined}, general: { passwordResetSegmentId: undefined, forgottenPasswordSegmentId: undefined, committeeSegmentId: undefined } } } }) } function saveConfig(config, key, saveCallback, errorSaveCallback) { return Config.saveConfig('mailchimp', config, key, saveCallback, errorSaveCallback); } return { getConfig: getConfig, saveConfig: saveConfig } }]) .factory('MailchimpHttpService', ["$log", "$q", "$http", "MailchimpErrorParserService", function ($log, $q, $http, MailchimpErrorParserService) { var logger = $log.getInstance('MailchimpHttpService'); $log.logLevels['MailchimpHttpService'] = $log.LEVEL.OFF; function call(serviceCallType, method, url, data, params) { var deferredTask = $q.defer(); deferredTask.notify(serviceCallType); logger.debug(serviceCallType); $http({ method: method, data: data, params: params, url: url }).then(function (response) { var responseData = response.data; var errorObject = MailchimpErrorParserService.extractError(responseData); if (errorObject.error) { var errorResponse = {message: serviceCallType + ' was not successful', error: errorObject.error}; logger.debug(errorResponse); deferredTask.reject(errorResponse); } else { logger.debug('success', responseData); deferredTask.resolve(responseData); return responseData; } }).catch(function (response) { var responseData = response.data; var errorObject = MailchimpErrorParserService.extractError(responseData); var errorResponse = {message: serviceCallType + ' was not successful', error: errorObject.error}; logger.debug(errorResponse); deferredTask.reject(errorResponse); }); return deferredTask.promise; } return { call: call } }]) .factory('MailchimpErrorParserService', ["$log", function ($log) { var logger = $log.getInstance('MailchimpErrorParserService'); $log.logLevels['MailchimpErrorParserService'] = $log.LEVEL.OFF; function extractError(responseData) { var error; if (responseData && (responseData.error || responseData.errno)) { error = {error: responseData} } else if (responseData && responseData.errors && responseData.errors.length > 0) { error = { error: _.map(responseData.errors, function (error) { var response = error.error; if (error.email && error.email.email) { response += (': ' + error.email.email); } return response; }).join(', ') } } else { error = {error: undefined} } logger.debug('responseData:', responseData, 'error:', error) return error; } return { extractError: extractError } }]) .factory('MailchimpLinkService', ["$log", "MAILCHIMP_APP_CONSTANTS", function ($log, MAILCHIMP_APP_CONSTANTS) { var logger = $log.getInstance('MailchimpLinkService'); $log.logLevels['MailchimpLinkService'] = $log.LEVEL.OFF; function campaignPreview(webId) { return MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/preview-content-html?id=" + webId; } function campaignEdit(webId) { return MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/preview-content-html?id=" + webId; } return { campaignPreview: campaignPreview } }]) .factory('MailchimpGroupService', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService) { var logger = $log.getInstance('MailchimpGroupService'); $log.logLevels['MailchimpGroupService'] = $log.LEVEL.OFF; var addInterestGroup = function (listType, interestGroupName, interestGroupingId) { return MailchimpHttpService.call('Adding Mailchimp Interest Group for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/interestGroupAdd', { interestGroupingId: interestGroupingId, interestGroupName: interestGroupName }); }; var deleteInterestGroup = function (listType, interestGroupName, interestGroupingId) { return MailchimpHttpService.call('Deleting Mailchimp Interest Group for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/interestGroupDel', { interestGroupingId: interestGroupingId, interestGroupName: interestGroupName }); }; var addInterestGrouping = function (listType, interestGroupingName, groups) { return MailchimpHttpService.call('Adding Mailchimp Interest Grouping for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/interestGroupingAdd', { groups: groups, interestGroupingName: interestGroupingName }); }; var deleteInterestGrouping = function (listType, interestGroupingId) { return MailchimpHttpService.call('Deleting Mailchimp Interest Grouping for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/interestGroupingDel', {interestGroupingId: interestGroupingId}); }; var listInterestGroupings = function (listType) { return MailchimpHttpService.call('Listing Mailchimp Interest Groupings for ' + listType, 'GET', 'mailchimp/lists/' + listType + '/interestGroupings'); }; var updateInterestGrouping = function (listType, interestGroupingId, interestGroupingName, interestGroupingValue) { return MailchimpHttpService.call('Updating Mailchimp Interest Groupings for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/interestGroupingUpdate', { interestGroupingId: interestGroupingId, interestGroupingName: interestGroupingName, interestGroupingValue: interestGroupingValue }); }; var updateInterestGroup = function (listType, oldName, newName) { return function (config) { var interestGroupingId = config.mailchimp.interestGroups[listType].interestGroupingId; return MailchimpHttpService.call('Updating Mailchimp Interest Group for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/interestGroupUpdate', { interestGroupingId: interestGroupingId, oldName: oldName, newName: newName }) .then(returnInterestGroupingId(interestGroupingId)); } }; var saveInterestGroup = function (listType, oldName, newName) { oldName = oldName.substring(0, 60); newName = newName.substring(0, 60); return MailchimpConfig.getConfig() .then(updateInterestGroup(listType, oldName, newName)) .then(findInterestGroup(listType, newName)); }; var createInterestGroup = function (listType, interestGroupName) { return MailchimpConfig.getConfig() .then(createOrUpdateInterestGroup(listType, interestGroupName)) .then(findInterestGroup(listType, interestGroupName)); }; var createOrUpdateInterestGroup = function (listType, interestGroupName) { return function (config) { logger.debug('createOrUpdateInterestGroup using config', config); var interestGroupingName = s.titleize(s.humanize(listType)); var interestGroupingId = config.mailchimp.interestGroups[listType].interestGroupingId; if (interestGroupingId) { return addInterestGroup(listType, interestGroupName, interestGroupingId) .then(returnInterestGroupingId(interestGroupingId)); } else { return addInterestGrouping(listType, interestGroupingName + ' Interest Groups', [interestGroupName]) .then(saveInterestGroupConfigAndReturnInterestGroupingId(listType, config)); } } }; var returnInterestGroupingId = function (interestGroupingId) { return function (response) { logger.debug('received', response, 'returning', interestGroupingId); return interestGroupingId; } }; var saveInterestGroupConfigAndReturnInterestGroupingId = function (listType, config) { return function (response) { config.mailchimp.interestGroups[listType].interestGroupingId = response.id; logger.debug('saving config', config); return MailchimpConfig.saveConfig(config, function () { logger.debug('config save was successful'); return response.id; }, function (error) { throw Error('config save was not successful. ' + error) }); } }; var findInterestGroup = function (listType, interestGroupName) { return function (interestGroupingId) { logger.debug('finding findInterestGroup ', interestGroupingId); return listInterestGroupings(listType) .then(filterInterestGroupings(interestGroupingId, interestGroupName)); } }; var filterInterestGroupings = function (interestGroupingId, interestGroupName) { return function (interestGroupings) { logger.debug('filterInterestGroupings: interestGroupings passed in ', interestGroupings, 'for interestGroupingId', interestGroupingId); var interestGrouping = _.find(interestGroupings, function (interestGrouping) { return interestGrouping.id === interestGroupingId; }); logger.debug('filterInterestGroupings: interestGrouping returned ', interestGrouping); var interestGroup = _.find(interestGrouping.groups, function (group) { return group.name === interestGroupName; }); logger.debug('filterInterestGroupings: interestGroup returned', interestGroup); return interestGroup; } }; return { createInterestGroup: createInterestGroup, saveInterestGroup: saveInterestGroup } }]) .factory('MailchimpSegmentService', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", "EmailSubscriptionService", "MemberService", "StringUtils", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService, EmailSubscriptionService, MemberService, StringUtils) { var logger = $log.getInstance('MailchimpSegmentService'); $log.logLevels['MailchimpSegmentService'] = $log.LEVEL.OFF; function addSegment(listType, segmentName) { return MailchimpHttpService.call('Adding Mailchimp segment for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentAdd', {segmentName: segmentName}); } function resetSegment(listType, segmentId) { return MailchimpHttpService.call('Resetting Mailchimp segment for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/segmentReset', {segmentId: segmentId}); } function deleteSegment(listType, segmentId) { return MailchimpHttpService.call('Deleting Mailchimp segment for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/segmentDel/' + segmentId); } function callRenameSegment(listType, segmentId, segmentName) { return function () { return renameSegment(listType, segmentId, segmentName); } } function renameSegment(listType, segmentId, segmentNameInput) { var segmentName = StringUtils.stripLineBreaks(StringUtils.left(segmentNameInput, 99), true); logger.debug('renaming segment with name=\'' + segmentName + '\' length=' + segmentName.length); return MailchimpHttpService.call('Renaming Mailchimp segment for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentRename', { segmentId: segmentId, segmentName: segmentName }); } function callAddSegmentMembers(listType, segmentId, segmentMembers) { return function () { return addSegmentMembers(listType, segmentId, segmentMembers); } } function addSegmentMembers(listType, segmentId, segmentMembers) { return MailchimpHttpService.call('Adding Mailchimp segment members ' + JSON.stringify(segmentMembers) + ' for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentMembersAdd', { segmentId: segmentId, segmentMembers: segmentMembers }); } function callDeleteSegmentMembers(listType, segmentId, segmentMembers) { return function () { return deleteSegmentMembers(listType, segmentId, segmentMembers); } } function deleteSegmentMembers(listType, segmentId, segmentMembers) { return MailchimpHttpService.call('Deleting Mailchimp segment members ' + segmentMembers + ' for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/segmentMembersDel', { segmentId: segmentId, segmentMembers: segmentMembers }); } function listSegments(listType) { return MailchimpHttpService.call('Listing Mailchimp segments for ' + listType, 'GET', 'mailchimp/lists/' + listType + '/segments'); } function buildSegmentMemberData(listType, memberIds, members) { var segmentMembers = _.chain(memberIds) .map(function (memberId) { return MemberService.toMember(memberId, members) }) .filter(function (member) { return member && member.email; }) .map(function (member) { return EmailSubscriptionService.addMailchimpIdentifiersToRequest(member, listType); }) .value(); if (!segmentMembers || segmentMembers.length === 0) throw new Error('No members were added to the ' + listType + ' email segment from the ' + memberIds.length + ' supplied members. Please check that they have a valid email address and are subscribed to ' + listType); return segmentMembers; } function saveSegment(listType, mailchimpConfig, memberIds, segmentName, members) { var segmentMembers = buildSegmentMemberData(listType, memberIds, members); logger.debug('saveSegment:buildSegmentMemberData:', listType, memberIds, segmentMembers); if (mailchimpConfig && mailchimpConfig.segmentId) { var segmentId = mailchimpConfig.segmentId; logger.debug('saveSegment:segmentId', mailchimpConfig); return resetSegment(listType, segmentId) .then(callRenameSegment(listType, segmentId, segmentName)) .then(addSegmentMembersDuringUpdate(listType, segmentId, segmentMembers)) .then(returnAddSegmentResponse({id: segmentId})); } else { return addSegment(listType, segmentName) .then(addSegmentMembersDuringAdd(listType, segmentMembers)) } } function returnAddSegmentResponse(addSegmentResponse) { return function (addSegmentMembersResponse) { return {members: addSegmentMembersResponse.members, segment: addSegmentResponse}; }; } function returnAddSegmentAndMemberResponse(addSegmentResponse) { return function (addMemberResponse) { return ({segment: addSegmentResponse, members: addMemberResponse}); }; } function addSegmentMembersDuringUpdate(listType, segmentId, segmentMembers) { return function (renameSegmentResponse) { if (segmentMembers.length > 0) { return addSegmentMembers(listType, segmentId, segmentMembers) .then(returnAddSegmentAndMemberResponse(renameSegmentResponse)); } else { return {segment: renameSegmentResponse.id, members: {}}; } } } function addSegmentMembersDuringAdd(listType, segmentMembers) { return function (addSegmentResponse) { if (segmentMembers.length > 0) { return addSegmentMembers(listType, addSegmentResponse.id, segmentMembers) .then(returnAddSegmentAndMemberResponse(addSegmentResponse)); } else { return {segment: addSegmentResponse, members: {}}; } } } function getMemberSegmentId(member, segmentType) { if (member.mailchimpSegmentIds) return member.mailchimpSegmentIds[segmentType]; } function setMemberSegmentId(member, segmentType, segmentId) { if (!member.mailchimpSegmentIds) member.mailchimpSegmentIds = {}; member.mailchimpSegmentIds[segmentType] = segmentId; } function formatSegmentName(prefix) { var date = ' (' + DateUtils.nowAsValue() + ')'; var segmentName = prefix.substring(0, 99 - date.length) + date; logger.debug('segmentName', segmentName, 'length', segmentName.length); return segmentName; } return { formatSegmentName: formatSegmentName, saveSegment: saveSegment, deleteSegment: deleteSegment, getMemberSegmentId: getMemberSegmentId, setMemberSegmentId: setMemberSegmentId } }]) .factory('MailchimpListService', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", "EmailSubscriptionService", "MemberService", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService, EmailSubscriptionService, MemberService) { var logger = $log.getInstance('MailchimpListService'); $log.logLevels['MailchimpListService'] = $log.LEVEL.OFF; var listSubscribers = function (listType) { return MailchimpHttpService.call('Listing Mailchimp subscribers for ' + listType, 'GET', 'mailchimp/lists/' + listType); }; var batchUnsubscribe = function (listType, subscribers) { return MailchimpHttpService.call('Batch unsubscribing members from Mailchimp List for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/batchUnsubscribe', subscribers); }; var batchUnsubscribeMembers = function (listType, allMembers, notificationCallback) { return listSubscribers(listType) .then(filterSubscriberResponsesForUnsubscriptions(listType, allMembers)) .then(batchUnsubscribeForListType(listType, allMembers, notificationCallback)) .then(returnUpdatedMembers); }; function returnUpdatedMembers() { return MemberService.all(); } function batchUnsubscribeForListType(listType, allMembers, notificationCallback) { return function (subscribers) { if (subscribers.length > 0) { return batchUnsubscribe(listType, subscribers) .then(removeSubscriberDetailsFromMembers(listType, allMembers, subscribers, notificationCallback)); } else { notificationCallback('No members needed to be unsubscribed from ' + listType + ' list'); } } } function removeSubscriberDetailsFromMembers(listType, allMembers, subscribers, notificationCallback) { return function () { var updatedMembers = _.chain(subscribers) .map(function (subscriber) { var member = EmailSubscriptionService.responseToMember(listType, allMembers, subscriber); if (member) { member.mailchimpLists[listType] = {subscribed: false, updated: true}; member.$saveOrUpdate(); } else { notificationCallback('Could not find member from ' + listType + ' response containing data ' + JSON.stringify(subscriber)); } return member; }) .filter(function (member) { return member; }) .value(); $q.all(updatedMembers).then(function () { notificationCallback('Successfully unsubscribed ' + updatedMembers.length + ' member(s) from ' + listType + ' list'); return updatedMembers; }) } } function filterSubscriberResponsesForUnsubscriptions(listType, allMembers) { return function (listResponse) { return _.chain(listResponse.data) .filter(function (subscriber) { return EmailSubscriptionService.includeSubscriberInUnsubscription(listType, allMembers, subscriber); }) .map(function (subscriber) { return { email: subscriber.email, euid: subscriber.euid, leid: subscriber.leid }; }) .value(); } } return { batchUnsubscribeMembers: batchUnsubscribeMembers } }]) .factory('MailchimpCampaignService', ["MAILCHIMP_APP_CONSTANTS", "$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", function (MAILCHIMP_APP_CONSTANTS, $log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService) { var logger = $log.getInstance('MailchimpCampaignService'); $log.logLevels['MailchimpCampaignService'] = $log.LEVEL.OFF; function addCampaign(campaignId, campaignName) { return MailchimpHttpService.call('Adding Mailchimp campaign ' + campaignId + ' with name ' + campaignName, 'POST', 'mailchimp/campaigns/' + campaignId + '/campaignAdd', {campaignName: campaignName}); } function deleteCampaign(campaignId) { return MailchimpHttpService.call('Deleting Mailchimp campaign ' + campaignId, 'DELETE', 'mailchimp/campaigns/' + campaignId + '/delete'); } function getContent(campaignId) { return MailchimpHttpService.call('Getting Mailchimp content for campaign ' + campaignId, 'GET', 'mailchimp/campaigns/' + campaignId + '/content'); } function list(options) { return MailchimpHttpService.call('Listing Mailchimp campaigns', 'GET', 'mailchimp/campaigns/list', {}, options); } function setContent(campaignId, contentSections) { return contentSections ? MailchimpHttpService.call('Setting Mailchimp content for campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/update', { updates: { name: "content", value: contentSections } }) : $q.when({ result: "success", campaignId: campaignId, message: "setContent skipped as no content provided" }) } function setOrClearSegment(replicatedCampaignId, optionalSegmentId) { if (optionalSegmentId) { return setSegmentId(replicatedCampaignId, optionalSegmentId); } else { return clearSegment(replicatedCampaignId) } } function setSegmentId(campaignId, segmentId) { return setSegmentOpts(campaignId, {saved_segment_id: segmentId}); } function clearSegment(campaignId) { return setSegmentOpts(campaignId, []); } function setSegmentOpts(campaignId, value) { return MailchimpHttpService.call('Setting Mailchimp segment opts for campaign ' + campaignId + ' with value ' + JSON.stringify(value), 'POST', 'mailchimp/campaigns/' + campaignId + '/update', { updates: { name: "segment_opts", value: value } }); } function setCampaignOptions(campaignId, campaignName, otherOptions) { var value = angular.extend({}, { title: campaignName.substring(0, 99), subject: campaignName }, otherOptions); return MailchimpHttpService.call('Setting Mailchimp campaign options for id ' + campaignId + ' with ' + JSON.stringify(value), 'POST', 'mailchimp/campaigns/' + campaignId + '/update', { updates: { name: "options", value: value } }); } function replicateCampaign(campaignId) { return MailchimpHttpService.call('Replicating Mailchimp campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/replicate'); } function sendCampaign(campaignId) { if (!MAILCHIMP_APP_CONSTANTS.allowSendCampaign) throw new Error('You cannot send campaign ' + campaignId + ' as sending has been disabled'); return MailchimpHttpService.call('Sending Mailchimp campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/send'); } function listCampaigns() { return MailchimpHttpService.call('Listing Mailchimp campaigns', 'GET', 'mailchimp/campaigns/list'); } function replicateAndSendWithOptions(options) { logger.debug('replicateAndSendWithOptions:options', options); return replicateCampaign(options.campaignId) .then(function (replicateCampaignResponse) { logger.debug('replicateCampaignResponse', replicateCampaignResponse); var replicatedCampaignId = replicateCampaignResponse.id; return setCampaignOptions(replicatedCampaignId, options.campaignName, options.otherSegmentOptions) .then(function (renameResponse) { logger.debug('renameResponse', renameResponse); return setContent(replicatedCampaignId, options.contentSections) .then(function (setContentResponse) { logger.debug('setContentResponse', setContentResponse); return setOrClearSegment(replicatedCampaignId, options.segmentId) .then(function (setSegmentResponse) { logger.debug('setSegmentResponse', setSegmentResponse); return options.dontSend ? replicateCampaignResponse : sendCampaign(replicatedCampaignId) }) }) }) }); } return { replicateAndSendWithOptions: replicateAndSendWithOptions, list: list } }]); /* concatenated from client/src/app/js/mailingPreferencesController.js */ angular.module('ekwgApp') .controller('MailingPreferencesController', ["$log", "$scope", "ProfileConfirmationService", "Notifier", "URLService", "LoggedInMemberService", "memberId", "close", function ($log, $scope, ProfileConfirmationService, Notifier, URLService, LoggedInMemberService, memberId, close) { var logger = $log.getInstance("MailingPreferencesController"); $log.logLevels["MailingPreferencesController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); LoggedInMemberService.getMemberForMemberId(memberId) .then(function (member) { logger.info('memberId ->', memberId, 'member ->', member); $scope.member = member; }); function saveOrUpdateUnsuccessful(message) { notify.showContactUs(true); notify.error({ continue: true, title: "Error in saving mailing preferences", message: "Changes to your mailing preferences could not be saved. " + (message || "Please try again later.") }); } $scope.actions = { save: function () { ProfileConfirmationService.confirmProfile($scope.member); LoggedInMemberService.saveMember($scope.member, $scope.actions.close, saveOrUpdateUnsuccessful); }, close: function () { close(); } }; }]); /* concatenated from client/src/app/js/markdownEditor.js */ angular.module('ekwgApp') .component('markdownEditor', { templateUrl: 'partials/components/markdown-editor.html', controller: ["$cookieStore", "$log", "$rootScope", "$scope", "$element", "$attrs", "ContentText", function ($cookieStore, $log, $rootScope, $scope, $element, $attrs, ContentText) { var logger = $log.getInstance('MarkdownEditorController'); $log.logLevels['MarkdownEditorController'] = $log.LEVEL.OFF; var ctrl = this; ctrl.userEdits = {preview: true, saveInProgress: false, revertInProgress: false}; function assignData(data) { ctrl.data = data; ctrl.originalData = _.clone(data); logger.debug(ctrl.name, 'content retrieved:', data); return data; } function populateContent(type) { if (type) ctrl.userEdits[type + 'InProgress'] = true; return ContentText.forName(ctrl.name).then(function (data) { data = assignData(data); if (type) ctrl.userEdits[type + 'InProgress'] = false; return data; }); } ctrl.edit = function () { ctrl.userEdits.preview = false; }; ctrl.revert = function () { logger.debug('reverting ' + ctrl.name, 'content'); ctrl.data = _.clone(ctrl.originalData); }; ctrl.dirty = function () { var dirty = ctrl.data && ctrl.originalData && (ctrl.data.text !== ctrl.originalData.text); logger.debug(ctrl.name, 'dirty ->', dirty); return dirty; }; ctrl.revertGlyph = function () { return ctrl.userEdits.revertInProgress ? "fa fa-spinner fa-spin" : "glyphicon glyphicon-remove markdown-preview-icon" }; ctrl.saveGlyph = function () { return ctrl.userEdits.saveInProgress ? "fa fa-spinner fa-spin" : "glyphicon glyphicon-ok markdown-preview-icon" }; ctrl.save = function () { ctrl.userEdits.saveInProgress = true; logger.info('saving', ctrl.name, 'content', ctrl.data, $element, $attrs); ctrl.data.$saveOrUpdate().then(function (data) { ctrl.userEdits.saveInProgress = false; assignData(data); }) }; ctrl.editSite = function () { return $cookieStore.get('editSite'); }; ctrl.rows = function () { var text = _.property(["data", "text"])(ctrl); var rows = text ? text.split(/\r*\n/).length + 1 : 1; logger.info('number of rows in text ', text, '->', rows); return rows; }; ctrl.preview = function () { logger.info('previewing ' + ctrl.name, 'content', $element, $attrs); ctrl.userEdits.preview = true; }; ctrl.$onInit = function () { logger.debug('initialising:', ctrl.name, 'content, editSite:', ctrl.editSite()); if (!ctrl.description) { ctrl.description = ctrl.name; } populateContent(); }; }], bindings: { name: '@', description: '@', } }); /* concatenated from client/src/app/js/meetupServices.js */ angular.module('ekwgApp') .factory('MeetupService', ["$log", "$http", "HTTPResponseService", function ($log, $http, HTTPResponseService) { var logger = $log.getInstance('MeetupService'); $log.logLevels['MeetupService'] = $log.LEVEL.OFF; return { config: function () { return $http.get('/meetup/config').then(HTTPResponseService.returnResponse); }, eventUrlFor: function (meetupEventUrl) { return $http.get('/meetup/config').then(HTTPResponseService.returnResponse).then(function (meetupConfig) { return meetupConfig.url + '/' + meetupConfig.group + '/events/' + meetupEventUrl; }); }, eventsForStatus: function (status) { var queriedStatus = status || 'upcoming'; return $http({ method: 'get', params: { status: queriedStatus, }, url: '/meetup/events' }).then(function (response) { var returnValue = HTTPResponseService.returnResponse(response); logger.debug('eventsForStatus', queriedStatus, returnValue); return returnValue; }) } } }]); /* concatenated from client/src/app/js/memberAdmin.js */ angular.module('ekwgApp') .controller('MemberAdminController', ["$timeout", "$location", "$window", "$log", "$q", "$rootScope", "$routeParams", "$scope", "ModalService", "Upload", "StringUtils", "DbUtils", "URLService", "LoggedInMemberService", "MemberService", "MemberAuditService", "MemberBulkLoadAuditService", "MemberUpdateAuditService", "ProfileConfirmationService", "EmailSubscriptionService", "DateUtils", "MailchimpConfig", "MailchimpSegmentService", "MemberNamingService", "MailchimpCampaignService", "MailchimpListService", "Notifier", "ErrorMessageService", "MemberBulkUploadService", "ContentMetaDataService", "MONGOLAB_CONFIG", "MAILCHIMP_APP_CONSTANTS", function ($timeout, $location, $window, $log, $q, $rootScope, $routeParams, $scope, ModalService, Upload, StringUtils, DbUtils, URLService, LoggedInMemberService, MemberService, MemberAuditService, MemberBulkLoadAuditService, MemberUpdateAuditService, ProfileConfirmationService, EmailSubscriptionService, DateUtils, MailchimpConfig, MailchimpSegmentService, MemberNamingService, MailchimpCampaignService, MailchimpListService, Notifier, ErrorMessageService, MemberBulkUploadService, ContentMetaDataService, MONGOLAB_CONFIG, MAILCHIMP_APP_CONSTANTS) { var logger = $log.getInstance('MemberAdminController'); var noLogger = $log.getInstance('MemberAdminControllerNoLogger'); $log.logLevels['MemberAdminController'] = $log.LEVEL.OFF; $log.logLevels['MemberAdminControllerNoLogger'] = $log.LEVEL.OFF; $scope.memberAdminBaseUrl = ContentMetaDataService.baseUrl('memberAdmin'); $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); var DESCENDING = '▼'; var ASCENDING = '▲'; $scope.today = DateUtils.momentNowNoTime().valueOf(); $scope.currentMember = {}; $scope.display = { saveInProgress: false }; $scope.calculateMemberFilterDate = function () { $scope.display.memberFilterDate = DateUtils.momentNowNoTime().subtract($scope.display && $scope.display.emailType.monthsInPast, 'months').valueOf(); }; $scope.showArea = function (area) { URLService.navigateTo('admin', area) }; $scope.display.emailTypes = [$scope.display.emailType]; $scope.dropSupported = true; $scope.memberAdminOpen = !URLService.hasRouteParameter('expenseId') && (URLService.isArea('member-admin') || URLService.noArea()); $scope.memberBulkLoadOpen = URLService.isArea('member-bulk-load'); $scope.memberAuditOpen = URLService.isArea('member-audit'); LoggedInMemberService.showLoginPromptWithRouteParameter('expenseId'); if (LoggedInMemberService.memberLoggedIn()) { refreshMembers() .then(refreshMemberAudit) .then(refreshMemberBulkLoadAudit) .then(refreshMemberUpdateAudit) .then(notify.clearBusy); } else { notify.clearBusy(); } $scope.currentMemberBulkLoadDisplayDate = function () { return DateUtils.currentMemberBulkLoadDisplayDate(); }; $scope.viewMailchimpListEntry = function (item) { $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/lists/members/view?id=" + item, '_blank'); }; $scope.showSendEmailsDialog = function () { $scope.alertTypeResetPassword = false; $scope.display.emailMembers = []; ModalService.showModal({ templateUrl: "partials/admin/send-emails-dialog.html", controller: "MemberAdminSendEmailsController", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, inputs: { members: $scope.members } }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; function handleSaveError(errorResponse) { $scope.display.saveInProgress = false; applyAllowEdits(); var message = ErrorMessageService.stringify(errorResponse); var duplicate = s.include(message, 'duplicate'); logger.debug('errorResponse', errorResponse, 'duplicate', duplicate); if (duplicate) { message = 'Duplicate data was detected. A member record must have a unique Email Address, Display Name, Ramblers Membership Number and combination of First Name, Last Name and Alias. Please amend the current member and try again.'; $scope.display.duplicate = true; } notify.clearBusy(); notify.error({ title: 'Member could not be saved', message: message }); } function resetSendFlags() { logger.debug('resetSendFlags'); $scope.display.saveInProgress = false; return applyAllowEdits(); } $scope.showPasswordResetAlert = function () { return $scope.notify.showAlert && $scope.alertTypeResetPassword; }; $scope.uploadSessionStatuses = [ {title: "All"}, {status: "created", title: "Created"}, {status: "summary", title: "Summary"}, {status: "skipped", title: "Skipped"}, {status: "updated", title: "Updated"}, {status: "error", title: "Error"}]; $scope.filters = { uploadSession: {selected: undefined}, memberUpdateAudit: { query: $scope.uploadSessionStatuses[0], orderByField: 'updateTime', reverseSort: true, sortDirection: DESCENDING }, membersUploaded: { query: '', orderByField: 'email', reverseSort: true, sortDirection: DESCENDING } }; function applySortTo(field, filterSource) { logger.debug('sorting by field', field, 'current value of filterSource', filterSource); if (field === 'member') { filterSource.orderByField = 'memberId | memberIdToFullName : members : "" : true'; } else { filterSource.orderByField = field; } filterSource.reverseSort = !filterSource.reverseSort; filterSource.sortDirection = filterSource.reverseSort ? DESCENDING : ASCENDING; logger.debug('sorting by field', field, 'new value of filterSource', filterSource); } $scope.uploadSessionChanged = function () { notify.setBusy(); notify.hide(); refreshMemberUpdateAudit().then(notify.clearBusy); }; $scope.sortMembersUploadedBy = function (field) { applySortTo(field, $scope.filters.membersUploaded); }; $scope.sortMemberUpdateAuditBy = function (field) { applySortTo(field, $scope.filters.memberUpdateAudit); }; $scope.showMemberUpdateAuditColumn = function (field) { return s.startsWith($scope.filters.memberUpdateAudit.orderByField, field); }; $scope.showMembersUploadedColumn = function (field) { return $scope.filters.membersUploaded.orderByField === field; }; $scope.sortMembersBy = function (field) { applySortTo(field, $scope.filters.members); }; $scope.showMembersColumn = function (field) { return s.startsWith($scope.filters.members.orderByField, field); }; $scope.toGlyphicon = function (status) { if (status === 'created') return "glyphicon glyphicon-plus green-icon"; if (status === 'complete' || status === 'summary') return "glyphicon-ok green-icon"; if (status === 'success') return "glyphicon-ok-circle green-icon"; if (status === 'info') return "glyphicon-info-sign blue-icon"; if (status === 'updated') return "glyphicon glyphicon-pencil green-icon"; if (status === 'error') return "glyphicon-remove-circle red-icon"; if (status === 'skipped') return "glyphicon glyphicon-thumbs-up green-icon"; }; $scope.filters.members = { query: '', orderByField: 'firstName', reverseSort: false, sortDirection: ASCENDING, filterBy: [ { title: "Active Group Member", group: 'Group Settings', filter: function (member) { return member.groupMember; } }, { title: "All Members", filter: function () { return true; } }, { title: "Active Social Member", group: 'Group Settings', filter: MemberService.filterFor.SOCIAL_MEMBERS }, { title: "Membership Date Active/Not set", group: 'From Ramblers Supplied Datas', filter: function (member) { return !member.membershipExpiryDate || (member.membershipExpiryDate >= $scope.today); } }, { title: "Membership Date Expired", group: 'From Ramblers Supplied Data', filter: function (member) { return member.membershipExpiryDate < $scope.today; } }, { title: "Not received in last Ramblers Bulk Load", group: 'From Ramblers Supplied Data', filter: function (member) { return !member.receivedInLastBulkLoad; } }, { title: "Was received in last Ramblers Bulk Load", group: 'From Ramblers Supplied Data', filter: function (member) { return member.receivedInLastBulkLoad; } }, { title: "Password Expired", group: 'Other Settings', filter: function (member) { return member.expiredPassword; } }, { title: "Walk Admin", group: 'Administrators', filter: function (member) { return member.walkAdmin; } }, { title: "Walk Change Notifications", group: 'Administrators', filter: function (member) { return member.walkChangeNotifications; } }, { title: "Social Admin", group: 'Administrators', filter: function (member) { return member.socialAdmin; } }, { title: "Member Admin", group: 'Administrators', filter: function (member) { return member.memberAdmin; } }, { title: "Finance Admin", group: 'Administrators', filter: function (member) { return member.financeAdmin; } }, { title: "File Admin", group: 'Administrators', filter: function (member) { return member.fileAdmin; } }, { title: "Treasury Admin", group: 'Administrators', filter: function (member) { return member.treasuryAdmin; } }, { title: "Content Admin", group: 'Administrators', filter: function (member) { return member.contentAdmin; } }, { title: "Committee Member", group: 'Administrators', filter: function (member) { return member.committee; } }, { title: "Subscribed to the General emails list", group: 'Email Subscriptions', filter: MemberService.filterFor.GENERAL_MEMBERS_SUBSCRIBED }, { title: "Subscribed to the Walks email list", group: 'Email Subscriptions', filter: MemberService.filterFor.WALKS_MEMBERS_SUBSCRIBED }, { title: "Subscribed to the Social email list", group: 'Email Subscriptions', filter: MemberService.filterFor.SOCIAL_MEMBERS_SUBSCRIBED } ] }; $scope.filters.members.filterSelection = $scope.filters.members.filterBy[0].filter; $scope.memberAuditTabs = [ {title: "All Member Logins", active: true} ]; applyAllowEdits(); $scope.allowConfirmDelete = false; $scope.open = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.members = []; $scope.memberAudit = []; $scope.memberUpdateAudit = []; $scope.membersUploaded = []; $scope.resetAllBatchSubscriptions = function () { // careful with calling this - it resets all batch subscriptions to default values return EmailSubscriptionService.resetAllBatchSubscriptions($scope.members, false); }; function updateWalksList(members) { return EmailSubscriptionService.createBatchSubscriptionForList('walks', members); } function updateSocialEventsList(members) { return EmailSubscriptionService.createBatchSubscriptionForList('socialEvents', members); } function updateGeneralList(members) { return EmailSubscriptionService.createBatchSubscriptionForList('general', members); } function notifyUpdatesComplete(members) { notify.success({title: 'Mailchimp updates', message: 'Mailchimp lists were updated successfully'}); $scope.members = members; notify.clearBusy(); } $scope.deleteMemberAudit = function (filteredMemberAudit) { removeAllRecordsAndRefresh(filteredMemberAudit, refreshMemberAudit, 'member audit'); }; $scope.deleteMemberUpdateAudit = function (filteredMemberUpdateAudit) { removeAllRecordsAndRefresh(filteredMemberUpdateAudit, refreshMemberUpdateAudit, 'member update audit'); }; function removeAllRecordsAndRefresh(records, refreshFunction, type) { notify.success('Deleting ' + records.length + ' ' + type + ' record(s)'); var removePromises = []; angular.forEach(records, function (record) { removePromises.push(record.$remove()) }); $q.all(removePromises).then(function () { notify.success('Deleted ' + records.length + ' ' + type + ' record(s)'); refreshFunction.apply(); }); } $scope.$on('memberLoginComplete', function () { applyAllowEdits('memberLoginComplete'); refreshMembers(); refreshMemberAudit(); refreshMemberBulkLoadAudit() .then(refreshMemberUpdateAudit); }); $scope.$on('memberSaveComplete', function () { refreshMembers(); }); $scope.$on('memberLogoutComplete', function () { applyAllowEdits('memberLogoutComplete'); }); $scope.createMemberFromAudit = function (memberFromAudit) { var member = new MemberService(memberFromAudit); EmailSubscriptionService.defaultMailchimpSettings(member, true); member.groupMember = true; showMemberDialog(member, 'Add New'); notify.warning({ title: 'Recreating Member', message: "Note that clicking Save immediately on this member is likely to cause the same error to occur as was originally logged in the audit. Therefore make the necessary changes here to allow the member record to be saved successfully" }) }; $scope.addMember = function () { var member = new MemberService(); EmailSubscriptionService.defaultMailchimpSettings(member, true); member.groupMember = true; showMemberDialog(member, 'Add New'); }; $scope.viewMember = function (member) { showMemberDialog(member, 'View'); }; $scope.editMember = function (member) { showMemberDialog(member, 'Edit Existing'); }; $scope.deleteMemberDetails = function () { $scope.allowDelete = false; $scope.allowConfirmDelete = true; }; function unsubscribeWalksList() { return MailchimpListService.batchUnsubscribeMembers('walks', $scope.members, notify.success); } function unsubscribeSocialEventsList(members) { return MailchimpListService.batchUnsubscribeMembers('socialEvents', members, notify.success); } function unsubscribeGeneralList(members) { return MailchimpListService.batchUnsubscribeMembers('general', members, notify.success); } $scope.updateMailchimpLists = function () { $scope.display.saveInProgress = true; return $q.when(notify.success('Sending updates to Mailchimp lists', true)) .then(refreshMembers, notify.error, notify.success) .then(updateWalksList, notify.error, notify.success) .then(updateSocialEventsList, notify.error, notify.success) .then(updateGeneralList, notify.error, notify.success) .then(unsubscribeWalksList, notify.error, notify.success) .then(unsubscribeSocialEventsList, notify.error, notify.success) .then(unsubscribeGeneralList, notify.error, notify.success) .then(notifyUpdatesComplete, notify.error, notify.success) .then(resetSendFlags) .catch(mailchimpError); }; function mailchimpError(errorResponse) { resetSendFlags(); notify.error({ title: 'Mailchimp updates failed', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + ErrorMessageService.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } $scope.confirmDeleteMemberDetails = function () { $scope.currentMember.$remove(hideMemberDialogAndRefreshMembers); }; $scope.cancelMemberDetails = function () { hideMemberDialogAndRefreshMembers(); }; $scope.profileSettingsConfirmedChecked = function () { ProfileConfirmationService.processMember($scope.currentMember); }; $scope.refreshMemberAudit = refreshMemberAudit; $scope.memberUrl = function () { return $scope.currentMember && $scope.currentMember.$id && (MONGOLAB_CONFIG.baseUrl + MONGOLAB_CONFIG.database + '/collections/members/' + $scope.currentMember.$id()); }; $scope.saveMemberDetails = function () { var member = DateUtils.convertDateFieldInObject($scope.currentMember, 'membershipExpiryDate'); $scope.display.saveInProgress = true; if (!member.userName) { member.userName = MemberNamingService.createUniqueUserName(member, $scope.members); logger.debug('creating username', member.userName); } if (!member.displayName) { member.displayName = MemberNamingService.createUniqueDisplayName(member, $scope.members); logger.debug('creating displayName', member.displayName); } function preProcessMemberBeforeSave() { DbUtils.removeEmptyFieldsIn(member); return EmailSubscriptionService.resetUpdateStatusForMember(member); } function removeEmptyFieldsIn(obj) { _.each(obj, function (value, field) { logger.debug('processing', typeof(field), 'field', field, 'value', value); if (_.contains([null, undefined, ""], value)) { logger.debug('removing non-populated', typeof(field), 'field', field); delete obj[field]; } }); } function saveAndHide() { return DbUtils.auditedSaveOrUpdate(member, hideMemberDialogAndRefreshMembers, notify.error) } $q.when(notify.success('Saving member', true)) .then(preProcessMemberBeforeSave, notify.error, notify.success) .then(saveAndHide, notify.error, notify.success) .then(resetSendFlags) .then(function () { return notify.success('Member saved successfully'); }) .catch(handleSaveError) }; $scope.copyDetailsToNewMember = function () { var copiedMember = new MemberService($scope.currentMember); delete copiedMember._id; EmailSubscriptionService.defaultMailchimpSettings(copiedMember, true); ProfileConfirmationService.unconfirmProfile(copiedMember); showMemberDialog(copiedMember, 'Copy Existing'); notify.success('Existing Member copied! Make changes here and save to create new member.') }; function applyAllowEdits() { $scope.allowEdits = LoggedInMemberService.allowMemberAdminEdits(); $scope.allowCopy = LoggedInMemberService.allowMemberAdminEdits(); return true; } function findLastLoginTimeForMember(member) { var memberAudit = _.chain($scope.memberAudit) .filter(function (memberAudit) { return memberAudit.userName === member.userName; }) .sortBy(function (memberAudit) { return memberAudit.lastLoggedIn; }) .last() .value(); return memberAudit === undefined ? undefined : memberAudit.loginTime; } $scope.bulkUploadRamblersDataStart = function () { $('#select-bulk-load-file').click(); }; $scope.resetSendFlagsAndNotifyError = function (error) { logger.error('resetSendFlagsAndNotifyError', error); resetSendFlags(); return notify.error(error); }; $scope.bulkUploadRamblersDataOpenFile = function (file) { if (file) { var fileUpload = file; $scope.display.saveInProgress = true; function bulkUploadRamblersResponse(memberBulkLoadServerResponse) { return MemberBulkUploadService.processMembershipRecords(file, memberBulkLoadServerResponse, $scope.members, notify) } function bulkUploadRamblersProgress(evt) { fileUpload.progress = parseInt(100.0 * evt.loaded / evt.total); logger.debug("bulkUploadRamblersProgress:progress event", evt); } $scope.uploadedFile = Upload.upload({ url: 'uploadRamblersData', method: 'POST', file: file }).then(bulkUploadRamblersResponse, $scope.resetSendFlagsAndNotifyError, bulkUploadRamblersProgress) .then(refreshMemberBulkLoadAudit) .then(refreshMemberUpdateAudit) .then(validateBulkUploadProcessingBeforeMailchimpUpdates) .catch($scope.resetSendFlagsAndNotifyError); } }; function showMemberDialog(member, memberEditMode) { logger.debug('showMemberDialog:', memberEditMode, member); $scope.alertTypeResetPassword = false; var existingRecordEditEnabled = $scope.allowEdits && s.startsWith(memberEditMode, 'Edit'); $scope.allowConfirmDelete = false; $scope.allowCopy = existingRecordEditEnabled; $scope.allowDelete = existingRecordEditEnabled; $scope.memberEditMode = memberEditMode; $scope.currentMember = member; $scope.currentMemberUpdateAudit = []; if ($scope.currentMember.$id()) { logger.debug('querying MemberUpdateAuditService for memberId', $scope.currentMember.$id()); MemberUpdateAuditService.query({memberId: $scope.currentMember.$id()}, {sort: {updateTime: -1}}) .then(function (data) { logger.debug('MemberUpdateAuditService:', data.length, 'events', data); $scope.currentMemberUpdateAudit = data; }); $scope.lastLoggedIn = findLastLoginTimeForMember(member); } else { logger.debug('new member with default values', $scope.currentMember); } $('#member-admin-dialog').modal(); } function hideMemberDialogAndRefreshMembers() { $q.when($('#member-admin-dialog').modal('hide')) .then(refreshMembers) .then(notify.clearBusy) .then(notify.hide) } function refreshMembers() { if (LoggedInMemberService.allowMemberAdminEdits()) { return MemberService.all() .then(function (refreshedMembers) { $scope.members = refreshedMembers; return $scope.members; }); } } function refreshMemberAudit() { if (LoggedInMemberService.allowMemberAdminEdits()) { MemberAuditService.all({limit: 100, sort: {loginTime: -1}}).then(function (memberAudit) { logger.debug('refreshed', memberAudit && memberAudit.length, 'member audit records'); $scope.memberAudit = memberAudit; }); } return true; } function refreshMemberBulkLoadAudit() { if (LoggedInMemberService.allowMemberAdminEdits()) { return MemberBulkLoadAuditService.all({limit: 100, sort: {createdDate: -1}}).then(function (uploadSessions) { logger.debug('refreshed', uploadSessions && uploadSessions.length, 'upload sessions'); $scope.uploadSessions = uploadSessions; $scope.filters.uploadSession.selected = _.first(uploadSessions); return $scope.filters.uploadSession.selected; }); } else { return true; } } function migrateAudits() { // temp - remove this! MemberUpdateAuditService.all({ limit: 10000, sort: {updateTime: -1} }).then(function (allMemberUpdateAudit) { logger.debug('temp queried all', allMemberUpdateAudit && allMemberUpdateAudit.length, 'member audit records'); var keys = []; var memberUpdateAuditServicePromises = []; var memberBulkLoadAuditServicePromises = []; var bulkAudits = _.chain(allMemberUpdateAudit) // .filter(function (audit) { // return !audit.uploadSessionId; // }) .map(function (audit) { var auditLog = { fileName: audit.fileName, createdDate: DateUtils.asValueNoTime(audit.updateTime), auditLog: [ { "status": "complete", "message": "Migrated audit log for upload of file " + audit.fileName } ] }; return auditLog; }) .uniq(JSON.stringify) .map(function (auditLog) { return new MemberBulkLoadAuditService(auditLog).$save() .then(function (auditResponse) { memberBulkLoadAuditServicePromises.push(auditResponse); logger.debug('saved bulk load session id', auditResponse.$id(), 'number', memberBulkLoadAuditServicePromises.length); return auditResponse; }); }) .value(); function saveAudit(audit) { memberUpdateAuditServicePromises.push(audit.$saveOrUpdate()); logger.debug('saved', audit.uploadSessionId, 'to audit number', memberUpdateAuditServicePromises.length); } $q.all(bulkAudits).then(function (savedBulkAuditRecords) { logger.debug('saved bulk load sessions', savedBulkAuditRecords); _.each(allMemberUpdateAudit, function (audit) { var parentBulkAudit = _.findWhere(savedBulkAuditRecords, { fileName: audit.fileName, createdDate: DateUtils.asValueNoTime(audit.updateTime) }); if (parentBulkAudit) { audit.uploadSessionId = parentBulkAudit.$id(); saveAudit(audit); } else { logger.error('no match for audit record', audit); } }); $q.all(memberUpdateAuditServicePromises).then(function (values) { logger.debug('saved', values.length, 'audit records'); }); }); }); } function refreshMemberUpdateAudit() { if (LoggedInMemberService.allowMemberAdminEdits()) { // migrateAudits(); if ($scope.filters.uploadSession.selected && $scope.filters.uploadSession.selected.$id) { var uploadSessionId = $scope.filters.uploadSession.selected.$id(); var query = {uploadSessionId: uploadSessionId}; if ($scope.filters.memberUpdateAudit.query.status) { angular.extend(query, {memberAction: $scope.filters.memberUpdateAudit.query.status}) } logger.debug('querying member audit records with', query); return MemberUpdateAuditService.query(query, {sort: {updateTime: -1}}).then(function (memberUpdateAudit) { $scope.memberUpdateAudit = memberUpdateAudit; logger.debug('refreshed', memberUpdateAudit && memberUpdateAudit.length, 'member audit records'); return $scope.memberUpdateAudit; }); } else { $scope.memberUpdateAudit = []; logger.debug('no member audit records'); return $q.when($scope.memberUpdateAudit); } } } function auditSummary() { return _.groupBy($scope.memberUpdateAudit, function (auditItem) { return auditItem.memberAction || 'unknown'; }); } function auditSummaryFormatted(auditSummary) { var total = _.reduce(auditSummary, function (memo, value) { return memo + value.length; }, 0); var summary = _.map(auditSummary, function (items, key) { return items.length + ':' + key; }).join(', '); return total + " Member audits " + (total ? '(' + summary + ')' : ''); } $scope.memberUpdateAuditSummary = function () { return auditSummaryFormatted(auditSummary()); }; function validateBulkUploadProcessingBeforeMailchimpUpdates() { logger.debug('validateBulkUploadProcessing:$scope.filters.uploadSession', $scope.filters.uploadSession); if ($scope.filters.uploadSession.selected.error) { notify.error({title: 'Bulk upload failed', message: $scope.filters.uploadSession.selected.error}); } else { var summary = auditSummary(); var summaryFormatted = auditSummaryFormatted(summary); logger.debug('summary', summary, 'summaryFormatted', summaryFormatted); if (summary.error) { notify.error({ title: "Bulk upload was not successful", message: "One or more errors occurred - " + summaryFormatted }); return false; } else return $scope.updateMailchimpLists(); } } }] ) ; /* concatenated from client/src/app/js/memberAdminSendEmailsController.js */ angular.module('ekwgApp') .controller('MemberAdminSendEmailsController', ["$log", "$q", "$scope", "$filter", "DateUtils", "DbUtils", "LoggedInMemberService", "ErrorMessageService", "EmailSubscriptionService", "MailchimpSegmentService", "MailchimpCampaignService", "MailchimpConfig", "Notifier", "members", "close", function ($log, $q, $scope, $filter, DateUtils, DbUtils, LoggedInMemberService, ErrorMessageService, EmailSubscriptionService, MailchimpSegmentService, MailchimpCampaignService, MailchimpConfig, Notifier, members, close) { var logger = $log.getInstance('MemberAdminSendEmailsController'); $log.logLevels['MemberAdminSendEmailsController'] = $log.LEVEL.OFF; var notify = Notifier($scope); notify.setBusy(); var CAMPAIGN_TYPE_WELCOME = "welcome"; var CAMPAIGN_TYPE_PASSWORD_RESET = "passwordReset"; var CAMPAIGN_TYPE_EXPIRED_MEMBERS_WARNING = "expiredMembersWarning"; var CAMPAIGN_TYPE_EXPIRED_MEMBERS = "expiredMembers"; $scope.today = DateUtils.momentNowNoTime().valueOf(); $scope.members = members; $scope.memberFilterDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.memberFilterDateCalendar.opened = true; } }; $scope.showHelp = function (show) { $scope.display.showHelp = show; }; $scope.cancel = function () { close(); }; $scope.display = { showHelp: false, selectableMembers: [], emailMembers: [], saveInProgress: false, monthsInPast: 1, memberFilterDate: undefined, emailType: {name: "(loading)"}, passwordResetCaption: function () { return 'About to send a ' + $scope.display.emailType.name + ' to ' + $scope.display.emailMembers.length + ' member' + ($scope.display.emailMembers.length === 1 ? '' : 's'); }, expiryEmailsSelected: function () { var returnValue = $scope.display.emailType.type === CAMPAIGN_TYPE_EXPIRED_MEMBERS_WARNING || $scope.display.emailType.type === CAMPAIGN_TYPE_EXPIRED_MEMBERS; logger.debug('expiryEmailsSelected -> ', returnValue); return returnValue; }, recentMemberEmailsSelected: function () { return $scope.display.emailType.type === CAMPAIGN_TYPE_WELCOME || $scope.display.emailType.type === CAMPAIGN_TYPE_PASSWORD_RESET; } }; $scope.populateSelectableMembers = function () { $scope.display.selectableMembers = _.chain($scope.members) .filter(function (member) { return EmailSubscriptionService.includeMemberInEmailList('general', member); }) .map(extendWithInformation) .value(); logger.debug('populateSelectableMembers:found', $scope.display.selectableMembers.length, 'members'); }; $scope.populateSelectableMembers(); $scope.calculateMemberFilterDate = function () { $scope.display.memberFilterDate = DateUtils.momentNowNoTime().subtract($scope.display && $scope.display.emailType.monthsInPast, 'months').valueOf(); }; $scope.clearDisplayEmailMembers = function () { $scope.display.emailMembers = []; notify.warning({ title: 'Member selection', message: 'current member selection was cleared' }); }; function extendWithInformation(member) { return $scope.display.expiryEmailsSelected() ? extendWithExpiryInformation(member) : extendWithCreatedInformation(member); } function extendWithExpiryInformation(member) { var expiredActive = member.membershipExpiryDate < $scope.today ? 'expired' : 'active'; var memberGrouping = member.receivedInLastBulkLoad ? expiredActive : 'missing from last bulk load'; var datePrefix = memberGrouping === 'expired' ? ': ' : ', ' + (member.membershipExpiryDate < $scope.today ? 'expired' : 'expiry') + ': '; var text = $filter('fullNameWithAlias')(member) + ' (' + memberGrouping + datePrefix + (DateUtils.displayDate(member.membershipExpiryDate) || 'not known') + ')'; return angular.extend({}, member, {id: member.$id(), text: text, memberGrouping: memberGrouping}); } function extendWithCreatedInformation(member) { var memberGrouping = member.membershipExpiryDate < $scope.today ? 'expired' : 'active'; var text = $filter('fullNameWithAlias')(member) + ' (created ' + (DateUtils.displayDate(member.createdDate) || 'not known') + ')'; return angular.extend({}, member, {id: member.$id(), text: text, memberGrouping: memberGrouping}); } $scope.memberGrouping = function (member) { return member.memberGrouping; }; function populateMembersBasedOnFilter(filter) { logger.debug('populateExpiredMembers: display.emailType ->', $scope.display.emailType); notify.setBusy(); notify.warning({ title: 'Automatically adding expired members', message: ' - please wait for list to be populated' }); $scope.display.memberFilterDate = DateUtils.convertDateField($scope.display.memberFilterDate); $scope.display.emailMembers = _($scope.display.selectableMembers) .filter(filter); notify.warning({ title: 'Members added to email selection', message: 'automatically added ' + $scope.display.emailMembers.length + ' members' }); notify.clearBusy(); } $scope.populateMembers = function (recalcMemberFilterDate) { logger.debug('$scope.display.memberSelection', $scope.display.emailType.memberSelection); this.populateSelectableMembers(); switch ($scope.display.emailType.memberSelection) { case 'recently-added': $scope.populateRecentlyAddedMembers(recalcMemberFilterDate); break; case 'expired-members': $scope.populateExpiredMembers(recalcMemberFilterDate); break } }; $scope.populateRecentlyAddedMembers = function (recalcMemberFilterDate) { if (recalcMemberFilterDate) { $scope.calculateMemberFilterDate(); } populateMembersBasedOnFilter(function (member) { return member.groupMember && (member.createdDate >= $scope.display.memberFilterDate); }); }; $scope.populateExpiredMembers = function (recalcMemberFilterDate) { if (recalcMemberFilterDate) { $scope.calculateMemberFilterDate(); } populateMembersBasedOnFilter(function (member) { return member.groupMember && member.membershipExpiryDate && (member.membershipExpiryDate < $scope.display.memberFilterDate); }); }; $scope.populateMembersMissingFromBulkLoad = function (recalcMemberFilterDate) { if (recalcMemberFilterDate) { $scope.calculateMemberFilterDate(); } populateMembersBasedOnFilter(function (member) { return member.groupMember && member.membershipExpiryDate && !member.receivedInLastBulkLoad; }) }; function displayEmailMembersToMembers() { return _.chain($scope.display.emailMembers) .map(function (memberId) { return _.find($scope.members, function (member) { return member.$id() === memberId.id; }) }) .filter(function (member) { return member && member.email; }).value(); } function addPasswordResetIdToMembers() { var saveMemberPromises = []; _.map(displayEmailMembersToMembers(), function (member) { LoggedInMemberService.setPasswordResetId(member); EmailSubscriptionService.resetUpdateStatusForMember(member); saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member)) }); return $q.all(saveMemberPromises).then(function () { return notify.success('Password reset prepared for ' + saveMemberPromises.length + ' member(s)'); }); } function includeInNextMailchimpListUpdate() { var saveMemberPromises = []; _.map(displayEmailMembersToMembers(), function (member) { EmailSubscriptionService.resetUpdateStatusForMember(member); saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member)) }); return $q.all(saveMemberPromises).then(function () { return notify.success('Member expiration prepared for ' + saveMemberPromises.length + ' member(s)'); }); } function noAction() { } function removeExpiredMembersFromGroup() { logger.debug('removing ', $scope.display.emailMembers.length, 'members from group'); var saveMemberPromises = []; _($scope.display.emailMembers) .map(function (memberId) { return _.find($scope.members, function (member) { return member.$id() === memberId.id; }) }).map(function (member) { member.groupMember = false; EmailSubscriptionService.resetUpdateStatusForMember(member); saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member)) }); return $q.all(saveMemberPromises) .then(function () { return notify.success('EKWG group membership removed for ' + saveMemberPromises.length + ' member(s)'); }) } $scope.cancelSendEmails = function () { $scope.cancel(); }; $scope.sendEmailsDisabled = function () { return $scope.display.emailMembers.length === 0 }; $scope.sendEmails = function () { $scope.alertTypeResetPassword = true; $scope.display.saveInProgress = true; $scope.display.duplicate = false; $q.when(notify.success('Preparing to email ' + $scope.display.emailMembers.length + ' member' + ($scope.display.emailMembers.length === 1 ? '' : 's'), true)) .then($scope.display.emailType.preSend) .then(updateGeneralList) .then(createOrSaveMailchimpSegment) .then(saveSegmentDataToMailchimpConfig) .then(sendEmailCampaign) .then($scope.display.emailType.postSend) .then(notify.clearBusy) .then($scope.cancel) .then(resetSendFlags) .catch(handleSendError); }; function resetSendFlags() { logger.debug('resetSendFlags'); $scope.display.saveInProgress = false; } function updateGeneralList() { return EmailSubscriptionService.createBatchSubscriptionForList('general', $scope.members).then(function (updatedMembers) { $scope.members = updatedMembers; }); } function createOrSaveMailchimpSegment() { return MailchimpSegmentService.saveSegment('general', {segmentId: $scope.display.emailType.segmentId}, $scope.display.emailMembers, $scope.display.emailType.name, $scope.members); } function saveSegmentDataToMailchimpConfig(segmentResponse) { logger.debug('saveSegmentDataToMailchimpConfig:segmentResponse', segmentResponse); return MailchimpConfig.getConfig() .then(function (config) { config.mailchimp.segments.general[$scope.display.emailType.type + 'SegmentId'] = segmentResponse.segment.id; return MailchimpConfig.saveConfig(config) .then(function () { logger.debug('saveSegmentDataToMailchimpConfig:returning segment id', segmentResponse.segment.id); return segmentResponse.segment.id; }); }); } function sendEmailCampaign(segmentId) { var members = $scope.display.emailMembers.length + ' member(s)'; notify.success('Sending ' + $scope.display.emailType.name + ' email to ' + members); logger.debug('about to sendEmailCampaign:', $scope.display.emailType.type, 'campaign Id', $scope.display.emailType.campaignId, 'segmentId', segmentId, 'campaignName', $scope.display.emailType.name); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: $scope.display.emailType.campaignId, campaignName: $scope.display.emailType.name, segmentId: segmentId }).then(function () { notify.success('Sending of ' + $scope.display.emailType.name + ' to ' + members + ' was successful'); }); } $scope.emailMemberList = function () { return _($scope.display.emailMembers) .sortBy(function (emailMember) { return emailMember.text; }).map(function (emailMember) { return emailMember.text; }).join(', '); }; function handleSendError(errorResponse) { $scope.display.saveInProgress = false; notify.error({ title: 'Your notification could not be sent', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + ErrorMessageService.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } MailchimpConfig.getConfig() .then(function (config) { $scope.display.emailTypes = [ { preSend: addPasswordResetIdToMembers, type: CAMPAIGN_TYPE_WELCOME, name: config.mailchimp.campaigns.welcome.name, monthsInPast: config.mailchimp.campaigns.welcome.monthsInPast, campaignId: config.mailchimp.campaigns.welcome.campaignId, segmentId: config.mailchimp.segments.general.welcomeSegmentId, memberSelection: 'recently-added', postSend: noAction, dateTooltip: "All members created in the last " + config.mailchimp.campaigns.welcome.monthsInPast + " month are displayed as a default, as these are most likely to need a welcome email sent" }, { preSend: addPasswordResetIdToMembers, type: CAMPAIGN_TYPE_PASSWORD_RESET, name: config.mailchimp.campaigns.passwordReset.name, monthsInPast: config.mailchimp.campaigns.passwordReset.monthsInPast, campaignId: config.mailchimp.campaigns.passwordReset.campaignId, segmentId: config.mailchimp.segments.general.passwordResetSegmentId, memberSelection: 'recently-added', postSend: noAction, dateTooltip: "All members created in the last " + config.mailchimp.campaigns.passwordReset.monthsInPast + " month are displayed as a default" }, { preSend: includeInNextMailchimpListUpdate, type: CAMPAIGN_TYPE_EXPIRED_MEMBERS_WARNING, name: config.mailchimp.campaigns.expiredMembersWarning.name, monthsInPast: config.mailchimp.campaigns.expiredMembersWarning.monthsInPast, campaignId: config.mailchimp.campaigns.expiredMembersWarning.campaignId, segmentId: config.mailchimp.segments.general.expiredMembersWarningSegmentId, memberSelection: 'expired-members', postSend: noAction, dateTooltip: "Using the expiry date field, you can choose which members will automatically be included. " + "A date " + config.mailchimp.campaigns.expiredMembersWarning.monthsInPast + " months in the past has been pre-selected, to avoid including members whose membership renewal is still progress" }, { preSend: includeInNextMailchimpListUpdate, type: CAMPAIGN_TYPE_EXPIRED_MEMBERS, name: config.mailchimp.campaigns.expiredMembers.name, monthsInPast: config.mailchimp.campaigns.expiredMembers.monthsInPast, campaignId: config.mailchimp.campaigns.expiredMembers.campaignId, segmentId: config.mailchimp.segments.general.expiredMembersSegmentId, memberSelection: 'expired-members', postSend: removeExpiredMembersFromGroup, dateTooltip: "Using the expiry date field, you can choose which members will automatically be included. " + "A date 3 months in the past has been pre-selected, to avoid including members whose membership renewal is still progress" } ]; $scope.display.emailType = $scope.display.emailTypes[0]; $scope.populateMembers(true); }); }] ); /* concatenated from client/src/app/js/memberResources.js */ angular.module('ekwgApp') .factory('MemberResourcesService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('memberResources'); }]) .factory('MemberResourcesReferenceData', ["$log", "URLService", "ContentMetaDataService", "FileUtils", "LoggedInMemberService", "SiteEditService", function ($log, URLService, ContentMetaDataService, FileUtils, LoggedInMemberService, SiteEditService) { var logger = $log.getInstance('MemberResourcesReferenceData'); $log.logLevels['MemberResourcesReferenceData'] = $log.LEVEL.OFF; const subjects = [ { id: "newsletter", description: "Newsletter" }, { id: "siteReleaseNote", description: "Site Release Note" }, { id: "walkPlanning", description: "Walking Planning Advice" } ]; const resourceTypes = [ { id: "email", description: "Email", action: "View email", icon: function () { return "assets/images/local/mailchimp.ico" }, resourceUrl: function (memberResource) { var data = _.property(['data', 'campaign', 'archive_url_long'])(memberResource); logger.debug('email:resourceUrl for', memberResource, data); return data; } }, { id: "file", description: "File", action: "Download", icon: function (memberResource) { return FileUtils.icon(memberResource, 'data') }, resourceUrl: function (memberResource) { var data = memberResource && memberResource.data.fileNameData ? URLService.baseUrl() + ContentMetaDataService.baseUrl("memberResources") + "/" + memberResource.data.fileNameData.awsFileName : ""; logger.debug('file:resourceUrl for', memberResource, data); return data; } }, { id: "url", action: "View page", description: "External Link", icon: function () { return "assets/images/ramblers/favicon.ico" }, resourceUrl: function () { return "TBA"; } } ]; const accessLevels = [ { id: "hidden", description: "Hidden", filter: function () { return SiteEditService.active() || false; } }, { id: "committee", description: "Committee", filter: function () { return SiteEditService.active() || LoggedInMemberService.allowCommittee(); } }, { id: "loggedInMember", description: "Logged-in member", filter: function () { return SiteEditService.active() || LoggedInMemberService.memberLoggedIn(); } }, { id: "public", description: "Public", filter: function () { return true; } }]; function resourceTypeFor(resourceType) { var type = _.find(resourceTypes, function (type) { return type.id === resourceType; }); logger.debug('resourceType for', type, type); return type; } function accessLevelFor(accessLevel) { var level = _.find(accessLevels, function (level) { return level.id === accessLevel; }); logger.debug('accessLevel for', accessLevel, level); return level; } return { subjects: subjects, resourceTypes: resourceTypes, accessLevels: accessLevels, resourceTypeFor: resourceTypeFor, accessLevelFor: accessLevelFor }; }]); /* concatenated from client/src/app/js/memberServices.js */ angular.module('ekwgApp') .factory('MemberUpdateAuditService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('memberUpdateAudit'); }]) .factory('MemberBulkLoadAuditService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('memberBulkLoadAudit'); }]) .factory('MemberAuditService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('memberAudit'); }]) .factory('ExpenseClaimsService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('expenseClaims'); }]) .factory('MemberNamingService', ["$log", "StringUtils", function ($log, StringUtils) { var logger = $log.getInstance('MemberNamingService'); $log.logLevels['MemberNamingService'] = $log.LEVEL.OFF; var createUserName = function (member) { return StringUtils.replaceAll(' ', '', (member.firstName + '.' + member.lastName).toLowerCase()); }; function createDisplayName(member) { return member.firstName.trim() + ' ' + member.lastName.trim().substring(0, 1).toUpperCase(); } function createUniqueUserName(member, members) { return createUniqueValueFrom(createUserName, 'userName', member, members) } function createUniqueDisplayName(member, members) { return createUniqueValueFrom(createDisplayName, 'displayName', member, members) } function createUniqueValueFrom(nameFunction, field, member, members) { var attempts = 0; var suffix = ""; while (true) { var createdName = nameFunction(member) + suffix; if (!memberFieldExists(field, createdName, members)) { return createdName } else { attempts++; suffix = attempts; } } } function memberFieldExists(field, value, members) { var member = _(members).find(function (member) { return member[field] === value; }); var returnValue = member && member[field]; logger.debug('field', field, 'matching', value, member, '->', returnValue); return returnValue; } return { createDisplayName: createDisplayName, createUserName: createUserName, createUniqueUserName: createUniqueUserName, createUniqueDisplayName: createUniqueDisplayName }; }]) .factory('MemberService', ["$mongolabResourceHttp", "$log", function ($mongolabResourceHttp, $log) { var logger = $log.getInstance('MemberService'); var noLogger = $log.getInstance('MemberServiceMuted'); $log.logLevels['MemberServiceMuted'] = $log.LEVEL.OFF; $log.logLevels['MemberService'] = $log.LEVEL.OFF; var memberService = $mongolabResourceHttp('members'); memberService.filterFor = { SOCIAL_MEMBERS_SUBSCRIBED: function (member) { return member.groupMember && member.socialMember && member.mailchimpLists.socialEvents.subscribed }, WALKS_MEMBERS_SUBSCRIBED: function (member) { return member.groupMember && member.mailchimpLists.walks.subscribed }, GENERAL_MEMBERS_SUBSCRIBED: function (member) { return member.groupMember && member.mailchimpLists.general.subscribed }, GROUP_MEMBERS: function (member) { return member.groupMember; }, COMMITTEE_MEMBERS: function (member) { return member.groupMember && member.committee; }, SOCIAL_MEMBERS: function (member) { return member.groupMember && member.socialMember; }, }; memberService.allLimitedFields = function allLimitedFields(filterFunction) { return memberService.all({ fields: { mailchimpLists: 1, groupMember: 1, socialMember: 1, financeAdmin: 1, treasuryAdmin: 1, fileAdmin: 1, committee: 1, walkChangeNotifications: 1, email: 1, displayName: 1, contactId: 1, mobileNumber: 1, $id: 1, firstName: 1, lastName: 1, nameAlias: 1 } }).then(function (members) { return _.chain(members) .filter(filterFunction) .sortBy(function (member) { return member.firstName + member.lastName; }).value(); }); }; memberService.toMember = function (memberIdOrObject, members) { var memberId = (_.has(memberIdOrObject, 'id') ? memberIdOrObject.id : memberIdOrObject); noLogger.info('toMember:memberIdOrObject', memberIdOrObject, '->', memberId); var member = _.find(members, function (member) { return member.$id() === memberId; }); noLogger.info('toMember:', memberIdOrObject, '->', member); return member; }; memberService.allMemberMembersWithPrivilege = function (privilege, members) { var filteredMembers = _.filter(members, function (member) { return member.groupMember && member[privilege]; }); logger.debug('allMemberMembersWithPrivilege:privilege', privilege, 'filtered from', members.length, '->', filteredMembers.length, 'members ->', filteredMembers); return filteredMembers; }; memberService.allMemberIdsWithPrivilege = function (privilege, members) { return memberService.allMemberMembersWithPrivilege(privilege, members).map(extractMemberId); function extractMemberId(member) { return member.$id() } }; return memberService; }]); /* concatenated from client/src/app/js/notificationUrl.js */ angular.module("ekwgApp") .component("notificationUrl", { templateUrl: "partials/components/notification-url.html", controller: ["$log", "URLService", "FileUtils", function ($log, URLService, FileUtils) { var ctrl = this; var logger = $log.getInstance("NotificationUrlController"); $log.logLevels['NotificationUrlController'] = $log.LEVEL.OFF; ctrl.anchor_href = function () { return URLService.notificationHref(ctrl); }; ctrl.anchor_target = function () { return "_blank"; }; ctrl.anchor_text = function () { var text = (!ctrl.text && ctrl.name) ? FileUtils.basename(ctrl.name) : ctrl.text || ctrl.anchor_href(); logger.debug("text", text); return text; }; }], bindings: { name: "@", text: "@", type: "@", id: "@", area: "@" } }); /* concatenated from client/src/app/js/notifier.js */ angular.module('ekwgApp') .factory('Notifier', ["$log", "ErrorMessageService", function ($log, ErrorMessageService) { var ALERT_ERROR = {class: 'alert-danger', icon: 'glyphicon-exclamation-sign', failure: true}; var ALERT_WARNING = {class: 'alert-warning', icon: 'glyphicon-info-sign'}; var ALERT_INFO = {class: 'alert-success', icon: 'glyphicon-info-sign'}; var ALERT_SUCCESS = {class: 'alert-success', icon: 'glyphicon-ok'}; var logger = $log.getInstance('Notifier'); $log.logLevels['Notifier'] = $log.LEVEL.OFF; return function (scope) { scope.alertClass = ALERT_SUCCESS.class; scope.alert = ALERT_SUCCESS; scope.alertMessages = []; scope.alertHeading = []; scope.ready = false; function setReady() { clearBusy(); return scope.ready = true; } function clearBusy() { logger.debug('clearing busy'); return scope.busy = false; } function setBusy() { logger.debug('setting busy'); return scope.busy = true; } function showContactUs(state) { logger.debug('setting showContactUs', state); return scope.showContactUs = state; } function notifyAlertMessage(alertType, message, append, busy) { var messageText = message && ErrorMessageService.stringify(_.has(message, 'message') ? message.message : message); if (busy) setBusy(); if (!append || alertType === ALERT_ERROR) scope.alertMessages = []; if (messageText) scope.alertMessages.push(messageText); scope.alertTitle = message && _.has(message, 'title') ? message.title : undefined; scope.alert = alertType; scope.alertClass = alertType.class; scope.showAlert = scope.alertMessages.length > 0; scope.alertMessage = scope.alertMessages.join(', '); if (alertType === ALERT_ERROR && !_.has(message, 'continue')) { logger.error('notifyAlertMessage:', 'class =', alertType, 'messageText =', messageText, 'append =', append); clearBusy(); throw message; } else { return logger.debug('notifyAlertMessage:', 'class =', alertType, 'messageText =', messageText, 'append =', append, 'showAlert =', scope.showAlert); } } function progress(message, busy) { return notifyAlertMessage(ALERT_INFO, message, false, busy) } function hide() { notifyAlertMessage(ALERT_SUCCESS); return clearBusy(); } function success(message, busy) { return notifyAlertMessage(ALERT_SUCCESS, message, false, busy) } function successWithAppend(message, busy) { return notifyAlertMessage(ALERT_SUCCESS, message, true, busy) } function error(message, append, busy) { return notifyAlertMessage(ALERT_ERROR, message, append, busy) } function warning(message, append, busy) { return notifyAlertMessage(ALERT_WARNING, message, append, busy) } return { success: success, successWithAppend: successWithAppend, progress: progress, progressWithAppend: successWithAppend, error: error, warning: warning, showContactUs: showContactUs, setBusy: setBusy, clearBusy: clearBusy, setReady: setReady, hide: hide } } }]); /* concatenated from client/src/app/js/profile.js */ angular.module('ekwgApp') .factory('ProfileConfirmationService', ["$filter", "LoggedInMemberService", "DateUtils", function ($filter, LoggedInMemberService, DateUtils) { var confirmProfile = function (member) { if (member) { member.profileSettingsConfirmed = true; member.profileSettingsConfirmedAt = DateUtils.nowAsValue(); member.profileSettingsConfirmedBy = $filter('fullNameWithAlias')(LoggedInMemberService.loggedInMember()); } }; var unconfirmProfile = function (member) { if (member) { delete member.profileSettingsConfirmed; delete member.profileSettingsConfirmedAt; delete member.profileSettingsConfirmedBy; } }; var processMember = function (member) { if (member) { if (member.profileSettingsConfirmed) { confirmProfile(member) } else { unconfirmProfile(member) } } }; return { confirmProfile: confirmProfile, unconfirmProfile: unconfirmProfile, processMember: processMember }; }]) .controller('ProfileController', ["$q", "$rootScope", "$routeParams", "$scope", "LoggedInMemberService", "MemberService", "URLService", "ProfileConfirmationService", "EmailSubscriptionService", "CommitteeReferenceData", function ($q, $rootScope, $routeParams, $scope, LoggedInMemberService, MemberService, URLService, ProfileConfirmationService, EmailSubscriptionService, CommitteeReferenceData) { $scope.showArea = function (area) { URLService.navigateTo('admin', area) }; $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; function isArea(area) { return (area === $routeParams.area); } var LOGIN_DETAILS = 'login details'; var PERSONAL_DETAILS = 'personal details'; var CONTACT_PREFERENCES = 'contact preferences'; var ALERT_CLASS_DANGER = 'alert-danger'; var ALERT_CLASS_SUCCESS = 'alert-success'; $scope.currentMember = {}; $scope.enteredMemberCredentials = {}; $scope.alertClass = ALERT_CLASS_SUCCESS; $scope.alertType = LOGIN_DETAILS; $scope.alertMessages = []; $scope.personalDetailsOpen = isArea('personal-details'); $scope.loginDetailsOpen = isArea('login-details'); $scope.contactPreferencesOpen = isArea('contact-preferences'); $scope.showAlertPersonalDetails = false; $scope.showAlertLoginDetails = false; $scope.showAlertContactPreferences = false; applyAllowEdits('controller init'); refreshMember(); $scope.$on('memberLoginComplete', function () { $scope.alertMessages = []; refreshMember(); applyAllowEdits('memberLoginComplete'); }); $scope.$on('memberLogoutComplete', function () { $scope.alertMessages = []; applyAllowEdits('memberLogoutComplete'); }); $scope.undoChanges = function () { refreshMember(); }; function saveOrUpdateSuccessful() { $scope.enteredMemberCredentials.newPassword = null; $scope.enteredMemberCredentials.newPasswordConfirm = null; $scope.alertMessages.push('Your ' + $scope.alertType + ' were saved successfully and will be effective on your next login.'); showAlert(ALERT_CLASS_SUCCESS, $scope.alertType); } function saveOrUpdateUnsuccessful(message) { var messageDefaulted = message || 'Please try again later.'; $scope.alertMessages.push('Changes to your ' + $scope.alertType + ' could not be saved. ' + messageDefaulted); showAlert(ALERT_CLASS_DANGER, $scope.alertType); } $scope.saveLoginDetails = function () { $scope.alertMessages = []; validateUserNameExistence(); }; $scope.$on('userNameExistenceCheckComplete', function () { validatePassword(); validateUserName(); if ($scope.alertMessages.length === 0) { saveMemberDetails(LOGIN_DETAILS) } else { showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); } }); $scope.savePersonalDetails = function () { $scope.alertMessages = []; saveMemberDetails(PERSONAL_DETAILS); }; $scope.saveContactPreferences = function () { $scope.alertMessages = []; ProfileConfirmationService.confirmProfile($scope.currentMember); saveMemberDetails(CONTACT_PREFERENCES); }; $scope.loggedIn = function () { return LoggedInMemberService.memberLoggedIn(); }; function validatePassword() { if ($scope.enteredMemberCredentials.newPassword || $scope.enteredMemberCredentials.newPasswordConfirm) { // console.log('validating password change old=', $scope.enteredMemberCredentials.newPassword, 'new=', $scope.enteredMemberCredentials.newPasswordConfirm); if ($scope.currentMember.password === $scope.enteredMemberCredentials.newPassword) { $scope.alertMessages.push('The new password was the same as the old one.'); } else if ($scope.enteredMemberCredentials.newPassword !== $scope.enteredMemberCredentials.newPasswordConfirm) { $scope.alertMessages.push('The new password was not confirmed correctly.'); } else if ($scope.enteredMemberCredentials.newPassword.length < 6) { $scope.alertMessages.push('The new password needs to be at least 6 characters long.'); } else { $scope.currentMember.password = $scope.enteredMemberCredentials.newPassword; // console.log('validating password change - successful'); } } } function validateUserName() { if ($scope.enteredMemberCredentials.userName !== $scope.currentMember.userName) { $scope.enteredMemberCredentials.userName = $scope.enteredMemberCredentials.userName.trim(); if ($scope.enteredMemberCredentials.userName.length === 0) { $scope.alertMessages.push('The new user name cannot be blank.'); } else { $scope.currentMember.userName = $scope.enteredMemberCredentials.userName; } } } function undoChangesTo(alertType) { refreshMember(); $scope.alertMessages = ['Changes to your ' + alertType + ' were reverted.']; showAlert(ALERT_CLASS_SUCCESS, alertType); } $scope.undoLoginDetails = function () { undoChangesTo(LOGIN_DETAILS); }; $scope.undoPersonalDetails = function () { undoChangesTo(PERSONAL_DETAILS); }; $scope.undoContactPreferences = function () { undoChangesTo(CONTACT_PREFERENCES); }; function saveMemberDetails(alertType) { $scope.alertType = alertType; EmailSubscriptionService.resetUpdateStatusForMember($scope.currentMember); LoggedInMemberService.saveMember($scope.currentMember, saveOrUpdateSuccessful, saveOrUpdateUnsuccessful); } function showAlert(alertClass, alertType) { if ($scope.alertMessages.length > 0) { $scope.alertClass = alertClass; $scope.alertMessage = $scope.alertMessages.join(', '); $scope.showAlertLoginDetails = alertType === LOGIN_DETAILS; $scope.showAlertPersonalDetails = alertType === PERSONAL_DETAILS; $scope.showAlertContactPreferences = alertType === CONTACT_PREFERENCES; } else { $scope.showAlertLoginDetails = false; $scope.showAlertPersonalDetails = false; $scope.showAlertContactPreferences = false; } } function applyAllowEdits(event) { $scope.allowEdits = LoggedInMemberService.memberLoggedIn(); $scope.isAdmin = LoggedInMemberService.allowMemberAdminEdits(); } function refreshMember() { if (LoggedInMemberService.memberLoggedIn()) { LoggedInMemberService.getMemberForUserName(LoggedInMemberService.loggedInMember().userName) .then(function (member) { if (!_.isEmpty(member)) { $scope.currentMember = member; $scope.enteredMemberCredentials = {userName: $scope.currentMember.userName}; } else { $scope.alertMessages.push('Could not refresh member'); showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); } }, function (response) { $scope.alertMessages.push('Unexpected error occurred: ' + response); showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); }) } } function validateUserNameExistence() { if ($scope.enteredMemberCredentials.userName !== $scope.currentMember.userName) { LoggedInMemberService.getMemberForUserName($scope.enteredMemberCredentials.userName) .then(function (member) { if (!_.isEmpty(member)) { $scope.alertMessages.push('The user name ' + $scope.enteredMemberCredentials.userName + ' is already used by another member. Please choose another.'); $scope.enteredMemberCredentials.userName = $scope.currentMember.userName; } $rootScope.$broadcast('userNameExistenceCheckComplete'); }, function (response) { $scope.alertMessages.push('Unexpected error occurred: ' + response); showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); }); } else { $rootScope.$broadcast('userNameExistenceCheckComplete'); } } }]); /* concatenated from client/src/app/js/ramblersWalksServices.js */ angular.module('ekwgApp') .factory('RamblersHttpService', ["$q", "$http", function ($q, $http) { function call(serviceCallType, method, url, data, params) { var deferredTask = $q.defer(); deferredTask.notify(serviceCallType); $http({ method: method, data: data, params: params, url: url }).then(function (response) { var responseData = response.data; if (responseData.error) { deferredTask.reject(response); } else { deferredTask.notify(responseData.information); deferredTask.resolve(responseData) } }).catch(function (response) { deferredTask.reject(response); }); return deferredTask.promise; } return { call: call } }]) .factory('RamblersWalksAndEventsService', ["$log", "$rootScope", "$http", "$q", "$filter", "DateUtils", "RamblersHttpService", "LoggedInMemberService", "CommitteeReferenceData", function ($log, $rootScope, $http, $q, $filter, DateUtils, RamblersHttpService, LoggedInMemberService, CommitteeReferenceData) { var logger = $log.getInstance('RamblersWalksAndEventsService'); $log.logLevels['RamblersWalksAndEventsService'] = $log.LEVEL.OFF; function uploadRamblersWalks(data) { return RamblersHttpService.call('Upload Ramblers walks', 'POST', 'walksAndEventsManager/uploadWalks', data); } function listRamblersWalks() { return RamblersHttpService.call('List Ramblers walks', 'GET', 'walksAndEventsManager/listWalks'); } var walkDescriptionPrefix = function () { return RamblersHttpService.call('Ramblers description Prefix', 'GET', 'walksAndEventsManager/walkDescriptionPrefix'); }; var walkBaseUrl = function () { return RamblersHttpService.call('Ramblers walk url', 'GET', 'walksAndEventsManager/walkBaseUrl'); }; function exportWalksFileName() { return 'walks-export-' + DateUtils.asMoment().format('DD-MMMM-YYYY-HH-mm') + '.csv' } function exportableWalks(walkExports) { return _.chain(walkExports) .filter(function (walkExport) { return walkExport.selected; }) .sortBy(function (walkExport) { return walkExport.walk.walkDate; }) .value(); } function exportWalks(walkExports, members) { return _(exportableWalks(walkExports)).pluck('walk').map(function (walk) { return walkToCsvRecord(walk, members) }); } function createWalksForExportPrompt(walks, members) { return listRamblersWalks() .then(updateWalksWithRamblersWalkData(walks)) .then(function (updatedWalks) { return returnWalksExport(updatedWalks, members); }); } function updateWalksWithRamblersWalkData(walks) { var unreferencedList = collectExistingRamblersIdsFrom(walks); logger.debug(unreferencedList.length, ' existing ramblers walk(s) found', unreferencedList); return function (ramblersWalksResponses) { var savePromises = []; _(ramblersWalksResponses.responseData).each(function (ramblersWalksResponse) { var foundWalk = _.find(walks, function (walk) { return DateUtils.asString(walk.walkDate, undefined, 'dddd, Do MMMM YYYY') === ramblersWalksResponse.ramblersWalkDate }); if (!foundWalk) { logger.debug('no match found for ramblersWalksResponse', ramblersWalksResponse); } else { unreferencedList = _.without(unreferencedList, ramblersWalksResponse.ramblersWalkId); if (foundWalk && foundWalk.ramblersWalkId !== ramblersWalksResponse.ramblersWalkId) { logger.debug('updating walk from', foundWalk.ramblersWalkId || 'empty', '->', ramblersWalksResponse.ramblersWalkId, 'on', $filter('displayDate')(foundWalk.walkDate)); foundWalk.ramblersWalkId = ramblersWalksResponse.ramblersWalkId; savePromises.push(foundWalk.$saveOrUpdate()) } else { logger.debug('no update required for walk', foundWalk.ramblersWalkId, foundWalk.walkDate, DateUtils.displayDay(foundWalk.walkDate)); } } }); if (unreferencedList.length > 0) { logger.debug('removing old ramblers walk(s)', unreferencedList, 'from existing walks'); _.chain(unreferencedList) .each(function (ramblersWalkId) { var walk = _.findWhere(walks, {ramblersWalkId: ramblersWalkId}); if (walk) { logger.debug('removing ramblers walk', walk.ramblersWalkId, 'from walk on', $filter('displayDate')(walk.walkDate)); delete walk.ramblersWalkId; savePromises.push(walk.$saveOrUpdate()) } }).value(); } return $q.all(savePromises).then(function () { return walks; }); } } function collectExistingRamblersIdsFrom(walks) { return _.chain(walks) .filter(function (walk) { return walk.ramblersWalkId; }) .map(function (walk) { return walk.ramblersWalkId; }) .value(); } function returnWalksExport(walks, members) { var todayValue = DateUtils.momentNowNoTime().valueOf(); return _.chain(walks) .filter(function (walk) { return (walk.walkDate >= todayValue) && walk.briefDescriptionAndStartPoint; }) .sortBy(function (walk) { return walk.walkDate; }) .map(function (walk) { return validateWalk(walk, members); }) .value(); } function uploadToRamblers(walkExports, members, notify) { notify.setBusy(); logger.debug('sourceData', walkExports); var deleteWalks = _.chain(exportableWalks(walkExports)).pluck('walk') .filter(function (walk) { return walk.ramblersWalkId; }).map(function (walk) { return walk.ramblersWalkId; }).value(); let rows = exportWalks(walkExports, members); let fileName = exportWalksFileName(); var data = { headings: exportColumnHeadings(), rows: rows, fileName: fileName, deleteWalks: deleteWalks, ramblersUser: LoggedInMemberService.loggedInMember().firstName }; logger.debug('exporting', data); notify.warning({ title: 'Ramblers walks upload', message: 'Uploading ' + rows.length + ' walk(s) to Ramblers...' }); return uploadRamblersWalks(data) .then(function (response) { notify.warning({ title: 'Ramblers walks upload', message: 'Upload of ' + rows.length + ' walk(s) to Ramblers has been submitted. Monitor the Walk upload audit tab for progress' }); logger.debug('success response data', response); notify.clearBusy(); return fileName; }) .catch(function (response) { logger.debug('error response data', response); notify.error({ title: 'Ramblers walks upload failed', message: response }); notify.clearBusy(); }); } function validateWalk(walk, members) { var walkValidations = []; if (_.isEmpty(walk)) { walkValidations.push('walk does not exist'); } else { if (_.isEmpty(walkTitle(walk))) walkValidations.push('title is missing'); if (_.isEmpty(walkDistanceMiles(walk))) walkValidations.push('distance is missing'); if (_.isEmpty(walk.startTime)) walkValidations.push('start time is missing'); if (walkStartTime(walk) === 'Invalid date') walkValidations.push('start time [' + walk.startTime + '] is invalid'); if (_.isEmpty(walk.grade)) walkValidations.push('grade is missing'); if (_.isEmpty(walk.longerDescription)) walkValidations.push('description is missing'); if (_.isEmpty(walk.postcode) && _.isEmpty(walk.gridReference)) walkValidations.push('both postcode and grid reference are missing'); if (_.isEmpty(walk.contactId)) { var contactIdMessage = LoggedInMemberService.allowWalkAdminEdits() ? 'this can be supplied for this walk on Walk Leader tab' : 'this will need to be setup for you by ' + CommitteeReferenceData.contactUsField('walks', 'fullName'); walkValidations.push('walk leader has no Ramblers contact Id setup on their member record (' + contactIdMessage + ')'); } if (_.isEmpty(walk.displayName) && _.isEmpty(walk.displayName)) walkValidations.push('displayName for walk leader is missing'); } return { walk: walk, walkValidations: walkValidations, publishedOnRamblers: walk && !_.isEmpty(walk.ramblersWalkId), selected: walk && walkValidations.length === 0 && _.isEmpty(walk.ramblersWalkId) } } var nearestTown = function (walk) { return walk.nearestTown ? 'Nearest Town is ' + walk.nearestTown : ''; }; function walkTitle(walk) { var walkDescription = []; if (walk.briefDescriptionAndStartPoint) walkDescription.push(walk.briefDescriptionAndStartPoint); return _.chain(walkDescription).map(replaceSpecialCharacters).value().join('. '); } function walkDescription(walk) { return replaceSpecialCharacters(walk.longerDescription); } function walkType(walk) { return walk.walkType || "Circular"; } function asString(value) { return value ? value : ''; } function contactDisplayName(walk) { return walk.displayName ? replaceSpecialCharacters(_.first(walk.displayName.split(' '))) : ''; } function contactIdLookup(walk, members) { if (walk.contactId) { return walk.contactId; } else { var member = _(members).find(function (member) { return member.$id() === walk.walkLeaderMemberId; }); var returnValue = member && member.contactId; logger.debug('contactId: for walkLeaderMemberId', walk.walkLeaderMemberId, '->', returnValue); return returnValue; } } function replaceSpecialCharacters(value) { return value ? value .replace("’", "'") .replace("é", "e") .replace("’", "'") .replace('…', '…') .replace('–', '–') .replace('’', '’') .replace('“', '“') : ''; } function walkDistanceMiles(walk) { return walk.distance ? String(parseFloat(walk.distance).toFixed(1)) : ''; } function walkStartTime(walk) { return walk.startTime ? DateUtils.asString(walk.startTime, 'HH mm', 'HH:mm') : ''; } function walkGridReference(walk) { return walk.gridReference ? walk.gridReference : ''; } function walkPostcode(walk) { return walk.gridReference ? '' : walk.postcode ? walk.postcode : ''; } function walkDate(walk) { return DateUtils.asString(walk.walkDate, undefined, 'DD-MM-YYYY'); } function exportColumnHeadings() { return [ "Date", "Title", "Description", "Linear or Circular", "Starting postcode", "Starting gridref", "Starting location details", "Show exact starting point", "Start time", "Show exact meeting point?", "Meeting time", "Restriction", "Difficulty", "Local walk grade", "Distance miles", "Contact id", "Contact display name" ]; } function walkToCsvRecord(walk, members) { return { "Date": walkDate(walk), "Title": walkTitle(walk), "Description": walkDescription(walk), "Linear or Circular": walkType(walk), "Starting postcode": walkPostcode(walk), "Starting gridref": walkGridReference(walk), "Starting location details": nearestTown(walk), "Show exact starting point": "Yes", "Start time": walkStartTime(walk), "Show exact meeting point?": "Yes", "Meeting time": walkStartTime(walk), "Restriction": "Public", "Difficulty": asString(walk.grade), "Local walk grade": asString(walk.grade), "Distance miles": walkDistanceMiles(walk), "Contact id": contactIdLookup(walk, members), "Contact display name": contactDisplayName(walk) }; } return { uploadToRamblers: uploadToRamblers, validateWalk: validateWalk, walkDescriptionPrefix: walkDescriptionPrefix, walkBaseUrl: walkBaseUrl, exportWalksFileName: exportWalksFileName, createWalksForExportPrompt: createWalksForExportPrompt, exportWalks: exportWalks, exportableWalks: exportableWalks, exportColumnHeadings: exportColumnHeadings } }] ); /* concatenated from client/src/app/js/resetPasswordController.js */ angular.module("ekwgApp") .controller("ResetPasswordController", ["$q", "$log", "$scope", "AuthenticationModalsService", "ValidationUtils", "LoggedInMemberService", "URLService", "Notifier", "userName", "message", "close", function ($q, $log, $scope, AuthenticationModalsService, ValidationUtils, LoggedInMemberService, URLService, Notifier, userName, message, close) { var logger = $log.getInstance('ResetPasswordController'); $log.logLevels['ResetPasswordController'] = $log.LEVEL.OFF; $scope.notify = {}; $scope.memberCredentials = {userName: userName}; var notify = Notifier($scope.notify); if (message) { notify.progress({ title: "Reset password", message: message }); } $scope.actions = { submittable: function () { var newPasswordPopulated = ValidationUtils.fieldPopulated($scope.memberCredentials, "newPassword"); var newPasswordConfirmPopulated = ValidationUtils.fieldPopulated($scope.memberCredentials, "newPasswordConfirm"); logger.info("notSubmittable: newPasswordConfirmPopulated", newPasswordConfirmPopulated, "newPasswordPopulated", newPasswordPopulated); return newPasswordPopulated && newPasswordConfirmPopulated; }, close: function () { close() }, resetPassword: function () { notify.showContactUs(false); notify.setBusy(); notify.progress({ busy: true, title: "Reset password", message: "Attempting reset of password for " + $scope.memberCredentials.userName }); LoggedInMemberService.resetPassword($scope.memberCredentials.userName, $scope.memberCredentials.newPassword, $scope.memberCredentials.newPasswordConfirm).then(function () { var loginResponse = LoggedInMemberService.loginResponse(); if (LoggedInMemberService.memberLoggedIn()) { notify.hide(); close(); if (!LoggedInMemberService.loggedInMember().profileSettingsConfirmed) { return URLService.navigateTo("mailing-preferences"); } return true; } else { notify.showContactUs(true); notify.error({ title: "Reset password failed", message: loginResponse.alertMessage }); } return true; }); } } }] ); /* concatenated from client/src/app/js/resetPasswordFailedController.js */ angular.module('ekwgApp') .controller('ResetPasswordFailedController', ["$log", "$scope", "URLService", "Notifier", "CommitteeReferenceData", "close", function ($log, $scope, URLService, Notifier, CommitteeReferenceData, close) { var logger = $log.getInstance('ResetPasswordFailedController'); $log.logLevels['MemberAdminController'] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); logger.info("CommitteeReferenceData:", CommitteeReferenceData.ready); notify.showContactUs(true); notify.error({ continue: true, title: "Reset password failed", message: "The password reset link you followed has either expired or is invalid. Click Restart Forgot Password to try again" }); $scope.actions = { close: function () { close() }, forgotPassword: function () { URLService.navigateTo("forgot-password"); }, } }]); /* concatenated from client/src/app/js/services.js */ angular.module('ekwgApp') .factory('DateUtils', ["$log", function ($log) { var logger = $log.getInstance('DateUtils'); $log.logLevels['DateUtils'] = $log.LEVEL.OFF; var formats = { displayDateAndTime: 'ddd DD-MMM-YYYY, h:mm:ss a', displayDateTh: 'MMMM Do YYYY', displayDate: 'ddd DD-MMM-YYYY', displayDay: 'dddd MMMM D, YYYY', ddmmyyyyWithSlashes: 'DD/MM/YYYY', yyyymmdd: 'YYYYMMDD' }; function isDate(value) { return value && asMoment(value).isValid(); } function asMoment(dateValue, inputFormat) { return moment(dateValue, inputFormat).tz("Europe/London"); } function momentNow() { return asMoment(); } function asString(dateValue, inputFormat, outputFormat) { var returnValue = dateValue ? asMoment(dateValue, inputFormat).format(outputFormat) : undefined; logger.debug('asString: dateValue ->', dateValue, 'inputFormat ->', inputFormat, 'outputFormat ->', outputFormat, 'returnValue ->', returnValue); return returnValue; } function asValue(dateValue, inputFormat) { return asMoment(dateValue, inputFormat).valueOf(); } function nowAsValue() { return asMoment(undefined, undefined).valueOf(); } function mailchimpDate(dateValue) { return asString(dateValue, undefined, formats.ddmmyyyyWithSlashes); } function displayDateAndTime(dateValue) { return asString(dateValue, undefined, formats.displayDateAndTime); } function displayDate(dateValue) { return asString(dateValue, undefined, formats.displayDate); } function displayDay(dateValue) { return asString(dateValue, undefined, formats.displayDay); } function asValueNoTime(dateValue, inputFormat) { var returnValue = asMoment(dateValue, inputFormat).startOf('day').valueOf(); logger.debug('asValueNoTime: dateValue ->', dateValue, 'returnValue ->', returnValue, '->', displayDateAndTime(returnValue)); return returnValue; } function currentMemberBulkLoadDisplayDate() { return asString(momentNowNoTime().startOf('month'), undefined, formats.yyyymmdd); } function momentNowNoTime() { return asMoment().startOf('day'); } function convertDateFieldInObject(object, field) { var inputValue = object[field]; object[field] = convertDateField(inputValue); return object; } function convertDateField(inputValue) { if (inputValue) { var dateValue = asValueNoTime(inputValue); if (dateValue !== inputValue) { logger.debug('Converting date from', inputValue, '(' + displayDateAndTime(inputValue) + ') to', dateValue, '(' + displayDateAndTime(dateValue) + ')'); return dateValue; } else { logger.debug(inputValue, inputValue, 'is already in correct format'); return inputValue; } } else { logger.debug(inputValue, 'is not a date - no conversion'); return inputValue; } } return { formats: formats, displayDateAndTime: displayDateAndTime, displayDay: displayDay, displayDate: displayDate, mailchimpDate: mailchimpDate, convertDateFieldInObject: convertDateFieldInObject, convertDateField: convertDateField, isDate: isDate, asMoment: asMoment, nowAsValue: nowAsValue, momentNow: momentNow, momentNowNoTime: momentNowNoTime, asString: asString, asValue: asValue, asValueNoTime: asValueNoTime, currentMemberBulkLoadDisplayDate: currentMemberBulkLoadDisplayDate }; }]) .factory('DbUtils', ["$log", "DateUtils", "LoggedInMemberService", "AUDIT_CONFIG", function ($log, DateUtils, LoggedInMemberService, AUDIT_CONFIG) { var logger = $log.getInstance('DbUtilsLogger'); $log.logLevels['DbUtilsLogger'] = $log.LEVEL.OFF; function removeEmptyFieldsIn(obj) { _.each(obj, function (value, field) { logger.debug('processing', typeof(field), 'field', field, 'value', value); if (_.contains([null, undefined, ""], value)) { logger.debug('removing non-populated', typeof(field), 'field', field); delete obj[field]; } }); } function auditedSaveOrUpdate(resource, updateCallback, errorCallback) { if (AUDIT_CONFIG.auditSave) { if (resource.$id()) { resource.updatedDate = DateUtils.nowAsValue(); resource.updatedBy = LoggedInMemberService.loggedInMember().memberId; logger.debug('Auditing save of existing document', resource); } else { resource.createdDate = DateUtils.nowAsValue(); resource.createdBy = LoggedInMemberService.loggedInMember().memberId; logger.debug('Auditing save of new document', resource); } } else { resource = DateUtils.convertDateFieldInObject(resource, 'createdDate'); logger.debug('Not auditing save of', resource); } return resource.$saveOrUpdate(updateCallback, updateCallback, errorCallback || updateCallback, errorCallback || updateCallback) } return { removeEmptyFieldsIn: removeEmptyFieldsIn, auditedSaveOrUpdate: auditedSaveOrUpdate, } }]) .factory('FileUtils', ["$log", "DateUtils", "URLService", "ContentMetaDataService", function ($log, DateUtils, URLService, ContentMetaDataService) { var logger = $log.getInstance('FileUtils'); $log.logLevels['FileUtils'] = $log.LEVEL.OFF; function basename(path) { return path.split(/[\\/]/).pop() } function path(path) { return path.split(basename(path))[0]; } function attachmentTitle(resource, container, resourceName) { return (resource && _.isEmpty(getFileNameData(resource, container)) ? 'Attach' : 'Replace') + ' ' + resourceName; } function getFileNameData(resource, container) { return container ? resource[container].fileNameData : resource.fileNameData; } function resourceUrl(resource, container, metaDataPathSegment) { var fileNameData = getFileNameData(resource, container); return resource && fileNameData ? URLService.baseUrl() + ContentMetaDataService.baseUrl(metaDataPathSegment) + '/' + fileNameData.awsFileName : ''; } function previewUrl(memberResource) { if (memberResource) { switch (memberResource.resourceType) { case "email": return memberResource.data.campaign.archive_url_long; case "file": return memberResource.data.campaign.archive_url_long; } } var fileNameData = getFileNameData(resource, container); return resource && fileNameData ? URLService.baseUrl() + ContentMetaDataService.baseUrl(metaDataPathSegment) + '/' + fileNameData.awsFileName : ''; } function resourceTitle(resource) { logger.debug('resourceTitle:resource =>', resource); return resource ? (DateUtils.asString(resource.resourceDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + (resource.data ? resource.data.fileNameData.title : "")) : ''; } function fileExtensionIs(fileName, extensions) { return _.contains(extensions, fileExtension(fileName)); } function fileExtension(fileName) { return fileName ? _.last(fileName.split('.')).toLowerCase() : ''; } function icon(resource, container) { var icon = 'icon-default.jpg'; var fileNameData = getFileNameData(resource, container); if (fileNameData && fileExtensionIs(fileNameData.awsFileName, ['doc', 'docx', 'jpg', 'pdf', 'ppt', 'png', 'txt', 'xls', 'xlsx'])) { icon = 'icon-' + fileExtension(fileNameData.awsFileName).substring(0, 3) + '.jpg'; } return "assets/images/ramblers/" + icon; } return { fileExtensionIs: fileExtensionIs, fileExtension: fileExtension, basename: basename, path: path, attachmentTitle: attachmentTitle, resourceUrl: resourceUrl, resourceTitle: resourceTitle, icon: icon } }]) .factory('StringUtils', ["DateUtils", "$filter", function (DateUtils, $filter) { function replaceAll(find, replace, str) { return str ? str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace) : str; } function stripLineBreaks(str, andTrim) { var replacedValue = str.replace(/(\r\n|\n|\r)/gm, ''); return andTrim && replacedValue ? replacedValue.trim() : replacedValue; } function left(str, chars) { return str.substr(0, chars); } function formatAudit(who, when, members) { var by = who ? 'by ' + $filter('memberIdToFullName')(who, members) : ''; return (who || when) ? by + (who && when ? ' on ' : '') + DateUtils.displayDateAndTime(when) : '(not audited)'; } return { left: left, replaceAll: replaceAll, stripLineBreaks: stripLineBreaks, formatAudit: formatAudit } }]).factory('ValidationUtils', function () { function fieldPopulated(object, path) { return (_.property(path)(object) || "").length > 0; } return { fieldPopulated: fieldPopulated, } }) .factory('NumberUtils', ["$log", function ($log) { var logger = $log.getInstance('NumberUtils'); $log.logLevels['NumberUtils'] = $log.LEVEL.OFF; function sumValues(items, fieldName) { if (!items) return 0; return _.chain(items).pluck(fieldName).reduce(function (memo, num) { return memo + asNumber(num); }, 0).value(); } function generateUid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } function asNumber(numberString, decimalPlaces) { if (!numberString) return 0; var isNumber = typeof numberString === 'number'; if (isNumber && !decimalPlaces) return numberString; var number = isNumber ? numberString : parseFloat(numberString.replace(/[^\d\.\-]/g, "")); if (isNaN(number)) return 0; var returnValue = (decimalPlaces) ? (parseFloat(number).toFixed(decimalPlaces)) / 1 : number; logger.debug('asNumber:', numberString, decimalPlaces, '->', returnValue); return returnValue; } return { asNumber: asNumber, sumValues: sumValues, generateUid: generateUid }; }]) .factory('ContentMetaData', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('contentMetaData'); }]) .factory('ConfigData', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('config'); }]) .factory('Config', ["$log", "ConfigData", "ErrorMessageService", function ($log, ConfigData, ErrorMessageService) { var logger = $log.getInstance('Config'); $log.logLevels['Config'] = $log.LEVEL.OFF; function getConfig(key, defaultOnEmpty) { logger.debug('getConfig:', key, 'defaultOnEmpty:', defaultOnEmpty); var queryObject = {}; queryObject[key] = {$exists: true}; return ConfigData.query(queryObject, {limit: 1}) .then(function (results) { if (results && results.length > 0) { return results[0]; } else { queryObject[key] = {}; return new ConfigData(defaultOnEmpty || queryObject); } }, function (response) { throw new Error('Query of ' + key + ' config failed: ' + response); }); } function saveConfig(key, config, saveCallback, errorSaveCallback) { logger.debug('saveConfig:', key); if (_.has(config, key)) { return config.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback || saveCallback, errorSaveCallback || saveCallback); } else { throw new Error('Attempt to save ' + ErrorMessageService.stringify(key) + ' config when ' + ErrorMessageService.stringify(key) + ' parent key not present in data: ' + ErrorMessageService.stringify(config)); } } return { getConfig: getConfig, saveConfig: saveConfig } }]) .factory('ExpenseClaimsService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('expenseClaims'); }]) .factory('RamblersUploadAudit', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('ramblersUploadAudit'); }]) .factory('ErrorTransformerService', ["ErrorMessageService", function (ErrorMessageService) { function transform(errorResponse) { var message = ErrorMessageService.stringify(errorResponse); var duplicate = s.include(errorResponse, 'duplicate'); if (duplicate) { message = 'Duplicate data was detected. A member record must have a unique Contact Email, Display Name, Ramblers Membership Number and combination of First Name, Last Name and Alias. Please amend the current member and try again.'; } return {duplicate: duplicate, message: message} } return {transform: transform} }]) .factory('ErrorMessageService', function () { function stringify(message) { return _.isObject(message) ? JSON.stringify(message, censor(message)) : message; } function censor(censor) { var i = 0; return function (key, value) { if (i !== 0 && typeof(censor) === 'object' && typeof(value) === 'object' && censor === value) return '[Circular]'; if (i >= 29) // seems to be a hard maximum of 30 serialized objects? return '[Unknown]'; ++i; // so we know we aren't using the original object anymore return value; } } return { stringify: stringify } }); /* concatenated from client/src/app/js/siteEditActions.js */ angular.module('ekwgApp') .component('siteEditActions', { templateUrl: 'partials/components/site-edit.html', controller: ["$log", "SiteEditService", function ($log, SiteEditService){ var logger = $log.getInstance('SiteEditActionsController'); $log.logLevels['SiteEditActionsController'] = $log.LEVEL.OFF; var ctrl = this; logger.info("initialised with SiteEditService.active()", SiteEditService.active()); ctrl.userEdits = {preview: true, saveInProgress: false, revertInProgress: false}; ctrl.editSiteActive = function () { return SiteEditService.active() ? "active" : ""; }; ctrl.editSiteCaption = function () { return SiteEditService.active() ? "editing site" : "edit site"; }; ctrl.toggleEditSite = function () { SiteEditService.toggle(); }; }], bindings: { name: '@', description: '@', } }); /* concatenated from client/src/app/js/siteEditService.js */ angular.module('ekwgApp') .factory('SiteEditService', ["$log", "$cookieStore", "$rootScope", function ($log, $cookieStore, $rootScope) { var logger = $log.getInstance('SiteEditService'); $log.logLevels['SiteEditService'] = $log.LEVEL.OFF; function active() { var active = Boolean($cookieStore.get("editSite")); logger.debug("active:", active); return active; } function toggle() { var priorState = active(); var newState = !priorState; logger.debug("toggle:priorState", priorState, "newState", newState); $cookieStore.put("editSite", newState); return $rootScope.$broadcast("editSite", newState); } return { active: active, toggle: toggle } }]); /* concatenated from client/src/app/js/socialEventNotifications.js */ angular.module('ekwgApp') .controller('SocialEventNotificationsController', ["MAILCHIMP_APP_CONSTANTS", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MailchimpConfig", "Notifier", "CommitteeReferenceData", "socialEvent", "close", function (MAILCHIMP_APP_CONSTANTS, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService, MailchimpConfig, Notifier, CommitteeReferenceData, socialEvent, close) { var logger = $log.getInstance('SocialEventNotificationsController'); $log.logLevels['SocialEventNotificationsController'] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); logger.debug('created with social event', socialEvent); $scope.attachmentBaseUrl = ContentMetaDataService.baseUrl('socialEvents'); $scope.destinationType = ''; $scope.members = []; $scope.selectableRecipients = []; $scope.committeeFiles = []; $scope.alertMessages = []; $scope.allowConfirmDelete = false; $scope.latestYearOpen = true; $scope.roles = {signoff: [], replyTo: []}; $scope.showAlertMessage = function () { return ($scope.notify.alert.class === 'alert-danger') || $scope.userEdits.sendInProgress; }; function initialiseNotification(socialEvent) { if (socialEvent) { $scope.socialEvent = socialEvent; onFirstNotificationOnly(); forEveryNotification(); } else { logger.error('no socialEvent - problem!'); } function onFirstNotificationOnly() { if (!$scope.socialEvent.notification) { $scope.socialEvent.notification = { destinationType: 'all-ekwg-social', recipients: [], addresseeType: 'Hi *|FNAME|*,', items: { title: {include: true}, notificationText: {include: true, value: ''}, description: {include: true}, attendees: {include: socialEvent.attendees.length > 0}, attachment: {include: socialEvent.attachment}, replyTo: { include: $scope.socialEvent.displayName, value: $scope.socialEvent.displayName ? 'organiser' : 'social' }, signoffText: { include: true, value: 'If you have any questions about the above, please don\'t hesitate to contact me.\n\nBest regards,' } } }; logger.debug('onFirstNotificationOnly - creating $scope.socialEvent.notification ->', $scope.socialEvent.notification); } } function forEveryNotification() { $scope.socialEvent.notification.items.signoffAs = { include: true, value: loggedOnRole().type || 'social' }; logger.debug('forEveryNotification - $scope.socialEvent.notification.signoffAs ->', $scope.socialEvent.notification.signoffAs); } } function loggedOnRole() { var memberId = LoggedInMemberService.loggedInMember().memberId; var loggedOnRoleData = _(CommitteeReferenceData.contactUsRolesAsArray()).find(function (role) { return role.memberId === memberId }); logger.debug('loggedOnRole for', memberId, '->', loggedOnRoleData); return loggedOnRoleData || {}; } function roleForType(type) { var role = _($scope.roles.replyTo).find(function (role) { return role.type === type; }); logger.debug('roleForType for', type, '->', role); return role; } function initialiseRoles() { $scope.roles.signoff = CommitteeReferenceData.contactUsRolesAsArray(); $scope.roles.replyTo = _.clone($scope.roles.signoff); if ($scope.socialEvent.eventContactMemberId) { $scope.roles.replyTo.unshift({ type: 'organiser', fullName: $scope.socialEvent.displayName, memberId: $scope.socialEvent.eventContactMemberId, description: 'Organiser (' + $scope.socialEvent.displayName + ')', email: $scope.socialEvent.contactEmail }); } logger.debug('initialiseRoles -> $scope.roles ->', $scope.roles); } $scope.formattedText = function () { return $filter('lineFeedsToBreaks')($scope.socialEvent.notification.items.notificationText.value); }; $scope.attachmentTitle = function (socialEvent) { return socialEvent && socialEvent.attachment ? (socialEvent.attachment.title || socialEvent.attachmentTitle || 'Attachment: ' + socialEvent.attachment.originalFileName) : ''; }; $scope.attachmentUrl = function (socialEvent) { return socialEvent && socialEvent.attachment ? URLService.baseUrl() + $scope.attachmentBaseUrl + '/' + socialEvent.attachment.awsFileName : ''; }; $scope.editAllSocialRecipients = function () { $scope.socialEvent.notification.destinationType = 'custom'; $scope.socialEvent.notification.recipients = $scope.userEdits.socialList(); }; $scope.editAttendeeRecipients = function () { $scope.socialEvent.notification.destinationType = 'custom'; $scope.socialEvent.notification.recipients = $scope.socialEvent.attendees; }; $scope.clearRecipients = function () { $scope.socialEvent.notification.recipients = []; }; $scope.formattedSignoffText = function () { return $filter('lineFeedsToBreaks')($scope.socialEvent.notification.items.signoffText.value); }; $scope.attendeeList = function () { return _($scope.socialEvent.notification && $scope.socialEvent.attendees) .sortBy(function (attendee) { return attendee.text; }).map(function (attendee) { return attendee.text; }).join(', '); }; $scope.memberGrouping = function (member) { return member.memberGrouping; }; function toSelectMember(member) { var memberGrouping; var order; if (member.socialMember && member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Subscribed to social emails'; order = 0; } else if (member.socialMember && !member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Not subscribed to social emails'; order = 1; } else if (!member.socialMember) { memberGrouping = 'Not a social member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } function refreshMembers() { if (LoggedInMemberService.memberLoggedIn()) { MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) { $scope.members = members; logger.debug('refreshMembers -> populated ->', $scope.members.length, 'members'); $scope.selectableRecipients = _.chain(members) .map(toSelectMember) .sortBy(function (member) { return member.order + member.text }) .value(); logger.debug('refreshMembers -> populated ->', $scope.selectableRecipients.length, 'selectableRecipients'); notify.clearBusy(); }); } } $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; $scope.userEdits = { sendInProgress: false, cancelFlow: false, socialList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.SOCIAL_MEMBERS_SUBSCRIBED) .map(toSelectMember).value(); }, replyToRole: function () { return _($scope.roles.replyTo).find(function (role) { return role.type === $scope.socialEvent.notification.items.replyTo.value; }); }, notReady: function () { return $scope.members.length === 0 || $scope.userEdits.sendInProgress; } }; $scope.cancelSendNotification = function () { close(); $('#social-event-dialog').modal('show'); }; $scope.completeInMailchimp = function () { notify.warning({ title: 'Complete in Mailchimp', message: 'You can close this dialog now as the message was presumably completed and sent in Mailchimp' }); $scope.confirmSendNotification(true); }; $scope.confirmSendNotification = function (dontSend) { notify.setBusy(); var campaignName = $scope.socialEvent.briefDescription; logger.debug('sendSocialNotification:notification->', $scope.socialEvent.notification); notify.progress({title: campaignName, message: 'preparing and sending notification'}); $scope.userEdits.sendInProgress = true; $scope.userEdits.cancelFlow = false; function getTemplate() { return $templateRequest($sce.getTrustedResourceUrl('partials/socialEvents/social-notification.html')) } return $q.when(createOrSaveMailchimpSegment()) .then(getTemplate) .then(renderTemplateContent) .then(populateContentSections) .then(sendEmailCampaign) .then(saveSocialEvent) .then(notifyEmailSendComplete) .catch(handleError); function handleError(errorResponse) { $scope.userEdits.sendInProgress = false; notify.error({ title: 'Your notification could not be sent', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } function renderTemplateContent(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction($scope); $timeout(function () { $scope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function populateContentSections(notificationText) { logger.debug('populateContentSections -> notificationText', notificationText); return { sections: { notification_text: notificationText } }; } function writeSegmentResponseDataToEvent(segmentResponse) { $scope.socialEvent.mailchimp = { segmentId: segmentResponse.segment.id }; if (segmentResponse.members) $scope.socialEvent.mailchimp.members = segmentResponse.members; } function createOrSaveMailchimpSegment() { var members = segmentMembers(); if (members.length > 0) { return MailchimpSegmentService.saveSegment('socialEvents', $scope.socialEvent.mailchimp, members, MailchimpSegmentService.formatSegmentName($scope.socialEvent.briefDescription), $scope.members) .then(writeSegmentResponseDataToEvent) .catch(handleError); } else { logger.debug('not saving segment data as destination type is whole mailing list ->', $scope.socialEvent.notification.destinationType); return true; } } function segmentMembers() { switch ($scope.socialEvent.notification.destinationType) { case 'attendees': return $scope.socialEvent.attendees; case 'custom': return $scope.socialEvent.notification.recipients; default: return []; } } function sendEmailCampaign(contentSections) { var replyToRole = roleForType($scope.socialEvent.notification.items.replyTo.value || 'social'); var otherOptions = ($scope.socialEvent.notification.items.replyTo.include && replyToRole.fullName && replyToRole.email) ? { from_name: replyToRole.fullName, from_email: replyToRole.email } : {}; notify.progress(dontSend ? ('Preparing to complete ' + campaignName + ' in Mailchimp') : ('Sending ' + campaignName)); logger.debug('Sending ' + campaignName, 'with otherOptions', otherOptions); return MailchimpConfig.getConfig() .then(function (config) { var campaignId = config.mailchimp.campaigns.socialEvents.campaignId; switch ($scope.socialEvent.notification.destinationType) { case 'all-ekwg-social': logger.debug('about to replicateAndSendWithOptions to all-ekwg-social with campaignName', campaignName, 'campaign Id', campaignId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); default: if (!$scope.socialEvent.mailchimp) notify.warning('Cant send campaign due to previous request failing. This could be due to network problems - please try this again'); var segmentId = $scope.socialEvent.mailchimp.segmentId; logger.debug('about to replicateAndSendWithOptions to social with campaignName', campaignName, 'campaign Id', campaignId, 'segmentId', segmentId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, segmentId: segmentId, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); } }) } function openInMailchimpIf(dontSend) { return function (replicateCampaignResponse) { logger.debug('openInMailchimpIf:replicateCampaignResponse', replicateCampaignResponse, 'dontSend', dontSend); if (dontSend) { return $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/wizard/neapolitan?id=" + replicateCampaignResponse.web_id, '_blank'); } else { return true; } } } function saveSocialEvent() { return $scope.socialEvent.$saveOrUpdate(); } function notifyEmailSendComplete() { notify.success('Sending of ' + campaignName + ' was successful.', false); $scope.userEdits.sendInProgress = false; if (!$scope.userEdits.cancelFlow) { close(); } notify.clearBusy(); } }; refreshMembers(); initialiseNotification(socialEvent); initialiseRoles(CommitteeReferenceData); }] ); /* concatenated from client/src/app/js/socialEvents.js */ angular.module('ekwgApp') .factory('SocialEventsService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('socialEvents'); }]) .factory('SocialEventAttendeeService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('socialEventAttendees'); }]) .controller('SocialEventsController', ["$routeParams", "$log", "$q", "$scope", "$filter", "URLService", "Upload", "SocialEventsService", "SiteEditService", "SocialEventAttendeeService", "LoggedInMemberService", "MemberService", "AWSConfig", "ContentMetaDataService", "DateUtils", "MailchimpSegmentService", "ClipboardService", "Notifier", "EKWGFileUpload", "CommitteeReferenceData", "ModalService", function ($routeParams, $log, $q, $scope, $filter, URLService, Upload, SocialEventsService, SiteEditService, SocialEventAttendeeService, LoggedInMemberService, MemberService, AWSConfig, ContentMetaDataService, DateUtils, MailchimpSegmentService, ClipboardService, Notifier, EKWGFileUpload, CommitteeReferenceData, ModalService) { $scope.userEdits = { copyToClipboard: ClipboardService.copyToClipboard, longerDescriptionPreview: true, socialEventLink: function (socialEvent) { return socialEvent && socialEvent.$id() ? URLService.notificationHref({ type: "socialEvent", area: "social", id: socialEvent.$id() }) : undefined; } }; $scope.previewLongerDescription = function () { logger.debug('previewLongerDescription'); $scope.userEdits.longerDescriptionPreview = true; }; $scope.editLongerDescription = function () { logger.debug('editLongerDescription'); $scope.userEdits.longerDescriptionPreview = false; }; $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; var logger = $log.getInstance('SocialEventsController'); $log.logLevels['SocialEventsController'] = $log.LEVEL.OFF; var notify = Notifier($scope); $scope.attachmentBaseUrl = ContentMetaDataService.baseUrl('socialEvents'); $scope.selectMembers = []; $scope.display = {attendees: []}; $scope.socialEventsDetailProgrammeOpen = true; $scope.socialEventsBriefProgrammeOpen = true; $scope.socialEventsInformationOpen = true; $scope.todayValue = DateUtils.momentNowNoTime().valueOf(); applyAllowEdits('controllerInitialisation'); $scope.eventDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.eventDateCalendar.opened = true; } }; $scope.$on('memberLoginComplete', function () { applyAllowEdits('memberLoginComplete'); refreshMembers(); refreshSocialEvents(); }); $scope.$on('memberLogoutComplete', function () { applyAllowEdits('memberLogoutComplete'); }); $scope.$on('editSite', function () { applyAllowEdits('editSite'); }); $scope.addSocialEvent = function () { showSocialEventDialog(new SocialEventsService({eventDate: $scope.todayValue, attendees: []}), 'Add New'); }; $scope.viewSocialEvent = function (socialEvent) { showSocialEventDialog(socialEvent, 'View'); }; $scope.editSocialEvent = function (socialEvent) { showSocialEventDialog(socialEvent, 'Edit Existing'); }; $scope.deleteSocialEventDetails = function () { $scope.allowDelete = false; $scope.allowConfirmDelete = true; }; $scope.cancelSocialEventDetails = function () { hideSocialEventDialogAndRefreshSocialEvents(); }; $scope.saveSocialEventDetails = function () { $q.when(notify.progress({title: 'Save in progress', message: 'Saving social event'}, true)) .then(prepareToSave, notify.error, notify.progress) .then(saveSocialEvent, notify.error, notify.progress) .then(notify.clearBusy, notify.error, notify.progress) .catch(notify.error); }; function prepareToSave() { DateUtils.convertDateFieldInObject($scope.currentSocialEvent, 'eventDate'); } function saveSocialEvent() { return $scope.currentSocialEvent.$saveOrUpdate(hideSocialEventDialogAndRefreshSocialEvents, hideSocialEventDialogAndRefreshSocialEvents); } $scope.confirmDeleteSocialEventDetails = function () { $q.when(notify.progress('Deleting social event', true)) .then(deleteMailchimpSegment, notify.error, notify.progress) .then(removeSocialEventHideSocialEventDialogAndRefreshSocialEvents, notify.error, notify.progress) .then(notify.clearBusy, notify.error, notify.progress) .catch(notify.error); }; var deleteMailchimpSegment = function () { if ($scope.currentSocialEvent.mailchimp && $scope.currentSocialEvent.mailchimp.segmentId) { return MailchimpSegmentService.deleteSegment('socialEvents', $scope.currentSocialEvent.mailchimp.segmentId); } }; var removeSocialEventHideSocialEventDialogAndRefreshSocialEvents = function () { $scope.currentSocialEvent.$remove(hideSocialEventDialogAndRefreshSocialEvents) }; $scope.copyDetailsToNewSocialEvent = function () { var copiedSocialEvent = new SocialEventsService($scope.currentSocialEvent); delete copiedSocialEvent._id; delete copiedSocialEvent.mailchimp; DateUtils.convertDateFieldInObject(copiedSocialEvent, 'eventDate'); showSocialEventDialog(copiedSocialEvent, 'Copy Existing'); notify.success({ title: 'Existing social event copied!', message: 'Make changes here and save to create a new social event.' }); }; $scope.selectMemberContactDetails = function () { var socialEvent = $scope.currentSocialEvent; var memberId = socialEvent.eventContactMemberId; if (memberId === null) { delete socialEvent.eventContactMemberId; delete socialEvent.displayName; delete socialEvent.contactPhone; delete socialEvent.contactEmail; // console.log('deleted contact details from', socialEvent); } else { var selectedMember = _.find($scope.members, function (member) { return member.$id() === memberId; }); socialEvent.displayName = selectedMember.displayName; socialEvent.contactPhone = selectedMember.mobileNumber; socialEvent.contactEmail = selectedMember.email; // console.log('set contact details on', socialEvent); } }; $scope.dataQueryParameters = { query: '', selectType: '1', newestFirst: 'false' }; $scope.removeAttachment = function () { delete $scope.currentSocialEvent.attachment; delete $scope.currentSocialEvent.attachmentTitle; $scope.uploadedFile = undefined; }; $scope.resetMailchimpData = function () { delete $scope.currentSocialEvent.mailchimp; }; $scope.addOrReplaceAttachment = function () { $('#hidden-input').click(); }; $scope.attachmentTitle = function (socialEvent) { return socialEvent && socialEvent.attachment ? (socialEvent.attachment.title || socialEvent.attachmentTitle || 'Attachment: ' + socialEvent.attachment.originalFileName) : ''; }; $scope.attachmentUrl = function (socialEvent) { return socialEvent && socialEvent.attachment ? $scope.attachmentBaseUrl + '/' + socialEvent.attachment.awsFileName : ''; }; $scope.onFileSelect = function (file) { if (file) { $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, 'socialEvents').then(function (fileNameData) { $scope.currentSocialEvent.attachment = fileNameData; }); } }; function allowSummaryView() { return (LoggedInMemberService.allowSocialAdminEdits() || !LoggedInMemberService.allowSocialDetailView()); } function applyAllowEdits(event) { $scope.allowDelete = false; $scope.allowConfirmDelete = false; $scope.allowDetailView = LoggedInMemberService.allowSocialDetailView(); $scope.allowEdits = LoggedInMemberService.allowSocialAdminEdits(); $scope.allowCopy = LoggedInMemberService.allowSocialAdminEdits(); $scope.allowContentEdits = SiteEditService.active() && LoggedInMemberService.allowContentEdits(); $scope.allowSummaryView = allowSummaryView(); } $scope.showLoginTooltip = function () { return !LoggedInMemberService.memberLoggedIn(); }; $scope.login = function () { if (!LoggedInMemberService.memberLoggedIn()) { URLService.navigateTo("login"); } }; function showSocialEventDialog(socialEvent, socialEventEditMode) { $scope.uploadedFile = undefined; $scope.showAlert = false; $scope.allowConfirmDelete = false; if (!socialEvent.attendees) socialEvent.attendees = []; $scope.allowEdits = LoggedInMemberService.allowSocialAdminEdits(); var existingRecordEditEnabled = $scope.allowEdits && s.startsWith(socialEventEditMode, 'Edit'); $scope.allowCopy = existingRecordEditEnabled; $scope.allowDelete = existingRecordEditEnabled; $scope.socialEventEditMode = socialEventEditMode; $scope.currentSocialEvent = socialEvent; $('#social-event-dialog').modal('show'); } $scope.attendeeCaption = function () { return $scope.currentSocialEvent && $scope.currentSocialEvent.attendees.length + ($scope.currentSocialEvent.attendees.length === 1 ? ' member is attending' : ' members are attending'); }; $scope.attendeeList = function () { return _($scope.display.attendees) .sortBy(function (attendee) { return attendee.text; }).map(function (attendee) { return attendee.text; }).join(', '); }; function hideSocialEventDialogAndRefreshSocialEvents() { $('#social-event-dialog').modal('hide'); refreshSocialEvents(); } function refreshMembers() { if (LoggedInMemberService.memberLoggedIn()) { MemberService.allLimitedFields(MemberService.filterFor.SOCIAL_MEMBERS).then(function (members) { $scope.members = members; logger.debug('found', $scope.members.length, 'members'); $scope.selectMembers = _($scope.members).map(function (member) { return {id: member.$id(), text: $filter('fullNameWithAlias')(member)}; }) }); } } $scope.sendSocialEventNotification = function () { $('#social-event-dialog').modal('hide'); ModalService.showModal({ templateUrl: "partials/socialEvents/send-notification-dialog.html", controller: "SocialEventNotificationsController", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, inputs: { socialEvent: $scope.currentSocialEvent } }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; function refreshSocialEvents() { if (URLService.hasRouteParameter('socialEventId')) { return SocialEventsService.getById($routeParams.socialEventId) .then(function (socialEvent) { if (!socialEvent) notify.error('Social event could not be found'); $scope.socialEvents = [socialEvent]; }); } else { var socialEvents = LoggedInMemberService.allowSocialDetailView() ? SocialEventsService.all() : SocialEventsService.all({ fields: { briefDescription: 1, eventDate: 1, thumbnail: 1 } }); socialEvents.then(function (socialEvents) { $scope.socialEvents = _.chain(socialEvents) .filter(function (socialEvent) { return socialEvent.eventDate >= $scope.todayValue }) .sortBy(function (socialEvent) { return socialEvent.eventDate; }) .value(); logger.debug('found', $scope.socialEvents.length, 'social events'); }); } } $q.when(refreshSocialEvents()) .then(refreshMembers) .then(refreshImages); function refreshImages() { ContentMetaDataService.getMetaData('imagesSocialEvents').then(function (contentMetaData) { $scope.interval = 5000; $scope.slides = contentMetaData.files; logger.debug('found', $scope.slides.length, 'slides'); }, function (response) { throw new Error(response); }); } }]); /* concatenated from client/src/app/js/urlServices.js */ angular.module('ekwgApp') .factory('URLService', ["$window", "$rootScope", "$timeout", "$location", "$routeParams", "$log", "PAGE_CONFIG", "ContentMetaDataService", function ($window, $rootScope, $timeout, $location, $routeParams, $log, PAGE_CONFIG, ContentMetaDataService) { var logger = $log.getInstance('URLService'); $log.logLevels['URLService'] = $log.LEVEL.OFF; function baseUrl(optionalUrl) { return _.first((optionalUrl || $location.absUrl()).split('/#')); } function relativeUrl(optionalUrl) { var relativeUrlValue = _.last((optionalUrl || $location.absUrl()).split("/#")); logger.debug("relativeUrlValue:", relativeUrlValue); return relativeUrlValue; } function relativeUrlFirstSegment(optionalUrl) { var relativeUrlValue = relativeUrl(optionalUrl); var index = relativeUrlValue.indexOf("/", 1); var relativeUrlFirstSegment = index === -1 ? relativeUrlValue : relativeUrlValue.substring(0, index); logger.debug("relativeUrl:", relativeUrlValue, "relativeUrlFirstSegment:", relativeUrlFirstSegment); return relativeUrlFirstSegment; } function resourceUrl(area, type, id) { return baseUrl() + '/#/' + area + '/' + type + 'Id/' + id; } function notificationHref(ctrl) { var href = (ctrl.name) ? resourceUrlForAWSFileName(ctrl.name) : resourceUrl(ctrl.area, ctrl.type, ctrl.id); logger.debug("href:", href); return href; } function resourceUrlForAWSFileName(fileName) { return baseUrl() + ContentMetaDataService.baseUrl(fileName); } function hasRouteParameter(parameter) { var hasRouteParameter = !!($routeParams[parameter]); logger.debug('hasRouteParameter', parameter, hasRouteParameter); return hasRouteParameter; } function isArea(areas) { logger.debug('isArea:areas', areas, '$routeParams', $routeParams); return _.some(_.isArray(areas) ? areas : [areas], function (area) { var matched = area === $routeParams.area; logger.debug('isArea', area, 'matched =', matched); return matched; }); } let pageUrl = function (page) { var pageOrEmpty = (page ? page : ""); return s.startsWith(pageOrEmpty, "/") ? pageOrEmpty : "/" + pageOrEmpty; }; function navigateTo(page, area) { $timeout(function () { var url = pageUrl(page) + (area ? "/" + area : ""); logger.info("navigating to page:", page, "area:", area, "->", url); $location.path(url); logger.info("$location.path is now", $location.path()) }, 1); } function navigateBackToLastMainPage() { var lastPage = _.chain($rootScope.pageHistory.reverse()) .find(function (page) { return _.contains(_.values(PAGE_CONFIG.mainPages), relativeUrlFirstSegment(page)); }) .value(); logger.info("navigateBackToLastMainPage:$rootScope.pageHistory", $rootScope.pageHistory, "lastPage->", lastPage); navigateTo(lastPage || "/") } function noArea() { return !$routeParams.area; } function setRoot() { return navigateTo(); } function area() { return $routeParams.area; } return { setRoot: setRoot, navigateBackToLastMainPage: navigateBackToLastMainPage, navigateTo: navigateTo, hasRouteParameter: hasRouteParameter, noArea: noArea, isArea: isArea, baseUrl: baseUrl, area: area, resourceUrlForAWSFileName: resourceUrlForAWSFileName, notificationHref: notificationHref, resourceUrl: resourceUrl, relativeUrlFirstSegment: relativeUrlFirstSegment, relativeUrl: relativeUrl } }]); /* concatenated from client/src/app/js/walkNotifications.js */ angular.module('ekwgApp') .controller('WalkNotificationsController', ["$log", "$scope", "WalkNotificationService", "RamblersWalksAndEventsService", function ($log, $scope, WalkNotificationService, RamblersWalksAndEventsService) { $scope.dataAuditDelta = WalkNotificationService.dataAuditDelta($scope.walk, $scope.status); $scope.validateWalk = RamblersWalksAndEventsService.validateWalk($scope.walk); RamblersWalksAndEventsService.walkBaseUrl().then(function (walkBaseUrl) { $scope.ramblersWalkBaseUrl = walkBaseUrl; }); }]) .factory('WalkNotificationService', ["$sce", "$log", "$timeout", "$filter", "$location", "$rootScope", "$q", "$compile", "$templateRequest", "$routeParams", "$cookieStore", "URLService", "MemberService", "MailchimpConfig", "MailchimpSegmentService", "WalksReferenceService", "MemberAuditService", "RamblersWalksAndEventsService", "MailchimpCampaignService", "LoggedInMemberService", "DateUtils", function ($sce, $log, $timeout, $filter, $location, $rootScope, $q, $compile, $templateRequest, $routeParams, $cookieStore, URLService, MemberService, MailchimpConfig, MailchimpSegmentService, WalksReferenceService, MemberAuditService, RamblersWalksAndEventsService, MailchimpCampaignService, LoggedInMemberService, DateUtils) { var logger = $log.getInstance('WalkNotificationService'); var noLogger = $log.getInstance('WalkNotificationServiceNoLog'); $log.logLevels['WalkNotificationService'] = $log.LEVEL.OFF; $log.logLevels['WalkNotificationServiceNoLog'] = $log.LEVEL.OFF; var basePartialsUrl = 'partials/walks/notifications'; var auditedFields = ['grade', 'walkDate', 'walkType', 'startTime', 'briefDescriptionAndStartPoint', 'longerDescription', 'distance', 'nearestTown', 'gridReference', 'meetupEventUrl', 'meetupEventTitle', 'osMapsRoute', 'osMapsTitle', 'postcode', 'walkLeaderMemberId', 'contactPhone', 'contactEmail', 'contactId', 'displayName', 'ramblersWalkId']; function currentDataValues(walk) { return _.compactObject(_.pick(walk, auditedFields)); } function previousDataValues(walk) { var event = latestWalkEvent(walk); return event && event.data || {}; } function latestWalkEvent(walk) { return (walk.events && _.last(walk.events)) || {}; } function eventsLatestFirst(walk) { var events = walk.events && _(walk.events).clone().reverse() || []; noLogger.info('eventsLatestFirst:', events); return events; } function latestEventWithStatusChange(walk) { return _(eventsLatestFirst(walk)).find(function (event) { return (WalksReferenceService.toEventType(event.eventType) || {}).statusChange; }) || {}; } function dataAuditDelta(walk, status) { if (!walk) return {}; var currentData = currentDataValues(walk); var previousData = previousDataValues(walk); var changedItems = calculateChangedItems(); var eventExists = latestEventWithStatusChangeIs(walk, status); var dataChanged = changedItems.length > 0; var dataAuditDelta = { currentData: currentData, previousData: previousData, changedItems: changedItems, eventExists: eventExists, dataChanged: dataChanged, notificationRequired: dataChanged || !eventExists, eventType: dataChanged && eventExists ? WalksReferenceService.eventTypes.walkDetailsUpdated.eventType : status }; dataAuditDelta.dataChanged && noLogger.info('dataAuditDelta', dataAuditDelta); return dataAuditDelta; function calculateChangedItems() { return _.compact(_.map(auditedFields, function (key) { var currentValue = currentData[key]; var previousValue = previousData[key]; noLogger.info('auditing', key, 'now:', currentValue, 'previous:', previousValue); if (previousValue !== currentValue) return { fieldName: key, previousValue: previousValue, currentValue: currentValue } })); } } function latestEventWithStatusChangeIs(walk, eventType) { if (!walk) return false; return latestEventWithStatusChange(walk).eventType === toEventTypeValue(eventType); } function toEventTypeValue(eventType) { return _.has(eventType, 'eventType') ? eventType.eventType : eventType; } function latestEventForEventType(walk, eventType) { if (walk) { var eventTypeString = toEventTypeValue(eventType); return eventsLatestFirst(walk).find(function (event) { return event.eventType === eventTypeString; }); } } function populateWalkApprovedEventsIfRequired(walks) { return _(walks).map(function (walk) { if (_.isArray(walk.events)) { return walk } else { var event = createEventIfRequired(walk, WalksReferenceService.eventTypes.approved.eventType, 'Marking past walk as approved'); writeEventIfRequired(walk, event); walk.$saveOrUpdate(); return walk; } }) } function createEventIfRequired(walk, status, reason) { var dataAuditDeltaInfo = dataAuditDelta(walk, status); logger.debug('createEventIfRequired:', dataAuditDeltaInfo); if (dataAuditDeltaInfo.notificationRequired) { var event = { "date": DateUtils.nowAsValue(), "memberId": LoggedInMemberService.loggedInMember().memberId, "data": dataAuditDeltaInfo.currentData, "eventType": dataAuditDeltaInfo.eventType }; if (reason) event.reason = reason; if (dataAuditDeltaInfo.dataChanged) event.description = 'Changed: ' + $filter('toAuditDeltaChangedItems')(dataAuditDeltaInfo.changedItems); logger.debug('createEventIfRequired: event created:', event); return event; } else { logger.debug('createEventIfRequired: event creation not necessary'); } } function writeEventIfRequired(walk, event) { if (event) { logger.debug('writing event', event); if (!_.isArray(walk.events)) walk.events = []; walk.events.push(event); } else { logger.debug('no event to write'); } } function createEventAndSendNotifications(members, walk, status, notify, sendNotification, reason) { notify.setBusy(); var event = createEventIfRequired(walk, status, reason); var notificationScope = $rootScope.$new(); notificationScope.walk = walk; notificationScope.members = members; notificationScope.event = event; notificationScope.status = status; var eventType = event && WalksReferenceService.toEventType(event.eventType); if (event && sendNotification) { return sendNotificationsToAllRoles() .then(function () { return writeEventIfRequired(walk, event); }) .then(function () { return true; }) .catch(function (error) { logger.debug('failed with error', error); return notify.error({title: error.message, message: error.error}) }); } else { logger.debug('Not sending notification'); return $q.when(writeEventIfRequired(walk, event)) .then(function () { return false; }); } function renderTemplateContent(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction(notificationScope); $timeout(function () { notificationScope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function sendNotificationsToAllRoles() { return LoggedInMemberService.getMemberForMemberId(walk.walkLeaderMemberId) .then(function (member) { logger.debug('sendNotification:', 'memberId', walk.walkLeaderMemberId, 'member', member); var walkLeaderName = $filter('fullNameWithAlias')(member); var walkDate = $filter('displayDate')(walk.walkDate); return $q.when(notify.progress('Preparing to send email notifications')) .then(sendLeaderNotifications, notify.error, notify.progress) .then(sendCoordinatorNotifications, notify.error, notify.progress); function sendLeaderNotifications() { if (eventType.notifyLeader) return sendNotificationsTo({ templateUrl: templateForEvent('leader', eventType.eventType), memberIds: [walk.walkLeaderMemberId], segmentType: 'walkLeader', segmentName: MailchimpSegmentService.formatSegmentName('Walk leader notifications for ' + walkLeaderName), emailSubject: 'Your walk on ' + walkDate, destination: 'walk leader' }); logger.debug('not sending leader notification'); } function sendCoordinatorNotifications() { if (eventType.notifyCoordinator) { var memberIds = MemberService.allMemberIdsWithPrivilege('walkChangeNotifications', members); if (memberIds.length > 0) { return sendNotificationsTo({ templateUrl: templateForEvent('coordinator', eventType.eventType), memberIds: memberIds, segmentType: 'walkCoordinator', segmentName: MailchimpSegmentService.formatSegmentName('Walk co-ordinator notifications for ' + walkLeaderName), emailSubject: walkLeaderName + "'s walk on " + walkDate, destination: 'walk co-ordinators' }); } else { logger.debug('not sending coordinator notifications as none are configured with walkChangeNotifications'); } } else { logger.debug('not sending coordinator notifications as event type is', eventType.eventType); } } function templateForEvent(role, eventTypeString) { return basePartialsUrl + '/' + role + '/' + s.dasherize(eventTypeString) + '.html'; } function sendNotificationsTo(templateAndNotificationMembers) { if (templateAndNotificationMembers.memberIds.length === 0) throw new Error('No members have been configured as ' + templateAndNotificationMembers.destination + ' therefore notifications cannot be sent'); var memberFullNames = $filter('memberIdsToFullNames')(templateAndNotificationMembers.memberIds, members); logger.debug('sendNotificationsTo:', templateAndNotificationMembers); var campaignName = templateAndNotificationMembers.emailSubject + ' (' + eventType.description + ')'; var segmentName = templateAndNotificationMembers.segmentName; return $templateRequest($sce.getTrustedResourceUrl(templateAndNotificationMembers.templateUrl)) .then(renderTemplateContent, notify.error) .then(populateContentSections, notify.error) .then(sendNotification(templateAndNotificationMembers), notify.error); function populateContentSections(walkNotificationText) { logger.debug('populateContentSections -> walkNotificationText', walkNotificationText); return { sections: { notification_text: walkNotificationText } }; } function sendNotification(templateAndNotificationMembers) { return function (contentSections) { return createOrSaveMailchimpSegment() .then(saveSegmentDataToMember, notify.error, notify.progress) .then(sendEmailCampaign, notify.error, notify.progress) .then(notifyEmailSendComplete, notify.error, notify.success); function createOrSaveMailchimpSegment() { return MailchimpSegmentService.saveSegment('walks', {segmentId: MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType)}, templateAndNotificationMembers.memberIds, segmentName, members); } function saveSegmentDataToMember(segmentResponse) { MailchimpSegmentService.setMemberSegmentId(member, templateAndNotificationMembers.segmentType, segmentResponse.segment.id); return LoggedInMemberService.saveMember(member); } function sendEmailCampaign() { notify.progress('Sending ' + campaignName); return MailchimpConfig.getConfig() .then(function (config) { var campaignId = config.mailchimp.campaigns.walkNotification.campaignId; var segmentId = MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType); logger.debug('about to send campaign', campaignName, 'campaign Id', campaignId, 'segmentId', segmentId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, segmentId: segmentId }); }) .then(function () { notify.progress('Sending of ' + campaignName + ' was successful', true); }); } function notifyEmailSendComplete() { notify.success('Sending of ' + campaignName + ' was successful. Check your inbox for details.'); return true; } } } } }); } } return { dataAuditDelta: dataAuditDelta, eventsLatestFirst: eventsLatestFirst, createEventIfRequired: createEventIfRequired, populateWalkApprovedEventsIfRequired: populateWalkApprovedEventsIfRequired, writeEventIfRequired: writeEventIfRequired, latestEventWithStatusChangeIs: latestEventWithStatusChangeIs, latestEventWithStatusChange: latestEventWithStatusChange, createEventAndSendNotifications: createEventAndSendNotifications } }]); /* concatenated from client/src/app/js/walkSlots.js.js */ angular.module('ekwgApp') .controller('WalkSlotsController', ["$rootScope", "$log", "$scope", "$filter", "$q", "WalksService", "WalksQueryService", "WalksReferenceService", "WalkNotificationService", "LoggedInMemberService", "DateUtils", "Notifier", function ($rootScope, $log, $scope, $filter, $q, WalksService, WalksQueryService, WalksReferenceService, WalkNotificationService, LoggedInMemberService, DateUtils, Notifier) { var logger = $log.getInstance('WalkSlotsController'); $log.logLevels['WalkSlotsController'] = $log.LEVEL.OFF; $scope.slotsAlert = {}; $scope.todayValue = DateUtils.momentNowNoTime().valueOf(); $scope.slot = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.slot.opened = true; }, validDate: function (date) { return DateUtils.isDate(date); }, until: DateUtils.momentNowNoTime().day(7 * 12).valueOf(), bulk: true }; var notify = Notifier($scope.slotsAlert); function createSlots(requiredSlots, confirmAction, prompt) { $scope.requiredWalkSlots = requiredSlots.map(function (date) { var walk = new WalksService({ walkDate: date }); walk.events = [WalkNotificationService.createEventIfRequired(walk, WalksReferenceService.eventTypes.awaitingLeader.eventType, 'Walk slot created')]; return walk; }); logger.debug('$scope.requiredWalkSlots', $scope.requiredWalkSlots); if ($scope.requiredWalkSlots.length > 0) { $scope.confirmAction = confirmAction; notify.warning(prompt) } else { notify.error({title: "Nothing to do!", message: "All slots are already created between today and " + $filter('displayDate')($scope.slot.until)}); delete $scope.confirmAction; } } $scope.addWalkSlots = function () { WalksService.query({walkDate: {$gte: $scope.todayValue}}, {fields: {events: 1, walkDate: 1}, sort: {walkDate: 1}}) .then(function (walks) { var sunday = DateUtils.momentNowNoTime().day(7); var untilDate = DateUtils.asMoment($scope.slot.until).startOf('day'); var weeks = untilDate.clone().diff(sunday, 'weeks'); var allGeneratedSlots = _.times(weeks, function (index) { return DateUtils.asValueNoTime(sunday.clone().add(index, 'week')); }).filter(function (date) { return DateUtils.asString(date, undefined, 'DD-MMM') !== '25-Dec'; }); var existingDates = _.pluck(WalksQueryService.activeWalks(walks), 'walkDate'); logger.debug('sunday', sunday, 'untilDate', untilDate, 'weeks', weeks); logger.debug('existingDatesAsDates', _(existingDates).map($filter('displayDateAndTime'))); logger.debug('allGeneratedSlotsAsDates', _(allGeneratedSlots).map($filter('displayDateAndTime'))); var requiredSlots = _.difference(allGeneratedSlots, existingDates); var requiredDates = $filter('displayDates')(requiredSlots); createSlots(requiredSlots, {addSlots: true}, { title: "Add walk slots", message: " - You are about to add " + requiredSlots.length + " empty walk slots up to " + $filter('displayDate')($scope.slot.until) + '. Slots are: ' + requiredDates }); }); }; $scope.addWalkSlot = function () { createSlots([DateUtils.asValueNoTime($scope.slot.single)], {addSlot: true}, { title: "Add walk slots", message: " - You are about to add 1 empty walk slot for " + $filter('displayDate')($scope.slot.single) }); }; $scope.selectBulk = function (bulk) { $scope.slot.bulk = bulk; delete $scope.confirmAction; notify.hide(); }; $scope.allow = { addSlot: function () { return !$scope.confirmAction && !$scope.slot.bulk && LoggedInMemberService.allowWalkAdminEdits(); }, addSlots: function () { return !$scope.confirmAction && $scope.slot.bulk && LoggedInMemberService.allowWalkAdminEdits(); }, close: function () { return !$scope.confirmAction; } }; $scope.cancelConfirmableAction = function () { delete $scope.confirmAction; notify.hide(); }; $scope.confirmAddWalkSlots = function () { notify.success({title: "Add walk slots - ", message: "now creating " + $scope.requiredWalkSlots.length + " empty walk slots up to " + $filter('displayDate')($scope.slot.until)}); $q.all($scope.requiredWalkSlots.map(function (slot) { return slot.$saveOrUpdate(); })).then(function () { notify.success({title: "Done!", message: "Choose Close to see your newly created slots"}); delete $scope.confirmAction; }); }; $scope.$on('addWalkSlotsDialogOpen', function () { $('#add-slots-dialog').modal(); delete $scope.confirmAction; notify.hide(); }); $scope.closeWalkSlotsDialog = function () { $('#add-slots-dialog').modal('hide'); $rootScope.$broadcast('walkSlotsCreated'); }; }] ); /* concatenated from client/src/app/js/walks.js */ angular.module('ekwgApp') .factory('WalksService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('walks') }]) .factory('WalksQueryService', ["WalkNotificationService", "WalksReferenceService", function (WalkNotificationService, WalksReferenceService) { function activeWalks(walks) { return _.filter(walks, function (walk) { return !WalkNotificationService.latestEventWithStatusChangeIs(walk, WalksReferenceService.eventTypes.deleted) }) } return { activeWalks: activeWalks } }]) .factory('WalksReferenceService', function () { var eventTypes = { awaitingLeader: { statusChange: true, eventType: 'awaitingLeader', description: 'Awaiting walk leader' }, awaitingWalkDetails: { mustHaveLeader: true, statusChange: true, eventType: 'awaitingWalkDetails', description: 'Awaiting walk details from leader', notifyLeader: true, notifyCoordinator: true }, walkDetailsRequested: { mustHaveLeader: true, eventType: 'walkDetailsRequested', description: 'Walk details requested from leader', notifyLeader: true, notifyCoordinator: true }, walkDetailsUpdated: { eventType: 'walkDetailsUpdated', description: 'Walk details updated', notifyLeader: true, notifyCoordinator: true }, walkDetailsCopied: { eventType: 'walkDetailsCopied', description: 'Walk details copied' }, awaitingApproval: { mustHaveLeader: true, mustPassValidation: true, statusChange: true, eventType: 'awaitingApproval', readyToBe: 'approved', description: 'Awaiting confirmation of walk details', notifyLeader: true, notifyCoordinator: true }, approved: { mustHaveLeader: true, mustPassValidation: true, showDetails: true, statusChange: true, eventType: 'approved', readyToBe: 'published', description: 'Approved', notifyLeader: true, notifyCoordinator: true }, deleted: { statusChange: true, eventType: 'deleted', description: 'Deleted', notifyLeader: true, notifyCoordinator: true } }; return { toEventType: function (eventTypeString) { if (eventTypeString) { if (_.includes(eventTypeString, ' ')) eventTypeString = s.camelcase(eventTypeString.toLowerCase()); var eventType = eventTypes[eventTypeString]; if (!eventType) throw new Error("Event Type '" + eventTypeString + "' does not exist. Must be one of: " + _.keys(eventTypes).join(', ')); return eventType; } }, walkEditModes: { add: {caption: 'add', title: 'Add new'}, edit: {caption: 'edit', title: 'Edit existing', editEnabled: true}, more: {caption: 'more', title: 'View'}, lead: {caption: 'lead', title: 'Lead this', initialiseWalkLeader: true} }, eventTypes: eventTypes, walkStatuses: _(eventTypes).filter(function (eventType) { return eventType.statusChange; }) } }) .controller('WalksController', ["$sce", "$log", "$routeParams", "$interval", "$rootScope", "$location", "$scope", "$filter", "$q", "RamblersUploadAudit", "WalksService", "WalksQueryService", "URLService", "ClipboardService", "WalksReferenceService", "WalkNotificationService", "LoggedInMemberService", "MemberService", "DateUtils", "BatchGeoExportService", "RamblersWalksAndEventsService", "Notifier", "CommitteeReferenceData", "GoogleMapsConfig", "MeetupService", function ($sce, $log, $routeParams, $interval, $rootScope, $location, $scope, $filter, $q, RamblersUploadAudit, WalksService, WalksQueryService, URLService, ClipboardService, WalksReferenceService, WalkNotificationService, LoggedInMemberService, MemberService, DateUtils, BatchGeoExportService, RamblersWalksAndEventsService, Notifier, CommitteeReferenceData, GoogleMapsConfig, MeetupService) { var logger = $log.getInstance('WalksController'); var noLogger = $log.getInstance('WalksControllerNoLogger'); $log.logLevels['WalksControllerNoLogger'] = $log.LEVEL.OFF; $log.logLevels['WalksController'] = $log.LEVEL.OFF; $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; $scope.$watch('filterParameters.quickSearch', function (quickSearch, oldQuery) { refreshFilteredWalks(); }); $scope.finalStatusError = function () { return _.findWhere($scope.ramblersUploadAudit, {status: "error"}); }; $scope.fileNameChanged = function () { logger.debug('filename changed to', $scope.userEdits.fileName); $scope.refreshRamblersUploadAudit(); }; $scope.refreshRamblersUploadAudit = function (stop) { logger.debug('refreshing audit trail records related to', $scope.userEdits.fileName); return RamblersUploadAudit.query({fileName: $scope.userEdits.fileName}, {sort: {auditTime: -1}}) .then(function (auditItems) { logger.debug('Filtering', auditItems.length, 'audit trail records related to', $scope.userEdits.fileName); $scope.ramblersUploadAudit = _.chain(auditItems) .filter(function (auditItem) { return $scope.userEdits.showDetail || auditItem.type !== "detail"; }) .map(function (auditItem) { if (auditItem.status === "complete") { logger.debug('Upload complete'); notifyWalkExport.success("Ramblers upload completed"); $interval.cancel(stop); $scope.userEdits.saveInProgress = false; } return auditItem; }) .value(); }); }; $scope.ramblersUploadAudit = []; $scope.walksForExport = []; $scope.walkEditModes = WalksReferenceService.walkEditModes; $scope.walkStatuses = WalksReferenceService.walkStatuses; $scope.walkAlert = {}; $scope.walkExport = {}; var notify = Notifier($scope); var notifyWalkExport = Notifier($scope.walkExport); var notifyWalkEdit = Notifier($scope.walkAlert); var SHOW_START_POINT = "show-start-point"; var SHOW_DRIVING_DIRECTIONS = "show-driving-directions"; notify.setBusy(); $scope.copyFrom = {walkTemplates: [], walkTemplate: {}}; $scope.userEdits = { copyToClipboard: ClipboardService.copyToClipboard, meetupEvent: {}, copySource: 'copy-selected-walk-leader', copySourceFromWalkLeaderMemberId: undefined, expandedWalks: [], mapDisplay: SHOW_START_POINT, longerDescriptionPreview: true, walkExportActive: function (activeTab) { return activeTab === $scope.walkExportActive; }, walkExportTab0Active: true, walkExportTab1Active: false, walkExportTabActive: 0, status: undefined, sendNotifications: true, saveInProgress: false, fileNames: [], walkLink: function (walk) { return walk && walk.$id() ? URLService.notificationHref({ type: "walk", area: "walks", id: walk.$id() }) : undefined } }; $scope.walks = []; $scope.busy = false; $scope.walksProgrammeOpen = URLService.isArea('programme', 'walkId') || URLService.noArea(); $scope.walksInformationOpen = URLService.isArea('information'); $scope.walksMapViewOpen = URLService.isArea('mapview'); $scope.todayValue = DateUtils.momentNowNoTime().valueOf(); $scope.userEdits.walkDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.userEdits.walkDateCalendar.opened = true; } }; $scope.addWalk = function () { showWalkDialog(new WalksService({ status: WalksReferenceService.eventTypes.awaitingLeader.eventType, walkType: $scope.type[0], walkDate: $scope.todayValue }), WalksReferenceService.walkEditModes.add); }; $scope.addWalkSlotsDialog = function () { $rootScope.$broadcast('addWalkSlotsDialogOpen'); }; $scope.unlinkRamblersDataFromCurrentWalk = function () { delete $scope.currentWalk.ramblersWalkId; notify.progress('Previous Ramblers walk has now been unlinked.') }; $scope.canUnlinkRamblers = function () { return LoggedInMemberService.allowWalkAdminEdits() && $scope.ramblersWalkExists(); }; $scope.notUploadedToRamblersYet = function () { return !$scope.ramblersWalkExists(); }; $scope.insufficientDataToUploadToRamblers = function () { return LoggedInMemberService.allowWalkAdminEdits() && $scope.currentWalk && !($scope.currentWalk.gridReference || $scope.currentWalk.postcode); }; $scope.canExportToRamblers = function () { return LoggedInMemberService.allowWalkAdminEdits() && $scope.validateWalk().selected; }; $scope.validateWalk = function () { return RamblersWalksAndEventsService.validateWalk($scope.currentWalk, $scope.members); }; $scope.walkValidations = function () { var walkValidations = $scope.validateWalk().walkValidations; return 'This walk cannot be included in the Ramblers Walks and Events Manager export due to the following ' + walkValidations.length + ' problem(s): ' + walkValidations.join(", ") + '.'; }; $scope.grades = ['Easy access', 'Easy', 'Leisurely', 'Moderate', 'Strenuous', 'Technical']; $scope.walkTypes = ['Circular', 'Linear']; $scope.meetupEventUrlChange = function (walk) { walk.meetupEventTitle = $scope.userEdits.meetupEvent.title; walk.meetupEventUrl = $scope.userEdits.meetupEvent.url; }; $scope.meetupSelectSync = function (walk) { $scope.userEdits.meetupEvent = _.findWhere($scope.meetupEvents, {url: walk.meetupEventUrl}); }; $scope.ramblersWalkExists = function () { return $scope.validateWalk().publishedOnRamblers }; function loggedInMemberIsLeadingWalk(walk) { return walk && walk.walkLeaderMemberId === LoggedInMemberService.loggedInMember().memberId } $scope.loggedIn = function () { return LoggedInMemberService.memberLoggedIn(); }; $scope.toWalkEditMode = function (walk) { if (LoggedInMemberService.memberLoggedIn()) { if (loggedInMemberIsLeadingWalk(walk) || LoggedInMemberService.allowWalkAdminEdits()) { return WalksReferenceService.walkEditModes.edit; } else if (!walk.walkLeaderMemberId) { return WalksReferenceService.walkEditModes.lead; } } }; $scope.actionWalk = function (walk) { showWalkDialog(walk, $scope.toWalkEditMode(walk)); }; $scope.deleteWalkDetails = function () { $scope.confirmAction = {delete: true}; notifyWalkEdit.warning({ title: 'Confirm delete of walk details.', message: 'If you confirm this, the slot for ' + $filter('displayDate')($scope.currentWalk.walkDate) + ' will be deleted from the site.' }); }; $scope.cancelWalkDetails = function () { $scope.confirmAction = {cancel: true}; notifyWalkEdit.warning({ title: 'Cancel changes.', message: 'Click Confirm to lose any changes you\'ve just made for ' + $filter('displayDate')($scope.currentWalk.walkDate) + ', or Cancel to carry on editing.' }); }; $scope.confirmCancelWalkDetails = function () { hideWalkDialogAndRefreshWalks(); }; function isWalkReadyForStatusChangeTo(eventType) { notifyWalkEdit.hide(); logger.info('isWalkReadyForStatusChangeTo ->', eventType); var walkValidations = $scope.validateWalk().walkValidations; if (eventType.mustHaveLeader && !$scope.currentWalk.walkLeaderMemberId) { notifyWalkEdit.warning( { title: 'Walk leader needed', message: ' - this walk cannot be changed to ' + eventType.description + ' yet.' }); revertToPriorWalkStatus(); return false; } else if (eventType.mustPassValidation && walkValidations.length > 0) { notifyWalkEdit.warning( { title: 'This walk is not ready to be ' + eventType.readyToBe + ' yet due to the following ' + walkValidations.length + ' problem(s): ', message: walkValidations.join(", ") + '. You can still save this walk, then come back later on to complete the rest of the details.' }); revertToPriorWalkStatus(); return false; } else { return true; } } function initiateEvent() { $scope.userEdits.saveInProgress = true; var walk = DateUtils.convertDateFieldInObject($scope.currentWalk, 'walkDate'); return WalkNotificationService.createEventAndSendNotifications($scope.members, walk, $scope.userEdits.status, notifyWalkEdit, $scope.userEdits.sendNotifications && walk.walkLeaderMemberId); } $scope.confirmDeleteWalkDetails = function () { $scope.userEdits.status = WalksReferenceService.eventTypes.deleted.eventType; return initiateEvent() .then(function () { return $scope.currentWalk.$saveOrUpdate(hideWalkDialogAndRefreshWalks, hideWalkDialogAndRefreshWalks); }) .catch(function () { $scope.userEdits.saveInProgress = false; }); }; $scope.saveWalkDetails = function () { return initiateEvent() .then(function (notificationSent) { return $scope.currentWalk.$saveOrUpdate(afterSaveWith(notificationSent), afterSaveWith(notificationSent)); }) .catch(function () { $scope.userEdits.saveInProgress = false; }); }; $scope.requestApproval = function () { logger.info('requestApproval called with current status:', $scope.userEdits.status); if (isWalkReadyForStatusChangeTo(WalksReferenceService.eventTypes.awaitingApproval)) { $scope.confirmAction = {requestApproval: true}; notifyWalkEdit.warning({ title: 'Confirm walk details complete.', message: 'If you confirm this, your walk details will be emailed to ' + walksCoordinatorName() + ' and they will publish these to the site.' }); } }; $scope.contactOther = function () { notifyWalkEdit.warning({ title: 'Confirm walk details complete.', message: 'If you confirm this, your walk details will be emailed to ' + walksCoordinatorName() + ' and they will publish these to the site.' }); }; $scope.walkStatusChange = function (status) { $scope.userEdits.priorStatus = status; notifyWalkEdit.hide(); logger.info('walkStatusChange - was:', status, 'now:', $scope.userEdits.status); if (isWalkReadyForStatusChangeTo(WalksReferenceService.toEventType($scope.userEdits.status))) switch ($scope.userEdits.status) { case WalksReferenceService.eventTypes.awaitingLeader.eventType: { var walkDate = $scope.currentWalk.walkDate; $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingLeader.eventType; $scope.currentWalk = new WalksService(_.pick($scope.currentWalk, ['_id', 'events', 'walkDate'])); return notifyWalkEdit.success({ title: 'Walk details reset for ' + $filter('displayDate')(walkDate) + '.', message: 'Status is now ' + WalksReferenceService.eventTypes.awaitingLeader.description }); } case WalksReferenceService.eventTypes.approved.eventType: { return $scope.approveWalkDetails(); } } }; $scope.approveWalkDetails = function () { var walkValidations = $scope.validateWalk().walkValidations; if (walkValidations.length > 0) { notifyWalkEdit.warning({ title: 'This walk still has the following ' + walkValidations.length + ' field(s) that need attention: ', message: walkValidations.join(", ") + '. You\'ll have to get the rest of these details completed before you mark the walk as approved.' }); revertToPriorWalkStatus(); } else { notifyWalkEdit.success({ title: 'Ready to publish walk details!', message: 'All fields appear to be filled in okay, so next time you save this walk it will be published.' }); } }; $scope.confirmRequestApproval = function () { $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingApproval.eventType; $scope.saveWalkDetails(); }; $scope.cancelConfirmableAction = function () { delete $scope.confirmAction; notify.hide(); notifyWalkEdit.hide(); }; function revertToPriorWalkStatus() { logger.info('revertToPriorWalkStatus:', $scope.userEdits.status, '->', $scope.userEdits.priorStatus); if ($scope.userEdits.priorStatus) $scope.userEdits.status = $scope.userEdits.priorStatus; } $scope.populateCurrentWalkFromTemplate = function () { var walkTemplate = _.clone($scope.copyFrom.walkTemplate); if (walkTemplate) { var templateDate = $filter('displayDate')(walkTemplate.walkDate); delete walkTemplate._id; delete walkTemplate.events; delete walkTemplate.ramblersWalkId; delete walkTemplate.walkDate; delete walkTemplate.displayName; delete walkTemplate.contactPhone; delete walkTemplate.contactEmail; angular.extend($scope.currentWalk, walkTemplate); var event = WalkNotificationService.createEventIfRequired($scope.currentWalk, WalksReferenceService.eventTypes.walkDetailsCopied.eventType, 'Copied from previous walk on ' + templateDate); WalkNotificationService.writeEventIfRequired($scope.currentWalk, event); notifyWalkEdit.success({ title: 'Walk details were copied from ' + templateDate + '.', message: 'Make any further changes here and save when you are done.' }); } }; $scope.filterParameters = { quickSearch: '', selectType: '1', ascending: "true" }; $scope.selectCopySelectedLeader = function () { $scope.userEdits.copySource = 'copy-selected-walk-leader'; $scope.populateWalkTemplates(); }; $scope.populateWalkTemplates = function (injectedMemberId) { var memberId = $scope.currentWalk.walkLeaderMemberId || injectedMemberId; var criteria; switch ($scope.userEdits.copySource) { case "copy-selected-walk-leader": { criteria = { walkLeaderMemberId: $scope.userEdits.copySourceFromWalkLeaderMemberId, briefDescriptionAndStartPoint: {$exists: true} }; break } case "copy-with-os-maps-route-selected": { criteria = {osMapsRoute: {$exists: true}}; break } default: { criteria = {walkLeaderMemberId: memberId}; } } logger.info('selecting walks', $scope.userEdits.copySource, criteria); WalksService.query(criteria, {sort: {walkDate: -1}}) .then(function (walks) { $scope.copyFrom.walkTemplates = walks; }); }; $scope.walkLeaderMemberIdChanged = function () { notifyWalkEdit.hide(); var walk = $scope.currentWalk; var memberId = walk.walkLeaderMemberId; if (!memberId) { $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingLeader.eventType; delete walk.walkLeaderMemberId; delete walk.contactId; delete walk.displayName; delete walk.contactPhone; delete walk.contactEmail; } else { var selectedMember = _.find($scope.members, function (member) { return member.$id() === memberId; }); if (selectedMember) { $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingWalkDetails.eventType; walk.contactId = selectedMember.contactId; walk.displayName = selectedMember.displayName; walk.contactPhone = selectedMember.mobileNumber; walk.contactEmail = selectedMember.email; $scope.populateWalkTemplates(memberId); } } }; $scope.myOrWalkLeader = function () { return loggedInMemberIsLeadingWalk($scope.currentWalk) ? 'my' : $scope.currentWalk && $scope.currentWalk.displayName + "'s"; }; $scope.meOrWalkLeader = function () { return loggedInMemberIsLeadingWalk($scope.currentWalk) ? 'me' : $scope.currentWalk && $scope.currentWalk.displayName; }; $scope.personToNotify = function () { return loggedInMemberIsLeadingWalk($scope.currentWalk) ? walksCoordinatorName() : $scope.currentWalk && $scope.currentWalk.displayName; }; function walksCoordinatorName() { return CommitteeReferenceData.contactUsField('walks', 'fullName'); } function convertWalkDateIfNotNumeric(walk) { var walkDate = DateUtils.asValueNoTime(walk.walkDate); if (walkDate !== walk.walkDate) { logger.info('Converting date from', walk.walkDate, '(' + $filter('displayDateAndTime')(walk.walkDate) + ') to', walkDate, '(' + $filter('displayDateAndTime')(walkDate) + ')'); walk.walkDate = walkDate; } else { logger.info('Walk date', walk.walkDate, 'is already in correct format'); } return walk; } function latestEventWithStatusChangeIs(eventType) { return WalkNotificationService.latestEventWithStatusChangeIs($scope.currentWalk, eventType); } $scope.dataHasChanged = function () { var dataAuditDelta = WalkNotificationService.dataAuditDelta($scope.currentWalk, $scope.userEdits.status); var notificationRequired = dataAuditDelta.notificationRequired; dataAuditDelta.notificationRequired && noLogger.info('dataAuditDelta - eventExists:', dataAuditDelta.eventExists, 'dataChanged:', dataAuditDelta.dataChanged, $filter('toAuditDeltaChangedItems')(dataAuditDelta.changedItems)); dataAuditDelta.dataChanged && noLogger.info('dataAuditDelta - previousData:', dataAuditDelta.previousData, 'currentData:', dataAuditDelta.currentData); return notificationRequired; }; function ownedAndAwaitingWalkDetails() { return loggedInMemberIsLeadingWalk($scope.currentWalk) && $scope.userEdits.status === WalksReferenceService.eventTypes.awaitingWalkDetails.eventType; } function editable() { return !$scope.confirmAction && (LoggedInMemberService.allowWalkAdminEdits() || loggedInMemberIsLeadingWalk($scope.currentWalk)); } function allowSave() { return editable() && $scope.dataHasChanged(); } $scope.allow = { close: function () { return !$scope.userEdits.saveInProgress && !$scope.confirmAction && !allowSave() }, save: allowSave, cancel: function () { return !$scope.userEdits.saveInProgress && editable() && $scope.dataHasChanged(); }, delete: function () { return !$scope.confirmAction && LoggedInMemberService.allowWalkAdminEdits() && $scope.walkEditMode && $scope.walkEditMode.editEnabled; }, notifyConfirmation: function () { return (allowSave() || $scope.confirmAction && $scope.confirmAction.delete) && $scope.currentWalk.walkLeaderMemberId; }, adminEdits: function () { return LoggedInMemberService.allowWalkAdminEdits(); }, edits: editable, historyView: function () { return loggedInMemberIsLeadingWalk($scope.currentWalk) || LoggedInMemberService.allowWalkAdminEdits(); }, detailView: function () { return LoggedInMemberService.memberLoggedIn(); }, approve: function () { return !$scope.confirmAction && LoggedInMemberService.allowWalkAdminEdits() && latestEventWithStatusChangeIs(WalksReferenceService.eventTypes.awaitingApproval); }, requestApproval: function () { return !$scope.confirmAction && ownedAndAwaitingWalkDetails(); } }; $scope.previewLongerDescription = function () { logger.debug('previewLongerDescription'); $scope.userEdits.longerDescriptionPreview = true; }; $scope.editLongerDescription = function () { logger.debug('editLongerDescription'); $scope.userEdits.longerDescriptionPreview = false; }; $scope.trustSrc = function (src) { return $sce.trustAsResourceUrl(src); }; $scope.showAllWalks = function () { $scope.expensesOpen = true; $location.path('/walks/programme') }; $scope.googleMaps = function (walk) { return $scope.userEdits.mapDisplay === SHOW_DRIVING_DIRECTIONS ? "https://www.google.com/maps/embed/v1/directions?origin=" + $scope.userEdits.fromPostcode + "&destination=" + walk.postcode + "&key=" + $scope.googleMapsConfig.apiKey : "https://www.google.com/maps/embed/v1/place?q=" + walk.postcode + "&zoom=" + $scope.googleMapsConfig.zoomLevel + "&key=" + $scope.googleMapsConfig.apiKey; }; $scope.autoSelectMapDisplay = function () { var switchToShowStartPoint = $scope.drivingDirectionsDisabled() && $scope.userEdits.mapDisplay === SHOW_DRIVING_DIRECTIONS; var switchToShowDrivingDirections = !$scope.drivingDirectionsDisabled() && $scope.userEdits.mapDisplay === SHOW_START_POINT; if (switchToShowStartPoint) { $scope.userEdits.mapDisplay = SHOW_START_POINT; } else if (switchToShowDrivingDirections) { $scope.userEdits.mapDisplay = SHOW_DRIVING_DIRECTIONS; } }; $scope.drivingDirectionsDisabled = function () { return $scope.userEdits.fromPostcode.length < 3; }; $scope.eventTypeFor = function (walk) { var latestEventWithStatusChange = WalkNotificationService.latestEventWithStatusChange(walk); var eventType = WalksReferenceService.toEventType(latestEventWithStatusChange.eventType) || walk.status || WalksReferenceService.eventTypes.awaitingWalkDetails.eventType; noLogger.info('latestEventWithStatusChange', latestEventWithStatusChange, 'eventType', eventType, 'walk.events', walk.events); return eventType; }; $scope.viewWalkField = function (walk, field) { var eventType = $scope.eventTypeFor(walk); if (eventType.showDetails) { return walk[field] || ''; } else if (field === 'briefDescriptionAndStartPoint') { return eventType.description; } else { return ''; } }; function showWalkDialog(walk, walkEditMode) { delete $scope.confirmAction; $scope.userEdits.sendNotifications = true; $scope.walkEditMode = walkEditMode; $scope.currentWalk = walk; if (walkEditMode.initialiseWalkLeader) { $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingWalkDetails.eventType; walk.walkLeaderMemberId = LoggedInMemberService.loggedInMember().memberId; $scope.walkLeaderMemberIdChanged(); notifyWalkEdit.success({ title: 'Thanks for offering to lead this walk ' + LoggedInMemberService.loggedInMember().firstName + '!', message: 'Please complete as many details you can, then save to allocate this slot on the walks programme. ' + 'It will be published to the public once it\'s approved. If you want to release this slot again, just click cancel.' }); } else { var eventTypeIfExists = WalkNotificationService.latestEventWithStatusChange($scope.currentWalk).eventType; if (eventTypeIfExists) { $scope.userEdits.status = eventTypeIfExists } $scope.userEdits.copySourceFromWalkLeaderMemberId = walk.walkLeaderMemberId || LoggedInMemberService.loggedInMember().memberId; $scope.populateWalkTemplates(); $scope.meetupSelectSync($scope.currentWalk); notifyWalkEdit.hide(); } $('#walk-dialog').modal(); } function walksCriteriaObject() { switch ($scope.filterParameters.selectType) { case '1': return {walkDate: {$gte: $scope.todayValue}}; case '2': return {walkDate: {$lt: $scope.todayValue}}; case '3': return {}; case '4': return {displayName: {$exists: false}}; case '5': return {briefDescriptionAndStartPoint: {$exists: false}}; } } function walksSortObject() { switch ($scope.filterParameters.ascending) { case 'true': return {sort: {walkDate: 1}}; case 'false': return {sort: {walkDate: -1}}; } } function query() { if (URLService.hasRouteParameter('walkId')) { return WalksService.getById($routeParams.walkId) .then(function (walk) { if (!walk) notify.error('Walk could not be found. Try opening again from the link in the notification email, or choose the Show All Walks button'); return [walk]; }); } else { return WalksService.query(walksCriteriaObject(), walksSortObject()); } } function refreshFilteredWalks() { notify.setBusy(); $scope.filteredWalks = $filter('filter')($scope.walks, $scope.filterParameters.quickSearch); var walksCount = ($scope.filteredWalks && $scope.filteredWalks.length) || 0; notify.progress('Showing ' + walksCount + ' walk(s)'); if ($scope.filteredWalks.length > 0) { $scope.userEdits.expandedWalks = [$scope.filteredWalks[0].$id()]; } notify.clearBusy(); } $scope.showTableHeader = function (walk) { return $scope.filteredWalks.indexOf(walk) === 0 || $scope.isExpandedFor($scope.filteredWalks[$scope.filteredWalks.indexOf(walk) - 1]); }; $scope.nextWalk = function (walk) { return walk && walk.$id() === $scope.nextWalkId; }; $scope.durationInFutureFor = function (walk) { return walk && walk.walkDate === $scope.todayValue ? 'today' : (DateUtils.asMoment(walk.walkDate).fromNow()); }; $scope.toggleViewFor = function (walk) { function arrayRemove(arr, value) { return arr.filter(function (ele) { return ele !== value; }); } var walkId = walk.$id(); if (_.contains($scope.userEdits.expandedWalks, walkId)) { $scope.userEdits.expandedWalks = arrayRemove($scope.userEdits.expandedWalks, walkId); logger.debug('toggleViewFor:', walkId, '-> collapsing'); } else { $scope.userEdits.expandedWalks.push(walkId); logger.debug('toggleViewFor:', walkId, '-> expanding'); } logger.debug('toggleViewFor:', walkId, '-> expandedWalks contains', $scope.userEdits.expandedWalks) }; $scope.isExpandedFor = function (walk) { return _.contains($scope.userEdits.expandedWalks, walk.$id()); }; $scope.tableRowOdd = function (walk) { return $scope.filteredWalks.indexOf(walk) % 2 === 0; }; function getNextWalkId(walks) { var nextWalk = _.chain(walks).sortBy('walkDate').find(function (walk) { return walk.walkDate >= $scope.todayValue; }).value(); return nextWalk && nextWalk.$id(); } $scope.refreshWalks = function (notificationSent) { notify.setBusy(); notify.progress('Refreshing walks...'); return query() .then(function (walks) { $scope.nextWalkId = URLService.hasRouteParameter('walkId') ? undefined : getNextWalkId(walks); $scope.walks = URLService.hasRouteParameter('walkId') ? walks : WalksQueryService.activeWalks(walks); refreshFilteredWalks(); notify.clearBusy(); if (!notificationSent) { notifyWalkEdit.hide(); } $scope.userEdits.saveInProgress = false; }); }; $scope.hideWalkDialog = function () { $('#walk-dialog').modal('hide'); delete $scope.confirmAction; }; function hideWalkDialogAndRefreshWalks() { logger.info('hideWalkDialogAndRefreshWalks'); $scope.hideWalkDialog(); $scope.refreshWalks(); } function afterSaveWith(notificationSent) { return function () { if (!notificationSent) $('#walk-dialog').modal('hide'); notifyWalkEdit.clearBusy(); delete $scope.confirmAction; $scope.refreshWalks(notificationSent); $scope.userEdits.saveInProgress = false; } } function refreshRamblersConfig() { RamblersWalksAndEventsService.walkBaseUrl().then(function (walkBaseUrl) { $scope.ramblersWalkBaseUrl = walkBaseUrl; }); } function refreshGoogleMapsConfig() { GoogleMapsConfig.getConfig().then(function (googleMapsConfig) { $scope.googleMapsConfig = googleMapsConfig; $scope.googleMapsConfig.zoomLevel = 12; }); } function refreshMeetupData() { MeetupService.config().then(function (meetupConfig) { $scope.meetupConfig = meetupConfig; }); MeetupService.eventsForStatus('past') .then(function (pastEvents) { MeetupService.eventsForStatus('upcoming') .then(function (futureEvents) { $scope.meetupEvents = _.sortBy(pastEvents.concat(futureEvents), 'date,').reverse(); }); }) } function refreshHomePostcode() { $scope.userEdits.fromPostcode = LoggedInMemberService.memberLoggedIn() ? LoggedInMemberService.loggedInMember().postcode : ""; logger.debug('set from postcode to', $scope.userEdits.fromPostcode); $scope.autoSelectMapDisplay(); } $scope.$on('memberLoginComplete', function () { refreshMembers(); refreshHomePostcode(); }); $scope.$on('walkSlotsCreated', function () { $scope.refreshWalks(); }); function refreshMembers() { if (LoggedInMemberService.memberLoggedIn()) MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS) .then(function (members) { $scope.members = members; return members; }); } $scope.batchGeoDownloadFile = function () { return BatchGeoExportService.exportWalks($scope.walks, $scope.members); }; $scope.batchGeoDownloadFileName = function () { return BatchGeoExportService.exportWalksFileName(); }; $scope.batchGeoDownloadHeader = function () { return BatchGeoExportService.exportColumnHeadings(); }; $scope.exportableWalks = function () { return RamblersWalksAndEventsService.exportableWalks($scope.walksForExport); }; $scope.walksDownloadFile = function () { return RamblersWalksAndEventsService.exportWalks($scope.exportableWalks(), $scope.members); }; $scope.uploadToRamblers = function () { $scope.ramblersUploadAudit = []; $scope.userEdits.walkExportTab0Active = false; $scope.userEdits.walkExportTab1Active = true; $scope.userEdits.saveInProgress = true; RamblersWalksAndEventsService.uploadToRamblers($scope.walksForExport, $scope.members, notifyWalkExport).then(function (fileName) { $scope.userEdits.fileName = fileName; var stop = $interval(callAtInterval, 2000, false); if (!_.contains($scope.userEdits.fileNames, $scope.userEdits.fileName)) { $scope.userEdits.fileNames.push($scope.userEdits.fileName); logger.debug('added', $scope.userEdits.fileName, 'to filenames of', $scope.userEdits.fileNames.length, 'audit trail records'); } delete $scope.finalStatusError; function callAtInterval() { logger.debug("Refreshing audit trail for file", $scope.userEdits.fileName, 'count =', $scope.ramblersUploadAudit.length); $scope.refreshRamblersUploadAudit(stop); } }); }; $scope.walksDownloadFileName = function () { return RamblersWalksAndEventsService.exportWalksFileName(); }; $scope.walksDownloadHeader = function () { return RamblersWalksAndEventsService.exportColumnHeadings(); }; $scope.selectWalksForExport = function () { showWalkExportDialog(); }; $scope.changeWalkExportSelection = function (walk) { if (walk.walkValidations.length === 0) { walk.selected = !walk.selected; notifyWalkExport.hide(); } else { notifyWalkExport.error({ title: 'You can\'t export the walk for ' + $filter('displayDate')(walk.walk.walkDate), message: walk.walkValidations.join(', ') }); } }; $scope.cancelExportWalkDetails = function () { $('#walk-export-dialog').modal('hide'); }; function populateWalkExport(walksForExport) { $scope.walksForExport = walksForExport; notifyWalkExport.success('Found total of ' + $scope.walksForExport.length + ' walk(s), ' + $scope.walksDownloadFile().length + ' preselected for export'); notifyWalkExport.clearBusy(); } function showWalkExportDialog() { $scope.walksForExport = []; notifyWalkExport.warning('Determining which walks to export', true); RamblersUploadAudit.all({limit: 1000, sort: {auditTime: -1}}) .then(function (auditItems) { logger.debug('found total of', auditItems.length, 'audit trail records'); $scope.userEdits.fileNames = _.chain(auditItems).pluck('fileName').unique().value(); logger.debug('unique total of', $scope.userEdits.fileNames.length, 'audit trail records'); }); RamblersWalksAndEventsService.createWalksForExportPrompt($scope.walks, $scope.members) .then(populateWalkExport) .catch(function (error) { logger.debug('error->', error); notifyWalkExport.error({title: 'Problem with Ramblers export preparation', message: JSON.stringify(error)}); }); $('#walk-export-dialog').modal(); } refreshMembers(); $scope.refreshWalks(); refreshRamblersConfig(); refreshGoogleMapsConfig(); refreshMeetupData(); refreshHomePostcode(); }] ) ;
nbarrett/ekwg
dist/app/js/ekwg.js
JavaScript
mit
405,222
angular.module('MEANcraftApp', ['ngRoute', 'MEANcraftApp.login', 'MEANcraftApp.overview', 'btford.socket-io'/*,'socket-io', 'flow'*/]) .config(function ($httpProvider, $routeProvider) { $httpProvider.interceptors.push('TokenInterceptor'); $routeProvider .when('/login', { templateUrl: 'app/login/login', controller: 'loginCtrl', protect: false }) .when('/overview', { templateUrl: 'app/overview/overview', //controller: 'overviewCtrl', protect: true, resolve: { initialData: function (ServerSocket, FetchData, $q) { return $q(function (resolve, reject) { ServerSocket.emit('info'); ServerSocket.once('info', function (data) { console.log(data); FetchData = angular.extend(FetchData, data); resolve(); }); }); } } }) .otherwise({ redirectTo: '/overview' }); }) .run(function ($rootScope, $location, $window, $routeParams, UserAuth) { if (!UserAuth.isLogged) { $location.path('/login'); } $rootScope.$on('$routeChangeStart', function (event, nextRoute, prevRoute) { console.groupCollapsed('%cAPP.RUN -> ROUTE CHANGE START', 'background: #222; color: #bada55;'); console.log('%cTOKEN -> %c' + $window.sessionStorage.token, 'font-weight: bold', ''); console.log('%cLOGGIN STATUS -> %c' + UserAuth.isLogged, 'font-weight: bold', UserAuth.isLogged ? 'color: green;' : 'color: red;'); console.groupEnd('APP.RUN -> ROUTE CHANGE START'); if (nextRoute.protect && UserAuth.isLogged === false && !$window.sessionStorage.token) { $location.path('/login'); console.error('Route protected, user not logged in'); } else if (!nextRoute.protect && UserAuth.isLogged) { $location.path('/overview'); } }); });
frotunato/MEANcraft
client/app/app.js
JavaScript
mit
1,953
var GridLayout = require("ui/layouts/grid-layout").GridLayout; var ListView = require("ui/list-view").ListView; var StackLayout = require("ui/layouts/stack-layout").StackLayout; var Image = require("ui/image").Image; var Label = require("ui/label").Label; var ScrapbookList = (function (_super) { global.__extends(ScrapbookList, _super); Object.defineProperty(ScrapbookList.prototype, "items", { get: function() { return this._items; }, set: function(value) { this._items = value; this.bindData(); } }); function ScrapbookList() { _super.call(this); this._items; this.rows = "*"; this.columns = "*"; var listView = new ListView(); listView.className = "list-group"; listView.itemTemplate = function() { var stackLayout = new StackLayout(); stackLayout.orientation = "horizontal"; stackLayout.bind({ targetProperty: "className", sourceProperty: "$value", expression: "isActive ? 'list-group-item active' : 'list-group-item'" }); var image = new Image(); image.className = "thumb img-circle"; image.bind({ targetProperty: "src", sourceProperty: "image" }); stackLayout.addChild(image); var label = new Label(); label.className = "list-group-item-text"; label.style.width = "100%"; label.textWrap = true; label.bind({ targetProperty: "text", sourceProperty: "title", expression: "(title === null || title === undefined ? 'New' : title + '\\\'s') + ' Scrapbook Page'" }); stackLayout.addChild(label); return stackLayout; }; listView.on(ListView.itemTapEvent, function(args) { onItemTap(this, args.index); }.bind(listView)); this.addChild(listView); this.bindData = function () { listView.bind({ sourceProperty: "$value", targetProperty: "items", twoWay: "true" }, this._items); }; var onItemTap = function(args, index) { this.notify({ eventName: "itemTap", object: this, index: index }); }.bind(this); } return ScrapbookList; })(GridLayout); ScrapbookList.itemTapEvent = "itemTap"; exports.ScrapbookList = ScrapbookList;
mikebranstein/NativeScriptInAction
AppendixB/PetScrapbook/app/views/shared/scrapbook-list/scrapbook-list.js
JavaScript
mit
3,048
<?php /** * @package toolkit */ /** * The Datasource class provides functionality to mainly process any parameters * that the fields will use in filters find the relevant Entries and return these Entries * data as XML so that XSLT can be applied on it to create your website. In Symphony, * there are four Datasource types provided, Section, Author, Navigation and Dynamic * XML. Section is the mostly commonly used Datasource, which allows the filtering * and searching for Entries in a Section to be returned as XML. Navigation datasources * expose the Symphony Navigation structure of the Pages in the installation. Authors * expose the Symphony Authors that are registered as users of the backend. Finally, * the Dynamic XML datasource allows XML pages to be retrieved. This is especially * helpful for working with Restful XML API's. Datasources are saved through the * Symphony backend, which uses a Datasource template defined in * `TEMPLATE . /datasource.tpl`. */ class DataSource { /** * A constant that represents if this filter is an AND filter in which * an Entry must match all these filters. This filter is triggered when * the filter string contains a ` + `. * * @since Symphony 2.3.2 * @var integer */ const FILTER_AND = 1; /** * A constant that represents if this filter is an OR filter in which an * entry can match any or all of these filters * * @since Symphony 2.3.2 * @var integer */ const FILTER_OR = 2; /** * Holds all the environment variables which include parameters set by * other Datasources or Events. * @var array */ protected $_env = array(); /** * If true, this datasource only will be outputting parameters from the * Entries, and no actual content. * @var boolean */ protected $_param_output_only; /** * An array of datasource dependancies. These are datasources that must * run first for this datasource to be able to execute correctly * @var array */ protected $_dependencies = array(); /** * When there is no entries found by the Datasource, this parameter will * be set to true, which will inject the default Symphony 'No records found' * message into the datasource's result * @var boolean */ protected $_force_empty_result = false; /** * When there is a negating parameter, this parameter will * be set to true, which will inject the default Symphony 'Results Negated' * message into the datasource's result * @var boolean */ protected $_negate_result = false; /** * Constructor for the datasource sets the parent, if `$process_params` is set, * the `$env` variable will be run through `Datasource::processParameters`. * * @see toolkit.Datasource#processParameters() * @param array $env * The environment variables from the Frontend class which includes * any params set by Symphony or Events or by other Datasources * @param boolean $process_params * If set to true, `Datasource::processParameters` will be called. By default * this is true * @throws FrontendPageNotFoundException */ public function __construct(array $env = null, $process_params = true) { // Support old the __construct (for the moment anyway). // The old signature was array/array/boolean // The new signature is array/boolean $arguments = func_get_args(); if (count($arguments) == 3 && is_bool($arguments[1]) && is_bool($arguments[2])) { $env = $arguments[0]; $process_params = $arguments[1]; } if ($process_params) { $this->processParameters($env); } } /** * This function is required in order to edit it in the datasource editor page. * Do not overload this function if you are creating a custom datasource. It is only * used by the datasource editor. If this is set to false, which is default, the * Datasource's `about()` information will be displayed. * * @return boolean * True if the Datasource can be edited, false otherwise. Defaults to false */ public function allowEditorToParse() { return false; } /** * This function is required in order to identify what section this Datasource is for. It * is used in the datasource editor. It must remain intact. Do not overload this function in * custom events. Other datasources may return a string here defining their datasource * type when they do not query a section. * * @return mixed */ public function getSource() { return null; } /** * Accessor function to return this Datasource's dependencies * * @return array */ public function getDependencies() { return $this->_dependencies; } /** * Returns an associative array of information about a datasource. * * @return array */ public function about() { return array(); } /** * @deprecated This function has been renamed to `execute` as of * Symphony 2.3.1, please use `execute()` instead. This function will * be removed in Symphony 2.5 * @see execute() */ public function grab(array &$param_pool = null) { return $this->execute($param_pool); } /** * The meat of the Datasource, this function includes the datasource * type's file that will preform the logic to return the data for this datasource * It is passed the current parameters. * * @param array $param_pool * The current parameter pool that this Datasource can use when filtering * and finding Entries or data. * @return XMLElement * The XMLElement to add into the XML for a page. */ public function execute(array &$param_pool = null) { $result = new XMLElement($this->dsParamROOTELEMENT); try { $result = $this->execute($param_pool); } catch (FrontendPageNotFoundException $e) { // Work around. This ensures the 404 page is displayed and // is not picked up by the default catch() statement below FrontendPageNotFoundExceptionHandler::render($e); } catch (Exception $e) { $result->appendChild(new XMLElement('error', $e->getMessage())); return $result; } if ($this->_force_empty_result) { $result = $this->emptyXMLSet(); } if ($this->_negate_result) { $result = $this->negateXMLSet(); } return $result; } /** * By default, all Symphony filters are considering to be AND filters, that is * they are all used and Entries must match each filter to be included. It is * possible to use OR filtering in a field by using an + to separate the values. * eg. If the filter is test1 + test2, this will match any entries where this field * is test1 OR test2. This function is run on each filter (ie. each field) in a * datasource * * @param string $value * The filter string for a field. * @return integer * DataSource::FILTER_OR or DataSource::FILTER_AND */ public function __determineFilterType($value) { return (preg_match('/\s+\+\s+/', $value) ? DataSource::FILTER_AND : DataSource::FILTER_OR); } /** * If there is no results to return this function calls `Datasource::__noRecordsFound` * which appends an XMLElement to the current root element. * * @param XMLElement $xml * The root element XMLElement for this datasource. By default, this will * the handle of the datasource, as defined by `$this->dsParamROOTELEMENT` * @return XMLElement */ public function emptyXMLSet(XMLElement $xml = null) { if (is_null($xml)) { $xml = new XMLElement($this->dsParamROOTELEMENT); } $xml->appendChild($this->__noRecordsFound()); return $xml; } /** * If the datasource has been negated this function calls `Datasource::__negateResult` * which appends an XMLElement to the current root element. * * @param XMLElement $xml * The root element XMLElement for this datasource. By default, this will * the handle of the datasource, as defined by `$this->dsParamROOTELEMENT` * @return XMLElement */ public function negateXMLSet(XMLElement $xml = null) { if (is_null($xml)) { $xml = new XMLElement($this->dsParamROOTELEMENT); } $xml->appendChild($this->__negateResult()); return $xml; } /** * Returns an error XMLElement with 'No records found' text * * @return XMLElement */ public function __noRecordsFound() { return new XMLElement('error', __('No records found.')); } /** * Returns an error XMLElement with 'Result Negated' text * * @return XMLElement */ public function __negateResult() { $error = new XMLElement('error', __("Data source not executed, forbidden parameter was found."), array( 'forbidden-param' => $this->dsParamNEGATEPARAM )); return $error; } /** * This function will iterates over the filters and replace any parameters with their * actual values. All other Datasource variables such as sorting, ordering and * pagination variables are also set by this function * * @param array $env * The environment variables from the Frontend class which includes * any params set by Symphony or Events or by other Datasources * @throws FrontendPageNotFoundException */ public function processParameters(array $env = null) { if ($env) { $this->_env = $env; } if ((isset($this->_env) && is_array($this->_env)) && isset($this->dsParamFILTERS) && is_array($this->dsParamFILTERS) && !empty($this->dsParamFILTERS)) { foreach ($this->dsParamFILTERS as $key => $value) { $value = stripslashes($value); $new_value = $this->__processParametersInString($value, $this->_env); // If a filter gets evaluated to nothing, eg. ` + ` or ``, then remove // the filter. RE: #1759 if (strlen(trim($new_value)) == 0 || !preg_match('/\w+/', $new_value)) { unset($this->dsParamFILTERS[$key]); } else { $this->dsParamFILTERS[$key] = $new_value; } } } if (isset($this->dsParamORDER)) { $this->dsParamORDER = $this->__processParametersInString($this->dsParamORDER, $this->_env); } if (isset($this->dsParamSORT)) { $this->dsParamSORT = $this->__processParametersInString($this->dsParamSORT, $this->_env); } if (isset($this->dsParamSTARTPAGE)) { $this->dsParamSTARTPAGE = $this->__processParametersInString($this->dsParamSTARTPAGE, $this->_env); if ($this->dsParamSTARTPAGE == '') { $this->dsParamSTARTPAGE = '1'; } } if (isset($this->dsParamLIMIT)) { $this->dsParamLIMIT = $this->__processParametersInString($this->dsParamLIMIT, $this->_env); } if ( isset($this->dsParamREQUIREDPARAM) && strlen(trim($this->dsParamREQUIREDPARAM)) > 0 && $this->__processParametersInString(trim($this->dsParamREQUIREDPARAM), $this->_env, false) == '' ) { $this->_force_empty_result = true; // don't output any XML $this->dsParamPARAMOUTPUT = null; // don't output any parameters $this->dsParamINCLUDEDELEMENTS = null; // don't query any fields in this section return; } if ( isset($this->dsParamNEGATEPARAM) && strlen(trim($this->dsParamNEGATEPARAM)) > 0 && $this->__processParametersInString(trim($this->dsParamNEGATEPARAM), $this->_env, false) != '' ) { $this->_negate_result = true; // don't output any XML $this->dsParamPARAMOUTPUT = null; // don't output any parameters $this->dsParamINCLUDEDELEMENTS = null; // don't query any fields in this section return; } $this->_param_output_only = ((!isset($this->dsParamINCLUDEDELEMENTS) || !is_array($this->dsParamINCLUDEDELEMENTS) || empty($this->dsParamINCLUDEDELEMENTS)) && !isset($this->dsParamGROUP)); if (isset($this->dsParamREDIRECTONEMPTY) && $this->dsParamREDIRECTONEMPTY == 'yes' && $this->_force_empty_result) { throw new FrontendPageNotFoundException; } } /** * This function will parse a string (usually a URL) and fully evaluate any * parameters (defined by {$param}) to return the absolute string value. * * @since Symphony 2.3 * @param string $url * The string (usually a URL) that contains the parameters (or doesn't) * @return string * The parsed URL */ public function parseParamURL($url = null) { if (!isset($url)) { return null; } // urlencode parameters $params = array(); if (preg_match_all('@{([^}]+)}@i', $url, $matches, PREG_SET_ORDER)) { foreach ($matches as $m) { $params[$m[1]] = array( 'param' => preg_replace('/:encoded$/', null, $m[1]), 'encode' => preg_match('/:encoded$/', $m[1]) ); } } foreach ($params as $key => $info) { $replacement = $this->__processParametersInString($info['param'], $this->_env, false); if ($info['encode'] == true) { $replacement = urlencode($replacement); } $url = str_replace("{{$key}}", $replacement, $url); } return $url; } /** * This function will replace any parameters in a string with their value. * Parameters are defined by being prefixed by a `$` character. In certain * situations, the parameter will be surrounded by `{}`, which Symphony * takes to mean, evaluate this parameter to a value, other times it will be * omitted which is usually used to indicate that this parameter exists * * @param string $value * The string with the parameters that need to be evaluated * @param array $env * The environment variables from the Frontend class which includes * any params set by Symphony or Events or by other Datasources * @param boolean $includeParenthesis * Parameters will sometimes not be surrounded by `{}`. If this is the case * setting this parameter to false will make this function automatically add * them to the parameter. By default this is true, which means all parameters * in the string already are surrounded by `{}` * @param boolean $escape * If set to true, the resulting value will passed through `urlencode` before * being returned. By default this is `false` * @return string * The string with all parameters evaluated. If a parameter is not found, it will * not be replaced and remain in the `$value`. */ public function __processParametersInString($value, array $env, $includeParenthesis = true, $escape = false) { if (trim($value) == '') { return null; } if (!$includeParenthesis) { $value = '{'.$value.'}'; } if (preg_match_all('@{([^}]+)}@i', $value, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { list($source, $cleaned) = $match; $replacement = null; $bits = preg_split('/:/', $cleaned, -1, PREG_SPLIT_NO_EMPTY); foreach ($bits as $param) { if ($param{0} != '$') { $replacement = $param; break; } $param = trim($param, '$'); $replacement = Datasource::findParameterInEnv($param, $env); if (is_array($replacement)) { $replacement = array_map(array('Datasource', 'escapeCommas'), $replacement); if (count($replacement) > 1) { $replacement = implode(',', $replacement); } else { $replacement = end($replacement); } } if (!empty($replacement)) { break; } } if ($escape == true) { $replacement = urlencode($replacement); } $value = str_replace($source, $replacement, $value); } } return $value; } /** * Using regexp, this escapes any commas in the given string * * @param string $string * The string to escape the commas in * @return string */ public static function escapeCommas($string) { return preg_replace('/(?<!\\\\),/', "\\,", $string); } /** * Used in conjunction with escapeCommas, this function will remove * the escaping pattern applied to the string (and commas) * * @param string $string * The string with the escaped commas in it to remove * @return string */ public static function removeEscapedCommas($string) { return preg_replace('/(?<!\\\\)\\\\,/', ',', $string); } /** * Parameters can exist in three different facets of Symphony; in the URL, * in the parameter pool or as an Symphony param. This function will attempt * to find a parameter in those three areas and return the value. If it is not found * null is returned * * @param string $needle * The parameter name * @param array $env * The environment variables from the Frontend class which includes * any params set by Symphony or Events or by other Datasources * @return mixed * If the value is not found, null, otherwise a string or an array is returned */ public static function findParameterInEnv($needle, $env) { if (isset($env['env']['url'][$needle])) { return $env['env']['url'][$needle]; } if (isset($env['env']['pool'][$needle])) { return $env['env']['pool'][$needle]; } if (isset($env['param'][$needle])) { return $env['param'][$needle]; } return null; } } require_once TOOLKIT . '/data-sources/class.datasource.author.php'; require_once TOOLKIT . '/data-sources/class.datasource.section.php'; require_once TOOLKIT . '/data-sources/class.datasource.static.php'; require_once TOOLKIT . '/data-sources/class.datasource.dynamic_xml.php'; require_once TOOLKIT . '/data-sources/class.datasource.navigation.php';
jdsimcoe/symphony-boilerplate
symphony/lib/toolkit/class.datasource.php
PHP
mit
19,238
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; const double EPS = 1e-9; inline char DBLCMP(double d) { if (fabs(d) < EPS) return 0; return d>0 ? 1 : -1; } struct spoint { double x, y, z; spoint() {} spoint(double xx, double yy, double zz): x(xx), y(yy), z(zz) {} void read() {scanf("%lf%lf%lf", &x, &y, &z);} }; spoint operator - (const spoint &v1, const spoint &v2) {return spoint(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z);} double dot(const spoint &v1, const spoint &v2) {return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z;} double norm(const spoint &v) {return sqrt(v.x*v.x+v.y*v.y+v.z*v.z);} double dis(const spoint &p1, const spoint &p2) {return norm(p2-p1);} spoint c, n, s, v, p; double r, t1, t2, i, j, k; //ax+b=0 //0 for no solution, 1 for one solution, 2 for infinitive solution char lneq(double a, double b, double &x) { if (DBLCMP(a) == 0) { if (DBLCMP(b) == 0) return 2; return 0; } x = -b/a; return 1; } //ax^2+bx+c=0, a!=0 //0 for no solution, 1 for one solution, 2 for 2 solutions //x1 <= x2 char qdeq(double a, double b, double c, double &x1, double &x2) { double delta = b*b-4*a*c; if (delta < 0) return 0; x1 = (-b+sqrt(delta))/(2*a); x2 = (-b-sqrt(delta))/(2*a); if (x1 > x2) swap(x1, x2); return DBLCMP(delta) ? 2 : 1; } int main() { c.read(); n.read(); scanf("%lf", &r); //printf("##%f\n", dis(spoint(0,0,0), spoint(1,1,1))); s.read(); v.read(); i = -5.0*n.z; j = dot(n, v); k = dot(n, s-c); if (DBLCMP(i)==0) { char sta = lneq(j, k, t1); if (sta==0 || sta==2 || DBLCMP(t1) <= 0) { puts("MISSED"); return 0; } p.x = s.x+v.x*t1; p.y = s.y+v.y*t1; p.z = s.z+v.z*t1-5.0*t1*t1; if (DBLCMP(dis(p, c)-r) < 0) { puts("HIT"); return 0; } puts("MISSED"); return 0; } if (!qdeq(i, j, k, t1, t2)) { puts("MISSED"); return 0; } if (DBLCMP(t1) > 0) { p.x = s.x+v.x*t1; p.y = s.y+v.y*t1; p.z = s.z+v.z*t1-5.0*t1*t1; if (DBLCMP(dis(p, c)-r) < 0) { puts("HIT"); return 0; } } if (DBLCMP(t2) > 0) { p.x = s.x+v.x*t2; p.y = s.y+v.y*t2; p.z = s.z+v.z*t2-5.0*t2*t2; if (DBLCMP(dis(p, c)-r) < 0) { puts("HIT"); return 0; } } puts("MISSED"); return 0; }
jffifa/algo-solution
ural/1093.cpp
C++
mit
2,211
<?php /** * Examples of ShareCouners usage * @author Dominik Bułaj <dominik@bulaj.com> */ include '../src/SharesCounter.php'; include '../src/Networks.php'; include '../src/Exception.php'; $url = 'http://www.huffingtonpost.com'; // 1. return shares from Facebook and Twitter $shares = new \SharesCounter\SharesCounter($url); $counts = $shares->getShares([\SharesCounter\Networks::NETWORK_FACEBOOK, \SharesCounter\Networks::NETWORK_TWITTER]); var_dump($counts); // 2. return shares from all available networks $shares = new \SharesCounter\SharesCounter($url); $counts = $shares->getShares([]); var_dump($counts); // 3. return shares from disabled by default network $url = 'http://www.moy-rebenok.ru'; $shares = new \SharesCounter\SharesCounter($url); $counts = $shares->getShares([\SharesCounter\Networks::NETWORK_VK, \SharesCounter\Networks::NETWORK_ODNOKLASSNIKI]); var_dump($counts); // 4. wykop.pl $url = 'http://pokazywarka.pl/margaryna/'; $shares = new \SharesCounter\SharesCounter($url); $counts = $shares->getShares([\SharesCounter\Networks::NETWORK_WYKOP]); var_dump($counts); // 4. helper method - return list of available networks $networks = new \SharesCounter\Networks(); $availableNetworks = $networks->getAvailableNetworks(); var_export($availableNetworks);
dominikbulaj/shares-counter-php
examples/index.php
PHP
mit
1,282
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCharactersLangTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Create the characters_lang table Schema::create('characters_lang', function($table) { $default_locale = \Config::get('app.locale'); $locales = \Config::get('app.locales', array($default_locale)); $table->increments('id'); $table->mediumInteger('character_id'); $table->string('firstname')->nullable(); $table->string('lastname')->nullable(); $table->string('nickname')->nullable(); $table->string('overview')->nullable(); $table->enum('locale', $locales); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Drop the characters_lang table Schema::dropIfExists('characters_lang'); } }
Truemedia/regeneration-character
src/database/migrations/2015_05_16_174527_create_characters_lang_table.php
PHP
mit
981
import React, {Component} from 'react'; import {Typeahead} from 'react-bootstrap-typeahead'; import {inject, observer} from 'mobx-react'; import {action, toJS, autorunAsync} from 'mobx'; import myClient from '../agents/client' require('react-bootstrap-typeahead/css/ClearButton.css'); require('react-bootstrap-typeahead/css/Loader.css'); require('react-bootstrap-typeahead/css/Token.css'); require('react-bootstrap-typeahead/css/Typeahead.css'); @inject('controlsStore', 'designStore') @observer export default class EroTypeahead extends Component { constructor(props) { super(props); } state = { options: [] }; // this will keep updating the next -ERO options as the ERO changes; disposeOfEroOptionsUpdate = autorunAsync('ero options update', () => { let ep = this.props.controlsStore.editPipe; let submitEro = toJS(ep.ero.hops); // keep track of the last hop; if we've reached Z we shouldn't keep going let lastHop = ep.a; if (ep.ero.hops.length > 0) { lastHop = ep.ero.hops[ep.ero.hops.length - 1]; } else { // if there's _nothing_ in our ERO then ask for options from pipe.a submitEro.push(ep.a); } // if this is the last hop, don't provide any options if (lastHop === ep.z) { this.setState({options: []}); return; } myClient.submit('POST', '/api/pce/nextHopsForEro', submitEro) .then( action((response) => { let nextHops = JSON.parse(response); if (nextHops.length > 0) { let opts = []; nextHops.map(h => { let entry = { id: h.urn, label: h.urn + ' through ' + h.through + ' to ' + h.to, through: h.through, to: h.to }; opts.push(entry); }); this.setState({options: opts}); } })); }, 500); componentWillUnmount() { this.disposeOfEroOptionsUpdate(); } onTypeaheadSelection = selection => { if (selection.length === 0) { return; } let wasAnOption = false; let through = ''; let urn = ''; let to = ''; this.state.options.map(opt => { if (opt.label === selection) { wasAnOption = true; through = opt.through; urn = opt.id; to = opt.to; } }); if (wasAnOption) { let ep = this.props.controlsStore.editPipe; let ero = []; ep.manual.ero.map(e => { ero.push(e); }); ero.push(through); ero.push(urn); ero.push(to); this.props.controlsStore.setParamsForEditPipe({ ero: { hops: ero }, manual: {ero: ero} }); this.typeAhead.getInstance().clear(); } }; render() { return ( <Typeahead minLength={0} ref={(ref) => { this.typeAhead = ref; }} placeholder='choose from selection' options={this.state.options} onInputChange={this.onTypeaheadSelection} clearButton /> ); } }
haniotak/oscars-frontend
src/main/js/components/eroTypeahead.js
JavaScript
mit
3,673
'use strict'; var convert = require('./convert'), func = convert('lt', require('../lt')); func.placeholder = require('./placeholder'); module.exports = func; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2x0LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsSUFBSSxVQUFVLFFBQVEsV0FBUixDQUFWO0lBQ0EsT0FBTyxRQUFRLElBQVIsRUFBYyxRQUFRLE9BQVIsQ0FBZCxDQUFQOztBQUVKLEtBQUssV0FBTCxHQUFtQixRQUFRLGVBQVIsQ0FBbkI7QUFDQSxPQUFPLE9BQVAsR0FBaUIsSUFBakIiLCJmaWxlIjoibHQuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgY29udmVydCA9IHJlcXVpcmUoJy4vY29udmVydCcpLFxuICAgIGZ1bmMgPSBjb252ZXJ0KCdsdCcsIHJlcXVpcmUoJy4uL2x0JykpO1xuXG5mdW5jLnBsYWNlaG9sZGVyID0gcmVxdWlyZSgnLi9wbGFjZWhvbGRlcicpO1xubW9kdWxlLmV4cG9ydHMgPSBmdW5jO1xuIl19
justin-lai/hackd.in
compiled/client/lib/lodash/fp/lt.js
JavaScript
mit
778
<?php /** * UserAccount * * This class has been auto-generated by the Doctrine ORM Framework * * @package blueprint * @subpackage model * @author Your name here * @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $ */ class UserAccount extends BaseUserAccount { }
zenkovnick/pfr
lib/model/doctrine/UserAccount.class.php
PHP
mit
299
<?php use PDFfiller\OAuth2\Client\Provider\Token; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = Token::one($provider, 3329); dd($e);
pdffiller/pdffiller-php-api-client
examples/token/3_get_token.php
PHP
mit
164
package sql.fredy.sqltools; /** XLSExport exports the result of a query into a XLS-file. To do this it is using HSSF from the Apache POI Project: http://jakarta.apache.org/poi Version 1.0 Date 7. aug. 2003 Author Fredy Fischer XLSExport is part of the Admin-Suite Once instantiated there are the following steps to go to get a XLS-file out of a query XLSExport xe = new XLSExport(java.sql.Connection con) xe.setQuery(java.lang.String query) please set herewith the the query to get its results as XLS-file int xe.createXLS(java.lang.String fileName) this will then create the XLS-File. If this file already exists, it will be overwritten! it returns the number of rows written to the File 2015-11-16 Creating an additional Worksheet containing the SQL-Query Admin is a Tool around SQL to do basic jobs for DB-Administrations, like: - create/ drop tables - create indices - perform sql-statements - simple form - a guided query and a other usefull things in DB-arena Copyright (c) 2017 Fredy Fischer, sql@hulmen.ch Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import sql.fredy.share.t_connect; import java.io.InputStream; import java.io.IOException; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.sql.*; import java.util.logging.*; import java.util.Date; import org.apache.poi.xssf.usermodel.*; import org.apache.poi.hssf.record.*; import org.apache.poi.hssf.model.*; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.*; import java.util.ArrayList; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; public class XLSExport { private Logger logger; Connection con = null; /** * Get the value of con. * * @return value of con. */ public Connection getCon() { return con; } /** * Set the value of con. * * @param v Value to assign to con. */ public void setCon(Connection v) { this.con = v; } String query=null; /** * Get the value of query. * * @return value of query. */ public String getQuery() { return query; } /** * Set the value of query. * * @param v Value to assign to query. */ public void setQuery(String v) { this.query = v; } java.sql.SQLException exception; /** * Get the value of exception. * * @return value of exception. */ public java.sql.SQLException getException() { return exception; } /** * Set the value of exception. * * @param v Value to assign to exception. */ public void setException(java.sql.SQLException v) { this.exception = v; } private PreparedStatement pstmt = null; /* is this file xlsx or xls? we detect this out of the filename extension */ private boolean xlsx = false; private void checkXlsx(String fileName) { String[] extension = fileName.split("\\."); int l = extension.length - 1; String fileType = extension[l].toLowerCase(); if ("xlsx".equals(fileType)) { setXlsx(true); } } /* we need to check, if the extension of the Filename is either xls or xlsx if not, we set to xlsx as default */ private String fixFileName(String f) { String prefix = "", postfix = ""; String fixed = f; int i = f.lastIndexOf("."); // no postfix at all set if (i < 0) { fixed = f + ".xlsx"; } else { prefix = f.substring(0, i); postfix = f.substring(i + 1); logger.log(Level.FINE, "Prefix: " + prefix + " Postfix: " + postfix); if ((postfix.equalsIgnoreCase("xlsx")) || (postfix.equalsIgnoreCase("xls"))) { // nothing to do } else { postfix = "xlsx"; } fixed = prefix + "." + postfix; } logger.log(Level.INFO, "Filename: " + fixed); return fixed; } /** * Create the XLS-File named fileName * * @param fileName is the Name (incl. Path) of the XLS-file to create * * */ public int createXLS(String fileName) { // I need to have a query to process if ((getQuery() == null) && (getPstmt() == null)) { logger.log(Level.WARNING, "Need to have a query to process"); return 0; } // I also need to have a file to write into if (fileName == null) { logger.log(Level.WARNING, "Need to know where to write into"); return 0; } fileName = fixFileName(fileName); checkXlsx(fileName); // I need to have a connection to the RDBMS if (getCon() == null) { logger.log(Level.WARNING, "Need to have a connection to process"); return 0; } //Statement stmt = null; ResultSet resultSet = null; ResultSetMetaData rsmd = null; try { // first we have to create the Statement if (getPstmt() == null) { pstmt = getCon().prepareStatement(getQuery()); } //stmt = getCon().createStatement(); } catch (SQLException sqle1) { setException(sqle1); logger.log(Level.WARNING, "Can not create Statement. Message: " + sqle1.getMessage().toString()); return 0; } logger.log(Level.FINE, "FileName: " + fileName); logger.log(Level.FINE, "Query : " + getQuery()); logger.log(Level.FINE, "Starting export..."); // create an empty sheet Workbook wb; Sheet sheet; Sheet sqlsheet; CreationHelper createHelper = null; //XSSFSheet xsheet; //HSSFSheet sheet; if (isXlsx()) { wb = new SXSSFWorkbook(); createHelper = wb.getCreationHelper(); } else { wb = new HSSFWorkbook(); createHelper = wb.getCreationHelper(); } sheet = wb.createSheet("Data Export"); // create a second sheet just containing the SQL Statement sqlsheet = wb.createSheet("SQL Statement"); Row sqlrow = sqlsheet.createRow(0); Cell sqltext = sqlrow.createCell(0); try { if ( getQuery() != null ) { sqltext.setCellValue(getQuery()); } else { sqltext.setCellValue(pstmt.toString()); } } catch (Exception lex) { } CellStyle style = wb.createCellStyle(); style.setWrapText(true); sqltext.setCellStyle(style); Row r = null; int row = 0; // row number int col = 0; // column number int columnCount = 0; try { //resultSet = stmt.executeQuery(getQuery()); resultSet = pstmt.executeQuery(); logger.log(Level.FINE, "query executed"); } catch (SQLException sqle2) { setException(sqle2); logger.log(Level.WARNING, "Can not execute query. Message: " + sqle2.getMessage().toString()); return 0; } // create Header in XLS-file ArrayList<String> head = new ArrayList(); try { rsmd = resultSet.getMetaData(); logger.log(Level.FINE, "Got MetaData of the resultset"); columnCount = rsmd.getColumnCount(); logger.log(Level.FINE, Integer.toString(columnCount) + " Columns in this resultset"); r = sheet.createRow(row); // titlerow if ((!isXlsx()) && (columnCount > 255)) { columnCount = 255; } for (int i = 0; i < columnCount; i++) { // we create the cell Cell cell = r.createCell(col); // set the value of the cell cell.setCellValue(rsmd.getColumnName(i + 1)); head.add(rsmd.getColumnName(i + 1)); // then we align center CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // now we make it bold //HSSFFont f = wb.createFont(); Font headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); cellStyle.setFont(headerFont); //cellStyle.setFont(f); // adapt this font to the cell cell.setCellStyle(cellStyle); col++; } } catch (SQLException sqle3) { setException(sqle3); logger.log(Level.WARNING, "Can not create XLS-Header. Message: " + sqle3.getMessage().toString()); return 0; } // looping the resultSet int wbCounter = 0; try { while (resultSet.next()) { // this is the next row col = 0; // put column counter back to 0 to start at the next row row++; // next row // create a new sheet if more then 60'000 Rows and xls file if ((!isXlsx()) && (row % 65530 == 0)) { wbCounter++; row = 0; sheet = wb.createSheet("Data Export " + Integer.toString(wbCounter)); logger.log(Level.INFO, "created a further page because of a huge amount of data"); // create the head r = sheet.createRow(row); // titlerow for (int i = 0; i < head.size(); i++) { // we create the cell Cell cell = r.createCell(col); // set the value of the cell cell.setCellValue((String) head.get(i)); // then we align center CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // now we make it bold //HSSFFont f = wb.createFont(); Font headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); cellStyle.setFont(headerFont); //cellStyle.setFont(f); // adapt this font to the cell cell.setCellStyle(cellStyle); col++; } row++; } try { r = sheet.createRow(row); } catch (Exception e) { logger.log(Level.WARNING, "Error while creating row number " + row + " " + e.getMessage()); wbCounter++; row = 0; sheet = wb.createSheet("Data Export " + Integer.toString(wbCounter)); logger.log(Level.WARNING, "created a further page in the hope it helps..."); // create the head r = sheet.createRow(row); // titlerow for (int i = 0; i < head.size(); i++) { // we create the cell Cell cell = r.createCell(col); // set the value of the cell cell.setCellValue((String) head.get(i)); // then we align center CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // now we make it bold //HSSFFont f = wb.createFont(); Font headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); cellStyle.setFont(headerFont); //cellStyle.setFont(f); // adapt this font to the cell cell.setCellStyle(cellStyle); col++; } row++; } col = 0; // put column counter back to 0 to start at the next row String previousMessage = ""; for (int i = 0; i < columnCount; i++) { try { // depending on the type, create the cell switch (rsmd.getColumnType(i + 1)) { case java.sql.Types.INTEGER: r.createCell(col).setCellValue(resultSet.getInt(i + 1)); break; case java.sql.Types.FLOAT: r.createCell(col).setCellValue(resultSet.getFloat(i + 1)); break; case java.sql.Types.DOUBLE: r.createCell(col).setCellValue(resultSet.getDouble(i + 1)); break; case java.sql.Types.DECIMAL: r.createCell(col).setCellValue(resultSet.getFloat(i + 1)); break; case java.sql.Types.NUMERIC: r.createCell(col).setCellValue(resultSet.getFloat(i + 1)); break; case java.sql.Types.BIGINT: r.createCell(col).setCellValue(resultSet.getInt(i + 1)); break; case java.sql.Types.TINYINT: r.createCell(col).setCellValue(resultSet.getInt(i + 1)); break; case java.sql.Types.SMALLINT: r.createCell(col).setCellValue(resultSet.getInt(i + 1)); break; case java.sql.Types.DATE: // first we get the date java.sql.Date dat = resultSet.getDate(i + 1); java.util.Date date = new java.util.Date(dat.getTime()); r.createCell(col).setCellValue(date); break; case java.sql.Types.TIMESTAMP: // first we get the date java.sql.Timestamp ts = resultSet.getTimestamp(i + 1); Cell c = r.createCell(col); try { c.setCellValue(ts); // r.createCell(col).setCellValue(ts); // Date Format CellStyle cellStyle = wb.createCellStyle(); cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy/mm/dd hh:mm:ss")); c.setCellStyle(cellStyle); } catch (Exception e) { c.setCellValue(" "); } break; case java.sql.Types.TIME: // first we get the date java.sql.Time time = resultSet.getTime(i + 1); r.createCell(col).setCellValue(time); break; case java.sql.Types.BIT: boolean b1 = resultSet.getBoolean(i + 1); r.createCell(col).setCellValue(b1); break; case java.sql.Types.BOOLEAN: boolean b2 = resultSet.getBoolean(i + 1); r.createCell(col).setCellValue(b2); break; case java.sql.Types.CHAR: r.createCell(col).setCellValue(resultSet.getString(i + 1)); break; case java.sql.Types.NVARCHAR: r.createCell(col).setCellValue(resultSet.getString(i + 1)); break; case java.sql.Types.VARCHAR: try { r.createCell(col).setCellValue(resultSet.getString(i + 1)); } catch (Exception e) { r.createCell(col).setCellValue(" "); logger.log(Level.WARNING, "Exception while writing column {0} row {3} type: {1} Message: {2}", new Object[]{col, rsmd.getColumnType(i + 1), e.getMessage(), row}); } break; default: r.createCell(col).setCellValue(resultSet.getString(i + 1)); break; } } catch (Exception e) { //e.printStackTrace(); if (resultSet.wasNull()) { r.createCell(col).setCellValue(" "); } else { logger.log(Level.WARNING, "Unhandled type at column {0}, row {3} type: {1}. Filling up with blank {2}", new Object[]{col, rsmd.getColumnType(i + 1), e.getMessage(), row}); r.createCell(col).setCellValue(" "); } } col++; } } //pstmt.close(); } catch (SQLException sqle3) { setException(sqle3); logger.log(Level.WARNING, "Exception while writing data into sheet. Message: " + sqle3.getMessage().toString()); } try { // Write the output to a file FileOutputStream fileOut = new FileOutputStream(fileName); wb.write(fileOut); fileOut.close(); logger.log(Level.INFO, "File created"); logger.log(Level.INFO, "Wrote: {0} lines into XLS-File", Integer.toString(row)); } catch (Exception e) { logger.log(Level.WARNING, "Exception while writing xls-File: " + e.getMessage().toString()); } return row; } public XLSExport(Connection con) { logger = Logger.getLogger("sql.fredy.sqltools"); setCon(con); } public XLSExport() { logger = Logger.getLogger("sql.fredy.sqltools"); } public static void main(String args[]) { String host = "localhost"; String user = System.getProperty("user.name"); String schema = "%"; String database = null; String password = null; String query = null; String file = null; System.out.println("XLSExport\n" + "----------\n" + "Syntax: java sql.fredy.sqltools.XLSExport\n" + " Parameters: -h Host (default: localhost)\n" + " -u User (default: " + System.getProperty("user.name") + ")\n" + " -p Password\n" + " -q Query\n" + " -Q Filename of the file containing the Query\n" + " -d database\n" + " -f File to write into (.xls or xlsx)\n"); int i = 0; while (i < args.length) { if (args[i].equals("-h")) { i++; host = args[i]; } if (args[i].equals("-u")) { i++; user = args[i]; } if (args[i].equals("-p")) { i++; password = args[i]; } if (args[i].equals("-d")) { i++; database = args[i]; } if (args[i].equals("-q")) { i++; query = args[i]; } if (args[i].equals("-Q")) { i++; sql.fredy.io.ReadFile rf = new sql.fredy.io.ReadFile(args[i]); query = rf.getText(); } if (args[i].equals("-f")) { i++; file = args[i]; } i++; }; t_connect tc = new t_connect(host, user, password, database); XLSExport xe = new XLSExport(tc.con); xe.setQuery(query); xe.createXLS(file); tc.close(); } /** * @return the xlsx */ public boolean isXlsx() { return xlsx; } /** * @param xlsx the xlsx to set */ public void setXlsx(boolean xlsx) { this.xlsx = xlsx; } /** * @return the pstmt */ public PreparedStatement getPstmt() { return pstmt; } /** * @param pstmt the pstmt to set */ public void setPstmt(PreparedStatement pstmt) { this.pstmt = pstmt; } }
hulmen/SQLAdmin
src/fredy/sqltools/XLSExport.java
Java
mit
23,048
# -*- coding: utf-8 -*- # Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ TODO... """ __all__ = ['GreedyPlayer'] import random from jdhp.tictactoe.player.abstract import Player class GreedyPlayer(Player): """ TODO... """ def play(self, game, state): """ TODO... """ action_list = game.getSetOfValidActions(state) choosen_action = None # Choose actions that lead to immediate victory... for action in action_list: next_state = game.nextState(state, action, self) if game.hasWon(self, next_state): choosen_action = action break # ... otherwise choose randomly if choosen_action is None: #print("randomly choose action") # debug choosen_action = random.choice(action_list) return choosen_action
jeremiedecock/tictactoe-py
jdhp/tictactoe/player/greedy.py
Python
mit
1,951
/* * Copyright (c) 2015. Vin @ vinexs.com (MIT License) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.vinexs.view; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.widget.LinearLayout; @SuppressWarnings("unused") public class ScalableLinearLayout extends LinearLayout { private ScaleGestureDetector scaleDetector; private float scaleFactor = 1.f; private float maxScaleFactor = 1.5f; private float minScaleFactor = 0.5f; public ScalableLinearLayout(Context context) { super(context); scaleDetector = new ScaleGestureDetector(context, new ScaleListener()); } public ScalableLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); scaleDetector = new ScaleGestureDetector(context, new ScaleListener()); } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { // Let the ScaleGestureDetector inspect all events. scaleDetector.onTouchEvent(event); return true; } @Override public void dispatchDraw(Canvas canvas) { canvas.save(); canvas.scale(scaleFactor, scaleFactor); super.dispatchDraw(canvas); canvas.restore(); } public ScalableLinearLayout setMaxScale(float scale) { maxScaleFactor = scale; return this; } public ScalableLinearLayout setMinScale(float scale) { minScaleFactor = scale; return this; } public ScaleGestureDetector getScaleGestureDetector() { return scaleDetector; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { scaleFactor *= detector.getScaleFactor(); scaleFactor = Math.max(minScaleFactor, Math.min(scaleFactor, maxScaleFactor)); invalidate(); return true; } } }
vinexs/extend-enhance-base
eeb-core/src/main/java/com/vinexs/view/ScalableLinearLayout.java
Java
mit
3,281
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DollarTracker.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DollarTracker.Core")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4fa07611-8eb7-4660-826c-5ac7c85c07c8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
alphaCoder/DollarTracker
DollarTracker.Net/DollarTracker.Core/Properties/AssemblyInfo.cs
C#
mit
1,412
__author__ = 'besta' class BestaPlayer: def __init__(self, fichier, player): self.fichier = fichier self.grille = self.getFirstGrid() self.best_hit = 0 self.players = player def getFirstGrid(self): """ Implements function to get the first grid. :return: the grid. """ li = [] with open(self.fichier, 'r') as fi: for line in fi.readlines(): li.append(line) return li def updateGrid(self): """ Implements function to update the grid to alter n-1 round values """ with open(self.fichier, 'r') as fi: for line in fi.readlines(): i = 0 for car in line: j = 0 if car != '\n': self.grille[i][j] = car j += 1 i += 1 def grilleEmpty(self): """ Implement function to check if the grid is empty. """ for line in self.grille: for car in line[:len(line) - 1]: if car != '0': return False return True def checkLines(self, player, inARow): """ Implements function to check the current lines setup to evaluate best combinaison. :param player: check for your numbers (your player number) or those of your opponent. :param inARow: how many tokens in a row (3 or 2). :return: true or false """ count = 0 flag = False for line_number, line in enumerate(self.grille): count = 0 for car_pos, car in enumerate(line[:len(line) - 1]): if int(car) == player and not flag: count = 1 flag = True elif int(car) == player and flag: count += 1 if count == inARow: if car_pos - inARow >= 0 and self.canPlayLine(line_number, car_pos - inARow): return True, car_pos - inARow if car_pos + 1 <= 6 and self.canPlayLine(line_number, car_pos + 1): return True, car_pos + 1 else: count = 0 return False, 0 def canPlayLine(self, line, col): """ Function to check if we can fill the line with a token. :param line: which line :param col: which column :return: true or false """ if line == 5: return self.grille[line][col] == '0' else: return self.grille[line][col] == '0' and self.grille[line + 1][col] != '0' def changeColumnInLines(self): """ Implements function to transform columns in lines to make tests eaiser. :return: a reverse matrice """ column = [] for x in xrange(7): col = '' for y in xrange(6): col += self.grille[y][x] column.append(col) return column def checkColumns(self, player, inARow): """ Implements function to check the current columns setup to evaluate best combinaison. :param player: check for your numbers (your player number) or those of your opponent. :param inARow: how many tokens in a row (3 or 2). :return: true or false """ column = self.changeColumnInLines() count = 0 flag = False for col_number, line in enumerate(column): count = 0 for car_pos, car in enumerate(line): if int(car) == player and not flag: count = 1 flag = True elif int(car) == player and flag: count += 1 if count == inARow and car_pos - inARow >= 0 and self.grille[car_pos - inARow][col_number] == '0': return True, col_number else: count = 0 return False, 0 def checkDiagonalLeftToRight(self, player, inARow): """ Implements function to check the current diagonal to evaluate best combinaison. :param player: check for your numbers or opponent ones. :param inARow: how many tokens in a row (3 or 2). :return: """ x = 3 flag = False while x < 6: count = 0 x_int = x y_int = 0 while x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int + 1 <= 6 and x_int - 1 >= 0 and self.grille[x_int][y_int + 1] != '0': return True, y_int + 1 else: count = 0 flag = False x_int -= 1 y_int += 1 x += 1 y = 1 flag = False while y <= 3: count = 0 x_int = 5 y_int = y while y_int <= 6 and x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int + 1 <= 6 and x_int - 1 >= 0 and self.grille[x_int][y + 1] != '0': return True, y_int + 1 else: count = 0 flage = False x_int -= 1 y_int += 1 y += 1 return False, 0 def checkDiagonalRightToLeft(self, player, inARow): """ Implements function to check the current diagonal to evaluate best combinaison. :param player: check for your numbers or opponent ones. :param inARow: how many tokens in a row (3 or 2). :return: """ x = 3 flag = False while x < 6: count = 0 x_int = x y_int = 6 while x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int - 1 >= 0 and x_int - 1 >= 0 and self.grille[x_int][y_int - 1] != '0': return True, y_int - 1 else: count = 0 flag = False x_int -= 1 y_int -= 1 x += 1 y = 5 flag = False while y <= 3: count = 0 x_int = 5 y_int = y while y_int >= 3 and x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int - 1 >= 0 and x_int - 1 >= 0 and self.grille[x_int][y - 1] != '0': return True, y_int - 1 else: count = 0 flage = False x_int -= 1 y_int -= 1 y -= 1 return False, 0 def checkDiagonals(self, player, inARow): """ Calls two diagonal functional. :return: an int, representing the column where to play or 0 and False if there is no pattern search. """ check = self.checkDiagonalLeftToRight(player, inARow) if check[0]: return check else: return self.checkDiagonalRightToLeft(player, inARow) def playSomeColumn(self, player, inARow): """ Call all function for a player and a number of tokens given. :param player: which player :param inARow: how many token :return: true or false (col number if true) """ methods = {'checklines': self.checkLines, 'checkcolumn': self.checkColumns, 'checkdiagonal': self.checkDiagonals} for key, function in methods.items(): which_col = function(player, inARow) if which_col[0]: return which_col return False, 0 def findFirstColumnEmpty(self): """ Implements function to get the first column where a slot remain. :return: the column """ for col in xrange(7): if self.grille[0][col] == '0': return col return -1 def decideColumn(self): """ Implements main function : to decide what is the better hit to do. :return: an int, representing the column where we play """ if self.grilleEmpty(): return 3 li_sequence = [3, 2, 1] li_players = [self.players[0], self.players[1]] for sequence in li_sequence: for player in li_players: choosen_col = self.playSomeColumn(player, sequence) if choosen_col[0]: return choosen_col[1] return self.findFirstColumnEmpty()
KeserOner/puissance4
bestaplayer.py
Python
mit
9,518
# Game Over screen. class GameOver def initialize(game) end def udpate end def draw end end
PhilCK/mermaid-game
game_over.rb
Ruby
mit
102
PP.lib.shader.shaders.color = { info: { name: 'color adjustement', author: 'Evan Wallace', link: 'https://github.com/evanw/glfx.js' }, uniforms: { textureIn: { type: "t", value: 0, texture: null }, brightness: { type: "f", value: 0.0 }, contrast: { type: "f", value: 0.0 }, hue: { type: "f", value: 0.0 }, saturation: { type: "f", value: 0.0 }, exposure: { type: "f", value: 0.0 }, negative: { type: "i", value: 0 } }, controls: { brightness: {min:-1, max: 1, step:.05}, contrast: {min:-1, max: 1, step:.05}, hue: {min:-1, max: 1, step:.05}, saturation: {min:-1, max: 1, step:.05}, exposure: {min:0, max: 1, step:.05}, negative: {} }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "varying vec2 vUv;", "uniform sampler2D textureIn;", "uniform float brightness;", "uniform float contrast;", "uniform float hue;", "uniform float saturation;", "uniform float exposure;", "uniform int negative;", "const float sqrtoftwo = 1.41421356237;", "void main() {", "vec4 color = texture2D(textureIn, vUv);", "color.rgb += brightness;", "if (contrast > 0.0) {", "color.rgb = (color.rgb - 0.5) / (1.0 - contrast) + 0.5;", "} else {", "color.rgb = (color.rgb - 0.5) * (1.0 + contrast) + 0.5;", "}", "/* hue adjustment, wolfram alpha: RotationTransform[angle, {1, 1, 1}][{x, y, z}] */", "float angle = hue * 3.14159265;", "float s = sin(angle), c = cos(angle);", "vec3 weights = (vec3(2.0 * c, -sqrt(3.0) * s - c, sqrt(3.0) * s - c) + 1.0) / 3.0;", "float len = length(color.rgb);", "color.rgb = vec3(", "dot(color.rgb, weights.xyz),", "dot(color.rgb, weights.zxy),", "dot(color.rgb, weights.yzx)", ");", "/* saturation adjustment */", "float average = (color.r + color.g + color.b) / 3.0;", "if (saturation > 0.0) {", "color.rgb += (average - color.rgb) * (1.0 - 1.0 / (1.0 - saturation));", "} else {", "color.rgb += (average - color.rgb) * (-saturation);", "}", "if(negative == 1){", " color.rgb = 1.0 - color.rgb;", "}", "if(exposure > 0.0){", " color = log2(vec4(pow(exposure + sqrtoftwo, 2.0))) * color;", "}", "gl_FragColor = color;", "}", ].join("\n") }; PP.lib.shader.shaders.bleach = { info: { name: 'Bleach', author: 'Brian Chirls @bchirls', link: 'https://github.com/brianchirls/Seriously.js' }, uniforms: { textureIn: { type: "t", value: 0, texture: null }, amount: { type: "f", value: 1.0 } }, controls: { amount: {min:0, max: 1, step:.1} }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ 'varying vec2 vUv;', 'uniform sampler2D textureIn;', 'uniform float amount;', 'const vec4 one = vec4(1.0);', 'const vec4 two = vec4(2.0);', 'const vec4 lumcoeff = vec4(0.2125,0.7154,0.0721,0.0);', 'vec4 overlay(vec4 myInput, vec4 previousmix, vec4 amount) {', ' float luminance = dot(previousmix,lumcoeff);', ' float mixamount = clamp((luminance - 0.45) * 10.0, 0.0, 1.0);', ' vec4 branch1 = two * previousmix * myInput;', ' vec4 branch2 = one - (two * (one - previousmix) * (one - myInput));', ' vec4 result = mix(branch1, branch2, vec4(mixamount) );', ' return mix(previousmix, result, amount);', '}', 'void main (void) {', ' vec4 pixel = texture2D(textureIn, vUv);', ' vec4 luma = vec4(vec3(dot(pixel,lumcoeff)), pixel.a);', ' gl_FragColor = overlay(luma, pixel, vec4(amount));', '}' ].join("\n") }; PP.lib.shader.shaders.plasma = { info: { name: 'plasma', author: 'iq', link: 'http://www.iquilezles.org' }, uniforms: { resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 }, saturation: { type: "f", value: 1.0 }, waves: { type: "f", value: .2 }, wiggle: { type: "f", value: 1000.0 }, scale: { type: "f", value: 1.0 } }, controls: { speed: {min:0, max: .1, step:.001}, saturation: {min:0, max: 10, step:.01}, waves: {min:0, max: .4, step:.0001}, wiggle: {min:0, max: 10000, step:1}, scale: {min:0, max: 10, step:.01} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "varying vec2 vUv;", "uniform float time;", "uniform float saturation;", "uniform vec2 resolution;", "uniform float waves;", "uniform float wiggle;", "uniform float scale;", "void main() {", "float x = gl_FragCoord.x*scale;", "float y = gl_FragCoord.y*scale;", "float mov0 = x+y+cos(sin(time)*2.)*100.+sin(x/100.)*wiggle;", "float mov1 = y / resolution.y / waves + time;", "float mov2 = x / resolution.x / waves;", "float r = abs(sin(mov1+time)/2.+mov2/2.-mov1-mov2+time);", "float g = abs(sin(r+sin(mov0/1000.+time)+sin(y/40.+time)+sin((x+y)/100.)*3.));", "float b = abs(sin(g+cos(mov1+mov2+g)+cos(mov2)+sin(x/1000.)));", "vec3 plasma = vec3(r,g,b) * saturation;", "gl_FragColor = vec4( plasma ,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasma2 = { info: { name: 'plasma2', author: 'mrDoob', link: 'http://mrdoob.com' }, uniforms: { resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 }, qteX: { type: "f", value: 80.0 }, qteY: { type: "f", value: 10.0 }, intensity: { type: "f", value: 10.0 }, hue: { type: "f", value: .25 } }, controls: { speed: {min:0, max: 1, step:.001}, qteX: {min:0, max: 200, step:1}, qteY: {min:0, max: 200, step:1}, intensity: {min:0, max: 50, step:.1}, hue: {min:0, max: 2, step:.001} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform float time;", "uniform vec2 resolution;", "uniform float qteX;", "uniform float qteY;", "uniform float intensity;", "uniform float hue;", "void main() {", "vec2 position = gl_FragCoord.xy / resolution.xy;", "float color = 0.0;", "color += sin( position.x * cos( time / 15.0 ) * qteX ) + cos( position.y * cos( time / 15.0 ) * qteY );", "color += sin( position.y * sin( time / 10.0 ) * 40.0 ) + cos( position.x * sin( time / 25.0 ) * 40.0 );", "color += sin( position.x * sin( time / 5.0 ) * 10.0 ) + sin( position.y * sin( time / 35.0 ) * 80.0 );", "color *= sin( time / intensity ) * 0.5;", "gl_FragColor = vec4( vec3( color, color * (hue*2.0), sin( color + time / (hue*12.0) ) * (hue*3.0) ), 1.0 );", "}" ].join("\n") }; PP.lib.shader.shaders.plasma3 = { info: { name: 'plasma 3', author: 'Hakim El Hattab', link: 'http://hakim.se' }, uniforms: { color: { type: "c", value: new THREE.Color( 0x8CC6DA ) }, resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.05 }, scale: { type: "f", value: 10.0 }, quantity: { type: "f", value: 5.0 }, lens: { type: "f", value: 2.0 }, intensity: { type: "f", value: .5 } }, controls: { speed: {min:0, max: 1, step:.001}, scale: {min:0, max: 100, step:.1}, quantity: {min:0, max: 100, step:1}, lens: {min:0, max: 100, step:1}, intensity: {min:0, max: 5, step:.01} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform float time;", "uniform vec2 resolution;", "uniform vec3 color;", "uniform float scale;", "uniform float quantity;", "uniform float lens;", "uniform float intensity;", "void main() {", "vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;", "p = p * scale;", "vec2 uv;", "float a = atan(p.y,p.x);", "float r = sqrt(dot(p,p));", "uv.x = 2.0*a/3.1416;", "uv.y = -time+ sin(7.0*r+time) + .7*cos(time+7.0*a);", "float w = intensity+1.0*(sin(time+lens*r)+ 1.0*cos(time+(quantity * 2.0)*a));", "gl_FragColor = vec4(color*w,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasma4 = { info: { name: 'plasma 4 (vortex)', author: 'Hakim El Hattab', link: 'http://hakim.se' }, uniforms: { color: { type: "c", value: new THREE.Color( 0xff5200 ) }, // 0x8CC6DA resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.05 }, scale: { type: "f", value: 20.0 }, wobble: { type: "f", value: 1.0 }, ripple: { type: "f", value: 5.0 }, light: { type: "f", value: 2.0 } }, controls: { speed: {min:0, max: 1, step:.001}, scale: {min:0, max: 100, step:.1}, wobble: {min:0, max: 50, step:1}, ripple: {min:0, max: 50, step:.1}, light: {min:1, max: 50, step:1} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform float time;", "uniform vec2 resolution;", "uniform vec3 color;", "uniform float scale;", "uniform float wobble;", "uniform float ripple;", "uniform float light;", "void main() {", "vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;", "vec2 uv;", "float a = atan(p.y,p.x);", "float r = sqrt(dot(p,p));", "float u = cos(a*(wobble * 2.0) + ripple * sin(-time + scale * r));", "float intensity = sqrt(pow(abs(p.x),light) + pow(abs(p.y),light));", "vec3 result = u*intensity*color;", "gl_FragColor = vec4(result,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasma5 = { info: { name: 'plasma 5', author: 'Silexars', link: 'http://www.silexars.com' }, uniforms: { resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 } }, controls: { speed: {min:0, max: .2, step:.001} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform vec2 resolution;", "uniform float time;", "void main() {", "vec3 col;", "float l,z=time;", "for(int i=0;i<3;i++){", "vec2 uv;", "vec2 p=gl_FragCoord.xy/resolution.xy;", "uv=p;", "p-=.5;", "p.x*=resolution.x/resolution.y;", "z+=.07;", "l=length(p);", "uv+=p/l*(sin(z)+1.)*abs(sin(l*9.-z*2.));", "col[i]=.01/length(abs(mod(uv,1.)-.5));", "}", "gl_FragColor=vec4(col/l,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasmaByTexture = { info: { name: 'plasma by texture', author: 'J3D', link: 'http://www.everyday3d.com/j3d/demo/011_Plasma.html' }, uniforms: { textureIn: { type: "t", value: 0, texture: null }, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 } }, controls: { speed: {min:0, max: .1, step:.001} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "varying vec2 vUv;", "uniform sampler2D textureIn;", "uniform float time;", "void main() {", "vec2 ca = vec2(0.1, 0.2);", "vec2 cb = vec2(0.7, 0.9);", "float da = distance(vUv, ca);", "float db = distance(vUv, cb);", "float t = time * 0.5;", "float c1 = sin(da * cos(t) * 16.0 + t * 4.0);", "float c2 = cos(vUv.y * 8.0 + t);", "float c3 = cos(db * 14.0) + sin(t);", "float p = (c1 + c2 + c3) / 3.0;", "gl_FragColor = texture2D(textureIn, vec2(p, p));", "}" ].join("\n") };
rdad/PP.js
src/lib/Shader.color.js
JavaScript
mit
20,938
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'save', 'de-ch', { toolbar: 'Speichern' } );
waxe/waxe.xml
waxe/xml/static/ckeditor/plugins/save/lang/de-ch.js
JavaScript
mit
225
// // The MIT License(MIT) // // Copyright(c) 2014 Demonsaw LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "command/socket_command.h" #include "component/socket_component.h" #include "component/tunnel_component.h" #include "entity/entity.h" #include "http/http_socket.h" #include "message/request/request_message.h" #include "message/response/response_message.h" namespace eja { // Client socket_request_message::ptr client_socket_command::execute(const entity::ptr router) { return socket_request_message::create(); } void client_socket_command::execute(const entity::ptr router, const std::shared_ptr<socket_response_message> response) { // N/A } // Router socket_response_message::ptr router_socket_command::execute(const entity::ptr client, const http_socket::ptr socket, const socket_request_message::ptr request) { // Socket const auto socket_set = m_entity->get<socket_set_component>(); { thread_lock(socket_set); socket_set->erase(socket); } // Tunnel const auto tunnel_list = client->get<tunnel_list_component>(); { thread_lock(tunnel_list); tunnel_list->push_back(socket); } return socket_response_message::create(); } }
demonsaw/Code
ds3/3_core/command/socket_command.cpp
C++
mit
2,225
cookbook_path ["berks-cookbooks", "cookbooks", "site-cookbooks"] node_path "nodes" role_path "roles" environment_path "environments" data_bag_path "data_bags" #encrypted_data_bag_secret "data_bag_key" knife[:berkshelf_path] = "berks-cookbooks" Chef::Config[:ssl_verify_mode] = :verify_peer if defined? ::Chef
rudijs/devops-starter
app/kitchen/.chef/knife.rb
Ruby
mit
330
// Specifically test buffer module regression. import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding, constants, kMaxLength, kStringMaxLength, Blob, } from 'buffer'; const utf8Buffer = new Buffer('test'); const base64Buffer = new Buffer('', 'base64'); const octets: Uint8Array = new Uint8Array(123); const octetBuffer = new Buffer(octets); const sharedBuffer = new Buffer(octets.buffer); const copiedBuffer = new Buffer(utf8Buffer); console.log(Buffer.isBuffer(octetBuffer)); console.log(Buffer.isEncoding('utf8')); console.log(Buffer.byteLength('xyz123')); console.log(Buffer.byteLength('xyz123', 'ascii')); const result1 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>); const result2 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>, 9999999); // Module constants { const value1: number = constants.MAX_LENGTH; const value2: number = constants.MAX_STRING_LENGTH; const value3: number = kMaxLength; const value4: number = kStringMaxLength; } // Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64() { const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); buf.swap16(); buf.swap32(); buf.swap64(); } // Class Method: Buffer.from(data) { // Array const buf1: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72] as ReadonlyArray<number>); // Buffer const buf2: Buffer = Buffer.from(buf1, 1, 2); // String const buf3: Buffer = Buffer.from('this is a tést'); // ArrayBuffer const arrUint16: Uint16Array = new Uint16Array(2); arrUint16[0] = 5000; arrUint16[1] = 4000; const buf4: Buffer = Buffer.from(arrUint16.buffer); const arrUint8: Uint8Array = new Uint8Array(2); const buf5: Buffer = Buffer.from(arrUint8); const buf6: Buffer = Buffer.from(buf1); const sb: SharedArrayBuffer = {} as any; const buf7: Buffer = Buffer.from(sb); // $ExpectError Buffer.from({}); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) { const arr: Uint16Array = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; let buf: Buffer; buf = Buffer.from(arr.buffer, 1); buf = Buffer.from(arr.buffer, 0, 1); // $ExpectError Buffer.from("this is a test", 1, 1); // Ideally passing a normal Buffer would be a type error too, but it's not // since Buffer is assignable to ArrayBuffer currently } // Class Method: Buffer.from(str[, encoding]) { const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); /* tslint:disable-next-line no-construct */ Buffer.from(new String("DEADBEEF"), "hex"); // $ExpectError Buffer.from(buf2, 'hex'); } // Class Method: Buffer.from(object, [, byteOffset[, length]]) (Implicit coercion) { const pseudoBuf = { valueOf() { return Buffer.from([1, 2, 3]); } }; let buf: Buffer = Buffer.from(pseudoBuf); const pseudoString = { valueOf() { return "Hello"; }}; buf = Buffer.from(pseudoString); buf = Buffer.from(pseudoString, "utf-8"); // $ExpectError Buffer.from(pseudoString, 1, 2); const pseudoArrayBuf = { valueOf() { return new Uint16Array(2); } }; buf = Buffer.from(pseudoArrayBuf, 1, 1); } // Class Method: Buffer.alloc(size[, fill[, encoding]]) { const buf1: Buffer = Buffer.alloc(5); const buf2: Buffer = Buffer.alloc(5, 'a'); const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); } // Class Method: Buffer.allocUnsafe(size) { const buf: Buffer = Buffer.allocUnsafe(5); } // Class Method: Buffer.allocUnsafeSlow(size) { const buf: Buffer = Buffer.allocUnsafeSlow(10); } // Class Method byteLenght { let len: number; len = Buffer.byteLength("foo"); len = Buffer.byteLength("foo", "utf8"); const b = Buffer.from("bar"); len = Buffer.byteLength(b); len = Buffer.byteLength(b, "utf16le"); const ab = new ArrayBuffer(15); len = Buffer.byteLength(ab); len = Buffer.byteLength(ab, "ascii"); const dv = new DataView(ab); len = Buffer.byteLength(dv); len = Buffer.byteLength(dv, "utf16le"); } // Class Method poolSize { let s: number; s = Buffer.poolSize; Buffer.poolSize = 4096; } // Test that TS 1.6 works with the 'as Buffer' annotation // on isBuffer. let a: Buffer | number; a = new Buffer(10); if (Buffer.isBuffer(a)) { a.writeUInt8(3, 4); } // write* methods return offsets. const b = new Buffer(16); let result: number = b.writeUInt32LE(0, 0); result = b.writeUInt16LE(0, 4); result = b.writeUInt8(0, 6); result = b.writeInt8(0, 7); result = b.writeDoubleLE(0, 8); result = b.write('asd'); result = b.write('asd', 'hex'); result = b.write('asd', 123, 'hex'); result = b.write('asd', 123, 123, 'hex'); // fill returns the input buffer. b.fill('a').fill('b'); { const buffer = new Buffer('123'); let index: number; index = buffer.indexOf("23"); index = buffer.indexOf("23", 1); index = buffer.indexOf("23", 1, "utf8"); index = buffer.indexOf(23); index = buffer.indexOf(buffer); } { const buffer = new Buffer('123'); let index: number; index = buffer.lastIndexOf("23"); index = buffer.lastIndexOf("23", 1); index = buffer.lastIndexOf("23", 1, "utf8"); index = buffer.lastIndexOf(23); index = buffer.lastIndexOf(buffer); } { const buffer = new Buffer('123'); const val: [number, number] = [1, 1]; /* comment out for --target es5 for (let entry of buffer.entries()) { val = entry; } */ } { const buffer = new Buffer('123'); let includes: boolean; includes = buffer.includes("23"); includes = buffer.includes("23", 1); includes = buffer.includes("23", 1, "utf8"); includes = buffer.includes(23); includes = buffer.includes(23, 1); includes = buffer.includes(23, 1, "utf8"); includes = buffer.includes(buffer); includes = buffer.includes(buffer, 1); includes = buffer.includes(buffer, 1, "utf8"); } { const buffer = new Buffer('123'); const val = 1; /* comment out for --target es5 for (let key of buffer.keys()) { val = key; } */ } { const buffer = new Buffer('123'); const val = 1; /* comment out for --target es5 for (let value of buffer.values()) { val = value; } */ } // Imported Buffer from buffer module works properly { const b = new ImportedBuffer('123'); b.writeUInt8(0, 6); const sb = new ImportedSlowBuffer(43); b.writeUInt8(0, 6); } // Buffer has Uint8Array's buffer field (an ArrayBuffer). { const buffer = new Buffer('123'); const octets = new Uint8Array(buffer.buffer); } // Inherited from Uint8Array but return buffer { const b = Buffer.from('asd'); let res: Buffer = b.reverse(); res = b.subarray(); res = b.subarray(1); res = b.subarray(1, 2); } // Buffer module, transcode function { transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer const source: TranscodeEncoding = 'utf8'; const target: TranscodeEncoding = 'ascii'; transcode(Buffer.from('€'), source, target); // $ExpectType Buffer } { const a = Buffer.alloc(1000); a.writeBigInt64BE(123n); a.writeBigInt64LE(123n); a.writeBigUInt64BE(123n); a.writeBigUInt64LE(123n); let b: bigint = a.readBigInt64BE(123); b = a.readBigInt64LE(123); b = a.readBigUInt64LE(123); b = a.readBigUInt64BE(123); } async () => { const blob = new Blob(['asd', Buffer.from('test'), new Blob(['dummy'])], { type: 'application/javascript', encoding: 'base64', }); blob.size; // $ExpectType number blob.type; // $ExpectType string blob.arrayBuffer(); // $ExpectType Promise<ArrayBuffer> blob.text(); // $ExpectType Promise<string> blob.slice(); // $ExpectType Blob blob.slice(1); // $ExpectType Blob blob.slice(1, 2); // $ExpectType Blob blob.slice(1, 2, 'other'); // $ExpectType Blob };
georgemarshall/DefinitelyTyped
types/node/test/buffer.ts
TypeScript
mit
8,030
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | AUTO-LOADER | ------------------------------------------------------------------- | This file specifies which systems should be loaded by default. | | In order to keep the framework as light-weight as possible only the | absolute minimal resources are loaded by default. For example, | the database is not connected to automatically since no assumption | is made regarding whether you intend to use it. This file lets | you globally define which systems you would like loaded with every | request. | | ------------------------------------------------------------------- | Instructions | ------------------------------------------------------------------- | | These are the things you can load automatically: | | 1. Packages | 2. Libraries | 3. Drivers | 4. Helper files | 5. Custom config files | 6. Language files | 7. Models | */ /* | ------------------------------------------------------------------- | Auto-load Packages | ------------------------------------------------------------------- | Prototype: | | $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared'); | */ $autoload['packages'] = array(); /* | ------------------------------------------------------------------- | Auto-load Libraries | ------------------------------------------------------------------- | These are the classes located in system/libraries/ or your | application/libraries/ directory, with the addition of the | 'database' library, which is somewhat of a special case. | | Prototype: | | $autoload['libraries'] = array('database', 'email', 'session'); | | You can also supply an alternative library name to be assigned | in the controller: | | $autoload['libraries'] = array('user_agent' => 'ua'); */ $autoload['libraries'] = array('database','session','template','form_validation'); /* | ------------------------------------------------------------------- | Auto-load Drivers | ------------------------------------------------------------------- | These classes are located in system/libraries/ or in your | application/libraries/ directory, but are also placed inside their | own subdirectory and they extend the CI_Driver_Library class. They | offer multiple interchangeable driver options. | | Prototype: | | $autoload['drivers'] = array('cache'); | | You can also supply an alternative property name to be assigned in | the controller: | | $autoload['drivers'] = array('cache' => 'cch'); | */ $autoload['drivers'] = array(); /* | ------------------------------------------------------------------- | Auto-load Helper Files | ------------------------------------------------------------------- | Prototype: | | $autoload['helper'] = array('url', 'file'); */ $autoload['helper'] = array('url','form','html','file'); /* | ------------------------------------------------------------------- | Auto-load Config files | ------------------------------------------------------------------- | Prototype: | | $autoload['config'] = array('config1', 'config2'); | | NOTE: This item is intended for use ONLY if you have created custom | config files. Otherwise, leave it blank. | */ $autoload['config'] = array(); /* | ------------------------------------------------------------------- | Auto-load Language files | ------------------------------------------------------------------- | Prototype: | | $autoload['language'] = array('lang1', 'lang2'); | | NOTE: Do not include the "_lang" part of your file. For example | "codeigniter_lang.php" would be referenced as array('codeigniter'); | */ $autoload['language'] = array(); /* | ------------------------------------------------------------------- | Auto-load Models | ------------------------------------------------------------------- | Prototype: | | $autoload['model'] = array('first_model', 'second_model'); | | You can also supply an alternative model name to be assigned | in the controller: | | $autoload['model'] = array('first_model' => 'first'); */ $autoload['model'] = array();
usmanantharikta/slsbmc
application/config/autoload.php
PHP
mit
4,100
// Karma configuration // Generated on Tue Sep 09 2014 13:58:24 GMT-0700 (PDT) 'use strict'; var browsers = ['Chrome', 'PhantomJS']; if ( /^win/.test(process.platform) ) { browsers = ['IE']; } if (process.env.TRAVIS ) { browsers = ['PhantomJS']; } module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['browserify', 'mocha'], browserify: { debug: true, transform: ['6to5ify'] }, // list of files / patterns to load in the browser files: [ 'node_modules/chai/chai.js', 'test/front-end/phantomjs-bind-polyfill.js', 'test/front-end/*-spec.js' ], // list of files to exclude exclude: [ '**/*.swp' ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'test/**/*-spec.js': ['browserify'] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: browsers, // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true }); };
chengzh2008/react-starter
karma.conf.js
JavaScript
mit
1,977
/* * Copyright (c) 2016-2017 Mozilla Foundation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ package nu.validator.xml; import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; public final class UseCountingXMLReaderWrapper implements XMLReader, ContentHandler { private final XMLReader wrappedReader; private ContentHandler contentHandler; private ErrorHandler errorHandler; private HttpServletRequest request; private StringBuilder documentContent; private boolean inBody; private boolean loggedLinkWithCharset; private boolean loggedScriptWithCharset; private boolean loggedStyleInBody; private boolean loggedRelAlternate; private boolean loggedRelAuthor; private boolean loggedRelBookmark; private boolean loggedRelCanonical; private boolean loggedRelDnsPrefetch; private boolean loggedRelExternal; private boolean loggedRelHelp; private boolean loggedRelIcon; private boolean loggedRelLicense; private boolean loggedRelNext; private boolean loggedRelNofollow; private boolean loggedRelNoopener; private boolean loggedRelNoreferrer; private boolean loggedRelPingback; private boolean loggedRelPreconnect; private boolean loggedRelPrefetch; private boolean loggedRelPreload; private boolean loggedRelPrerender; private boolean loggedRelPrev; private boolean loggedRelSearch; private boolean loggedRelServiceworker; private boolean loggedRelStylesheet; private boolean loggedRelTag; public UseCountingXMLReaderWrapper(XMLReader wrappedReader, HttpServletRequest request) { this.wrappedReader = wrappedReader; this.contentHandler = wrappedReader.getContentHandler(); this.request = request; this.inBody = false; this.loggedLinkWithCharset = false; this.loggedScriptWithCharset = false; this.loggedStyleInBody = false; this.loggedRelAlternate = false; this.loggedRelAuthor = false; this.loggedRelBookmark = false; this.loggedRelCanonical = false; this.loggedRelAlternate = false; this.loggedRelAuthor = false; this.loggedRelBookmark = false; this.loggedRelCanonical = false; this.loggedRelDnsPrefetch = false; this.loggedRelExternal = false; this.loggedRelHelp = false; this.loggedRelIcon = false; this.loggedRelLicense = false; this.loggedRelNext = false; this.loggedRelNofollow = false; this.loggedRelNoopener = false; this.loggedRelNoreferrer = false; this.loggedRelPingback = false; this.loggedRelPreconnect = false; this.loggedRelPrefetch = false; this.loggedRelPreload = false; this.loggedRelPrerender = false; this.loggedRelPrev = false; this.loggedRelSearch = false; this.loggedRelServiceworker = false; this.loggedRelStylesheet = false; this.loggedRelTag = false; this.documentContent = new StringBuilder(); wrappedReader.setContentHandler(this); } /** * @see org.xml.sax.helpers.XMLFilterImpl#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (contentHandler == null) { return; } contentHandler.characters(ch, start, length); } /** * @see org.xml.sax.helpers.XMLFilterImpl#endElement(java.lang.String, * java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (contentHandler == null) { return; } contentHandler.endElement(uri, localName, qName); } /** * @see org.xml.sax.helpers.XMLFilterImpl#startDocument() */ @Override public void startDocument() throws SAXException { if (contentHandler == null) { return; } documentContent.setLength(0); contentHandler.startDocument(); } /** * @see org.xml.sax.helpers.XMLFilterImpl#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (contentHandler == null) { return; } if ("link".equals(localName)) { boolean hasAppleTouchIcon = false; boolean hasSizes = false; for (int i = 0; i < atts.getLength(); i++) { if ("rel".equals(atts.getLocalName(i))) { if (atts.getValue(i).contains("apple-touch-icon")) { hasAppleTouchIcon = true; } } else if ("sizes".equals(atts.getLocalName(i))) { hasSizes = true; } else if ("charset".equals(atts.getLocalName(i)) && !loggedLinkWithCharset) { loggedLinkWithCharset = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/link-with-charset-found", true); } } } if (request != null && hasAppleTouchIcon && hasSizes) { request.setAttribute( "http://validator.nu/properties/apple-touch-icon-with-sizes-found", true); } } else if ("script".equals(localName) && !loggedScriptWithCharset) { for (int i = 0; i < atts.getLength(); i++) { if ("charset".equals(atts.getLocalName(i))) { loggedScriptWithCharset = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/script-with-charset-found", true); } } } } else if (inBody && "style".equals(localName) && !loggedStyleInBody) { loggedStyleInBody = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/style-in-body-found", true); } } if (atts.getIndex("", "rel") > -1 && ("link".equals(localName) || "a".equals(localName))) { List<String> relValues = Arrays.asList( atts.getValue("", "rel").trim().toLowerCase() // .split("\\s+")); if (relValues.contains("alternate") && !loggedRelAlternate) { loggedRelAlternate = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-alternate-found", true); } } if (relValues.contains("author") && !loggedRelAuthor) { loggedRelAuthor = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-author-found", true); } } if (relValues.contains("bookmark") && !loggedRelBookmark) { loggedRelBookmark = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-bookmark-found", true); } } if (relValues.contains("canonical") && !loggedRelCanonical) { loggedRelCanonical = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-canonical-found", true); } } if (relValues.contains("dns-prefetch") && !loggedRelDnsPrefetch) { loggedRelDnsPrefetch = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-dns-prefetch-found", true); } } if (relValues.contains("external") && !loggedRelExternal) { loggedRelExternal = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-external-found", true); } } if (relValues.contains("help") && !loggedRelHelp) { loggedRelHelp = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-help-found", true); } } if (relValues.contains("icon") && !loggedRelIcon) { loggedRelIcon = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-icon-found", true); } } if (relValues.contains("license") && !loggedRelLicense) { loggedRelLicense = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-license-found", true); } } if (relValues.contains("next") && !loggedRelNext) { loggedRelNext = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-next-found", true); } } if (relValues.contains("nofollow") && !loggedRelNofollow) { loggedRelNofollow = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-nofollow-found", true); } } if (relValues.contains("noopener") && !loggedRelNoopener) { loggedRelNoopener = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-noopener-found", true); } } if (relValues.contains("noreferrer") && !loggedRelNoreferrer) { loggedRelNoreferrer = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-noreferrer-found", true); } } if (relValues.contains("pingback") && !loggedRelPingback) { loggedRelPingback = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-pingback-found", true); } } if (relValues.contains("preconnect") && !loggedRelPreconnect) { loggedRelPreconnect = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-preconnect-found", true); } } if (relValues.contains("prefetch") && !loggedRelPrefetch) { loggedRelPrefetch = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-prefetch-found", true); } } if (relValues.contains("preload") && !loggedRelPreload) { loggedRelPreload = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-preload-found", true); } } if (relValues.contains("prerender") && !loggedRelPrerender) { loggedRelPrerender = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-prerender-found", true); } } if (relValues.contains("prev") && !loggedRelPrev) { loggedRelPrev = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-prev-found", true); } } if (relValues.contains("search") && !loggedRelSearch) { loggedRelSearch = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-search-found", true); } } if (relValues.contains("serviceworker") && !loggedRelServiceworker) { loggedRelServiceworker = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-serviceworker-found", true); } } if (relValues.contains("stylesheet") && !loggedRelStylesheet) { loggedRelStylesheet = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-stylesheet-found", true); } } if (relValues.contains("tag") && !loggedRelTag) { loggedRelTag = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-tag-found", true); } } } contentHandler.startElement(uri, localName, qName, atts); } /** * @see org.xml.sax.helpers.XMLFilterImpl#setDocumentLocator(org.xml.sax.Locator) */ @Override public void setDocumentLocator(Locator locator) { if (contentHandler == null) { return; } contentHandler.setDocumentLocator(locator); } @Override public ContentHandler getContentHandler() { return contentHandler; } /** * @throws SAXException * @see org.xml.sax.ContentHandler#endDocument() */ @Override public void endDocument() throws SAXException { if (contentHandler == null) { return; } contentHandler.endDocument(); } /** * @param prefix * @throws SAXException * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) */ @Override public void endPrefixMapping(String prefix) throws SAXException { if (contentHandler == null) { return; } contentHandler.endPrefixMapping(prefix); } /** * @param ch * @param start * @param length * @throws SAXException * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) */ @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (contentHandler == null) { return; } contentHandler.ignorableWhitespace(ch, start, length); } /** * @param target * @param data * @throws SAXException * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, * java.lang.String) */ @Override public void processingInstruction(String target, String data) throws SAXException { if (contentHandler == null) { return; } contentHandler.processingInstruction(target, data); } /** * @param name * @throws SAXException * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) */ @Override public void skippedEntity(String name) throws SAXException { if (contentHandler == null) { return; } contentHandler.skippedEntity(name); } /** * @param prefix * @param uri * @throws SAXException * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, * java.lang.String) */ @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { if (contentHandler == null) { return; } contentHandler.startPrefixMapping(prefix, uri); } /** * @return * @see org.xml.sax.XMLReader#getDTDHandler() */ @Override public DTDHandler getDTDHandler() { return wrappedReader.getDTDHandler(); } /** * @return * @see org.xml.sax.XMLReader#getEntityResolver() */ @Override public EntityResolver getEntityResolver() { return wrappedReader.getEntityResolver(); } /** * @return * @see org.xml.sax.XMLReader#getErrorHandler() */ @Override public ErrorHandler getErrorHandler() { return errorHandler; } /** * @param name * @return * @throws SAXNotRecognizedException * @throws SAXNotSupportedException * @see org.xml.sax.XMLReader#getFeature(java.lang.String) */ @Override public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { return wrappedReader.getFeature(name); } /** * @param name * @return * @throws SAXNotRecognizedException * @throws SAXNotSupportedException * @see org.xml.sax.XMLReader#getProperty(java.lang.String) */ @Override public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { return wrappedReader.getProperty(name); } /** * @param input * @throws IOException * @throws SAXException * @see org.xml.sax.XMLReader#parse(org.xml.sax.InputSource) */ @Override public void parse(InputSource input) throws IOException, SAXException { wrappedReader.parse(input); } /** * @param systemId * @throws IOException * @throws SAXException * @see org.xml.sax.XMLReader#parse(java.lang.String) */ @Override public void parse(String systemId) throws IOException, SAXException { wrappedReader.parse(systemId); } /** * @param handler * @see org.xml.sax.XMLReader#setContentHandler(org.xml.sax.ContentHandler) */ @Override public void setContentHandler(ContentHandler handler) { contentHandler = handler; } /** * @param handler * @see org.xml.sax.XMLReader#setDTDHandler(org.xml.sax.DTDHandler) */ @Override public void setDTDHandler(DTDHandler handler) { wrappedReader.setDTDHandler(handler); } /** * @param resolver * @see org.xml.sax.XMLReader#setEntityResolver(org.xml.sax.EntityResolver) */ @Override public void setEntityResolver(EntityResolver resolver) { wrappedReader.setEntityResolver(resolver); } /** * @param handler * @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler) */ @Override public void setErrorHandler(ErrorHandler handler) { wrappedReader.setErrorHandler(handler); } /** * @param name * @param value * @throws SAXNotRecognizedException * @throws SAXNotSupportedException * @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean) */ @Override public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { wrappedReader.setFeature(name, value); } /** * @param name * @param value * @throws SAXNotRecognizedException * @throws SAXNotSupportedException * @see org.xml.sax.XMLReader#setProperty(java.lang.String, * java.lang.Object) */ @Override public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { wrappedReader.setProperty(name, value); } }
tripu/validator
src/nu/validator/xml/UseCountingXMLReaderWrapper.java
Java
mit
22,613
"use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _ = require("../../../"); var _2 = _interopRequireDefault(_); describe(".toString()", function () { var User = (function (_Model) { _inherits(User, _Model); function User() { _classCallCheck(this, User); _get(Object.getPrototypeOf(User.prototype), "constructor", this).apply(this, arguments); } return User; })(_2["default"]); describe("User.find.one.where(\"id\", 1)", function () { it("should return a string representation of the chain", function () { User.find.one.where("id", 1).toString().should.eql("User.find.one.where(\"id\", 1)"); }); it("should not matter which order the chain is called in", function () { User.find.where("id", 1).one.toString().should.eql("User.find.one.where(\"id\", 1)"); }); }); describe("User.find.all.where(\"id\", 1)", function () { it("should return a string representation of the chain", function () { User.find.all.where("id", 1).toString().should.eql("User.find.all.where(\"id\", 1)"); }); }); describe("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1)", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).andWhere("id", ">", 1).toString().should.eql("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1)"); }); }); describe("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1).andWhere(\"id\", \"!=\", 3)", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).andWhere("id", ">", 1).andWhere("id", "!=", 3).toString().should.eql("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1).andWhere(\"id\", \"!=\", 3)"); }); }); describe("User.find.where(\"id\", \"<\", 10).orWhere(\"id\", \">\", 1)", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).orWhere("id", ">", 1).toString().should.eql("User.find.where(\"id\", \"<\", 10).orWhere(\"id\", \">\", 1)"); }); }); describe("User.find.where(\"id\", \"<\", 10).groupBy(\"categoryId\")", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).groupBy("categoryId").toString().should.eql("User.find.where(\"id\", \"<\", 10).groupBy(\"categoryId\")"); }); }); describe("User.find.where(\"id\", \"<\", 10).orderBy(\"categoryId\")", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).orderBy("categoryId", "desc").toString().should.eql("User.find.where(\"id\", \"<\", 10).orderBy(\"categoryId\", \"desc\")"); }); }); describe("User.find.where(\"id\", \">\", 2).limit(4)", function () { it("should return a string representation of the chain", function () { User.find.where("id", ">", 2).limit(4).toString().should.eql("User.find.where(\"id\", \">\", 2).limit(4)"); }); }); describe("User.count.where(\"id\", 1)", function () { it("should return a string representation of the chain", function () { User.count.where("id", 1).toString().should.eql("User.count.where(\"id\", 1)"); }); }); });
FreeAllMedia/dovima
es5/spec/model/toString.spec.js
JavaScript
mit
4,683
namespace FTJFundChoice.OrionClient.Models.Enums { public enum HowIsAdvRegistered { Unknown = 0, SECRegistered = 1, StateRegistered = 2, Unregistered = 3, Other = 4 } }
FTJFundChoice/OrionClient
FTJFundChoice.OrionClient/Models/Enums/HowIsAdvRegistered.cs
C#
mit
220
<?php //Announce.php namespace litepubl\post; use litepubl\view\Lang; use litepubl\view\Schema; use litepubl\view\Vars; /** * Post announces * * @property-write callable $before * @property-write callable $after * @property-write callable $onHead * @method array before(array $params) * @method array after(array $params) * @method array onHead(array $params) */ class Announce extends \litepubl\core\Events { use \litepubl\core\PoolStorageTrait; protected function create() { parent::create(); $this->basename = 'announce'; $this->addEvents('before', 'after', 'onhead'); } public function getHead(array $items): string { $result = ''; if (count($items)) { Posts::i()->loadItems($items); foreach ($items as $id) { $post = Post::i($id); $result.= $post->rawhead; } } $r = $this->onHead(['content' => $result, 'items' => $items]); return $r['content']; } public function getPosts(array $items, Schema $schema): string { $r = $this->before(['content' => '', 'items' => $items, 'schema' => $schema]); $result = $r['content']; $theme = $schema->theme; $items = $r['items']; if (count($items)) { Posts::i()->loadItems($items); $vars = new Vars(); $vars->lang = Lang::i('default'); foreach ($items as $id) { $post = Post::i($id); $view = $post->view; $vars->post = $view; $view->setTheme($theme); $result.= $view->getAnnounce($schema->postannounce); // has $author.* tags in tml if (isset($vars->author)) { unset($vars->author); } } } if ($tmlContainer = $theme->templates['content.excerpts' . ($schema->postannounce == 'excerpt' ? '' : '.' . $schema->postannounce) ]) { $result = str_replace('$excerpt', $result, $theme->parse($tmlContainer)); } $r = $this->after(['content' => $result, 'items' => $items, 'schema' => $schema]); return $r['content']; } public function getNavi(array $items, Schema $schema, string $url, int $count): string { $result = $this->getPosts($items, $schema); $result .= $this->getPages($schema, $url, $count); return $result; } public function getPages(Schema $schema, string $url, int $count): string { $app = $this->getApp(); if ($schema->perpage) { $perpage = $schema->perpage; } else { $perpage = $app->options->perpage; } return $schema->theme->getPages($url, $app->context->request->page, ceil($count / $perpage)); } //used in plugins such as singlecat public function getLinks(string $where, string $tml): string { $db = $this->getApp()->db; $t = $db->posts; $items = $db->res2assoc( $db->query( "select $t.id, $t.title, $db->urlmap.url as url from $t, $db->urlmap where $t.status = 'published' and $where and $db->urlmap.id = $t.idurl" ) ); if (!count($items)) { return ''; } $result = ''; $args = new Args(); $theme = Theme::i(); foreach ($items as $item) { $args->add($item); $result.= $theme->parseArg($tml, $args); } return $result; } } //Factory.php namespace litepubl\post; use litepubl\comments\Comments; use litepubl\comments\Pingbacks; use litepubl\core\Users; use litepubl\pages\Users as UserPages; use litepubl\tag\Cats; use litepubl\tag\Tags; class Factory { use \litepubl\core\Singleton; public function __get($name) { return $this->{'get' . $name}(); } public function getPosts() { return Posts::i(); } public function getFiles() { return Files::i(); } public function getFileView() { return FileView::i(); } public function getTags() { return Tags::i(); } public function getCats() { return Cats::i(); } public function getCategories() { return $this->getcats(); } public function getTemplatecomments() { return Templates::i(); } public function getComments($id) { return Comments::i($id); } public function getPingbacks($id) { return Pingbacks::i($id); } public function getMeta($id) { return Meta::i($id); } public function getUsers() { return Users::i(); } public function getUserpages() { return UserPages::i(); } public function getView() { return View::i(); } } //Files.php namespace litepubl\post; use litepubl\core\Event; use litepubl\core\Str; use litepubl\view\Filter; /** * Manage uploaded files * * @property-read FilesItems $itemsPosts * @property-write callable $changed * @property-write callable $edited * @method array changed(array $params) * @method array edited(array $params) */ class Files extends \litepubl\core\Items { protected function create() { $this->dbversion = true; parent::create(); $this->basename = 'files'; $this->table = 'files'; $this->addEvents('changed', 'edited'); } public function getItemsPosts(): FilesItems { return FilesItems::i(); } public function preload(array $items) { $items = array_diff($items, array_keys($this->items)); if (count($items)) { $this->select(sprintf('(id in (%1$s)) or (parent in (%1$s))', implode(',', $items)), ''); } } public function getUrl(int $id): string { $item = $this->getItem($id); return $this->getApp()->site->files . '/files/' . $item['filename']; } public function getLink(int $id): string { $item = $this->getItem($id); return sprintf('<a href="%1$s/files/%2$s" title="%3$s">%4$s</a>', $this->getApp()->site->files, $item['filename'], $item['title'], $item['description']); } public function getHash(string $filename): string { return trim(base64_encode(md5_file($filename, true)), '='); } public function addItem(array $item): int { $realfile = $this->getApp()->paths->files . str_replace('/', DIRECTORY_SEPARATOR, $item['filename']); $item['author'] = $this->getApp()->options->user; $item['posted'] = Str::sqlDate(); $item['hash'] = $this->gethash($realfile); $item['size'] = filesize($realfile); //fix empty props foreach (['mime', 'title', 'description', 'keywords'] as $prop) { if (!isset($item[$prop])) { $item[$prop] = ''; } } return $this->insert($item); } public function insert(array $item): int { $item = $this->escape($item); $id = $this->db->add($item); $this->items[$id] = $item; $this->changed([]); $this->added(['id' => $id]); return $id; } public function escape(array $item): array { foreach (['title', 'description', 'keywords'] as $name) { $item[$name] = Filter::escape(Filter::unescape($item[$name])); } return $item; } public function edit(int $id, string $title, string $description, string $keywords) { $item = $this->getItem($id); if (($item['title'] == $title) && ($item['description'] == $description) && ($item['keywords'] == $keywords)) { return false; } $item['title'] = $title; $item['description'] = $description; $item['keywords'] = $keywords; $item = $this->escape($item); $this->items[$id] = $item; $this->db->updateassoc($item); $this->changed([]); $this->edited(['id' => $id]); return true; } public function delete($id) { if (!$this->itemExists($id)) { return false; } $list = $this->itemsposts->getposts($id); $this->itemsPosts->deleteItem($id); $this->itemsPosts->updatePosts($list, 'files'); $item = $this->getItem($id); if ($item['idperm'] == 0) { @unlink($this->getApp()->paths->files . str_replace('/', DIRECTORY_SEPARATOR, $item['filename'])); } else { @unlink($this->getApp()->paths->files . 'private' . DIRECTORY_SEPARATOR . basename($item['filename'])); $this->getApp()->router->delete('/files/' . $item['filename']); } parent::delete($id); if ((int)$item['preview']) { $this->delete($item['preview']); } if ((int)$item['midle']) { $this->delete($item['midle']); } $this->getdb('imghashes')->delete("id = $id"); $this->changed([]); $this->deleted(['id' => $id]); return true; } public function setContent(int $id, string $content): bool { if (!$this->itemExists($id)) { return false; } $item = $this->getitem($id); $realfile = $this->getApp()->paths->files . str_replace('/', DIRECTORY_SEPARATOR, $item['filename']); if (file_put_contents($realfile, $content)) { $item['hash'] = $this->gethash($realfile); $item['size'] = filesize($realfile); $this->items[$id] = $item; $item['id'] = $id; $this->db->updateassoc($item); } return true; } public function exists(string $filename): bool { return $this->indexOf('filename', $filename); } public function postEdited(Event $event) { $post = Post::i($event->id); $this->itemsPosts->setItems($post->id, $post->files); } } //FilesItems.php namespace litepubl\post; class FilesItems extends \litepubl\core\ItemsPosts { protected function create() { $this->dbversion = true; parent::create(); $this->basename = 'fileitems'; $this->table = 'filesitemsposts'; } } //FileView.php namespace litepubl\post; use litepubl\core\Str; use litepubl\view\Args; use litepubl\view\Theme; use litepubl\view\Vars; /** * View file list * * @property-write callable $onGetFilelist * @property-write callable $onlist * @method array onGetFilelist(array $params) * @method array onlist(array $params) */ class FileView extends \litepubl\core\Events { protected $templates; protected function create() { parent::create(); $this->basename = 'fileview'; $this->addEvents('ongetfilelist', 'onlist'); $this->templates = []; } public function getFiles(): Files { return Files::i(); } public function getFileList(array $list, bool $excerpt, Theme $theme): string { $r = $this->onGetFilelist(['list' => $list, 'excerpt' => $excerpt, 'result' => false]); if ($r['result']) { return $r['result']; } if (!count($list)) { return ''; } $tml = $excerpt ? $this->getTml($theme, 'content.excerpts.excerpt.filelist') : $this->getTml($theme, 'content.post.filelist'); return $this->getList($list, $tml); } public function getTml(Theme $theme, string $basekey): array { if (isset($this->templates[$theme->name][$basekey])) { return $this->templates[$theme->name][$basekey]; } $result = [ 'container' => $theme->templates[$basekey], ]; $key = $basekey . '.'; foreach ($theme->templates as $k => $v) { if (Str::begin($k, $key)) { $result[substr($k, strlen($key)) ] = $v; } } if (!isset($this->templates[$theme->name])) { $this->templates[$theme->name] = []; } $this->templates[$theme->name][$basekey] = $result; return $result; } public function getList(array $list, array $tml): string { if (!count($list)) { return ''; } $this->onList(['list' => $list]); $result = ''; $files = $this->getFiles(); $files->preLoad($list); //sort by media type $items = []; foreach ($list as $id) { if (!isset($files->items[$id])) { continue; } $item = $files->items[$id]; $type = $item['media']; if (isset($tml[$type])) { $items[$type][] = $id; } else { $items['file'][] = $id; } } $theme = Theme::i(); $args = new Args(); $args->count = count($list); $url = $this->getApp()->site->files . '/files/'; $preview = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); $vars = new Vars(); $vars->preview = $preview; $midle = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); $vars->midle = $midle; $index = 0; foreach ($items as $type => $subitems) { $args->subcount = count($subitems); $sublist = ''; foreach ($subitems as $typeindex => $id) { $item = $files->items[$id]; $args->add($item); $args->link = $url . $item['filename']; $args->id = $id; $args->typeindex = $typeindex; $args->index = $index++; $args->preview = ''; $preview->exchangeArray([]); if ($idmidle = (int)$item['midle']) { $midle->exchangeArray($files->getItem($idmidle)); $midle->link = $url . $midle->filename; $midle->json = $this->getJson($idmidle); } else { $midle->exchangeArray([]); $midle->link = ''; $midle->json = ''; } if ((int)$item['preview']) { $preview->exchangeArray($files->getItem($item['preview'])); } elseif ($type == 'image') { $preview->exchangeArray($item); $preview->id = $id; } elseif ($type == 'video') { $args->preview = $theme->parseArg($tml['videos.fallback'], $args); $preview->exchangeArray([]); } if ($preview->count()) { $preview->link = $url . $preview->filename; $args->preview = $theme->parseArg($tml['preview'], $args); } $args->json = $this->getJson($id); $sublist.= $theme->parseArg($tml[$type], $args); } $args->__set($type, $sublist); $result.= $theme->parseArg($tml[$type . 's'], $args); } $args->files = $result; return $theme->parseArg($tml['container'], $args); } public function getFirstImage(array $items): string { $files = $this->getFiles(); foreach ($items as $id) { $item = $files->getItem($id); if (('image' == $item['media']) && ($idpreview = (int)$item['preview'])) { $baseurl = $this->getApp()->site->files . '/files/'; $args = new Args(); $args->add($item); $args->link = $baseurl . $item['filename']; $args->json = $this->getJson($id); $preview = new \ArrayObject($files->getItem($idpreview), \ArrayObject::ARRAY_AS_PROPS); $preview->link = $baseurl . $preview->filename; $midle = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); if ($idmidle = (int)$item['midle']) { $midle->exchangeArray($files->getItem($idmidle)); $midle->link = $baseurl . $midle->filename; $midle->json = $this->getJson($idmidle); } else { $midle->json = ''; } $vars = new Vars(); $vars->preview = $preview; $vars->midle = $midle; $theme = Theme::i(); return $theme->parseArg($theme->templates['content.excerpts.excerpt.firstimage'], $args); } } return ''; } public function getJson(int $id): string { $item = $this->getFiles()->getItem($id); return Str::jsonAttr( [ 'id' => $id, 'link' => $this->getApp()->site->files . '/files/' . $item['filename'], 'width' => $item['width'], 'height' => $item['height'], 'size' => $item['size'], 'midle' => $item['midle'], 'preview' => $item['preview'], ] ); } } //Meta.php namespace litepubl\post; use litepubl\core\Str; class Meta extends \litepubl\core\Item { public static function getInstancename() { return 'postmeta'; } protected function create() { $this->table = 'postsmeta'; } public function getDbversion() { return true; } public function __set($name, $value) { if ($name == 'id') { return $this->setId($value); } $exists = isset($this->data[$name]); if ($exists && ($this->data[$name] == $value)) { return true; } $this->data[$name] = $value; $name = Str::quote($name); $value = Str::quote($value); if ($exists) { $this->db->update("value = $value", "id = $this->id and name = $name"); } else { $this->db->insertrow("(id, name, value) values ($this->id, $name, $value)"); } } public function __unset($name) { $this->remove($name); } //db public function load() { $this->LoadFromDB(); return true; } protected function LoadFromDB() { $db = $this->db; $res = $db->select("id = $this->id"); if (is_object($res)) { while ($r = $res->fetch_assoc()) { $this->data[$r['name']] = $r['value']; } } return true; } protected function SaveToDB() { $db = $this->db; $db->delete("id = $this->id"); foreach ($this->data as $name => $value) { if ($name == 'id') { continue; } $name = Str::quote($name); $value = Str::quote($value); $this->db->insertrow("(id, name, value) values ($this->id, $name, $value)"); } } public function remove($name) { if ($name == 'id') { return; } unset($this->data[$name]); $this->db->delete("id = $this->id and name = '$name'"); } public static function loaditems(array $items) { if (!count($items)) { return; } //exclude already loaded items if (isset(static ::$instances['postmeta'])) { $items = array_diff($items, array_keys(static ::$instances['postmeta'])); if (!count($items)) { return; } } else { static ::$instances['postmeta'] = []; } $instances = & static ::$instances['postmeta']; $db = static::getAppInstance()->db; $db->table = 'postsmeta'; $res = $db->select(sprintf('id in (%s)', implode(',', $items))); while ($row = $db->fetchassoc($res)) { $id = (int)$row['id']; if (!isset($instances[$id])) { $instances[$id] = new static(); $instances[$id]->data['id'] = $id; } $instances[$id]->data[$row['name']] = $row['value']; } return $items; } } //Post.php namespace litepubl\post; use litepubl\core\Arr; use litepubl\core\Str; use litepubl\view\Filter; /** * This is the post base class * * @property int $idschema * @property int $idurl * @property int $parent * @property int $author * @property int $revision * @property int $idperm * @property string $class * @property int $posted timestamp * @property string $title * @property string $title2 * @property string $filtered * @property string $excerpt * @property string $keywords * @property string $description * @property string $rawhead * @property string $moretitle * @property array $categories * @property array $tags * @property array $files * @property string $status enum * @property string $comstatus enum * @property int $pingenabled bool * @property string $password * @property int $commentscount * @property int $pingbackscount * @property int $pagescount * @property string $url * @property int $created timestamp * @property int $modified timestamp * @property array $pages * @property string $rawcontent * @property-read string $instanceName * @property-read string $childTable * @property-read Factory $factory * @property-read View $view * @property-read Meta $meta * @property string $link absolute url * @property-read string isoDate * @property string pubDate * @property-read string sqlDate * @property string $tagNames tags title separated by , * @property string $catNames categories title separated by , * @property-read string $category first category title * @property-read int $idCat first category ID * @property-read bool $hasPages true if has content or comments pages * @property-read int $pagesCount index from 1 * @property-read int $countPages maximum of content or comments pages * @property-read int commentPages * @property-read string lastCommentUrl * @property-read string schemaLink to generate new url */ class Post extends \litepubl\core\Item { use \litepubl\core\Callbacks; protected $childTable; protected $rawTable; protected $pagesTable; protected $childData; protected $cacheData; protected $rawData; protected $factory; private $metaInstance; public static function i($id = 0) { if ($id = (int) $id) { if (isset(static::$instances['post'][$id])) { $result = static::$instances['post'][$id]; } elseif ($result = static::loadPost($id)) { // nothing: set $instances in afterLoad method } else { $result = null; } } else { $result = parent::itemInstance(get_called_class(), $id); } return $result; } public static function loadPost(int $id) { if ($a = static::loadAssoc($id)) { $self = static::newPost($a['class']); $self->setAssoc($a); if ($table = $self->getChildTable()) { $items = static::selectChildItems( $table, [ $id ] ); $self->childData = $items[$id]; unset($self->childData['id']); } $self->afterLoad(); return $self; } return false; } public static function loadAssoc(int $id) { $db = static::getAppInstance()->db; $table = static::getChildTable(); if ($table) { return $db->selectAssoc( "select $db->posts.*, $db->prefix$table.*, $db->urlmap.url as url from $db->posts, $db->prefix$table, $db->urlmap where $db->posts.id = $id and $db->prefix$table.id = $id and $db->urlmap.id = $db->posts.idurl limit 1" ); } else { return $db->selectAssoc( "select $db->posts.*, $db->urlmap.url as url from $db->posts, $db->urlmap where $db->posts.id = $id and $db->urlmap.id = $db->posts.idurl limit 1" ); } } public static function newPost(string $classname): Post { $classname = $classname ? str_replace('-', '\\', $classname) : get_called_class(); return new $classname(); } public static function getInstanceName(): string { return 'post'; } public static function getChildTable(): string { return ''; } public static function selectChildItems(string $table, array $items): array { if (! $table || ! count($items)) { return []; } $db = static::getAppInstance()->db; $childTable = $db->prefix . $table; $list = implode(',', $items); $count = count($items); return $db->res2items($db->query("select $childTable.* from $childTable where id in ($list) limit $count")); } protected function create() { $this->table = 'posts'; $this->rawTable = 'rawposts'; $this->pagesTable = 'pages'; $this->childTable = static::getChildTable(); $options = $this->getApp()->options; $this->data = [ 'id' => 0, 'idschema' => 1, 'idurl' => 0, 'parent' => 0, 'author' => 0, 'revision' => 0, 'idperm' => 0, 'class' => str_replace('\\', '-', get_class($this)), 'posted' => static::ZERODATE, 'title' => '', 'title2' => '', 'filtered' => '', 'excerpt' => '', 'keywords' => '', 'description' => '', 'rawhead' => '', 'moretitle' => '', 'categories' => '', 'tags' => '', 'files' => '', 'status' => 'published', 'comstatus' => $options->comstatus, 'pingenabled' => $options->pingenabled ? '1' : '0', 'password' => '', 'commentscount' => 0, 'pingbackscount' => 0, 'pagescount' => 0 ]; $this->rawData = []; $this->childData = []; $this->cacheData = [ 'posted' => 0, 'categories' => [], 'tags' => [], 'files' => [], 'url' => '', 'created' => 0, 'modified' => 0, 'pages' => [] ]; $this->factory = $this->getfactory(); } public function getFactory() { return Factory::i(); } public function getView(): View { $view = $this->factory->getView(); $view->setPost($this); return $view; } public function __get($name) { if ($name == 'id') { $result = (int) $this->data['id']; } elseif (method_exists($this, $get = 'get' . $name)) { $result = $this->$get(); } elseif (array_key_exists($name, $this->cacheData)) { $result = $this->cacheData[$name]; } elseif (method_exists($this, $get = 'getCache' . $name)) { $result = $this->$get(); $this->cacheData[$name] = $result; } elseif (array_key_exists($name, $this->data)) { $result = $this->data[$name]; } elseif (array_key_exists($name, $this->childData)) { $result = $this->childData[$name]; } elseif (array_key_exists($name, $this->rawData)) { $result = $this->rawData[$name]; } else { $result = parent::__get($name); } return $result; } public function __set($name, $value) { if ($name == 'id') { $this->setId($value); } elseif (method_exists($this, $set = 'set' . $name)) { $this->$set($value); } elseif (array_key_exists($name, $this->cacheData)) { $this->cacheData[$name] = $value; } elseif (array_key_exists($name, $this->data)) { $this->data[$name] = $value; } elseif (array_key_exists($name, $this->childData)) { $this->childData[$name] = $value; } elseif (array_key_exists($name, $this->rawData)) { $this->rawData[$name] = $value; } else { return parent::__set($name, $value); } return true; } public function __isset($name) { return parent::__isset($name) || array_key_exists($name, $this->cacheData) || array_key_exists($name, $this->childData) || array_key_exists($name, $this->rawData) || method_exists($this, 'getCache' . $name); } public function load() { return true; } public function afterLoad() { static::$instances['post'][$this->id] = $this; parent::afterLoad(); } public function setAssoc(array $a) { $this->cacheData = []; foreach ($a as $k => $v) { if (array_key_exists($k, $this->data)) { $this->data[$k] = $v; } elseif (array_key_exists($k, $this->childData)) { $this->childData[$k] = $v; } elseif (array_key_exists($k, $this->rawData)) { $this->rawData[$k] = $v; } else { $this->cacheData[$k] = $v; } } } public function save() { if ($this->lockcount > 0) { return; } $this->saveToDB(); } protected function saveToDB() { if (! $this->id) { return $this->add(); } $this->db->updateAssoc($this->data); $this->modified = time(); $this->getDB($this->rawTable)->setValues($this->id, $this->rawData); if ($this->childTable) { $this->getDB($this->childTable)->setValues($this->id, $this->childData); } } public function add(): int { $a = $this->data; unset($a['id']); $id = $this->db->add($a); $rawData = $this->prepareRawData(); $rawData['id'] = $id; $this->getDB($this->rawTable)->insert($rawData); $this->setId($id); $this->savePages(); if ($this->childTable) { $childData = $this->childData; $childData['id'] = $id; $this->getDB($this->childTable)->insert($childData); } $this->idurl = $this->createUrl(); $this->db->setValue($id, 'idurl', $this->idurl); $this->triggerOnId(); return $id; } protected function prepareRawData() { if (! $this->created) { $this->created = time(); } if (! $this->modified) { $this->modified = time(); } if (! isset($this->rawData['rawcontent'])) { $this->rawData['rawcontent'] = ''; } return $this->rawData; } public function createUrl() { return $this->getApp()->router->add($this->url, get_class($this), (int) $this->id); } public function onId(callable $callback) { $this->addCallback('onid', $callback); } protected function triggerOnId() { $this->triggerCallback('onid'); $this->clearCallbacks('onid'); if (isset($this->metaInstance)) { $this->metaInstance->id = $this->id; $this->metaInstance->save(); } } public function free() { if (isset($this->metaInstance)) { $this->metaInstance->free(); } parent::free(); } public function getComments() { return $this->factory->getcomments($this->id); } public function getPingbacks() { return $this->factory->getpingbacks($this->id); } public function getMeta() { if (! isset($this->metaInstance)) { $this->metaInstance = $this->factory->getmeta($this->id); } return $this->metaInstance; } // props protected function setDataProp($name, $value, $sql) { $this->cacheData[$name] = $value; if (array_key_exists($name, $this->data)) { $this->data[$name] = $sql; } elseif (array_key_exists($name, $this->childData)) { $this->childData[$name] = $sql; } elseif (array_key_exists($name, $this->rawData)) { $this->rawData[$name] = $sql; } } protected function setArrProp($name, array $list) { Arr::clean($list); $this->setDataProp($name, $list, implode(',', $list)); } protected function setBoolProp($name, $value) { $this->setDataProp($name, $value, $value ? '1' : '0'); } // cache props protected function getArrProp($name) { if ($s = $this->data[$name]) { return explode(',', $s); } else { return []; } } protected function getCacheCategories() { return $this->getArrProp('categories'); } protected function getCacheTags() { return $this->getArrProp('tags'); } protected function getCacheFiles() { return $this->getArrProp('files'); } public function setFiles(array $list) { $this->setArrProp('files', $list); } public function setCategories(array $list) { $this->setArrProp('categories', $list); } public function setTags(array $list) { $this->setArrProp('tags', $list); } protected function getCachePosted() { return $this->data['posted'] == static::ZERODATE ? 0 : strtotime($this->data['posted']); } public function setPosted($timestamp) { $this->data['posted'] = Str::sqlDate($timestamp); $this->cacheData['posted'] = $timestamp; } protected function getCacheModified() { return ! isset($this->rawData['modified']) || $this->rawData['modified'] == static::ZERODATE ? 0 : strtotime($this->rawData['modified']); } public function setModified($timestamp) { $this->rawData['modified'] = Str::sqlDate($timestamp); $this->cacheData['modified'] = $timestamp; } protected function getCacheCreated() { return ! isset($this->rawData['created']) || $this->rawData['created'] == static::ZERODATE ? 0 : strtotime($this->rawData['created']); } public function setCreated($timestamp) { $this->rawData['created'] = Str::sqlDate($timestamp); $this->cacheData['created'] = $timestamp; } public function Getlink() { return $this->getApp()->site->url . $this->url; } public function Setlink($link) { if ($a = @parse_url($link)) { if (empty($a['query'])) { $this->url = $a['path']; } else { $this->url = $a['path'] . '?' . $a['query']; } } } public function setTitle($title) { $this->data['title'] = Filter::escape(Filter::unescape($title)); } public function getIsoDate() { return date('c', $this->posted); } public function getPubDate() { return date('r', $this->posted); } public function setPubDate($date) { $this->setDateProp('posted', strtotime($date)); } public function getSqlDate() { return $this->data['posted']; } public function getTagnames() { if (count($this->tags)) { $tags = $this->factory->tags; return implode(', ', $tags->getnames($this->tags)); } return ''; } public function setTagNames(string $names) { $tags = $this->factory->tags; $this->tags = $tags->createnames($names); } public function getCatnames() { if (count($this->categories)) { $categories = $this->factory->categories; return implode(', ', $categories->getnames($this->categories)); } return ''; } public function setCatNames($names) { $categories = $this->factory->categories; $catItems = $categories->createnames($names); if (! count($catItems)) { $defaultid = $categories->defaultid; if ($defaultid > 0) { $catItems[] = $defaultid; } } $this->categories = $catItems; } public function getCategory(): string { if ($idcat = $this->getidcat()) { return $this->factory->categories->getName($idcat); } return ''; } public function getIdCat(): int { if (($cats = $this->categories) && count($cats)) { return $cats[0]; } return 0; } public function checkRevision() { $this->updateRevision((int) $this->factory->posts->revision); } public function updateRevision($value) { if ($value != $this->revision) { $this->updateFiltered(); $posts = $this->factory->posts; $this->revision = (int) $posts->revision; if ($this->id > 0) { $this->save(); } } } public function updateFiltered() { Filter::i()->filterPost($this, $this->rawcontent); } public function setRawContent($s) { $this->rawData['rawcontent'] = $s; } public function getRawContent() { if (isset($this->rawData['rawcontent'])) { return $this->rawData['rawcontent']; } if (! $this->id) { return ''; } $this->rawData = $this->getDB($this->rawTable)->getItem($this->id); unset($this->rawData['id']); return $this->rawData['rawcontent']; } public function getPage(int $i) { if (isset($this->cacheData['pages'][$i])) { return $this->cacheData['pages'][$i]; } if ($this->id > 0) { if ($r = $this->getdb($this->pagesTable)->getAssoc("(id = $this->id) and (page = $i) limit 1")) { $s = $r['content']; } else { $s = false; } $this->cacheData['pages'][$i] = $s; return $s; } return false; } public function addPage($s) { $this->cacheData['pages'][] = $s; $this->data['pagescount'] = count($this->cacheData['pages']); if ($this->id > 0) { $this->getdb($this->pagesTable)->insert( [ 'id' => $this->id, 'page' => $this->data['pagescount'] - 1, 'content' => $s ] ); } } public function deletePages() { $this->cacheData['pages'] = []; $this->data['pagescount'] = 0; if ($this->id > 0) { $this->getdb($this->pagesTable)->idDelete($this->id); } } public function savePages() { if (isset($this->cacheData['pages'])) { $db = $this->getDB($this->pagesTable); foreach ($this->cacheData['pages'] as $index => $content) { $db->insert( [ 'id' => $this->id, 'page' => $index, 'content' => $content ] ); } } } public function getHasPages(): bool { return ($this->pagescount > 1) || ($this->commentpages > 1); } public function getPagesCount() { return $this->data['pagescount'] + 1; } public function getCountPages() { return max($this->pagescount, $this->commentpages); } public function getCommentPages() { $options = $this->getApp()->options; if (! $options->commentpages || ($this->commentscount <= $options->commentsperpage)) { return 1; } return ceil($this->commentscount / $options->commentsperpage); } public function getLastCommentUrl() { $c = $this->commentpages; $url = $this->url; if (($c > 1) && ! $this->getApp()->options->comments_invert_order) { $url = rtrim($url, '/') . "/page/$c/"; } return $url; } public function clearCache() { $this->getApp()->cache->clearUrl($this->url); } public function getSchemalink(): string { return 'post'; } public function setContent($s) { if (! is_string($s)) { $this->error('Error! Post content must be string'); } $this->rawcontent = $s; Filter::i()->filterpost($this, $s); } } //Posts.php namespace litepubl\post; use litepubl\core\Cron; use litepubl\core\Str; use litepubl\utils\LinkGenerator; use litepubl\view\Schemes; /** * Main class to manage posts * * @property int $archivescount * @property int $revision * @property bool $syncmeta * @property-write callable $edited * @property-write callable $changed * @property-write callable $singleCron * @property-write callable $onSelect * @method array edited(array $params) * @method array changed(array $params) * @method array singleCron(array $params) * @method array onselect(array $params) */ class Posts extends \litepubl\core\Items { const POSTCLASS = __NAMESPACE__ . '/Post'; public $itemcoclasses; public $archives; public $rawtable; public $childTable; public static function unsub($obj) { static ::i()->unbind($obj); } protected function create() { $this->dbversion = true; parent::create(); $this->table = 'posts'; $this->childTable = ''; $this->rawtable = 'rawposts'; $this->basename = 'posts/index'; $this->addEvents('edited', 'changed', 'singlecron', 'onselect'); $this->data['archivescount'] = 0; $this->data['revision'] = 0; $this->data['syncmeta'] = false; $this->addmap('itemcoclasses', []); } public function getItem($id) { if ($result = Post::i($id)) { return $result; } $this->error("Item $id not found in class " . get_class($this)); } public function findItems(string $where, string $limit): array { if (isset(Post::$instances['post']) && (count(Post::$instances['post']))) { $result = $this->db->idSelect($where . ' ' . $limit); $this->loadItems($result); return $result; } else { return $this->select($where, $limit); } } public function loadItems(array $items) { //exclude already loaded items if (!isset(Post::$instances['post'])) { Post::$instances['post'] = []; } $loaded = array_keys(Post::$instances['post']); $newitems = array_diff($items, $loaded); if (!count($newitems)) { return $items; } $newitems = $this->select(sprintf('%s.id in (%s)', $this->thistable, implode(',', $newitems)), 'limit ' . count($newitems)); return array_merge($newitems, array_intersect($loaded, $items)); } public function setAssoc(array $items) { if (!count($items)) { return []; } $result = []; $fileitems = []; foreach ($items as $a) { $post = Post::newPost($a['class']); $post->setAssoc($a); $post->afterLoad(); $result[] = $post->id; $f = $post->files; if (count($f)) { $fileitems = array_merge($fileitems, array_diff($f, $fileitems)); } } if ($this->syncmeta) { Meta::loadItems($result); } if (count($fileitems)) { Files::i()->preLoad($fileitems); } $this->onSelect(['items' => $result]); return $result; } public function select(string $where, string $limit): array { $db = $this->getApp()->db; if ($this->childTable) { $childTable = $db->prefix . $this->childTable; return $this->setAssoc( $db->res2items( $db->query( "select $db->posts.*, $childTable.*, $db->urlmap.url as url from $db->posts, $childTable, $db->urlmap where $where and $db->posts.id = $childTable.id and $db->urlmap.id = $db->posts.idurl $limit" ) ) ); } $items = $db->res2items( $db->query( "select $db->posts.*, $db->urlmap.url as url from $db->posts, $db->urlmap where $where and $db->urlmap.id = $db->posts.idurl $limit" ) ); if (!count($items)) { return []; } $subclasses = []; foreach ($items as $id => $item) { if (empty($item['class'])) { $items[$id]['class'] = static ::POSTCLASS; } elseif ($item['class'] != static ::POSTCLASS) { $subclasses[$item['class']][] = $id; } } foreach ($subclasses as $class => $list) { $class = str_replace('-', '\\', $class); $childDataItems = $class::selectChildItems($class::getChildTable(), $list); foreach ($childDataItems as $id => $childData) { $items[$id] = array_merge($items[$id], $childData); } } return $this->setAssoc($items); } public function getCount() { return $this->db->getcount("status<> 'deleted'"); } public function getChildsCount($where) { if (!$this->childTable) { return 0; } $db = $this->getApp()->db; $childTable = $db->prefix . $this->childTable; $res = $db->query( "SELECT COUNT($db->posts.id) as count FROM $db->posts, $childTable where $db->posts.status <> 'deleted' and $childTable.id = $db->posts.id $where" ); if ($res && ($r = $db->fetchassoc($res))) { return $r['count']; } return 0; } private function beforeChange($post) { $post->title = trim($post->title); $post->modified = time(); $post->revision = $this->revision; $post->class = str_replace('\\', '-', ltrim(get_class($post), '\\')); if (($post->status == 'published') && ($post->posted > time())) { $post->status = 'future'; } elseif (($post->status == 'future') && ($post->posted <= time())) { $post->status = 'published'; } } public function add(Post $post): int { $this->beforeChange($post); if (!$post->posted) { $post->posted = time(); } if ($post->posted <= time()) { if ($post->status == 'future') { $post->status = 'published'; } } else { if ($post->status == 'published') { $post->status = 'future'; } } if ($post->idschema == 1) { $schemes = Schemes::i(); if (isset($schemes->defaults['post'])) { $post->data['idschema'] = $schemes->defaults['post']; } } $post->url = LinkGenerator::i()->addUrl($post, $post->schemaLink); $id = $post->add(); $this->updated($post); $this->added(['id' => $id]); $this->changed([]); $this->getApp()->cache->clear(); return $id; } public function edit(Post $post) { $this->beforeChange($post); $linkgen = LinkGenerator::i(); $linkgen->editurl($post, $post->schemaLink); if ($post->posted <= time()) { if ($post->status == 'future') { $post->status = 'published'; } } else { if ($post->status == 'published') { $post->status = 'future'; } } $this->lock(); $post->save(); $this->updated($post); $this->unlock(); $this->edited(['id' => $post->id]); $this->changed([]); $this->getApp()->cache->clear(); } public function delete($id) { if (!$this->itemExists($id)) { return false; } $this->db->setvalue($id, 'status', 'deleted'); if ($this->childTable) { $db = $this->getdb($this->childTable); $db->delete("id = $id"); } $this->lock(); $this->PublishFuture(); $this->UpdateArchives(); $this->unlock(); $this->deleted(['id' => $id]); $this->changed([]); $this->getApp()->cache->clear(); return true; } public function updated(Post $post) { $this->PublishFuture(); $this->UpdateArchives(); Cron::i()->add('single', get_class($this), 'dosinglecron', $post->id); } public function UpdateArchives() { $this->archivescount = $this->db->getcount("status = 'published' and posted <= '" . Str::sqlDate() . "'"); } public function doSingleCron($id) { $this->PublishFuture(); Theme::$vars['post'] = Post::i($id); $this->singleCron(['id' => $id]); unset(Theme::$vars['post']); } public function hourcron() { $this->PublishFuture(); } private function publish($id) { $post = Post::i($id); $post->status = 'published'; $this->edit($post); } public function PublishFuture() { if ($list = $this->db->idselect(sprintf('status = \'future\' and posted <= \'%s\' order by posted asc', Str::sqlDate()))) { foreach ($list as $id) { $this->publish($id); } } } public function getRecent($author, $count) { $author = (int)$author; $where = "status != 'deleted'"; if ($author > 1) { $where.= " and author = $author"; } return $this->findItems($where, ' order by posted desc limit ' . (int)$count); } public function getPage(int $author, int $page, int $perpage, bool $invertorder): array { $from = ($page - 1) * $perpage; $t = $this->thistable; $where = "$t.status = 'published'"; if ($author > 1) { $where.= " and $t.author = $author"; } $order = $invertorder ? 'asc' : 'desc'; return $this->findItems($where, " order by $t.posted $order limit $from, $perpage"); } public function stripDrafts(array $items): array { if (count($items) == 0) { return []; } $list = implode(',', $items); $t = $this->thistable; return $this->db->idSelect("$t.status = 'published' and $t.id in ($list)"); } public function addRevision(): int { $this->data['revision']++; $this->save(); $this->getApp()->cache->clear(); return $this->data['revision']; } public function getSitemap($from, $count) { return $this->externalfunc( __class__, 'Getsitemap', [ $from, $count ] ); } } //View.php namespace litepubl\post; use litepubl\comments\Templates; use litepubl\core\Context; use litepubl\core\Str; use litepubl\view\Args; use litepubl\view\Lang; use litepubl\view\MainView; use litepubl\view\Schema; use litepubl\view\Theme; /** * Post view * * @property-write callable $beforeContent * @property-write callable $afterContent * @property-write callable $beforeExcerpt * @property-write callable $afterExcerpt * @property-write callable $onHead * @property-write callable $onTags * @method array beforeContent(array $params) * @method array afterContent(array $params) * @method array beforeExcerpt(array $params) * @method array afterExcerpt(array $params) * @method array onHead(array $params) * @method array onTags(array $params) */ class View extends \litepubl\core\Events implements \litepubl\view\ViewInterface { use \litepubl\core\PoolStorageTrait; public $post; public $context; private $prevPost; private $nextPost; private $themeInstance; protected function create() { parent::create(); $this->basename = 'postview'; $this->addEvents('beforecontent', 'aftercontent', 'beforeexcerpt', 'afterexcerpt', 'onhead', 'ontags'); $this->table = 'posts'; } public function setPost(Post $post) { $this->post = $post; $this->themeInstance = null; } public function getView() { return $this; } public function __get($name) { if (method_exists($this, $get = 'get' . $name)) { $result = $this->$get(); } else { switch ($name) { case 'catlinks': $result = $this->get_taglinks('categories', false); break; case 'taglinks': $result = $this->get_taglinks('tags', false); break; case 'excerptcatlinks': $result = $this->get_taglinks('categories', true); break; case 'excerpttaglinks': $result = $this->get_taglinks('tags', true); break; default: if (isset($this->post->$name)) { $result = $this->post->$name; } else { $result = parent::__get($name); } } } return $result; } public function __set($name, $value) { if (parent::__set($name, $value)) { return true; } if (isset($this->post->$name)) { $this->post->$name = $value; return true; } return false; } public function __call($name, $args) { if (method_exists($this->post, $name)) { return call_user_func_array([$this->post, $name], $args); } else { return parent::__call($name, $args); } } public function getPrev() { if (!is_null($this->prevPost)) { return $this->prevPost; } $this->prevPost = false; if ($id = $this->db->findid("status = 'published' and posted < '$this->sqldate' order by posted desc")) { $this->prevPost = Post::i($id); } return $this->prevPost; } public function getNext() { if (!is_null($this->nextPost)) { return $this->nextPost; } $this->nextPost = false; if ($id = $this->db->findid("status = 'published' and posted > '$this->sqldate' order by posted asc")) { $this->nextPost = Post::i($id); } return $this->nextPost; } public function getTheme(): Theme { if (!$this->themeInstance) { $this->themeInstance = $this->post ? $this->schema->theme : Theme::context(); } $this->themeInstance->setvar('post', $this); return $this->themeInstance; } public function setTheme(Theme $theme) { $this->themeInstance = $theme; } public function parseTml(string $path): string { $theme = $this->theme; return $theme->parse($theme->templates[$path]); } public function getExtra() { $theme = $this->theme; return $theme->parse($theme->extratml); } public function getBookmark() { return $this->theme->parse($this->theme->templates['content.post.bookmark']); } public function getRssComments(): string { return $this->getApp()->site->url . "/comments/$this->id.xml"; } public function getIdImage(): int { if (!count($this->files)) { return 0; } $files = $this->factory->files; foreach ($this->files as $id) { $item = $files->getItem($id); if ('image' == $item['media']) { return $id; } } return 0; } public function getImage(): string { if ($id = $this->getIdImage()) { return $this->factory->files->getUrl($id); } return ''; } public function getThumb(): string { if (!count($this->files)) { return ''; } $files = $this->factory->files; foreach ($this->files as $id) { $item = $files->getItem($id); if ((int)$item['preview']) { return $files->getUrl($item['preview']); } } return ''; } public function getFirstImage(): string { $items = $this->files; if (count($items)) { return $this->factory->fileView->getFirstImage($items); } return ''; } //template protected function get_taglinks($name, $excerpt) { $items = $this->__get($name); if (!count($items)) { return ''; } $theme = $this->theme; $tmlpath = $excerpt ? 'content.excerpts.excerpt' : 'content.post'; $tmlpath.= $name == 'tags' ? '.taglinks' : '.catlinks'; $tmlitem = $theme->templates[$tmlpath . '.item']; $tags = Str::begin($name, 'tag') ? $this->factory->tags : $this->factory->categories; $tags->loaditems($items); $args = new Args(); $list = []; foreach ($items as $id) { if ($id && ($item = $tags->getItem($id))) { $args->add($item); $list[] = $theme->parseArg($tmlitem, $args); } } $args->items = ' ' . implode($theme->templates[$tmlpath . '.divider'], $list); $result = $theme->parseArg($theme->templates[$tmlpath], $args); $r = $this->onTags(['tags' => $tags, 'excerpt' => $excerpt, 'content' => $result]); return $r['content']; } public function getDate(): string { return Lang::date($this->posted, $this->theme->templates['content.post.date']); } public function getExcerptDate(): string { return Lang::date($this->posted, $this->theme->templates['content.excerpts.excerpt.date']); } public function getDay(): string { return date($this->posted, 'D'); } public function getMonth(): string { return Lang::date($this->posted, 'M'); } public function getYear(): string { return date($this->posted, 'Y'); } public function getMoreLink(): string { if ($this->moretitle) { return $this->parsetml('content.excerpts.excerpt.morelink'); } return ''; } public function request(Context $context) { $app = $this->getApp(); if ($this->status != 'published') { if (!$app->options->show_draft_post) { $context->response->status = 404; return; } $groupname = $app->options->group; if (($groupname == 'admin') || ($groupname == 'editor')) { return; } if ($this->author == $app->options->user) { return; } $context->response->status = 404; return; } $this->context = $context; } public function getPage(): int { return $this->context->request->page; } public function getTitle(): string { return $this->post->title; } public function getHead(): string { $result = $this->rawhead; MainView::i()->ltoptions['idpost'] = $this->id; $theme = $this->theme; $result.= $theme->templates['head.post']; if ($prev = $this->prev) { Theme::$vars['prev'] = $prev; $result.= $theme->templates['head.post.prev']; } if ($next = $this->next) { Theme::$vars['next'] = $next; $result.= $theme->templates['head.post.next']; } if ($this->hascomm) { Lang::i('comment'); $result.= $theme->templates['head.post.rss']; } $result = $theme->parse($result); $r = $this->onHead(['post' => $this->post, 'content' => $result]); return $r['content']; } public function getKeywords(): string { if ($result = $this->post->keywords) { return $result; } else { return $this->Gettagnames(); } } public function getDescription(): string { return $this->post->description; } public function getIdSchema(): int { return $this->post->idschema; } public function setIdSchema(int $id) { if ($id != $this->idschema) { $this->post->idschema = $id; if ($this->id) { $this->post->db->setvalue($this->id, 'idschema', $id); } } } public function getSchema(): Schema { return Schema::getSchema($this); } //to override schema in post, id schema not changed public function getFileList(): string { $items = $this->files; if (!count($items) || (($this->page > 1) && $this->getApp()->options->hidefilesonpage)) { return ''; } $fileView = $this->factory->fileView; return $fileView->getFileList($items, false, $this->theme); } public function getExcerptFileList(): string { $items = $this->files; if (count($items) == 0) { return ''; } $fileView = $this->factory->fileView; return $fileView->getFileList($items, true, $this->theme); } public function getIndexTml() { $theme = $this->theme; if (!empty($theme->templates['index.post'])) { return $theme->templates['index.post']; } return false; } public function getCont(): string { return $this->parsetml('content.post'); } public function getRssLink(): string { if ($this->hascomm) { return $this->parseTml('content.post.rsslink'); } return ''; } public function onRssItem($item) { } public function getRss(): string { $this->getApp()->getLogManager()->trace('get rss deprecated post property'); return $this->post->excerpt; } public function getPrevNext(): string { $prev = ''; $next = ''; $theme = $this->theme; if ($prevpost = $this->prev) { Theme::$vars['prevpost'] = $prevpost; $prev = $theme->parse($theme->templates['content.post.prevnext.prev']); } if ($nextpost = $this->next) { Theme::$vars['nextpost'] = $nextpost; $next = $theme->parse($theme->templates['content.post.prevnext.next']); } if (($prev == '') && ($next == '')) { return ''; } $result = strtr( $theme->parse($theme->templates['content.post.prevnext']), [ '$prev' => $prev, '$next' => $next ] ); unset(Theme::$vars['prevpost'], Theme::$vars['nextpost']); return $result; } public function getCommentsLink(): string { $tml = sprintf('<a href="%s%s#comments">%%s</a>', $this->getApp()->site->url, $this->getlastcommenturl()); if (($this->comstatus == 'closed') || !$this->getApp()->options->commentspool) { if (($this->commentscount == 0) && (($this->comstatus == 'closed'))) { return ''; } return sprintf($tml, $this->getcmtcount()); } //inject php code return sprintf('<?php echo litepubl\comments\Pool::i()->getLink(%d, \'%s\'); ?>', $this->id, $tml); } public function getCmtCount(): string { $l = Lang::i()->ini['comment']; switch ($this->commentscount) { case 0: return $l[0]; case 1: return $l[1]; default: return sprintf($l[2], $this->commentscount); } } public function getTemplateComments(): string { $result = ''; $countpages = $this->countpages; if ($countpages > 1) { $result.= $this->theme->getpages($this->url, $this->page, $countpages); } if (($this->commentscount > 0) || ($this->comstatus != 'closed') || ($this->pingbackscount > 0)) { if (($countpages > 1) && ($this->commentpages < $this->page)) { $result.= $this->getCommentsLink(); } else { $result.= Templates::i()->getcomments($this); } } return $result; } public function getHasComm(): bool { return ($this->comstatus != 'closed') && ((int)$this->commentscount > 0); } public function getAnnounce(string $announceType): string { $tmlKey = 'content.excerpts.' . ($announceType == 'excerpt' ? 'excerpt' : $announceType . '.excerpt'); return $this->parseTml($tmlKey); } public function getExcerptContent(): string { $this->post->checkRevision(); $r = $this->beforeExcerpt(['post' => $this->post, 'content' => $this->excerpt]); $result = $this->replaceMore($r['content'], true); if ($this->getApp()->options->parsepost) { $result = $this->theme->parse($result); } $r = $this->afterExcerpt(['post' => $this->post, 'content' => $result]); return $r['content']; } public function replaceMore(string $content, string $excerpt): string { $more = $this->parseTml($excerpt ? 'content.excerpts.excerpt.morelink' : 'content.post.more'); $tag = '<!--more-->'; if (strpos($content, $tag)) { return str_replace($tag, $more, $content); } else { return $excerpt ? $content : $more . $content; } } protected function getTeaser(): string { $content = $this->filtered; $tag = '<!--more-->'; if ($i = strpos($content, $tag)) { $content = substr($content, $i + strlen($tag)); if (!Str::begin($content, '<p>')) { $content = '<p>' . $content; } return $content; } return ''; } protected function getContentPage(int $page): string { $result = ''; if ($page == 1) { $result.= $this->filtered; $result = $this->replaceMore($result, false); } elseif ($s = $this->post->getPage($page - 2)) { $result.= $s; } elseif ($page <= $this->commentpages) { } else { $result.= Lang::i()->notfound; } return $result; } public function getContent(): string { $this->post->checkRevision(); $r = $this->beforeContent(['post' => $this->post, 'content' => '']); $result = $r['content']; $result.= $this->getContentPage($this->page); if ($this->getApp()->options->parsepost) { $result = $this->theme->parse($result); } $r = $this->afterContent(['post' => $this->post, 'content' => $result]); return $r['content']; } //author protected function getAuthorName(): string { return $this->getusername($this->author, false); } protected function getAuthorLink() { return $this->getusername($this->author, true); } protected function getUserName($id, $link) { if ($id <= 1) { if ($link) { return sprintf('<a href="%s/" rel="author" title="%2$s">%2$s</a>', $this->getApp()->site->url, $this->getApp()->site->author); } else { return $this->getApp()->site->author; } } else { $users = $this->factory->users; if (!$users->itemExists($id)) { return ''; } $item = $users->getitem($id); if (!$link || ($item['website'] == '')) { return $item['name']; } return sprintf('<a href="%s/users.htm%sid=%s">%s</a>', $this->getApp()->site->url, $this->getApp()->site->q, $id, $item['name']); } } public function getAuthorPage() { $id = $this->author; if ($id <= 1) { return sprintf('<a href="%s/" rel="author" title="%2$s">%2$s</a>', $this->getApp()->site->url, $this->getApp()->site->author); } else { $pages = $this->factory->userpages; if (!$pages->itemExists($id)) { return ''; } $pages->id = $id; if ($pages->url == '') { return ''; } return sprintf('<a href="%s%s" title="%3$s" rel="author"><%3$s</a>', $this->getApp()->site->url, $pages->url, $pages->name); } } }
litepubl/cms
lib/post/kernel.php
PHP
mit
69,969
#ifndef GLMESH_H #define GLMESH_H #include <GLplus.hpp> namespace tinyobj { struct shape_t; } // end namespace tinyobj namespace GLmesh { class StaticMesh { std::shared_ptr<GLplus::Buffer> mpPositions; std::shared_ptr<GLplus::Buffer> mpTexcoords; std::shared_ptr<GLplus::Buffer> mpNormals; std::shared_ptr<GLplus::Buffer> mpIndices; size_t mVertexCount = 0; std::shared_ptr<GLplus::Texture2D> mpDiffuseTexture; public: void LoadShape(const tinyobj::shape_t& shape); void Render(GLplus::Program& program) const; }; } // end namespace GLmesh #endif // GLMESH_H
nguillemot/LD48-Beneath-The-Surface
GLmesh/include/GLmesh.hpp
C++
mit
605
<?php namespace spec\Welp\MailchimpBundle\Event; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class WebhookEventSpec extends ObjectBehavior { function let($data = ['test' => 0, 'data' => 154158]) { $this->beConstructedWith($data); } function it_is_initializable() { $this->shouldHaveType('Welp\MailchimpBundle\Event\WebhookEvent'); $this->shouldHaveType('Symfony\Component\EventDispatcher\Event'); } function it_has_data($data) { $this->getData()->shouldReturn($data); } }
welpdev/mailchimp-bundle
spec/Event/WebhookEventSpec.php
PHP
mit
552
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) require 'bundler/setup' # Set up gems listed in the Gemfile. require 'rubygems' require 'rails/commands/server' =begin module Rails class Server alias :default_options_bk :default_options def default_options default_options_bk.merge!(Host: '120.27.94.221') end end end =end
xiaominghe2014/AccountsSys
config/boot.rb
Ruby
mit
365
<!DOCTYPE html> <html lang="en"> <head> <?php include "htmlheader.php" ?> <title>The War of 1812</title> </head> <body> <?php include "pageheader.php"; ?> <!-- Page Header --> <!-- Set your background image for this header on the line below. --> <header class="intro-header" style="background-image: url('img/1812ships.jpg')"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="post-heading"> <h1>The Second American War for Independence</h1> <h2 class="subheading">And what caused it</h2> <span class="meta">Content created by Wat Adair and Scotty Fulgham</span> </div> </div> </div> </div> </header> <!-- Post Content --> <article> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <p>At the outset of the 19th century, Great Britain was locked in a long and bitter conflict with Napoleon Bonaparte’s France. In an attempt to cut off supplies from reaching the enemy, both sides attempted to block the United States from trading with the other. In 1807, Britain passed the Orders in Council, which required neutral countries to obtain a license from its authorities before trading with France or French colonies.</p> <p>The Royal Navy also outraged Americans by its practice of impressment, or removing seamen from U.S. merchant vessels and forcing them to serve on behalf of the British. In 1809, the U.S. Congress repealed Thomas Jefferson’s unpopular Embargo Act, which by restricting trade had hurt Americans more than either Britain or France. Its replacement, the Non-Intercourse Act, specifically prohibited trade with Britain and France. It also proved ineffective, and in turn was replaced with a May 1810 bill stating that if either power dropped trade restrictions against the United States, Congress would in turn resume non-intercourse with the opposing power</p> <h2 class="section-heading">Causes of the War</h2> <p>In the War of 1812, the United States took on the greatest naval power in the world, Great Britain, in a conflict that would have an immense impact on the young country’s future. Causes of the war included British attempts to restrict U.S. trade, the Royal Navy’s impressment of American seamen and America’s desire to expand its territory.</p> <h2 class="section-heading">Effects of the War</h2> <p>The war of 1812 was thought of as a relatively minor war but it had some lasting results, It is thought of as a decisive turning point in canadians and native americans losing efforts to govern themselves. The war also put an end to the federalist party. The party had been accused of being unpatriotic because they were against war. Some people think the most important effect of the war was the confidence that it gave america.</p> <blockquote> "The war has renewed and reinstated the national feelings and character which the Revolution had given, and which were daily lessened. The people . . . . are more American; they feel and act more as a nation; and I hope the permanency of the Union is thereby better secured." - First Lady Dolley Madison, 24 August 1814, writing to her sister as the British attacked Washington, D.C. </blockquote> <p><i>Page content written by Wat Adair and Scotty Fulgham.</i></p> </div> </div> </div> </article> <hr> <?php include "pagefooter.php"; ?> </body> </html>
roll11tide/europeanwar
1812.html.php
PHP
mit
3,908
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.data.types; import org.spongepowered.api.CatalogType; import org.spongepowered.api.util.annotation.CatalogedBy; /** * Represents a type of instrument. */ @CatalogedBy(InstrumentTypes.class) public interface InstrumentType extends CatalogType { }
frogocomics/SpongeAPI
src/main/java/org/spongepowered/api/data/types/InstrumentType.java
Java
mit
1,532
import React, { PropTypes } from 'react'; class Link extends React.Component { render() { return <article key={this.props.item.id} className="List-Item"> <header className="List-Item-Header"> <cite className="List-Item-Title"><a href={this.props.item.href}>{this.props.item.title}</a></cite> </header> <p className="List-Item-Description List-Item-Description--Short">{this.props.item.short_description}</p> </article> } } export default Link;
Shroder/essential-javascript-links
src/modules/List/components/Link/index.js
JavaScript
mit
484
load File.expand_path("../target.rb", __FILE__) module ActiveRecord::Magic class Param::Server < Param::Target def default_options { online:nil, wildcard:false, autocomplete:true, current_server:false, current_channel:false, users:false, channels:false, servers:true, ambigious: false } end end end
gizmore/ricer4
lib/ricer4/core/params/server.rb
Ruby
mit
358
package components.diagram.edit.commands; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.common.core.command.CommandResult; import org.eclipse.gmf.runtime.common.core.command.ICommand; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateRelationshipRequest; import components.Component; import components.ComponentsFactory; import components.Connection; import components.Port; import components.diagram.edit.policies.ComponentModelBaseItemSemanticEditPolicy; /** * @generated */ public class ConnectionCreateCommand extends EditElementCommand { /** * @generated */ private final EObject source; /** * @generated */ private final EObject target; /** * @generated */ private final Component container; /** * @generated */ public ConnectionCreateCommand(CreateRelationshipRequest request, EObject source, EObject target) { super(request.getLabel(), null, request); this.source = source; this.target = target; container = deduceContainer(source, target); } /** * @generated */ public boolean canExecute() { if (source == null && target == null) { return false; } if (source != null && false == source instanceof Port) { return false; } if (target != null && false == target instanceof Port) { return false; } if (getSource() == null) { return true; // link creation is in progress; source is not defined yet } // target may be null here but it's possible to check constraint if (getContainer() == null) { return false; } return ComponentModelBaseItemSemanticEditPolicy.getLinkConstraints().canCreateConnection_4001(getContainer(), getSource(), getTarget()); } /** * @generated */ protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { if (!canExecute()) { throw new ExecutionException("Invalid arguments in create link command"); //$NON-NLS-1$ } Connection newElement = ComponentsFactory.eINSTANCE.createConnection(); getContainer().getConnections().add(newElement); newElement.getTarget().add(getSource()); newElement.getTarget().add(getTarget()); doConfigure(newElement, monitor, info); ((CreateElementRequest) getRequest()).setNewElement(newElement); return CommandResult.newOKCommandResult(newElement); } /** * @generated */ protected void doConfigure(Connection newElement, IProgressMonitor monitor, IAdaptable info) throws ExecutionException { IElementType elementType = ((CreateElementRequest) getRequest()).getElementType(); ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement, elementType); configureRequest.setClientContext(((CreateElementRequest) getRequest()).getClientContext()); configureRequest.addParameters(getRequest().getParameters()); configureRequest.setParameter(CreateRelationshipRequest.SOURCE, getSource()); configureRequest.setParameter(CreateRelationshipRequest.TARGET, getTarget()); ICommand configureCommand = elementType.getEditCommand(configureRequest); if (configureCommand != null && configureCommand.canExecute()) { configureCommand.execute(monitor, info); } } /** * @generated */ protected void setElementToEdit(EObject element) { throw new UnsupportedOperationException(); } /** * @generated */ protected Port getSource() { return (Port) source; } /** * @generated */ protected Port getTarget() { return (Port) target; } /** * @generated */ public Component getContainer() { return container; } /** * Default approach is to traverse ancestors of the source to find instance of container. * Modify with appropriate logic. * @generated */ private static Component deduceContainer(EObject source, EObject target) { // Find container element for the new link. // Climb up by containment hierarchy starting from the source // and return the first element that is instance of the container class. for (EObject element = source; element != null; element = element.eContainer()) { if (element instanceof Component) { return (Component) element; } } return null; } }
peterbartha/component-diagram
ComponentTester.diagram/src/components/diagram/edit/commands/ConnectionCreateCommand.java
Java
mit
4,550
import Vue from 'vue'; import merge from 'element-ui/src/utils/merge'; import PopupManager from 'element-ui/src/utils/popup/popup-manager'; import getScrollBarWidth from '../scrollbar-width'; let idSeed = 1; const transitions = []; const hookTransition = (transition) => { if (transitions.indexOf(transition) !== -1) return; const getVueInstance = (element) => { let instance = element.__vue__; if (!instance) { const textNode = element.previousSibling; if (textNode.__vue__) { instance = textNode.__vue__; } } return instance; }; Vue.transition(transition, { afterEnter(el) { const instance = getVueInstance(el); if (instance) { instance.doAfterOpen && instance.doAfterOpen(); } }, afterLeave(el) { const instance = getVueInstance(el); if (instance) { instance.doAfterClose && instance.doAfterClose(); } } }); }; let scrollBarWidth; const getDOM = function(dom) { if (dom.nodeType === 3) { dom = dom.nextElementSibling || dom.nextSibling; getDOM(dom); } return dom; }; export default { model: { prop: 'visible', event: 'visible-change' }, props: { visible: { type: Boolean, default: false }, transition: { type: String, default: '' }, openDelay: {}, closeDelay: {}, zIndex: {}, modal: { type: Boolean, default: false }, modalFade: { type: Boolean, default: true }, modalClass: {}, modalAppendToBody: { type: Boolean, default: false }, lockScroll: { type: Boolean, default: true }, closeOnPressEscape: { type: Boolean, default: false }, closeOnClickModal: { type: Boolean, default: false } }, created() { if (this.transition) { hookTransition(this.transition); } }, beforeMount() { this._popupId = 'popup-' + idSeed++; PopupManager.register(this._popupId, this); }, beforeDestroy() { PopupManager.deregister(this._popupId); PopupManager.closeModal(this._popupId); if (this.modal && this.bodyOverflow !== null && this.bodyOverflow !== 'hidden') { document.body.style.overflow = this.bodyOverflow; document.body.style.paddingRight = this.bodyPaddingRight; } this.bodyOverflow = null; this.bodyPaddingRight = null; }, data() { return { opened: false, bodyOverflow: null, bodyPaddingRight: null, rendered: false }; }, watch: { visible(val) { if (val) { if (this._opening) return; if (!this.rendered) { this.rendered = true; Vue.nextTick(() => { this.open(); }); } else { this.open(); } } else { this.close(); } } }, methods: { open(options) { if (!this.rendered) { this.rendered = true; this.$emit('visible-change', true); } const props = merge({}, this.$props || this, options); if (this._closeTimer) { clearTimeout(this._closeTimer); this._closeTimer = null; } clearTimeout(this._openTimer); const openDelay = Number(props.openDelay); if (openDelay > 0) { this._openTimer = setTimeout(() => { this._openTimer = null; this.doOpen(props); }, openDelay); } else { this.doOpen(props); } }, doOpen(props) { if (this.$isServer) return; if (this.willOpen && !this.willOpen()) return; if (this.opened) return; this._opening = true; this.$emit('visible-change', true); const dom = getDOM(this.$el); const modal = props.modal; const zIndex = props.zIndex; if (zIndex) { PopupManager.zIndex = zIndex; } if (modal) { if (this._closing) { PopupManager.closeModal(this._popupId); this._closing = false; } PopupManager.openModal(this._popupId, PopupManager.nextZIndex(), this.modalAppendToBody ? undefined : dom, props.modalClass, props.modalFade); if (props.lockScroll) { if (!this.bodyOverflow) { this.bodyPaddingRight = document.body.style.paddingRight; this.bodyOverflow = document.body.style.overflow; } scrollBarWidth = getScrollBarWidth(); let bodyHasOverflow = document.documentElement.clientHeight < document.body.scrollHeight; if (scrollBarWidth > 0 && bodyHasOverflow) { document.body.style.paddingRight = scrollBarWidth + 'px'; } document.body.style.overflow = 'hidden'; } } if (getComputedStyle(dom).position === 'static') { dom.style.position = 'absolute'; } dom.style.zIndex = PopupManager.nextZIndex(); this.opened = true; this.onOpen && this.onOpen(); if (!this.transition) { this.doAfterOpen(); } }, doAfterOpen() { this._opening = false; }, close() { if (this.willClose && !this.willClose()) return; if (this._openTimer !== null) { clearTimeout(this._openTimer); this._openTimer = null; } clearTimeout(this._closeTimer); const closeDelay = Number(this.closeDelay); if (closeDelay > 0) { this._closeTimer = setTimeout(() => { this._closeTimer = null; this.doClose(); }, closeDelay); } else { this.doClose(); } }, doClose() { this.$emit('visible-change', false); this._closing = true; this.onClose && this.onClose(); if (this.lockScroll) { setTimeout(() => { if (this.modal && this.bodyOverflow !== 'hidden') { document.body.style.overflow = this.bodyOverflow; document.body.style.paddingRight = this.bodyPaddingRight; } this.bodyOverflow = null; this.bodyPaddingRight = null; }, 200); } this.opened = false; if (!this.transition) { this.doAfterClose(); } }, doAfterClose() { PopupManager.closeModal(this._popupId); this._closing = false; } } }; export { PopupManager };
JavascriptTips/element
src/utils/popup/index.js
JavaScript
mit
6,321
package edu.gatech.oad.antlab.pkg1; import edu.cs2335.antlab.pkg3.*; import edu.gatech.oad.antlab.person.*; import edu.gatech.oad.antlab.pkg2.*; /** * CS2335 Ant Lab * * Prints out a simple message gathered from all of the other classes * in the package structure */ public class AntLabMain { /**antlab11.java message class*/ private AntLab11 ant11; /**antlab12.java message class*/ private AntLab12 ant12; /**antlab21.java message class*/ private AntLab21 ant21; /**antlab22.java message class*/ private AntLab22 ant22; /**antlab31 java message class which is contained in a jar resource file*/ private AntLab31 ant31; /** * the constructor that intializes all the helper classes */ public AntLabMain () { ant11 = new AntLab11(); ant12 = new AntLab12(); ant21 = new AntLab21(); ant22 = new AntLab22(); ant31 = new AntLab31(); } /** * gathers a string from all the other classes and prints the message * out to the console * */ public void printOutMessage() { String toPrint = ant11.getMessage() + ant12.getMessage() + ant21.getMessage() + ant22.getMessage() + ant31.getMessage(); //Person1 replace P1 with your name //and gburdell1 with your gt id Person1 p1 = new Person1("Pranov"); toPrint += p1.toString("pduggasani3"); //Person2 replace P2 with your name //and gburdell with your gt id Person2 p2 = new Person2("Austin Dang"); toPrint += p2.toString("adang31"); //Person3 replace P3 with your name //and gburdell3 with your gt id Person3 p3 = new Person3("Jay Patel"); toPrint += p3.toString("jpatel345"); //Person4 replace P4 with your name //and gburdell4 with your gt id Person4 p4 = new Person4("Jin Chung"); toPrint += p4.toString("jchung89"); //Person5 replace P4 with your name //and gburdell5 with your gt id Person5 p5 = new Person5("Zachary Hussin"); toPrint += p5.toString("zhussin3"); System.out.println(toPrint); } /** * entry point for the program */ public static void main(String[] args) { new AntLabMain().printOutMessage(); } }
PranovD/CS2340
M2/src/main/java/edu/gatech/oad/antlab/pkg1/AntLabMain.java
Java
mit
2,551
package net.alloyggp.tournament.internal.admin; import net.alloyggp.escaperope.Delimiters; import net.alloyggp.escaperope.RopeDelimiter; import net.alloyggp.escaperope.rope.Rope; import net.alloyggp.escaperope.rope.ropify.SubclassWeaver; import net.alloyggp.escaperope.rope.ropify.Weaver; import net.alloyggp.tournament.api.TAdminAction; public class InternalAdminActions { private InternalAdminActions() { //Not instantiable } @SuppressWarnings("deprecation") public static final Weaver<TAdminAction> WEAVER = SubclassWeaver.builder(TAdminAction.class) .add(ReplaceGameAction.class, "ReplaceGame", ReplaceGameAction.WEAVER) .build(); public static RopeDelimiter getStandardDelimiter() { return Delimiters.getJsonArrayRopeDelimiter(); } public static TAdminAction fromPersistedString(String persistedString) { Rope rope = getStandardDelimiter().undelimit(persistedString); return WEAVER.fromRope(rope); } public static String toPersistedString(TAdminAction adminAction) { Rope rope = WEAVER.toRope(adminAction); return getStandardDelimiter().delimit(rope); } }
AlexLandau/ggp-tournament
src/main/java/net/alloyggp/tournament/internal/admin/InternalAdminActions.java
Java
mit
1,179
<div id="content-alerts"> <table id="conten-2" border="1px"> <tbody> <?php echo $sidemenu ?> <tr> <td style="vertical-align: top;"> <div style="padding: 5px 5px 5px 5px"> <table border="1" cellspacing="1px"> <tr style="background-color: #DBDBDB"> <th>ATM ID</th> <th>ĐẦU ĐỌC THẺ</th> <th>BỘ PHẬN TRẢ TIỀN</th> <th>BÀN PHÍM</th> <th>MÁY IN HÓA ĐƠN</th> <th>MẠNG</th> <th>SẴN SÀNG</th> </tr> <?php foreach ($result as $item) { echo "<tr>"; echo "<td>$item->AtmId</td>"; echo "<td>".(empty($item->CardReader) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->CashDispenser) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->PinPad) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->ReceiptPrinter) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->NetDown) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->Service) ? "OK" : "Không")."</td>"; echo "</tr>"; } ?> </table> </div> </td> </tr> </tbody> </table> </div>
thaingochieu/atmphp
fuel/app/views/hoatdong/summary/atmerror.php
PHP
mit
1,690
<?xml version="1.0" ?><!DOCTYPE TS><TS language="hr" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About TelcoCoin</source> <translation>O TelcoCoin-u</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;TelcoCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;TelcoCoin&lt;/b&gt; verzija</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The TelcoCoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adresar</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dvostruki klik za uređivanje adrese ili oznake</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Dodajte novu adresu</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopiraj trenutno odabranu adresu u međuspremnik</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Nova adresa</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your TelcoCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Ovo su vaše TelcoCoin adrese za primanje isplate. Možda želite dati drukčiju adresu svakom primatelju tako da možete pratiti tko je platio.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopirati adresu</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Prikaži &amp;QR Kôd</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a TelcoCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Izvoz podataka iz trenutnog taba u datoteku</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified TelcoCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Brisanje</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your TelcoCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopirati &amp;oznaku</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Izmjeniti</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Izvoz podataka adresara</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Datoteka vrijednosti odvojenih zarezom (*. csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Pogreška kod izvoza</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ne mogu pisati u datoteku %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Oznaka</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(bez oznake)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Unesite lozinku</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova lozinka</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ponovite novu lozinku</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Unesite novi lozinku za novčanik. &lt;br/&gt; Molimo Vas da koristite zaporku od &lt;b&gt;10 ili više slučajnih znakova,&lt;/b&gt; ili &lt;b&gt;osam ili više riječi.&lt;/b&gt;</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Šifriranje novčanika</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ova operacija treba lozinku vašeg novčanika kako bi se novčanik otključao.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Otključaj novčanik</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ova operacija treba lozinku vašeg novčanika kako bi se novčanik dešifrirao.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Dešifriranje novčanika.</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Promjena lozinke</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Unesite staru i novu lozinku za novčanik.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Potvrdi šifriranje novčanika</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR TelcoCoinS&lt;/b&gt;!</source> <translation>Upozorenje: Ako šifrirate vaš novčanik i izgubite lozinku, &lt;b&gt;IZGUBIT ĆETE SVE SVOJE TelcoCoinSE!&lt;/b&gt;</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Jeste li sigurni da želite šifrirati svoj novčanik?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Novčanik šifriran</translation> </message> <message> <location line="-56"/> <source>TelcoCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your TelcoCoins from being stolen by malware infecting your computer.</source> <translation>TelcoCoin će se sada zatvoriti kako bi dovršio postupak šifriranja. Zapamtite da šifriranje vašeg novčanika ne može u potpunosti zaštititi vaše TelcoCoine od krađe preko zloćudnog softvera koji bi bio na vašem računalu.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Šifriranje novčanika nije uspjelo</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Šifriranje novčanika nije uspjelo zbog interne pogreške. Vaš novčanik nije šifriran.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Priložene lozinke se ne podudaraju.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Otključavanje novčanika nije uspjelo</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Lozinka za dešifriranje novčanika nije točna.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Dešifriranje novčanika nije uspjelo</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Lozinka novčanika je uspješno promijenjena.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Potpišite poruku...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Usklađivanje s mrežom ...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Pregled</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Prikaži opći pregled novčanika</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transakcije</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Pretraži povijest transakcija</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels for sending</source> <translation>Uređivanje popisa pohranjenih adresa i oznaka</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Prikaži popis adresa za primanje isplate</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Izlaz</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Izlazak iz programa</translation> </message> <message> <location line="+4"/> <source>Show information about TelcoCoin</source> <translation>Prikaži informacije o TelcoCoinu</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Više o &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Prikaži informacije o Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Postavke</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Šifriraj novčanik...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup novčanika...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Promijena lozinke...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importiranje blokova sa diska...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Re-indeksiranje blokova na disku...</translation> </message> <message> <location line="-347"/> <source>Send coins to a TelcoCoin address</source> <translation>Slanje novca na TelcoCoin adresu</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for TelcoCoin</source> <translation>Promijeni postavke konfiguracije za TelcoCoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Napravite sigurnosnu kopiju novčanika na drugoj lokaciji</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Promijenite lozinku za šifriranje novčanika</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>TelcoCoin</source> <translation>TelcoCoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Novčanik</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About TelcoCoin</source> <translation>&amp;O TelcoCoinu</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your TelcoCoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified TelcoCoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Datoteka</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Konfiguracija</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Pomoć</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Traka kartica</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>TelcoCoin client</source> <translation>TelcoCoin klijent</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to TelcoCoin network</source> <translation><numerusform>%n aktivna veza na TelcoCoin mrežu</numerusform><numerusform>%n aktivne veze na TelcoCoin mrežu</numerusform><numerusform>%n aktivnih veza na TelcoCoin mrežu</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Obrađeno %1 blokova povijesti transakcije.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Greška</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Ažurno</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Ažuriranje...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Poslana transakcija</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Dolazna transakcija</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum:%1 Iznos:%2 Tip:%3 Adresa:%4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid TelcoCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Novčanik je &lt;b&gt;šifriran&lt;/b&gt; i trenutno &lt;b&gt;otključan&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Novčanik je &lt;b&gt;šifriran&lt;/b&gt; i trenutno &lt;b&gt;zaključan&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. TelcoCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Izmjeni adresu</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Oznaka</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Oznaka ovog upisa u adresar</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresa</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adresa ovog upisa u adresar. Može se mjenjati samo kod adresa za slanje.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nova adresa za primanje</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nova adresa za slanje</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Uredi adresu za primanje</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Uredi adresu za slanje</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Upisana adresa &quot;%1&quot; je već u adresaru.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid TelcoCoin address.</source> <translation>Upisana adresa &quot;%1&quot; nije valjana TelcoCoin adresa.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Ne mogu otključati novčanik.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Stvaranje novog ključa nije uspjelo.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>TelcoCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation>verzija</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Upotreba:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI postavke</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Pokreni minimiziran</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Postavke</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Glavno</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Plati &amp;naknadu za transakciju</translation> </message> <message> <location line="+31"/> <source>Automatically start TelcoCoin after logging in to the system.</source> <translation>Automatski pokreni TelcoCoin kad se uključi računalo</translation> </message> <message> <location line="+3"/> <source>&amp;Start TelcoCoin on system login</source> <translation>&amp;Pokreni TelcoCoin kod pokretanja sustava</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the TelcoCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatski otvori port TelcoCoin klijenta na ruteru. To radi samo ako ruter podržava UPnP i ako je omogućen.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapiraj port koristeći &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the TelcoCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Spojite se na Bitcon mrežu putem SOCKS proxy-a (npr. kod povezivanja kroz Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Povezivanje putem SOCKS proxy-a:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP adresa proxy-a (npr. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Port od proxy-a (npr. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Prikaži samo ikonu u sistemskoj traci nakon minimiziranja prozora</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimiziraj u sistemsku traku umjesto u traku programa</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimizirati umjesto izaći iz aplikacije kada je prozor zatvoren. Kada je ova opcija omogućena, aplikacija će biti zatvorena tek nakon odabira Izlaz u izborniku.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimiziraj kod zatvaranja</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Prikaz</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting TelcoCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Jedinica za prikazivanje iznosa:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Izaberite željeni najmanji dio TelcoCoina koji će biti prikazan u sučelju i koji će se koristiti za plaćanje.</translation> </message> <message> <location line="+9"/> <source>Whether to show TelcoCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Prikaži adrese u popisu transakcija</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Upozorenje</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting TelcoCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Oblik</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the TelcoCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Stanje:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Nepotvrđene:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Novčanik</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Nedavne transakcije&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Vaše trenutno stanje računa</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Ukupni iznos transakcija koje tek trebaju biti potvrđene, i još uvijek nisu uračunate u trenutni saldo</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start TelcoCoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR Code Dijalog</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Zatraži plaćanje</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Iznos:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Oznaka</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Poruka:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Spremi kao...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Rezultirajući URI je predug, probajte umanjiti tekst za naslov / poruku.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG slike (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Lanac blokova</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Trenutni broj blokova</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Procjenjeni ukupni broj blokova</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Posljednje vrijeme bloka</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the TelcoCoin-Qt help message to get a list with possible TelcoCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>TelcoCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>TelcoCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the TelcoCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the TelcoCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Slanje novca</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Pošalji k nekoliko primatelja odjednom</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Dodaj primatelja</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Obriši sva polja transakcija</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Obriši &amp;sve</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Stanje:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123,456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Potvrdi akciju slanja</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Pošalji</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; do %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Potvrdi slanje novca</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Jeste li sigurni da želite poslati %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>i</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Adresa primatelja je nevaljala, molimo provjerite je ponovo.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Iznos mora biti veći od 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Iznos je veći od stanja računa.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Iznos je veći od stanja računa kad se doda naknada za transakcije od %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Pronašli smo adresu koja se ponavlja. U svakom plaćanju program može svaku adresu koristiti samo jedanput.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Generirani novčići moraju pričekati nastanak 120 blokova prije nego što ih je moguće potrošiti. Kad ste generirali taj blok, on je bio emitiran u mrežu kako bi bio dodan postojećim lancima blokova. Ako ne uspije biti dodan, njegov status bit će promijenjen u &quot;nije prihvatljiv&quot; i on neće biti potrošiv. S vremena na vrijeme tako nešto se može desiti ako neki drugi nod približno istovremeno generira blok.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Oblik</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Iznos:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Primatelj plaćanja:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Unesite oznaku za ovu adresu kako bi ju dodali u vaš adresar</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Oznaka:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Odaberite adresu iz adresara</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Zalijepi adresu iz međuspremnika</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Ukloni ovog primatelja</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a TelcoCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Unesite TelcoCoin adresu (npr. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Potpišite poruku</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Možete potpisati poruke sa svojom adresom kako bi dokazali da ih posjedujete. Budite oprezni da ne potpisujete ništa mutno, jer bi vas phishing napadi mogli na prevaru natjerati da prepišete svoj identitet njima. Potpisujte samo detaljno objašnjene izjave sa kojima se slažete.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Unesite TelcoCoin adresu (npr. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Odaberite adresu iz adresara</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Zalijepi adresu iz međuspremnika</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Upišite poruku koju želite potpisati ovdje</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this TelcoCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Obriši &amp;sve</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Unesite TelcoCoin adresu (npr. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified TelcoCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a TelcoCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Unesite TelcoCoin adresu (npr. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter TelcoCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The TelcoCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Otvoren do %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1 nije dostupan</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nepotvrđeno</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 potvrda</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generiran</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Od</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Za</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>oznaka</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Uplaćeno</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>Nije prihvaćeno</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Zaduženje</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Naknada za transakciju</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Neto iznos</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Poruka</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Komentar</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Generirani novčići moraju pričekati nastanak 120 blokova prije nego što ih je moguće potrošiti. Kad ste generirali taj blok, on je bio emitiran u mrežu kako bi bio dodan postojećim lancima blokova. Ako ne uspije biti dodan, njegov status bit će promijenjen u &quot;nije prihvaćen&quot; i on neće biti potrošiv. S vremena na vrijeme tako nešto se može desiti ako neki drugi nod generira blok u približno isto vrijeme.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Iznos</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, još nije bio uspješno emitiran</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>nepoznato</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detalji transakcije</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Ova panela prikazuje detaljni opis transakcije</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tip</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Iznos</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Otvoren do %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Nije na mreži (%1 potvrda)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepotvrđen (%1 od %2 potvrda)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Potvrđen (%1 potvrda)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Generirano - Upozorenje: ovaj blok nije bio primljen od strane bilo kojeg drugog noda i vjerojatno neće biti prihvaćen!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generirano, ali nije prihvaćeno</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Primljeno s</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Primljeno od</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Poslano za</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Plaćanje samom sebi</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Rudareno</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/d)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status transakcije</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum i vrijeme kad je transakcija primljena</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Vrsta transakcije.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Odredište transakcije</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Iznos odbijen od ili dodan k saldu.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Sve</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Danas</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Ovaj tjedan</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Ovaj mjesec</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Prošli mjesec</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Ove godine</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Raspon...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Primljeno s</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Poslano za</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Tebi</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Rudareno</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Ostalo</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Unesite adresu ili oznaku za pretraživanje</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min iznos</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopirati adresu</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopirati oznaku</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopiraj iznos</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Izmjeniti oznaku</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Izvoz podataka transakcija</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Datoteka podataka odvojenih zarezima (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Potvrđeno</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tip</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Oznaka</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Iznos</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Izvoz pogreške</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ne mogu pisati u datoteku %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Raspon:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>za</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Slanje novca</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Izvoz podataka iz trenutnog taba u datoteku</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>TelcoCoin version</source> <translation>TelcoCoin verzija</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Upotreba:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or TelcoCoind</source> <translation>Pošalji komandu usluzi -server ili TelcoCoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Prikaži komande</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Potraži pomoć za komandu</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Postavke:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: TelcoCoin.conf)</source> <translation>Odredi konfiguracijsku datoteku (ugrađeni izbor: TelcoCoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: TelcoCoind.pid)</source> <translation>Odredi proces ID datoteku (ugrađeni izbor: TelcoCoin.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Odredi direktorij za datoteke</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Postavi cache za bazu podataka u MB (zadano:25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 22556 or testnet: 44556)</source> <translation>Slušaj na &lt;port&gt;u (default: 22556 ili testnet: 44556)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Održavaj najviše &lt;n&gt; veza sa članovima (default: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Prag za odspajanje članova koji se čudno ponašaju (default: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Broj sekundi koliko se članovima koji se čudno ponašaju neće dopustiti da se opet spoje (default: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 22555 or testnet: 44555)</source> <translation>Prihvaćaj JSON-RPC povezivanje na portu broj &lt;port&gt; (ugrađeni izbor: 22555 or testnet: 44555)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Prihvati komande iz tekst moda i JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Izvršavaj u pozadini kao uslužnik i prihvaćaj komande</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Koristi test mrežu</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=TelcoCoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;TelcoCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. TelcoCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Upozorenje: -paytxfee je podešen na preveliki iznos. To je iznos koji ćete platiti za obradu transakcije.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong TelcoCoin will not work properly.</source> <translation>Upozorenje: Molimo provjerite jesu li datum i vrijeme na vašem računalu točni. Ako vaš sat ide krivo, TelcoCoin neće raditi ispravno.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opcije za kreiranje bloka:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Poveži se samo sa određenim nodom</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importiraj blokove sa vanjskog blk000??.dat fajla</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Nevaljala -tor adresa: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Prihvati samo lance blokova koji se podudaraju sa ugrađenim checkpoint-ovima (default: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp (default: 1)</source> <translation>Dodaj izlaz debuga na početak sa vremenskom oznakom</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the TelcoCoin Wiki for SSL setup instructions)</source> <translation>SSL postavke: (za detalje o podešavanju SSL opcija vidi TelcoCoin Wiki)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Šalji trace/debug informacije na konzolu umjesto u debug.log datoteku</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Pošalji trace/debug informacije u debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Podesite maksimalnu veličinu bloka u bajtovima (default: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Podesite minimalnu veličinu bloka u bajtovima (default: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Odredi vremenski prozor za spajanje na mrežu u milisekundama (ugrađeni izbor: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Pokušaj koristiti UPnP da otvoriš port za uslugu (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Pokušaj koristiti UPnP da otvoriš port za uslugu (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Korisničko ime za JSON-RPC veze</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Lozinka za JSON-RPC veze</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Dozvoli JSON-RPC povezivanje s određene IP adrese</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Pošalji komande nodu na adresi &lt;ip&gt; (ugrađeni izbor: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Izvršite naredbu kada se najbolji blok promjeni (%s u cmd je zamjenjen sa block hash)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Nadogradite novčanik u posljednji format.</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Podesi memorijski prostor za ključeve na &lt;n&gt; (ugrađeni izbor: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ponovno pretraži lanac blokova za transakcije koje nedostaju</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Koristi OpenSSL (https) za JSON-RPC povezivanje</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Uslužnikov SSL certifikat (ugrađeni izbor: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Uslužnikov privatni ključ (ugrađeni izbor: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Prihvaljivi načini šifriranja (ugrađeni izbor: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Ova poruka za pomoć</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Program ne može koristiti %s na ovom računalu (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Poveži se kroz socks proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Dozvoli DNS upite za dodavanje nodova i povezivanje</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Učitavanje adresa...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Greška kod učitavanja wallet.dat: Novčanik pokvaren</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of TelcoCoin</source> <translation>Greška kod učitavanja wallet.dat: Novčanik zahtjeva noviju verziju TelcoCoina</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart TelcoCoin to complete</source> <translation>Novčanik je trebao prepravak: ponovo pokrenite TelcoCoin</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Greška kod učitavanja wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Nevaljala -proxy adresa: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Nevaljali iznos za opciju -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Nevaljali iznos za opciju</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Nedovoljna sredstva</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Učitavanje indeksa blokova...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Unesite nod s kojim se želite spojiti and attempt to keep the connection open</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. TelcoCoin is probably already running.</source> <translation>Program ne može koristiti %s na ovom računalu. TelcoCoin program je vjerojatno već pokrenut.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Naknada posredniku po KB-u koja će biti dodana svakoj transakciji koju pošalješ</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Učitavanje novčanika...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Nije moguće novčanik vratiti na prijašnju verziju.</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Nije moguće upisati zadanu adresu.</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Rescaniranje</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Učitavanje gotovo</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>Greška</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
telcocoin-project/telcocoin
src/qt/locale/bitcoin_hr.ts
TypeScript
mit
107,245
<?php namespace BungieNetPlatform\Exceptions\Platform; use BungieNetPlatform\Exceptions\PlatformException; /** * DestinyStatsParameterMembershipIdParseError */ class DestinyStatsParameterMembershipIdParseErrorException extends PlatformException { public function __construct($message, $code = 1608, \Exception $previous = null) { parent::__construct($message, $code, $previous); } }
dazarobbo/BungieNetPlatform
src/Exceptions/Platform/DestinyStatsParameterMembershipIdParseErrorException.php
PHP
mit
410
$LOAD_PATH.unshift File.expand_path('../lib') require 'rspec' RSpec.configure do |conf| conf.color = true conf.formatter = 'documentation' conf.order = 'random' end
timuruski/press_any_key
spec/spec_helper.rb
Ruby
mit
173
(function () { 'use strict'; /** * @ngdoc function * @name app.test:homeTest * @description * # homeTest * Test of the app */ describe('homeCtrl', function () { var controller = null, $scope = null, $location; beforeEach(function () { module('g4mify-client-app'); }); beforeEach(inject(function ($controller, $rootScope, _$location_) { $scope = $rootScope.$new(); $location = _$location_; controller = $controller('HomeCtrl', { $scope: $scope }); })); it('Should HomeCtrl must be defined', function () { expect(controller).toBeDefined(); }); it('Should match the path Module name', function () { $location.path('/home'); expect($location.path()).toBe('/home'); }); }); })();
ltouroumov/amt-g4mify
client/app/modules/home/home-test.js
JavaScript
mit
739
var eejs = require('ep_etherpad-lite/node/eejs') /* * Handle incoming delete requests from clients */ exports.handleMessage = function(hook_name, context, callback){ var Pad = require('ep_etherpad-lite/node/db/Pad.js').Pad // Firstly ignore any request that aren't about chat var isDeleteRequest = false; if(context) { if(context.message && context.message){ if(context.message.type === 'COLLABROOM'){ if(context.message.data){ if(context.message.data.type){ if(context.message.data.type === 'ep_push2delete'){ isDeleteRequest = true; } } } } } } if(!isDeleteRequest){ callback(false); return false; } console.log('DELETION REQUEST!') var packet = context.message.data; /*** What's available in a packet? * action -- The action IE chatPosition * padId -- The padId of the pad both authors are on ***/ if(packet.action === 'deletePad'){ var pad = new Pad(packet.padId) pad.remove(function(er) { if(er) console.warn('ep_push2delete', er) callback([null]); }) } } exports.eejsBlock_editbarMenuRight = function(hook_name, args, cb) { if(!args.renderContext.req.url.match(/^\/(p\/r\..{16})/)) { args.content = eejs.require('ep_push2delete/templates/delete_button.ejs') + args.content; } cb(); };
marcelklehr/ep_push2delete
index.js
JavaScript
mit
1,374
using Microsoft.Xna.Framework; using System; namespace Gem.Gui.Animations { public static class Time { public static Animation<double> Elapsed { get { return Animation.Create(context => context.TotalMilliseconds); } } public static Animation<TTime> Constant<TTime>(TTime time) { return Animation.Create(context => time); } public static Animation<double> Wave { get { return Animation.Create(context => Math.Sin(context.TotalSeconds)); } } } }
gmich/Gem
Gem.Gui/Animations/Time.cs
C#
mit
610
version https://git-lfs.github.com/spec/v1 oid sha256:355954a2b585f8b34c53b8bea9346fabde06b161ec86b87e9b829bea4acb87e9 size 108190
yogeshsaroya/new-cdnjs
ajax/libs/materialize/0.95.0/js/materialize.min.js
JavaScript
mit
131
using Robust.Shared.GameObjects; namespace Content.Server.MachineLinking.Components { [RegisterComponent] public sealed class TriggerOnSignalReceivedComponent : Component { } }
space-wizards/space-station-14
Content.Server/MachineLinking/Components/TriggerOnSignalReceivedComponent.cs
C#
mit
197
module Softlayer module Container module Dns autoload :Domain, 'softlayer/container/dns/domain' end end end
zertico/softlayer
lib/softlayer/container/dns.rb
Ruby
mit
126
<aside class="main-sidebar"> <section class="sidebar"> <div class="user-panel"> <div class="pull-left image"> <img src="<?php echo base_url() ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <div class="pull-left info"> <p>Alexander Pierce</p> <i class="fa fa-circle text-success"></i> Online </div> </div> <!-- sidebar menu: : style can be found in sidebar.less --> <ul class="sidebar-menu"> <li class="treeview"> <a href="#"> <i class="fa fa-users"></i> <span>Funcionarios</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="<?php echo base_url()?>funcionarios/Index/registroFuncionarios"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="<?php echo base_url()?>funcionarios/Index/listadoFuncionarios"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-cogs"></i> <span>Cuentas de Usuarios</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-graduation-cap" aria-hidden="true"></i> <span>Matrícula de Párvulos</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-cubes" aria-hidden="true"></i> <span>Niveles Jardín</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="<?php echo base_url() ?>niveles/Index/crearNivel"><i class="fa fa-circle-o text-aqua"></i> Registrar Niveles Jardín</a></li> <li><a href="<?php echo base_url() ?>niveles/Index/crearNivelAnual"><i class="fa fa-circle-o text-aqua"></i> Crear Niveles Anuales</a></li> <li><a href="<?php echo base_url() ?>niveles/Index/armarNivelAnual"><i class="fa fa-circle-o text-aqua"></i> Armar Niveles</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Niveles</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-book" aria-hidden="true"></i> <span>Unidades de Contenido</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-laptop" aria-hidden="true"></i> <span>Planific. Educadora</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-bar-chart" aria-hidden="true"></i> <span>Reportes</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-question-circle" aria-hidden="true"></i> <span>Ayuda</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> </ul> </section> </aside>
codenous/intranet_planEvalWeb
application/views/template/sidebar.php
PHP
mit
5,929
package com.agileEAP.workflow.definition; /** 活动类型 */ public enum ActivityType { /** 开始活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("开始活动")] StartActivity(1), /** 人工活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("人工活动")] ManualActivity(2), /** 路由活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("路由活动")] RouterActivity(3), /** 子流程活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("子流程活动")] SubflowActivity(4), /** 自动活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("自动活动")] AutoActivity(5), /** 结束活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("结束活动")] EndActivity(6), /** 处理活动 */ //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("处理活动")] ProcessActivity(7); private int intValue; private static java.util.HashMap<Integer, ActivityType> mappings; private synchronized static java.util.HashMap<Integer, ActivityType> getMappings() { if (mappings == null) { mappings = new java.util.HashMap<Integer, ActivityType>(); } return mappings; } private ActivityType(int value) { intValue = value; ActivityType.getMappings().put(value, this); } public int getValue() { return intValue; } public static ActivityType forValue(int value) { return getMappings().get(value); } }
AgileEAP/aglieEAP
agileEAP-workflow/src/main/java/com/agileEAP/workflow/definition/ActivityType.java
Java
mit
1,812
<?xml version="1.0" ?><!DOCTYPE TS><TS language="uk" version="2.0"> <defaumlcodec>UTF-8</defaumlcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Menlocoin</source> <translation>Про Menlocoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Menlocoin&lt;/b&gt; version</source> <translation>Версія &lt;b&gt;Menlocoin&apos;a&lt;b&gt;</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Це програмне забезпечення є експериментальним. Поширюється за ліцензією MIT/X11, додаткова інформація міститься у файлі COPYING, а також за адресою http://www.opensource.org/licenses/mit-license.php. Цей продукт включає в себе програмне забезпечення, розроблене в рамках проекту OpenSSL (http://www.openssl.org/), криптографічне програмне забезпечення, написане Еріком Янгом (eay@cryptsoft.com), та функції для роботи з UPnP, написані Томасом Бернардом.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Авторське право</translation> </message> <message> <location line="+0"/> <source>The Menlocoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Адресна книга</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Двічі клікніть на адресу чи назву для їх зміни</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Створити нову адресу</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Копіювати виділену адресу в буфер обміну</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Створити адресу</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Menlocoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Це ваші адреси для отримання платежів. Ви можете давати різні адреси різним людям, таким чином маючи можливість відслідкувати хто конкретно і скільки вам заплатив.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Скопіювати адресу</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Показати QR-&amp;Код</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Menlocoin address</source> <translation>Підпишіть повідомлення щоб довести, що ви є власником цієї адреси</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Вилучити вибрані адреси з переліку</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Експортувати дані з поточної вкладки в файл</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Menlocoin address</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Menlocoin-адресою</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Видалити</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Menlocoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Скопіювати &amp;мітку</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Редагувати</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Експортувати адресну книгу</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Файли відділені комами (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Помилка при експортуванні</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Неможливо записати у файл %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Назва</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(немає назви)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Діалог введення паролю</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Введіть пароль</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Новий пароль</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Повторіть пароль</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Введіть новий пароль для гаманця.&lt;br/&gt;Будь ласка, використовуйте паролі що містять &lt;b&gt;як мінімум 10 випадкових символів&lt;/b&gt;, або &lt;b&gt;як мінімум 8 слів&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Зашифрувати гаманець</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ця операція потребує пароль для розблокування гаманця.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Розблокувати гаманець</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ця операція потребує пароль для дешифрування гаманця.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Дешифрувати гаманець</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Змінити пароль</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Ввести старий та новий паролі для гаманця.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Підтвердити шифрування гаманця</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>УВАГА: Якщо ви зашифруєте гаманець і забудете пароль, ви &lt;b&gt;ВТРАТИТЕ ВСІ СВОЇ БІТКОІНИ&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Ви дійсно хочете зашифрувати свій гаманець?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Увага: Ввімкнено Caps Lock!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Гаманець зашифровано</translation> </message> <message> <location line="-56"/> <source>Menlocoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your menlocoins from being stolen by malware infecting your computer.</source> <translation>Біткоін-клієнт буде закрито для завершення процесу шифрування. Пам&apos;ятайте, що шифрування гаманця не може повністю захистити ваші біткоіни від крадіжки, у випадку якщо ваш комп&apos;ютер буде інфіковано шкідливими програмами.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Не вдалося зашифрувати гаманець</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Виникла помилка під час шифрування гаманця. Ваш гаманець не було зашифровано.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Введені паролі не співпадають.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Не вдалося розблокувати гаманець</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Введений пароль є невірним.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Не вдалося розшифрувати гаманець</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Пароль було успішно змінено.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Підписати повідомлення...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Синхронізація з мережею...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Огляд</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Показати загальний огляд гаманця</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>Транзакції</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Переглянути історію транзакцій</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Редагувати список збережених адрес та міток</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Показати список адрес для отримання платежів</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Вихід</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Вийти</translation> </message> <message> <location line="+4"/> <source>Show information about Menlocoin</source> <translation>Показати інформацію про Menlocoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>&amp;Про Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Показати інформацію про Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Параметри...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Шифрування гаманця...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Резервне копіювання гаманця...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Змінити парол&amp;ь...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Імпорт блоків з диску...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Menlocoin address</source> <translation>Відправити монети на вказану адресу</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Menlocoin</source> <translation>Редагувати параметри</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Резервне копіювання гаманця в інше місце</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Змінити пароль, який використовується для шифрування гаманця</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Вікно зневадження</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Відкрити консоль зневадження і діагностики</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>Перевірити повідомлення...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Menlocoin</source> <translation>Menlocoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Гаманець</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Menlocoin</source> <translation>&amp;Про Menlocoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Показати / Приховати</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Показує або приховує головне вікно</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Menlocoin addresses to prove you own them</source> <translation>Підтвердіть, що Ви є власником повідомлення підписавши його Вашою Menlocoin-адресою </translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Menlocoin addresses</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Menlocoin-адресою</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Файл</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Налаштування</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Довідка</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Панель вкладок</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[тестова мережа]</translation> </message> <message> <location line="+47"/> <source>Menlocoin client</source> <translation>Menlocoin-клієнт</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Menlocoin network</source> <translation><numerusform>%n активне з&apos;єднання з мережею</numerusform><numerusform>%n активні з&apos;єднання з мережею</numerusform><numerusform>%n активних з&apos;єднань з мережею</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Оброблено %1 блоків історії транзакцій.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Помилка</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Увага</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Інформація</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Синхронізовано</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Синхронізується...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Підтвердити комісію</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Надіслані транзакції</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Отримані перекази</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Дата: %1 Кількість: %2 Тип: %3 Адреса: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Обробка URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Menlocoin address or malformed URI parameters.</source> <translation>Неможливо обробити URI! Це може бути викликано неправильною Menlocoin-адресою, чи невірними параметрами URI.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>&lt;b&gt;Зашифрований&lt;/b&gt; гаманець &lt;b&gt;розблоковано&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>&lt;b&gt;Зашифрований&lt;/b&gt; гаманець &lt;b&gt;заблоковано&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Menlocoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Сповіщення мережі</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Редагувати адресу</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Мітка</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Мітка, пов&apos;язана з цим записом адресної книги</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Адреса</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Адреса, пов&apos;язана з цим записом адресної книги. Може бути змінено тільки для адреси відправника.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Нова адреса для отримання</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Нова адреса для відправлення</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Редагувати адресу для отримання</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Редагувати адресу для відправлення</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Введена адреса «%1» вже присутня в адресній книзі.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Menlocoin address.</source> <translation>Введена адреса «%1» не є коректною адресою в мережі Menlocoin.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Неможливо розблокувати гаманець.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Не вдалося згенерувати нові ключі.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Menlocoin-Qt</source> <translation>Menlocoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>версія</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Використання:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>параметри командного рядка</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Параметри інтерфейсу</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Встановлення мови, наприклад &quot;de_DE&quot; (типово: системна)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Запускати згорнутим</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Показувати заставку під час запуску (типово: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Параметри</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Головні</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Заплатити комісі&amp;ю</translation> </message> <message> <location line="+31"/> <source>Automatically start Menlocoin after logging in to the system.</source> <translation>Автоматично запускати гаманець при вході до системи.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Menlocoin on system login</source> <translation>&amp;Запускати гаманець при вході в систему</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Скинути всі параметри клієнта на типові.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>Скинути параметри</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Мережа</translation> </message> <message> <location line="+6"/> <source>Automatically open the Menlocoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Автоматично відкривати порт для клієнту біткоін на роутері. Працює лише якщо ваш роутер підтримує UPnP і ця функція увімкнена.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Відображення порту через &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Menlocoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Підключатись до мережі Menlocoin через SOCKS-проксі (наприклад при використанні Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>Підключатись через &amp;SOCKS-проксі:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP проксі:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-адреса проксі-сервера (наприклад 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Порт:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Порт проксі-сервера (наприклад 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS версії:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Версія SOCKS-проксі (наприклад 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Вікно</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Показувати лише іконку в треї після згортання вікна.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>Мінімізувати &amp;у трей</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Згортати замість закриття. Якщо ця опція включена, програма закриється лише після вибору відповідного пункту в меню.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Згортати замість закритт&amp;я</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Відображення</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Мова інтерфейсу користувача:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Menlocoin.</source> <translation>Встановлює мову інтерфейсу. Зміни набудуть чинності після перезапуску Menlocoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>В&amp;имірювати монети в:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Виберіть одиницю вимірювання монет, яка буде відображатись в гаманці та при відправленні.</translation> </message> <message> <location line="+9"/> <source>Whether to show Menlocoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Відображати адресу в списку транзакцій</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Гаразд</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Скасувати</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Застосувати</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>типово</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Підтвердження скидання параметрів</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Деякі параметри потребують перезапуск клієнта для набуття чинності.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Продовжувати?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Увага</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Menlocoin.</source> <translation>Цей параметр набуде чинності після перезапуску Menlocoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Невірно вказано адресу проксі.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Menlocoin network after a connection is established, but this process has not completed yet.</source> <translation>Показана інформація вже може бути застарілою. Ваш гаманець буде автоматично синхронізовано з мережею Menlocoin після встановлення підключення, але цей процес ще не завершено.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Баланс:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Непідтверджені:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Гаманець</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Недавні транзакції&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Ваш поточний баланс</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Загальна сума всіх транзакцій, які ще не підтверджені, та до цих пір не враховуються в загальному балансі</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>не синхронізовано</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start menlocoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Діалог QR-коду</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Запросити Платіж</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Кількість:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Мітка:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Повідомлення:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Зберегти як...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Помилка при кодуванні URI в QR-код.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Невірно введено кількість, будь ласка, перевірте.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Кінцевий URI занадто довгий, спробуйте зменшити текст для мітки / повідомлення.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Зберегти QR-код</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG-зображення (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Назва клієнту</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>Н/Д</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Версія клієнту</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Інформація</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Використовується OpenSSL версії</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation>Мережа</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Кількість підключень</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>В тестовій мережі</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Поточне число блоків</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>Відкрити</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Параметри командного рядка</translation> </message> <message> <location line="+7"/> <source>Show the Menlocoin-Qt help message to get a list with possible Menlocoin command-line options.</source> <translation>Показати довідку Menlocoin-Qt для отримання переліку можливих параметрів командного рядка.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>Показати</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>Консоль</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Дата збирання</translation> </message> <message> <location line="-104"/> <source>Menlocoin - Debug window</source> <translation>Menlocoin - Вікно зневадження</translation> </message> <message> <location line="+25"/> <source>Menlocoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Файл звіту зневадження</translation> </message> <message> <location line="+7"/> <source>Open the Menlocoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Очистити консоль</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Menlocoin RPC console.</source> <translation>Вітаємо у консолі Menlocoin RPC.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Використовуйте стрілки вгору вниз для навігації по історії, і &lt;b&gt;Ctrl-L&lt;/b&gt; для очищення екрана.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Наберіть &lt;b&gt;help&lt;/b&gt; для перегляду доступних команд.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Відправити</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Відправити на декілька адрес</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Дод&amp;ати одержувача</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Видалити всі поля транзакції</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Очистити &amp;все</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Баланс:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Підтвердити відправлення</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Відправити</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; адресату %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Підтвердіть відправлення</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Ви впевнені що хочете відправити %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> і </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Адреса отримувача невірна, будь ласка перепровірте.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Кількість монет для відправлення повинна бути більшою 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Кількість монет для відправлення перевищує ваш баланс.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Сума перевищить ваш баланс, якщо комісія %1 буде додана до вашої транзакції.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Знайдено адресу що дублюється. Відправлення на кожну адресу дозволяється лише один раз на кожну операцію переказу.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Помилка: Не вдалося створити транзакцію!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Помилка: транзакцію було відхилено. Це може статись, якщо декілька монет з вашого гаманця вже використані, наприклад, якщо ви використовуєте одну копію гаманця (wallet.dat), а монети були використані з іншої копії, але не позначені як використані в цій.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Кількість:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Отримувач:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Введіть мітку для цієї адреси для додавання її в адресну книгу</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Мітка:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Вибрати адресу з адресної книги</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Вставити адресу</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Видалити цього отримувача</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Menlocoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу Menlocoin (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Підписи - Підпис / Перевірка повідомлення</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу Menlocoin (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Вибрати адресу з адресної книги</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Вставити адресу</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Введіть повідомлення, яке ви хочете підписати тут</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Підпис</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Копіювати поточну сигнатуру до системного буферу обміну</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Menlocoin address</source> <translation>Підпишіть повідомлення щоб довести, що ви є власником цієї адреси</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Скинути всі поля підпису повідомлення</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Очистити &amp;все</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу Menlocoin (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Menlocoin address</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Menlocoin-адресою</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Скинути всі поля перевірки повідомлення</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Menlocoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу Menlocoin (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Натисніть кнопку «Підписати повідомлення», для отримання підпису</translation> </message> <message> <location line="+3"/> <source>Enter Menlocoin signature</source> <translation>Введіть сигнатуру Menlocoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Введена нечинна адреса.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Будь ласка, перевірте адресу та спробуйте ще.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Не вдалося підписати повідомлення.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Повідомлення підписано.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Підпис не можливо декодувати.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Будь ласка, перевірте підпис та спробуйте ще.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Не вдалося перевірити повідомлення.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Повідомлення перевірено.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Menlocoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[тестова мережа]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Відкрити до %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/поза інтернетом</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/не підтверджено</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 підтверджень</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Статус</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Згенеровано</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Відправник</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Отримувач</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>Мітка</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Кредит</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>не прийнято</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Дебет</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Комісія за транзакцію</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Загальна сума</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Повідомлення</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Коментар</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID транзакції</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Після генерації монет, потрібно зачекати 120 блоків, перш ніж їх можна буде використати. Коли ви згенерували цей блок, його було відправлено в мережу для того, щоб він був доданий до ланцюжка блоків. Якщо ця процедура не вдасться, статус буде змінено на «не підтверджено» і ви не зможете потратити згенеровані монету. Таке може статись, якщо хтось інший згенерував блок на декілька секунд раніше.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Транзакція</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Кількість</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>true</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>false</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ще не було успішно розіслано</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>невідомий</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Деталі транзакції</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Даний діалог показує детальну статистику по вибраній транзакції</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Кількість</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Відкрити до %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Поза інтернетом (%1 підтверджень)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Непідтверджено (%1 із %2 підтверджень)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Підтверджено (%1 підтверджень)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Цей блок не був отриманий жодними іншими вузлами і, ймовірно, не буде прийнятий!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Згенеровано, але не підтверджено</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Отримано</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Отримано від</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Відправлено</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Відправлено собі</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Добуто</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(недоступно)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Статус транзакції. Наведіть вказівник на це поле, щоб показати кількість підтверджень.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Дата і час, коли транзакцію було отримано.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Тип транзакції.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Адреса отримувача транзакції.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Сума, додана чи знята з балансу.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Всі</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Сьогодні</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>На цьому тижні</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>На цьому місяці</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Минулого місяця</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Цього року</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Проміжок...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Отримані на</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Відправлені на</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Відправлені собі</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Добуті</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Інше</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Введіть адресу чи мітку для пошуку</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Мінімальна сума</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Скопіювати адресу</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Скопіювати мітку</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Копіювати кількість</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Редагувати мітку</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Показати деталі транзакції</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Експортувати дані транзакцій</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Файли, розділені комою (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Підтверджені</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Мітка</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Кількість</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>Ідентифікатор</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Помилка експорту</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Неможливо записати у файл %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Діапазон від:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>до</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Відправити</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Експортувати дані з поточної вкладки в файл</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Виникла помилка при спробі зберегти гаманець в новому місці.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Успішне створення резервної копії</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Данні гаманця успішно збережено в новому місці призначення.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Menlocoin version</source> <translation>Версія</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Використання:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or menlocoind</source> <translation>Відправити команду серверу -server чи демону</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Список команд</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Отримати довідку по команді</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Параметри:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: menlocoin.conf)</source> <translation>Вкажіть файл конфігурації (типово: menlocoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: menlocoind.pid)</source> <translation>Вкажіть pid-файл (типово: menlocoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Вкажіть робочий каталог</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Встановити розмір кешу бази даних в мегабайтах (типово: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Чекати на з&apos;єднання на &lt;port&gt; (типово: 9333 або тестова мережа: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Підтримувати не більше &lt;n&gt; зв&apos;язків з колегами (типово: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Поріг відключення неправильно під&apos;єднаних пірів (типово: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Максимальній розмір вхідного буферу на одне з&apos;єднання (типово: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Прослуховувати &lt;port&gt; для JSON-RPC-з&apos;єднань (типово: 9332 або тестова мережа: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Приймати команди із командного рядка та команди JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Запустити в фоновому режимі (як демон) та приймати команди</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Використовувати тестову мережу</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=menlocoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Menlocoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Menlocoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Помилка: транзакцію було відхилено. Це може статись, якщо декілька монет з вашого гаманця вже використані, наприклад, якщо ви використовуєте одну копію гаманця (wallet.dat), а монети були використані з іншої копії, але не позначені як використані в цій.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Увага: встановлено занадто велику комісію (-paytxfee). Комісія зніматиметься кожен раз коли ви проводитимете транзакції.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Menlocoin will not work properly.</source> <translation>Увага: будь ласка, перевірте дату і час на своєму комп&apos;ютері. Якщо ваш годинник йде неправильно, Menlocoin може працювати некоректно.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Увага: помилка читання wallet.dat! Всі ключі прочитано коректно, але дані транзакцій чи записи адресної книги можуть бути пропущені, або пошкоджені.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Увага: файл wallet.dat пошкоджено, дані врятовано! Оригінальний wallet.dat збережено як wallet.{timestamp}.bak до %s; якщо Ваш баланс чи транзакції неправильні, Ви можете відновити їх з резервної копії. </translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Спроба відновити закриті ключі з пошкодженого wallet.dat</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Підключитись лише до вказаного вузла</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Помилка ініціалізації бази даних блоків</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Помилка завантаження бази даних блоків</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Помилка: Мало вільного місця на диску!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Помилка: Гаманець заблокований, неможливо створити транзакцію!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Помилка: системна помилка: </translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Скільки блоків перевіряти під час запуску (типово: 288, 0 = всі)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Імпорт блоків з зовнішнього файлу blk000??.dat</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>Інформація</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Помилка в адресі -tor: «%s»</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Максимальний буфер, &lt;n&gt;*1000 байт (типово: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Максимальній розмір вихідного буферу на одне з&apos;єднання, &lt;n&gt;*1000 байт (типово: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Виводити більше налагоджувальної інформації. Мається на увазі всі шнші -debug* параметри</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Доповнювати налагоджувальний вивід відміткою часу</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Menlocoin Wiki for SSL setup instructions)</source> <translation>Параметри SSL: (див. Menlocoin Wiki для налаштування SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Вибір версії socks-проксі для використання (4-5, типово: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Відсилати налагоджувальну інформацію на консоль, а не у файл debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Відсилати налагоджувальну інформацію до налагоджувача</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Встановити максимальний розмір блоку у байтах (типово: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Встановити мінімальний розмір блоку у байтах (типово: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Стискати файл debug.log під час старту клієнта (типово: 1 коли відсутутній параметр -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Вказати тайм-аут підключення у мілісекундах (типово: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Системна помилка: </translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Намагатись використовувати UPnP для відображення порту, що прослуховується на роутері (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Намагатись використовувати UPnP для відображення порту, що прослуховується на роутері (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Ім&apos;я користувача для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Попередження</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Увага: Поточна версія застаріла, необхідне оновлення!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat пошкоджено, відновлення не вдалося</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Пароль для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Дозволити JSON-RPC-з&apos;єднання з вказаної IP-адреси</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Відправляти команди на вузол, запущений на &lt;ip&gt; (типово: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Модернізувати гаманець до останнього формату</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Встановити розмір пулу ключів &lt;n&gt; (типово: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Пересканувати ланцюжок блоків, в пошуку втрачених транзакцій</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Використовувати OpenSSL (https) для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Файл сертифіката сервера (типово: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Закритий ключ сервера (типово: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Допустимі шифри (типово: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Дана довідка</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Неможливо прив&apos;язати до порту %s на цьому комп&apos;ютері (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Підключитись через SOCKS-проксі</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Дозволити пошук в DNS для команд -addnode, -seednode та -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Завантаження адрес...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Помилка при завантаженні wallet.dat: Гаманець пошкоджено</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Menlocoin</source> <translation>Помилка при завантаженні wallet.dat: Гаманець потребує новішої версії Біткоін-клієнта</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Menlocoin to complete</source> <translation>Потрібно перезаписати гаманець: перезапустіть Біткоін-клієнт для завершення</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Помилка при завантаженні wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Помилка в адресі проксі-сервера: «%s»</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Невідома мережа вказана в -onlynet: «%s»</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Помилка у величині комісії -paytxfee=&lt;amount&gt;: «%s»</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Некоректна кількість</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Недостатньо коштів</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Завантаження індексу блоків...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Додати вузол до підключення і лишити його відкритим</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Menlocoin is probably already running.</source> <translation>Неможливо прив&apos;язати до порту %s на цьому комп&apos;ютері. Можливо гаманець вже запущено.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Комісія за КБ</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Завантаження гаманця...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Неможливо записати типову адресу</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Сканування...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Завантаження завершене</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>Помилка</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Ви мусите встановити rpcpassword=&lt;password&gt; в файлі конфігурації: %s Якщо файл не існує, створіть його із правами тільки для читання власником (owner-readable-only).</translation> </message> </context> </TS>
iLoftis/Menlo-Coin
src/qt/locale/bitcoin_uk.ts
TypeScript
mit
123,486
package com.asayama.rps.simulator; public enum Hand { ROCK, PAPER, SCISSORS; }
kyoken74/rock-paper-scissors
src/main/java/com/asayama/rps/simulator/Hand.java
Java
mit
83
package foodtruck.linxup; import java.util.List; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.joda.time.DateTime; import foodtruck.model.Location; /** * @author aviolette * @since 11/1/16 */ public class Trip { private Location start; private Location end; private DateTime startTime; private DateTime endTime; private List<Position> positions; private Trip(Builder builder) { this.start = builder.start; this.end = builder.end; this.startTime = builder.startTime; this.endTime = builder.endTime; this.positions = ImmutableList.copyOf(builder.positions); } public static Builder builder() { return new Builder(); } public static Builder builder(Trip instance) { return new Builder(instance); } public String getName() { return start.getShortenedName() + " to " + end.getShortenedName(); } public Location getStart() { return start; } public Location getEnd() { return end; } public DateTime getStartTime() { return startTime; } public DateTime getEndTime() { return endTime; } public List<Position> getPositions() { return positions; } @Override public String toString() { return MoreObjects.toStringHelper(this) // .add("start", start) // .add("end", end) .add("startTime", startTime) .add("endTime", endTime) .toString(); } public static class Builder { private Location start; private Location end; private DateTime startTime; private DateTime endTime; private List<Position> positions = Lists.newLinkedList(); public Builder() { } public Builder(Trip instance) { this.start = instance.start; this.end = instance.end; this.startTime = instance.startTime; this.endTime = instance.endTime; this.positions = instance.positions; } public Builder start(Location start) { this.start = start; return this; } public Builder end(Location end) { this.end = end; return this; } public Builder startTime(DateTime startTime) { this.startTime = startTime; return this; } public Builder endTime(DateTime endTime) { this.endTime = endTime; return this; } public Trip build() { return new Trip(this); } public DateTime getStartTime() { return startTime; } public DateTime getEndTime() { return endTime; } public Builder addPosition(Position position) { positions.add(position); return this; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("start", start.getShortenedName()) .add("end", end.getShortenedName()) // .add("start", start) // .add("end", end) .add("startTime", startTime) .add("endTime", endTime) .toString(); } } }
aviolette/foodtrucklocator
main/src/main/java/foodtruck/linxup/Trip.java
Java
mit
3,020
/** * Copyright (c) 2015, Alexander Orzechowski. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Currently in beta stage. Changes can and will be made to the core mechanic * making this not backwards compatible. * * Github: https://github.com/Need4Speed402/tessellator */ Tessellator.TextureDummy = function (ready){ this.super(null); if (ready){ this.setReady(); }; }; Tessellator.extend(Tessellator.TextureDummy, Tessellator.Texture); Tessellator.TextureDummy.prototype.configure = Tessellator.EMPTY_FUNC; Tessellator.TextureDummy.prototype.bind = Tessellator.EMPTY_FUNC;
Need4Speed402/tessellator
src/textures/TextureDummy.js
JavaScript
mit
1,646
#include "Extensions.hpp" #include "Extensions.inl" #include <Math/Rect.hpp> #include <Math/Vector.hpp> #include <Script/ScriptExtensions.hpp> #include <SFML/Graphics/CircleShape.hpp> #include <angelscript.h> #include <cassert> namespace { void create_CircleShape(void* memory) { new(memory)sf::CircleShape(); } void create_CircleShape_rad(float radius, unsigned int count, void* memory) { new(memory)sf::CircleShape(radius, count); } bool Reg() { Script::ScriptExtensions::AddExtension([](asIScriptEngine* eng) { int r = 0; r = eng->SetDefaultNamespace("Shapes"); assert(r >= 0); r = eng->RegisterObjectType("Circle", sizeof(sf::CircleShape), asOBJ_VALUE | asGetTypeTraits<sf::CircleShape>()); assert(r >= 0); r = eng->RegisterObjectBehaviour("Circle", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(create_CircleShape), asCALL_CDECL_OBJLAST); assert(r >= 0); r = eng->RegisterObjectBehaviour("Circle", asBEHAVE_CONSTRUCT, "void f(float,uint=30)", asFUNCTION(create_CircleShape_rad), asCALL_CDECL_OBJLAST); assert(r >= 0); r = eng->RegisterObjectMethod("Circle", "void set_PointCount(uint)", asMETHOD(sf::CircleShape, setPointCount), asCALL_THISCALL); assert(r >= 0); r = eng->RegisterObjectMethod("Circle", "float get_Radius()", asMETHOD(sf::CircleShape, getRadius), asCALL_THISCALL); assert(r >= 0); r = eng->RegisterObjectMethod("Circle", "void set_Radius(float)", asMETHOD(sf::CircleShape, setRadius), asCALL_THISCALL); assert(r >= 0); Script::SFML::registerShape<sf::CircleShape>("Circle", eng); r = eng->SetDefaultNamespace(""); assert(r >= 0); }, 6); return true; } } bool Script::SFML::Extensions::CircleShape = Reg();
ace13/LD31
Source/Script/SFML/CircleShape.cpp
C++
mit
1,833
'use strict'; module.exports = function(sequelize, DataTypes) { var Student = sequelize.define('Student', { name: DataTypes.STRING, timeReq: DataTypes.INTEGER, }, { classMethods: { associate: function() { } } }); return Student; };
troops2devs/minutes
models/student.js
JavaScript
mit
268
module Culqi VERSION = '1.2.8' end
augustosamame/culqiruby
lib/culqi/version.rb
Ruby
mit
37
#include <CImageLibI.h> #include <CImageColorDefP.h> #include <cstring> bool CImageColorDef:: getRGB(const std::string &name, double *r, double *g, double *b) { int ri, gi, bi; if (! getRGBI(name, &ri, &gi, &bi)) return false; double rgb_scale = 1.0/255.0; *r = ri*rgb_scale; *g = gi*rgb_scale; *b = bi*rgb_scale; return true; } bool CImageColorDef:: getRGBI(const std::string &name, int *r, int *g, int *b) { int i; std::string lname = CStrUtil::toLower(name); const char *name1 = lname.c_str(); for (i = 0; color_def_data[i].name != 0; ++i) if (strcmp(color_def_data[i].name, name1) == 0) break; if (color_def_data[i].name == 0) return false; *r = color_def_data[i].r; *g = color_def_data[i].g; *b = color_def_data[i].b; return true; }
colinw7/CImageLib
src/CImageColorDef.cpp
C++
mit
801
const {xObjectForm} = require('./xObjectForm'); exports._getPathOptions = function _getPathOptions(options = {}, originX, originY) { this.current = this.current || {}; const colorspace = options.colorspace || this.options.colorspace; const colorName = options.colorName; const pathOptions = { originX, originY, font: this._getFont(options), size: options.size || this.current.defaultFontSize, charSpace: options.charSpace || 0, underline: false, color: this._transformColor(options.color, {colorspace:colorspace, colorName:options.colorName}), colorspace, colorName, colorArray: [], lineCap: this._lineCap(), lineJoin: this._lineJoin(), miterLimit: 1.414, width: 2, align: options.align }; if (options.opacity == void(0) || isNaN(options.opacity)) { options.opacity = 1; } else { options.opacity = (options.opacity < 0) ? 0 : (options.opacity > 1) ? 1 : options.opacity; } pathOptions.opacity = options.opacity; const extGStates = this._createExtGStates(options.opacity); pathOptions.strokeGsId = extGStates.stroke; pathOptions.fillGsId = extGStates.fill; if (options.size || options.fontSize) { const size = options.size || options.fontSize; if (!isNaN(size)) { pathOptions.size = (size <= 0) ? 1 : size; } } if (options.width || options.lineWidth) { const width = options.width || options.lineWidth; if (!isNaN(width)) { pathOptions.width = (width <= 0) ? 1 : width; } } const colorOpts = {colorspace:colorspace, wantColorModel:true, colorName: options.colorName}; if (options.stroke) { pathOptions.strokeModel = this._transformColor(options.stroke, colorOpts); pathOptions.stroke = pathOptions.strokeModel.color; } if (options.fill) { pathOptions.fillModel = this._transformColor(options.fill, colorOpts); pathOptions.fill = pathOptions.fillModel.color; } pathOptions.colorModel = this._transformColor((options.color || options.colour), colorOpts); pathOptions.color = pathOptions.colorModel.color; pathOptions.colorspace = pathOptions.colorModel.colorspace; // rotation if (options.rotation !== void(0)) { const rotation = parseFloat(options.rotation); pathOptions.rotation = rotation; pathOptions.rotationOrigin = options.rotationOrigin || null; } // skew if (options.skewX !== void(0)) { pathOptions.skewX = options.skewX; } if (options.skewY != void(0)) { pathOptions.skewY = options.skewY; } // Page 127 of PDF 1.7 specification pathOptions.dash = (Array.isArray(options.dash)) ? options.dash : []; pathOptions.dashPhase = (!isNaN(options.dashPhase)) ? options.dashPhase : 0; if (pathOptions.dash[0] == 0 && pathOptions.dash[1] == 0) { pathOptions.dash = []; // no dash, solid unbroken line pathOptions.dashPhase = 0; } // Page 125-126 of PDF 1.7 specification if (options.lineJoin !== void(0)) { pathOptions.lineJoin = this._lineJoin(options.lineJoin); } if (options.lineCap !== void(0)) { pathOptions.lineCap = this._lineCap(options.lineCap); } if (options.miterLimit !== void(0)) { if (!isNaN(options.miterLimit)) { pathOptions.miterLimit = options.miterLimit; } } return pathOptions; }; exports._getDistance = function _getDistance(coordA, coordB) { const disX = Math.abs(coordB[0] - coordA[0]); const disY = Math.abs(coordB[1] - coordB[1]); const distance = Math.sqrt(((disX * disX) + (disY * disY))); return distance; }; exports._getTransformParams = getTransformParams; function getTransformParams(inAngle, x, y, offsetX, offsetY) { const theta = toRadians(inAngle); const cosTheta = Math.cos(theta); const sinTheta = Math.sin(theta); const nx = (cosTheta * -offsetX) + (sinTheta * -offsetY); const ny = (cosTheta * -offsetY) - (sinTheta * -offsetX); return [cosTheta, -sinTheta, sinTheta, cosTheta, x - nx, y - ny]; } exports._setRotationContext = function _setRotationTransform(context, x, y, options) { const deltaY = (options.deltaY) ? options.deltaY : 0; if (options.rotation === undefined || options.rotation === 0) { context.cm(1, 0, 0, 1, x, y-deltaY); // no rotation } else { let rotationOrigin; if (!hasRotation(options)) { rotationOrigin = [options.originX, options.originY]; // supply default } else { if (options.useGivenCoords) { rotationOrigin = options.rotationOrigin; } else { const orig = this._calibrateCoordinate(options.rotationOrigin[0], options.rotationOrigin[1]); rotationOrigin = [orig.nx, orig.ny]; } } const rm = getTransformParams( // rotation matrix options.rotation, rotationOrigin[0], rotationOrigin[1], x - rotationOrigin[0], y - rotationOrigin[1] - deltaY ); context.cm(rm[0], rm[1], rm[2], rm[3], rm[4], rm[5]); } }; function hasRotation(options) { return options.rotationOrigin && Array.isArray(options.rotationOrigin) && options.rotationOrigin.length === 2; } function toRadians(angle) { return 2 * Math.PI * ((angle % 360) / 360); } function getSkewTransform(skewXAngle= 0 , skewYAngle = 0) { const alpha = toRadians(skewXAngle); const beta = toRadians(skewYAngle); const tanAlpha = Math.tan(alpha); const tanBeta = Math.tan(beta); return [1, tanAlpha, tanBeta, 1, 0, 0]; } exports._setSkewContext = function _setSkewTransform(context, options) { if (options.skewX || options.skewY) { const sm = getSkewTransform(options.skewX, options.skewY); context.cm(sm[0], sm[1], sm[2], sm[3], sm[4], sm[5]); } }; exports._setScalingTransform = function _setScalingTransform(context, options) { if (options.ratio) { context.cm(options.ratio[0], 0, 0, options.ratio[1], 0, 0); } }; exports._drawObject = function _drawObject(self, x, y, width, height, options, callback) { let xObject = options.xObject; // allows caller to supply existing form object if (!xObject) { self.pauseContext(); xObject = new xObjectForm(self.writer, width, height); const xObjectCtx = xObject.getContentContext(); xObjectCtx.q(); callback(xObjectCtx, xObject); xObjectCtx.Q(); xObject.end(); self.resumeContext(); } const context = self.pageContext; context.q(); self._setRotationContext(context, x, y, options); self._setSkewContext(context, options); self._setScalingTransform(context, options); context .doXObject(xObject) .Q(); }; exports._lineCap = function _lineCap(type) { const round = 1; let cap = round; if (type) { const capStyle = ['butt', 'round', 'square']; const capType = capStyle.indexOf(type); cap = (capType !== -1) ? capType : round; } return cap; }; exports._lineJoin = function _lineJoin(type) { const round = 1; let join = round; if (type) { const joinStyle = ['miter', 'round', 'bevel']; const joinType = joinStyle.indexOf(type); join = (joinType !== -1) ? joinType : round; } return join; };
chunyenHuang/hummusRecipe
lib/vector.helper.js
JavaScript
mit
7,549
#define BOOST_TEST_MODULE test_dsu #define BOOST_TEST_DYN_LINK #include "test.hpp" #include "dsu.hpp" using bdata::make; using bdata::xrange; BOOST_AUTO_TEST_CASE(one) { auto dsu = DisjointSetUnion<int>(); dsu.push_back(1); BOOST_TEST(dsu.xs[1] == 1); BOOST_TEST(dsu.ws[1] == 1); } BOOST_AUTO_TEST_CASE(two) { auto dsu = DisjointSetUnion<int>(); dsu.push_back(1); dsu.push_back(2); BOOST_TEST(dsu.xs[1] == 1); BOOST_TEST(dsu.ws[1] == 1); BOOST_TEST(dsu.xs[2] == 2); BOOST_TEST(dsu.ws[2] == 1); } BOOST_AUTO_TEST_CASE(unite2) { auto dsu = DisjointSetUnion<int>({1, 2}); dsu.unite(1, 2); BOOST_TEST((dsu.find(1) == dsu.find(2))); } BOOST_DATA_TEST_CASE(unite_all_0, xrange(2, 256) * xrange(10), n, s) { auto xs = create_vector(n, s); auto dsu = DisjointSetUnion<int>(xs.begin(), xs.end()); for (auto i = 1; i < n; ++i) { dsu.unite(xs[0], xs[i]); } for (auto i = 1; i < n; ++i) { BOOST_TEST((dsu.find(xs[0]) == dsu.find(xs[i]))); } } BOOST_DATA_TEST_CASE(unite_all_1, xrange(2, 256) * xrange(10), n, s) { auto xs = create_vector(n, s); auto dsu = DisjointSetUnion<int>(xs.begin(), xs.end()); for (auto i = 1; i < n; ++i) { dsu.unite(xs[i - 1], xs[i]); } for (auto i = 1; i < n; ++i) { BOOST_TEST((dsu.find(xs[0]) == dsu.find(xs[i]))); } } BOOST_DATA_TEST_CASE(check_xs_ys, xrange(2, 256) * xrange(10), n, s) { auto xs = create_vector(n, s); auto ys = xs; auto engine = std::default_random_engine{}; std::shuffle(ys.begin(), ys.end(), engine); auto dsu = DisjointSetUnion<int>(xs.begin(), xs.end()); for (auto i = 0; i < n; ++i) { dsu.unite(xs[i], ys[i]); } for (auto i = 0; i < n; ++i) { BOOST_TEST((dsu.find(xs[i]) == dsu.find(ys[i]))); } }
all3fox/algos-cpp
tests/test_dsu.cpp
C++
mit
1,854
<?php namespace WebEd\Base\ThemesManagement\Actions; use WebEd\Base\Actions\AbstractAction; class EnableThemeAction extends AbstractAction { /** * @param $alias * @return array */ public function run($alias) { do_action(WEBED_THEME_BEFORE_ENABLE, $alias); $theme = get_theme_information($alias); if (!$theme) { return $this->error('Plugin not exists'); } $checkRelatedModules = check_module_require($theme); if ($checkRelatedModules['error']) { $messages = []; foreach ($checkRelatedModules['messages'] as $message) { $messages[] = $message; } return $this->error($messages); } themes_management()->enableTheme($alias); do_action(WEBED_THEME_ENABLED, $alias); modules_management()->refreshComposerAutoload(); return $this->success('Your theme has been enabled'); } }
sgsoft-studio/themes-management
src/Actions/EnableThemeAction.php
PHP
mit
971
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package models import ( "bufio" "bytes" "fmt" "html" "html/template" "io" "io/ioutil" "os" "os/exec" "strings" "github.com/Unknwon/com" "github.com/sergi/go-diff/diffmatchpatch" "golang.org/x/net/html/charset" "golang.org/x/text/transform" "github.com/gogits/git-module" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/process" ) type DiffLineType uint8 const ( DIFF_LINE_PLAIN DiffLineType = iota + 1 DIFF_LINE_ADD DIFF_LINE_DEL DIFF_LINE_SECTION ) type DiffFileType uint8 const ( DIFF_FILE_ADD DiffFileType = iota + 1 DIFF_FILE_CHANGE DIFF_FILE_DEL DIFF_FILE_RENAME ) type DiffLine struct { LeftIdx int RightIdx int Type DiffLineType Content string } func (d *DiffLine) GetType() int { return int(d.Type) } type DiffSection struct { Name string Lines []*DiffLine } var ( addedCodePrefix = []byte("<span class=\"added-code\">") removedCodePrefix = []byte("<span class=\"removed-code\">") codeTagSuffix = []byte("</span>") ) func diffToHTML(diffs []diffmatchpatch.Diff, lineType DiffLineType) template.HTML { var buf bytes.Buffer for i := range diffs { if diffs[i].Type == diffmatchpatch.DiffInsert && lineType == DIFF_LINE_ADD { buf.Write(addedCodePrefix) buf.WriteString(html.EscapeString(diffs[i].Text)) buf.Write(codeTagSuffix) } else if diffs[i].Type == diffmatchpatch.DiffDelete && lineType == DIFF_LINE_DEL { buf.Write(removedCodePrefix) buf.WriteString(html.EscapeString(diffs[i].Text)) buf.Write(codeTagSuffix) } else if diffs[i].Type == diffmatchpatch.DiffEqual { buf.WriteString(html.EscapeString(diffs[i].Text)) } } return template.HTML(buf.Bytes()) } // get an specific line by type (add or del) and file line number func (diffSection *DiffSection) GetLine(lineType DiffLineType, idx int) *DiffLine { difference := 0 for _, diffLine := range diffSection.Lines { if diffLine.Type == DIFF_LINE_PLAIN { // get the difference of line numbers between ADD and DEL versions difference = diffLine.RightIdx - diffLine.LeftIdx continue } if lineType == DIFF_LINE_DEL { if diffLine.RightIdx == 0 && diffLine.LeftIdx == idx-difference { return diffLine } } else if lineType == DIFF_LINE_ADD { if diffLine.LeftIdx == 0 && diffLine.RightIdx == idx+difference { return diffLine } } } return nil } // computes inline diff for the given line func (diffSection *DiffSection) GetComputedInlineDiffFor(diffLine *DiffLine) template.HTML { var compareDiffLine *DiffLine var diff1, diff2 string getDefaultReturn := func() template.HTML { return template.HTML(html.EscapeString(diffLine.Content[1:])) } // just compute diff for adds and removes if diffLine.Type != DIFF_LINE_ADD && diffLine.Type != DIFF_LINE_DEL { return getDefaultReturn() } // try to find equivalent diff line. ignore, otherwise if diffLine.Type == DIFF_LINE_ADD { compareDiffLine = diffSection.GetLine(DIFF_LINE_DEL, diffLine.RightIdx) if compareDiffLine == nil { return getDefaultReturn() } diff1 = compareDiffLine.Content diff2 = diffLine.Content } else { compareDiffLine = diffSection.GetLine(DIFF_LINE_ADD, diffLine.LeftIdx) if compareDiffLine == nil { return getDefaultReturn() } diff1 = diffLine.Content diff2 = compareDiffLine.Content } dmp := diffmatchpatch.New() diffRecord := dmp.DiffMain(diff1[1:], diff2[1:], true) diffRecord = dmp.DiffCleanupSemantic(diffRecord) return diffToHTML(diffRecord, diffLine.Type) } type DiffFile struct { Name string OldName string Index int Addition, Deletion int Type DiffFileType IsCreated bool IsDeleted bool IsBin bool IsRenamed bool Sections []*DiffSection } func (diffFile *DiffFile) GetType() int { return int(diffFile.Type) } type Diff struct { TotalAddition, TotalDeletion int Files []*DiffFile } func (diff *Diff) NumFiles() int { return len(diff.Files) } const DIFF_HEAD = "diff --git " func ParsePatch(maxlines int, reader io.Reader) (*Diff, error) { var ( diff = &Diff{Files: make([]*DiffFile, 0)} curFile *DiffFile curSection = &DiffSection{ Lines: make([]*DiffLine, 0, 10), } leftLine, rightLine int lineCount int ) input := bufio.NewReader(reader) isEOF := false for { if isEOF { break } line, err := input.ReadString('\n') if err != nil { if err == io.EOF { isEOF = true } else { return nil, fmt.Errorf("ReadString: %v", err) } } if len(line) > 0 && line[len(line)-1] == '\n' { // Remove line break. line = line[:len(line)-1] } if strings.HasPrefix(line, "+++ ") || strings.HasPrefix(line, "--- ") { continue } else if len(line) == 0 { continue } lineCount++ // Diff data too large, we only show the first about maxlines lines if lineCount >= maxlines { log.Warn("Diff data too large") io.Copy(ioutil.Discard, reader) diff.Files = nil return diff, nil } switch { case line[0] == ' ': diffLine := &DiffLine{Type: DIFF_LINE_PLAIN, Content: line, LeftIdx: leftLine, RightIdx: rightLine} leftLine++ rightLine++ curSection.Lines = append(curSection.Lines, diffLine) continue case line[0] == '@': curSection = &DiffSection{} curFile.Sections = append(curFile.Sections, curSection) ss := strings.Split(line, "@@") diffLine := &DiffLine{Type: DIFF_LINE_SECTION, Content: line} curSection.Lines = append(curSection.Lines, diffLine) // Parse line number. ranges := strings.Split(ss[1][1:], " ") leftLine, _ = com.StrTo(strings.Split(ranges[0], ",")[0][1:]).Int() if len(ranges) > 1 { rightLine, _ = com.StrTo(strings.Split(ranges[1], ",")[0]).Int() } else { log.Warn("Parse line number failed: %v", line) rightLine = leftLine } continue case line[0] == '+': curFile.Addition++ diff.TotalAddition++ diffLine := &DiffLine{Type: DIFF_LINE_ADD, Content: line, RightIdx: rightLine} rightLine++ curSection.Lines = append(curSection.Lines, diffLine) continue case line[0] == '-': curFile.Deletion++ diff.TotalDeletion++ diffLine := &DiffLine{Type: DIFF_LINE_DEL, Content: line, LeftIdx: leftLine} if leftLine > 0 { leftLine++ } curSection.Lines = append(curSection.Lines, diffLine) case strings.HasPrefix(line, "Binary"): curFile.IsBin = true continue } // Get new file. if strings.HasPrefix(line, DIFF_HEAD) { middle := -1 // Note: In case file name is surrounded by double quotes (it happens only in git-shell). // e.g. diff --git "a/xxx" "b/xxx" hasQuote := line[len(DIFF_HEAD)] == '"' if hasQuote { middle = strings.Index(line, ` "b/`) } else { middle = strings.Index(line, " b/") } beg := len(DIFF_HEAD) a := line[beg+2 : middle] b := line[middle+3:] if hasQuote { a = string(git.UnescapeChars([]byte(a[1 : len(a)-1]))) b = string(git.UnescapeChars([]byte(b[1 : len(b)-1]))) } curFile = &DiffFile{ Name: a, Index: len(diff.Files) + 1, Type: DIFF_FILE_CHANGE, Sections: make([]*DiffSection, 0, 10), } diff.Files = append(diff.Files, curFile) // Check file diff type. for { line, err := input.ReadString('\n') if err != nil { if err == io.EOF { isEOF = true } else { return nil, fmt.Errorf("ReadString: %v", err) } } switch { case strings.HasPrefix(line, "new file"): curFile.Type = DIFF_FILE_ADD curFile.IsCreated = true case strings.HasPrefix(line, "deleted"): curFile.Type = DIFF_FILE_DEL curFile.IsDeleted = true case strings.HasPrefix(line, "index"): curFile.Type = DIFF_FILE_CHANGE case strings.HasPrefix(line, "similarity index 100%"): curFile.Type = DIFF_FILE_RENAME curFile.IsRenamed = true curFile.OldName = curFile.Name curFile.Name = b } if curFile.Type > 0 { break } } } } // FIXME: detect encoding while parsing. var buf bytes.Buffer for _, f := range diff.Files { buf.Reset() for _, sec := range f.Sections { for _, l := range sec.Lines { buf.WriteString(l.Content) buf.WriteString("\n") } } charsetLabel, err := base.DetectEncoding(buf.Bytes()) if charsetLabel != "UTF-8" && err == nil { encoding, _ := charset.Lookup(charsetLabel) if encoding != nil { d := encoding.NewDecoder() for _, sec := range f.Sections { for _, l := range sec.Lines { if c, _, err := transform.String(d, l.Content); err == nil { l.Content = c } } } } } } return diff, nil } func GetDiffRange(repoPath, beforeCommitID string, afterCommitID string, maxlines int) (*Diff, error) { repo, err := git.OpenRepository(repoPath) if err != nil { return nil, err } commit, err := repo.GetCommit(afterCommitID) if err != nil { return nil, err } var cmd *exec.Cmd // if "after" commit given if len(beforeCommitID) == 0 { // First commit of repository. if commit.ParentCount() == 0 { cmd = exec.Command("git", "show", afterCommitID) } else { c, _ := commit.Parent(0) cmd = exec.Command("git", "diff", "-M", c.ID.String(), afterCommitID) } } else { cmd = exec.Command("git", "diff", "-M", beforeCommitID, afterCommitID) } cmd.Dir = repoPath cmd.Stderr = os.Stderr stdout, err := cmd.StdoutPipe() if err != nil { return nil, fmt.Errorf("StdoutPipe: %v", err) } if err = cmd.Start(); err != nil { return nil, fmt.Errorf("Start: %v", err) } pid := process.Add(fmt.Sprintf("GetDiffRange (%s)", repoPath), cmd) defer process.Remove(pid) diff, err := ParsePatch(maxlines, stdout) if err != nil { return nil, fmt.Errorf("ParsePatch: %v", err) } if err = cmd.Wait(); err != nil { return nil, fmt.Errorf("Wait: %v", err) } return diff, nil } func GetDiffCommit(repoPath, commitId string, maxlines int) (*Diff, error) { return GetDiffRange(repoPath, "", commitId, maxlines) }
svcavallar/gogs
models/git_diff.go
GO
mit
10,244
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe Admin::PreferencesController do dataset :users it "should allow you to view your preferences" do user = login_as(:non_admin) get :edit response.should be_success assigned_user = assigns(:user) assigned_user.should == user assigned_user.object_id.should_not == user.object_id assigned_user.email.should == 'non_admin@example.com' end it "should allow you to save your preferences" do login_as :non_admin put :update, :user => { :password => '', :password_confirmation => '', :email => 'updated@gmail.com' } user = users(:non_admin) response.should redirect_to(admin_pages_path) flash[:notice].should match(/preferences.*?updated/i) user.email.should == 'updated@gmail.com' end it "should not allow you to update your login through the preferences page" do login_as :non_admin put :update, 'user' => { :login => 'superman' } response.should be_success flash[:error].should match(/bad form data/i) end it "should allow you to change your password" do login_as :non_admin put :update, { :user => { :password => 'funtimes', :password_confirmation => 'funtimes' } } user = users(:non_admin) user.password.should == user.sha1('funtimes') rails_log.should_not match(/"password"=>"funtimes"/) rails_log.should_not match(/"password_confirmation"=>"funtimes"/) end end
dosire/dosire
spec/controllers/admin/preferences_controller_spec.rb
Ruby
mit
1,463
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. /** * This package contains the classes for AutoRestParameterGroupingTestService. * Test Infrastructure for AutoRest. */ package fixtures.azureparametergrouping;
matt-gibbs/AutoRest
AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/package-info.java
Java
mit
485
using System; using Pulse.FS; namespace Pulse.UI { public sealed class UiWpdLeafsAccessor : IUiLeafsAccessor { private readonly WpdArchiveListing _listing; private readonly WpdEntry[] _leafs; private readonly bool? _conversion; public UiNodeType Type { get { return UiNodeType.DataTable; } } public UiWpdLeafsAccessor(WpdArchiveListing listing, bool? conversion, params WpdEntry[] leafs) { _listing = listing; _leafs = leafs; _conversion = conversion; } public void Extract(IUiExtractionTarget target) { using (UiWpdExtractor extractor = new UiWpdExtractor(_listing, _leafs, _conversion, target)) extractor.Extract(); } public void Inject(IUiInjectionSource source, UiInjectionManager manager) { using (UiWpdInjector injector = new UiWpdInjector(_listing, _leafs, _conversion, source)) injector.Inject(manager); } } }
kidaa/Pulse
Pulse.UI/Windows/Main/Dockables/GameFileCommander/UiTree/Accessors/UiWpdLeafsAccessor.cs
C#
mit
1,061
import * as React from 'react'; import { DocumentCard } from './DocumentCard'; import { DocumentCardTitle } from './DocumentCardTitle'; import { DocumentCardPreview } from './DocumentCardPreview'; import { DocumentCardLocation } from './DocumentCardLocation'; import { DocumentCardActivity } from './DocumentCardActivity'; import { DocumentCardActions } from './DocumentCardActions'; import { PersonaInitialsColor } from '../../Persona'; import { ImageFit } from '../../Image'; import { IButtonProps } from '../../Button'; export interface IDocumentCard { } export interface IDocumentCardProps extends React.Props<DocumentCard> { /** * Optional callback to access the IDocumentCard interface. Use this instead of ref for accessing * the public methods and properties of the component. */ componentRef?: (component: IDocumentCard) => void; /** * The type of DocumentCard to display. * @default DocumentCardType.normal */ type?: DocumentCardType; /** * Function to call when the card is clicked or keyboard Enter/Space is pushed. */ onClick?: (ev?: React.SyntheticEvent<HTMLElement>) => void; /** * A URL to navigate to when the card is clicked. If a function has also been provided, * it will be used instead of the URL. */ onClickHref?: string; /** * Optional class for document card. */ className?: string; /** * Hex color value of the line below the card, which should correspond to the document type. * This should only be supplied when using the 'compact' card layout. */ accentColor?: string; } export enum DocumentCardType { /** * Standard DocumentCard. */ normal = 0, /** * Compact layout. Displays the preview beside the details, rather than above. */ compact = 1 } export interface IDocumentCardPreviewProps extends React.Props<DocumentCardPreview> { /** * One or more preview images to display. */ previewImages: IDocumentCardPreviewImage[]; /** * The function return string that will describe the number of overflow documents. * such as (overflowCount: number) => `+${ overflowCount } more`, */ getOverflowDocumentCountText?: (overflowCount: number) => string; } export interface IDocumentCardPreviewImage { /** * File name for the document this preview represents. */ name?: string; /** * URL to view the file. */ url?: string; /** * Path to the preview image. */ previewImageSrc?: string; /** * Deprecated at v1.3.6, to be removed at >= v2.0.0. * @deprecated */ errorImageSrc?: string; /** * Path to the icon associated with this document type. */ iconSrc?: string; /** * If provided, forces the preview image to be this width. */ width?: number; /** * If provided, forces the preview image to be this height. */ height?: number; /** * Used to determine how to size the image to fit the dimensions of the component. * If both dimensions are provided, then the image is fit using ImageFit.scale, otherwise ImageFit.none is used. */ imageFit?: ImageFit; /** * Hex color value of the line below the preview, which should correspond to the document type. */ accentColor?: string; } export interface IDocumentCardTitleProps extends React.Props<DocumentCardTitle> { /** * Title text. If the card represents more than one document, this should be the title of one document and a "+X" string. For example, a collection of four documents would have a string of "Document.docx +3". */ title: string; /** * Whether we truncate the title to fit within the box. May have a performance impact. * @defaultvalue true */ shouldTruncate?: boolean; } export interface IDocumentCardLocationProps extends React.Props<DocumentCardLocation> { /** * Text for the location of the document. */ location: string; /** * URL to navigate to for this location. */ locationHref?: string; /** * Function to call when the location is clicked. */ onClick?: (ev?: React.MouseEvent<HTMLElement>) => void; /** * Aria label for the link to the document location. */ ariaLabel?: string; } export interface IDocumentCardActivityProps extends React.Props<DocumentCardActivity> { /** * Describes the activity that has taken place, such as "Created Feb 23, 2016". */ activity: string; /** * One or more people who are involved in this activity. */ people: IDocumentCardActivityPerson[]; } export interface IDocumentCardActivityPerson { /** * The name of the person. */ name: string; /** * Path to the profile photo of the person. */ profileImageSrc: string; /** * The user's initials to display in the profile photo area when there is no image. */ initials?: string; /** * The background color when the user's initials are displayed. * @defaultvalue PersonaInitialsColor.blue */ initialsColor?: PersonaInitialsColor; } export interface IDocumentCardActionsProps extends React.Props<DocumentCardActions> { /** * The actions available for this document. */ actions: IButtonProps[]; /** * The number of views this document has received. */ views?: Number; }
SpatialMap/SpatialMapDev
node_modules/office-ui-fabric-react/src/components/DocumentCard/DocumentCard.Props.ts
TypeScript
mit
5,213
// // Created by paysonl on 16-10-20. // #include <vector> using std::vector; #include <iostream> #include <cassert> int min3(int a, int b, int c); int minSubSum(const vector<int>& a); int minSubRec(const vector<int>& a, int left, int right); int main() { vector<int> v{-2, -1, -2, 3, -4}; assert(minSubSum(v) == -6); } int minSubSum(const vector<int>& a) { return minSubRec(a, 0, a.size() - 1); } int minSubRec(const vector<int>& a, int left, int right) { if (left == right) if (a[left] < 0) return a[left]; else return 0; int mid = (left + right) / 2; int minLeftSum = minSubRec(a, left, mid); int minRightSum = minSubRec(a, mid + 1, right); int minLeftBorderSum = 0, leftBorderSum = 0; for (int i = mid; i >= left; --i) { leftBorderSum += a[i]; if (leftBorderSum < minLeftBorderSum) minLeftBorderSum = leftBorderSum; } int minRightBorderSum = 0, rightBorderSum = 0; for (int i = mid + 1; i <= right; ++i) { rightBorderSum += a[i]; if (rightBorderSum < minRightBorderSum) minRightBorderSum = rightBorderSum; } return min3(minLeftSum, minRightSum, minLeftBorderSum + minRightBorderSum); } int min3(int a, int b, int c) { int min2 = a < b ? a : b; return min2 < c ? min2 : c; }
frostRed/Exercises
DS_a_Algo_in_CPP/ch2/2-17-a.cpp
C++
mit
1,349
<?php /** * Created by PhpStorm. * User: Jan * Date: 17.03.2015 * Time: 17:03 */ namespace AppBundle\Repository; use Doctrine\ORM\EntityRepository; class ThreadRepository extends EntityRepository { public function findAllOrderedByLastModifiedDate($category_id) { $repository = $this->getEntityManager() ->getRepository('AppBundle:Thread'); $query = $repository->createQueryBuilder('t') ->where("t.category = :id") ->setParameter('id', $category_id) ->orderBy('t.last_modified_date', 'desc') ->getQuery(); return $query; } public function findAllPostsOrderedById($thread_id) { $repository = $this->getEntityManager() ->getRepository('AppBundle:Post'); $query = $repository->createQueryBuilder('p') ->where("p.thread = :id") ->setParameter('id', $thread_id) ->getQuery(); return $query; } }
mueller-jan/symfony-forum
src/AppBundle/Repository/ThreadRepository.php
PHP
mit
978
# User info wrapper object import logging class User(object): """ Wrapper object around an entry in users.json. Behaves like a read-only dictionary if asked, but adds some useful logic to decouple the front end from the JSON structure. """ _NAME_KEYS = ["display_name", "real_name"] _DEFAULT_IMAGE_KEY = "image_512" def __init__(self, raw_data): self._raw = raw_data def __getitem__(self, key): return self._raw[key] @property def display_name(self): """ Find the most appropriate display name for a user: look for a "display_name", then a "real_name", and finally fall back to the always-present "name". """ for k in self._NAME_KEYS: if self._raw.get(k): return self._raw[k] if "profile" in self._raw and self._raw["profile"].get(k): return self._raw["profile"][k] return self._raw["name"] @property def email(self): """ Shortcut property for finding the e-mail address or bot URL. """ if "profile" in self._raw: email = self._raw["profile"].get("email") elif "bot_url" in self._raw: email = self._raw["bot_url"] else: email = None if not email: logging.debug("No email found for %s", self._raw.get("name")) return email def image_url(self, pixel_size=None): """ Get the URL for the user icon in the desired pixel size, if it exists. If no size is supplied, give the URL for the full-size image. """ if "profile" not in self._raw: return profile = self._raw["profile"] if (pixel_size): img_key = "image_%s" % pixel_size if img_key in profile: return profile[img_key] return profile[self._DEFAULT_IMAGE_KEY] def deleted_user(id): """ Create a User object for a deleted user. """ deleted_user = { "id": id, "name": "deleted-" + id, "deleted": True, "is_bot": False, "is_app_user": False, } return User(deleted_user)
hfaran/slack-export-viewer
slackviewer/user.py
Python
mit
2,188
<?php declare(strict_types = 1); /** * /src/DTO/RestDtoInterface.php * * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ namespace App\DTO; use App\Entity\Interfaces\EntityInterface; use Throwable; /** * Interface RestDtoInterface * * @package App\DTO * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ interface RestDtoInterface { public function setId(string $id): self; /** * Getter method for visited setters. This is needed for dto patching. * * @return array<int, string> */ public function getVisited(): array; /** * Setter for visited data. This is needed for dto patching. */ public function setVisited(string $property): self; /** * Method to load DTO data from specified entity. */ public function load(EntityInterface $entity): self; /** * Method to update specified entity with DTO data. */ public function update(EntityInterface $entity): EntityInterface; /** * Method to patch current dto with another one. * * @throws Throwable */ public function patch(self $dto): self; }
tarlepp/symfony-flex-backend
src/DTO/RestDtoInterface.php
PHP
mit
1,141
package net.lightstone.net.codec; import java.io.IOException; import net.lightstone.msg.Message; import org.jboss.netty.buffer.ChannelBuffer; public abstract class MessageCodec<T extends Message> { private final Class<T> clazz; private final int opcode; public MessageCodec(Class<T> clazz, int opcode) { this.clazz = clazz; this.opcode = opcode; } public final Class<T> getType() { return clazz; } public final int getOpcode() { return opcode; } public abstract ChannelBuffer encode(T message) throws IOException; public abstract T decode(ChannelBuffer buffer) throws IOException; }
grahamedgecombe/lightstone
src/net/lightstone/net/codec/MessageCodec.java
Java
mit
613
#define _IRR_STATIC_LIB_ #include <irrlicht.h> #include <stdio.h> #include <string> #include <sstream> #include <iostream> #include "dc-config.h" #include "manager_gui.h" #include "manager_filesystem.h" #include "manager_core.h" #include "irrlicht_event_handler.h" #include "context_application.h" using namespace irr; using namespace irr::core; using namespace scene; using namespace video; using namespace io; using namespace gui; using namespace decentralised::managers; using namespace decentralised::context; #ifdef _WINDOWS #ifndef _DEBUG #pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") #endif #pragma comment(lib, "irrlicht.lib") #endif template <typename T> std::wstring to_wstring(T val) { std::wstringstream stream; stream << val; return stream.str(); } int main() { E_DRIVER_TYPE driverType = EDT_OPENGL; #if defined ( _IRR_WINDOWS_ ) driverType = EDT_DIRECT3D9; #endif manager_filesystem* fileManager = new manager_filesystem(); context_application context; context.config = fileManager->loadConfig(); context.skin = fileManager->loadSkin(context.config[L"Skin"]); context.language = fileManager->loadLanguage(context.config[L"Language"]); context.device = createDevice(driverType, irr::core::dimension2d<u32>(800, 600)); if (context.device == 0) return 1; context.device->setResizable(true); std::wstring title = std::wstring(APP_TITLE) .append(L" ") .append(to_wstring(Decentralised_VERSION_MAJOR)) .append(L".") .append(to_wstring(Decentralised_VERSION_MINOR)) .append(L"\n").c_str(); context.device->setWindowCaption(title.c_str()); context.gui_manager = new manager_gui(context.device, context.language, context.skin, context.config); context.gui_manager->Initialize(); context.world_manager = new manager_world(context.device); IVideoDriver* driver = context.device->getVideoDriver(); context.gui_manager->AddConsoleLine(SColor(255,255,255,255), APP_TITLE); irrlicht_event_handler receiver(context); context.network_manager = new manager_core(); context.network_manager->setEventReceiver(&receiver); context.device->setEventReceiver(&receiver); context.network_manager->start(); ISceneManager *scene = context.device->getSceneManager(); while (context.device->run() && driver) if (!context.device->isWindowMinimized() || context.device->isWindowActive()) { driver->beginScene(true, true, SColor(0, 0, 0, 0)); scene->drawAll(); context.gui_manager->DrawAll(); driver->endScene(); } context.network_manager->stop(); delete context.world_manager; delete context.gui_manager; delete context.network_manager; delete fileManager; return 0; }
ballisticwhisper/decentralised
src/decentralised/main.cpp
C++
mit
2,662
test('has a constructor for initialization', () => { // Create an Animal class // Add a constructor that takes one param, the name. // Set this.name to the name passed in const animal = new Animal() const dog = new Animal('Dog') expect(animal.name).toBeUndefined() expect(dog.name).toBe('Dog') }) test('constructor can have default param values', () => { // Create an Animal class with a constructor // Make your class default (using default params) the name to 'Honey Badger' const animal = new Animal() const dog = new Animal('Dog') expect(animal.name).toBe('Honey Badger') expect(dog.name).toBe('Dog') }) test('can have instance methods', () => { // Create an Animal class, pass in the name to the constructor, and add a sayName function to the class definition const animal = new Animal() expect(animal.sayName).toBeDefined() expect(Animal.sayName).toBeUndefined() expect(animal.sayName()).toBe('My name is: Honey Badger') }) test('can have static methods', () => { // Create an Animal class, pass in the name to the constructor, // and add a create method that takes a name and returns an instance const animal = new Animal() expect(animal.create).toBeUndefined() expect(Animal.create).toBeDefined() }) test('can extend another class', () => { // Create an Animal class // Create a Dog class that extends Animal // Add sayName to Animal const dog = new Dog('Fido') expect(dog instanceof Dog).toBe(true) expect(dog instanceof Animal).toBe(true) }) test('can use property setters and getters', () => { // Create an Animal class (don't pass name into constructor) // Add property setter for name // Add property getter for name const animal = new Animal() animal.name = 'Dog' expect(animal.name).toBe('Dog type of animal') animal.name = 'Cat' expect(animal.name).toBe('Cat type of animal') }) //////// EXTRA CREDIT //////// // If you get this far, try adding a few more tests, then file a pull request to add them to the extra credit! // Learn more here: https://github.com/kentcdodds/es6-workshop/blob/master/CONTRIBUTING.md#development
wizzy25/es6-workshop
exercises/10_class.test.js
JavaScript
mit
2,133
using Caliburn.Micro; using FollowMe.Messages; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace FollowMe.WebService { /// <summary> /// RemoteControl to control the Ar.Drone indirectly. /// You can start and stop the person following. /// </summary> [ServiceBehavior( ConcurrencyMode=ConcurrencyMode.Single, InstanceContextMode=InstanceContextMode.Single)] public class RemoteControl : IRemoteControl, IHandle<DangerLocationMessage>, IHandle<PersonLocationMessage> { private static readonly ILog Log = LogManager.GetLog(typeof(RemoteControl)); private readonly IEventAggregator eventAggregator; private Enums.TargetLocation personLocation = Enums.TargetLocation.Unknown; private Enums.TargetLocation dangerLocation = Enums.TargetLocation.Unknown; public RemoteControl(IEventAggregator eventAggregator) { if (eventAggregator == null) throw new ArgumentNullException("eventAggregator"); this.eventAggregator = eventAggregator; this.eventAggregator.Subscribe(this); } /// <summary> /// Start the person following /// </summary> public void Start() { Log.Info("Start - BECAUSE OF SECURITY REASONS NOT IMPLEMENTED"); } /// <summary> /// Stop the Person following /// </summary> public void Stop() { Log.Info("Stop"); eventAggregator.Publish(new StopMessage(), action => { Task.Factory.StartNew(action); }); } public Enums.TargetLocation GetPersonLocation() { Log.Info("GetPersonLocation {0}", personLocation); return personLocation; } public Enums.TargetLocation GetDangerLocation() { Log.Info("GetDangerLocation {0}", dangerLocation); return dangerLocation; } public PersonAndDangerLocation GetPersonAndDangerLocation() { Log.Info("GetPersonAndDangerLocation, person: {0}, danger: {1}", personLocation, dangerLocation); return new PersonAndDangerLocation { DangerLocation = dangerLocation, PersonLocation = personLocation }; } public void Handle(DangerLocationMessage message) { this.dangerLocation = message.DangerLocation; } public void Handle(PersonLocationMessage message) { this.personLocation = message.PersonLocation; } } }
HeinrichChristian/FlyingRobotToWarnVisuallyImpaired
FollowMe/WebService/RemoteControl.cs
C#
mit
2,774