repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
ControlSystemStudio/cs-studio | thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/core/src/main/java/org/hibernate/engine/Cascade.java | 16254 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.engine;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Stack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.event.EventSource;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.AbstractComponentType;
import org.hibernate.type.AssociationType;
import org.hibernate.type.CollectionType;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
import org.hibernate.util.CollectionHelper;
/**
* Delegate responsible for, in conjunction with the various
* {@link CascadingAction actions}, implementing cascade processing.
*
* @author Gavin King
* @see CascadingAction
*/
public final class Cascade {
/**
* A cascade point that occurs just after the insertion of the parent entity and
* just before deletion
*/
public static final int AFTER_INSERT_BEFORE_DELETE = 1;
/**
* A cascade point that occurs just before the insertion of the parent entity and
* just after deletion
*/
public static final int BEFORE_INSERT_AFTER_DELETE = 2;
/**
* A cascade point that occurs just after the insertion of the parent entity and
* just before deletion, inside a collection
*/
public static final int AFTER_INSERT_BEFORE_DELETE_VIA_COLLECTION = 3;
/**
* A cascade point that occurs just after update of the parent entity
*/
public static final int AFTER_UPDATE = 0;
/**
* A cascade point that occurs just before the session is flushed
*/
public static final int BEFORE_FLUSH = 0;
/**
* A cascade point that occurs just after eviction of the parent entity from the
* session cache
*/
public static final int AFTER_EVICT = 0;
/**
* A cascade point that occurs just after locking a transient parent entity into the
* session cache
*/
public static final int BEFORE_REFRESH = 0;
/**
* A cascade point that occurs just after refreshing a parent entity
*/
public static final int AFTER_LOCK = 0;
/**
* A cascade point that occurs just before merging from a transient parent entity into
* the object in the session cache
*/
public static final int BEFORE_MERGE = 0;
private static final Logger log = LoggerFactory.getLogger( Cascade.class );
private int cascadeTo;
private EventSource eventSource;
private CascadingAction action;
public Cascade(final CascadingAction action, final int cascadeTo, final EventSource eventSource) {
this.cascadeTo = cascadeTo;
this.eventSource = eventSource;
this.action = action;
}
private SessionFactoryImplementor getFactory() {
return eventSource.getFactory();
}
/**
* Cascade an action from the parent entity instance to all its children.
*
* @param persister The parent's entity persister
* @param parent The parent reference.
* @throws HibernateException
*/
public void cascade(final EntityPersister persister, final Object parent)
throws HibernateException {
cascade( persister, parent, null );
}
/**
* Cascade an action from the parent entity instance to all its children. This
* form is typicaly called from within cascade actions.
*
* @param persister The parent's entity persister
* @param parent The parent reference.
* @param anything Anything ;) Typically some form of cascade-local cache
* which is specific to each CascadingAction type
* @throws HibernateException
*/
public void cascade(final EntityPersister persister, final Object parent, final Object anything)
throws HibernateException {
if ( persister.hasCascades() || action.requiresNoCascadeChecking() ) { // performance opt
if ( log.isTraceEnabled() ) {
log.trace( "processing cascade " + action + " for: " + persister.getEntityName() );
}
Type[] types = persister.getPropertyTypes();
CascadeStyle[] cascadeStyles = persister.getPropertyCascadeStyles();
EntityMode entityMode = eventSource.getEntityMode();
boolean hasUninitializedLazyProperties = persister.hasUninitializedLazyProperties( parent, entityMode );
for ( int i=0; i<types.length; i++) {
final CascadeStyle style = cascadeStyles[i];
final String propertyName = persister.getPropertyNames()[i];
if ( hasUninitializedLazyProperties && persister.getPropertyLaziness()[i] && ! action.performOnLazyProperty() ) {
//do nothing to avoid a lazy property initialization
continue;
}
if ( style.doCascade( action ) ) {
cascadeProperty(
parent,
persister.getPropertyValue( parent, i, entityMode ),
types[i],
style,
propertyName,
anything,
false
);
}
else if ( action.requiresNoCascadeChecking() ) {
action.noCascade(
eventSource,
persister.getPropertyValue( parent, i, entityMode ),
parent,
persister,
i
);
}
}
if ( log.isTraceEnabled() ) {
log.trace( "done processing cascade " + action + " for: " + persister.getEntityName() );
}
}
}
/**
* Cascade an action to the child or children
*/
private void cascadeProperty(
final Object parent,
final Object child,
final Type type,
final CascadeStyle style,
final String propertyName,
final Object anything,
final boolean isCascadeDeleteEnabled) throws HibernateException {
if (child!=null) {
if ( type.isAssociationType() ) {
AssociationType associationType = (AssociationType) type;
if ( cascadeAssociationNow( associationType ) ) {
cascadeAssociation(
parent,
child,
type,
style,
anything,
isCascadeDeleteEnabled
);
}
}
else if ( type.isComponentType() ) {
cascadeComponent( parent, child, (AbstractComponentType) type, propertyName, anything );
}
}
else {
// potentially we need to handle orphan deletes for one-to-ones here...
if ( isLogicalOneToOne( type ) ) {
// We have a physical or logical one-to-one and from previous checks we know we
// have a null value. See if the attribute cascade settings and action-type require
// orphan checking
if ( style.hasOrphanDelete() && action.deleteOrphans() ) {
// value is orphaned if loaded state for this property shows not null
// because it is currently null.
final EntityEntry entry = eventSource.getPersistenceContext().getEntry( parent );
if ( entry != null && entry.getStatus() != Status.SAVING ) {
final Object loadedValue;
if ( componentPathStack.isEmpty() ) {
// association defined on entity
loadedValue = entry.getLoadedValue( propertyName );
}
else {
// association defined on component
// todo : this is currently unsupported because of the fact that
// we do not know the loaded state of this value properly
// and doing so would be very difficult given how components and
// entities are loaded (and how 'loaded state' is put into the
// EntityEntry). Solutions here are to either:
// 1) properly account for components as a 2-phase load construct
// 2) just assume the association was just now orphaned and
// issue the orphan delete. This would require a special
// set of SQL statements though since we do not know the
// orphaned value, something a delete with a subquery to
// match the owner.
// final EntityType entityType = (EntityType) type;
// final String propertyPath = composePropertyPath( entityType.getPropertyName() );
loadedValue = null;
}
if ( loadedValue != null ) {
final String entityName = entry.getPersister().getEntityName();
if ( log.isTraceEnabled() ) {
final Serializable id = entry.getPersister().getIdentifier( loadedValue, eventSource );
final String description = MessageHelper.infoString( entityName, id );
log.trace( "deleting orphaned entity instance: " + description );
}
eventSource.delete( entityName, loadedValue, false, new HashSet() );
}
}
}
}
}
}
/**
* Check if the association is a one to one in the logical model (either a shared-pk
* or unique fk).
*
* @param type The type representing the attribute metadata
*
* @return True if the attribute represents a logical one to one association
*/
private boolean isLogicalOneToOne(Type type) {
return type.isEntityType() && ( (EntityType) type ).isLogicalOneToOne();
}
private String composePropertyPath(String propertyName) {
if ( componentPathStack.isEmpty() ) {
return propertyName;
}
else {
StringBuffer buffer = new StringBuffer();
Iterator itr = componentPathStack.iterator();
while ( itr.hasNext() ) {
buffer.append( itr.next() ).append( '.' );
}
buffer.append( propertyName );
return buffer.toString();
}
}
private Stack componentPathStack = new Stack();
private boolean cascadeAssociationNow(AssociationType associationType) {
return associationType.getForeignKeyDirection().cascadeNow(cascadeTo) &&
( eventSource.getEntityMode()!=EntityMode.DOM4J || associationType.isEmbeddedInXML() );
}
private void cascadeComponent(
final Object parent,
final Object child,
final AbstractComponentType componentType,
final String componentPropertyName,
final Object anything) {
componentPathStack.push( componentPropertyName );
Object[] children = componentType.getPropertyValues( child, eventSource );
Type[] types = componentType.getSubtypes();
for ( int i=0; i<types.length; i++ ) {
final CascadeStyle componentPropertyStyle = componentType.getCascadeStyle(i);
final String subPropertyName = componentType.getPropertyNames()[i];
if ( componentPropertyStyle.doCascade(action) ) {
cascadeProperty(
parent,
children[i],
types[i],
componentPropertyStyle,
subPropertyName,
anything,
false
);
}
}
componentPathStack.pop();
}
private void cascadeAssociation(
final Object parent,
final Object child,
final Type type,
final CascadeStyle style,
final Object anything,
final boolean isCascadeDeleteEnabled) {
if ( type.isEntityType() || type.isAnyType() ) {
cascadeToOne( parent, child, type, style, anything, isCascadeDeleteEnabled );
}
else if ( type.isCollectionType() ) {
cascadeCollection( parent, child, style, anything, (CollectionType) type );
}
}
/**
* Cascade an action to a collection
*/
private void cascadeCollection(
final Object parent,
final Object child,
final CascadeStyle style,
final Object anything,
final CollectionType type) {
CollectionPersister persister = eventSource.getFactory()
.getCollectionPersister( type.getRole() );
Type elemType = persister.getElementType();
final int oldCascadeTo = cascadeTo;
if ( cascadeTo==AFTER_INSERT_BEFORE_DELETE) {
cascadeTo = AFTER_INSERT_BEFORE_DELETE_VIA_COLLECTION;
}
//cascade to current collection elements
if ( elemType.isEntityType() || elemType.isAnyType() || elemType.isComponentType() ) {
cascadeCollectionElements(
parent,
child,
type,
style,
elemType,
anything,
persister.isCascadeDeleteEnabled()
);
}
cascadeTo = oldCascadeTo;
}
/**
* Cascade an action to a to-one association or any type
*/
private void cascadeToOne(
final Object parent,
final Object child,
final Type type,
final CascadeStyle style,
final Object anything,
final boolean isCascadeDeleteEnabled) {
final String entityName = type.isEntityType()
? ( (EntityType) type ).getAssociatedEntityName()
: null;
if ( style.reallyDoCascade(action) ) { //not really necessary, but good for consistency...
eventSource.getPersistenceContext().addChildParent(child, parent);
try {
action.cascade(eventSource, child, entityName, anything, isCascadeDeleteEnabled);
}
finally {
eventSource.getPersistenceContext().removeChildParent(child);
}
}
}
/**
* Cascade to the collection elements
*/
private void cascadeCollectionElements(
final Object parent,
final Object child,
final CollectionType collectionType,
final CascadeStyle style,
final Type elemType,
final Object anything,
final boolean isCascadeDeleteEnabled) throws HibernateException {
// we can't cascade to non-embedded elements
boolean embeddedElements = eventSource.getEntityMode()!=EntityMode.DOM4J ||
( (EntityType) collectionType.getElementType( eventSource.getFactory() ) ).isEmbeddedInXML();
boolean reallyDoCascade = style.reallyDoCascade(action) &&
embeddedElements && child!=CollectionType.UNFETCHED_COLLECTION;
if ( reallyDoCascade ) {
if ( log.isTraceEnabled() ) {
log.trace( "cascade " + action + " for collection: " + collectionType.getRole() );
}
Iterator iter = action.getCascadableChildrenIterator(eventSource, collectionType, child);
while ( iter.hasNext() ) {
cascadeProperty(
parent,
iter.next(),
elemType,
style,
null,
anything,
isCascadeDeleteEnabled
);
}
if ( log.isTraceEnabled() ) {
log.trace( "done cascade " + action + " for collection: " + collectionType.getRole() );
}
}
final boolean deleteOrphans = style.hasOrphanDelete() &&
action.deleteOrphans() &&
elemType.isEntityType() &&
child instanceof PersistentCollection; //a newly instantiated collection can't have orphans
if ( deleteOrphans ) { // handle orphaned entities!!
if ( log.isTraceEnabled() ) {
log.trace( "deleting orphans for collection: " + collectionType.getRole() );
}
// we can do the cast since orphan-delete does not apply to:
// 1. newly instantiated collections
// 2. arrays (we can't track orphans for detached arrays)
final String entityName = collectionType.getAssociatedEntityName( eventSource.getFactory() );
deleteOrphans( entityName, (PersistentCollection) child );
if ( log.isTraceEnabled() ) {
log.trace( "done deleting orphans for collection: " + collectionType.getRole() );
}
}
}
/**
* Delete any entities that were removed from the collection
*/
private void deleteOrphans(String entityName, PersistentCollection pc) throws HibernateException {
//TODO: suck this logic into the collection!
final Collection orphans;
if ( pc.wasInitialized() ) {
CollectionEntry ce = eventSource.getPersistenceContext().getCollectionEntry(pc);
orphans = ce==null ?
CollectionHelper.EMPTY_COLLECTION :
ce.getOrphans(entityName, pc);
}
else {
orphans = pc.getQueuedOrphans(entityName);
}
final Iterator orphanIter = orphans.iterator();
while ( orphanIter.hasNext() ) {
Object orphan = orphanIter.next();
if (orphan!=null) {
if ( log.isTraceEnabled() ) {
log.trace("deleting orphaned entity instance: " + entityName);
}
eventSource.delete( entityName, orphan, false, new HashSet() );
}
}
}
}
| epl-1.0 |
yhxs3344/Nsis_chinese | Source/zlib/ZLIB.H | 9669 | /*
* This file is a part of the zlib compression module for NSIS.
*
* Copyright and license information can be found below.
* Modifications Copyright (C) 1999-2016 Nullsoft and Contributors
*
* The original zlib source code is available at
* http://www.zlib.net/
*
* This software is provided 'as-is', without any express or implied
* warranty.
*
* Unicode support by Jim Park -- 08/27/2007
*/
/* zlib.h -- interface of the 'zlib' general purpose compression library
version 1.1.3, July 9th, 1998
Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
*/
#ifndef _ZLIB_H
#define _ZLIB_H
#include "ZCONF.H"
#include "ZUTIL.H"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef EXEHEAD
typedef struct inflate_huft_s FAR inflate_huft;
typedef enum { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
CODES_START, /* x: set up for LEN */
CODES_LEN, /* i: get length/literal/eob next */
CODES_LENEXT, /* i: getting length extra (have base) */
CODES_DIST, /* i: get distance next */
CODES_DISTEXT, /* i: getting distance extra */
CODES_COPY, /* o: copying bytes in window, waiting for space */
CODES_LIT, /* o: got literal, waiting for output space */
CODES_WASH, /* o: got eob, possibly still output waiting */
//CODES_END, /* x: got eob and all data flushed */
//CODES_BADCODE, /* x: got error */
TYPE, /* get type bits (3, including end bit) */
LENS, /* get lengths for stored */
STORED, /* processing stored block */
TABLE, /* get table lengths */
BTREE, /* get bit lengths tree for a dynamic block */
DTREE, /* get length, distance trees for a dynamic block */
CODES, /* processing fixed or dynamic block */
DRY, /* output remaining window bytes */
DONE, /* finished last block, done */
BAD /* got a data error--stuck here */
} inflate_mode;
/* inflate codes private state */
struct inflate_codes_state {
/* mode */
//inflate_mode mode; /* current inflate_codes mode */
/* mode dependent information */
uInt len;
union {
struct {
inflate_huft *tree; /* pointer into tree */
uInt need; /* bits needed */
} code; /* if LEN or DIST, where in tree */
uInt lit; /* if LIT, literal */
struct {
uInt get; /* bits to get for extra */
uInt dist; /* distance back to copy from */
} copy; /* if EXT or COPY, where and how much */
} sub; /* submode */
/* mode independent information */
Byte lbits; /* ltree bits decoded per branch */
Byte dbits; /* dtree bits decoder per branch */
inflate_huft *ltree; /* literal/length/eob tree */
inflate_huft *dtree; /* distance tree */
};
struct inflate_huft_s {
union {
struct {
Byte Exop; /* number of extra bits or operation */
Byte Bits; /* number of bits in this code or subcode */
} what;
} word;
unsigned short base; /* literal, length base, distance base,
or table offset */
};
#define MANY 1440
typedef struct inflate_codes_state inflate_codes_statef;
struct inflate_blocks_state {
/* mode */
inflate_mode mode; /* current inflate_block mode */
/* mode dependent information */
union {
uInt left; /* if STORED, bytes left to copy */
struct {
uInt table; /* table lengths (14 bits) */
uInt index; /* index into blens (or border) */
uIntf t_blens[258+31+31]; /* bit lengths of codes */
uInt bb; /* bit length tree depth */
inflate_huft *tb; /* bit length decoding tree */
} trees; /* if DTREE, decoding info for trees */
struct {
inflate_codes_statef t_codes;
} decode; /* if CODES, current state */
} sub; /* submode */
uInt last; /* DRY if this block is the last block, TYPE otherwise */
/* mode independent information */
uInt bitk; /* bits in bit buffer */
uLong bitb; /* bit buffer */
inflate_huft hufts[MANY]; /* single malloc for tree space */
Bytef window[1 << MAX_WBITS]; /* sliding window */
Bytef *end; /* one byte after sliding window */
Bytef *read; /* window read pointer */
Bytef *write; /* window write pointer */
uLong check; /* check on output */
};
#else
struct internal_state;
#endif
typedef struct z_stream_s {
Bytef *next_in; /* next input byte */
uInt avail_in; /* number of bytes available at next_in */
#ifndef EXEHEAD
uLong total_in; /* total nb of input bytes read so far */
#endif
Bytef *next_out; /* next output byte should be put there */
uInt avail_out; /* remaining free space at next_out */
#ifndef EXEHEAD
uLong total_out; /* total nb of bytes output so far */
#endif
// TCHAR *msg; /* last error message, NULL if no error */
//struct internal_state FAR *state; /* not visible by applications */
#ifdef EXEHEAD
struct inflate_blocks_state blocks; /* current inflate_blocks state */
#else
struct internal_state *state;
#endif
} z_stream;
typedef z_stream FAR *z_streamp;
#define Z_NO_FLUSH 0
#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
#define Z_SYNC_FLUSH 2
#define Z_FULL_FLUSH 3
#define Z_FINISH 4
/* Allowed flush values; see deflate() below for details */
#define Z_OK 0
#define Z_STREAM_END 1
#define Z_NEED_DICT 2
#define Z_ERRNO (-1)
#ifndef EXEHEAD
#define Z_STREAM_ERROR (-2)
#define Z_DATA_ERROR (-3)
#define Z_MEM_ERROR (-4)
#define Z_BUF_ERROR (-5)
#define Z_VERSION_ERROR (-6)
#else
// EXEHEAD doesn't need a specific return code, just < 0
#define Z_STREAM_ERROR Z_ERRNO
#define Z_DATA_ERROR Z_ERRNO
#define Z_MEM_ERROR Z_ERRNO
#define Z_BUF_ERROR Z_ERRNO
#define Z_VERSION_ERROR Z_ERRNO
#endif
/* Return codes for the compression/decompression functions. Negative
* values are errors, positive values are used for special but normal events.
*/
#define Z_NO_COMPRESSION 0
#define Z_BEST_SPEED 1
#define Z_BEST_COMPRESSION 9
#define Z_DEFAULT_COMPRESSION (-1)
/* compression levels */
#define Z_FILTERED 1
#define Z_HUFFMAN_ONLY 2
#define Z_DEFAULT_STRATEGY 0
/* compression strategy; see deflateInit2() below for details */
#define Z_BINARY 0
#define Z_ASCII 1
#define Z_UNKNOWN 2
/* Possible values of the data_type field */
#define Z_DEFLATED 8
/* The deflate compression method (the only one supported in this version) */
#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
#define inflateInit(x) inflateReset(x)
int ZEXPORT inflate(z_streamp z);
ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
int level,
int method,
int windowBits,
int memLevel,
int strategy));
ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
//void ZEXPORT inflateReset OF((
// z_streamp));
#define inflateReset(z) \
{ \
(z)->blocks.mode = TYPE; \
(z)->blocks.bitk = (z)->blocks.bitb = 0; \
(z)->blocks.read = (z)->blocks.write = (z)->blocks.window; \
(z)->blocks.end = (z)->blocks.window + (1 << DEF_WBITS); \
}
/* various hacks, don't look :) */
/* deflateInit and inflateInit are macros to allow checking the zlib version
* and the compiler's view of z_stream:
*/
ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
const TCHAR *version, int stream_size));
//ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
// const TCHAR *version, int stream_size));
ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
int windowBits, int memLevel,
int strategy, const TCHAR *version,
int stream_size));
#define deflateInit(strm, level) \
deflateInit_((strm), (level), _T(""), sizeof(z_stream))
#ifdef __cplusplus
}
#endif
#endif /* _ZLIB_H */
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/MonitoringFrameworkExtender.java | 20778 | /*******************************************************************************
* Copyright (c) 2010, 2021 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.monitor.internal;
import java.lang.annotation.Annotation;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.SynchronousBundleListener;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.packageadmin.PackageAdmin;
import com.ibm.websphere.monitor.MonitorManager;
import com.ibm.websphere.monitor.annotation.Monitor;
import com.ibm.websphere.monitor.annotation.ProbeSite;
import com.ibm.websphere.monitor.annotation.PublishedMetric;
import com.ibm.websphere.monitor.meters.Meter;
import com.ibm.websphere.monitor.meters.MeterCollection;
import com.ibm.websphere.pmi.PmiConstants;
import com.ibm.websphere.ras.Tr;
import com.ibm.websphere.ras.TraceComponent;
import com.ibm.ws.ffdc.FFDCFilter;
import com.ibm.ws.pmi.server.PmiRegistry;
import com.ibm.wsspi.kernel.service.utils.FrameworkState;
// TODO: Java 2 Security
// TODO: Lazy instantiation of the monitor - requires passing config / metadata
public class MonitoringFrameworkExtender implements SynchronousBundleListener {
public final static String MONITORING_COMPONENT_BUNDLE_HEADER = "Liberty-Monitoring-Components";
public static final ArrayList<String> groupList = new ArrayList<String>();
Map<Long, Set<MonitorObject>> processedBundles = new HashMap<Long, Set<MonitorObject>>();
public static final ConcurrentMap<Object, Set<ObjectName>> mxmap = new ConcurrentHashMap<Object, Set<ObjectName>>();
MBeanServer mbeanServer = AccessController.doPrivileged((PrivilegedAction<MBeanServer>) () -> ManagementFactory.getPlatformMBeanServer());
public final ConcurrentMap<Object, MonitorObject> objectMap = new ConcurrentHashMap<Object, MonitorObject>();
private final static String MONITORING_GROUP_FILTER = "filter";
private final static String MONITORING_TRADITIONALPMI = "enableTraditionalPMI";
private volatile boolean isDeactivated = false;
MonitorManager monitorManager;
PackageAdmin packageAdmin;
BundleContext bundleContext;
private static final TraceComponent tc = Tr.register(MonitoringFrameworkExtender.class);
protected synchronized void activate(BundleContext bundleContext, Map<String, Object> properties) {
this.bundleContext = bundleContext;
Boolean val = (Boolean) properties.get(MONITORING_TRADITIONALPMI);
if (val != null && val) {
PmiRegistry.enable();
} else {
PmiRegistry.disable();
}
String filter = (String) properties.get(MONITORING_GROUP_FILTER);
if (filter != null) {
StringTokenizer st = new StringTokenizer(filter, ",");
while (st.hasMoreTokens()) {
groupList.add(st.nextToken());
}
}
bundleContext.addBundleListener(this);
for (Bundle bundle : bundleContext.getBundles()) {
activateMonitors(bundle);
}
}
protected synchronized void deactivate() {
isDeactivated = true;
if (tc.isDebugEnabled()) {
Tr.debug(tc, "isDeactivated in deactivate() is", isDeactivated);
}
bundleContext.removeBundleListener(this);
for (Bundle bundle : bundleContext.getBundles()) {
deactivateMonitors(bundle);
}
this.bundleContext = null;
}
protected synchronized void setMonitorManager(MonitorManager monitorManager) {
this.monitorManager = monitorManager;
}
protected synchronized void unsetMonitorManager(MonitorManager monitorManager) {
if (monitorManager == this.monitorManager) {
this.monitorManager = null;
}
}
protected void setPackageAdmin(PackageAdmin packageAdmin) {
this.packageAdmin = packageAdmin;
}
protected void unsetPackageAdmin(PackageAdmin packageAdmin) {
if (packageAdmin == this.packageAdmin) {
this.packageAdmin = null;
}
}
@Override
public synchronized void bundleChanged(BundleEvent event) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "isDeactivated in bundleChanged is", isDeactivated);
}
if (!isDeactivated) {
switch (event.getType()) {
case BundleEvent.LAZY_ACTIVATION:
case BundleEvent.STARTED:
activateMonitors(event.getBundle());
break;
case BundleEvent.STOPPING:
case BundleEvent.STOPPED:
deactivateMonitors(event.getBundle());
break;
default:
break;
}
}
}
/**
* @param bundle
* Starting point for activation/processing/registration/filtering process of any bundle which is eligible for monitoring.This will be
* decided by scanning each bundle for bundle header "Liberty-Monitoring-Components".
*/
synchronized void activateMonitors(Bundle bundle) {
Long bundleId = bundle.getBundleId();
if (processedBundles.containsKey(bundleId)) {
return;
}
if (bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING) {
return;
}
if (bundle.getHeaders("").get(MONITORING_COMPONENT_BUNDLE_HEADER) == null) {
return;
}
if (bundle.getBundleContext() == null) {
return;
}
//Defect # 62098
//We are seeing Server stop operating is somehow invoking activate() for this class,
//which calls registerMonitor to fail.
//Adding following check.
//If server is being stop, don't register monitors.
if (FrameworkState.isStopping()) {
return;
}
Set<MonitorObject> bundleMonitors = new HashSet<MonitorObject>();
processedBundles.put(bundleId, bundleMonitors);
for (Class<?> clazz : MonitoringUtility.loadMonitoringClasses(bundle)) {
boolean filterGroup = true;
Monitor groups = clazz.getAnnotation(Monitor.class);
if (!(groupList.size() == 0)) {
for (String group : groups.group()) {
filterGroup = groupList.contains(group);
}
}
for (int i = 0; i < clazz.getMethods().length; i++) {
Annotation anno = ((clazz.getMethods()[i]).getAnnotation(ProbeSite.class));
if (anno != null) {
String temp = ((ProbeSite) anno).clazz();
if (monitorManager != null) {
monitorManager.updateNonExcludedClassesSet(temp); //RTCD 89497
}
}
}
Object monitor = constructMonitor(clazz);
if (monitor != null) {
MonitorObject mObject = new MonitorObject(bundleId, groups, monitor, clazz);
objectMap.put(monitor, mObject);
bundleMonitors.add(mObject);
if (!filterGroup) {
continue;
}
processANDregister((objectMap.get(monitor)).getMonitor(), objectMap.get(monitor));
}
}
}
/**
* @param monitor
* Initate calls for processing the Monitor Object( which includes generating ObectNames) and registering of the object.
*/
private void processANDregister(Object monitor, MonitorObject mob) {
// TODO Auto-generated method stub
try {
Set<ObjectName> mxbeanset = new HashSet<ObjectName>();
mxmap.put(monitor, mxbeanset);
processMeters(monitor);
if (monitorManager != null) {
monitorManager.registerMonitor(monitor);
mob.setMonitor(monitor);
mob.setRegistered(true);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Registration Successfull for object", monitor);
}
} else {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Monitor Manager is NULL");
}
}
} catch (Exception e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "processANDregister exception message: ", e.getMessage());
FFDCFilter.processException(e, getClass().getSimpleName(), "processANDregister:Exception");
}
}
}
/**
* @param clazz
* @return
* Constructs Object for the respective Monitorable classes.
*/
protected Object constructMonitor(Class<?> clazz) {
Object monitor = null;
for (Constructor<?> ctor : ReflectionHelper.getConstructors(clazz)) {
// TODO: Filter for compatible constructors and use most flexible
Class<?>[] parameterTypes = ctor.getParameterTypes();
if (parameterTypes.length == 0) {
monitor = ReflectionHelper.newInstance(ctor);
} else if (parameterTypes.length == 1) {
Class<?> argType = parameterTypes[0];
if (argType.equals(MonitorManager.class)) {
monitor = ReflectionHelper.newInstance(ctor, monitorManager);
}
}
}
return monitor;
}
/**
* @param instance
* Takes care of creating ObjectNames for Monitor which has MeterType Ex:JVM and later add it to the mxMap set which
* maintains the MBean objectNames.
*/
private void processMeters(Object instance) {
try {
Set<Field> publishedFields = new HashSet<Field>();
Class<?> clazz = instance.getClass();
for (Field f : clazz.getDeclaredFields()) {
PublishedMetric publishedMetric = f.getAnnotation(PublishedMetric.class);
if (publishedMetric == null) {
continue;
}
f.setAccessible(true);
//If Stats extends Meter, create MXBean with specified type
//WebSphere:type=<ClassSimleName>
if (Meter.class.isAssignableFrom(f.getType())) {
Object o = f.get(instance);
if (o != null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "need to create MBEAN for " + o);
}
publishedFields.add(f);
MBeanServer mbeanServer = AccessController.doPrivileged((PrivilegedAction<MBeanServer>) () -> ManagementFactory.getPlatformMBeanServer());
StringBuilder sb = new StringBuilder("WebSphere:");
sb.append("type=").append(o.getClass().getSimpleName());
ObjectName objectName = new ObjectName(sb.toString());
mbeanServer.registerMBean(o, objectName);
Set<ObjectName> temp = mxmap.get(instance);
if (temp != null) {
temp.add(objectName);
} else {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "ObjectName returned from mxMap is null");
}
}
}
} else if (MeterCollection.class.isAssignableFrom(f.getType())) {
//If Stats extends MeterCollection, create MXBean with specified type
//WebSphere:type=<ClassSimleName>,name=<instanceName>
//This is Handled in MeterCollection, as during initialisation, we don't know all instances.
}
}
} catch (Exception e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, e.getMessage());
}
}
}
/**
* @param bundle
* Checks to see if the bundle being deactivated is Monitoring bundle ,if so unregister the PerfMBean which
* is registered if traditional PMI is enabled .Later initiate call for unregisterMonitor.
*/
synchronized void deactivateMonitors(Bundle bundle) {
if (bundle.getSymbolicName().equals("com.ibm.ws.monitor")) {
//deregister MBean
try {
MBeanServer mServer = AccessController.doPrivileged((PrivilegedAction<MBeanServer>) () -> ManagementFactory.getPlatformMBeanServer());
mServer.unregisterMBean(new ObjectName(PmiConstants.MBEAN_NAME));
} catch (Exception e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Unregisterung MBean Failed due to ", e.getMessage());
}
}
}
unregisterMonitor(bundle.getBundleId(), null);
}
/**
* @param bundleId
* @param monitor
* This method is used to unregister the monitor and cleansup the Mbeans associated with those monitors.
* The call to this method happens during deactivation of any bundle(Which includes monitor bundles) or
* from the modified method.
*/
public synchronized void unregisterMonitor(Long bundleId, MonitorObject monitor) {
if (monitor != null) {
if (mbeanServer == null)
mbeanServer = AccessController.doPrivileged((PrivilegedAction<MBeanServer>) () -> ManagementFactory.getPlatformMBeanServer());
Set<ObjectName> onameSet = mxmap.remove(monitor.getMonitor());
unregisterMbeans(onameSet);
monitorManager.unregisterMonitor(monitor.getMonitor());
monitor.setRegistered(false);
//(processedBundles.get(bundleId)).remove(monitor);
} else {
Set<MonitorObject> bundleMonitors = processedBundles.remove(bundleId);
if (bundleMonitors == null) {
return;
}
for (MonitorObject o : bundleMonitors) {
Set<ObjectName> mbeanonameset = mxmap.remove(o.getMonitor());
unregisterMbeans(mbeanonameset);
monitorManager.unregisterMonitor(o.getMonitor());
o.setRegistered(false);
}
}
}
/**
* @param context ComponentContext
* @param newProperties
* @throws Exception
* This method is called when ever there is change in server.xml.In Here we will be looking for the list of monitor's which needs
* to be instrumented.If groupMonitoring is specified and there is no input ex: groupMonitoring="" we assume that all the monitors
* needs to be instrumented.If atleast one is preset as part of groupMonitoring i.e, groupMonitoring="WebContainer,JVM,ThreadPool"
* then those present will be instrumented.Please note that rest all monitors which are nor present in groupMonitoring will be
* unregistered and respective Mbeans are removed from the MBeanServer.
*/
protected void modified(ComponentContext context, Map<String, Object> newProperties) throws Exception {
try {
groupList.clear();
String filter = (String) newProperties.get(MONITORING_GROUP_FILTER);
if (!(filter.length() > 0)) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Enabling All:Started");
}
Set<Object> monitorkeys = objectMap.keySet();
Iterator monitorIterator = monitorkeys.iterator();
while (monitorIterator.hasNext()) {
Object monobj = monitorIterator.next();
MonitorObject mob = objectMap.get(monobj);
if (!(mob.getRegistered())) {
Object regMon = constructMonitor(mob.getClazz());
processANDregister(regMon, mob);
}
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Enabling All:Completed");
}
return;
}
StringTokenizer st = new StringTokenizer(filter, ",");
while (st.hasMoreTokens()) {
groupList.add(st.nextToken());
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Enabling those Monitors specified in groupMonitoring and " +
"disabling those which are not specified and are already being monitored");
}
Set<Object> monitorkeys = objectMap.keySet();
Iterator monitorIterator = monitorkeys.iterator();
if (groupList.size() > 0) {
while (monitorIterator.hasNext()) {
Object monobj = monitorIterator.next();
MonitorObject mob = objectMap.get(monobj);
Monitor groups = mob.getGroups();
for (String group : groups.group()) {
if (!(groupList.contains(group))) {
unregisterMonitor(mob.getBundleId(), mob);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Unregistered " + group);
}
} else {
if (!(mob.getRegistered())) {
Object regMon = constructMonitor(mob.getClazz());
processANDregister(regMon, mob);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Registered " + group);
}
}
}
}
}
} else {
while (monitorIterator.hasNext()) {
Object monobj = monitorIterator.next();
MonitorObject mob = objectMap.get(monobj);
if (mob.getRegistered()) {
unregisterMonitor(mob.getBundleId(), mob);
}
}
}
} catch (Exception e) {
e.getMessage();
}
}
/**
* @param onameset
* Used to Unregister Mbeans and takes set as Input.This set contains ObjectNames of the Mbeans which needs to be unregistered.
*/
private void unregisterMbeans(Set<ObjectName> onameset) {
if (mbeanServer != null) {
mbeanServer = AccessController.doPrivileged((PrivilegedAction<MBeanServer>) () -> ManagementFactory.getPlatformMBeanServer());
}
if (onameset == null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Returning from here is onameset is null");
}
return;
} else {
for (ObjectName on : onameset) {
try {
mbeanServer.unregisterMBean(on);
} catch (MBeanRegistrationException e) {
FFDCFilter.processException(e, getClass().getSimpleName(), "deactivateMonitors:MBeanRegistrationException");
} catch (InstanceNotFoundException e) {
FFDCFilter.processException(e, getClass().getSimpleName(), "deactivateMonitors:InstanceNotFoundException");
}
}
}
}
} | epl-1.0 |
coiouhkc/mqg | src/main/java/org/abratuhi/mqg/QueryGenerator.java | 6119 | package org.abratuhi.mqg;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Transformer;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.javatuples.Pair;
public class QueryGenerator {
private static final Logger LOG = Logger.getLogger(QueryGenerator.class);
public class Path {
@Getter @Setter List<Table> tables = new ArrayList<>();
public Path() {}
public Path(Table table) {
tables.add(table);
}
public Path(Path path, Table table) {
tables.addAll(path.getTables());
tables.add(table);
}
public Table last() {
return tables.get(tables.size()-1);
}
public boolean isEmpty() {
return tables.isEmpty();
}
public String toString() {
StringBuffer sb = new StringBuffer();
for(int i=0; i<tables.size()-1; i++) {sb.append(tables.get(i).getName() + " -> "); }
sb.append(last().getName());
return sb.toString();
}
}
@Getter @Setter private IRelatedTableProvider provider;
public List<Table> computeIntermediateJoinTables(Table start, Table end) {
List<Table> result = new ArrayList<>();
return result;
}
public List<Path> computeJoinPaths(List<Table> tables) throws SqlGeneratorException {
List<Path> result = new ArrayList<>();
if(!tables.isEmpty()) {
Table master = tables.get(0);
for (int i = 1; i<tables.size(); i++) {
Table slave = tables.get(i);
Path path = visit(master, slave);
if (path == null) {
path = visit(slave, master);
if (path == null) {
throw new SqlGeneratorException("No join path found for " + master.getName() + " and " + slave.getName());
}
}
result.add(path);
}
}
return result;
}
public Path visit(Table start, Table end) throws SqlGeneratorException {
return visit(start, end, new ArrayList<Path>(), new HashSet<Table>());
}
public Path visit(Table start, Table end, List<Path> paths, Set<Table> visited) throws SqlGeneratorException {
LOG.debug("visit ");
for (Table visit : visited) {
LOG.debug("visit - visited = " + visit.getName());
}
List<Path> npaths = new ArrayList<>();
if (start.equals(end)) {
LOG.debug("visit - start=end, empty path");
return new Path();
} else if (paths.isEmpty()) {
LOG.debug("visit - path list empty, add start path to list");
npaths.add(new Path(start));
visited.add(start);
return visit(start, end, npaths, new HashSet<Table>(visited));
} else {
LOG.debug("visit - examine neighbors");
for (Path path : paths) {
Table last = path.last();
Set<Table> neighbors = new HashSet<>();
neighbors.addAll(provider.getRelated(last));
neighbors.removeAll(visited);
for (Table neighbor : neighbors) {
LOG.debug("visit - neighbour (" + last.getName() + ") = " + neighbor.getName());
}
for (Table table: neighbors) {
Path p = new Path(path, table);
visited.add(table);
if (table.equals(end)) {
return p;
} else {
npaths.add(p);
}
}
}
if (npaths.isEmpty()) {
return null;
} else {
return visit(start, end, npaths, visited);
}
}
}
public Query path2join(Path path) {
Query query = new Query(Junctor.AND);
for(int i=0; i<path.getTables().size()-1; i++) {
Table from = path.getTables().get(i);
Table to = path.getTables().get(i+1);
Pair<Column, Column> joinColumns = provider.getJoinColumns(from, to);
if (null != joinColumns) {
query.addQueryTerm(new Predicate<Column>(Operator.EQUALS, joinColumns.getValue0(), joinColumns.getValue1()));
}
}
return query;
}
public String toSql(Query query) throws SqlGeneratorException {
List<Table> queryTables = new ArrayList<>(query.getUniqueTables());
List<Path> joinPaths = computeJoinPaths(queryTables);
List<Query> joinQueries = new ArrayList<Query>(CollectionUtils.collect(joinPaths, new Transformer<Path, Query>() {
@Override
public Query transform(Path o) {
return QueryGenerator.this.path2join(o);
}
}));
Query queryWithJoins = new Query(Junctor.AND);
queryWithJoins.addQueryTerm(query);
queryWithJoins.addQueryTerms(joinQueries);
StringBuffer sb = new StringBuffer();
sb.append("SELECT ");
if (query.getProjectiles().isEmpty()) {
sb.append("* ");
} else {
String selectSql = StringUtils.join(CollectionUtils.collect(query.getProjectiles(), new Transformer<Column,String>() {
@Override
public String transform(Column projectile) {
return projectile.getTable().getAlias() + "." + projectile.getName();
}
}), ", ");
sb.append(selectSql);
}
queryTables = new ArrayList<>(queryWithJoins.getUniqueTables());
String fromSql = StringUtils.join(CollectionUtils.collect(queryTables, new Transformer<Table,String>() {
@Override
public String transform(Table table) {
return table.getFqdn() + " " + table.getAlias();
}
}), ", ");
sb.append(" FROM ");
sb.append(fromSql);
sb.append(" WHERE ");
sb.append(StringUtils.join(CollectionUtils.collect(queryWithJoins.getTerms(), new Transformer<IQueryTerm, String>() {
@Override
public String transform(IQueryTerm o) {
return o.toSql();
}
}), " " + queryWithJoins.getJunctor() + " "));
return sb.toString();
}
}
| epl-1.0 |
enphoneh/Glide3.6.1_fixbug | src/com/bumptech/glide/request/target/Target.java | 3470 | package com.bumptech.glide.request.target;
import android.graphics.drawable.Drawable;
import com.bumptech.glide.manager.LifecycleListener;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.animation.GlideAnimation;
/**
* An interface that Glide can load a resource into and notify of relevant lifecycle events during a load.
*
* <p>
* The lifecycle events in this class are as follows:
* <ul>
* <li>onLoadStarted</li>
* <li>onResourceReady</li>
* <li>onLoadCleared</li>
* <li>onLoadFailed</li>
* </ul>
*
* The typical lifecycle is onLoadStarted -> onResourceReady or onLoadFailed -> onLoadCleared. However, there are no
* guarantees. onLoadStarted may not be called if the resource is in memory or if the load will fail because of a
* null model object. onLoadCleared similarly may never be called if the target is never cleared. See the docs for
* the individual methods for details.
* </p>
*
* @param <R> The type of resource the target can display.
*/
public interface Target<R> extends LifecycleListener {
/**
* Indicates that we want the resource in its original unmodified width and/or height.
*/
int SIZE_ORIGINAL = Integer.MIN_VALUE;
/**
* A lifecycle callback that is called when a load is started.
*
* <p>
* Note - This may not be called for every load, it is possible for example for loads to fail before the load
* starts (when the model object is null).
* </p>
*
* <p>
* Note - This method may be called multiple times before any other lifecycle method is called. Loads can be
* paused and restarted due to lifecycle or connectivity events and each restart may cause a call here.
* </p>
*
* @param placeholder The placeholder drawable to optionally show, or null.
*/
void onLoadStarted(Drawable placeholder);
/**
* A lifecycle callback that is called when a load fails.
*
* <p>
* Note - This may be called before {@link #onLoadStarted(android.graphics.drawable.Drawable)} if the model
* object is null.
* </p>
*
* @param e The exception causing the load to fail, or null if no exception occurred (usually because a decoder
* simply returned null).
* @param errorDrawable The error drawable to optionally show, or null.
*/
void onLoadFailed(Exception e, Drawable errorDrawable);
/**
* The method that will be called when the resource load has finished.
*
* @param resource the loaded resource.
*/
void onResourceReady(R resource, GlideAnimation<? super R> glideAnimation);
/**
* A lifecycle callback that is called when a load is cancelled and its resources are freed.
*
* @param placeholder The placeholder drawable to optionally show, or null.
*/
void onLoadCleared(Drawable placeholder);
/**
* A method to retrieve the size of this target.
*
* @param cb The callback that must be called when the size of the target has been determined
*/
void getSize(SizeReadyCallback cb);
/**
* Sets the current request for this target to retain, should not be called outside of Glide.
*/
void setRequest(Request request);
/**
* Retrieves the current request for this target, should not be called outside of Glide.
*/
Request getRequest();
}
| epl-1.0 |
InspiringCode/Inspiring.MVVM | Source/Mvvm/Common/Behaviors/BehaviorChainTemplateKeys.cs | 461 | namespace Inspiring.Mvvm.ViewModels.Core {
using System;
using System.Linq.Expressions;
using Inspiring.Mvvm.Common;
public abstract class BehaviorChainTemplateKeys {
protected static BehaviorChainTemplateKey Key(Expression<Func<BehaviorChainTemplateKey>> behaviorFieldSelector) {
string key = ExpressionService.GetPropertyName(behaviorFieldSelector);
return new BehaviorChainTemplateKey(key);
}
}
}
| epl-1.0 |
riuvshin/che-plugins | plugin-runner/che-plugin-runner-ext-runner/src/main/java/org/eclipse/che/ide/ext/runner/client/tabs/console/panel/ConsoleImpl.java | 7259 | /*******************************************************************************
* Copyright (c) 2012-2015 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.ext.runner.client.tabs.console.panel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import org.eclipse.che.api.core.rest.shared.dto.Link;
import org.eclipse.che.ide.ext.runner.client.RunnerResources;
import org.eclipse.che.ide.ext.runner.client.inject.factories.WidgetFactory;
import org.eclipse.che.ide.ext.runner.client.models.Runner;
import javax.validation.constraints.NotNull;
import static org.eclipse.che.ide.ext.runner.client.tabs.console.panel.Lines.CLEANED;
import static org.eclipse.che.ide.ext.runner.client.tabs.console.panel.Lines.MAXIMUM;
import static org.eclipse.che.ide.ext.runner.client.tabs.console.panel.MessageType.DOCKER;
import static org.eclipse.che.ide.ext.runner.client.tabs.console.panel.MessageType.ERROR;
import static org.eclipse.che.ide.ext.runner.client.tabs.console.panel.MessageType.INFO;
import static org.eclipse.che.ide.ext.runner.client.tabs.console.panel.MessageType.WARNING;
/**
* @author Artem Zatsarynnyy
* @author Vitaliy Guliy
* @author Mihail Kuznyetsov
* @author Andrey Plotnikov
* @author Valeriy Svydenko
*/
public class ConsoleImpl extends Composite implements Console {
interface ConsoleImplUiBinder extends UiBinder<Widget, ConsoleImpl> {
}
private static final ConsoleImplUiBinder UI_BINDER = GWT.create(ConsoleImplUiBinder.class);
@UiField
ScrollPanel panel;
@UiField
FlowPanel output;
@UiField
FlowPanel mainPanel;
@UiField(provided = true)
final RunnerResources res;
private final Provider<MessageBuilder> messageBuilderProvider;
private final WidgetFactory widgetFactory;
private final Runner runner;
private boolean isWrappedText;
@Inject
public ConsoleImpl(RunnerResources resources,
Provider<MessageBuilder> messageBuilderProvider,
WidgetFactory widgetFactory,
@NotNull @Assisted Runner runner) {
this.res = resources;
this.messageBuilderProvider = messageBuilderProvider;
this.widgetFactory = widgetFactory;
this.runner = runner;
initWidget(UI_BINDER.createAndBindUi(this));
}
/** {@inheritDoc} */
@Override
public void print(@NotNull String text) {
// nothing to display
if (text.isEmpty()) {
return;
}
//The message from server can be include a few lines of console
// We detect type from the full message which can be multiline
MessageType messageType = MessageType.detect(text);
for (String message : text.split("\n")) {
if (message.isEmpty()) {
// don't print empty message
continue;
}
MessageBuilder messageBuilder = messageBuilderProvider.get()
.message(message)
.type(messageType);
if (DOCKER.equals(messageType) && message.startsWith(DOCKER.getPrefix() + ' ' + ERROR.getPrefix())) {
messageBuilder.type(ERROR);
}
print(messageBuilder.build());
}
}
/** {@inheritDoc} */
@Override
public void printInfo(@NotNull String line) {
MessageBuilder messageBuilder = messageBuilderProvider.get()
.type(INFO)
.message(INFO.getPrefix() + ' ' + line);
print(messageBuilder.build());
}
/** {@inheritDoc} */
@Override
public void printError(@NotNull String line) {
MessageBuilder messageBuilder = messageBuilderProvider.get()
.type(ERROR)
.message(ERROR.getPrefix() + ' ' + line);
print(messageBuilder.build());
}
/** {@inheritDoc} */
@Override
public void printWarn(@NotNull String line) {
MessageBuilder messageBuilder = messageBuilderProvider.get()
.type(WARNING)
.message(WARNING.getPrefix() + ' ' + line);
print(messageBuilder.build());
}
private void print(@NotNull SafeHtml message) {
cleanOverHeadLinesIfAny();
HTML html = new HTML(message);
html.getElement().getStyle().setPaddingLeft(2, Style.Unit.PX);
if (isWrappedText) {
html.addStyleName(res.runnerCss().wrappedText());
}
output.add(html);
scrollBottom();
}
private void cleanOverHeadLinesIfAny() {
if (output.getWidgetCount() < MAXIMUM.getValue()) {
return;
}
// remove first 10% of current lines on screen
for (int i = 0; i < CLEANED.getValue(); i++) {
output.remove(0);
}
Link logLink = runner.getLogUrl();
if (logLink == null) {
return;
}
String logUrl = logLink.getHref();
if (logUrl == null) {
return;
}
// print link to full logs in top of console
output.insert(widgetFactory.createFullLogMessage(logUrl), 0);
}
/** {@inheritDoc} */
@Override
public void scrollBottom() {
panel.getElement().setScrollTop(panel.getElement().getScrollHeight());
}
/** {@inheritDoc} */
@Override
public void clear() {
output.clear();
}
/** {@inheritDoc} */
@Override
public void changeWrapTextParam() {
isWrappedText = !isWrappedText;
String wrappedText = res.runnerCss().wrappedText();
for (int i = 0; i < output.getWidgetCount(); i++) {
Widget widget = output.getWidget(i);
if (isWrappedText) {
widget.addStyleName(wrappedText);
} else {
widget.removeStyleName(wrappedText);
}
}
}
/** {@inheritDoc} */
@Override
public boolean isWrapText() {
return isWrappedText;
}
}
| epl-1.0 |
cschwer/com.zsmartsystems.zigbee | com.zsmartsystems.zigbee/src/main/java/com/zsmartsystems/zigbee/zcl/clusters/iasace/GetZoneIdMapCommand.java | 1463 | /**
* Copyright (c) 2016-2019 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.zsmartsystems.zigbee.zcl.clusters.iasace;
import javax.annotation.Generated;
import com.zsmartsystems.zigbee.zcl.ZclCommand;
import com.zsmartsystems.zigbee.zcl.protocol.ZclCommandDirection;
/**
* Get Zone ID Map Command value object class.
* <p>
* Cluster: <b>IAS ACE</b>. Command is sent <b>TO</b> the server.
* This command is a <b>specific</b> command used for the IAS ACE cluster.
* <p>
* Code is auto-generated. Modifications may be overwritten!
*/
@Generated(value = "com.zsmartsystems.zigbee.autocode.ZclProtocolCodeGenerator", date = "2018-04-13T17:16:42Z")
public class GetZoneIdMapCommand extends ZclCommand {
/**
* Default constructor.
*/
public GetZoneIdMapCommand() {
genericCommand = false;
clusterId = 1281;
commandId = 5;
commandDirection = ZclCommandDirection.CLIENT_TO_SERVER;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder(22);
builder.append("GetZoneIdMapCommand [");
builder.append(super.toString());
builder.append(']');
return builder.toString();
}
}
| epl-1.0 |
devonbryant/safe | safe-core/src/main/scala/safe/io/LocalAudioFileIterator.scala | 1910 | package safe.io
import safe.audio.Audio
import java.io.File
import scala.collection.mutable
class LocalAudioFileIterator(path: String, recursive: Boolean = false) extends Iterator[String] {
val pathFile = new File(path)
val queue = new mutable.Queue[File]()
if (pathFile.isDirectory()) queue ++= nextFiles(pathFile)
else if (supportedFileType(pathFile)) queue += pathFile
lazy val totalSize = countFiles(new File(path))
// Get the child files in a directory that are supported audio types or sub-directories
def nextFiles(file: File) = listDir(file) filter { f =>
(f.isDirectory() && recursive) || supportedFileType(f)
}
def countFiles(file: File): Int = {
if (file.isDirectory()) {
var count = 0
listDir(file) foreach { f =>
if (recursive) count += countFiles(f)
else if (supportedFileType(f)) count += 1
}
count
}
else if (supportedFileType(file)) 1
else 0
}
def listDir(file: File) = Option(file.listFiles()).getOrElse(Array[File]())
def supportedFileType(file: File) = {
val name = file.getName()
val idx = name.lastIndexOf('.')
if (idx == -1) false
else {
val extension = name.substring(idx + 1)
Audio.supportedFormats exists { _.equalsIgnoreCase(extension) }
}
}
override def size() = totalSize
override def hasNext() = {
if (queue.isEmpty) false
else if (!queue.front.isDirectory) true // We have an audio file at the front of the queue
else {
// Process/Load the queue until an audio file is at the front
while (!queue.isEmpty && queue.front.isDirectory) {
queue ++= nextFiles(queue.dequeue())
}
!queue.isEmpty
}
}
override def next() = {
if (hasNext()) {
queue.dequeue().getAbsolutePath()
}
else throw new java.util.NoSuchElementException("Iterator is empty")
}
} | epl-1.0 |
bunsha/french | app/User.php | 803 | <?php namespace French;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/t24/core/com.odcgroup.t24.application.model/src/main/generated/com/odcgroup/t24/applicationimport/schema/ApplicationField.java | 20798 |
package com.odcgroup.t24.applicationimport.schema;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ApplicationField complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ApplicationField">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="alignment" type="{http://www.temenos.com/t24-meta}FieldAlignment" minOccurs="0"/>
* <element name="business-type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="concat-file" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="core" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="gen-operation" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="documentation" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="input-behaviour" type="{http://www.temenos.com/t24-meta}InputBehaviour"/>
* <element name="is-image" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="is-textarea" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="onchange-behaviour" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="label" type="{http://www.temenos.com/t24-meta}Translation" maxOccurs="unbounded" minOccurs="0"/>
* <element name="mandatory" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="mask" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="max-length" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/>
* <element name="multi-language" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="multi-value-group-name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="mv-sv-expansion-access" type="{http://www.temenos.com/t24-meta}MvSvExpansionAccess" minOccurs="0"/>
* <element name="name-t24" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="primary-key" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="range" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="ref-application" type="{http://www.temenos.com/t24-meta}ApplicationReference" minOccurs="0"/>
* <element name="sub-value-group-name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="sys-number" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/>
* <element name="tooltip" type="{http://www.temenos.com/t24-meta}Translation" maxOccurs="unbounded" minOccurs="0"/>
* <element name="type" type="{http://www.temenos.com/t24-meta}FieldType" minOccurs="0"/>
* <element name="type-modifiers" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="valid-value" type="{http://www.temenos.com/t24-meta}FieldValidValue" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ApplicationField", propOrder = {
"alignment",
"businessType",
"concatFile",
"core",
"genOperation",
"documentation",
"inputBehaviour",
"isImage",
"isTextarea",
"onchangeBehaviour",
"label",
"mandatory",
"mask",
"maxLength",
"multiLanguage",
"multiValueGroupName",
"mvSvExpansionAccess",
"nameT24",
"primaryKey",
"range",
"refApplication",
"subValueGroupName",
"sysNumber",
"tooltip",
"type",
"typeModifiers",
"validValue"
})
public class ApplicationField {
protected FieldAlignment alignment;
@XmlElement(name = "business-type")
protected String businessType;
@XmlElement(name = "concat-file")
protected String concatFile;
protected boolean core;
@XmlElement(name = "gen-operation")
protected String genOperation;
protected String documentation;
@XmlElement(name = "input-behaviour", required = true)
protected InputBehaviour inputBehaviour;
@XmlElement(name = "is-image")
protected Boolean isImage;
@XmlElement(name = "is-textarea")
protected Boolean isTextarea;
@XmlElement(name = "onchange-behaviour")
protected String onchangeBehaviour;
protected List<Translation> label;
protected Boolean mandatory;
protected String mask;
@XmlElement(name = "max-length")
protected BigInteger maxLength;
@XmlElement(name = "multi-language")
protected Boolean multiLanguage;
@XmlElement(name = "multi-value-group-name")
protected String multiValueGroupName;
@XmlElement(name = "mv-sv-expansion-access")
protected MvSvExpansionAccess mvSvExpansionAccess;
@XmlElement(name = "name-t24")
protected String nameT24;
@XmlElement(name = "primary-key")
protected Boolean primaryKey;
protected String range;
@XmlElement(name = "ref-application")
protected ApplicationReference refApplication;
@XmlElement(name = "sub-value-group-name")
protected String subValueGroupName;
@XmlElement(name = "sys-number")
protected Double sysNumber;
protected List<Translation> tooltip;
protected FieldType type;
@XmlElement(name = "type-modifiers")
protected String typeModifiers;
@XmlElement(name = "valid-value")
protected List<FieldValidValue> validValue;
@XmlAttribute(name = "name", required = true)
protected String name;
/**
* Gets the value of the alignment property.
*
* @return
* possible object is
* {@link FieldAlignment }
*
*/
public FieldAlignment getAlignment() {
return alignment;
}
/**
* Sets the value of the alignment property.
*
* @param value
* allowed object is
* {@link FieldAlignment }
*
*/
public void setAlignment(FieldAlignment value) {
this.alignment = value;
}
/**
* Gets the value of the businessType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBusinessType() {
return businessType;
}
/**
* Sets the value of the businessType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBusinessType(String value) {
this.businessType = value;
}
/**
* Gets the value of the concatFile property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConcatFile() {
return concatFile;
}
/**
* Sets the value of the concatFile property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConcatFile(String value) {
this.concatFile = value;
}
/**
* Gets the value of the core property.
*
*/
public boolean isCore() {
return core;
}
/**
* Sets the value of the core property.
*
*/
public void setCore(boolean value) {
this.core = value;
}
/**
* Gets the value of the genOperation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGenOperation() {
return genOperation;
}
/**
* Sets the value of the genOperation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGenOperation(String value) {
this.genOperation = value;
}
/**
* Gets the value of the documentation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDocumentation() {
return documentation;
}
/**
* Sets the value of the documentation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDocumentation(String value) {
this.documentation = value;
}
/**
* Gets the value of the inputBehaviour property.
*
* @return
* possible object is
* {@link InputBehaviour }
*
*/
public InputBehaviour getInputBehaviour() {
return inputBehaviour;
}
/**
* Sets the value of the inputBehaviour property.
*
* @param value
* allowed object is
* {@link InputBehaviour }
*
*/
public void setInputBehaviour(InputBehaviour value) {
this.inputBehaviour = value;
}
/**
* Gets the value of the isImage property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isIsImage() {
return isImage;
}
/**
* Sets the value of the isImage property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setIsImage(Boolean value) {
this.isImage = value;
}
/**
* Gets the value of the isTextarea property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isIsTextarea() {
return isTextarea;
}
/**
* Sets the value of the isTextarea property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setIsTextarea(Boolean value) {
this.isTextarea = value;
}
/**
* Gets the value of the onchangeBehaviour property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOnchangeBehaviour() {
return onchangeBehaviour;
}
/**
* Sets the value of the onchangeBehaviour property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOnchangeBehaviour(String value) {
this.onchangeBehaviour = value;
}
/**
* Gets the value of the label property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the label property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLabel().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Translation }
*
*
*/
public List<Translation> getLabel() {
if (label == null) {
label = new ArrayList<Translation>();
}
return this.label;
}
/**
* Gets the value of the mandatory property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isMandatory() {
return mandatory;
}
/**
* Sets the value of the mandatory property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setMandatory(Boolean value) {
this.mandatory = value;
}
/**
* Gets the value of the mask property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMask() {
return mask;
}
/**
* Sets the value of the mask property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMask(String value) {
this.mask = value;
}
/**
* Gets the value of the maxLength property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getMaxLength() {
return maxLength;
}
/**
* Sets the value of the maxLength property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setMaxLength(BigInteger value) {
this.maxLength = value;
}
/**
* Gets the value of the multiLanguage property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isMultiLanguage() {
return multiLanguage;
}
/**
* Sets the value of the multiLanguage property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setMultiLanguage(Boolean value) {
this.multiLanguage = value;
}
/**
* Gets the value of the multiValueGroupName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMultiValueGroupName() {
return multiValueGroupName;
}
/**
* Sets the value of the multiValueGroupName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMultiValueGroupName(String value) {
this.multiValueGroupName = value;
}
/**
* Gets the value of the mvSvExpansionAccess property.
*
* @return
* possible object is
* {@link MvSvExpansionAccess }
*
*/
public MvSvExpansionAccess getMvSvExpansionAccess() {
return mvSvExpansionAccess;
}
/**
* Sets the value of the mvSvExpansionAccess property.
*
* @param value
* allowed object is
* {@link MvSvExpansionAccess }
*
*/
public void setMvSvExpansionAccess(MvSvExpansionAccess value) {
this.mvSvExpansionAccess = value;
}
/**
* Gets the value of the nameT24 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNameT24() {
return nameT24;
}
/**
* Sets the value of the nameT24 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNameT24(String value) {
this.nameT24 = value;
}
/**
* Gets the value of the primaryKey property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isPrimaryKey() {
return primaryKey;
}
/**
* Sets the value of the primaryKey property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setPrimaryKey(Boolean value) {
this.primaryKey = value;
}
/**
* Gets the value of the range property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRange() {
return range;
}
/**
* Sets the value of the range property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRange(String value) {
this.range = value;
}
/**
* Gets the value of the refApplication property.
*
* @return
* possible object is
* {@link ApplicationReference }
*
*/
public ApplicationReference getRefApplication() {
return refApplication;
}
/**
* Sets the value of the refApplication property.
*
* @param value
* allowed object is
* {@link ApplicationReference }
*
*/
public void setRefApplication(ApplicationReference value) {
this.refApplication = value;
}
/**
* Gets the value of the subValueGroupName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSubValueGroupName() {
return subValueGroupName;
}
/**
* Sets the value of the subValueGroupName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSubValueGroupName(String value) {
this.subValueGroupName = value;
}
/**
* Gets the value of the sysNumber property.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getSysNumber() {
return sysNumber;
}
/**
* Sets the value of the sysNumber property.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setSysNumber(Double value) {
this.sysNumber = value;
}
/**
* Gets the value of the tooltip property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the tooltip property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTooltip().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Translation }
*
*
*/
public List<Translation> getTooltip() {
if (tooltip == null) {
tooltip = new ArrayList<Translation>();
}
return this.tooltip;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link FieldType }
*
*/
public FieldType getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link FieldType }
*
*/
public void setType(FieldType value) {
this.type = value;
}
/**
* Gets the value of the typeModifiers property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTypeModifiers() {
return typeModifiers;
}
/**
* Sets the value of the typeModifiers property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTypeModifiers(String value) {
this.typeModifiers = value;
}
/**
* Gets the value of the validValue property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the validValue property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getValidValue().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FieldValidValue }
*
*
*/
public List<FieldValidValue> getValidValue() {
if (validValue == null) {
validValue = new ArrayList<FieldValidValue>();
}
return this.validValue;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
}
| epl-1.0 |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/UriTaskProviderModelParser.java | 4213 | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
/**
* Parser for json-formatted information about a URI task provider.
*/
public class UriTaskProviderModelParser {
private static final Gson GSON = new GsonBuilder()
.registerTypeAdapter(UriTaskProviderModel.Metadata.class, new MetaDataAdapter())
.registerTypeAdapter(UriTaskProviderModel.class, new UriTaskModelAdapter())
.create();
private static final class Types {
static final Type metadata = new TypeToken<UriTaskProviderModel.Metadata>(){}.getType();
public static Type uriArray = new TypeToken<URI[]>(){}.getType();
}
private static class MetaDataAdapter implements JsonDeserializer<UriTaskProviderModel.Metadata> {
public UriTaskProviderModel.Metadata deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jo = json.getAsJsonObject();
String description = deserialize(jo, "description");
if (description == null) {
throw new JsonParseException("description is missing");
}
return new UriTaskProviderModel.Metadata(
deserialize(jo, "name"),
description,
deserialize(jo, "contact"));
}
private String deserialize(JsonObject jo, String field) {
JsonElement val = jo.get(field);
if (val == null) {
return null;
}
return val.getAsString();
}
}
private static class UriTaskModelAdapter implements JsonDeserializer<UriTaskProviderModel> {
private static final String TYPE = "com.google.eclipse.mechanic.UriTaskProviderModel";
public UriTaskProviderModel deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jo = json.getAsJsonObject();
JsonElement je = jo.get("type");
if (je == null || !je.getAsString().equals(TYPE)) {
throw new IllegalArgumentException(
String.format("URI task models must have an entry type='%s'", TYPE));
}
UriTaskProviderModel.Metadata metadata = (UriTaskProviderModel.Metadata) context.deserialize(
jo.get("metadata"), Types.metadata);
if (metadata == null) {
throw new JsonParseException("metadata is required");
}
URI[] uriArray = (URI[]) context.deserialize(jo.get("tasks"), Types.uriArray);
if (uriArray == null) {
throw new JsonParseException("tasks is requried");
}
List<URI> tasks = Arrays.asList(uriArray);
return new UriTaskProviderModel(metadata, tasks);
}
}
public static UriTaskProviderModel read(InputStream is) throws JsonSyntaxException, JsonIOException{
return GSON.fromJson(new InputStreamReader(is), UriTaskProviderModel.class);
}
/**
* Parse a model from a string.
*
* This has to exist here because GSON isn't made available outside this
* plug-in, and the {@link #read(InputStream)} function throws
* JsonSyntaxException and JsonIOException.
*/
public static UriTaskProviderModel readForTests(String text) throws RuntimeException {
return read(new ByteArrayInputStream(text.getBytes()));
}
}
| epl-1.0 |
forge/javaee-descriptors | api/src/main/java/org/jboss/shrinkwrap/descriptor/api/beans11/Beans.java | 7530 | package org.jboss.shrinkwrap.descriptor.api.beans11;
import java.util.List;
import org.jboss.shrinkwrap.descriptor.api.Child;
/**
* This interface defines the contract for the <code> beans </code> xsd type
* @author <a href="mailto:ralf.battenfeld@bluewin.ch">Ralf Battenfeld</a>
* @author <a href="mailto:alr@jboss.org">Andrew Lee Rubinger</a>
*/
public interface Beans<T> extends Child<T>
{
// --------------------------------------------------------------------------------------------------------||
// ClassName: Beans ElementName: javaee:interceptors ElementType : interceptors
// MaxOccurs: -unbounded isGeneric: true isAttribute: false isEnum: false isDataType: false
// --------------------------------------------------------------------------------------------------------||
/**
* If not already created, a new <code>interceptors</code> element will be created and returned.
* Otherwise, the first existing <code>interceptors</code> element will be returned.
* @return the instance defined for the element <code>interceptors</code>
*/
public Interceptors<Beans<T>> getOrCreateInterceptors();
/**
* Creates a new <code>interceptors</code> element
* @return the new created instance of <code>Interceptors<Beans<T>></code>
*/
public Interceptors<Beans<T>> createInterceptors();
/**
* Returns all <code>interceptors</code> elements
* @return list of <code>interceptors</code>
*/
public List<Interceptors<Beans<T>>> getAllInterceptors();
/**
* Removes all <code>interceptors</code> elements
* @return the current instance of <code>Interceptors<Beans<T>></code>
*/
public Beans<T> removeAllInterceptors();
// --------------------------------------------------------------------------------------------------------||
// ClassName: Beans ElementName: javaee:decorators ElementType : decorators
// MaxOccurs: -unbounded isGeneric: true isAttribute: false isEnum: false isDataType: false
// --------------------------------------------------------------------------------------------------------||
/**
* If not already created, a new <code>decorators</code> element will be created and returned.
* Otherwise, the first existing <code>decorators</code> element will be returned.
* @return the instance defined for the element <code>decorators</code>
*/
public Decorators<Beans<T>> getOrCreateDecorators();
/**
* Creates a new <code>decorators</code> element
* @return the new created instance of <code>Decorators<Beans<T>></code>
*/
public Decorators<Beans<T>> createDecorators();
/**
* Returns all <code>decorators</code> elements
* @return list of <code>decorators</code>
*/
public List<Decorators<Beans<T>>> getAllDecorators();
/**
* Removes all <code>decorators</code> elements
* @return the current instance of <code>Decorators<Beans<T>></code>
*/
public Beans<T> removeAllDecorators();
// --------------------------------------------------------------------------------------------------------||
// ClassName: Beans ElementName: javaee:alternatives ElementType : alternatives
// MaxOccurs: -unbounded isGeneric: true isAttribute: false isEnum: false isDataType: false
// --------------------------------------------------------------------------------------------------------||
/**
* If not already created, a new <code>alternatives</code> element will be created and returned.
* Otherwise, the first existing <code>alternatives</code> element will be returned.
* @return the instance defined for the element <code>alternatives</code>
*/
public Alternatives<Beans<T>> getOrCreateAlternatives();
/**
* Creates a new <code>alternatives</code> element
* @return the new created instance of <code>Alternatives<Beans<T>></code>
*/
public Alternatives<Beans<T>> createAlternatives();
/**
* Returns all <code>alternatives</code> elements
* @return list of <code>alternatives</code>
*/
public List<Alternatives<Beans<T>>> getAllAlternatives();
/**
* Removes all <code>alternatives</code> elements
* @return the current instance of <code>Alternatives<Beans<T>></code>
*/
public Beans<T> removeAllAlternatives();
// --------------------------------------------------------------------------------------------------------||
// ClassName: Beans ElementName: javaee:scan ElementType : scan
// MaxOccurs: -unbounded isGeneric: true isAttribute: false isEnum: false isDataType: false
// --------------------------------------------------------------------------------------------------------||
/**
* If not already created, a new <code>scan</code> element will be created and returned.
* Otherwise, the first existing <code>scan</code> element will be returned.
* @return the instance defined for the element <code>scan</code>
*/
public Scan<Beans<T>> getOrCreateScan();
/**
* Creates a new <code>scan</code> element
* @return the new created instance of <code>Scan<Beans<T>></code>
*/
public Scan<Beans<T>> createScan();
/**
* Returns all <code>scan</code> elements
* @return list of <code>scan</code>
*/
public List<Scan<Beans<T>>> getAllScan();
/**
* Removes all <code>scan</code> elements
* @return the current instance of <code>Scan<Beans<T>></code>
*/
public Beans<T> removeAllScan();
// --------------------------------------------------------------------------------------------------------||
// ClassName: Beans ElementName: xsd:string ElementType : version
// MaxOccurs: - isGeneric: true isAttribute: true isEnum: false isDataType: true
// --------------------------------------------------------------------------------------------------------||
/**
* Sets the <code>version</code> attribute
* @param version the value for the attribute <code>version</code>
* @return the current instance of <code>Beans<T></code>
*/
public Beans<T> version(String version);
/**
* Returns the <code>version</code> attribute
* @return the value defined for the attribute <code>version</code>
*/
public String getVersion();
/**
* Removes the <code>version</code> attribute
* @return the current instance of <code>Beans<T></code>
*/
public Beans<T> removeVersion();
// --------------------------------------------------------------------------------------------------------||
// ClassName: Beans ElementName: xsd:string ElementType : bean-discovery-mode
// MaxOccurs: - isGeneric: true isAttribute: true isEnum: false isDataType: true
// --------------------------------------------------------------------------------------------------------||
/**
* Sets the <code>bean-discovery-mode</code> attribute
* @param beanDiscoveryMode the value for the attribute <code>bean-discovery-mode</code>
* @return the current instance of <code>Beans<T></code>
*/
public Beans<T> beanDiscoveryMode(String beanDiscoveryMode);
/**
* Returns the <code>bean-discovery-mode</code> attribute
* @return the value defined for the attribute <code>bean-discovery-mode</code>
*/
public String getBeanDiscoveryMode();
/**
* Removes the <code>bean-discovery-mode</code> attribute
* @return the current instance of <code>Beans<T></code>
*/
public Beans<T> removeBeanDiscoveryMode();
}
| epl-1.0 |
EBusinesss/SW_STSIR | StationJPA/src/org/lmcu/siredo/jpa/Station.java | 1361 | /**
*
*/
package org.lmcu.siredo.jpa;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
/**
* @author LAMGHARI Mohammed
*
*/
@Entity
public class Station {
@Id
@SequenceGenerator( name = "id_StationSeq", sequenceName = "id_Station_seq", allocationSize = 1, initialValue = 1 )
@GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "id_StationSeq" )
@Column( name = "id_Station" )
private int id_Station;
/* @Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id_Station;*/
private String nom_Station;
private String adr_Station;
@ManyToOne
@JoinColumn(name="id_Marque")
private Marque marque;
public String getNom_Station() {
return nom_Station;
}
public void setNom_Station(String nom_Station) {
this.nom_Station = nom_Station;
}
public Marque getMarque() {
return marque;
}
public void setMarque(Marque marque) {
this.marque = marque;
}
public int getId_Station() {
return id_Station;
}
public String getAdr_Station() {
return adr_Station;
}
public void setAdr_Station(String adr_Station) {
this.adr_Station = adr_Station;
}
}
| epl-1.0 |
lunifera/lunifera-ecview | org.lunifera.ecview.core.common.model/src/org/lunifera/ecview/core/common/model/binding/impl/YBindingSetImpl.java | 12411 | /**
* Copyright (c) 2011 - 2015, Lunifera GmbH (Gross Enzersdorf), Loetz KG (Heidelberg)
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Florian Pirchner - Initial implementation
*/
package org.lunifera.ecview.core.common.model.binding.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.lunifera.ecview.core.common.model.binding.BindingFactory;
import org.lunifera.ecview.core.common.model.binding.BindingPackage;
import org.lunifera.ecview.core.common.model.binding.YBinding;
import org.lunifera.ecview.core.common.model.binding.YBindingSet;
import org.lunifera.ecview.core.common.model.binding.YBindingUpdateStrategy;
import org.lunifera.ecview.core.common.model.binding.YListBinding;
import org.lunifera.ecview.core.common.model.binding.YListBindingEndpoint;
import org.lunifera.ecview.core.common.model.binding.YValueBinding;
import org.lunifera.ecview.core.common.model.binding.YValueBindingEndpoint;
import org.lunifera.ecview.core.common.model.core.YView;
/**
* <!-- begin-user-doc --> An implementation of the model object '
* <em><b>YBinding Set</b></em>'. <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.lunifera.ecview.core.common.model.binding.impl.YBindingSetImpl#getId <em>Id</em>}</li>
* <li>{@link org.lunifera.ecview.core.common.model.binding.impl.YBindingSetImpl#getName <em>Name</em>}</li>
* <li>{@link org.lunifera.ecview.core.common.model.binding.impl.YBindingSetImpl#getBindings <em>Bindings</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class YBindingSetImpl extends MinimalEObjectImpl.Container implements
YBindingSet {
/**
* The default value of the '{@link #getId() <em>Id</em>}' attribute. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @see #getId()
* @generated
* @ordered
*/
protected static final String ID_EDEFAULT = null;
/**
* The cached value of the '{@link #getId() <em>Id</em>}' attribute. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @see #getId()
* @generated
* @ordered
*/
protected String id = ID_EDEFAULT;
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The cached value of the '{@link #getBindings() <em>Bindings</em>}' containment reference list.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getBindings()
* @generated
* @ordered
*/
protected EList<YBinding> bindings;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
protected YBindingSetImpl() {
super();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return BindingPackage.Literals.YBINDING_SET;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public String getId() {
return id;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setId(String newId) {
String oldId = id;
id = newId;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BindingPackage.YBINDING_SET__ID, oldId, id));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BindingPackage.YBINDING_SET__NAME, oldName, name));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EList<YBinding> getBindings() {
if (bindings == null) {
bindings = new EObjectContainmentEList.Resolving<YBinding>(YBinding.class, this, BindingPackage.YBINDING_SET__BINDINGS);
}
return bindings;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public YValueBinding addBindingGen(YValueBindingEndpoint targetValue,
YValueBindingEndpoint modelValue) {
// TODO: implement this method
// Ensure that you remove @generated or mark it @generated NOT
throw new UnsupportedOperationException();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
public YValueBinding addBinding(YValueBindingEndpoint targetValue,
YValueBindingEndpoint modelValue) {
return addBinding(targetValue, modelValue,
YBindingUpdateStrategy.UPDATE, YBindingUpdateStrategy.UPDATE);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public YListBinding addBindingGen(YListBindingEndpoint targetValue,
YListBindingEndpoint modelValue) {
// TODO: implement this method
// Ensure that you remove @generated or mark it @generated NOT
throw new UnsupportedOperationException();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
public YListBinding addBinding(YListBindingEndpoint targetValue,
YListBindingEndpoint modelValue) {
return addBinding(targetValue, modelValue,
YBindingUpdateStrategy.UPDATE, YBindingUpdateStrategy.UPDATE);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
public YValueBinding addBinding(YValueBindingEndpoint targetValue,
YValueBindingEndpoint modelValue,
YBindingUpdateStrategy targetToModelStrategy,
YBindingUpdateStrategy modelToTargetStrategy) {
// create a new binding
YValueBinding binding = BindingFactory.eINSTANCE.createYValueBinding();
binding.setTargetEndpoint(targetValue);
binding.setModelEndpoint(modelValue);
binding.setModelToTargetStrategy(modelToTargetStrategy);
binding.setTargetToModelStrategy(targetToModelStrategy);
// add the binding to the internal list of bindings
getBindings().add(binding);
return binding;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
public YListBinding addBinding(YListBindingEndpoint targetValue,
YListBindingEndpoint modelValue,
YBindingUpdateStrategy targetToModelStrategy,
YBindingUpdateStrategy modelToTargetStrategy) {
// create a new binding
YListBinding binding = BindingFactory.eINSTANCE.createYListBinding();
binding.setTargetEndpoint(targetValue);
binding.setModelEndpoint(modelValue);
binding.setModelToTargetStrategy(modelToTargetStrategy);
binding.setTargetToModelStrategy(targetToModelStrategy);
// add the binding to the internal list of bindings
getBindings().add(binding);
return binding;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public YValueBinding addBindingGen(YValueBindingEndpoint targetValue,
YValueBindingEndpoint modelValue,
YBindingUpdateStrategy targetToModelStrategy,
YBindingUpdateStrategy modelToTargetStrategy) {
// TODO: implement this method
// Ensure that you remove @generated or mark it @generated NOT
throw new UnsupportedOperationException();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public YListBinding addBindingGen(YListBindingEndpoint targetValue,
YListBindingEndpoint modelValue,
YBindingUpdateStrategy targetToModelStrategy,
YBindingUpdateStrategy modelToTargetStrategy) {
// TODO: implement this method
// Ensure that you remove @generated or mark it @generated NOT
throw new UnsupportedOperationException();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public YView getViewGen() {
// TODO: implement this method
// Ensure that you remove @generated or mark it @generated NOT
throw new UnsupportedOperationException();
}
/**
* Returns the view that binding set is attached to.
*
* @generated NOT
*/
public YView getView() {
return (YView) eContainer();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void addBindingGen(YBinding binding) {
// TODO: implement this method
// Ensure that you remove @generated or mark it @generated NOT
throw new UnsupportedOperationException();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
public void addBinding(YBinding binding) {
getBindings().add(binding);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void removeBindingGen(YBinding binding) {
// TODO: implement this method
// Ensure that you remove @generated or mark it @generated NOT
throw new UnsupportedOperationException();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
public void removeBinding(YBinding binding) {
getBindings().remove(binding);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd,
int featureID, NotificationChain msgs) {
switch (featureID) {
case BindingPackage.YBINDING_SET__BINDINGS:
return ((InternalEList<?>)getBindings()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case BindingPackage.YBINDING_SET__ID:
return getId();
case BindingPackage.YBINDING_SET__NAME:
return getName();
case BindingPackage.YBINDING_SET__BINDINGS:
return getBindings();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case BindingPackage.YBINDING_SET__ID:
setId((String)newValue);
return;
case BindingPackage.YBINDING_SET__NAME:
setName((String)newValue);
return;
case BindingPackage.YBINDING_SET__BINDINGS:
getBindings().clear();
getBindings().addAll((Collection<? extends YBinding>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case BindingPackage.YBINDING_SET__ID:
setId(ID_EDEFAULT);
return;
case BindingPackage.YBINDING_SET__NAME:
setName(NAME_EDEFAULT);
return;
case BindingPackage.YBINDING_SET__BINDINGS:
getBindings().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case BindingPackage.YBINDING_SET__ID:
return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id);
case BindingPackage.YBINDING_SET__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case BindingPackage.YBINDING_SET__BINDINGS:
return bindings != null && !bindings.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (id: ");
result.append(id);
result.append(", name: ");
result.append(name);
result.append(')');
return result.toString();
}
} // YBindingSetImpl
| epl-1.0 |
belkassaby/dawnsci | org.eclipse.dawnsci.remotedataset.test/src/org/eclipse/dawnsci/remotedataset/test/client/MJPGTest.java | 2908 | /*-
*******************************************************************************
* Copyright (c) 2011, 2016 Diamond Light Source Ltd.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Gerring - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.dawnsci.remotedataset.test.client;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.dawnsci.analysis.api.io.IRemoteDatasetService;
import org.eclipse.dawnsci.analysis.dataset.function.Downsample;
import org.eclipse.dawnsci.remotedataset.ServiceHolder;
import org.eclipse.dawnsci.remotedataset.client.RemoteDatasetServiceImpl;
import org.eclipse.dawnsci.remotedataset.test.mock.ImageServiceMock;
import org.eclipse.dawnsci.remotedataset.test.mock.LoaderServiceMock;
import org.eclipse.dawnsci.remotedataset.test.mock.PlotImageServiceMock;
import org.eclipse.january.dataset.DataEvent;
import org.eclipse.january.dataset.IDataListener;
import org.eclipse.january.dataset.IDatasetConnector;
import org.junit.Before;
import org.junit.Test;
/**
* Test using MJPG datasets how they are supposed to be used.
*
* @author Matthew Gerring
*
*/
public class MJPGTest {
private IRemoteDatasetService service;
@Before
public void createService() throws Exception {
service = new RemoteDatasetServiceImpl(); // Normally this would come from OSGi
// Sorry but the concrete classes for these services are not part of an eclipse project.
// To get these concrete services go to dawnsci.org and follow the instructions for
// setting up dawnsci to run in your application.
ServiceHolder.setDownService(new Downsample());
ServiceHolder.setImageService(new ImageServiceMock());
ServiceHolder.setLoaderService(new LoaderServiceMock()); // TODO Implement the mock to get the test working again.
ServiceHolder.setPlotImageService(new PlotImageServiceMock());
}
@Test
public void testMJPGEPICS() throws Exception {
IDatasetConnector set = service.createMJPGDataset(new URL("http://ws157.diamond.ac.uk:8080/ADSIM.mjpg.mjpg"), 250, 10);
set.connect();
try {
final List<Integer> count = new ArrayList<>(1);
count.add(0);
set.addDataListener(new IDataListener() {
@Override
public void dataChangePerformed(DataEvent evt) {
System.out.println(count.get(0)+" images recevied!");
count.set(0, count.get(0).intValue()+1);
}
});
Thread.sleep(5000);
if (count.get(0)<10) throw new Exception("Less images than expected from stream! "+count.get(0));
} finally {
set.disconnect();
}
}
}
| epl-1.0 |
gaiandb/gaiandb | java/Asset/VTIs/com/ibm/gaiandb/mongodb/MongoConnectionFactory.java | 3791 | /*
* (C) Copyright IBM Corp. 2014
*
* LICENSE: Eclipse Public License v1.0
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.ibm.gaiandb.mongodb;
import java.net.ConnectException;
import java.net.UnknownHostException;
import javax.naming.AuthenticationException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
/**
* This class holds code allowing connection to a remote MongoDB process.
*
* @author Paul Stone
*/
public class MongoConnectionFactory {
// Use PROPRIETARY notice if class contains a main() method, otherwise use COPYRIGHT notice.
public static final String COPYRIGHT_NOTICE = "(c) Copyright IBM Corp. 2014";
/**
* Returns a handle to a Mongo Collection object - which may be used to execute mongoDB queries.
*
* @param connectionParams - object containing all the parameters needed to connect to MongoDB
* @exception UnknownHostException - if we cannot connect to the mongoDB host specified
* @exception AuthenticationException - if authentication with the mongoDB process fails.
*
*/
public static DBCollection getMongoCollection (MongoConnectionParams connectionParams) throws Exception{
String collectionName = connectionParams.getCollectionName();
if ( null == collectionName )
throw new Exception("Missing collection name. Check URL syntax matches 'usr:pwd@host:port/database/collection'");
// Now we should have an authenticated connection the mongo database, validate that the collection exists.
DBCollection mongoCollection = getMongoDB(connectionParams).getCollection( collectionName );
return mongoCollection;
}
/**
* Returns a handle to a Mongo DB object - which may be used to manage collections.
*
* @param connectionParams - object containing all the parameters needed to connect to MongoDB
* @exception UnknownHostException - if we cannot connect to the mongoDB host specified
* @exception AuthenticationException - if authentication with the mongoDB process fails.
*
*/
public static DB getMongoDB (MongoConnectionParams connectionParams) throws Exception{
// connect to the mongo process
MongoClient mongoClient = new MongoClient(connectionParams.getHostAddress(), connectionParams.getHostPort());
if (mongoClient == null) throw new ConnectException(MongoMessages.DSWRAPPER_MONGODB_CONNECTION_ERROR);
// Connect to the specific database
DB mongoDb = mongoClient.getDB(connectionParams.getDatabaseName()); // TBD possibly try to reuse these.
if (mongoDb == null) throw new ConnectException(MongoMessages.DSWRAPPER_MONGODB_DATABASE_CONN_ERROR);
// Authenticate if the configuration parameters have been set
String userName = connectionParams.getUserName();
String password = connectionParams.getPassword();
if (userName != null && password != null) {
boolean authenticated = mongoDb.authenticate(userName, password.toCharArray());
if (!authenticated){
throw new AuthenticationException(MongoMessages.DSWRAPPER_MONGODB_AUTHENTICATION_ERROR);
}
}
return mongoDb;
}
/**
* Closes the Mongo Collection object - frees up any resources held by the collection and the related
* connection object.
*
* @param connectionParams - object containing all the parameters needed to connect to MongoDB
* @exception UnknownHostException - if we cannot connect to the mongoDB host specified
* @exception AuthenticationException - if authentication with the mongoDB process fails.
*
*/
public static void closeMongoCollection (DBCollection mongoCollection) {
//we have to close the mongo client object, get a reference to it via the database object.
DB mongoDB = mongoCollection.getDB();
MongoClient mongoClient = (MongoClient)mongoDB.getMongo();
mongoClient.close();
}
}
| epl-1.0 |
SOM-Research/EMFtoCSP | plugins/fr.inria.atlanmod.emftocsp.emf/src/fr/inria/atlanmod/emftocsp/emf/impl/EmfModelToCspSolverFactory.java | 1121 | /*******************************************************************************
* Copyright (c) 2011 INRIA Rennes Bretagne-Atlantique.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* INRIA Rennes Bretagne-Atlantique - initial API and implementation
*******************************************************************************/
package fr.inria.atlanmod.emftocsp.emf.impl;
import org.eclipse.emf.ecore.resource.Resource;
import com.parctechnologies.eclipse.CompoundTerm;
import fr.inria.atlanmod.emftocsp.IModelToCspSolver;
import fr.inria.atlanmod.emftocsp.emf.IEmfModelToCspSolverFactory;
/**
* @author <a href="mailto:carlos.gonzalez@inria.fr">Carlos A. González</a>
*
*/
public class EmfModelToCspSolverFactory implements IEmfModelToCspSolverFactory {
@Override
public IModelToCspSolver<Resource,CompoundTerm> getModelToCspSolver() {
return new EmfModelToCspSolver();
}
}
| epl-1.0 |
ttimbul/eclipse.wst | bundles/org.eclipse.wst.xml.core/src/org/eclipse/wst/xml/core/internal/DebugAdapterFactory.java | 2302 | /*******************************************************************************
* Copyright (c) 2001, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Jens Lukowski/Innoopract - initial renaming/restructuring
*
*******************************************************************************/
package org.eclipse.wst.xml.core.internal;
import java.util.ArrayList;
import org.eclipse.wst.sse.core.internal.PropagatingAdapterFactory;
import org.eclipse.wst.sse.core.internal.provisional.AbstractAdapterFactory;
import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter;
import org.eclipse.wst.sse.core.internal.provisional.INodeAdapterFactory;
import org.eclipse.wst.sse.core.internal.provisional.INodeNotifier;
public class DebugAdapterFactory extends AbstractAdapterFactory implements PropagatingAdapterFactory {
/**
* Constructor for DebugAdapterFactory.
*/
public DebugAdapterFactory() {
this(IDebugAdapter.class, true);
}
/**
* Constructor for DebugAdapterFactory.
*
* @param fAdapterKey
* @param registerAdapters
*/
private DebugAdapterFactory(Object adapterKey, boolean registerAdapters) {
super(adapterKey, registerAdapters);
}
public void addContributedFactories(INodeAdapterFactory factory) {
//none expected
}
public INodeAdapterFactory copy() {
return new DebugAdapterFactory(getAdapterKey(), isShouldRegisterAdapter());
}
protected INodeAdapter createAdapter(INodeNotifier target) {
EveryNodeDebugAdapter result = null;
result = EveryNodeDebugAdapter.getInstance();
return result;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.sse.core.IAdapterFactory#isFactoryForType(java.lang.Object)
*/
public boolean isFactoryForType(Object type) {
return IDebugAdapter.class == type;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.sse.core.PropagatingAdapterFactory#setContributedFactories(java.util.ArrayList)
*/
public void setContributedFactories(ArrayList list) {
// none expected
}
}
| epl-1.0 |
debabratahazra/OptimaLA | Optima/com.ose.dbgserver/src/com/ose/dbgserver/protocol/DBGBpFired.java | 1066 | /*
This module was generated automatically from /vobs/ose5/core_ext/dbgserver/private/dbgserverinterface.stl.
DO NOT EDIT THIS FILE
*/
package com.ose.dbgserver.protocol;
import java.io.*;
public class DBGBpFired extends Message implements dbgserverinterfaceConstants{
public int bpid;
public int pid;
public DBGBpFired(int _bpid, int _pid) {
bpid = _bpid;
pid = _pid;
}
public DBGBpFired(DataInputStream _s) throws IOException { signalNo = 33032; read(_s);}
public final void sendMessage(DataOutputStream _s) throws IOException { write(_s, this.bpid, this.pid);}
public final static void write(DataOutputStream _s, int _bpid, int _pid ) throws IOException {
int _i;
_s.writeInt(DBGBPFIRED);
int _size=16;
_s.writeInt(_size);
_s.writeInt(_bpid);
_s.writeInt(_pid);
}
public final void read(DataInputStream _s) throws IOException {
int _i;
int _size=_s.readInt();
bpid=_s.readInt();
pid=_s.readInt();
}
}
| epl-1.0 |
bertbaron/intravatar | main.go | 8026 | package main
import (
"crypto/md5"
"flag"
"fmt"
"github.com/vharitonsky/iniflags"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)
// Options
var (
dataDir = flag.String("data", "data", "Path to data files relative to current working dir.")
port = flag.Int("port", 8080, "Webserver port number.")
webroot = flag.String("webroot", "", "The webroot of the service, defaults to http://localhost:<port>")
logfile = flag.String("logfile", "", "Path to log file, if empty, the log will go to stderr of the process")
remote = flag.String("remote", "https://gravatar.com/avatar", "Comma-separated list of gravatar-compatible avatar\n"+
" services to use if no avatar is found.")
emailDomain = flag.String("emailDomain", "", "Comma-separated list of email domains\n"+
" allowed to change avatars. Empty value mean all domains are allowed.")
dflt = flag.String("default", "remote:monsterid", "Default avatar. Use 'remote' to use the default of the (last) remote\n"+
" service, or 'remote:<option>' to use a builtin default. For example: 'remote:monsterid'. This is passed as\n"+
" '?d=monsterid' to the remote service. See https://nl.gravatar.com/site/implement/images/.\n"+
" If no remote and no local default is configured, resources/mm is used as default.")
smtpHost = flag.String("smtp-host", "", "SMTP host used for email confirmation, if not configured no confirmation emails will be required")
smtpPort = flag.Int("smtp-port", 25, "SMTP port")
smtpUser = flag.String("smtp-user", "", "SMTP user")
smtpPassword = flag.String("smtp-password", "", "SMTP password")
sender = flag.String("sender", "", "Senders email address")
noTLS = flag.Bool("no-tls", false, "Disable tls encription for email, less secure! Can be useful if certificates of in-house mailhost are expired.")
testMailAddr = flag.String("test-mail-addr", "", "If specified, sends a test email on startup to the given email address")
)
var (
defaultImage = "resources/mm"
defaultFormat = "jpeg"
remoteUrls = []string{}
emailDomains = []string{}
remoteDefault = ""
templates *template.Template
)
const (
minSize = 8
maxSize = 512
configFile = "config.ini"
)
func exists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
log.Fatalf("Error looking up directory %s", path)
return false
}
func mkdir(path string) {
if !exists(path) {
log.Printf("Creating directory %s", path)
os.Mkdir(path, 0700)
}
}
func createDirectoryStructure() {
mkdir(*dataDir)
mkdir(filepath.Join(*dataDir, "avatars"))
mkdir(filepath.Join(*dataDir, "unconfirmed"))
}
func createAvatarPath(hash string) string {
//return fmt.Sprintf("%s/avatars/%s", *dataDir, hash)
return filepath.Join(*dataDir, "avatars", hash)
}
func createUnconfirmedAvatarPath(hash string, token string) string {
//return fmt.Sprintf("%s/unconfirmed/%s-%s", *dataDir, token, hash)
return filepath.Join(*dataDir, "unconfirmed", fmt.Sprintf("%s-%s", token, hash))
}
func getUnconfirmedDir() string {
return fmt.Sprintf("%s/unconfirmed", *dataDir)
}
func setHeaderField(w http.ResponseWriter, key string, value string) {
if value != "" {
w.Header().Set(key, value)
}
}
func renderTemplate(w http.ResponseWriter, tmpl string, data interface{}) {
err := templates.ExecuteTemplate(w, tmpl+".html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func createHash(email string) string {
h := md5.New()
io.WriteString(h, strings.TrimSpace(strings.ToLower(email)))
return fmt.Sprintf("%x", h.Sum(nil))
}
func getServiceURL() string {
url := *webroot
if url == "" {
portName := ""
if *port != 80 {
portName = fmt.Sprintf(":%d", *port)
}
url = "http://localhost" + portName
}
return url + "/"
}
func homeHandler(w http.ResponseWriter, r *http.Request, title string) {
url := getServiceURL() + "avatar/"
renderTemplate(w, "index", map[string]string{"AvatarLink": url})
}
// Creates a http request handler
// pattern is a regular expression that validates the URL. The first matching group is passes to the handler as title
func makeHandler(fn func(http.ResponseWriter, *http.Request, string), pattern string) http.HandlerFunc {
regex := regexp.MustCompile(pattern)
return func(w http.ResponseWriter, r *http.Request) {
// log.Printf("Request: %v", r)
m := regex.FindStringSubmatch(r.URL.Path)
if m == nil {
log.Print("Invalid request: ", r.URL)
http.NotFound(w, r)
return
}
log.Printf("Handling request %v %v from %v", r.Method, r.URL, strings.Split(r.RemoteAddr, ":")[0])
start := time.Now()
fn(w, r, m[1])
log.Printf("Handled request %v %v in %v", r.Method, r.URL, time.Since(start))
}
}
func initTemplates() {
files, err := ioutil.ReadDir("resources/templates")
if err != nil {
log.Fatal(err)
}
var fileNames []string
for _, file := range files {
fileNames = append(fileNames, "resources/templates/"+file.Name())
}
templates = template.Must(template.ParseFiles(fileNames...))
}
// serves a single file
func serveSingle(pattern string, filename string) {
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filename)
})
}
func main() {
if _, e := os.Stat(configFile); e == nil {
log.Printf("Default configuration file %v", configFile)
iniflags.SetConfigFile(configFile)
}
iniflags.Parse()
if *logfile != "" {
file, err := os.OpenFile(*logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file for logging: %v", err)
}
log.Printf("Logging will be redirected to %v", *logfile)
defer file.Close()
log.SetOutput(file)
}
if *smtpHost != "" && *sender == "" {
if *sender == "" {
log.Fatal("It is required to configure 'sender' when smtp host is not empty!")
}
}
initTemplates()
log.Printf("data dir = %s\n", *dataDir)
address := fmt.Sprintf(":%d", *port)
if *remote == "" {
remoteUrls = []string{}
} else {
remoteUrls = strings.Split(*remote, ",")
log.Printf("Missing avatars will be redirected to %s", remoteUrls)
}
if *emailDomain == "" {
emailDomains = []string{}
} else {
emailDomains = strings.Split(*emailDomain, ",")
for idx, domain := range emailDomains {
emailDomains[idx] = strings.ToLower(domain)
}
log.Printf("Avatars will only be stored for email domains %s", emailDomains)
}
remoteFallbackPattern := regexp.MustCompile("^remote:([a-zA-Z]+)$")
if *dflt == "fallback" {
log.Printf("Default image will be provided by the remote service if configured")
remoteDefault = ""
} else if builtin := remoteFallbackPattern.FindStringSubmatch(*dflt); builtin != nil {
remoteDefault = builtin[1]
log.Printf("Default image will be provided by the remote service using '?d=%s' if a remote is configured", remoteDefault)
} else {
defaultImage = *dflt
remoteDefault = "404"
log.Printf("Using %s as default image", defaultImage)
}
if *testMailAddr != "" {
if err := sendTestMail(*testMailAddr); err != nil {
log.Fatalf("Failed to send test email to %s: %v", *testMailAddr, err)
}
}
createDirectoryStructure()
log.Printf("Listening on %s\n", address)
log.Printf("Service url: %s\n", getServiceURL())
http.HandleFunc("/", makeHandler(homeHandler, "^/()$"))
// Mandatory root-based resources
serveSingle("/favicon.ico", "resources/favicon.ico")
// Other static resources
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("resources/static/"))))
// Application
http.HandleFunc("/avatar/", makeHandler(avatarHandler, "^/avatar/([a-zA-Z0-9]+)(\\.[a-zA-Z0-9]+)?$"))
http.HandleFunc("/upload/", makeHandler(uploadHandler, "^/(upload)/$"))
http.HandleFunc("/save/", makeHandler(saveHandler, "^/(save)/$"))
http.HandleFunc("/confirm/", makeHandler(confirmHandler, "^/confirm/([a-zA-Z0-9]+)$"))
x := http.ListenAndServe(address, nil)
fmt.Println("Result: ", x)
}
| epl-1.0 |
inevo/mondrian | src/main/mondrian/calc/MemberListCalc.java | 1055 | /*
// $Id$
// This software is subject to the terms of the Eclipse Public License v1.0
// Agreement, available at the following URL:
// http://www.eclipse.org/legal/epl-v10.html.
// Copyright (C) 2006-2009 Julian Hyde
// All Rights Reserved.
// You must accept the terms of that agreement to use this software.
*/
package mondrian.calc;
import java.util.List;
import mondrian.olap.Evaluator;
import mondrian.olap.Member;
/**
* Expression which evaluates a set of members or tuples to a list.
*
* @author jhyde
* @version $Id$
* @since Sep 27, 2005
*/
public interface MemberListCalc extends ListCalc {
/**
* Evaluates an expression to yield a list of members.
*
* <p>The list is immutable if {@link #getResultStyle()} yields
* {@link mondrian.calc.ResultStyle#MUTABLE_LIST}. Otherwise,
* the caller must not modify the list.
*
* @param evaluator Evaluation context
* @return A list of members, never null.
*/
List<Member> evaluateMemberList(Evaluator evaluator);
}
// End MemberListCalc.java
| epl-1.0 |
CyberdyneOfCerrado/Backups | src/bancoDeDados/CarregaBanco.java | 142 | package bancoDeDados;
public class CarregaBanco {
public boolean inciaBanco(){
BancoDeDados.obterInstancia();
return true;
}
}
| epl-1.0 |
jaytaylor/persistit | src/main/java/com/persistit/ui/PoolDisplayPanel.java | 9723 | /**
* Copyright © 2005-2012 Akiban Technologies, Inc. All rights reserved.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This program may also be available under different license terms.
* For more information, see www.akiban.com or contact licensing@akiban.com.
*
* Contributors:
* Akiban Technologies, Inc.
*/
package com.persistit.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.text.DecimalFormat;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToggleButton;
import javax.swing.table.AbstractTableModel;
import com.persistit.Management;
import com.persistit.Management.BufferInfo;
import com.persistit.Management.BufferPoolInfo;
public class PoolDisplayPanel extends JPanel {
private final static String[] HEADER_NAMES = { "Index", "Page", "Type", "Status", "Writer Thread",
"Available Space", "Right Sibling", };
private Management _management;
private BufferTableModel _btm = new BufferTableModel();
public PoolDisplayPanel(Management management) {
_management = management;
setLayout(new BorderLayout());
setMinimumSize(new Dimension(800, 600));
add(new JScrollPane(new JTable(_btm)), BorderLayout.CENTER);
JPanel selector = new JPanel(new FlowLayout());
add(selector, BorderLayout.SOUTH);
ButtonGroup bg = new ButtonGroup();
JRadioButton rb;
final JLabel stats = new JLabel();
stats.setMinimumSize(new Dimension(150, 15));
rb = new JRadioButton(new AbstractAction("All") {
@Override
public void actionPerformed(ActionEvent ae) {
_btm.setSource(0);
stats.setText(_btm.getBufferStats());
}
});
bg.add(rb);
selector.add(rb);
rb.setSelected(true);
rb = new JRadioButton(new AbstractAction("LRU Queue") {
@Override
public void actionPerformed(ActionEvent ae) {
_btm.setSource(1);
}
});
bg.add(rb);
selector.add(rb);
rb = new JRadioButton(new AbstractAction("Invalid Queue") {
@Override
public void actionPerformed(ActionEvent ae) {
_btm.setSource(2);
stats.setText(_btm.getBufferStats());
}
});
bg.add(rb);
selector.add(rb);
JToggleButton tb;
tb = new JToggleButton(new AbstractAction("Valid") {
@Override
public void actionPerformed(ActionEvent ae) {
_btm.setIncludeMask("v", ((JToggleButton) (ae.getSource())).isSelected());
stats.setText(_btm.getBufferStats());
}
});
selector.add(tb);
tb = new JToggleButton(new AbstractAction("Dirty") {
@Override
public void actionPerformed(ActionEvent ae) {
_btm.setIncludeMask("d", ((JToggleButton) (ae.getSource())).isSelected());
stats.setText(_btm.getBufferStats());
}
});
selector.add(tb);
tb = new JToggleButton(new AbstractAction("Reader") {
@Override
public void actionPerformed(ActionEvent ae) {
_btm.setIncludeMask("r", ((JToggleButton) (ae.getSource())).isSelected());
stats.setText(_btm.getBufferStats());
}
});
selector.add(tb);
tb = new JToggleButton(new AbstractAction("Writer") {
@Override
public void actionPerformed(ActionEvent ae) {
_btm.setIncludeMask("w", ((JToggleButton) (ae.getSource())).isSelected());
stats.setText(_btm.getBufferStats());
}
});
selector.add(tb);
JButton b = new JButton(new AbstractAction("Refresh") {
@Override
public void actionPerformed(ActionEvent ae) {
_btm._selectedBufferCount = -1;
_btm.fireTableDataChanged();
stats.setText(_btm.getBufferStats());
}
});
selector.add(b);
selector.add(stats);
}
private class BufferTableModel extends AbstractTableModel {
private int _traversalType = 0;
private String _includeMask = null;
private String _excludeMask = null;
private long _missCount;
private long _newCount;
private long _hitCount;
private double _hitRatio;
private DecimalFormat _df = new DecimalFormat("#####.#####");
private BufferInfo[] _buffers;
private int _selectedBufferCount = -1;
void setIncludeMask(String mask, boolean selected) {
if (selected && _includeMask == null)
_includeMask = "";
if (selected && (_includeMask.indexOf(mask) == -1)) {
_includeMask += mask;
_selectedBufferCount = -1;
fireTableDataChanged();
} else if (!selected && (_includeMask != null) && (_includeMask.indexOf(mask) != -1)) {
int p = _includeMask.indexOf(mask);
_includeMask = _includeMask.substring(0, p) + _includeMask.substring(p + 1);
_selectedBufferCount = -1;
if (_includeMask.length() == 0)
_includeMask = null;
fireTableDataChanged();
}
}
void setSource(int code) {
if (_traversalType != code) {
_traversalType = code;
_selectedBufferCount = -1;
fireTableDataChanged();
}
}
@Override
public int getRowCount() {
if (_selectedBufferCount < 0)
loadBuffers();
return _selectedBufferCount;
}
@Override
public int getColumnCount() {
return HEADER_NAMES.length;
}
@Override
public String getColumnName(int column) {
return HEADER_NAMES[column];
}
@Override
public Object getValueAt(int row, int column) {
if (_selectedBufferCount < 0)
loadBuffers();
if (row >= _selectedBufferCount)
return "";
BufferInfo bufferInfo = _buffers[row];
switch (column) {
case 0:
return Integer.toString(bufferInfo.getPoolIndex());
case 1:
return Long.toString(bufferInfo.getPageAddress());
case 2:
if (bufferInfo.getStatusName().indexOf('v') != -1 && bufferInfo.getPageAddress() == 0)
return "Base";
else
return bufferInfo.getTypeName();
case 3:
return bufferInfo.getStatusName();
case 4:
String threadName = bufferInfo.getWriterThreadName();
return threadName == null ? "" : threadName;
case 5:
return Integer.toString(bufferInfo.getAvailableBytes());
case 6:
return Long.toString(bufferInfo.getRightSiblingAddress());
default:
return "?";
}
}
private void loadBuffers() {
try {
BufferPoolInfo[] pools = _management.getBufferPoolInfoArray();
if (pools.length < 1) {
_selectedBufferCount = 0;
_hitCount = 0;
_missCount = 0;
_newCount = 0;
_hitRatio = 0;
} else {
String managementClassName = _management.getClass().getName();
boolean isRemote = managementClassName.indexOf("Stub") > 0;
BufferPoolInfo info = pools[0];
if (isRemote) {
_buffers = _management.getBufferInfoArray(info.getBufferSize(), _traversalType, _includeMask,
_excludeMask);
_selectedBufferCount = _buffers == null ? -1 : _buffers.length;
} else {
if (_buffers == null || _buffers.length < pools[0].getBufferCount()) {
_buffers = new BufferInfo[info.getBufferCount()];
}
_selectedBufferCount = _management.populateBufferInfoArray(_buffers, info.getBufferSize(),
_traversalType, _includeMask, _excludeMask);
}
_hitCount = info.getHitCount();
_missCount = info.getMissCount();
_newCount = info.getNewCount();
_hitRatio = info.getHitRatio();
}
} catch (Exception ex) {
ex.printStackTrace();
_selectedBufferCount = 0;
_hitCount = 0;
_missCount = 0;
_hitRatio = 0;
}
}
private String getBufferStats() {
return Long.toString(_hitCount) + " / (" + Long.toString(_missCount) + "+" + Long.toString(_newCount)
+ ") = " + _df.format(_hitRatio);
}
}
}
| epl-1.0 |
elucash/eclipse-oxygen | org.eclipse.jdt.core/src/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java | 49008 | /*******************************************************************************
* Copyright (c) 2000, 2017 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.core.hierarchy;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.SafeRunner;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaModelStatusConstants;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.ITypeHierarchyChangedListener;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.WorkingCopyOwner;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.core.ClassFile;
import org.eclipse.jdt.internal.core.CompilationUnit;
import org.eclipse.jdt.internal.core.JavaElement;
import org.eclipse.jdt.internal.core.JavaModelStatus;
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.jdt.internal.core.Openable;
import org.eclipse.jdt.internal.core.PackageFragment;
import org.eclipse.jdt.internal.core.Region;
import org.eclipse.jdt.internal.core.TypeVector;
import org.eclipse.jdt.internal.core.util.Messages;
import org.eclipse.jdt.internal.core.util.Util;
/**
* @see ITypeHierarchy
*/
public class TypeHierarchy implements ITypeHierarchy, IElementChangedListener {
public static boolean DEBUG = false;
static final byte VERSION = 0x0000;
// SEPARATOR
static final byte SEPARATOR1 = '\n';
static final byte SEPARATOR2 = ',';
static final byte SEPARATOR3 = '>';
static final byte SEPARATOR4 = '\r';
// general info
static final byte COMPUTE_SUBTYPES = 0x0001;
// type info
static final byte CLASS = 0x0000;
static final byte INTERFACE = 0x0001;
static final byte COMPUTED_FOR = 0x0002;
static final byte ROOT = 0x0004;
// cst
static final byte[] NO_FLAGS = new byte[]{};
static final int SIZE = 10;
/**
* The Java Project in which the hierarchy is being built - this
* provides the context for determining a classpath and namelookup rules.
* Possibly null.
*/
protected IJavaProject project;
/**
* The type the hierarchy was specifically computed for,
* possibly null.
*/
protected IType focusType;
/*
* The working copies that take precedence over original compilation units
*/
protected ICompilationUnit[] workingCopies;
protected Map<IType, IType> classToSuperclass;
protected Map<IType, IType[]> typeToSuperInterfaces;
protected Map<IType, TypeVector> typeToSubtypes;
protected Map<IType, Integer> typeFlags;
protected TypeVector rootClasses = new TypeVector();
protected ArrayList<IType> interfaces = new ArrayList<IType>(10);
public ArrayList<String> missingTypes = new ArrayList<String>(4);
protected static final IType[] NO_TYPE = new IType[0];
/**
* The progress monitor to report work completed too.
*/
protected SubMonitor progressMonitor = SubMonitor.convert(null);
/**
* Change listeners - null if no one is listening.
*/
protected ArrayList<ITypeHierarchyChangedListener> changeListeners = null;
/*
* A map from Openables to ArrayLists of ITypes
*/
public Map<IOpenable, ArrayList<IType>> files = null;
/**
* A region describing the packages considered by this
* hierarchy. Null if not activated.
*/
protected Region packageRegion = null;
/**
* A region describing the projects considered by this
* hierarchy. Null if not activated.
*/
protected Region projectRegion = null;
/**
* Whether this hierarchy should contains subtypes.
*/
protected boolean computeSubtypes;
/**
* The scope this hierarchy should restrain itsef in.
*/
IJavaSearchScope scope;
/*
* Whether this hierarchy needs refresh
*/
public boolean needsRefresh = true;
/*
* Collects changes to types
*/
protected ChangeCollector changeCollector;
/**
* Creates an empty TypeHierarchy
*/
public TypeHierarchy() {
// Creates an empty TypeHierarchy
}
/**
* Creates a TypeHierarchy on the given type.
*/
public TypeHierarchy(IType type, ICompilationUnit[] workingCopies, IJavaProject project, boolean computeSubtypes) {
this(type, workingCopies, SearchEngine.createJavaSearchScope(new IJavaElement[] {project}), computeSubtypes);
this.project = project;
}
/**
* Creates a TypeHierarchy on the given type.
*/
public TypeHierarchy(IType type, ICompilationUnit[] workingCopies, IJavaSearchScope scope, boolean computeSubtypes) {
this.focusType = type == null ? null : (IType) ((JavaElement) type).unresolved(); // unsure the focus type is unresolved (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=92357)
this.workingCopies = workingCopies;
this.computeSubtypes = computeSubtypes;
this.scope = scope;
}
/**
* Initializes the file, package and project regions
*/
protected void initializeRegions() {
IType[] allTypes = getAllTypes();
for (int i = 0; i < allTypes.length; i++) {
IType type = allTypes[i];
Openable o = (Openable) ((JavaElement) type).getOpenableParent();
if (o != null) {
ArrayList<IType> types = this.files.get(o);
if (types == null) {
types = new ArrayList<>();
this.files.put(o, types);
}
types.add(type);
}
IPackageFragment pkg = type.getPackageFragment();
this.packageRegion.add(pkg);
IJavaProject declaringProject = type.getJavaProject();
if (declaringProject != null) {
this.projectRegion.add(declaringProject);
}
checkCanceled();
}
}
/**
* Adds the type to the collection of interfaces.
*/
protected void addInterface(IType type) {
this.interfaces.add(type);
}
/**
* Adds the type to the collection of root classes
* if the classes is not already present in the collection.
*/
protected void addRootClass(IType type) {
if (this.rootClasses.contains(type)) return;
this.rootClasses.add(type);
}
/**
* Adds the given subtype to the type.
*/
protected void addSubtype(IType type, IType subtype) {
TypeVector subtypes = this.typeToSubtypes.get(type);
if (subtypes == null) {
subtypes = new TypeVector();
this.typeToSubtypes.put(type, subtypes);
}
if (!subtypes.contains(subtype)) {
subtypes.add(subtype);
}
}
/**
* @see ITypeHierarchy
*/
public synchronized void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) {
ArrayList<ITypeHierarchyChangedListener> listeners = this.changeListeners;
if (listeners == null) {
this.changeListeners = listeners = new ArrayList<>();
}
// register with JavaCore to get Java element delta on first listener added
if (listeners.size() == 0) {
JavaCore.addElementChangedListener(this);
}
// add listener only if it is not already present
if (listeners.indexOf(listener) == -1) {
listeners.add(listener);
}
}
private static Integer bytesToFlags(byte[] bytes){
if(bytes != null && bytes.length > 0) {
return Integer.valueOf(new String(bytes));
} else {
return null;
}
}
/**
* cacheFlags.
*/
public void cacheFlags(IType type, int flags) {
this.typeFlags.put(type, Integer.valueOf(flags));
}
/**
* Caches the handle of the superclass for the specified type.
* As a side effect cache this type as a subtype of the superclass.
*/
protected void cacheSuperclass(IType type, IType superclass) {
if (superclass != null) {
if (superclass.equals(type)) {
Util.log(IStatus.ERROR, "Type "+type.getFullyQualifiedName()+" is it's own superclass"); //$NON-NLS-1$//$NON-NLS-2$
return; // refuse to enter what could lead to a stackoverflow later
}
this.classToSuperclass.put(type, superclass);
addSubtype(superclass, type);
}
}
/**
* Caches all of the superinterfaces that are specified for the
* type.
*/
protected void cacheSuperInterfaces(IType type, IType[] superinterfaces) {
this.typeToSuperInterfaces.put(type, superinterfaces);
for (int i = 0; i < superinterfaces.length; i++) {
IType superinterface = superinterfaces[i];
if (superinterface != null) {
addSubtype(superinterface, type);
}
}
}
/**
* Checks with the progress monitor to see whether the creation of the type hierarchy
* should be canceled. Should be regularly called
* so that the user can cancel.
*
* @exception OperationCanceledException if cancelling the operation has been requested
* @see IProgressMonitor#isCanceled
*/
protected void checkCanceled() {
if (this.progressMonitor != null && this.progressMonitor.isCanceled()) {
throw new OperationCanceledException();
}
}
/**
* Compute this type hierarchy.
*/
protected void compute() throws JavaModelException, CoreException {
if (this.focusType != null) {
HierarchyBuilder builder =
new IndexBasedHierarchyBuilder(
this,
this.scope);
builder.build(this.computeSubtypes);
} // else a RegionBasedTypeHierarchy should be used
}
/**
* @see ITypeHierarchy
*/
public boolean contains(IType type) {
// classes
if (this.classToSuperclass.get(type) != null) {
return true;
}
// root classes
if (this.rootClasses.contains(type)) return true;
// interfaces
if (this.interfaces.contains(type)) return true;
return false;
}
/**
* Determines if the change affects this hierarchy, and fires
* change notification if required.
*/
public void elementChanged(ElementChangedEvent event) {
// type hierarchy change has already been fired
if (this.needsRefresh) return;
if (isAffected(event.getDelta(), event.getType())) {
this.needsRefresh = true;
fireChange();
}
}
/**
* @see ITypeHierarchy
*/
public boolean exists() {
if (!this.needsRefresh) return true;
return (this.focusType == null || this.focusType.exists()) && javaProject().exists();
}
/**
* Notifies listeners that this hierarchy has changed and needs
* refreshing. Note that listeners can be removed as we iterate
* through the list.
*/
public void fireChange() {
ArrayList<ITypeHierarchyChangedListener> listeners = getClonedChangeListeners(); // clone so that a listener cannot have a side-effect on this list when being notified
if (listeners == null) {
return;
}
if (DEBUG) {
System.out.println("FIRING hierarchy change ["+Thread.currentThread()+"]"); //$NON-NLS-1$ //$NON-NLS-2$
if (this.focusType != null) {
System.out.println(" for hierarchy focused on " + ((JavaElement)this.focusType).toStringWithAncestors()); //$NON-NLS-1$
}
}
for (int i= 0; i < listeners.size(); i++) {
final ITypeHierarchyChangedListener listener= listeners.get(i);
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable exception) {
Util.log(exception, "Exception occurred in listener of Type hierarchy change notification"); //$NON-NLS-1$
}
public void run() throws Exception {
listener.typeHierarchyChanged(TypeHierarchy.this);
}
});
}
}
@SuppressWarnings("unchecked")
private synchronized ArrayList<ITypeHierarchyChangedListener> getClonedChangeListeners() {
ArrayList<ITypeHierarchyChangedListener> listeners = this.changeListeners;
if (listeners == null) {
return null;
}
return (ArrayList<ITypeHierarchyChangedListener>) listeners.clone();
}
private static byte[] flagsToBytes(Integer flags){
if(flags != null) {
return flags.toString().getBytes();
} else {
return NO_FLAGS;
}
}
/**
* @see ITypeHierarchy
*/
public IType[] getAllClasses() {
TypeVector classes = this.rootClasses.copy();
for (Iterator<IType> iter = this.classToSuperclass.keySet().iterator(); iter.hasNext();){
classes.add(iter.next());
}
return classes.elements();
}
/**
* @see ITypeHierarchy
*/
public IType[] getAllInterfaces() {
IType[] collection= new IType[this.interfaces.size()];
this.interfaces.toArray(collection);
return collection;
}
/**
* @see ITypeHierarchy
*/
public IType[] getAllSubtypes(IType type) {
return getAllSubtypesForType(type);
}
/**
* @see #getAllSubtypes(IType)
*/
private IType[] getAllSubtypesForType(IType type) {
ArrayList<IType> subTypes = new ArrayList<>();
getAllSubtypesForType0(type, subTypes);
IType[] subClasses = new IType[subTypes.size()];
subTypes.toArray(subClasses);
return subClasses;
}
/**
*/
private void getAllSubtypesForType0(IType type, ArrayList<IType> subs) {
IType[] subTypes = getSubtypesForType(type);
if (subTypes.length != 0) {
for (int i = 0; i < subTypes.length; i++) {
IType subType = subTypes[i];
if (subs.contains(subType)) continue;
subs.add(subType);
getAllSubtypesForType0(subType, subs);
}
}
}
/**
* @see ITypeHierarchy
*/
public IType[] getAllSuperclasses(IType type) {
IType superclass = getSuperclass(type);
TypeVector supers = new TypeVector();
while (superclass != null) {
supers.add(superclass);
superclass = getSuperclass(superclass);
}
return supers.elements();
}
/**
* @see ITypeHierarchy
*/
public IType[] getAllSuperInterfaces(IType type) {
ArrayList<IType> supers = getAllSuperInterfaces0(type, null);
if (supers == null)
return NO_TYPE;
IType[] superinterfaces = new IType[supers.size()];
supers.toArray(superinterfaces);
return superinterfaces;
}
private ArrayList<IType> getAllSuperInterfaces0(IType type, ArrayList<IType> supers) {
IType[] superinterfaces = this.typeToSuperInterfaces.get(type);
if (superinterfaces == null) // type is not part of the hierarchy
return supers;
if (superinterfaces.length != 0) {
if (supers == null)
supers = new ArrayList<IType>();
for (int i1 = 0; i1 < superinterfaces.length; i1++) {
IType element = superinterfaces[i1];
if (supers.contains(element)) continue;
supers.add(element);
supers = getAllSuperInterfaces0(element, supers);
}
}
IType superclass = this.classToSuperclass.get(type);
if (superclass != null) {
supers = getAllSuperInterfaces0(superclass, supers);
}
return supers;
}
/**
* @see ITypeHierarchy
*/
public IType[] getAllSupertypes(IType type) {
ArrayList<IType> supers = getAllSupertypes0(type, null);
if (supers == null)
return NO_TYPE;
IType[] supertypes = new IType[supers.size()];
supers.toArray(supertypes);
return supertypes;
}
private ArrayList<IType> getAllSupertypes0(IType type, ArrayList<IType> supers) {
IType[] superinterfaces = this.typeToSuperInterfaces.get(type);
if (superinterfaces == null) // type is not part of the hierarchy
return supers;
if (superinterfaces.length != 0) {
if (supers == null)
supers = new ArrayList<IType>();
for (int i1 = 0; i1 < superinterfaces.length; i1++) {
IType element = superinterfaces[i1];
if (!supers.contains(element)) {
supers.add(element);
supers = getAllSuperInterfaces0(element, supers);
}
}
}
IType superclass = this.classToSuperclass.get(type);
if (superclass != null) {
if (supers == null)
supers = new ArrayList<>();
supers.add(superclass);
supers = getAllSupertypes0(superclass, supers);
}
return supers;
}
/**
* @see ITypeHierarchy
*/
public IType[] getAllTypes() {
IType[] classes = getAllClasses();
int classesLength = classes.length;
IType[] allInterfaces = getAllInterfaces();
int interfacesLength = allInterfaces.length;
IType[] all = new IType[classesLength + interfacesLength];
System.arraycopy(classes, 0, all, 0, classesLength);
System.arraycopy(allInterfaces, 0, all, classesLength, interfacesLength);
return all;
}
/**
* @see ITypeHierarchy#getCachedFlags(IType)
*/
public int getCachedFlags(IType type) {
Integer flagObject = this.typeFlags.get(type);
if (flagObject != null){
return flagObject.intValue();
}
return -1;
}
/**
* @see ITypeHierarchy
*/
public IType[] getExtendingInterfaces(IType type) {
if (!isInterface(type)) return NO_TYPE;
return getExtendingInterfaces0(type);
}
/**
* Assumes that the type is an interface
* @see #getExtendingInterfaces
*/
private IType[] getExtendingInterfaces0(IType extendedInterface) {
Iterator<Entry<IType, IType[]>> iter = this.typeToSuperInterfaces.entrySet().iterator();
ArrayList<IType> interfaceList = new ArrayList<>();
while (iter.hasNext()) {
Map.Entry<IType, IType[]> entry = iter.next();
IType type = entry.getKey();
if (!isInterface(type)) {
continue;
}
IType[] superInterfaces = entry.getValue();
if (superInterfaces != null) {
for (int i = 0; i < superInterfaces.length; i++) {
IType superInterface = superInterfaces[i];
if (superInterface.equals(extendedInterface)) {
interfaceList.add(type);
}
}
}
}
IType[] extendingInterfaces = new IType[interfaceList.size()];
interfaceList.toArray(extendingInterfaces);
return extendingInterfaces;
}
/**
* @see ITypeHierarchy
*/
public IType[] getImplementingClasses(IType type) {
if (!isInterface(type)) {
return NO_TYPE;
}
return getImplementingClasses0(type);
}
/**
* Assumes that the type is an interface
* @see #getImplementingClasses
*/
private IType[] getImplementingClasses0(IType interfce) {
Iterator<Map.Entry<IType,IType[]>> iter = this.typeToSuperInterfaces.entrySet().iterator();
ArrayList<IType> iMenters = new ArrayList<>();
while (iter.hasNext()) {
Map.Entry<IType, IType[]> entry = iter.next();
IType type = entry.getKey();
if (isInterface(type)) {
continue;
}
IType[] types = entry.getValue();
for (int i = 0; i < types.length; i++) {
IType iFace = types[i];
if (iFace.equals(interfce)) {
iMenters.add(type);
}
}
}
IType[] implementers = new IType[iMenters.size()];
iMenters.toArray(implementers);
return implementers;
}
/**
* @see ITypeHierarchy
*/
public IType[] getRootClasses() {
return this.rootClasses.elements();
}
/**
* @see ITypeHierarchy
*/
public IType[] getRootInterfaces() {
IType[] allInterfaces = getAllInterfaces();
IType[] roots = new IType[allInterfaces.length];
int rootNumber = 0;
for (int i = 0; i < allInterfaces.length; i++) {
IType[] superInterfaces = getSuperInterfaces(allInterfaces[i]);
if (superInterfaces == null || superInterfaces.length == 0) {
roots[rootNumber++] = allInterfaces[i];
}
}
IType[] result = new IType[rootNumber];
if (result.length > 0) {
System.arraycopy(roots, 0, result, 0, rootNumber);
}
return result;
}
/**
* @see ITypeHierarchy
*/
public IType[] getSubclasses(IType type) {
if (isInterface(type)) {
return NO_TYPE;
}
TypeVector vector = this.typeToSubtypes.get(type);
if (vector == null)
return NO_TYPE;
else
return vector.elements();
}
/**
* @see ITypeHierarchy
*/
public IType[] getSubtypes(IType type) {
return getSubtypesForType(type);
}
/**
* Returns an array of subtypes for the given type - will never return null.
*/
private IType[] getSubtypesForType(IType type) {
TypeVector vector = this.typeToSubtypes.get(type);
if (vector == null)
return NO_TYPE;
else
return vector.elements();
}
/**
* @see ITypeHierarchy
*/
public IType getSuperclass(IType type) {
if (isInterface(type)) {
return null;
}
return this.classToSuperclass.get(type);
}
/**
* @see ITypeHierarchy
*/
public IType[] getSuperInterfaces(IType type) {
IType[] types = this.typeToSuperInterfaces.get(type);
if (types == null) {
return NO_TYPE;
}
return types;
}
/**
* @see ITypeHierarchy
*/
public IType[] getSupertypes(IType type) {
IType superclass = getSuperclass(type);
if (superclass == null) {
return getSuperInterfaces(type);
} else {
TypeVector superTypes = new TypeVector(getSuperInterfaces(type));
superTypes.add(superclass);
return superTypes.elements();
}
}
/**
* @see ITypeHierarchy
*/
public IType getType() {
return this.focusType;
}
/**
* Adds the new elements to a new array that contains all of the elements of the old array.
* Returns the new array.
*/
protected IType[] growAndAddToArray(IType[] array, IType[] additions) {
if (array == null || array.length == 0) {
return additions;
}
IType[] old = array;
array = new IType[old.length + additions.length];
System.arraycopy(old, 0, array, 0, old.length);
System.arraycopy(additions, 0, array, old.length, additions.length);
return array;
}
/**
* Adds the new element to a new array that contains all of the elements of the old array.
* Returns the new array.
*/
protected IType[] growAndAddToArray(IType[] array, IType addition) {
if (array == null || array.length == 0) {
return new IType[] {addition};
}
IType[] old = array;
array = new IType[old.length + 1];
System.arraycopy(old, 0, array, 0, old.length);
array[old.length] = addition;
return array;
}
/*
* Whether fine-grained deltas where collected and affects this hierarchy.
*/
public boolean hasFineGrainChanges() {
ChangeCollector collector = this.changeCollector;
return collector != null && collector.needsRefresh();
}
/**
* Returns whether this type or one of the subtypes in this hierarchy has the
* same simple name as the given name.
*/
private boolean hasSubtypeNamed(String name) {
int idx = -1;
String rawName = (idx = name.indexOf('<')) > -1 ? name.substring(0, idx) : name;
String simpleName = (idx = rawName.lastIndexOf('.')) > -1 ? rawName.substring(idx + 1) : rawName;
if (this.focusType != null && this.focusType.getElementName().equals(simpleName)) {
return true;
}
IType[] types = this.focusType == null ? getAllTypes() : getAllSubtypes(this.focusType);
for (int i = 0, length = types.length; i < length; i++) {
if (types[i].getElementName().equals(simpleName)) {
return true;
}
}
return false;
}
/**
* Returns whether one of the types in this hierarchy has the given simple name.
*/
private boolean hasTypeNamed(String simpleName) {
IType[] types = getAllTypes();
for (int i = 0, length = types.length; i < length; i++) {
if (types[i].getElementName().equals(simpleName)) {
return true;
}
}
return false;
}
/**
* Returns whether the simple name of the given type or one of its supertypes is
* the simple name of one of the types in this hierarchy.
*/
boolean includesTypeOrSupertype(IType type) {
try {
// check type
if (hasTypeNamed(type.getElementName())) return true;
// check superclass
String superclassName = type.getSuperclassName();
if (superclassName != null) {
int lastSeparator = superclassName.lastIndexOf('.');
String simpleName = superclassName.substring(lastSeparator+1);
if (hasTypeNamed(simpleName)) return true;
}
// check superinterfaces
String[] superinterfaceNames = type.getSuperInterfaceNames();
if (superinterfaceNames != null) {
for (int i = 0, length = superinterfaceNames.length; i < length; i++) {
String superinterfaceName = superinterfaceNames[i];
int lastSeparator = superinterfaceName.lastIndexOf('.');
String simpleName = superinterfaceName.substring(lastSeparator+1);
if (hasTypeNamed(simpleName)) return true;
}
}
} catch (JavaModelException e) {
// ignore
}
return false;
}
/**
* Initializes this hierarchy's internal tables with the given size.
*/
protected void initialize(int size) {
if (size < 10) {
size = 10;
}
int smallSize = (size / 2);
this.classToSuperclass = new HashMap<>(size);
this.interfaces = new ArrayList<>(smallSize);
this.missingTypes = new ArrayList<>(smallSize);
this.rootClasses = new TypeVector();
this.typeToSubtypes = new HashMap<>(smallSize);
this.typeToSuperInterfaces = new HashMap<>(smallSize);
this.typeFlags = new HashMap<>(smallSize);
this.projectRegion = new Region();
this.packageRegion = new Region();
this.files = new HashMap<>(5);
}
/**
* Returns true if the given delta could change this type hierarchy
* @param eventType TODO
*/
public synchronized boolean isAffected(IJavaElementDelta delta, int eventType) {
IJavaElement element= delta.getElement();
switch (element.getElementType()) {
case IJavaElement.JAVA_MODEL:
return isAffectedByJavaModel(delta, element, eventType);
case IJavaElement.JAVA_PROJECT:
return isAffectedByJavaProject(delta, element, eventType);
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
return isAffectedByPackageFragmentRoot(delta, element, eventType);
case IJavaElement.PACKAGE_FRAGMENT:
return isAffectedByPackageFragment(delta, (PackageFragment) element, eventType);
case IJavaElement.CLASS_FILE:
case IJavaElement.COMPILATION_UNIT:
return isAffectedByOpenable(delta, element, eventType);
}
return false;
}
/**
* Returns true if any of the children of a project, package
* fragment root, or package fragment have changed in a way that
* affects this type hierarchy.
* @param eventType TODO
*/
private boolean isAffectedByChildren(IJavaElementDelta delta, int eventType) {
if ((delta.getFlags() & IJavaElementDelta.F_CHILDREN) > 0) {
IJavaElementDelta[] children= delta.getAffectedChildren();
for (int i= 0; i < children.length; i++) {
if (isAffected(children[i], eventType)) {
return true;
}
}
}
return false;
}
/**
* Returns true if the given java model delta could affect this type hierarchy
* @param eventType TODO
*/
private boolean isAffectedByJavaModel(IJavaElementDelta delta, IJavaElement element, int eventType) {
switch (delta.getKind()) {
case IJavaElementDelta.ADDED :
case IJavaElementDelta.REMOVED :
return element.equals(javaProject().getJavaModel());
case IJavaElementDelta.CHANGED :
return isAffectedByChildren(delta, eventType);
}
return false;
}
/**
* Returns true if the given java project delta could affect this type hierarchy
* @param eventType TODO
*/
private boolean isAffectedByJavaProject(IJavaElementDelta delta, IJavaElement element, int eventType) {
int kind = delta.getKind();
int flags = delta.getFlags();
if ((flags & IJavaElementDelta.F_OPENED) != 0) {
kind = IJavaElementDelta.ADDED; // affected in the same way
}
if ((flags & IJavaElementDelta.F_CLOSED) != 0) {
kind = IJavaElementDelta.REMOVED; // affected in the same way
}
switch (kind) {
case IJavaElementDelta.ADDED :
try {
// if the added project is on the classpath, then the hierarchy has changed
IClasspathEntry[] classpath = ((JavaProject)javaProject()).getExpandedClasspath();
for (int i = 0; i < classpath.length; i++) {
if (classpath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT
&& classpath[i].getPath().equals(element.getPath())) {
return true;
}
}
if (this.focusType != null) {
// if the hierarchy's project is on the added project classpath, then the hierarchy has changed
classpath = ((JavaProject)element).getExpandedClasspath();
IPath hierarchyProject = javaProject().getPath();
for (int i = 0; i < classpath.length; i++) {
if (classpath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT
&& classpath[i].getPath().equals(hierarchyProject)) {
return true;
}
}
}
return false;
} catch (JavaModelException e) {
return false;
}
case IJavaElementDelta.REMOVED :
// removed project - if it contains packages we are interested in
// then the type hierarchy has changed
IJavaElement[] pkgs = this.packageRegion.getElements();
for (int i = 0; i < pkgs.length; i++) {
IJavaProject javaProject = pkgs[i].getJavaProject();
if (javaProject != null && javaProject.equals(element)) {
return true;
}
}
return false;
case IJavaElementDelta.CHANGED :
return isAffectedByChildren(delta, eventType);
}
return false;
}
/**
* Returns true if the given package fragment delta could affect this type hierarchy
* @param eventType TODO
*/
private boolean isAffectedByPackageFragment(IJavaElementDelta delta, PackageFragment element, int eventType) {
switch (delta.getKind()) {
case IJavaElementDelta.ADDED :
// if the package fragment is in the projects being considered, this could
// introduce new types, changing the hierarchy
return this.projectRegion.contains(element);
case IJavaElementDelta.REMOVED :
// is a change if the package fragment contains types in this hierarchy
return packageRegionContainsSamePackageFragment(element);
case IJavaElementDelta.CHANGED :
// look at the files in the package fragment
return isAffectedByChildren(delta, eventType);
}
return false;
}
/**
* Returns true if the given package fragment root delta could affect this type hierarchy
* @param eventType TODO
*/
private boolean isAffectedByPackageFragmentRoot(IJavaElementDelta delta, IJavaElement element, int eventType) {
switch (delta.getKind()) {
case IJavaElementDelta.ADDED :
return this.projectRegion.contains(element);
case IJavaElementDelta.REMOVED :
case IJavaElementDelta.CHANGED :
int flags = delta.getFlags();
if ((flags & IJavaElementDelta.F_ADDED_TO_CLASSPATH) > 0) {
// check if the root is in the classpath of one of the projects of this hierarchy
if (this.projectRegion != null) {
IPackageFragmentRoot root = (IPackageFragmentRoot)element;
IPath rootPath = root.getPath();
IJavaElement[] elements = this.projectRegion.getElements();
for (int i = 0; i < elements.length; i++) {
JavaProject javaProject = (JavaProject)elements[i];
try {
IClasspathEntry entry = javaProject.getClasspathEntryFor(rootPath);
if (entry != null) {
return true;
}
} catch (JavaModelException e) {
// igmore this project
}
}
}
}
if ((flags & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) > 0 || (flags & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) > 0) {
// 1. removed from classpath - if it contains packages we are interested in
// the the type hierarchy has changed
// 2. content of a jar changed - if it contains packages we are interested in
// then the type hierarchy has changed
IJavaElement[] pkgs = this.packageRegion.getElements();
for (int i = 0; i < pkgs.length; i++) {
if (pkgs[i].getParent().equals(element)) {
return true;
}
}
return false;
}
}
return isAffectedByChildren(delta, eventType);
}
/**
* Returns true if the given type delta (a compilation unit delta or a class file delta)
* could affect this type hierarchy.
* @param eventType TODO
*/
protected boolean isAffectedByOpenable(IJavaElementDelta delta, IJavaElement element, int eventType) {
if (element instanceof CompilationUnit) {
CompilationUnit cu = (CompilationUnit)element;
ICompilationUnit focusCU =
this.focusType != null ? this.focusType.getCompilationUnit() : null;
if (focusCU != null && focusCU.getOwner() != cu.getOwner())
return false;
//ADDED delta arising from getWorkingCopy() should be ignored
if (eventType != ElementChangedEvent.POST_RECONCILE && !cu.isPrimary() &&
delta.getKind() == IJavaElementDelta.ADDED)
return false;
ChangeCollector collector = this.changeCollector;
if (collector == null) {
collector = new ChangeCollector(this);
}
try {
collector.addChange(cu, delta);
} catch (JavaModelException e) {
if (DEBUG)
e.printStackTrace();
}
if (cu.isWorkingCopy() && eventType == ElementChangedEvent.POST_RECONCILE) {
// changes to working copies are batched
this.changeCollector = collector;
return false;
} else {
return collector.needsRefresh();
}
} else if (element instanceof ClassFile) {
switch (delta.getKind()) {
case IJavaElementDelta.REMOVED:
IOpenable o = (IOpenable) element;
return this.files.get(o) != null;
case IJavaElementDelta.ADDED:
IType type = ((ClassFile)element).getType();
String typeName = type.getElementName();
if (hasSupertype(typeName)
|| subtypesIncludeSupertypeOf(type)
|| this.missingTypes.contains(typeName)) {
return true;
}
break;
case IJavaElementDelta.CHANGED:
IJavaElementDelta[] children = delta.getAffectedChildren();
for (int i = 0, length = children.length; i < length; i++) {
IJavaElementDelta child = children[i];
IJavaElement childElement = child.getElement();
if (childElement instanceof IType) {
type = (IType)childElement;
boolean hasVisibilityChange = (delta.getFlags() & IJavaElementDelta.F_MODIFIERS) > 0;
boolean hasSupertypeChange = (delta.getFlags() & IJavaElementDelta.F_SUPER_TYPES) > 0;
if ((hasVisibilityChange && hasSupertype(type.getElementName()))
|| (hasSupertypeChange && includesTypeOrSupertype(type))) {
return true;
}
}
}
break;
}
}
return false;
}
private boolean isInterface(IType type) {
int flags = getCachedFlags(type);
if (flags == -1) {
try {
return type.isInterface();
} catch (JavaModelException e) {
return false;
}
} else {
return Flags.isInterface(flags);
}
}
/**
* Returns the java project this hierarchy was created in.
*/
public IJavaProject javaProject() {
return this.focusType.getJavaProject();
}
protected static byte[] readUntil(InputStream input, byte separator) throws JavaModelException, IOException{
return readUntil(input, separator, 0);
}
protected static byte[] readUntil(InputStream input, byte separator, int offset) throws IOException, JavaModelException{
int length = 0;
byte[] bytes = new byte[SIZE];
byte b;
while((b = (byte)input.read()) != separator && b != -1) {
if(bytes.length == length) {
System.arraycopy(bytes, 0, bytes = new byte[length*2], 0, length);
}
bytes[length++] = b;
}
if(b == -1) {
throw new JavaModelException(new JavaModelStatus(IStatus.ERROR));
}
System.arraycopy(bytes, 0, bytes = new byte[length + offset], offset, length);
return bytes;
}
public static ITypeHierarchy load(IType type, InputStream input, WorkingCopyOwner owner) throws JavaModelException {
try {
TypeHierarchy typeHierarchy = new TypeHierarchy();
typeHierarchy.initialize(1);
IType[] types = new IType[SIZE];
int typeCount = 0;
byte version = (byte)input.read();
if(version != VERSION) {
throw new JavaModelException(new JavaModelStatus(IStatus.ERROR));
}
byte generalInfo = (byte)input.read();
if((generalInfo & COMPUTE_SUBTYPES) != 0) {
typeHierarchy.computeSubtypes = true;
}
byte b;
byte[] bytes;
// read project
bytes = readUntil(input, SEPARATOR1);
if(bytes.length > 0) {
typeHierarchy.project = (IJavaProject)JavaCore.create(new String(bytes));
typeHierarchy.scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {typeHierarchy.project});
} else {
typeHierarchy.project = null;
typeHierarchy.scope = SearchEngine.createWorkspaceScope();
}
// read missing type
{
bytes = readUntil(input, SEPARATOR1);
byte[] missing;
int j = 0;
int length = bytes.length;
for (int i = 0; i < length; i++) {
b = bytes[i];
if(b == SEPARATOR2) {
missing = new byte[i - j];
System.arraycopy(bytes, j, missing, 0, i - j);
typeHierarchy.missingTypes.add(new String(missing));
j = i + 1;
}
}
System.arraycopy(bytes, j, missing = new byte[length - j], 0, length - j);
typeHierarchy.missingTypes.add(new String(missing));
}
// read types
while((b = (byte)input.read()) != SEPARATOR1 && b != -1) {
bytes = readUntil(input, SEPARATOR4, 1);
bytes[0] = b;
IType element = (IType)JavaCore.create(new String(bytes), owner);
if(types.length == typeCount) {
System.arraycopy(types, 0, types = new IType[typeCount * 2], 0, typeCount);
}
types[typeCount++] = element;
// read flags
bytes = readUntil(input, SEPARATOR4);
Integer flags = bytesToFlags(bytes);
if(flags != null) {
typeHierarchy.cacheFlags(element, flags.intValue());
}
// read info
byte info = (byte)input.read();
if((info & INTERFACE) != 0) {
typeHierarchy.addInterface(element);
}
if((info & COMPUTED_FOR) != 0) {
if(!element.equals(type)) {
throw new JavaModelException(new JavaModelStatus(IStatus.ERROR));
}
typeHierarchy.focusType = element;
}
if((info & ROOT) != 0) {
typeHierarchy.addRootClass(element);
}
}
// read super class
while((b = (byte)input.read()) != SEPARATOR1 && b != -1) {
bytes = readUntil(input, SEPARATOR3, 1);
bytes[0] = b;
int subClass = Integer.parseInt(new String(bytes));
// read super type
bytes = readUntil(input, SEPARATOR1);
int superClass = Integer.parseInt(new String(bytes));
typeHierarchy.cacheSuperclass(
types[subClass],
types[superClass]);
}
// read super interface
while((b = (byte)input.read()) != SEPARATOR1 && b != -1) {
bytes = readUntil(input, SEPARATOR3, 1);
bytes[0] = b;
int subClass = Integer.parseInt(new String(bytes));
// read super interface
bytes = readUntil(input, SEPARATOR1);
IType[] superInterfaces = new IType[(bytes.length / 2) + 1];
int interfaceCount = 0;
int j = 0;
byte[] b2;
for (int i = 0; i < bytes.length; i++) {
if(bytes[i] == SEPARATOR2){
b2 = new byte[i - j];
System.arraycopy(bytes, j, b2, 0, i - j);
j = i + 1;
superInterfaces[interfaceCount++] = types[Integer.parseInt(new String(b2))];
}
}
b2 = new byte[bytes.length - j];
System.arraycopy(bytes, j, b2, 0, bytes.length - j);
superInterfaces[interfaceCount++] = types[Integer.parseInt(new String(b2))];
System.arraycopy(superInterfaces, 0, superInterfaces = new IType[interfaceCount], 0, interfaceCount);
typeHierarchy.cacheSuperInterfaces(
types[subClass],
superInterfaces);
}
if(b == -1) {
throw new JavaModelException(new JavaModelStatus(IStatus.ERROR));
}
return typeHierarchy;
} catch(IOException e){
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
}
}
/**
* Returns <code>true</code> if an equivalent package fragment is included in the package
* region. Package fragments are equivalent if they both have the same name.
*/
protected boolean packageRegionContainsSamePackageFragment(PackageFragment element) {
IJavaElement[] pkgs = this.packageRegion.getElements();
for (int i = 0; i < pkgs.length; i++) {
PackageFragment pkg = (PackageFragment) pkgs[i];
if (Util.equalArraysOrNull(pkg.names, element.names))
return true;
}
return false;
}
/**
* @see ITypeHierarchy
* TODO (jerome) should use a PerThreadObject to build the hierarchy instead of synchronizing
* (see also isAffected(IJavaElementDelta))
*/
public synchronized void refresh(IProgressMonitor monitor) throws JavaModelException {
try {
this.progressMonitor = SubMonitor.convert(monitor,
this.focusType != null ?
Messages.bind(Messages.hierarchy_creatingOnType, this.focusType.getFullyQualifiedName()) :
Messages.hierarchy_creating,
100);
long start = -1;
if (DEBUG) {
start = System.currentTimeMillis();
if (this.computeSubtypes) {
System.out.println("CREATING TYPE HIERARCHY [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
System.out.println("CREATING SUPER TYPE HIERARCHY [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$
}
if (this.focusType != null) {
System.out.println(" on type " + ((JavaElement)this.focusType).toStringWithAncestors()); //$NON-NLS-1$
}
}
compute();
initializeRegions();
this.needsRefresh = false;
this.changeCollector = null;
if (DEBUG) {
if (this.computeSubtypes) {
System.out.println("CREATED TYPE HIERARCHY in " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
System.out.println("CREATED SUPER TYPE HIERARCHY in " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
}
System.out.println(this.toString());
}
} catch (JavaModelException e) {
throw e;
} catch (CoreException e) {
throw new JavaModelException(e);
} finally {
if (monitor != null) {
monitor.done();
}
this.progressMonitor = null;
}
}
/**
* @see ITypeHierarchy
*/
public synchronized void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) {
ArrayList<ITypeHierarchyChangedListener> listeners = this.changeListeners;
if (listeners == null) {
return;
}
listeners.remove(listener);
// deregister from JavaCore on last listener removed
if (listeners.isEmpty()) {
JavaCore.removeElementChangedListener(this);
}
}
/**
* @see ITypeHierarchy
*/
@SuppressWarnings("unchecked")
public void store(OutputStream output, IProgressMonitor monitor) throws JavaModelException {
try {
// compute types in hierarchy
Hashtable<IType, Integer> hashtable = new Hashtable<>();
Hashtable<Integer, IType> hashtable2 = new Hashtable<>();
int count = 0;
if(this.focusType != null) {
Integer index = Integer.valueOf(count++);
hashtable.put(this.focusType, index);
hashtable2.put(index, this.focusType);
}
Object[] types = this.classToSuperclass.entrySet().toArray();
for (int i = 0; i < types.length; i++) {
Map.Entry<IType, IType> entry = (Map.Entry<IType, IType>) types[i];
IType t = entry.getKey();
if(hashtable.get(t) == null) {
Integer index = Integer.valueOf(count++);
hashtable.put(t, index);
hashtable2.put(index, t);
}
IType superClass = entry.getValue();
if(superClass != null && hashtable.get(superClass) == null) {
Integer index = Integer.valueOf(count++);
hashtable.put(superClass, index);
hashtable2.put(index, superClass);
}
}
Object[] intfs = this.typeToSuperInterfaces.entrySet().toArray();
for (int i = 0; i < intfs.length; i++) {
Map.Entry<IType, IType[]> entry = (Map.Entry<IType, IType[]>) intfs[i];
IType t = entry.getKey();
if(hashtable.get(t) == null) {
Integer index = Integer.valueOf(count++);
hashtable.put(t, index);
hashtable2.put(index, t);
}
IType[] sp = entry.getValue();
if(sp != null) {
for (int j = 0; j < sp.length; j++) {
IType superInterface = sp[j];
if(sp[j] != null && hashtable.get(superInterface) == null) {
Integer index = Integer.valueOf(count++);
hashtable.put(superInterface, index);
hashtable2.put(index, superInterface);
}
}
}
}
// save version of the hierarchy format
output.write(VERSION);
// save general info
byte generalInfo = 0;
if(this.computeSubtypes) {
generalInfo |= COMPUTE_SUBTYPES;
}
output.write(generalInfo);
// save project
if(this.project != null) {
output.write(this.project.getHandleIdentifier().getBytes());
}
output.write(SEPARATOR1);
// save missing types
for (int i = 0; i < this.missingTypes.size(); i++) {
if(i != 0) {
output.write(SEPARATOR2);
}
output.write((this.missingTypes.get(i)).getBytes());
}
output.write(SEPARATOR1);
// save types
for (int i = 0; i < count ; i++) {
IType t = hashtable2.get(Integer.valueOf(i));
// n bytes
output.write(t.getHandleIdentifier().getBytes());
output.write(SEPARATOR4);
output.write(flagsToBytes(this.typeFlags.get(t)));
output.write(SEPARATOR4);
byte info = CLASS;
if(this.focusType != null && this.focusType.equals(t)) {
info |= COMPUTED_FOR;
}
if(this.interfaces.contains(t)) {
info |= INTERFACE;
}
if(this.rootClasses.contains(t)) {
info |= ROOT;
}
output.write(info);
}
output.write(SEPARATOR1);
// save superclasses
types = this.classToSuperclass.entrySet().toArray();
for (int i = 0; i < types.length; i++) {
Map.Entry<IType, IType> entry = (Map.Entry<IType, IType>) types[i];
IJavaElement key = entry.getKey();
IJavaElement value = entry.getValue();
output.write(hashtable.get(key).toString().getBytes());
output.write('>');
output.write(hashtable.get(value).toString().getBytes());
output.write(SEPARATOR1);
}
output.write(SEPARATOR1);
// save superinterfaces
intfs = this.typeToSuperInterfaces.entrySet().toArray();
for (int i = 0; i < intfs.length; i++) {
Map.Entry<IType, IType[]> entry = (Map.Entry<IType, IType[]>) intfs[i];
IJavaElement key = entry.getKey();
IJavaElement[] values = entry.getValue();
if(values.length > 0) {
output.write(hashtable.get(key).toString().getBytes());
output.write(SEPARATOR3);
for (int j = 0; j < values.length; j++) {
IJavaElement value = values[j];
if(j != 0) output.write(SEPARATOR2);
output.write(hashtable.get(value).toString().getBytes());
}
output.write(SEPARATOR1);
}
}
output.write(SEPARATOR1);
} catch(IOException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
}
}
/**
* Returns whether the simple name of a supertype of the given type is
* the simple name of one of the subtypes in this hierarchy or the
* simple name of this type.
*/
boolean subtypesIncludeSupertypeOf(IType type) {
// look for superclass
String superclassName = null;
try {
superclassName = type.getSuperclassName();
} catch (JavaModelException e) {
if (DEBUG) {
e.printStackTrace();
}
return false;
}
if (superclassName == null) {
superclassName = "Object"; //$NON-NLS-1$
}
if (hasSubtypeNamed(superclassName)) {
return true;
}
// look for super interfaces
String[] interfaceNames = null;
try {
interfaceNames = type.getSuperInterfaceNames();
} catch (JavaModelException e) {
if (DEBUG)
e.printStackTrace();
return false;
}
for (int i = 0, length = interfaceNames.length; i < length; i++) {
String interfaceName = interfaceNames[i];
if (hasSubtypeNamed(interfaceName)) {
return true;
}
}
return false;
}
/**
* @see ITypeHierarchy
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Focus: "); //$NON-NLS-1$
if (this.focusType == null) {
buffer.append("<NONE>\n"); //$NON-NLS-1$
} else {
toString(buffer, this.focusType, 0);
}
if (exists()) {
if (this.focusType != null) {
buffer.append("Super types:\n"); //$NON-NLS-1$
toString(buffer, this.focusType, 0, true);
buffer.append("Sub types:\n"); //$NON-NLS-1$
toString(buffer, this.focusType, 0, false);
} else {
if (this.rootClasses.size > 0) {
IJavaElement[] roots = Util.sortCopy(getRootClasses());
buffer.append("Super types of root classes:\n"); //$NON-NLS-1$
int length = roots.length;
for (int i = 0; i < length; i++) {
IJavaElement root = roots[i];
toString(buffer, root, 1);
toString(buffer, root, 1, true);
}
buffer.append("Sub types of root classes:\n"); //$NON-NLS-1$
for (int i = 0; i < length; i++) {
IJavaElement root = roots[i];
toString(buffer, root, 1);
toString(buffer, root, 1, false);
}
} else if (this.rootClasses.size == 0) {
// see http://bugs.eclipse.org/bugs/show_bug.cgi?id=24691
buffer.append("No root classes"); //$NON-NLS-1$
}
}
} else {
buffer.append("(Hierarchy became stale)"); //$NON-NLS-1$
}
return buffer.toString();
}
/**
* Append a String to the given buffer representing the hierarchy for the type,
* beginning with the specified indentation level.
* If ascendant, shows the super types, otherwise show the sub types.
*/
private void toString(StringBuffer buffer, IJavaElement type, int indent, boolean ascendant) {
IType[] types= ascendant ? getSupertypes((IType) type) : getSubtypes((IType) type);
IJavaElement[] sortedTypes = Util.sortCopy(types);
for (int i= 0; i < sortedTypes.length; i++) {
toString(buffer, sortedTypes[i], indent + 1);
toString(buffer, sortedTypes[i], indent + 1, ascendant);
}
}
private void toString(StringBuffer buffer, IJavaElement type, int indent) {
for (int j= 0; j < indent; j++) {
buffer.append(" "); //$NON-NLS-1$
}
buffer.append(((JavaElement) type).toStringWithAncestors(false/*don't show key*/));
buffer.append('\n');
}
/**
* Returns whether one of the types in this hierarchy has a supertype whose simple
* name is the given simple name.
*/
boolean hasSupertype(String simpleName) {
for(Iterator<IType> iter = this.classToSuperclass.values().iterator(); iter.hasNext();){
IType superType = iter.next();
if (superType.getElementName().equals(simpleName)) {
return true;
}
}
return false;
}
/**
* @see IProgressMonitor
*/
protected void worked(int work) {
if (this.progressMonitor != null) {
this.progressMonitor.worked(work);
checkCanceled();
}
}
}
| epl-1.0 |
jesusc/anatlyzer | evaluation/anatlyzer.evaluation.mutants/src/anatlyzer/evaluation/tester/EvaluationFinishedOnRequest.java | 178 | package anatlyzer.evaluation.tester;
public class EvaluationFinishedOnRequest extends RuntimeException {
private static final long serialVersionUID = -8131442733125817354L;
}
| epl-1.0 |
NABUCCO/org.nabucco.framework.base | org.nabucco.framework.base.facade.exception/src/main/gen/org/nabucco/framework/base/facade/exception/service/ProduceException.java | 1839 | /*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package org.nabucco.framework.base.facade.exception.service;
import org.nabucco.framework.base.facade.exception.service.ServiceException;
/**
* ProduceException<p/>Exception for produce services within NABUCCO<p/>
*
* @version 1.0
* @author Stefanie Feld, PRODYNA AG, 2010-03-29
*/
public class ProduceException extends ServiceException {
private static final long serialVersionUID = 1L;
/** Constructs a new ProduceException instance. */
public ProduceException() {
super();
}
/**
* Constructs a new ProduceException instance.
*
* @param message the String.
*/
public ProduceException(String message) {
super(message);
}
/**
* Constructs a new ProduceException instance.
*
* @param cause the Throwable.
*/
public ProduceException(Throwable cause) {
super(cause);
}
/**
* Constructs a new ProduceException instance.
*
* @param cause the Throwable.
* @param message the String.
*/
public ProduceException(String message, Throwable cause) {
super(message, cause);
}
}
| epl-1.0 |
smkr/pyclipse | plugins/com.python.pydev/src/com/python/pydev/interactiveconsole/EvaluateActionSetter.java | 9151 | /**
* Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
/*
* Created on Mar 7, 2006
*/
package com.python.pydev.interactiveconsole;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.ListResourceBundle;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IConsoleView;
import org.python.pydev.core.docutils.PySelection;
import org.python.pydev.core.log.Log;
import org.python.pydev.debug.newconsole.PydevConsole;
import org.python.pydev.debug.newconsole.PydevConsoleConstants;
import org.python.pydev.debug.newconsole.PydevConsoleFactory;
import org.python.pydev.debug.newconsole.prefs.InteractiveConsolePrefs;
import org.python.pydev.editor.IPyEditListener;
import org.python.pydev.editor.PyEdit;
import com.aptana.interactive_console.console.codegen.PythonSnippetUtils;
import com.aptana.interactive_console.console.ui.ScriptConsole;
import com.aptana.interactive_console.console.ui.internal.ScriptConsoleViewer;
import com.aptana.interactive_console.console.ui.internal.actions.IInteractiveConsoleConstants;
/**
* This class will setup the editor so that we can create interactive consoles, send code to it or make an execfile.
*
* It is as a 'singleton' for all PyEdit editors.
*/
public class EvaluateActionSetter implements IPyEditListener {
private class EvaluateAction extends Action {
private final PyEdit edit;
private EvaluateAction(PyEdit edit) {
super();
this.edit = edit;
}
public void run() {
try {
PySelection selection = new PySelection(edit);
ScriptConsole console = getActiveScriptConsole(PydevConsoleConstants.CONSOLE_TYPE);
if (console == null) {
//if no console is available, create it (if possible).
PydevConsoleFactory factory = new PydevConsoleFactory();
String cmd = null;
//Check if the current selection should be sent to the editor.
if (InteractiveConsolePrefs.getSendCommandOnCreationFromEditor()) {
cmd = getCommandToSend(edit, selection);
if (cmd != null) {
cmd = "\n" + cmd;
}
}
factory.createConsole(cmd);
} else {
if (console instanceof PydevConsole) {
//ok, console available
sendCommandToConsole(selection, console, this.edit);
}
}
} catch (Exception e) {
Log.log(e);
}
}
}
/**
* Sends the current selected text/editor to the console.
*/
private static void sendCommandToConsole(PySelection selection, ScriptConsole console, PyEdit edit)
throws BadLocationException {
PydevConsole pydevConsole = (PydevConsole) console;
IDocument document = pydevConsole.getDocument();
String cmd = getCommandToSend(edit, selection);
if (cmd != null) {
document.replace(document.getLength(), 0, cmd);
}
if (InteractiveConsolePrefs.getFocusConsoleOnSendCommand()) {
ScriptConsoleViewer viewer = pydevConsole.getViewer();
if (viewer == null) {
return;
}
StyledText textWidget = viewer.getTextWidget();
if (textWidget == null) {
return;
}
textWidget.setFocus();
}
}
/**
* Gets the command to send to the console (either the selected text or an execfile with the editor).
*/
private static String getCommandToSend(PyEdit edit, PySelection selection) {
String cmd = null;
String code = selection.getTextSelection().getText();
if (code.length() != 0) {
cmd = code + "\n";
} else {
//no code available: do an execfile in the current context
File editorFile = edit.getEditorFile();
if (editorFile != null) {
cmd = PythonSnippetUtils.getExecfileCommand(editorFile);
}
}
return cmd;
}
/**
* @param consoleType the console type we're searching for
* @return the currently active console.
*/
private ScriptConsole getActiveScriptConsole(String consoleType) {
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window != null) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
List<IViewPart> consoleParts = getConsoleParts(page, false);
if (consoleParts.size() == 0) {
consoleParts = getConsoleParts(page, true);
}
if (consoleParts.size() > 0) {
IConsoleView view = null;
long lastChangeMillis = Long.MIN_VALUE;
if (consoleParts.size() == 1) {
view = (IConsoleView) consoleParts.get(0);
} else {
//more than 1 view available
for (int i = 0; i < consoleParts.size(); i++) {
IConsoleView temp = (IConsoleView) consoleParts.get(i);
IConsole console = temp.getConsole();
if (console instanceof PydevConsole) {
PydevConsole tempConsole = (PydevConsole) console;
ScriptConsoleViewer viewer = tempConsole.getViewer();
long tempLastChangeMillis = viewer.getLastChangeMillis();
if (tempLastChangeMillis > lastChangeMillis) {
lastChangeMillis = tempLastChangeMillis;
view = temp;
}
}
}
}
if (view != null) {
IConsole console = view.getConsole();
if (console instanceof ScriptConsole && console.getType().equals(consoleType)) {
return (ScriptConsole) console;
}
}
}
}
}
return null;
}
/**
* @param page the page where the console view is
* @param restore whether we should try to restore it
* @return a list with the parts containing the console
*/
private List<IViewPart> getConsoleParts(IWorkbenchPage page, boolean restore) {
List<IViewPart> consoleParts = new ArrayList<IViewPart>();
IViewReference[] viewReferences = page.getViewReferences();
for (IViewReference ref : viewReferences) {
if (ref.getId().equals(IConsoleConstants.ID_CONSOLE_VIEW)) {
IViewPart part = ref.getView(restore);
if (part != null) {
consoleParts.add(part);
if (restore) {
return consoleParts;
}
}
}
}
return consoleParts;
}
/**
* This method associates Ctrl+new line with the evaluation of commands in the console.
*/
public void onCreateActions(ListResourceBundle resources, final PyEdit edit, IProgressMonitor monitor) {
final EvaluateAction evaluateAction = new EvaluateAction(edit);
evaluateAction.setActionDefinitionId(IInteractiveConsoleConstants.EVALUATE_ACTION_ID);
evaluateAction.setId(IInteractiveConsoleConstants.EVALUATE_ACTION_ID);
Runnable runnable = new Runnable() {
public void run() {
if (!edit.isDisposed()) {
edit.setAction(IInteractiveConsoleConstants.EVALUATE_ACTION_ID, evaluateAction);
}
}
};
Display.getDefault().syncExec(runnable);
}
public void onSave(PyEdit edit, IProgressMonitor monitor) {
//ignore
}
public void onDispose(PyEdit edit, IProgressMonitor monitor) {
//ignore
}
public void onSetDocument(IDocument document, PyEdit edit, IProgressMonitor monitor) {
//ignore
}
}
| epl-1.0 |
jesusc/bento | componetization/bento.componetization.atl/src/bento/componetization/atl/refactorings/RemoveEmptyClass.java | 2886 | package bento.componetization.atl.refactorings;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.EcoreUtil;
import bento.componetization.atl.BaseRefactoring;
import bento.componetization.atl.IMetamodelInfo;
import bento.componetization.atl.IStaticAnalysisInfo;
/**
* This refactoring remove empty classes in an inheritance hierarchy,
* taking into account that classes explicitly named in the transformation
* cannot be removed.
*
* @author jesus
*
*/
public class RemoveEmptyClass extends BaseRefactoring {
public RemoveEmptyClass(IStaticAnalysisInfo analysis, IMetamodelInfo metamodel) {
super(analysis, metamodel);
}
@Override
public boolean match() {
List<IMatch> matches = new ArrayList<IMatch>();
Set<EClass> classes = metamodel.getClasses();
for (EClass eClass : classes) {
if ( eClass.getEStructuralFeatures().size() == 0 ) {
if ( analysis.getExplicitlyUsedTypes().contains(eClass) )
continue;
IMatch m = checkMatchType(eClass);
if ( m != null )
matches.add(m);
}
}
return save(matches);
}
private IMatch checkMatchType(EClass eClass) {
List<EReference> pointers = new ArrayList<EReference>();
for(EStructuralFeature f : metamodel.getFeatures()) {
if ( f instanceof EReference ) {
EReference r = (EReference) f;
if ( r.getEReferenceType() == eClass ) {
pointers.add(r);
}
}
}
if ( pointers.size() == 0 )
return new RemoveEmptyClassMatch_NoPointer(eClass);
//if ( pointers.size() <= maxPointersToEmptyClass )
// return new RemoveEmptyClassMatch_Pointer(tgtClass, pointers);
return null;
}
public class RemoveEmptyClassMatch_NoPointer extends BaseMatch {
private EClass eClass;
public RemoveEmptyClassMatch_NoPointer(EClass eClass) {
super(RemoveEmptyClass.this);
this.eClass = eClass;
}
@Override
public Collection<EClass> getAffectedClasses() {
ArrayList<EClass> info = new ArrayList<EClass>();
info.add(eClass);
return info;
}
@Override
public void apply() {
System.out.println("REFACTORING: Remove empty class " + eClass.getName());
Set<EClass> classes = metamodel.getClasses();
for (EClass possibleSubclass : classes) {
if ( possibleSubclass.getESuperTypes().contains(eClass) ) {
possibleSubclass.getESuperTypes().remove(eClass);
for(EClass superclass : eClass.getESuperTypes() ) {
possibleSubclass.getESuperTypes().add(superclass);
}
}
}
EcoreUtil.delete(eClass, true);
// EcoreUtil.remove(tgtClass);
// prunner.removeClass(tgtClass);
}
@Override
public boolean coevolutionRequired() {
return false;
}
}
}
| epl-1.0 |
sleshchenko/che | ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/action/Action.java | 2256 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.ide.api.action;
/**
* Represents an entity that has a state, a presentation and can be performed.
*
* <p>For an action to be useful, you need to implement {@link BaseAction#actionPerformed} and
* optionally to override {@link BaseAction#update}. By overriding the {@link BaseAction#update}
* method you can dynamically change action's presentation.
*
* <p>The same action can have various presentations.
*
* @author Yevhen Vydolob
*/
public interface Action {
/**
* Updates the state of the action. Default implementation does nothing. Override this method to
* provide the ability to dynamically change action's state and(or) presentation depending on the
* context (For example when your action state depends on the selection you can check for
* selection and change the state accordingly). This method can be called frequently, for
* instance, if an action is added to a toolbar, it will be updated twice a second. This means
* that this method is supposed to work really fast, no real work should be done at this phase.
* For example, checking selection in a tree or a list, is considered valid, but working with a
* file system is not. If you cannot understand the state of the action fast you should do it in
* the {@link #actionPerformed(ActionEvent)} method and notify the user that action cannot be
* executed if it's the case.
*
* @param e Carries information on the invocation place and data available
*/
void update(ActionEvent e);
/**
* Returns a template presentation that will be used as a template for created presentations.
*
* @return template presentation
*/
Presentation getTemplatePresentation();
/**
* Implement this method to provide your action handler.
*
* @param e Carries information on the invocation place
*/
void actionPerformed(ActionEvent e);
}
| epl-1.0 |
astechishin/CMET_Maint | app/models/cmet.rb | 446 | class Cmet < ActiveRecord::Base
self.primary_key = :ident
belongs_to :work_group
has_many :cmet_versions
scope :id_order, -> { order(ident: :asc) }
include PgSearch
pg_search_scope :search, against: [:descriptor, :description],
using: {tsearch: {dictionary: "english"}}
def self.text_search(query)
if query.present?
search(query)
else
all.id_order.includes(:work_group)
end
end
end
| epl-1.0 |
kaskr/CppAD | example/utility/runge45_1.cpp | 3226 | /* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Eclipse Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin runge45_1.cpp$$
$spell
Runge
$$
$section Runge45: Example and Test$$
$mindex Runge45$$
Define
$latex X : \B{R} \rightarrow \B{R}^n$$ by
$latex \[
X_i (t) = t^{i+1}
\] $$
for $latex i = 1 , \ldots , n-1$$.
It follows that
$latex \[
\begin{array}{rclr}
X_i(0) & = & 0 & {\rm for \; all \;} i \\
X_i ' (t) & = & 1 & {\rm if \;} i = 0 \\
X_i '(t) & = & (i+1) t^i = (i+1) X_{i-1} (t) & {\rm if \;} i > 0
\end{array}
\] $$
The example tests Runge45 using the relations above:
$code
$srcfile%example/utility/runge45_1.cpp%0%// BEGIN C++%// END C++%1%$$
$$
$end
*/
// BEGIN C++
# include <cstddef> // for size_t
# include <cppad/utility/near_equal.hpp> // for CppAD::NearEqual
# include <cppad/utility/vector.hpp> // for CppAD::vector
# include <cppad/utility/runge_45.hpp> // for CppAD::Runge45
// Runge45 requires fabs to be defined (not std::fabs)
// <cppad/cppad.hpp> defines this for doubles, but runge_45.hpp does not.
# include <math.h> // for fabs without std in front
namespace {
class Fun {
public:
// constructor
Fun(bool use_x_) : use_x(use_x_)
{ }
// set f = x'(t)
void Ode(
const double &t,
const CppAD::vector<double> &x,
CppAD::vector<double> &f)
{ size_t n = x.size();
double ti = 1.;
f[0] = 1.;
size_t i;
for(i = 1; i < n; i++)
{ ti *= t;
if( use_x )
f[i] = double(i+1) * x[i-1];
else f[i] = double(i+1) * ti;
}
}
private:
const bool use_x;
};
}
bool runge_45_1(void)
{ bool ok = true; // initial return value
size_t i; // temporary indices
using CppAD::NearEqual;
double eps99 = 99.0 * std::numeric_limits<double>::epsilon();
size_t n = 5; // number components in X(t) and order of method
size_t M = 2; // number of Runge45 steps in [ti, tf]
double ti = 0.; // initial time
double tf = 2.; // final time
// xi = X(0)
CppAD::vector<double> xi(n);
for(i = 0; i <n; i++)
xi[i] = 0.;
size_t use_x;
for( use_x = 0; use_x < 2; use_x++)
{ // function object depends on value of use_x
Fun F(use_x > 0);
// compute Runge45 approximation for X(tf)
CppAD::vector<double> xf(n), e(n);
xf = CppAD::Runge45(F, M, ti, tf, xi, e);
double check = tf;
for(i = 0; i < n; i++)
{ // check that error is always positive
ok &= (e[i] >= 0.);
// 5th order method is exact for i < 5
if( i < 5 ) ok &=
NearEqual(xf[i], check, eps99, eps99);
// 4th order method is exact for i < 4
if( i < 4 )
ok &= (e[i] <= eps99);
// check value for next i
check *= tf;
}
}
return ok;
}
// END C++
| epl-1.0 |
calabash/calabash | lib/calabash/ios/automator/coordinates.rb | 1070 | module Calabash
module IOS
# @!visibility private
module Automator
# @!visibility private
class Coordinates
# @!visibility private
def self.end_point_for_swipe(dir, element)
case dir
when :left
degrees = 0
when :up
degrees = 90
when :right
degrees = 180
when :down
degrees = 270
end
radians = degrees * Math::PI / 180.0
element_width = element["rect"]["width"]
element_height = element["rect"]["height"]
x_center = element["rect"]["center_x"]
y_center = element["rect"]["center_y"]
radius = ([element_width, element_height].min) * 0.33
to_x = x_center - (radius * Math.cos(radians))
to_y = y_center - (radius * Math.sin(radians))
{:x => to_x, :y => to_y}
end
def self.distance(from, to)
Math.sqrt((from[:x] - to[:x]) ** 2 + (from[:y] - to[:y]) ** 2)
end
end
end
end
end
| epl-1.0 |
Tasktop/code2cloud.server | com.tasktop.c2c.server/com.tasktop.c2c.server.tasks.web.ui/src/main/java/com/tasktop/c2c/server/tasks/client/widgets/chooser/keywords/KeywordCompositeFactory.java | 1376 | /*******************************************************************************
* Copyright (c) 2010, 2012 Tasktop Technologies
* Copyright (c) 2010, 2011 SpringSource, a division of VMware
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
******************************************************************************/
package com.tasktop.c2c.server.tasks.client.widgets.chooser.keywords;
import com.tasktop.c2c.server.common.web.client.widgets.chooser.AbstractValueChooser;
import com.tasktop.c2c.server.common.web.client.widgets.chooser.AbstractValueComposite;
import com.tasktop.c2c.server.common.web.client.widgets.chooser.ValueCompositeFactory;
import com.tasktop.c2c.server.tasks.domain.Keyword;
public class KeywordCompositeFactory extends ValueCompositeFactory<Keyword> {
@Override
public AbstractValueComposite<Keyword> getComposite(AbstractValueChooser<Keyword> valueChooser, Keyword origin) {
KeywordValueComposite valueComposite = new KeywordValueComposite(valueChooser);
valueComposite.setValue(origin);
valueComposite.initWidget();
return valueComposite;
}
}
| epl-1.0 |
kdjones/lse | Source/MeasurementSampler/Model/ECA/PhasorCollection.cs | 146 | namespace MeasurementSampler.Model.ECA
{
public partial class PhasorCollection
{
public Phasor[] Phasors { get; set; }
}
}
| epl-1.0 |
soluvas/tutorial-rabbitmq | src/main/java/org/soluvas/tutorial/rabbitmq/core/ToJson.java | 1260 | package org.soluvas.tutorial.rabbitmq.core;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.google.common.base.Throwables;
import org.apache.camel.Body;
import org.springframework.stereotype.Service;
import java.util.function.Function;
/**
* Created by ceefour on 19/01/15.
*/
@Service
public class ToJson implements Function<Object, String> {
protected ObjectMapper mapper;
public ToJson() {
mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.registerModule(new GuavaModule());
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
@Override
public String apply(@Body Object o) {
try {
return o != null ? mapper.writeValueAsString(o) : null;
} catch (JsonProcessingException e) {
Throwables.propagate(e);
return null;
}
}
public ObjectMapper getMapper() {
return mapper;
}
}
| epl-1.0 |
cbaerikebc/kapua | service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceCreator.java | 10760 | /*******************************************************************************
* Copyright (c) 2011, 2017 Eurotech and/or its affiliates and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech - initial API and implementation
*
*******************************************************************************/
package org.eclipse.kapua.service.device.registry;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.eclipse.kapua.model.KapuaUpdatableEntityCreator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.model.id.KapuaIdAdapter;
import org.eclipse.kapua.service.device.registry.event.DeviceEvent;
/**
* {@link DeviceCreator} encapsulates all the information needed to create a new {@link Device} in the system.<br>
* The data provided will be used to seed the new {@link Device} and its related information.<br>
* The fields of the {@link DeviceCreator} presents the attributes that are searchable for a given device.<br>
* The DeviceCreator Properties field can be used to provide additional properties associated to the Device;
* those properties will not be searchable through Device queries.<br>
* The clientId field of the Device is used to store the MAC address of the primary network interface of the device.
*
* @since 1.0.0
*/
@XmlRootElement(name = "deviceCreator")
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlType(propOrder = {
"groupId",
"clientId",
"status",
"connectionId",
"lastEventId",
"displayName",
"serialNumber",
"modelId",
"imei",
"imsi",
"iccid",
"biosVersion",
"firmwareVersion",
"osVersion",
"jvmVersion",
"osgiFrameworkVersion",
"applicationFrameworkVersion",
"applicationIdentifiers",
"acceptEncoding",
"customAttribute1",
"customAttribute2",
"customAttribute3",
"customAttribute4",
"customAttribute5",
"credentialsMode",
"preferredUserId" //
}, //
factoryClass = DeviceXmlRegistry.class, factoryMethod = "newDeviceCreator")
public interface DeviceCreator extends KapuaUpdatableEntityCreator<Device> {
/**
* Get the group identifier
*
* @return
*/
@XmlElement(name = "groupId")
@XmlJavaTypeAdapter(KapuaIdAdapter.class)
public KapuaId getGroupId();
/**
* Set the group identifier
*
* @param groupId
*/
public void setGroupId(KapuaId groupId);
/**
* Get the client identifier
*
* @return
*/
@XmlElement(name = "clientId")
public String getClientId();
/**
* Set the client identifier
*
* @param clientId
*/
public void setClientId(String clientId);
/**
* Get the device status
*
* @return
*/
@XmlElement
public DeviceStatus getStatus();
/**
* Sets the device status
*
* @param status
*/
public void setStatus(DeviceStatus status);
/**
* Get the connection identifier
*
* @return
*/
@XmlElement(name = "connectionId")
@XmlJavaTypeAdapter(KapuaIdAdapter.class)
public KapuaId getConnectionId();
/**
* Set the connection identifier
*
* @param connectionId
*/
public void setConnectionId(KapuaId connectionId);
/**
* Get the last {@link DeviceEvent} identifier
*
* @return
*/
@XmlElement(name = "lastEventId")
@XmlJavaTypeAdapter(KapuaIdAdapter.class)
public KapuaId getLastEventId();
/**
* Set the last {@link DeviceEvent} identifier.
*
* @param lastEventId
*/
public void setLastEventId(KapuaId lastEventId);
/**
* Get the display name
*
* @return
*/
@XmlElement(name = "displayName")
public String getDisplayName();
/**
* Set the display name
*
* @param displayName
*/
public void setDisplayName(String displayName);
/**
* Get the serial number
*
* @return
*/
@XmlElement(name = "serialNumber")
public String getSerialNumber();
/**
* Set the serial number
*
* @param serialNumber
*/
public void setSerialNumber(String serialNumber);
/**
* Get the model identifier
*
* @return
*/
@XmlElement(name = "modelId")
public String getModelId();
/**
* Set the model identifier
*
* @param modelId
*/
public void setModelId(String modelId);
/**
* Get the imei
*
* @return
*/
@XmlElement(name = "imei")
public String getImei();
/**
* Set the imei
*
* @param imei
*/
public void setImei(String imei);
/**
* Get the imsi
*
* @return
*/
@XmlElement(name = "imsi")
public String getImsi();
/**
* Set the imsi
*
* @param imsi
*/
public void setImsi(String imsi);
/**
* Get the iccid
*
* @return
*/
@XmlElement(name = "iccid")
public String getIccid();
/**
* Set the iccid
*
* @param iccid
*/
public void setIccid(String iccid);
/**
* Get bios version
*
* @return
*/
@XmlElement(name = "biosVersion")
public String getBiosVersion();
/**
* Set bios version
*
* @param biosVersion
*/
public void setBiosVersion(String biosVersion);
/**
* Get firmware version
*
* @return
*/
@XmlElement(name = "firmwareVersion")
public String getFirmwareVersion();
/**
* Set firmware version
*
* @param firmwareVersion
*/
public void setFirmwareVersion(String firmwareVersion);
/**
* Get os version
*
* @return
*/
@XmlElement(name = "osVersion")
public String getOsVersion();
/**
* Set os version
*
* @param osVersion
*/
public void setOsVersion(String osVersion);
/**
* Get jvm version
*
* @return
*/
@XmlElement(name = "jvmVersion")
public String getJvmVersion();
/**
* Set jvm version
*
* @param jvmVersion
*/
public void setJvmVersion(String jvmVersion);
/**
* Get osgi framework version
*
* @return
*/
@XmlElement(name = "osgiFrameworkVersion")
public String getOsgiFrameworkVersion();
/**
* Set osgi framework version
*
* @param osgiFrameworkVersion
*/
public void setOsgiFrameworkVersion(String osgiFrameworkVersion);
/**
* Get application framework version
*
* @return
*/
@XmlElement(name = "applicationFrameworkVersion")
public String getApplicationFrameworkVersion();
/**
* Set application framework version
*
* @param appFrameworkVersion
*/
public void setApplicationFrameworkVersion(String appFrameworkVersion);
/**
* Get application identifiers
*
* @return
*/
@XmlElement(name = "applicationIdentifiers")
public String getApplicationIdentifiers();
/**
* Set application identifiers
*
* @param applicationIdentifiers
*/
public void setApplicationIdentifiers(String applicationIdentifiers);
/**
* Get accept encoding flag
*
* @return
*/
@XmlElement(name = "acceptEncoding")
public String getAcceptEncoding();
/**
* Set accept encoding flag
*
* @param acceptEncoding
*/
public void setAcceptEncoding(String acceptEncoding);
/**
* Get custom attribute 1
*
* @return
*/
@XmlElement(name = "customAttribute1")
public String getCustomAttribute1();
/**
* Set custom attribute 1
*
* @param customAttribute1
*/
public void setCustomAttribute1(String customAttribute1);
/**
* Get custom attribute 2
*
* @return
*/
@XmlElement(name = "customAttribute2")
public String getCustomAttribute2();
/**
* Set custom attribute 2
*
* @param customAttribute2
*/
public void setCustomAttribute2(String customAttribute2);
/**
* Get custom attribute 3
*
* @return
*/
@XmlElement(name = "customAttribute3")
public String getCustomAttribute3();
/**
* Set custom attribute 3
*
* @param customAttribute3
*/
public void setCustomAttribute3(String customAttribute3);
/**
* Get custom attribute 4
*
* @return
*/
@XmlElement(name = "customAttribute4")
public String getCustomAttribute4();
/**
* Set custom attribute 4
*
* @param customAttribute4
*/
public void setCustomAttribute4(String customAttribute4);
/**
* Get custom attribute 5
*
* @return
*/
@XmlElement(name = "customAttribute5")
public String getCustomAttribute5();
/**
* Set custom attribute 5
*
* @param customAttribute5
*/
public void setCustomAttribute5(String customAttribute5);
/**
* Get credentials mode.<br>
* The device credential mode sets a security level for the devices, setting a specific user connection policy between the available policies.
*
* @return
*/
@XmlElement(name = "credentialsMode")
public DeviceCredentialsMode getCredentialsMode();
/**
* Set credentials mode.<br>
* The device credential mode sets a security level for the devices, setting a specific user connection policy between the available policies.
*
* @param credentialsMode
*/
public void setCredentialsMode(DeviceCredentialsMode credentialsMode);
/**
* Get preferred user identifier.<br>
* Set the preferred user identifier that can connect to this device.
*
* @return
*/
@XmlElement(name = "preferredUserId")
@XmlJavaTypeAdapter(KapuaIdAdapter.class)
public KapuaId getPreferredUserId();
/**
* Set preferred user identifier.<br>
* Set the preferred user identifier that can connect to this device.
*
* @param preferredUserId
*/
public void setPreferredUserId(KapuaId preferredUserId);
}
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/handler/SensiboSkyHandler.java | 23692 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.sensibo.internal.handler;
import static org.openhab.binding.sensibo.internal.SensiboBindingConstants.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.measure.IncommensurableException;
import javax.measure.UnconvertibleException;
import javax.measure.Unit;
import javax.measure.UnitConverter;
import javax.measure.quantity.Temperature;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.commons.lang3.text.WordUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.sensibo.internal.CallbackChannelsTypeProvider;
import org.openhab.binding.sensibo.internal.SensiboBindingConstants;
import org.openhab.binding.sensibo.internal.config.SensiboSkyConfiguration;
import org.openhab.binding.sensibo.internal.dto.poddetails.TemperatureDTO;
import org.openhab.binding.sensibo.internal.model.SensiboModel;
import org.openhab.binding.sensibo.internal.model.SensiboSky;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.QuantityType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.library.unit.SIUnits;
import org.openhab.core.library.unit.Units;
import org.openhab.core.thing.Channel;
import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.binding.ThingHandlerService;
import org.openhab.core.thing.binding.builder.ChannelBuilder;
import org.openhab.core.thing.type.ChannelType;
import org.openhab.core.thing.type.ChannelTypeBuilder;
import org.openhab.core.thing.type.ChannelTypeProvider;
import org.openhab.core.thing.type.ChannelTypeUID;
import org.openhab.core.thing.type.StateChannelTypeBuilder;
import org.openhab.core.types.Command;
import org.openhab.core.types.RefreshType;
import org.openhab.core.types.StateDescriptionFragmentBuilder;
import org.openhab.core.types.StateOption;
import org.openhab.core.types.UnDefType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The {@link SensiboSkyHandler} is responsible for handling commands, which are
* sent to one of the channels.
*
* @author Arne Seime - Initial contribution
*/
@NonNullByDefault
public class SensiboSkyHandler extends SensiboBaseThingHandler implements ChannelTypeProvider {
public static final String SWING_PROPERTY = "swing";
public static final String MASTER_SWITCH_PROPERTY = "on";
public static final String FAN_LEVEL_PROPERTY = "fanLevel";
public static final String MODE_PROPERTY = "mode";
public static final String TARGET_TEMPERATURE_PROPERTY = "targetTemperature";
public static final String SWING_MODE_LABEL = "Swing Mode";
public static final String FAN_LEVEL_LABEL = "Fan Level";
public static final String MODE_LABEL = "Mode";
public static final String TARGET_TEMPERATURE_LABEL = "Target Temperature";
private static final String ITEM_TYPE_STRING = "String";
private static final String ITEM_TYPE_NUMBER_TEMPERATURE = "Number:Temperature";
private final Logger logger = LoggerFactory.getLogger(SensiboSkyHandler.class);
private final Map<ChannelTypeUID, ChannelType> generatedChannelTypes = new HashMap<>();
private Optional<SensiboSkyConfiguration> config = Optional.empty();
public SensiboSkyHandler(final Thing thing) {
super(thing);
}
private static String beautify(final String camelCaseWording) {
final StringBuilder b = new StringBuilder();
for (final String s : StringUtils.splitByCharacterTypeCamelCase(camelCaseWording)) {
b.append(" ");
b.append(s);
}
final StringBuilder bs = new StringBuilder();
for (final String t : StringUtils.splitByWholeSeparator(b.toString(), " _")) {
bs.append(" ");
bs.append(t);
}
return WordUtils.capitalizeFully(bs.toString()).trim();
}
private String getMacAddress() {
if (config.isPresent()) {
return config.get().macAddress;
}
throw new IllegalArgumentException("No configuration present");
}
@Override
public void handleCommand(final ChannelUID channelUID, final Command command) {
handleCommand(channelUID, command, getSensiboModel());
}
/*
* Package private in order to be reachable from unit test
*/
void updateAcState(SensiboSky sensiboSky, String property, Object value) {
StateChange stateChange = checkStateChangeValid(sensiboSky, property, value);
if (stateChange.valid) {
getAccountHandler().ifPresent(
handler -> handler.updateSensiboSkyAcState(getMacAddress(), property, stateChange.value, this));
} else {
logger.info("Update command not sent; invalid state change for SensiboSky AC state: {}",
stateChange.validationMessage);
}
}
private void updateTimer(@Nullable Integer secondsFromNowUntilSwitchOff) {
getAccountHandler()
.ifPresent(handler -> handler.updateSensiboSkyTimer(getMacAddress(), secondsFromNowUntilSwitchOff));
}
@Override
protected void handleCommand(final ChannelUID channelUID, final Command command, final SensiboModel model) {
model.findSensiboSkyByMacAddress(getMacAddress()).ifPresent(sensiboSky -> {
if (sensiboSky.isAlive()) {
if (getThing().getStatus() != ThingStatus.ONLINE) {
addDynamicChannelsAndProperties(sensiboSky);
updateStatus(ThingStatus.ONLINE); // In case it has been offline
}
switch (channelUID.getId()) {
case CHANNEL_CURRENT_HUMIDITY:
handleCurrentHumidityCommand(channelUID, command, sensiboSky);
break;
case CHANNEL_CURRENT_TEMPERATURE:
handleCurrentTemperatureCommand(channelUID, command, sensiboSky);
break;
case CHANNEL_MASTER_SWITCH:
handleMasterSwitchCommand(channelUID, command, sensiboSky);
break;
case CHANNEL_TARGET_TEMPERATURE:
handleTargetTemperatureCommand(channelUID, command, sensiboSky);
break;
case CHANNEL_MODE:
handleModeCommand(channelUID, command, sensiboSky);
break;
case CHANNEL_SWING_MODE:
handleSwingCommand(channelUID, command, sensiboSky);
break;
case CHANNEL_FAN_LEVEL:
handleFanLevelCommand(channelUID, command, sensiboSky);
break;
case CHANNEL_TIMER:
handleTimerCommand(channelUID, command, sensiboSky);
break;
default:
logger.debug("Received command on unknown channel {}, ignoring", channelUID.getId());
}
} else {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"Unreachable by Sensibo servers");
}
});
}
private void handleTimerCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
if (command instanceof RefreshType) {
if (sensiboSky.getTimer().isPresent() && sensiboSky.getTimer().get().secondsRemaining > 0) {
updateState(channelUID, new DecimalType(sensiboSky.getTimer().get().secondsRemaining));
} else {
updateState(channelUID, UnDefType.UNDEF);
}
} else if (command instanceof DecimalType) {
final DecimalType newValue = (DecimalType) command;
updateTimer(newValue.intValue());
} else {
updateTimer(null);
}
}
private void handleFanLevelCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
if (command instanceof RefreshType) {
if (sensiboSky.getAcState().isPresent() && sensiboSky.getAcState().get().getFanLevel() != null) {
updateState(channelUID, new StringType(sensiboSky.getAcState().get().getFanLevel()));
} else {
updateState(channelUID, UnDefType.UNDEF);
}
} else if (command instanceof StringType) {
final StringType newValue = (StringType) command;
updateAcState(sensiboSky, FAN_LEVEL_PROPERTY, newValue.toString());
}
}
private void handleSwingCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
if (command instanceof RefreshType && sensiboSky.getAcState().isPresent()) {
if (sensiboSky.getAcState().isPresent() && sensiboSky.getAcState().get().getSwing() != null) {
updateState(channelUID, new StringType(sensiboSky.getAcState().get().getSwing()));
} else {
updateState(channelUID, UnDefType.UNDEF);
}
} else if (command instanceof StringType) {
final StringType newValue = (StringType) command;
updateAcState(sensiboSky, SWING_PROPERTY, newValue.toString());
}
}
private void handleModeCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
if (command instanceof RefreshType) {
if (sensiboSky.getAcState().isPresent()) {
updateState(channelUID, new StringType(sensiboSky.getAcState().get().getMode()));
} else {
updateState(channelUID, UnDefType.UNDEF);
}
} else if (command instanceof StringType) {
final StringType newValue = (StringType) command;
updateAcState(sensiboSky, MODE_PROPERTY, newValue.toString());
addDynamicChannelsAndProperties(sensiboSky);
}
}
private void handleTargetTemperatureCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
if (command instanceof RefreshType) {
sensiboSky.getAcState().ifPresent(acState -> {
@Nullable
Integer targetTemperature = acState.getTargetTemperature();
if (targetTemperature != null) {
updateState(channelUID, new QuantityType<>(targetTemperature, sensiboSky.getTemperatureUnit()));
} else {
updateState(channelUID, UnDefType.UNDEF);
}
});
if (!sensiboSky.getAcState().isPresent()) {
updateState(channelUID, UnDefType.UNDEF);
}
} else if (command instanceof QuantityType<?>) {
QuantityType<?> newValue = (QuantityType<?>) command;
if (!Objects.equals(sensiboSky.getTemperatureUnit(), newValue.getUnit())) {
// If quantity is given in celsius when fahrenheit is used or opposite
try {
UnitConverter temperatureConverter = newValue.getUnit()
.getConverterToAny(sensiboSky.getTemperatureUnit());
// No decimals supported
long convertedValue = (long) temperatureConverter.convert(newValue.longValue());
updateAcState(sensiboSky, TARGET_TEMPERATURE_PROPERTY, new DecimalType(convertedValue));
} catch (UnconvertibleException | IncommensurableException e) {
logger.info("Could not convert {} to {}: {}", newValue, sensiboSky.getTemperatureUnit(),
e.getMessage());
}
} else {
updateAcState(sensiboSky, TARGET_TEMPERATURE_PROPERTY, new DecimalType(newValue.intValue()));
}
} else if (command instanceof DecimalType) {
updateAcState(sensiboSky, TARGET_TEMPERATURE_PROPERTY, command);
}
}
private void handleMasterSwitchCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
if (command instanceof RefreshType) {
sensiboSky.getAcState().ifPresent(e -> updateState(channelUID, OnOffType.from(e.isOn())));
} else if (command instanceof OnOffType) {
updateAcState(sensiboSky, MASTER_SWITCH_PROPERTY, command == OnOffType.ON);
}
}
private void handleCurrentTemperatureCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
if (command instanceof RefreshType) {
updateState(channelUID, new QuantityType<>(sensiboSky.getTemperature(), SIUnits.CELSIUS));
}
}
private void handleCurrentHumidityCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
if (command instanceof RefreshType) {
updateState(channelUID, new QuantityType<>(sensiboSky.getHumidity(), Units.PERCENT));
}
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(CallbackChannelsTypeProvider.class);
}
@Override
public void initialize() {
config = Optional.ofNullable(getConfigAs(SensiboSkyConfiguration.class));
logger.debug("Initializing SensiboSky using config {}", config);
getSensiboModel().findSensiboSkyByMacAddress(getMacAddress()).ifPresent(pod -> {
if (pod.isAlive()) {
addDynamicChannelsAndProperties(pod);
updateStatus(ThingStatus.ONLINE);
} else {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"Unreachable by Sensibo servers");
}
});
}
private boolean isDynamicChannel(final ChannelTypeUID uid) {
return SensiboBindingConstants.DYNAMIC_CHANNEL_TYPES.stream().anyMatch(e -> uid.getId().startsWith(e));
}
private void addDynamicChannelsAndProperties(final SensiboSky sensiboSky) {
logger.debug("Updating dynamic channels for {}", sensiboSky.getId());
final List<Channel> newChannels = new ArrayList<>();
for (final Channel channel : getThing().getChannels()) {
final ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
if (channelTypeUID != null && !isDynamicChannel(channelTypeUID)) {
newChannels.add(channel);
}
}
newChannels.addAll(createDynamicChannels(sensiboSky));
Map<String, String> properties = sensiboSky.getThingProperties();
updateThing(editThing().withChannels(newChannels).withProperties(properties).build());
}
public List<Channel> createDynamicChannels(final SensiboSky sensiboSky) {
final List<Channel> newChannels = new ArrayList<>();
generatedChannelTypes.clear();
sensiboSky.getCurrentModeCapabilities().ifPresent(capabilities -> {
// Not all modes have swing and fan level
final ChannelTypeUID swingModeChannelType = addChannelType(SensiboBindingConstants.CHANNEL_TYPE_SWING_MODE,
SWING_MODE_LABEL, ITEM_TYPE_STRING, capabilities.swingModes, null, null);
newChannels
.add(ChannelBuilder
.create(new ChannelUID(getThing().getUID(), SensiboBindingConstants.CHANNEL_SWING_MODE),
ITEM_TYPE_STRING)
.withLabel(SWING_MODE_LABEL).withType(swingModeChannelType).build());
final ChannelTypeUID fanLevelChannelType = addChannelType(SensiboBindingConstants.CHANNEL_TYPE_FAN_LEVEL,
FAN_LEVEL_LABEL, ITEM_TYPE_STRING, capabilities.fanLevels, null, null);
newChannels.add(ChannelBuilder
.create(new ChannelUID(getThing().getUID(), SensiboBindingConstants.CHANNEL_FAN_LEVEL),
ITEM_TYPE_STRING)
.withLabel(FAN_LEVEL_LABEL).withType(fanLevelChannelType).build());
});
final ChannelTypeUID modeChannelType = addChannelType(SensiboBindingConstants.CHANNEL_TYPE_MODE, MODE_LABEL,
ITEM_TYPE_STRING, sensiboSky.getRemoteCapabilities().keySet(), null, null);
newChannels.add(ChannelBuilder
.create(new ChannelUID(getThing().getUID(), SensiboBindingConstants.CHANNEL_MODE), ITEM_TYPE_STRING)
.withLabel(MODE_LABEL).withType(modeChannelType).build());
final ChannelTypeUID targetTemperatureChannelType = addChannelType(
SensiboBindingConstants.CHANNEL_TYPE_TARGET_TEMPERATURE, TARGET_TEMPERATURE_LABEL,
ITEM_TYPE_NUMBER_TEMPERATURE, sensiboSky.getTargetTemperatures(), "%d %unit%", "TargetTemperature");
newChannels.add(ChannelBuilder
.create(new ChannelUID(getThing().getUID(), SensiboBindingConstants.CHANNEL_TARGET_TEMPERATURE),
ITEM_TYPE_NUMBER_TEMPERATURE)
.withLabel(TARGET_TEMPERATURE_LABEL).withType(targetTemperatureChannelType).build());
return newChannels;
}
private ChannelTypeUID addChannelType(final String channelTypePrefix, final String label, final String itemType,
final Collection<?> options, @Nullable final String pattern, @Nullable final String tag) {
final ChannelTypeUID channelTypeUID = new ChannelTypeUID(SensiboBindingConstants.BINDING_ID,
channelTypePrefix + getThing().getUID().getId());
final List<StateOption> stateOptions = options.stream()
.map(e -> new StateOption(e.toString(), e instanceof String ? beautify((String) e) : e.toString()))
.collect(Collectors.toList());
StateDescriptionFragmentBuilder stateDescription = StateDescriptionFragmentBuilder.create().withReadOnly(false)
.withOptions(stateOptions);
if (pattern != null) {
stateDescription = stateDescription.withPattern(pattern);
}
final StateChannelTypeBuilder builder = ChannelTypeBuilder.state(channelTypeUID, label, itemType)
.withStateDescriptionFragment(stateDescription.build());
if (tag != null) {
builder.withTag(tag);
}
final ChannelType channelType = builder.build();
generatedChannelTypes.put(channelTypeUID, channelType);
return channelTypeUID;
}
@Override
public Collection<ChannelType> getChannelTypes(@Nullable final Locale locale) {
return generatedChannelTypes.values();
}
@Override
public @Nullable ChannelType getChannelType(final ChannelTypeUID channelTypeUID, @Nullable final Locale locale) {
return generatedChannelTypes.get(channelTypeUID);
}
/*
* Package private in order to be reachable from unit test
*/
StateChange checkStateChangeValid(SensiboSky sensiboSky, String property, Object newPropertyValue) {
StateChange stateChange = new StateChange(newPropertyValue);
sensiboSky.getCurrentModeCapabilities().ifPresent(currentModeCapabilities -> {
switch (property) {
case TARGET_TEMPERATURE_PROPERTY:
Unit<Temperature> temperatureUnit = sensiboSky.getTemperatureUnit();
TemperatureDTO validTemperatures = currentModeCapabilities.temperatures
.get(temperatureUnit == SIUnits.CELSIUS ? "C" : "F");
DecimalType rawValue = (DecimalType) newPropertyValue;
stateChange.updateValue(rawValue.intValue());
if (!validTemperatures.validValues.contains(rawValue.intValue())) {
stateChange.addError(String.format(
"Cannot change targetTemperature to '%d', valid targetTemperatures are one of %s",
rawValue.intValue(), ToStringBuilder.reflectionToString(
validTemperatures.validValues.toArray(), ToStringStyle.SIMPLE_STYLE)));
}
break;
case MODE_PROPERTY:
if (!sensiboSky.getRemoteCapabilities().containsKey(newPropertyValue)) {
stateChange.addError(
String.format("Cannot change mode to %s, valid modes are %s", newPropertyValue,
ToStringBuilder.reflectionToString(
sensiboSky.getRemoteCapabilities().keySet().toArray(),
ToStringStyle.SIMPLE_STYLE)));
}
break;
case FAN_LEVEL_PROPERTY:
if (!currentModeCapabilities.fanLevels.contains(newPropertyValue)) {
stateChange.addError(String.format("Cannot change fanLevel to %s, valid fanLevels are %s",
newPropertyValue, ToStringBuilder.reflectionToString(
currentModeCapabilities.fanLevels.toArray(), ToStringStyle.SIMPLE_STYLE)));
}
break;
case MASTER_SWITCH_PROPERTY:
// Always allowed
break;
case SWING_PROPERTY:
if (!currentModeCapabilities.swingModes.contains(newPropertyValue)) {
stateChange.addError(String.format("Cannot change swing to %s, valid swings are %s",
newPropertyValue, ToStringBuilder.reflectionToString(
currentModeCapabilities.swingModes.toArray(), ToStringStyle.SIMPLE_STYLE)));
}
break;
default:
stateChange.addError(String.format("No such ac state property %s", property));
}
logger.debug("State change request {}", stateChange);
});
return stateChange;
}
@NonNullByDefault
public class StateChange {
Object value;
boolean valid = true;
@Nullable
String validationMessage;
public StateChange(Object value) {
this.value = value;
}
public void updateValue(Object updatedValue) {
value = updatedValue;
}
public void addError(String validationMessage) {
valid = false;
this.validationMessage = validationMessage;
}
@Override
public String toString() {
return "StateChange [valid=" + valid + ", validationMessage=" + validationMessage + ", value=" + value
+ ", value Class=" + value.getClass() + "]";
}
}
}
| epl-1.0 |
jonlyles/QuickApps | app/Cake/Cache/Engine/FileEngine.php | 7616 | <?php
/**
* File Storage engine for cache. Filestorage is the slowest cache storage
* to read and write. However, it is good for servers that don't have other storage
* engine available, or have content which is not performance sensitive.
*
* You can configure a FileEngine cache, using Cache::config()
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2.0.4933
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* File Storage engine for cache
*
* @package Cake.Cache.Engine
*/
class FileEngine extends CacheEngine {
/**
* Instance of SplFileObject class
*
* @var _File
* @access protected
*/
protected $_File = null;
/**
* Settings
*
* - path = absolute path to cache directory, default => CACHE
* - prefix = string prefix for filename, default => cake_
* - lock = enable file locking on write, default => false
* - serialize = serialize the data, default => true
*
* @var array
* @see CacheEngine::__defaults
* @access public
*/
public $settings = array();
/**
* True unless FileEngine::__active(); fails
*
* @var boolean
* @access protected
*/
protected $_init = true;
/**
* Initialize the Cache Engine
*
* Called automatically by the cache frontend
* To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
*
* @param array $settings array of setting for the engine
* @return boolean True if the engine has been successfully initialized, false if not
*/
public function init($settings = array()) {
parent::init(array_merge(
array(
'engine' => 'File', 'path' => CACHE, 'prefix'=> 'cake_', 'lock'=> false,
'serialize'=> true, 'isWindows' => false
),
$settings
));
if (DS === '\\') {
$this->settings['isWindows'] = true;
}
if (substr($this->settings['path'], -1) !== DS) {
$this->settings['path'] .= DS;
}
return $this->_active();
}
/**
* Garbage collection. Permanently remove all expired and deleted data
*
* @return boolean True if garbage collection was succesful, false on failure
*/
public function gc() {
return $this->clear(true);
}
/**
* Write data for key into cache
*
* @param string $key Identifier for the data
* @param mixed $data Data to be cached
* @param mixed $duration How long to cache the data, in seconds
* @return boolean True if the data was successfully cached, false on failure
*/
public function write($key, $data, $duration) {
if ($data === '' || !$this->_init) {
return false;
}
if ($this->_setKey($key, true) === false) {
return false;
}
$lineBreak = "\n";
if ($this->settings['isWindows']) {
$lineBreak = "\r\n";
}
if (!empty($this->settings['serialize'])) {
if ($this->settings['isWindows']) {
$data = str_replace('\\', '\\\\\\\\', serialize($data));
} else {
$data = serialize($data);
}
}
$expires = time() + $duration;
$contents = $expires . $lineBreak . $data . $lineBreak;
if (!$handle = fopen($this->_File->getPathName(), 'c')) {
return false;
}
if ($this->settings['lock']) {
flock($handle, LOCK_EX);
}
$success = ftruncate($handle, 0) && fwrite($handle, $contents) && fflush($handle);
if ($this->settings['lock']) {
flock($handle, LOCK_UN);
}
fclose($handle);
return $success;
}
/**
* Read a key from the cache
*
* @param string $key Identifier for the data
* @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
*/
public function read($key) {
if (!$this->_init || $this->_setKey($key) === false) {
return false;
}
if ($this->settings['lock']) {
$this->_File->flock(LOCK_SH);
}
$this->_File->rewind();
$time = time();
$cachetime = intval($this->_File->current());
if ($cachetime !== false && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) {
return false;
}
$data = '';
$this->_File->next();
while ($this->_File->valid()) {
$data .= $this->_File->current();
$this->_File->next();
}
if ($this->settings['lock']) {
$this->_File->flock(LOCK_UN);
}
$data = trim($data);
if ($data !== '' && !empty($this->settings['serialize'])) {
if ($this->settings['isWindows']) {
$data = str_replace('\\\\\\\\', '\\', $data);
}
$data = unserialize((string)$data);
}
return $data;
}
/**
* Delete a key from the cache
*
* @param string $key Identifier for the data
* @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
*/
public function delete($key) {
if ($this->_setKey($key) === false || !$this->_init) {
return false;
}
$path = $this->_File->getRealPath();
$this->_File = null;
return unlink($path);
}
/**
* Delete all values from the cache
*
* @param boolean $check Optional - only delete expired cache items
* @return boolean True if the cache was successfully cleared, false otherwise
*/
public function clear($check) {
if (!$this->_init) {
return false;
}
$dir = dir($this->settings['path']);
if ($check) {
$now = time();
$threshold = $now - $this->settings['duration'];
}
$prefixLength = strlen($this->settings['prefix']);
while (($entry = $dir->read()) !== false) {
if (substr($entry, 0, $prefixLength) !== $this->settings['prefix']) {
continue;
}
if ($this->_setKey($entry) === false) {
continue;
}
if ($check) {
$mtime = $this->_File->getMTime();
if ($mtime > $threshold) {
continue;
}
$expires = (int)$this->_File->current();
if ($expires > $now) {
continue;
}
}
$path = $this->_File->getRealPath();
$this->_File = null;
unlink($path);
}
$dir->close();
return true;
}
/**
* Not implemented
*
* @return void
* @throws CacheException
*/
public function decrement($key, $offset = 1) {
throw new CacheException(__d('cake_dev', 'Files cannot be atomically decremented.'));
}
/**
* Not implemented
*
* @return void
* @throws CacheException
*/
public function increment($key, $offset = 1) {
throw new CacheException(__d('cake_dev', 'Files cannot be atomically incremented.'));
}
/**
* Sets the current cache key this class is managing
*
* @param string $key The key
* @param boolean $createKey Whether the key should be created if it doesn't exists, or not
* @return boolean true if the cache key could be set, false otherwise
* @access protected
*/
protected function _setKey($key, $createKey = false) {
$path = new SplFileInfo($this->settings['path'] . $key);
if (!$createKey && !$path->isFile()) {
return false;
}
$old = umask(0);
if (empty($this->_File) || $this->_File->getBaseName() !== $key) {
$this->_File = $path->openFile('a+');
}
umask($old);
return true;
}
/**
* Determine is cache directory is writable
*
* @return boolean
* @access protected
*/
protected function _active() {
$dir = new SplFileInfo($this->settings['path']);
if ($this->_init && !($dir->isDir() && $dir->isWritable())) {
$this->_init = false;
trigger_error(__d('cake_dev', '%s is not writable', $this->settings['path']), E_USER_WARNING);
return false;
}
return true;
}
}
| gpl-2.0 |
blisskid/xuanqi | wp-content/themes/dt-the7/inc/helpers/header-helpers.php | 15077 | <?php
if ( ! function_exists( 'presscore_header_style' ) ) :
/**
* Output header inline css
*
* @uses Presscore_Config Global config storage
* @uses dt_stylesheet_color_hex2rgba
*
* @since 1.0.0
*/
function presscore_header_style() {
$config = Presscore_Config::get_instance();
$style = array();
if ( in_array( $config->get( 'page_title.background.mode' ), array( 'background', 'gradient' ) ) || in_array( $config->get( 'header_title' ), array( 'fancy', 'slideshow' ) ) ) {
if ( 'transparent' == $config->get( 'header_background' ) ) {
$transparent_bg_color = dt_stylesheet_color_hex2rgba( $config->get( 'header.transparent.background.color' ), $config->get( 'header.transparent.background.opacity' ) );
switch( $config->get( 'header.transparent.background.style' ) ) {
case 'full_width_line':
$style[] = 'border-bottom-color: ' . $transparent_bg_color;
break;
case 'solid_background':
$style[] = 'background-color: ' . $transparent_bg_color;
break;
}
}
}
echo $style ? ' style="' . esc_attr( implode( '; ', $style ) ) . '"' : '';
}
endif;
if ( ! function_exists( 'presscore_header_class' ) ) :
/**
* Display the classes for the header.
*
* @since 1.0.0
*
* @param string|array $class One or more classes to add to the class list.
*/
function presscore_header_class( $class = '' ) {
echo 'class="' . esc_attr( implode( ' ', presscore_get_header_class( $class ) ) ) . '"';
}
endif; // presscore_header_class
if ( ! function_exists( 'presscore_get_header_class' ) ) :
/**
* Retrieve the classes for the top bar as an array.
*
* @since 1.0.0
*
* @param string|array $class One or more classes to add to the class list.
* @return array Array of classes
*/
function presscore_get_header_class( $class = '' ) {
$config = Presscore_Config::get_instance();
$classes = array();
$header_layout = $config->get( 'header.layout' );
switch ( $header_layout ) {
case 'left':
if ( $config->get( 'header.layout.left.fullwidth' ) ) {
$classes[] = 'menu-centered';
}
break;
case 'center':
if ( $menu_bg_mode_class = presscore_get_menu_bg_mode_class( $config->get( 'header.layout.center.menu.background.mode' ) ) ) {
$classes[] = $menu_bg_mode_class;
}
break;
case 'classic':
if ( $menu_bg_mode_class = presscore_get_menu_bg_mode_class( $config->get( 'header.layout.classic.menu.background.mode' ) ) ) {
$classes[] = $menu_bg_mode_class;
}
break;
case 'side':
if ( 'down' == $config->get( 'header.layout.side.menu.dropdown.style' ) ) {
$classes[] = 'sub-downwards';
}
break;
}
// mobile logo
if ( 'mobile' == $config->get( 'header.mobile.logo.first_switch' ) ) {
$classes[] = 'show-device-logo';
}
if ( 'mobile' == $config->get( 'header.mobile.logo.second_switch' ) ) {
$classes[] = 'show-mobile-logo';
}
// transparent header
$header_title_mode = $config->get( 'header_title' );
$is_side_header_layout = ( 'side' == $header_layout );
$is_transparent_header = ( 'transparent' == $config->get( 'header_background' ) );
$is_transparent_fancy_header = in_array( $header_title_mode, array( 'slideshow', 'fancy' ) ) && $is_transparent_header;
$is_transparent_page_title =
'enabled' == $header_title_mode
&& 'background' == $config->get( 'page_title.background.mode' )
&& $is_transparent_header;
if ( ! $is_side_header_layout && ( $is_transparent_fancy_header || $is_transparent_page_title ) ) {
$transparent_header_color_modes_html_classes = array(
'menu_text' => array( 'light' => 'light-menu', 'dark' => 'dark-menu' ),
'menu_decoration' => array( 'light' => 'light-menu-decoration', 'dark' => 'dark-menu-decoration' ),
'top_bar' => array( 'light' => 'light-top-bar', 'dark' => 'dark-top-bar' )
);
$transparent_header_color_modes = array(
'menu_text' => $config->get( 'header.transparent.menu_text.color.mode' ),
'menu_decoration' => $config->get( 'header.transparent.menu_decoration.color.mode' ),
'top_bar' => $config->get( 'header.transparent.top_bar.color.mode' )
);
foreach ( $transparent_header_color_modes as $place=>$mode ) {
if ( isset( $transparent_header_color_modes_html_classes[ $place ][ $mode ] ) ) {
$classes[] = $transparent_header_color_modes_html_classes[ $place ][ $mode ];
}
}
switch ( $config->get( 'header.transparent.background.style' ) ) {
case 'content_width_line':
$classes[] = 'content-width-line';
break;
case 'full_width_line':
$classes[] = 'full-width-line';
break;
}
}
if ( $config->get( 'header.menu.submenu.parent_clickable' ) ) {
$classes[] = 'dt-parent-menu-clickable';
}
switch ( $config->get( 'header.decoration' ) ) {
case 'shadow':
$classes[] = 'shadow-decoration';
break;
case 'line':
$classes[] = 'line-decoration';
break;
}
if ( ! empty( $class ) ) {
if ( !is_array( $class ) ) {
$class = preg_split( '#\s+#', $class );
}
$classes = array_merge( $classes, $class );
} else {
// Ensure that we always coerce class to being an array.
$class = array();
}
return apply_filters( 'presscore_header_classes', $classes, $class );
}
endif; // presscore_get_header_class
if ( ! function_exists( 'presscore_header_table_style' ) ) :
function presscore_header_table_style() {
$config = Presscore_Config::get_instance();
$style = array();
if ( 'transparent' == $config->get( 'header_background' ) && 'content_width_line' == $config->get( 'header.transparent.background.style' ) ) {
$style[] = 'border-bottom-color: ' . dt_stylesheet_color_hex2rgba( $config->get( 'header.transparent.background.color' ), $config->get( 'header.transparent.background.opacity' ) );
}
echo $style ? ' style="' . esc_attr( implode( '; ', $style ) ) . '"' : '';
}
endif;
if ( ! function_exists( 'presscore_get_header_elements_list' ) ) :
/**
* Get header elements list based on current header layout and $field_name.
*
* @param string $field_name Field name
*
* @return array Elements list like array( 'element1', 'element2', ... )
*/
function presscore_get_header_elements_list( $field_name ) {
switch ( of_get_option( 'header-layout', 'left' ) ) {
case 'side' :
$fields_visibility_option_id = 'header-side_layout_elements_visibility';
$fields_option_id = 'header-side_layout_elements';
break;
case 'center' :
$fields_visibility_option_id = 'header-center_layout_elements_visibility';
$fields_option_id = 'header-center_layout_elements';
break;
case 'classic' :
$fields_visibility_option_id = 'header-classic_layout_elements_visibility';
$fields_option_id = 'header-classic_layout_elements';
break;
default : // left
$fields_visibility_option_id = 'header-left_layout_elements_visibility';
$fields_option_id = 'header-left_layout_elements';
}
if ( 'show' == of_get_option( $fields_visibility_option_id, 'show' ) ) {
$fields = of_get_option( $fields_option_id, array() );
if ( array_key_exists($field_name, $fields) && is_array( $fields[ $field_name ] ) && !empty( $fields[ $field_name ] ) ) {
return $fields[ $field_name ];
}
}
return array();
}
endif; // presscore_get_header_elements_list
if ( ! function_exists( 'presscore_render_header_elements' ) ) :
/**
* Renders header elements for $field_name header field.
*
* @param string $field_name Field name
*/
function presscore_render_header_elements( $field_name, $class = 'wf-td' ) {
$field_elements = presscore_get_header_elements_list( $field_name );
if ( $field_elements ) {
// render wrap open tags
switch ( $field_name ) {
case 'top_bar_right':
$wrap_class = 'right-block';
break;
case 'nav_area':
$wrap_class = 'right-block text-near-menu';
break;
case 'logo_area':
$wrap_class = 'right-block text-near-logo ' . presscore_get_font_size_class( of_get_option('header-near_logo_font_size', 'small') );
break;
default:
$wrap_class = '';
}
$wrap_class .= " {$class}";
echo '<div class="' . esc_attr( $wrap_class ) . '">';
// render elements
foreach ( $field_elements as $element ) {
switch ( $element ) {
case 'search':
dt_get_template_part( 'header/searchform' );
break;
case 'social_icons':
$topbar_soc_icons = presscore_get_topbar_social_icons();
if ( $topbar_soc_icons ) {
echo $topbar_soc_icons;
}
break;
case 'cart':
if ( class_exists( 'Woocommerce' ) ) {
dt_woocommerce_mini_cart();
}
break;
case 'custom_menu':
presscore_nav_menu_list('top');
break;
case 'login':
pressocore_render_login_form();
break;
case 'text_area':
$top_text = of_get_option('header-text', '');
if ( $top_text ) {
echo '<div class="text-area">' . wpautop($top_text) . '</div>';
}
break;
case 'skype':
presscore_top_bar_contact_element('skype');
break;
case 'email':
presscore_top_bar_contact_element('email');
break;
case 'address':
presscore_top_bar_contact_element('address');
break;
case 'phone':
presscore_top_bar_contact_element('phone');
break;
case 'working_hours':
presscore_top_bar_contact_element('clock');
break;
case 'info':
presscore_top_bar_contact_element('info');
break;
}
do_action( "presscore_render_header_element-{$element}" );
}
// render wrap close tags
echo '</div>';
}
return '';
}
endif; //presscore_render_header_elements
if ( ! function_exists( 'presscore_get_topbar_bg_mode_class' ) ) :
/**
* Return proper class accordingly to $topbar_bg_mode.
*
* @uses presscore_get_menu_bg_mode_class
*
* @param string $topbar_bg_mode Font size f.e. solid
*
* @return string Class
*/
function presscore_get_topbar_bg_mode_class( $topbar_bg_mode = '' ) {
return presscore_get_menu_bg_mode_class( $topbar_bg_mode );
}
endif; // presscore_get_topbar_bg_mode_class
if ( ! function_exists( 'presscore_top_bar_class' ) ) :
/**
* Display the classes for the top bar.
*
* @since 1.0.0
*
* @param string|array $class One or more classes to add to the class list.
*/
function presscore_top_bar_class( $class = '' ) {
echo 'class="' . implode( ' ', presscore_get_top_bar_class( $class ) ) . '"';
}
endif; // presscore_top_bar_class
if ( ! function_exists( 'presscore_get_top_bar_class()' ) ) :
/**
* Retrieve the classes for the top bar as an array.
*
* @since 1.0.0
*
* @param string|array $class One or more classes to add to the class list.
* @return array Array of classes
*/
function presscore_get_top_bar_class( $class = '' ) {
$classes = array();
$classes[] = presscore_get_font_size_class( of_get_option('top_bar-font_size') );
if ( $topbar_bg_mode_class = presscore_get_topbar_bg_mode_class( of_get_option('top_bar-bg_mode') ) ) {
$classes[] = $topbar_bg_mode_class;
}
$config = presscore_get_config();
switch ( $config->get( 'header.top_bar.mobile.position' ) ) {
case 'closed':
$classes[] = 'top-bar-hide';
break;
case 'opened':
$classes[] = 'top-bar-opened';
break;
case 'disabled':
$classes[] = 'top-bar-disabled';
break;
}
if ( ! empty( $class ) ) {
if ( !is_array( $class ) ) {
$class = preg_split( '#\s+#', $class );
}
$classes = array_merge( $classes, $class );
} else {
// Ensure that we always coerce class to being an array.
$class = array();
}
$classes = array_map( 'esc_attr', $classes );
return apply_filters( 'presscore_top_bar_class', $classes, $class );
}
endif; // presscore_get_top_bar_class
if ( ! function_exists( 'presscore_top_bar_contact_element' ) ) :
/**
* Get contact information element.
*
* @since 1.0.0
*/
function presscore_top_bar_contact_element( $element ){
$white_list = array(
'address',
'phone',
'email',
'skype',
'clock'
);
if ( in_array($element, $white_list) ) {
$contact_content = of_get_option( 'header-contact_' . $element );
if ( $contact_content ) {
$class = $element;
if ( !of_get_option( 'header-contact_' . $element . '_icon', true ) ) {
$class .= ' icon-off';
}
echo '<span class="mini-contacts ' . esc_attr( $class ) . '">' . $contact_content . '</span>';
}
}
}
endif; // presscore_top_bar_contact_element
if ( ! function_exists( 'presscore_get_topbar_social_icons' ) ) :
/**
* Display topbar social icons. Data grabbed from theme options.
*
*/
function presscore_get_topbar_social_icons() {
$icons_data = presscore_get_social_icons_data();
$icons_white_list = array_keys($icons_data);
$saved_icons = of_get_option('header-soc_icons');
$clean_icons = array();
if ( !is_array($saved_icons) || empty($saved_icons) ) {
return '';
}
foreach ( $saved_icons as $saved_icon ) {
if ( !is_array($saved_icon) ) {
continue;
}
if ( empty($saved_icon['url']) || empty($saved_icon['icon']) || !in_array( $saved_icon['icon'], $icons_white_list ) ) {
continue;
}
$icon = $saved_icon['icon'];
$clean_icons[] = array(
'icon' => $icon,
'title' => $icons_data[ $icon ],
'link' => $saved_icon['url']
);
}
$output = '';
if ( $clean_icons ) {
$class = '';
switch ( of_get_option( 'header-soc_icon_bg_color_mode' ) ) {
case 'gradient':
$class .= ' gradient-bg';
break;
case 'outline':
$class .= ' outline-style';
break;
case 'accent':
$class .= ' accent-bg';
break;
case 'color':
$class .= ' custom-bg';
break;
case 'disabled':
$class .= ' disabled-bg';
break;
}
switch ( of_get_option( 'header-soc_icon_hover_bg_color_mode' ) ) {
case 'gradient':
$class .= ' hover-gradient-bg';
break;
case 'outline':
$class .= ' outline-style-hover';
break;
case 'accent':
$class .= ' hover-accent-bg';
break;
case 'color':
$class .= ' hover-custom-bg';
break;
case 'disabled':
$class .= ' hover-disabled-bg';
break;
}
$output .= '<div class="soc-ico' . $class . '">';
$output .= presscore_get_social_icons( $clean_icons );
$output .= '</div>';
}
return $output;
}
endif; // presscore_get_topbar_social_icons
| gpl-2.0 |
emundus/v6 | administrator/components/com_falang/models/TranslationFilter.php | 57365 | <?php
/**
* @package Falang for Joomla!
* @author Stéphane Bouey <stephane.bouey@faboba.com> - http://www.faboba.com
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* @copyright Copyright (C) 2010-2017. Faboba.com All rights reserved.
*/
// No direct access to this file
defined('_JEXEC') or die;
function getTranslationFilters($catid, $contentElement)
{
if (!$contentElement) return array();
$filterNames=$contentElement->getAllFilters();
//reset keyword filter is add with keyword search since joomla 3.0
if (FALANG_J30) {} else {
if (count($filterNames)>0) {
$filterNames["reset"]="reset";
}
}
$filters=array();
foreach ($filterNames as $key=>$value){
$filterType = "translation".ucfirst(strtolower($key))."Filter" ;
$classFile = JPATH_SITE."/administrator/components/com_falang/contentelements/$filterType.php" ;
if (!class_exists($filterType)){
if (file_exists($classFile )) include_once($classFile);
if (!class_exists($filterType)) {
continue;
}
}
$filters[strtolower($key)] = new $filterType($contentElement);
}
return $filters;
}
class translationFilter
{
var $filterNullValue;
var $filterType;
var $filter_value;
var $filterField = false;
var $tableName = "";
var $filterHTML="";
// Should we use session data to remember previous selections?
var $rememberValues = true;
public function __construct($contentElement=null){
if (intval(JRequest::getVar('filter_reset',0))){
$this->filter_value = $this->filterNullValue;
}
else if ($this->rememberValues){
// TODO consider making the filter variable name content type specific
$app = JFactory::getApplication();
// $this->filter_value = $app->getUserStateFromRequest($this->filterType.'_filter_value',$this->filterType.'.filter',$this->filterNullValue);
$this->filter_value = $app->getUserStateFromRequest($this->filterType.'_filter_value', $this->filterType.'_filter_value', $this->filterNullValue);
}
else {
$this->filter_value = JRequest::getVar( $this->filterType.'_filter_value', $this->filterNullValue );
}
//echo $this->filterType.'_filter_value = '.$this->filter_value."<br/>";
$this->tableName = isset($contentElement)?$contentElement->getTableName():"";
}
function _createFilter(){
if (!$this->filterField ) return "";
$filter="";
//since joomla 3.0 filter_value can be '' too not only filterNullValue
if (isset($this->filter_value) && strlen($this->filter_value) > 0 && $this->filter_value!=$this->filterNullValue){
if (is_int($this->filter_value)) {
$filter = "c.".$this->filterField."=$this->filter_value";
} else {
$filter = "c.".$this->filterField."='".$this->filter_value."'";
}
}
return $filter;
}
function _createfilterHTML(){ return "";}
}
class translationResetFilter extends translationFilter
{
public function __construct($contentElement){
$this->filterNullValue=-1;
$this->filterType="reset";
$this->filterField = "";
parent::__construct($contentElement);
}
function _createFilter(){
return "";
}
/**
* Creates javascript session memory reset action
*
*/
function _createfilterHTML(){
$reset["title"]= JText::_('COM_FALANG_FILTER_RESET');
if (FALANG_J30) {
$reset['position'] = 'sidebar';
$reset["html"] = '<input type=\'hidden\' name=\'filter_reset\' id=\'filter_reset\' value=\'0\' /><button class="btn hasTooltip" onclick="document.getElementById(\'filter_reset\').value=1;document.adminForm.submit()" type="button" data-original-title="'.JText::_("COM_FALANG_FILTER_RESET").'"> <i class="icon-remove"></i></button>';
} else {
$reset["html"] = "<input type='hidden' name='filter_reset' id='filter_reset' value='0' /><input type='button' value='".JText::_("COM_FALANG_FILTER_RESET")."' onclick='document.getElementById(\"filter_reset\").value=1;document.adminForm.submit()' />";
}
return $reset;
}
}
class translationFrontpageFilter extends translationFilter
{
public function __construct($contentElement){
$this->filterNullValue=-1;
$this->filterType="frontpage";
$this->filterField = $contentElement->getFilter("frontpage");
parent::__construct($contentElement);
}
function _createFilter(){
if (!$this->filterField) return "";
$filter="";
//since joomla 3.0 filter_value can be '' too not only filterNullValue
if (isset($this->filter_value) && strlen($this->filter_value) > 0 && $this->filter_value!=$this->filterNullValue){
$db = JFactory::getDBO();
$sql = "SELECT content_id FROM #__content_frontpage order by ordering";
$db->setQuery($sql);
$ids = $db->loadColumn();
if (is_null($ids)){
$ids = array();
}
$ids[] = -1;
$idstring = implode(",",$ids);
$not = "";
if ($this->filter_value==0){
$not = " NOT ";
}
$filter = " c.".$this->filterField.$not." IN (".$idstring.") ";
}
return $filter;
}
/**
* Creates frontpage filter
*
* @param unknown_type $filtertype
* @param unknown_type $contentElement
* @return unknown
*/
function _createfilterHTML(){
$db = JFactory::getDBO();
if (!$this->filterField) return "";
$FrontpageOptions=array();
if (!FALANG_J30) {
$FrontpageOptions[] = JHTML::_('select.option', -1, JText::_('COM_FALANG_FILTER_ANY'));
}
$FrontpageOptions[] = JHTML::_('select.option', 1, JText::_('JYES'));
$FrontpageOptions[] = JHTML::_('select.option', 0, JText::_('JNO'));
$frontpageList=array();
if (FALANG_J30) {
$frontpageList["title"]= JText::_('COM_FALANG_SELECT_FRONTPAGE');
$frontpageList["position"] = 'sidebar';
$frontpageList["name"]= 'frontpage_filter_value';
$frontpageList["type"]= 'frontpage';
$frontpageList["options"] = $FrontpageOptions;
$frontpageList["html"] = JHTML::_('select.genericlist', $FrontpageOptions, 'frontpage_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
} else {
$frontpageList["title"]= JText::_('COM_FALANG_FILTER_FRONTPAGE');
$frontpageList["html"] = JHTML::_('select.genericlist', $FrontpageOptions, 'frontpage_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
}
return $frontpageList;
}
}
class translationArchiveFilter extends translationFilter
{
public function __construct($contentElement){
$this->filterNullValue=-1;
$this->filterType="archive";
$this->filterField = $contentElement->getFilter("archive");
parent::__construct($contentElement);
}
function _createFilter(){
if (!$this->filterField) return "";
$filter="";
//since joomla 3.0 filter_value can be '' too not only filterNullValue
if (isset($this->filter_value) && strlen($this->filter_value) > 0 && $this->filter_value!=$this->filterNullValue){
if ($this->filter_value==0){
$filter = " c.".$this->filterField." >=0 ";
}
else {
$filter = " c.".$this->filterField." =-1 ";
}
}
return $filter;
}
/**
* Creates archive filter
*
* @param unknown_type $filtertype
* @param unknown_type $contentElement
* @return unknown
*/
function _createfilterHTML(){
$db = JFactory::getDBO();
if (!$this->filterField) return "";
$FrontpageOptions=array();
if (!FALANG_J30) {
$FrontpageOptions[] = JHTML::_('select.option', -1, JText::_('COM_FALANG_FILTER_ANY'));
}
$FrontpageOptions[] = JHTML::_('select.option', 1, JText::_('JYES'));
$FrontpageOptions[] = JHTML::_('select.option', 0, JText::_('JNO'));
$frontpageList=array();
if (FALANG_J30) {
$frontpageList["title"]= JText::_('COM_FALANG_SELECT_ARCHIVE');
$frontpageList["position"] = 'sidebar';
$frontpageList["name"]= 'archive_filter_value';
$frontpageList["type"]= 'archive';
$frontpageList["options"] = $FrontpageOptions;
$frontpageList["html"] = JHTML::_('select.genericlist', $FrontpageOptions, 'archive_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
} else {
$frontpageList["title"]= JText::_('COM_FALANG_FILTER_ARCHIVE');
$frontpageList["html"] = JHTML::_('select.genericlist', $FrontpageOptions, 'archive_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
}
return $frontpageList;
}
}
class translationCategoryFilter extends translationFilter
{
var $section_filter_value;
public function __construct($contentElement){
$this->filterNullValue=-1;
$this->filterType="category";
$this->filterField = $contentElement->getFilter("category");
parent::__construct($contentElement);
}
function _createFilter(){
if (!$this->filterField) return "";
$filter="";
//since joomla 3.0 filter_value can be '' too not only filterNullValue
if (isset($this->filter_value) && strlen($this->filter_value) > 0 && $this->filter_value!=$this->filterNullValue){
$filter = " c.".$this->filterField." = ".$this->filter_value;
}
return $filter;
}
function _createfilterHTML(){
$db = JFactory::getDBO();
if (!$this->filterField) return "";
$allCategoryOptions = array();
$extension = 'com_'.$this->tableName;
$options = JHtml::_('category.options', $extension);
if (!FALANG_J30) {
$allCategoryOptions[-1] = JHTML::_('select.option', '-1',JText::_('COM_FALANG_ALL_CATEGORIES') );
}
$options = array_merge($allCategoryOptions, $options);
$categoryList=array();
if (FALANG_J30) {
$categoryList["title"]= JText::_('COM_FALANG_SELECT_CATEGORY');
$categoryList["position"] = 'sidebar';
$categoryList["name"]= 'category_filter_value';
$categoryList["type"]= 'category';
$categoryList["options"] = $options;
$categoryList["html"] = JHTML::_('select.genericlist', $options, 'category_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
} else {
$categoryList["title"]= JText::_('COM_FALANG_CATEGORY_FILTER');
$categoryList["html"] = JHTML::_('select.genericlist', $options, 'category_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
}
return $categoryList;
}
}
class translationAuthorFilter extends translationFilter
{
public function __construct($contentElement){
$this->filterNullValue=-1;
$this->filterType="author";
$this->filterField = $contentElement->getFilter("author");
parent::__construct($contentElement);
}
function _createfilterHTML(){
$db = JFactory::getDBO();
if (!$this->filterField) return "";
$AuthorOptions=array();
if (!FALANG_J30) {
$AuthorOptions[] = JHTML::_('select.option', '-1',JText::_('COM_FALANG_ALL_AUTHORS') );
}
// $sql = "SELECT c.id, c.title FROM #__categories as c ORDER BY c.title";
$sql = "SELECT DISTINCT auth.id, auth.username FROM #__users as auth, #__".$this->tableName." as c
WHERE c.".$this->filterField."=auth.id ORDER BY auth.username";
$db->setQuery($sql);
$cats = $db->loadObjectList();
$catcount=0;
foreach($cats as $cat){
$AuthorOptions[] = JHTML::_('select.option', $cat->id,$cat->username);
$catcount++;
}
$Authorlist=array();
if (FALANG_J30) {
$Authorlist["title"]=JText::_('COM_FALANG_SELECT_AUTHOR');
$Authorlist["position"] = 'sidebar';
$Authorlist["name"]= 'author_filter_value';
$Authorlist["type"]= 'author';
$Authorlist["options"] = $AuthorOptions;
$Authorlist["html"] = JHTML::_('select.genericlist', $AuthorOptions, 'author_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
} else {
$Authorlist["title"]=JText::_('COM_FALANG_AUTHOR_FILTER');
$Authorlist["html"] = JHTML::_('select.genericlist', $AuthorOptions, 'author_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
}
return $Authorlist;
}
}
class translationExtensionFilter extends translationFilter
{
public function __construct($contentElement){
$this->filterNullValue='';
$this->filterType="extension";
$this->filterField = $contentElement->getFilter("extension");
parent::__construct($contentElement);
}
function _createfilterHTML(){
$db = JFactory::getDBO();
if (!$this->filterField) return "";
$ExtensionOptions=array();
//not necessary in joomla 3.0
if (!FALANG_J30) {
$ExtensionOptions[] = JHTML::_('select.option', '',JText::_('COM_FALANG_ALL_EXTENSION') );
}
$query = $db->getQuery(true);
$query
->select('DISTINCT c.extension')
->from('#__'.$this->tableName.' as c')
->where('c.'.$this->filterField.' != '.$db->q('system'))
->order('c.extension');
$db->setQuery($query);
$extensions = $db->loadObjectList();
$extcount=0;
foreach($extensions as $extension){
$ExtensionOptions[] = JHTML::_('select.option', $extension->extension,$extension->extension);
$extcount++;
}
$Extensionlist=array();
if (FALANG_J30) {
$Extensionlist["title"]=JText::_('COM_FALANG_SELECT_EXTENSION');
$Extensionlist["position"] = 'sidebar';
$Extensionlist["name"]= 'extension_filter_value';
$Extensionlist["type"]= 'extension';
$Extensionlist["options"] = $ExtensionOptions;
$Extensionlist["html"] = JHTML::_('select.genericlist', $ExtensionOptions, 'extension_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
} else {
$Extensionlist["title"]=JText::_('COM_FALANG_EXTENSION_FILTER');
$Extensionlist["html"] = JHTML::_('select.genericlist', $ExtensionOptions, 'extension_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
}
return $Extensionlist;
}
}
class translationKeywordFilter extends translationFilter
{
public function __construct($contentElement){
$this->filterNullValue="";
$this->filterType="keyword";
$this->filterField = $contentElement->getFilter("keyword");
parent::__construct($contentElement);
}
function _createFilter(){
if (!$this->filterField) return "";
$filter="";
if ($this->filter_value!=""){
$db = JFactory::getDBO();
$filter = "LOWER(c.".$this->filterField." ) LIKE '%".$db->escape( $this->filter_value, true )."%'";
}
return $filter;
}
/**
* Creates Keyword filter
*
* @param unknown_type $filtertype
* @param unknown_type $contentElement
* @return unknown
*/
function _createfilterHTML(){
if (!$this->filterField) return "";
$Keywordlist=array();
$Keywordlist["title"]= JText::_('COM_FALANG_KEYWORD_FILTER');
if (FALANG_J30) {
$Keywordlist["position"] = 'top';
$Keywordlist['html'] = '<label class="element-invisible" for="keyword_filter_value">'.$Keywordlist["title"].'</label>';
$Keywordlist['html'] .= '<input type="text" name="keyword_filter_value" id="keyword_filter_value" title="'.$Keywordlist["title"].'" placeholder="'.$Keywordlist["title"].'" value="'.$this->filter_value.'" onChange="document.adminForm.submit();" />';
$Keywordlist['html'] .= '</div><div class="btn-group pull-left">';
$Keywordlist['html'] .= '<button class="btn hasTooltip" type="submit" data-original-title="'.JText::_('SEARCH').'"><i class="icon-search"></i></button>';
$Keywordlist['html'] .= '<button type="button" class="btn tip" onclick="document.id(\'keyword_filter_value\').value=\'\';this.form.submit();" title="'.JText::_('JSEARCH_FILTER_CLEAR').'"><i class="icon-remove"></i></button>';
} else {
$Keywordlist["html"] = '<input type="text" name="keyword_filter_value" value="'.$this->filter_value.'" class="text_area" onChange="document.adminForm.submit();" />';
}
return $Keywordlist;
}
}
class translationModuleFilter extends translationFilter
{
public function __construct($contentElement){
$this->filterNullValue=-1;
$this->filterType="module";
$this->filterField = $contentElement->getFilter("module");
parent::__construct($contentElement);
}
function _createFilter(){
$filter = "c.".$this->filterField."<99";
return $filter;
}
function _createfilterHTML(){
return "";
}
}
//new 2.8.2 filter by module type
class translationModuletypeFilter extends translationFilter
{
public function __construct($contentElement){
$this->filterNullValue="-+-+";
$this->filterType="moduletype";
$this->filterField = $contentElement->getFilter("moduletype");
parent::__construct($contentElement);
}
function _createFilter(){
if (!$this->filterField ) return "";
$filter="";
//since joomla 3.0 filter_value can be '' too not only filterNullValue
if (isset($this->filter_value) && strlen($this->filter_value) > 0 && $this->filter_value!=$this->filterNullValue){
$filter = "c.".$this->filterField."='".$this->filter_value."'";
}
return $filter;
}
function _createfilterHTML(){
$db = JFactory::getDBO();
$lang = JFactory::getLanguage();
if (!$this->filterField) return "";
$MmoduletypeOptions=array();
$sql = "SELECT DISTINCT module FROM #__modules WHERE client_id = 0 ORDER BY module ASC";
$db->setQuery($sql);
$cats = $db->loadObjectList();
$catcount=0;
foreach($cats as $cat){
//get translate name system by administrator/components/com_modules/models/modules.php translate method
$extension = $cat->module;
$clientPath = JPATH_SITE;
$source = $clientPath . "/modules/$extension";
$lang->load("$extension.sys", $clientPath, null, false, true)
|| $lang->load("$extension.sys", $source, null, false, true);
$name = JText::_($cat->module);
$MmoduletypeOptions[] = JHTML::_('select.option', $cat->module, $name);
$catcount++;
}
$Menutypelist=array();
$Menutypelist["title"]= JText::_('COM_FALANG_SELECT_MODULE');
$Menutypelist["position"] = 'sidebar';
$Menutypelist["name"]= 'moduletype_filter_value';
$Menutypelist["type"]= 'moduletype';
$Menutypelist["options"] = $MmoduletypeOptions;
$Menutypelist["html"] = JHTML::_('select.genericlist', $MmoduletypeOptions, 'moduletype_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
return $Menutypelist;
}
}
class translationMenutypeFilter extends translationFilter
{
public function __construct($contentElement){
$this->filterNullValue="-+-+";
$this->filterType="menutype";
$this->filterField = $contentElement->getFilter("menutype");
parent::__construct($contentElement);
}
function _createFilter(){
if (!$this->filterField ) return "";
$filter="";
//since joomla 3.0 filter_value can be '' too not only filterNullValue
if (isset($this->filter_value) && strlen($this->filter_value) > 0 && $this->filter_value!=$this->filterNullValue){
$filter = "c.".$this->filterField."='".$this->filter_value."'";
}
return $filter;
}
function _createfilterHTML(){
$db = JFactory::getDBO();
if (!$this->filterField) return "";
$MenutypeOptions=array();
if (!FALANG_J30) {
$MenutypeOptions[] = JHTML::_('select.option', $this->filterNullValue, JText::_('COM_FALANG_ALL_MENUS') );
}
//dont't add root menu to the list != 1
$sql = "SELECT DISTINCT mt.menutype FROM #__menu as mt WHERE id != 1 ORDER BY menutype ASC";
$db->setQuery($sql);
$cats = $db->loadObjectList();
$catcount=0;
foreach($cats as $cat){
$MenutypeOptions[] = JHTML::_('select.option', $cat->menutype,$cat->menutype);
$catcount++;
}
$Menutypelist=array();
if (FALANG_J30) {
$Menutypelist["title"]= JText::_('COM_FALANG_SELECT_MENU');
$Menutypelist["position"] = 'sidebar';
$Menutypelist["name"]= 'menutype_filter_value';
$Menutypelist["type"]= 'menutype';
$Menutypelist["options"] = $MenutypeOptions;
$Menutypelist["html"] = JHTML::_('select.genericlist', $MenutypeOptions, 'menutype_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
} else {
$Menutypelist["title"]= JText::_('COM_FALANG_MENU_FILTER');
$Menutypelist["html"] = JHTML::_('select.genericlist', $MenutypeOptions, 'menutype_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
}
return $Menutypelist;
}
}
/**
* filters translations based on creation/modification date of original
*
*/
class translationChangedFilter extends translationFilter
{
public function __construct($contentElement){
$this->filterNullValue=-1;
$this->filterType="lastchanged";
$this->filterField = $contentElement->getFilter("changed");
list($this->_createdField,$this->_modifiedField) = explode("|",$this->filterField);
parent::__construct($contentElement);
}
function _createFilter(){
if (!$this->filterField) return "";
$filter="";
//since joomla 3.0 filter_value can be '' too not only filterNullValue
if (isset($this->filter_value) && strlen($this->filter_value) > 0 && $this->filter_value!=$this->filterNullValue && $this->filter_value==1){
// translations must be created after creation date so no need to check this!
$filter = "( c.$this->_modifiedField>0 AND jfc.modified < c.$this->_modifiedField)" ;
}
else if (isset($this->filter_value) && strlen($this->filter_value) > 0 && $this->filter_value!=$this->filterNullValue){
$filter = "( ";
$filter .= "( c.$this->_modifiedField>0 AND jfc.modified >= c.$this->_modifiedField)" ;
$filter .= " OR ( c.$this->_modifiedField=0 AND jfc.modified >= c.$this->_createdField)" ;
$filter .= " )";
}
return $filter;
}
function _createfilterHTML(){
$db = JFactory::getDBO();
if (!$this->filterField) return "";
$ChangedOptions=array();
if (!FALANG_J30) {
$ChangedOptions[] = JHTML::_('select.option', -1,JText::_('COM_FALANG_FILTER_BOTH'));
}
$ChangedOptions[] = JHTML::_('select.option', 1, JText::_('COM_FALANG_FILTER_ORIGINAL_NEWER'));
$ChangedOptions[] = JHTML::_('select.option', 0, JText::_('COM_FALANG_FILTER_TRANSLATION_NEWER'));
$ChangedList=array();
if (FALANG_J30) {
$ChangedList["title"]= JText::_('COM_FALANG_SELECT_TRANSLATION_AGE');
$ChangedList["position"] = 'sidebar';
$ChangedList["name"]= 'lastchanged_filter_value';
$ChangedList["type"]= 'lastchanged';
$ChangedList["options"] = $ChangedOptions;
$ChangedList["html"] = JHTML::_('select.genericlist', $ChangedOptions, $this->filterType.'_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
} else {
$ChangedList["title"]= JText::_('COM_FALANG_FILTER_TRANSLATION_AGE');
$ChangedList["html"] = JHTML::_('select.genericlist', $ChangedOptions, $this->filterType.'_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
}
return $ChangedList;
}
}
/**
* Look for unpublished translations - i.e. no translation or translation is unpublished
* Really only makes sense with a specific language selected
*
*/
class translationTrashFilter extends translationFilter
{
public function __construct($contentElement){
$this->filterNullValue=-1;
$this->filterType="trash";
$this->filterField = $contentElement->getFilter("trash");
parent::__construct($contentElement);
}
function _createFilter(){
// -1 = archive, -2 = trash
$filter = "c.".$this->filterField.">=-1";
return $filter;
}
function _createfilterHTML(){
return "";
}
}
/**
* Look for unpublished translations - i.e. no translation or translation is unpublished
* Really only makes sense with a specific language selected
*
*/
class translationPublishedFilter extends translationFilter
{
public function __construct($contentElement){
$this->filterNullValue='';
$this->filterType="published";
$this->filterField = $contentElement->getFilter("published");
parent::__construct($contentElement);
}
function _createFilter(){
if (!$this->filterField) return "";
$filter="";
if ($this->filter_value!=$this->filterNullValue){
if ($this->filter_value==1){
$filter = "jfc.".$this->filterField."=$this->filter_value";
}
else if ($this->filter_value==0){
$filter = " ( jfc.".$this->filterField."=$this->filter_value AND jfc.reference_field IS NOT NULL ) ";
}
else if ($this->filter_value==2){
$filter = " jfc.reference_field IS NULL ";
}
else if ($this->filter_value==3){
$filter = " jfc.reference_field IS NOT NULL ";
}
}
return $filter;
}
function _createfilterHTML(){
$db = JFactory::getDBO();
if (!$this->filterField) return "";
$PublishedOptions=array();
if (!FALANG_J30) {
$PublishedOptions[] = JHTML::_('select.option', -1, JText::_('COM_FALANG_FILTER_ANY'));
}
$PublishedOptions[] = JHTML::_('select.option', 3, JText::_('COM_FALANG_FILTER_AVAILABLE'));
$PublishedOptions[] = JHTML::_('select.option', 1, JText::_('COM_FALANG_TITLE_PUBLISHED'));
$PublishedOptions[] = JHTML::_('select.option', 0, JText::_('COM_FALANG_TITLE_UNPUBLISHED'));
$PublishedOptions[] = JHTML::_('select.option', 2, JText::_('COM_FALANG_FILTER_MISSING'));
$publishedList=array();
if (FALANG_J30) {
$publishedList["title"]= JText::_('COM_FALANG_SELECT_TRANSLATION_AVAILABILITY');
$publishedList["position"] = 'sidebar';
$publishedList["name"]= 'published_filter_value';
$publishedList["type"]= 'published';
$publishedList["options"] = $PublishedOptions;
$publishedList["html"] = JHTML::_('select.genericlist', $PublishedOptions, 'published_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
} else {
$publishedList["title"]= JText::_('COM_FALANG_FILTER_TRANSLATION_AVAILABILITY');
$publishedList["html"] = JHTML::_('select.genericlist', $PublishedOptions, 'published_filter_value', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $this->filter_value );
}
return $publishedList;
}
}
class TranslateParams
{
var $origparams;
var $defaultparams;
var $transparams;
var $fields;
var $fieldname;
public function __construct($original, $translation, $fieldname, $fields=null){
$this->origparams = $original;
$this->transparams = $translation;
$this->fieldname = $fieldname;
$this->fields = $fields;
}
public function showOriginal()
{
echo $this->origparams;
}
public function showDefault()
{
echo "";
}
function editTranslation(){
$returnval = array( "editor_".$this->fieldname, "refField_".$this->fieldname );
JFactory::getEditor()->display("editor_" . $this->fieldname, $this->transparams, "refField_" . $this->fieldname, '100%;', '300', '70', '15');
echo $this->transparams;
return $returnval;
}
}
class TranslateParams_xml extends TranslateParams
{
function showOriginal()
{
$output = "";
$fieldname = 'orig_' . $this->fieldname;
$output .= $this->origparams->render($fieldname);
$output .= <<<SCRIPT
<script language='javascript'>
function copyParams(srctype, srcfield){
var orig = document.getElementsByTagName('select');
for (var i=0;i<orig.length;i++){
if (orig[i].name.indexOf(srctype)>=0 && orig[i].name.indexOf("[")>=0){
// TODO double check the str replacement only replaces one instance!!!
targetName = orig[i].name.replace(srctype,"refField");
target = document.getElementsByName(targetName);
if (target.length!=1){
alert(targetName+" problem "+target.length);
}
else {
target[0].selectedIndex = orig[i].selectedIndex;
}
}
}
var orig = document.getElementsByTagName('input');
for (var i=0;i<orig.length;i++){
if (orig[i].name.indexOf(srctype)>=0 && orig[i].name.indexOf("[")>=0){
// treat radio buttons differently
if (orig[i].type.toLowerCase()=="radio"){
//alert( orig[i].id+" "+orig[i].checked);
targetId = orig[i].id;
if (targetId){
targetId = targetId.replace(srctype,"refField");
target = document.getElementById(targetId);
if (!target){
alert("missing target for radio button "+orig[i].name);
}
else {
target.checked = orig[i].checked;
}
}
else {
alert("missing id for radio button "+orig[i].name);
}
}
else {
// TODO double check the str replacement only replaces one instance!!!
targetName = orig[i].name.replace(srctype,"refField");
target = document.getElementsByName(targetName);
if (target.length!=1){
alert(targetName+" problem "+target.length);
}
else {
target[0].value = orig[i].value;
}
}
}
}
var orig = document.getElementsByTagName('textarea');
for (var i=0;i<orig.length;i++){
if (orig[i].name.indexOf(srctype)>=0 && orig[i].name.indexOf("[")>=0){
// TODO double check the str replacement only replaces one instance!!!
targetName = orig[i].name.replace(srctype,"refField");
target = document.getElementsByName(targetName);
if (target.length!=1){
alert(targetName+" problem "+target.length);
}
else {
target[0].value = orig[i].value;
}
}
}
}
var orig = document.getElementsByTagName('select');
for (var i=0;i<orig.length;i++){
if (orig[i].name.indexOf("$fieldname")>=0){
orig[i].disabled = true;
}
}
var orig = document.getElementsByTagName('input');
for (var i=0;i<orig.length;i++){
if (orig[i].name.indexOf("$fieldname")>=0){
orig[i].disabled = true;
}
}
</script>
SCRIPT;
echo $output;
}
function showDefault()
{
$output = "<span style='display:none'>";
$output .= $this->defaultparams->render("defaultvalue_" . $this->fieldname);
$output .= "</span>\n";
echo $output;
}
function editTranslation(){
echo '<div class="form-horizontal translation-field-'.$this->fieldname.'">';
echo $this->transparams->render("refField_".$this->fieldname);
echo '</div';
return false;
}
}
class JFMenuParams extends JObject
{
var $form = null;
function __construct($form=null, $item=null)
{
$this->form = $form;
}
function render($type)
{
$this->menuform = $this->form;
echo JHtml::_('bootstrap.startTabSet', 'myTab', array('active' => 'collapse0'));
$i = 0;
$fieldSets = $this->form->getFieldsets('request');
if ($fieldSets)
{
foreach ($fieldSets as $name => $fieldSet)
{
$hidden_fields = '';
$label = !empty($fieldSet->label) ? $fieldSet->label : 'COM_MENUS_' . $name . '_FIELDSET_LABEL';
echo JHtml::_('bootstrap.addTab', 'myTab', 'collapse' . ($i++), addslashes(JText::_($label)), true);
if (isset($fieldSet->description) && trim($fieldSet->description)) :
echo '<p class="tip">' . htmlspecialchars(JText::_($fieldSet->description), ENT_QUOTES, 'UTF-8') . '</p>';
endif;
?>
<div class="clr"></div>
<fieldset class="panelform">
<?php foreach ($this->form->getFieldset($name) as $field){ ?>
<?php if (!$field->hidden)
{
echo $field->renderField();
}
else
{
$hidden_fields.= $field->input;
?>
<?php } ?>
<?php } ?>
<?php echo $hidden_fields; ?>
</fieldset>
<?php
echo JHtml::_('bootstrap.endTab');
}
}
$paramsfieldSets = $this->form->getFieldsets('params');
if ($paramsfieldSets)
{
foreach ($paramsfieldSets as $name => $fieldSet)
{
$label = !empty($fieldSet->label) ? $fieldSet->label : 'COM_MENUS_' . $name . '_FIELDSET_LABEL';
echo JHtml::_('bootstrap.addTab', 'myTab', 'collapse' . ($i++),JText::_($label), true);
if (isset($fieldSet->description) && trim($fieldSet->description)) :
echo '<p class="tip">' . htmlspecialchars(JText::_($fieldSet->description), ENT_QUOTES, 'UTF-8') . '</p>';
endif;
?>
<div class="clr"></div>
<fieldset class="panelform">
<ul class="adminformlist">
<?php foreach ($this->form->getFieldset($name) as $field) : ?>
<?php echo $field->renderField(); ?>
<?php endforeach; ?>
</ul>
</fieldset>
<?php
echo JHtml::_('bootstrap.endTab');
}
}
echo JHtml::_('bootstrap.endTabSet');
return;
}
}
class JFContentParams extends JObject
{
var $form = null;
function __construct($form=null, $item=null)
{
$this->form = $form;
}
function render($type)
{
echo JHtml::_('bootstrap.startTabSet', 'myTab', array('active' => 'basic'));
$paramsfieldSets = $this->form->getFieldsets('attribs');
if ($paramsfieldSets)
{
foreach ($paramsfieldSets as $name => $fieldSet)
{
$label = !empty($fieldSet->label) ? $fieldSet->label : 'COM_CONTENT_' . $name . '_FIELDSET_LABEL';
if ($name == 'basic-limited') {
continue;
}
if ($name == 'editorConfig' ) {
$label = 'COM_CONTENT_SLIDER_EDITOR_CONFIG';
}
echo JHtml::_('bootstrap.addTab', 'myTab', $name, addslashes(JText::_($label)), true);
if (isset($fieldSet->description) && trim($fieldSet->description)) :
echo '<p class="tip">' . htmlspecialchars(JText::_($fieldSet->description), ENT_QUOTES, 'UTF-8') . '</p>';
endif;
?>
<div class="clr"></div>
<fieldset class="panelform">
<?php foreach ($this->form->getFieldset($name) as $field) : ?>
<?php echo $field->renderField(); ?>
<?php endforeach; ?>
</fieldset>
<?php
echo JHtml::_('bootstrap.endTab');
}
}
//v2.1 add images in translation
$params = JComponentHelper::getParams('com_content');
if ($params->get('show_urls_images_backend') == 1) {
$imagesfields = $this->form->getGroup('images');
$urlsfields = $this->form->getGroup('urls');
echo JHtml::_('bootstrap.addTab', 'myTab', 'images', JText::_('COM_CONTENT_FIELDSET_URLS_AND_IMAGES', true));
?> <div class="row-fluid"> <?php
if ($imagesfields) {
?>
<div class="span6">
<?php echo $this->form->renderField('images') ?>
<?php foreach ($imagesfields as $field) : ?>
<?php echo $field->renderField(); ?>
<?php endforeach; ?>
</div>
<?php
}
if ($urlsfields) {
?>
<div class="span6">
<?php echo $this->form->renderField('urls') ?>
<?php foreach ($urlsfields as $field) : ?>
<?php echo $field->renderField(); ?>
<?php endforeach; ?>
</div>
<?php
}
?> </div> <?php
echo JHtml::_('bootstrap.endTab');
}
//2.8.3 support of custom fields
$customfieldSets = $this->form->getFieldsets('com_fields');
if (isset($customfieldSets))
{
foreach ($customfieldSets as $name => $fieldSet)
{
$label = !empty($fieldSet->label) ? $fieldSet->label : 'COM_CONTENT_' . $name . '_FIELDSET_LABEL';
echo JHtml::_('bootstrap.addTab', 'myTab', $name, addslashes(JText::_($label)), true);
if (isset($fieldSet->description) && trim($fieldSet->description)) :
echo '<p class="tip">' . htmlspecialchars(JText::_($fieldSet->description), ENT_QUOTES, 'UTF-8') . '</p>';
endif;
?>
<div class="clr"></div>
<fieldset class="panelform">
<ul class="adminformlist">
<?php foreach ($this->form->getFieldset($name) as $field) : ?>
<?php echo $field->renderField(); ?>
<?php endforeach; ?>
</ul>
</fieldset>
<?php
echo JHtml::_('bootstrap.endTab');
}
}
echo JHtml::_('bootstrap.endTabSet');
return;
}
}
class TranslateParams_menu extends TranslateParams_xml
{
var $_menutype;
var $_menuViewItem;
var $orig_modelItem;
var $trans_modelItem;
function __construct($original, $translation, $fieldname, $fields=null)
{
parent::__construct($original, $translation, $fieldname, $fields);
$lang = JFactory::getLanguage();
$lang->load("com_menus", JPATH_ADMINISTRATOR);
$cid = JRequest::getVar('cid', array(0));
$oldcid = $cid;
$translation_id = 0;
if (strpos($cid[0], '|') !== false)
{
list($translation_id, $contentid, $language_id) = explode('|', $cid[0]);
}
JRequest::setVar("cid", array($contentid));
JRequest::setVar("edit", true);
JLoader::import('models.JFMenusModelItem', FALANG_ADMINPATH);
$this->orig_modelItem = new JFMenusModelItem();
// Get The Original State Data
// model's populate state method assumes the id is in the request object!
$oldid = JRequest::getInt("id", 0);
JRequest::setVar("id", $contentid);
// NOW GET THE TRANSLATION - IF AVAILABLE
$this->trans_modelItem = new JFMenusModelItem();
$this->trans_modelItem->setState('item.id', $contentid);
if ($translation != "")
{
//fix bug in hikashop force return as array
$translation = json_decode($translation,true);
}
$translationMenuModelForm = $this->trans_modelItem->getForm();
//2.8.4
//due to hikashop bugfix we need to get jfrequest by $translation['jfrequest'] and no more by $translation->jfrequest
if (isset($translation['jfrequest'])){
$translationMenuModelForm->bind(array("params" => $translation, "request" =>$translation['jfrequest']));
}
else {
$translationMenuModelForm->bind(array("params" => $translation));
}
$cid = $oldcid;
JRequest::setVar('cid', $cid);
JRequest::setVar("id", $oldid);
$this->transparams = new JFMenuParams($translationMenuModelForm);
}
function editTranslation()
{
if ($this->_menutype == "wrapper")
{
?>
<table width="100%" class="paramlist">
<tr>
<td width="40%" align="right" valign="top"><span class="editlinktip"><!-- Tooltip -->
<span onmouseover="return overlib('Link for Wrapper', CAPTION, 'Wrapper Link', BELOW, RIGHT);" onmouseout="return nd();" >Wrapper Link</span></span></td>
<td align="left" valign="top"><input type="text" name="refField_params[url]" value="<?php echo $this->transparams->get('url', '') ?>" class="text_area" size="30" /></td>
</tr>
</table>
<?php
}
parent::editTranslation();
}
}
class JFModuleParams extends JObject
{
protected $form = null;
protected $item = null;
function __construct($form=null, $item=null)
{
$this->form = $form;
$this->item = $item;
}
function render($type)
{
echo JHtml::_('bootstrap.startTabSet', 'module-sliders', array('active' => 'basic-options'));
$paramsfieldSets = $this->form->getFieldsets('params');
if ($paramsfieldSets)
{
foreach ($paramsfieldSets as $name => $fieldSet)
{
$label = !empty($fieldSet->label) ? $fieldSet->label : 'COM_MODULES_' . $name . '_FIELDSET_LABEL';
echo JHtml::_('bootstrap.addTab', 'module-sliders', $name.'-options', addslashes(JText::_($label)));
if (isset($fieldSet->description) && trim($fieldSet->description)) :
echo '<p class="tip">' . htmlspecialchars(JText::_($fieldSet->description), ENT_QUOTES, 'UTF-8') . '</p>';
endif;
?>
<div class="clr"></div>
<fieldset class="panelform">
<?php foreach ($this->form->getFieldset($name) as $field) : ?>
<?php echo $field->renderField(); ?>
<?php endforeach; ?>
</fieldset>
<?php
echo JHtml::_('bootstrap.endTab');
}
}
//not render assignment menu
//depends on the original menu
echo JHtml::_('bootstrap.endTabSet');
return;
}
}
class JFFieldsParams extends JObject
{
protected $form = null;
protected $item = null;
function __construct($form=null, $item=null)
{
$this->form = $form;
$this->item = $item;
}
function render($type)
{
$options = ['readonly' => true];
$paramsfieldSets = $this->form->getFieldsets('fieldparams');
if ($paramsfieldSets) {
foreach ($paramsfieldSets as $name => $fieldSet) {
foreach ($this->form->getFieldset($name) as $field) {
echo $field->renderField($options);
}
}
}
return;
}
}
class TranslateParams_modules extends TranslateParams_xml
{
function __construct($original, $translation, $fieldname, $fields=null)
{
if (FALANG_J30){
require_once JPATH_ADMINISTRATOR.'/components/com_modules/helpers/modules.php';
}
parent::__construct($original, $translation, $fieldname, $fields);
$lang = JFactory::getLanguage();
$lang->load("com_modules", JPATH_ADMINISTRATOR);
$cid = JRequest::getVar('cid', array(0));
$oldcid = $cid;
$translation_id = 0;
if (strpos($cid[0], '|') !== false)
{
list($translation_id, $contentid, $language_id) = explode('|', $cid[0]);
}
// if we have an existing translation then load this directly!
// This is important for modules to populate the assignement fields
//$contentid = $translation_id?$translation_id : $contentid;
//TODO sbou check this
JRequest::setVar("cid", array($contentid));
JRequest::setVar("edit", true);
JLoader::import('models.JFModuleModelItem', FALANG_ADMINPATH);
// Get The Original State Data
// model's populate state method assumes the id is in the request object!
$oldid = JRequest::getInt("id", 0);
JRequest::setVar("id", $contentid);
// NOW GET THE TRANSLATION - IF AVAILABLE
$this->trans_modelItem = new JFModuleModelItem();
$this->trans_modelItem->setState('module.id', $contentid);
if ($translation != "")
{
//for return as associated array and not a stdclass
//fix bug with easyblog
$translation = json_decode($translation,true);
}
$translationModuleModelForm = $this->trans_modelItem->getForm();
if (isset($translation->jfrequest)){
$translationModuleModelForm->bind(array("params" => $translation, "request" =>$translation->jfrequest));
}
else {
$translationModuleModelForm->bind(array("params" => $translation));
}
$cid = $oldcid;
JRequest::setVar('cid', $cid);
JRequest::setVar("id", $oldid);
$this->transparams = new JFModuleParams($translationModuleModelForm, $this->trans_modelItem->getItem());
}
function showOriginal()
{
parent::showOriginal();
$output = "";
if ($this->origparams->getNumParams('advanced'))
{
$fieldname = 'orig_' . $this->fieldname;
$output .= $this->origparams->render($fieldname, 'advanced');
}
if ($this->origparams->getNumParams('other'))
{
$fieldname = 'orig_' . $this->fieldname;
$output .= $this->origparams->render($fieldname, 'other');
}
if ($this->origparams->getNumParams('legacy'))
{
$fieldname = 'orig_' . $this->fieldname;
$output .= $this->origparams->render($fieldname, 'legacy');
}
echo $output;
}
function editTranslation()
{
parent::editTranslation();
}
}
class TranslateParams_fields extends TranslateParams_xml
{
function __construct($original, $translation, $fieldname, $fields=null)
{
require_once JPATH_ADMINISTRATOR.'/components/com_fields/helpers/fields.php';
parent::__construct($original, $translation, $fieldname, $fields);
$lang = JFactory::getLanguage();
$lang->load("com_fields", JPATH_ADMINISTRATOR);
$cid = JRequest::getVar('cid', array(0));
$oldcid = $cid;
$translation_id = 0;
if (strpos($cid[0], '|') !== false)
{
list($translation_id, $contentid, $language_id) = explode('|', $cid[0]);
}
// if we have an existing translation then load this directly!
// This is important for modules to populate the assignement fields
//$contentid = $translation_id?$translation_id : $contentid;
//TODO sbou check this
JRequest::setVar("cid", array($contentid));
JRequest::setVar("edit", true);
JLoader::import('models.JFFieldModelItem', FALANG_ADMINPATH);
// Get The Original State Data
// model's populate state method assumes the id is in the request object!
$oldid = JRequest::getInt("id", 0);
JRequest::setVar("id", $contentid);
// NOW GET THE TRANSLATION - IF AVAILABLE
$this->trans_modelItem = new JFFieldModelItem();
$this->trans_modelItem->setState('field.id', $contentid);
if ($translation != "")
{
//for return as associated array and not a stdclass
//fix bug with easyblog
$translation = json_decode($translation,true);
}
$translationFieldModelForm = $this->trans_modelItem->getForm();
if (isset($translation->jfrequest)){
$translationFieldModelForm->bind(array("fieldparams" => $translation, "request" =>$translation->jfrequest));
}
else {
$translationFieldModelForm->bind(array("fieldparams" => $translation));
}
$cid = $oldcid;
JRequest::setVar('cid', $cid);
JRequest::setVar("id", $oldid);
$this->transparams = new JFFieldsParams($translationFieldModelForm, $this->trans_modelItem->getItem());
}
function showOriginal()
{
parent::showOriginal();
$output = "";
if ($this->origparams->getNumParams('advanced'))
{
$fieldname = 'orig_' . $this->fieldname;
$output .= $this->origparams->render($fieldname, 'advanced');
}
if ($this->origparams->getNumParams('other'))
{
$fieldname = 'orig_' . $this->fieldname;
$output .= $this->origparams->render($fieldname, 'other');
}
if ($this->origparams->getNumParams('legacy'))
{
$fieldname = 'orig_' . $this->fieldname;
$output .= $this->origparams->render($fieldname, 'legacy');
}
echo $output;
}
function editTranslation()
{
parent::editTranslation();
}
}
class TranslateParams_content extends TranslateParams_xml
{
var $orig_contentModelItem;
var $trans_contentModelItem;
function __construct($original, $translation, $fieldname, $fields=null)
{
if (FALANG_J30){
require_once JPATH_ADMINISTRATOR.'/components/com_content/helpers/content.php';
}
parent::__construct($original, $translation, $fieldname, $fields);
$lang = JFactory::getLanguage();
$lang->load("com_content", JPATH_ADMINISTRATOR);
$cid = JRequest::getVar('cid', array(0));
$oldcid = $cid;
$translation_id = 0;
if (strpos($cid[0], '|') !== false)
{
list($translation_id, $contentid, $language_id) = explode('|', $cid[0]);
}
JRequest::setVar("cid", array($contentid));
JRequest::setVar("edit", true);
// model's populate state method assumes the id is in the request object!
$oldid = JRequest::getInt("article_id", 0);
// Take care of the name of the id for the item
JRequest::setVar("article_id", $contentid);
JLoader::import('models.JFContentModelItem', FALANG_ADMINPATH);
$this->orig_contentModelItem = new JFContentModelItem();
// Get The Original form
// JRequest does NOT this for us in articles!!
$this->orig_contentModelItem->setState('article.id',$contentid);
$jfcontentModelForm = $this->orig_contentModelItem->getForm();
// NOW GET THE TRANSLATION - IF AVAILABLE
$this->trans_contentModelItem = new JFContentModelItem();
$this->trans_contentModelItem->setState('article.id', $contentid);
if ($translation != "")
{
$translation = json_decode($translation,true);
}
$translationcontentModelForm = $this->trans_contentModelItem->getForm();
if (isset($translation->jfrequest)) {
$translationcontentModelForm->bind(array("attribs" => $translation,"images" => $translation,"urls" => $translation, "request" => $translation->jfrequest));
} else {
$translationcontentModelForm->bind(array("attribs" => $translation,"images" => $translation,"urls" => $translation));
}
// reset old values in REQUEST array
$cid = $oldcid;
JRequest::setVar('cid', $cid);
JRequest::setVar("article_id", $oldid);
// $this->origparams = new JFContentParams( $jfcontentModelForm);
$this->transparams = new JFContentParams($translationcontentModelForm);
}
function showOriginal()
{
parent::showOriginal();
$output = "";
if ($this->origparams->getNumParams('advanced'))
{
$fieldname = 'orig_' . $this->fieldname;
$output .= $this->origparams->render($fieldname, 'advanced');
}
if ($this->origparams->getNumParams('legacy'))
{
$fieldname = 'orig_' . $this->fieldname;
$output .= $this->origparams->render($fieldname, 'legacy');
}
echo $output;
}
function editTranslation()
{
parent::editTranslation();
}
}
class TranslateParams_components extends TranslateParams_xml
{
var $_menutype;
var $_menuViewItem;
var $orig_menuModelItem;
var $trans_menuModelItem;
public function __construct($original, $translation, $fieldname, $fields=null){
$lang = JFactory::getLanguage();
$lang->load("com_config", JPATH_ADMINISTRATOR);
$this->fieldname = $fieldname;
global $mainframe;
$content = null;
foreach ($fields as $field) {
if ($field->Name=="option"){
$comp = $field->originalValue;
break;
}
}
$lang->load($comp, JPATH_ADMINISTRATOR);
$path = DS."components".DS.$comp.DS."config.xml";
//sbou
$xmlfile = $path;
//$xmlfile = JApplicationHelper::_checkPath($path);
//fin sbou
$this->origparams = new JParameter($original, $xmlfile,"component");
$this->transparams = new JParameter($translation, $xmlfile,"component");
$this->defaultparams = new JParameter("", $xmlfile,"component");
$this->fields = $fields;
}
function showOriginal(){
if ($this->_menutype=="wrapper"){
?>
<table width="100%" class="paramlist">
<tr>
<td width="40%" align="right" valign="top"><span class="editlinktip"><!-- Tooltip -->
<span onmouseover="return overlib('Link for Wrapper', CAPTION, 'Wrapper Link', BELOW, RIGHT);" onmouseout="return nd();" >Wrapper Link</span></span></td>
<td align="left" valign="top"><input type="text" name="orig_params[url]" value="<?php echo $this->origparams->get('url','')?>" class="text_area" size="30" /></td>
</tr>
</table>
<?php
}
parent::showOriginal();
}
function editTranslation(){
if ($this->_menutype=="wrapper"){
?>
<table width="100%" class="paramlist">
<tr>
<td width="40%" align="right" valign="top"><span class="editlinktip"><!-- Tooltip -->
<span onmouseover="return overlib('Link for Wrapper', CAPTION, 'Wrapper Link', BELOW, RIGHT);" onmouseout="return nd();" >Wrapper Link</span></span></td>
<td align="left" valign="top"><input type="text" name="refField_params[url]" value="<?php echo $this->transparams->get('url','')?>" class="text_area" size="30" /></td>
</tr>
</table>
<?php
}
parent::editTranslation();
}
}
//new Falang 2.0
class JFCategoryParams extends JObject
{
protected $form = null;
protected $item = null;
function __construct($form=null, $item=null)
{
$this->form = $form;
$this->item = $item;
}
function render($type)
{
echo JHtml::_('bootstrap.startTabSet', 'myTab', array('active' => 'basic'));
$paramsfieldSets = $this->form->getFieldsets('params');
if ($paramsfieldSets)
{
foreach ($paramsfieldSets as $name => $fieldSet)
{
$label = !empty($fieldSet->label) ? $fieldSet->label : 'COM_CATEGORIES_' . $name . '_FIELDSET_LABEL';
echo JHtml::_('bootstrap.addTab', 'myTab', $name, addslashes(JText::_($label)), true);
if (isset($fieldSet->description) && trim($fieldSet->description)) :
echo '<p class="tip">' . htmlspecialchars(JText::_($fieldSet->description), ENT_QUOTES, 'UTF-8') . '</p>';
endif;
?>
<div class="clr"></div>
<fieldset class="panelform">
<ul class="adminformlist">
<?php foreach ($this->form->getFieldset($name) as $field) : ?>
<?php echo $field->renderField(); ?>
<?php endforeach; ?>
</ul>
</fieldset>
<?php
echo JHtml::_('bootstrap.endTab');
}
}
echo JHtml::_('bootstrap.endTabSet');
return;
}
}
class TranslateParams_categories extends TranslateParams_xml
{
function __construct($original, $translation, $fieldname, $fields=null)
{
if (FALANG_J30){
require_once JPATH_ADMINISTRATOR.'/components/com_categories/helpers/categories.php';
}
parent::__construct($original, $translation, $fieldname, $fields);
$lang = JFactory::getLanguage();
$lang->load("com_categories", JPATH_ADMINISTRATOR);
$cid = JRequest::getVar('cid', array(0));
$oldcid = $cid;
$translation_id = 0;
if (strpos($cid[0], '|') !== false)
{
list($translation_id, $contentid, $language_id) = explode('|', $cid[0]);
}
// if we have an existing translation then load this directly!
// This is important for modules to populate the assignement fields
//$contentid = $translation_id?$translation_id : $contentid;
//TODO sbou check this
JRequest::setVar("cid", array($contentid));
JRequest::setVar("edit", true);
JLoader::import('models.JFCategoryModelItem', FALANG_ADMINPATH);
// Get The Original State Data
// model's populate state method assumes the id is in the request object!
$oldid = JRequest::getInt("id", 0);
JRequest::setVar("id", $contentid);
// NOW GET THE TRANSLATION - IF AVAILABLE
$this->trans_modelItem = new JFCategoryModelItem();
$this->trans_modelItem->setState('category.id', $contentid);
if ($translation != "")
{
$translation = json_decode($translation,true);
}
$translationCategoryModelForm = $this->trans_modelItem->getForm();
if (isset($translation->jfrequest)){
$translationCategoryModelForm->bind(array("params" => $translation, "request" =>$translation->jfrequest));
}
else {
$translationCategoryModelForm->bind(array("params" => $translation));
}
$cid = $oldcid;
JRequest::setVar('cid', $cid);
JRequest::setVar("id", $oldid);
$this->transparams = new JFCategoryParams($translationCategoryModelForm, $this->trans_modelItem->getItem());
}
function showOriginal()
{
parent::showOriginal();
$output = "";
if ($this->origparams->getNumParams('advanced'))
{
$fieldname = 'orig_' . $this->fieldname;
$output .= $this->origparams->render($fieldname, 'advanced');
}
if ($this->origparams->getNumParams('other'))
{
$fieldname = 'orig_' . $this->fieldname;
$output .= $this->origparams->render($fieldname, 'other');
}
if ($this->origparams->getNumParams('legacy'))
{
$fieldname = 'orig_' . $this->fieldname;
$output .= $this->origparams->render($fieldname, 'legacy');
}
echo $output;
}
function editTranslation()
{
parent::editTranslation();
}
}
| gpl-2.0 |
lukacsaron/lesarrail | wp-content/plugins/usp-pro/uninstall.php | 417 | <?php // uninstall remove options
if(!defined('ABSPATH') && !defined('WP_UNINSTALL_PLUGIN')) exit();
// delete options
delete_option('usp_admin');
delete_option('usp_advanced');
delete_option('usp_general');
delete_option('usp_uploads');
delete_option('usp_more');
// delete widgets
delete_option('widget_usp_form_widget');
// delete license
delete_option('usp_license_key');
delete_option('usp_license_status');
| gpl-2.0 |
vivoconunxino/counter | src/com/example/counter/CategoriesActivity.java | 3547 | /**
*
*/
package com.example.counter;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
/**
* @author vivo
*
*/
public class CategoriesActivity extends Activity {
private StatisticsDataSource statistics;
private ArrayList<Category> arraylist_categories;
private CategoriesListViewAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Debug.log("init categories activity");
setContentView(R.layout.activity_categories);
statistics = new StatisticsDataSource(this.getApplicationContext());
arraylist_categories = statistics.getArrayCategories();
adapter = new CategoriesListViewAdapter(arraylist_categories, this);
ListView list_view = (ListView) this.findViewById(android.R.id.list);
list_view.setAdapter(adapter);
//Scrolling on top
scrollMyListViewToPos(0);
//on top of listview
//ListView list_view = (ListView) this.findViewById(android.R.id.list);
//ListView list_view = getListView();
list_view.setSelectionAfterHeaderView();
//final ListView list_view = (ListView) this.findViewById(android.R.id.list);
//list_view.setSelectionAfterHeaderView();;
//list_view.smoothScrollToPosition(0);
}
/*
@Override
protected void onListItemClick(ListView list_view, View view, int position, long id)
{
super.onListItemClick(list_view, view, position, id);
//Object o = getListAdapter().getItem(position);
Debug.log("onListItemClick");
view.setSelected(true);
}
*/
/** saves a new category
*/
public void createCategory(View v)
{
Debug.log("Activity runs updateCategory");
Category cat = new Category();
TextView txt_category = (TextView) this.findViewById(R.id.txt_category);
String name = txt_category.getText().toString();
if(name != "")
{
cat.setName(name);
statistics.createCategory(cat);
//added dinamically to the listView
arraylist_categories.add(cat);
adapter.notifyDataSetChanged();
int pos = adapter.getCount() - 1;
scrollMyListViewToPos(pos);
}
}
/** updates an existing category
* @param cat Category
*/
public void updateCategory(Category cat)
{
Debug.log("CategoriesActivity runs updateCategory");
statistics.updateCategory(cat);
}
/** resets category count
* this means all counts of this category will be reset
* @param cat Category
*/
public void resetCategory(Category cat)
{
Debug.log("CategoriesActivity runs resetCategory");
statistics.resetCategory(cat);
}
/** resets category count
* this means all counts of this category will be reset
* it ends the current activity
* @param cat Category
*/
public void selectCategory(Category cat)
{
Debug.log("CategoriesActivity runs selectCategory");
statistics.selectCategory(cat);
finish();
}
/** deletes an existing category
* @param cat Category
*/
public void deleteCategory(Category cat)
{
Debug.log("CategoriesActivity runs deleteCategory");
statistics.deleteCategory(cat);
}
/** Scrolls the list view to the position given
*/
private void scrollMyListViewToPos(final int pos) {
Debug.log("Scrolling to position "+pos);
final ListView list_view = (ListView) this.findViewById(android.R.id.list);
list_view.post(new Runnable() {
@Override
public void run() {
// Select the last row so it will scroll into view...
//list_view.setSelection(pos);
list_view.smoothScrollToPosition(pos);
}
});
}
}
| gpl-2.0 |
czfshine/Don-t-Starve | data/scripts/components/reticule.lua | 1947 | --[[
Add this component to items that need a targetting reticule
during use with a controller. Creation of the reticule is handled by
playercontroller.lua equip and unequip events.
--]]
local Reticule = Class(function(self, inst)
self.inst = inst
self.targetpos = nil
self.ease = false
self.smoothing = 6.66
self.targetfn = nil
self.reticuleprefab = "reticule"
self.reticule = nil
self.validcolour = {204/255,131/255,57/255,.3}
self.invalidcolour = {1,0,0,.3}
end)
function Reticule:CreateReticule()
local reticule = SpawnPrefab(self.reticuleprefab)
if not reticule then return end
if self.targetfn then
self.targetpos = self.targetfn()
end
if self.targetpos then
reticule.Transform:SetPosition(self.targetpos:Get())
end
self.reticule = reticule
self.inst:StartUpdatingComponent(self)
end
function Reticule:DestroyReticule()
if not self.reticule then return end
self.reticule:Remove()
self.reticule = nil
self.inst:StopUpdatingComponent(self)
end
function Reticule:OnUpdate(dt)
if not self.targetfn then return end
self.targetpos = self.targetfn()
if not self.targetpos then return end
local pt = self.reticule:GetPosition()
local x,y,z = self.targetpos:Get()
if self.ease then
x = Lerp(pt.x, self.targetpos.x, dt*self.smoothing)
y = Lerp(pt.y, self.targetpos.y, dt*self.smoothing)
z = Lerp(pt.z, self.targetpos.z, dt*self.smoothing)
end
local tile = GetWorld().Map:GetTileAtPoint(self.targetpos:Get())
local passable = tile ~= GROUND.IMPASSABLE
if not passable then
self.reticule.components.colourtweener:StartTween(self.invalidcolour, 0)
self.reticule.AnimState:ClearBloomEffectHandle()
self.reticule:Hide()
else
self.reticule.components.colourtweener:StartTween(self.validcolour, 0)
self.reticule.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
self.reticule:Show()
end
self.reticule.Transform:SetPosition(x,y,z)
end
return Reticule | gpl-2.0 |
carlosthe19916/SistCoopEE_Rest | restapi-organizacion/src/main/java/org/softgreen/sistcoop/organizacion/restapi/resources/UsuarioResource.java | 3461 | package org.softgreen.sistcoop.organizacion.restapi.resources;
import java.util.List;
import javax.annotation.security.PermitAll;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import org.jboss.ejb3.annotation.SecurityDomain;
import org.softgreen.sistcoop.organizacion.client.models.AgenciaModel;
import org.softgreen.sistcoop.organizacion.client.models.CajaModel;
import org.softgreen.sistcoop.organizacion.client.models.SucursalModel;
import org.softgreen.sistcoop.organizacion.client.models.TrabajadorCajaModel;
import org.softgreen.sistcoop.organizacion.client.models.TrabajadorModel;
import org.softgreen.sistcoop.organizacion.client.models.TrabajadorProvider;
import org.softgreen.sistcoop.organizacion.client.models.util.ModelToRepresentation;
import org.softgreen.sistcoop.organizacion.client.representations.idm.AgenciaRepresentation;
import org.softgreen.sistcoop.organizacion.client.representations.idm.CajaRepresentation;
import org.softgreen.sistcoop.organizacion.client.representations.idm.SucursalRepresentation;
import org.softgreen.sistcoop.organizacion.client.representations.idm.TrabajadorRepresentation;
@Path("/usuarios")
@Stateless
@SecurityDomain("keycloak")
public class UsuarioResource {
@Inject
protected TrabajadorProvider trabajadorProvider;
@GET
@Path("/{username}/sucursal")
@Produces({ "application/xml", "application/json" })
@PermitAll
public SucursalRepresentation getSucursal(@PathParam("username") String username) {
TrabajadorModel trabajadorModel = trabajadorProvider.getTrabajadorByUsuario(username);
if (trabajadorModel == null)
return null;
AgenciaModel agenciaModel = trabajadorModel.getAgencia();
SucursalModel sucursalModel = agenciaModel.getSucursal();
return ModelToRepresentation.toRepresentation(sucursalModel);
}
@GET
@Path("/{username}/agencia")
@Produces({ "application/xml", "application/json" })
@PermitAll
public AgenciaRepresentation getAgencia(@PathParam("username") String username) {
TrabajadorModel trabajadorModel = trabajadorProvider.getTrabajadorByUsuario(username);
if (trabajadorModel == null)
return null;
AgenciaModel agenciaModel = trabajadorModel.getAgencia();
return ModelToRepresentation.toRepresentation(agenciaModel);
}
@GET
@Path("/{username}/trabajador")
@Produces({ "application/xml", "application/json" })
@PermitAll
public TrabajadorRepresentation getTrabajador(@PathParam("username") String username) {
TrabajadorModel trabajadorModel = trabajadorProvider.getTrabajadorByUsuario(username);
return ModelToRepresentation.toRepresentation(trabajadorModel);
}
@GET
@Path("/{username}/caja")
@Produces({ "application/xml", "application/json" })
@PermitAll
public CajaRepresentation getCaja(@PathParam("username") String username) {
TrabajadorModel trabajadorModel = trabajadorProvider.getTrabajadorByUsuario(username);
if (trabajadorModel == null)
return null;
List<TrabajadorCajaModel> trabajadorCajas = trabajadorModel.getTrabajadorCajas();
TrabajadorCajaModel trabajadorCajaModel = null;
for (TrabajadorCajaModel trabCajModel : trabajadorCajas) {
trabajadorCajaModel = trabCajModel;
break;
}
if (trabajadorCajaModel != null) {
CajaModel cajaModel = trabajadorCajaModel.getCaja();
return ModelToRepresentation.toRepresentation(cajaModel);
} else {
return null;
}
}
} | gpl-2.0 |
Piervit/Cap2IJC | net/sourceforge/javacardtools/Cap2IJC/Cap2IJC.java | 6208 | /**
*
* Initial author: lusing
* Modified by : Pierre Vittet (FIME)
*
* Project recovered from http://sourceforge.net/p/openjcvm/code/HEAD/tree/Trunk/.
*
* The project licence is GPLV2 (see LICENCE).
*
*/
package net.sourceforge.javacardtools.Cap2IJC;
import java.io.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Cap2IJC {
/**
*
* @param sCapFileName
* @throws FileNotFoundException
* @throws IOException
*/
public static void readCap(Options options)
throws FileNotFoundException, IOException {
byte[] baHeader = null;
byte[] baDirectory = null;
byte[] baApplet = null;
byte[] baImport = null;
byte[] baConstantPool = null;
byte[] baClass = null;
byte[] baMethod = null;
byte[] baStaticField = null;
byte[] baRefLocation = null;
byte[] baDescriptor = null;
byte[] baExport = null;
byte[] baDebug = null;
String sCapFileName = options.getCapPath();
ZipInputStream zin = new ZipInputStream(new FileInputStream(
sCapFileName));
ZipEntry zEntry;
while ((zEntry = zin.getNextEntry()) != null) {
// System.out.println("Reading --- " + zEntry.getName());
if (zEntry.isDirectory()) {
System.out.println("Found " + zEntry.getName() + " directory!");
} else {
String[] sDirs;
String sFileName = zEntry.getName();
sDirs = sFileName.split("/");
if (sDirs[sDirs.length - 1].equals("Header.cap")) {
System.out.println("Processing Header.cap...");
baHeader = setComponent(zEntry, zin);
} else if (sDirs[sDirs.length - 1].equals("Directory.cap")) {
System.out.println("Processing Directory.cap...");
baDirectory = setComponent(zEntry, zin);
} else if (sDirs[sDirs.length - 1].equals("Applet.cap")) {
System.out.println("Processing Applet.cap...");
baApplet = setComponent(zEntry, zin);
} else if (sDirs[sDirs.length - 1].equals("Import.cap")) {
System.out.println("Processing Import.cap...");
baImport = setComponent(zEntry, zin);
} else if (sDirs[sDirs.length - 1].equals("ConstantPool.cap")) {
System.out.println("Processing ConstantPool.cap...");
baConstantPool = setComponent(zEntry, zin);
} else if (sDirs[sDirs.length - 1].equals("Class.cap")) {
System.out.println("Processing Class.cap...");
baClass = setComponent(zEntry, zin);
} else if (sDirs[sDirs.length - 1].equals("Method.cap")) {
System.out.println("Processing Method.cap...");
baMethod = setComponent(zEntry, zin);
} else if (sDirs[sDirs.length - 1].equals("StaticField.cap")) {
System.out.println("Processing StaticField.cap...");
baStaticField = setComponent(zEntry, zin);
} else if (sDirs[sDirs.length - 1].equals("RefLocation.cap")) {
System.out.println("Processing RefLocation.cap...");
baRefLocation = setComponent(zEntry, zin);
} else if (sDirs[sDirs.length - 1].equals("Export.cap")) {
System.out.println("Processing Export.cap...");
baExport = setComponent(zEntry, zin);
} else if (sDirs[sDirs.length - 1].equals("Descriptor.cap")) {
System.out.println("Processing Descriptor.cap...");
baDescriptor = setComponent(zEntry, zin);
} else if (sDirs[sDirs.length - 1].equals("Debug.cap")) {
System.out.println("Processing Debug.cap...");
baDebug = setComponent(zEntry, zin);
}
}
}
zin.close();
String[] sDirsOut;
sDirsOut = sCapFileName.split("/");
String sCapFile = sDirsOut[sDirsOut.length - 1];
String sIJCFileName = null;
if(options.getOutPath() != null){
sIJCFileName = options.getOutPath();
}
else{
sIJCFileName = sCapFile.substring(0, sCapFile.length() - 4)
+ ".ijc";
}
System.out.println(sIJCFileName);
File fOut = new File(sIJCFileName);
BufferedOutputStream fos = new BufferedOutputStream(
new FileOutputStream(fOut));
if (!options.getAllComponent()) {
/*
* Install order defined in JCVM specification section 6.2
* Descriptor component will be not included.
*/
outComponent(fos, baHeader);
outComponent(fos, baDirectory);
outComponent(fos, baImport);
outComponent(fos, baApplet);
outComponent(fos, baClass);
outComponent(fos, baMethod);
outComponent(fos, baStaticField);
outComponent(fos, baExport);
outComponent(fos, baConstantPool);
outComponent(fos, baRefLocation);
// outComponent(fos,baDescriptor);
// outComponent(fos,baDebug);
} else {
/*
* Install order defined in JCVM specification section 6.2 All
* components are included.
*/
outComponent(fos, baHeader);
outComponent(fos, baDirectory);
outComponent(fos, baImport);
outComponent(fos, baApplet);
outComponent(fos, baClass);
outComponent(fos, baMethod);
outComponent(fos, baStaticField);
outComponent(fos, baExport);
outComponent(fos, baConstantPool);
outComponent(fos, baRefLocation);
outComponent(fos, baDescriptor);
outComponent(fos, baDebug);
}
fos.close();
}
public static void outComponent(OutputStream os, byte[] baComp)
throws IOException {
if (baComp != null) {
os.write(baComp);
}
}
public static byte[] setComponent(ZipEntry zEntry, ZipInputStream zin)
throws IOException {
int length = (int) zEntry.getSize();
byte[] baComp = new byte[length];
int b;
int iPos = 0;
while ((b = zin.read()) != -1) {
baComp[iPos++] = (byte) b;
}
return baComp;
}
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) {
try {
System.out.println("---Cap2IJC version 1.0---");
Options options = Options.getOption();
options.getArgs(args);
readCap(options);
} catch (FileNotFoundException fnfe) {
System.out.println("File " + args[0] + " Not Found");
fnfe.printStackTrace();
} catch (IOException ioe) {
System.out.println("IO Exception!");
ioe.printStackTrace();
}
}
}
| gpl-2.0 |
vasi/kdelibs | solid/solid/backends/upower/upowermanager.cpp | 5005 | /*
Copyright 2010 Michael Zanetti <mzanetti@kde.org>
Copyright 2010 Lukas Tinkl <ltinkl@redhat.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), which shall
act as a proxy defined in Section 6 of version 3 of the license.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "upowermanager.h"
#include "upowerdevice.h"
#include "upower.h"
#include <QtDBus/QDBusReply>
#include <QtCore/QDebug>
#include <QtDBus/QDBusMetaType>
#include <QtDBus/QDBusConnectionInterface>
#include "../shared/rootdevice.h"
using namespace Solid::Backends::UPower;
using namespace Solid::Backends::Shared;
UPowerManager::UPowerManager(QObject *parent)
: Solid::Ifaces::DeviceManager(parent),
m_manager(UP_DBUS_SERVICE,
UP_DBUS_PATH,
UP_DBUS_INTERFACE,
QDBusConnection::systemBus())
{
m_supportedInterfaces
<< Solid::DeviceInterface::GenericInterface
<< Solid::DeviceInterface::AcAdapter
<< Solid::DeviceInterface::Battery;
qDBusRegisterMetaType<QList<QDBusObjectPath> >();
qDBusRegisterMetaType<QVariantMap>();
bool serviceFound = m_manager.isValid();
if (!serviceFound) {
// find out whether it will be activated automatically
QDBusMessage message = QDBusMessage::createMethodCall("org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"ListActivatableNames");
QDBusReply<QStringList> reply = QDBusConnection::systemBus().call(message);
if (reply.isValid() && reply.value().contains(UP_DBUS_SERVICE)) {
QDBusConnection::systemBus().interface()->startService(UP_DBUS_SERVICE);
serviceFound = true;
}
}
if (serviceFound) {
connect(&m_manager, SIGNAL(DeviceAdded(QString)),
this, SLOT(slotDeviceAdded(QString)));
connect(&m_manager, SIGNAL(DeviceRemoved(QString)),
this, SLOT(slotDeviceRemoved(QString)));
}
}
UPowerManager::~UPowerManager()
{
}
QObject* UPowerManager::createDevice(const QString& udi)
{
if (udi==udiPrefix()) {
RootDevice *root = new RootDevice(udiPrefix());
root->setProduct(tr("Power Management"));
root->setDescription(tr("Batteries and other sources of power"));
root->setIcon("preferences-system-power-management");
return root;
} else if (allDevices().contains(udi)) {
return new UPowerDevice(udi);
} else {
return 0;
}
}
QStringList UPowerManager::devicesFromQuery(const QString& parentUdi, Solid::DeviceInterface::Type type)
{
QStringList allDev = allDevices();
QStringList result;
if (!parentUdi.isEmpty())
{
foreach (const QString & udi, allDev)
{
UPowerDevice device(udi);
if (device.queryDeviceInterface(type) && device.parentUdi() == parentUdi)
result << udi;
}
return result;
}
else if (type != Solid::DeviceInterface::Unknown)
{
foreach (const QString & udi, allDev)
{
UPowerDevice device(udi);
if (device.queryDeviceInterface(type))
result << udi;
}
return result;
}
else
return allDev;
}
QStringList UPowerManager::allDevices()
{
QDBusReply<QList<QDBusObjectPath> > reply = m_manager.call("EnumerateDevices");
if (!reply.isValid()) {
qWarning() << Q_FUNC_INFO << " error: " << reply.error().name();
return QStringList();
}
QStringList retList;
retList << udiPrefix();
foreach (const QDBusObjectPath &path, reply.value()) {
retList << path.path();
}
return retList;
}
QSet< Solid::DeviceInterface::Type > UPowerManager::supportedInterfaces() const
{
return m_supportedInterfaces;
}
QString UPowerManager::udiPrefix() const
{
return UP_UDI_PREFIX;
}
void UPowerManager::slotDeviceAdded(const QString &opath)
{
emit deviceAdded(opath);
}
void UPowerManager::slotDeviceRemoved(const QString &opath)
{
emit deviceRemoved(opath);
}
#include "backends/upower/upowermanager.moc"
| gpl-2.0 |
danielcb29/SISCONDOC | SISCONDOC/src/almacenamiento/controlador/ControlFormadorTIC.java | 3012 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package almacenamiento.controlador;
import almacenamiento.accesodatos.DAOFormadorTIC;
import java.sql.Connection;
import proceso.FormadorTIC;
/**
*
* @author daniel
*/
public class ControlFormadorTIC {
private DAOFormadorTIC daoForm;
public ControlFormadorTIC(Connection conn){
daoForm = new DAOFormadorTIC(conn);
}
/**
* Metodo que permite crear una serie de registros formadorTic a partir de un arreglo y la cedula del aspirante al cual pertenece
* @param form : arreglo que contiene los distintos objetos FormadorTIC
* @param cedula : identificacion del aspirante al cual se le asignaran esos registros
* @return numero de confirmacion , 1 exitoso , -1 problema general , -2 problema de sql
*/
public int createFormador(FormadorTIC[] form, String cedula){
int size = form.length;
int result = 0;
for(int i = 0; i< size ; i++){
result = daoForm.crateFormador(form[i],cedula);
}
return result;
}
/**
* Metodo que permite listar todos los registros que estan en la tabla formadorTic de un aspirante en particular
* @param cedula : cedula del aspirante a consultar
* @return arreglo con los registros del aspirante
*/
public FormadorTIC[] listFormador(String cedula){
FormadorTIC[] list = daoForm.listFormador(cedula);
return list;
}
/**
* Metodo que permite leer un registro de la tabla formadorTic de un aspirante en un grupo de formados en especial
* @param cedula: identificacion del aspirante a consultar
* @param people: peronas que fueron formadas , son 3 categorias
* @return
*/
public FormadorTIC readFormador(String cedula, String people){
FormadorTIC form = daoForm.readFormador(people, cedula);
return form;
}
/**
* Metodo que permite eliminar (cambiar estado a inactivo) un registro en la tabla formadorTic
* @param cedula: cedula del aspirante al cual se elimina el registro
* @param people: categoria de formados a eliminar
* @return numero de verificacion , 1 ok ,-1 error general, -2 error sql
*/
public int deleteFormador(String cedula , String people){
int result = daoForm.deletFormador(cedula, people);
return result;
}
/**
* Metodo que permite actualizar un registro de la tabla formadorTic en la base de datos de acuerdo al aspirante y a los formados
* @param cedula: identificacion del aspirante a actualizar el registro
* @param people : personas formadas , son 3 categorias , debe ser una de las 3
* @param form : objeto FormadorTIC con la informacion actualizada
* @return
*/
public int updateFormador(String cedula,String people ,FormadorTIC form){
int result = daoForm.updateFormador(cedula, people, form);
return result;
}
}
| gpl-2.0 |
CarlAtComputer/tracker | playground/other_gef/org.eclipse.gef.examples.shapes/src/org/eclipse/gef/examples/shapes/parts/ShapeTreeEditPart.java | 3103 | /*******************************************************************************
* Copyright (c) 2004, 2005 Elias Volanakis and others.
�* All rights reserved. This program and the accompanying materials
�* are made available under the terms of the Eclipse Public License v1.0
�* which accompanies this distribution, and is available at
�* http://www.eclipse.org/legal/epl-v10.html
�*
�* Contributors:
�*����Elias Volanakis - initial API and implementation
�*******************************************************************************/
package org.eclipse.gef.examples.shapes.parts;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.editparts.AbstractTreeEditPart;
import org.eclipse.gef.examples.shapes.model.ModelElement;
import org.eclipse.gef.examples.shapes.model.Shape;
/**
* TreeEditPart used for Shape instances (more specific for EllipticalShape and
* RectangularShape instances). This is used in the Outline View of the
* ShapesEditor.
* <p>
* This edit part must implement the PropertyChangeListener interface, so it can
* be notified of property changes in the corresponding model element.
* </p>
*
* @author Elias Volanakis
*/
class ShapeTreeEditPart extends AbstractTreeEditPart implements
PropertyChangeListener {
/**
* Create a new instance of this edit part using the given model element.
*
* @param model
* a non-null Shapes instance
*/
ShapeTreeEditPart(Shape model) {
super(model);
}
/**
* Upon activation, attach to the model element as a property change
* listener.
*/
public void activate() {
if (!isActive()) {
super.activate();
((ModelElement) getModel()).addPropertyChangeListener(this);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.editparts.AbstractTreeEditPart#createEditPolicies()
*/
protected void createEditPolicies() {
// allow removal of the associated model element
installEditPolicy(EditPolicy.COMPONENT_ROLE,
new ShapeComponentEditPolicy());
}
/**
* Upon deactivation, detach from the model element as a property change
* listener.
*/
public void deactivate() {
if (isActive()) {
super.deactivate();
((ModelElement) getModel()).removePropertyChangeListener(this);
}
}
private Shape getCastedModel() {
return (Shape) getModel();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.editparts.AbstractTreeEditPart#getImage()
*/
protected Image getImage() {
return getCastedModel().getIcon();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.editparts.AbstractTreeEditPart#getText()
*/
protected String getText() {
return getCastedModel().toString();
}
/*
* (non-Javadoc)
*
* @see java.beans.PropertyChangeListener#propertyChange(java.beans.
* PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent evt) {
refreshVisuals(); // this will cause an invocation of getImage() and
// getText(), see below
}
} | gpl-2.0 |
Saboteur777/flavantic | wp-content/plugins/wp-mail-logging/inc/redux/redux-framework/ReduxCore/inc/fields/link_color/field_link_color.js | 4049 | /*
Field Link Color
*/
/*global jQuery, document, redux_change, redux*/
(function( $ ) {
'use strict';
redux.field_objects = redux.field_objects || {};
redux.field_objects.link_color = redux.field_objects.link_color || {};
$( document ).ready(
function() {
}
);
redux.field_objects.link_color.init = function( selector ) {
if ( !selector ) {
selector = $( document ).find( '.redux-container-link_color:visible' );
}
$( selector ).each(
function() {
var el = $( this );
var parent = el;
if ( !el.hasClass( 'redux-field-container' ) ) {
parent = el.parents( '.redux-field-container:first' );
}
if ( parent.is( ":hidden" ) ) { // Skip hidden fields
return;
}
if ( parent.hasClass( 'redux-field-init' ) ) {
parent.removeClass( 'redux-field-init' );
} else {
return;
}
el.find( '.redux-color-init' ).wpColorPicker({
change: function( u ) {
redux_change( $( this ) );
el.find( '#' + u.target.getAttribute( 'data-id' ) + '-transparency' ).removeAttr( 'checked' );
},
clear: function() {
redux_change( $( this ).parent().find( '.redux-color-init' ) );
}
});
el.find( '.redux-color' ).on(
'keyup', function() {
var value = $( this ).val();
var color = colorValidate( this );
var id = '#' + $( this ).attr( 'id' );
if ( value === "transparent" ) {
$( this ).parent().parent().find( '.wp-color-result' ).css(
'background-color', 'transparent'
);
el.find( id + '-transparency' ).attr( 'checked', 'checked' );
} else {
el.find( id + '-transparency' ).removeAttr( 'checked' );
if ( color && color !== $( this ).val() ) {
$( this ).val( color );
}
}
}
);
// Replace and validate field on blur
el.find( '.redux-color' ).on(
'blur', function() {
var value = $( this ).val();
var id = '#' + $( this ).attr( 'id' );
if ( value === "transparent" ) {
$( this ).parent().parent().find( '.wp-color-result' ).css(
'background-color', 'transparent'
);
el.find( id + '-transparency' ).attr( 'checked', 'checked' );
} else {
if ( colorValidate( this ) === value ) {
if ( value.indexOf( "#" ) !== 0 ) {
$( this ).val( $( this ).data( 'oldcolor' ) );
}
}
el.find( id + '-transparency' ).removeAttr( 'checked' );
}
}
);
// Store the old valid color on keydown
el.find( '.redux-color' ).on(
'keydown', function() {
$( this ).data( 'oldkeypress', $( this ).val() );
}
);
}
);
};
})( jQuery );
| gpl-2.0 |
ShimShtein/katello | test/controllers/api/v2/systems_controller_test.rb | 8032 | # encoding: utf-8
#
# Copyright 2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the implied warranties of MERCHANTABILITY,
# NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should
# have received a copy of GPLv2 along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
require "katello_test_helper"
module Katello
class Api::V2::SystemsControllerTest < ActionController::TestCase
include Support::ForemanTasks::Task
def models
@system = katello_systems(:simple_server)
@errata_system = katello_systems(:errata_server)
@host_collections = katello_host_collections
@organization = get_organization
@repo = Repository.find(katello_repositories(:rhel_6_x86_64))
@content_view_environment = ContentViewEnvironment.find(katello_content_view_environments(:library_dev_view_library))
end
def permissions
@view_permission = :view_content_hosts
@create_permission = :create_content_hosts
@update_permission = :edit_content_hosts
@destroy_permission = :destroy_content_hosts
end
def setup
setup_controller_defaults_api
login_user(User.find(users(:admin)))
@request.env['HTTP_ACCEPT'] = 'application/json'
@request.env['CONTENT_TYPE'] = 'application/json'
System.any_instance.stubs(:candlepin_consumer_info).returns(:facts => {})
System.any_instance.stubs(:katello_agent_installed?).returns(true)
System.any_instance.stubs(:refresh_subscriptions).returns(true)
System.any_instance.stubs(:content_overrides).returns([])
System.any_instance.stubs(:products).returns([{:id => 1, :name => 'product', :available_content => []}])
@fake_search_service = @controller.load_search_service(Support::SearchService::FakeSearchService.new)
Katello::Package.stubs(:package_count).returns(0)
Katello::PuppetModule.stubs(:module_count).returns(0)
models
permissions
end
def test_index
get :index, :organization_id => get_organization.id
assert_response :success
assert_template 'api/v2/systems/index'
end
def test_index_errata
errata = @repo.errata.first
get :index, :organization_id => get_organization.id, :erratum_id => errata.uuid
assert_response :success
assert_template 'api/v2/systems/index'
end
def test_index_errata_applicable
@controller.load_search_service(Support::SearchService::FakeSearchService.new)
errata = @repo.errata.first
get :index, :organization_id => get_organization.id, :erratum_id => errata.uuid, :available => "false"
assert_response :success
assert_template 'api/v2/systems/index'
end
def test_index_protected
allowed_perms = [@view_permission]
denied_perms = [@create_permission, @update_permission, @destroy_permission]
assert_protected_action(:index, allowed_perms, denied_perms) do
get :index, :organization_id => @organization.id
end
end
def test_create
@controller.stubs(:sync_task).returns(true)
System.stubs(:new).returns(@system)
cp_id = @content_view_environment.cp_id
ContentViewEnvironment.expects(:find_by_cp_id!).with(cp_id).returns(@content_view_environment)
post :create, :name => "needs more tests", :environment_id => cp_id.to_s,
:organization_id => @organization.id
assert_response :success
end
def test_create_without_environment
@controller.stubs(:sync_task).returns(true)
System.stubs(:new).returns(@system)
post :create, :name => "needs more tests", :organization_id => @organization.id
assert_response :success
end
def test_index_with_system_id_only
mock = Api::V2::SystemsController.any_instance.expects(:item_search).with do |_model, _params, options|
terms = options[:filters].inject({}) { |all_terms, filter| all_terms.merge(filter[:terms]) }
terms[:environment_id] == @system.environment.id.to_s
end
mock.returns({})
get :index, :environment_id => @system.environment.id
assert_response :success
assert_template 'api/v2/systems/index'
end
def test_index_with_org_id_only
mock = Api::V2::SystemsController.any_instance.expects(:item_search).with do |_model, _params, options|
terms = options[:filters].inject({}) { |all_terms, filter| all_terms.merge(filter[:terms]) }
terms[:environment_id] == @organization.kt_environments.pluck(:id)
end
mock.returns({})
get :index, :organization_id => @organization.id
assert_response :success
assert_template 'api/v2/systems/index'
end
def test_index_with_system_id_and_org_id
mock = Api::V2::SystemsController.any_instance.expects(:item_search).with do |_model, _params, options|
terms = options[:filters].inject({}) { |all_terms, filter| all_terms.merge(filter[:terms]) }
terms[:environment_id] == [@system.environment.id]
end
mock.returns({})
get :index, :organization_id => @organization.id, :environment_id => @system.environment.id
assert_response :success
assert_template 'api/v2/systems/index'
end
def test_show
get :show, :id => @system.uuid
assert_response :success
assert_template 'api/v2/systems/show'
end
def test_show_protected
allowed_perms = [@view_permission]
denied_perms = [@create_permission, @update_permission, @destroy_permission]
assert_protected_action(:show, allowed_perms, denied_perms) do
get :show, :id => @system.uuid
end
end
def test_refresh_subscriptions
input = {
:id => @system.id
}
System.expects(:first).returns(@system)
assert_sync_task(::Actions::Katello::System::AutoAttachSubscriptions) do |sys|
sys.must_equal @system
end
put :refresh_subscriptions, input
assert_response :success
assert_template 'api/v2/systems/show'
end
def test_refresh_subscriptions_protected
allowed_perms = [@update_permission]
denied_perms = [@create_permission, @view_permission, @destroy_permission]
assert_protected_action(:refresh_subscriptions, allowed_perms, denied_perms) do
put :refresh_subscriptions, :id => @system.uuid
end
end
def test_available_host_collections
get :available_host_collections, :id => @system.uuid
assert_response :success
assert_template 'api/v2/systems/available_host_collections'
end
def test_available_host_collections_protected
allowed_perms = [@view_permission]
denied_perms = [@create_permission, @update_permission, @destroy_permission]
assert_protected_action(:available_host_collections, allowed_perms, denied_perms) do
get :available_host_collections, :id => @system.uuid
end
end
def test_errata
get :errata, :id => @errata_system.uuid
assert_response :success
assert_template 'api/v2/systems/errata'
end
def test_update
input = {
:id => @system.id,
:name => 'newname'
}
System.expects(:first).returns(@system)
@controller.expects(:system_params).returns(input)
assert_sync_task(::Actions::Katello::System::Update) do |sys, inp|
sys.must_equal @system
inp.must_equal input
end
post :update, input
assert_response :success
end
def test_errata_other_env
get :errata, :id => @errata_system.uuid, :content_view_id => @errata_system.organization.default_content_view.id,
:environment_id => @errata_system.organization.library.id
assert_response :success
assert_template 'api/v2/systems/errata'
end
end
end
| gpl-2.0 |
caronnee/pdfeditor | core/xpdf/xpdf/Function.cc | 34775 | //========================================================================
//
// Function.cc
//
// Copyright 2001-2003 Glyph & Cog, LLC
//
//========================================================================
#include <xpdf-aconf.h>
#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include "goo/gmem.h"
#include "xpdf/Object.h"
#include "xpdf/Dict.h"
#include "xpdf/Stream.h"
#include "xpdf/Error.h"
#include "xpdf/Function.h"
//------------------------------------------------------------------------
// Function
//------------------------------------------------------------------------
Function::Function() {
}
Function::~Function() {
}
Function *Function::parse(const Object *funcObj) {
Function *func;
const Dict *dict;
int funcType;
Object obj1;
if (funcObj->isStream()) {
dict = funcObj->streamGetDict();
} else if (funcObj->isDict()) {
dict = funcObj->getDict();
} else if (funcObj->isName("Identity")) {
return new IdentityFunction();
} else {
error(-1, "Expected function dictionary or stream");
return NULL;
}
if (!dict->lookup("FunctionType", &obj1)->isInt()) {
error(-1, "Function type is missing or wrong type");
obj1.free();
return NULL;
}
funcType = obj1.getInt();
obj1.free();
if (funcType == 0) {
func = new SampledFunction(funcObj, dict);
} else if (funcType == 2) {
func = new ExponentialFunction(funcObj, dict);
} else if (funcType == 3) {
func = new StitchingFunction(funcObj, dict);
} else if (funcType == 4) {
func = new PostScriptFunction(funcObj, dict);
} else {
error(-1, "Unimplemented function type (%d)", funcType);
return NULL;
}
if (!func->isOk()) {
delete func;
return NULL;
}
return func;
}
GBool Function::init(const Dict *dict) {
Object obj1, obj2;
int i;
//----- Domain
if (!dict->lookup("Domain", &obj1)->isArray()) {
error(-1, "Function is missing domain");
goto err2;
}
m = obj1.arrayGetLength() / 2;
if (m > funcMaxInputs) {
error(-1, "Functions with more than %d inputs are unsupported",
funcMaxInputs);
goto err2;
}
for (i = 0; i < m; ++i) {
obj1.arrayGet(2*i, &obj2);
if (!obj2.isNum()) {
error(-1, "Illegal value in function domain array");
goto err1;
}
domain[i][0] = obj2.getNum();
obj2.free();
obj1.arrayGet(2*i+1, &obj2);
if (!obj2.isNum()) {
error(-1, "Illegal value in function domain array");
goto err1;
}
domain[i][1] = obj2.getNum();
obj2.free();
}
obj1.free();
//----- Range
hasRange = gFalse;
n = 0;
if (dict->lookup("Range", &obj1)->isArray()) {
hasRange = gTrue;
n = obj1.arrayGetLength() / 2;
if (n > funcMaxOutputs) {
error(-1, "Functions with more than %d outputs are unsupported",
funcMaxOutputs);
goto err2;
}
for (i = 0; i < n; ++i) {
obj1.arrayGet(2*i, &obj2);
if (!obj2.isNum()) {
error(-1, "Illegal value in function range array");
goto err1;
}
range[i][0] = obj2.getNum();
obj2.free();
obj1.arrayGet(2*i+1, &obj2);
if (!obj2.isNum()) {
error(-1, "Illegal value in function range array");
goto err1;
}
range[i][1] = obj2.getNum();
obj2.free();
}
}
obj1.free();
return gTrue;
err1:
obj2.free();
err2:
obj1.free();
return gFalse;
}
//------------------------------------------------------------------------
// IdentityFunction
//------------------------------------------------------------------------
IdentityFunction::IdentityFunction() {
int i;
// fill these in with arbitrary values just in case they get used
// somewhere
m = funcMaxInputs;
n = funcMaxOutputs;
for (i = 0; i < funcMaxInputs; ++i) {
domain[i][0] = 0;
domain[i][1] = 1;
}
hasRange = gFalse;
}
IdentityFunction::~IdentityFunction() {
}
void IdentityFunction::transform(const double *in, double *out)const {
int i;
for (i = 0; i < funcMaxOutputs; ++i) {
out[i] = in[i];
}
}
//------------------------------------------------------------------------
// SampledFunction
//------------------------------------------------------------------------
SampledFunction::SampledFunction(const Object *funcObj, const Dict *dict) {
Stream *str;
int sampleBits;
double sampleMul;
Object obj1, obj2;
Guint buf, bitMask;
int bits;
Guint s;
int i;
samples = NULL;
sBuf = NULL;
ok = gFalse;
//----- initialize the generic stuff
if (!init(dict)) {
goto err1;
}
if (!hasRange) {
error(-1, "Type 0 function is missing range");
goto err1;
}
if (m > sampledFuncMaxInputs) {
error(-1, "Sampled functions with more than %d inputs are unsupported",
sampledFuncMaxInputs);
goto err1;
}
//----- buffer
sBuf = (double *)gmallocn(1 << m, sizeof(double));
//----- get the stream
if (!funcObj->isStream()) {
error(-1, "Type 0 function isn't a stream");
goto err1;
}
str = funcObj->getStream();
//----- Size
if (!dict->lookup("Size", &obj1)->isArray() ||
obj1.arrayGetLength() != m) {
error(-1, "Function has missing or invalid size array");
goto err2;
}
for (i = 0; i < m; ++i) {
obj1.arrayGet(i, &obj2);
if (!obj2.isInt()) {
error(-1, "Illegal value in function size array");
goto err3;
}
sampleSize[i] = obj2.getInt();
obj2.free();
}
obj1.free();
idxMul[0] = n;
for (i = 1; i < m; ++i) {
idxMul[i] = idxMul[i-1] * sampleSize[i-1];
}
//----- BitsPerSample
if (!dict->lookup("BitsPerSample", &obj1)->isInt()) {
error(-1, "Function has missing or invalid BitsPerSample");
goto err2;
}
sampleBits = obj1.getInt();
sampleMul = 1.0 / (pow(2.0, (double)sampleBits) - 1);
obj1.free();
//----- Encode
if (dict->lookup("Encode", &obj1)->isArray() &&
obj1.arrayGetLength() == 2*m) {
for (i = 0; i < m; ++i) {
obj1.arrayGet(2*i, &obj2);
if (!obj2.isNum()) {
error(-1, "Illegal value in function encode array");
goto err3;
}
encode[i][0] = obj2.getNum();
obj2.free();
obj1.arrayGet(2*i+1, &obj2);
if (!obj2.isNum()) {
error(-1, "Illegal value in function encode array");
goto err3;
}
encode[i][1] = obj2.getNum();
obj2.free();
}
} else {
for (i = 0; i < m; ++i) {
encode[i][0] = 0;
encode[i][1] = sampleSize[i] - 1;
}
}
obj1.free();
for (i = 0; i < m; ++i) {
inputMul[i] = (encode[i][1] - encode[i][0]) /
(domain[i][1] - domain[i][0]);
}
//----- Decode
if (dict->lookup("Decode", &obj1)->isArray() &&
obj1.arrayGetLength() == 2*n) {
for (i = 0; i < n; ++i) {
obj1.arrayGet(2*i, &obj2);
if (!obj2.isNum()) {
error(-1, "Illegal value in function decode array");
goto err3;
}
decode[i][0] = obj2.getNum();
obj2.free();
obj1.arrayGet(2*i+1, &obj2);
if (!obj2.isNum()) {
error(-1, "Illegal value in function decode array");
goto err3;
}
decode[i][1] = obj2.getNum();
obj2.free();
}
} else {
for (i = 0; i < n; ++i) {
decode[i][0] = range[i][0];
decode[i][1] = range[i][1];
}
}
obj1.free();
//----- samples
nSamples = n;
for (i = 0; i < m; ++i)
nSamples *= sampleSize[i];
samples = (double *)gmallocn(nSamples, sizeof(double));
buf = 0;
bits = 0;
bitMask = (1 << sampleBits) - 1;
str->reset();
for (i = 0; i < nSamples; ++i) {
if (sampleBits == 8) {
s = str->getChar();
} else if (sampleBits == 16) {
s = str->getChar();
s = (s << 8) + str->getChar();
} else if (sampleBits == 32) {
s = str->getChar();
s = (s << 8) + str->getChar();
s = (s << 8) + str->getChar();
s = (s << 8) + str->getChar();
} else {
while (bits < sampleBits) {
buf = (buf << 8) | (str->getChar() & 0xff);
bits += 8;
}
s = (buf >> (bits - sampleBits)) & bitMask;
bits -= sampleBits;
}
samples[i] = (double)s * sampleMul;
}
str->close();
ok = gTrue;
return;
err3:
obj2.free();
err2:
obj1.free();
err1:
return;
}
SampledFunction::~SampledFunction() {
if (samples) {
gfree(samples);
}
if (sBuf) {
gfree(sBuf);
}
}
SampledFunction::SampledFunction(const SampledFunction *func) {
memcpy(this, func, sizeof(SampledFunction));
samples = (double *)gmallocn(nSamples, sizeof(double));
memcpy(samples, func->samples, nSamples * sizeof(double));
sBuf = (double *)gmallocn(1 << m, sizeof(double));
}
void SampledFunction::transform(const double *in, double *out)const {
double x;
int e[funcMaxInputs][2];
double efrac0[funcMaxInputs];
double efrac1[funcMaxInputs];
int i, j, k, idx, t;
// map input values into sample array
for (i = 0; i < m; ++i) {
x = (in[i] - domain[i][0]) * inputMul[i] + encode[i][0];
if (x < 0) {
x = 0;
} else if (x > sampleSize[i] - 1) {
x = sampleSize[i] - 1;
}
e[i][0] = (int)x;
if ((e[i][1] = e[i][0] + 1) >= sampleSize[i]) {
// this happens if in[i] = domain[i][1]
e[i][1] = e[i][0];
}
efrac1[i] = x - e[i][0];
efrac0[i] = 1 - efrac1[i];
}
// for each output, do m-linear interpolation
for (i = 0; i < n; ++i) {
// pull 2^m values out of the sample array
for (j = 0; j < (1<<m); ++j) {
idx = i;
for (k = 0, t = j; k < m; ++k, t >>= 1) {
idx += idxMul[k] * (e[k][t & 1]);
}
if (idx >= 0 && idx < nSamples) {
sBuf[j] = samples[idx];
} else {
sBuf[j] = 0;
}
}
// do m sets of interpolations
for (j = 0, t = (1<<m); j < m; ++j, t >>= 1) {
for (k = 0; k < t; k += 2) {
sBuf[k >> 1] = efrac0[j] * sBuf[k] + efrac1[j] * sBuf[k+1];
}
}
// map output value to range
out[i] = sBuf[0] * (decode[i][1] - decode[i][0]) + decode[i][0];
if (out[i] < range[i][0]) {
out[i] = range[i][0];
} else if (out[i] > range[i][1]) {
out[i] = range[i][1];
}
}
}
//------------------------------------------------------------------------
// ExponentialFunction
//------------------------------------------------------------------------
ExponentialFunction::ExponentialFunction(const Object *funcObj, const Dict *dict) {
Object obj1, obj2;
int i;
ok = gFalse;
//----- initialize the generic stuff
if (!init(dict)) {
goto err1;
}
if (m != 1) {
error(-1, "Exponential function with more than one input");
goto err1;
}
//----- C0
if (dict->lookup("C0", &obj1)->isArray()) {
if (hasRange && obj1.arrayGetLength() != n) {
error(-1, "Function's C0 array is wrong length");
goto err2;
}
n = obj1.arrayGetLength();
for (i = 0; i < n; ++i) {
obj1.arrayGet(i, &obj2);
if (!obj2.isNum()) {
error(-1, "Illegal value in function C0 array");
goto err3;
}
c0[i] = obj2.getNum();
obj2.free();
}
} else {
if (hasRange && n != 1) {
error(-1, "Function's C0 array is wrong length");
goto err2;
}
n = 1;
c0[0] = 0;
}
obj1.free();
//----- C1
if (dict->lookup("C1", &obj1)->isArray()) {
if (obj1.arrayGetLength() != n) {
error(-1, "Function's C1 array is wrong length");
goto err2;
}
for (i = 0; i < n; ++i) {
obj1.arrayGet(i, &obj2);
if (!obj2.isNum()) {
error(-1, "Illegal value in function C1 array");
goto err3;
}
c1[i] = obj2.getNum();
obj2.free();
}
} else {
if (n != 1) {
error(-1, "Function's C1 array is wrong length");
goto err2;
}
c1[0] = 1;
}
obj1.free();
//----- N (exponent)
if (!dict->lookup("N", &obj1)->isNum()) {
error(-1, "Function has missing or invalid N");
goto err2;
}
e = obj1.getNum();
obj1.free();
ok = gTrue;
return;
err3:
obj2.free();
err2:
obj1.free();
err1:
return;
}
ExponentialFunction::~ExponentialFunction() {
}
ExponentialFunction::ExponentialFunction(const ExponentialFunction *func) {
memcpy(this, func, sizeof(ExponentialFunction));
}
void ExponentialFunction::transform(const double *in, double *out)const {
double x;
int i;
if (in[0] < domain[0][0]) {
x = domain[0][0];
} else if (in[0] > domain[0][1]) {
x = domain[0][1];
} else {
x = in[0];
}
for (i = 0; i < n; ++i) {
out[i] = c0[i] + pow(x, e) * (c1[i] - c0[i]);
if (hasRange) {
if (out[i] < range[i][0]) {
out[i] = range[i][0];
} else if (out[i] > range[i][1]) {
out[i] = range[i][1];
}
}
}
return;
}
//------------------------------------------------------------------------
// StitchingFunction
//------------------------------------------------------------------------
StitchingFunction::StitchingFunction(const Object *funcObj, const Dict *dict) {
Object obj1, obj2;
int i;
ok = gFalse;
funcs = NULL;
bounds = NULL;
encode = NULL;
scale = NULL;
//----- initialize the generic stuff
if (!init(dict)) {
goto err1;
}
if (m != 1) {
error(-1, "Stitching function with more than one input");
goto err1;
}
//----- Functions
if (!dict->lookup("Functions", &obj1)->isArray()) {
error(-1, "Missing 'Functions' entry in stitching function");
goto err1;
}
k = obj1.arrayGetLength();
funcs = (Function **)gmallocn(k, sizeof(Function *));
bounds = (double *)gmallocn(k + 1, sizeof(double));
encode = (double *)gmallocn(2 * k, sizeof(double));
scale = (double *)gmallocn(k, sizeof(double));
for (i = 0; i < k; ++i) {
funcs[i] = NULL;
}
for (i = 0; i < k; ++i) {
if (!(funcs[i] = Function::parse(obj1.arrayGet(i, &obj2)))) {
goto err2;
}
if (i > 0 && (funcs[i]->getInputSize() != 1 ||
funcs[i]->getOutputSize() != funcs[0]->getOutputSize())) {
error(-1, "Incompatible subfunctions in stitching function");
goto err2;
}
obj2.free();
}
obj1.free();
//----- Bounds
if (!dict->lookup("Bounds", &obj1)->isArray() ||
obj1.arrayGetLength() != k - 1) {
error(-1, "Missing or invalid 'Bounds' entry in stitching function");
goto err1;
}
bounds[0] = domain[0][0];
for (i = 1; i < k; ++i) {
if (!obj1.arrayGet(i - 1, &obj2)->isNum()) {
error(-1, "Invalid type in 'Bounds' array in stitching function");
goto err2;
}
bounds[i] = obj2.getNum();
obj2.free();
}
bounds[k] = domain[0][1];
obj1.free();
//----- Encode
if (!dict->lookup("Encode", &obj1)->isArray() ||
obj1.arrayGetLength() != 2 * k) {
error(-1, "Missing or invalid 'Encode' entry in stitching function");
goto err1;
}
for (i = 0; i < 2 * k; ++i) {
if (!obj1.arrayGet(i, &obj2)->isNum()) {
error(-1, "Invalid type in 'Encode' array in stitching function");
goto err2;
}
encode[i] = obj2.getNum();
obj2.free();
}
obj1.free();
//----- pre-compute the scale factors
for (i = 0; i < k; ++i) {
if (bounds[i] == bounds[i+1]) {
// avoid a divide-by-zero -- in this situation, function i will
// never be used anyway
scale[i] = 0;
} else {
scale[i] = (encode[2*i+1] - encode[2*i]) / (bounds[i+1] - bounds[i]);
}
}
ok = gTrue;
return;
err2:
obj2.free();
err1:
obj1.free();
}
StitchingFunction::StitchingFunction(const StitchingFunction *func) {
int i;
k = func->k;
funcs = (Function **)gmallocn(k, sizeof(Function *));
for (i = 0; i < k; ++i) {
funcs[i] = func->funcs[i]->copy();
}
bounds = (double *)gmallocn(k + 1, sizeof(double));
memcpy(bounds, func->bounds, (k + 1) * sizeof(double));
encode = (double *)gmallocn(2 * k, sizeof(double));
memcpy(encode, func->encode, 2 * k * sizeof(double));
scale = (double *)gmallocn(k, sizeof(double));
memcpy(scale, func->scale, k * sizeof(double));
ok = gTrue;
}
StitchingFunction::~StitchingFunction() {
int i;
if (funcs) {
for (i = 0; i < k; ++i) {
if (funcs[i]) {
delete funcs[i];
}
}
}
gfree(funcs);
gfree(bounds);
gfree(encode);
gfree(scale);
}
void StitchingFunction::transform(const double *in, double *out)const {
double x;
int i;
if (in[0] < domain[0][0]) {
x = domain[0][0];
} else if (in[0] > domain[0][1]) {
x = domain[0][1];
} else {
x = in[0];
}
for (i = 0; i < k - 1; ++i) {
if (x < bounds[i+1]) {
break;
}
}
x = encode[2*i] + (x - bounds[i]) * scale[i];
funcs[i]->transform(&x, out);
}
//------------------------------------------------------------------------
// PostScriptFunction
//------------------------------------------------------------------------
enum PSOp {
psOpAbs,
psOpAdd,
psOpAnd,
psOpAtan,
psOpBitshift,
psOpCeiling,
psOpCopy,
psOpCos,
psOpCvi,
psOpCvr,
psOpDiv,
psOpDup,
psOpEq,
psOpExch,
psOpExp,
psOpFalse,
psOpFloor,
psOpGe,
psOpGt,
psOpIdiv,
psOpIndex,
psOpLe,
psOpLn,
psOpLog,
psOpLt,
psOpMod,
psOpMul,
psOpNe,
psOpNeg,
psOpNot,
psOpOr,
psOpPop,
psOpRoll,
psOpRound,
psOpSin,
psOpSqrt,
psOpSub,
psOpTrue,
psOpTruncate,
psOpXor,
psOpIf,
psOpIfelse,
psOpReturn
};
// Note: 'if' and 'ifelse' are parsed separately.
// The rest are listed here in alphabetical order.
// The index in this table is equivalent to the entry in PSOp.
char *psOpNames[] = {
"abs",
"add",
"and",
"atan",
"bitshift",
"ceiling",
"copy",
"cos",
"cvi",
"cvr",
"div",
"dup",
"eq",
"exch",
"exp",
"false",
"floor",
"ge",
"gt",
"idiv",
"index",
"le",
"ln",
"log",
"lt",
"mod",
"mul",
"ne",
"neg",
"not",
"or",
"pop",
"roll",
"round",
"sin",
"sqrt",
"sub",
"true",
"truncate",
"xor"
};
#define nPSOps (sizeof(psOpNames) / sizeof(char *))
enum PSObjectType {
psBool,
psInt,
psReal,
psOperator,
psBlock
};
// In the code array, 'if'/'ifelse' operators take up three slots
// plus space for the code in the subclause(s).
//
// +---------------------------------+
// | psOperator: psOpIf / psOpIfelse |
// +---------------------------------+
// | psBlock: ptr=<A> |
// +---------------------------------+
// | psBlock: ptr=<B> |
// +---------------------------------+
// | if clause |
// | ... |
// | psOperator: psOpReturn |
// +---------------------------------+
// <A> | else clause |
// | ... |
// | psOperator: psOpReturn |
// +---------------------------------+
// <B> | ... |
//
// For 'if', pointer <A> is present in the code stream but unused.
struct PSObject {
PSObjectType type;
union {
GBool booln; // boolean (stack only)
int intg; // integer (stack and code)
double real; // real (stack and code)
PSOp op; // operator (code only)
int blk; // if/ifelse block pointer (code only)
};
};
#define psStackSize 100
class PSStack {
public:
PSStack() { sp = psStackSize; }
void pushBool(GBool booln);
void pushInt(int intg);
void pushReal(double real);
GBool popBool();
int popInt();
double popNum();
GBool empty() { return sp == psStackSize; }
GBool topIsInt() { return sp < psStackSize && stack[sp].type == psInt; }
GBool topTwoAreInts()
{ return sp < psStackSize - 1 &&
stack[sp].type == psInt &&
stack[sp+1].type == psInt; }
GBool topIsReal() { return sp < psStackSize && stack[sp].type == psReal; }
GBool topTwoAreNums()
{ return sp < psStackSize - 1 &&
(stack[sp].type == psInt || stack[sp].type == psReal) &&
(stack[sp+1].type == psInt || stack[sp+1].type == psReal); }
void copy(int n);
void roll(int n, int j);
void index(int i);
void pop();
private:
GBool checkOverflow(int n = 1);
GBool checkUnderflow();
GBool checkType(PSObjectType t1, PSObjectType t2);
PSObject stack[psStackSize];
int sp;
};
GBool PSStack::checkOverflow(int n) {
if (sp - n < 0) {
error(-1, "Stack overflow in PostScript function");
return gFalse;
}
return gTrue;
}
GBool PSStack::checkUnderflow() {
if (sp == psStackSize) {
error(-1, "Stack underflow in PostScript function");
return gFalse;
}
return gTrue;
}
GBool PSStack::checkType(PSObjectType t1, PSObjectType t2) {
if (stack[sp].type != t1 && stack[sp].type != t2) {
error(-1, "Type mismatch in PostScript function");
return gFalse;
}
return gTrue;
}
void PSStack::pushBool(GBool booln) {
if (checkOverflow()) {
stack[--sp].type = psBool;
stack[sp].booln = booln;
}
}
void PSStack::pushInt(int intg) {
if (checkOverflow()) {
stack[--sp].type = psInt;
stack[sp].intg = intg;
}
}
void PSStack::pushReal(double real) {
if (checkOverflow()) {
stack[--sp].type = psReal;
stack[sp].real = real;
}
}
GBool PSStack::popBool() {
if (checkUnderflow() && checkType(psBool, psBool)) {
return stack[sp++].booln;
}
return gFalse;
}
int PSStack::popInt() {
if (checkUnderflow() && checkType(psInt, psInt)) {
return stack[sp++].intg;
}
return 0;
}
double PSStack::popNum() {
double ret;
if (checkUnderflow() && checkType(psInt, psReal)) {
ret = (stack[sp].type == psInt) ? (double)stack[sp].intg : stack[sp].real;
++sp;
return ret;
}
return 0;
}
void PSStack::copy(int n) {
int i;
if (sp + n > psStackSize) {
error(-1, "Stack underflow in PostScript function");
return;
}
if (!checkOverflow(n)) {
return;
}
for (i = sp + n - 1; i >= sp; --i) {
stack[i - n] = stack[i];
}
sp -= n;
}
void PSStack::roll(int n, int j) {
PSObject obj;
int i, k;
if (j >= 0) {
j %= n;
} else {
j = -j % n;
if (j != 0) {
j = n - j;
}
}
if (n <= 0 || j == 0) {
return;
}
for (i = 0; i < j; ++i) {
obj = stack[sp];
for (k = sp; k < sp + n - 1; ++k) {
stack[k] = stack[k+1];
}
stack[sp + n - 1] = obj;
}
}
void PSStack::index(int i) {
if (!checkOverflow()) {
return;
}
--sp;
stack[sp] = stack[sp + 1 + i];
}
void PSStack::pop() {
if (!checkUnderflow()) {
return;
}
++sp;
}
PostScriptFunction::PostScriptFunction(const Object *funcObj, const Dict *dict) {
Stream *str;
int codePtr;
GString *tok;
code = NULL;
codeSize = 0;
ok = gFalse;
//----- initialize the generic stuff
if (!init(dict)) {
goto err1;
}
if (!hasRange) {
error(-1, "Type 4 function is missing range");
goto err1;
}
//----- get the stream
if (!funcObj->isStream()) {
error(-1, "Type 4 function isn't a stream");
goto err1;
}
str = funcObj->getStream();
//----- parse the function
codeString = new GString();
str->reset();
if (!(tok = getToken(str)) || tok->cmp("{")) {
error(-1, "Expected '{' at start of PostScript function");
if (tok) {
delete tok;
}
goto err1;
}
delete tok;
codePtr = 0;
if (!parseCode(str, &codePtr)) {
goto err2;
}
str->close();
ok = gTrue;
err2:
str->close();
err1:
return;
}
PostScriptFunction::PostScriptFunction(const PostScriptFunction *func) {
memcpy(this, func, sizeof(PostScriptFunction));
code = (PSObject *)gmallocn(codeSize, sizeof(PSObject));
memcpy(code, func->code, codeSize * sizeof(PSObject));
codeString = func->codeString->copy();
}
PostScriptFunction::~PostScriptFunction() {
gfree(code);
delete codeString;
}
void PostScriptFunction::transform(const double *in, double *out)const {
PSStack *stack;
int i;
stack = new PSStack();
for (i = 0; i < m; ++i) {
//~ may need to check for integers here
stack->pushReal(in[i]);
}
exec(stack, 0);
for (i = n - 1; i >= 0; --i) {
out[i] = stack->popNum();
if (out[i] < range[i][0]) {
out[i] = range[i][0];
} else if (out[i] > range[i][1]) {
out[i] = range[i][1];
}
}
// if (!stack->empty()) {
// error(-1, "Extra values on stack at end of PostScript function");
// }
delete stack;
}
GBool PostScriptFunction::parseCode(Stream *str, int *codePtr) {
GString *tok;
char *p;
GBool isReal;
int opPtr, elsePtr;
int a, b, mid, cmp;
while (1) {
if (!(tok = getToken(str))) {
error(-1, "Unexpected end of PostScript function stream");
return gFalse;
}
p = tok->getCString();
if (isdigit((unsigned char)*p) || *p == '.' || *p == '-') {
isReal = gFalse;
for (++p; *p; ++p) {
if (*p == '.') {
isReal = gTrue;
break;
}
}
resizeCode(*codePtr);
if (isReal) {
code[*codePtr].type = psReal;
code[*codePtr].real = atof(tok->getCString());
} else {
code[*codePtr].type = psInt;
code[*codePtr].intg = atoi(tok->getCString());
}
++*codePtr;
delete tok;
} else if (!tok->cmp("{")) {
delete tok;
opPtr = *codePtr;
*codePtr += 3;
resizeCode(opPtr + 2);
if (!parseCode(str, codePtr)) {
return gFalse;
}
if (!(tok = getToken(str))) {
error(-1, "Unexpected end of PostScript function stream");
return gFalse;
}
if (!tok->cmp("{")) {
elsePtr = *codePtr;
if (!parseCode(str, codePtr)) {
return gFalse;
}
delete tok;
if (!(tok = getToken(str))) {
error(-1, "Unexpected end of PostScript function stream");
return gFalse;
}
} else {
elsePtr = -1;
}
if (!tok->cmp("if")) {
if (elsePtr >= 0) {
error(-1, "Got 'if' operator with two blocks in PostScript function");
return gFalse;
}
code[opPtr].type = psOperator;
code[opPtr].op = psOpIf;
code[opPtr+2].type = psBlock;
code[opPtr+2].blk = *codePtr;
} else if (!tok->cmp("ifelse")) {
if (elsePtr < 0) {
error(-1, "Got 'ifelse' operator with one blocks in PostScript function");
return gFalse;
}
code[opPtr].type = psOperator;
code[opPtr].op = psOpIfelse;
code[opPtr+1].type = psBlock;
code[opPtr+1].blk = elsePtr;
code[opPtr+2].type = psBlock;
code[opPtr+2].blk = *codePtr;
} else {
error(-1, "Expected if/ifelse operator in PostScript function");
delete tok;
return gFalse;
}
delete tok;
} else if (!tok->cmp("}")) {
delete tok;
resizeCode(*codePtr);
code[*codePtr].type = psOperator;
code[*codePtr].op = psOpReturn;
++*codePtr;
break;
} else {
a = -1;
b = nPSOps;
// invariant: psOpNames[a] < tok < psOpNames[b]
while (b - a > 1) {
mid = (a + b) / 2;
cmp = tok->cmp(psOpNames[mid]);
if (cmp > 0) {
a = mid;
} else if (cmp < 0) {
b = mid;
} else {
a = b = mid;
}
}
if (cmp != 0) {
error(-1, "Unknown operator '%s' in PostScript function",
tok->getCString());
delete tok;
return gFalse;
}
delete tok;
resizeCode(*codePtr);
code[*codePtr].type = psOperator;
code[*codePtr].op = (PSOp)a;
++*codePtr;
}
}
return gTrue;
}
GString *PostScriptFunction::getToken(Stream *str) {
GString *s;
int c;
GBool comment;
s = new GString();
comment = gFalse;
while (1) {
if ((c = str->getChar()) == EOF) {
break;
}
codeString->append(c);
if (comment) {
if (c == '\x0a' || c == '\x0d') {
comment = gFalse;
}
} else if (c == '%') {
comment = gTrue;
} else if (!isspace((unsigned char)c)) {
break;
}
}
if (c == '{' || c == '}') {
s->append((char)c);
} else if (isdigit((unsigned char)c) || c == '.' || c == '-') {
while (1) {
s->append((char)c);
c = str->lookChar();
if (c == EOF || !(isdigit((unsigned char)c) || c == '.' || c == '-')) {
break;
}
str->getChar();
codeString->append(c);
}
} else {
while (1) {
s->append((char)c);
c = str->lookChar();
if (c == EOF || !isalnum((unsigned char)c)) {
break;
}
str->getChar();
codeString->append(c);
}
}
return s;
}
void PostScriptFunction::resizeCode(int newSize) {
if (newSize >= codeSize) {
codeSize += 64;
code = (PSObject *)greallocn(code, codeSize, sizeof(PSObject));
}
}
void PostScriptFunction::exec(PSStack *stack, int codePtr)const {
int i1, i2;
double r1, r2;
GBool b1, b2;
while (1) {
switch (code[codePtr].type) {
case psInt:
stack->pushInt(code[codePtr++].intg);
break;
case psReal:
stack->pushReal(code[codePtr++].real);
break;
case psOperator:
switch (code[codePtr++].op) {
case psOpAbs:
if (stack->topIsInt()) {
stack->pushInt(abs(stack->popInt()));
} else {
stack->pushReal(fabs(stack->popNum()));
}
break;
case psOpAdd:
if (stack->topTwoAreInts()) {
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushInt(i1 + i2);
} else {
r2 = stack->popNum();
r1 = stack->popNum();
stack->pushReal(r1 + r2);
}
break;
case psOpAnd:
if (stack->topTwoAreInts()) {
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushInt(i1 & i2);
} else {
b2 = stack->popBool();
b1 = stack->popBool();
stack->pushBool(b1 && b2);
}
break;
case psOpAtan:
r2 = stack->popNum();
r1 = stack->popNum();
stack->pushReal(atan2(r1, r2));
break;
case psOpBitshift:
i2 = stack->popInt();
i1 = stack->popInt();
if (i2 > 0) {
stack->pushInt(i1 << i2);
} else if (i2 < 0) {
stack->pushInt((int)((Guint)i1 >> i2));
} else {
stack->pushInt(i1);
}
break;
case psOpCeiling:
if (!stack->topIsInt()) {
stack->pushReal(ceil(stack->popNum()));
}
break;
case psOpCopy:
stack->copy(stack->popInt());
break;
case psOpCos:
stack->pushReal(cos(stack->popNum()));
break;
case psOpCvi:
if (!stack->topIsInt()) {
stack->pushInt((int)stack->popNum());
}
break;
case psOpCvr:
if (!stack->topIsReal()) {
stack->pushReal(stack->popNum());
}
break;
case psOpDiv:
r2 = stack->popNum();
r1 = stack->popNum();
stack->pushReal(r1 / r2);
break;
case psOpDup:
stack->copy(1);
break;
case psOpEq:
if (stack->topTwoAreInts()) {
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushBool(i1 == i2);
} else if (stack->topTwoAreNums()) {
r2 = stack->popNum();
r1 = stack->popNum();
stack->pushBool(r1 == r2);
} else {
b2 = stack->popBool();
b1 = stack->popBool();
stack->pushBool(b1 == b2);
}
break;
case psOpExch:
stack->roll(2, 1);
break;
case psOpExp:
r2 = stack->popNum();
r1 = stack->popNum();
stack->pushReal(pow(r1, r2));
break;
case psOpFalse:
stack->pushBool(gFalse);
break;
case psOpFloor:
if (!stack->topIsInt()) {
stack->pushReal(floor(stack->popNum()));
}
break;
case psOpGe:
if (stack->topTwoAreInts()) {
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushBool(i1 >= i2);
} else {
r2 = stack->popNum();
r1 = stack->popNum();
stack->pushBool(r1 >= r2);
}
break;
case psOpGt:
if (stack->topTwoAreInts()) {
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushBool(i1 > i2);
} else {
r2 = stack->popNum();
r1 = stack->popNum();
stack->pushBool(r1 > r2);
}
break;
case psOpIdiv:
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushInt(i1 / i2);
break;
case psOpIndex:
stack->index(stack->popInt());
break;
case psOpLe:
if (stack->topTwoAreInts()) {
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushBool(i1 <= i2);
} else {
r2 = stack->popNum();
r1 = stack->popNum();
stack->pushBool(r1 <= r2);
}
break;
case psOpLn:
stack->pushReal(log(stack->popNum()));
break;
case psOpLog:
stack->pushReal(log10(stack->popNum()));
break;
case psOpLt:
if (stack->topTwoAreInts()) {
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushBool(i1 < i2);
} else {
r2 = stack->popNum();
r1 = stack->popNum();
stack->pushBool(r1 < r2);
}
break;
case psOpMod:
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushInt(i1 % i2);
break;
case psOpMul:
if (stack->topTwoAreInts()) {
i2 = stack->popInt();
i1 = stack->popInt();
//~ should check for out-of-range, and push a real instead
stack->pushInt(i1 * i2);
} else {
r2 = stack->popNum();
r1 = stack->popNum();
stack->pushReal(r1 * r2);
}
break;
case psOpNe:
if (stack->topTwoAreInts()) {
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushBool(i1 != i2);
} else if (stack->topTwoAreNums()) {
r2 = stack->popNum();
r1 = stack->popNum();
stack->pushBool(r1 != r2);
} else {
b2 = stack->popBool();
b1 = stack->popBool();
stack->pushBool(b1 != b2);
}
break;
case psOpNeg:
if (stack->topIsInt()) {
stack->pushInt(-stack->popInt());
} else {
stack->pushReal(-stack->popNum());
}
break;
case psOpNot:
if (stack->topIsInt()) {
stack->pushInt(~stack->popInt());
} else {
stack->pushBool(!stack->popBool());
}
break;
case psOpOr:
if (stack->topTwoAreInts()) {
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushInt(i1 | i2);
} else {
b2 = stack->popBool();
b1 = stack->popBool();
stack->pushBool(b1 || b2);
}
break;
case psOpPop:
stack->pop();
break;
case psOpRoll:
i2 = stack->popInt();
i1 = stack->popInt();
stack->roll(i1, i2);
break;
case psOpRound:
if (!stack->topIsInt()) {
r1 = stack->popNum();
stack->pushReal((r1 >= 0) ? floor(r1 + 0.5) : ceil(r1 - 0.5));
}
break;
case psOpSin:
stack->pushReal(sin(stack->popNum()));
break;
case psOpSqrt:
stack->pushReal(sqrt(stack->popNum()));
break;
case psOpSub:
if (stack->topTwoAreInts()) {
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushInt(i1 - i2);
} else {
r2 = stack->popNum();
r1 = stack->popNum();
stack->pushReal(r1 - r2);
}
break;
case psOpTrue:
stack->pushBool(gTrue);
break;
case psOpTruncate:
if (!stack->topIsInt()) {
r1 = stack->popNum();
stack->pushReal((r1 >= 0) ? floor(r1) : ceil(r1));
}
break;
case psOpXor:
if (stack->topTwoAreInts()) {
i2 = stack->popInt();
i1 = stack->popInt();
stack->pushInt(i1 ^ i2);
} else {
b2 = stack->popBool();
b1 = stack->popBool();
stack->pushBool(b1 ^ b2);
}
break;
case psOpIf:
b1 = stack->popBool();
if (b1) {
exec(stack, codePtr + 2);
}
codePtr = code[codePtr + 1].blk;
break;
case psOpIfelse:
b1 = stack->popBool();
if (b1) {
exec(stack, codePtr + 2);
} else {
exec(stack, code[codePtr].blk);
}
codePtr = code[codePtr + 1].blk;
break;
case psOpReturn:
return;
}
break;
default:
error(-1, "Internal: bad object in PostScript function code");
break;
}
}
}
| gpl-2.0 |
tallythemes/tally-framework | core/assets/js/theme.js | 1798 | jQuery(document).ready(function($) {
$("#nav>div>ul").tinyNav();
if(jQuery().fitVids) {
$(".digita-video").fitVids();
}
if(jQuery().prettyPhoto){
$("a[rel^='prettyPhoto']").prettyPhoto({ deeplinking: false, social_tools : false });
}
$(".blog_entry:last").addClass("last");
new WOW().init();
});
(function( $ ){
$.fn.digita_stickyMenu = function( options ) {
var $this = this,
defaults = {
'left' : 0,
'top' : 0,
'menu_offset_top' : $this.offset().top
},
settings = $.extend({}, defaults, options);
$(window).on('scroll.stickyMenu', function(){
if ($(window).scrollTop() > settings.menu_offset_top)
{
/*$this.css({
'position': 'fixed',
'top':settings.left,
'left':settings.top,
'zIndex':9999,
'width':'100%'
});*/
$this.addClass('stickyMenu');
}
else
{
/*$this.css({
'position': 'relative',
}); */
$this.removeClass('stickyMenu');
}
});
return $this;
};
})(jQuery);
jQuery(document).ready(function($) {
$('#header').digita_stickyMenu();
});
jQuery(function($) {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
| gpl-2.0 |
pivotal/tcs-hq-management-plugin | com.springsource.hq.plugin.tcserver.serverconfig.domain/src/test/java/com/springsource/hq/plugin/tcserver/serverconfig/services/connector/ConnectorTests.java | 3745 | /*
* Copyright (C) 2009-2015 Pivotal Software, Inc
*
* This program is is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.springsource.hq.plugin.tcserver.serverconfig.services.connector;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.springframework.validation.BeanPropertyBindingResult;
import com.springsource.hq.plugin.tcserver.serverconfig.Hierarchical;
import com.springsource.hq.plugin.tcserver.serverconfig.Identity;
import com.springsource.hq.plugin.tcserver.serverconfig.Settings;
import com.springsource.hq.plugin.tcserver.serverconfig.services.Service;
/**
* Unit tests for {@link Connector}
*/
public class ConnectorTests {
private Connector connector;
@Before
public void setup() {
connector = new MockConnector();
}
@Test
public void testHierarchical() {
assertTrue(connector instanceof Hierarchical);
}
@Test
public void testParent_null() {
assertNull(connector.parent());
}
@Test
public void testParent_reflective() {
Service service = new Service();
connector.setParent(service);
assertSame(service, connector.parent());
}
@Test
public void testApplyParentToChildren() {
connector.applyParentToChildren();
}
@Test
public void testIdentity() {
assertTrue(connector instanceof Identity);
}
@Test
public void testGetId_null() {
assertNull(connector.getId());
}
@Test
public void testGetId_reflective() {
String id = "testId";
connector.setId(id);
assertEquals(id, connector.getId());
}
@Test
public void testGetHumanId() {
connector.setAddress("the/address");
connector.setPort(8080L);
assertEquals("theaddress:8080", connector.getHumanId());
}
@Test
public void testGetHumanId_noAddress() {
connector.setPort(8080L);
assertEquals(":8080", connector.getHumanId());
}
@Test
public void validateWithTwoConnectorsWithNullPorts() {
connector.setScheme("http");
Service service = new MockService();
MockSettings settings = new MockSettings();
settings.getServices().add(service);
service.setParent(settings);
service.getConnectors().add(connector);
connector.setParent(service);
Connector connector2 = new MockConnector();
connector2.setScheme("https");
service.getConnectors().add(connector2);
connector.setParent(service);
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(connector, "connector");
connector.validate(connector, errors);
assertEquals(1, errors.getErrorCount());
assertEquals(1, errors.getFieldErrorCount("port"));
}
private class MockConnector extends Connector {
}
private class MockService extends Service {
}
private class MockSettings extends Settings {
}
}
| gpl-2.0 |
mekolat/ManaPlus | src/net/ea/buysellhandler.cpp | 1297 | /*
* The ManaPlus Client
* Copyright (C) 2004-2009 The Mana World Development Team
* Copyright (C) 2009-2010 The Mana Developers
* Copyright (C) 2011-2018 The ManaPlus Developers
*
* This file is part of The ManaPlus Client.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "net/ea/buysellhandler.h"
#include "net/ea/buysellrecv.h"
#include "debug.h"
namespace Ea
{
BuySellHandler::BuySellHandler()
{
BuySellRecv::mNpcId = BeingId_zero;
BuySellRecv::mBuyDialog = nullptr;
}
void BuySellHandler::cleanDialogReference(const BuyDialog *const dialog) const
{
if (BuySellRecv::mBuyDialog == dialog)
BuySellRecv::mBuyDialog = nullptr;
}
} // namespace Ea
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/ServerHandshaker/AnonCipherWithWantClientAuth.java | 8224 | /*
* Copyright 2001-2002 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 4392475
* @summary Calling setWantClientAuth(true) disables anonymous suites
* @run main/timeout=180 AnonCipherWithWantClientAuth
*/
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class AnonCipherWithWantClientAuth {
/*
* =============================================================
* Set the various variables needed for the tests, then
* specify what tests to run on each side.
*/
/*
* Should we run the client or server in a separate thread?
* Both sides can throw exceptions, but do you have a preference
* as to which side should be the main thread.
*/
static boolean separateServerThread = false;
/*
* Where do we find the keystores?
*/
static String pathToStores = "../../../../../../../etc";
static String keyStoreFile = "keystore";
static String trustStoreFile = "truststore";
static String passwd = "passphrase";
/*
* Is the server ready to serve?
*/
volatile static boolean serverReady = false;
/*
* Turn on SSL debugging?
*/
static boolean debug = false;
/*
* If the client or server is doing some kind of object creation
* that the other side depends on, and that thread prematurely
* exits, you may experience a hang. The test harness will
* terminate all hung threads after its timeout has expired,
* currently 3 minutes by default, but you might try to be
* smart about it....
*/
/*
* Define the server side of the test.
*
* If the server prematurely exits, serverReady will be set to true
* to avoid infinite hangs.
*/
void doServerSide() throws Exception {
SSLServerSocketFactory sslssf =
(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslServerSocket =
(SSLServerSocket) sslssf.createServerSocket(serverPort);
serverPort = sslServerSocket.getLocalPort();
String ciphers[]={"SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DH_anon_EXPORT_WITH_RC4_40_MD5",
"SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"};
sslServerSocket.setEnabledCipherSuites(ciphers);
sslServerSocket.setWantClientAuth(true);
/*
* Signal Client, we're ready for his connect.
*/
serverReady = true;
SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
InputStream sslIS = sslSocket.getInputStream();
OutputStream sslOS = sslSocket.getOutputStream();
sslIS.read();
sslOS.write(85);
sslOS.flush();
sslSocket.close();
}
/*
* Define the client side of the test.
*
* If the server prematurely exits, serverReady will be set to true
* to avoid infinite hangs.
*/
void doClientSide() throws Exception {
/*
* Wait for server to get started.
*/
while (!serverReady) {
Thread.sleep(50);
}
SSLSocketFactory sslsf =
(SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket)
sslsf.createSocket("localhost", serverPort);
String ciphers[] = {"SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DH_anon_EXPORT_WITH_RC4_40_MD5"};
sslSocket.setEnabledCipherSuites(ciphers);
sslSocket.setUseClientMode(true);
InputStream sslIS = sslSocket.getInputStream();
OutputStream sslOS = sslSocket.getOutputStream();
sslOS.write(280);
sslOS.flush();
sslIS.read();
sslSocket.close();
}
/*
* =============================================================
* The remainder is just support stuff
*/
// use any free port by default
volatile int serverPort = 0;
volatile Exception serverException = null;
volatile Exception clientException = null;
public static void main(String[] args) throws Exception {
String keyFilename =
System.getProperty("test.src", "./") + "/" + pathToStores +
"/" + keyStoreFile;
String trustFilename =
System.getProperty("test.src", "./") + "/" + pathToStores +
"/" + trustStoreFile;
System.setProperty("javax.net.ssl.keyStore", keyFilename);
System.setProperty("javax.net.ssl.keyStorePassword", passwd);
System.setProperty("javax.net.ssl.trustStore", trustFilename);
System.setProperty("javax.net.ssl.trustStorePassword", passwd);
if (debug)
System.setProperty("javax.net.debug", "all");
/*
* Start the tests.
*/
new AnonCipherWithWantClientAuth();
}
Thread clientThread = null;
Thread serverThread = null;
/*
* Primary constructor, used to drive remainder of the test.
*
* Fork off the other side, then do your work.
*/
AnonCipherWithWantClientAuth () throws Exception {
if (separateServerThread) {
startServer(true);
startClient(false);
} else {
startClient(true);
startServer(false);
}
/*
* Wait for other side to close down.
*/
if (separateServerThread) {
serverThread.join();
} else {
clientThread.join();
}
/*
* When we get here, the test is pretty much over.
*
* If the main thread excepted, that propagates back
* immediately. If the other thread threw an exception, we
* should report back.
*/
if (serverException != null)
throw serverException;
if (clientException != null)
throw clientException;
}
void startServer(boolean newThread) throws Exception {
if (newThread) {
serverThread = new Thread() {
public void run() {
try {
doServerSide();
} catch (Exception e) {
/*
* Our server thread just died.
*/
System.err.println("Server died...");
serverReady = true;
serverException = e;
}
}
};
serverThread.start();
} else {
doServerSide();
}
}
void startClient(boolean newThread) throws Exception {
if (newThread) {
clientThread = new Thread() {
public void run() {
try {
doClientSide();
} catch (Exception e) {
/*
* Our client thread just died.
*/
System.err.println("Client died...");
clientException = e;
}
}
};
clientThread.start();
} else {
doClientSide();
}
}
}
| gpl-2.0 |
sh01/liasis | src/liasis/crypto.py | 2750 | #!/usr/bin/env python
#Copyright 2008 Sebastian Hagen
# This file is part of liasis.
#
# liasis is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# liasis is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ARC4 implementation, derives from description on
# <http://en.wikipedia.org/wiki/ARC4>
class ARC4:
def __init__(self, key:bytes):
"""Initialize new ARC4 instance"""
self._S = S = bytearray(range(256))
j = 0
for i in range(256):
j = (j + S[i] + key[i % len(key)]) % 256
(S[i], S[j]) = (S[j], S[i])
self._i = 0
self._j = 0
@classmethod
def new(cls, *args, **kwargs):
"""Alternate constructor for API compatibility with Crypto.Cipher.ARC4"""
return cls(*args, **kwargs)
def _crypt(self, plaintext:bytes) -> bytearray:
"""{En,De}crypt binary data."""
i = self._i
j = self._j
S = self._S
rv = bytearray(len(plaintext))
if (isinstance(plaintext, memoryview)):
plaintext = bytes(plaintext)
for k in range(len(plaintext)):
i = (i + 1) % 256
j = (j + S[i]) % 256
(S[i], S[j]) = (S[j], S[i])
rv[k] = int(plaintext[k]) ^ S[(S[i] + S[j]) % 256]
self._i = i
self._j = j
return rv
encrypt = decrypt = _crypt
def _selftest():
from binascii import b2a_hex
for (key,pt,ct) in (
(b"secret",b"What's the airspeed of an unladen swallow?",
b'\xba^\xb3h\xa5\xd7\xf6\xd2Z\xae\x9b\xbd\x9a\x94\x86G\xc8R\x16\xc2\xec\x95\xe4=\x1e\\\x01\x89\xb6\x0b1z\xd1\xd9l\xf4\xa7/B\xb4=\xee'),
(b"topsecret",bytearray(b"I'm being oppressed!"),
b'\x9cO\xc2\xb5\xfd\x065\xa3p\x86\xb4\xc6.L\xf7\xa83\\\x99\xda'),
(b"pass", memoryview(b"Nobody expects the Spanish inquisition!"),
b'\x0e\xaf\xd6\xabX\xde\x90\x97\xcf4\xfa\xcc\xf9\xa9\x91\xe8\xc4\xcaN\x1c\xf4\x12\x1b.<\xa5\xf8\x07=\xbc\xdfo\xa8\xe5\xe7cbo\x8e')):
a4ct = bytes(ARC4(key).encrypt(pt))
if (ct != a4ct):
raise Exception("Key {0} yielded ciphertext {1}, expected {2}".format(key.decode('ascii'), a4ct, ct))
print ('correct ciphertext: {0}'.format(b2a_hex(a4ct)))
if (__name__ == '__main__'):
_selftest()
| gpl-2.0 |
eworm-de/PackageKit | backends/aptcc/apt-intf.cpp | 89622 | /* apt-intf.cpp
*
* Copyright (c) 1999-2008 Daniel Burrows
* Copyright (c) 2004 Michael Vogt <mvo@debian.org>
* 2009-2018 Daniel Nicoletti <dantti12@gmail.com>
* 2012-2015 Matthias Klumpp <matthias@tenstral.net>
* 2016 Harald Sitter <sitter@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include "apt-intf.h"
#include <apt-pkg/aptconfiguration.h>
#include <apt-pkg/init.h>
#include <apt-pkg/error.h>
#include <apt-pkg/fileutl.h>
#include <apt-pkg/install-progress.h>
#include <apt-pkg/sourcelist.h>
#include <apt-pkg/update.h>
#include <apt-pkg/algorithms.h>
#include <apt-pkg/pkgsystem.h>
#include <apt-pkg/version.h>
#include <appstream.h>
#include <sys/statvfs.h>
#include <sys/statfs.h>
#include <sys/wait.h>
#include <sys/fcntl.h>
#include <pty.h>
#include <iostream>
#include <memory>
#include <fstream>
#include <dirent.h>
#include "apt-cache-file.h"
#include "apt-utils.h"
#include "gst-matcher.h"
#include "apt-messages.h"
#include "acqpkitstatus.h"
#include "deb-file.h"
using namespace APT;
#define RAMFS_MAGIC 0x858458f6
AptIntf::AptIntf(PkBackendJob *job) :
m_cache(0),
m_job(job),
m_cancel(false),
m_lastSubProgress(0),
m_terminalTimeout(120)
{
m_cancel = false;
}
bool AptIntf::init(gchar **localDebs)
{
const gchar *http_proxy;
const gchar *ftp_proxy;
m_isMultiArch = APT::Configuration::getArchitectures(false).size() > 1;
// set locale
setEnvLocaleFromJob();
// set http proxy
http_proxy = pk_backend_job_get_proxy_http(m_job);
if (http_proxy != NULL) {
g_autofree gchar *uri = pk_backend_convert_uri(http_proxy);
g_setenv("http_proxy", uri, TRUE);
}
// set ftp proxy
ftp_proxy = pk_backend_job_get_proxy_ftp(m_job);
if (ftp_proxy != NULL) {
g_autofree gchar *uri = pk_backend_convert_uri(ftp_proxy);
g_setenv("ftp_proxy", uri, TRUE);
}
// Check if we should open the Cache with lock
bool withLock;
bool AllowBroken = false;
PkRoleEnum role = pk_backend_job_get_role(m_job);
switch (role) {
case PK_ROLE_ENUM_INSTALL_PACKAGES:
case PK_ROLE_ENUM_INSTALL_FILES:
case PK_ROLE_ENUM_REMOVE_PACKAGES:
case PK_ROLE_ENUM_UPDATE_PACKAGES:
withLock = true;
break;
case PK_ROLE_ENUM_REPAIR_SYSTEM:
AllowBroken = true;
break;
default:
withLock = false;
}
bool simulate = false;
if (withLock) {
// Get the simulate value to see if the lock is valid
PkBitfield transactionFlags = pk_backend_job_get_transaction_flags(m_job);
simulate = pk_bitfield_contain(transactionFlags, PK_TRANSACTION_FLAG_ENUM_SIMULATE);
// Disable the lock if we are simulating
withLock = !simulate;
}
// Create the AptCacheFile class to search for packages
m_cache = new AptCacheFile(m_job);
if (localDebs) {
PkBitfield flags = pk_backend_job_get_transaction_flags(m_job);
if (pk_bitfield_contain(flags, PK_TRANSACTION_FLAG_ENUM_ONLY_TRUSTED)) {
// We are NOT simulating and have untrusted packages
// fail the transaction.
pk_backend_job_error_code(m_job,
PK_ERROR_ENUM_CANNOT_INSTALL_REPO_UNSIGNED,
"Local packages cannot be authenticated");
return false;
}
for (guint i = 0; i < g_strv_length(localDebs); ++i)
markFileForInstall(localDebs[i]);
}
int timeout = 10;
// TODO test this
while (m_cache->Open(withLock) == false) {
if (withLock == false || (timeout <= 0)) {
show_errors(m_job, PK_ERROR_ENUM_CANNOT_GET_LOCK);
return false;
} else {
_error->Discard();
pk_backend_job_set_status(m_job, PK_STATUS_ENUM_WAITING_FOR_LOCK);
sleep(1);
timeout--;
}
// Close the cache if we are going to try again
m_cache->Close();
}
// default settings
_config->CndSet("APT::Get::AutomaticRemove::Kernels", _config->FindB("APT::Get::AutomaticRemove", true));
m_interactive = pk_backend_job_get_interactive(m_job);
if (!m_interactive) {
// Do not ask about config updates if we are not interactive
_config->Set("Dpkg::Options::", "--force-confdef");
_config->Set("Dpkg::Options::", "--force-confold");
// Ensure nothing interferes with questions
g_setenv("APT_LISTCHANGES_FRONTEND", "none", TRUE);
g_setenv("APT_LISTBUGS_FRONTEND", "none", TRUE);
}
// Check if there are half-installed packages and if we can fix them
return m_cache->CheckDeps(AllowBroken);
}
AptIntf::~AptIntf()
{
delete m_cache;
}
void AptIntf::setEnvLocaleFromJob()
{
const gchar *locale = pk_backend_job_get_locale(m_job);
if (locale == NULL)
return;
// set daemon locale
setlocale(LC_ALL, locale);
// processes spawned by APT need to inherit the right locale as well
g_setenv("LANG", locale, TRUE);
g_setenv("LANGUAGE", locale, TRUE);
}
void AptIntf::cancel()
{
if (!m_cancel) {
m_cancel = true;
pk_backend_job_set_status(m_job, PK_STATUS_ENUM_CANCEL);
}
if (m_child_pid > 0) {
kill(m_child_pid, SIGTERM);
}
}
bool AptIntf::cancelled() const
{
return m_cancel;
}
bool AptIntf::matchPackage(const pkgCache::VerIterator &ver, PkBitfield filters)
{
if (filters != 0) {
const pkgCache::PkgIterator &pkg = ver.ParentPkg();
bool installed = false;
// Check if the package is installed
if (pkg->CurrentState == pkgCache::State::Installed && pkg.CurrentVer() == ver) {
installed = true;
}
// if we are on multiarch check also the arch filter
if (m_isMultiArch && pk_bitfield_contain(filters, PK_FILTER_ENUM_ARCH)/* && !installed*/) {
// don't emit the package if it does not match
// the native architecture
if (strcmp(ver.Arch(), "all") != 0 &&
strcmp(ver.Arch(), _config->Find("APT::Architecture").c_str()) != 0) {
return false;
}
}
std::string str = ver.Section() == NULL ? "" : ver.Section();
std::string section, component;
size_t found;
found = str.find_last_of("/");
section = str.substr(found + 1);
if(found == str.npos) {
component = "main";
} else {
component = str.substr(0, found);
}
if (pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_INSTALLED) && installed) {
return false;
} else if (pk_bitfield_contain(filters, PK_FILTER_ENUM_INSTALLED) && !installed) {
return false;
}
if (pk_bitfield_contain(filters, PK_FILTER_ENUM_DEVELOPMENT)) {
// if ver.end() means unknow
// strcmp will be true when it's different than devel
std::string pkgName = pkg.Name();
if (!ends_with(pkgName, "-dev") &&
!ends_with(pkgName, "-dbg") &&
section.compare("devel") &&
section.compare("libdevel")) {
return false;
}
} else if (pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_DEVELOPMENT)) {
std::string pkgName = pkg.Name();
if (ends_with(pkgName, "-dev") ||
ends_with(pkgName, "-dbg") ||
!section.compare("devel") ||
!section.compare("libdevel")) {
return false;
}
}
if (pk_bitfield_contain(filters, PK_FILTER_ENUM_GUI)) {
// if ver.end() means unknow
// strcmp will be true when it's different than x11
if (section.compare("x11") && section.compare("gnome") &&
section.compare("kde") && section.compare("graphics")) {
return false;
}
} else if (pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_GUI)) {
if (!section.compare("x11") || !section.compare("gnome") ||
!section.compare("kde") || !section.compare("graphics")) {
return false;
}
}
if (pk_bitfield_contain(filters, PK_FILTER_ENUM_FREE)) {
if (component.compare("main") != 0 &&
component.compare("universe") != 0) {
// Must be in main and universe to be free
return false;
}
} else if (pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_FREE)) {
if (component.compare("main") == 0 ||
component.compare("universe") == 0) {
// Must not be in main or universe to be free
return false;
}
}
// Check for supported packages
if (pk_bitfield_contain(filters, PK_FILTER_ENUM_SUPPORTED)) {
if (!packageIsSupported(ver, component)) {
return false;
}
} else if (pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_SUPPORTED)) {
if (packageIsSupported(ver, component)) {
return false;
}
}
// Check for applications, if they have files with .desktop
if (pk_bitfield_contain(filters, PK_FILTER_ENUM_APPLICATION)) {
// We do not support checking if it is an Application
// if NOT installed
if (!installed || !isApplication(ver)) {
return false;
}
} else if (pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_APPLICATION)) {
// We do not support checking if it is an Application
// if NOT installed
if (!installed || isApplication(ver)) {
return false;
}
}
// TODO test this one..
#if 0
// I couldn'tfind any packages with the metapackages component, and I
// think the check is the wrong way around; PK_FILTER_ENUM_COLLECTIONS
// is for virtual group packages -- hughsie
if (pk_bitfield_contain(filters, PK_FILTER_ENUM_COLLECTIONS)) {
if (!component.compare("metapackages")) {
return false;
}
} else if (pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_COLLECTIONS)) {
if (component.compare("metapackages")) {
return false;
}
}
#endif
}
return true;
}
PkgList AptIntf::filterPackages(const PkgList &packages, PkBitfield filters)
{
if (filters != 0) {
PkgList ret;
ret.reserve(packages.size());
for (const pkgCache::VerIterator &ver : packages) {
if (matchPackage(ver, filters)) {
ret.push_back(ver);
}
}
// This filter is more complex so we filter it after the list has shrunk
if (pk_bitfield_contain(filters, PK_FILTER_ENUM_DOWNLOADED) && ret.size() > 0) {
PkgList downloaded;
pkgProblemResolver Fix(*m_cache);
{
pkgDepCache::ActionGroup group(*m_cache);
for (auto autoInst : { true, false }) {
for (const pkgCache::VerIterator &ver : ret) {
if (m_cancel) {
break;
}
m_cache->tryToInstall(Fix, ver, false, autoInst, false);
}
}
}
// get a fetcher
pkgAcquire fetcher;
// Read the source list
if (m_cache->BuildSourceList() == false) {
return downloaded;
}
// Create the package manager and prepare to download
std::unique_ptr<pkgPackageManager> PM (_system->CreatePM(*m_cache));
if (!PM->GetArchives(&fetcher, m_cache->GetSourceList(), m_cache->GetPkgRecords()) ||
_error->PendingError() == true) {
return downloaded;
}
for (const pkgCache::VerIterator &verIt : ret) {
bool found = false;
for (pkgAcquire::ItemIterator it = fetcher.ItemsBegin(); it < fetcher.ItemsEnd(); ++it) {
pkgAcqArchiveSane *archive = static_cast<pkgAcqArchiveSane*>(dynamic_cast<pkgAcqArchive*>(*it));
if (archive == nullptr) {
continue;
}
const pkgCache::VerIterator ver = archive->version();
if ((*it)->Local && verIt == ver) {
found = true;
break;
}
}
if (found) {
downloaded.push_back(verIt);
}
}
return downloaded;
}
return ret;
} else {
return packages;
}
}
// used to emit packages it collects all the needed info
void AptIntf::emitPackage(const pkgCache::VerIterator &ver, PkInfoEnum state)
{
// check the state enum to see if it was not set.
if (state == PK_INFO_ENUM_UNKNOWN) {
const pkgCache::PkgIterator &pkg = ver.ParentPkg();
if (pkg->CurrentState == pkgCache::State::Installed &&
pkg.CurrentVer() == ver) {
state = PK_INFO_ENUM_INSTALLED;
} else {
state = PK_INFO_ENUM_AVAILABLE;
}
}
gchar *package_id;
package_id = utilBuildPackageId(ver);
pk_backend_job_package(m_job,
state,
package_id,
m_cache->getShortDescription(ver).c_str());
g_free(package_id);
}
void AptIntf::emitPackageProgress(const pkgCache::VerIterator &ver, PkStatusEnum status, uint percentage)
{
gchar *package_id;
package_id = utilBuildPackageId(ver);
pk_backend_job_set_item_progress(m_job, package_id, status, percentage);
g_free(package_id);
}
void AptIntf::emitPackages(PkgList &output, PkBitfield filters, PkInfoEnum state)
{
// Sort so we can remove the duplicated entries
output.sort();
// Remove the duplicated entries
output.removeDuplicates();
output = filterPackages(output, filters);
for (const pkgCache::VerIterator &verIt : output) {
if (m_cancel) {
break;
}
emitPackage(verIt, state);
}
}
void AptIntf::emitRequireRestart(PkgList &output)
{
// Sort so we can remove the duplicated entries
output.sort();
// Remove the duplicated entries
output.removeDuplicates();
for (const pkgCache::VerIterator &verIt : output) {
gchar *package_id;
package_id = utilBuildPackageId(verIt);
pk_backend_job_require_restart(m_job, PK_RESTART_ENUM_SYSTEM, package_id);
g_free(package_id);
}
}
void AptIntf::emitUpdates(PkgList &output, PkBitfield filters)
{
PkInfoEnum state;
// Sort so we can remove the duplicated entries
output.sort();
// Remove the duplicated entries
output.removeDuplicates();
output = filterPackages(output, filters);
for (const pkgCache::VerIterator &verIt : output) {
if (m_cancel) {
break;
}
// the default update info
state = PK_INFO_ENUM_NORMAL;
// let find what kind of upgrade this is
pkgCache::VerFileIterator vf = verIt.FileList();
std::string origin = vf.File().Origin() == NULL ? "" : vf.File().Origin();
std::string archive = vf.File().Archive() == NULL ? "" : vf.File().Archive();
std::string label = vf.File().Label() == NULL ? "" : vf.File().Label();
if (origin.compare("Debian") == 0 ||
origin.compare("Ubuntu") == 0) {
if (ends_with(archive, "-security") ||
label.compare("Debian-Security") == 0) {
state = PK_INFO_ENUM_SECURITY;
} else if (ends_with(archive, "-backports")) {
state = PK_INFO_ENUM_ENHANCEMENT;
} else if (ends_with(archive, "-updates")) {
state = PK_INFO_ENUM_BUGFIX;
}
} else if (origin.compare("Backports.org archive") == 0 ||
ends_with(origin, "-backports")) {
state = PK_INFO_ENUM_ENHANCEMENT;
}
emitPackage(verIt, state);
}
}
// search packages which provide a codec (specified in "values")
void AptIntf::providesCodec(PkgList &output, gchar **values)
{
string arch;
GstMatcher matcher(values);
if (!matcher.hasMatches()) {
return;
}
for (pkgCache::PkgIterator pkg = m_cache->GetPkgCache()->PkgBegin(); !pkg.end(); ++pkg) {
if (m_cancel) {
break;
}
// Ignore packages that exist only due to dependencies.
if (pkg.VersionList().end() && pkg.ProvidesList().end()) {
continue;
}
// Ignore debug packages - these aren't interesting as codec providers,
// but they do have apt GStreamer-* metadata.
if (ends_with (pkg.Name(), "-dbg") || ends_with (pkg.Name(), "-dbgsym")) {
continue;
}
// TODO search in updates packages
// Ignore virtual packages
pkgCache::VerIterator ver = m_cache->findVer(pkg);
if (ver.end() == true) {
ver = m_cache->findCandidateVer(pkg);
}
if (ver.end() == true) {
continue;
}
arch = string(ver.Arch());
pkgCache::VerFileIterator vf = ver.FileList();
pkgRecords::Parser &rec = m_cache->GetPkgRecords()->Lookup(vf);
const char *start, *stop;
rec.GetRec(start, stop);
string record(start, stop - start);
if (matcher.matches(record, arch)) {
output.push_back(ver);
}
}
}
// search packages which provide the libraries specified in "values"
void AptIntf::providesLibrary(PkgList &output, gchar **values)
{
bool ret = false;
// Quick-check for library names
for (uint i = 0; i < g_strv_length(values); i++) {
if (g_str_has_prefix(values[i], "lib")) {
ret = true;
break;
}
}
if (!ret) {
return;
}
const char *libreg_str = "^\\(lib.*\\)\\.so\\.[0-9]*";
g_debug("RegStr: %s", libreg_str);
regex_t libreg;
if(regcomp(&libreg, libreg_str, 0) != 0) {
g_debug("Error compiling regular expression to match libraries.");
return;
}
gchar *value;
for (uint i = 0; i < g_strv_length(values); i++) {
value = values[i];
regmatch_t matches[2];
if (regexec(&libreg, value, 2, matches, 0) != REG_NOMATCH) {
string libPkgName = string(value, matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so);
string strvalue = string(value);
ssize_t pos = strvalue.find (".so.");
if ((pos > 0) && ((size_t) pos != string::npos)) {
// If last char is a number, add a "-" (to be policy-compliant)
if (g_ascii_isdigit (libPkgName.at (libPkgName.length () - 1))) {
libPkgName.append ("-");
}
libPkgName.append (strvalue.substr (pos + 4));
}
g_debug ("pkg-name: %s", libPkgName.c_str ());
for (pkgCache::PkgIterator pkg = m_cache->GetPkgCache()->PkgBegin(); !pkg.end(); ++pkg) {
// Ignore packages that exist only due to dependencies.
if (pkg.VersionList().end() && pkg.ProvidesList().end()) {
continue;
}
// TODO: Ignore virtual packages
pkgCache::VerIterator ver = m_cache->findVer(pkg);
if (ver.end()) {
ver = m_cache->findCandidateVer(pkg);
if (ver.end()) {
continue;
}
}
// Make everything lower-case
std::transform(libPkgName.begin(), libPkgName.end(), libPkgName.begin(), ::tolower);
if (g_strcmp0 (pkg.Name (), libPkgName.c_str ()) == 0) {
output.push_back(ver);
}
}
} else {
g_debug("libmatcher: Did not match: %s", value);
}
}
}
// Mostly copied from pkgAcqArchive.
bool AptIntf::getArchive(pkgAcquire *Owner,
const pkgCache::VerIterator &Version,
std::string directory,
std::string &StoreFilename)
{
pkgCache::VerFileIterator Vf=Version.FileList();
if (Version.Arch() == 0) {
return _error->Error("I wasn't able to locate a file for the %s package. "
"This might mean you need to manually fix this package. (due to missing arch)",
Version.ParentPkg().Name());
}
/* We need to find a filename to determine the extension. We make the
assumption here that all the available sources for this version share
the same extension.. */
// Skip not source sources, they do not have file fields.
for (; Vf.end() == false; Vf++) {
if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0) {
continue;
}
break;
}
// Does not really matter here.. we are going to fail out below
if (Vf.end() != true) {
// If this fails to get a file name we will bomb out below.
pkgRecords::Parser &Parse = m_cache->GetPkgRecords()->Lookup(Vf);
if (_error->PendingError() == true) {
return false;
}
// Generate the final file name as: package_version_arch.foo
StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
QuoteString(Version.VerStr(),"_:") + '_' +
QuoteString(Version.Arch(),"_:.") +
"." + flExtension(Parse.FileName());
}
for (; Vf.end() == false; Vf++) {
// Ignore not source sources
if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0) {
continue;
}
// Try to cross match against the source list
pkgIndexFile *Index;
if (m_cache->GetSourceList()->FindIndex(Vf.File(),Index) == false) {
continue;
}
// Grab the text package record
pkgRecords::Parser &Parse = m_cache->GetPkgRecords()->Lookup(Vf);
if (_error->PendingError() == true) {
return false;
}
const string PkgFile = Parse.FileName();
const HashStringList hashes = Parse.Hashes();
if (PkgFile.empty() == true) {
return _error->Error("The package index files are corrupted. No Filename: "
"field for package %s.",
Version.ParentPkg().Name());
}
string DestFile = directory + "/" + flNotDir(StoreFilename);
// Create the item
new pkgAcqFile(Owner,
Index->ArchiveURI(PkgFile),
hashes,
Version->Size,
Index->ArchiveInfo(Version),
Version.ParentPkg().Name(),
"",
DestFile);
Vf++;
return true;
}
return false;
}
AptCacheFile* AptIntf::aptCacheFile() const
{
return m_cache;
}
// used to emit packages it collects all the needed info
void AptIntf::emitPackageDetail(const pkgCache::VerIterator &ver)
{
if (ver.end() == true) {
return;
}
const pkgCache::PkgIterator &pkg = ver.ParentPkg();
std::string section = ver.Section() == NULL ? "" : ver.Section();
size_t found;
found = section.find_last_of("/");
section = section.substr(found + 1);
pkgCache::VerFileIterator vf = ver.FileList();
pkgRecords::Parser &rec = m_cache->GetPkgRecords()->Lookup(vf);
long size;
if (pkg->CurrentState == pkgCache::State::Installed && pkg.CurrentVer() == ver) {
// if the package is installed emit the installed size
size = ver->InstalledSize;
} else {
size = ver->Size;
}
gchar *package_id;
package_id = utilBuildPackageId(ver);
pk_backend_job_details(m_job,
package_id,
m_cache->getShortDescription(ver).c_str(),
"unknown",
get_enum_group(section),
m_cache->getLongDescriptionParsed(ver).c_str(),
rec.Homepage().c_str(),
size);
g_free(package_id);
}
void AptIntf::emitDetails(PkgList &pkgs)
{
// Sort so we can remove the duplicated entries
pkgs.sort();
// Remove the duplicated entries
pkgs.removeDuplicates();
for (const pkgCache::VerIterator &verIt : pkgs) {
if (m_cancel) {
break;
}
emitPackageDetail(verIt);
}
}
// used to emit packages it collects all the needed info
void AptIntf::emitUpdateDetail(const pkgCache::VerIterator &candver)
{
// Verify if our update version is valid
if (candver.end()) {
// No candidate version was provided
return;
}
const pkgCache::PkgIterator &pkg = candver.ParentPkg();
// Get the version of the current package
const pkgCache::VerIterator &currver = m_cache->findVer(pkg);
// Build a package_id from the current version
gchar *current_package_id = utilBuildPackageId(currver);
pkgCache::VerFileIterator vf = candver.FileList();
string origin = vf.File().Origin() == NULL ? "" : vf.File().Origin();
pkgRecords::Parser &rec = m_cache->GetPkgRecords()->Lookup(candver.FileList());
string changelog;
string update_text;
string updated;
string issued;
string srcpkg;
if (rec.SourcePkg().empty()) {
srcpkg = pkg.Name();
} else {
srcpkg = rec.SourcePkg();
}
PkBackend *backend = PK_BACKEND(pk_backend_job_get_backend(m_job));
if (pk_backend_is_online(backend)) {
// Create the download object
AcqPackageKitStatus Stat(this, m_job);
// get a fetcher
pkgAcquire fetcher;
fetcher.SetLog(&Stat);
// fetch the changelog
pk_backend_job_set_status(m_job, PK_STATUS_ENUM_DOWNLOAD_CHANGELOG);
changelog = fetchChangelogData(*m_cache,
fetcher,
candver,
currver,
&update_text,
&updated,
&issued);
}
// Check if the update was updates since it was issued
if (issued.compare(updated) == 0) {
updated = "";
}
// Build a package_id from the update version
string archive = vf.File().Archive() == NULL ? "" : vf.File().Archive();
gchar *package_id;
package_id = utilBuildPackageId(candver);
PkUpdateStateEnum updateState = PK_UPDATE_STATE_ENUM_UNKNOWN;
if (archive.compare("stable") == 0) {
updateState = PK_UPDATE_STATE_ENUM_STABLE;
} else if (archive.compare("testing") == 0) {
updateState = PK_UPDATE_STATE_ENUM_TESTING;
} else if (archive.compare("unstable") == 0 ||
archive.compare("experimental") == 0) {
updateState = PK_UPDATE_STATE_ENUM_UNSTABLE;
}
PkRestartEnum restart = PK_RESTART_ENUM_NONE;
if (utilRestartRequired(pkg.Name())) {
restart = PK_RESTART_ENUM_SYSTEM;
}
gchar **updates;
updates = (gchar **) g_malloc(2 * sizeof(gchar *));
updates[0] = current_package_id;
updates[1] = NULL;
GPtrArray *bugzilla_urls;
GPtrArray *cve_urls;
bugzilla_urls = getBugzillaUrls(changelog);
cve_urls = getCVEUrls(changelog);
GPtrArray *obsoletes = g_ptr_array_new();
for (auto deps = candver.DependsList(); not deps.end(); ++deps)
{
if (deps->Type == pkgCache::Dep::Obsoletes)
{
g_ptr_array_add(obsoletes, (void*) deps.TargetPkg().Name());
}
}
// NULL terminate
g_ptr_array_add(obsoletes, NULL);
pk_backend_job_update_detail(m_job,
package_id,
updates,//const gchar *updates
(gchar **) obsoletes->pdata,//const gchar *obsoletes
NULL,//const gchar *vendor_url
(gchar **) bugzilla_urls->pdata,// gchar **bugzilla_urls
(gchar **) cve_urls->pdata,// gchar **cve_urls
restart,//PkRestartEnum restart
update_text.c_str(),//const gchar *update_text
changelog.c_str(),//const gchar *changelog
updateState,//PkUpdateStateEnum state
issued.c_str(), //const gchar *issued_text
updated.c_str() //const gchar *updated_text
);
g_free(package_id);
g_strfreev(updates);
g_ptr_array_unref(obsoletes);
g_ptr_array_unref(bugzilla_urls);
g_ptr_array_unref(cve_urls);
}
void AptIntf::emitUpdateDetails(const PkgList &pkgs)
{
for (const pkgCache::VerIterator &verIt : pkgs) {
if (m_cancel) {
break;
}
emitUpdateDetail(verIt);
}
}
void AptIntf::getDepends(PkgList &output,
const pkgCache::VerIterator &ver,
bool recursive)
{
pkgCache::DepIterator dep = ver.DependsList();
while (!dep.end()) {
if (m_cancel) {
break;
}
const pkgCache::VerIterator &ver = m_cache->findVer(dep.TargetPkg());
// Ignore packages that exist only due to dependencies.
if (ver.end()) {
dep++;
continue;
} else if (dep->Type == pkgCache::Dep::Depends) {
if (recursive) {
if (!output.contains(dep.TargetPkg())) {
output.push_back(ver);
getDepends(output, ver, recursive);
}
} else {
output.push_back(ver);
}
}
dep++;
}
}
void AptIntf::getRequires(PkgList &output,
const pkgCache::VerIterator &ver,
bool recursive)
{
for (pkgCache::PkgIterator parentPkg = m_cache->GetPkgCache()->PkgBegin(); !parentPkg.end(); ++parentPkg) {
if (m_cancel) {
break;
}
// Ignore packages that exist only due to dependencies.
if (parentPkg.VersionList().end() && parentPkg.ProvidesList().end()) {
continue;
}
// Don't insert virtual packages instead add what it provides
const pkgCache::VerIterator &parentVer = m_cache->findVer(parentPkg);
if (parentVer.end() == false) {
PkgList deps;
getDepends(deps, parentVer, false);
for (const pkgCache::VerIterator &depVer : deps) {
if (depVer == ver) {
if (recursive) {
if (!output.contains(parentPkg)) {
output.push_back(parentVer);
getRequires(output, parentVer, recursive);
}
} else {
output.push_back(parentVer);
}
break;
}
}
}
}
}
PkgList AptIntf::getPackages()
{
pk_backend_job_set_status(m_job, PK_STATUS_ENUM_QUERY);
PkgList output;
output.reserve(m_cache->GetPkgCache()->HeaderP->PackageCount);
for (pkgCache::PkgIterator pkg = m_cache->GetPkgCache()->PkgBegin(); !pkg.end(); ++pkg) {
if (m_cancel) {
break;
}
// Ignore packages that exist only due to dependencies.
if(pkg.VersionList().end() && pkg.ProvidesList().end()) {
continue;
}
// Don't insert virtual packages as they don't have all kinds of info
const pkgCache::VerIterator &ver = m_cache->findVer(pkg);
if (ver.end() == false) {
output.push_back(ver);
}
}
return output;
}
PkgList AptIntf::getPackagesFromRepo(SourcesList::SourceRecord *&rec)
{
pk_backend_job_set_status(m_job, PK_STATUS_ENUM_QUERY);
PkgList output;
output.reserve(m_cache->GetPkgCache()->HeaderP->PackageCount);
for (pkgCache::PkgIterator pkg = m_cache->GetPkgCache()->PkgBegin(); !pkg.end(); ++pkg) {
if (m_cancel) {
break;
}
// Ignore packages that exist only due to dependencies.
if(pkg.VersionList().end() && pkg.ProvidesList().end()) {
continue;
}
// Don't insert virtual packages as they don't have all kinds of info
const pkgCache::VerIterator &ver = m_cache->findVer(pkg);
if (ver.end()) {
continue;
}
// only installed packages matters
if (!(pkg->CurrentState == pkgCache::State::Installed && pkg.CurrentVer() == ver)) {
continue;
}
// Distro name
pkgCache::VerFileIterator vf = ver.FileList();
if (vf.File().Archive() == NULL || rec->Dist.compare(vf.File().Archive()) != 0){
continue;
}
// Section part
if (vf.File().Component() == NULL || !rec->hasSection(vf.File().Component())) {
continue;
}
// Check if the site the package comes from is include in the Repo uri
if (vf.File().Site() == NULL || rec->URI.find(vf.File().Site()) == std::string::npos) {
continue;
}
output.push_back(ver);
}
return output;
}
PkgList AptIntf::getPackagesFromGroup(gchar **values)
{
pk_backend_job_set_status(m_job, PK_STATUS_ENUM_QUERY);
PkgList output;
vector<PkGroupEnum> groups;
uint len = g_strv_length(values);
for (uint i = 0; i < len; i++) {
if (values[i] == NULL) {
pk_backend_job_error_code(m_job,
PK_ERROR_ENUM_GROUP_NOT_FOUND,
"An empty group was received");
return output;
} else {
groups.push_back(pk_group_enum_from_string(values[i]));
}
}
pk_backend_job_set_allow_cancel(m_job, true);
for (pkgCache::PkgIterator pkg = m_cache->GetPkgCache()->PkgBegin(); !pkg.end(); ++pkg) {
if (m_cancel) {
break;
}
// Ignore packages that exist only due to dependencies.
if (pkg.VersionList().end() && pkg.ProvidesList().end()) {
continue;
}
// Ignore virtual packages
const pkgCache::VerIterator &ver = m_cache->findVer(pkg);
if (ver.end() == false) {
string section = pkg.VersionList().Section() == NULL ? "" : pkg.VersionList().Section();
size_t found;
found = section.find_last_of("/");
section = section.substr(found + 1);
// Don't insert virtual packages instead add what it provides
for (PkGroupEnum group : groups) {
if (group == get_enum_group(section)) {
output.push_back(ver);
break;
}
}
}
}
return output;
}
bool AptIntf::matchesQueries(const vector<string> &queries, string s) {
for (string query : queries) {
// Case insensitive "string.contains"
auto it = std::search(
s.begin(), s.end(),
query.begin(), query.end(),
[](unsigned char ch1, unsigned char ch2) {
return std::tolower(ch1) == std::tolower(ch2);
}
);
if (it != s.end()) {
return true;
}
}
return false;
}
PkgList AptIntf::searchPackageName(const vector<string> &queries)
{
PkgList output;
for (pkgCache::PkgIterator pkg = m_cache->GetPkgCache()->PkgBegin(); !pkg.end(); ++pkg) {
if (m_cancel) {
break;
}
// Ignore packages that exist only due to dependencies.
if (pkg.VersionList().end() && pkg.ProvidesList().end()) {
continue;
}
if (matchesQueries(queries, pkg.Name())) {
// Don't insert virtual packages instead add what it provides
const pkgCache::VerIterator &ver = m_cache->findVer(pkg);
if (ver.end() == false) {
output.push_back(ver);
} else {
// iterate over the provides list
for (pkgCache::PrvIterator Prv = pkg.ProvidesList(); Prv.end() == false; ++Prv) {
const pkgCache::VerIterator &ownerVer = m_cache->findVer(Prv.OwnerPkg());
// check to see if the provided package isn't virtual too
if (ownerVer.end() == false) {
// we add the package now because we will need to
// remove duplicates later anyway
output.push_back(ownerVer);
}
}
}
}
}
return output;
}
PkgList AptIntf::searchPackageDetails(const vector<string> &queries)
{
PkgList output;
for (pkgCache::PkgIterator pkg = m_cache->GetPkgCache()->PkgBegin(); !pkg.end(); ++pkg) {
if (m_cancel) {
break;
}
// Ignore packages that exist only due to dependencies.
if (pkg.VersionList().end() && pkg.ProvidesList().end()) {
continue;
}
const pkgCache::VerIterator &ver = m_cache->findVer(pkg);
if (ver.end() == false) {
if (matchesQueries(queries, pkg.Name()) ||
matchesQueries(queries, (*m_cache).getLongDescription(ver))) {
// The package matched
output.push_back(ver);
}
} else if (matchesQueries(queries, pkg.Name())) {
// The package is virtual and MATCHED the name
// Don't insert virtual packages instead add what it provides
// iterate over the provides list
for (pkgCache::PrvIterator Prv = pkg.ProvidesList(); Prv.end() == false; ++Prv) {
const pkgCache::VerIterator &ownerVer = m_cache->findVer(Prv.OwnerPkg());
// check to see if the provided package isn't virtual too
if (ownerVer.end() == false) {
// we add the package now because we will need to
// remove duplicates later anyway
output.push_back(ownerVer);
}
}
}
}
return output;
}
// used to return files it reads, using the info from the files in /var/lib/dpkg/info/
PkgList AptIntf::searchPackageFiles(gchar **values)
{
PkgList output;
vector<string> packages;
string search;
regex_t re;
for (uint i = 0; i < g_strv_length(values); ++i) {
gchar *value = values[i];
if (strlen(value) < 1) {
continue;
}
if (!search.empty()) {
search.append("|");
}
if (value[0] == '/') {
search.append("^");
search.append(value);
search.append("$");
} else {
search.append(value);
search.append("$");
}
}
if(regcomp(&re, search.c_str(), REG_NOSUB) != 0) {
g_debug("Regex compilation error");
return output;
}
DIR *dp;
struct dirent *dirp;
if (!(dp = opendir("/var/lib/dpkg/info/"))) {
g_debug ("Error opening /var/lib/dpkg/info/\n");
regfree(&re);
return output;
}
string line;
while ((dirp = readdir(dp)) != NULL) {
if (m_cancel) {
break;
}
if (ends_with(dirp->d_name, ".list")) {
string file(dirp->d_name);
string f = "/var/lib/dpkg/info/" + file;
ifstream in(f.c_str());
if (!in != 0) {
continue;
}
while (!in.eof()) {
getline(in, line);
if (regexec(&re, line.c_str(), (size_t)0, NULL, 0) == 0) {
packages.push_back(file.erase(file.size() - 5, file.size()));
break;
}
}
}
}
closedir(dp);
regfree(&re);
// Resolve the package names now
for (const string &name : packages) {
if (m_cancel) {
break;
}
pkgCache::PkgIterator pkg;
if (name.find(':') != std::string::npos) {
pkg = (*m_cache)->FindPkg(name);
if (pkg.end()) {
continue;
}
} else {
pkgCache::GrpIterator grp = (*m_cache)->FindGrp(name);
for (pkg = grp.PackageList(); pkg.end() == false; pkg = grp.NextPkg(pkg)) {
if (pkg->CurrentState == pkgCache::State::Installed) {
break;
}
}
if (pkg->CurrentState != pkgCache::State::Installed) {
continue;
}
}
const pkgCache::VerIterator &ver = m_cache->findVer(pkg);
if (ver.end()) {
continue;
}
output.push_back(ver);
}
return output;
}
PkgList AptIntf::getUpdates(PkgList &blocked, PkgList &downgrades, PkgList &installs, PkgList &removals, PkgList &obsoleted)
{
PkgList updates;
if (m_cache->DistUpgrade() == false) {
m_cache->ShowBroken(false);
g_debug("Internal error, DistUpgrade broke stuff");
cout << "Internal error, DistUpgrade broke stuff" << endl;
return updates;
}
for (pkgCache::PkgIterator pkg = (*m_cache)->PkgBegin(); !pkg.end(); ++pkg) {
const auto &state = (*m_cache)[pkg];
if (pkg->SelectedState == pkgCache::State::Hold) {
// We pretend held packages are not upgradable at all since we can't represent
// the concept of holds in PackageKit.
// https://github.com/PackageKit/PackageKit/issues/120
continue;
} else if (state.Upgrade() == true && state.NewInstall() == false) {
const pkgCache::VerIterator &ver = m_cache->findCandidateVer(pkg);
if (!ver.end()) {
updates.push_back(ver);
}
} else if (state.Downgrade() == true) {
const pkgCache::VerIterator &ver = m_cache->findCandidateVer(pkg);
if (!ver.end()) {
downgrades.push_back(ver);
}
} else if (state.Upgradable() == true &&
pkg->CurrentVer != 0 &&
state.Delete() == false) {
const pkgCache::VerIterator &ver = m_cache->findCandidateVer(pkg);
if (!ver.end()) {
blocked.push_back(ver);
}
} else if (state.NewInstall()) {
const pkgCache::VerIterator &ver = m_cache->findCandidateVer(pkg);
if (!ver.end()) {
installs.push_back(ver);
}
} else if (state.Delete()) {
const pkgCache::VerIterator &ver = m_cache->findCandidateVer(pkg);
if (!ver.end()) {
bool is_obsoleted = false;
for (pkgCache::DepIterator D = pkg.RevDependsList(); not D.end(); ++D)
{
if ((D->Type == pkgCache::Dep::Obsoletes)
&& ((*m_cache)[D.ParentPkg()].CandidateVer != nullptr)
&& (*m_cache)[D.ParentPkg()].CandidateVerIter(*m_cache).Downloadable()
&& ((pkgCache::Version*)D.ParentVer() == (*m_cache)[D.ParentPkg()].CandidateVer)
&& (*m_cache)->VS().CheckDep(pkg.CurrentVer().VerStr(), D->CompareOp, D.TargetVer())
&& ((*m_cache)->GetPolicy().GetPriority(D.ParentPkg()) >= (*m_cache)->GetPolicy().GetPriority(pkg)))
{
is_obsoleted = true;
break;
}
}
if( is_obsoleted )
{
/* Obsoleted packages */
obsoleted.push_back(ver);
}
else
{
/* Removed packages */
removals.push_back(ver);
}
}
}
}
return updates;
}
// used to return files it reads, using the info from the files in /var/lib/dpkg/info/
void AptIntf::providesMimeType(PkgList &output, gchar **values)
{
g_autoptr(AsPool) pool = NULL;
g_autoptr(GError) error = NULL;
guint i;
vector<string> packages;
pool = as_pool_new ();
as_pool_load (pool, NULL, &error);
if (error != NULL) {
/* we do not fail here because even with error we might still find metadata */
g_warning ("Issue while loading the AppStream metadata pool: %s", error->message);
g_error_free (error);
error = NULL;
}
for (i = 0; values[i] != NULL; i++) {
g_autoptr(GPtrArray) result = NULL;
guint j;
if (m_cancel)
break;
result = as_pool_get_components_by_provided_item (pool, AS_PROVIDED_KIND_MIMETYPE, values[i]);
for (j = 0; j < result->len; j++) {
AsComponent *cpt = AS_COMPONENT (g_ptr_array_index (result, j));
/* we only select one package per component - on Debian systems, AppStream components never reference multiple packages */
packages.push_back (as_component_get_pkgname (cpt));
}
}
/* resolve the package names */
for (const string &package : packages) {
if (m_cancel)
break;
const pkgCache::PkgIterator &pkg = (*m_cache)->FindPkg(package);
if (pkg.end() == true)
continue;
const pkgCache::VerIterator &ver = m_cache->findVer(pkg);
if (ver.end() == true)
continue;
output.push_back(ver);
}
/* check if we found nothing because AppStream data is missing completely */
if (output.empty()) {
g_autoptr(GPtrArray) all_cpts = as_pool_get_components (pool);
if (all_cpts->len <= 0) {
pk_backend_job_error_code(m_job,
PK_ERROR_ENUM_INTERNAL_ERROR,
"No AppStream metadata was found. This means we are unable to find any information for your request.");
}
}
}
bool AptIntf::isApplication(const pkgCache::VerIterator &ver)
{
bool ret = false;
gchar *fileName;
string line;
fileName = g_strdup_printf("/var/lib/dpkg/info/%s:%s.list",
ver.ParentPkg().Name(),
ver.Arch());
if (!FileExists(fileName)) {
g_free(fileName);
// if the file was not found try without the arch field
fileName = g_strdup_printf("/var/lib/dpkg/info/%s.list",
ver.ParentPkg().Name());
}
if (FileExists(fileName)) {
ifstream in(fileName);
if (!in != 0) {
g_free(fileName);
return false;
}
while (in.eof() == false) {
getline(in, line);
if (ends_with(line, ".desktop")) {
ret = true;
break;
}
}
}
g_free(fileName);
return ret;
}
// used to emit files it reads the info directly from the files
void AptIntf::emitPackageFiles(const gchar *pi)
{
GPtrArray *files;
string line;
gchar **parts;
parts = pk_package_id_split(pi);
string fName;
fName = "/var/lib/dpkg/info/" +
string(parts[PK_PACKAGE_ID_NAME]) +
":" +
string(parts[PK_PACKAGE_ID_ARCH]) +
".list";
if (!FileExists(fName)) {
// if the file was not found try without the arch field
fName = "/var/lib/dpkg/info/" +
string(parts[PK_PACKAGE_ID_NAME]) +
".list";
}
g_strfreev (parts);
if (FileExists(fName)) {
ifstream in(fName.c_str());
if (!in != 0) {
return;
}
files = g_ptr_array_new_with_free_func(g_free);
while (in.eof() == false) {
getline(in, line);
if (!line.empty()) {
g_ptr_array_add(files, g_strdup(line.c_str()));
}
}
if (files->len) {
g_ptr_array_add(files, NULL);
pk_backend_job_files(m_job, pi, (gchar **) files->pdata);
}
g_ptr_array_unref(files);
}
}
void AptIntf::emitPackageFilesLocal(const gchar *file)
{
DebFile deb(file);
if (!deb.isValid()){
return;
}
gchar *package_id;
package_id = pk_package_id_build(deb.packageName().c_str(),
deb.version().c_str(),
deb.architecture().c_str(),
file);
GPtrArray *files = g_ptr_array_new_with_free_func(g_free);
for (auto file : deb.files()) {
g_ptr_array_add(files, g_strdup(file.c_str()));
}
g_ptr_array_add(files, NULL);
pk_backend_job_files(m_job, package_id, (gchar **) files->pdata);
g_ptr_array_unref(files);
}
/**
* Check if package is officially supported by the current distribution
*/
bool AptIntf::packageIsSupported(const pkgCache::VerIterator &verIter, string component)
{
string origin;
if (!verIter.end()) {
pkgCache::VerFileIterator vf = verIter.FileList();
origin = vf.File().Origin() == NULL ? "" : vf.File().Origin();
}
if (component.empty()) {
component = "main";
}
// Get a fetcher
AcqPackageKitStatus Stat(this, m_job);
pkgAcquire fetcher;
fetcher.SetLog(&Stat);
PkBitfield flags = pk_backend_job_get_transaction_flags(m_job);
bool trusted = checkTrusted(fetcher, flags);
if ((origin.compare("Debian") == 0) || (origin.compare("Ubuntu") == 0)) {
if ((component.compare("main") == 0 ||
component.compare("restricted") == 0 ||
component.compare("unstable") == 0 ||
component.compare("testing") == 0) && trusted) {
return true;
}
}
return false;
}
bool AptIntf::checkTrusted(pkgAcquire &fetcher, PkBitfield flags)
{
string UntrustedList;
PkgList untrusted;
for (pkgAcquire::ItemIterator I = fetcher.ItemsBegin(); I < fetcher.ItemsEnd(); ++I) {
if (!(*I)->IsTrusted()) {
// The pkgAcquire::Item had a version hiden on it's subclass
// pkgAcqArchive but it was protected our subclass exposes that
pkgAcqArchiveSane *archive = static_cast<pkgAcqArchiveSane*>(dynamic_cast<pkgAcqArchive*>(*I));
if (archive == nullptr) {
continue;
}
untrusted.push_back(archive->version());
UntrustedList += string((*I)->ShortDesc()) + " ";
}
}
if (untrusted.empty()) {
return true;
} else if (pk_bitfield_contain(flags, PK_TRANSACTION_FLAG_ENUM_SIMULATE)) {
// We are just simulating and have untrusted packages emit them
// and return true to continue processing
emitPackages(untrusted, PK_FILTER_ENUM_NONE, PK_INFO_ENUM_UNTRUSTED);
return true;
} else if (pk_bitfield_contain(flags, PK_TRANSACTION_FLAG_ENUM_ONLY_TRUSTED)) {
// We are NOT simulating and have untrusted packages
// fail the transaction.
pk_backend_job_error_code(m_job,
PK_ERROR_ENUM_CANNOT_INSTALL_REPO_UNSIGNED,
"The following packages cannot be authenticated:\n%s",
UntrustedList.c_str());
_error->Discard();
return false;
} else {
// We are NOT simulating and have untrusted packages
// But the user didn't set ONLY_TRUSTED flag
g_debug ("Authentication warning overridden.\n");
return true;
}
}
/**
* checkChangedPackages - Check whas is goind to happen to the packages
*/
PkgList AptIntf::checkChangedPackages(bool emitChanged)
{
PkgList ret;
PkgList installing;
PkgList removing;
PkgList updating;
PkgList downgrading;
PkgList obsoleting;
for (pkgCache::PkgIterator pkg = (*m_cache)->PkgBegin(); ! pkg.end(); ++pkg) {
if ((*m_cache)[pkg].NewInstall() == true) {
// installing;
const pkgCache::VerIterator &ver = m_cache->findCandidateVer(pkg);
if (!ver.end()) {
ret.push_back(ver);
installing.push_back(ver);
// append to the restart required list
if (utilRestartRequired(pkg.Name())) {
m_restartPackages.push_back(ver);
}
}
} else if ((*m_cache)[pkg].Delete() == true) {
// removing
const pkgCache::VerIterator &ver = m_cache->findVer(pkg);
if (!ver.end()) {
ret.push_back(ver);
bool is_obsoleted = false;
for (pkgCache::DepIterator D = pkg.RevDependsList(); not D.end(); ++D)
{
if ((D->Type == pkgCache::Dep::Obsoletes)
&& ((*m_cache)[D.ParentPkg()].CandidateVer != nullptr)
&& (*m_cache)[D.ParentPkg()].CandidateVerIter(*m_cache).Downloadable()
&& ((pkgCache::Version*)D.ParentVer() == (*m_cache)[D.ParentPkg()].CandidateVer)
&& (*m_cache)->VS().CheckDep(pkg.CurrentVer().VerStr(), D->CompareOp, D.TargetVer())
&& ((*m_cache)->GetPolicy().GetPriority(D.ParentPkg()) >= (*m_cache)->GetPolicy().GetPriority(pkg)))
{
is_obsoleted = true;
break;
}
}
if (!is_obsoleted) {
removing.push_back(ver);
} else {
obsoleting.push_back(ver);
}
// append to the restart required list
if (utilRestartRequired(pkg.Name())) {
m_restartPackages.push_back(ver);
}
}
} else if ((*m_cache)[pkg].Upgrade() == true) {
// updating
const pkgCache::VerIterator &ver = m_cache->findCandidateVer(pkg);
if (!ver.end()) {
ret.push_back(ver);
updating.push_back(ver);
// append to the restart required list
if (utilRestartRequired(pkg.Name())) {
m_restartPackages.push_back(ver);
}
}
} else if ((*m_cache)[pkg].Downgrade() == true) {
// downgrading
const pkgCache::VerIterator &ver = m_cache->findVer(pkg);
if (!ver.end()) {
ret.push_back(ver);
downgrading.push_back(ver);
// append to the restart required list
if (utilRestartRequired(pkg.Name())) {
m_restartPackages.push_back(ver);
}
}
}
}
if (emitChanged) {
// emit packages that have changes
emitPackages(obsoleting, PK_FILTER_ENUM_NONE, PK_INFO_ENUM_OBSOLETING);
emitPackages(removing, PK_FILTER_ENUM_NONE, PK_INFO_ENUM_REMOVING);
emitPackages(downgrading, PK_FILTER_ENUM_NONE, PK_INFO_ENUM_DOWNGRADING);
emitPackages(installing, PK_FILTER_ENUM_NONE, PK_INFO_ENUM_INSTALLING);
emitPackages(updating, PK_FILTER_ENUM_NONE, PK_INFO_ENUM_UPDATING);
}
return ret;
}
pkgCache::VerIterator AptIntf::findTransactionPackage(const std::string &name)
{
for (const pkgCache::VerIterator &verIt : m_pkgs) {
if (verIt.ParentPkg().Name() == name) {
return verIt;
}
}
const pkgCache::PkgIterator &pkg = (*m_cache)->FindPkg(name);
// Ignore packages that could not be found or that exist only due to dependencies.
if (pkg.end() == true ||
(pkg.VersionList().end() && pkg.ProvidesList().end())) {
return pkgCache::VerIterator();
}
const pkgCache::VerIterator &ver = m_cache->findVer(pkg);
// check to see if the provided package isn't virtual too
if (ver.end() == false) {
return ver;
}
const pkgCache::VerIterator &candidateVer = m_cache->findCandidateVer(pkg);
// Return the last try anyway
return candidateVer;
}
void AptIntf::updateInterface(int fd, int writeFd)
{
char buf[2];
static char line[1024] = "";
while (1) {
// This algorithm should be improved (it's the same as the rpm one ;)
int len = read(fd, buf, 1);
// nothing was read
if(len < 1) {
break;
}
// update the time we last saw some action
m_lastTermAction = time(NULL);
if( buf[0] == '\n') {
if (m_cancel) {
kill(m_child_pid, SIGTERM);
}
//cout << "got line: " << line << endl;
gchar **split = g_strsplit(line, ":",5);
gchar *status = g_strstrip(split[0]);
gchar *pkg = g_strstrip(split[1]);
gchar *percent = g_strstrip(split[2]);
gchar *str = g_strdup(g_strstrip(split[3]));
// major problem here, we got unexpected input. should _never_ happen
if(!(pkg && status)) {
continue;
}
// Since PackageKit doesn't emulate finished anymore
// we need to manually do it here, as at this point
// dpkg doesn't process two packages at the same time
if (!m_lastPackage.empty() && m_lastPackage.compare(pkg) != 0) {
const pkgCache::VerIterator &ver = findTransactionPackage(m_lastPackage);
if (!ver.end()) {
emitPackage(ver, PK_INFO_ENUM_FINISHED);
}
m_lastSubProgress = 0;
}
// first check for errors and conf-file prompts
if (strstr(status, "pmerror") != NULL) {
// error from dpkg
pk_backend_job_error_code(m_job,
PK_ERROR_ENUM_PACKAGE_FAILED_TO_INSTALL,
"Error while installing package: %s",
str);
} else if (strstr(status, "pmconffile") != NULL) {
// conffile-request from dpkg, needs to be parsed different
int i = 0;
string orig_file, new_file;
// go to first ' and read until the end
for(;str[i] != '\'' || str[i] == 0; i++)
/*nothing*/
;
i++;
for(;str[i] != '\'' || str[i] == 0; i++)
orig_file.append(1, str[i]);
i++;
// same for second ' and read until the end
for(;str[i] != '\'' || str[i] == 0; i++)
/*nothing*/
;
i++;
for(;str[i] != '\'' || str[i] == 0; i++)
new_file.append(1, str[i]);
i++;
gchar *filename;
filename = g_build_filename(DATADIR, "PackageKit", "helpers", "aptcc", "pkconffile", NULL);
gchar **argv;
gchar **envp;
GError *error = NULL;
argv = (gchar **) g_malloc(5 * sizeof(gchar *));
argv[0] = filename;
argv[1] = g_strdup(m_lastPackage.c_str());
argv[2] = g_strdup(orig_file.c_str());
argv[3] = g_strdup(new_file.c_str());
argv[4] = NULL;
const gchar *socket = pk_backend_job_get_frontend_socket(m_job);
if ((m_interactive) && (socket != NULL)) {
envp = (gchar **) g_malloc(3 * sizeof(gchar *));
envp[0] = g_strdup("DEBIAN_FRONTEND=passthrough");
envp[1] = g_strdup_printf("DEBCONF_PIPE=%s", socket);
envp[2] = NULL;
} else {
// we don't have a socket set or are non-interactive. Use the noninteractive frontend.
envp = (gchar **) g_malloc(2 * sizeof(gchar *));
envp[0] = g_strdup("DEBIAN_FRONTEND=noninteractive");
envp[1] = NULL;
}
gboolean ret;
gint exitStatus;
ret = g_spawn_sync(NULL, // working dir
argv, // argv
envp, // envp
G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
NULL, // child_setup
NULL, // user_data
NULL, // standard_output
NULL, // standard_error
&exitStatus,
&error);
int exit_code = WEXITSTATUS(exitStatus);
cout << filename << " " << exit_code << " ret: "<< ret << endl;
g_strfreev(argv);
g_strfreev(envp);
if (exit_code == 10) {
// 1 means the user wants the package config
if (write(writeFd, "Y\n", 2) != 2) {
// TODO we need a DPKG patch to use debconf
g_debug("Failed to write");
}
} else if (exit_code == 20) {
// 2 means the user wants to keep the current config
if (write(writeFd, "N\n", 2) != 2) {
// TODO we need a DPKG patch to use debconf
g_debug("Failed to write");
}
} else {
// either the user didn't choose an option or the front end failed'
// pk_backend_job_message(m_job,
// PK_MESSAGE_ENUM_CONFIG_FILES_CHANGED,
// "The configuration file '%s' "
// "(modified by you or a script) "
// "has a newer version '%s'.\n"
// "Please verify your changes and update it manually.",
// orig_file.c_str(),
// new_file.c_str());
// fall back to keep the current config file
if (write(writeFd, "N\n", 2) != 2) {
// TODO we need a DPKG patch to use debconf
g_debug("Failed to write");
}
}
} else if (strstr(status, "pmstatus") != NULL) {
// INSTALL & UPDATE
// - Running dpkg
// loops ALL
// - 0 Installing pkg (sometimes this is skiped)
// - 25 Preparing pkg
// - 50 Unpacking pkg
// - 75 Preparing to configure pkg
// ** Some pkgs have
// - Running post-installation
// - Running dpkg
// reloops all
// - 0 Configuring pkg
// - +25 Configuring pkg (SOMETIMES)
// - 100 Installed pkg
// after all
// - Running post-installation
// REMOVE
// - Running dpkg
// loops
// - 25 Removing pkg
// - 50 Preparing for removal of pkg
// - 75 Removing pkg
// - 100 Removed pkg
// after all
// - Running post-installation
// Let's start parsing the status:
if (starts_with(str, "Preparing to configure")) {
// Preparing to Install/configure
// cout << "Found Preparing to configure! " << line << endl;
// The next item might be Configuring so better it be 100
m_lastSubProgress = 100;
const pkgCache::VerIterator &ver = findTransactionPackage(pkg);
if (!ver.end()) {
emitPackage(ver, PK_INFO_ENUM_PREPARING);
emitPackageProgress(ver, PK_STATUS_ENUM_SETUP, 75);
}
} else if (starts_with(str, "Preparing for removal")) {
// Preparing to Install/configure
// cout << "Found Preparing for removal! " << line << endl;
m_lastSubProgress = 50;
const pkgCache::VerIterator &ver = findTransactionPackage(pkg);
if (!ver.end()) {
emitPackage(ver, PK_INFO_ENUM_REMOVING);
emitPackageProgress(ver, PK_STATUS_ENUM_SETUP, m_lastSubProgress);
}
} else if (starts_with(str, "Preparing")) {
// Preparing to Install/configure
// cout << "Found Preparing! " << line << endl;
const pkgCache::VerIterator &ver = findTransactionPackage(pkg);
if (!ver.end()) {
emitPackage(ver, PK_INFO_ENUM_PREPARING);
emitPackageProgress(ver, PK_STATUS_ENUM_SETUP, 25);
}
} else if (starts_with(str, "Unpacking")) {
// cout << "Found Unpacking! " << line << endl;
const pkgCache::VerIterator &ver = findTransactionPackage(pkg);
if (!ver.end()) {
emitPackage(ver, PK_INFO_ENUM_DECOMPRESSING);
emitPackageProgress(ver, PK_STATUS_ENUM_INSTALL, 50);
}
} else if (starts_with(str, "Configuring")) {
// Installing Package
// cout << "Found Configuring! " << line << endl;
if (m_lastSubProgress >= 100 && !m_lastPackage.empty()) {
// cout << "FINISH the last package: " << m_lastPackage << endl;
const pkgCache::VerIterator &ver = findTransactionPackage(m_lastPackage);
if (!ver.end()) {
emitPackage(ver, PK_INFO_ENUM_FINISHED);
}
m_lastSubProgress = 0;
}
const pkgCache::VerIterator &ver = findTransactionPackage(pkg);
if (!ver.end()) {
emitPackage(ver, PK_INFO_ENUM_INSTALLING);
emitPackageProgress(ver, PK_STATUS_ENUM_INSTALL, m_lastSubProgress);
}
m_lastSubProgress += 25;
} else if (starts_with(str, "Running dpkg")) {
// cout << "Found Running dpkg! " << line << endl;
} else if (starts_with(str, "Running")) {
// cout << "Found Running! " << line << endl;
pk_backend_job_set_status (m_job, PK_STATUS_ENUM_COMMIT);
} else if (starts_with(str, "Installing")) {
// cout << "Found Installing! " << line << endl;
// FINISH the last package
if (!m_lastPackage.empty()) {
// cout << "FINISH the last package: " << m_lastPackage << endl;
const pkgCache::VerIterator &ver = findTransactionPackage(m_lastPackage);
if (!ver.end()) {
emitPackage(ver, PK_INFO_ENUM_FINISHED);
}
}
m_lastSubProgress = 0;
const pkgCache::VerIterator &ver = findTransactionPackage(pkg);
if (!ver.end()) {
emitPackage(ver, PK_INFO_ENUM_INSTALLING);
emitPackageProgress(ver, PK_STATUS_ENUM_INSTALL, m_lastSubProgress);
}
} else if (starts_with(str, "Removing")) {
// cout << "Found Removing! " << line << endl;
if (m_lastSubProgress >= 100 && !m_lastPackage.empty()) {
// cout << "FINISH the last package: " << m_lastPackage << endl;
const pkgCache::VerIterator &ver = findTransactionPackage(m_lastPackage);
if (!ver.end()) {
emitPackage(ver, PK_INFO_ENUM_FINISHED);
}
}
m_lastSubProgress += 25;
const pkgCache::VerIterator &ver = findTransactionPackage(pkg);
if (!ver.end()) {
emitPackage(ver, PK_INFO_ENUM_REMOVING);
emitPackageProgress(ver, PK_STATUS_ENUM_REMOVE, m_lastSubProgress);
}
} else if (starts_with(str, "Installed") ||
starts_with(str, "Removed")) {
// cout << "Found FINISHED! " << line << endl;
m_lastSubProgress = 100;
const pkgCache::VerIterator &ver = findTransactionPackage(pkg);
if (!ver.end()) {
emitPackage(ver, PK_INFO_ENUM_FINISHED);
// emitPackageProgress(ver, m_lastSubProgress);
}
} else {
cout << ">>>Unmaped value<<< :" << line << endl;
}
if (!starts_with(str, "Running")) {
m_lastPackage = pkg;
}
m_startCounting = true;
} else {
m_startCounting = true;
}
int val = atoi(percent);
//cout << "progress: " << val << endl;
pk_backend_job_set_percentage(m_job, val);
// clean-up
g_strfreev(split);
g_free(str);
line[0] = 0;
} else {
buf[1] = 0;
strcat(line, buf);
}
}
time_t now = time(NULL);
if(!m_startCounting) {
usleep(100000);
// wait until we get the first message from apt
m_lastTermAction = now;
}
if ((now - m_lastTermAction) > m_terminalTimeout) {
// get some debug info
g_warning("no statusfd changes/content updates in terminal for %i"
" seconds",m_terminalTimeout);
m_lastTermAction = time(NULL);
}
// sleep for a while to don't obcess over it
usleep(5000);
}
PkgList AptIntf::resolvePackageIds(gchar **package_ids, PkBitfield filters)
{
gchar *pi;
PkgList ret;
pk_backend_job_set_status (m_job, PK_STATUS_ENUM_QUERY);
// Don't fail if package list is empty
if (package_ids == NULL) {
return ret;
}
for (uint i = 0; i < g_strv_length(package_ids); ++i) {
if (m_cancel) {
break;
}
pi = package_ids[i];
// Check if it's a valid package id
if (pk_package_id_check(pi) == false) {
string name(pi);
// Check if the package name didn't contains the arch field
if (name.find(':') == std::string::npos) {
// OK FindPkg is not suitable on muitarch without ":arch"
// it can only return one package in this case we need to
// search the whole package cache and match the package
// name manually
pkgCache::PkgIterator pkg;
// Name can be supplied user input and may not be an actually valid id. In this
// case FindGrp can come back with a bad group we shouldn't process any further
// as results are undefined.
pkgCache::GrpIterator grp = (*m_cache)->FindGrp(name);
for (pkg = grp.PackageList(); grp.IsGood() && pkg.end() == false; pkg = grp.NextPkg(pkg)) {
if (m_cancel) {
break;
}
// Ignore packages that exist only due to dependencies.
if (pkg.VersionList().end() && pkg.ProvidesList().end()) {
continue;
}
const pkgCache::VerIterator &ver = m_cache->findVer(pkg);
// check to see if the provided package isn't virtual too
if (!ver.end()) {
ret.push_back(ver);
}
const pkgCache::VerIterator &candidateVer = m_cache->findCandidateVer(pkg);
// check to see if the provided package isn't virtual too
if (!candidateVer.end()) {
ret.push_back(candidateVer);
}
}
} else {
const pkgCache::PkgIterator &pkg = (*m_cache)->FindPkg(name);
// Ignore packages that could not be found or that exist only due to dependencies.
if (pkg.end() == true || (pkg.VersionList().end() && pkg.ProvidesList().end())) {
continue;
}
const pkgCache::VerIterator &ver = m_cache->findVer(pkg);
// check to see if the provided package isn't virtual too
if (ver.end() == false) {
ret.push_back(ver);
}
const pkgCache::VerIterator &candidateVer = m_cache->findCandidateVer(pkg);
// check to see if the provided package isn't virtual too
if (candidateVer.end() == false) {
ret.push_back(candidateVer);
}
}
} else {
const pkgCache::VerIterator &ver = m_cache->resolvePkgID(pi);
// check to see if we found the package
if (!ver.end()) {
ret.push_back(ver);
}
}
}
return filterPackages(ret, filters);
}
void AptIntf::refreshCache()
{
pk_backend_job_set_status(m_job, PK_STATUS_ENUM_REFRESH_CACHE);
if (m_cache->BuildSourceList() == false) {
return;
}
// Create the progress
AcqPackageKitStatus Stat(this, m_job);
// do the work
ListUpdate(Stat, *m_cache->GetSourceList());
// Rebuild the cache.
pkgCacheFile::RemoveCaches();
if (m_cache->BuildCaches() == false) {
return;
}
}
void AptIntf::markAutoInstalled(const PkgList &pkgs)
{
for (const pkgCache::VerIterator &verIt : pkgs) {
if (m_cancel) {
break;
}
// Mark package as auto-installed
(*m_cache)->MarkAuto(verIt.ParentPkg(), true);
}
}
bool AptIntf::markFileForInstall(std::string const &file)
{
return m_cache->GetSourceList()->AddVolatileFile(file);
}
PkgList AptIntf::resolveLocalFiles(gchar **localDebs)
{
PkgList ret;
for (guint i = 0; i < g_strv_length(localDebs); ++i) {
pkgCache::PkgIterator const P = (*m_cache)->FindPkg(localDebs[i]);
if (P.end()) {
continue;
}
// Set any version providing the .deb as the candidate.
for (auto Prv = P.ProvidesList(); Prv.end() == false; Prv++) {
ret.push_back(Prv.OwnerVer());
}
// TODO do we need this?
// via cacheset to have our usual virtual handling
//APT::VersionContainerInterface::FromPackage(&(verset[MOD_INSTALL]), Cache, P, APT::CacheSetHelper::CANDIDATE, helper);
}
return ret;
}
bool AptIntf::runTransaction(const PkgList &install, const PkgList &remove, const PkgList &update,
bool fixBroken, PkBitfield flags, bool autoremove)
{
pk_backend_job_set_status (m_job, PK_STATUS_ENUM_RUNNING);
// Enter the special broken fixing mode if the user specified arguments
// THIS mode will run if fixBroken is false and the cache has broken packages
bool BrokenFix = false;
if ((*m_cache)->BrokenCount() != 0) {
BrokenFix = true;
}
pkgProblemResolver Fix(*m_cache);
// TODO: could use std::bind an have a generic operation array iff toRemove had the same
// signature
struct Operation {
const PkgList &list;
const bool preserveAuto;
};
// Calculate existing garbage before the transaction
PkgList initial_garbage;
if (autoremove) {
for (pkgCache::PkgIterator pkg = (*m_cache)->PkgBegin(); ! pkg.end(); ++pkg) {
const pkgCache::VerIterator &ver = pkg.CurrentVer();
if (!ver.end() && m_cache->isGarbage(pkg))
initial_garbage.push_back(ver);
}
}
// new scope for the ActionGroup
{
pkgDepCache::ActionGroup group(*m_cache);
for (auto op : { Operation { install, false }, Operation { update, true } }) {
for (auto autoInst : { false, true }) {
for (const pkgCache::VerIterator &verIt : op.list) {
if (m_cancel) {
break;
}
if (!m_cache->tryToInstall(Fix, verIt, BrokenFix, autoInst, op.preserveAuto)) {
return false;
}
}
}
}
for (const pkgCache::VerIterator &verIt : remove) {
if (m_cancel) {
break;
}
m_cache->tryToRemove(Fix, verIt);
}
// Call the scored problem resolver
if (Fix.Resolve(true) == false) {
_error->Discard();
}
// Now we check the state of the packages,
if ((*m_cache)->BrokenCount() != 0) {
// if the problem resolver could not fix all broken things
// suggest to run RepairSystem by saying that the last transaction
// did not finish well
m_cache->ShowBroken(false, PK_ERROR_ENUM_DEP_RESOLUTION_FAILED);
return false;
}
}
// Remove new garbage that is created
if (autoremove) {
for (pkgCache::PkgIterator pkg = (*m_cache)->PkgBegin(); ! pkg.end(); ++pkg) {
const pkgCache::VerIterator &ver = pkg.CurrentVer();
if (!ver.end() && !initial_garbage.contains(pkg) && m_cache->isGarbage(pkg))
m_cache->tryToRemove (Fix, ver);
}
}
// Prepare for the restart thing
struct stat restartStatStart;
if (g_file_test(REBOOT_REQUIRED, G_FILE_TEST_EXISTS)) {
g_stat(REBOOT_REQUIRED, &restartStatStart);
}
// If we are simulating the install packages
// will just calculate the trusted packages
const auto ret = installPackages(flags);
if (g_file_test(REBOOT_REQUIRED, G_FILE_TEST_EXISTS)) {
struct stat restartStat;
g_stat(REBOOT_REQUIRED, &restartStat);
if (restartStat.st_mtime > restartStatStart.st_mtime) {
// Emit the packages that caused the restart
if (!m_restartPackages.empty()) {
emitRequireRestart(m_restartPackages);
} else if (!m_pkgs.empty()) {
// Assume all of them
emitRequireRestart(m_pkgs);
} else {
// Emit a foo require restart
pk_backend_job_require_restart(m_job, PK_RESTART_ENUM_SYSTEM, "aptcc;;;");
}
}
}
return ret;
}
/**
* InstallPackages - Download and install the packages
*
* This displays the informative messages describing what is going to
* happen and then calls the download routines
*/
bool AptIntf::installPackages(PkBitfield flags)
{
bool simulate = pk_bitfield_contain(flags, PK_TRANSACTION_FLAG_ENUM_SIMULATE);
PkBackend *backend = PK_BACKEND(pk_backend_job_get_backend(m_job));
//cout << "installPackages() called" << endl;
// check for essential packages!!!
if (m_cache->isRemovingEssentialPackages()) {
return false;
}
// Sanity check
if ((*m_cache)->BrokenCount() != 0) {
// TODO
m_cache->ShowBroken(false);
_error->Error("Internal error, InstallPackages was called with broken packages!");
return false;
}
if ((*m_cache)->DelCount() == 0 && (*m_cache)->InstCount() == 0 &&
(*m_cache)->BadCount() == 0) {
return true;
}
// Create the download object
AcqPackageKitStatus Stat(this, m_job);
// get a fetcher
pkgAcquire fetcher(&Stat);
if (!simulate) {
// Only lock the archive directory if we will download
if (fetcher.GetLock(_config->FindDir("Dir::Cache::Archives")) == false) {
return false;
}
}
// Read the source list
if (m_cache->BuildSourceList() == false) {
return false;
}
// Create the package manager and prepare to download
std::unique_ptr<pkgPackageManager> PM (_system->CreatePM(*m_cache));
if (!PM->GetArchives(&fetcher, m_cache->GetSourceList(), m_cache->GetPkgRecords()) ||
_error->PendingError() == true) {
return false;
}
// Display statistics
unsigned long long FetchBytes = fetcher.FetchNeeded();
unsigned long long FetchPBytes = fetcher.PartialPresent();
unsigned long long DebBytes = fetcher.TotalNeeded();
if (DebBytes != (*m_cache)->DebSize()) {
cout << DebBytes << ',' << (*m_cache)->DebSize() << endl;
cout << "How odd.. The sizes didn't match, email apt@packages.debian.org";
}
// Number of bytes
if (FetchBytes != 0) {
// Emit the remainig download size
pk_backend_job_set_download_size_remaining(m_job, FetchBytes);
// check network state if we are going to download
// something or if we are not simulating
if (!simulate && !pk_backend_is_online(backend)) {
pk_backend_job_error_code(m_job,
PK_ERROR_ENUM_NO_NETWORK,
"Cannot download packages whilst offline");
return false;
}
}
/* Check for enough free space */
struct statvfs Buf;
string OutputDir = _config->FindDir("Dir::Cache::Archives");
if (statvfs(OutputDir.c_str(),&Buf) != 0) {
return _error->Errno("statvfs",
"Couldn't determine free space in %s",
OutputDir.c_str());
}
if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize) {
struct statfs Stat;
if (statfs(OutputDir.c_str(), &Stat) != 0 ||
unsigned(Stat.f_type) != RAMFS_MAGIC) {
pk_backend_job_error_code(m_job,
PK_ERROR_ENUM_NO_SPACE_ON_DEVICE,
"You don't have enough free space in %s",
OutputDir.c_str());
return false;
}
}
if (_error->PendingError() == true) {
cout << "PendingError " << endl;
return false;
}
// Make sure we are not installing any untrusted package is untrusted is not set
if (!checkTrusted(fetcher, flags) && !simulate) {
return false;
}
if (simulate) {
// Print out a list of packages that are going to be installed extra
checkChangedPackages(true);
return true;
} else {
// Store the packages that are going to change
// so we can emit them as we process it
m_pkgs = checkChangedPackages(false);
}
// Download and check if we can continue
if (fetcher.Run() != pkgAcquire::Continue
&& m_cancel == false) {
// We failed and we did not cancel
show_errors(m_job, PK_ERROR_ENUM_PACKAGE_DOWNLOAD_FAILED);
return false;
}
if (_error->PendingError() == true) {
cout << "PendingError download" << endl;
return false;
}
// Download finished, check if we should proceed the install
if (pk_bitfield_contain(flags, PK_TRANSACTION_FLAG_ENUM_ONLY_DOWNLOAD)) {
return true;
}
// Check if the user canceled
if (m_cancel) {
return true;
}
// Right now it's not safe to cancel
pk_backend_job_set_allow_cancel(m_job, false);
// Download should be finished by now, changing it's status
pk_backend_job_set_percentage(m_job, PK_BACKEND_PERCENTAGE_INVALID);
// we could try to see if this is the case
g_setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", TRUE);
_system->UnLockInner();
pkgPackageManager::OrderResult res;
res = PM->DoInstallPreFork();
if (res == pkgPackageManager::Failed) {
g_warning ("Failed to prepare installation");
show_errors(m_job, PK_ERROR_ENUM_PACKAGE_DOWNLOAD_FAILED);
return false;
}
// File descriptors for reading dpkg --status-fd
int readFromChildFD[2];
if (pipe(readFromChildFD) < 0) {
cout << "Failed to create a pipe" << endl;
return false;
}
int pty_master;
m_child_pid = forkpty(&pty_master, NULL, NULL, NULL);
if (m_child_pid == -1) {
return false;
}
if (m_child_pid == 0) {
//cout << "FORKED: installPackages(): DoInstall" << endl;
// close pipe we don't need
close(readFromChildFD[0]);
// Change the locale to not get libapt localization
setlocale(LC_ALL, "C.UTF-8");
g_setenv("LANG", "C.UTF-8", TRUE);
g_setenv("LANGUAGE", "C.UTF-8", TRUE);
// Debconf handling
const gchar *socket = pk_backend_job_get_frontend_socket(m_job);
if ((m_interactive) && (socket != NULL)) {
g_setenv("DEBIAN_FRONTEND", "passthrough", TRUE);
g_setenv("DEBCONF_PIPE", socket, TRUE);
} else {
// we don't have a socket set or are not interactive, let's fallback to noninteractive
g_setenv("DEBIAN_FRONTEND", "noninteractive", TRUE);
}
// Set the LANGUAGE so debconf messages get localization
setEnvLocaleFromJob();
// apt will record this in its history.log
guint uid = pk_backend_job_get_uid(m_job);
if (uid > 0) {
gchar buf[16];
snprintf(buf, sizeof(buf), "%d", uid);
g_setenv("PACKAGEKIT_CALLER_UID", buf, TRUE);
}
PkRoleEnum role = pk_backend_job_get_role(m_job);
gchar *cmd = g_strdup_printf("packagekit role='%s'", pk_role_enum_to_string(role));
_config->Set("CommandLine::AsString", cmd);
g_free(cmd);
// Pass the write end of the pipe to the install function
auto *progress = new Progress::PackageManagerProgressFd(readFromChildFD[1]);
res = PM->DoInstallPostFork(progress);
delete progress;
// dump errors into cerr (pass it to the parent process)
_error->DumpErrors();
// finishes the child process, _exit is used to not
// close some parent file descriptors
_exit(res);
}
cout << "PARENT process running..." << endl;
// make it nonblocking, verry important otherwise
// when the child finish we stay stuck.
fcntl(readFromChildFD[0], F_SETFL, O_NONBLOCK);
fcntl(pty_master, F_SETFL, O_NONBLOCK);
// init the timer
m_lastTermAction = time(NULL);
m_startCounting = false;
// Check if the child died
int ret;
char masterbuf[1024];
while (waitpid(m_child_pid, &ret, WNOHANG) == 0) {
// TODO: This is dpkg's raw output. Maybe save it for error-solving?
while(read(pty_master, masterbuf, sizeof(masterbuf)) > 0);
updateInterface(readFromChildFD[0], pty_master);
}
close(readFromChildFD[0]);
close(readFromChildFD[1]);
close(pty_master);
_system->LockInner();
cout << "Parent finished..." << endl;
return true;
}
| gpl-2.0 |
ldsc/lib_ldsc | src/EstruturaDados/ObjetoRede/CObjetoRede.cpp | 17602 | /**
===============================================================================
PROJETO: Biblioteca LIB_LDSC
Ramo: AnaliseImagem/Caracterizacao/GrafoConexaoSerial
===============================================================================
Desenvolvido por:
Laboratorio de Desenvolvimento de Software Cientifico [LDSC].
@author: André Duarte Bueno
@file: CObjetoRede.cpp
@begin: Sat Sep 16 2000
@copyright: (C) 2000 by André Duarte Bueno
@email: andreduartebueno@gmail.com
*/
// -----------------------------------------------------------------------
// Bibliotecas C/C++
// -----------------------------------------------------------------------
#include <iostream>
// #include <vector>
#include <iomanip>
#include <algorithm>
#include <map>
// -----------------------------------------------------------------------
// Bibliotecas LIB_LDSC
// -----------------------------------------------------------------------
#include <EstruturaDados/ObjetoRede/CObjetoRede.h>
using namespace std;
// -------------------------------------------------------------------------
// Função: Conectar
// -------------------------------------------------------------------------
/**
* @brief Função que recebe um ponteiro para um CObjetoRede objA e o inclue na lista de conexões.
* Faz a conexão de this com o objeto recebido. Usada por objetos do tipo Sitio.
* Note que oculta versão que recebe CObjetoGrafo.
* @author : André Duarte Bueno
* @param : objeto a quem será conectado
* @return : void
*/
inline void CObjetoRede::Conectar ( CObjetoRede* objA )
{
this->conexao.push_back ( objA );
this->condutancia.push_back ( objA->propriedade );
}
// -------------------------------------------------------------------------
// Função: Conectar
// -------------------------------------------------------------------------
/**
* @brief Função que recebe um ponteiro para um CObjetoRede objA e o inclue na lista de conexões.
* Faz a conexão de this com o objeto recebido. Usada por objetos do tipo Sitio.
* A condutância entre this e o objA é o segundo parâmetro (a _condutancia é calculada externamente).
* @author : André Duarte Bueno
* @param : objeto objA a quem será conectado e condutancia entre this e objA.
* @return : void
*/
inline void CObjetoRede::Conectar ( CObjetoRede* objA, long double _condutancia )
{
this->conexao.push_back ( objA );
this->condutancia.push_back ( _condutancia );
}
// -------------------------------------------------------------------------
// Função: Conectar
// -------------------------------------------------------------------------
/**
* @brief Função que recebe um ponteiro para um CObjetoRede objA e um ponteiro para um objeto B
* e os inclue na lista de conexões. Usada por objetos do tipo Ligação.
* Faz a conexão de this com os objetos recebidos.
* Note que oculta versão que recebe CObjetoGrafo.
* Note que como não recebe a condutância, vai fazer a condutancia igual a
* propriedade do objeto ao qual estou conectado:
* conexao[i] = objA;
* condutancia[i] = objA.propriedade;
* @author : André Duarte Bueno
* @param : objetos objA e objB a quem será conectado
* @return : void
*/
/*inline */ void CObjetoRede::Conectar ( CObjetoRede* objA, CObjetoRede* objB )
{
this->conexao.push_back ( objA );
this->condutancia.push_back ( objA->propriedade );
this->conexao.push_back ( objB );
this->condutancia.push_back ( objB->propriedade );
}
// -------------------------------------------------------------------------
// Função: Conectar
// -------------------------------------------------------------------------
/**
* @brief Função que recebe um ponteiro para um CObjetoRede objA e um ponteiro para um objeto B
* e os inclue na lista de conexões. Usada por objetos do tipo Ligação.
* Faz a conexão de this com os objetos recebidos.
* Note que oculta versão que recebe CObjetoGrafo.
* Note que como não recebe a condutância, vai fazer a condutancia igual a
* propriedade do objeto ao qual estou conectado:
* conexao[i] = objA;
* condutancia[i] = _condutanciaA;
* @author : André Duarte Bueno
* @param : objeto objA a quem será conectado e condutancia entre this e objA.
* @param : objeto objB a quem será conectado e condutancia entre this e objB.
* @return : void
*/
/*inline */ void CObjetoRede::Conectar ( CObjetoRede* objA, long double _condutanciaA ,
CObjetoRede* objB , long double _condutanciaB )
{
this->conexao.push_back ( objA );
this->condutancia.push_back ( _condutanciaA );
this->conexao.push_back ( objB );
this->condutancia.push_back ( _condutanciaB );
}
// -------------------------------------------------------------------------
// Função: DeletarConexao
// -------------------------------------------------------------------------
/** Deleta conexões de ramos mortos
@short : Deleta conexões de ramos mortos
@author : André Duarte Bueno
@param : unsigned int pos
@return : void
Nota: o código abaixo pode deixar o processo lento se o número de conexões foram
grande e se este método for muito chamado! Pensar em usar <list>
*/
void CObjetoRede::DeletarConexao ( unsigned int pos )
{
// Deleta a conexão
this->conexao.erase ( conexao.begin() + pos );
// e, adicionalmente, deleta a condutancia associada ao objeto pos
this->condutancia.erase ( condutancia.begin () + pos );
}
// -------------------------------------------------------------------------
// Função: DeletarConexao
// -------------------------------------------------------------------------
/**
@short : Recebe um vetor com o índice das conexões a serem deletadas.
(Deleta várias conexões ao mesmo tempo).
@author : André Duarte Bueno
@param : vetor com índice i dos objetos a serem deletados.
@return : void
*/
void CObjetoRede::DeletarConexao ( vector<unsigned int> di )
{
unsigned int marcar_para_delecao = conexao.size();
for ( unsigned int i = 0; i < di.size (); i++ )
// Se di[i] for um rótulo inválido para conexao ocorre estouro de pilha!
conexao[ di[i] ]->rotulo = marcar_para_delecao;
// Chama DeletarConexoesInvalidadas que deleta conexões marcadas para deleção.
this->DeletarConexoesInvalidadas ( marcar_para_delecao );
}
/** Marca e deleta os links para objetos invalidados (marcados para deleção).
@short : Deleta a conexao de um ramo morto
@author : André Duarte Bueno
@param : unsigned int marcada_para_delecao
@return : void
*/
bool CObjetoRede::DeletarConexoesInvalidadas ( unsigned int marcado_para_delecao )
{
unsigned int indice_rotulo_valido {0};
// Percorre todas as conexões
for ( unsigned int i = 0; i < conexao.size (); i++ )
// Se o objeto para quem aponta não foi marcado_para_delecao, armazena no vetor das conexões.
// Se foi marcado_para_delecao vai ser pulado.
if ( conexao[i]->rotulo != marcado_para_delecao ) {
conexao[indice_rotulo_valido] = conexao[i];
condutancia[indice_rotulo_valido] = condutancia[i];
indice_rotulo_valido++;
}
// Redimensiona o vetor das conexões e deleta elementos não usados.
conexao.resize ( indice_rotulo_valido );
conexao.erase ( conexao.begin() + indice_rotulo_valido , conexao.end () );
// Redimensiona o vetor das condutâncias e deleta elementos não usados.
condutancia.resize ( indice_rotulo_valido );
condutancia.erase ( condutancia.begin() + indice_rotulo_valido , condutancia.end () );
return 1;
}
/**
@short : Deleta as conexões repetidas.
@author : André Duarte Bueno
@param :
@return : bool
@todo : da forma como esta funciona, mas pode ser mais simples! testar!
*/
unsigned int CObjetoRede::DeletarConexoesRepetidas_e_SomarCondutanciasParalelo()
{
// Número de links deletados
// acumula número de links no início
unsigned int numeroLinksDeletados = conexao.size ();
// Cria uma cópia do vetor das conexões, ordena e elimina repeticoes
vector < CObjetoRede* > c ( conexao );
// Funcao EliminaDuplicatas para containers (pg487 stroustrup)
sort ( c.begin (), c.end () ); // c sai de escopo e é deletado!
// Cria um map que associa o link com as condutâncias
std::map < CObjetoRede*, long double > m;
// Copia para o map os links (já ordenados e únicos de c) e inicializa os valores com 0.
for ( unsigned int i = 0; i < c.size (); i++ )
m[c[i]] = 0.0;
// Percorre as conexões e acumula as condutâncias no map
// map.insert( container_map::value_type( chave, valor ) );
for ( unsigned int i = 0; i < conexao.size (); i++ )
m[conexao[i]] += condutancia[i];
// for ( iter = listatelefones.begin(); iter != listatelefones.end(); ++iter )
// cout << setw(campo)<<iter->first << setw(20)<< iter->second ;
for ( unsigned int i = 0; i < c.size (); i++ ) {
conexao[i] = c[i];
condutancia[i] = m[c[i]];
}
// #ifdef OTIMIZAR_MEMORIA
// Redimensiona o vetor das conexões e deleta elementos não usados.
conexao.resize ( c.size () );
conexao.erase ( conexao.begin() + c.size () , conexao.end () );
// Redimensiona o vetor das condutâncias e deleta elementos não usados.
condutancia.resize ( c.size () );
condutancia.erase ( condutancia.begin() + c.size () , condutancia.end () );
// #endif
numeroLinksDeletados = numeroLinksDeletados - c.size ();
return numeroLinksDeletados;
}
/**
* /// @todo tentativa otimizar DeletarConexoesRepetidas_e_SomarCondutanciasParalelo
* terminar de implementar, testar velocidade, ficar com a versao + rápida.
int CObjetoRede::DeletarConeccoesRepetidas_V2 ()
{
// cria um vetor de pair.
vector < pair<CObjetoRede *, long double> > par_conexao_condutancia(conexao.size());
// preenche o par.
for (unsigned int i = 0 ; i< conexao.size(); i++)
par_conexao_condutancia[i] = make_pair( conexao[i], condutancia[i]);
// ordena o par considerando como critério a conexão.
sort(begin(par_conexao_condutancia), end(par_conexao_condutancia),
[]( pair<CObjetoRede *, long double> par ) { par.first } ); // corrigir comparação
// Acumular as condutâncias repetidas
...use equalrange para localizar os trechos com condutâncias repetidas.
//
for ( unsigned int i = equalrange.ini; i < equalrange.end; i++ )
condutanciaTotal += condut[i]
condutancia[equalrange.ini] = condutanciaTotal;
erase(conexao.begin()+equalrange.ini+1, conexao.begin()+ equalrange.end);
erase(condutancia.begin()+equalrange.ini+1, condutancia.begin()+ equalrange.end);
}
*/
// -------------------------------------------------------------------------
// Função: Write
// -------------------------------------------------------------------------
/** Salva dados do objeto sítio em novo formato.
@short :
Formato novo Write (Andre Format):
---------------------------------
NumeroSitios // salvo pelo grafo
Tipo
Rotulo
propriedade // raio hidraulico ou condutancia
x // pressão
NumeroConeccoes
Lista_dos_rotulos_das_conexões
@author : André Duarte Bueno
@param : Recebe uma referencia para uma ostream
@return : void
*/
ostream& CObjetoRede::Write ( ostream& out ) const
{
out.setf ( ios::left );
// Tipo de contorno
out << setw ( 5 ) << static_cast<uint8_t> ( Tipo() ) ;
// Rótulo de this
out << ' ' << setw ( 5 ) << rotulo;
// x de this (pressão)
out << ' ' << setw ( 10 ) << x;
// propriedade de this (condutancia)
out << ' ' << setw ( 10 ) << propriedade;
// Numero de links do sítio
out << ' ' << setw ( 5 ) << conexao.size ();
// lista dos rótulos da conexao
for ( auto &objeto_conectado : conexao )
out << ' ' << setw ( 5 ) << objeto_conectado->rotulo;
// Lista das propriedades (condutâncias das ligações)
for ( auto &condutancia_i : condutancia )
out << ' ' << setw ( 10 ) << condutancia_i;
//out << '\n';
return out;
}
// -------------------------------------------------------------------------
// Função: operator<<
// -------------------------------------------------------------------------
/** Escreve os atributos do objeto em disco.
@short : Escreve os atributos do objeto em disco.
Sobrecarga operador entrada streams (antiga CObjetoRedeEsqueleto).
@author : André Duarte Bueno
@param : ostream& e CObjetoRede&
@return : ostream&
*/
ostream& operator<< ( ostream& out, CObjetoRede& s )
{
s.Write ( out );
return out;
}
// -------------------------------------------------------------------------
// Função: operator>>
// -------------------------------------------------------------------------
/** Sobrecarga operador entrada streams
@short : Sobrecarga operador entrada streams
@author : André Duarte Bueno
@param : istream& is, CObjetoRede& s
@return : istream&
*/
/*istream& operator>> (istream& is, CObjetoRede& s)
{
// Lê a informação do tipo de contorno
int contorno;// CContorno::ETipoContorno
is >> contorno; // Descartada ??
// Lê a informação do numero de ligações
int numeroLigacoes;
is >> numeroLigacoes;
// Precisa deletar o vetor de conexões existente,
// mas não os objetos apontados pelo vetor,
// os CObjetoGrafo são alocados e deletados pelo CGrafo
// Rótulo do objeto
int rotulo;
// Ponteiro para objeto
CObjetoGrafo * objA;
double propriedade;
// Monta vetor das conexões
for(unsigned long int i = 0 ; i < numeroLigacoes; i++)
{
// Lê o rotulo do objeto a quem estou conectado em i
is >> rotulo;
// Pesquisa e localiza objeto que tem este rotulo
// retorna copia do ponteiro para objeto com o rotulo
objA = grafo->FindObjeto(rotulo); // Implementar Find Avançado (eficiente)
conexao.push_back(objA);
// Lê a propriedade
is >> propriedade;
// Armazena no ojeto ??
conexao[i]->propriedade = propriedade;
}
return is;
} */
// -------------------------------------------------------------------------
// Função: Go
// -------------------------------------------------------------------------
/**
* A função Go calcula o novo valor de x, considerando o relacionamento
com os demais objetos a quem esta conectado.
Note que x(ex:a pressão do objeto) é desconsiderada, considera condutâncias
e x(ex:pressão dos vizinhos).
@short :
Observe que calcula o novo valor de this->x (a pressão) e o retorna,
mas não altera o valor de this->x.
O novo valor de x, retornado por Go() pode ser usado externamente.
Por exemplo,
um solver externo vai usar esta nova previsão de x para definir,
no momento adequado, o novo valor de this->x.
ex: objeto->x = objeto->Go();
Mudança de formato no acesso aos outros sítios:
-----------------------------------------------
A versão 1 de CGrafo usava o rótulo para identificar o objeto a ser acessado,
mas era necessário receber o grafo todo.
Agora o vetor conexão de cada sítio armazena direto o endereço dos sítios
a quem esta conectado.
Abaixo precisava do grafo para acessar os objetos
somatorio_da_condutancia_vezes_x +=
conexao[i]->propriedade * grafo->objeto[this->conexao[i]->rotulo]->x;
Agora acessa os objetos diretamente, o rótulo do objeto esta sendo utilizado
apenas para salvar o mesmo em disco.
somatorio_da_condutancia_vezes_x +=
conexao[i]->propriedade * grafo->objeto[i]->x;
@author : André Duarte Bueno
@param : long double
@return : long double
*/
long double CObjetoRede::Go ( long double /*d */ )
{
// Ex:
// propriedade = condutancia
// x = pressao
// Cria variáveis auxiliares (uma única vez, pois são estáticas)
static long double somatorio_da_condutancia;
static long double somatorio_da_condutancia_vezes_x;
// Se não tem nenhuma conexão, retorna x atual (a pressão atual)
// tecnicamente nunca ocorre pois objetos sem conexão foram deletados!
// if (conexao.size() == 0)
// return x;
// zera o somatório (a cada passagem por Go)
somatorio_da_condutancia_vezes_x = somatorio_da_condutancia = 0.0;
for ( unsigned int i = 0; i < conexao.size (); i++ ) {
// condutância entre this e o objeto conectado vezes x(pressão) do objeto_conectado
somatorio_da_condutancia_vezes_x += this->condutancia[i] * conexao[i]->x;
// Acumula a condutancia total
somatorio_da_condutancia += this->condutancia[i];
}
// Somatorio (condutancia*pressao) / somatorio_da_condutancia
// retorna um novo valor de x (pressão) sem alterar x diretamente.
return somatorio_da_condutancia_vezes_x / somatorio_da_condutancia;
}
// -------------------------------------------------------------------------
// Função: Fluxo
// -------------------------------------------------------------------------
/**
@short : Determina o fluxo associado a este sítio.
Fluxo = Condutancia média vezes a pressao deste sítio menos a pressao do objeto conexo
@author : André Duarte Bueno
@param : void
@return : long double ( o fluxo associado a this)
*/
long double CObjetoRede::Fluxo () const
{
static long double fluxo ;
fluxo = 0.0 ; // zera a cada passagem
for ( unsigned long int i = 0; i < conexao.size (); i++ ) {
// Ex: se x é a pressao; calcula condutancia * dP
fluxo += condutancia[i] * ( this->x - conexao[i]->x );
}
return fluxo;
}
| gpl-2.0 |
Droces/casabio | sites/all/modules/custom/contribute/scripts/contribute_maps.js | 1248 | /**
* @file
* A JavaScript file for…
*/
// JavaScript should be made compatible with libraries other than jQuery by
// wrapping it with an "anonymous closure". See:
// - https://drupal.org/node/1446420
// - http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
(function ($, Drupal, window, document, undefined) {
var page_is_setup = false;
// To understand behaviors, see https://drupal.org/node/756722#behaviors
Drupal.behaviors.contribute_maps = {
attach: function(context, settings) {
// console.log('Called: Drupal.behaviors.contribute_maps');
// console.log('context: ', context);
// console.log('settings: ', settings);
if (! page_is_setup) {
add_listeners(context, settings);
page_is_setup = true;
}
},
weight: 11
};
/**
* Adds event listeners to page elements.
*/
function add_listeners(context, settings) {
$( window ).load(function() {
// console.log('window has loaded');
// On Upload page, in the map, set path ('linestring') as default edit mode.
var button_selector = '.page-contribute-upload .openlayers-map-container button.ol-geofield-linestring';
$(button_selector).trigger('click');
});
}
})(jQuery, Drupal, this, this.document);
| gpl-2.0 |
damasiorafael/inppnet | cache/t3_pages/53bbb79b4980f60ea0786b85df096904-cache-t3_pages-df27635ae3d7346966f76062a75ffbe5.php | 874 | <?php die("Access Denied"); ?>#x#s:832:" 1405040141<?xml version="1.0" encoding="utf-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
<ShortName>Inppnet - Instituto Nacional de Parapsicologia Psicometafísica</ShortName>
<Description>Instituto Nacional de Parapsicologia Psicometafísica. Cursos Online</Description>
<InputEncoding>UTF-8</InputEncoding>
<Image type="image/vnd.microsoft.icon" width="16" height="16">http://sala.inppnet.com.br/templates/ja_university/favicon.ico</Image>
<Url type="application/opensearchdescription+xml" rel="self" template="http://sala.inppnet.com.br/index.php?option=com_search&view=category&id=28&Itemid=557&format=opensearch"/>
<Url type="text/html" template="http://sala.inppnet.com.br/index.php?option=com_search&searchword={searchTerms}"/>
</OpenSearchDescription>
"; | gpl-2.0 |
fedyk/fl.ru.am | kango/kango.1.3/kango/builders/chrome.py | 12122 | import struct
import os
import shutil
import sys
import json
import codecs
import subprocess
import xml
from array import *
from kango.utils import zip as zip_file
from kango.builders import ExtensionBuilderBase
from kango import logger
from kango import die
from kango.settings import KEYWORDS
class ExtensionBuilder(ExtensionBuilderBase):
key = 'chrome'
package_extension = '.crx'
_manifest_filename = 'manifest.json'
_background_host_filename = 'background.html'
_info = None
_kango_path = None
_permission_table = {
'context_menu': 'contextMenus',
'web_navigation': 'webNavigation',
'notifications': 'notifications',
'cookies': 'cookies',
'tabs': 'tabs'
}
def __init__(self, info, kango_path):
self._info = info
self._kango_path = kango_path
def _unix_find_app(self, prog_filename):
bdirs = (
'$HOME/Environment/local/bin/',
'$HOME/bin/',
'/share/apps/bin/',
'/usr/local/bin/',
'/usr/bin/'
)
for dir in bdirs:
path = os.path.expandvars(os.path.join(dir, prog_filename))
if os.path.exists(path):
return path
return None
def get_chrome_path(self):
if sys.platform.startswith('win'):
root_pathes = (
'${LOCALAPPDATA}',
'${APPDATA}',
'${ProgramFiles(x86)}',
'${ProgramFiles}'
)
app_pathes = (os.path.join('Google', 'Chrome', 'Application', 'chrome.exe'),
os.path.join('Chromium', 'Application', 'chrome.exe'))
for root_path in root_pathes:
for app_path in app_pathes:
path = os.path.expandvars(os.path.join(root_path, app_path))
if os.path.exists(path):
return path
elif sys.platform.startswith('linux'):
for apppath in ('chromium-browser', 'google-chrome', 'chromium'):
path = self._unix_find_app(apppath)
if path is not None:
return path
elif sys.platform.startswith('darwin'):
if os.path.exists('/Applications/Google Chrome.app'):
return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
elif os.path.exists('/Applications/Chromium.app'):
return '/Applications/Chromium.app/Contents/MacOS/Chromium'
return None
def _load_manifest(self, manifest_path):
with open(manifest_path, 'r') as f:
manifest = json.load(f)
return manifest
def _save_manifest(self, manifest, manifest_path):
with open(manifest_path, 'w') as f:
json.dump(manifest, f, skipkeys=True, indent=4)
def _patch_manifest(self, info, manifest):
if info.update_url == '':
del manifest['update_url']
if info.homepage_url == '':
del manifest['homepage_url']
if info.chrome_public_key != '':
manifest['key'] = info.chrome_public_key
for elem in manifest:
if elem not in('content_scripts', 'permissions') and hasattr(info, elem):
manifest[elem] = getattr(info, elem)
if info.browser_button is None:
del manifest['browser_action']
else:
manifest['browser_action']['default_icon'] = info.browser_button['icon']
manifest['browser_action']['default_title'] = info.browser_button['tooltipText']
if 'popup' not in info.browser_button:
del manifest['browser_action']['default_popup']
if not info.content_scripts:
del manifest['content_scripts']
if info.options_page is None:
del manifest['options_page']
if info.context_menu_item is None:
manifest['permissions'].remove('contextMenus')
if info.permissions['xhr'] != self.DEFAULT_XHR_PERMISSIONS:
for key in self.DEFAULT_XHR_PERMISSIONS:
manifest['permissions'].remove(key)
manifest['permissions'].extend(info.permissions['xhr'])
if info.permissions['content_scripts'] != self.DEFAULT_CONTENT_SCRIPTS_MATCHES:
manifest['content_scripts'][0]['matches'] = info.permissions['content_scripts']
for key in self._permission_table:
if not info.permissions[key]:
manifest['permissions'].remove(self._permission_table[key])
def _process_includes(self, manifest, out_path):
includes_path = os.path.join(out_path, 'includes')
if 'content_scripts' in manifest:
self.merge_files(os.path.join(includes_path, 'content.js'),
map(lambda path: os.path.join(out_path, path), manifest['content_scripts'][0]['js']))
os.remove(os.path.join(includes_path, 'content_%s.js') % KEYWORDS['kango'])
os.remove(os.path.join(includes_path, 'content_init.js'))
manifest['content_scripts'][0]['js'] = ['includes/content.js']
else:
shutil.rmtree(includes_path, True)
def _zip2crx(self, zipPath, keyPath, crxPath):
"""
:param zipPath: path to .zip file
:param keyPath: path to .pem file
:param crxPath: path to .crx file to be created
"""
# Sign the zip file with the private key in PEM format
signature = subprocess.Popen(['openssl', 'sha1', '-sign', keyPath, zipPath], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
# Convert the PEM key to DER (and extract the public form) for inclusion in the CRX header
derkey = subprocess.Popen(['openssl', 'rsa', '-pubout', '-inform', 'PEM', '-outform', 'DER', '-in', keyPath], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
out = open(crxPath, 'wb')
out.write('Cr24') # Extension file magic number
header = array('L') if struct.calcsize('L') == 4 else array('I')
header.append(2) # Version 2
header.append(len(derkey))
header.append(len(signature))
header.tofile(out)
out.write(derkey)
out.write(signature)
out.write(open(zipPath, 'rb').read())
def _generate_private_key(self, keyPath):
subprocess.Popen(['openssl', 'genrsa', '-out', './out.pem', '1024'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
subprocess.Popen(['openssl', 'pkey', '-in', './out.pem', '-out', keyPath], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
os.remove('./out.pem')
def _pack_via_open_ssl(self, zipPath, keyPath, crxPath):
if not os.path.isfile(keyPath):
self._generate_private_key(keyPath)
self._zip2crx(zipPath, keyPath, crxPath)
def _pack_zip(self, dst, src):
filename = self.get_package_name(self._info) + '_chrome_webstore.zip'
outpath = os.path.abspath(os.path.join(dst, filename))
zip_file.pack_directory(src, outpath)
return outpath
def _build_locales(self, manifest, out_path):
if len(self._info.locales) > 0:
special_keys = ('name', 'description')
locale_keys = ['__info_%s__' % key for key in special_keys]
chrome_keys = ['info_%s' % key for key in special_keys]
locales = self.get_locales(self._info.locales, out_path)
for name, locale in locales:
chrome_locale = {}
for key, locale_key, chrome_key in zip(special_keys, locale_keys, chrome_keys):
if locale_key in locale:
chrome_locale[chrome_key] = {'message': locale[locale_key]}
manifest[key] = '__MSG_%s__' % chrome_key
locale_dir = os.path.join(out_path, '_locales', name)
os.makedirs(locale_dir)
with open(os.path.join(locale_dir, 'messages.json'), 'w') as f:
json.dump(chrome_locale, f, skipkeys=True, indent=4)
manifest['default_locale'] = self._info.default_locale
def _validate(self, info):
if len(info.description) > 132:
logger.warning('description should be no more than 132 characters')
if info.context_menu_item is not None and not info.permissions['context_menu']:
die('context_menu_item used, but permissions.context_menu set to false')
def build(self, out_path):
self._validate(self._info)
manifest_path = os.path.join(out_path, self._manifest_filename)
manifest = self._load_manifest(manifest_path)
self._patch_manifest(self._info, manifest)
self._build_locales(manifest, out_path)
self._process_includes(manifest, out_path)
self._save_manifest(manifest, manifest_path)
self.patch_background_host(os.path.join(out_path, self._background_host_filename), self._info.modules)
return out_path
def pack(self, output_path, extension_path, project_src_path, certificates_path):
if not os.path.exists(certificates_path):
os.makedirs(certificates_path)
pem_path = os.path.join(certificates_path, 'chrome.pem')
extension_dst = os.path.abspath(os.path.join(extension_path, '../', 'chrome.crx'))
crx_path = os.path.join(output_path, self.get_full_package_name(self._info))
chrome_path = self.get_chrome_path()
if chrome_path is not None:
args = [chrome_path, '--pack-extension=%s' % extension_path, '--no-message-box']
if os.path.isfile(pem_path):
args.append('--pack-extension-key=%s' % pem_path)
subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
try:
shutil.move(os.path.abspath(os.path.join(extension_path, '../', 'chrome.pem')), pem_path)
except:
pass
shutil.move(extension_dst, crx_path)
else:
logger.info('Chrome/Chromium is not installed, trying OpenSSL...')
try:
zip_path = self._pack_zip(output_path, extension_path)
self._pack_via_open_ssl(zip_path, pem_path, crx_path)
except:
logger.error("Can't build extension with OpenSSL")
if self._info.update_url != '':
manifest_path = os.path.join(extension_path, self._manifest_filename)
manifest = self._load_manifest(manifest_path)
del manifest['update_url']
self._save_manifest(manifest, manifest_path)
self._pack_zip(output_path, extension_path)
def setup_update(self, output_path):
if self._info.update_url != '' or self._info.update_path_url != '':
update_xml_filename = 'update_chrome.xml'
xml_path = os.path.join(self._kango_path, 'src', 'xml', update_xml_filename)
doc = xml.dom.minidom.parse(xml_path)
app = doc.getElementsByTagName('app')[0]
app.setAttribute('appid', self._info.id)
updatecheck = app.getElementsByTagName('updatecheck')[0]
updatecheck.setAttribute('codebase', self._info.update_path_url + self.get_full_package_name(self._info))
updatecheck.setAttribute('version', self._info.version)
with codecs.open(os.path.join(output_path, update_xml_filename), 'w', 'utf-8') as f:
doc.writexml(f, encoding='utf-8')
self._info.update_url = self._info.update_url if self._info.update_url != '' else self._info.update_path_url + update_xml_filename
def migrate(self, src_path):
pass | gpl-2.0 |
oceanscan/ros-imc-broker | workspace/src/ros_imc_broker/include/IMC/Spec/TransportBindings.hpp | 4442 | //***************************************************************************
// Copyright 2017 OceanScan - Marine Systems & Technology, Lda. *
//***************************************************************************
// Licensed under the Apache License, Version 2.0 (the "License"); *
// you may not use this file except in compliance with the License. *
// You may obtain a copy of the License at *
// *
// http://www.apache.org/licenses/LICENSE-2.0 *
// *
// Unless required by applicable law or agreed to in writing, software *
// distributed under the License is distributed on an "AS IS" BASIS, *
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
// See the License for the specific language governing permissions and *
// limitations under the License. *
//***************************************************************************
// Author: Ricardo Martins *
//***************************************************************************
// Automatically generated. *
//***************************************************************************
// IMC XML MD5: 74f41081eac3414e0a982ae6a8fe7347 *
//***************************************************************************
#ifndef IMC_TRANSPORTBINDINGS_HPP_INCLUDED_
#define IMC_TRANSPORTBINDINGS_HPP_INCLUDED_
// ISO C++ 98 headers.
#include <ostream>
#include <string>
#include <vector>
// IMC headers.
#include <IMC/Base/Config.hpp>
#include <IMC/Base/Message.hpp>
#include <IMC/Base/InlineMessage.hpp>
#include <IMC/Base/MessageList.hpp>
#include <IMC/Base/JSON.hpp>
#include <IMC/Base/Serialization.hpp>
#include <IMC/Spec/Enumerations.hpp>
#include <IMC/Spec/Bitfields.hpp>
namespace IMC
{
//! Transport Bindings.
class TransportBindings: public Message
{
public:
//! Consumer name.
std::string consumer;
//! Message Identifier.
uint16_t message_id;
static uint16_t
getIdStatic(void)
{
return 8;
}
static TransportBindings*
cast(Message* msg__)
{
return (TransportBindings*)msg__;
}
TransportBindings(void)
{
m_header.mgid = TransportBindings::getIdStatic();
clear();
}
TransportBindings*
clone(void) const
{
return new TransportBindings(*this);
}
void
clear(void)
{
consumer.clear();
message_id = 0;
}
bool
fieldsEqual(const Message& msg__) const
{
const IMC::TransportBindings& other__ = static_cast<const TransportBindings&>(msg__);
if (consumer != other__.consumer) return false;
if (message_id != other__.message_id) return false;
return true;
}
uint8_t*
serializeFields(uint8_t* bfr__) const
{
uint8_t* ptr__ = bfr__;
ptr__ += IMC::serialize(consumer, ptr__);
ptr__ += IMC::serialize(message_id, ptr__);
return ptr__;
}
size_t
deserializeFields(const uint8_t* bfr__, size_t size__)
{
const uint8_t* start__ = bfr__;
bfr__ += IMC::deserialize(consumer, bfr__, size__);
bfr__ += IMC::deserialize(message_id, bfr__, size__);
return bfr__ - start__;
}
size_t
reverseDeserializeFields(const uint8_t* bfr__, size_t size__)
{
const uint8_t* start__ = bfr__;
bfr__ += IMC::reverseDeserialize(consumer, bfr__, size__);
bfr__ += IMC::reverseDeserialize(message_id, bfr__, size__);
return bfr__ - start__;
}
uint16_t
getId(void) const
{
return TransportBindings::getIdStatic();
}
const char*
getName(void) const
{
return "TransportBindings";
}
size_t
getFixedSerializationSize(void) const
{
return 2;
}
size_t
getVariableSerializationSize(void) const
{
return IMC::getSerializationSize(consumer);
}
void
fieldsToJSON(std::ostream& os__, unsigned nindent__) const
{
IMC::toJSON(os__, "consumer", consumer, nindent__);
IMC::toJSON(os__, "message_id", message_id, nindent__);
}
};
}
#endif
| gpl-2.0 |
sublimeye/eventer | client/sources/scripts/app/home/auth.js | 148 | 'use strict';
define({
type: 'POST',
url: '/hey',
dataType: 'json',
success: function (data) {
alert(data.data);
}
});
| gpl-2.0 |
xavierhardy/ecm-clustering | src/Random/RandomExp.java | 1134 | /*
Copyright 2014, Xavier Hardy, Clément Pique
This file is part of ecm-classifier.
ecm-classifier is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ecm-classifier is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ecm-classifier. If not, see <http://www.gnu.org/licenses/>.
*/
package Random;
public class RandomExp extends AbstractRandom {
double lambda = 1;
public RandomExp(){
super();
}
public RandomExp(double lambda){
super();
this.lambda = lambda;
}
public double next(){
return - (1 / lambda) * Math.log( 1 - rnd.nextDouble() );
}
public String toString() {
return "Distribution exponentielle";
}
}
| gpl-2.0 |
Starlex/yugrarector | rsrinfo.php | 943 | <?php
include 'admin/block/db.php';
include 'blocks/header.php';
include 'blocks/menu.php';
?>
<div id='content'>
<?php
$count=0;
echo '<h2 align="center">Информация Российского Союза Ректоров</h2>';
$sql = "SELECT p_id, p_rus_name FROM rectorugra_page WHERE p_submenu = 1 AND p_parrent = 'rsrinfo'";
$query = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($query))
{
$count++;
echo '<a style="font-size:18px;" href="subcontent.php?p_id='.$row['p_id'].'">'.str_replace("_", " ", $row['p_rus_name']).'</a><br /><br />';
}
if($count==0)
{
$sql_con="SELECT p_content FROM rectorugra_page WHERE p_name = 'rsrinfo'";
$query_con=mysql_query($sql_con) or die(mysql_error());
$row_con=mysql_fetch_assoc($query_con);
echo $row_con['p_content'];
}
?>
</div>
<?php include 'blocks/footer.php';?> | gpl-2.0 |
alandow/uneeosce_backend | ad_curl.php | 2313 |
<?php
//this is a little experiment. Basically the server I was hosting on could not access the LDAP service, so I made this and hosted it elsewhere
// It takes a username, gets the details from LDAP and returns an XML with the user details.
// Modify it to suit :)
$username = $_REQUEST['user'];
try {
$error = false;
$adServer = "ldaps://ldap.someserver.edu.au";
$ldap = ldap_connect($adServer) or die('cannot connect to ldap');
$password = "password";
$ldaprdn = "username";
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($ldap, $ldaprdn, $password);
if ($bind) {
$filter = "(CN=$username)";
$result = ldap_search($ldap, "OU=Others,DC=yourorganisation,DC=edu,DC=au", $filter);
ldap_sort($ldap, $result, "sn");
$info = ldap_get_entries($ldap, $result);
if ($info["count"] > 0) {
print("<data><name>{$info[0]["displayname"][0]}</name></data>");
exit();
} else {
$error = true;
$errordetail = "The username ' . $username . ' is not a valid UoN Active Directory user";
}
}
} catch (Exception $e) {
$error = true;
// try second connection
$errordetail = "connection to server 2 failed";
}
if ($error) {
print( '<data><error>AD error</error><detail>' . $errordetail . '</detail></data>');
exit();
}
function strtotitle($title) {
// Converts $title to Title Case, and returns the result.
// Our array of 'small words' which shouldn't be capitalised if
// they aren't the first word. Add your own words to taste.
$smallwordsarray = array(
'of', 'a', 'the', 'and', 'an', 'or', 'nor', 'but', 'is', 'if', 'then', 'else', 'when',
'at', 'from', 'by', 'on', 'off', 'for', 'in', 'out', 'over', 'to', 'into', 'with'
);
// Split the string into separate words
$words = explode(' ', $title);
foreach ($words as $key => $word) {
// If this word is the first, or it's not one of our small words, capitalise it
// with ucwords().
if ($key == 0 or !in_array($word, $smallwordsarray))
$words[$key] = ucwords($word);
}
// Join the words back into a string
$newtitle = implode(' ', $words);
return $newtitle;
}
?>
| gpl-2.0 |
TeoTwawki/VirtualDub | src/VirtualDub/source/F_list.cpp | 1930 | // VirtualDub - Video processing and capture application
// Copyright (C) 1998-2001 Avery Lee
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#include "filter.h"
#include "filters.h"
#include <vd2/plugin/vdvideofilt.h>
#include <vd2/VDXFrame/VideoFilter.h>
#include <vd2/VDFilters/VFList.h>
extern const VDXFilterDefinition
#ifdef _DEBUG
filterDef_debugerror,
filterDef_debugcrop,
filterDef_showinfo,
#endif
filterDef_curves,
filterDef_resize,
filterDef_test;
extern FilterDefinition
filterDef_fill,
filterDef_levels,
filterDef_logo,
filterDef_convolute,
filterDef_emboss
;
static const FilterDefinition *const builtin_filters[]={
&filterDef_fill,
&filterDef_resize,
&filterDef_levels,
&filterDef_logo,
// &filterDef_curves,
&filterDef_convolute,
&filterDef_emboss,
#ifdef _DEBUG
&filterDef_debugerror,
&filterDef_debugcrop,
&filterDef_showinfo,
&filterDef_test,
#endif
NULL
};
void InitBuiltinFilters() {
const FilterDefinition *cur, *const *cpp;
VDXVideoFilter::SetAPIVersion(VIRTUALDUB_FILTERDEF_VERSION);
cpp = builtin_filters;
while(cur = *cpp++)
FilterAddBuiltin(cur);
cpp = VDVFGetList();
while(cur = *cpp++)
FilterAddBuiltin(cur);
}
| gpl-2.0 |
librelab/qtmoko-test | qtopiacore/qt/config.tests/unix/gstreamer/gstreamer.cpp | 2328 | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the config.tests of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <gst/gst.h>
#include <gst/interfaces/propertyprobe.h>
#include <gst/interfaces/xoverlay.h>
#if !defined(GST_VERSION_MAJOR) \
|| !defined(GST_VERSION_MINOR)
# error "No GST_VERSION_* macros"
#elif GST_VERION_MAJOR != 0 && GST_VERSION_MINOR != 10
# error "Incompatible version of GStreamer found (Version 0.10.x is required)."
#endif
int main(int argc, char **argv)
{
}
| gpl-2.0 |
BiglySoftware/BiglyBT | uis/src/com/biglybt/ui/swt/components/graphics/BackGroundGraphic.java | 4831 | /*
* File : ScaledGraphic.java
* Created : 15 d�c. 2003}
* By : Olivier
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details ( see the LICENSE file ).
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.biglybt.ui.swt.components.graphics;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import com.biglybt.core.config.COConfigurationManager;
import com.biglybt.core.internat.MessageText;
import com.biglybt.core.util.AEMonitor;
import com.biglybt.ui.swt.mainwindow.Colors;
import com.biglybt.ui.swt.utils.ColorCache;
/**
* @author Olivier
*
*/
public class BackGroundGraphic implements Graphic {
protected Canvas drawCanvas;
protected Image bufferBackground;
protected Color lightGrey;
protected Color lightGrey2;
protected Color colorWhite;
protected AEMonitor this_mon = new AEMonitor( "BackGroundGraphic" );
private boolean isSIIECSensitive;
public BackGroundGraphic() {
}
protected void
setSIIECSensitive(
boolean b )
{
isSIIECSensitive = b;
}
@Override
public void initialize(Canvas canvas) {
this.drawCanvas = canvas;
lightGrey = ColorCache.getColor(canvas.getDisplay(), 250, 250, 250);
lightGrey2 = ColorCache.getColor(canvas.getDisplay(), 233, 233, 233);
colorWhite = ColorCache.getColor(canvas.getDisplay(), 255, 255, 255);
Menu menu = new Menu( canvas );
final MenuItem mi_binary = new MenuItem( menu, SWT.CHECK );
mi_binary.setText( MessageText.getString( "label.binary.scale.basis" ));
mi_binary.setSelection( COConfigurationManager.getBooleanParameter( "ui.scaled.graphics.binary.based" ));
mi_binary.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
COConfigurationManager.setParameter("ui.scaled.graphics.binary.based", mi_binary.getSelection());
}
});
if ( isSIIECSensitive ){
final MenuItem mi_iec = new MenuItem( menu, SWT.CHECK );
mi_iec.setText( MessageText.getString( "ConfigView.section.style.useSIUnits" ));
mi_iec.setSelection( COConfigurationManager.getBooleanParameter( "config.style.useSIUnits" ));
mi_iec.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
COConfigurationManager.setParameter("config.style.useSIUnits", mi_iec.getSelection());
}
});
}
addMenuItems( menu );
canvas.setMenu( menu );
}
protected void
addMenuItems(
Menu menu )
{
}
@Override
public void refresh(boolean force) {
}
protected void drawBackGround(boolean sizeChanged) {
if(drawCanvas == null || drawCanvas.isDisposed())
return;
if(sizeChanged || bufferBackground == null) {
Rectangle bounds = drawCanvas.getClientArea();
if(bounds.height < 1 || bounds.width < 1)
return;
if(bufferBackground != null && ! bufferBackground.isDisposed())
bufferBackground.dispose();
if(bounds.width > 10000 || bounds.height > 10000) return;
bufferBackground = new Image(drawCanvas.getDisplay(),bounds);
Color colors[] = new Color[4];
colors[0] = colorWhite;
colors[1] = lightGrey;
colors[2] = lightGrey2;
colors[3] = lightGrey;
GC gcBuffer = new GC(bufferBackground);
for(int i = 0 ; i < bounds.height - 2 ; i++) {
gcBuffer.setForeground(colors[i%4]);
gcBuffer.drawLine(1,i+1,bounds.width-1,i+1);
}
gcBuffer.setForeground(Colors.black);
gcBuffer.drawLine(bounds.width-70,0,bounds.width-70,bounds.height-1);
gcBuffer.drawRectangle(0,0,bounds.width-1,bounds.height-1);
gcBuffer.dispose();
}
}
public void dispose() {
if(bufferBackground != null && ! bufferBackground.isDisposed())
bufferBackground.dispose();
}
public void setColors(Color color1, Color color2, Color color3) {
colorWhite = color1;
lightGrey = color2;
lightGrey2 = color3;
drawCanvas.redraw();
}
}
| gpl-2.0 |
kolab-groupware/kdepim | korganizer/kohelper.cpp | 2844 | /*
This file is part of KOrganizer.
Copyright (C) 2005 Reinhold Kainhofer <reinhold@kainhofer.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "kohelper.h"
#include "koprefs.h"
#include <calendarsupport/kcalprefs.h>
#include <KMessageBox>
QColor KOHelper::getTextColor( const QColor &c )
{
double luminance = ( c.red() * 0.299 ) + ( c.green() * 0.587 ) + ( c.blue() * 0.114 );
return ( luminance > 128.0 ) ? QColor( 0, 0, 0 ) : QColor( 255, 255, 255 );
}
QColor KOHelper::resourceColor( const Akonadi::Collection &coll )
{
if ( !coll.isValid() ) {
return QColor();
}
const QString id = QString::number( coll.id() );
return KOPrefs::instance()->resourceColor( id );
}
QColor KOHelper::resourceColorKnown( const Akonadi::Collection &coll )
{
if ( !coll.isValid() ) {
return QColor();
}
const QString id = QString::number( coll.id() );
return KOPrefs::instance()->resourceColorKnown( id );
}
void KOHelper::setResourceColor(const Akonadi::Collection &collection, const QColor &color)
{
if ( collection.isValid() ) {
const QString id = QString::number( collection.id() );
return KOPrefs::instance()->setResourceColor(id, color);
}
}
QColor KOHelper::resourceColor( const Akonadi::Item &item )
{
if ( !item.isValid() ) {
return QColor();
}
const QString id = QString::number( item.storageCollectionId() );
return KOPrefs::instance()->resourceColor( id );
}
int KOHelper::yearDiff( const QDate &start, const QDate &end )
{
return end.year() - start.year();
}
bool KOHelper::isStandardCalendar( const Akonadi::Entity::Id &id )
{
return id == CalendarSupport::KCalPrefs::instance()->defaultCalendarId();
}
void KOHelper::showSaveIncidenceErrorMsg( QWidget *parent,
const KCalCore::Incidence::Ptr &incidence )
{
KMessageBox::sorry(
parent,
i18n( "Unable to save %1 \"%2\".",
i18n( incidence->typeStr() ), incidence->summary() ) );
}
| gpl-2.0 |
magsilva/jortho | src/com/inet/jorthodictionaries/BookGenerator_sv.java | 1134 | /*
* JOrtho
*
* Copyright (C) 2009 by Kennet Svanberg
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Created on 03.11.2005
*/
package com.inet.jorthodictionaries;
/**
* @author Kennet Svanberg
*/
public class BookGenerator_sv extends BookGenerator {
@Override
boolean isValidLanguage( String word, String wikiText ) {
if(wikiText.indexOf("{{sv") < 0 ){
return false;
}
return true;
}
}
| gpl-2.0 |
aschnell/yast-storage-ng | src/lib/y2storage/autoinst_proposal.rb | 12911 | # Copyright (c) [2017] SUSE LLC
#
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, contact SUSE LLC.
#
# To contact SUSE LLC about this file by physical or electronic mail, you may
# find current contact information at www.suse.com.
require "yast"
require "y2storage/proposal_settings"
require "y2storage/exceptions"
require "y2storage/planned"
require "y2storage/proposal"
module Y2Storage
# Class to calculate a storage proposal for autoinstallation
#
# @example Creating a proposal from the current AutoYaST profile
# partitioning = Yast::Profile.current["partitioning"]
# proposal = Y2Storage::AutoinstProposal.new(partitioning: partitioning)
# proposal.proposed? # => false
# proposal.devices # => nil
# proposal.planned_devices # => nil
#
# proposal.propose # Performs the calculation
#
# proposal.proposed? # => true
# proposal.devices # => Proposed layout
#
class AutoinstProposal < Proposal::Base
# @return [Hash] Partitioning layout from an AutoYaST profile
attr_reader :partitioning
# @return [AutoinstIssues::List] List of found AutoYaST issues
attr_reader :issues_list
# @return [DiskSize] Missing space for the originally planned devices
attr_reader :missing_space
# Constructor
#
# @param partitioning [Array<Hash>] Partitioning schema from an AutoYaST profile
# @param proposal_settings [Y2Storage::ProposalSettings] Guided proposal settings
# @param devicegraph [Devicegraph] starting point. If nil, then probed devicegraph
# will be used
# @param disk_analyzer [DiskAnalyzer] by default, the method will create a new one
# based on the initial devicegraph or will use the one in {StorageManager} if
# starting from probed (i.e. 'devicegraph' argument is also missing)
# @param issues_list [AutoinstIssues::List] List of AutoYaST issues to register them
def initialize(partitioning: [], proposal_settings: nil, devicegraph: nil, disk_analyzer: nil,
issues_list: nil)
super(devicegraph: devicegraph, disk_analyzer: disk_analyzer)
@issues_list = issues_list || Y2Storage::AutoinstIssues::List.new
@proposal_settings = proposal_settings
@partitioning = AutoinstProfile::PartitioningSection.new_from_hashes(partitioning)
end
private
# Calculates the proposal
#
# @raise [NoDiskSpaceError] if there is no enough space to perform the installation
def calculate_proposal
drives = Proposal::AutoinstDrivesMap.new(initial_devicegraph, partitioning, issues_list)
if issues_list.fatal?
@devices = []
return @devices
end
@devices = propose_devicegraph(initial_devicegraph, drives)
end
# Proposes a devicegraph based on given drives map
#
# This method falls back to #proposed_guided_devicegraph when the device map
# does not contain any partition.
#
# @param devicegraph [Devicegraph] Starting point
# @param drives [Proposal::AutoinstDrivesMap] Devices map from an AutoYaST profile
# @return [Devicegraph] Devicegraph containing the planned devices
def propose_devicegraph(devicegraph, drives)
if drives.partitions?
@planned_devices = plan_devices(devicegraph, drives)
devicegraph = clean_graph(devicegraph, drives, @planned_devices)
add_partition_tables(devicegraph, drives)
result = create_devices(devicegraph, @planned_devices, drives.disk_names)
add_reduced_devices_issues(result)
@missing_space = result.missing_space
result.devicegraph
else
log.info "No partitions were specified. Falling back to guided setup planning."
propose_guided_devicegraph(devicegraph, drives)
end
end
# Add partition tables
#
# This method create/change partitions tables according to information
# specified in the profile. Disks containing any partition will be ignored.
#
# The devicegraph which is passed as first argument will be modified.
#
# @param devicegraph [Devicegraph] Starting point
# @param drives [Proposal::AutoinstDrivesMap] Devices map from an AutoYaST profile
def add_partition_tables(devicegraph, drives)
drives.each do |disk_name, drive_spec|
next if drive_spec.unwanted_partitions?
disk = devicegraph.disk_devices.find { |d| d.name == disk_name }
update_partition_table(disk, suitable_ptable_type(disk, drive_spec)) if disk
end
end
# Determines which partition table type should be used
#
# @param disk [Y2Storage::Disk] Disk to set the partition table on
# @param drive_spec [Y2Storage::AutoinstProfile::DriveSection] Drive section from the profile
# @return [Y2Storage::PartitionTables::Type] Partition table type
def suitable_ptable_type(disk, drive_spec)
ptable_type = nil
ptable_type = Y2Storage::PartitionTables::Type.find(drive_spec.disklabel) if drive_spec.disklabel
disk_ptable_type = disk.partition_table ? disk.partition_table.type : nil
ptable_type || disk_ptable_type || disk.preferred_ptable_type
end
# Update partition table
#
# It does nothing if current partition table type and wanted one are the same.
# The disk object is modified.
#
# @param disk [Y2Storage::Disk] Disk to set the partition table on
# @param ptable_type [Y2Storage::PartitionTables::Type] Partition table type
def update_partition_table(disk, ptable_type)
return unless update_partition_table?(disk, ptable_type)
disk.remove_descendants if disk.partition_table
disk.create_partition_table(ptable_type)
end
# Determines whether the partition table must be updated
#
# @param disk [Y2Storage::Disk] Disk to set the partition table on
# @param ptable_type [Y2Storage::PartitionTables::Type] Partition table type
def update_partition_table?(disk, ptable_type)
disk.partitions.empty? &&
(disk.partition_table.nil? || disk.partition_table.type != ptable_type)
end
# Add devices to make the system bootable
#
# The devicegraph which is passed as first argument will be modified.
#
# @param devicegraph [Devicegraph] Starting point
# @return [Array<Planned::DevicesCollection>] List of required planned devices to boot
def boot_devices(devicegraph, devices)
return unless root?(devices.mountable_devices)
checker = BootRequirementsChecker.new(devicegraph, planned_devices: devices.mountable_devices)
begin
result = checker.needed_partitions
rescue BootRequirementsChecker::Error => e
issues_list.add(:could_not_calculate_boot)
log.error e.message
result = []
end
result
end
# Determines whether the list of devices includes a root partition
#
# @param devices [Array<Planned:Device>] List of planned devices
# @return [Boolean] true if there is a root partition; false otherwise.
def root?(devices)
return true if devices.any? { |d| d.respond_to?(:mount_point) && d.mount_point == "/" }
issues_list.add(:missing_root)
end
# Finds a suitable devicegraph using the guided proposal approach
#
# If the :desired target fails, it will retry with the :min target.
#
# @param devicegraph [Devicegraph] Starting point
# @param drives [AutoinstDrivesMap] Devices map from an AutoYaST profile
# @return [Devicegraph] Proposed devicegraph using the guided proposal approach
#
# @raise [Error] No suitable devicegraph was found
# @see proposed_guided_devicegraph
def propose_guided_devicegraph(devicegraph, drives)
devicegraph = clean_graph(devicegraph, drives, [])
begin
guided_devicegraph_for_target(devicegraph, drives, :desired)
rescue Error
guided_devicegraph_for_target(devicegraph, drives, :min)
end
end
# Calculates list of planned devices
#
# If the list does not contain any partition, then it follows the same
# approach as the guided proposal
#
# @param devicegraph [Devicegraph] Starting point
# @param drives [Proposal::AutoinstDrivesMap] Devices map from an AutoYaST profile
# @return [Planned::DevicesCollection] Devices to add
def plan_devices(devicegraph, drives)
planner = Proposal::AutoinstDevicesPlanner.new(devicegraph, issues_list)
planner.planned_devices(drives)
end
# Clean a devicegraph according to an AutoYaST drives map
#
# @param devicegraph [Devicegraph] Starting point
# @param drives [AutoinstDrivesMap] Devices map from an AutoYaST profile
# @param planned_devices [<Planned::DevicesCollection>] Planned devices
# @return [Devicegraph] Clean devicegraph
#
# @see Y2Storage::Proposal::AutoinstSpaceMaker
def clean_graph(devicegraph, drives, planned_devices)
space_maker = Proposal::AutoinstSpaceMaker.new(disk_analyzer, issues_list)
space_maker.cleaned_devicegraph(devicegraph, drives, planned_devices)
end
# Creates a devicegraph using the same approach as guided partitioning
#
# @param devicegraph [Devicegraph] Starting point
# @param drives [AutoinstDrivesMap] Devices map from an AutoYaST profile
# @param target [Symbol] :desired means the sizes of the partitions should
# be the ideal ones, :min for generating the smallest functional partitions
# @return [Devicegraph] Copy of devicegraph containing the planned devices
def guided_devicegraph_for_target(devicegraph, drives, target)
guided_settings = proposal_settings_for_disks(drives)
guided_planner = Proposal::DevicesPlanner.new(guided_settings, devicegraph)
@planned_devices = Planned::DevicesCollection.new(guided_planner.planned_devices(target))
result = create_devices(devicegraph, @planned_devices, drives.disk_names)
result.devicegraph
end
# Creates planned devices on a given devicegraph
#
# If adding boot devices makes impossible to create the rest of devices,
# it will try again without them. In such a case, it will register an
# issue.
#
# As a side effect, it updates the planned devices list if needed.
#
# @param devicegraph [Devicegraph] Starting point
# @param planned_devices [Planned::DevicesCollection] Devices to add
# @param disk_names [Array<String>] Names of the disks to consider
# @return [Devicegraph] Copy of devicegraph containing the planned devices
def create_devices(devicegraph, planned_devices, disk_names)
boot_parts = boot_devices(devicegraph, @planned_devices)
devices_creator = Proposal::AutoinstDevicesCreator.new(devicegraph, issues_list)
begin
planned_with_boot = planned_devices.prepend(boot_parts)
result = devices_creator.populated_devicegraph(planned_with_boot, disk_names)
@planned_devices = planned_with_boot
rescue Y2Storage::NoDiskSpaceError
raise if boot_parts.empty?
result = devices_creator.populated_devicegraph(planned_devices, disk_names)
issues_list.add(:could_not_create_boot, boot_parts)
end
result
end
# Add shrinked devices to the issues list
#
# @param result [Proposal::CreatorResult] Result after creating the planned devices
def add_reduced_devices_issues(result)
if !result.shrinked_partitions.empty?
issues_list.add(:shrinked_planned_devices, result.shrinked_partitions)
end
issues_list.add(:shrinked_planned_devices, result.shrinked_lvs) if !result.shrinked_lvs.empty?
end
# Returns the product's proposal settings for a given set of disks
#
# @param drives [Proposal::AutoinstDrivesMap] Devices map from an AutoYaST profile
# @return [ProposalSettings] Proposal settings considering only the given disks
#
# @see Y2Storage::BlkDevice#name
def proposal_settings_for_disks(drives)
settings = @proposal_settings || ProposalSettings.new_for_current_product
settings.use_snapshots = drives.use_snapshots?
settings.candidate_devices = drives.disk_names
settings
end
end
end
| gpl-2.0 |
sinelaw/keepass | KeePass/Forms/PwEntryForm.cs | 60153 | /*
KeePass Password Safe - The Open-Source Password Manager
Copyright (C) 2003-2014 Dominik Reichl <dominik.reichl@t-online.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Diagnostics;
using KeePass.App;
using KeePass.App.Configuration;
using KeePass.Native;
using KeePass.Resources;
using KeePass.UI;
using KeePass.Util;
using KeePassLib;
using KeePassLib.Collections;
using KeePassLib.Cryptography;
using KeePassLib.Cryptography.PasswordGenerator;
using KeePassLib.Delegates;
using KeePassLib.Security;
using KeePassLib.Utility;
namespace KeePass.Forms
{
public enum PwEditMode
{
Invalid = 0,
AddNewEntry,
EditExistingEntry,
ViewReadOnlyEntry
}
public partial class PwEntryForm : Form
{
private PwEditMode m_pwEditMode = PwEditMode.Invalid;
private PwDatabase m_pwDatabase = null;
private bool m_bShowAdvancedByDefault = false;
private bool m_bSelectFullTitle = false;
private PwEntry m_pwEntry = null;
private PwEntry m_pwInitialEntry = null;
private ProtectedStringDictionary m_vStrings = null;
private ProtectedBinaryDictionary m_vBinaries = null;
private AutoTypeConfig m_atConfig = null;
private PwObjectList<PwEntry> m_vHistory = null;
private Color m_clrForeground = Color.Empty;
private Color m_clrBackground = Color.Empty;
private PwIcon m_pwEntryIcon = PwIcon.Key;
private PwUuid m_pwCustomIconID = PwUuid.Zero;
private ImageList m_ilIcons = null;
private bool m_bLockEnabledState = false;
private bool m_bTouchedOnce = false;
private bool m_bInitializing = false;
private bool m_bForceClosing = false;
private PwInputControlGroup m_icgPassword = new PwInputControlGroup();
private ExpiryControlGroup m_cgExpiry = new ExpiryControlGroup();
private RichTextBoxContextMenu m_ctxNotes = new RichTextBoxContextMenu();
private Image m_imgPwGen = null;
private Image m_imgStdExpire = null;
private List<Image> m_lOverrideUrlIcons = new List<Image>();
private ContextMenuStrip m_ctxBinOpen = null;
private DynamicMenu m_dynBinOpen = null;
private readonly string DeriveFromPrevious = "(" +
KPRes.GenPwBasedOnPrevious + ")";
private readonly string AutoGenProfile = "(" +
KPRes.AutoGeneratedPasswordSettings + ")";
private DynamicMenu m_dynGenProfiles;
private const PwIcon m_pwObjectProtected = PwIcon.PaperLocked;
private const PwIcon m_pwObjectPlainText = PwIcon.PaperNew;
public event EventHandler<CancellableOperationEventArgs> EntrySaving;
public event EventHandler EntrySaved;
private const PwCompareOptions m_cmpOpt = (PwCompareOptions.NullEmptyEquivStd |
PwCompareOptions.IgnoreTimes);
public bool HasModifiedEntry
{
get
{
if((m_pwEntry == null) || (m_pwInitialEntry == null))
{
Debug.Assert(false);
return true;
}
return !m_pwEntry.EqualsEntry(m_pwInitialEntry, m_cmpOpt,
MemProtCmpMode.CustomOnly);
}
}
public PwEntry EntryRef { get { return m_pwEntry; } }
public ProtectedStringDictionary EntryStrings { get { return m_vStrings; } }
public ProtectedBinaryDictionary EntryBinaries { get { return m_vBinaries; } }
public ContextMenuStrip ToolsContextMenu
{
get { return m_ctxTools; }
}
public ContextMenuStrip DefaultTimesContextMenu
{
get { return m_ctxDefaultTimes; }
}
public ContextMenuStrip ListOperationsContextMenu
{
get { return m_ctxListOperations; }
}
public ContextMenuStrip PasswordGeneratorContextMenu
{
get { return m_ctxPwGen; }
}
public ContextMenuStrip StandardStringMovementContextMenu
{
get { return m_ctxStrMoveToStandard; }
}
public ContextMenuStrip AttachmentsContextMenu
{
get { return m_ctxBinAttach; }
}
private bool m_bInitSwitchToHistory = false;
internal bool InitSwitchToHistoryTab
{
// get { return m_bInitSwitchToHistory; } // Internal, uncalled
set { m_bInitSwitchToHistory = value; }
}
public PwEntryForm()
{
InitializeComponent();
Program.Translation.ApplyTo(this);
Program.Translation.ApplyTo("KeePass.Forms.PwEntryForm.m_ctxTools", m_ctxTools.Items);
Program.Translation.ApplyTo("KeePass.Forms.PwEntryForm.m_ctxDefaultTimes", m_ctxDefaultTimes.Items);
Program.Translation.ApplyTo("KeePass.Forms.PwEntryForm.m_ctxListOperations", m_ctxListOperations.Items);
Program.Translation.ApplyTo("KeePass.Forms.PwEntryForm.m_ctxPwGen", m_ctxPwGen.Items);
Program.Translation.ApplyTo("KeePass.Forms.PwEntryForm.m_ctxStrMoveToStandard", m_ctxStrMoveToStandard.Items);
Program.Translation.ApplyTo("KeePass.Forms.PwEntryForm.m_ctxBinAttach", m_ctxBinAttach.Items);
}
public void InitEx(PwEntry pwEntry, PwEditMode pwMode, PwDatabase pwDatabase,
ImageList ilIcons, bool bShowAdvancedByDefault, bool bSelectFullTitle)
{
Debug.Assert(pwEntry != null); if(pwEntry == null) throw new ArgumentNullException("pwEntry");
Debug.Assert(pwMode != PwEditMode.Invalid); if(pwMode == PwEditMode.Invalid) throw new ArgumentException();
Debug.Assert(ilIcons != null); if(ilIcons == null) throw new ArgumentNullException("ilIcons");
m_pwEntry = pwEntry;
m_pwEditMode = pwMode;
m_pwDatabase = pwDatabase;
m_ilIcons = ilIcons;
m_bShowAdvancedByDefault = bShowAdvancedByDefault;
m_bSelectFullTitle = bSelectFullTitle;
m_vStrings = m_pwEntry.Strings.CloneDeep();
m_vBinaries = m_pwEntry.Binaries.CloneDeep();
m_atConfig = m_pwEntry.AutoType.CloneDeep();
m_vHistory = m_pwEntry.History.CloneDeep();
}
private void InitEntryTab()
{
m_pwEntryIcon = m_pwEntry.IconId;
m_pwCustomIconID = m_pwEntry.CustomIconUuid;
if(!m_pwCustomIconID.Equals(PwUuid.Zero))
{
// int nInx = (int)PwIcon.Count + m_pwDatabase.GetCustomIconIndex(m_pwCustomIconID);
// if((nInx > -1) && (nInx < m_ilIcons.Images.Count))
// m_btnIcon.Image = m_ilIcons.Images[nInx];
// else m_btnIcon.Image = m_ilIcons.Images[(int)m_pwEntryIcon];
Image imgCustom = m_pwDatabase.GetCustomIcon(m_pwCustomIconID);
// m_btnIcon.Image = (imgCustom ?? m_ilIcons.Images[(int)m_pwEntryIcon]);
UIUtil.SetButtonImage(m_btnIcon, (imgCustom ?? m_ilIcons.Images[
(int)m_pwEntryIcon]), true);
}
else
{
// m_btnIcon.Image = m_ilIcons.Images[(int)m_pwEntryIcon];
UIUtil.SetButtonImage(m_btnIcon, m_ilIcons.Images[
(int)m_pwEntryIcon], true);
}
bool bHideInitial = m_cbHidePassword.Checked;
m_icgPassword.Attach(m_tbPassword, m_cbHidePassword, m_lblPasswordRepeat,
m_tbRepeatPassword, m_lblQuality, m_pbQuality, m_lblQualityBitsText,
this, bHideInitial, false);
if(m_pwEntry.Expires)
{
m_dtExpireDateTime.Value = m_pwEntry.ExpiryTime;
m_cbExpires.Checked = true;
}
else // Does not expire
{
m_dtExpireDateTime.Value = DateTime.Now.Date;
m_cbExpires.Checked = false;
}
m_cgExpiry.Attach(m_cbExpires, m_dtExpireDateTime);
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
{
m_tbTitle.ReadOnly = m_tbUserName.ReadOnly = m_tbPassword.ReadOnly =
m_tbRepeatPassword.ReadOnly = m_tbUrl.ReadOnly =
m_rtNotes.ReadOnly = true;
m_btnIcon.Enabled = m_btnGenPw.Enabled = m_cbExpires.Enabled =
m_dtExpireDateTime.Enabled =
m_btnStandardExpires.Enabled = false;
m_rtNotes.SelectAll();
m_rtNotes.BackColor = m_rtNotes.SelectionBackColor =
AppDefs.ColorControlDisabled;
m_rtNotes.DeselectAll();
m_ctxToolsUrlSelApp.Enabled = m_ctxToolsUrlSelDoc.Enabled = false;
m_ctxToolsFieldRefsInTitle.Enabled = m_ctxToolsFieldRefsInUserName.Enabled =
m_ctxToolsFieldRefsInPassword.Enabled = m_ctxToolsFieldRefsInUrl.Enabled =
m_ctxToolsFieldRefsInNotes.Enabled = false;
m_ctxToolsFieldRefs.Enabled = false;
m_btnOK.Enabled = false;
}
// Show URL in blue, if it's black in the current visual theme
if(m_tbUrl.ForeColor.ToArgb() == Color.Black.ToArgb())
m_tbUrl.ForeColor = Color.Blue;
}
private void InitAdvancedTab()
{
m_lvStrings.SmallImageList = m_ilIcons;
m_lvBinaries.SmallImageList = m_ilIcons;
int nWidth = m_lvStrings.ClientRectangle.Width / 2;
m_lvStrings.Columns.Add(KPRes.FieldName, nWidth);
m_lvStrings.Columns.Add(KPRes.FieldValue, nWidth);
nWidth = m_lvBinaries.ClientRectangle.Width / 2;
m_lvBinaries.Columns.Add(KPRes.Attachments, nWidth);
m_lvBinaries.Columns.Add(KPRes.Size, nWidth, HorizontalAlignment.Right);
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
{
m_btnStrAdd.Enabled = m_btnStrEdit.Enabled =
m_btnStrDelete.Enabled = m_btnStrMove.Enabled =
m_btnBinAdd.Enabled = m_btnBinDelete.Enabled = false;
// Always available:
// m_btnBinOpen.Enabled = m_btnBinSave.Enabled = false;
m_lvBinaries.LabelEdit = false;
}
}
// Public for plugins
public void UpdateEntryStrings(bool bGuiToInternal, bool bSetRepeatPw)
{
if(bGuiToInternal)
{
m_vStrings.Set(PwDefs.TitleField, new ProtectedString(m_pwDatabase.MemoryProtection.ProtectTitle,
m_tbTitle.Text));
m_vStrings.Set(PwDefs.UserNameField, new ProtectedString(m_pwDatabase.MemoryProtection.ProtectUserName,
m_tbUserName.Text));
byte[] pb = m_icgPassword.GetPasswordUtf8();
m_vStrings.Set(PwDefs.PasswordField, new ProtectedString(m_pwDatabase.MemoryProtection.ProtectPassword,
pb));
MemUtil.ZeroByteArray(pb);
m_vStrings.Set(PwDefs.UrlField, new ProtectedString(m_pwDatabase.MemoryProtection.ProtectUrl,
m_tbUrl.Text));
m_vStrings.Set(PwDefs.NotesField, new ProtectedString(m_pwDatabase.MemoryProtection.ProtectNotes,
m_rtNotes.Text));
}
else // Internal to GUI
{
m_tbTitle.Text = m_vStrings.ReadSafe(PwDefs.TitleField);
m_tbUserName.Text = m_vStrings.ReadSafe(PwDefs.UserNameField);
byte[] pb = m_vStrings.GetSafe(PwDefs.PasswordField).ReadUtf8();
m_icgPassword.SetPassword(pb, bSetRepeatPw);
MemUtil.ZeroByteArray(pb);
m_tbUrl.Text = m_vStrings.ReadSafe(PwDefs.UrlField);
m_rtNotes.Text = m_vStrings.ReadSafe(PwDefs.NotesField);
int iTopVisible = UIUtil.GetTopVisibleItem(m_lvStrings);
m_lvStrings.Items.Clear();
foreach(KeyValuePair<string, ProtectedString> kvpStr in m_vStrings)
{
if(!PwDefs.IsStandardField(kvpStr.Key))
{
PwIcon pwIcon = (kvpStr.Value.IsProtected ? m_pwObjectProtected :
m_pwObjectPlainText);
ListViewItem lvi = m_lvStrings.Items.Add(kvpStr.Key, (int)pwIcon);
if(kvpStr.Value.IsProtected)
lvi.SubItems.Add(PwDefs.HiddenPassword);
else
{
string strValue = StrUtil.MultiToSingleLine(
kvpStr.Value.ReadString());
lvi.SubItems.Add(strValue);
}
}
}
UIUtil.SetTopVisibleItem(m_lvStrings, iTopVisible);
}
}
// Public for plugins
public void UpdateEntryBinaries(bool bGuiToInternal)
{
UpdateEntryBinaries(bGuiToInternal, false, null);
}
public void UpdateEntryBinaries(bool bGuiToInternal, bool bUpdateState)
{
UpdateEntryBinaries(bGuiToInternal, bUpdateState, null);
}
public void UpdateEntryBinaries(bool bGuiToInternal, bool bUpdateState,
string strFocusItem)
{
if(bGuiToInternal) { }
else // Internal to GUI
{
int iTopVisible = UIUtil.GetTopVisibleItem(m_lvBinaries);
m_lvBinaries.Items.Clear();
foreach(KeyValuePair<string, ProtectedBinary> kvpBin in m_vBinaries)
{
PwIcon pwIcon = (kvpBin.Value.IsProtected ?
m_pwObjectProtected : m_pwObjectPlainText);
ListViewItem lvi = m_lvBinaries.Items.Add(kvpBin.Key, (int)pwIcon);
lvi.SubItems.Add(StrUtil.FormatDataSizeKB(kvpBin.Value.Length));
}
UIUtil.SetTopVisibleItem(m_lvBinaries, iTopVisible);
if(strFocusItem != null)
{
ListViewItem lvi = m_lvBinaries.FindItemWithText(strFocusItem,
false, 0, false);
if(lvi != null)
{
m_lvBinaries.EnsureVisible(lvi.Index);
UIUtil.SetFocusedItem(m_lvBinaries, lvi, true);
}
else { Debug.Assert(false); }
}
}
if(bUpdateState) EnableControlsEx();
}
internal static Image CreateColorButtonImage(Button btn, Color clr)
{
return UIUtil.CreateColorBitmap24(btn.ClientRectangle.Width - 8,
btn.ClientRectangle.Height - 8, clr);
}
private void InitPropertiesTab()
{
m_clrForeground = m_pwEntry.ForegroundColor;
m_clrBackground = m_pwEntry.BackgroundColor;
if(m_clrForeground != Color.Empty)
UIUtil.SetButtonImage(m_btnPickFgColor, CreateColorButtonImage(
m_btnPickFgColor, m_clrForeground), false);
if(m_clrBackground != Color.Empty)
UIUtil.SetButtonImage(m_btnPickBgColor, CreateColorButtonImage(
m_btnPickBgColor, m_clrBackground), false);
m_cbCustomForegroundColor.Checked = (m_clrForeground != Color.Empty);
m_cbCustomBackgroundColor.Checked = (m_clrBackground != Color.Empty);
m_cmbOverrideUrl.Text = m_pwEntry.OverrideUrl;
m_tbTags.Text = StrUtil.TagsToString(m_pwEntry.Tags, true);
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
{
m_cbCustomForegroundColor.Enabled = false;
m_cbCustomBackgroundColor.Enabled = false;
m_btnPickFgColor.Enabled = false;
m_btnPickBgColor.Enabled = false;
m_cmbOverrideUrl.Enabled = false;
m_tbTags.ReadOnly = true;
}
m_tbUuid.Text = m_pwEntry.Uuid.ToHexString();
}
private void InitAutoTypeTab()
{
m_lvAutoType.SmallImageList = m_ilIcons;
m_cbAutoTypeEnabled.Checked = m_atConfig.Enabled;
m_cbAutoTypeObfuscation.Checked = !(m_atConfig.ObfuscationOptions ==
AutoTypeObfuscationOptions.None);
string strDefaultSeq = m_atConfig.DefaultSequence;
if(strDefaultSeq.Length > 0) m_rbAutoTypeOverride.Checked = true;
else m_rbAutoTypeSeqInherit.Checked = true;
if(strDefaultSeq.Length == 0)
{
PwGroup pg = m_pwEntry.ParentGroup;
if(pg != null)
{
strDefaultSeq = pg.GetAutoTypeSequenceInherited();
if(strDefaultSeq.Length == 0)
{
if(PwDefs.IsTanEntry(m_pwEntry))
strDefaultSeq = PwDefs.DefaultAutoTypeSequenceTan;
else
strDefaultSeq = PwDefs.DefaultAutoTypeSequence;
}
}
}
m_tbDefaultAutoTypeSeq.Text = strDefaultSeq;
int nWidth = m_lvAutoType.ClientRectangle.Width / 2;
m_lvAutoType.Columns.Add(KPRes.TargetWindow, nWidth);
m_lvAutoType.Columns.Add(KPRes.Sequence, nWidth);
UpdateAutoTypeList();
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
{
m_cbAutoTypeEnabled.Enabled = m_cbAutoTypeObfuscation.Enabled =
m_rbAutoTypeSeqInherit.Enabled =
m_rbAutoTypeOverride.Enabled = m_btnAutoTypeAdd.Enabled =
m_btnAutoTypeDelete.Enabled = m_btnAutoTypeEdit.Enabled = false;
m_tbDefaultAutoTypeSeq.Enabled = m_btnAutoTypeEditDefault.Enabled =
false;
}
}
private void UpdateAutoTypeList()
{
m_lvAutoType.Items.Clear();
string strDefault = "(" + KPRes.Default + ")";
foreach(AutoTypeAssociation a in m_atConfig.Associations)
{
ListViewItem lvi = m_lvAutoType.Items.Add(a.WindowName, (int)PwIcon.List);
lvi.SubItems.Add((a.Sequence.Length > 0) ? a.Sequence : strDefault);
}
}
private void InitHistoryTab()
{
m_lvHistory.SmallImageList = m_ilIcons;
m_lvHistory.Columns.Add(KPRes.Version);
m_lvHistory.Columns.Add(KPRes.Title);
m_lvHistory.Columns.Add(KPRes.UserName);
m_lvHistory.Columns.Add(KPRes.Size, 72, HorizontalAlignment.Right);
UpdateHistoryList();
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
{
m_btnHistoryDelete.Enabled = m_btnHistoryRestore.Enabled =
m_btnHistoryView.Enabled = false;
}
}
private void UpdateHistoryList()
{
m_lvHistory.Items.Clear();
foreach(PwEntry pe in m_vHistory)
{
ListViewItem lvi = m_lvHistory.Items.Add(TimeUtil.ToDisplayString(
pe.LastModificationTime), (int)pe.IconId);
lvi.SubItems.Add(pe.Strings.ReadSafe(PwDefs.TitleField));
lvi.SubItems.Add(pe.Strings.ReadSafe(PwDefs.UserNameField));
lvi.SubItems.Add(StrUtil.FormatDataSizeKB(pe.GetSize()));
}
}
private void ResizeColumnHeaders()
{
Debug.Assert(m_lvStrings.Columns.Count == 2);
int dx = m_lvStrings.ClientRectangle.Width;
m_lvStrings.Columns[0].Width = dx / 2;
m_lvStrings.Columns[1].Width = dx / 2;
Debug.Assert(m_lvBinaries.Columns.Count == 2);
dx = m_lvBinaries.ClientRectangle.Width;
m_lvBinaries.Columns[0].Width = (dx * 4) / 5;
m_lvBinaries.Columns[1].Width = dx / 5;
Debug.Assert(m_lvAutoType.Columns.Count == 2);
dx = m_lvAutoType.ClientRectangle.Width;
m_lvAutoType.Columns[0].Width = m_lvAutoType.Columns[1].Width = dx / 2;
Debug.Assert(m_lvHistory.Columns.Count == 4);
dx = m_lvHistory.ClientRectangle.Width;
int dt = dx / 85;
m_lvHistory.Columns[0].Width = (dx * 2) / 7 + dt;
m_lvHistory.Columns[1].Width = (dx * 2) / 7;
m_lvHistory.Columns[2].Width = ((dx * 2) / 7) - (dt * 2);
m_lvHistory.Columns[3].Width = (dx / 7) + dt;
}
private void OnFormLoad(object sender, EventArgs e)
{
Debug.Assert(m_pwEntry != null); if(m_pwEntry == null) throw new InvalidOperationException();
Debug.Assert(m_pwEditMode != PwEditMode.Invalid); if(m_pwEditMode == PwEditMode.Invalid) throw new ArgumentException();
Debug.Assert(m_pwDatabase != null); if(m_pwDatabase == null) throw new InvalidOperationException();
Debug.Assert(m_ilIcons != null); if(m_ilIcons == null) throw new InvalidOperationException();
GlobalWindowManager.AddWindow(this);
GlobalWindowManager.CustomizeControl(m_ctxTools);
GlobalWindowManager.CustomizeControl(m_ctxPwGen);
GlobalWindowManager.CustomizeControl(m_ctxStrMoveToStandard);
m_pwInitialEntry = m_pwEntry.CloneDeep();
StrUtil.NormalizeNewLines(m_pwInitialEntry.Strings, true);
m_ttRect.SetToolTip(m_btnIcon, KPRes.SelectIcon);
m_ttRect.SetToolTip(m_cbHidePassword, KPRes.TogglePasswordAsterisks);
m_ttRect.SetToolTip(m_btnGenPw, KPRes.GeneratePassword);
m_ttRect.SetToolTip(m_btnStandardExpires, KPRes.StandardExpireSelect);
m_ttBalloon.SetToolTip(m_tbRepeatPassword, KPRes.PasswordRepeatHint);
m_dynGenProfiles = new DynamicMenu(m_ctxPwGen.Items);
m_dynGenProfiles.MenuClick += this.OnProfilesDynamicMenuClick;
m_ctxNotes.Attach(m_rtNotes, this);
m_ctxBinOpen = new ContextMenuStrip();
m_ctxBinOpen.Opening += this.OnCtxBinOpenOpening;
m_dynBinOpen = new DynamicMenu(m_ctxBinOpen.Items);
m_dynBinOpen.MenuClick += this.OnDynBinOpen;
m_btnBinOpen.SplitDropDownMenu = m_ctxBinOpen;
string strTitle = string.Empty, strDesc = string.Empty;
if(m_pwEditMode == PwEditMode.AddNewEntry)
{
strTitle = KPRes.AddEntry;
strDesc = KPRes.AddEntryDesc;
}
else if(m_pwEditMode == PwEditMode.EditExistingEntry)
{
strTitle = KPRes.EditEntry;
strDesc = KPRes.EditEntryDesc;
}
else if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
{
strTitle = KPRes.ViewEntry;
strDesc = KPRes.ViewEntryDesc;
}
else { Debug.Assert(false); }
BannerFactory.CreateBannerEx(this, m_bannerImage,
KeePass.Properties.Resources.B48x48_KGPG_Sign, strTitle, strDesc);
this.Icon = Properties.Resources.KeePass;
this.Text = strTitle;
m_imgPwGen = UIUtil.CreateDropDownImage(Properties.Resources.B16x16_Key_New);
m_imgStdExpire = UIUtil.CreateDropDownImage(Properties.Resources.B16x16_History);
UIUtil.SetButtonImage(m_btnTools,
Properties.Resources.B16x16_Package_Settings, true);
UIUtil.SetButtonImage(m_btnGenPw, m_imgPwGen, true);
UIUtil.SetButtonImage(m_btnStandardExpires, m_imgStdExpire, true);
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
m_bLockEnabledState = true;
// UIUtil.SetExplorerTheme(m_lvStrings, true);
// UIUtil.SetExplorerTheme(m_lvBinaries, true);
// UIUtil.SetExplorerTheme(m_lvAutoType, true);
// UIUtil.SetExplorerTheme(m_lvHistory, true);
UIUtil.PrepareStandardMultilineControl(m_rtNotes, true, true);
m_bInitializing = true;
bool bForceHide = !AppPolicy.Current.UnhidePasswords;
if(Program.Config.UI.Hiding.SeparateHidingSettings)
m_cbHidePassword.Checked = (Program.Config.UI.Hiding.HideInEntryWindow || bForceHide);
else
{
AceColumn colPw = Program.Config.MainWindow.FindColumn(AceColumnType.Password);
m_cbHidePassword.Checked = (((colPw != null) ? colPw.HideWithAsterisks :
true) || bForceHide);
}
InitEntryTab();
InitAdvancedTab();
InitPropertiesTab();
InitAutoTypeTab();
InitHistoryTab();
UpdateEntryStrings(false, true);
UpdateEntryBinaries(false, false);
if(PwDefs.IsTanEntry(m_pwEntry)) m_btnTools.Enabled = false;
CustomizeForScreenReader();
m_bInitializing = false;
if(m_bInitSwitchToHistory) // Before 'Advanced' tab switch
m_tabMain.SelectedTab = m_tabHistory;
else if(m_bShowAdvancedByDefault)
m_tabMain.SelectedTab = m_tabAdvanced;
ResizeColumnHeaders();
EnableControlsEx();
ThreadPool.QueueUserWorkItem(delegate(object state)
{
try { InitOverridesBox(); }
catch(Exception) { Debug.Assert(false); }
});
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
m_btnCancel.Select();
else
{
if(m_bSelectFullTitle) m_tbTitle.Select(0, m_tbTitle.TextLength);
else m_tbTitle.Select(0, 0);
m_tbTitle.Select();
}
}
private void CustomizeForScreenReader()
{
if(!Program.Config.UI.OptimizeForScreenReader) return;
m_btnIcon.Text = KPRes.PickIcon;
m_cbHidePassword.Text = KPRes.HideUsingAsterisks;
m_btnGenPw.Text = m_ttRect.GetToolTip(m_btnGenPw);
m_btnStandardExpires.Text = m_ttRect.GetToolTip(m_btnStandardExpires);
m_btnPickFgColor.Text = KPRes.SelectColor;
m_btnPickBgColor.Text = KPRes.SelectColor;
}
private void EnableControlsEx()
{
if(m_bInitializing) return;
int nStringsSel = m_lvStrings.SelectedItems.Count;
int nBinSel = m_lvBinaries.SelectedItems.Count;
m_btnBinOpen.Enabled = (nBinSel == 1);
m_btnBinSave.Enabled = (nBinSel >= 1);
if(m_bLockEnabledState) return;
m_btnStrEdit.Enabled = (nStringsSel == 1);
m_btnStrDelete.Enabled = (nStringsSel >= 1);
m_btnBinDelete.Enabled = (nBinSel >= 1);
m_btnPickFgColor.Enabled = m_cbCustomForegroundColor.Checked;
m_btnPickBgColor.Enabled = m_cbCustomBackgroundColor.Checked;
bool bATEnabled = m_cbAutoTypeEnabled.Checked;
m_lvAutoType.Enabled = m_btnAutoTypeAdd.Enabled =
m_rbAutoTypeSeqInherit.Enabled = m_rbAutoTypeOverride.Enabled =
m_cbAutoTypeObfuscation.Enabled = bATEnabled;
if(!m_rbAutoTypeOverride.Checked)
m_tbDefaultAutoTypeSeq.Enabled = m_btnAutoTypeEditDefault.Enabled = false;
else
m_tbDefaultAutoTypeSeq.Enabled = m_btnAutoTypeEditDefault.Enabled =
bATEnabled;
int nAutoTypeSel = m_lvAutoType.SelectedItems.Count;
if(m_pwEditMode != PwEditMode.ViewReadOnlyEntry)
{
m_btnAutoTypeEdit.Enabled = (bATEnabled && (nAutoTypeSel == 1));
m_btnAutoTypeDelete.Enabled = (bATEnabled && (nAutoTypeSel >= 1));
}
int nAccumSel = nStringsSel + nBinSel + nAutoTypeSel;
m_menuListCtxCopyFieldValue.Enabled = (nAccumSel != 0);
int nHistorySel = m_lvHistory.SelectedIndices.Count;
m_btnHistoryRestore.Enabled = (nHistorySel == 1);
m_btnHistoryDelete.Enabled = m_btnHistoryView.Enabled = (nHistorySel >= 1);
m_menuListCtxMoveStandardTitle.Enabled = m_menuListCtxMoveStandardUser.Enabled =
m_menuListCtxMoveStandardPassword.Enabled = m_menuListCtxMoveStandardURL.Enabled =
m_menuListCtxMoveStandardNotes.Enabled = m_btnStrMove.Enabled =
(nStringsSel == 1);
}
private bool SaveEntry(PwEntry peTarget, bool bValidate)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return true;
if(bValidate && !m_icgPassword.ValidateData(true)) return false;
if(this.EntrySaving != null)
{
CancellableOperationEventArgs eaCancel = new CancellableOperationEventArgs();
this.EntrySaving(this, eaCancel);
if(eaCancel.Cancel) return false;
}
peTarget.History = m_vHistory; // Must be called before CreateBackup()
bool bCreateBackup = (m_pwEditMode != PwEditMode.AddNewEntry);
if(bCreateBackup) peTarget.CreateBackup(null);
peTarget.IconId = m_pwEntryIcon;
peTarget.CustomIconUuid = m_pwCustomIconID;
if(m_cbCustomForegroundColor.Checked)
peTarget.ForegroundColor = m_clrForeground;
else peTarget.ForegroundColor = Color.Empty;
if(m_cbCustomBackgroundColor.Checked)
peTarget.BackgroundColor = m_clrBackground;
else peTarget.BackgroundColor = Color.Empty;
peTarget.OverrideUrl = m_cmbOverrideUrl.Text;
List<string> vNewTags = StrUtil.StringToTags(m_tbTags.Text);
peTarget.Tags.Clear();
foreach(string strTag in vNewTags) peTarget.AddTag(strTag);
peTarget.Expires = m_cgExpiry.Checked;
if(peTarget.Expires) peTarget.ExpiryTime = m_cgExpiry.Value;
UpdateEntryStrings(true, false);
peTarget.Strings = m_vStrings;
peTarget.Binaries = m_vBinaries;
m_atConfig.Enabled = m_cbAutoTypeEnabled.Checked;
m_atConfig.ObfuscationOptions = (m_cbAutoTypeObfuscation.Checked ?
AutoTypeObfuscationOptions.UseClipboard :
AutoTypeObfuscationOptions.None);
SaveDefaultSeq();
peTarget.AutoType = m_atConfig;
peTarget.Touch(true, false); // Touch *after* backup
if(object.ReferenceEquals(peTarget, m_pwEntry)) m_bTouchedOnce = true;
StrUtil.NormalizeNewLines(peTarget.Strings, true);
bool bUndoBackup = false;
PwCompareOptions cmpOpt = m_cmpOpt;
if(bCreateBackup) cmpOpt |= PwCompareOptions.IgnoreLastBackup;
if(peTarget.EqualsEntry(m_pwInitialEntry, cmpOpt, MemProtCmpMode.CustomOnly))
{
// No modifications at all => restore last mod time and undo backup
peTarget.LastModificationTime = m_pwInitialEntry.LastModificationTime;
bUndoBackup = bCreateBackup;
}
else if(bCreateBackup)
{
// If only history items have been modified (deleted) => undo
// backup, but without restoring the last mod time
PwCompareOptions cmpOptNH = (m_cmpOpt | PwCompareOptions.IgnoreHistory);
if(peTarget.EqualsEntry(m_pwInitialEntry, cmpOptNH, MemProtCmpMode.CustomOnly))
bUndoBackup = true;
}
if(bUndoBackup) peTarget.History.RemoveAt(peTarget.History.UCount - 1);
peTarget.MaintainBackups(m_pwDatabase);
if(this.EntrySaved != null) this.EntrySaved(this, EventArgs.Empty);
return true;
}
private void SaveDefaultSeq()
{
if(m_rbAutoTypeSeqInherit.Checked)
m_atConfig.DefaultSequence = string.Empty;
else if(m_rbAutoTypeOverride.Checked)
m_atConfig.DefaultSequence = m_tbDefaultAutoTypeSeq.Text;
else { Debug.Assert(false); }
}
private void OnBtnOK(object sender, EventArgs e)
{
if(SaveEntry(m_pwEntry, true)) m_bForceClosing = true;
else this.DialogResult = DialogResult.None;
}
private void OnBtnCancel(object sender, EventArgs e)
{
m_bForceClosing = true;
try
{
ushort usEsc = NativeMethods.GetAsyncKeyState((int)Keys.Escape);
if((usEsc & 0x8000) != 0) m_bForceClosing = false;
}
catch(Exception) { Debug.Assert(KeePassLib.Native.NativeLib.IsUnix()); }
}
private void CleanUpEx()
{
m_dynGenProfiles.MenuClick -= this.OnProfilesDynamicMenuClick;
m_dynGenProfiles.Clear();
m_btnBinOpen.SplitDropDownMenu = null;
m_dynBinOpen.MenuClick -= this.OnDynBinOpen;
m_dynBinOpen.Clear();
m_ctxBinOpen.Opening -= this.OnCtxBinOpenOpening;
m_ctxBinOpen.Dispose();
if(m_pwEditMode != PwEditMode.ViewReadOnlyEntry)
Program.Config.UI.Hiding.HideInEntryWindow = m_cbHidePassword.Checked;
m_ctxNotes.Detach();
m_icgPassword.Release();
m_cgExpiry.Release();
m_cmbOverrideUrl.OrderedImageList = null;
foreach(Image img in m_lOverrideUrlIcons)
{
if(img != null) img.Dispose();
}
m_lOverrideUrlIcons.Clear();
// Detach event handlers
m_lvStrings.SmallImageList = null;
m_lvBinaries.SmallImageList = null;
m_lvAutoType.SmallImageList = null;
m_lvHistory.SmallImageList = null;
m_btnGenPw.Image = null;
m_imgPwGen.Dispose();
m_imgPwGen = null;
m_btnStandardExpires.Image = null;
m_imgStdExpire.Dispose();
m_imgStdExpire = null;
}
private void OnBtnStrAdd(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
UpdateEntryStrings(true, false);
EditStringForm esf = new EditStringForm();
esf.InitEx(m_vStrings, null, null, m_pwDatabase);
if(UIUtil.ShowDialogAndDestroy(esf) == DialogResult.OK)
{
UpdateEntryStrings(false, false);
ResizeColumnHeaders();
}
}
private void OnBtnStrEdit(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
ListView.SelectedListViewItemCollection vSel = m_lvStrings.SelectedItems;
if(vSel.Count <= 0) return;
UpdateEntryStrings(true, false);
string strName = vSel[0].Text;
ProtectedString psValue = m_vStrings.Get(strName);
Debug.Assert(psValue != null);
EditStringForm esf = new EditStringForm();
esf.InitEx(m_vStrings, strName, psValue, m_pwDatabase);
if(UIUtil.ShowDialogAndDestroy(esf) == DialogResult.OK)
UpdateEntryStrings(false, false);
}
private void OnBtnStrDelete(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
UpdateEntryStrings(true, false);
ListView.SelectedListViewItemCollection lvsicSel = m_lvStrings.SelectedItems;
for(int i = 0; i < lvsicSel.Count; ++i)
{
if(!m_vStrings.Remove(lvsicSel[i].Text)) { Debug.Assert(false); }
}
if(lvsicSel.Count > 0)
{
UpdateEntryStrings(false, false);
ResizeColumnHeaders();
}
}
private void OnBtnBinAdd(object sender, EventArgs e)
{
m_ctxBinAttach.Show(m_btnBinAdd, new Point(0, m_btnBinAdd.Height));
}
private void OnBtnBinDelete(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
UpdateEntryBinaries(true, false);
ListView.SelectedListViewItemCollection lvsc = m_lvBinaries.SelectedItems;
int nSelCount = lvsc.Count;
if(nSelCount == 0) { Debug.Assert(false); return; }
for(int i = 0; i < nSelCount; ++i)
m_vBinaries.Remove(lvsc[nSelCount - i - 1].Text);
UpdateEntryBinaries(false, true);
ResizeColumnHeaders();
}
private void OnBtnBinSave(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection lvsc = m_lvBinaries.SelectedItems;
int nSelCount = lvsc.Count;
if(nSelCount == 0) { Debug.Assert(false); return; }
if(nSelCount == 1)
{
SaveFileDialogEx sfd = UIUtil.CreateSaveFileDialog(KPRes.AttachmentSave,
lvsc[0].Text, UIUtil.CreateFileTypeFilter(null, null, true), 1, null,
AppDefs.FileDialogContext.Attachments);
if(sfd.ShowDialog() == DialogResult.OK)
SaveAttachmentTo(lvsc[0], sfd.FileName, false);
}
else // nSelCount > 1
{
FolderBrowserDialog fbd = UIUtil.CreateFolderBrowserDialog(KPRes.AttachmentsSave);
if(fbd.ShowDialog() == DialogResult.OK)
{
string strRootPath = UrlUtil.EnsureTerminatingSeparator(fbd.SelectedPath, false);
foreach(ListViewItem lvi in lvsc)
SaveAttachmentTo(lvi, strRootPath + lvi.Text, true);
}
fbd.Dispose();
}
}
private void SaveAttachmentTo(ListViewItem lvi, string strFileName,
bool bConfirmOverwrite)
{
Debug.Assert(lvi != null); if(lvi == null) throw new ArgumentNullException("lvi");
Debug.Assert(strFileName != null); if(strFileName == null) throw new ArgumentNullException("strFileName");
if(bConfirmOverwrite && File.Exists(strFileName))
{
string strMsg = KPRes.FileExistsAlready + MessageService.NewLine +
strFileName + MessageService.NewParagraph +
KPRes.OverwriteExistingFileQuestion;
if(MessageService.AskYesNo(strMsg) == false)
return;
}
ProtectedBinary pb = m_vBinaries.Get(lvi.Text);
Debug.Assert(pb != null); if(pb == null) throw new ArgumentException();
byte[] pbData = pb.ReadData();
try { File.WriteAllBytes(strFileName, pbData); }
catch(Exception exWrite)
{
MessageService.ShowWarning(strFileName, exWrite);
}
MemUtil.ZeroByteArray(pbData);
}
private void OnBtnAutoTypeAdd(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
EditAutoTypeItemForm dlg = new EditAutoTypeItemForm();
dlg.InitEx(m_atConfig, -1, false, m_tbDefaultAutoTypeSeq.Text, m_vStrings);
if(UIUtil.ShowDialogAndDestroy(dlg) == DialogResult.OK)
{
UpdateAutoTypeList();
ResizeColumnHeaders();
}
}
private void OnBtnAutoTypeEdit(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
ListView.SelectedIndexCollection lvSel = m_lvAutoType.SelectedIndices;
Debug.Assert(lvSel.Count == 1); if(lvSel.Count != 1) return;
EditAutoTypeItemForm dlg = new EditAutoTypeItemForm();
dlg.InitEx(m_atConfig, lvSel[0], false, m_tbDefaultAutoTypeSeq.Text,
m_vStrings);
if(UIUtil.ShowDialogAndDestroy(dlg) == DialogResult.OK)
UpdateAutoTypeList();
}
private void OnBtnAutoTypeDelete(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
int j, nItemCount = m_lvAutoType.Items.Count;
for(int i = 0; i < nItemCount; ++i)
{
j = nItemCount - i - 1;
if(m_lvAutoType.Items[j].Selected)
m_atConfig.RemoveAt(j);
}
UpdateAutoTypeList();
ResizeColumnHeaders();
}
private void OnBtnHistoryView(object sender, EventArgs e)
{
Debug.Assert(m_vHistory.UCount == m_lvHistory.Items.Count);
ListView.SelectedIndexCollection lvsi = m_lvHistory.SelectedIndices;
if(lvsi.Count != 1) { Debug.Assert(false); return; }
PwEntry pe = m_vHistory.GetAt((uint)lvsi[0]);
if(pe == null) { Debug.Assert(false); return; }
PwEntryForm pwf = new PwEntryForm();
pwf.InitEx(pe, PwEditMode.ViewReadOnlyEntry, m_pwDatabase,
m_ilIcons, false, false);
UIUtil.ShowDialogAndDestroy(pwf);
}
private void OnBtnHistoryDelete(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
Debug.Assert(m_vHistory.UCount == m_lvHistory.Items.Count);
ListView.SelectedIndexCollection lvsi = m_lvHistory.SelectedIndices;
int nSelCount = lvsi.Count;
if(nSelCount == 0) return;
for(int i = 0; i < lvsi.Count; ++i)
m_vHistory.Remove(m_vHistory.GetAt((uint)lvsi[nSelCount - i - 1]));
UpdateHistoryList();
ResizeColumnHeaders();
}
private void OnBtnHistoryRestore(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
Debug.Assert(m_vHistory.UCount == m_lvHistory.Items.Count);
ListView.SelectedIndexCollection lvsi = m_lvHistory.SelectedIndices;
if(lvsi.Count != 1) { Debug.Assert(false); return; }
m_pwEntry.RestoreFromBackup((uint)lvsi[0], m_pwDatabase);
m_pwEntry.Touch(true, false);
m_bTouchedOnce = true;
this.DialogResult = DialogResult.OK; // Doesn't invoke OnBtnOK
}
private void OnHistorySelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnStringsSelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnBinariesSelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void SetExpireIn(int nYears, int nMonths, int nDays)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
DateTime dt = DateTime.Now.Date;
dt = dt.AddYears(nYears);
dt = dt.AddMonths(nMonths);
dt = dt.AddDays(nDays);
DateTime dtPrevTime = m_cgExpiry.Value;
dt = dt.AddHours(dtPrevTime.Hour);
dt = dt.AddMinutes(dtPrevTime.Minute);
dt = dt.AddSeconds(dtPrevTime.Second);
m_cgExpiry.Checked = true;
m_cgExpiry.Value = dt;
EnableControlsEx();
}
private void OnMenuExpireNow(object sender, EventArgs e)
{
SetExpireIn(0, 0, 0);
}
private void OnMenuExpire1Week(object sender, EventArgs e)
{
SetExpireIn(0, 0, 7);
}
private void OnMenuExpire2Weeks(object sender, EventArgs e)
{
SetExpireIn(0, 0, 14);
}
private void OnMenuExpire1Month(object sender, EventArgs e)
{
SetExpireIn(0, 1, 0);
}
private void OnMenuExpire3Months(object sender, EventArgs e)
{
SetExpireIn(0, 3, 0);
}
private void OnMenuExpire6Months(object sender, EventArgs e)
{
SetExpireIn(0, 6, 0);
}
private void OnMenuExpire1Year(object sender, EventArgs e)
{
SetExpireIn(1, 0, 0);
}
private void OnBtnStandardExpiresClick(object sender, EventArgs e)
{
m_ctxDefaultTimes.Show(m_btnStandardExpires, 0, m_btnStandardExpires.Height);
}
private void OnCtxCopyFieldValue(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection lvsc;
if(m_lvStrings.Focused)
{
lvsc = m_lvStrings.SelectedItems;
if((lvsc != null) && (lvsc.Count > 0))
{
string strName = lvsc[0].Text;
ClipboardUtil.Copy(m_vStrings.ReadSafe(strName), true, true,
null, m_pwDatabase, this.Handle);
}
}
else if(m_lvAutoType.Focused)
{
lvsc = m_lvAutoType.SelectedItems;
if((lvsc != null) && (lvsc.Count > 0))
ClipboardUtil.Copy(lvsc[0].SubItems[1].Text, true, true, null,
m_pwDatabase, this.Handle);
}
else { Debug.Assert(false); }
}
private void OnBtnPickIcon(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
IconPickerForm ipf = new IconPickerForm();
ipf.InitEx(m_ilIcons, (uint)PwIcon.Count, m_pwDatabase,
(uint)m_pwEntryIcon, m_pwCustomIconID);
if(ipf.ShowDialog() == DialogResult.OK)
{
if(!ipf.ChosenCustomIconUuid.Equals(PwUuid.Zero)) // Custom icon
{
m_pwCustomIconID = ipf.ChosenCustomIconUuid;
UIUtil.SetButtonImage(m_btnIcon, m_pwDatabase.GetCustomIcon(
m_pwCustomIconID), true);
}
else // Standard icon
{
m_pwEntryIcon = (PwIcon)ipf.ChosenIconId;
m_pwCustomIconID = PwUuid.Zero;
UIUtil.SetButtonImage(m_btnIcon, m_ilIcons.Images[
(int)m_pwEntryIcon], true);
}
}
UIUtil.DestroyForm(ipf);
}
private void OnAutoTypeSeqInheritCheckedChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnAutoTypeEnableCheckedChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnBtnAutoTypeEditDefault(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
SaveDefaultSeq();
EditAutoTypeItemForm ef = new EditAutoTypeItemForm();
ef.InitEx(m_atConfig, -1, true, m_tbDefaultAutoTypeSeq.Text, m_vStrings);
if(UIUtil.ShowDialogAndDestroy(ef) == DialogResult.OK)
m_tbDefaultAutoTypeSeq.Text = m_atConfig.DefaultSequence;
}
private void OnCtxMoveToTitle(object sender, EventArgs e)
{
MoveSelectedStringTo(PwDefs.TitleField);
}
private void OnCtxMoveToUserName(object sender, EventArgs e)
{
MoveSelectedStringTo(PwDefs.UserNameField);
}
private void OnCtxMoveToPassword(object sender, EventArgs e)
{
MoveSelectedStringTo(PwDefs.PasswordField);
}
private void OnCtxMoveToURL(object sender, EventArgs e)
{
MoveSelectedStringTo(PwDefs.UrlField);
}
private void OnCtxMoveToNotes(object sender, EventArgs e)
{
MoveSelectedStringTo(PwDefs.NotesField);
}
private void MoveSelectedStringTo(string strStandardField)
{
ListView.SelectedListViewItemCollection lvsic = m_lvStrings.SelectedItems;
Debug.Assert(lvsic.Count == 1); if(lvsic.Count != 1) return;
ListViewItem lvi = lvsic[0];
string strText = m_vStrings.ReadSafe(lvi.Text);
if(strStandardField == PwDefs.TitleField)
{
if((m_tbTitle.TextLength > 0) && (strText.Length > 0))
m_tbTitle.Text += ", ";
m_tbTitle.Text += strText;
}
else if(strStandardField == PwDefs.UserNameField)
{
if((m_tbUserName.TextLength > 0) && (strText.Length > 0))
m_tbUserName.Text += ", ";
m_tbUserName.Text += strText;
}
else if(strStandardField == PwDefs.PasswordField)
{
string strPw = m_icgPassword.GetPassword();
if((strPw.Length > 0) && (strText.Length > 0)) strPw += ", ";
strPw += strText;
string strRep = m_icgPassword.GetRepeat();
if((strRep.Length > 0) && (strText.Length > 0)) strRep += ", ";
strRep += strText;
m_icgPassword.SetPasswords(strPw, strRep);
}
else if(strStandardField == PwDefs.UrlField)
{
if((m_tbUrl.TextLength > 0) && (strText.Length > 0))
m_tbUrl.Text += ", ";
m_tbUrl.Text += strText;
}
else if(strStandardField == PwDefs.NotesField)
{
if((m_rtNotes.TextLength > 0) && (strText.Length > 0))
m_rtNotes.Text += MessageService.NewParagraph;
m_rtNotes.Text += strText;
}
else { Debug.Assert(false); }
UpdateEntryStrings(true, false);
m_vStrings.Remove(lvi.Text);
UpdateEntryStrings(false, false);
EnableControlsEx();
}
private void OnBtnStrMove(object sender, EventArgs e)
{
m_ctxStrMoveToStandard.Show(m_btnStrMove, 0, m_btnStrMove.Height);
}
private void OnNotesLinkClicked(object sender, LinkClickedEventArgs e)
{
WinUtil.OpenUrl(e.LinkText, m_pwEntry);
}
private void OnAutoTypeSelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnAutoTypeItemActivate(object sender, EventArgs e)
{
OnBtnAutoTypeEdit(sender, e);
}
private void OnStringsItemActivate(object sender, EventArgs e)
{
OnBtnStrEdit(sender, e);
}
private void OnPwGenOpen(object sender, EventArgs e)
{
byte[] pbCurPassword = m_icgPassword.GetPasswordUtf8();
bool bAtLeastOneChar = (pbCurPassword.Length > 0);
ProtectedString ps = new ProtectedString(true, pbCurPassword);
Array.Clear(pbCurPassword, 0, pbCurPassword.Length);
PwProfile opt = PwProfile.DeriveFromPassword(ps);
PwGeneratorForm pgf = new PwGeneratorForm();
pgf.InitEx((bAtLeastOneChar ? opt : null), true, false);
if(pgf.ShowDialog() == DialogResult.OK)
{
byte[] pbEntropy = EntropyForm.CollectEntropyIfEnabled(pgf.SelectedProfile);
ProtectedString psNew;
PwGenerator.Generate(out psNew, pgf.SelectedProfile, pbEntropy,
Program.PwGeneratorPool);
byte[] pbNew = psNew.ReadUtf8();
m_icgPassword.SetPassword(pbNew, true);
MemUtil.ZeroByteArray(pbNew);
}
UIUtil.DestroyForm(pgf);
EnableControlsEx();
}
private void OnProfilesDynamicMenuClick(object sender, DynamicMenuEventArgs e)
{
PwProfile pwp = null;
if(e.ItemName == DeriveFromPrevious)
{
byte[] pbCur = m_icgPassword.GetPasswordUtf8();
ProtectedString psCur = new ProtectedString(true, pbCur);
MemUtil.ZeroByteArray(pbCur);
pwp = PwProfile.DeriveFromPassword(psCur);
}
else if(e.ItemName == AutoGenProfile)
pwp = Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile;
else
{
foreach(PwProfile pwgo in PwGeneratorUtil.GetAllProfiles(false))
{
if(pwgo.Name == e.ItemName)
{
pwp = pwgo;
break;
}
}
}
if(pwp != null)
{
ProtectedString psNew;
PwGenerator.Generate(out psNew, pwp, null, Program.PwGeneratorPool);
byte[] pbNew = psNew.ReadUtf8();
m_icgPassword.SetPassword(pbNew, true);
MemUtil.ZeroByteArray(pbNew);
}
else { Debug.Assert(false); }
}
private void OnPwGenClick(object sender, EventArgs e)
{
m_dynGenProfiles.Clear();
m_dynGenProfiles.AddSeparator();
m_dynGenProfiles.AddItem(DeriveFromPrevious, Properties.Resources.B16x16_CompFile);
m_dynGenProfiles.AddItem(AutoGenProfile, Properties.Resources.B16x16_FileNew);
bool bHideBuiltIn = ((Program.Config.UI.UIFlags &
(ulong)AceUIFlags.HideBuiltInPwGenPrfInEntryDlg) != 0);
List<KeyValuePair<string, Image>> l = new List<KeyValuePair<string, Image>>();
foreach(PwProfile pwgo in PwGeneratorUtil.GetAllProfiles(true))
{
if((pwgo.Name != DeriveFromPrevious) && (pwgo.Name != AutoGenProfile))
{
if(bHideBuiltIn && PwGeneratorUtil.IsBuiltInProfile(pwgo.Name))
continue;
l.Add(new KeyValuePair<string, Image>(pwgo.Name,
Properties.Resources.B16x16_KOrganizer));
}
}
if(l.Count > 0) m_dynGenProfiles.AddSeparator();
foreach(KeyValuePair<string, Image> kvp in l)
m_dynGenProfiles.AddItem(kvp.Key, kvp.Value);
m_ctxPwGen.Show(m_btnGenPw, new Point(0, m_btnGenPw.Height));
}
private void OnPickForegroundColor(object sender, EventArgs e)
{
Color? clr = UIUtil.ShowColorDialog(m_clrForeground);
if(clr.HasValue)
{
m_clrForeground = clr.Value;
UIUtil.SetButtonImage(m_btnPickFgColor, CreateColorButtonImage(
m_btnPickFgColor, m_clrForeground), false);
}
}
private void OnPickBackgroundColor(object sender, EventArgs e)
{
Color? clr = UIUtil.ShowColorDialog(m_clrBackground);
if(clr.HasValue)
{
m_clrBackground = clr.Value;
UIUtil.SetButtonImage(m_btnPickBgColor, CreateColorButtonImage(
m_btnPickBgColor, m_clrBackground), false);
}
}
private void OnCustomForegroundColorCheckedChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnCustomBackgroundColorCheckedChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnFormClosed(object sender, FormClosedEventArgs e)
{
GlobalWindowManager.RemoveWindow(this);
}
private void OnAutoTypeObfuscationLink(object sender, LinkLabelLinkClickedEventArgs e)
{
if(e.Button == MouseButtons.Left)
AppHelp.ShowHelp(AppDefs.HelpTopics.AutoTypeObfuscation, null);
}
private void OnAutoTypeObfuscationCheckedChanged(object sender, EventArgs e)
{
if(m_bInitializing) return;
if(m_cbAutoTypeObfuscation.Checked == false) return;
MessageService.ShowInfo(KPRes.AutoTypeObfuscationHint,
KPRes.DocumentationHint);
}
private bool GetSelBin(out string strDataItem, out ProtectedBinary pb)
{
strDataItem = null;
pb = null;
ListView.SelectedListViewItemCollection lvsic = m_lvBinaries.SelectedItems;
if((lvsic == null) || (lvsic.Count != 1)) return false; // No assert
strDataItem = lvsic[0].Text;
pb = m_vBinaries.Get(strDataItem);
if(pb == null) { Debug.Assert(false); return false; }
return true;
}
private void OpenSelBin(BinaryDataOpenOptions optBase)
{
string strDataItem;
ProtectedBinary pb;
if(!GetSelBin(out strDataItem, out pb)) return;
BinaryDataOpenOptions opt = ((optBase != null) ? optBase.CloneDeep() :
new BinaryDataOpenOptions());
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry)
{
if(optBase == null)
opt.Handler = BinaryDataHandler.InternalViewer;
opt.ReadOnly = true;
}
ProtectedBinary pbMod = BinaryDataUtil.Open(strDataItem, pb, opt);
if(pbMod != null)
{
m_vBinaries.Set(strDataItem, pbMod);
UpdateEntryBinaries(false, true, strDataItem); // Update size
}
}
private void OnBtnBinOpen(object sender, EventArgs e)
{
OpenSelBin(null);
}
private void OnDynBinOpen(object sender, DynamicMenuEventArgs e)
{
if(e == null) { Debug.Assert(false); return; }
BinaryDataOpenOptions opt = (e.Tag as BinaryDataOpenOptions);
if(opt == null) { Debug.Assert(false); return; }
OpenSelBin(opt);
}
private void OnCtxBinOpenOpening(object sender, CancelEventArgs e)
{
string strDataItem;
ProtectedBinary pb;
if(!GetSelBin(out strDataItem, out pb))
{
e.Cancel = true;
return;
}
BinaryDataUtil.BuildOpenWithMenu(m_dynBinOpen, strDataItem, pb,
(m_pwEditMode == PwEditMode.ViewReadOnlyEntry));
}
private void OnBtnTools(object sender, EventArgs e)
{
m_ctxTools.Show(m_btnTools, 0, m_btnTools.Height);
}
private void OnCtxToolsHelp(object sender, EventArgs e)
{
if(m_tabMain.SelectedTab == m_tabAdvanced)
AppHelp.ShowHelp(AppDefs.HelpTopics.Entry, AppDefs.HelpTopics.EntryStrings);
else if(m_tabMain.SelectedTab == m_tabAutoType)
AppHelp.ShowHelp(AppDefs.HelpTopics.Entry, AppDefs.HelpTopics.EntryAutoType);
else if(m_tabMain.SelectedTab == m_tabHistory)
AppHelp.ShowHelp(AppDefs.HelpTopics.Entry, AppDefs.HelpTopics.EntryHistory);
else
AppHelp.ShowHelp(AppDefs.HelpTopics.Entry, null);
}
private void OnCtxUrlHelp(object sender, EventArgs e)
{
AppHelp.ShowHelp(AppDefs.HelpTopics.UrlField, null);
}
private void SelectFileAsUrl(string strFilter)
{
string strFlt = string.Empty;
if(strFilter != null) strFlt += strFilter;
strFlt += KPRes.AllFiles + @" (*.*)|*.*";
OpenFileDialogEx dlg = UIUtil.CreateOpenFileDialog(null, strFlt, 1, null,
false, AppDefs.FileDialogContext.Attachments);
if(dlg.ShowDialog() == DialogResult.OK)
m_tbUrl.Text = "cmd://\"" + dlg.FileName + "\"";
}
private void OnCtxUrlSelApp(object sender, EventArgs e)
{
SelectFileAsUrl(KPRes.Application + @" (*.exe, *.com, *.bat, *.cmd)|" +
@"*.exe;*.com;*.bat;*.cmd|");
}
private void OnCtxUrlSelDoc(object sender, EventArgs e)
{
SelectFileAsUrl(null);
}
private string CreateFieldReference()
{
FieldRefForm dlg = new FieldRefForm();
dlg.InitEx(m_pwDatabase.RootGroup, m_ilIcons);
string strResult = string.Empty;
if(dlg.ShowDialog() == DialogResult.OK) strResult = dlg.ResultReference;
UIUtil.DestroyForm(dlg);
return strResult;
}
private void OnFieldRefInTitle(object sender, EventArgs e)
{
m_tbTitle.Text += CreateFieldReference();
}
private void OnFieldRefInUserName(object sender, EventArgs e)
{
m_tbUserName.Text += CreateFieldReference();
}
private void OnFieldRefInPassword(object sender, EventArgs e)
{
string strRef = CreateFieldReference();
if(strRef.Length == 0) return;
string strPw = m_icgPassword.GetPassword();
string strRep = m_icgPassword.GetRepeat();
m_icgPassword.SetPasswords(strPw + strRef, strRep + strRef);
}
private void OnFieldRefInUrl(object sender, EventArgs e)
{
m_tbUrl.Text += CreateFieldReference();
}
private void OnFieldRefInNotes(object sender, EventArgs e)
{
string strRef = CreateFieldReference();
if(m_rtNotes.Text.Length == 0) m_rtNotes.Text = strRef;
else m_rtNotes.Text += "\r\n" + strRef;
}
protected override bool ProcessDialogKey(Keys keyData)
{
if(((keyData == Keys.Return) || (keyData == Keys.Enter)) && m_rtNotes.Focused)
return false; // Forward to RichTextBox
return base.ProcessDialogKey(keyData);
}
private bool m_bClosing = false; // Mono bug workaround
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
if(m_bClosing) return;
m_bClosing = true;
HandleFormClosing(e);
m_bClosing = false;
}
private void HandleFormClosing(FormClosingEventArgs e)
{
bool bCancel = false;
if(!m_bForceClosing && (m_pwEditMode != PwEditMode.ViewReadOnlyEntry))
{
PwEntry pe = m_pwInitialEntry.CloneDeep();
SaveEntry(pe, false);
bool bModified = !pe.EqualsEntry(m_pwInitialEntry, m_cmpOpt,
MemProtCmpMode.CustomOnly);
bModified |= !m_icgPassword.ValidateData(false);
if(bModified)
{
DialogResult dr = MessageService.Ask(KPRes.SaveBeforeCloseQuestion,
PwDefs.ShortProductName, MessageBoxButtons.YesNoCancel);
if((dr == DialogResult.Yes) || (dr == DialogResult.OK))
{
bCancel = !SaveEntry(m_pwEntry, true);
if(!bCancel) this.DialogResult = DialogResult.OK;
}
else if(dr == DialogResult.Cancel) bCancel = true;
}
}
if(bCancel)
{
this.DialogResult = DialogResult.None;
e.Cancel = true;
return;
}
if(!m_bTouchedOnce) m_pwEntry.Touch(false, false);
CleanUpEx();
}
private void OnBinariesItemActivate(object sender, EventArgs e)
{
OnBtnBinOpen(sender, e);
}
private void OnHistoryItemActivate(object sender, EventArgs e)
{
OnBtnHistoryView(sender, e);
}
private void OnCtxBinImport(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
OpenFileDialogEx ofd = UIUtil.CreateOpenFileDialog(KPRes.AttachFiles,
UIUtil.CreateFileTypeFilter(null, null, true), 1, null, true,
AppDefs.FileDialogContext.Attachments);
if(ofd.ShowDialog() == DialogResult.OK)
BinImportFiles(ofd.FileNames);
}
private void BinImportFiles(string[] vPaths)
{
if(vPaths == null) { Debug.Assert(false); return; }
UpdateEntryBinaries(true, false);
foreach(string strFile in vPaths)
{
if(string.IsNullOrEmpty(strFile)) { Debug.Assert(false); continue; }
byte[] vBytes = null;
string strMsg, strItem = UrlUtil.GetFileName(strFile);
if(m_vBinaries.Get(strItem) != null)
{
strMsg = KPRes.AttachedExistsAlready + MessageService.NewLine +
strItem + MessageService.NewParagraph + KPRes.AttachNewRename +
MessageService.NewParagraph + KPRes.AttachNewRenameRemarks0 +
MessageService.NewLine + KPRes.AttachNewRenameRemarks1 +
MessageService.NewLine + KPRes.AttachNewRenameRemarks2;
DialogResult dr = MessageService.Ask(strMsg, null,
MessageBoxButtons.YesNoCancel);
if(dr == DialogResult.Cancel) continue;
else if(dr == DialogResult.Yes)
{
string strFileName = UrlUtil.StripExtension(strItem);
string strExtension = "." + UrlUtil.GetExtension(strItem);
int nTry = 0;
while(true)
{
string strNewName = strFileName + nTry.ToString() + strExtension;
if(m_vBinaries.Get(strNewName) == null)
{
strItem = strNewName;
break;
}
++nTry;
}
}
}
try
{
vBytes = File.ReadAllBytes(strFile);
vBytes = DataEditorForm.ConvertAttachment(strItem, vBytes);
if(vBytes != null)
{
ProtectedBinary pb = new ProtectedBinary(false, vBytes);
m_vBinaries.Set(strItem, pb);
}
}
catch(Exception exAttach)
{
MessageService.ShowWarning(KPRes.AttachFailed, strFile, exAttach);
}
}
UpdateEntryBinaries(false, true);
ResizeColumnHeaders();
}
private void OnCtxBinNew(object sender, EventArgs e)
{
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
string strName;
for(int i = 0; ; ++i)
{
strName = KPRes.New;
if(i >= 1) strName += " (" + i.ToString() + ")";
strName += ".rtf";
if(m_vBinaries.Get(strName) == null) break;
}
ProtectedBinary pb = new ProtectedBinary();
m_vBinaries.Set(strName, pb);
UpdateEntryBinaries(false, true, strName);
ResizeColumnHeaders();
ListViewItem lviNew = m_lvBinaries.FindItemWithText(strName,
false, 0, false);
if(lviNew != null) lviNew.BeginEdit();
}
private void OnBinAfterLabelEdit(object sender, LabelEditEventArgs e)
{
string strNew = e.Label;
e.CancelEdit = true; // In the case of success, we update it on our own
if(string.IsNullOrEmpty(strNew)) return;
if(m_pwEditMode == PwEditMode.ViewReadOnlyEntry) return;
int iItem = e.Item;
if((iItem < 0) || (iItem >= m_lvBinaries.Items.Count)) return;
string strOld = m_lvBinaries.Items[iItem].Text;
if(strNew == strOld) return;
if(m_vBinaries.Get(strNew) != null)
{
MessageService.ShowWarning(KPRes.FieldNameExistsAlready);
return;
}
ProtectedBinary pb = m_vBinaries.Get(strOld);
if(pb == null) { Debug.Assert(false); return; }
m_vBinaries.Remove(strOld);
m_vBinaries.Set(strNew, pb);
UpdateEntryBinaries(false, true, strNew);
}
private static void BinDragAccept(DragEventArgs e)
{
if(e == null) { Debug.Assert(false); return; }
IDataObject ido = e.Data;
if((ido == null) || !ido.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.None;
else e.Effect = DragDropEffects.Copy;
}
private void OnBinDragEnter(object sender, DragEventArgs e)
{
BinDragAccept(e);
}
private void OnBinDragOver(object sender, DragEventArgs e)
{
BinDragAccept(e);
}
private void OnBinDragDrop(object sender, DragEventArgs e)
{
try
{
BinImportFiles(e.Data.GetData(DataFormats.FileDrop) as string[]);
}
catch(Exception) { Debug.Assert(false); }
}
private void InitOverridesBox()
{
List<KeyValuePair<string, Image>> l = new List<KeyValuePair<string, Image>>();
AddOverrideUrlItem(l, "cmd://{INTERNETEXPLORER} \"{URL}\"",
AppLocator.InternetExplorerPath);
AddOverrideUrlItem(l, "cmd://{FIREFOX} \"{URL}\"",
AppLocator.FirefoxPath);
AddOverrideUrlItem(l, "cmd://{OPERA} \"{URL}\"",
AppLocator.OperaPath);
AddOverrideUrlItem(l, "cmd://{GOOGLECHROME} \"{URL}\"",
AppLocator.ChromePath);
AddOverrideUrlItem(l, "cmd://{SAFARI} \"{URL}\"",
AppLocator.SafariPath);
Debug.Assert(m_cmbOverrideUrl.InvokeRequired);
VoidDelegate f = delegate()
{
try
{
Debug.Assert(!m_cmbOverrideUrl.InvokeRequired);
foreach(KeyValuePair<string, Image> kvp in l)
{
m_cmbOverrideUrl.Items.Add(kvp.Key);
m_lOverrideUrlIcons.Add(kvp.Value);
}
m_cmbOverrideUrl.OrderedImageList = m_lOverrideUrlIcons;
}
catch(Exception) { Debug.Assert(false); }
};
m_cmbOverrideUrl.Invoke(f);
}
private void AddOverrideUrlItem(List<KeyValuePair<string, Image>> l,
string strOverride, string strIconPath)
{
if(string.IsNullOrEmpty(strOverride)) { Debug.Assert(false); return; }
const int qSize = 16;
Image img = null;
string str = UrlUtil.GetQuotedAppPath(strIconPath ?? string.Empty);
str = str.Trim();
if(str.Length > 0) img = UIUtil.GetFileIcon(str, qSize, qSize);
if(img == null)
img = UIUtil.CreateScaledImage(m_ilIcons.Images[
(int)PwIcon.Console], qSize, qSize);
l.Add(new KeyValuePair<string, Image>(strOverride, img));
}
}
}
| gpl-2.0 |
raedkleelsame/phpmyadmin | themes/pmahomme/css/common.css.php | 55593 | <?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Common styles for the pmahomme theme
*
* @package PhpMyAdmin-theme
* @subpackage PMAHomme
*/
// unplanned execution path
if (! defined('PMA_MINIMUM_COMMON') && ! defined('TESTSUITE')) {
exit();
}
?>
/******************************************************************************/
/* general tags */
html {
font-size: <?php echo $_SESSION['PMA_Theme']->getFontSize(); ?>
}
input,
select,
textarea {
font-size: 1em;
}
body {
<?php if (! empty($GLOBALS['cfg']['FontFamily'])) { ?>
font-family: <?php echo $GLOBALS['cfg']['FontFamily']; ?>;
<?php } ?>
padding: 0;
margin: 0;
margin-<?php echo $left; ?>: 240px;
color: #444;
background: #fff;
}
body#loginform {
margin: 0;
}
#page_content {
margin: 0 .5em;
}
<?php if (! empty($GLOBALS['cfg']['FontFamilyFixed'])) { ?>
textarea,
tt,
pre,
code {
font-family: <?php echo $GLOBALS['cfg']['FontFamilyFixed']; ?>;
}
<?php } ?>
h1 {
font-size: 140%;
font-weight: bold;
}
h2 {
font-size: 2em;
font-weight: normal;
text-shadow: 0 1px 0 #fff;
padding: 10px 0 10px;
padding-<?php echo $left; ?>: 3px;
color: #777;
}
/* Hiding icons in the page titles */
h2 img {
display: none;
}
h2 a img {
display: inline;
}
.data,
.data_full_width {
margin: 0 0 12px;
}
.data_full_width {
width: 100%;
}
#table_results td.data {
border-right: 1px solid #bbb;
}
h3 {
font-weight: bold;
}
a,
a:link,
a:visited,
a:active {
text-decoration: none;
color: #235a81;
cursor: pointer;
outline: none;
}
a:hover {
text-decoration: underline;
color: #235a81;
}
#initials_table {
background: #f3f3f3;
border: 1px solid #aaa;
margin-bottom: 10px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
}
#initials_table td {
padding: 8px !important;
}
#initials_table a {
border: 1px solid #aaa;
background: #fff;
padding: 4px 8px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
<?php echo $_SESSION['PMA_Theme']->getCssGradient('ffffff', 'e0e0e0'); ?>
}
#initials_table a.active {
border: 1px solid #666;
box-shadow: 0 0 2px #999;
<?php echo $_SESSION['PMA_Theme']->getCssGradient('bbbbbb', 'ffffff'); ?>
}
dfn {
font-style: normal;
}
dfn:hover {
font-style: normal;
cursor: help;
}
th {
font-weight: bold;
color: <?php echo $GLOBALS['cfg']['ThColor']; ?>;
background: #f3f3f3;
<?php echo $_SESSION['PMA_Theme']->getCssGradient('ffffff', 'cccccc'); ?>
}
a img {
border: 0;
}
hr {
color: <?php echo $GLOBALS['cfg']['MainColor']; ?>;
background-color: <?php echo $GLOBALS['cfg']['MainColor']; ?>;
border: 0;
height: 1px;
}
form {
padding: 0;
margin: 0;
display: inline;
}
input,
select {
/* Fix outline in Chrome: */
outline: none;
}
input[type=text],
input[type=password],
input[type=number],
input[type=date] {
border-radius: 2px;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
background: white;
border: 1px solid #aaa;
color: #555;
padding: 4px;
margin: 6px;
}
input[type=text],
input[type=password],
input[type=number],
input[type=date],
select {
transition: all 0.2s;
-ms-transition: all 0.2s;
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
}
input[type=text][disabled],
input[type=text][disabled]:hover,
input[type=password][disabled],
input[type=password][disabled]:hover,
input[type=number][disabled],
input[type=number][disabled]:hover,
input[type=date][disabled],
input[type=date][disabled]:hover,
select[disabled],
select[disabled]:hover {
background: #e8e8e8;
box-shadow: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
}
input[type=text]:hover,
input[type=text]:focus,
input[type=password]:hover,
input[type=password]:focus,
input[type=number]:hover,
input[type=number]:focus,
input[type=date]:hover,
input[type=date]:focus,
select:focus,
select:hover {
border: 1px solid #7c7c7c;
background: #fff;
}
input[type=text]:hover,
input[type=password]:hover,
input[type=number]:hover,
input[type=date]:hover,
select:hover {
box-shadow: 0 1px 3px #aaa;
-webkit-box-shadow: 0 1px 3px #aaa;
-moz-box-shadow: 0 1px 3px #aaa;
}
input[type=submit],
button[type=submit]:not(.mult_submit) {
font-weight: bold !important;
}
input[type=submit],
button[type=submit]:not(.mult_submit),
input[type=reset],
input[name=submit_reset],
input.button {
margin-left: 14px;
border: 1px solid #aaa;
padding: 3px 7px;
color: #111;
text-decoration: none;
background: #ddd;
border-radius: 12px;
-webkit-border-radius: 12px;
-moz-border-radius: 12px;
text-shadow: 0 1px 0 #fff;
<?php echo $_SESSION['PMA_Theme']->getCssGradient('ffffff', 'cccccc'); ?>
}
input[type=submit]:hover,
button[type=submit]:not(.mult_submit):hover,
input[type=reset]:hover,
input[name=submit_reset]:hover,
input.button:hover {
position: relative;
<?php echo $_SESSION['PMA_Theme']->getCssGradient('cccccc', 'dddddd'); ?>
cursor: pointer;
}
input[type=submit]:active,
button[type=submit]:not(.mult_submit):active,
input[type=reset]:active,
input[name=submit_reset]:active,
input.button:active {
position: relative;
top: 1px;
left: 1px;
}
textarea {
overflow: visible;
height: <?php echo ceil($GLOBALS['cfg']['TextareaRows'] * 1.2); ?>em;
}
textarea.char {
height: <?php echo ceil($GLOBALS['cfg']['CharTextareaRows'] * 1.2); ?>em;
}
fieldset {
margin-top: 1em;
border-radius: 4px 4px 0 0;
-moz-border-radius: 4px 4px 0 0;
-webkit-border-radius: 4px 4px 0 0;
border: #aaa solid 1px;
padding: 1.5em;
background: #eee;
text-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 2px #fff inset;
-moz-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 2px #fff inset;
-webkit-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 2px #fff inset;
box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 2px #fff inset;
}
fieldset fieldset {
margin: .8em;
background: #fff;
border: 1px solid #aaa;
background: #E8E8E8;
}
fieldset legend {
font-weight: bold;
color: #444;
padding: 5px 10px;
border-radius: 2px;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
border: 1px solid #aaa;
background-color: #fff;
-moz-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>3px 3px 15px #bbb;
-webkit-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>3px 3px 15px #bbb;
box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>3px 3px 15px #bbb;
max-width: 100%;
}
.some-margin {
margin: 1.5em;
}
/* buttons in some browsers (eg. Konqueror) are block elements,
this breaks design */
button {
display: inline;
}
table caption,
table th,
table td {
padding: .3em;
margin: .1em;
vertical-align: top;
text-shadow: 0 1px 0 #fff;
}
/* 3.4 */
table {
border-collapse: collapse;
}
th {
border-right: 1px solid #fff;
text-align: left;
}
img,
button {
vertical-align: middle;
}
input[type="checkbox"],
input[type="radio"] {
vertical-align: -11%;
}
select {
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
border-radius: 2px;
border: 1px solid #bbb;
color: #333;
padding: 3px;
background: white;
}
select[multiple] {
<?php echo $_SESSION['PMA_Theme']->getCssGradient('ffffff', 'f2f2f2'); ?>
}
/******************************************************************************/
/* classes */
.clearfloat {
clear: both;
}
.floatleft {
float: <?php echo $left; ?>;
margin-<?php echo $right; ?>: 1em;
}
.floatright {
float: <?php echo $right; ?>;
}
.center {
text-align: center;
}
table.nospacing {
border-spacing: 0;
}
table.nopadding tr th, table.nopadding tr td {
padding: 0;
}
th.left, td.left {
text-align: left;
}
th.center, td.center {
text-align: center;
}
th.right, td.right {
text-align: right;
}
tr.vtop th, tr.vtop td, th.vtop, td.vtop {
vertical-align: top;
}
tr.vmiddle th, tr.vmiddle td, th.vmiddle, td.vmiddle {
vertical-align: middle;
}
tr.vbottom th, tr.vbottom td, th.vbottom, td.vbottom {
vertical-align: bottom;
}
.paddingtop {
padding-top: 1em;
}
.separator {
color: #fff;
text-shadow: 0 1px 0 #000;
}
div.tools {
/* border: 1px solid #000; */
padding: .2em;
}
div.tools a {
color: #3a7ead !important;
}
div.tools,
fieldset.tblFooters {
margin-top: 0;
margin-bottom: .5em;
/* avoid a thick line since this should be used under another fieldset */
border-top: 0;
text-align: <?php echo $right; ?>;
float: none;
clear: both;
-webkit-border-radius: 0 0 4px 4px;
-moz-border-radius: 0 0 4px 4px;
border-radius: 0 0 4px 5px;
}
div.null_div {
height: 20px;
text-align: center;
font-style: normal;
min-width: 50px;
}
fieldset .formelement {
float: <?php echo $left; ?>;
margin-<?php echo $right; ?>: .5em;
/* IE */
white-space: nowrap;
}
@media all and (min-width: 1600px) {
fieldset .formelement {
clear: none;
}
#relationalTable td:first-child + td {
width: 25%;
}
#relationalTable td:first-child + td select {
width: 32%;
margin-right: 1%;
}
#relationalTable {
width: 100%;
}
}
/* revert for Gecko */
fieldset div[class=formelement] {
white-space: normal;
}
button.mult_submit {
border: none;
background-color: transparent;
}
/* odd items 1,3,5,7,... */
table tr.odd th,
.odd {
background: #fff;
<?php echo $_SESSION['PMA_Theme']->getCssIEClearFilter(); ?>
}
/* even items 2,4,6,8,... */
/* (tested on CRTs and ACLs) */
table tr.even th,
.even {
background: #DFDFDF;
<?php echo $_SESSION['PMA_Theme']->getCssIEClearFilter(); ?>
}
/* odd table rows 1,3,5,7,... */
table tr.odd th,
table tr.odd,
table tr.even th,
table tr.even {
text-align: <?php echo $left; ?>;
}
<?php if ($GLOBALS['cfg']['BrowseMarkerEnable']) { ?>
/* marked table rows */
td.marked,
table tr.marked td,
table tr.marked th,
table tr.marked {
<?php echo $_SESSION['PMA_Theme']->getCssGradient('ced6df', 'b6c6d7'); ?>
color: <?php echo $GLOBALS['cfg']['BrowseMarkerColor']; ?>;
}
<?php } ?>
<?php if ($GLOBALS['cfg']['BrowsePointerEnable']) { ?>
/* hovered items */
.odd:hover,
.even:hover,
.hover {
<?php echo $_SESSION['PMA_Theme']->getCssGradient('ced6df', 'b6c6d7'); ?>
color: <?php echo $GLOBALS['cfg']['BrowsePointerColor']; ?>;
}
/* hovered table rows */
table tr.odd:hover th,
table tr.even:hover th,
table tr.hover th {
<?php echo $_SESSION['PMA_Theme']->getCssGradient('ced6df', 'b6c6d7'); ?>
color: <?php echo $GLOBALS['cfg']['BrowsePointerColor']; ?>;
}
<?php } ?>
/**
* marks table rows/cells if the db field is in a where condition
*/
.condition {
border-color: <?php echo $GLOBALS['cfg']['BrowseMarkerBackground']; ?> !important;
}
th.condition {
border-width: 1px 1px 0 1px;
border-style: solid;
}
td.condition {
border-width: 0 1px 0 1px;
border-style: solid;
}
tr:last-child td.condition {
border-width: 0 1px 1px 1px;
}
<?php if ($GLOBALS['text_dir'] === 'ltr') { ?>
/* for first th which must have right border set (ltr only) */
.before-condition {
border-right: 1px solid <?php echo $GLOBALS['cfg']['BrowseMarkerBackground']; ?>;
}
<?php } ?>
/**
* cells with the value NULL
*/
td.null {
font-style: italic;
text-align: <?php echo $right; ?>;
}
table .valueHeader {
text-align: <?php echo $right; ?>;
white-space: normal;
}
table .value {
text-align: <?php echo $right; ?>;
white-space: normal;
}
/* IE doesnt handles 'pre' right */
table [class=value] {
white-space: normal;
}
<?php if (! empty($GLOBALS['cfg']['FontFamilyFixed'])) { ?>
.value {
font-family: <?php echo $GLOBALS['cfg']['FontFamilyFixed']; ?>;
}
<?php } ?>
.attention {
color: red;
font-weight: bold;
}
.allfine {
color: green;
}
img.lightbulb {
cursor: pointer;
}
.pdflayout {
overflow: hidden;
clip: inherit;
background-color: #fff;
display: none;
border: 1px solid #000;
position: relative;
}
.pdflayout_table {
background: #D3DCE3;
color: #000;
overflow: hidden;
clip: inherit;
z-index: 2;
display: inline;
visibility: inherit;
cursor: move;
position: absolute;
font-size: 80%;
border: 1px dashed #000;
}
/* Doc links in SQL */
.cm-sql-doc {
text-decoration: none;
border-bottom: 1px dotted #000;
color: inherit !important;
}
/* no extra space in table cells */
td .icon {
margin: 0;
}
.selectallarrow {
margin-<?php echo $right; ?>: .3em;
margin-<?php echo $left; ?>: .6em;
}
/* message boxes: error, confirmation */
#pma_errors, #pma_demo {
padding: 0 0.5em;
}
.success h1,
.notice h1,
div.error h1 {
border-bottom: 2px solid;
font-weight: bold;
text-align: <?php echo $left; ?>;
margin: 0 0 .2em 0;
}
div.success,
div.notice,
div.error {
margin: .5em 0 1.3em;
border: 1px solid;
background-repeat: no-repeat;
<?php if ($GLOBALS['text_dir'] === 'ltr') { ?>
background-position: 10px 50%;
padding: 10px 10px 10px 10px;
<?php } else { ?>
background-position: 99% 50%;
padding: 10px 35px 10px 10px;
<?php } ?>
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: 0 1px 1px #fff inset;
-webkit-box-shadow: 0 1px 1px #fff inset;
box-shadow: 0 1px 1px #fff inset;
}
.success a,
.notice a,
.error a {
text-decoration: underline;
}
.success {
color: #000;
background-color: #ebf8a4;
}
h1.success,
div.success {
border-color: #a2d246;
}
.success h1 {
border-color: #00FF00;
}
.notice {
color: #000;
background-color: #e8eef1;
}
h1.notice,
div.notice {
border-color: #3a6c7e;
}
.notice h1 {
border-color: #ffb10a;
}
.error {
border: 1px solid maroon !important;
color: #000;
background: pink;
}
h1.error,
div.error {
border-color: #333;
}
div.error h1 {
border-color: #ff0000;
}
.confirmation {
color: #000;
background-color: pink;
}
fieldset.confirmation {
}
fieldset.confirmation legend {
}
/* end messageboxes */
.tblcomment {
font-size: 70%;
font-weight: normal;
color: #000099;
}
.tblHeaders {
font-weight: bold;
color: <?php echo $GLOBALS['cfg']['ThColor']; ?>;
background: <?php echo $GLOBALS['cfg']['ThBackground']; ?>;
}
div.tools,
.tblFooters {
font-weight: normal;
color: <?php echo $GLOBALS['cfg']['ThColor']; ?>;
background: <?php echo $GLOBALS['cfg']['ThBackground']; ?>;
}
.tblHeaders a:link,
.tblHeaders a:active,
.tblHeaders a:visited,
div.tools a:link,
div.tools a:visited,
div.tools a:active,
.tblFooters a:link,
.tblFooters a:active,
.tblFooters a:visited {
color: #0000FF;
}
.tblHeaders a:hover,
div.tools a:hover,
.tblFooters a:hover {
color: #FF0000;
}
/* forbidden, no privileges */
.noPrivileges {
color: #FF0000;
font-weight: bold;
}
/* disabled text */
.disabled,
.disabled a:link,
.disabled a:active,
.disabled a:visited {
color: #666;
}
.disabled a:hover {
color: #666;
text-decoration: none;
}
tr.disabled td,
td.disabled {
background-color: #f3f3f3;
color: #aaa;
}
.nowrap {
white-space: nowrap;
}
/**
* login form
*/
body#loginform h1,
body#loginform a.logo {
display: block;
text-align: center;
}
body#loginform {
margin-top: 1em;
text-align: center;
}
body#loginform div.container {
text-align: <?php echo $left; ?>;
width: 30em;
margin: 0 auto;
}
form.login label {
float: <?php echo $left; ?>;
width: 10em;
font-weight: bolder;
}
.commented_column {
border-bottom: 1px dashed #000;
}
.column_attribute {
font-size: 70%;
}
/******************************************************************************/
/* specific elements */
/* topmenu */
#topmenu a {
text-shadow: 0 1px 0 #fff;
}
#topmenu .error {
background: #eee;border: 0 !important;color: #aaa;
}
ul#topmenu,
ul#topmenu2,
ul.tabs {
font-weight: bold;
list-style-type: none;
margin: 0;
padding: 0;
}
ul#topmenu2 {
margin: .25em .5em 0;
height: 2em;
clear: both;
}
ul#topmenu li,
ul#topmenu2 li {
float: <?php echo $left; ?>;
margin: 0;
vertical-align: middle;
}
#topmenu img,
#topmenu2 img {
margin-right: .5em;
vertical-align: -3px;
}
.menucontainer {
<?php echo $_SESSION['PMA_Theme']->getCssGradient('ffffff', 'dcdcdc'); ?>
border-top: 1px solid #aaa;
}
/* default tab styles */
.tabactive {
background: #fff !important;
}
ul#topmenu2 a {
display: block;
margin: 7px 6px 7px;
margin-<?php echo $left; ?>: 0;
padding: 4px 10px;
white-space: nowrap;
border: 1px solid #ddd;
border-radius: 20px;
-moz-border-radius: 20px;
-webkit-border-radius: 20px;
background: #f2f2f2;
}
fieldset.caution a {
color: #FF0000;
}
fieldset.caution a:hover {
color: #fff;
background-color: #FF0000;
}
#topmenu {
margin-top: .5em;
padding: .1em .3em;
}
ul#topmenu ul {
-moz-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 6px #ddd;
-webkit-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>2px 2px 3px #666;
box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>2px 2px 3px #666;
}
ul#topmenu ul.only {
<?php echo $left; ?>: 0;
}
ul#topmenu > li {
border-right: 1px solid #fff;
border-left: 1px solid #ccc;
border-bottom: 1px solid #ccc;
}
ul#topmenu > li:first-child {
border-left: 0;
}
/* default tab styles */
ul#topmenu a,
ul#topmenu span {
padding: .6em;
}
ul#topmenu ul a {
border-width: 1pt 0 0 0;
-moz-border-radius: 0;
-webkit-border-radius: 0;
border-radius: 0;
}
ul#topmenu ul li:first-child a {
border-width: 0;
}
/* enabled hover/active tabs */
ul#topmenu > li > a:hover,
ul#topmenu > li > .tabactive {
text-decoration: none;
}
ul#topmenu ul a:hover,
ul#topmenu ul .tabactive {
text-decoration: none;
}
ul#topmenu a.tab:hover,
ul#topmenu .tabactive {
/* background-color: <?php echo $GLOBALS['cfg']['MainBackground']; ?>; */
}
ul#topmenu2 a.tab:hover,
ul#topmenu2 a.tabactive {
background-color: <?php echo $GLOBALS['cfg']['BgOne']; ?>;
border-radius: .3em;
-moz-border-radius: .3em;
-webkit-border-radius: .3em;
text-decoration: none;
}
/* to be able to cancel the bottom border, use <li class="active"> */
ul#topmenu > li.active {
/* border-bottom: 0pt solid <?php echo $GLOBALS['cfg']['MainBackground']; ?>; */
border-right: 0;
border-bottom-color: #fff;
}
/* end topmenu */
/* zoom search */
div#dataDisplay input,
div#dataDisplay select {
margin: 0;
margin-<?php echo $right; ?>: .5em;
}
div#dataDisplay th {
line-height: 2em;
}
/* Calendar */
table.calendar {
width: 100%;
}
table.calendar td {
text-align: center;
}
table.calendar td a {
display: block;
}
table.calendar td a:hover {
background-color: #CCFFCC;
}
table.calendar th {
background-color: #D3DCE3;
}
table.calendar td.selected {
background-color: #FFCC99;
}
img.calendar {
border: none;
}
form.clock {
text-align: center;
}
/* end Calendar */
/* table stats */
div#tablestatistics table {
float: <?php echo $left; ?>;
margin-bottom: .5em;
margin-<?php echo $right; ?>: 1.5em;
margin-top: .5em;
min-width: 16em;
}
/* end table stats */
/* server privileges */
#tableuserrights td,
#tablespecificuserrights td,
#tabledatabases td {
vertical-align: middle;
}
/* end server privileges */
/* Heading */
#topmenucontainer {
padding-<?php echo $right; ?>: 1em;
width: 100%;
}
#serverinfo {
border-bottom: 1px solid #fff;
background: #888;
padding: .3em .9em;
padding-<?php echo $left; ?>: 2.2em;
text-shadow: 0 1px 0 #000;
width: 10000px;
overflow: hidden;
}
#serverinfo .item {
white-space: nowrap;
color: #fff;
}
#goto_pagetop {
position: fixed;
padding: .25em .25em .2em;
top: 0;
<?php echo $right; ?>: 0;
z-index: 900;
background: #888;
}
#span_table_comment {
font-weight: bold;
font-style: italic;
white-space: nowrap;
margin-left: 10px;
color: #D6D6D6;
text-shadow: none;
}
#serverinfo img {
margin: 0 .1em 0;
margin-<?php echo $left; ?>: .2em;
}
#textSQLDUMP {
width: 95%;
height: 95%;
font-family: Consolas, "Courier New", Courier, mono;
font-size: 110%;
}
#TooltipContainer {
position: absolute;
z-index: 99;
width: 20em;
height: auto;
overflow: visible;
visibility: hidden;
background-color: #ffffcc;
color: #006600;
border: .1em solid #000;
padding: .5em;
}
/* user privileges */
#fieldset_add_user_login div.item {
border-bottom: 1px solid silver;
padding-bottom: .3em;
margin-bottom: .3em;
}
#fieldset_add_user_login label {
float: <?php echo $left; ?>;
display: block;
width: 10em;
max-width: 100%;
text-align: <?php echo $right; ?>;
padding-<?php echo $right; ?>: .5em;
}
#fieldset_add_user_login span.options #select_pred_username,
#fieldset_add_user_login span.options #select_pred_hostname,
#fieldset_add_user_login span.options #select_pred_password {
width: 100%;
max-width: 100%;
}
#fieldset_add_user_login span.options {
float: <?php echo $left; ?>;
display: block;
width: 12em;
max-width: 100%;
padding-<?php echo $right; ?>: .5em;
}
#fieldset_add_user_login input {
width: 12em;
clear: <?php echo $right; ?>;
max-width: 100%;
}
#fieldset_add_user_login span.options input {
width: auto;
}
#fieldset_user_priv div.item {
float: <?php echo $left; ?>;
width: 9em;
max-width: 100%;
}
#fieldset_user_priv div.item div.item {
float: none;
}
#fieldset_user_priv div.item label {
white-space: nowrap;
}
#fieldset_user_priv div.item select {
width: 100%;
}
#fieldset_user_global_rights fieldset {
float: <?php echo $left; ?>;
}
#fieldset_user_group_rights fieldset {
float: <?php echo $left; ?>;
}
#fieldset_user_global_rights legend input {
margin-<?php echo $left; ?>: 2em;
}
/* end user privileges */
/* serverstatus */
.linkElem:hover {
text-decoration: underline;
color: #235a81;
cursor: pointer;
}
h3#serverstatusqueries span {
font-size: 60%;
display: inline;
}
img.sortableIcon {
float: <?php echo $right; ?>;
background-repeat: no-repeat;
margin: 0;
}
.buttonlinks {
float: <?php echo $right; ?>;
white-space: nowrap;
}
/* Also used for the variables page */
fieldset#tableFilter {
margin-bottom: 1em;
}
div#serverStatusTabs {
margin-top: 1em;
}
caption a.top {
float: <?php echo $right; ?>;
}
div#serverstatusquerieschart {
float: <?php echo $left; ?>;
width: 500px;
height: 350px;
padding-<?php echo $left; ?>: 30px;
}
table#serverstatusqueriesdetails,
table#serverstatustraffic {
float: <?php echo $left; ?>;
}
table#serverstatusqueriesdetails th {
min-width: 35px;
}
table#serverstatusvariables {
width: 100%;
margin-bottom: 1em;
}
table#serverstatusvariables .name {
width: 18em;
white-space: nowrap;
}
table#serverstatusvariables .value {
width: 6em;
}
table#serverstatusconnections {
float: <?php echo $left; ?>;
margin-<?php echo $left; ?>: 30px;
}
div#serverstatus table tbody td.descr a,
div#serverstatus table .tblFooters a {
white-space: nowrap;
}
div.liveChart {
clear: both;
min-width: 500px;
height: 400px;
padding-bottom: 80px;
}
#addChartDialog input[type="text"] {
margin: 0;
padding: 3px;
}
div#chartVariableSettings {
border: 1px solid #ddd;
background-color: #E6E6E6;
margin-left: 10px;
}
table#chartGrid div.monitorChart {
background: #EBEBEB;
}
div#serverstatus div.tabLinks {
float: <?php echo $left; ?>;
padding-bottom: 10px;
}
.popupContent {
display: none;
position: absolute;
border: 1px solid #CCC;
margin: 0;
padding: 3px;
-moz-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>2px 2px 3px #666;
-webkit-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>2px 2px 3px #666;
box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>2px 2px 3px #666;
background-color: #fff;
z-index: 2;
}
div#logTable {
padding-top: 10px;
clear: both;
}
div#logTable table {
width: 100%;
}
div#queryAnalyzerDialog {
min-width: 700px;
}
div#queryAnalyzerDialog div.CodeMirror-scroll {
height: auto;
}
div#queryAnalyzerDialog div#queryProfiling {
height: 300px;
}
div#queryAnalyzerDialog td.explain {
width: 250px;
}
div#queryAnalyzerDialog table.queryNums {
display: none;
border: 0;
text-align: left;
}
.smallIndent {
padding-<?php echo $left; ?>: 7px;
}
/* end serverstatus */
/* server variables */
#serverVariables {
min-width: 30em;
}
#serverVariables .var-row > div {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
line-height: 2em;
}
#serverVariables .var-header {
color: <?php echo $GLOBALS['cfg']['ThColor']; ?>;
background: #f3f3f3;
<?php echo $_SESSION['PMA_Theme']->getCssGradient('ffffff', 'cccccc'); ?>
font-weight: bold;
}
#serverVariables .var-header .var-value {
text-align: <?php echo $left; ?>;
}
#serverVariables .var-row {
padding: 0.5em;
min-height: 18px;
}
#serverVariables .var-name {
width: 45%;
float: <?php echo $left; ?>;
font-weight: bold;
}
#serverVariables .var-name.session {
font-weight: normal;
font-style: italic;
}
#serverVariables .var-value {
width: 50%;
float: <?php echo $right; ?>;
text-align: <?php echo $right; ?>;
}
#serverVariables .var-doc {
overflow:visible;
float: <?php echo $right; ?>;
}
/* server variables editor */
#serverVariables .editLink {
padding-<?php echo $right; ?>: 1em;
float: <?php echo $left; ?>;
font-family: sans-serif;
}
#serverVariables .serverVariableEditor {
width: 100%;
overflow: hidden;
}
#serverVariables .serverVariableEditor input {
width: 100%;
margin: 0 0.5em;
box-sizing: border-box;
-ms-box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
height: 2.2em;
}
#serverVariables .serverVariableEditor div {
display: block;
overflow: hidden;
padding-<?php echo $right; ?>: 1em;
}
#serverVariables .serverVariableEditor a {
float: <?php echo $right; ?>;
margin: 0 0.5em;
line-height: 2em;
}
/* end server variables */
p.notice {
margin: 1.5em 0;
border: 1px solid #000;
background-repeat: no-repeat;
<?php if ($GLOBALS['text_dir'] === 'ltr') { ?>
background-position: 10px 50%;
padding: 10px 10px 10px 25px;
<?php } else { ?>
background-position: 99% 50%;
padding: 25px 10px 10px 10px
<?php } ?>
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: 0 1px 2px #fff inset;
-webkit-box-shadow: 0 1px 2px #fff inset;
box-shadow: 0 1px 2px #fff inset;
background: #555;
color: #d4fb6a;
}
p.notice a {
color: #fff;
text-decoration: underline;
}
/* querywindow */
body#bodyquerywindow {
margin: 0;
padding: 0;
background-image: none;
background-color: #F5F5F5;
}
div#querywindowcontainer {
margin: 0;
padding: 0;
width: 100%;
}
div#querywindowcontainer fieldset {
margin-top: 0;
}
/* end querywindow */
/* profiling */
div#profilingchart {
width: 550px;
height: 370px;
float: <?php echo $left; ?>;
}
#profilingchart .jqplot-highlighter-tooltip{
top: auto !important;
left: 11px;
bottom:24px;
}
#profilesummarytable th.header, #profiletable th.header{
cursor: pointer;
}
#profilesummarytable th.header .sorticon, #profiletable th.header .sorticon{
width: 16px;
height: 16px;
background-repeat: no-repeat;
background-position: right center;
display: inline-block;
vertical-align: middle;
float: right;
}
#profilesummarytable th.headerSortUp .sorticon, #profiletable th.headerSortUp .sorticon{
background-image: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('s_desc.png');?>);
}
#profilesummarytable th.headerSortDown .sorticon, #profiletable th.headerSortDown .sorticon{
background-image: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('s_asc.png');?>);
}
/* end profiling */
/* table charting */
#resizer {
border: 1px solid silver;
}
#inner-resizer { /* make room for the resize handle */
padding: 10px;
}
/* end table charting */
/* querybox */
#togglequerybox {
margin: 0 10px;
}
#serverstatus h3
{
margin: 15px 0;
font-weight: normal;
color: #999;
font-size: 1.7em;
}
#sectionlinks {
padding: 16px;
background: #f3f3f3;
border: 1px solid #aaa;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
box-shadow: 0 1px 1px #fff inset;
-webkit-box-shadow: 0 1px 1px #fff inset;
-moz-box-shadow: 0 1px 1px #fff inset;
}
#sectionlinks a,
.buttonlinks a,
a.button {
font-size: .88em;
font-weight: bold;
text-shadow: 0 1px 0 #fff;
line-height: 35px;
margin-<?php echo $left; ?>: 7px;
border: 1px solid #aaa;
padding: 5px 10px;
color: #111;
text-decoration: none;
background: #ddd;
white-space: nowrap;
border-radius: 20px;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 2px rgba(0,0,0,.5);
/*
-webkit-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 2px rgba(0,0,0,.5);
-moz-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 2px rgba(0,0,0,.5);
text-shadow: #fff 0 1px 0;
*/
<?php echo $_SESSION['PMA_Theme']->getCssGradient('ffffff', 'cccccc'); ?>
}
#sectionlinks a:hover,
.buttonlinks a:hover,
a.button:hover {
<?php echo $_SESSION['PMA_Theme']->getCssGradient('cccccc', 'dddddd'); ?>
}
div#sqlquerycontainer {
float: <?php echo $left; ?>;
width: 69%;
/* height: 15em; */
}
div#tablefieldscontainer {
float: <?php echo $right; ?>;
width: 29%;
/* height: 15em; */
}
div#tablefieldscontainer select {
width: 100%;
background: #fff;
/* height: 12em; */
}
textarea#sqlquery {
width: 100%;
/* height: 100%; */
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
border: 1px solid #aaa;
padding: 5px;
font-family: inherit;
}
textarea#sql_query_edit {
height: 7em;
width: 95%;
display: block;
}
div#queryboxcontainer div#bookmarkoptions {
margin-top: .5em;
}
/* end querybox */
/* main page */
#maincontainer {
/* background-image: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('logo_right.png');?>); */
/* background-position: <?php echo $right; ?> bottom; */
/* background-repeat: no-repeat; */
}
#mysqlmaininformation,
#pmamaininformation {
float: <?php echo $left; ?>;
width: 49%;
}
#maincontainer ul {
list-style-type: disc;
vertical-align: middle;
}
#maincontainer li {
margin-bottom: .3em;
}
#full_name_layer {
position: absolute;
padding: 2px;
margin-top: -3px;
z-index: 801;
border-radius: 3px;
border: solid 1px #888;
background: #fff;
}
/* end main page */
/* iconic view for ul items */
li.no_bullets {
list-style-type:none !important;
margin-left: -25px !important; //align with other list items which have bullets
}
/* end iconic view for ul items */
#body_browse_foreigners {
background: <?php echo $GLOBALS['cfg']['NaviBackground']; ?>;
margin: .5em .5em 0 .5em;
}
#bodyquerywindow {
background: <?php echo $GLOBALS['cfg']['NaviBackground']; ?>;
}
#bodythemes {
width: 500px;
margin: auto;
text-align: center;
}
#bodythemes img {
border: .1em solid #000;
}
#bodythemes a:hover img {
border: .1em solid red;
}
#fieldset_select_fields {
float: <?php echo $left; ?>;
}
#selflink {
clear: both;
display: block;
margin-top: 1em;
margin-bottom: 1em;
width: 98%;
margin-<?php echo $left; ?>: 1%;
border-top: .1em solid silver;
text-align: <?php echo $right; ?>;
}
#table_innodb_bufferpool_usage,
#table_innodb_bufferpool_activity {
float: <?php echo $left; ?>;
}
#div_mysql_charset_collations table {
float: <?php echo $left; ?>;
}
#div_mysql_charset_collations table th,
#div_mysql_charset_collations table td {
padding: 0.4em;
}
#div_mysql_charset_collations table th#collationHeader {
width: 35%;
}
.operations_half_width {
width: 48%;
float: <?php echo $left; ?>;
}
.operations_half_width input[type=text],
.operations_half_width input[type=password],
.operations_half_width input[type=number],
.operations_half_width select {
width: 95%;
}
.operations_half_width input[type=text].halfWidth,
.operations_half_width input[type=password].halfWidth,
.operations_half_width input[type=number].halfWidth,
.operations_half_width select.halfWidth {
width: 40%;
}
.operations_half_width ul {
list-style-type: none;
padding: 0;
}
.operations_full_width {
width: 100%;
clear: both;
}
#qbe_div_table_list {
float: <?php echo $left; ?>;
}
#qbe_div_sql_query {
float: <?php echo $left; ?>;
}
label.desc {
width: 30em;
float: <?php echo $left; ?>;
}
label.desc sup {
position: absolute;
}
code.sql,
div.sqlvalidate {
display: block;
padding: 1em;
margin-top: 0;
margin-bottom: 0;
max-height: 10em;
overflow: auto;
}
#result_query div.sqlOuter {
background: <?php echo $GLOBALS['cfg']['BgOne']; ?>;
padding: 1em;
}
#PMA_slidingMessage code.sql,
div.sqlvalidate {
background: <?php echo $GLOBALS['cfg']['BgOne']; ?>;
}
#main_pane_left {
width: 60%;
min-width: 260px;
float: <?php echo $left; ?>;
padding-top: 1em;
}
#main_pane_right {
overflow: hidden;
min-width: 160px;
padding-top: 1em;
padding-<?php echo $left; ?>: 1em;
}
.group {
border: 1px solid #999;
background: #f3f3f3;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
-moz-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>2px 2px 5px #ccc;
-webkit-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>2px 2px 5px #ccc;
box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>2px 2px 5px #ccc;
margin-bottom: 1em;
padding-bottom: 1em;
}
.group h2 {
background-color: #bbb;
padding: .1em .3em;
margin-top: 0;
color: #fff;
font-size: 1.6em;
font-weight: normal;
text-shadow: 0 1px 0 #777;
-moz-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 15px #999 inset;
-webkit-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 15px #999 inset;
box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 15px #999 inset;
}
.group-cnt {
padding: 0;
padding-<?php echo $left; ?>: .5em;
display: inline-block;
width: 98%;
}
textarea#partitiondefinition {
height: 3em;
}
/* for elements that should be revealed only via js */
.hide {
display: none;
}
#list_server {
list-style-image: none;
}
/**
* Progress bar styles
*/
div.upload_progress
{
width: 400px;
margin: 3em auto;
text-align: center;
}
div.upload_progress_bar_outer
{
border: 1px solid #000;
width: 202px;
position: relative;
margin: 0 auto 1em;
color: <?php echo $GLOBALS['cfg']['MainColor']; ?>;
}
div.upload_progress_bar_inner
{
background-color: <?php echo $GLOBALS['cfg']['NaviPointerBackground']; ?>;
width: 0;
height: 12px;
margin: 1px;
overflow: hidden;
color: <?php echo $GLOBALS['cfg']['BrowseMarkerColor']; ?>;
position: relative;
}
div.upload_progress_bar_outer div.percentage
{
position: absolute;
top: 0;
<?php echo $left; ?>: 0;
width: 202px;
}
div.upload_progress_bar_inner div.percentage
{
top: -1px;
<?php echo $left; ?>: -1px;
}
div#statustext {
margin-top: .5em;
}
table#serverconnection_src_remote,
table#serverconnection_trg_remote,
table#serverconnection_src_local,
table#serverconnection_trg_local {
float: <?php echo $left; ?>;
}
/**
* Validation error message styles
*/
input[type=text].invalid_value,
input[type=password].invalid_value,
input[type=number].invalid_value,
input[type=date].invalid_value,
.invalid_value {
background: #FFCCCC;
}
/**
* Ajax notification styling
*/
.ajax_notification {
top: 0; /** The notification needs to be shown on the top of the page */
position: fixed;
margin-top: 0;
margin-right: auto;
margin-bottom: 0;
margin-<?php echo $left; ?>: auto;
padding: 5px; /** Keep a little space on the sides of the text */
width: 350px;
z-index: 1100; /** If this is not kept at a high z-index, the jQueryUI modal dialogs (z-index: 1000) might hide this */
text-align: center;
display: inline;
left: 0;
right: 0;
background-image: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('ajax_clock_small.gif');?>);
background-repeat: no-repeat;
background-position: 2%;
border: 1px solid #e2b709;
}
/* additional styles */
.ajax_notification {
margin-top: 200px;
background: #ffe57e;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
box-shadow: 0 5px 90px #888;
-moz-box-shadow: 0 5px 90px #888;
-webkit-box-shadow: 0 5px 90px #888;
}
#loading_parent {
/** Need this parent to properly center the notification division */
position: relative;
width: 100%;
}
/**
* Export and Import styles
*/
.exportoptions h3,
.importoptions h3 {
border-bottom: 1px #999 solid;
font-size: 110%;
}
.exportoptions ul,
.importoptions ul,
.format_specific_options ul {
list-style-type: none;
margin-bottom: 15px;
}
.exportoptions li,
.importoptions li {
margin: 7px;
}
.exportoptions label,
.importoptions label,
.exportoptions p,
.importoptions p {
margin: 5px;
float: none;
}
#csv_options label.desc,
#ldi_options label.desc,
#latex_options label.desc,
#output label.desc {
float: <?php echo $left; ?>;
width: 15em;
}
.exportoptions,
.importoptions {
margin: 20px 30px 30px;
margin-<?php echo $left; ?>: 10px;
}
.exportoptions #buttonGo,
.importoptions #buttonGo {
font-weight: bold;
margin-<?php echo $left; ?>: 14px;
border: 1px solid #aaa;
padding: 5px 12px;
color: #111;
text-decoration: none;
background: #ddd;
border-radius: 12px;
-webkit-border-radius: 12px;
-moz-border-radius: 12px;
text-shadow: 0 1px 0 #fff;
<?php echo $_SESSION['PMA_Theme']->getCssGradient('ffffff', 'cccccc'); ?>
cursor: pointer;
}
#buttonGo:hover {
<?php echo $_SESSION['PMA_Theme']->getCssGradient('cccccc', 'dddddd'); ?>
}
.format_specific_options h3 {
margin: 10px 0 0;
margin-<?php echo $left; ?>: 10px;
border: 0;
}
.format_specific_options {
border: 1px solid #999;
margin: 7px 0;
padding: 3px;
}
p.desc {
margin: 5px;
}
/**
* Export styles only
*/
select#db_select,
select#table_select {
width: 400px;
}
.export_sub_options {
margin: 20px 0 0;
margin-<?php echo $left; ?>: 30px;
}
.export_sub_options h4 {
border-bottom: 1px #999 solid;
}
.export_sub_options li.subgroup {
display: inline-block;
margin-top: 0;
}
.export_sub_options li {
margin-bottom: 0;
}
#output_quick_export {
display: none;
}
/**
* Import styles only
*/
.importoptions #import_notification {
margin: 10px 0;
font-style: italic;
}
input#input_import_file {
margin: 5px;
}
.formelementrow {
margin: 5px 0 5px 0;
}
#popup_background {
display: none;
position: fixed;
_position: absolute; /* hack for IE6 */
width: 100%;
height: 100%;
top: 0;
<?php echo $left; ?>: 0;
background: #000;
z-index: 1000;
overflow: hidden;
}
/**
* Table structure styles
*/
#fieldsForm ul.table-structure-actions {
margin: 0;
padding: 0;
list-style: none;
}
#fieldsForm ul.table-structure-actions li {
float: <?php echo $left; ?>;
margin-<?php echo $right; ?>: 0.3em; /* same as padding of "table td" */
}
#fieldsForm ul.table-structure-actions .submenu li {
padding: 0;
margin: 0;
}
#fieldsForm ul.table-structure-actions .submenu li span {
padding: 0.3em;
margin: 0.1em;
}
#structure-action-links a {
margin-<?php echo $right; ?>: 1em;
}
#addColumns input[type="radio"] {
margin: 3px 0 0;
margin-<?php echo $left; ?>: 1em;
}
/**
* Indexes
*/
#index_frm .index_info input,
#index_frm .index_info select {
width: 14em;
box-sizing: border-box;
-ms-box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
#index_frm .index_info div {
padding: .2em 0;
}
#index_frm .index_info .label {
float: <?php echo $left; ?>;
min-width: 12em;
}
#index_frm .slider {
width: 10em;
margin: .6em;
float: <?php echo $left; ?>;
}
#index_frm .add_fields {
float: <?php echo $left; ?>;
}
#index_frm .add_fields input {
margin-<?php echo $left; ?>: 1em;
}
#index_frm input {
margin: 0;
}
#index_frm td {
vertical-align: middle;
}
table#index_columns {
width: 100%;
}
table#index_columns select {
width: 100%;
}
#move_columns_dialog div {
padding: 1em;
}
#move_columns_dialog ul {
list-style: none;
margin: 0;
padding: 0;
}
#move_columns_dialog li {
background: <?php echo $GLOBALS['cfg']['ThBackground']; ?>;
border: 1px solid #aaa;
color: <?php echo $GLOBALS['cfg']['ThColor']; ?>;
font-weight: bold;
margin: .4em;
padding: .2em;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
}
.margin#change_column_dialog {
margin: 0 .5em;
}
/* config forms */
.config-form ul.tabs {
margin: 1.1em .2em 0;
padding: 0 0 .3em 0;
list-style: none;
font-weight: bold;
}
.config-form ul.tabs li {
float: <?php echo $left; ?>;
margin-bottom: -1px;
}
.config-form ul.tabs li a {
display: block;
margin: .1em .2em 0;
white-space: nowrap;
text-decoration: none;
border: 1px solid <?php echo $GLOBALS['cfg']['BgTwo']; ?>;
border-bottom: 1px solid #aaa;
}
.config-form ul.tabs li a {
padding: 7px 10px;
-webkit-border-radius: 5px 5px 0 0;
-moz-border-radius: 5px 5px 0 0;
border-radius: 5px 5px 0 0;
background: #f2f2f2;
color: #555;
text-shadow: 0 1px 0 #fff;
}
.config-form ul.tabs li a:hover,
.config-form ul.tabs li a:active {
background: #e5e5e5;
}
.config-form ul.tabs li.active a {
background-color: #fff;
margin-top: 1px;
color: #000;
text-shadow: none;
border-color: #aaa;
border-bottom: 1px solid #fff;
}
.config-form fieldset {
margin-top: 0;
padding: 0;
clear: both;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
}
.config-form legend {
display: none;
}
.config-form fieldset p {
margin: 0;
padding: .5em;
background: #fff;
border-top: 0;
}
.config-form fieldset .errors { /* form error list */
margin: 0 -2px 1em;
padding: .5em 1.5em;
background: #FBEAD9;
border: 0 #C83838 solid;
border-width: 1px 0;
list-style: none;
font-family: sans-serif;
font-size: small;
}
.config-form fieldset .inline_errors { /* field error list */
margin: .3em .3em .3em;
margin-<?php echo $left; ?>: 0;
padding: 0;
list-style: none;
color: #9A0000;
font-size: small;
}
.config-form fieldset th {
padding: .3em .3em .3em;
padding-<?php echo $left; ?>: .5em;
text-align: <?php echo $left; ?>;
vertical-align: top;
width: 40%;
background: transparent;
filter: none;
}
.config-form fieldset .doc,
.config-form fieldset .disabled-notice {
margin-<?php echo $left; ?>: 1em;
}
.config-form fieldset .disabled-notice {
font-size: 80%;
text-transform: uppercase;
color: #E00;
cursor: help;
}
.config-form fieldset td {
padding-top: .3em;
padding-bottom: .3em;
vertical-align: top;
}
.config-form fieldset th small {
display: block;
font-weight: normal;
font-family: sans-serif;
font-size: x-small;
color: #444;
}
.config-form fieldset th,
.config-form fieldset td {
border-top: 1px <?php echo $GLOBALS['cfg']['BgTwo']; ?> solid;
border-<?php echo $right; ?>: none;
}
fieldset .group-header th {
background: <?php echo $GLOBALS['cfg']['BgTwo']; ?>;
}
fieldset .group-header + tr th {
padding-top: .6em;
}
fieldset .group-field-1 th,
fieldset .group-header-2 th {
padding-<?php echo $left; ?>: 1.5em;
}
fieldset .group-field-2 th,
fieldset .group-header-3 th {
padding-<?php echo $left; ?>: 3em;
}
fieldset .group-field-3 th {
padding-<?php echo $left; ?>: 4.5em;
}
fieldset .disabled-field th,
fieldset .disabled-field th small,
fieldset .disabled-field td {
color: #666;
background-color: #ddd;
}
.config-form .lastrow {
border-top: 1px #000 solid;
}
.config-form .lastrow {
background: <?php echo $GLOBALS['cfg']['ThBackground']; ?>;
padding: .5em;
text-align: center;
}
.config-form .lastrow input {
font-weight: bold;
}
/* form elements */
.config-form span.checkbox {
padding: 2px;
display: inline-block;
}
.config-form .custom { /* customized field */
background: #FFC;
}
.config-form span.checkbox.custom {
padding: 1px;
border: 1px #EDEC90 solid;
background: #FFC;
}
.config-form .field-error {
border-color: #A11 !important;
}
.config-form input[type="text"],
.config-form input[type="password"],
.config-form input[type="number"],
.config-form select,
.config-form textarea {
border: 1px #A7A6AA solid;
height: auto;
}
.config-form input[type="text"]:focus,
.config-form input[type="password"]:focus,
.config-form input[type="number"]:focus,
.config-form select:focus,
.config-form textarea:focus {
border: 1px #6676FF solid;
background: #F7FBFF;
}
.config-form .field-comment-mark {
font-family: serif;
color: #007;
cursor: help;
padding: 0 .2em;
font-weight: bold;
font-style: italic;
}
.config-form .field-comment-warning {
color: #A00;
}
/* error list */
.config-form dd {
margin-<?php echo $left; ?>: .5em;
}
.config-form dd:before {
content: "\25B8 ";
}
.click-hide-message {
cursor: pointer;
}
.prefsmanage_opts {
margin-<?php echo $left; ?>: 2em;
}
#prefs_autoload {
margin-bottom: .5em;
}
#placeholder .button {
position: absolute;
cursor: pointer;
}
#placeholder div.button {
font-size: smaller;
color: #999;
background-color: #eee;
padding: 2px;
}
.wrapper {
float: <?php echo $left; ?>;
margin-bottom: 1.5em;
}
.toggleButton {
position: relative;
cursor: pointer;
font-size: .8em;
text-align: center;
line-height: 1.4em;
height: 1.55em;
overflow: hidden;
border-right: .1em solid #888;
border-left: .1em solid #888;
-webkit-border-radius: .3em;
-moz-border-radius: .3em;
border-radius: .3em;
}
.toggleButton table,
.toggleButton td,
.toggleButton img {
padding: 0;
position: relative;
}
.toggleButton .container {
position: absolute;
}
.toggleButton .toggleOn {
color: #fff;
padding: 0 1em;
text-shadow: 0 0 .2em #000;
}
.toggleButton .toggleOff {
padding: 0 1em;
}
.doubleFieldset fieldset {
width: 48%;
float: <?php echo $left; ?>;
padding: 0;
}
.doubleFieldset fieldset.left {
margin-<?php echo $right; ?>: 1%;
}
.doubleFieldset fieldset.right {
margin-<?php echo $left; ?>: 1%;
}
.doubleFieldset legend {
margin-<?php echo $left; ?>: 1.5em;
}
.doubleFieldset div.wrap {
padding: 1.5em;
}
#table_columns input[type="text"],
#table_columns input[type="password"],
#table_columns input[type="number"],
#table_columns select {
width: 10em;
box-sizing: border-box;
-ms-box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
#table_columns select {
margin: 0 6px;
}
#placeholder {
position: relative;
border: 1px solid #aaa;
float: <?php echo $right; ?>;
overflow: hidden;
}
.placeholderDrag {
cursor: move;
}
#placeholder .button {
position: absolute;
}
#left_arrow {
left: 8px;
top: 26px;
}
#right_arrow {
left: 26px;
top: 26px;
}
#up_arrow {
left: 17px;
top: 8px;
}
#down_arrow {
left: 17px;
top: 44px;
}
#zoom_in {
left: 17px;
top: 67px;
}
#zoom_world {
left: 17px;
top: 85px;
}
#zoom_out {
left: 17px;
top: 103px;
}
.colborder {
cursor: col-resize;
height: 100%;
margin-<?php echo $left; ?>: -6px;
position: absolute;
width: 5px;
}
.colborder_active {
border-<?php echo $right; ?>: 2px solid #a44;
}
.pma_table td {
position: static;
}
.pma_table th.draggable span,
.pma_table tbody td span {
display: block;
overflow: hidden;
}
.pma_table th.draggable span {
margin-<?php echo $right; ?>: 10px;
}
.modal-copy input {
display: block;
width: 100%;
margin-top: 1.5em;
padding: .3em 0;
}
.cRsz {
position: absolute;
}
.cCpy {
background: #333;
color: #FFF;
font-weight: bold;
margin: .1em;
padding: .3em;
position: absolute;
text-shadow: -1px -1px #000;
-moz-box-shadow: 0 0 .7em #000;
-webkit-box-shadow: 0 0 .7em #000;
box-shadow: 0 0 .7em #000;
-moz-border-radius: .3em;
-webkit-border-radius: .3em;
border-radius: .3em;
}
.cPointer {
background: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('col_pointer.png');?>);
height: 20px;
margin-<?php echo $left; ?>: -5px; /* must be minus half of its width */
margin-top: -10px;
position: absolute;
width: 10px;
}
.tooltip {
background: #333 !important;
opacity: .8 !important;
border: 1px solid #000 !important;
-moz-border-radius: .3em !important;
-webkit-border-radius: .3em !important;
border-radius: .3em !important;
text-shadow: -1px -1px #000 !important;
font-size: .8em !important;
font-weight: bold !important;
padding: 1px 3px !important;
}
.tooltip * {
background: none !important;
color: #FFF !important;
}
.cDrop {
left: 0;
position: absolute;
top: 0;
}
.coldrop {
background: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('col_drop.png');?>);
cursor: pointer;
height: 16px;
margin-<?php echo $left; ?>: .3em;
margin-top: .3em;
position: absolute;
width: 16px;
}
.coldrop:hover,
.coldrop-hover {
background-color: #999;
}
.cList {
background: #EEE;
border: solid 1px #999;
position: absolute;
-moz-box-shadow: 0 .2em .5em #333;
-webkit-box-shadow: 0 .2em .5em #333;
box-shadow: 0 .2em .5em #333;
}
.cList .lDiv div {
padding: .2em .5em .2em;
padding-<?php echo $left; ?>: .2em;
}
.cList .lDiv div:hover {
background: #DDD;
cursor: pointer;
}
.cList .lDiv div input {
cursor: pointer;
}
.showAllColBtn {
border-bottom: solid 1px #999;
border-top: solid 1px #999;
cursor: pointer;
font-size: .9em;
font-weight: bold;
padding: .35em 1em;
text-align: center;
}
.showAllColBtn:hover {
background: #DDD;
}
.turnOffSelect {
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
user-select: none;
}
#page_content {
background-color: white;
}
.navigation {
margin: .8em 0;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
<?php echo $_SESSION['PMA_Theme']->getCssGradient('eeeeee', 'cccccc'); ?>
}
.navigation td {
margin: 0;
padding: 0;
vertical-align: middle;
white-space: nowrap;
}
.navigation_separator {
color: #999;
display: inline-block;
font-size: 1.5em;
text-align: center;
height: 1.4em;
width: 1.2em;
text-shadow: 1px 0 #FFF;
}
.navigation input[type=submit] {
background: none;
border: 0;
filter: none;
margin: 0;
padding: .8em .5em;
border-radius: 0;
-webkit-border-radius: 0;
-moz-border-radius: 0;
}
.navigation input[type=submit]:hover,
.navigation input.edit_mode_active {
color: #fff;
cursor: pointer;
text-shadow: none;
<?php echo $_SESSION['PMA_Theme']->getCssGradient('333333', '555555'); ?>
}
.navigation select {
margin: 0 .8em;
}
.cEdit {
margin: 0;
padding: 0;
position: absolute;
}
.cEdit input[type=text] {
background: #FFF;
height: 100%;
margin: 0;
padding: 0;
}
.cEdit .edit_area {
background: #FFF;
border: 1px solid #999;
min-width: 10em;
padding: .3em .5em;
}
.cEdit .edit_area select,
.cEdit .edit_area textarea {
width: 97%;
}
.cEdit .cell_edit_hint {
color: #555;
font-size: .8em;
margin: .3em .2em;
}
.cEdit .edit_box {
overflow: hidden;
padding: 0;
}
.cEdit .edit_box_posting {
background: #FFF url(<?php echo $_SESSION['PMA_Theme']->getImgPath('ajax_clock_small.gif');?>) no-repeat right center;
padding-<?php echo $right; ?>: 1.5em;
}
.cEdit .edit_area_loading {
background: #FFF url(<?php echo $_SESSION['PMA_Theme']->getImgPath('ajax_clock_small.gif');?>) no-repeat center;
height: 10em;
}
.cEdit .edit_area_right {
position: absolute;
right: 0;
}
.cEdit .goto_link {
background: #EEE;
color: #555;
padding: .2em .3em;
}
.saving_edited_data {
background: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('ajax_clock_small.gif');?>) no-repeat left;
padding-<?php echo $left; ?>: 20px;
}
#relationalTable select {
width: 125px;
margin-right: 5px;
}
/* css for timepicker */
.ui-timepicker-div .ui-widget-header { margin-bottom: 8px; }
.ui-timepicker-div dl { text-align: <?php echo $left; ?>; }
.ui-timepicker-div dl dt { height: 25px; margin-bottom: -25px; }
.ui-timepicker-div dl dd { margin: 0 10px 10px 85px; }
.ui-timepicker-div td { font-size: 90%; }
.ui-tpicker-grid-label { background: none; border: none; margin: 0; padding: 0; }
.ui-timepicker-rtl { direction: rtl; }
.ui-timepicker-rtl dl { text-align: right; }
.ui-timepicker-rtl dl dd { margin: 0 65px 10px 10px; }
input.btn {
color: #333;
background-color: #D0DCE0;
}
body .ui-widget {
font-size: 1em;
}
.ui-dialog fieldset legend a {
color: #235A81;
}
/* over-riding jqplot-yaxis class */
.jqplot-yaxis {
left:0px !important;
min-width:25px;
width:auto;
}
.jqplot-axis {
overflow:hidden;
}
.report-data {
height:13em;
overflow:scroll;
width:570px;
border: solid 1px;
background: white;
padding: 2px;
}
.report-description {
height:10em;
width:570px;
}
| gpl-2.0 |
ozalvarez/elcubo9 | elcubo9.data/Order.cs | 1881 | using elcubo9.data.binding;
using elcubo9.data.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace elcubo9.data
{
public class Order : OrderBase
{
[ForeignKey("UserID")]
public virtual ApplicationUser User { get; set; }
[ForeignKey("CustomerID")]
public virtual Customer Customer { get; set; }
public virtual List<OrderMenu> OrderMenus { get; set; }
}
public class OrderMenu
{
public int OrderMenuID { get; set; }
public int OrderID { get; set; }
public int MenuID { get; set; }
public int Quantity { get; set; }
public string AdditionalInfo { get; set; }
[ForeignKey("OrderID")]
public virtual Order Order { get; set; }
[ForeignKey("MenuID")]
public virtual Menu Menu { get; set; }
public virtual List<OrderMenuAdditional> OrderMenuAdditionals { get; set; }
}
public class OrderMenuAdditional
{
public int OrderMenuAdditionalID { get; set; }
public int OrderMenuID { get; set; }
public int AdditionalItemID { get; set; }
[ForeignKey("OrderMenuID")]
public virtual OrderMenu OrderMenu { get; set; }
[ForeignKey("AdditionalItemID")]
public virtual AdditionalItem AdditionalItem { get; set; }
}
public class OrderEmailSent
{
[Key, Column(Order = 1)]
public int CustomerEmailID { get; set; }
[Key, Column(Order = 2)]
public int OrderID { get; set; }
[ForeignKey("CustomerEmailID")]
public virtual CustomerEmail CustomerEmail { get; set; }
[ForeignKey("OrderID")]
public virtual Order Order { get; set; }
}
}
| gpl-2.0 |
joomla-extensions/boilerplate | src/j4component/administrator/components/com_foos/Table/FooTable.php | 2122 | <?php
/**
* @package Joomla.Administrator
* @subpackage com_foos
*
* @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\Component\Foos\Administrator\Table;
defined('_JEXEC') or die;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Table\Table;
use Joomla\Database\DatabaseDriver;
use Joomla\Registry\Registry;
/**
* Foos Table class.
*
* @since 1.0
*/
class FooTable extends Table
{
/**
* Indicates that columns fully support the NULL value in the database
*
* @var boolean
* @since 4.0.0
*/
protected $_supportNullValue = true;
/**
* Constructor
*
* @param DatabaseDriver $db Database connector object
*
* @since 1.0
*/
public function __construct(DatabaseDriver $db)
{
$this->typeAlias = 'com_foos.foo';
parent::__construct('#__foos_details', 'id', $db);
}
/**
* Stores a contact.
*
* @param boolean $updateNulls True to update fields even if they are null.
*
* @return boolean True on success, false on failure.
*
* @since 1.0
*/
public function store($updateNulls = false)
{
// Transform the params field
if (is_array($this->params))
{
$registry = new Registry($this->params);
$this->params = (string) $registry;
}
return parent::store($updateNulls);
}
/**
* Overloaded check function
*
* @return boolean
*
* @see Table::check
* @since 1.5
*/
public function check()
{
try
{
parent::check();
}
catch (\Exception $e)
{
$this->setError($e->getMessage());
return false;
}
// Check the publish down date is not earlier than publish up.
if ($this->publish_down > $this->_db->getNullDate() && $this->publish_down < $this->publish_up)
{
$this->setError(Text::_('JGLOBAL_START_PUBLISH_AFTER_FINISH'));
return false;
}
// Set publish_up, publish_down to null if not set
if (!$this->publish_up)
{
$this->publish_up = null;
}
if (!$this->publish_down)
{
$this->publish_down = null;
}
return true;
}
}
| gpl-2.0 |
rasken2003/fuga-it-business | wp-content/themes/colormag/inc/customizer/core/assets/js/customizer-controls.js | 1933 | /**
* Customizer controls.
*
* @package ColorMag
*/
(
function ( $ ) {
/* Internal shorthand */
var api = wp.customize;
/**
* Helper class for the main Customizer interface.
*
* @class ColorMagCustomizer
*/
ColorMagCustomizer = {
controls : {},
/**
* Initializes our custom logic for the Customizer.
*
* @method init
*/
init : function () {
ColorMagCustomizer._initToggles();
},
/**
* Initializes the logic for showing and hiding controls
* when a setting changes.
*
* @since 1.0.0
* @access private
* @method _initToggles
*/
_initToggles : function () {
// Trigger the Adv Tab Click trigger.
ColorMagControlTrigger.triggerHook( 'colormag-toggle-control', api );
// Loop through each setting.
$.each(
ColorMagCustomizerToggles,
function ( settingId, toggles ) {
// Get the setting object.
api(
settingId,
function ( setting ) {
// Loop though the toggles for the setting.
$.each(
toggles,
function ( i, toggle ) {
// Loop through the controls for the toggle.
$.each(
toggle.controls,
function ( k, controlId ) {
// Get the control object.
api.control(
controlId,
function ( control ) {
// Define the visibility callback.
var visibility = function ( to ) {
control.container.toggle( toggle.callback( to ) );
};
// Init visibility.
visibility( setting.get() );
// Bind the visibility callback to the setting.
setting.bind( visibility );
}
);
}
);
}
);
}
);
}
);
}
};
$(
function () {
ColorMagCustomizer.init();
}
);
}
)( jQuery );
| gpl-2.0 |
UnaCloud/UnaCloud2 | UnaCloudWeb/grails-app/assets/javascripts/pages.js | 12490 | $(document).on('ready',function(){
$('.delete_user').click(function (event){
event.preventDefault();
redirectConfirm($(this).data("id"), $(this).attr("href"), 'User')
});
$('.delete_group').click(function (event){
event.preventDefault();
redirectConfirm($(this).data("id"), $(this).attr("href"), 'Group')
});
$('.delete_cluster').click(function (event){
event.preventDefault();
redirectConfirm($(this).data("id"), $(this).attr("href"), 'Cluster')
});
$(".delete_images").click(function (event){
event.preventDefault();
redirectConfirm($(this).data("id"), $(this).attr("href"), 'Image')
});
$(".delete_repo").click(function (event){
event.preventDefault();
redirectConfirm($(this).data("id"), $(this).attr("href"), 'Storage')
});
$(".delete_platform").click(function (event){
event.preventDefault();
redirectConfirm($(this).data("id"), $(this).attr("href"), 'Platform')
});
$(".delete_os").click(function (event){
event.preventDefault();
redirectConfirm($(this).data("id"), $(this).attr("href"), 'Operating System')
});
$("#delete-lab").click(function (event){
event.preventDefault();
redirectConfirm($(this).data("id"), $(this).attr("href"), 'Laboratory', $(this).attr("method"))
});
$(".delete_ip").click(function (event){
event.preventDefault();
redirectConfirm($(this).data("id"), $(this).attr("href"), 'IP', 'delete')
});
$(".delete_pool").click(function (event){
event.preventDefault();
redirectConfirm($(this).data("id"), $(this).attr("href"), 'IP Pool', 'delete')
});
$(".delete_machines").click(function (event){
event.preventDefault();
redirectConfirm($(this).data("id"), $(this).attr("href"), 'Host', 'delete')
});
$(".stop-agents").click(function (event){
event.preventDefault();
var href = $(this).attr("href");
var form = $('#form_machines');
submitConfirm(form, href, 'All selected host machines will be stopped. Do you want to continue?');
});
$(".stop-executions").click(function (event){
event.preventDefault();
var href = $(this).attr("href");
var form = $('#form_deployments');
submitConfirm(form, href, 'All selected executions will be stopped. Do you want to continue?');
});
$(".cache-agents").click(function (event){
event.preventDefault();
var href = $(this).attr("href");
var form = $('#form_machines');
submitConfirm(form, href, 'All selected host machines will erase their cache. Do you want to continue?');
});
$(".update-agents").click(function (event){
event.preventDefault();
var href = $(this).attr("href");
var form = $('#form_machines');
submitConfirm(form, href, 'All selected host machines will update their agents, some processes in agents will be stopped. Do you want to continue?');
});
$(".no_required_confirm_task").click(function (event){
event.preventDefault();
var href = $(this).attr("href");
var form = $('#form_machines');
submitConfirm(form, href);
});
$(".multiple_selection_confirm_task").click(function (event){
event.preventDefault();
var href = $(this).attr("href");
var form = $('#form_machines');
fastConfirm(form, href);
});
$('.clear_image').click(function (event){
event.preventDefault();
var data = $(this).data("id");
var href = $(this).attr("href");
sendConfirm('This image will be removed from all currently connected physical machines. Are you sure you want to remove it?',href,data)
});
$('#disable-lab').click(function (event){
event.preventDefault();
var data = $(this).data("id");
var href = $(this).attr("href");
var state = $(this).data("state");
var method = $(this).data("method");
var text = "";
if(state) text = "enabled to disabled"
else text = "disabled to enabled"
sendConfirm('This laboratory will change its status from <strong>'+text+'</strong>. Are you sure you want to change it?', href, data, method);
});
$('#button-upload').click(function (event){
cleanLabel('#label-message');
var form = $('#form-new');
requestFile(form)
});
$('#button-update').click(function (event){
cleanLabel('#label-message');
var form = $('#form-change');
requestFile(form)
});
$('.btn-variable').click(function(event){
var parent = $(this).parent();
parent.find('input.btn-submit').removeClass('hide-segment');
parent.find('input.btn-cancel').removeClass('hide-segment');
parent.find('input.btn-variable').addClass('hide-segment');
$('.'+parent.attr('id')).prop('disabled', false);
});
$('.btn-cancel').click(function(event){
var parent = $(this).parent();
parent.find('input.btn-submit').addClass('hide-segment');
parent.find('input.btn-cancel').addClass('hide-segment');
parent.find('input.btn-variable').removeClass('hide-segment');
$('.'+parent.attr('id')).prop('disabled', true);
});
$(".download_btn").on("click",function(event){
event.preventDefault();
var execution = $(this).data("id");
var href = $(this).attr("href");
var imagename = $(this).data("imagename");
bootbox.dialog({
title: "Save Image Copy",
message: "<form id='form_copy' method='post'>"+
"<div class='box-body'>"+
"<div class='form-group'>"+
"<label>Write the name that will be used to save the copy</label>"+
"<input class='form-control' id='imageName' name='name' type='text' value='"+imagename+"'>"+
"</div>"+
"</div>"+
"</form>",
buttons: {
success: {
label: "Save",
className: "btn-success",
callback: function () {
var form = $('#form_copy');
form.attr('action',href+execution);
form.submit()
}
},
cancel: {
label: "Cancel",
className: "btn-danger",
},
}
});
});
$("#unacloudTable").dataTable();
$("#unacloudTable2").dataTable();
tableChecker();
editImage();
mask();
$(".btn-time-nxt").on("click",function(event){
event.preventDefault();
var goElement = $(this).data("element");
$(".time-title"+goElement).addClass("hidden")
$(".time-element"+goElement).removeClass("hidden").addClass("animated fadeIn")
$(".time-title"+(goElement-1)).removeClass("hidden")
$(".time-element"+(goElement-1)).addClass("hidden")
$("#time-icon"+goElement).removeClass("fa-circle-o").removeClass("bg-gray").addClass("fa-adjust").addClass("bg-blue")
$("#time-icon"+(goElement-1)).removeClass("fa-adjust").removeClass("bg-blue").addClass("fa-check").addClass("bg-green")
});
$(".btn-time-bck").on("click",function(event){
event.preventDefault();
var goElement = $(this).data("element");
$(".time-title"+goElement).addClass("hidden")
$(".time-element"+goElement).removeClass("hidden").addClass("animated fadeIn")
$(".time-title"+(goElement+1)).removeClass("hidden")
$(".time-element"+(goElement+1)).addClass("hidden")
$("#time-icon"+goElement).removeClass("fa-check").removeClass("bg-green").addClass("fa-adjust").addClass("bg-blue")
$("#time-icon"+(goElement+1)).removeClass("fa-adjust").removeClass("bg-blue").addClass("fa-circle-o").addClass("bg-gray")
});
});
function tableChecker(){
var checks = 0;
$('#selectAll').click(function (event) {
var selected = this.checked;
if(selected)$('#btn-group-agent').removeClass("hide-segment");
else{
$('#btn-group-agent').addClass("hide-segment");
checks = 0;
}
$('.all:checkbox').each(function () {
if(!this.checked&&selected)checks++;
this.checked = selected;
});
});
$('.all:checkbox').click(function(event){
var selected = this.checked;
if(selected)checks++;
else checks--;
if(checks>=1)$('#btn-group-agent').removeClass("hide-segment");
else $('#btn-group-agent').addClass("hide-segment");
});
$('.image_check').click(function (event) {
var selected = this.checked;
var id = $(this).data("id");
$('.image_'+id+':checkbox').each(function () {
if(!this.checked&&selected)checks++;
else checks--;
this.checked = selected;
});
});
}
function showMessage(data, message){
if(data.success){
addLabel('#label-message', message, false);
}
}
function checkSelected(){
cleanLabel('#label-message');
var selected = false;
$('.all:checkbox').each(function () {
if(this.checked){
selected = true;
return;
}
});
if(!selected){
addLabel('#label-message','At least one physical machine should be selected.',true);
}
return selected;
}
function submitConfirm(form, href, message) {
if (checkSelected()) {
var func = function () {
form.attr('action', href);
form.submit()
}
if (message)
showConfirm('Confirm', message, func);
else
func();
}
}
function fastConfirm(form, href, message) {
var func = function () {
form.attr('action', href);
form.submit()
}
func();
}
function redirectConfirm(data, href, name, method){
sendConfirm('This <strong>'+name+'</strong> will be deleted. Are you sure you want to confirm it?', href, data, method)
}
function sendConfirm(message, href, data, method){
var url = href + data
if(method)
url = href + data + '/' + method;
showConfirm('Confirm', message, function(){
window.location.href = url;
});
}
function requestFile(form){
$.post(form.attr('action'), form.serialize(), function(data){
if(data.success){
bootbox.dialog({
title: "Upload Image",
message:"<form id='form_image' method='post' action='"+data.url+"' enctype='multipart/form-data'>"+
"<div class='box-body'>"+
"<div class='form-group'>"+
"<label>Image File input</label>"+
"<input type='file' name='files' multiple>"+
"<input type='hidden' name='token' value='"+data.token+"'>"+
"</div>"+
"</div>"+
"</form>",
buttons: {
success: {
label: "Upload",
className: "btn-success",
callback: function () {
var form_image = document.getElementById('form_image');
uploadForm(form_image)
}
},
}
});
}else{
addLabel('#label-message',data.message,true)
}
}, 'json')
}
function uploadForm(form){
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
updateUploading(e);
};
xhr.onload = function() {
hideLoading();
if (xhr.status == 200) {
var jsonResponse = JSON.parse(xhr.responseText);
console.log(jsonResponse);
if(jsonResponse.success){
if((jsonResponse.cPublic&&jsonResponse.cPublic==true)||jsonResponse.cPublic==undefined){
window.location.href = jsonResponse.redirect;
}else{
showClose('Error saving as a public image!','There is another public image with the same name. Your image was saved as a private one', function(){
window.location.href = jsonResponse.redirect;
});
}
}
else addLabel('#label-message', jsonResponse.message, true);
}else showError('Error!','Upload failed: '+xhr.response);
};
xhr.onerror = function() {
hideLoading();
showError('Error!','Upload failed. Cannot connect to server.')
};
showLoadingUploading();
xhr.open("POST", form.action)
xhr.send(formData);
}
function editImage(){
var pub = $("#check_public").is(':checked')
$('#button-submit-edit').click(function (event){
event.preventDefault();
cleanLabel('#label-message');
var form = document.getElementById("form-edit");
if(form["name"].value&&form["name"].value.length > 0&&
form["user"].value&&form["user"].value.length > 0){
var call = function(){
form.submit()
}
if(form["isPublic"].checked!=pub){
if(pub) showConfirm('Confirm','Your image will change its privacy policy from public to private and others users won\'t be allowed to copy it. Are you sure you want to change it?', call);
else showConfirm('Confirm','Your image will change its privacy policy from private to public and others users will be allowed to copy it. Are you sure you want to change it?', call);
}else call();
}else addLabel('#label-message', 'Name and user are required', true);
});
}
function mask(){
$("[data-mask]").inputmask();
//$("[data-mask-mac]").inputmask("[AA]:[AA]:[AA]:[AA]:[AA]:[AA]");
}
| gpl-2.0 |
pobbes/gambio | admin/includes/magnalister/php/modules/yatego/categorymatching.php | 22372 | <?php
/**
* 888888ba dP .88888. dP
* 88 `8b 88 d8' `88 88
* 88aaaa8P' .d8888b. .d888b88 88 .d8888b. .d8888b. 88 .dP .d8888b.
* 88 `8b. 88ooood8 88' `88 88 YP88 88ooood8 88' `"" 88888" 88' `88
* 88 88 88. ... 88. .88 Y8. .88 88. ... 88. ... 88 `8b. 88. .88
* dP dP `88888P' `88888P8 `88888' `88888P' `88888P' dP `YP `88888P'
*
* m a g n a l i s t e r
* boost your Online-Shop
*
* -----------------------------------------------------------------------------
* $Id: categorymatching.php 744 2011-01-31 13:19:21Z derpapst $
*
* (c) 2010 RedGecko GmbH -- http://www.redgecko.de
* Released under the GNU General Public License v2 or later
* -----------------------------------------------------------------------------
*/
defined('_VALID_XTC') or die('Direct Access to this location is not allowed.');
class YategoCategoryMatching {
private $request = 'view';
private $mpID = null;
private $url;
public function __construct($request = 'view') {
global $_url, $_MagnaSession;
$this->request = $request;
$this->mpID = $_MagnaSession['mpID'];
$this->url = $_url;
}
private function getYategoCategories($object_id = '') {
if ($object_id == '') {
$level = 0;
} else {
$level = substr_count($object_id, '-') + 1;
}
$field = '';
switch ($level) {
case 2: {
$field = 'title_l';
break;
}
case 1: {
$field = 'title_m';
break;
}
default: {
$field = 'title_h';
break;
}
}
$yategoCategories = MagnaDB::gi()->fetchArray('
SELECT DISTINCT '.$field.' AS title, object_id
FROM '.TABLE_MAGNA_YATEGO_CATEGORIES.'
WHERE object_id LIKE \''.$object_id.'%\'
GROUP BY '.$field.'
');
if (empty($yategoCategories)) {
return false;
}
if ($level < 2) {
foreach ($yategoCategories as &$item) {
if ($level == 1) {
$item['object_id'] = substr($item['object_id'], 0, strrpos($item['object_id'], '-'));
} else {
$item['object_id'] = substr($item['object_id'], 0, strpos($item['object_id'], '-'));
}
}
}
return $yategoCategories;
}
private function getShopCategories($cID) {
$subCats = MagnaDB::gi()->fetchArray('
SELECT c.categories_id, c.parent_id, cd.categories_name
FROM '.TABLE_CATEGORIES.' c, '.TABLE_CATEGORIES_DESCRIPTION.' cd
WHERE c.categories_id = cd.categories_id AND
c.parent_id = '.$cID.' AND
cd.language_id = \''.$_SESSION['languages_id'].'\'
ORDER BY TRIM(cd.categories_name) ASC
');
if (empty($subCats)) {
return false;
}
foreach($subCats as &$item) {
$item['children'] = MagnaDB::gi()->fetchOne('
SELECT count(c.parent_id) FROM '.TABLE_CATEGORIES.' c WHERE c.parent_id = '.$item['categories_id']
);
$item['yCats'] = MagnaDB::gi()->fetchOne('
SELECT count(yatego_category_id)
FROM '.TABLE_MAGNA_YATEGO_CATEGORYMATCHING.'
WHERE category_id=\''.$item['categories_id'].'\'
AND mpID=\''.$this->mpID.'\'
GROUP BY category_id'
);
}
return $subCats;
}
private function renderShopCategories($cID) {
$catTree = $this->getShopCategories($cID);
foreach ($catTree as $item) {
$class = array('toggle');
if ($item['children']) {
$class[] = 'plus';
} else {
$class[] = 'leaf';
}
if ($item['yCats']) {
$class[] = 'tick';
}
$item['categories_name'] = htmlspecialchars($item['categories_name']);
$html .= '
<div class="catelem" id="s_'.$item['categories_id'].'"'.(!empty($subcats) ? ' style="display:none"' : '').'>
<span class="'.implode(' ', $class).'" id="s_toggle_'.$item['categories_id'].'"> </span>
<div class="catname" id="s_select_'.$item['categories_id'].'">
<span class="catname">'.fixHTMLUTF8Entities($item['categories_name']).'</span>
</div>
</div>';
}
if ($cID == 0) {
$html = '
<div class="catelem" id="s_0">
<span class="toggle minus" id="s_toggle_0"> </span>
<div class="catname" id="s_select_0">
<span class="catname">'.fixHTMLUTF8Entities(ML_LABEL_CATEGORY_TOP).'</span>'.$html.'
</div>
</div>';
}
return $html;
}
private function renderYategoCategories($object_id = '') {
$isLeaf = substr_count($object_id, '-')+1 == 2;
$yategoSubCats = $this->getYategoCategories($object_id);
if ($yategoSubCats === false) {
return ML_YAGETO_ERROR_CATEGORIES_NOT_IMPORTED_YET;
}
$yategoTopLevelList = '';
foreach ($yategoSubCats as $item) {
if ($isLeaf) {
$class = 'leaf';
} else {
$class = 'plus';
}
$yategoTopLevelList .= '
<div class="catelem" id="y_'.$item['object_id'].'">
<span class="toggle '.$class.'" id="y_toggle_'.$item['object_id'].'"> </span>
<div class="catname" id="y_select_'.$item['object_id'].'">
<span class="catname">'.fixHTMLUTF8Entities($item['title']).'</span>
</div>
</div>';
}
return $yategoTopLevelList;
}
private function getYategoCategoryPath($object_id) {
$yCP = MagnaDB::gi()->fetchRow('
SELECT * FROM '.TABLE_MAGNA_YATEGO_CATEGORIES.'
WHERE object_id=\''.$object_id.'\'
LIMIT 1
');
if ($yCP === false) {
return '<span class="invalid">'.ML_LABEL_INVALID.'</span>';
}
$appendedText = ' <span class="cp_next">></span> ';
return fixHTMLUTF8Entities($yCP['title_h']).$appendedText.
fixHTMLUTF8Entities($yCP['title_m']).$appendedText.
fixHTMLUTF8Entities($yCP['title_l']);
}
private function renderYategoCategoryItem($id) {
return '
<div id="yc_'.$id.'" class="yategoCategory">
<div id="y_remove_'.$id.'" class="y_rm_handle"> </div><div class="ycpath">'.$this->getYategoCategoryPath($id).'</div>
</div>';
}
public function renderView() {
$html = '
<table id="catMatch"><tbody>
<tr>
<td class="headline">'.ML_YATEGO_LABEL_SHOP_CATEGORIES.'</td>
<td class="spacer"> </td>
<td class="headline">'.ML_YATEGO_LABEL_YATEGO_CATEGORIES.'</td>
<td class="spacer"> </td>
<td class="headline">'.ML_YATEGO_LABEL_SELECTED_SHOP_CAT.'</td>
</tr>
<tr>
<td rowspan="3" id="shopCats" class="catView"><div class="catView">'.$this->renderShopCategories(0).'</div></td>
<td rowspan="3" class="spacer"> </td>
<td rowspan="3" id="yategoCats" class="catView"><div class="catView">'.$this->renderYategoCategories('').'</div></td>
<td rowspan="3" class="spacer"> </td>
<td id="selectedShopCategory" class="catView">
<div class="catView"></div>
</td>
</tr>
<tr>
<td class="headline">'.ML_YATEGO_LABEL_SELECTED_YATEGO_CATS.'</td>
</tr>
<tr>
<td id="selectedYategoCategories" class="catView">
<div class="catView"></div>
</td>
</tr>
<tr class="spacer">
<td colspan="5"> </td>
</tr>
</tbody></table>
<div id="messageDialog" class="dialog2"></div>
<table class="actions">
<thead><tr><th>'.ML_LABEL_ACTIONS.'</th></tr></thead>
<tbody>
<tr class="firstChild"><td>
<table><tbody><tr>
<td class="firstChild">'.
'<input type="button" class="button" value="'.ML_YATEGO_LABEL_PURGE_CATEGORIES.'" id="yPurgeCategories" />
<div id="confirmPurgeDiag" class="dialog2" title="'.ML_YATEGO_HINT_HEADLINE_PURGE_CATEGORIES.'">'.ML_YATEGO_TEXT_PURGE_CATEGORIES.'</div>
<script type="text/javascript">/*<![CDATA[*/
$(document).ready(function() {
$(\'#yPurgeCategories\').click(function() {
$(\'#confirmPurgeDiag\').jDialog({
buttons: {
'.ML_BUTTON_LABEL_ABORT.': function() {
$(this).dialog(\'close\');
},
'.ML_BUTTON_LABEL_OK.': function() {
window.location.href = \''.toURL($this->url, array('yPurgeCategories' => 'true'), true).'\';
$(this).dialog(\'close\');
}
}
});
});
});
/*]]>*/</script>'.
'</td>
<td class="lastChild">'.'<input type="button" class="button" value="'.ML_BUTTON_LABEL_SAVE_DATA.'" id="saveMatching"/>'.'</td>
</tr></tbody></table>
</td></tr>
</tbody>
</table>
';
ob_start();
?>
<script type="text/javascript">/*<![CDATA[*/
var selectedShopCategory = '';
var selectedYategoCategories = new Array();
var madeChanges = false;
function collapseAllNodes(elem) {
$('div.catelem span.toggle:not(.leaf)', $(elem)).each(function() {
$(this).removeClass('minus').addClass('plus');
$(this).parent().children('div.catname').children('div.catelem').css({display: 'none'});
});
$('div.catname span.catname.selected', $(elem)).removeClass('selected').css({'font-weight':'normal'});
}
function resetEverything() {
madeChanges = false;
collapseAllNodes($('#yategoCats'));
collapseAllNodes($('#shopCats'));
/* Expand Top-Node */
$('#s_toggle_0').removeClass('plus').addClass('minus').parent().children('div.catname').children('div.catelem').css({display: 'block'});
$('#selectedYategoCategories div.catView').empty();
$('#selectedShopCategory div.catView').empty();
selectedYategoCategories = new Array();
selectedShopCategory = '';
}
function appendYategoCategory(yID, html) {
madeChanges = true;
$('#selectedYategoCategories div.catView').append(html).children().last().data({'origID': yID}).click(function() {
madeChanges = true;
origID = $(this).data('origID');
$('#'+origID+' span.catname.selected').removeClass('selected').css({'font-weight':'normal'});
$(this).remove();
//myConsole.log(origID, selectedYategoCategories);
array_remove(selectedYategoCategories, origID);
myConsole.log(origID, selectedYategoCategories);
//myConsole.log($(this));
});
selectedYategoCategories.push(yID);
myConsole.log('selectedYategoCategories', selectedYategoCategories);
$('#'+yID+' span.catname').addClass('selected').css({'font-weight':'bold'});
}
function selectShopCategory(elem, doit) {
if ((selectedYategoCategories.length > 0) && (madeChanges) && !doit) {
$('#messageDialog').html(
'<?php echo preg_replace('/\s\s+/', ' ', ML_YATEGO_MESSAGE_NOT_YET_SAVED); ?>'
).jDialog({
title: '<?php echo ML_LABEL_NOTE; ?>',
buttons: {
'<?php echo ML_BUTTON_LABEL_YES; ?>': function() {
$(this).dialog('close');
selectShopCategory(elem, true);
},
'<?php echo ML_BUTTON_LABEL_NO; ?>': function() {
$(this).dialog('close');
return;
}
}
});
return;
}
if (selectedYategoCategories.length > 0) {
collapseAllNodes($('#yategoCats'));
}
$('#selectedYategoCategories div.catView').empty();
selectedYategoCategories = new Array();
tmpNewID = $(elem).parent().attr('id');
if (selectedShopCategory != tmpNewID) {
$('#shopCats div.catname span.catname.selected').removeClass('selected').css({'font-weight':'normal'});
$(elem).addClass('selected').css({'font-weight':'bold'});
jQuery.blockUI(blockUILoading);
jQuery.ajax({
type: 'POST',
url: '<?php echo toURL($this->url, array('kind' => 'ajax'), true);?>',
data: {
'action': 'getCategoryPath',
'id': tmpNewID
},
success: function(data) {
myConsole.log(data.shopCatHtml);
$('#selectedShopCategory div.catView').html(data.shopCatHtml);
if (data.yCategories.length > 0) {
for (var c = 0; c < data.yCategories.length; ++c) {
yCat = data.yCategories[c];
myConsole.log('yCat', yCat);
appendYategoCategory(yCat.origID, yCat.html);
}
}
madeChanges = false;
jQuery.unblockUI();
},
error: function() {
jQuery.unblockUI();
},
dataType: 'json'
});
selectedShopCategory = tmpNewID;
}
}
function addShopCategoriesEventListener(elem) {
/* Shop Kategorien */
$('div.catelem span.toggle:not(.leaf)', $(elem)).each(function() {
$(this).click(function () {
myConsole.log($(this).attr('id'));
if ($(this).hasClass('plus')) {
tmpElem = $(this);
tmpElem.removeClass('plus').addClass('minus');
if (tmpElem.parent().children('div.catname').children('div.catelem').length == 0) {
jQuery.blockUI(blockUILoading);
jQuery.ajax({
type: 'POST',
url: '<?php echo toURL($this->url, array('kind' => 'ajax'), true);?>',
data: {
'action': 'getShopCategories',
'cID': tmpElem.attr('id')
},
success: function(data) {
appendTo = tmpElem.parent().children('div.catname');
appendTo.append(data);
addShopCategoriesEventListener(appendTo);
appendTo.children('div.catelem').css({display: 'block'});
jQuery.unblockUI();
},
error: function() {
jQuery.unblockUI();
},
dataType: 'html'
});
} else {
tmpElem.parent().children('div.catname').children('div.catelem').css({display: 'block'});
}
} else {
$(this).removeClass('minus').addClass('plus');
$(this).parent().children('div.catname').children('div.catelem').css({display: 'none'});
}
});
// myConsole.log($(this).attr('id'));
});
$('div.catelem span.toggle.leaf', $(elem)).each(function() {
$(this).click(function () {
selectShopCategory($(this).parent().children('div.catname').children('span.catname'));
});
});
$('div.catname span.catname', $(elem)).each(function() {
$(this).click(function () {
selectShopCategory($(this));
});
});
}
function array_remove( inputArr ) {
var argv = arguments, argc = argv.length;
for (i = 1; i < argc; ++i) {
if ((ix = inputArr.indexOf(argv[i])) != -1) {
inputArr.splice(ix, 1);
}
}
}
function addYategoCategory(elem) {
if ($('#selectedShopCategory div.catView:empty').length) {
$('#messageDialog').html(
'<?php echo preg_replace('/\s\s+/', ' ', ML_YATEGO_MESSAGE_SELECT_SHOP_CAT_FIRST); ?>'
).jDialog({
title: '<?php echo ML_LABEL_NOTE; ?>'
});
return;
}
tmpNewID = $(elem).parent().attr('id');
if (in_array(tmpNewID, selectedYategoCategories)) {
return;
}
shortYID = tmpNewID.substr(0, tmpNewID.lastIndexOf('-'));
for (i = 0; i < selectedYategoCategories.length; ++i) {
if (shortYID == selectedYategoCategories[i].substr(0, selectedYategoCategories[i].lastIndexOf('-'))) {
$('#messageDialog').html(
'<?php echo preg_replace('/\s\s+/', ' ', ML_YATEGO_MESSAGE_ONLY_ONE_SUBCAT); ?>'
).jDialog({
title: '<?php echo ML_LABEL_NOTE; ?>'
});
return;
}
}
jQuery.blockUI(blockUILoading);
jQuery.ajax({
type: 'POST',
url: '<?php echo toURL($this->url, array('kind' => 'ajax'), true);?>',
data: {
'action': 'getYategoCategoryPath',
'id': tmpNewID
},
success: function(data) {
appendYategoCategory(tmpNewID, data);
jQuery.unblockUI();
},
error: function() {
jQuery.unblockUI();
},
dataType: 'html'
});
}
function addYategoCategoriesEventListener(elem) {
$('div.catelem span.toggle:not(.leaf)', $(elem)).each(function() {
$(this).click(function () {
myConsole.log($(this).attr('id'));
if ($(this).hasClass('plus')) {
tmpElem = $(this);
tmpElem.removeClass('plus').addClass('minus');
if (tmpElem.parent().children('div.catname').children('div.catelem').length == 0) {
jQuery.blockUI(blockUILoading);
jQuery.ajax({
type: 'POST',
url: '<?php echo toURL($this->url, array('kind' => 'ajax'), true);?>',
data: {
'action': 'getYategoCategories',
'objID': tmpElem.attr('id')
},
success: function(data) {
appendTo = tmpElem.parent().children('div.catname');
appendTo.append(data);
addYategoCategoriesEventListener(appendTo);
appendTo.children('div.catelem').css({display: 'block'});
jQuery.unblockUI();
},
error: function() {
jQuery.unblockUI();
},
dataType: 'html'
});
} else {
tmpElem.parent().children('div.catname').children('div.catelem').css({display: 'block'});
}
} else {
$(this).removeClass('minus').addClass('plus');
$(this).parent().children('div.catname').children('div.catelem').css({display: 'none'});
}
});
});
$('div.catelem span.toggle.leaf', $(elem)).each(function() {
$(this).click(function () {
addYategoCategory($(this).parent().children('div.catname').children('span.catname'));
});
$(this).parent().children('div.catname').children('span.catname').each(function() {
$(this).click(function () {
addYategoCategory($(this));
});
if (in_array($(this).parent().attr('id'), selectedYategoCategories)) {
$(this).addClass('selected').css({'font-weight':'bold'});
}
});
});
}
$(document).ready(function() {
addShopCategoriesEventListener($('#shopCats'));
addYategoCategoriesEventListener($('#yategoCats'));
$('#saveMatching').click(function() {
if (selectedShopCategory == '') {
$('#messageDialog').html(
'<?php echo preg_replace('/\s\s+/', ' ', ML_YATEGO_MESSAGE_SAVE_SELECT_SHOP_CAT_FIRST); ?>'
).jDialog({
title: '<?php echo ML_LABEL_NOTE; ?>'
});
return;
}
/*
if (selectedYategoCategories.length == 0) {
$('#messageDialog').html(
'Es kann nichts gespeichert werden, da Sie der ausgewählten Shop-Kategorie noch keine Yatego-Kategorien hinzugefügt haben.'
).jDialog({
title: '<?php echo ML_LABEL_NOTE; ?>'
});
return;
}
*/
jQuery.blockUI(blockUILoading);
jQuery.ajax({
type: 'POST',
url: '<?php echo toURL($this->url, array('kind' => 'ajax'), true);?>',
data: {
'action': 'saveCategoryMatching',
'selectedShopCategory': selectedShopCategory,
'selectedYategoCategories': selectedYategoCategories
},
success: function(data) {
jQuery.unblockUI();
myConsole.log('data', data);
myConsole.log('data.error', data.error);
if (data.error == "") {
$('#messageDialog').html(
'<?php echo preg_replace('/\s\s+/', ' ', ML_YATEGO_MESSAGE_MATCHING_SAVED); ?>'
).jDialog({
title: '<?php echo ML_LABEL_SAVED_SUCCESSFULLY; ?>'
});
if (selectedYategoCategories.length > 0) {
$('#'+selectedShopCategory).parent().children('span.toggle').addClass('tick');
} else {
$('#'+selectedShopCategory).parent().children('span.toggle').removeClass('tick');
}
resetEverything();
} else {
$('#messageDialog').html(
data.error
).jDialog({
title: '<?php echo ML_ERROR_LABEL; ?>'
});
}
},
error: function() {
jQuery.unblockUI();
$('#messageDialog').html(
'<?php echo preg_replace('/\s\s+/', ' ', ML_YATEGO_ERROR_WHILE_SAVING); ?>'
).jDialog({
title: '<?php echo ML_LABEL_NOTE; ?>'
});
},
dataType: 'json'
});
});
});
/*]]>*/</script>
<?php
$html .= ob_get_contents();
ob_end_clean();
return $html;
}
public function renderAjax() {
$id = '';
if (isset($_POST['id'])) {
$id = substr($_POST['id'], strrpos($_POST['id'], '_')+1);
}
switch($_POST['action']) {
case 'getCategoryPath': {
$_timer = microtime(true);
$cID = (int)$id;
$yIDs = MagnaDB::gi()->fetchArray('
SELECT yatego_category_id
FROM '.TABLE_MAGNA_YATEGO_CATEGORYMATCHING.'
WHERE category_id=\''.$cID.'\' AND mpID=\''.$this->mpID.'\'', true
);
$yategoCategories = array();
if (!empty($yIDs)) {
foreach ($yIDs as $yID) {
$yategoCategories[] = array(
'origID' => 'y_select_'.$yID,
'html' => $this->renderYategoCategoryItem($yID)
);
}
}
$shopCatHtml = renderCategoryPath($cID);
return json_encode(array(
'shopCatHtml' => $shopCatHtml,
'yCategories' => $yategoCategories,
'timer' => microtime2human(microtime(true) - $_timer)
));
break;
}
case 'getYategoCategories': {
return $this->renderYategoCategories(str_replace('y_toggle_', '', $_POST['objID']));
break;
}
case 'getShopCategories': {
return $this->renderShopCategories(str_replace('s_toggle_', '', $_POST['cID']));
break;
}
case 'getYategoCategoryPath': {
return $this->renderYategoCategoryItem($id);
}
case 'saveCategoryMatching': {
if (!isset($_POST['selectedShopCategory']) || empty($_POST['selectedShopCategory']) ||
(isset($_POST['selectedYategoCategories']) && !is_array($_POST['selectedYategoCategories']))
) {
return json_encode(array(
'debug' => var_dump_pre($_POST['selectedYategoCategories'], true),
'error' => preg_replace('/\s\s+/', ' ', ML_YATEGO_ERROR_SAVING_INVALID_YATEGO_CATS)
));
}
$cID = str_replace('s_select_', '', $_POST['selectedShopCategory']);
if (!ctype_digit($cID)) {
return json_encode(array(
'debug' => var_dump_pre($cID, true),
'error' => preg_replace('/\s\s+/', ' ', ML_YATEGO_ERROR_SAVING_INVALID_SHOP_CAT)
));
}
$cID = (int)$cID;
if (isset($_POST['selectedYategoCategories']) && !empty($_POST['selectedYategoCategories'])) {
$yategoIDs = array();
foreach ($_POST['selectedYategoCategories'] as $tmpYID) {
$tmpYID = str_replace('y_select_', '', $tmpYID);
if (preg_match('/^[0-9]{2}-[0-9]{2}-[0-9]{2}$/', $tmpYID)) {
$yategoIDs[] = $tmpYID;
}
}
if (empty($yategoIDs)) {
return json_encode(array(
'error' => preg_replace('/\s\s+/', ' ', ML_YATEGO_ERROR_SAVING_INVALID_YATEGO_CATS_ALL)
));
}
MagnaDB::gi()->delete(TABLE_MAGNA_YATEGO_CATEGORYMATCHING, array (
'category_id' => $cID,
'mpID' => $this->mpID,
));
foreach ($yategoIDs as $yID) {
MagnaDB::gi()->insert(TABLE_MAGNA_YATEGO_CATEGORYMATCHING, array (
'category_id' => $cID,
'yatego_category_id' => $yID,
'mpID' => $this->mpID,
));
}
} else {
MagnaDB::gi()->delete(TABLE_MAGNA_YATEGO_CATEGORYMATCHING, array (
'category_id' => $cID,
'mpID' => $this->mpID,
));
}
return json_encode(array(
'error' => ''
));
break;
}
default: {
return json_encode(array(
'error' => ML_YATEGO_ERROR_REQUEST_INVALID
));
}
}
}
public function render() {
if ($this->request == 'ajax') {
return $this->renderAjax();
} else {
return $this->renderView();
}
}
}
$_url['mode'] = $_magnaQuery['mode'];
$ycm = new YategoCategoryMatching((isset($_GET['kind']) && ($_GET['kind'] == 'ajax')) ? 'ajax' : 'view');
echo $ycm->render();
| gpl-2.0 |
GraphProcessor/CommunityDetectionCodes | Algorithms/2010-CONGA/conga_src/src/main/java/conga/util/StrPair.java | 398 | package conga.util;//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
public class StrPair {
public String value1;
public String value2;
public StrPair(String var1, String var2) {
this.value1 = var1;
this.value2 = var2;
}
public String toString() {
return this.value1 + "/" + this.value2;
}
}
| gpl-2.0 |
williamgrosset/OSCAR-ConCert | src/main/java/oscar/oscarTags/TagObject.java | 2808 | /**
* Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* This software was written for the
* Department of Family Medicine
* McMaster University
* Hamilton
* Ontario, Canada
*/
package oscar.oscarTags;
import java.util.ArrayList;
public class TagObject {
private ArrayList assignedTags;
private String objectId;
private String objectClass;
public void assignTag(String tagName) {
getAssignedTags().add(tagName);
}
public ArrayList getAssignedTags() {
return assignedTags;
}
public void setAssignedTags(ArrayList assignedTags) {
this.assignedTags = assignedTags;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
public String getObjectClass() {
return objectClass;
}
public void setObjectClass(String objectClass) {
this.objectClass = objectClass;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((assignedTags == null) ? 0 : assignedTags.hashCode());
result = prime * result + ((objectClass == null) ? 0 : objectClass.hashCode());
result = prime * result + ((objectId == null) ? 0 : objectId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
TagObject other = (TagObject) obj;
if (assignedTags == null) {
if (other.assignedTags != null) return false;
} else if (!assignedTags.equals(other.assignedTags)) return false;
if (objectClass == null) {
if (other.objectClass != null) return false;
} else if (!objectClass.equals(other.objectClass)) return false;
if (objectId == null) {
if (other.objectId != null) return false;
} else if (!objectId.equals(other.objectId)) return false;
return true;
}
}
| gpl-2.0 |
Rockam/XgameJS | src/JS/XNA_Classes/Song.js | 2473 | /**
* A song.
* @constructor
* @param {String} name - the path to the resource.
*/
function Song(name) {
"use strict";
/*global Audio*/
this.Name = name;
this.Audio = new Audio();
this.Audio.src = name;
this.Audio.loop = true;
this.Audio.muted = false;
this.Audio.volume = 0.8;
}
/**
* Gets the duration of the song.
* @name Duration
* @function
* @memberOf Song
*/
Song.prototype.Duration = function () {
"use strict";
return this.Audio.duration;
};
/**
* Gets or set the muted setting for the song.
* @name IsMuted
* @function
* @param {Boolean|Undefined} mute - The mute property (true, false or undefined)
* @memberOf Song
*/
Song.prototype.IsMuted = function (mute) {
"use strict";
if (typeof mute === "undefined") {
return this.Audio.muted;
}
this.Audio.muted = mute;
};
/**
* Gets or set the loop setting for the song.
* @name IsRepeating
* @function
* @param {Boolean|Undefined} loop - The loop property (true, false or undefined)
* @memberOf Song
*/
Song.prototype.IsRepeating = function (loop) {
"use strict";
if (typeof loop === "undefined") {
return this.Audio.loop;
}
this.Audio.loop = loop;
};
/**
* Gets the play position within the currently playing song.
* @name PlayPosition
* @function
* @memberOf Song
*/
Song.prototype.PlayPosition = function () {
"use strict";
return this.Audio.currentTime;
};
/**
* Gets or sets the media player volume.
* @name Volume
* @function
* @param {Number} volume - The loop volume.
* @memberOf Song
*/
Song.prototype.Volume = function (volume) {
"use strict";
var self = this;
if (typeof volume === "undefined") {
return self.Audio.volume;
}
if (volume < 0) {
self.Audio.volume = 0;
} else if (volume > 1) {
self.Audio.volume = 1;
} else {
self.Audio.volume = volume;
}
};
/**
* Plays the Song.
* @name Play
* @function
* @memberOf Song
*/
Song.prototype.Play = function () {
"use strict";
this.Audio.play();
};
/**
* Pauses the Song.
* @name Pause
* @function
* @memberOf Song
*/
Song.prototype.Pause = function () {
"use strict";
this.Audio.pause();
};
/**
* Resumes the Song.
* @name Resume
* @function
* @memberOf Song
*/
Song.prototype.Resume = function () {
"use strict";
this.Audio.play();
};
/**
* Stops the Song.
* @name Stop
* @function
* @memberOf Song
*/
Song.prototype.Stop = function () {
"use strict";
this.Audio.pause();
this.Audio.currentTime = 0.0;
}; | gpl-2.0 |
asterics/KeyboardX | Player/Load/Element/KeyboardElement.cs | 1261 | using System;
namespace Player.Load.Element
{
/// <summary>
/// Base type for all elements of a keyboard.
/// </summary>
public interface KeyboardElement
{
/// <remarks>
/// There is a contract between the Loader and it's client. The Loader should only return valid keyboard models. Because validation of the
/// keyboard file via XSD is not powerful enough to detect all possible problems, this function is added to every keyboard element.
///
/// All in all there are 3 stages of validation:
/// 1. XSD validation
/// 2. validation checks while parsing
/// 3. validation checks on the keyboard elements (this function)
///
/// After the 3rd stage (i.e. calling this function on keyboard model) it should be guaranteed that a valid keyboard model was loaded.
///
/// If we have several grids in one keyboard and want to use lazy loading mechanism, the question is when a logical error in a grid should
/// be reported. Either on loading time of the keyboard file, in other words here at this function, or when the grid is really loaded.
/// </remarks>
void Validate();
}
}
| gpl-2.0 |
webeing/room012 | page-registrazione.php | 9226 | <?php
/*
* Template name: Registrazione
*/
get_header();?>
<?php if($_POST['r012_registration']):
$registration = r012_registration();
if( $registration ): ?>
<h3 class="alert alert-success"><?php _e('Benvenuto in ROOM 012!','r012');?></br>
<?php _e('Il tuo profilo sarà visibile non appena approvato dagli operatori.','r012');?></br>
<?php _e('Riceverai una mail di conferma appena approvato. ','r012'); ?></br>
<?php _e('A presto','r012'); ?>
</h3>
<?php
$post = get_post($registration);
echo '<h2 class="alignleft>'. $post->post_title .'</h2>';
if (has_post_thumbnail($registration))
the_post_thumbnail('thumbnail', array('class' => "alignleft"), $registration);
?>
<?php else: ?>
<h3 class="alert alert-error"><?php _e('Errori durante il processo, ripetere la procedura di iscrizione','r012') ?></h3>
<?php endif; ?>
<br class="clear"/>
<?php else: ?>
<form id="r012_register_form" name="r012_register_form" method="post" enctype="multipart/form-data" novalidate="novalidate" class="form-horizontal">
<fieldset>
<legend><h2>Guest book ROOM 012: Registrati</h2></legend>
<input id="r012_registration" name="r012_registration" value="1" type="hidden" />
<p class="control-group span5">
<label for="r012_nome_id"><?php _e("Nome", 'r012' ); ?> <small class="red">[*]</small></label>
<input type="text" name="r012_nome" id="r012_nome_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_cognome_id"><?php _e("Cognome", 'r012' ); ?> <small class="red">[*]</small></label>
<input type="text" name="r012_cognome" id="r012_cognome_id" value="" />
</p>
<p class="control-group span12">
<label for="r012_biografia_id"><?php _e("Breve biografia", 'r012' ); ?> <small>max 2000 caratteri</small></label>
<textarea id="r012_biografia_id" name="r012_biografia" rows="3"></textarea>
</p>
<p class="control-group span5">
<label for="r012_piva_id"><?php _e("P. IVA", 'r012' ); ?> </label>
<input type="text" name="r012_piva" id="r012_piva_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_titolo_id"><?php _e("Titolo professionale", 'r012' ); ?> <small class="red">[*]</small></label>
<?php
$r012_args = array(
'show_option_none' => 'Seleziona un titolo',
'order' => 'ASC',
'name' => 'r012_titolo',
'id' => 'r012_titolo_id',
'hide_empty' => 0,
'taxonomy' => 'categorie_professionisti'
);
wp_dropdown_categories( $r012_args ); ?>
</p>
<p class="control-group span5">
<label for="r012_ordine_id"><?php _e("Ordine iscrizione", 'r012' ); ?> </label>
<input type="text" name="r012_ordine" id="r012_ordine_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_numero_id"><?php _e("Numero iscrizione", 'r012' ); ?> </label>
<input type="text" name="r012_numero" id="r012_numero_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_nome_studio_id"><?php _e("Nome studio", 'r012' ); ?> </label>
<input type="text" name="r012_nome_studio" id="r012_nome_studio_id" value="" />
</p>
<p class="control-group span5">
<span><?php _e("Registra utente come studio", 'r012' ); ?></span>
<input value="1" type="checkbox" name="r012_studio" id="r012_studio_id"/>
</p>
<p class="control-group span5">
<label for="r012_posizione_id"><?php _e("Posizione", 'r012' ); ?> </label>
<input type="text" name="r012_posizione" id="r012_posizione_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_telefono_id"><?php _e("Telefono", 'r012' ); ?> </label>
<input type="text" name="r012_telefono" id="r012_telefono_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_mobile_id"><?php _e("Mobile", 'r012' ); ?></label>
<input type="text" name="r012_mobile" id="r012_mobile_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_fax_id"><?php _e("Fax", 'r012' ); ?> </label>
<input type="text" name="r012_fax" id="r012_fax_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_mail_id"><?php _e("Email", 'r012' ); ?> <small class="red">[*]</small></label>
<input type="email" name="r012_mail" id="r012_mail_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_sito_id"><?php _e("Sito web", 'r012' ); ?> </label>
<input type="text" name="r012_sito" id="r012_sito_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_citta_id"><?php _e("Città", 'r012' ); ?> </label>
<input type="text" name="r012_citta" id="r012_citta_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_citta_id"><?php _e("Via", 'r012' ); ?> </label>
<input type="text" name="r012_via" id="r012_via_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_cap_id"><?php _e("Cap", 'r012' ); ?> </label>
<input type="text" name="r012_cap" id="r012_cap_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_provincia_id"><?php _e("Provincia", 'r012' ); ?> </label>
<input type="text" name="r012_provincia" id="r012_provincia_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_immagine_id"><?php _e("Immagine", 'r012' ); ?> <small>risoluzione 72dpi 500px per 500px</small></label>
<input type="file" name="r012_immagine" id="r012_immagine_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_facebook_id"><?php _e("Account Facebook", 'r012' ); ?> </label>
<input type="text" name="r012_facebook" id="r012_facebook_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_twitter_id"><?php _e("Account Twitter", 'r012' ); ?> </label>
<input type="text" name="r012_twitter" id="r012_twitter_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_skype_id"><?php _e("Account Skype", 'r012' ); ?> </label>
<input type="text" name="r012_skype" id="r012_skype_id" value="" />
</p>
<p class="control-group span5">
<label for="r012_linkedin_id"><?php _e("Account Linkedin", 'r012' ); ?> </label>
<input type="text" name="r012_linkedin" id="r012_linkedin_id" value="" />
</p>
<p class="control-group span5">
<span><a href="<?php echo get_permalink(R012_ID_PAGE_TERMINI_CONDIZIONI); ?>" target="_blank">Accetta termini e condizioni</a> <small class="red">[*]</small></span>
<input name="r012_licenza" id="r012_licenza" class="text" value="" type="checkbox"/>
</p>
<p class="control-group span9 p-captcha">
<label>Codice di sicurezza:</label>
<?php echo recaptcha_get_html(R012_CAPTCHA_PUBKEY, ""); ?>
<input id="r012_remote_addr" name="r012_remote_addr" type="hidden" value="<?php echo $_SERVER['REMOTE_ADDR'] ?>"/>
</p>
</fieldset>
<?php/* echo do_shortcode('[fu-upload-form title="Upload your Photos"]
[input type="text" name="name" id="ug_name" description="Your name"]
[input type="file" name="photo" id="ug_photo" description="Your Photo"]
[input type="submit" value="Submit"] [/fu-upload-form]') */ ?>
<p><input id="registerbtn" name="r012_registrazione" value="<?php _e('Registrati', 'r012') ;?>" type="button" class="btn" /></p>
<div class="alert span9">
<button type="button" class="close" data-dismiss="alert">×</button>
<small>I campi contrassegnati con [*] sono obbligatori</small>
<div id="result_register"></div>
</div>
<div class="clear"></div>
</form>
<?php endif; ?>
<?php get_footer();?> | gpl-2.0 |
imageboards/Orphereus | Orphereus/lib/interfaces/AbstractSearchModule.py | 114 | class AbstractSearchModule(object):
def search(self, filteringClause, text, page, postsPerPage):
pass
| gpl-2.0 |
as-ideas/crowdsource | crowdsource-frontend/local_modules/angular-translate-extract/src/adapter/pot-adapter.js | 1460 | import fs from 'fs'
import path from 'path'
import Po from 'pofile'
import _ from 'lodash'
export class PotObject {
constructor(id, msg = '', ctx = '') {
this.id = id
this.msg = msg
this.ctx = ctx
}
toString() {
return `msgctxt "${PotObject.escapeString(this.ctx)}"
msgid "${PotObject.escapeString(this.id)}"
msgstr "${PotObject.escapeString(this.msg)}"`
}
}
PotObject.escapeString = (str) => (""+str).replace(/"/g, '\\"')
export class PotAdapter {
constructor(log, basePath) {
this.log = log
this.basePath = basePath
this.params = {
dest: '.',
prefix: '',
suffix: '.pot'
}
}
init(params) {
this.params = _.defaults(params, this.params)
try {
this.log.debug('Init PodAdapter', this.params.dest, this.params.prefix, this.params.suffix)
} catch(e) {}
}
persist(translations) {
var catalog = new Po()
catalog.headers = {
'Content-Type': 'text/plain; charset=UTF-8',
'Content-Transfer-Encoding': '8bit',
'Project-Id-Version': ''
}
_.forEach(translations.getFlatTranslations(), (value, msg) => {
catalog.items.push(new PotObject(msg, value))
})
catalog.items.sort(function(a, b) {
return a.id.toLowerCase().localeCompare(b.id.toLowerCase())
})
var fullPath = path.resolve(this.basePath, this.params.dest, this.params.prefix + this.params.suffix)
fs.writeFileSync(fullPath, catalog.toString())
}
} | gpl-2.0 |
rjbaniel/upoor | wp-content/themes/MyProduct/searchform.php | 322 | <form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>/">
<div>
<input type="text" value="<?php echo esc_attr( get_search_query() ); ?>" name="s" id="s" />
<input type="submit" id="searchsubmit" value="<?php esc_attr_e('Search','MyProduct'); ?>" />
</div>
</form> | gpl-2.0 |
supertigerzou/taskManager | src/app/js/services.js | 351 | 'use strict';
/* Services */
var taskManagerServices = angular.module('taskManagerServices', ['ngResource']);
taskManagerServices.factory('Task', ['$resource',
function($resource){
return $resource('https://jira.englishtown.com/rest/api/2/issue/:taskId', {}, {
query: {method:'GET', url:'tasks/tasks.json', isArray:true}
});
}]);
| gpl-2.0 |
ufal/lindat-kontext | public/files/js/models/concordance/detail.ts | 34010 | /*
* Copyright (c) 2016 Charles University in Prague, Faculty of Arts,
* Institute of the Czech National Corpus
* Copyright (c) 2016 Tomas Machalek <tomas.machalek@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* dated June, 1991.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import {MultiDict, importColor} from '../../util';
import {Kontext} from '../../types/common';
import {PluginInterfaces} from '../../types/plugins';
import {AjaxResponse} from '../../types/ajaxResponses';
import {StatefulModel} from '../base';
import {PageModel} from '../../app/main';
import {ConcLineModel} from './lines';
import {AudioPlayer} from './media';
import * as Immutable from 'immutable';
import { Action, IFullActionControl } from 'kombo';
import { Observable, of as rxOf, forkJoin } from 'rxjs';
import { tap, map } from 'rxjs/operators';
/**
*
*/
export type ConcDetailText = Array<{str:string; class:string}>;
/**
*
*/
export interface Speech {
text:ConcDetailText;
speakerId:string;
segments:Immutable.List<string>;
colorCode:Kontext.RGBAColor;
metadata:Immutable.Map<string, string>;
}
/**
* Note: A single speech line contains an array of
* simultaneous speeches (i.e. if two people speak
* at the same time then the array contains two items).
*/
export type SpeechLine = Array<Speech>;
export type SpeechLines = Array<SpeechLine>;
type ExpandArgs = [number, number];
export interface SpeechOptions {
speakerIdAttr:[string, string];
speechSegment:[string, string];
speechAttrs:Array<string>;
speechOverlapAttr:[string, string];
speechOverlapVal:string;
}
/**
* A model providing access to a detailed/extended kwic information.
*/
export class ConcDetailModel extends StatefulModel {
private static SPK_LABEL_OPACITY:number = 0.8;
private static ATTR_NAME_ALLOWED_CHARS:string = 'a-zA-Z0-9_';
private static SPK_OVERLAP_MODE_FULL:string = 'full';
private static SPK_OVERLAP_MODE_SIMPLE:string = 'simple';
private layoutModel:PageModel;
private linesModel:ConcLineModel;
private concDetail:ConcDetailText;
private expandLeftArgs:Immutable.List<ExpandArgs>;
private expandRightArgs:Immutable.List<ExpandArgs>;
private corpusId:string;
private kwicTokenNum:number;
private tokenConnectData:PluginInterfaces.TokenConnect.TCData;
private kwicLength:number;
private lineIdx:number;
private wholeDocumentLoaded:boolean;
private structCtx:string;
private speechOpts:SpeechOptions;
private speechAttrs:Array<string>;
private audioPlayer:AudioPlayer;
private playingRowIdx:number;
private speakerColors:Immutable.List<Kontext.RGBAColor>;
private wideCtxGlobals:Array<[string, string]>;
private spkOverlapMode:string;
/**
* Either 'default' or 'speech'.
* An initial mode is inferred from speechOpts
* (see constructor).
*/
private mode:string;
/**
* Speaker colors attachments must survive context expansion.
* Otherwise it would confusing if e.g. green speaker '01'
* changed into red one after a context expasion due to
* some new incoming or outcoming users.
*/
private speakerColorsAttachments:Immutable.Map<string, Kontext.RGBAColor>;
private isBusy:boolean;
private tokenConnectIsBusy:boolean;
/**
* Currently expanded side. In case the model is not busy the
* value represent last expanded side (it is not reset after expansion).
* Values: 'left', 'right'
*/
private expaningSide:string;
private tokenConnectPlg:PluginInterfaces.TokenConnect.IPlugin;
constructor(layoutModel:PageModel, dispatcher:IFullActionControl, linesModel:ConcLineModel, structCtx:string,
speechOpts:SpeechOptions, speakerColors:Array<string>, wideCtxGlobals:Array<[string, string]>,
tokenConnectPlg:PluginInterfaces.TokenConnect.IPlugin) {
super(dispatcher);
this.layoutModel = layoutModel;
this.linesModel = linesModel;
this.structCtx = structCtx;
this.speechOpts = speechOpts;
this.mode = this.speechOpts.speakerIdAttr ? 'speech' : 'default';
this.speechAttrs = speechOpts.speechAttrs;
this.wideCtxGlobals = wideCtxGlobals;
this.lineIdx = null;
this.playingRowIdx = -1;
this.wholeDocumentLoaded = false;
this.speakerColors = Immutable.List<Kontext.RGBAColor>(speakerColors.map(item => importColor(item, ConcDetailModel.SPK_LABEL_OPACITY)));
this.speakerColorsAttachments = Immutable.Map<string, Kontext.RGBAColor>();
this.spkOverlapMode = (speechOpts.speechOverlapAttr || [])[1] ?
ConcDetailModel.SPK_OVERLAP_MODE_FULL : ConcDetailModel.SPK_OVERLAP_MODE_SIMPLE;
this.expandLeftArgs = Immutable.List<ExpandArgs>();
this.expandRightArgs = Immutable.List<ExpandArgs>();
this.tokenConnectPlg = tokenConnectPlg;
this.tokenConnectData = {
token: null,
renders: Immutable.List<PluginInterfaces.TokenConnect.DataAndRenderer>()
};
this.concDetail = null;
this.audioPlayer = new AudioPlayer(
this.layoutModel.createStaticUrl('misc/soundmanager2/'),
() => {
this.emitChange();
},
() => {
this.playingRowIdx = -1;
this.emitChange();
},
() => {
this.playingRowIdx = -1;
this.audioPlayer.stop();
this.emitChange();
this.layoutModel.showMessage('error',
this.layoutModel.translate('concview__failed_to_play_audio'));
}
);
this.isBusy = false;
this.tokenConnectIsBusy = false;
this.dispatcher.registerActionListener((action:Action) => {
switch (action.name) {
case 'CONCORDANCE_EXPAND_KWIC_DETAIL':
this.expaningSide = action.payload['position'];
this.isBusy = true;
this.emitChange();
this.loadConcDetail(
this.corpusId,
this.kwicTokenNum,
this.kwicLength,
this.lineIdx,
[],
action.payload['position']
).subscribe(
() => {
this.isBusy = false;
this.linesModel.setLineFocus(this.lineIdx, true);
this.linesModel.emitChange();
this.emitChange();
},
(err) => {
this.isBusy = false;
this.emitChange();
this.layoutModel.showMessage('error', err);
}
);
break;
case 'CONCORDANCE_SHOW_KWIC_DETAIL':
this.isBusy = true;
this.tokenConnectIsBusy = true;
this.expandLeftArgs = Immutable.List<ExpandArgs>();
this.expandRightArgs = Immutable.List<ExpandArgs>();
forkJoin(
this.loadConcDetail(
action.payload['corpusId'],
action.payload['tokenNumber'],
action.payload['kwicLength'],
action.payload['lineIdx'],
[],
this.expandLeftArgs.size > 1 && this.expandRightArgs.size > 1 ? 'reload' : null
),
this.loadTokenConnect(
action.payload['corpusId'],
action.payload['tokenNumber'],
action.payload['kwicLength'],
action.payload['lineIdx']
)
).subscribe(
() => {
this.isBusy = false;
this.tokenConnectIsBusy = false;
this.linesModel.setLineFocus(action.payload['lineIdx'], true);
this.linesModel.emitChange();
this.emitChange();
},
(err) => {
this.isBusy = false;
this.tokenConnectIsBusy = false;
this.emitChange();
this.layoutModel.showMessage('error', err);
}
);
break;
case 'CONCORDANCE_SHOW_TOKEN_DETAIL':
this.resetKwicDetail();
this.resetTokenConnect();
this.tokenConnectIsBusy = true;
this.emitChange();
this.loadTokenConnect(
action.payload['corpusId'],
action.payload['tokenNumber'],
1,
action.payload['lineIdx']
).subscribe(
() => {
this.tokenConnectIsBusy = false;
this.emitChange();
},
(err) => {
this.emitChange();
this.tokenConnectIsBusy = false;
this.layoutModel.showMessage('error', err);
}
);
break;
case 'CONCORDANCE_SHOW_WHOLE_DOCUMENT':
this.loadWholeDocument().subscribe(
() => {
this.emitChange();
},
(err) => {
this.layoutModel.showMessage('error', err);
}
);
break;
case 'CONCORDANCE_SHOW_SPEECH_DETAIL':
this.mode = 'speech';
this.expandLeftArgs = Immutable.List<ExpandArgs>();
this.expandRightArgs = Immutable.List<ExpandArgs>();
this.speakerColorsAttachments = this.speakerColorsAttachments.clear();
this.isBusy = true;
this.emitChange();
this.loadSpeechDetail(
action.payload['corpusId'],
action.payload['tokenNumber'],
action.payload['kwicLength'],
action.payload['lineIdx'],
this.expandLeftArgs.size > 1 && this.expandRightArgs.size > 1 ? 'reload' : null).subscribe(
() => {
this.isBusy = false;
this.linesModel.setLineFocus(action.payload['lineIdx'], true);
this.linesModel.emitChange();
this.emitChange();
},
(err) => {
this.isBusy = false;
this.emitChange();
this.layoutModel.showMessage('error', err);
}
);
break;
case 'CONCORDANCE_EXPAND_SPEECH_DETAIL':
this.expaningSide = action.payload['position'];
this.isBusy = true;
this.emitChange();
this.loadSpeechDetail(
this.corpusId,
this.kwicTokenNum,
this.kwicLength,
this.lineIdx,
action.payload['position']).subscribe(
() => {
this.isBusy = false;
this.linesModel.setLineFocus(this.lineIdx, true);
this.linesModel.emitChange();
this.emitChange();
},
(err) => {
this.isBusy = false;
this.layoutModel.showMessage('error', err);
}
);
break;
case 'CONCORDANCE_DETAIL_SWITCH_MODE':
(() => {
if (action.payload['value'] === 'default') {
this.mode = 'default';
this.expandLeftArgs = Immutable.List<ExpandArgs>();
this.expandRightArgs = Immutable.List<ExpandArgs>();
this.expaningSide = null;
this.concDetail = null;
this.isBusy = true;
this.emitChange();
return this.reloadConcDetail();
} else if (action.payload['value'] === 'speech') {
this.mode = 'speech';
this.expandLeftArgs = Immutable.List<ExpandArgs>();
this.expandRightArgs = Immutable.List<ExpandArgs>();
this.speakerColorsAttachments = this.speakerColorsAttachments.clear();
this.expaningSide = null;
this.concDetail = null;
this.isBusy = true;
this.emitChange();
return this.reloadSpeechDetail();
} else {
this.mode = action.payload['value'];
this.expandLeftArgs = Immutable.List<ExpandArgs>();
this.expandRightArgs = Immutable.List<ExpandArgs>();
this.expaningSide = null;
this.concDetail = null;
this.isBusy = true;
this.emitChange();
return rxOf(null);
}
})().subscribe(
() => {
this.isBusy = false;
this.emitChange();
},
(err) => {
this.isBusy = false;
this.layoutModel.showMessage('error', err);
this.emitChange();
}
);
break;
case 'CONCORDANCE_RESET_DETAIL':
case 'CONCORDANCE_SHOW_REF_DETAIL':
this.resetKwicDetail();
this.resetTokenConnect();
this.emitChange();
this.linesModel.emitChange();
break;
case 'CONCORDANCE_PLAY_SPEECH':
if (this.playingRowIdx > -1) {
this.playingRowIdx = null;
this.audioPlayer.stop();
this.emitChange();
}
this.playingRowIdx = action.payload['rowIdx'];
const itemsToPlay = (<Immutable.List<string>>action.payload['segments']).map(item => {
return this.layoutModel.createActionUrl(`audio?corpname=${this.corpusId}&chunk=${item}`);
}).toArray();
if (itemsToPlay.length > 0) {
this.audioPlayer.start(itemsToPlay);
} else {
this.playingRowIdx = -1;
this.layoutModel.showMessage('error', this.layoutModel.translate('concview__nothing_to_play'));
this.emitChange();
}
break;
case 'CONCORDANCE_STOP_SPEECH':
if (this.playingRowIdx > -1) {
this.playingRowIdx = null;
this.audioPlayer.stop();
this.emitChange();
}
break;
}
});
}
private resetKwicDetail():void {
if (this.lineIdx !== null) {
this.linesModel.setLineFocus(this.lineIdx, false);
this.lineIdx = null;
this.corpusId = null;
this.kwicTokenNum = null;
this.kwicLength = null;
this.wholeDocumentLoaded = false;
this.expandLeftArgs = this.expandLeftArgs.clear();
this.expandRightArgs = this.expandRightArgs.clear();
this.speakerColorsAttachments = this.speakerColorsAttachments.clear();
this.concDetail = null;
}
}
private resetTokenConnect():void {
this.tokenConnectData = {
token: null,
renders: this.tokenConnectData.renders.clear()
};
}
getPlayingRowIdx():number {
return this.playingRowIdx;
}
getConcDetail():ConcDetailText {
return this.concDetail;
}
hasConcDetailData():boolean {
return this.concDetail !== null;
}
getSpeechesDetail():SpeechLines {
let spkId = null;
const parseTag = (name:string, s:string):{[key:string]:string} => {
const srch = new RegExp(`<${name}(\\s+[^>]+)>`).exec(s);
if (srch) {
const ans:{[key:string]:string} = {};
const items = srch[1].trim()
.split(new RegExp(`([${ConcDetailModel.ATTR_NAME_ALLOWED_CHARS}]+)=`)).slice(1);
for (let i = 0; i < items.length; i += 2) {
ans[items[i]] = (items[i+1] || '').trim();
}
return ans;
}
return null;
};
const createNewSpeech = (speakerId:string, colorCode:Kontext.RGBAColor, metadata:{[attr:string]:string}):Speech => {
const importedMetadata = Immutable.Map<string, string>(metadata)
.filter((val, attr) => attr !== this.speechOpts.speechSegment[1] &&
attr !== this.speechOpts.speakerIdAttr[1])
.toMap();
return {
text: [],
speakerId: speakerId,
segments: Immutable.List<string>(),
metadata: importedMetadata,
colorCode: colorCode
};
};
const isOverlap = (s1:Speech, s2:Speech):boolean => {
if (s1 && s2 && this.spkOverlapMode === ConcDetailModel.SPK_OVERLAP_MODE_FULL) {
const flag1 = s1.metadata.get(this.speechOpts.speechOverlapAttr[1]);
const flag2 = s2.metadata.get(this.speechOpts.speechOverlapAttr[1]);
if (flag1 === flag2
&& flag2 === this.speechOpts.speechOverlapVal
&& s1.segments.get(0) === s2.segments.get(0)) {
return true;
}
}
return false;
};
const mergeOverlaps = (speeches:Array<Speech>):SpeechLines => {
const ans:SpeechLines = [];
let prevSpeech:Speech = null;
speeches.forEach((item, i) => {
if (isOverlap(prevSpeech, item)) {
ans[ans.length - 1].push(item);
ans[ans.length - 1] = ans[ans.length - 1].sort((s1, s2) => {
if (s1.speakerId > s2.speakerId) {
return 1;
} else if (s1.speakerId < s2.speakerId) {
return -1;
} else {
return 0;
}
});
} else {
ans.push([item]);
}
prevSpeech = item;
});
return ans;
};
let currSpeech:Speech = createNewSpeech('\u2026', null, {});
let prevSpeech:Speech = null;
const tmp:Array<Speech> = [];
(this.concDetail || []).forEach((item, i) => {
if (item.class === 'strc') {
const attrs = parseTag(this.speechOpts.speakerIdAttr[0], item.str);
if (attrs !== null && attrs[this.speechOpts.speakerIdAttr[1]]) {
tmp.push(currSpeech);
const newSpeakerId = attrs[this.speechOpts.speakerIdAttr[1]];
if (!this.speakerColorsAttachments.has(newSpeakerId)) {
this.speakerColorsAttachments = this.speakerColorsAttachments.set(
newSpeakerId, this.speakerColors.get(this.speakerColorsAttachments.size)
)
}
prevSpeech = currSpeech;
currSpeech = createNewSpeech(
newSpeakerId,
this.speakerColorsAttachments.get(newSpeakerId),
attrs
);
}
if (item.str.indexOf(`<${this.speechOpts.speechSegment[0]}`) > -1) {
const attrs = parseTag(this.speechOpts.speechSegment[0], item.str);
if (attrs) {
currSpeech.segments = currSpeech.segments.push(attrs[this.speechOpts.speechSegment[1]]);
}
}
if (this.spkOverlapMode === ConcDetailModel.SPK_OVERLAP_MODE_SIMPLE) {
const overlapSrch = new RegExp(`</?(${this.speechOpts.speechOverlapAttr[0]})(>|[^>]+>)`, 'g');
let srch;
let i = 0;
while ((srch = overlapSrch.exec(item.str)) !== null) {
if (srch[0].indexOf('</') === 0
&& item.str.indexOf(`<${this.speechOpts.speakerIdAttr[0]}`) > 0) {
prevSpeech.text.push({str: srch[0], class: item.class});
} else {
currSpeech.text.push({str: srch[0], class: item.class});
}
i += 1;
}
}
} else {
currSpeech.text.push({
str: item.str,
class: item.class
});
}
});
if (currSpeech.text.length > 0) {
tmp.push(currSpeech);
}
return mergeOverlaps(tmp);
}
setWideCtxGlobals(data:Array<[string, string]>):void {
this.wideCtxGlobals = data;
}
/**
*
*/
private loadWholeDocument():Observable<any> {
return this.layoutModel.ajax$<AjaxResponse.WideCtx>(
'GET',
this.layoutModel.createActionUrl('structctx'),
{
corpname: this.corpusId,
pos: this.kwicTokenNum,
struct: this.structCtx
},
{}
).pipe(
tap(
(data) => {
this.concDetail = data.content;
this.wholeDocumentLoaded = true;
this.expandLeftArgs = Immutable.List<ExpandArgs>();
this.expandRightArgs = Immutable.List<ExpandArgs>();
}
)
);
}
/**
*
*/
private loadSpeechDetail(corpusId:string, tokenNum:number, kwicLength:number, lineIdx:number, expand?:string):Observable<boolean> {
const structs = this.layoutModel.getConcArgs().getList('structs');
const args = this.speechAttrs
.map(x => `${this.speechOpts.speakerIdAttr[0]}.${x}`)
.concat([this.speechOpts.speechSegment.join('.')]);
const [overlapStruct, overlapAttr] = (this.speechOpts.speechOverlapAttr || [undefined, undefined]);
if (overlapStruct !== this.speechOpts.speakerIdAttr[0]
&& structs.indexOf(overlapStruct) === -1) {
if (overlapStruct && overlapAttr) {
args.push(`${overlapStruct}.${overlapAttr}`);
} else if (overlapStruct) {
args.push(overlapStruct);
}
}
return this.loadConcDetail(corpusId, tokenNum, kwicLength, lineIdx, args, expand);
}
private reloadSpeechDetail():Observable<boolean> {
return this.loadSpeechDetail(this.corpusId, this.kwicTokenNum, this.kwicLength, this.lineIdx);
}
private loadTokenConnect(corpusId:string, tokenNum:number, numTokens:number, lineIdx:number):Observable<boolean> {
return (() => {
if (this.tokenConnectPlg) {
return this.tokenConnectPlg.fetchTokenConnect(corpusId, tokenNum, numTokens);
} else {
return rxOf<PluginInterfaces.TokenConnect.TCData>(null);
}
})().pipe(
tap(
(data) => {
if (data) {
this.tokenConnectData = {
token: data.token,
renders: data.renders
};
this.lineIdx = lineIdx;
}
}
),
map(
(data) => data ? true : false
)
);
}
/**
*
*/
private loadConcDetail(corpusId:string, tokenNum:number, kwicLength:number, lineIdx:number, structs:Array<string>,
expand?:string):Observable<boolean> {
this.corpusId = corpusId;
this.kwicTokenNum = tokenNum;
this.kwicLength = kwicLength;
this.lineIdx = lineIdx;
this.wholeDocumentLoaded = false;
const args = new MultiDict(this.wideCtxGlobals);
args.set('corpname', corpusId); // just for sure (is should be already in args)
// we must delete 'usesubcorp' as the server API does not need it
// and in case of an aligned corpus it even produces an error
args.remove('usesubcorp');
args.set('pos', String(tokenNum));
args.set('format', 'json');
if (this.kwicLength && this.kwicLength > 1) {
args.set('hitlen', this.kwicLength);
}
if (structs) {
args.set('structs', (args.getFirst('structs') || '').split(',').concat(structs).join(','));
}
if (expand === 'left') {
args.set('detail_left_ctx', String(this.expandLeftArgs.get(-1)[0]));
args.set('detail_right_ctx', String(this.expandLeftArgs.get(-1)[1]));
} else if (expand === 'right') {
args.set('detail_left_ctx', String(this.expandRightArgs.get(-1)[0]));
args.set('detail_right_ctx', String(this.expandRightArgs.get(-1)[1]));
} else if (expand === 'reload' && this.expandLeftArgs.size > 1
&& this.expandRightArgs.size > 1) {
// Please note that the following lines do not contain any 'left - right'
// mismatch as we have to fetch the 'current' state, not the 'next' one and such
// info is always on the other side of expansion (expand-left contains
// also current right and vice versa)
args.set('detail_left_ctx', String(this.expandRightArgs.get(-1)[0]));
args.set('detail_right_ctx', String(this.expandLeftArgs.get(-1)[1]));
}
this.isBusy = true;
this.emitChange();
return this.layoutModel.ajax$<AjaxResponse.WideCtx>(
'GET',
this.layoutModel.createActionUrl('widectx'),
args,
{}
).pipe(
tap(
(data) => {
this.concDetail = data.content;
if (data.expand_left_args) {
this.expandLeftArgs = this.expandLeftArgs.push([
data.expand_left_args.detail_left_ctx, data.expand_left_args.detail_right_ctx
]);
} else {
this.expandLeftArgs = this.expandLeftArgs.push(null);
}
if (data.expand_right_args) {
this.expandRightArgs = this.expandRightArgs.push([
data.expand_right_args.detail_left_ctx, data.expand_right_args.detail_right_ctx
]);
} else {
this.expandRightArgs = this.expandRightArgs.push(null);
}
}
),
map(d => !!d)
);
}
private reloadConcDetail():Observable<boolean> {
return this.loadConcDetail(this.corpusId, this.kwicTokenNum, this.kwicLength, this.lineIdx, [], 'reload');
}
hasExpandLeft():boolean {
return !!this.expandLeftArgs.get(-1);
}
hasExpandRight():boolean {
return !!this.expandRightArgs.get(-1);
}
canDisplayWholeDocument():boolean {
return this.structCtx && !this.wholeDocumentLoaded;
}
getViewMode():string {
return this.mode;
}
getTokenConnectData():PluginInterfaces.TokenConnect.TCData {
return this.tokenConnectData;
}
hasTokenConnectData():boolean {
return this.tokenConnectData.renders.size > 0;
}
getIsBusy():boolean {
return this.isBusy;
}
getTokenConnectIsBusy():boolean {
return this.tokenConnectIsBusy;
}
getExpaningSide():string {
return this.expaningSide;
}
supportsTokenConnect():boolean {
return this.tokenConnectPlg ? this.tokenConnectPlg.providesAnyTokenInfo() : false;
}
supportsSpeechView():boolean {
return !!this.speechOpts.speakerIdAttr;
}
}
export interface RefsColumn {
name:string;
val:string;
}
/**
* Model providing structural attribute information (aka "text types") related to a specific token
*/
export class RefsDetailModel extends StatefulModel {
private layoutModel:PageModel;
private data:Immutable.List<RefsColumn>;
private linesModel:ConcLineModel;
private lineIdx:number;
private isBusy:boolean;
constructor(layoutModel:PageModel, dispatcher:IFullActionControl, linesModel:ConcLineModel) {
super(dispatcher);
this.layoutModel = layoutModel;
this.linesModel = linesModel;
this.lineIdx = null;
this.data = Immutable.List<RefsColumn>();
this.isBusy = false;
this.dispatcher.registerActionListener((action:Action) => {
switch (action.name) {
case 'CONCORDANCE_SHOW_REF_DETAIL':
this.isBusy = true;
this.emitChange();
this.loadRefs(action.payload['corpusId'], action.payload['tokenNumber'], action.payload['lineIdx']).subscribe(
() => {
this.linesModel.setLineFocus(action.payload['lineIdx'], true);
this.linesModel.emitChange();
this.isBusy = false;
this.emitChange();
},
(err) => {
this.layoutModel.showMessage('error', err);
this.isBusy = false;
this.emitChange();
}
);
break;
case 'CONCORDANCE_REF_RESET_DETAIL':
case 'CONCORDANCE_SHOW_SPEECH_DETAIL':
case 'CONCORDANCE_SHOW_KWIC_DETAIL':
case 'CONCORDANCE_SHOW_TOKEN_DETAIL':
if (this.lineIdx !== null) {
this.linesModel.setLineFocus(this.lineIdx, false);
this.lineIdx = null;
this.emitChange();
this.linesModel.emitChange();
}
break;
}
});
}
getData():Immutable.List<[RefsColumn, RefsColumn]> {
if (this.lineIdx !== null) {
const ans:Array<[RefsColumn, RefsColumn]> = [];
for (let i = 0; i < this.data.size; i += 2) {
ans.push([this.data.get(i), this.data.get(i+1)]);
}
return Immutable.List<[RefsColumn, RefsColumn]>(ans);
} else if (this.isBusy) {
return Immutable.List<[RefsColumn, RefsColumn]>();
} else {
return null;
}
}
private loadRefs(corpusId:string, tokenNum:number, lineIdx:number):Observable<boolean> {
return this.layoutModel.ajax$<AjaxResponse.FullRef>(
'GET',
this.layoutModel.createActionUrl('fullref'),
{corpname: corpusId, pos: tokenNum}
).pipe(
tap(
(data) => {
this.lineIdx = lineIdx;
this.data = Immutable.List<RefsColumn>(data.Refs);
}
),
map(data => !!data)
);
}
getIsBusy():boolean {
return this.isBusy;
}
}
| gpl-2.0 |
opusappteam/PLGLPI0842 | inc/ticket.class.php | 243478 | <?php
/*
* @version $Id: ticket.class.php 21575 2013-08-27 09:22:50Z moyo $
-------------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2003-2013 by the INDEPNET Development Team.
http://indepnet.net/ http://glpi-project.org
-------------------------------------------------------------------------
LICENSE
This file is part of GLPI.
GLPI is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/// Tracking class
class Ticket extends CommonITILObject {
// From CommonDBTM
public $dohistory = true;
static protected $forward_entity_to = array('TicketValidation', 'TicketCost');
// From CommonITIL
public $userlinkclass = 'Ticket_User';
public $grouplinkclass = 'Group_Ticket';
public $supplierlinkclass = 'Supplier_Ticket';
protected $userentity_oncreate = true;
const MATRIX_FIELD = 'priority_matrix';
const URGENCY_MASK_FIELD = 'urgency_mask';
const IMPACT_MASK_FIELD = 'impact_mask';
const STATUS_MATRIX_FIELD = 'ticket_status';
// HELPDESK LINK HARDWARE DEFINITION : CHECKSUM SYSTEM : BOTH=1*2^0+1*2^1=3
const HELPDESK_MY_HARDWARE = 0;
const HELPDESK_ALL_HARDWARE = 1;
// Specific ones
/// Hardware datas used by getFromDBwithData
var $hardwaredatas = NULL;
/// Is a hardware found in getHardwareData / getFromDBwithData : hardware link to the job
var $computerfound = 0;
// Request type
const INCIDENT_TYPE = 1;
// Demand type
const DEMAND_TYPE = 2;
function getForbiddenStandardMassiveAction() {
$forbidden = parent::getForbiddenStandardMassiveAction();
if (!Session::haveRight('update_ticket', 1)) {
$forbidden[] = 'update';
}
if (!Session::haveRight('delete_ticket', 1)) {
$forbidden[] = 'delete';
$forbidden[] = 'purge';
$forbidden[] = 'restore';
}
return $forbidden;
}
/**
* Name of the type
*
* @param $nb : number of item in the type (default 0)
**/
static function getTypeName($nb=0) {
return _n('Ticket','Tickets',$nb);
}
function canAdminActors() {
return Session::haveRight('update_ticket', 1);
}
function canAssign() {
return Session::haveRight('assign_ticket', 1);
}
function canAssignToMe() {
return (Session::haveRight("steal_ticket","1")
|| (Session::haveRight("own_ticket","1")
&& ($this->countUsers(CommonITILActor::ASSIGN) == 0)));
}
static function canCreate() {
return Session::haveRight('create_ticket', 1);
}
static function canUpdate() {
return (Session::haveRight('update_ticket', 1)
|| Session::haveRight('create_ticket', 1)
|| Session::haveRight('assign_ticket', 1)
|| Session::haveRight('own_ticket', 1)
|| Session::haveRight('steal_ticket', 1));
}
static function canView() {
if (isset($_SESSION['glpiactiveprofile']['interface'])
&& $_SESSION['glpiactiveprofile']['interface'] == 'helpdesk') {
return true;
}
return (Session::haveRight("show_all_ticket","1")
|| Session::haveRight('create_ticket','1')
|| Session::haveRight('update_ticket','1')
|| Session::haveRight('show_all_ticket','1')
|| Session::haveRight("show_assign_ticket",'1')
|| Session::haveRight("own_ticket",'1')
|| Session::haveRight('validate_request','1')
|| Session::haveRight('validate_incident','1')
|| Session::haveRight("show_group_ticket",'1'));
}
/**
* Is the current user have right to show the current ticket ?
*
* @return boolean
**/
function canViewItem() {
if (!Session::haveAccessToEntity($this->getEntityID())) {
return false;
}
return (Session::haveRight("show_all_ticket","1")
|| ($this->fields["users_id_recipient"] === Session::getLoginUserID())
|| $this->isUser(CommonITILActor::REQUESTER, Session::getLoginUserID())
|| $this->isUser(CommonITILActor::OBSERVER, Session::getLoginUserID())
|| (Session::haveRight("show_group_ticket",'1')
&& isset($_SESSION["glpigroups"])
&& ($this->haveAGroup(CommonITILActor::REQUESTER, $_SESSION["glpigroups"])
|| $this->haveAGroup(CommonITILActor::OBSERVER, $_SESSION["glpigroups"])))
|| (Session::haveRight("show_assign_ticket",'1')
&& ($this->isUser(CommonITILActor::ASSIGN, Session::getLoginUserID())
|| (isset($_SESSION["glpigroups"])
&& $this->haveAGroup(CommonITILActor::ASSIGN, $_SESSION["glpigroups"]))
|| (Session::haveRight('assign_ticket',1)
&& ($this->fields["status"] == self::INCOMING))))
|| ((Session::haveRight('validate_incident','1')
|| Session::haveRight('validate_request','1'))
&& TicketValidation::canValidate($this->fields["id"])));
}
/**
* Is the current user have right to solve the current ticket ?
*
* @return boolean
**/
function canSolve() {
return ((Session::haveRight("update_ticket","1")
|| $this->isUser(CommonITILActor::ASSIGN, Session::getLoginUserID())
|| (isset($_SESSION["glpigroups"])
&& $this->haveAGroup(CommonITILActor::ASSIGN, $_SESSION["glpigroups"])))
&& self::isAllowedStatus($this->fields['status'], self::SOLVED)
// No edition on closed status
&& !in_array($this->fields['status'], $this->getClosedStatusArray()));
}
/**
* Is the current user have right to approve solution of the current ticket ?
*
* @return boolean
**/
function canApprove() {
return (($this->fields["users_id_recipient"] === Session::getLoginUserID())
|| $this->isUser(CommonITILActor::REQUESTER, Session::getLoginUserID())
|| (isset($_SESSION["glpigroups"])
&& $this->haveAGroup(CommonITILActor::REQUESTER, $_SESSION["glpigroups"])));
}
/**
* @see CommonDBTM::canMassiveAction()
**/
function canMassiveAction($action, $field, $value) {
switch ($action) {
case 'update' :
switch ($field) {
case 'status' :
if (!self::isAllowedStatus($this->fields['status'], $value)) {
return false;
}
break;
}
break;
}
return true;
}
/**
* Get Datas to be added for SLA add
*
* @param $slas_id SLA id
* @param $entities_id entity ID of the ticket
* @param $date begin date of the ticket
*
* @return array of datas to add in ticket
**/
function getDatasToAddSLA($slas_id, $entities_id, $date) {
$calendars_id = Entity::getUsedConfig('calendars_id', $entities_id);
$data = array();
$sla = new SLA();
if ($sla->getFromDB($slas_id)) {
$sla->setTicketCalendar($calendars_id);
// Get first SLA Level
$data["slalevels_id"] = SlaLevel::getFirstSlaLevel($slas_id);
// Compute due_date
$data['due_date'] = $sla->computeDueDate($date);
$data['sla_waiting_duration'] = 0;
} else {
$data["slalevels_id"] = 0;
$data["slas_id"] = 0;
$data['sla_waiting_duration'] = 0;
}
return $data;
}
/**
* Delete SLA for the ticket
*
* @param $id ID of the ticket
*
* @return boolean
**/
function deleteSLA($id) {
global $DB;
$input['slas_id'] = 0;
$input['slalevels_id'] = 0;
$input['sla_waiting_duration'] = 0;
$input['id'] = $id;
SlaLevel_Ticket::deleteForTicket($id);
return $this->update($input);
}
/**
* Is the current user have right to create the current ticket ?
*
* @return boolean
**/
function canCreateItem() {
if (!Session::haveAccessToEntity($this->getEntityID())) {
return false;
}
return Session::haveRight('create_ticket', '1');
}
/**
* Is the current user have right to update the current ticket ?
*
* @return boolean
**/
function canUpdateItem() {
if (!Session::haveAccessToEntity($this->getEntityID())) {
return false;
}
if (($this->numberOfFollowups() == 0)
&& ($this->numberOfTasks() == 0)
&& ($this->isUser(CommonITILActor::REQUESTER,Session::getLoginUserID())
|| ($this->fields["users_id_recipient"] === Session::getLoginUserID()))) {
return true;
}
return static::canUpdate();
}
/**
* Is the current user have right to delete the current ticket ?
*
* @return boolean
**/
function canDeleteItem() {
if (!Session::haveAccessToEntity($this->getEntityID())) {
return false;
}
// user can delete his ticket if no action on it
if (($this->isUser(CommonITILActor::REQUESTER, Session::getLoginUserID())
|| ($this->fields["users_id_recipient"] === Session::getLoginUserID()))
&& ($this->numberOfFollowups() == 0)
&& ($this->numberOfTasks() == 0)
&& ($this->fields["date"] == $this->fields["date_mod"])) {
return true;
}
return Session::haveRight('delete_ticket', '1');
}
/**
* @see CommonITILObject::getDefaultActor()
**/
function getDefaultActor($type) {
if ($type == CommonITILActor::ASSIGN) {
if (Session::haveRight("own_ticket","1")
&& $_SESSION['glpiset_default_tech']) {
return Session::getLoginUserID();
}
}
return 0;
}
/**
* @see CommonITILObject::getDefaultActorRightSearch()
**/
function getDefaultActorRightSearch($type) {
$right = "all";
if ($type == CommonITILActor::ASSIGN) {
$right = "own_ticket";
if (!Session::haveRight("assign_ticket","1")) {
$right = 'id';
}
}
return $right;
}
function pre_deleteItem() {
NotificationEvent::raiseEvent('delete',$this);
return true;
}
function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
if (static::canView()) {
$nb = 0;
$title = self::getTypeName(2);
if ($_SESSION['glpishow_count_on_tabs']) {
switch ($item->getType()) {
case 'Change' :
$nb = countElementsInTable('glpi_changes_tickets',
"`changes_id` = '".$item->getID()."'");
break;
case 'Problem' :
$nb = countElementsInTable('glpi_problems_tickets',
"`problems_id` = '".$item->getID()."'");
break;
case 'User' :
$nb = countElementsInTable('glpi_tickets_users',
"`users_id` = '".$item->getID()."'
AND `type` = ".CommonITILActor::REQUESTER);
$title = __('Created tickets');
break;
case 'Supplier' :
$nb = countElementsInTable('glpi_suppliers_tickets',
"`suppliers_id` = '".$item->getID()."'");
break;
case 'SLA' :
$nb = countElementsInTable('glpi_tickets',
"`slas_id` = '".$item->getID()."'");
break;
case 'Group' :
$nb = countElementsInTable('glpi_groups_tickets',
"`groups_id` = '".$item->getID()."'
AND `type` = ".CommonITILActor::REQUESTER);
$title = __('Created tickets');
break;
default :
// Direct one
$nb = countElementsInTable('glpi_tickets',
" `itemtype` = '".$item->getType()."'
AND `items_id` = '".$item->getID()."'");
// Linked items
if ($subquery = $item->getSelectLinkedItem()) {
$nb += countElementsInTable('glpi_tickets',
"(`itemtype`,`items_id`) IN (" . $subquery . ")");
}
break;
}
} // glpishow_count_on_tabs
// Not for Ticket class
if ($item->getType() != __CLASS__) {
return self::createTabEntry($title, $nb);
}
} // show_all_ticket right check
// Not check show_all_ticket for Ticket itself
switch ($item->getType()) {
case __CLASS__ :
$ong = array();
$ong[2] = _n('Solution', 'Solutions', 1);
// enquete si statut clos
if ($item->fields['status'] == self::CLOSED) {
$satisfaction = new TicketSatisfaction();
if ($satisfaction->getFromDB($item->getID())) {
$ong[3] = __('Satisfaction');
}
}
if (Session::haveRight('observe_ticket','1')) {
$ong[4] = __('Statistics');
}
return $ong;
// default :
// return _n('Ticket','Tickets',2);
}
return '';
}
static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
switch ($item->getType()) {
case 'Change' :
Change_Ticket::showForChange($item);
break;
case 'Problem' :
Problem_Ticket::showForProblem($item);
break;
case __CLASS__ :
switch ($tabnum) {
case 2 :
if (!isset($_POST['load_kb_sol'])) {
$_POST['load_kb_sol'] = 0;
}
$item->showSolutionForm($_POST['load_kb_sol']);
if ($item->canApprove()) {
$fup = new TicketFollowup();
$fup->showApprobationForm($item);
}
break;
case 3 :
$satisfaction = new TicketSatisfaction();
if (($item->fields['status'] == self::CLOSED)
&& $satisfaction->getFromDB($_POST["id"])) {
$satisfaction->showSatisfactionForm($item);
} else {
echo "<p class='center b'>".__('No generated survey')."</p>";
}
break;
case 4 :
$item->showStats();
break;
}
break;
case 'Group' :
case 'SLA' :
default :
self::showListForItem($item);
}
return true;
}
function defineTabs($options=array()) {
$ong = array();
$this->addStandardTab('TicketFollowup',$ong, $options);
// $this->addStandardTab('TicketValidation', $ong, $options);
$this->addStandardTab('TicketTask', $ong, $options);
$this->addStandardTab(__CLASS__, $ong, $options);
// $this->addStandardTab('TicketCost', $ong, $options);
$this->addStandardTab('Document_Item', $ong, $options);
// $this->addStandardTab('Problem', $ong, $options);
//// $this->addStandardTab('Change', $ong, $options);
$this->addStandardTab('Log', $ong, $options);
return $ong;
}
/**
* Retrieve data of the hardware linked to the ticket if exists
*
* @return nothing : set computerfound to 1 if founded
**/
function getAdditionalDatas() {
if ($this->fields["itemtype"]
&& ($item = getItemForItemtype($this->fields["itemtype"]))) {
if ($item->getFromDB($this->fields["items_id"])) {
$this->hardwaredatas=$item;
}
} else {
$this->hardwaredatas = NULL;
}
}
function cleanDBonPurge() {
global $DB;
$query1 = "DELETE
FROM `glpi_tickettasks`
WHERE `tickets_id` = '".$this->fields['id']."'";
$DB->query($query1);
$query1 = "DELETE
FROM `glpi_ticketfollowups`
WHERE `tickets_id` = '".$this->fields['id']."'";
$DB->query($query1);
$ts = new TicketValidation();
$ts->cleanDBonItemDelete($this->getType(), $this->fields['id']);
$query1 = "DELETE
FROM `glpi_ticketsatisfactions`
WHERE `tickets_id` = '".$this->fields['id']."'";
$DB->query($query1);
$pt = new Problem_Ticket();
$pt->cleanDBonItemDelete('Ticket', $this->fields['id']);
$ts = new TicketCost();
$ts->cleanDBonItemDelete($this->getType(), $this->fields['id']);
SlaLevel_Ticket::deleteForTicket($this->getID());
$query1 = "DELETE
FROM `glpi_tickets_tickets`
WHERE `tickets_id_1` = '".$this->fields['id']."'
OR `tickets_id_2` = '".$this->fields['id']."'";
$DB->query($query1);
parent::cleanDBonPurge();
}
function prepareInputForUpdate($input) {
global $CFG_GLPI;
// Get ticket : need for comparison
$this->getFromDB($input['id']);
// automatic recalculate if user changes urgence or technician change impact
if (isset($input['urgency'])
&& isset($input['impact'])
&& (($input['urgency'] != $this->fields['urgency'])
|| $input['impact'] != $this->fields['impact'])
&& !isset($input['priority'])) {
$input['priority'] = self::computePriority($input['urgency'], $input['impact']);
}
// Security checks
if (!Session::isCron()
&& !Session::haveRight("assign_ticket","1")) {
if (isset($input["_itil_assign"])
&& isset($input['_itil_assign']['_type'])
&& ($input['_itil_assign']['_type'] == 'user')) {
// must own_ticket to grab a non assign ticket
if ($this->countUsers(CommonITILActor::ASSIGN) == 0) {
if ((!Session::haveRight("steal_ticket","1")
&& !Session::haveRight("own_ticket","1"))
|| !isset($input["_itil_assign"]['users_id'])
|| ($input["_itil_assign"]['users_id'] != Session::getLoginUserID())) {
unset($input["_itil_assign"]);
}
} else {
// Can not steal or can steal and not assign to me
if (!Session::haveRight("steal_ticket","1")
|| !isset($input["_itil_assign"]['users_id'])
|| ($input["_itil_assign"]['users_id'] != Session::getLoginUserID())) {
unset($input["_itil_assign"]);
}
}
}
// No supplier assign
if (isset($input["_itil_assign"])
&& isset($input['_itil_assign']['_type'])
&& ($input['_itil_assign']['_type'] == 'supplier')) {
unset($input["_itil_assign"]);
}
// No group
if (isset($input["_itil_assign"])
&& isset($input['_itil_assign']['_type'])
&& ($input['_itil_assign']['_type'] == 'group')) {
unset($input["_itil_assign"]);
}
}
$check_allowed_fields_for_template = false;
if (!Session::isCron()
&& !Session::haveRight("update_ticket","1")) {
$allowed_fields = array('id');
$check_allowed_fields_for_template = true;
if ($this->canApprove()
&& isset($input["status"])) {
$allowed_fields[] = 'status';
}
// for post-only with validate right or validation created by rules
if (TicketValidation::canValidate($this->fields['id'])
|| TicketValidation::canCreate()
|| isset($input["_rule_process"])) {
$allowed_fields[] = 'global_validation';
}
// Manage assign and steal right
if (Session::haveRight('assign_ticket',1)
|| Session::haveRight('steal_ticket',1)) {
$allowed_fields[] = '_itil_assign';
}
// Can only update initial fields if no followup or task already added
if (($this->numberOfFollowups() == 0)
&& ($this->numberOfTasks() == 0)
&& $this->isUser(CommonITILActor::REQUESTER, Session::getLoginUserID())) {
$allowed_fields[] = 'content';
$allowed_fields[] = 'urgency';
$allowed_fields[] = 'priority'; // automatic recalculate if user changes urgence
$allowed_fields[] = 'itilcategories_id';
$allowed_fields[] = 'itemtype';
$allowed_fields[] = 'items_id';
$allowed_fields[] = 'name';
}
if ($this->canSolve()) {
$allowed_fields[] = 'solutiontypes_id';
$allowed_fields[] = 'solution';
}
foreach ($allowed_fields as $field) {
if (isset($input[$field])) {
$ret[$field] = $input[$field];
}
}
$input = $ret;
}
//// check mandatory fields
// First get ticket template associated : entity and type/category
if (isset($input['entities_id'])) {
$entid = $input['entities_id'];
} else {
$entid = $this->fields['entities_id'];
}
if (isset($input['type'])) {
$type = $input['type'];
} else {
$type = $this->fields['type'];
}
if (isset($input['itilcategories_id'])) {
$categid = $input['itilcategories_id'];
} else {
$categid = $this->fields['itilcategories_id'];
}
$tt = $this->getTicketTemplateToUse(0, $type, $categid, $entid);
if (count($tt->mandatory)) {
$mandatory_missing = array();
$fieldsname = $tt->getAllowedFieldsNames(true);
foreach ($tt->mandatory as $key => $val) {
if ((!$check_allowed_fields_for_template || in_array($key,$allowed_fields))
&& (isset($input[$key])
&& (empty($input[$key]) || ($input[$key] == 'NULL'))
// Take only into account already set items : do not block old tickets
&& (!empty($this->fields[$key]))
)) {
$mandatory_missing[$key] = $fieldsname[$val];
}
}
if (count($mandatory_missing)) {
//TRANS: %s are the fields concerned
$message = sprintf(__('Mandatory fields are not filled. Please correct: %s'),
implode(", ",$mandatory_missing));
Session::addMessageAfterRedirect($message, false, ERROR);
return false;
}
}
// Manage fields from auto update : map rule actions to standard ones
if (isset($input['_auto_update'])) {
if (isset($input['_users_id_assign'])) {
$input['_itil_assign']['_type'] = 'user';
$input['_itil_assign']['users_id'] = $input['_users_id_assign'];
}
if (isset($input['_groups_id_assign'])) {
$input['_itil_assign']['_type'] = 'group';
$input['_itil_assign']['groups_id'] = $input['_groups_id_assign'];
}
if (isset($input['_suppliers_id_assign'])) {
$input['_itil_assign']['_type'] = 'supplier';
$input['_itil_assign']['suppliers_id'] = $input['_suppliers_id_assign'];
}
if (isset($input['_users_id_requester'])) {
$input['_itil_requester']['_type'] = 'user';
$input['_itil_requester']['users_id'] = $input['_users_id_requester'];
}
if (isset($input['_groups_id_requester'])) {
$input['_itil_requester']['_type'] = 'group';
$input['_itil_requester']['groups_id'] = $input['_groups_id_requester'];
}
if (isset($input['_users_id_observer'])) {
$input['_itil_observer']['_type'] = 'user';
$input['_itil_observer']['users_id'] = $input['_users_id_observer'];
}
if (isset($input['_groups_id_observer'])) {
$input['_itil_observer']['_type'] = 'group';
$input['_itil_observer']['groups_id'] = $input['_groups_id_observer'];
}
}
if (isset($input['_link'])) {
$ticket_ticket = new Ticket_Ticket();
if (!empty($input['_link']['tickets_id_2'])) {
if ($ticket_ticket->can(-1, 'w', $input['_link'])) {
if ($ticket_ticket->add($input['_link'])) {
$input['_forcenotif'] = true;
}
} else {
Session::addMessageAfterRedirect(__('Unknown ticket'), false, ERROR);
}
}
}
if (isset($input["items_id"]) && ($input["items_id"] >= 0)
&& isset($input["itemtype"])) {
if (isset($this->fields['groups_id'])
&& ($this->fields['groups_id'] == 0)
&& (!isset($input['groups_id']) || ($input['groups_id'] == 0))) {
if ($input["itemtype"]
&& ($item = getItemForItemtype($input["itemtype"]))) {
$item->getFromDB($input["items_id"]);
if ($item->isField('groups_id')) {
$input["groups_id"] = $item->getField('groups_id');
}
}
}
} else if (isset($input["itemtype"]) && empty($input["itemtype"])) {
$input["items_id"] = 0;
} else {
unset($input["items_id"]);
unset($input["itemtype"]);
}
//Action for send_validation rule
if (isset($this->input["_add_validation"]) && ($this->input["_add_validation"] > 0)) {
$validation = new TicketValidation();
// if auto_update, tranfert it for validation
if (isset($this->input['_auto_update'])) {
$values['_auto_update'] = $this->input['_auto_update'];
}
$values['tickets_id'] = $this->input['id'];
$values['users_id_validate'] = $this->input["_add_validation"];
if (Session::isCron()
|| $validation->can(-1, 'w', $values)) { // cron or allowed user
$validation->add($values);
Event::log($this->fields['id'], "ticket", 4, "tracking",
sprintf(__('%1$s updates the item %2$s'),
(is_numeric(Session::getLoginUserID(false))?$_SESSION["glpiname"]
:'cron'),
$this->fields['id']));
}
}
if (isset($this->input["slas_id"]) && ($this->input["slas_id"] > 0)
&& ($this->fields['slas_id'] == 0)) {
$date = $this->fields['date'];
/// Use updated date if also done
if (isset($this->input["date"])) {
$date = $this->input["date"];
}
// Get datas to initialize SLA and set it
$sla_data = $this->getDatasToAddSLA($this->input["slas_id"], $this->fields['entities_id'],
$date);
if (count($sla_data)) {
foreach ($sla_data as $key => $val) {
$input[$key] = $val;
}
}
}
$input = parent::prepareInputForUpdate($input);
return $input;
}
function pre_updateInDB() {
// takeintoaccount :
// - update done by someone who have update right
// see also updatedatemod used by ticketfollowup updates
if (($this->fields['takeintoaccount_delay_stat'] == 0)
&& (Session::haveRight("global_add_tasks", "1")
|| Session::haveRight("global_add_followups", "1")
|| $this->isUser(CommonITILActor::ASSIGN, Session::getLoginUserID())
|| (isset($_SESSION["glpigroups"])
&& $this->haveAGroup(CommonITILActor::ASSIGN, $_SESSION['glpigroups'])))) {
$this->updates[] = "takeintoaccount_delay_stat";
$this->fields['takeintoaccount_delay_stat'] = $this->computeTakeIntoAccountDelayStat();
}
parent::pre_updateInDB();
}
/// Compute take into account stat of the current ticket
function computeTakeIntoAccountDelayStat() {
if (isset($this->fields['id'])
&& !empty($this->fields['date'])) {
$calendars_id = Entity::getUsedConfig('calendars_id', $this->fields['entities_id']);
$calendar = new Calendar();
// Using calendar
if (($calendars_id > 0) && $calendar->getFromDB($calendars_id)) {
return max(0, $calendar->getActiveTimeBetween($this->fields['date'],
$_SESSION["glpi_currenttime"]));
}
// Not calendar defined
return max(0, strtotime($_SESSION["glpi_currenttime"])-strtotime($this->fields['date']));
}
return 0;
}
function post_updateItem($history=1) {
global $CFG_GLPI;
$donotif = count($this->updates);
if (isset($this->input['_forcenotif'])) {
$donotif = true;
}
// Manage SLA Level : add actions
if (in_array("slas_id", $this->updates)
&& ($this->fields["slas_id"] > 0)) {
// Add First Level
$calendars_id = Entity::getUsedConfig('calendars_id', $this->fields['entities_id']);
$sla = new SLA();
if ($sla->getFromDB($this->fields["slas_id"])) {
$sla->setTicketCalendar($calendars_id);
// Add first level in working table
if ($this->fields["slalevels_id"] > 0) {
$sla->addLevelToDo($this);
}
}
SlaLevel_Ticket::replayForTicket($this->getID());
}
if (count($this->updates)) {
// Update Ticket Tco
if (in_array("actiontime", $this->updates)
|| in_array("cost_time", $this->updates)
|| in_array("cost_fixed", $this->updates)
|| in_array("cost_material", $this->updates)) {
if ($this->fields["itemtype"]
&& ($item = getItemForItemtype($this->fields["itemtype"]))) {
if ($item->getFromDB($this->fields["items_id"])) {
$newinput = array();
$newinput['id'] = $this->fields["items_id"];
$newinput['ticket_tco'] = self::computeTco($item);
$item->update($newinput);
}
}
}
// Setting a solution type means the ticket is solved
if ((in_array("solutiontypes_id", $this->updates)
|| in_array("solution", $this->updates))
&& (in_array($this->input["status"], $this->getSolvedStatusArray())
|| in_array($this->input["status"], $this->getClosedStatusArray()))) { // auto close case
Ticket_Ticket::manageLinkedTicketsOnSolved($this->fields['id']);
}
// Clean content to mail
$this->fields["content"] = stripslashes($this->fields["content"]);
$donotif = true;
}
if (isset($this->input['_disablenotif'])) {
$donotif = false;
}
if ($donotif && $CFG_GLPI["use_mailing"]) {
$mailtype = "update";
if (isset($this->input["status"])
&& $this->input["status"]
&& in_array("status", $this->updates)
&& in_array($this->input["status"], $this->getSolvedStatusArray())) {
$mailtype = "solved";
}
if (isset($this->input["status"])
&& $this->input["status"]
&& in_array("status",$this->updates)
&& in_array($this->input["status"], $this->getClosedStatusArray())) {
$mailtype = "closed";
}
// Read again ticket to be sure that all data are up to date
$this->getFromDB($this->fields['id']);
NotificationEvent::raiseEvent($mailtype, $this);
}
// inquest created immediatly if delay = O
$inquest = new TicketSatisfaction();
$rate = Entity::getUsedConfig('inquest_config', $this->fields['entities_id'],
'inquest_rate');
$delay = Entity::getUsedConfig('inquest_config', $this->fields['entities_id'],
'inquest_delay');
$type = Entity::getUsedConfig('inquest_config', $this->fields['entities_id']);
$max_closedate = $this->fields['closedate'];
if (in_array("status",$this->updates)
&& in_array($this->input["status"], $this->getClosedStatusArray())
&& ($delay == 0)
&& ($rate > 0)
&& (mt_rand(1,100) <= $rate)) {
$inquest->add(array('tickets_id' => $this->fields['id'],
'date_begin' => $_SESSION["glpi_currenttime"],
'entities_id' => $this->fields['entities_id'],
'type' => $type,
'max_closedate' => $max_closedate));
}
}
function prepareInputForAdd($input) {
global $CFG_GLPI;
// save value before clean;
$title = ltrim($input['name']);
// Standard clean datas
$input = parent::prepareInputForAdd($input);
// Do not check mandatory on auto import (mailgates)
if (!isset($input['_auto_import'])) {
if (isset($input['_tickettemplates_id']) && $input['_tickettemplates_id']) {
$tt = new TicketTemplate();
if ($tt->getFromDBWithDatas($input['_tickettemplates_id'])) {
if (count($tt->mandatory)) {
$mandatory_missing = array();
$fieldsname = $tt->getAllowedFieldsNames(true);
foreach ($tt->mandatory as $key => $val) {
// for title if mandatory (restore initial value)
if ($key == 'name') {
$input['name'] = $title;
}
// Check only defined values : Not defined not in form
if (isset($input[$key])) {
// If content is also predefined need to be different from predefined value
if (($key == 'content')
&& isset($tt->predefined['content'])) {
// Clean new lines to be fix encoding
if (strcmp(preg_replace("/\r?\n/", "",
Html::cleanPostForTextArea($input[$key])),
preg_replace("/\r?\n/", "",
$tt->predefined['content'])) == 0) {
$mandatory_missing[$key] = $fieldsname[$val];
}
}
if (empty($input[$key]) || ($input[$key] == 'NULL')) {
$mandatory_missing[$key] = $fieldsname[$val];
}
}
// For due_date : check also slas_id
if ($key == 'due_date'
&& isset($input['slas_id']) && ($input['slas_id'] > 0)
&& isset($mandatory_missing['due_date'])) {
unset($mandatory_missing['due_date']);
}
}
if (count($mandatory_missing)) {
//TRANS: %s are the fields concerned
$message = sprintf(__('Mandatory fields are not filled. Please correct: %s'),
implode(", ",$mandatory_missing));
Session::addMessageAfterRedirect($message, false, ERROR);
return false;
}
}
}
}
}
if (!isset($input["requesttypes_id"])) {
$input["requesttypes_id"] = RequestType::getDefault('helpdesk');
}
if (!isset($input['global_validation'])) {
$input['global_validation'] = 'none';
}
// Set additional default dropdown
$dropdown_fields = array('items_id', 'items_locations', 'users_locations');
foreach ($dropdown_fields as $field ) {
if (!isset($input[$field])) {
$input[$field] = 0;
}
}
if (!isset($input['itemtype']) || !($input['items_id'] > 0)) {
$input['itemtype'] = '';
}
$item = NULL;
if (($input["items_id"] > 0) && !empty($input["itemtype"])) {
if ($item = getItemForItemtype($input["itemtype"])) {
if ($item->getFromDB($input["items_id"])) {
if ($item->isField('locations_id')) {
$input['items_locations'] = $item->fields['locations_id'];
}
} else {
$item = NULL;
}
}
}
// Business Rules do not override manual SLA
$manual_slas_id = 0;
if (isset($input['slas_id']) && ($input['slas_id'] > 0)) {
$manual_slas_id = $input['slas_id'];
}
// Process Business Rules
$rules = new RuleTicketCollection($input['entities_id']);
// Set unset variables with are needed
$user = new User();
if (isset($input["_users_id_requester"])
&& $user->getFromDB($input["_users_id_requester"])) {
$input['users_locations'] = $user->fields['locations_id'];
$tmprequester = $input["_users_id_requester"];
} else {
$tmprequester = 0;
}
// Clean new lines before passing to rules
if (isset($input["content"])) {
$input["content"] = preg_replace('/\\\\r\\\\n/',"\n",$input['content']);
$input["content"] = preg_replace('/\\\\n/',"\n",$input['content']);
}
$input = $rules->processAllRules(Toolbox::stripslashes_deep($input),
Toolbox::stripslashes_deep($input),
array('recursive' => true));
// Recompute default values based on values computed by rules
$input = $this->computeDefaultValuesForAdd($input);
if (isset($input['_users_id_requester'])
&& ($input['_users_id_requester'] != $tmprequester)) {
// if requester set by rule, clear address from mailcollector
unset($input['_users_id_requester_notif']);
}
// Restore slas_id
if ($manual_slas_id > 0) {
$input['slas_id'] = $manual_slas_id;
}
// Manage auto assign
$auto_assign_mode = Entity::getUsedConfig('auto_assign_mode', $input['entities_id']);
switch ($auto_assign_mode) {
case Entity::CONFIG_NEVER :
break;
case Entity::AUTO_ASSIGN_HARDWARE_CATEGORY :
if ($item != NULL) {
// Auto assign tech from item
if ((!isset($input['_users_id_assign']) || ($input['_users_id_assign'] == 0))
&& $item->isField('users_id_tech')) {
$input['_users_id_assign'] = $item->getField('users_id_tech');
}
// Auto assign group from item
if ((!isset($input['_groups_id_assign']) || ($input['_groups_id_assign'] == 0))
&& $item->isField('groups_id_tech')) {
$input['_groups_id_assign'] = $item->getField('groups_id_tech');
}
}
// Auto assign tech/group from Category
if (($input['itilcategories_id'] > 0)
&& ((!isset($input['_users_id_assign']) || !$input['_users_id_assign'])
|| (!isset($input['_groups_id_assign']) || !$input['_groups_id_assign']))) {
$cat = new ITILCategory();
$cat->getFromDB($input['itilcategories_id']);
if ((!isset($input['_users_id_assign']) || !$input['_users_id_assign'])
&& $cat->isField('users_id')) {
$input['_users_id_assign'] = $cat->getField('users_id');
}
if ((!isset($input['_groups_id_assign']) || !$input['_groups_id_assign'])
&& $cat->isField('groups_id')) {
$input['_groups_id_assign'] = $cat->getField('groups_id');
}
}
break;
case Entity::AUTO_ASSIGN_CATEGORY_HARDWARE :
// Auto assign tech/group from Category
if (($input['itilcategories_id'] > 0)
&& ((!isset($input['_users_id_assign']) || !$input['_users_id_assign'])
|| (!isset($input['_groups_id_assign']) || !$input['_groups_id_assign']))) {
$cat = new ITILCategory();
$cat->getFromDB($input['itilcategories_id']);
if ((!isset($input['_users_id_assign']) || !$input['_users_id_assign'])
&& $cat->isField('users_id')) {
$input['_users_id_assign'] = $cat->getField('users_id');
}
if ((!isset($input['_groups_id_assign']) || !$input['_groups_id_assign'])
&& $cat->isField('groups_id')) {
$input['_groups_id_assign'] = $cat->getField('groups_id');
}
}
if ($item != NULL) {
// Auto assign tech from item
if ((!isset($input['_users_id_assign']) || ($input['_users_id_assign'] == 0))
&& $item->isField('users_id_tech')) {
$input['_users_id_assign'] = $item->getField('users_id_tech');
}
// Auto assign group from item
if ((!isset($input['_groups_id_assign']) || ($input['_groups_id_assign'] == 0))
&& $item->isField('groups_id_tech')) {
$input['_groups_id_assign'] = $item->getField('groups_id_tech');
}
}
break;
}
// Replay setting auto assign if set in rules engine or by auto_assign_mode
if (((isset($input["_users_id_assign"]) && ($input["_users_id_assign"] > 0))
|| (isset($input["_groups_id_assign"]) && ($input["_groups_id_assign"] > 0))
|| (isset($input["_suppliers_id_assign"]) && ($input["_suppliers_id_assign"] > 0)))
&& (in_array($input['status'], $this->getNewStatusArray()))) {
$input["status"] = self::ASSIGNED;
}
//// Manage SLA assignment
// Manual SLA defined : reset due date
// No manual SLA and due date defined : reset auto SLA
if (($manual_slas_id == 0)
&& isset($input["due_date"]) && ($input['due_date'] != 'NULL')) {
// Valid due date
if ($input['due_date'] > $input['date']) {
if (isset($input["slas_id"])) {
unset($input["slas_id"]);
}
} else {
// Unset due date
unset($input["due_date"]);
}
}
if (isset($input["slas_id"]) && ($input["slas_id"] > 0)) {
// Get datas to initialize SLA and set it
$sla_data = $this->getDatasToAddSLA($input["slas_id"], $input['entities_id'],
$input['date']);
if (count($sla_data)) {
foreach ($sla_data as $key => $val) {
$input[$key] = $val;
}
}
}
// auto set type if not set
if (!isset($input["type"])) {
$input['type'] = Entity::getUsedConfig('tickettype', $input['entities_id'], '',
Ticket::INCIDENT_TYPE);
}
return $input;
}
function post_addItem() {
global $CFG_GLPI;
// Log this event
$username = 'anonymous';
if (isset($_SESSION["glpiname"])) {
$username = $_SESSION["glpiname"];
}
Event::log($this->fields['id'], "ticket", 4, "tracking",
sprintf(__('%1$s adds the item %2$s'), $username,
$this->fields['id']));
if (isset($this->input["_followup"])
&& is_array($this->input["_followup"])
&& (strlen($this->input["_followup"]['content']) > 0)) {
$fup = new TicketFollowup();
$type = "new";
if (isset($this->fields["status"]) && ($this->fields["status"] == self::SOLVED)) {
$type = "solved";
}
$toadd = array("type" => $type,
"tickets_id" => $this->fields['id']);
if (isset($this->input["_followup"]['content'])
&& (strlen($this->input["_followup"]['content']) > 0)) {
$toadd["content"] = $this->input["_followup"]['content'];
}
if (isset($this->input["_followup"]['is_private'])) {
$toadd["is_private"] = $this->input["_followup"]['is_private'];
}
$toadd['_no_notif'] = true;
$fup->add($toadd);
}
if ((isset($this->input["plan"]) && count($this->input["plan"]))
|| (isset($this->input["actiontime"]) && ($this->input["actiontime"] > 0))) {
$task = new TicketTask();
$type = "new";
if (isset($this->fields["status"]) && ($this->fields["status"] == self::SOLVED)) {
$type = "solved";
}
$toadd = array("type" => $type,
"tickets_id" => $this->fields['id'],
"actiontime" => $this->input["actiontime"]);
if (isset($this->input["plan"]) && count($this->input["plan"])) {
$toadd["plan"] = $this->input["plan"];
}
if (isset($_SESSION['glpitask_private'])) {
$toadd['is_private'] = $_SESSION['glpitask_private'];
}
$toadd['_no_notif'] = true;
$task->add($toadd);
}
$ticket_ticket = new Ticket_Ticket();
// From interface
if (isset($this->input['_link'])) {
$this->input['_link']['tickets_id_1'] = $this->fields['id'];
// message if ticket's ID doesn't exist
if (!empty($this->input['_link']['tickets_id_2'])) {
if ($ticket_ticket->can(-1, 'w', $this->input['_link'])) {
$ticket_ticket->add($this->input['_link']);
} else {
Session::addMessageAfterRedirect(__('Unknown ticket'), false, ERROR);
}
}
}
// From mailcollector : do not check rights
if (isset($this->input["_linkedto"])) {
$input2['tickets_id_1'] = $this->fields['id'];
$input2['tickets_id_2'] = $this->input["_linkedto"];
$input2['link'] = Ticket_Ticket::LINK_TO;
$ticket_ticket->add($input2);
}
// Manage SLA Level : add actions
if (isset($this->input["slas_id"]) && ($this->input["slas_id"] > 0)
&& isset($this->input["slalevels_id"]) && ($this->input["slalevels_id"] > 0)) {
$calendars_id = Entity::getUsedConfig('calendars_id', $this->fields['entities_id']);
$sla = new SLA();
if ($sla->getFromDB($this->input["slas_id"])) {
$sla->setTicketCalendar($calendars_id);
// Add first level in working table
if ($this->input["slalevels_id"] > 0) {
$sla->addLevelToDo($this);
}
// Replay action in case of open date is set before now
}
SlaLevel_Ticket::replayForTicket($this->getID());
}
parent::post_addItem();
//Action for send_validation rule
if (isset($this->input["_add_validation"])) {
$validations_to_send = array();
if (!is_array($this->input["_add_validation"])) {
$this->input["_add_validation"] = array($this->input["_add_validation"]);
}
foreach ($this->input["_add_validation"] as $validation) {
switch ($validation) {
case 'requester_supervisor' :
if (isset($this->input['_groups_id_requester'])
&& $this->input['_groups_id_requester']) {
$users = Group_User::getGroupUsers($this->input['_groups_id_requester'],
"is_manager='1'");
foreach ($users as $data) {
$validations_to_send[] = $data['id'];
}
}
break;
case 'assign_supervisor' :
if (isset($this->input['_groups_id_assign'])
&& $this->input['_groups_id_assign']) {
$users = Group_User::getGroupUsers($this->input['_groups_id_assign'],
"is_manager='1'");
foreach ($users as $data) {
$validations_to_send[] = $data['id'];
}
}
break;
default :
$validations_to_send[] = $validation;
}
}
// Keep only one
$validations_to_send = array_unique($validations_to_send);
$validation = new TicketValidation();
foreach ($validations_to_send as $users_id) {
if ($users_id > 0) {
$values = array();
$values['tickets_id'] = $this->fields['id'];
$values['users_id_validate'] = $users_id;
$values['_ticket_add'] = true;
// to know update by rules
if (isset($this->input["_rule_process"])) {
$values['_rule_process'] = $this->input["_rule_process"];
}
// if auto_import, tranfert it for validation
if (isset($this->input['_auto_import'])) {
$values['_auto_import'] = $this->input['_auto_import'];
}
// Cron or rule process of hability to do
if (Session::isCron()
|| isset($this->input["_auto_import"])
|| isset($this->input["_rule_process"])
|| $validation->can(-1, 'w', $values)) { // cron or allowed user
$validation->add($values);
Event::log($this->fields['id'], "ticket", 4, "tracking",
sprintf(__('%1$s updates the item %2$s'), $_SESSION["glpiname"],
$this->fields['id']));
}
}
}
}
// Processing Email
if ($CFG_GLPI["use_mailing"]) {
// Clean reload of the ticket
$this->getFromDB($this->fields['id']);
$type = "new";
if (isset($this->fields["status"]) && ($this->fields["status"] == self::SOLVED)) {
$type = "solved";
}
NotificationEvent::raiseEvent($type, $this);
}
if (isset($_SESSION['glpiis_ids_visible']) && !$_SESSION['glpiis_ids_visible']) {
Session::addMessageAfterRedirect(sprintf(__('%1$s (%2$s)'),
__('Your ticket has been registered, its treatment is in progress.'),
sprintf(__('%1$s: %2$s'), __('Ticket'),
"<a href='".$CFG_GLPI["root_doc"].
"/front/ticket.form.php?id=".
$this->fields['id']."'>".
$this->fields['id']."</a>")));
}
}
// SPECIFIC FUNCTIONS
/**
* Number of followups of the ticket
*
* @param $with_private boolean : true : all followups / false : only public ones (default 1)
*
* @return followup count
**/
function numberOfFollowups($with_private=1) {
global $DB;
$RESTRICT = "";
if ($with_private!=1) {
$RESTRICT = " AND `is_private` = '0'";
}
// Set number of followups
$query = "SELECT COUNT(*)
FROM `glpi_ticketfollowups`
WHERE `tickets_id` = '".$this->fields["id"]."'
$RESTRICT";
$result = $DB->query($query);
return $DB->result($result, 0, 0);
}
/**
* Number of tasks of the ticket
*
* @param $with_private boolean : true : all ticket / false : only public ones (default 1)
*
* @return followup count
**/
function numberOfTasks($with_private=1) {
global $DB;
$RESTRICT = "";
if ($with_private!=1) {
$RESTRICT = " AND `is_private` = '0'";
}
// Set number of followups
$query = "SELECT COUNT(*)
FROM `glpi_tickettasks`
WHERE `tickets_id` = '".$this->fields["id"]."'
$RESTRICT";
$result = $DB->query($query);
return $DB->result($result, 0, 0);
}
/**
* Get active or solved tickets for an hardware last X days
*
* @since version 0.83
*
* @param $itemtype string Item type
* @param $items_id integer ID of the Item
* @param $days integer day number
*
* @return integer
**/
function getActiveOrSolvedLastDaysTicketsForItem($itemtype, $items_id, $days) {
global $DB;
$result = array();
$query = "SELECT *
FROM `".$this->getTable()."`
WHERE `".$this->getTable()."`.`itemtype` = '$itemtype'
AND `".$this->getTable()."`.`items_id` = '$items_id'
AND (`".$this->getTable()."`.`status`
NOT IN ('".implode("', '", array_merge($this->getSolvedStatusArray(),
$this->getClosedStatusArray())
)."')
OR (`".$this->getTable()."`.`solvedate` IS NOT NULL
AND ADDDATE(`".$this->getTable()."`.`solvedate`, INTERVAL $days DAY)
> NOW()))";
foreach ($DB->request($query) as $tick) {
$result[$tick['id']] = $tick['name'];
}
return $result;
}
/**
* Count active tickets for an hardware
*
* @since version 0.83
*
* @param $itemtype string Item type
* @param $items_id integer ID of the Item
*
* @return integer
**/
function countActiveTicketsForItem($itemtype, $items_id) {
return countElementsInTable($this->getTable(),
"`".$this->getTable()."`.`itemtype` = '$itemtype'
AND `".$this->getTable()."`.`items_id` = '$items_id'
AND `".$this->getTable()."`.`status`
NOT IN ('".implode("', '",
array_merge($this->getSolvedStatusArray(),
$this->getClosedStatusArray())
)."')");
}
/**
* Count solved tickets for an hardware last X days
*
* @since version 0.83
*
* @param $itemtype string Item type
* @param $items_id integer ID of the Item
* @param $days integer day number
*
* @return integer
**/
function countSolvedTicketsForItemLastDays($itemtype, $items_id, $days) {
return countElementsInTable($this->getTable(),
"`".$this->getTable()."`.`itemtype` = '$itemtype'
AND `".$this->getTable()."`.`items_id` = '$items_id'
AND `".$this->getTable()."`.`solvedate` IS NOT NULL
AND ADDDATE(`".$this->getTable()."`.`solvedate`,
INTERVAL $days DAY) > NOW()
AND `".$this->getTable()."`.`status`
IN ('".implode("', '",
array_merge($this->getSolvedStatusArray(),
$this->getClosedStatusArray())
)."')");
}
/**
* Update date mod of the ticket
*
* @since version 0.83.3 new proto
*
* @param $ID ID of the ticket
* @param $no_stat_computation boolean do not cumpute take into account stat (false by default)
* @param $users_id_lastupdater integer to force last_update id (default 0 = not used)
**/
function updateDateMod($ID, $no_stat_computation=false, $users_id_lastupdater=0) {
global $DB;
if ($this->getFromDB($ID)) {
if (!$no_stat_computation
&& (Session::haveRight("global_add_tasks", "1")
|| Session::haveRight("global_add_followups", "1")
|| $this->isUser(CommonITILActor::ASSIGN, Session::getLoginUserID())
|| (isset($_SESSION["glpigroups"])
&& $this->haveAGroup(CommonITILActor::ASSIGN, $_SESSION['glpigroups'])))) {
if ($this->fields['takeintoaccount_delay_stat'] == 0) {
return $this->update(array('id' => $ID,
'takeintoaccount_delay_stat'
=> $this->computeTakeIntoAccountDelayStat(),
'_disablenotif' => true));
}
}
parent::updateDateMod($ID, $no_stat_computation, $users_id_lastupdater);
}
}
/**
* Overloaded from commonDBTM
*
* @since version 0.83
*
* @param $type itemtype of object to add
*
* @return rights
**/
function canAddItem($type) {
if (($type == 'Document')
&& ($this->getField('status') == self::CLOSED)) {
return false;
}
return parent::canAddItem($type);
}
/**
* Is the current user have right to add followups to the current ticket ?
*
* @return boolean
**/
function canAddFollowups() {
return ((Session::haveRight("add_followups","1")
&& ($this->isUser(CommonITILActor::REQUESTER, Session::getLoginUserID())
|| ($this->fields["users_id_recipient"] === Session::getLoginUserID())))
|| Session::haveRight("global_add_followups","1")
|| (Session::haveRight("group_add_followups","1")
&& isset($_SESSION["glpigroups"])
&& $this->haveAGroup(CommonITILActor::REQUESTER, $_SESSION['glpigroups']))
|| $this->isUser(CommonITILActor::ASSIGN, Session::getLoginUserID())
|| (isset($_SESSION["glpigroups"])
&& $this->haveAGroup(CommonITILActor::ASSIGN, $_SESSION['glpigroups'])));
}
/**
* Get default values to search engine to override
**/
static function getDefaultSearchRequest() {
$search = array('field' => array(0 => 12),
'searchtype' => array(0 => 'equals'),
'contains' => array(0 => 'notclosed'),
'sort' => 19,
'order' => 'DESC');
if (Session::haveRight('show_all_ticket', 1)) {
$search['contains'] = array(0 => 'notold');
}
return $search;
}
/**
* @see CommonDBTM::getSpecificMassiveActions()
**/
function getSpecificMassiveActions($checkitem=NULL) {
$isadmin = static::canUpdate();
$actions = parent::getSpecificMassiveActions($checkitem);
if (TicketFollowup::canCreate()
&& ($_SESSION['glpiactiveprofile']['interface'] == 'central')) {
$actions['add_followup'] = __('Add a new followup');
}
if (TicketTask::canCreate()) {
$actions['add_task'] = __('Add a new task');
}
if (TicketValidation::canCreate()) {
$actions['submit_validation'] = __('Approval request');
}
if (Session::haveRight("update_ticket","1")) {
$actions['add_actor'] = __('Add an actor');
$actions['link_ticket'] = _x('button', 'Link tickets');
}
if (Session::haveRight('transfer','r')
&& Session::isMultiEntitiesMode()
&& Session::haveRight("update_ticket","1")) {
$actions['add_transfer_list'] = _x('button', 'Add to transfer list');
}
return $actions;
}
/**
* @see CommonDBTM::showSpecificMassiveActionsParameters()
**/
function showSpecificMassiveActionsParameters($input=array()) {
switch ($input['action']) {
case "add_followup" :
TicketFollowup::showFormMassiveAction();
return true;
case "link_ticket" :
$rand = Ticket_Ticket::dropdownLinks('link');
printf(__('%1$s: %2$s'), __('Ticket'), __('ID'));
echo " <input type='text' name='tickets_id_1' value='' size='10'>\n";
echo "<br><br><input type='submit' name='massiveaction' class='submit' value='".
_sx('button','Post')."'>";
return true;
case "submit_validation" :
TicketValidation::showFormMassiveAction();
return true;
default :
return parent::showSpecificMassiveActionsParameters($input);
}
return false;
}
/**
* @see CommonDBTM::doSpecificMassiveActions()
**/
function doSpecificMassiveActions($input=array()) {
$res = array('ok' => 0,
'ko' => 0,
'noright' => 0);
switch ($input['action']) {
case "link_ticket" :
if (isset($input['link'])
&& isset($input['tickets_id_1'])) {
if ($this->getFromDB($input['tickets_id_1'])) {
foreach ($input["item"] as $key => $val) {
if ($val == 1) {
$input2 = array();
$input2['id'] = $input['tickets_id_1'];
$input2['_link']['tickets_id_1'] = $input['tickets_id_1'];
$input2['_link']['link'] = $input['link'];
$input2['_link']['tickets_id_2'] = $key;
if ($this->can($input['tickets_id_1'],'w')) {
if ($this->update($input2)) {
$res['ok']++;
} else {
$res['ko']++;
}
} else {
$res['noright']++;
}
}
}
}
}
break;
case "submit_validation" :
$valid = new TicketValidation();
foreach ($input["item"] as $key => $val) {
if ($val == 1) {
$input2 = array('tickets_id' => $key,
'users_id_validate' => $input['users_id_validate'],
'comment_submission' => $input['comment_submission']);
if ($valid->can(-1,'w',$input2)) {
if ($valid->add($input2)) {
$res['ok']++;
} else {
$res['ko']++;
}
} else {
$res['noright']++;
}
}
}
break;
case "add_followup" :
$fup = new TicketFollowup();
foreach ($input["item"] as $key => $val) {
if ($val == 1) {
$input2 = array('tickets_id' => $key,
'is_private' => $input['is_private'],
'requesttypes_id' => $input['requesttypes_id'],
'content' => $input['content']);
if ($fup->can(-1,'w',$input2)) {
if ($fup->add($input2)) {
$res['ok']++;
} else {
$res['ko']++;
}
} else {
$res['noright']++;
}
}
}
break;
default :
return parent::doSpecificMassiveActions($input);
}
return $res;
}
function getSearchOptions() {
$tab = array();
$tab['common'] = __('Characteristics');
$tab[1]['table'] = $this->getTable();
$tab[1]['field'] = 'name';
$tab[1]['name'] = __('Title');
$tab[1]['searchtype'] = 'contains';
$tab[1]['datatype'] = 'itemlink';
$tab[1]['massiveaction'] = false;
$tab[21]['table'] = $this->getTable();
$tab[21]['field'] = 'content';
$tab[21]['name'] = __('Description');
$tab[21]['massiveaction'] = false;
$tab[21]['datatype'] = 'text';
$tab[2]['table'] = $this->getTable();
$tab[2]['field'] = 'id';
$tab[2]['name'] = __('ID');
$tab[2]['massiveaction'] = false;
$tab[2]['datatype'] = 'number';
$tab[12]['table'] = $this->getTable();
$tab[12]['field'] = 'status';
$tab[12]['name'] = __('Status');
$tab[12]['searchtype'] = 'equals';
$tab[12]['datatype'] = 'specific';
$tab[14]['table'] = $this->getTable();
$tab[14]['field'] = 'type';
$tab[14]['name'] = __('Type');
$tab[14]['searchtype'] = 'equals';
$tab[14]['datatype'] = 'specific';
$tab[10]['table'] = $this->getTable();
$tab[10]['field'] = 'urgency';
$tab[10]['name'] = __('Urgency');
$tab[10]['searchtype'] = 'equals';
$tab[10]['datatype'] = 'specific';
$tab[11]['table'] = $this->getTable();
$tab[11]['field'] = 'impact';
$tab[11]['name'] = __('Impact');
$tab[11]['searchtype'] = 'equals';
$tab[11]['datatype'] = 'specific';
$tab[3]['table'] = $this->getTable();
$tab[3]['field'] = 'priority';
$tab[3]['name'] = __('Priority');
$tab[3]['searchtype'] = 'equals';
$tab[3]['datatype'] = 'specific';
$tab[15]['table'] = $this->getTable();
$tab[15]['field'] = 'date';
$tab[15]['name'] = __('Opening date');
$tab[15]['datatype'] = 'datetime';
$tab[15]['massiveaction'] = false;
$tab[16]['table'] = $this->getTable();
$tab[16]['field'] = 'closedate';
$tab[16]['name'] = __('Closing date');
$tab[16]['datatype'] = 'datetime';
$tab[16]['massiveaction'] = false;
$tab[18]['table'] = $this->getTable();
$tab[18]['field'] = 'due_date';
$tab[18]['name'] = __('Due date');
$tab[18]['datatype'] = 'datetime';
$tab[18]['maybefuture'] = true;
$tab[18]['massiveaction'] = false;
$tab[151]['table'] = $this->getTable();
$tab[151]['field'] = 'due_date';
$tab[151]['name'] = __('Due date + Progress');
$tab[151]['massiveaction'] = false;
$tab[151]['nosearch'] = true;
$tab[82]['table'] = $this->getTable();
$tab[82]['field'] = 'is_late';
$tab[82]['name'] = __('Late');
$tab[82]['datatype'] = 'bool';
$tab[82]['massiveaction'] = false;
$tab[17]['table'] = $this->getTable();
$tab[17]['field'] = 'solvedate';
$tab[17]['name'] = __('Resolution date');
$tab[17]['datatype'] = 'datetime';
$tab[17]['massiveaction'] = false;
$tab[19]['table'] = $this->getTable();
$tab[19]['field'] = 'date_mod';
$tab[19]['name'] = __('Last update');
$tab[19]['datatype'] = 'datetime';
$tab[19]['massiveaction'] = false;
$tab[7]['table'] = 'glpi_itilcategories';
$tab[7]['field'] = 'completename';
$tab[7]['name'] = __('Category');
$tab[7]['datatype'] = 'dropdown';
if (!Session::isCron() // no filter for cron
&& isset($_SESSION['glpiactiveprofile']['interface'])
&& $_SESSION['glpiactiveprofile']['interface'] == 'helpdesk') {
$tab[7]['condition'] = "`is_helpdeskvisible`='1'";
}
$tab[13]['table'] = $this->getTable();
$tab[13]['field'] = 'items_id';
$tab[13]['name'] = __('Associated element');
$tab[13]['datatype'] = 'specific';
$tab[13]['nosearch'] = true;
$tab[13]['nosort'] = true;
$tab[13]['massiveaction'] = false;
$tab[13]['additionalfields'] = array('itemtype');
$tab[131]['table'] = $this->getTable();
$tab[131]['field'] = 'itemtype';
$tab[131]['name'] = __('Associated item type');
$tab[131]['datatype'] = 'itemtypename';
$tab[131]['itemtype_list'] = 'ticket_types';
$tab[131]['nosort'] = true;
$tab[131]['massiveaction'] = false;
$tab[9]['table'] = 'glpi_requesttypes';
$tab[9]['field'] = 'name';
$tab[9]['name'] = __('Request source');
$tab[9]['datatype'] = 'dropdown';
// Can't use Location::getSearchOptionsToAdd because id conflicts
$tab[83]['table'] = 'glpi_locations';
$tab[83]['field'] = 'completename';
$tab[83]['name'] = __('Location');
$tab[83]['datatype'] = 'dropdown';
$tab[80]['table'] = 'glpi_entities';
$tab[80]['field'] = 'completename';
$tab[80]['name'] = __('Entity');
$tab[80]['massiveaction'] = false;
$tab[80]['datatype'] = 'dropdown';
$tab[45]['table'] = $this->getTable();
$tab[45]['field'] = 'actiontime';
$tab[45]['name'] = __('Total duration');
$tab[45]['datatype'] = 'timestamp';
$tab[45]['withdays'] = false;
$tab[45]['massiveaction'] = false;
$tab[45]['nosearch'] = true;
$tab[64]['table'] = 'glpi_users';
$tab[64]['field'] = 'name';
$tab[64]['linkfield'] = 'users_id_lastupdater';
$tab[64]['name'] = __('Last updater');
$tab[64]['massiveaction'] = false;
$tab[64]['datatype'] = 'dropdown';
$tab[64]['right'] = 'all';
$tab += $this->getSearchOptionsActors();
$tab['sla'] = __('SLA');
$tab[30]['table'] = 'glpi_slas';
$tab[30]['field'] = 'name';
$tab[30]['name'] = __('SLA');
$tab[30]['massiveaction'] = false;
$tab[30]['datatype'] = 'dropdown';
$tab[32]['table'] = 'glpi_slalevels';
$tab[32]['field'] = 'name';
$tab[32]['name'] = __('Escalation level');
$tab[32]['massiveaction'] = false;
$tab[32]['datatype'] = 'dropdown';
$tab['validation'] = __('Approval');
$tab[52]['table'] = $this->getTable();
$tab[52]['field'] = 'global_validation';
$tab[52]['name'] = __('Approval');
$tab[52]['searchtype'] = 'equals';
$tab[52]['datatype'] = 'specific';
$tab[53]['table'] = 'glpi_ticketvalidations';
$tab[53]['field'] = 'comment_submission';
$tab[53]['name'] = sprintf(__('%1$s: %2$s'), __('Request'), __('Comments'));
$tab[53]['datatype'] = 'text';
$tab[53]['forcegroupby'] = true;
$tab[53]['massiveaction'] = false;
$tab[53]['joinparams'] = array('jointype' => 'child');
$tab[54]['table'] = 'glpi_ticketvalidations';
$tab[54]['field'] = 'comment_validation';
$tab[54]['name'] = sprintf(__('%1$s: %2$s'), __('Approval'), __('Comments'));
$tab[54]['datatype'] = 'text';
$tab[54]['forcegroupby'] = true;
$tab[54]['massiveaction'] = false;
$tab[54]['joinparams'] = array('jointype' => 'child');
$tab[55]['table'] = 'glpi_ticketvalidations';
$tab[55]['field'] = 'status';
$tab[55]['datatype'] = 'specific';
$tab[55]['name'] = sprintf(__('%1$s: %2$s'), __('Approval'), __('Status'));
$tab[55]['searchtype'] = 'equals';
$tab[55]['forcegroupby'] = true;
$tab[55]['massiveaction'] = false;
$tab[55]['joinparams'] = array('jointype' => 'child');
$tab[56]['table'] = 'glpi_ticketvalidations';
$tab[56]['field'] = 'submission_date';
$tab[56]['name'] = sprintf(__('%1$s: %2$s'), __('Request'), __('Date'));
$tab[56]['datatype'] = 'datetime';
$tab[56]['forcegroupby'] = true;
$tab[56]['massiveaction'] = false;
$tab[56]['joinparams'] = array('jointype' => 'child');
$tab[57]['table'] = 'glpi_ticketvalidations';
$tab[57]['field'] = 'validation_date';
$tab[57]['name'] = sprintf(__('%1$s: %2$s'), __('Approval'), __('Date'));
$tab[57]['datatype'] = 'datetime';
$tab[57]['forcegroupby'] = true;
$tab[57]['massiveaction'] = false;
$tab[57]['joinparams'] = array('jointype' => 'child');
$tab[58]['table'] = 'glpi_users';
$tab[58]['field'] = 'name';
$tab[58]['name'] = __('Requester');
$tab[58]['datatype'] = 'itemlink';
$tab[58]['right'] = array('create_incident_validation',
'create_request_validation');
$tab[58]['forcegroupby'] = true;
$tab[58]['massiveaction'] = false;
$tab[58]['joinparams'] = array('beforejoin'
=> array('table' => 'glpi_ticketvalidations',
'joinparams' => array('jointype' => 'child')));
$tab[59]['table'] = 'glpi_users';
$tab[59]['field'] = 'name';
$tab[59]['linkfield'] = 'users_id_validate';
$tab[59]['name'] = __('Approver');
$tab[59]['datatype'] = 'itemlink';
$tab[59]['right'] = array('validate_request', 'validate_incident');
$tab[59]['forcegroupby'] = true;
$tab[59]['massiveaction'] = false;
$tab[59]['joinparams'] = array('beforejoin'
=> array('table' => 'glpi_ticketvalidations',
'joinparams' => array('jointype' => 'child')));
$tab['satisfaction'] = __('Satisfaction survey');
$tab[31]['table'] = 'glpi_ticketsatisfactions';
$tab[31]['field'] = 'type';
$tab[31]['name'] = __('Type');
$tab[31]['massiveaction'] = false;
$tab[31]['searchtype'] = 'equals';
$tab[31]['joinparams'] = array('jointype' => 'child');
$tab[31]['datatype'] = 'specific';
$tab[60]['table'] = 'glpi_ticketsatisfactions';
$tab[60]['field'] = 'date_begin';
$tab[60]['name'] = __('Creation date');
$tab[60]['datatype'] = 'datetime';
$tab[60]['massiveaction'] = false;
$tab[60]['joinparams'] = array('jointype' => 'child');
$tab[61]['table'] = 'glpi_ticketsatisfactions';
$tab[61]['field'] = 'date_answered';
$tab[61]['name'] = __('Response date');
$tab[61]['datatype'] = 'datetime';
$tab[61]['massiveaction'] = false;
$tab[61]['joinparams'] = array('jointype' => 'child');
$tab[62]['table'] = 'glpi_ticketsatisfactions';
$tab[62]['field'] = 'satisfaction';
$tab[62]['name'] = __('Satisfaction');
$tab[62]['datatype'] = 'number';
$tab[62]['massiveaction'] = false;
$tab[62]['joinparams'] = array('jointype' => 'child');
$tab[63]['table'] = 'glpi_ticketsatisfactions';
$tab[63]['field'] = 'comment';
$tab[63]['name'] = __('Comments');
$tab[63]['datatype'] = 'text';
$tab[63]['massiveaction'] = false;
$tab[63]['joinparams'] = array('jointype' => 'child');
$tab['followup'] = _n('Followup', 'Followups', 2);
$followup_condition = '';
if (!Session::haveRight('show_full_ticket', 1)) {
$followup_condition = "AND (`NEWTABLE`.`is_private` = '0'
OR `NEWTABLE`.`users_id` = '".Session::getLoginUserID()."')";
}
$tab[25]['table'] = 'glpi_ticketfollowups';
$tab[25]['field'] = 'content';
$tab[25]['name'] = __('Description');
$tab[25]['forcegroupby'] = true;
$tab[25]['splititems'] = true;
$tab[25]['massiveaction'] = false;
$tab[25]['joinparams'] = array('jointype' => 'child',
'condition' => $followup_condition);
$tab[25]['datatype'] = 'text';
$tab[27]['table'] = 'glpi_ticketfollowups';
$tab[27]['field'] = 'count';
$tab[27]['name'] = __('Number of followups');
$tab[27]['forcegroupby'] = true;
$tab[27]['usehaving'] = true;
$tab[27]['datatype'] = 'number';
$tab[27]['massiveaction'] = false;
$tab[27]['joinparams'] = array('jointype' => 'child',
'condition' => $followup_condition);
$tab[29]['table'] = 'glpi_requesttypes';
$tab[29]['field'] = 'name';
$tab[29]['name'] = __('Request source');
$tab[29]['datatype'] = 'dropdown';
$tab[29]['forcegroupby'] = true;
$tab[29]['massiveaction'] = false;
$tab[29]['joinparams'] = array('beforejoin'
=> array('table'
=> 'glpi_ticketfollowups',
'joinparams'
=> array('jointype' => 'child',
'condition' => $followup_condition)));
$tab[91]['table'] = 'glpi_ticketfollowups';
$tab[91]['field'] = 'is_private';
$tab[91]['name'] = __('Private followup');
$tab[91]['datatype'] = 'bool';
$tab[91]['forcegroupby'] = true;
$tab[91]['splititems'] = true;
$tab[91]['massiveaction'] = false;
$tab[91]['joinparams'] = array('jointype' => 'child',
'condition' => $followup_condition);
$tab[93]['table'] = 'glpi_users';
$tab[93]['field'] = 'name';
$tab[93]['name'] = __('Writer');
$tab[93]['datatype'] = 'itemlink';
$tab[93]['right'] = 'all';
$tab[93]['forcegroupby'] = true;
$tab[93]['massiveaction'] = false;
$tab[93]['joinparams'] = array('beforejoin'
=> array('table'
=> 'glpi_ticketfollowups',
'joinparams'
=> array('jointype' => 'child',
'condition' => $followup_condition)));
$tab += $this->getSearchOptionsStats();
$tab[150]['table'] = $this->getTable();
$tab[150]['field'] = 'takeintoaccount_delay_stat';
$tab[150]['name'] = __('Take into account time');
$tab[150]['datatype'] = 'timestamp';
$tab[150]['forcegroupby'] = true;
$tab[150]['massiveaction'] = false;
if (Session::haveRight("show_all_ticket","1")
|| Session::haveRight("show_assign_ticket","1")
|| Session::haveRight("own_ticket","1")) {
$tab['linktickets'] = _n('Linked ticket', 'Linked tickets', 2);
$tab[40]['table'] = 'glpi_tickets';
$tab[40]['field'] = 'name';
$tab[40]['name'] = __('All linked tickets');
$tab[40]['massiveaction'] = false;
$tab[40]['joinparams'] = array('jointype'
=> 'item_item_revert',
'condition'
=> "AND NEWTABLE.`id` <> `glpi_tickets`.`id`",
'beforejoin'
=> array('table'
=> 'glpi_tickets_tickets',
'joinparams'
=> array('jointype' => 'item_item')));
$tab[40]['datatype'] = 'dropdown';
$tab[40]['forcegroupby'] = true;
$tab[47]['table'] = 'glpi_tickets';
$tab[47]['field'] = 'name';
$tab[47]['name'] = __('Duplicated tickets');
$tab[47]['massiveaction'] = false;
$tab[47]['joinparams'] = array('jointype'
=> 'item_item_revert',
'condition'
=> "AND NEWTABLE.`id` <> `glpi_tickets`.`id`",
'beforejoin'
=> array('table'
=> 'glpi_tickets_tickets',
'joinparams'
=> array('jointype'
=> 'item_item',
'condition'
=> "AND NEWTABLE.`link` = ".
Ticket_Ticket::DUPLICATE_WITH)));
$tab[47]['datatype'] = 'dropdown';
$tab[47]['forcegroupby'] = true;
$tab[41]['table'] = 'glpi_tickets_tickets';
$tab[41]['field'] = 'count';
$tab[41]['name'] = __('Number of all linked tickets');
$tab[41]['massiveaction'] = false;
$tab[41]['datatype'] = 'number';
$tab[41]['usehaving'] = true;
$tab[41]['joinparams'] = array('jointype' => 'item_item');
$tab[46]['table'] = 'glpi_tickets_tickets';
$tab[46]['field'] = 'count';
$tab[46]['name'] = __('Number of duplicated tickets');
$tab[46]['massiveaction'] = false;
$tab[46]['datatype'] = 'number';
$tab[46]['usehaving'] = true;
$tab[46]['joinparams'] = array('jointype' => 'item_item',
'condition' => "AND NEWTABLE.`link` = ".
Ticket_Ticket::DUPLICATE_WITH);
$tab['task'] = _n('Task', 'Tasks', 2);
$tab[26]['table'] = 'glpi_tickettasks';
$tab[26]['field'] = 'content';
$tab[26]['name'] = __('Description');
$tab[26]['datatype'] = 'text';
$tab[26]['forcegroupby'] = true;
$tab[26]['splititems'] = true;
$tab[26]['massiveaction'] = false;
$tab[26]['joinparams'] = array('jointype' => 'child');
$tab[28]['table'] = 'glpi_tickettasks';
$tab[28]['field'] = 'count';
$tab[28]['name'] = __('Number of tasks');
$tab[28]['forcegroupby'] = true;
$tab[28]['usehaving'] = true;
$tab[28]['datatype'] = 'number';
$tab[28]['massiveaction'] = false;
$tab[28]['joinparams'] = array('jointype' => 'child');
$tab[20]['table'] = 'glpi_taskcategories';
$tab[20]['field'] = 'name';
$tab[20]['datatype'] = 'dropdown';
$tab[20]['name'] = __('Task category');
$tab[20]['forcegroupby'] = true;
$tab[20]['splititems'] = true;
$tab[20]['massiveaction'] = false;
$tab[20]['joinparams'] = array('beforejoin'
=> array('table' => 'glpi_tickettasks',
'joinparams' => array('jointype' => 'child')));
$tab[92]['table'] = 'glpi_tickettasks';
$tab[92]['field'] = 'is_private';
$tab[92]['name'] = __('Private task');
$tab[92]['datatype'] = 'bool';
$tab[92]['forcegroupby'] = true;
$tab[92]['splititems'] = true;
$tab[92]['massiveaction'] = false;
$tab[92]['joinparams'] = array('jointype' => 'child');
$tab[94]['table'] = 'glpi_users';
$tab[94]['field'] = 'name';
$tab[94]['name'] = __('Writer');
$tab[94]['datatype'] = 'itemlink';
$tab[94]['right'] = 'all';
$tab[94]['forcegroupby'] = true;
$tab[94]['massiveaction'] = false;
$tab[94]['joinparams'] = array('beforejoin'
=> array('table' => 'glpi_tickettasks',
'joinparams' => array('jointype' => 'child')));
$tab[95]['table'] = 'glpi_users';
$tab[95]['field'] = 'name';
$tab[95]['linkfield'] = 'users_id_tech';
$tab[95]['name'] = __('Technician');
$tab[95]['datatype'] = 'itemlink';
$tab[95]['right'] = 'own_ticket';
$tab[95]['forcegroupby'] = true;
$tab[95]['massiveaction'] = false;
$tab[95]['joinparams'] = array('beforejoin'
=> array('table' => 'glpi_tickettasks',
'joinparams' => array('jointype' => 'child')));
$tab[96]['table'] = 'glpi_tickettasks';
$tab[96]['field'] = 'actiontime';
$tab[96]['name'] = __('Duration');
$tab[96]['datatype'] = 'timestamp';
$tab[96]['massiveaction'] = false;
$tab[96]['forcegroupby'] = true;
$tab[96]['joinparams'] = array('jointype' => 'child');
$tab[97]['table'] = 'glpi_tickettasks';
$tab[97]['field'] = 'date';
$tab[97]['name'] = __('Date');
$tab[97]['datatype'] = 'datetime';
$tab[97]['massiveaction'] = false;
$tab[97]['forcegroupby'] = true;
$tab[97]['joinparams'] = array('jointype' => 'child');
$tab[33]['table'] = 'glpi_tickettasks';
$tab[33]['field'] = 'state';
$tab[33]['name'] = __('Status');
$tab[33]['datatype'] = 'specific';
$tab[33]['searchtype'] = 'equals';
$tab[33]['searchequalsonfield'] = true;
$tab[33]['massiveaction'] = false;
$tab[33]['forcegroupby'] = true;
$tab[33]['joinparams'] = array('jointype' => 'child');
$tab['solution'] = _n('Solution', 'Solutions', 1);
$tab[23]['table'] = 'glpi_solutiontypes';
$tab[23]['field'] = 'name';
$tab[23]['name'] = __('Solution type');
$tab[23]['datatype'] = 'dropdown';
$tab[24]['table'] = $this->getTable();
$tab[24]['field'] = 'solution';
$tab[24]['name'] = _n('Solution', 'Solutions', 1);
$tab[24]['datatype'] = 'text';
$tab[24]['htmltext'] = true;
$tab[24]['massiveaction'] = false;
$tab['cost'] = __('Cost');
$tab[48]['table'] = 'glpi_ticketcosts';
$tab[48]['field'] = 'totalcost';
$tab[48]['name'] = __('Total cost');
$tab[48]['datatype'] = 'decimal';
$tab[48]['forcegroupby'] = true;
$tab[48]['usehaving'] = true;
$tab[48]['massiveaction'] = false;
$tab[48]['joinparams'] = array('jointype' => 'child');
$tab[42]['table'] = 'glpi_ticketcosts';
$tab[42]['field'] = 'cost_time';
$tab[42]['name'] = __('Time cost');
$tab[42]['datatype'] = 'decimal';
$tab[42]['forcegroupby'] = true;
$tab[42]['massiveaction'] = false;
$tab[42]['joinparams'] = array('jointype' => 'child');
$tab[49]['table'] = 'glpi_ticketcosts';
$tab[49]['field'] = 'actiontime';
$tab[49]['name'] = sprintf(__('%1$s - %2$s'), __('Cost'), __('Duration'));
$tab[49]['datatype'] = 'timestamp';
$tab[49]['forcegroupby'] = true;
$tab[49]['massiveaction'] = false;
$tab[49]['joinparams'] = array('jointype' => 'child');
$tab[43]['table'] = 'glpi_ticketcosts';
$tab[43]['field'] = 'cost_fixed';
$tab[43]['name'] = __('Fixed cost');
$tab[43]['datatype'] = 'decimal';
$tab[43]['forcegroupby'] = true;
$tab[43]['massiveaction'] = false;
$tab[43]['joinparams'] = array('jointype' => 'child');
$tab[44]['table'] = 'glpi_ticketcosts';
$tab[44]['field'] = 'cost_material';
$tab[44]['name'] = __('Material cost');
$tab[44]['datatype'] = 'decimal';
$tab[44]['forcegroupby'] = true;
$tab[44]['massiveaction'] = false;
$tab[44]['joinparams'] = array('jointype' => 'child');
$tab['problem'] = Problem::getTypeName(2);
$tab[141]['table'] = 'glpi_problems_tickets';
$tab[141]['field'] = 'count';
$tab[141]['name'] = __('Number of problems');
$tab[141]['forcegroupby'] = true;
$tab[141]['usehaving'] = true;
$tab[141]['datatype'] = 'number';
$tab[141]['massiveaction'] = false;
$tab[141]['joinparams'] = array('jointype' => 'child');
}
// Filter search fields for helpdesk
if (!Session::isCron() // no filter for cron
&& (!isset($_SESSION['glpiactiveprofile']['interface'])
|| ($_SESSION['glpiactiveprofile']['interface'] == 'helpdesk'))) {
$tokeep = array('common', 'requester');
if (Session::haveRight('validate_request',1)
|| Session::haveRight('validate_incident',1)
|| Session::haveRight('create_incident_validation',1)
|| Session::haveRight('create_request_validation',1)) {
$tokeep[] = 'validation';
}
$keep = false;
foreach ($tab as $key => $val) {
if (!is_array($val)) {
$keep = in_array($key, $tokeep);
}
if (!$keep) {
if (is_array($val)) {
$tab[$key]['nosearch'] = true;
}
}
}
// last updater no search
$tab[64]['nosearch'] = true;
}
return $tab;
}
/**
* @since version 0.84
*
* @param $field
* @param $values
* @param $options array
**/
static function getSpecificValueToDisplay($field, $values, array $options=array()) {
if (!is_array($values)) {
$values = array($field => $values);
}
switch ($field) {
case 'global_validation' :
return TicketValidation::getStatus($values[$field]);
case 'type':
return self::getTicketTypeName($values[$field]);
case 'items_id':
if (isset($values['itemtype'])) {
if (isset($options['comments']) && $options['comments']) {
$tmp = Dropdown::getDropdownName(getTableForItemtype($values['itemtype']),
$values[$field], 1);
return sprintf(__('%1$s %2$s'), $tmp['name'],
Html::showToolTip($tmp['comment'], array('display' => false)));
}
return Dropdown::getDropdownName(getTableForItemtype($values['itemtype']),
$values[$field]);
}
break;
}
return parent::getSpecificValueToDisplay($field, $values, $options);
}
/**
* @since version 0.84
*
* @param $field
* @param $name (default '')
* @param $values (default '')
* @param $options array
*
* @return string
**/
static function getSpecificValueToSelect($field, $name='', $values='', array $options=array()) {
if (!is_array($values)) {
$values = array($field => $values);
}
$options['display'] = false;
switch ($field) {
case 'items_id' :
if (isset($values['itemtype']) && !empty($values['itemtype'])) {
$options['name'] = $name;
$options['value'] = $values[$field];
return Dropdown::show($values['itemtype'], $options);
}
break;
case 'type':
$options['value'] = $values[$field];
return self::dropdownType($name, $options);
case 'global_validation' :
$options['global'] = true;
$options['value'] = $values[$field];
return TicketValidation::dropdownStatus($name, $options);
}
return parent::getSpecificValueToSelect($field, $name, $values, $options);
}
/**
* Dropdown of ticket type
*
* @param $name select name
* @param $options array of options:
* - value : integer / preselected value (default 0)
* - toadd : array / array of specific values to add at the begining
* - on_change : string / value to transmit to "onChange"
* - display : boolean / display or get string (default true)
*
* @return string id of the select
**/
static function dropdownType($name, $options=array()) {
$params['value'] = 0;
$params['toadd'] = array();
$params['on_change'] = '';
$params['display'] = true;
if (is_array($options) && count($options)) {
foreach ($options as $key => $val) {
$params[$key] = $val;
}
}
$items = array();
if (count($params['toadd']) > 0) {
$items = $params['toadd'];
}
$items += self::getTypes();
return Dropdown::showFromArray($name, $items, $params);
}
/**
* Get ticket types
*
* @return array of types
**/
static function getTypes() {
$options[self::INCIDENT_TYPE] = __('Incident');
$options[self::DEMAND_TYPE] = __('Request');
return $options;
}
/**
* Get ticket type Name
*
* @param $value type ID
**/
static function getTicketTypeName($value) {
switch ($value) {
case self::INCIDENT_TYPE :
return __('Incident');
case self::DEMAND_TYPE :
return __('Request');
default :
// Return $value if not defined
return $value;
}
}
/**
* get the Ticket status list
*
* @param $withmetaforsearch boolean (false by default)
*
* @return an array
**/
static function getAllStatusArray($withmetaforsearch=false) {
// To be overridden by class
$tab = array(self::INCOMING => _x('ticket', 'New'),
self::ASSIGNED => __('Processing (assigned)'),
self::PLANNED => __('Processing (planned)'),
self::WAITING => __('Pending'),
self::SOLVED => __('Solved'),
self::CLOSED => __('Closed'));
if ($withmetaforsearch) {
$tab['notold'] = __('Not solved');
$tab['notclosed'] = __('Not closed');
$tab['process'] = __('Processing');
$tab['old'] = __('Solved + Closed');
$tab['all'] = __('All');
}
return $tab;
}
/**
* Get the ITIL object closed status list
*
* @since version 0.83
*
* @return an array
**/
static function getClosedStatusArray() {
return array(self::CLOSED);
}
/**
* Get the ITIL object solved status list
*
* @since version 0.83
*
* @return an array
**/
static function getSolvedStatusArray() {
return array(self::SOLVED);
}
/**
* Get the ITIL object new status list
*
* @since version 0.83.8
*
* @return an array
**/
static function getNewStatusArray() {
return array(self::INCOMING);
}
/**
* Get the ITIL object assign or plan status list
*
* @since version 0.83
*
* @return an array
**/
static function getProcessStatusArray() {
return array(self::ASSIGNED, self::PLANNED);
}
/**
* Make a select box for Ticket my devices
*
* @param $userID User ID for my device section (default 0)
* @param $entity_restrict restrict to a specific entity (default -1)
* @param $itemtype of selected item (default 0)
* @param $items_id of selected item (default 0)
*
* @return nothing (print out an HTML select box)
**/
static function dropdownMyDevices($userID=0, $entity_restrict=-1, $itemtype=0, $items_id=0) {
global $DB, $CFG_GLPI;
if ($userID == 0) {
$userID = Session::getLoginUserID();
}
$rand = mt_rand();
$already_add = array();
if ($_SESSION["glpiactiveprofile"]["helpdesk_hardware"]&pow(2, self::HELPDESK_MY_HARDWARE)) {
$my_devices = "";
$my_item = $itemtype.'_'.$items_id;
// My items
foreach ($CFG_GLPI["linkuser_types"] as $itemtype) {
if (($item = getItemForItemtype($itemtype))
&& parent::isPossibleToAssignType($itemtype)) {
$itemtable = getTableForItemType($itemtype);
$query = "SELECT *
FROM `$itemtable`
WHERE `users_id` = '$userID'";
if ($item->maybeDeleted()) {
$query .= " AND `is_deleted` = '0' ";
}
if ($item->maybeTemplate()) {
$query .= " AND `is_template` = '0' ";
}
if (in_array($itemtype,$CFG_GLPI["helpdesk_visible_types"])) {
$query .= " AND `is_helpdesk_visible` = '1' ";
}
$query .= getEntitiesRestrictRequest("AND",$itemtable,"",$entity_restrict,
$item->maybeRecursive())."
ORDER BY `name` ";
$result = $DB->query($query);
$nb = $DB->numrows($result);
if ($DB->numrows($result) > 0) {
$type_name = $item->getTypeName($nb);
while ($data = $DB->fetch_assoc($result)) {
$output = $data["name"];
if (empty($output) || $_SESSION["glpiis_ids_visible"]) {
$output = sprintf(__('%1$s (%2$s)'), $output, $data['id']);
}
$output = sprintf(__('%1$s - %2$s'), $type_name, $output);
if ($itemtype != 'Software') {
if (!empty($data['serial'])) {
$output = sprintf(__('%1$s - %2$s'), $output, $data['serial']);
}
if (!empty($data['otherserial'])) {
$output = sprintf(__('%1$s - %2$s'), $output, $data['otherserial']);
}
}
$my_devices .= "<option title=\"$output\" value='".$itemtype."_".$data["id"].
"' ".(($my_item == $itemtype."_".$data["id"])?"selected":"").">".
Toolbox::substr($output, 0,
$_SESSION["glpidropdown_chars_limit"]).
"</option>";
$already_add[$itemtype][] = $data["id"];
}
}
}
}
if (!empty($my_devices)) {
$my_devices = "<optgroup label=\"".__s('My devices')."\">".$my_devices."</optgroup>";
}
// My group items
if (Session::haveRight("show_group_hardware","1")) {
$group_where = "";
$query = "SELECT `glpi_groups_users`.`groups_id`, `glpi_groups`.`name`
FROM `glpi_groups_users`
LEFT JOIN `glpi_groups`
ON (`glpi_groups`.`id` = `glpi_groups_users`.`groups_id`)
WHERE `glpi_groups_users`.`users_id` = '$userID' ".
getEntitiesRestrictRequest("AND", "glpi_groups", "",
$entity_restrict, true);
$result = $DB->query($query);
$first = true;
if ($DB->numrows($result) > 0) {
while ($data = $DB->fetch_assoc($result)) {
if ($first) {
$first = false;
} else {
$group_where .= " OR ";
}
$a_groups = getAncestorsOf("glpi_groups", $data["groups_id"]);
$a_groups[$data["groups_id"]] = $data["groups_id"];
$group_where .= " `groups_id` IN (".implode(',', $a_groups).") ";
}
$tmp_device = "";
foreach ($CFG_GLPI["linkgroup_types"] as $itemtype) {
if (($item = getItemForItemtype($itemtype))
&& parent::isPossibleToAssignType($itemtype)) {
$itemtable = getTableForItemType($itemtype);
$query = "SELECT *
FROM `$itemtable`
WHERE ($group_where) ".
getEntitiesRestrictRequest("AND", $itemtable, "",
$entity_restrict,
$item->maybeRecursive());
if ($item->maybeDeleted()) {
$query .= " AND `is_deleted` = '0' ";
}
if ($item->maybeTemplate()) {
$query .= " AND `is_template` = '0' ";
}
$result = $DB->query($query);
if ($DB->numrows($result) > 0) {
$type_name = $item->getTypeName();
if (!isset($already_add[$itemtype])) {
$already_add[$itemtype] = array();
}
while ($data = $DB->fetch_assoc($result)) {
if (!in_array($data["id"], $already_add[$itemtype])) {
$output = '';
if (isset($data["name"])) {
$output = $data["name"];
}
if (empty($output) || $_SESSION["glpiis_ids_visible"]) {
$output = sprintf(__('%1$s (%2$s)'), $output, $data['id']);
}
$output = sprintf(__('%1$s - %2$s'), $type_name, $output);
if (isset($data['serial'])) {
$output = sprintf(__('%1$s - %2$s'), $output, $data['serial']);
}
if (isset($data['otherserial'])) {
$output = sprintf(__('%1$s - %2$s'), $output, $data['otherserial']);
}
$tmp_device .= "<option title=\"$output\" value='".$itemtype."_".
$data["id"]."' ".
(($my_item == $itemtype."_".$data["id"])?"selected"
:"").">".
Toolbox::substr($output,0,
$_SESSION["glpidropdown_chars_limit"]).
"</option>";
$already_add[$itemtype][] = $data["id"];
}
}
}
}
}
if (!empty($tmp_device)) {
$my_devices .= "<optgroup label=\"".__s('Devices own by my groups')."\">".
$tmp_device."</optgroup>";
}
}
}
// Get linked items to computers
if (isset($already_add['Computer']) && count($already_add['Computer'])) {
$search_computer = " XXXX IN (".implode(',',$already_add['Computer']).') ';
$tmp_device = "";
// Direct Connection
$types = array('Monitor', 'Peripheral', 'Phone', 'Printer');
foreach ($types as $itemtype) {
if (in_array($itemtype,$_SESSION["glpiactiveprofile"]["helpdesk_item_type"])
&& ($item = getItemForItemtype($itemtype))) {
$itemtable = getTableForItemType($itemtype);
if (!isset($already_add[$itemtype])) {
$already_add[$itemtype] = array();
}
$query = "SELECT DISTINCT `$itemtable`.*
FROM `glpi_computers_items`
LEFT JOIN `$itemtable`
ON (`glpi_computers_items`.`items_id` = `$itemtable`.`id`)
WHERE `glpi_computers_items`.`itemtype` = '$itemtype'
AND ".str_replace("XXXX","`glpi_computers_items`.`computers_id`",
$search_computer);
if ($item->maybeDeleted()) {
$query .= " AND `$itemtable`.`is_deleted` = '0' ";
}
if ($item->maybeTemplate()) {
$query .= " AND `$itemtable`.`is_template` = '0' ";
}
$query .= getEntitiesRestrictRequest("AND",$itemtable,"",$entity_restrict)."
ORDER BY `$itemtable`.`name`";
$result = $DB->query($query);
if ($DB->numrows($result) > 0) {
$type_name = $item->getTypeName();
while ($data = $DB->fetch_assoc($result)) {
if (!in_array($data["id"],$already_add[$itemtype])) {
$output = $data["name"];
if (empty($output) || $_SESSION["glpiis_ids_visible"]) {
$output = sprintf(__('%1$s (%2$s)'), $output, $data['id']);
}
$output = sprintf(__('%1$s - %2$s'), $type_name, $output);
if ($itemtype != 'Software') {
$output = sprintf(__('%1$s - %2$s'), $output, $data['otherserial']);
}
$tmp_device .= "<option title=\"$output\" value='".$itemtype."_".
$data["id"]."' ".
($my_item==$itemtype."_".$data["id"]?"selected":"").">".
Toolbox::substr($output,0,
$_SESSION["glpidropdown_chars_limit"]).
"</option>";
$already_add[$itemtype][] = $data["id"];
}
}
}
}
}
if (!empty($tmp_device)) {
$my_devices .= "<optgroup label=\"".__s('Connected devices')."\">".$tmp_device.
"</optgroup>";
}
// Software
if (in_array('Software', $_SESSION["glpiactiveprofile"]["helpdesk_item_type"])) {
$query = "SELECT DISTINCT `glpi_softwareversions`.`name` AS version,
`glpi_softwares`.`name` AS name, `glpi_softwares`.`id`
FROM `glpi_computers_softwareversions`, `glpi_softwares`,
`glpi_softwareversions`
WHERE `glpi_computers_softwareversions`.`softwareversions_id` =
`glpi_softwareversions`.`id`
AND `glpi_softwareversions`.`softwares_id` = `glpi_softwares`.`id`
AND ".str_replace("XXXX",
"`glpi_computers_softwareversions`.`computers_id`",
$search_computer)."
AND `glpi_softwares`.`is_helpdesk_visible` = '1' ".
getEntitiesRestrictRequest("AND","glpi_softwares","",
$entity_restrict)."
ORDER BY `glpi_softwares`.`name`";
$result = $DB->query($query);
if ($DB->numrows($result) > 0) {
$tmp_device = "";
$item = new Software();
$type_name = $item->getTypeName();
if (!isset($already_add['Software'])) {
$already_add['Software'] = array();
}
while ($data = $DB->fetch_assoc($result)) {
if (!in_array($data["id"], $already_add['Software'])) {
$output = sprintf(__('%1$s - %2$s'), $type_name, $data["name"]);
$output = sprintf(__('%1$s (%2$s)'), $output,
sprintf(__('%1$s: %2$s'), __('version'),
$data["version"]));
if ($_SESSION["glpiis_ids_visible"]) {
$output = sprintf(__('%1$s (%2$s)'), $output, $data["id"]);
}
$tmp_device .= "<option title=\"$output\" value='Software_".$data["id"]."' ".
(($my_item == 'Software'."_".$data["id"])?"selected":"").">".
Toolbox::substr($output, 0,
$_SESSION["glpidropdown_chars_limit"]).
"</option>";
$already_add['Software'][] = $data["id"];
}
}
if (!empty($tmp_device)) {
$my_devices .= "<optgroup label=\""._sn('Installed software',
'Installed software', 2)."\">";
$my_devices .= $tmp_device."</optgroup>";
}
}
}
}
echo "<div id='tracking_my_devices'>";
echo "<select id='my_items' name='_my_items'>";
echo "<option value=''>--- ";
echo __('General')." ---</option>$my_devices</select></div>";
// Auto update summary of active or just solved tickets
$params = array('my_items' => '__VALUE__');
Ajax::updateItemOnSelectEvent("my_items","item_ticket_selection_information",
$CFG_GLPI["root_doc"]."/ajax/ticketiteminformation.php",
$params);
}
}
/**
* Make a select box for Tracking All Devices
*
* @param $myname select name
* @param $itemtype preselected value.for item type
* @param $items_id preselected value for item ID (default 0)
* @param $admin is an admin access ? (default 0)
* @param $users_id user ID used to display my devices (default 0
* @param $entity_restrict Restrict to a defined entity (default -1)
*
* @return nothing (print out an HTML select box)
**/
static function dropdownAllDevices($myname, $itemtype, $items_id=0, $admin=0, $users_id=0,
$entity_restrict=-1) {
global $CFG_GLPI, $DB;
$rand = mt_rand();
if ($_SESSION["glpiactiveprofile"]["helpdesk_hardware"] == 0) {
echo "<input type='hidden' name='$myname' value='0'>";
echo "<input type='hidden' name='items_id' value='0'>";
} else {
echo "<div id='tracking_all_devices'>";
if ($_SESSION["glpiactiveprofile"]["helpdesk_hardware"]&pow(2,
self::HELPDESK_ALL_HARDWARE)) {
// Display a message if view my hardware
if ($users_id
&& $_SESSION["glpiactiveprofile"]["helpdesk_hardware"]&pow(2,
self::HELPDESK_MY_HARDWARE)) {
echo __('Or complete search')." ";
}
$types = parent::getAllTypesForHelpdesk();
echo "<select id='search_$myname$rand' name='$myname'>\n";
echo "<option value='-1' >".Dropdown::EMPTY_VALUE."</option>\n";
echo "<option value='' ".((empty($itemtype)|| ($itemtype === 0))?" selected":"").">".
__('General')."</option>";
$found_type = false;
foreach ($types as $type => $label) {
if (strcmp($type,$itemtype) == 0) {
$found_type = true;
}
echo "<option value='".$type."' ".((strcmp($type,$itemtype) == 0)?" selected":"").">".
$label."</option>\n";
}
echo "</select>";
$params = array('itemtype' => '__VALUE__',
'entity_restrict' => $entity_restrict,
'admin' => $admin,
'myname' => "items_id",);
Ajax::updateItemOnSelectEvent("search_$myname$rand","results_$myname$rand",
$CFG_GLPI["root_doc"].
"/ajax/dropdownTrackingDeviceType.php",
$params);
echo "<span id='results_$myname$rand'>\n";
// Display default value if itemtype is displayed
if ($found_type
&& $itemtype) {
if (($item = getItemForItemtype($itemtype))
&& $items_id) {
if ($item->getFromDB($items_id)) {
echo "<select name='items_id'>\n";
echo "<option value='$items_id'>".$item->getName()."</option>";
echo "</select>";
}
} else {
$params['itemtype'] = $itemtype;
echo "<script type='text/javascript' >\n";
Ajax::updateItemJsCode("results_$myname$rand",
$CFG_GLPI["root_doc"].
"/ajax/dropdownTrackingDeviceType.php",
$params);
echo '</script>';
}
}
echo "</span>\n";
}
echo "</div>";
}
return $rand;
}
/**
* Calculate Ticket TCO for an item
*
*@param $item CommonDBTM object of the item
*
*@return float
**/
static function computeTco(CommonDBTM $item) {
global $DB;
$totalcost = 0;
$query = "SELECT `glpi_ticketcosts`.*
FROM `glpi_tickets`, `glpi_ticketcosts`
WHERE `glpi_ticketcosts`.`tickets_id` = `glpi_tickets`.`id`
AND `glpi_tickets`.`itemtype` = '".get_class($item)."'
AND `glpi_tickets`.`items_id` = '".$item->getField('id')."'
AND (`glpi_ticketcosts`.`cost_time` > '0'
OR `glpi_ticketcosts`.`cost_fixed` > '0'
OR `glpi_ticketcosts`.`cost_material` > '0')";
$result = $DB->query($query);
$i = 0;
if ($DB->numrows($result)) {
while ($data = $DB->fetch_assoc($result)) {
$totalcost += TicketCost::computeTotalCost($data["actiontime"], $data["cost_time"],
$data["cost_fixed"], $data["cost_material"]);
}
}
return $totalcost;
}
/**
* Print the helpdesk form
*
* @param $ID integer ID of the user who want to display the Helpdesk
* @param $ticket_template boolean ticket template for preview : false if not used for preview
* (false by default)
*
* @return nothing (print the helpdesk)
**/
function showFormHelpdesk($ID, $ticket_template=false) {
global $DB, $CFG_GLPI;
if (!Session::haveRight("create_ticket","1")) {
return false;
}
if (!$ticket_template
&& (Session::haveRight('validate_incident',1)
|| Session::haveRight('validate_request',1))) {
$opt = array();
$opt['reset'] = 'reset';
$opt['field'][0] = 55; // validation status
$opt['searchtype'][0] = 'equals';
$opt['contains'][0] = 'waiting';
$opt['link'][0] = 'AND';
$opt['field'][1] = 59; // validation aprobator
$opt['searchtype'][1] = 'equals';
$opt['contains'][1] = Session::getLoginUserID();
$opt['link'][1] = 'AND';
$url_validate = $CFG_GLPI["root_doc"]."/front/ticket.php?".Toolbox::append_params($opt,
'&');
if (TicketValidation::getNumberTicketsToValidate(Session::getLoginUserID()) > 0) {
echo "<a href='$url_validate' title=\"".__s('Ticket waiting for your approval')."\"
alt=\"".__s('Ticket waiting for your approval')."\">".
__('Tickets awaiting approval')."</a><br><br>";
}
}
$query = "SELECT `realname`, `firstname`, `name`
FROM `glpi_users`
WHERE `id` = '$ID'";
$result = $DB->query($query);
$email = UserEmail::getDefaultForUser($ID);
// Set default values...
$default_values = array('_users_id_requester_notif'
=> array('use_notification'
=> (($email == "")?0:1)),
'nodelegate' => 1,
'_users_id_requester' => 0,
'name' => '',
'content' => '',
'itilcategories_id' => 0,
'locations_id' => 0,
'urgency' => 3,
'itemtype' => '',
'items_id' => 0,
'entities_id' => $_SESSION['glpiactive_entity'],
'plan' => array(),
'global_validation' => 'none',
'due_date' => 'NULL',
'slas_id' => 0,
'_add_validation' => 0,
'type' => Entity::getUsedConfig('tickettype',
$_SESSION['glpiactive_entity'],
'', Ticket::INCIDENT_TYPE),
'_right' => "id");
// Get default values from posted values on reload form
if (!$ticket_template) {
if (isset($_POST)) {
$values = Html::cleanPostForTextArea($_POST);
}
}
// Restore saved value or override with page parameter
$saved = $this->restoreInput();
foreach ($default_values as $name => $value) {
if (!isset($values[$name])) {
if (isset($saved[$name])) {
$values[$name] = $saved[$name];
} else {
$values[$name] = $value;
}
}
}
if (!$ticket_template) {
echo "<form method='post' name='helpdeskform' action='".
$CFG_GLPI["root_doc"]."/front/tracking.injector.php' enctype='multipart/form-data'>";
}
$delegating = User::getDelegateGroupsForUser($values['entities_id']);
if (count($delegating)) {
echo "<div class='center'><table class='tab_cadre_fixe'>";
echo "<tr><th colspan='2'>".__('This ticket concerns me')." ";
$rand = Dropdown::showYesNo("nodelegate", $values['nodelegate']);
$params = array ('nodelegate' => '__VALUE__',
'rand' => $rand,
'right' => "delegate",
'_users_id_requester'
=> $values['_users_id_requester'],
'_users_id_requester_notif'
=> $values['_users_id_requester_notif'],
'use_notification'
=> $values['_users_id_requester_notif']['use_notification'],
'entity_restrict'
=> $_SESSION["glpiactive_entity"]);
Ajax::UpdateItemOnSelectEvent("dropdown_nodelegate".$rand, "show_result".$rand,
$CFG_GLPI["root_doc"]."/ajax/dropdownDelegationUsers.php",
$params);
if ($CFG_GLPI['use_check_pref'] && $values['nodelegate']) {
echo "</th><th>".__('Check your personnal information');
}
echo "</th></tr>";
echo "<tr class='tab_bg_1'><td colspan='2' class='center'>";
echo "<div id='show_result$rand'>";
$self = new self();
if ($values["_users_id_requester"] == 0) {
$values['_users_id_requester'] = Session::getLoginUserID();
} else {
$values['_right'] = "delegate";
}
$self->showActorAddFormOnCreate(CommonITILActor::REQUESTER, $values);
echo "</div>";
if ($CFG_GLPI['use_check_pref'] && $values['nodelegate']) {
echo "</td><td class='center'>";
User::showPersonalInformation(Session::getLoginUserID());
}
echo "</td></tr>";
echo "</table></div>";
echo "<input type='hidden' name='_users_id_recipient' value='".Session::getLoginUserID()."'>";
} else {
// User as requester
$values['_users_id_requester'] = Session::getLoginUserID();
if ($CFG_GLPI['use_check_pref']) {
echo "<div class='center'><table class='tab_cadre_fixe'>";
echo "<tr><th>".__('Check your personnal information')."</th></tr>";
echo "<tr class='tab_bg_1'><td class='center'>";
User::showPersonalInformation(Session::getLoginUserID());
echo "</td></tr>";
echo "</table></div>";
}
}
echo "<input type='hidden' name='_from_helpdesk' value='1'>";
echo "<input type='hidden' name='requesttypes_id' value='".RequestType::getDefault('helpdesk').
"'>";
// Load ticket template if available :
$tt = $this->getTicketTemplateToUse($ticket_template, $values['type'],
$values['itilcategories_id'],
$_SESSION["glpiactive_entity"]);
// Predefined fields from template : reset them
if (isset($values['_predefined_fields'])) {
$values['_predefined_fields']
= Toolbox::decodeArrayFromInput($values['_predefined_fields']);
} else {
$values['_predefined_fields'] = array();
}
// Store predefined fields to be able not to take into account on change template
$predefined_fields = array();
if (isset($tt->predefined) && count($tt->predefined)) {
foreach ($tt->predefined as $predeffield => $predefvalue) {
if (isset($values[$predeffield]) && isset($default_values[$predeffield])) {
// Is always default value : not set
// Set if already predefined field
// Set if ticket template change
if (($values[$predeffield] == $default_values[$predeffield])
|| (isset($values['_predefined_fields'][$predeffield])
&& ($values[$predeffield] == $values['_predefined_fields'][$predeffield]))
|| (isset($values['_tickettemplates_id'])
&& ($values['_tickettemplates_id'] != $tt->getID()))) {
$values[$predeffield] = $predefvalue;
$predefined_fields[$predeffield] = $predefvalue;
}
} else { // Not defined options set as hidden field
echo "<input type='hidden' name='$predeffield' value='$predefvalue'>";
}
}
} else { // No template load : reset predefined values
if (count($values['_predefined_fields'])) {
foreach ($values['_predefined_fields'] as $predeffield => $predefvalue) {
if ($values[$predeffield] == $predefvalue) {
$values[$predeffield] = $default_values[$predeffield];
}
}
}
}
if (($CFG_GLPI['urgency_mask'] == (1<<3))
|| $tt->isHiddenField('urgency')) {
// Dont show dropdown if only 1 value enabled or field is hidden
echo "<input type='hidden' name='urgency' value='".$values['urgency']."'>";
}
// Display predefined fields if hidden
if ($tt->isHiddenField('itemtype')) {
echo "<input type='hidden' name='itemtype' value='".$values['itemtype']."'>";
echo "<input type='hidden' name='items_id' value='".$values['items_id']."'>";
}
if ($tt->isHiddenField('locations_id')) {
echo "<input type='hidden' name='locations_id' value='".$values['locations_id']."'>";
}
echo "<input type='hidden' name='entities_id' value='".$_SESSION["glpiactive_entity"]."'>";
echo "<div class='center'><table class='tab_cadre_fixe'>";
echo "<tr><th>".__('Describe the incident or request')."</th><th>";
if (Session::isMultiEntitiesMode()) {
echo "(".Dropdown::getDropdownName("glpi_entities", $_SESSION["glpiactive_entity"]).")";
}
echo "</th></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".sprintf(__('%1$s%2$s'), __('Type'), $tt->getMandatoryMark('type'))."</td>";
echo "<td>";
self::dropdownType('type', array('value' => $values['type'],
'on_change' => 'submit()'));
echo "</td></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".sprintf(__('%1$s%2$s'), __('Category'),
$tt->getMandatoryMark('itilcategories_id'))."</td>";
echo "<td>";
$condition = "`is_helpdeskvisible`='1'";
switch ($values['type']) {
case self::DEMAND_TYPE :
$condition .= " AND `is_request`='1'";
break;
default: // self::INCIDENT_TYPE :
$condition .= " AND `is_incident`='1'";
}
$opt = array('value' => $values['itilcategories_id'],
'condition' => $condition,
'on_change' => 'submit()');
if ($values['itilcategories_id'] && $tt->isMandatoryField("itilcategories_id")) {
$opt['display_emptychoice'] = false;
}
ITILCategory::dropdown($opt);
echo "</td></tr>";
if ($CFG_GLPI['urgency_mask'] != (1<<3)) {
if (!$tt->isHiddenField('urgency')) {
echo "<tr class='tab_bg_1'>";
echo "<td>".sprintf(__('%1$s%2$s'), __('Urgency'), $tt->getMandatoryMark('urgency')).
"</td>";
echo "<td>";
self::dropdownUrgency(array('value' => $values["urgency"]));
echo "</td></tr>";
}
}
if (empty($delegating)
&& NotificationTargetTicket::isAuthorMailingActivatedForHelpdesk()) {
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Inform me about the actions taken')."</td>";
echo "<td>";
if ($values["_users_id_requester"] == 0) {
$values['_users_id_requester'] = Session::getLoginUserID();
}
$_POST['value'] = $values['_users_id_requester'];
$_POST['field'] = '_users_id_requester_notif';
$_POST['use_notification'] = $values['_users_id_requester_notif']['use_notification'];
include (GLPI_ROOT."/ajax/uemailUpdate.php");
echo "</td></tr>";
}
if ($_SESSION["glpiactiveprofile"]["helpdesk_hardware"] != 0) {
if (!$tt->isHiddenField('itemtype')) {
echo "<tr class='tab_bg_1'>";
echo "<td>".sprintf(__('%1$s%2$s'), __('Hardware type'),
$tt->getMandatoryMark('itemtype'))."</td>";
echo "<td>";
self::dropdownMyDevices($values['_users_id_requester'], $_SESSION["glpiactive_entity"],
$values['itemtype'], $values['items_id']);
self::dropdownAllDevices("itemtype", $values['itemtype'], $values['items_id'], 0,
$values['_users_id_requester'],
$_SESSION["glpiactive_entity"]);
echo "<span id='item_ticket_selection_information'></span>";
echo "</td></tr>";
}
}
if (!$tt->isHiddenField('locations_id')) {
echo "<tr class='tab_bg_1'><td>";
printf(__('%1$s%2$s'), __('Location'), $tt->getMandatoryMark('locations_id'));
echo "</td><td>";
Location::dropdown(array('value' => $values["locations_id"]));
echo "</td></tr>";
}
if (!$tt->isHiddenField('name')
|| $tt->isPredefinedField('name')) {
echo "<tr class='tab_bg_1'>";
echo "<td>".sprintf(__('%1$s%2$s'), __('Title'), $tt->getMandatoryMark('name'))."</td>";
echo "<td><input type='text' maxlength='250' size='80' name='name'
value=\"".$values['name']."\"></td></tr>";
}
if (!$tt->isHiddenField('content')
|| $tt->isPredefinedField('content')) {
echo "<tr class='tab_bg_1'>";
echo "<td>".sprintf(__('%1$s%2$s'), __('Description'), $tt->getMandatoryMark('content')).
"</td>";
echo "<td><textarea name='content' cols='80' rows='14'>".$values['content']."</textarea>";
echo "</td></tr>";
}
echo "<tr class='tab_bg_1'>";
echo "<td>".sprintf(__('%1$s (%2$s)'), __('File'), Document::getMaxUploadSize());
echo "<img src='".$CFG_GLPI["root_doc"]."/pics/aide.png' class='pointer' alt='".
__s('Help')."' onclick=\"window.open('".$CFG_GLPI["root_doc"].
"/front/documenttype.list.php','Help','scrollbars=1,resizable=1,width=1000,height=800')\">";
echo " ";
self::showDocumentAddButton(60);
echo "</td>";
echo "<td><div id='uploadfiles'><input type='file' name='filename[]' value='' size='60'></div>";
echo "</td></tr>";
if (!$ticket_template) {
echo "<tr class='tab_bg_1'>";
echo "<td colspan='2' class='center'>";
if ($tt->isField('id') && ($tt->fields['id'] > 0)) {
echo "<input type='hidden' name='_tickettemplates_id' value='".$tt->fields['id']."'>";
echo "<input type='hidden' name='_predefined_fields'
value=\"".Toolbox::prepareArrayForInput($predefined_fields)."\">";
}
echo "<input type='submit' name='add' value=\"".__s('Submit message')."\" class='submit'>";
echo "</td></tr>";
}
echo "</table></div>";
if (!$ticket_template) {
Html::closeForm();
}
}
/**
* @since version 0.83
*
* @param $entity integer entities_id usefull is function called by cron (default 0)
**/
static function getDefaultValues($entity=0) {
global $CFG_GLPI;
if (is_numeric(Session::getLoginUserID(false))) {
$users_id_requester = Session::getLoginUserID();
// No default requester if own ticket right = tech and update_ticket right to update requester
if (Session::haveRight('own_ticket',1)
&& Session::haveRight('update_ticket',1)) {
$users_id_requester = 0;
}
$entity = $_SESSION['glpiactive_entity'];
$requesttype = $_SESSION['glpidefault_requesttypes_id'];
} else {
$users_id_requester = 0;
$requesttype = $CFG_GLPI['default_requesttypes_id'];
}
$type = Entity::getUsedConfig('tickettype', $entity, '', Ticket::INCIDENT_TYPE);
// Set default values...
return array('_users_id_requester' => $users_id_requester,
'_users_id_requester_notif' => array('use_notification' => 1,
'alternative_email' => ''),
'_groups_id_requester' => 0,
'_users_id_assign' => 0,
'_users_id_assign_notif' => array('use_notification' => 1,
'alternative_email' => ''),
'_groups_id_assign' => 0,
'_users_id_observer' => 0,
'_users_id_observer_notif' => array('use_notification' => 1,
'alternative_email' => ''),
'_groups_id_observer' => 0,
'_link' => array('tickets_id_2' => '',
'link' => ''),
'_suppliers_id_assign' => 0,
'name' => '',
'content' => '',
'itilcategories_id' => 0,
'urgency' => 3,
'impact' => 3,
'priority' => self::computePriority(3, 3),
'requesttypes_id' => $requesttype,
'actiontime' => 0,
'date' => $_SESSION["glpi_currenttime"],
'entities_id' => $entity,
'status' => self::INCOMING,
'followup' => array(),
'itemtype' => '',
'items_id' => 0,
'locations_id' => 0,
'plan' => array(),
'global_validation' => 'none',
'due_date' => 'NULL',
'slas_id' => 0,
'_add_validation' => 0,
'type' => $type);
}
/**
* Get ticket template to use
* Use force_template first, then try on template define for type and category
* then use default template of active profile of connected user and then use default entity one
*
* @param $force_template integer tickettemplate_id to used (case of preview for example)
* (default 0)
* @param $type integer type of the ticket (default 0)
* @param $itilcategories_id integer ticket category (default 0)
* @param $entities_id integer (default -1)
*
* @since version 0.84
*
* @return ticket template object
**/
function getTicketTemplateToUse($force_template=0, $type=0, $itilcategories_id=0,
$entities_id=-1) {
// Load ticket template if available :
$tt = new TicketTemplate();
$template_loaded = false;
if ($force_template) {
// with type and categ
if ($tt->getFromDBWithDatas($force_template, true)) {
$template_loaded = true;
}
}
if (!$template_loaded
&& $type
&& $itilcategories_id) {
$categ = new ITILCategory();
if ($categ->getFromDB($itilcategories_id)) {
$field = '';
switch ($type) {
case self::INCIDENT_TYPE :
$field = 'tickettemplates_id_incident';
break;
case self::DEMAND_TYPE :
$field = 'tickettemplates_id_demand';
break;
}
if (!empty($field) && $categ->fields[$field]) {
// without type and categ
if ($tt->getFromDBWithDatas($categ->fields[$field], false)) {
$template_loaded = true;
}
}
}
}
// If template loaded from type and category do not check after
if ($template_loaded) {
return $tt;
}
if (!$template_loaded) {
// load default profile one if not already loaded
if (isset($_SESSION['glpiactiveprofile']['tickettemplates_id'])
&& $_SESSION['glpiactiveprofile']['tickettemplates_id']) {
// with type and categ
if ($tt->getFromDBWithDatas($_SESSION['glpiactiveprofile']['tickettemplates_id'],
true)) {
$template_loaded = true;
}
}
}
if (!$template_loaded
&& ($entities_id >= 0)) {
// load default entity one if not already loaded
if ($template_id = Entity::getUsedConfig('tickettemplates_id', $entities_id)) {
// with type and categ
if ($tt->getFromDBWithDatas($template_id, true)) {
$template_loaded = true;
}
}
}
// Check if profile / entity set type and category and try to load template for these values
if ($template_loaded) { // template loaded for profile or entity
$newtype = $type;
$newitilcategories_id = $itilcategories_id;
// Get predefined values for ticket template
if (isset($tt->predefined['itilcategories_id']) && $tt->predefined['itilcategories_id']){
$newitilcategories_id = $tt->predefined['itilcategories_id'];
}
if (isset($tt->predefined['type']) && $tt->predefined['type']){
$newtype = $tt->predefined['type'];
}
if ($newtype
&& $newitilcategories_id) {
$categ = new ITILCategory();
if ($categ->getFromDB($newitilcategories_id)) {
$field = '';
switch ($newtype) {
case self::INCIDENT_TYPE :
$field = 'tickettemplates_id_incident';
break;
case self::DEMAND_TYPE :
$field = 'tickettemplates_id_demand';
break;
}
if (!empty($field) && $categ->fields[$field]) {
// without type and categ
if ($tt->getFromDBWithDatas($categ->fields[$field], false)) {
$template_loaded = true;
}
}
}
}
}
return $tt;
}
function showForm($ID, $options=array()) {
global $DB, $CFG_GLPI;
$default_values = self::getDefaultValues();
// Get default values from posted values on reload form
if (!isset($options['template_preview'])) {
if (isset($_POST)) {
$values = Html::cleanPostForTextArea($_POST);
}
}
// Restore saved value or override with page parameter
$saved = $this->restoreInput();
foreach ($default_values as $name => $value) {
if (!isset($values[$name])) {
if (isset($saved[$name])) {
$values[$name] = $saved[$name];
} else {
$values[$name] = $value;
}
}
}
// Default check
if ($ID > 0) {
$this->check($ID,'r');
} else {
// Create item
$this->check(-1,'w',$values);
}
if (!$ID) {
$this->userentities = array();
if ($values["_users_id_requester"]) {
//Get all the user's entities
$all_entities = Profile_User::getUserEntities($values["_users_id_requester"], true,
true);
//For each user's entity, check if the technician which creates the ticket have access to it
foreach ($all_entities as $tmp => $ID_entity) {
if (Session::haveAccessToEntity($ID_entity)) {
$this->userentities[] = $ID_entity;
}
}
}
$this->countentitiesforuser = count($this->userentities);
if (($this->countentitiesforuser > 0)
&& !in_array($this->fields["entities_id"], $this->userentities)) {
// If entity is not in the list of user's entities,
// then use as default value the first value of the user's entites list
$this->fields["entities_id"] = $this->userentities[0];
// Pass to values
$values['entities_id'] = $this->userentities[0];
}
}
if ($values['type'] <= 0) {
$values['type'] = Entity::getUsedConfig('tickettype', $values['entities_id'], '',
Ticket::INCIDENT_TYPE);
}
if (!isset($options['template_preview'])) {
$options['template_preview'] = 0;
}
// Load ticket template if available :
$tt = $this->getTicketTemplateToUse($options['template_preview'], $values['type'],
$values['itilcategories_id'], $values['entities_id']);
// Predefined fields from template : reset them
if (isset($values['_predefined_fields'])) {
$values['_predefined_fields']
= Toolbox::decodeArrayFromInput($values['_predefined_fields']);
} else {
$values['_predefined_fields'] = array();
}
// Store predefined fields to be able not to take into account on change template
// Only manage predefined values on ticket creation
$predefined_fields = array();
if (!$ID) {
if (isset($tt->predefined) && count($tt->predefined)) {
foreach ($tt->predefined as $predeffield => $predefvalue) {
if (isset($default_values[$predeffield])) {
// Is always default value : not set
// Set if already predefined field
// Set if ticket template change
if (($values[$predeffield] == $default_values[$predeffield])
|| (isset($values['_predefined_fields'][$predeffield])
&& ($values[$predeffield] == $values['_predefined_fields'][$predeffield]))
|| (isset($values['_tickettemplates_id'])
&& ($values['_tickettemplates_id'] != $tt->getID()))) {
// Load template data
$values[$predeffield] = $predefvalue;
$this->fields[$predeffield] = $predefvalue;
$predefined_fields[$predeffield] = $predefvalue;
}
}
}
} else { // No template load : reset predefined values
if (count($values['_predefined_fields'])) {
foreach ($values['_predefined_fields'] as $predeffield => $predefvalue) {
if ($values[$predeffield] == $predefvalue) {
$values[$predeffield] = $default_values[$predeffield];
}
}
}
}
}
// Put ticket template on $values for actors
$values['_tickettemplate'] = $tt;
$canupdate = Session::haveRight('update_ticket', '1');
$canpriority = Session::haveRight('update_priority', '1');
$canstatus = $canupdate;
if (in_array($this->fields['status'], $this->getClosedStatusArray())) {
$canupdate = false;
}
$showuserlink = 0;
if (Session::haveRight('user','r')) {
$showuserlink = 1;
}
if (!$options['template_preview']) {
$this->showTabs($options);
} else {
// Add all values to fields of tickets for template preview
foreach ($values as $key => $val) {
if (!isset($this->fields[$key])) {
$this->fields[$key] = $val;
}
}
}
// In percent
$colsize1 = '13';
$colsize2 = '29';
$colsize3 = '13';
$colsize4 = '45';
$canupdate_descr = $canupdate
|| (($this->fields['status'] == self::INCOMING)
&& $this->isUser(CommonITILActor::REQUESTER, Session::getLoginUserID())
&& ($this->numberOfFollowups() == 0)
&& ($this->numberOfTasks() == 0));
if (!$options['template_preview']) {
echo "<form method='post' name='form_ticket' enctype='multipart/form-data' action='".
$CFG_GLPI["root_doc"]."/front/ticket.form.php'>";
}
echo "<div class='spaced' id='tabsbody'>";
echo "<table class='tab_cadre_fixe' id='mainformtable'>";
// Optional line
$ismultientities = Session::isMultiEntitiesMode();
echo "<tr class='headerRow'>";
echo "<th colspan='4'>";
if ($ID) {
$text = sprintf(__('%1$s - %2$s'), $this->getTypeName(1),
sprintf(__('%1$s: %2$s'), __('ID'), $ID));
if ($ismultientities) {
$text = sprintf(__('%1$s (%2$s)'), $text,
Dropdown::getDropdownName('glpi_entities',
$this->fields['entities_id']));
}
echo $text;
} else {
if ($ismultientities) {
printf(__('The ticket will be added in the entity %s'),
Dropdown::getDropdownName("glpi_entities", $this->fields['entities_id']));
} else {
_e('New ticket');
}
}
echo "</th></tr>";
echo "<tr class='tab_bg_1'>";
echo "<th width='$colsize1%'>";
echo $tt->getBeginHiddenFieldText('date');
if (!$ID) {
printf(__('%1$s%2$s'), __('Opening date'), $tt->getMandatoryMark('date'));
} else {
_e('Opening date');
}
echo $tt->getEndHiddenFieldText('date');
echo "</th>";
echo "<td width='$colsize2%'>";
echo $tt->getBeginHiddenFieldValue('date');
$date = $this->fields["date"];
if ($canupdate) {
Html::showDateTimeFormItem("date", $date, 1, false);
} else {
echo Html::convDateTime($date);
}
echo $tt->getEndHiddenFieldValue('date', $this);
echo "</td>";
// SLA
echo "<th width='$colsize3%'>".$tt->getBeginHiddenFieldText('due_date');
if (!$ID) {
printf(__('%1$s%2$s'), __('Due date'), $tt->getMandatoryMark('due_date'));
} else {
_e('Due date');
}
echo $tt->getEndHiddenFieldText('due_date');
echo "</th>";
echo "<td width='$colsize4%' class='nopadding'>";
if ($ID) {
if ($this->fields["slas_id"] > 0) {
echo "<table width='100%'><tr><td class='nopadding'>";
echo Html::convDateTime($this->fields["due_date"]);
echo "</td><td class='b'>".__('SLA')."</td>";
echo "<td class='nopadding'>";
echo Dropdown::getDropdownName("glpi_slas", $this->fields["slas_id"]);
$commentsla = "";
$slalevel = new SlaLevel();
if ($slalevel->getFromDB($this->fields['slalevels_id'])) {
$commentsla .= '<span class="b spaced">'.
sprintf(__('%1$s: %2$s'), __('Escalation level'),
$slalevel->getName()).'</span><br>';
}
$nextaction = new SlaLevel_Ticket();
if ($nextaction->getFromDBForTicket($this->fields["id"])) {
$commentsla .= '<span class="b spaced">'.
sprintf(__('Next escalation: %s'),
Html::convDateTime($nextaction->fields['date'])).'</span>';
if ($slalevel->getFromDB($nextaction->fields['slalevels_id'])) {
$commentsla .= '<span class="b spaced">'.
sprintf(__('%1$s: %2$s'), __('Escalation level'),
$slalevel->getName()).'</span>';
}
}
$slaoptions = array();
if (Session::haveRight('config', 'r')) {
$slaoptions['link'] = Toolbox::getItemTypeFormURL('SLA').
"?id=".$this->fields["slas_id"];
}
Html::showToolTip($commentsla,$slaoptions);
if ($canupdate) {
echo " <input type='submit' class='submit' name='sla_delete' value='".
_sx('button', 'Delete permanently')."'>";
}
echo "</td>";
echo "</tr></table>";
} else {
echo "<table><tr><td class='nopadding'>";
echo $tt->getBeginHiddenFieldValue('due_date');
Html::showDateTimeFormItem("due_date", $this->fields["due_date"], 1, true, $canupdate);
echo $tt->getEndHiddenFieldValue('due_date',$this);
echo "</td>";
if ($canupdate) {
echo "<td>";
echo $tt->getBeginHiddenFieldText('slas_id');
echo "<span id='sla_action'>";
echo "<a class='vsubmit' ".
Html::addConfirmationOnAction(array(__('The assignment of a SLA to a ticket causes the recalculation of the due date.'),
__("Escalations defined in the SLA will be triggered under this new date.")),
"cleanhide('sla_action');cleandisplay('sla_choice');").
">".__('Assign a SLA').'</a>';
echo "</span>";
echo "<span id='sla_choice' style='display:none'>";
echo "<span class='b'>".__('SLA')."</span> ";
Sla::dropdown(array('entity' => $this->fields["entities_id"],
'value' => $this->fields["slas_id"]));
echo "</span>";
echo $tt->getEndHiddenFieldText('slas_id');
echo "</td>";
}
echo "</tr></table>";
}
} else { // New Ticket
echo "<table><tr><td class='nopadding'>";
if ($this->fields["due_date"] == 'NULL') {
$this->fields["due_date"]='';
}
echo $tt->getBeginHiddenFieldValue('due_date');
Html::showDateTimeFormItem("due_date", $this->fields["due_date"], 1, false, $canupdate);
echo $tt->getEndHiddenFieldValue('due_date',$this);
echo "</td>";
if ($canupdate) {
echo "<td class='nopadding b'>".$tt->getBeginHiddenFieldText('slas_id');
printf(__('%1$s%2$s'), __('SLA'), $tt->getMandatoryMark('slas_id'));
echo $tt->getEndHiddenFieldText('slas_id')."</td>";
echo "<td class='nopadding'>".$tt->getBeginHiddenFieldValue('slas_id');
Sla::dropdown(array('entity' => $this->fields["entities_id"],
'value' => $this->fields["slas_id"]));
echo $tt->getEndHiddenFieldValue('slas_id',$this);
echo "</td>";
}
echo "</tr></table>";
}
echo "</td></tr>";
if ($ID) {
echo "<tr class='tab_bg_1'>";
echo "<th width='$colsize1%'>".__('By')."</th>";
echo "<td width='$colsize2%'>";
if ($canupdate) {
User::dropdown(array('name' => 'users_id_recipient',
'value' => $this->fields["users_id_recipient"],
'entity' => $this->fields["entities_id"],
'right' => 'all'));
} else {
echo getUserName($this->fields["users_id_recipient"], $showuserlink);
}
echo "</td>";
echo "<th width='$colsize3%'>".__('Last update')."</th>";
echo "<td width='$colsize4%'>";
if ($this->fields['users_id_lastupdater'] > 0) {
//TRANS: %1$s is the update date, %2$s is the last updater name
printf(__('%1$s by %2$s'), Html::convDateTime($this->fields["date_mod"]),
getUserName($this->fields["users_id_lastupdater"], $showuserlink));
}
echo "</td>";
echo "</tr>";
}
if ($ID
&& (in_array($this->fields["status"], $this->getSolvedStatusArray())
|| in_array($this->fields["status"], $this->getClosedStatusArray()))) {
echo "<tr class='tab_bg_1'>";
echo "<th width='$colsize1%'>".__('Resolution date')."</th>";
echo "<td width='$colsize2%'>";
Html::showDateTimeFormItem("solvedate", $this->fields["solvedate"], 1, false,
$canupdate);
echo "</td>";
if (in_array($this->fields["status"], $this->getClosedStatusArray())) {
echo "<th width='$colsize3%'>".__('Close date')."</th>";
echo "<td width='$colsize4%'>";
Html::showDateTimeFormItem("closedate", $this->fields["closedate"], 1, false,
$canupdate);
echo "</td>";
} else {
echo "<td colspan='2'> </td>";
}
echo "</tr>";
}
if ($ID) {
echo "</table>";
echo "<table class='tab_cadre_fixe' id='mainformtable2'>";
}
echo "<tr class='tab_bg_1'>";
echo "<th width='$colsize1%'>".sprintf(__('%1$s%2$s'), __('Type'),
$tt->getMandatoryMark('type'))."</th>";
echo "<td width='$colsize2%'>";
// Permit to set type when creating ticket without update right
if ($canupdate || !$ID) {
$opt = array('value' => $this->fields["type"]);
/// Auto submit to load template
if (!$ID) {
$opt['on_change'] = 'submit()';
}
$rand = self::dropdownType('type', $opt);
if ($ID) {
$params = array('type' => '__VALUE__',
'entity_restrict' => $this->fields['entities_id'],
'value' => $this->fields['itilcategories_id'],
'currenttype' => $this->fields['type']);
Ajax::updateItemOnSelectEvent("dropdown_type$rand", "show_category_by_type",
$CFG_GLPI["root_doc"]."/ajax/dropdownTicketCategories.php",
$params);
}
} else {
echo self::getTicketTypeName($this->fields["type"]);
}
echo "</td>";
echo "<th width='$colsize3%'>".sprintf(__('%1$s%2$s'), __('Category'),
$tt->getMandatoryMark('itilcategories_id'))."</th>";
echo "<td width='$colsize4%'>";
// Permit to set category when creating ticket without update right
if ($canupdate
|| !$ID
|| $canupdate_descr) {
$opt = array('value' => $this->fields["itilcategories_id"],
'entity' => $this->fields["entities_id"]);
if ($_SESSION["glpiactiveprofile"]["interface"] == "helpdesk") {
$opt['condition'] = "`is_helpdeskvisible`='1' AND ";
} else {
$opt['condition'] = '';
}
/// Auto submit to load template
if (!$ID) {
$opt['on_change'] = 'submit()';
}
/// if category mandatory, no empty choice
/// no empty choice is default value set on ticket creation, else yes
if (($ID || $values['itilcategories_id'])
&& $tt->isMandatoryField("itilcategories_id")
&& ($this->fields["itilcategories_id"] > 0)) {
$opt['display_emptychoice'] = false;
}
switch ($this->fields["type"]) {
case self::INCIDENT_TYPE :
$opt['condition'] .= "`is_incident`='1'";
break;
case self::DEMAND_TYPE :
$opt['condition'] .= "`is_request`='1'";
break;
default :
break;
}
echo "<span id='show_category_by_type'>";
ITILCategory::dropdown($opt);
echo "</span>";
} else {
echo Dropdown::getDropdownName("glpi_itilcategories", $this->fields["itilcategories_id"]);
}
echo "</td>";
echo "</tr>";
if (!$ID) {
echo "</table>";
$this->showActorsPartForm($ID,$values);
echo "<table class='tab_cadre_fixe' id='mainformtable3'>";
}
echo "<tr class='tab_bg_1'>";
echo "<th width='$colsize1%'>".$tt->getBeginHiddenFieldText('status');
printf(__('%1$s%2$s'), __('Status'), $tt->getMandatoryMark('status'));
echo $tt->getEndHiddenFieldText('status')."</th>";
echo "<td width='$colsize2%'>";
echo $tt->getBeginHiddenFieldValue('status');
if ($canstatus) {
self::dropdownStatus(array('value' => $this->fields["status"],
'showtype' => 'allowed'));
} else {
echo self::getStatus($this->fields["status"]);
}
echo $tt->getEndHiddenFieldValue('status',$this);
echo "</td>";
echo "<th width='$colsize3%'>".$tt->getBeginHiddenFieldText('requesttypes_id');
printf(__('%1$s%2$s'), __('Request source'), $tt->getMandatoryMark('requesttypes_id'));
echo $tt->getEndHiddenFieldText('requesttypes_id')."</th>";
echo "<td width='$colsize4%'>";
echo $tt->getBeginHiddenFieldValue('requesttypes_id');
if ($canupdate) {
RequestType::dropdown(array('value' => $this->fields["requesttypes_id"]));
} else {
echo Dropdown::getDropdownName('glpi_requesttypes', $this->fields["requesttypes_id"]);
}
echo $tt->getEndHiddenFieldValue('requesttypes_id',$this);
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<th>".$tt->getBeginHiddenFieldText('urgency');
printf(__('%1$s%2$s'), __('Urgency'), $tt->getMandatoryMark('urgency'));
echo $tt->getEndHiddenFieldText('urgency')."</th>";
echo "<td>";
if (($canupdate && $canpriority)
|| !$ID
|| $canupdate_descr) {
// Only change during creation OR when allowed to change priority OR when user is the creator
echo $tt->getBeginHiddenFieldValue('urgency');
$idurgency = self::dropdownUrgency(array('value' => $this->fields["urgency"]));
echo $tt->getEndHiddenFieldValue('urgency', $this);
} else {
$idurgency = "value_urgency".mt_rand();
echo "<input id='$idurgency' type='hidden' name='urgency' value='".
$this->fields["urgency"]."'>";
echo parent::getUrgencyName($this->fields["urgency"]);
}
echo "</td>";
// Display validation state
echo "<th>";
if (!$ID) {
echo $tt->getBeginHiddenFieldText('_add_validation');
printf(__('%1$s%2$s'), __('Approval request'), $tt->getMandatoryMark('_add_validation'));
echo $tt->getEndHiddenFieldText('_add_validation');
} else {
echo $tt->getBeginHiddenFieldText('global_validation');
_e('Approval');
echo $tt->getEndHiddenFieldText('global_validation');
}
echo "</th>";
echo "<td>";
if (!$ID) {
echo $tt->getBeginHiddenFieldValue('_add_validation');
$validation_right = '';
if (($values['type'] == self::INCIDENT_TYPE)
&& Session::haveRight('create_incident_validation', 1)) {
$validation_right = 'validate_incident';
}
if (($values['type'] == self::DEMAND_TYPE)
&& Session::haveRight('create_request_validation', 1)) {
$validation_right = 'validate_request';
}
if (!empty($validation_right)) {
User::dropdown(array('name' => "_add_validation",
'entity' => $this->fields['entities_id'],
'right' => $validation_right,
'value' => $values['_add_validation']));
}
echo $tt->getEndHiddenFieldValue('_add_validation',$this);
if ($tt->isPredefinedField('global_validation')) {
echo "<input type='hidden' name='global_validation' value='".$tt->predefined['global_validation']."'>";
}
} else {
echo $tt->getBeginHiddenFieldValue('global_validation');
if ($canupdate) {
TicketValidation::dropdownStatus('global_validation',
array('global' => true,
'value' => $this->fields['global_validation']));
} else {
echo TicketValidation::getStatus($this->fields['global_validation']);
}
echo $tt->getEndHiddenFieldValue('global_validation',$this);
}
echo "</td></tr>";
echo "<tr class='tab_bg_1'>";
echo "<th>".$tt->getBeginHiddenFieldText('impact');
printf(__('%1$s%2$s'), __('Impact'), $tt->getMandatoryMark('impact'));
echo $tt->getEndHiddenFieldText('impact')."</th>";
echo "<td>";
echo $tt->getBeginHiddenFieldValue('impact');
if ($canupdate) {
$idimpact = self::dropdownImpact(array('value' => $this->fields["impact"]));
} else {
$idimpact = "value_impact".mt_rand();
echo "<input id='$idimpact' type='hidden' name='impact' value='".$this->fields["impact"]."'>";
echo parent::getImpactName($this->fields["impact"]);
}
echo $tt->getEndHiddenFieldValue('impact',$this);
echo "</td>";
echo "<th rowspan='2'>".$tt->getBeginHiddenFieldText('itemtype');
printf(__('%1$s%2$s'), __('Associated element'), $tt->getMandatoryMark('itemtype'));
if ($ID && $canupdate) {
echo " <img title='".__s('Update')."' alt='".__s('Update')."'
onClick=\"Ext.get('tickethardwareselection$ID').setDisplayed('block')\"
class='pointer' src='".$CFG_GLPI["root_doc"]."/pics/showselect.png'>";
}
echo $tt->getEndHiddenFieldText('itemtype');
echo "</th>";
echo "<td rowspan='2'>";
echo $tt->getBeginHiddenFieldValue('itemtype');
// Select hardware on creation or if have update right
if ($canupdate
|| !$ID
|| $canupdate_descr) {
if ($ID) {
if ($this->fields['itemtype']
&& ($item = getItemForItemtype($this->fields['itemtype']))
&& $this->fields["items_id"]) {
if ($item->can($this->fields["items_id"],'r')) {
printf(__('%1$s - %2$s'), $item->getTypeName(),
$item->getLink(array('comments' => true)));
} else {
printf(__('%1$s - %2$s'), $item->getTypeName(), $item->getNameID());
}
}
}
$dev_user_id = 0;
$dev_itemtype = $this->fields["itemtype"];
$dev_items_id = $this->fields["items_id"];
if (!$ID) {
$dev_user_id = $values['_users_id_requester'];
$dev_itemtype = $values["itemtype"];
$dev_items_id = $values["items_id"];
} else if (isset($this->users[CommonITILActor::REQUESTER])
&& (count($this->users[CommonITILActor::REQUESTER]) == 1)) {
foreach ($this->users[CommonITILActor::REQUESTER] as $user_id_single) {
$dev_user_id = $user_id_single['users_id'];
}
}
if ($ID) {
echo "<div id='tickethardwareselection$ID' style='display:none'>";
}
if ($dev_user_id > 0) {
self::dropdownMyDevices($dev_user_id, $this->fields["entities_id"],
$dev_itemtype, $dev_items_id);
}
self::dropdownAllDevices("itemtype", $dev_itemtype, $dev_items_id,
1, $dev_user_id, $this->fields["entities_id"]);
if ($ID) {
echo "</div>";
}
echo "<span id='item_ticket_selection_information'></span>";
} else {
if ($ID
&& $this->fields['itemtype']
&& ($item = getItemForItemtype($this->fields['itemtype']))) {
$item->getFromDB($this->fields['items_id']);
printf(__('%1$s - %2$s'), $item->getTypeName(), $item->getNameID());
} else {
_e('General');
}
}
echo $tt->getEndHiddenFieldValue('itemtype',$this);
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<th>".sprintf(__('%1$s%2$s'), __('Priority'), $tt->getMandatoryMark('priority'))."</th>";
echo "<td>";
$idajax = 'change_priority_' . mt_rand();
if ($canupdate
&& $canpriority
&& !$tt->isHiddenField('priority')) {
$idpriority = parent::dropdownPriority(array('value' => $this->fields["priority"],
'withmajor' => true));
echo " <span id='$idajax' style='display:none'></span>";
} else {
$idpriority = 0;
echo "<span id='$idajax'>".parent::getPriorityName($this->fields["priority"])."</span>";
}
if ($canupdate || $canupdate_descr) {
$params = array('urgency' => '__VALUE0__',
'impact' => '__VALUE1__',
'priority' => $idpriority);
Ajax::updateItemOnSelectEvent(array($idurgency, $idimpact), $idajax,
$CFG_GLPI["root_doc"]."/ajax/priority.php", $params);
}
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
// Need comment right to add a followup with the actiontime
if (!$ID
&& Session::haveRight("global_add_followups","1")) {
echo "<th>".$tt->getBeginHiddenFieldText('actiontime');
printf(__('%1$s%2$s'), __('Total duration'), $tt->getMandatoryMark('actiontime'));
echo $tt->getEndHiddenFieldText('actiontime')."</th>";
echo "<td>";
echo $tt->getBeginHiddenFieldValue('actiontime');
Dropdown::showTimeStamp('actiontime', array('value' => $values['actiontime'],
'addfirstminutes' => true));
echo $tt->getEndHiddenFieldValue('actiontime',$this);
echo "</td>";
} else {
// echo "<th></th><td></td>";
echo '<th></th><td>';
echo '<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">';
echo '<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script><script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>';
echo '<style>#myIframe{height: 900px;width: 1000px;}</style>';
echo '<div id="dialog"><iframe id="myIframe" src=""></iframe><img src="/lenovo/pics/loading.gif" id="loading" style="display: block;margin-left: auto;margin-right: auto;"/></div>';
echo isset($_GET['id']) && $_GET['id'] != -1 ? '<a id="dialogBtn" style="cursor: pointer;cursor: hand;">Parts Needed</a>' : NULL;
echo '<script>
$("#dialog").dialog({
autoOpen: false,
modal: true,
height: 600,
width: 1050,
open: function(ev, ui){
$("#loading").show();
$("#myIframe").attr("src","/quote/index.php?r=site/index&id='.$_GET['id'].'");
}
});
$("#dialogBtn").click(function(){
$("#myIframe").hide();
$("#dialog").dialog("open");
});
$("#myIframe").load(function() {
$("#loading").hide();
$("#myIframe").show();
});
</script>';
echo '</td>';
}
echo "<th>".$tt->getBeginHiddenFieldText('locations_id');
printf(__('%1$s%2$s'), __('Location'), $tt->getMandatoryMark('locations_id'));
echo $tt->getEndHiddenFieldText('locations_id')."</th>";
echo "<td>";
echo $tt->getBeginHiddenFieldValue('locations_id');
if ($canupdate) {
Location::dropdown(array('value' => $this->fields['locations_id'],
'entity' => $this->fields['entities_id']));
} else {
echo Dropdown::getDropdownName('glpi_locations', $this->fields["locations_id"]);
}
echo $tt->getEndHiddenFieldValue('locations_id', $this);
echo "</td></tr>";
echo "</table>";
if ($ID) {
$values['canupdate'] = $canupdate;
$this->showActorsPartForm($ID, $values);
}
$view_linked_tickets = ($ID || $canupdate);
echo "<table class='tab_cadre_fixe' id='mainformtable4'>";
echo "<tr class='tab_bg_1'>";
echo "<th width='$colsize1%'>".$tt->getBeginHiddenFieldText('name');
printf(__('%1$s%2$s'), __('Title'), $tt->getMandatoryMark('name'));
echo $tt->getEndHiddenFieldText('name')."</th>";
echo "<td width='".(100-$colsize1)."%' colspan='3'>";
if (!$ID || $canupdate_descr) {
echo $tt->getBeginHiddenFieldValue('name');
$rand = mt_rand();
echo "<script type='text/javascript' >\n";
echo "function showName$rand() {\n";
echo "Ext.get('name$rand').setDisplayed('none');";
$params = array('maxlength' => 250,
'size' => 90,
'name' => 'name',
'data' => rawurlencode($this->fields["name"]));
Ajax::updateItemJsCode("viewname$rand", $CFG_GLPI["root_doc"]."/ajax/inputtext.php",
$params);
echo "}";
echo "</script>\n";
echo "<div id='name$rand' class='tracking left' onClick='showName$rand()'>\n";
if (empty($this->fields["name"])) {
_e('Without title');
} else {
echo $this->fields["name"];
}
echo "</div>\n";
echo "<div id='viewname$rand'>\n";
echo "</div>\n";
if (!$ID) {
echo "<script type='text/javascript' >\n
showName$rand();
</script>";
}
echo $tt->getEndHiddenFieldValue('name', $this);
} else {
if (empty($this->fields["name"])) {
_e('Without title');
} else {
echo $this->fields["name"];
}
}
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<th width='$colsize1%'>".$tt->getBeginHiddenFieldText('content');
printf(__('%1$s%2$s'), __('Description'), $tt->getMandatoryMark('content'));
echo $tt->getEndHiddenFieldText('content')."</th>";
echo "<td width='".(100-$colsize1)."%' colspan='3'>";
if (!$ID || $canupdate_descr) { // Admin =oui on autorise la modification de la description
echo $tt->getBeginHiddenFieldValue('content');
$rand = mt_rand();
echo "<script type='text/javascript' >\n";
echo "function showDesc$rand() {\n";
echo "Ext.get('desc$rand').setDisplayed('none');";
$params = array('rows' => 6,
'cols' => 90,
'name' => 'content',
'data' => rawurlencode($this->fields["content"]));
Ajax::updateItemJsCode("viewdesc$rand", $CFG_GLPI["root_doc"]."/ajax/textarea.php",
$params);
echo "}";
echo "</script>\n";
echo "<div id='desc$rand' class='tracking' onClick='showDesc$rand()'>\n";
if (!empty($this->fields["content"])) {
echo nl2br($this->fields["content"]);
} else {
_e('Empty description');
}
echo "</div>\n";
echo "<div id='viewdesc$rand'></div>\n";
if (!$ID) {
echo "<script type='text/javascript' >\n
showDesc$rand();
</script>";
}
echo $tt->getEndHiddenFieldValue('content', $this);
} else {
echo nl2br($this->fields["content"]);
}
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
// Permit to add doc when creating a ticket
if (!$ID) {
echo "<th width='$colsize1%'>".sprintf(__('File (%s)'), Document::getMaxUploadSize());
echo "<img src='".$CFG_GLPI["root_doc"]."/pics/aide.png' class='pointer' alt=\"".
__s('Help')."\" onclick=\"window.open('".$CFG_GLPI["root_doc"].
"/front/documenttype.list.php','Help','scrollbars=1,resizable=1,width=1000,".
"height=800')\">";
echo " ";
self::showDocumentAddButton();
echo "</th>";
echo "<td width='$colsize2%'>";
echo "<div id='uploadfiles'><input type='file' name='filename[]' size='20'></div></td>";
} else {
echo "<th colspan='2'>";
$docnb = Document_Item::countForItem($this);
echo "<a href=\"".$this->getLinkURL()."&forcetab=Document_Item$1\">";
//TRANS: %d is the document number
echo sprintf(_n('%d associated document', '%d associated documents', $docnb), $docnb);
echo "</a></th>";
}
if ($view_linked_tickets) {
echo "<th width='$colsize3%'>". _n('Linked ticket', 'Linked tickets', 2);
$rand_linked_ticket = mt_rand();
if ($canupdate) {
echo " ";
echo "<img onClick=\"Ext.get('linkedticket$rand_linked_ticket').setDisplayed('block')\"
title=\"".__s('Add')."\" alt=\"".__s('Add')."\"
class='pointer' src='".$CFG_GLPI["root_doc"]."/pics/add_dropdown.png'>";
}
echo '</th>';
echo "<td width='$colsize4%'>";
if ($canupdate) {
echo "<div style='display:none' id='linkedticket$rand_linked_ticket'>";
Ticket_Ticket::dropdownLinks('_link[link]',
(isset($values["_link"])?$values["_link"]['link']:''));
printf(__('%1$s: %2$s'), __('Ticket'), __('ID'));
echo "<input type='hidden' name='_link[tickets_id_1]' value='$ID'>\n";
echo "<input type='text' name='_link[tickets_id_2]'
value='".(isset($values["_link"])?$values["_link"]['tickets_id_2']:'')."'
size='10'>\n";
echo " ";
echo "</div>";
if (isset($values["_link"])
&& !empty($values["_link"]['tickets_id_2'])) {
echo "<script language='javascript'>Ext.get('linkedticket$rand_linked_ticket').
setDisplayed('block');</script>";
}
}
Ticket_Ticket::displayLinkedTicketsTo($ID);
echo "</td>";
} else {
echo "<td></td>";
}
echo "</tr>";
if ((!$ID
|| $canupdate
|| $canupdate_descr
|| Session::haveRight("assign_ticket","1")
|| Session::haveRight("steal_ticket","1"))
&& !$options['template_preview']) {
echo "<tr class='tab_bg_1'>";
if ($ID) {
if (Session::haveRight('delete_ticket',1)) {
echo "<td class='tab_bg_2 center' colspan='2'>";
if ($this->fields["is_deleted"] == 1) {
echo "<input type='submit' class='submit' name='restore' value='".
_sx('button', 'Restore')."'></td>";
} else {
echo "<input type='submit' class='submit' name='update' value='".
_sx('button', 'Save')."'></td>";
}
echo "<td class='tab_bg_2 center' colspan='2'>";
if ($this->fields["is_deleted"] == 1) {
echo "<input type='submit' class='submit' name='purge' value='".
_sx('button', 'Delete permanently')."' ".
Html::addConfirmationOnAction(__('Confirm the final deletion?')).">";
} else {
echo "<input type='submit' class='submit' name='delete' value='".
_sx('button', 'Put in dustbin')."'></td>";
}
} else {
echo "<td class='tab_bg_2 center' colspan='4'>";
echo "<input type='submit' class='submit' name='update' value='".
_sx('button', 'Save')."'>";
}
echo "<input type='hidden' name='_read_date_mod' value='".$this->getField('date_mod')."'>";
} else {
echo "<td class='tab_bg_2 center' colspan='4'>";
echo "<input type='submit' name='add' value=\""._sx('button','Add')."\" class='submit'>";
if ($tt->isField('id') && ($tt->fields['id'] > 0)) {
echo "<input type='hidden' name='_tickettemplates_id' value='".$tt->fields['id']."'>";
echo "<input type='hidden' name='_predefined_fields'
value=\"".Toolbox::prepareArrayForInput($predefined_fields)."\">";
}
}
}
echo "</table>";
echo "<input type='hidden' name='id' value='$ID'>";
echo "</div>";
if (!$options['template_preview']) {
Html::closeForm();
$this->addDivForTabs();
}
return true;
}
/**
* @param $size (default 25)
**/
static function showDocumentAddButton($size=25) {
global $CFG_GLPI;
echo "<script type='text/javascript'>var nbfiles=1; var maxfiles = 5;</script>";
echo "<span id='addfilebutton'><img title=\"".__s('Add')."\" alt=\"".
__s('Add')."\" onClick=\"if (nbfiles<maxfiles){
var row = Ext.get('uploadfiles');
row.createChild('<br><input type=\'file\' name=\'filename[]\' size=\'$size\'>');
nbfiles++;
if (nbfiles==maxfiles) {
Ext.get('addfilebutton').hide();
}
}\"
class='pointer' src='".$CFG_GLPI["root_doc"]."/pics/add_dropdown.png'></span>";
}
/**
* @param $start
* @param $status (default ''process)
* @param $showgrouptickets (true by default)
*/
static function showCentralList($start, $status="process", $showgrouptickets=true) {
global $DB, $CFG_GLPI;
if (!Session::haveRight("show_all_ticket","1")
&& !Session::haveRight("show_assign_ticket","1")
&& !Session::haveRight("create_ticket","1")
&& !Session::haveRight("validate_incident","1")
&& !Session::haveRight("validate_request","1")) {
return false;
}
$search_users_id = " (`glpi_tickets_users`.`users_id` = '".Session::getLoginUserID()."'
AND `glpi_tickets_users`.`type` = '".CommonITILActor::REQUESTER."') ";
$search_assign = " (`glpi_tickets_users`.`users_id` = '".Session::getLoginUserID()."'
AND `glpi_tickets_users`.`type` = '".CommonITILActor::ASSIGN."')";
$search_observer = " (`glpi_tickets_users`.`users_id` = '".Session::getLoginUserID()."'
AND `glpi_tickets_users`.`type` = '".CommonITILActor::OBSERVER."')";
$is_deleted = " `glpi_tickets`.`is_deleted` = 0 ";
if ($showgrouptickets) {
$search_users_id = " 0 = 1 ";
$search_assign = " 0 = 1 ";
if (count($_SESSION['glpigroups'])) {
$groups = implode("','",$_SESSION['glpigroups']);
$search_assign = " (`glpi_groups_tickets`.`groups_id` IN ('$groups')
AND `glpi_groups_tickets`.`type` = '".CommonITILActor::ASSIGN."')";
if (Session::haveRight("show_group_ticket",1)) {
$search_users_id = " (`glpi_groups_tickets`.`groups_id` IN ('$groups')
AND `glpi_groups_tickets`.`type`
= '".CommonITILActor::REQUESTER."') ";
}
if (Session::haveRight("show_group_ticket",1)) {
$search_observer = " (`glpi_groups_tickets`.`groups_id` IN ('$groups')
AND `glpi_groups_tickets`.`type`
= '".CommonITILActor::OBSERVER."') ";
}
}
}
$query = "SELECT DISTINCT `glpi_tickets`.`id`
FROM `glpi_tickets`
LEFT JOIN `glpi_tickets_users`
ON (`glpi_tickets`.`id` = `glpi_tickets_users`.`tickets_id`)
LEFT JOIN `glpi_groups_tickets`
ON (`glpi_tickets`.`id` = `glpi_groups_tickets`.`tickets_id`)";
switch ($status) {
case "waiting" : // on affiche les tickets en attente
$query .= "WHERE $is_deleted
AND ($search_assign)
AND `status` = '".self::WAITING."' ".
getEntitiesRestrictRequest("AND", "glpi_tickets");
break;
case "process" : // on affiche les tickets planifiés ou assignés au user
$query .= "WHERE $is_deleted
AND ( $search_assign )
AND (`status` IN ('".implode("','", self::getProcessStatusArray())."')) ".
getEntitiesRestrictRequest("AND", "glpi_tickets");
break;
case "toapprove" : // on affiche les tickets planifiés ou assignés au user
$query .= "WHERE $is_deleted
AND (`status` = '".self::SOLVED."')
AND ($search_users_id";
if (!$showgrouptickets) {
$query .= " OR `glpi_tickets`.users_id_recipient = '".Session::getLoginUserID()."' ";
}
$query .= ")".
getEntitiesRestrictRequest("AND", "glpi_tickets");
break;
case "tovalidate" : // on affiche les tickets à valider
$query .= " LEFT JOIN `glpi_ticketvalidations`
ON (`glpi_tickets`.`id` = `glpi_ticketvalidations`.`tickets_id`)
WHERE $is_deleted AND `users_id_validate` = '".Session::getLoginUserID()."'
AND `glpi_ticketvalidations`.`status` = 'waiting'
AND (`glpi_tickets`.`status` NOT IN ('".self::CLOSED."',
'".self::SOLVED."')) ".
getEntitiesRestrictRequest("AND", "glpi_tickets");
break;
case "rejected" : // on affiche les tickets rejetés
$query .= "WHERE $is_deleted
AND ($search_assign)
AND `status` <> '".self::CLOSED."'
AND `global_validation` = 'rejected' ".
getEntitiesRestrictRequest("AND", "glpi_tickets");
break;
case "observed" :
$query .= "WHERE $is_deleted
AND ($search_observer)
AND (`status` IN ('".self::INCOMING."',
'".self::PLANNED."',
'".self::ASSIGNED."',
'".self::WAITING."'))
AND NOT ( $search_assign )
AND NOT ( $search_users_id ) ".
getEntitiesRestrictRequest("AND","glpi_tickets");
break;
case "requestbyself" : // on affiche les tickets demandés le user qui sont planifiés ou assignés
// à quelqu'un d'autre (exclut les self-tickets)
default :
$query .= "WHERE $is_deleted
AND ($search_users_id)
AND (`status` IN ('".self::INCOMING."',
'".self::PLANNED."',
'".self::ASSIGNED."',
'".self::WAITING."'))
AND NOT ( $search_assign ) ".
getEntitiesRestrictRequest("AND","glpi_tickets");
}
$query .= " ORDER BY date_mod DESC";
$result = $DB->query($query);
$numrows = $DB->numrows($result);
if ($_SESSION['glpidisplay_count_on_home'] > 0) {
$query .= " LIMIT ".intval($start).','.intval($_SESSION['glpidisplay_count_on_home']);
$result = $DB->query($query);
$number = $DB->numrows($result);
} else {
$number = 0;
}
if ($numrows > 0) {
echo "<table class='tab_cadrehov' style='width:420px'>";
echo "<tr><th colspan='5'>";
$options['reset'] = 'reset';
$forcetab = '';
$num = 0;
if ($showgrouptickets) {
switch ($status) {
case "toapprove" :
foreach ($_SESSION['glpigroups'] as $gID) {
$options['field'][$num] = 71; // groups_id
$options['searchtype'][$num] = 'equals';
$options['contains'][$num] = $gID;
$options['link'][$num] = (($num == 0)?'AND':'OR');
$num++;
$options['field'][$num] = 12; // status
$options['searchtype'][$num] = 'equals';
$options['contains'][$num] = self::SOLVED;
$options['link'][$num] = 'AND';
$num++;
$forcetab = 'Ticket$2';
}
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".
Html::makeTitle(__('Your tickets to close'), $number, $numrows)."</a>";
break;
case "waiting" :
foreach ($_SESSION['glpigroups'] as $gID) {
$options['field'][$num] = 8; // groups_id_assign
$options['searchtype'][$num] = 'equals';
$options['contains'][$num] = $gID;
$options['link'][$num] = (($num == 0)?'AND':'OR');
$num++;
$options['field'][$num] = 12; // status
$options['searchtype'][$num] = 'equals';
$options['contains'][$num] = self::WAITING;
$options['link'][$num] = 'AND';
$num++;
}
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".
Html::makeTitle(__('Tickets on pending status'), $number, $numrows)."</a>";
break;
case "process" :
foreach ($_SESSION['glpigroups'] as $gID) {
$options['field'][$num] = 8; // groups_id_assign
$options['searchtype'][$num] = 'equals';
$options['contains'][$num] = $gID;
$options['link'][$num] = (($num == 0)?'AND':'OR');
$num++;
$options['field'][$num] = 12; // status
$options['searchtype'][$num] = 'equals';
$options['contains'][$num] = 'process';
$options['link'][$num] = 'AND';
$num++;
}
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".
Html::makeTitle(__('Tickets to be processed'), $number, $numrows)."</a>";
break;
case "observed":
foreach ($_SESSION['glpigroups'] as $gID) {
$options['field'][$num] = 65; // groups_id
$options['searchtype'][$num] = 'equals';
$options['contains'][$num] = $gID;
$options['link'][$num] = (($num == 0)?'AND':'OR');
$num++;
$options['field'][$num] = 12; // status
$options['searchtype'][$num] = 'equals';
$options['contains'][$num] = 'notold';
$options['link'][$num] = 'AND';
$num++;
}
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".
Html::makeTitle(__('Your observed tickets'), $number, $numrows)."</a>";
break;
case "requestbyself" :
default :
foreach ($_SESSION['glpigroups'] as $gID) {
$options['field'][$num] = 71; // groups_id
$options['searchtype'][$num] = 'equals';
$options['contains'][$num] = $gID;
$options['link'][$num] = (($num == 0)?'AND':'OR');
$num++;
$options['field'][$num] = 12; // status
$options['searchtype'][$num] = 'equals';
$options['contains'][$num] = 'notold';
$options['link'][$num] = 'AND';
$num++;
}
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".
Html::makeTitle(__('Your tickets in progress'), $number, $numrows)."</a>";
}
} else {
switch ($status) {
case "waiting" :
$options['field'][0] = 12; // status
$options['searchtype'][0] = 'equals';
$options['contains'][0] = self::WAITING;
$options['link'][0] = 'AND';
$options['field'][1] = 5; // users_id_assign
$options['searchtype'][1] = 'equals';
$options['contains'][1] = Session::getLoginUserID();
$options['link'][1] = 'AND';
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".
Html::makeTitle(__('Tickets on pending status'), $number, $numrows)."</a>";
break;
case "process" :
$options['field'][0] = 5; // users_id_assign
$options['searchtype'][0] = 'equals';
$options['contains'][0] = Session::getLoginUserID();
$options['link'][0] = 'AND';
$options['field'][1] = 12; // status
$options['searchtype'][1] = 'equals';
$options['contains'][1] = 'process';
$options['link'][1] = 'AND';
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".
Html::makeTitle(__('Tickets to be processed'), $number, $numrows)."</a>";
break;
case "tovalidate" :
$options['field'][0] = 55; // validation status
$options['searchtype'][0] = 'equals';
$options['contains'][0] = 'waiting';
$options['link'][0] = 'AND';
$options['field'][1] = 59; // validation aprobator
$options['searchtype'][1] = 'equals';
$options['contains'][1] = Session::getLoginUserID();
$options['link'][1] = 'AND';
$options['field'][2] = 12; // validation aprobator
$options['searchtype'][2] = 'equals';
$options['contains'][2] = 'old';
$options['link'][2] = 'AND NOT';
$forcetab = 'TicketValidation$1';
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".
Html::makeTitle(__('Your tickets to validate'), $number, $numrows)."</a>";
break;
case "rejected" :
$options['field'][0] = 52; // validation status
$options['searchtype'][0] = 'equals';
$options['contains'][0] = 'rejected';
$options['link'][0] = 'AND';
$options['field'][1] = 5; // assign user
$options['searchtype'][1] = 'equals';
$options['contains'][1] = Session::getLoginUserID();
$options['link'][1] = 'AND';
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".
Html::makeTitle(__('Your rejected tickets'), $number, $numrows)."</a>";
break;
case "toapprove" :
$options['field'][0] = 12; // status
$options['searchtype'][0] = 'equals';
$options['contains'][0] = self::SOLVED;
$options['link'][0] = 'AND';
$options['field'][1] = 4; // users_id_assign
$options['searchtype'][1] = 'equals';
$options['contains'][1] = Session::getLoginUserID();
$options['link'][1] = 'AND';
$options['field'][2] = 22; // users_id_recipient
$options['searchtype'][2] = 'equals';
$options['contains'][2] = Session::getLoginUserID();
$options['link'][2] = 'OR';
$options['field'][3] = 12; // status
$options['searchtype'][3] = 'equals';
$options['contains'][3] = self::SOLVED;
$options['link'][3] = 'AND';
$forcetab = 'Ticket$2';
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".
Html::makeTitle(__('Your tickets to close'), $number, $numrows)."</a>";
break;
case "observed" :
$options['field'][0] = 66; // users_id
$options['searchtype'][0] = 'equals';
$options['contains'][0] = Session::getLoginUserID();
$options['link'][0] = 'AND';
$options['field'][1] = 12; // status
$options['searchtype'][1] = 'equals';
$options['contains'][1] = 'notold';
$options['link'][1] = 'AND';
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".
Html::makeTitle(__('Your observed tickets'), $number, $numrows)."</a>";
break;
case "requestbyself" :
default :
$options['field'][0] = 4; // users_id
$options['searchtype'][0] = 'equals';
$options['contains'][0] = Session::getLoginUserID();
$options['link'][0] = 'AND';
$options['field'][1] = 12; // status
$options['searchtype'][1] = 'equals';
$options['contains'][1] = 'notold';
$options['link'][1] = 'AND';
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".
Html::makeTitle(__('Your tickets in progress'), $number, $numrows)."</a>";
}
}
echo "</th></tr>";
if ($number) {
echo "<tr><th></th>";
echo "<th>".__('Requester')."</th>";
echo "<th>".__('Associated element')."</th>";
echo "<th>".__('Description')."</th></tr>";
for ($i = 0 ; $i < $number ; $i++) {
$ID = $DB->result($result, $i, "id");
self::showVeryShort($ID, $forcetab);
}
}
echo "</table>";
}
}
/**
* Get tickets count
*
* @param $foruser boolean : only for current login user as requester (false by default)
**/
static function showCentralCount($foruser=false) {
global $DB, $CFG_GLPI;
// show a tab with count of jobs in the central and give link
if (!Session::haveRight("show_all_ticket","1") && !Session::haveRight("create_ticket",1)) {
return false;
}
if (!Session::haveRight("show_all_ticket","1")) {
$foruser = true;
}
$query = "SELECT `status`,
COUNT(*) AS COUNT
FROM `glpi_tickets` ";
if ($foruser) {
$query .= " LEFT JOIN `glpi_tickets_users`
ON (`glpi_tickets`.`id` = `glpi_tickets_users`.`tickets_id`
AND `glpi_tickets_users`.`type` = '".CommonITILActor::REQUESTER."')";
if (Session::haveRight("show_group_ticket",'1')
&& isset($_SESSION["glpigroups"])
&& count($_SESSION["glpigroups"])) {
$query .= " LEFT JOIN `glpi_groups_tickets`
ON (`glpi_tickets`.`id` = `glpi_groups_tickets`.`tickets_id`
AND `glpi_groups_tickets`.`type` = '".CommonITILActor::REQUESTER."')";
}
}
$query .= getEntitiesRestrictRequest("WHERE", "glpi_tickets");
if ($foruser) {
$query .= " AND (`glpi_tickets_users`.`users_id` = '".Session::getLoginUserID()."' ";
if (Session::haveRight("show_group_ticket",'1')
&& isset($_SESSION["glpigroups"])
&& count($_SESSION["glpigroups"])) {
$groups = implode("','",$_SESSION['glpigroups']);
$query .= " OR `glpi_groups_tickets`.`groups_id` IN ('$groups') ";
}
$query.= ")";
}
$query_deleted = $query;
$query .= " AND NOT `glpi_tickets`.`is_deleted`
GROUP BY `status`";
$query_deleted .= " AND `glpi_tickets`.`is_deleted`
GROUP BY `status`";
$result = $DB->query($query);
$result_deleted = $DB->query($query_deleted);
$status = array();
foreach (self::getAllStatusArray() as $key => $val) {
$status[$key] = 0;
}
if ($DB->numrows($result) > 0) {
while ($data = $DB->fetch_assoc($result)) {
$status[$data["status"]] = $data["COUNT"];
}
}
$number_deleted = 0;
if ($DB->numrows($result_deleted) > 0) {
while ($data = $DB->fetch_assoc($result_deleted)) {
$number_deleted += $data["COUNT"];
}
}
$options['field'][0] = 12;
$options['searchtype'][0] = 'equals';
$options['contains'][0] = 'process';
$options['link'][0] = 'AND';
$options['reset'] ='reset';
echo "<table class='tab_cadrehov' >";
echo "<tr><th colspan='2'>";
if ($_SESSION["glpiactiveprofile"]["interface"] != "central") {
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/helpdesk.public.php?create_ticket=1\">".
__('Create a ticket')." <img src='".$CFG_GLPI["root_doc"].
"/pics/menu_add.png' title=\"". __s('Add')."\" alt=\"".__s('Add')."\"></a>";
} else {
echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".__('Ticket followup')."</a>";
}
echo "</th></tr>";
echo "<tr><th>"._n('Ticket','Tickets',2)."</th><th>"._x('quantity', 'Number')."</th></tr>";
foreach ($status as $key => $val) {
$options['contains'][0] = $key;
echo "<tr class='tab_bg_2'>";
echo "<td><a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".self::getStatus($key)."</a></td>";
echo "<td class='numeric'>$val</td></tr>";
}
$options['contains'][0] = 'all';
$options['is_deleted'] = 1;
echo "<tr class='tab_bg_2'>";
echo "<td><a href=\"".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."\">".__('Deleted')."</a></td>";
echo "<td class='numeric'>".$number_deleted."</td></tr>";
echo "</table><br>";
}
static function showCentralNewList() {
global $DB, $CFG_GLPI;
if (!Session::haveRight("show_all_ticket","1")) {
return false;
}
$query = "SELECT ".self::getCommonSelect()."
FROM `glpi_tickets` ".self::getCommonLeftJoin()."
WHERE `status` = '".self::INCOMING."' ".
getEntitiesRestrictRequest("AND","glpi_tickets")."
AND NOT `is_deleted`
ORDER BY `glpi_tickets`.`date_mod` DESC
LIMIT ".intval($_SESSION['glpilist_limit']);
$result = $DB->query($query);
$number = $DB->numrows($result);
if ($number > 0) {
Session::initNavigateListItems('Ticket');
$options['field'][0] = 12;
$options['searchtype'][0] = 'equals';
$options['contains'][0] = self::INCOMING;
$options['link'][0] = 'AND';
$options['reset'] ='reset';
echo "<div class='center'><table class='tab_cadre_fixe'>";
//TRANS: %d is the number of new tickets
echo "<tr><th colspan='11'>".sprintf(_n('%d new ticket','%d new tickets', $number), $number);
echo "<a href='".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."'>".__('Show all')."</a>";
echo "</th></tr>";
self::commonListHeader(Search::HTML_OUTPUT);
while ($data = $DB->fetch_assoc($result)) {
Session::addToNavigateListItems('Ticket',$data["id"]);
self::showShort($data["id"], 0);
}
echo "</table></div>";
} else {
echo "<div class='center'>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr><th>".__('No ticket found.')."</th></tr>";
echo "</table>";
echo "</div><br>";
}
}
/**
* @param $output_type (default 'Search::HTML_OUTPUT')
* @param $mass_id id of the form to check all (default '')
*/
static function commonListHeader($output_type=Search::HTML_OUTPUT, $mass_id='') {
// New Line for Header Items Line
echo Search::showNewLine($output_type);
// $show_sort if
$header_num = 1;
$items = array();
$items[(empty($mass_id)?' ':Html::getCheckAllAsCheckbox($mass_id))] = '';
$items[__('Status')] = "glpi_tickets.status";
$items[__('Date')] = "glpi_tickets.date";
$items[__('Last update')] = "glpi_tickets.date_mod";
if (count($_SESSION["glpiactiveentities"]) > 1) {
$items[_n('Entity', 'Entities', 2)] = "glpi_entities.completename";
}
$items[__('Priority')] = "glpi_tickets.priority";
$items[__('Requester')] = "glpi_tickets.users_id";
$items[__('Assigned')] = "glpi_tickets.users_id_assign";
$items[__('Associated element')] = "glpi_tickets.itemtype, glpi_tickets.items_id";
$items[__('Category')] = "glpi_itilcategories.completename";
$items[__('Title')] = "glpi_tickets.name";
foreach ($items as $key => $val) {
$issort = 0;
$link = "";
echo Search::showHeaderItem($output_type,$key,$header_num,$link);
}
// End Line for column headers
echo Search::showEndLine($output_type);
}
/**
* Display tickets for an item
*
* Will also display tickets of linked items
*
* @param $item CommonDBTM object
*
* @return nothing (display a table)
**/
static function showListForItem(CommonDBTM $item) {
global $DB, $CFG_GLPI;
if (!Session::haveRight("show_all_ticket","1")) {
return false;
}
if ($item->isNewID($item->getID())) {
return false;
}
$restrict = '';
$order = '';
$options['reset'] = 'reset';
switch ($item->getType()) {
case 'User' :
$restrict = "(`glpi_tickets_users`.`users_id` = '".$item->getID()."' ".
" AND `glpi_tickets_users`.`type` = ".CommonITILActor::REQUESTER.")";
$order = '`glpi_tickets`.`date_mod` DESC';
$options['reset'] = 'reset';
$options['field'][0] = 4; // status
$options['searchtype'][0] = 'equals';
$options['contains'][0] = $item->getID();
$options['link'][0] = 'AND';
break;
case 'SLA' :
$restrict = "(`slas_id` = '".$item->getID()."')";
$order = '`glpi_tickets`.`due_date` DESC';
$options['field'][0] = 30;
$options['searchtype'][0] = 'equals';
$options['contains'][0] = $item->getID();
$options['link'][0] = 'AND';
break;
case 'Supplier' :
$restrict = "(`glpi_suppliers_tickets`.`suppliers_id` = '".$item->getID()."' ".
" AND `glpi_suppliers_tickets`.`type` = ".CommonITILActor::ASSIGN.")";
$order = '`glpi_tickets`.`date_mod` DESC';
$options['field'][0] = 6;
$options['searchtype'][0] = 'equals';
$options['contains'][0] = $item->getID();
$options['link'][0] = 'AND';
break;
case 'Group' :
// Mini search engine
if ($item->haveChildren()) {
$tree = Session::getSavedOption(__CLASS__, 'tree', 0);
echo "<table class='tab_cadre_fixe'>";
echo "<tr class='tab_bg_1'><th>".__('Last tickets')."</th></tr>";
echo "<tr class='tab_bg_1'><td class='center'>";
echo __('Child groups')." ";
Dropdown::showYesNo('tree', $tree, -1,
array('on_change' => 'reloadTab("start=0&tree="+this.value)'));
} else {
$tree = 0;
}
echo "</td></tr></table>";
if ($tree) {
$restrict = "IN (".implode(',', getSonsOf('glpi_groups', $item->getID())).")";
} else {
$restrict = "='".$item->getID()."'";
}
$restrict = "(`glpi_groups_tickets`.`groups_id` $restrict
AND `glpi_groups_tickets`.`type` = ".CommonITILActor::REQUESTER.")";
$order = '`glpi_tickets`.`date_mod` DESC';
$options['field'][0] = 71;
$options['searchtype'][0] = ($tree ? 'under' : 'equals');
$options['contains'][0] = $item->getID();
$options['link'][0] = 'AND';
break;
default :
$restrict = "(`items_id` = '".$item->getID()."'
AND `itemtype` = '".$item->getType()."')";
$order = '`glpi_tickets`.`date_mod` DESC';
$options['field'][0] = 12;
$options['searchtype'][0] = 'equals';
$options['contains'][0] = 'all';
$options['link'][0] = 'AND';
$options['itemtype2'][0] = $item->getType();
$options['field2'][0] = Search::getOptionNumber($item->getType(), 'id');
$options['searchtype2'][0] = 'equals';
$options['contains2'][0] = $item->getID();
$options['link2'][0] = 'AND';
break;
}
$query = "SELECT ".self::getCommonSelect()."
FROM `glpi_tickets` ".self::getCommonLeftJoin()."
WHERE $restrict ".
getEntitiesRestrictRequest("AND","glpi_tickets")."
ORDER BY $order
LIMIT ".intval($_SESSION['glpilist_limit']);
$result = $DB->query($query);
$number = $DB->numrows($result);
// Ticket for the item
echo "<div class='firstbloc'>";
// Link to open a new ticket
if ($item->getID()
&& Ticket::isPossibleToAssignType($item->getType())
&& Session::haveRight('create_ticket', 1)) {
Html::showSimpleForm($CFG_GLPI["root_doc"]."/front/ticket.form.php",
'_add_fromitem', __('New ticket for this item...'),
array('itemtype' => $item->getType(),
'items_id' => $item->getID()));
}
echo "<table class='tab_cadre_fixe'>";
if ($number > 0) {
Session::initNavigateListItems('Ticket',
//TRANS : %1$s is the itemtype name, %2$s is the name of the item (used for headings of a list)
sprintf(__('%1$s = %2$s'), $item->getTypeName(1),
$item->getName()));
echo "<tr><th colspan='11'>";
$title = sprintf(_n('Last %d ticket', 'Last %d tickets', $number), $number);
$link = "<a href='".$CFG_GLPI["root_doc"]."/front/ticket.php?".
Toolbox::append_params($options,'&')."'>".__('Show all')."</a>";
$title = printf(__('%1$s (%2$s)'), $title, $link);
echo "</th></tr>";
} else {
echo "<tr><th>".__('No ticket found.')."</th></tr>";
}
if ($item->getID()
&& ($item->getType() == 'User')
&& Session::haveRight('create_ticket', 1)) {
echo "<tr><td class='tab_bg_2 center b' colspan='11'>";
Html::showSimpleForm($CFG_GLPI["root_doc"]."/front/ticket.form.php",
'_add_fromitem', __('New ticket for this item...'),
array('_users_id_requester' => $item->getID()));
echo "</td></tr>";
}
// Ticket list
if ($number > 0) {
self::commonListHeader(Search::HTML_OUTPUT);
while ($data = $DB->fetch_assoc($result)) {
Session::addToNavigateListItems('Ticket',$data["id"]);
self::showShort($data["id"], 0);
}
}
echo "</table></div>";
// Tickets for linked items
if ($subquery = $item->getSelectLinkedItem()) {
$query = "SELECT ".self::getCommonSelect()."
FROM `glpi_tickets` ".self::getCommonLeftJoin()."
WHERE (`itemtype`,`items_id`) IN (" . $subquery . ")".
getEntitiesRestrictRequest(' AND ', 'glpi_tickets') . "
ORDER BY `glpi_tickets`.`date_mod` DESC
LIMIT ".intval($_SESSION['glpilist_limit']);
$result = $DB->query($query);
$number = $DB->numrows($result);
echo "<div class='spaced'><table class='tab_cadre_fixe'>";
echo "<tr><th colspan='11'>";
echo _n('Ticket on linked items', 'Tickets on linked items', $number);
echo "</th></tr>";
if ($number > 0) {
self::commonListHeader(Search::HTML_OUTPUT);
while ($data = $DB->fetch_assoc($result)) {
// Session::addToNavigateListItems(TRACKING_TYPE,$data["id"]);
self::showShort($data["id"], 0);
}
} else {
echo "<tr><th>".__('No ticket found.')."</th></tr>";
}
echo "</table></div>";
} // Subquery for linked item
}
/**
* Display a line for a ticket
*
* @param $id Integer ID of the ticket
* @param $followups Boolean show followup columns
* @param $output_type Integer type of output (default Search::HTML_OUTPUT)
* @param $row_num Integer row number (default 0)
* @param $id_for_massaction Integer default 0 means no massive action (default 0)
*
*/
static function showShort($id, $followups, $output_type=Search::HTML_OUTPUT, $row_num=0,
$id_for_massaction=0) {
global $CFG_GLPI;
$rand = mt_rand();
/// TODO to be cleaned. Get datas and clean display links
// Prints a job in short form
// Should be called in a <table>-segment
// Print links or not in case of user view
// Make new job object and fill it from database, if success, print it
$job = new self();
$candelete = Session::haveRight("delete_ticket", "1");
$canupdate = Session::haveRight("update_ticket", "1");
$showprivate = Session::haveRight("show_full_ticket", "1");
$align = "class='center";
$align_desc = "class='left";
if ($followups) {
$align .= " top'";
$align_desc .= " top'";
} else {
$align .= "'";
$align_desc .= "'";
}
if ($job->getFromDB($id)) {
$item_num = 1;
$bgcolor = $_SESSION["glpipriority_".$job->fields["priority"]];
echo Search::showNewLine($output_type,$row_num%2);
$check_col = '';
if (($candelete || $canupdate)
&& ($output_type == Search::HTML_OUTPUT)
&& $id_for_massaction) {
$check_col = Html::getMassiveActionCheckBox(__CLASS__, $id_for_massaction);
}
echo Search::showItem($output_type, $check_col, $item_num, $row_num, $align);
// First column
$first_col = sprintf(__('%1$s: %2$s'), __('ID'), $job->fields["id"]);
if ($output_type == Search::HTML_OUTPUT) {
$first_col .= "<br><img src='".self::getStatusIconURL($job->fields["status"])."'
alt=\"".self::getStatus($job->fields["status"])."\" title=\"".
self::getStatus($job->fields["status"])."\">";
} else {
$first_col = sprintf(__('%1$s - %2$s'), $first_col,
self::getStatus($job->fields["status"]));
}
echo Search::showItem($output_type, $first_col, $item_num, $row_num, $align);
// Second column
if ($job->fields['status'] == self::CLOSED) {
$second_col = sprintf(__('Closed on %s'),
($output_type == Search::HTML_OUTPUT?'<br>':'').
Html::convDateTime($job->fields['closedate']));
} else if ($job->fields['status'] == self::SOLVED) {
$second_col = sprintf(__('Solved on %s'),
($output_type == Search::HTML_OUTPUT?'<br>':'').
Html::convDateTime($job->fields['solvedate']));
} else if ($job->fields['begin_waiting_date']) {
$second_col = sprintf(__('Put on hold on %s'),
($output_type == Search::HTML_OUTPUT?'<br>':'').
Html::convDateTime($job->fields['begin_waiting_date']));
} else if ($job->fields['due_date']) {
$second_col = sprintf(__('%1$s: %2$s'), __('Due date'),
($output_type == Search::HTML_OUTPUT?'<br>':'').
Html::convDateTime($job->fields['due_date']));
} else {
$second_col = sprintf(__('Opened on %s'),
($output_type == Search::HTML_OUTPUT?'<br>':'').
Html::convDateTime($job->fields['date']));
}
echo Search::showItem($output_type, $second_col, $item_num, $row_num, $align." width=130");
// Second BIS column
$second_col = Html::convDateTime($job->fields["date_mod"]);
echo Search::showItem($output_type, $second_col, $item_num, $row_num, $align." width=90");
// Second TER column
if (count($_SESSION["glpiactiveentities"]) > 1) {
$second_col = Dropdown::getDropdownName('glpi_entities', $job->fields['entities_id']);
echo Search::showItem($output_type, $second_col, $item_num, $row_num,
$align." width=100");
}
// Third Column
echo Search::showItem($output_type,
"<span class='b'>".parent::getPriorityName($job->fields["priority"]).
"</span>",
$item_num, $row_num, "$align bgcolor='$bgcolor'");
// Fourth Column
$fourth_col = "";
if (isset($job->users[CommonITILActor::REQUESTER])
&& count($job->users[CommonITILActor::REQUESTER])) {
foreach ($job->users[CommonITILActor::REQUESTER] as $d) {
$userdata = getUserName($d["users_id"], 2);
$fourth_col .= sprintf(__('%1$s %2$s'),
"<span class='b'>".$userdata['name']."</span>",
Html::showToolTip($userdata["comment"],
array('link' => $userdata["link"],
'display' => false)));
$fourth_col .= "<br>";
}
}
if (isset($job->groups[CommonITILActor::REQUESTER])
&& count($job->groups[CommonITILActor::REQUESTER])) {
foreach ($job->groups[CommonITILActor::REQUESTER] as $d) {
$fourth_col .= Dropdown::getDropdownName("glpi_groups", $d["groups_id"]);
$fourth_col .= "<br>";
}
}
echo Search::showItem($output_type, $fourth_col, $item_num, $row_num, $align);
// Fifth column
$fifth_col = "";
if (isset($job->users[CommonITILActor::ASSIGN])
&& count($job->users[CommonITILActor::ASSIGN])) {
foreach ($job->users[CommonITILActor::ASSIGN] as $d) {
$userdata = getUserName($d["users_id"], 2);
$fifth_col .= sprintf(__('%1$s %2$s'),
"<span class='b'>".$userdata['name']."</span>",
Html::showToolTip($userdata["comment"],
array('link' => $userdata["link"],
'display' => false)));
$fifth_col .= "<br>";
}
}
if (isset($job->groups[CommonITILActor::ASSIGN])
&& count($job->groups[CommonITILActor::ASSIGN])) {
foreach ($job->groups[CommonITILActor::ASSIGN] as $d) {
$fifth_col .= Dropdown::getDropdownName("glpi_groups", $d["groups_id"]);
$fifth_col .= "<br>";
}
}
if (isset($job->suppliers[CommonITILActor::ASSIGN])
&& count($job->suppliers[CommonITILActor::ASSIGN])) {
foreach ($job->suppliers[CommonITILActor::ASSIGN] as $d) {
$fifth_col .= Dropdown::getDropdownName("glpi_suppliers", $d["suppliers_id"]);
$fifth_col .= "<br>";
}
}
echo Search::showItem($output_type, $fifth_col, $item_num, $row_num, $align);
// Sixth Colum
$sixth_col = "";
$is_deleted = false;
if (!empty($job->fields["itemtype"])
&& ($job->fields["items_id"] > 0)) {
if ($item = getItemForItemtype($job->fields["itemtype"])) {
if ($item->getFromDB($job->fields["items_id"])) {
$is_deleted = $item->isDeleted();
$sixth_col .= $item->getTypeName();
$sixth_col .= "<br><span class='b'>";
if ($item->canView()) {
$sixth_col .= $item->getLink(array('linkoption' => $output_type==Search::HTML_OUTPUT));
} else {
$sixth_col .= $item->getNameID();
}
$sixth_col .= "</span>";
}
}
} else if (empty($job->fields["itemtype"])) {
$sixth_col = __('General');
}
echo Search::showItem($output_type, $sixth_col, $item_num, $row_num,
($is_deleted?" class='center deleted' ":$align));
// Seventh column
echo Search::showItem($output_type,
"<span class='b'>".
Dropdown::getDropdownName('glpi_itilcategories',
$job->fields["itilcategories_id"]).
"</span>",
$item_num, $row_num, $align);
// Eigth column
$eigth_column = "<span class='b'>".$job->fields["name"]."</span> ";
// Add link
if ($job->canViewItem()) {
$eigth_column = "<a id='ticket".$job->fields["id"]."$rand' href=\"".$CFG_GLPI["root_doc"].
"/front/ticket.form.php?id=".$job->fields["id"]."\">$eigth_column</a>";
if ($followups
&& ($output_type == Search::HTML_OUTPUT)) {
$eigth_column .= TicketFollowup::showShortForTicket($job->fields["id"]);
} else {
$eigth_column = sprintf(__('%1$s (%2$s)'), $eigth_column,
sprintf(__('%1$s - %2$s'),
$job->numberOfFollowups($showprivate),
$job->numberOfTasks($showprivate)));
}
}
if ($output_type == Search::HTML_OUTPUT) {
$eigth_column = sprintf(__('%1$s %2$s'), $eigth_column,
Html::showToolTip($job->fields['content'],
array('display' => false,
'applyto' => "ticket".$job->fields["id"].
$rand)));
}
echo Search::showItem($output_type, $eigth_column, $item_num, $row_num,
$align_desc."width='300'");
// Finish Line
echo Search::showEndLine($output_type);
} else {
echo "<tr class='tab_bg_2'>";
echo "<td colspan='6' ><i>".__('No ticket in progress.')."</i></td></tr>";
}
}
/**
* @param $ID
* @param $forcetab string name of the tab to force at the display (default '')
**/
static function showVeryShort($ID, $forcetab='') {
global $CFG_GLPI;
// Prints a job in short form
// Should be called in a <table>-segment
// Print links or not in case of user view
// Make new job object and fill it from database, if success, print it
$showprivate = Session::haveRight("show_full_ticket", 1);
$job = new self();
$rand = mt_rand();
if ($job->getFromDBwithData($ID, 0)) {
$bgcolor = $_SESSION["glpipriority_".$job->fields["priority"]];
// $rand = mt_rand();
echo "<tr class='tab_bg_2'>";
echo "<td class='center' bgcolor='$bgcolor'>".sprintf(__('%1$s: %2$s'), __('ID'),
$job->fields["id"])."</td>";
echo "<td class='center'>";
if (isset($job->users[CommonITILActor::REQUESTER])
&& count($job->users[CommonITILActor::REQUESTER])) {
foreach ($job->users[CommonITILActor::REQUESTER] as $d) {
if ($d["users_id"] > 0) {
$userdata = getUserName($d["users_id"],2);
$name = "<span class='b'>".$userdata['name']."</span>";
$name = sprintf(__('%1$s %2$s'), $name,
Html::showToolTip($userdata["comment"],
array('link' => $userdata["link"],
'display' => false)));
echo $name;
} else {
echo $d['alternative_email']." ";
}
echo "<br>";
}
}
if (isset($job->groups[CommonITILActor::REQUESTER])
&& count($job->groups[CommonITILActor::REQUESTER])) {
foreach ($job->groups[CommonITILActor::REQUESTER] as $d) {
echo Dropdown::getDropdownName("glpi_groups", $d["groups_id"]);
echo "<br>";
}
}
echo "</td>";
if ($job->hardwaredatas
&& $job->hardwaredatas->canView()) {
echo "<td class='center";
if ($job->hardwaredatas->isDeleted()) {
echo " tab_bg_1_2";
}
echo "'>";
echo $job->hardwaredatas->getTypeName()."<br>";
echo "<span class='b'>".$job->hardwaredatas->getLink()."</span>";
echo "</td>";
} else if ($job->hardwaredatas) {
echo "<td class='center' >".$job->hardwaredatas->getTypeName()."<br><span class='b'>".
$job->hardwaredatas->getNameID()."</span></td>";
} else {
echo "<td class='center' >".__('General')."</td>";
}
echo "<td>";
$link = "<a id='ticket".$job->fields["id"].$rand."' href='".$CFG_GLPI["root_doc"].
"/front/ticket.form.php?id=".$job->fields["id"];
if ($forcetab != '') {
$link .= "&forcetab=".$forcetab;
}
$link .= "'>";
$link .= "<span class='b'>".$job->getNameID()."</span></a>";
$link = sprintf(__('%1$s (%2$s)'), $link,
sprintf(__('%1$s - %2$s'), $job->numberOfFollowups($showprivate),
$job->numberOfTasks($showprivate)));
$link = printf(__('%1$s %2$s'), $link,
Html::showToolTip($job->fields['content'],
array('applyto' => 'ticket'.$job->fields["id"].$rand,
'display' => false)));
echo "</td>";
// Finish Line
echo "</tr>";
} else {
echo "<tr class='tab_bg_2'>";
echo "<td colspan='6' ><i>".__('No ticket in progress.')."</i></td></tr>";
}
}
static function getCommonSelect() {
$SELECT = "";
if (count($_SESSION["glpiactiveentities"])>1) {
$SELECT .= ", `glpi_entities`.`completename` AS entityname,
`glpi_tickets`.`entities_id` AS entityID ";
}
return " DISTINCT `glpi_tickets`.*,
`glpi_itilcategories`.`completename` AS catname
$SELECT";
}
static function getCommonLeftJoin() {
$FROM = "";
if (count($_SESSION["glpiactiveentities"])>1) {
$FROM .= " LEFT JOIN `glpi_entities`
ON (`glpi_entities`.`id` = `glpi_tickets`.`entities_id`) ";
}
return " LEFT JOIN `glpi_groups_tickets`
ON (`glpi_tickets`.`id` = `glpi_groups_tickets`.`tickets_id`)
LEFT JOIN `glpi_tickets_users`
ON (`glpi_tickets`.`id` = `glpi_tickets_users`.`tickets_id`)
LEFT JOIN `glpi_suppliers_tickets`
ON (`glpi_tickets`.`id` = `glpi_suppliers_tickets`.`tickets_id`)
LEFT JOIN `glpi_itilcategories`
ON (`glpi_tickets`.`itilcategories_id` = `glpi_itilcategories`.`id`)
$FROM";
}
/**
* @param $output
**/
static function showPreviewAssignAction($output) {
//If ticket is assign to an object, display this information first
if (isset($output["entities_id"])
&& isset($output["items_id"])
&& isset($output["itemtype"])) {
if ($item = getItemForItemtype($output["itemtype"])) {
if ($item->getFromDB($output["items_id"])) {
echo "<tr class='tab_bg_2'>";
echo "<td>".__('Assign equipment')."</td>";
echo "<td>".$item->getLink(array('comments' => true))."</td>";
echo "</tr>";
}
}
unset($output["items_id"]);
unset($output["itemtype"]);
}
unset($output["entities_id"]);
return $output;
}
/**
* Give cron information
*
* @param $name : task's name
*
* @return arrray of information
**/
static function cronInfo($name) {
switch ($name) {
case 'closeticket' :
return array('description' => __('Automatic tickets closing'));
case 'alertnotclosed' :
return array('description' => __('Not solved tickets'));
case 'createinquest' :
return array('description' => __('Generation of satisfaction surveys'));
}
return array();
}
/**
* Cron for ticket's automatic close
*
* @param $task : crontask object
*
* @return integer (0 : nothing done - 1 : done)
**/
static function cronCloseTicket($task) {
global $DB;
$ticket = new self();
// Recherche des entités
$tot = 0;
foreach (Entity::getEntitiesToNotify('autoclose_delay') as $entity => $delay) {
if ($delay >= 0) {
$query = "SELECT *
FROM `glpi_tickets`
WHERE `entities_id` = '".$entity."'
AND `status` = '".self::SOLVED."'
AND `is_deleted` = 0";
if ($delay > 0) {
$query .= " AND ADDDATE(`solvedate`, INTERVAL ".$delay." DAY) < CURDATE()";
}
$nb = 0;
foreach ($DB->request($query) as $tick) {
$ticket->update(array('id' => $tick['id'],
'status' => self::CLOSED,
'_auto_update' => true));
$nb++;
}
if ($nb) {
$tot += $nb;
$task->addVolume($nb);
$task->log(Dropdown::getDropdownName('glpi_entities', $entity)." : $nb");
}
}
}
return ($tot > 0);
}
/**
* Cron for alert old tickets which are not solved
*
* @param $task : crontask object
*
* @return integer (0 : nothing done - 1 : done)
**/
static function cronAlertNotClosed($task) {
global $DB, $CFG_GLPI;
if (!$CFG_GLPI["use_mailing"]) {
return 0;
}
// Recherche des entités
$tot = 0;
foreach (Entity::getEntitiesToNotify('notclosed_delay') as $entity => $value) {
$query = "SELECT `glpi_tickets`.*
FROM `glpi_tickets`
WHERE `glpi_tickets`.`entities_id` = '".$entity."'
AND `glpi_tickets`.`is_deleted` = 0
AND `glpi_tickets`.`status` IN ('".self::INCOMING."',
'".self::ASSIGNED."',
'".self::PLANNED."',
'".self::WAITING."')
AND `glpi_tickets`.`closedate` IS NULL
AND ADDDATE(`glpi_tickets`.`date`, INTERVAL ".$value." DAY) < NOW()";
$tickets = array();
foreach ($DB->request($query) as $tick) {
$tickets[] = $tick;
}
if (!empty($tickets)) {
if (NotificationEvent::raiseEvent('alertnotclosed', new self(),
array('items' => $tickets,
'entities_id' => $entity))) {
$tot += count($tickets);
$task->addVolume(count($tickets));
$task->log(sprintf(__('%1$s: %2$s'),
Dropdown::getDropdownName('glpi_entities', $entity),
count($tickets)));
}
}
}
return ($tot > 0);
}
/**
* Cron for ticketsatisfaction's automatic generated
*
* @param $task : crontask object
*
* @return integer (0 : nothing done - 1 : done)
**/
static function cronCreateInquest($task) {
global $DB;
$conf = new Entity();
$inquest = new TicketSatisfaction();
$tot = 0;
$maxentity = array();
$tabentities = array();
$rate = Entity::getUsedConfig('inquest_config', 0, 'inquest_rate');
if ($rate > 0) {
$tabentities[0] = $rate;
}
foreach ($DB->request('glpi_entities') as $entity) {
$rate = Entity::getUsedConfig('inquest_config', $entity['id'], 'inquest_rate');
$parent = Entity::getUsedConfig('inquest_config', $entity['id'], 'entities_id');
if ($rate > 0) {
$tabentities[$entity['id']] = $rate;
}
}
foreach ($tabentities as $entity => $rate) {
$parent = Entity::getUsedConfig('inquest_config', $entity, 'entities_id');
$delay = Entity::getUsedConfig('inquest_config', $entity, 'inquest_delay');
$type = Entity::getUsedConfig('inquest_config', $entity);
$max_closedate = Entity::getUsedConfig('inquest_config', $entity, 'max_closedate');
$query = "SELECT `glpi_tickets`.`id`,
`glpi_tickets`.`closedate`,
`glpi_tickets`.`entities_id`
FROM `glpi_tickets`
LEFT JOIN `glpi_ticketsatisfactions`
ON `glpi_ticketsatisfactions`.`tickets_id` = `glpi_tickets`.`id`
WHERE `glpi_tickets`.`entities_id` = '$entity'
AND `glpi_tickets`.`is_deleted` = 0
AND `glpi_tickets`.`status` = '".self::CLOSED."'
AND `glpi_tickets`.`closedate` > '$max_closedate'
AND ADDDATE(`glpi_tickets`.`closedate`, INTERVAL $delay DAY)<=NOW()
AND `glpi_ticketsatisfactions`.`id` IS NULL
ORDER BY `closedate` ASC";
$nb = 0;
$max_closedate = '';
foreach ($DB->request($query) as $tick) {
$max_closedate = $tick['closedate'];
if (mt_rand(1,100) <= $rate) {
if ($inquest->add(array('tickets_id' => $tick['id'],
'date_begin' => $_SESSION["glpi_currenttime"],
'entities_id' => $tick['entities_id'],
'type' => $type))) {
$nb++;
}
}
}
// conservation de toutes les max_closedate des entites filles
if (!empty($max_closedate)
&& (!isset($maxentity[$parent])
|| ($max_closedate > $maxentity[$parent]))) {
$maxentity[$parent] = $max_closedate;
}
if ($nb) {
$tot += $nb;
$task->addVolume($nb);
$task->log(sprintf(__('%1$s: %2$s'),
Dropdown::getDropdownName('glpi_entities', $entity), $nb));
}
}
// Sauvegarde du max_closedate pour ne pas tester les même tickets 2 fois
foreach ($maxentity as $parent => $maxdate) {
$conf->getFromDB($parent);
$conf->update(array('id' => $conf->fields['id'],
'entities_id' => $parent,
'max_closedate' => $maxdate));
}
return ($tot > 0);
}
/**
* Display debug information for current object
**/
function showDebug() {
NotificationEvent::debugEvent($this);
}
}
?>
| gpl-2.0 |
scottjmoore/assetassist | userdatatable.php | 1339 | <?php
/* AssetAssist - Asset tracking system
Copyright (C) 2013 Scott Moore Software Ltd.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
AssetAssist version 0.0.1, Copyright (C) 2013 Scott Moore Software Ltd.
AssetAssist comes with ABSOLUTELY NO WARRANTY; for details type `cat WARRENTY'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `cat LICENSE' for details */
require_once "datatable.php";
class UserDataTable extends DataTable {
public function UserDataTable($database, $tablename) {
parent::DataTable($database, $tablename);
$this->_datarowtype = 'UserDataRow';
}
}
?>
| gpl-2.0 |
mcasu/streamlisproject | players/dashplayer/play-live.php | 2249 | <!DOCTYPE html>
<?PHP
include(getenv("DOCUMENT_ROOT") . "/check_login.php");
$app_name = filter_input(INPUT_GET, 'app_name');
$stream_name = filter_input(INPUT_GET, 'stream_name');
$stream_type = filter_input(INPUT_GET, 'stream_type');
if(!isset($stream_name) || empty($stream_name) || !isset($stream_type))
{
// Access forbidden:
header('HTTP/1.1 403 Forbidden');
// Set our response code
http_response_code(403);
echo "<h1>403 Forbidden - Url non valida.</h1><br/><h3>Contattare l'amministratore di sistema.</h3>";
exit;
}
if ($myhostname == "lnxstreamserver-dev")
{
$ip_actual = $ip_private;
}
else
{
$ip_actual = $ip_public;
}
?>
<html>
<head>
<meta charset="utf-8"/>
<title>HTML5 Player</title>
<meta name="description" content="" />
<script type="text/javascript" src="bitmovin-player/bitmovinplayer.js"></script>
<!-- <style>
video {
width: 480px;
height: 360px;
}
</style>-->
<body>
<div id="player"></div>
<script type="text/javascript">
var conf = {
key: "87f64fdd-b06e-4ce6-8bcc-2ccdf6249f9a",
source: {
<?php
if ($stream_type == "dash") { echo 'dash: "https://www.streamlis.it/dash/'.$stream_name.'/index.mpd"'; }
if ($stream_type == "hls") { echo 'hls: "https://www.streamlis.it/hls/'.$stream_name.'/index.m3u8"'; }
?>
},
playback: {
autoplay: true
},
tweaks: {
autoqualityswitching : true,
max_buffer_level : 2
}
};
var player = bitmovin.player("player");
player.setup(conf).then(function(value) {
// Success
console.log("Successfully created bitmovin player instance");
}, function(reason) {
// Error!
console.log("Error while creating bitmovin player instance");
});
</script>
</body>
</html> | gpl-2.0 |
Ravenwolfe/ServUO16 | Scripts/Items/Equipment/Armor/LeatherShorts.cs | 1861 | using System;
namespace Server.Items
{
[FlipableAttribute(0x1c00, 0x1c01)]
public class LeatherShorts : BaseArmor
{
[Constructable]
public LeatherShorts()
: base(0x1C00)
{
this.Weight = 3.0;
}
public LeatherShorts(Serial serial)
: base(serial)
{
}
public override int InitMinHits
{
get
{
return 30;
}
}
public override int InitMaxHits
{
get
{
return 40;
}
}
public override int OldStrReq
{
get
{
return 10;
}
}
public override int ArmorBase
{
get
{
return 13;
}
}
public override ArmorMaterialType MaterialType
{
get
{
return ArmorMaterialType.Leather;
}
}
public override CraftResource DefaultResource
{
get
{
return CraftResource.RegularLeather;
}
}
public override ArmorMeditationAllowance DefMedAllowance
{
get
{
return ArmorMeditationAllowance.All;
}
}
public override bool AllowMaleWearer
{
get
{
return false;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | gpl-2.0 |
tobiasvdk/icingaweb2-module-director | library/Director/Util.php | 5972 | <?php
namespace Icinga\Module\Director;
use Icinga\Authentication\Auth;
use Icinga\Data\ResourceFactory;
use Icinga\Module\Director\Web\Form\QuickForm;
use Icinga\Exception\NotImplementedError;
use Icinga\Exception\ProgrammingError;
use Icinga\Web\Url;
use Zend_Db_Expr;
class Util
{
protected static $auth;
protected static $allowedResources;
public static function pgBinEscape($binary)
{
return new Zend_Db_Expr("'\\x" . bin2hex($binary) . "'");
}
public static function hex2binary($bin)
{
return pack('H*', $bin);
}
public static function binary2hex($hex)
{
return current(unpack('H*', $hex));
}
/**
* PBKDF2 - Password-Based Cryptography Specification (RFC2898)
*
* This method strictly follows examples in php.net's documentation
* comments. Hint: RFC6070 would be a good source for related tests
*
* @param string $alg Desired hash algorythm (sha1, sha256...)
* @param string $secret Shared secret, password
* @param string $salt Hash salt
* @param int $iterations How many iterations to perform. Please use at
* least 1000+. More iterations make it slower
* but more secure.
* @param int $length Desired key length
* @param bool $raw Returns the binary key if true, hex string otherwise
*
* @throws NotImplementedError when asking for an unsupported algorightm
* @throws ProgrammingError when passing invalid parameters
*
* @return string A $length byte long key, derived from secret and salt
*/
public static function pbkdf2($alg, $secret, $salt, $iterations, $length, $raw = false)
{
if (! in_array($alg, hash_algos(), true)) {
throw new NotImplementedError('No such hash algorithm found: "%s"', $alg);
}
if ($iterations <= 0 || $length <= 0) {
throw new ProgrammingError('Positive iterations and length required');
}
$hashLength = strlen(hash($alg, '', true));
$blocks = ceil($length / $hashLength);
$out = '';
for ($i = 1; $i <= $blocks; $i++) {
// $i encoded as 4 bytes, big endian.
$last = $salt . pack('N', $i);
// first iteration
$last = $xorsum = hash_hmac($alg, $last, $secret, true);
// perform the other $iterations - 1 iterations
for ($j = 1; $j < $iterations; $j++) {
$xorsum ^= ($last = hash_hmac($alg, $last, $secret, true));
}
$out .= $xorsum;
}
if ($raw) {
return substr($out, 0, $length);
}
return bin2hex(substr($out, 0, $length));
}
public static function getIcingaTicket($certname, $salt)
{
return self::pbkdf2('sha1', $certname, $salt, 50000, 20);
}
public static function auth()
{
if (self::$auth === null) {
self::$auth = Auth::getInstance();
}
return self::$auth;
}
public static function hasPermission($name)
{
return self::auth()->hasPermission($name);
}
public static function getRestrictions($name)
{
return self::auth()->getRestrictions($name);
}
public static function resourceIsAllowed($name)
{
if (self::$allowedResources === null) {
$restrictions = self::getRestrictions('director/resources/use');
$list = array();
foreach ($restrictions as $restriction) {
foreach (preg_split('/\s*,\s*/', $restriction, -1, PREG_SPLIT_NO_EMPTY) as $key) {
$list[$key] = $key;
}
}
self::$allowedResources = $list;
} else {
$list = self::$allowedResources;
}
if (empty($list) || array_key_exists($name, $list)) {
return true;
}
return false;
}
public static function enumDbResources()
{
return self::enumResources('db');
}
public static function enumLdapResources()
{
return self::enumResources('ldap');
}
protected static function enumResources($type)
{
$resources = array();
foreach (ResourceFactory::getResourceConfigs() as $name => $resource) {
if ($resource->get('type') === $type && self::resourceIsAllowed($name)) {
$resources[$name] = $name;
}
}
return $resources;
}
public static function addDbResourceFormElement(QuickForm $form, $name)
{
return self::addResourceFormElement($form, $name, 'db');
}
public static function addLdapResourceFormElement(QuickForm $form, $name)
{
return self::addResourceFormElement($form, $name, 'ldap');
}
protected static function addResourceFormElement(QuickForm $form, $name, $type)
{
$list = self::enumResources($type);
$form->addElement('select', $name, array(
'label' => 'Resource name',
'multiOptions' => $form->optionalEnum($list),
'required' => true,
));
if (true && empty($list)) {
if (self::hasPermission('config/application/resources')) {
$hint = $form->translate('Please click %s to create new resources');
$link = sprintf(
'<a href="' . Url::fromPath('config/resource') . '" data-base-target="_main">%s</a>',
$form->translate('here')
);
$form->addHtmlHint(sprintf($hint, $link));
$msg = sprintf($form->translate('No %s resource available'), $type);
} else {
$msg = $form->translate('Please ask an administrator to grant you access to resources');
}
$form->getElement($name)->addError($msg);
}
}
}
| gpl-2.0 |
ko2ic/reuse-calculator-sample | reuse-calculator/src/main/java/ko2/ic/android/common/core/utils/LogUtil.java | 4523 | package ko2.ic.android.common.core.utils;
import android.util.Log;
public final class LogUtil {
/** ログ出力用のタグ */
private static String loggerTag = "ko2-andoid-application";
/** ログを出力するかどうか */
private static boolean isWriteLog = true;
/**
* プライベートコンストラクタ<br>
*/
private LogUtil() {
}
/**
* 初期化を行う。<br>
* @param newLoggerTag ロガーのタグ
* @param newWriteLog ログを出力するかどうか
*/
public static void init(String newLoggerTag, boolean newWriteLog) {
loggerTag = newLoggerTag;
isWriteLog = newWriteLog;
}
/**
* ログを出力するかどうか。<br>
* @return ログを出力する場合true。
*/
public static boolean isWriteLog() {
return isWriteLog;
}
/**
* ログを出力する。<br>
* @param clazz 対象クラス
* @param message メッセージ
*/
public static void v(Class<?> clazz, String message) {
if (!isWriteLog) {
return;
}
Log.v(loggerTag, buildMessage(clazz, message));
}
/**
* ログを出力する。<br>
* @param clazz 対象クラス
* @param message メッセージ
* @param t 例外
*/
public static void v(Class<?> clazz, String message, Throwable t) {
if (!isWriteLog) {
return;
}
Log.v(loggerTag, buildMessage(clazz, message), t);
}
/**
* ログをデバッグ出力する。<br>
* @param clazz 対象クラス
* @param message メッセージ
*/
public static void d(Class<?> clazz, String message) {
if (!isWriteLog) {
return;
}
Log.d(loggerTag, buildMessage(clazz, message));
}
/**
* ログをデバッグ出力する。<br>
* @param clazz 対象クラス
* @param message メッセージ
* @param t 例外
*/
public static void d(Class<?> clazz, String message, Throwable t) {
if (!isWriteLog) {
return;
}
Log.d(loggerTag, buildMessage(clazz, message), t);
}
/**
* ログを情報出力する。<br>
* @param clazz 対象クラス
* @param message メッセージ
*/
public static void i(Class<?> clazz, String message) {
if (!isWriteLog) {
return;
}
Log.i(loggerTag, buildMessage(clazz, message));
}
/**
* ログを情報出力する。<br>
* @param clazz 対象クラス
* @param message メッセージ
* @param t 例外
*/
public static void i(Class<?> clazz, String message, Throwable t) {
if (!isWriteLog) {
return;
}
Log.i(loggerTag, buildMessage(clazz, message), t);
}
/**
* ログを警告出力する。<br>
* @param clazz 対象クラス
* @param message メッセージ
*/
public static void w(Class<?> clazz, String message) {
if (!isWriteLog) {
return;
}
Log.w(loggerTag, buildMessage(clazz, message));
}
/**
* ログを警告出力する。<br>
* @param clazz 対象クラス
* @param message メッセージ
* @param t 例外
*/
public static void w(Class<?> clazz, String message, Throwable t) {
if (!isWriteLog) {
return;
}
Log.w(loggerTag, buildMessage(clazz, message), t);
}
/**
* ログをエラー出力する。<br>
* @param clazz 対象クラス
* @param message メッセージ
*/
public static void e(Class<?> clazz, String message) {
if (!isWriteLog) {
return;
}
Log.e(loggerTag, buildMessage(clazz, message));
}
/**
* ログをエラー出力する。<br>
* @param clazz 対象クラス
* @param message メッセージ
* @param t 例外
*/
public static void e(Class<?> clazz, String message, Throwable t) {
if (!isWriteLog) {
return;
}
Log.e(loggerTag, buildMessage(clazz, message), t);
}
/**
* 表示するログメッセージを作成する。<br>
* @param clazz 対象のクラス名
* @param message メッセージ
* @return ログメッセージ
*/
private static String buildMessage(Class<?> clazz, String message) {
return clazz.getSimpleName() + ":" + message;
}
}
| gpl-2.0 |
benmmurphy/ssl_npn | src/main/java/sslnpn/ssl/EngineArgs.java | 7289 | /*
* Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sslnpn.ssl;
import javax.net.ssl.*;
import java.nio.*;
/*
* A multi-purpose class which handles all of the SSLEngine arguments.
* It validates arguments, checks for RO conditions, does space
* calculations, performs scatter/gather, etc.
*
* @author Brad R. Wetmore
*/
class EngineArgs {
/*
* Keep track of the input parameters.
*/
ByteBuffer netData;
ByteBuffer [] appData;
private int offset; // offset/len for the appData array.
private int len;
/*
* The initial pos/limit conditions. This is useful because we can
* quickly calculate the amount consumed/produced in successful
* operations, or easily return the buffers to their pre-error
* conditions.
*/
private int netPos;
private int netLim;
private int [] appPoss;
private int [] appLims;
/*
* Sum total of the space remaining in all of the appData buffers
*/
private int appRemaining = 0;
private boolean wrapMethod;
/*
* Called by the SSLEngine.wrap() method.
*/
EngineArgs(ByteBuffer [] appData, int offset, int len,
ByteBuffer netData) {
this.wrapMethod = true;
init(netData, appData, offset, len);
}
/*
* Called by the SSLEngine.unwrap() method.
*/
EngineArgs(ByteBuffer netData, ByteBuffer [] appData, int offset,
int len) {
this.wrapMethod = false;
init(netData, appData, offset, len);
}
/*
* The main initialization method for the arguments. Most
* of them are pretty obvious as to what they do.
*
* Since we're already iterating over appData array for validity
* checking, we also keep track of how much remainging space is
* available. Info is used in both unwrap (to see if there is
* enough space available in the destination), and in wrap (to
* determine how much more we can copy into the outgoing data
* buffer.
*/
private void init(ByteBuffer netData, ByteBuffer [] appData,
int offset, int len) {
if ((netData == null) || (appData == null)) {
throw new IllegalArgumentException("src/dst is null");
}
if ((offset < 0) || (len < 0) || (offset > appData.length - len)) {
throw new IndexOutOfBoundsException();
}
if (wrapMethod && netData.isReadOnly()) {
throw new ReadOnlyBufferException();
}
netPos = netData.position();
netLim = netData.limit();
appPoss = new int [appData.length];
appLims = new int [appData.length];
for (int i = offset; i < offset + len; i++) {
if (appData[i] == null) {
throw new IllegalArgumentException(
"appData[" + i + "] == null");
}
/*
* If we're unwrapping, then check to make sure our
* destination bufffers are writable.
*/
if (!wrapMethod && appData[i].isReadOnly()) {
throw new ReadOnlyBufferException();
}
appRemaining += appData[i].remaining();
appPoss[i] = appData[i].position();
appLims[i] = appData[i].limit();
}
/*
* Ok, looks like we have a good set of args, let's
* store the rest of this stuff.
*/
this.netData = netData;
this.appData = appData;
this.offset = offset;
this.len = len;
}
/*
* Given spaceLeft bytes to transfer, gather up that much data
* from the appData buffers (starting at offset in the array),
* and transfer it into the netData buffer.
*
* The user has already ensured there is enough room.
*/
void gather(int spaceLeft) {
for (int i = offset; (i < (offset + len)) && (spaceLeft > 0); i++) {
int amount = Math.min(appData[i].remaining(), spaceLeft);
appData[i].limit(appData[i].position() + amount);
netData.put(appData[i]);
spaceLeft -= amount;
}
}
/*
* Using the supplied buffer, scatter the data into the appData buffers
* (starting at offset in the array).
*
* The user has already ensured there is enough room.
*/
void scatter(ByteBuffer readyData) {
int amountLeft = readyData.remaining();
for (int i = offset; (i < (offset + len)) && (amountLeft > 0);
i++) {
int amount = Math.min(appData[i].remaining(), amountLeft);
readyData.limit(readyData.position() + amount);
appData[i].put(readyData);
amountLeft -= amount;
}
assert(readyData.remaining() == 0);
}
int getAppRemaining() {
return appRemaining;
}
/*
* Calculate the bytesConsumed/byteProduced. Aren't you glad
* we saved this off earlier?
*/
int deltaNet() {
return (netData.position() - netPos);
}
/*
* Calculate the bytesConsumed/byteProduced. Aren't you glad
* we saved this off earlier?
*/
int deltaApp() {
int sum = 0; // Only calculating 2^14 here, don't need a long.
for (int i = offset; i < offset + len; i++) {
sum += appData[i].position() - appPoss[i];
}
return sum;
}
/*
* In the case of Exception, we want to reset the positions
* to appear as though no data has been consumed or produced.
*/
void resetPos() {
netData.position(netPos);
for (int i = offset; i < offset + len; i++) {
appData[i].position(appPoss[i]);
}
}
/*
* We are doing lots of ByteBuffer manipulations, in which case
* we need to make sure that the limits get set back correctly.
* This is one of the last things to get done before returning to
* the user.
*/
void resetLim() {
netData.limit(netLim);
for (int i = offset; i < offset + len; i++) {
appData[i].limit(appLims[i]);
}
}
}
| gpl-2.0 |
wells369/Rubato | java/src/org/rubato/math/module/morphism/CAffineMorphism.java | 6722 | /*
* Copyright (C) 2001, 2005 Gérard Milmeister
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*/
package org.rubato.math.module.morphism;
import static org.rubato.xml.XMLConstants.MODULEMORPHISM;
import static org.rubato.xml.XMLConstants.TYPE_ATTR;
import org.rubato.math.arith.Complex;
import org.rubato.math.module.*;
import org.rubato.xml.XMLInputOutput;
import org.rubato.xml.XMLReader;
import org.rubato.xml.XMLWriter;
import org.w3c.dom.Element;
/**
* Affine morphism in <i>C</i>.
* The morphism <code>h</code> is such that <i>h(x) = a*x+b</i>
* where <code>a</code> and <code>b</code> are complex numbers.
*
* @author Gérard Milmeister
*/
public final class CAffineMorphism extends CAbstractMorphism {
/**
* Constructs an affine morphism <i>h(x) = a*x+b</i>.
*/
public CAffineMorphism(Complex a, Complex b) {
super();
this.a = a;
this.b = b;
}
public Complex mapValue(Complex c) {
return a.product(c).sum(b);
}
public boolean isModuleHomomorphism() {
return true;
}
public boolean isRingHomomorphism() {
return b.isZero() && (a.isOne() || b.isZero());
}
public boolean isLinear() {
return b.isZero();
}
public boolean isIdentity() {
return a.isOne() && b.isZero();
}
public boolean isConstant() {
return a.isZero();
}
public ModuleMorphism compose(ModuleMorphism morphism)
throws CompositionException {
if (morphism instanceof CAffineMorphism) {
CAffineMorphism rm = (CAffineMorphism)morphism;
return new CAffineMorphism(a.product(rm.a), a.product(rm.b).sum(b));
}
else {
return super.compose(morphism);
}
}
public ModuleMorphism sum(ModuleMorphism morphism)
throws CompositionException {
if (morphism instanceof CAffineMorphism) {
CAffineMorphism rm = (CAffineMorphism) morphism;
return new CAffineMorphism(a.sum(rm.a), b.sum(rm.b));
}
else {
return super.sum(morphism);
}
}
public ModuleMorphism difference(ModuleMorphism morphism)
throws CompositionException {
if (morphism instanceof CAffineMorphism) {
CAffineMorphism rm = (CAffineMorphism) morphism;
return new CAffineMorphism(a.difference(rm.a),b.difference(rm.b));
}
else {
return super.difference(morphism);
}
}
public ModuleMorphism scaled(RingElement element)
throws CompositionException {
if (element instanceof CElement) {
Complex s = ((CElement)element).getValue();
if (s.isZero()) {
return getConstantMorphism(element);
}
else {
return new CAffineMorphism(getA().product(s), getB().product(s));
}
}
else {
throw new CompositionException("CAffineMorphism.scaled: Cannot scale "+this+" by "+element);
}
}
public ModuleElement atZero() {
return new CElement(getB());
}
public int compareTo(ModuleMorphism object) {
if (object instanceof CAffineMorphism) {
CAffineMorphism morphism = (CAffineMorphism)object;
int comp = a.compareTo(morphism.a);
if (comp == 0) {
return b.compareTo(morphism.b);
}
else {
return comp;
}
}
else {
return super.compareTo(object);
}
}
public boolean equals(Object object) {
if (object instanceof CAffineMorphism) {
CAffineMorphism morphism = (CAffineMorphism)object;
return a.equals(morphism.a) && b.equals(morphism.b);
}
else {
return false;
}
}
public String toString() {
return "CAffineMorphism["+a+","+b+"]";
}
private final static String A_ATTR = "a";
private final static String B_ATTR = "b";
public void toXML(XMLWriter writer) {
writer.emptyWithType(MODULEMORPHISM, getElementTypeName(), A_ATTR, a, B_ATTR, b);
}
public ModuleMorphism fromXML(XMLReader reader, Element element) {
assert(element.getAttribute(TYPE_ATTR).equals(getElementTypeName()));
if (!element.hasAttribute("a")) {
reader.setError("Type %%1 is missing attribute %%2.", getElementTypeName(), A_ATTR);
return null;
}
if (!element.hasAttribute("b")) {
reader.setError("Type %%1 is missing attribute %%2.", getElementTypeName(), B_ATTR);
return null;
}
Complex a0;
Complex b0;
try {
a0 = Complex.parseComplex(element.getAttribute(A_ATTR));
}
catch (NumberFormatException e) {
reader.setError("Attribute %%1 of type %%2 must be a complex number.", A_ATTR, getElementTypeName());
return null;
}
try {
b0 = Complex.parseComplex(element.getAttribute(B_ATTR));
}
catch (NumberFormatException e) {
reader.setError("Attribute %%1 of type %%2 must be a complex number.", B_ATTR, getElementTypeName());
return null;
}
return new CAffineMorphism(a0, b0);
}
private static final XMLInputOutput<ModuleMorphism> xmlIO = new CAffineMorphism(new Complex(0), new Complex(0));
public static XMLInputOutput<ModuleMorphism> getXMLInputOutput() {
return xmlIO;
}
public String getElementTypeName() {
return "CAffineMorphism";
}
/**
* Returns the linear part.
*/
public Complex getA() {
return a;
}
/**
* Returns the translation part.
*/
public Complex getB() {
return b;
}
private Complex a;
private Complex b;
}
| gpl-2.0 |
tea-dragon/triplea | src/main/java/games/strategy/engine/history/HistoryNode.java | 696 | package games.strategy.engine.history;
import java.io.Serializable;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* Known subclasses of HistoryNode:<br>
* -> RootHistoryNode<br>
* -> EventChild<br>
* -> IndexedHistoryNode<br>
* -> -> Step<br>
* -> -> Event<br>
* -> -> Round
*
*/
public abstract class HistoryNode extends DefaultMutableTreeNode implements Serializable
{
private static final long serialVersionUID = 628623470654123887L;
public HistoryNode(final String title, final boolean allowsChildren)
{
super(title, allowsChildren);
}
public String getTitle()
{
return (String) super.getUserObject();
}
public abstract SerializationWriter getWriter();
}
| gpl-2.0 |
SirPiter/folk | www/administrator/components/com_cats/views/cat/view.html.php | 2664 | <?php
/**
* @version 1.0.0
* @package com_cats
* @copyright Copyright (C) 2011 Amy Stephen. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
jimport('joomla.application.component.view');
/**
* View to edit an cat.
*
* @package Joomla
* @subpackage com_cats
* @since 1.7
*/
class CatsViewCat extends JView
{
protected $form;
protected $item;
protected $state;
/**
* Display the view
*/
public function display($tpl = null)
{
// Initialiase variables.
$this->form = $this->get('Form');
$this->item = $this->get('Item');
$this->state = $this->get('State');
$this->canDo = CatsHelper::getActions($this->state->get('filter.category_id'));
// Check for errors.
if (count($errors = $this->get('Errors'))) {
JError::raiseError(500, implode("\n", $errors));
return false;
}
$this->addToolbar();
parent::display($tpl);
}
/**
* Add the page title and toolbar.
*
* @since 1.6
*/
protected function addToolbar()
{
JRequest::setVar('hidemainmenu', true);
$user = JFactory::getUser();
$userId = $user->get('id');
$isNew = ($this->item->id == 0);
$checkedOut = !($this->item->checked_out == 0 || $this->item->checked_out == $userId);
$canDo = CatsHelper::getActions($this->state->get('filter.category_id'), $this->item->id);
JToolBarHelper::title(JText::_('COM_CATS_PAGE_'.($checkedOut ? 'VIEW_CAT' : ($isNew ? 'ADD_CAT' : 'EDIT_CAT'))), 'cat-add.png');
// Built the actions for new and existing records.
// For new records, check the create permission.
if ($isNew && (count($user->getAuthorisedCategories('com_cats', 'core.create')) > 0)) {
JToolBarHelper::apply('cat.apply');
JToolBarHelper::save('cat.save');
JToolBarHelper::save2new('cat.save2new');
JToolBarHelper::cancel('cat.cancel');
}
else {
// Can't save the record if it's checked out.
if (!$checkedOut) {
// Since it's an existing record, check the edit permission, or fall back to edit own if the owner.
if ($canDo->get('core.edit') || ($canDo->get('core.edit.own') && $this->item->created_by == $userId)) {
JToolBarHelper::apply('cat.apply');
JToolBarHelper::save('cat.save');
// We can save this record, but check the create permission to see if we can return to make a new one.
if ($canDo->get('core.create')) {
JToolBarHelper::save2new('cat.save2new');
}
}
}
// If checked out, we can still save
if ($canDo->get('core.create')) {
JToolBarHelper::save2copy('cat.save2copy');
}
JToolBarHelper::cancel('cat.cancel', 'JTOOLBAR_CLOSE');
}
}
} | gpl-2.0 |