code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/**
* @license Highcharts JS v8.2.2 (2020-10-22)
* @module highcharts/modules/funnel3d
* @requires highcharts
* @requires highcharts/highcharts-3d
* @requires highcharts/modules/cylinder
*
* Highcharts funnel module
*
* (c) 2010-2019 Kacper Madej
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Series/Funnel3DSeries.js';
| cdnjs/cdnjs | ajax/libs/highcharts/8.2.2/es-modules/masters/modules/funnel3d.src.js | JavaScript | mit | 357 |
/**
* Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) 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
*/
package org.eclipse.smarthome.io.rest.core.link;
import java.util.ArrayList;
import java.util.Collection;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.link.AbstractLink;
import org.eclipse.smarthome.core.thing.link.ItemChannelLink;
import org.eclipse.smarthome.core.thing.link.ItemChannelLinkRegistry;
import org.eclipse.smarthome.core.thing.link.ThingLinkManager;
import org.eclipse.smarthome.core.thing.link.dto.AbstractLinkDTO;
import org.eclipse.smarthome.core.thing.link.dto.ItemChannelLinkDTO;
import org.eclipse.smarthome.io.rest.JSONResponse;
import org.eclipse.smarthome.io.rest.RESTResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
* This class acts as a REST resource for links.
*
* @author Dennis Nobel - Initial contribution
* @author Yordan Zhelev - Added Swagger annotations
* @author Kai Kreuzer - Removed Thing links and added auto link url
*/
@Path(ItemChannelLinkResource.PATH_LINKS)
@Api(value = ItemChannelLinkResource.PATH_LINKS)
public class ItemChannelLinkResource implements RESTResource {
/** The URI path to this resource */
public static final String PATH_LINKS = "links";
private ItemChannelLinkRegistry itemChannelLinkRegistry;
private ThingLinkManager thingLinkManager;
@Context
UriInfo uriInfo;
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Gets all available links.", response = ItemChannelLinkDTO.class, responseContainer = "Collection")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK") })
public Response getAll() {
Collection<ItemChannelLink> channelLinks = itemChannelLinkRegistry.getAll();
return Response.ok(toBeans(channelLinks)).build();
}
@GET
@Path("/auto")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Tells whether automatic link mode is active or not", response = Boolean.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK") })
public Response isAutomatic() {
return Response.ok(thingLinkManager.isAutoLinksEnabled()).build();
}
@PUT
@Path("/{itemName}/{channelUID}")
@ApiOperation(value = "Links item to a channel.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 400, message = "Item already linked to the channel.") })
public Response link(@PathParam("itemName") @ApiParam(value = "itemName") String itemName,
@PathParam("channelUID") @ApiParam(value = "channelUID") String channelUid) {
itemChannelLinkRegistry.add(new ItemChannelLink(itemName, new ChannelUID(channelUid)));
return Response.ok().build();
}
@DELETE
@Path("/{itemName}/{channelUID}")
@ApiOperation(value = "Unlinks item from a channel.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Link not found."),
@ApiResponse(code = 405, message = "Link not editable.") })
public Response unlink(@PathParam("itemName") @ApiParam(value = "itemName") String itemName,
@PathParam("channelUID") @ApiParam(value = "channelUID") String channelUid) {
String linkId = AbstractLink.getIDFor(itemName, new ChannelUID(channelUid));
if (itemChannelLinkRegistry.get(linkId) == null) {
String message = "Link " + linkId + " does not exist!";
return JSONResponse.createResponse(Status.NOT_FOUND, null, message);
}
ItemChannelLink result = itemChannelLinkRegistry
.remove(AbstractLink.getIDFor(itemName, new ChannelUID(channelUid)));
if (result != null) {
return Response.ok().build();
} else {
return JSONResponse.createErrorResponse(Status.METHOD_NOT_ALLOWED, "Channel is read-only.");
}
}
protected void setThingLinkManager(ThingLinkManager thingLinkManager) {
this.thingLinkManager = thingLinkManager;
}
protected void unsetThingLinkManager(ThingLinkManager thingLinkManager) {
this.thingLinkManager = null;
}
protected void setItemChannelLinkRegistry(ItemChannelLinkRegistry itemChannelLinkRegistry) {
this.itemChannelLinkRegistry = itemChannelLinkRegistry;
}
protected void unsetItemChannelLinkRegistry(ItemChannelLinkRegistry itemChannelLinkRegistry) {
this.itemChannelLinkRegistry = null;
}
private Collection<AbstractLinkDTO> toBeans(Iterable<ItemChannelLink> links) {
Collection<AbstractLinkDTO> beans = new ArrayList<>();
for (AbstractLink link : links) {
ItemChannelLinkDTO bean = new ItemChannelLinkDTO(link.getItemName(), link.getUID().toString());
beans.add(bean);
}
return beans;
}
}
| marinmitev/smarthome | bundles/io/org.eclipse.smarthome.io.rest.core/src/main/java/org/eclipse/smarthome/io/rest/core/link/ItemChannelLinkResource.java | Java | epl-1.0 | 5,631 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vIBM 2.2.3-11/28/2011 06:21 AM(foreman)-
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.06.11 at 05:49:00 PM EDT
//
package com.ibm.jbatch.jsl.model.v2;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Batchlet complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Batchlet">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="properties" type="{https://jakarta.ee/xml/ns/jakartaee}Properties" minOccurs="0"/>
* </sequence>
* <attribute name="ref" use="required" type="{https://jakarta.ee/xml/ns/jakartaee}artifactRef" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Batchlet", propOrder = {
"properties"
})
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public class Batchlet extends com.ibm.jbatch.jsl.model.Batchlet {
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
protected JSLProperties properties;
@XmlAttribute(name = "ref", required = true)
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
protected String ref;
/** {@inheritDoc} */
@Override
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public JSLProperties getProperties() {
return properties;
}
/** {@inheritDoc} */
@Override
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public void setProperties(com.ibm.jbatch.jsl.model.JSLProperties value) {
this.properties = (JSLProperties) value;
}
/** {@inheritDoc} */
@Override
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public String getRef() {
return ref;
}
/** {@inheritDoc} */
@Override
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public void setRef(String value) {
this.ref = value;
}
/**
* Copyright 2013 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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.
*/
/*
* Appended by build tooling.
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder(100);
buf.append("Batchlet: ref=" + ref);
buf.append("\n");
buf.append("Properties = " + com.ibm.jbatch.jsl.model.helper.PropertiesToStringHelper.getString(properties));
return buf.toString();
}
} | OpenLiberty/open-liberty | dev/com.ibm.jbatch.jsl.model/src/com/ibm/jbatch/jsl/model/v2/Batchlet.java | Java | epl-1.0 | 4,330 |
/*
* Copyright (c) 2012-2017 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.multiuser.machine.authentication.server;
import static com.google.common.base.Strings.nullToEmpty;
import java.io.IOException;
import java.security.Principal;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.api.core.model.user.User;
import org.eclipse.che.api.user.server.UserManager;
import org.eclipse.che.commons.auth.token.RequestTokenExtractor;
import org.eclipse.che.commons.env.EnvironmentContext;
import org.eclipse.che.commons.subject.Subject;
import org.eclipse.che.commons.subject.SubjectImpl;
import org.eclipse.che.multiuser.api.permission.server.AuthorizedSubject;
import org.eclipse.che.multiuser.api.permission.server.PermissionChecker;
/** @author Max Shaposhnik (mshaposhnik@codenvy.com) */
@Singleton
public class MachineLoginFilter implements Filter {
@Inject private RequestTokenExtractor tokenExtractor;
@Inject private MachineTokenRegistry machineTokenRegistry;
@Inject private UserManager userManager;
@Inject private PermissionChecker permissionChecker;
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(
ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
if (httpRequest.getScheme().startsWith("ws")
|| !nullToEmpty(tokenExtractor.getToken(httpRequest)).startsWith("machine")) {
filterChain.doFilter(servletRequest, servletResponse);
return;
} else {
String tokenString;
User user;
try {
tokenString = tokenExtractor.getToken(httpRequest);
String userId = machineTokenRegistry.getUserId(tokenString);
user = userManager.getById(userId);
} catch (NotFoundException | ServerException e) {
throw new ServletException("Cannot find user by machine token.");
}
final Subject subject =
new AuthorizedSubject(
new SubjectImpl(user.getName(), user.getId(), tokenString, false), permissionChecker);
try {
EnvironmentContext.getCurrent().setSubject(subject);
filterChain.doFilter(addUserInRequest(httpRequest, subject), servletResponse);
} finally {
EnvironmentContext.reset();
}
}
}
private HttpServletRequest addUserInRequest(
final HttpServletRequest httpRequest, final Subject subject) {
return new HttpServletRequestWrapper(httpRequest) {
@Override
public String getRemoteUser() {
return subject.getUserName();
}
@Override
public Principal getUserPrincipal() {
return subject::getUserName;
}
};
}
@Override
public void destroy() {}
}
| TypeFox/che | multiuser/machine-auth/che-multiuser-machine-authentication/src/main/java/org/eclipse/che/multiuser/machine/authentication/server/MachineLoginFilter.java | Java | epl-1.0 | 3,592 |
/*******************************************************************************
* Copyright (c) 2012 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.cdi.services.impl;
import javax.enterprise.context.Dependent;
/**
* This class only needs to be here to make sure this is a BDA with a BeanManager
*/
@Dependent
public class MyPojoUser {
public String getUser() {
String s = "DefaultPojoUser";
return s;
}
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.cdi.jee_fat/test-applications/resourceWebServicesProvider.war/src/com/ibm/ws/cdi/services/impl/MyPojoUser.java | Java | epl-1.0 | 840 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package javax.faces;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.ExternalContext;
/**
* Provide utility methods used by FactoryFinder class to lookup for SPI interface FactoryFinderProvider.
*
* @since 2.0.5
*/
class _FactoryFinderProviderFactory
{
public static final String FACTORY_FINDER_PROVIDER_FACTORY_CLASS_NAME = "org.apache.myfaces.spi" +
".FactoryFinderProviderFactory";
public static final String FACTORY_FINDER_PROVIDER_CLASS_NAME = "org.apache.myfaces.spi.FactoryFinderProvider";
public static final String INJECTION_PROVIDER_FACTORY_CLASS_NAME =
"org.apache.myfaces.spi.InjectionProviderFactory";
// INJECTION_PROVIDER_CLASS_NAME to provide use of new Injection Provider methods which take a
// a class as an input. This is required for CDI 1.2, particularly in regard to constructor injection/
public static final String INJECTION_PROVIDER_CLASS_NAME = "com.ibm.ws.jsf.spi.WASInjectionProvider";
// MANAGED_OBJECT_CLASS_NAME added for CDI 1.2 support. Because CDI now creates the class, inject needs
// to return two objects : the instance of the required class and the creational context. To do this
// an Managed object is returned from which both of the required objects can be obtained.
public static final String MANAGED_OBJECT_CLASS_NAME = "com.ibm.ws.managedobject.ManagedObject";
public static final Class<?> FACTORY_FINDER_PROVIDER_FACTORY_CLASS;
public static final Method FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD;
public static final Method FACTORY_FINDER_PROVIDER_FACTORY_GET_FACTORY_FINDER_METHOD;
public static final Class<?> FACTORY_FINDER_PROVIDER_CLASS;
public static final Method FACTORY_FINDER_PROVIDER_GET_FACTORY_METHOD;
public static final Method FACTORY_FINDER_PROVIDER_SET_FACTORY_METHOD;
public static final Method FACTORY_FINDER_PROVIDER_RELEASE_FACTORIES_METHOD;
public static final Class<?> INJECTION_PROVIDER_FACTORY_CLASS;
public static final Method INJECTION_PROVIDER_FACTORY_GET_INSTANCE_METHOD;
public static final Method INJECTION_PROVIDER_FACTORY_GET_INJECTION_PROVIDER_METHOD;
public static final Class<?> INJECTION_PROVIDER_CLASS;
public static final Method INJECTION_PROVIDER_INJECT_OBJECT_METHOD;
public static final Method INJECTION_PROVIDER_INJECT_CLASS_METHOD;
public static final Method INJECTION_PROVIDER_POST_CONSTRUCT_METHOD;
public static final Method INJECTION_PROVIDER_PRE_DESTROY_METHOD;
// New for CDI 1.2
public static final Class<?> MANAGED_OBJECT_CLASS;
public static final Method MANAGED_OBJECT_GET_OBJECT_METHOD;
public static final Method MANAGED_OBJECT_GET_CONTEXT_DATA_METHOD;
static
{
Class factoryFinderFactoryClass = null;
Method factoryFinderproviderFactoryGetMethod = null;
Method factoryFinderproviderFactoryGetFactoryFinderMethod = null;
Class<?> factoryFinderProviderClass = null;
Method factoryFinderProviderGetFactoryMethod = null;
Method factoryFinderProviderSetFactoryMethod = null;
Method factoryFinderProviderReleaseFactoriesMethod = null;
Class injectionProviderFactoryClass = null;
Method injectionProviderFactoryGetInstanceMethod = null;
Method injectionProviderFactoryGetInjectionProviderMethod = null;
Class injectionProviderClass = null;
Method injectionProviderInjectObjectMethod = null;
Method injectionProviderInjectClassMethod = null;
Method injectionProviderPostConstructMethod = null;
Method injectionProviderPreDestroyMethod = null;
Class managedObjectClass = null;
Method managedObjectGetObjectMethod = null;
Method managedObjectGetContextDataMethod = null;
try
{
factoryFinderFactoryClass = classForName(FACTORY_FINDER_PROVIDER_FACTORY_CLASS_NAME);
if (factoryFinderFactoryClass != null)
{
factoryFinderproviderFactoryGetMethod = factoryFinderFactoryClass.getMethod
("getInstance", null);
factoryFinderproviderFactoryGetFactoryFinderMethod = factoryFinderFactoryClass
.getMethod("getFactoryFinderProvider", null);
}
factoryFinderProviderClass = classForName(FACTORY_FINDER_PROVIDER_CLASS_NAME);
if (factoryFinderProviderClass != null)
{
factoryFinderProviderGetFactoryMethod = factoryFinderProviderClass.getMethod("getFactory",
new Class[]{String.class});
factoryFinderProviderSetFactoryMethod = factoryFinderProviderClass.getMethod("setFactory",
new Class[]{String.class, String.class});
factoryFinderProviderReleaseFactoriesMethod = factoryFinderProviderClass.getMethod
("releaseFactories", null);
}
injectionProviderFactoryClass = classForName(INJECTION_PROVIDER_FACTORY_CLASS_NAME);
if (injectionProviderFactoryClass != null)
{
injectionProviderFactoryGetInstanceMethod = injectionProviderFactoryClass.
getMethod("getInjectionProviderFactory", null);
injectionProviderFactoryGetInjectionProviderMethod = injectionProviderFactoryClass.
getMethod("getInjectionProvider", ExternalContext.class);
}
injectionProviderClass = classForName(INJECTION_PROVIDER_CLASS_NAME);
if (injectionProviderClass != null)
{
injectionProviderInjectObjectMethod = injectionProviderClass.
getMethod("inject", Object.class);
injectionProviderInjectClassMethod = injectionProviderClass.
getMethod("inject", Class.class);
injectionProviderPostConstructMethod = injectionProviderClass.
getMethod("postConstruct", Object.class, Object.class);
injectionProviderPreDestroyMethod = injectionProviderClass.
getMethod("preDestroy", Object.class, Object.class);
}
// get managed object and getObject and getContextData methods for CDI 1.2 support.
// getObject() is used to the created object instance
// getContextData(Class) is used to get the creational context
managedObjectClass = classForName(MANAGED_OBJECT_CLASS_NAME);
if (managedObjectClass != null)
{
managedObjectGetObjectMethod = managedObjectClass.getMethod("getObject", null);
managedObjectGetContextDataMethod = managedObjectClass.getMethod("getContextData", Class.class);
}
}
catch (Exception e)
{
// no op
}
FACTORY_FINDER_PROVIDER_FACTORY_CLASS = factoryFinderFactoryClass;
FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD = factoryFinderproviderFactoryGetMethod;
FACTORY_FINDER_PROVIDER_FACTORY_GET_FACTORY_FINDER_METHOD = factoryFinderproviderFactoryGetFactoryFinderMethod;
FACTORY_FINDER_PROVIDER_CLASS = factoryFinderProviderClass;
FACTORY_FINDER_PROVIDER_GET_FACTORY_METHOD = factoryFinderProviderGetFactoryMethod;
FACTORY_FINDER_PROVIDER_SET_FACTORY_METHOD = factoryFinderProviderSetFactoryMethod;
FACTORY_FINDER_PROVIDER_RELEASE_FACTORIES_METHOD = factoryFinderProviderReleaseFactoriesMethod;
INJECTION_PROVIDER_FACTORY_CLASS = injectionProviderFactoryClass;
INJECTION_PROVIDER_FACTORY_GET_INSTANCE_METHOD = injectionProviderFactoryGetInstanceMethod;
INJECTION_PROVIDER_FACTORY_GET_INJECTION_PROVIDER_METHOD = injectionProviderFactoryGetInjectionProviderMethod;
INJECTION_PROVIDER_CLASS = injectionProviderClass;
INJECTION_PROVIDER_INJECT_OBJECT_METHOD = injectionProviderInjectObjectMethod;
INJECTION_PROVIDER_INJECT_CLASS_METHOD = injectionProviderInjectClassMethod;
INJECTION_PROVIDER_POST_CONSTRUCT_METHOD = injectionProviderPostConstructMethod;
INJECTION_PROVIDER_PRE_DESTROY_METHOD = injectionProviderPreDestroyMethod;
MANAGED_OBJECT_CLASS = managedObjectClass;
MANAGED_OBJECT_GET_OBJECT_METHOD = managedObjectGetObjectMethod;
MANAGED_OBJECT_GET_CONTEXT_DATA_METHOD = managedObjectGetContextDataMethod;
}
public static Object getInstance()
{
if (FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD != null)
{
try
{
return FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD.invoke(FACTORY_FINDER_PROVIDER_FACTORY_CLASS, null);
}
catch (Exception e)
{
//No op
Logger log = Logger.getLogger(_FactoryFinderProviderFactory.class.getName());
if (log.isLoggable(Level.WARNING))
{
log.log(Level.WARNING, "Cannot retrieve current FactoryFinder instance from " +
"FactoryFinderProviderFactory." +
" Default strategy using thread context class loader will be used.", e);
}
}
}
return null;
}
// ~ Methods Copied from _ClassUtils
// ------------------------------------------------------------------------------------
/**
* Tries a Class.loadClass with the context class loader of the current thread first and automatically falls back
* to
* the ClassUtils class loader (i.e. the loader of the myfaces.jar lib) if necessary.
*
* @param type fully qualified name of a non-primitive non-array class
* @return the corresponding Class
* @throws NullPointerException if type is null
* @throws ClassNotFoundException
*/
public static Class<?> classForName(String type) throws ClassNotFoundException
{
if (type == null)
{
throw new NullPointerException("type");
}
try
{
// Try WebApp ClassLoader first
return Class.forName(type, false, // do not initialize for faster startup
getContextClassLoader());
}
catch (ClassNotFoundException ignore)
{
// fallback: Try ClassLoader for ClassUtils (i.e. the myfaces.jar lib)
return Class.forName(type, false, // do not initialize for faster startup
_FactoryFinderProviderFactory.class.getClassLoader());
}
}
/**
* Gets the ClassLoader associated with the current thread. Returns the class loader associated with the specified
* default object if no context loader is associated with the current thread.
*
* @return ClassLoader
*/
protected static ClassLoader getContextClassLoader()
{
if (System.getSecurityManager() != null)
{
try
{
Object cl = AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws PrivilegedActionException
{
return Thread.currentThread().getContextClassLoader();
}
});
return (ClassLoader) cl;
}
catch (PrivilegedActionException pae)
{
throw new FacesException(pae);
}
}
else
{
return Thread.currentThread().getContextClassLoader();
}
}
}
| OpenLiberty/open-liberty | dev/com.ibm.websphere.javaee.jsf.2.2/src/javax/faces/_FactoryFinderProviderFactory.java | Java | epl-1.0 | 12,732 |
/**
* Copyright (c) 2010-2020 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.http.internal.config;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.http.internal.converter.ColorItemConverter;
import org.openhab.core.library.types.IncreaseDecreaseType;
import org.openhab.core.library.types.NextPreviousType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.OpenClosedType;
import org.openhab.core.library.types.PlayPauseType;
import org.openhab.core.library.types.RewindFastforwardType;
import org.openhab.core.library.types.StopMoveType;
import org.openhab.core.library.types.UpDownType;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
/**
* The {@link HttpChannelConfig} class contains fields mapping channel configuration parameters.
*
* @author Jan N. Klug - Initial contribution
*/
@NonNullByDefault
public class HttpChannelConfig {
private final Map<String, State> stringStateMap = new HashMap<>();
private final Map<Command, @Nullable String> commandStringMap = new HashMap<>();
private boolean initialized = false;
public @Nullable String stateExtension;
public @Nullable String commandExtension;
public @Nullable String stateTransformation;
public @Nullable String commandTransformation;
public HttpChannelMode mode = HttpChannelMode.READWRITE;
// switch, dimmer, color
public @Nullable String onValue;
public @Nullable String offValue;
// dimmer, color
public BigDecimal step = BigDecimal.ONE;
public @Nullable String increaseValue;
public @Nullable String decreaseValue;
// color
public ColorItemConverter.ColorMode colorMode = ColorItemConverter.ColorMode.RGB;
// contact
public @Nullable String openValue;
public @Nullable String closedValue;
// rollershutter
public @Nullable String upValue;
public @Nullable String downValue;
public @Nullable String stopValue;
public @Nullable String moveValue;
// player
public @Nullable String playValue;
public @Nullable String pauseValue;
public @Nullable String nextValue;
public @Nullable String previousValue;
public @Nullable String rewindValue;
public @Nullable String fastforwardValue;
/**
* maps a command to a user-defined string
*
* @param command the command to map
* @return a string or null if no mapping found
*/
public @Nullable String commandToFixedValue(Command command) {
if (!initialized) {
createMaps();
}
return commandStringMap.get(command);
}
/**
* maps a user-defined string to a state
*
* @param string the string to map
* @return the state or null if no mapping found
*/
public @Nullable State fixedValueToState(String string) {
if (!initialized) {
createMaps();
}
return stringStateMap.get(string);
}
private void createMaps() {
addToMaps(this.onValue, OnOffType.ON);
addToMaps(this.offValue, OnOffType.OFF);
addToMaps(this.openValue, OpenClosedType.OPEN);
addToMaps(this.closedValue, OpenClosedType.CLOSED);
addToMaps(this.upValue, UpDownType.UP);
addToMaps(this.downValue, UpDownType.DOWN);
commandStringMap.put(IncreaseDecreaseType.INCREASE, increaseValue);
commandStringMap.put(IncreaseDecreaseType.DECREASE, decreaseValue);
commandStringMap.put(StopMoveType.STOP, stopValue);
commandStringMap.put(StopMoveType.MOVE, moveValue);
commandStringMap.put(PlayPauseType.PLAY, playValue);
commandStringMap.put(PlayPauseType.PAUSE, pauseValue);
commandStringMap.put(NextPreviousType.NEXT, nextValue);
commandStringMap.put(NextPreviousType.PREVIOUS, previousValue);
commandStringMap.put(RewindFastforwardType.REWIND, rewindValue);
commandStringMap.put(RewindFastforwardType.FASTFORWARD, fastforwardValue);
initialized = true;
}
private void addToMaps(@Nullable String value, State state) {
if (value != null) {
commandStringMap.put((Command) state, value);
stringStateMap.put(value, state);
}
}
}
| openhab/openhab2 | bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/config/HttpChannelConfig.java | Java | epl-1.0 | 4,709 |
/*******************************************************************************
* Copyright (c) 2012 Max Hohenegger.
* 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:
* Max Hohenegger - initial implementation
******************************************************************************/
package eu.hohenegger.c0ffee_tips.tests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import eu.hohenegger.c0ffee_tips.TestBasic;
@RunWith(Suite.class)
@SuiteClasses({TestBasic.class})
public class AllTests {
}
| Treehopper/c0ffee_tips | eu.hohenegger.c0ffee_tips.tests/src/eu/hohenegger/c0ffee_tips/tests/AllTests.java | Java | epl-1.0 | 791 |
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC 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 Middleware LLC.
*
* 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.hql.ast.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Collection;
import org.hibernate.AssertionFailure;
import org.hibernate.dialect.Dialect;
import org.hibernate.impl.FilterImpl;
import org.hibernate.type.Type;
import org.hibernate.param.DynamicFilterParameterSpecification;
import org.hibernate.param.CollectionFilterKeyParameterSpecification;
import org.hibernate.engine.JoinSequence;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.LoadQueryInfluencers;
import org.hibernate.hql.antlr.SqlTokenTypes;
import org.hibernate.hql.ast.HqlSqlWalker;
import org.hibernate.hql.ast.tree.FromClause;
import org.hibernate.hql.ast.tree.FromElement;
import org.hibernate.hql.ast.tree.QueryNode;
import org.hibernate.hql.ast.tree.DotNode;
import org.hibernate.hql.ast.tree.ParameterContainer;
import org.hibernate.hql.classic.ParserHelper;
import org.hibernate.sql.JoinFragment;
import org.hibernate.util.StringHelper;
import org.hibernate.util.ArrayHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Performs the post-processing of the join information gathered during semantic analysis.
* The join generating classes are complex, this encapsulates some of the JoinSequence-related
* code.
*
* @author Joshua Davis
*/
public class JoinProcessor implements SqlTokenTypes {
private static final Logger log = LoggerFactory.getLogger( JoinProcessor.class );
private final HqlSqlWalker walker;
private final SyntheticAndFactory syntheticAndFactory;
/**
* Constructs a new JoinProcessor.
*
* @param walker The walker to which we are bound, giving us access to needed resources.
*/
public JoinProcessor(HqlSqlWalker walker) {
this.walker = walker;
this.syntheticAndFactory = new SyntheticAndFactory( walker );
}
/**
* Translates an AST join type (i.e., the token type) into a JoinFragment.XXX join type.
*
* @param astJoinType The AST join type (from HqlSqlTokenTypes or SqlTokenTypes)
* @return a JoinFragment.XXX join type.
* @see JoinFragment
* @see SqlTokenTypes
*/
public static int toHibernateJoinType(int astJoinType) {
switch ( astJoinType ) {
case LEFT_OUTER:
return JoinFragment.LEFT_OUTER_JOIN;
case INNER:
return JoinFragment.INNER_JOIN;
case RIGHT_OUTER:
return JoinFragment.RIGHT_OUTER_JOIN;
default:
throw new AssertionFailure( "undefined join type " + astJoinType );
}
}
public void processJoins(QueryNode query) {
final FromClause fromClause = query.getFromClause();
final List fromElements;
if ( DotNode.useThetaStyleImplicitJoins ) {
// for regression testing against output from the old parser...
// found it easiest to simply reorder the FromElements here into ascending order
// in terms of injecting them into the resulting sql ast in orders relative to those
// expected by the old parser; this is definitely another of those "only needed
// for regression purposes". The SyntheticAndFactory, then, simply injects them as it
// encounters them.
fromElements = new ArrayList();
ListIterator liter = fromClause.getFromElements().listIterator( fromClause.getFromElements().size() );
while ( liter.hasPrevious() ) {
fromElements.add( liter.previous() );
}
}
else {
fromElements = fromClause.getFromElements();
}
// Iterate through the alias,JoinSequence pairs and generate SQL token nodes.
Iterator iter = fromElements.iterator();
while ( iter.hasNext() ) {
final FromElement fromElement = ( FromElement ) iter.next();
JoinSequence join = fromElement.getJoinSequence();
join.setSelector(
new JoinSequence.Selector() {
public boolean includeSubclasses(String alias) {
// The uber-rule here is that we need to include subclass joins if
// the FromElement is in any way dereferenced by a property from
// the subclass table; otherwise we end up with column references
// qualified by a non-existent table reference in the resulting SQL...
boolean containsTableAlias = fromClause.containsTableAlias( alias );
if ( fromElement.isDereferencedBySubclassProperty() ) {
// TODO : or should we return 'containsTableAlias'??
log.trace( "forcing inclusion of extra joins [alias=" + alias + ", containsTableAlias=" + containsTableAlias + "]" );
return true;
}
boolean shallowQuery = walker.isShallowQuery();
boolean includeSubclasses = fromElement.isIncludeSubclasses();
boolean subQuery = fromClause.isSubQuery();
return includeSubclasses && containsTableAlias && !subQuery && !shallowQuery;
}
}
);
addJoinNodes( query, join, fromElement );
}
}
private void addJoinNodes(QueryNode query, JoinSequence join, FromElement fromElement) {
JoinFragment joinFragment = join.toJoinFragment(
walker.getEnabledFilters(),
fromElement.useFromFragment() || fromElement.isDereferencedBySuperclassOrSubclassProperty(),
fromElement.getWithClauseFragment(),
fromElement.getWithClauseJoinAlias()
);
String frag = joinFragment.toFromFragmentString();
String whereFrag = joinFragment.toWhereFragmentString();
// If the from element represents a JOIN_FRAGMENT and it is
// a theta-style join, convert its type from JOIN_FRAGMENT
// to FROM_FRAGMENT
if ( fromElement.getType() == JOIN_FRAGMENT &&
( join.isThetaStyle() || StringHelper.isNotEmpty( whereFrag ) ) ) {
fromElement.setType( FROM_FRAGMENT );
fromElement.getJoinSequence().setUseThetaStyle( true ); // this is used during SqlGenerator processing
}
// If there is a FROM fragment and the FROM element is an explicit, then add the from part.
if ( fromElement.useFromFragment() /*&& StringHelper.isNotEmpty( frag )*/ ) {
String fromFragment = processFromFragment( frag, join ).trim();
if ( log.isDebugEnabled() ) {
log.debug( "Using FROM fragment [" + fromFragment + "]" );
}
processDynamicFilterParameters(
fromFragment,
fromElement,
walker
);
}
syntheticAndFactory.addWhereFragment(
joinFragment,
whereFrag,
query,
fromElement,
walker
);
}
private String processFromFragment(String frag, JoinSequence join) {
String fromFragment = frag.trim();
// The FROM fragment will probably begin with ', '. Remove this if it is present.
if ( fromFragment.startsWith( ", " ) ) {
fromFragment = fromFragment.substring( 2 );
}
return fromFragment;
}
public static void processDynamicFilterParameters(
final String sqlFragment,
final ParameterContainer container,
final HqlSqlWalker walker) {
if ( walker.getEnabledFilters().isEmpty()
&& ( ! hasDynamicFilterParam( sqlFragment ) )
&& ( ! ( hasCollectionFilterParam( sqlFragment ) ) ) ) {
return;
}
Dialect dialect = walker.getSessionFactoryHelper().getFactory().getDialect();
String symbols = new StringBuffer().append( ParserHelper.HQL_SEPARATORS )
.append( dialect.openQuote() )
.append( dialect.closeQuote() )
.toString();
StringTokenizer tokens = new StringTokenizer( sqlFragment, symbols, true );
StringBuffer result = new StringBuffer();
while ( tokens.hasMoreTokens() ) {
final String token = tokens.nextToken();
if ( token.startsWith( ParserHelper.HQL_VARIABLE_PREFIX ) ) {
final String filterParameterName = token.substring( 1 );
final String[] parts = LoadQueryInfluencers.parseFilterParameterName( filterParameterName );
final FilterImpl filter = ( FilterImpl ) walker.getEnabledFilters().get( parts[0] );
final Object value = filter.getParameter( parts[1] );
final Type type = filter.getFilterDefinition().getParameterType( parts[1] );
final String typeBindFragment = StringHelper.join(
",",
ArrayHelper.fillArray( "?", type.getColumnSpan( walker.getSessionFactoryHelper().getFactory() ) )
);
final String bindFragment = ( value != null && Collection.class.isInstance( value ) )
? StringHelper.join( ",", ArrayHelper.fillArray( typeBindFragment, ( ( Collection ) value ).size() ) )
: typeBindFragment;
result.append( bindFragment );
container.addEmbeddedParameter( new DynamicFilterParameterSpecification( parts[0], parts[1], type ) );
}
else {
result.append( token );
}
}
container.setText( result.toString() );
}
private static boolean hasDynamicFilterParam(String sqlFragment) {
return sqlFragment.indexOf( ParserHelper.HQL_VARIABLE_PREFIX ) < 0;
}
private static boolean hasCollectionFilterParam(String sqlFragment) {
return sqlFragment.indexOf( "?" ) < 0;
}
}
| ControlSystemStudio/cs-studio | thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/core/src/main/java/org/hibernate/hql/ast/util/JoinProcessor.java | Java | epl-1.0 | 9,793 |
/**
* Copyright (c) 2010-2016 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 org.openhab.binding.tinkerforge.internal.model.impl;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.atomic.AtomicBoolean;
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.EcoreUtil;
import org.openhab.binding.tinkerforge.internal.LoggerConstants;
import org.openhab.binding.tinkerforge.internal.TinkerforgeErrorHandler;
import org.openhab.binding.tinkerforge.internal.model.MBaseDevice;
import org.openhab.binding.tinkerforge.internal.model.MIndustrialQuadRelay;
import org.openhab.binding.tinkerforge.internal.model.MIndustrialQuadRelayBricklet;
import org.openhab.binding.tinkerforge.internal.model.MSubDevice;
import org.openhab.binding.tinkerforge.internal.model.MSubDeviceHolder;
import org.openhab.binding.tinkerforge.internal.model.ModelPackage;
import org.openhab.binding.tinkerforge.internal.types.OnOffValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.tinkerforge.NotConnectedException;
import com.tinkerforge.TimeoutException;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>MIndustrial Quad Relay</b></em>'.
*
* @author Theo Weiss
* @since 1.4.0
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getSwitchState
* <em>Switch State</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getLogger
* <em>Logger</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getUid <em>Uid</em>}
* </li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#isPoll <em>Poll</em>}
* </li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getEnabledA
* <em>Enabled A</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getSubId
* <em>Sub Id</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getMbrick
* <em>Mbrick</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getDeviceType
* <em>Device Type</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class MIndustrialQuadRelayImpl extends MinimalEObjectImpl.Container implements MIndustrialQuadRelay {
/**
* The default value of the '{@link #getSwitchState() <em>Switch State</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getSwitchState()
* @generated
* @ordered
*/
protected static final OnOffValue SWITCH_STATE_EDEFAULT = null;
/**
* The cached value of the '{@link #getSwitchState() <em>Switch State</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getSwitchState()
* @generated
* @ordered
*/
protected OnOffValue switchState = SWITCH_STATE_EDEFAULT;
/**
* The default value of the '{@link #getLogger() <em>Logger</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getLogger()
* @generated
* @ordered
*/
protected static final Logger LOGGER_EDEFAULT = null;
/**
* The cached value of the '{@link #getLogger() <em>Logger</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getLogger()
* @generated
* @ordered
*/
protected Logger logger = LOGGER_EDEFAULT;
/**
* The default value of the '{@link #getUid() <em>Uid</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getUid()
* @generated
* @ordered
*/
protected static final String UID_EDEFAULT = null;
/**
* The cached value of the '{@link #getUid() <em>Uid</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getUid()
* @generated
* @ordered
*/
protected String uid = UID_EDEFAULT;
/**
* The default value of the '{@link #isPoll() <em>Poll</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #isPoll()
* @generated
* @ordered
*/
protected static final boolean POLL_EDEFAULT = true;
/**
* The cached value of the '{@link #isPoll() <em>Poll</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #isPoll()
* @generated
* @ordered
*/
protected boolean poll = POLL_EDEFAULT;
/**
* The default value of the '{@link #getEnabledA() <em>Enabled A</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getEnabledA()
* @generated
* @ordered
*/
protected static final AtomicBoolean ENABLED_A_EDEFAULT = null;
/**
* The cached value of the '{@link #getEnabledA() <em>Enabled A</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getEnabledA()
* @generated
* @ordered
*/
protected AtomicBoolean enabledA = ENABLED_A_EDEFAULT;
/**
* The default value of the '{@link #getSubId() <em>Sub Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getSubId()
* @generated
* @ordered
*/
protected static final String SUB_ID_EDEFAULT = null;
/**
* The cached value of the '{@link #getSubId() <em>Sub Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getSubId()
* @generated
* @ordered
*/
protected String subId = SUB_ID_EDEFAULT;
/**
* The default value of the '{@link #getDeviceType() <em>Device Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getDeviceType()
* @generated
* @ordered
*/
protected static final String DEVICE_TYPE_EDEFAULT = "quad_relay";
/**
* The cached value of the '{@link #getDeviceType() <em>Device Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getDeviceType()
* @generated
* @ordered
*/
protected String deviceType = DEVICE_TYPE_EDEFAULT;
private short relayNum;
private int mask;
private static final byte DEFAULT_SELECTION_MASK = 0000000000000001;
private static final byte OFF_BYTE = 0000000000000000;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected MIndustrialQuadRelayImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
protected EClass eStaticClass() {
return ModelPackage.Literals.MINDUSTRIAL_QUAD_RELAY;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public OnOffValue getSwitchState() {
return switchState;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setSwitchState(OnOffValue newSwitchState) {
OnOffValue oldSwitchState = switchState;
switchState = newSwitchState;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE,
oldSwitchState, switchState));
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void turnSwitch(OnOffValue state) {
logger.debug("turnSwitchState called on: {}", MIndustrialQuadRelayBrickletImpl.class);
try {
if (state == OnOffValue.OFF) {
logger.debug("setSwitchValue off");
getMbrick().getTinkerforgeDevice().setSelectedValues(mask, OFF_BYTE);
} else if (state == OnOffValue.ON) {
logger.debug("setSwitchState on");
getMbrick().getTinkerforgeDevice().setSelectedValues(mask, mask);
} else {
logger.error("{} unkown switchstate {}", LoggerConstants.TFMODELUPDATE, state);
}
setSwitchState(state);
} catch (TimeoutException e) {
TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_TIMEOUT_EXCEPTION, e);
} catch (NotConnectedException e) {
TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_NOT_CONNECTION_EXCEPTION, e);
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void fetchSwitchState() {
OnOffValue value = OnOffValue.UNDEF;
try {
int deviceValue = getMbrick().getTinkerforgeDevice().getValue();
if ((deviceValue & mask) == mask) {
value = OnOffValue.ON;
} else {
value = OnOffValue.OFF;
}
setSwitchState(value);
} catch (TimeoutException e) {
TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_TIMEOUT_EXCEPTION, e);
} catch (NotConnectedException e) {
TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_NOT_CONNECTION_EXCEPTION, e);
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Logger getLogger() {
return logger;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setLogger(Logger newLogger) {
Logger oldLogger = logger;
logger = newLogger;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER,
oldLogger, logger));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getUid() {
return uid;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setUid(String newUid) {
String oldUid = uid;
uid = newUid;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID, oldUid,
uid));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean isPoll() {
return poll;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setPoll(boolean newPoll) {
boolean oldPoll = poll;
poll = newPoll;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL, oldPoll,
poll));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public AtomicBoolean getEnabledA() {
return enabledA;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setEnabledA(AtomicBoolean newEnabledA) {
AtomicBoolean oldEnabledA = enabledA;
enabledA = newEnabledA;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A,
oldEnabledA, enabledA));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getSubId() {
return subId;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setSubId(String newSubId) {
String oldSubId = subId;
subId = newSubId;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID, oldSubId,
subId));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public MIndustrialQuadRelayBricklet getMbrick() {
if (eContainerFeatureID() != ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK) {
return null;
}
return (MIndustrialQuadRelayBricklet) eContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public NotificationChain basicSetMbrick(MIndustrialQuadRelayBricklet newMbrick, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject) newMbrick, ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setMbrick(MIndustrialQuadRelayBricklet newMbrick) {
if (newMbrick != eInternalContainer()
|| (eContainerFeatureID() != ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK && newMbrick != null)) {
if (EcoreUtil.isAncestor(this, newMbrick)) {
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
}
NotificationChain msgs = null;
if (eInternalContainer() != null) {
msgs = eBasicRemoveFromContainer(msgs);
}
if (newMbrick != null) {
msgs = ((InternalEObject) newMbrick).eInverseAdd(this, ModelPackage.MSUB_DEVICE_HOLDER__MSUBDEVICES,
MSubDeviceHolder.class, msgs);
}
msgs = basicSetMbrick(newMbrick, msgs);
if (msgs != null) {
msgs.dispatch();
}
} else if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK,
newMbrick, newMbrick));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getDeviceType() {
return deviceType;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void init() {
setEnabledA(new AtomicBoolean());
poll = true; // don't use the setter to prevent notification
logger = LoggerFactory.getLogger(MIndustrialQuadRelay.class);
relayNum = Short.parseShort(String.valueOf(subId.charAt(subId.length() - 1)));
mask = DEFAULT_SELECTION_MASK << relayNum;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void enable() {
logger.debug("enable called on MIndustrialQuadRelayImpl");
fetchSwitchState();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void disable() {
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
if (eInternalContainer() != null) {
msgs = eBasicRemoveFromContainer(msgs);
}
return basicSetMbrick((MIndustrialQuadRelayBricklet) otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return basicSetMbrick(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return eInternalContainer().eInverseRemove(this, ModelPackage.MSUB_DEVICE_HOLDER__MSUBDEVICES,
MSubDeviceHolder.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE:
return getSwitchState();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
return getLogger();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
return getUid();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
return isPoll();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
return getEnabledA();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
return getSubId();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return getMbrick();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__DEVICE_TYPE:
return getDeviceType();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE:
setSwitchState((OnOffValue) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
setLogger((Logger) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
setUid((String) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
setPoll((Boolean) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
setEnabledA((AtomicBoolean) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
setSubId((String) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
setMbrick((MIndustrialQuadRelayBricklet) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE:
setSwitchState(SWITCH_STATE_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
setLogger(LOGGER_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
setUid(UID_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
setPoll(POLL_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
setEnabledA(ENABLED_A_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
setSubId(SUB_ID_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
setMbrick((MIndustrialQuadRelayBricklet) null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE:
return SWITCH_STATE_EDEFAULT == null ? switchState != null : !SWITCH_STATE_EDEFAULT.equals(switchState);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
return LOGGER_EDEFAULT == null ? logger != null : !LOGGER_EDEFAULT.equals(logger);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
return UID_EDEFAULT == null ? uid != null : !UID_EDEFAULT.equals(uid);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
return poll != POLL_EDEFAULT;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
return ENABLED_A_EDEFAULT == null ? enabledA != null : !ENABLED_A_EDEFAULT.equals(enabledA);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
return SUB_ID_EDEFAULT == null ? subId != null : !SUB_ID_EDEFAULT.equals(subId);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return getMbrick() != null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__DEVICE_TYPE:
return DEVICE_TYPE_EDEFAULT == null ? deviceType != null : !DEVICE_TYPE_EDEFAULT.equals(deviceType);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) {
if (baseClass == MBaseDevice.class) {
switch (derivedFeatureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
return ModelPackage.MBASE_DEVICE__LOGGER;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
return ModelPackage.MBASE_DEVICE__UID;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
return ModelPackage.MBASE_DEVICE__POLL;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
return ModelPackage.MBASE_DEVICE__ENABLED_A;
default:
return -1;
}
}
if (baseClass == MSubDevice.class) {
switch (derivedFeatureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
return ModelPackage.MSUB_DEVICE__SUB_ID;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return ModelPackage.MSUB_DEVICE__MBRICK;
default:
return -1;
}
}
return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) {
if (baseClass == MBaseDevice.class) {
switch (baseFeatureID) {
case ModelPackage.MBASE_DEVICE__LOGGER:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER;
case ModelPackage.MBASE_DEVICE__UID:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID;
case ModelPackage.MBASE_DEVICE__POLL:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL;
case ModelPackage.MBASE_DEVICE__ENABLED_A:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A;
default:
return -1;
}
}
if (baseClass == MSubDevice.class) {
switch (baseFeatureID) {
case ModelPackage.MSUB_DEVICE__SUB_ID:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID;
case ModelPackage.MSUB_DEVICE__MBRICK:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK;
default:
return -1;
}
}
return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public int eDerivedOperationID(int baseOperationID, Class<?> baseClass) {
if (baseClass == MBaseDevice.class) {
switch (baseOperationID) {
case ModelPackage.MBASE_DEVICE___INIT:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY___INIT;
case ModelPackage.MBASE_DEVICE___ENABLE:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY___ENABLE;
case ModelPackage.MBASE_DEVICE___DISABLE:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY___DISABLE;
default:
return -1;
}
}
if (baseClass == MSubDevice.class) {
switch (baseOperationID) {
default:
return -1;
}
}
return super.eDerivedOperationID(baseOperationID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException {
switch (operationID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___INIT:
init();
return null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___ENABLE:
enable();
return null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___DISABLE:
disable();
return null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___TURN_SWITCH__ONOFFVALUE:
turnSwitch((OnOffValue) arguments.get(0));
return null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___FETCH_SWITCH_STATE:
fetchSwitchState();
return null;
}
return super.eInvoke(operationID, arguments);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) {
return super.toString();
}
StringBuffer result = new StringBuffer(super.toString());
result.append(" (switchState: ");
result.append(switchState);
result.append(", logger: ");
result.append(logger);
result.append(", uid: ");
result.append(uid);
result.append(", poll: ");
result.append(poll);
result.append(", enabledA: ");
result.append(enabledA);
result.append(", subId: ");
result.append(subId);
result.append(", deviceType: ");
result.append(deviceType);
result.append(')');
return result.toString();
}
} // MIndustrialQuadRelayImpl
| sytone/openhab | bundles/binding/org.openhab.binding.tinkerforge/src/main/java/org/openhab/binding/tinkerforge/internal/model/impl/MIndustrialQuadRelayImpl.java | Java | epl-1.0 | 28,553 |
package org.hibernate.envers.tools;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.OneToMany;
import org.hibernate.mapping.ToOne;
import org.hibernate.mapping.Value;
/**
* @author Adam Warski (adam at warski dot org)
*/
public class MappingTools {
/**
* @param componentName Name of the component, that is, name of the property in the entity that references the
* component.
* @return A prefix for properties in the given component.
*/
public static String createComponentPrefix(String componentName) {
return componentName + "_";
}
/**
* @param referencePropertyName The name of the property that holds the relation to the entity.
* @return A prefix which should be used to prefix an id mapper for the related entity.
*/
public static String createToOneRelationPrefix(String referencePropertyName) {
return referencePropertyName + "_";
}
public static String getReferencedEntityName(Value value) {
if (value instanceof ToOne) {
return ((ToOne) value).getReferencedEntityName();
} else if (value instanceof OneToMany) {
return ((OneToMany) value).getReferencedEntityName();
} else if (value instanceof Collection) {
return getReferencedEntityName(((Collection) value).getElement());
}
return null;
}
}
| ControlSystemStudio/cs-studio | thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/envers/src/main/java/org/hibernate/envers/tools/MappingTools.java | Java | epl-1.0 | 1,365 |
/*******************************************************************************
* Copyright (c) 2012 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.security.oauth20.web;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringTokenizer;
import javax.security.auth.Subject;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import com.ibm.ejs.ras.TraceNLS;
import com.ibm.oauth.core.api.OAuthResult;
import com.ibm.oauth.core.api.attributes.AttributeList;
import com.ibm.oauth.core.api.error.OidcServerException;
import com.ibm.oauth.core.api.error.oauth20.OAuth20AccessDeniedException;
import com.ibm.oauth.core.api.error.oauth20.OAuth20DuplicateParameterException;
import com.ibm.oauth.core.api.error.oauth20.OAuth20Exception;
import com.ibm.oauth.core.api.oauth20.token.OAuth20Token;
import com.ibm.oauth.core.internal.oauth20.OAuth20Constants;
import com.ibm.oauth.core.internal.oauth20.OAuth20Util;
import com.ibm.oauth.core.internal.oauth20.OAuthResultImpl;
import com.ibm.websphere.ras.Tr;
import com.ibm.websphere.ras.TraceComponent;
import com.ibm.websphere.security.WSSecurityException;
import com.ibm.websphere.security.auth.WSSubject;
import com.ibm.ws.ffdc.FFDCFilter;
import com.ibm.ws.ffdc.annotation.FFDCIgnore;
import com.ibm.ws.security.SecurityService;
import com.ibm.ws.security.common.claims.UserClaims;
import com.ibm.ws.security.oauth20.ProvidersService;
import com.ibm.ws.security.oauth20.api.Constants;
import com.ibm.ws.security.oauth20.api.OAuth20EnhancedTokenCache;
import com.ibm.ws.security.oauth20.api.OAuth20Provider;
import com.ibm.ws.security.oauth20.error.impl.OAuth20TokenRequestExceptionHandler;
import com.ibm.ws.security.oauth20.exception.OAuth20BadParameterException;
import com.ibm.ws.security.oauth20.plugins.OAuth20TokenImpl;
import com.ibm.ws.security.oauth20.plugins.OidcBaseClient;
import com.ibm.ws.security.oauth20.util.ConfigUtils;
import com.ibm.ws.security.oauth20.util.Nonce;
import com.ibm.ws.security.oauth20.util.OAuth20ProviderUtils;
import com.ibm.ws.security.oauth20.util.OIDCConstants;
import com.ibm.ws.security.oauth20.util.OidcOAuth20Util;
import com.ibm.ws.security.oauth20.web.OAuth20Request.EndpointType;
import com.ibm.ws.webcontainer.security.CookieHelper;
import com.ibm.ws.webcontainer.security.ReferrerURLCookieHandler;
import com.ibm.ws.webcontainer.security.WebAppSecurityCollaboratorImpl;
import com.ibm.wsspi.kernel.service.utils.AtomicServiceReference;
import com.ibm.wsspi.kernel.service.utils.ConcurrentServiceReferenceMap;
import com.ibm.wsspi.security.oauth20.JwtAccessTokenMediator;
import com.ibm.wsspi.security.oauth20.TokenIntrospectProvider;
@Component(service = OAuth20EndpointServices.class, name = "com.ibm.ws.security.oauth20.web.OAuth20EndpointServices", immediate = true, configurationPolicy = ConfigurationPolicy.IGNORE, property = "service.vendor=IBM")
public class OAuth20EndpointServices {
private static TraceComponent tc = Tr.register(OAuth20EndpointServices.class);
private static TraceComponent tc2 = Tr.register(OAuth20EndpointServices.class, // use this one when bundle is the usual bundle.
TraceConstants.TRACE_GROUP,
TraceConstants.MESSAGE_BUNDLE);
protected static final String MESSAGE_BUNDLE = "com.ibm.ws.security.oauth20.internal.resources.OAuthMessages";
protected static final String MSG_RESOURCE_BUNDLE = "com.ibm.ws.security.oauth20.resources.ProviderMsgs";
public static final String KEY_SERVICE_PID = "service.pid";
public static final String KEY_SECURITY_SERVICE = "securityService";
protected final AtomicServiceReference<SecurityService> securityServiceRef = new AtomicServiceReference<SecurityService>(KEY_SECURITY_SERVICE);
public static final String KEY_TOKEN_INTROSPECT_PROVIDER = "tokenIntrospectProvider";
private final ConcurrentServiceReferenceMap<String, TokenIntrospectProvider> tokenIntrospectProviderRef = new ConcurrentServiceReferenceMap<String, TokenIntrospectProvider>(KEY_TOKEN_INTROSPECT_PROVIDER);
public static final String KEY_JWT_MEDIATOR = "jwtAccessTokenMediator";
private final ConcurrentServiceReferenceMap<String, JwtAccessTokenMediator> jwtAccessTokenMediatorRef = new ConcurrentServiceReferenceMap<String, JwtAccessTokenMediator>(KEY_JWT_MEDIATOR);
public static final String KEY_OAUTH_CLIENT_METATYPE_SERVICE = "oauth20ClientMetatypeService";
private static final AtomicServiceReference<OAuth20ClientMetatypeService> oauth20ClientMetatypeServiceRef = new AtomicServiceReference<OAuth20ClientMetatypeService>(KEY_OAUTH_CLIENT_METATYPE_SERVICE);
private static final String ATTR_NONCE = "consentNonce";
public static final String AUTHENTICATED = "authenticated";
protected volatile ClientAuthentication clientAuthentication = new ClientAuthentication();
protected volatile ClientAuthorization clientAuthorization = new ClientAuthorization();
protected volatile UserAuthentication userAuthentication = new UserAuthentication();
protected volatile CoverageMapEndpointServices coverageMapServices = new CoverageMapEndpointServices();
protected volatile RegistrationEndpointServices registrationEndpointServices = new RegistrationEndpointServices();
protected volatile Consent consent = new Consent();
protected volatile TokenExchange tokenExchange = new TokenExchange();
@Reference(service = SecurityService.class, name = KEY_SECURITY_SERVICE, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY)
protected void setSecurityService(ServiceReference<SecurityService> reference) {
securityServiceRef.setReference(reference);
}
protected void unsetSecurityService(ServiceReference<SecurityService> reference) {
securityServiceRef.unsetReference(reference);
}
@Reference(service = TokenIntrospectProvider.class, name = KEY_TOKEN_INTROSPECT_PROVIDER, policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY)
protected void setTokenIntrospectProvider(ServiceReference<TokenIntrospectProvider> ref) {
synchronized (tokenIntrospectProviderRef) {
tokenIntrospectProviderRef.putReference((String) ref.getProperty(KEY_SERVICE_PID), ref);
}
}
protected void unsetTokenIntrospectProvider(ServiceReference<TokenIntrospectProvider> ref) {
synchronized (tokenIntrospectProviderRef) {
tokenIntrospectProviderRef.removeReference((String) ref.getProperty(KEY_SERVICE_PID), ref);
}
}
@Reference(service = JwtAccessTokenMediator.class, name = KEY_JWT_MEDIATOR, policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.OPTIONAL, policyOption = ReferencePolicyOption.GREEDY)
protected void setJwtAccessTokenMediator(ServiceReference<JwtAccessTokenMediator> ref) {
synchronized (jwtAccessTokenMediatorRef) {
jwtAccessTokenMediatorRef.putReference((String) ref.getProperty(KEY_SERVICE_PID), ref);
}
}
protected void unsetJwtAccessTokenMediator(ServiceReference<JwtAccessTokenMediator> ref) {
synchronized (jwtAccessTokenMediatorRef) {
jwtAccessTokenMediatorRef.removeReference((String) ref.getProperty(KEY_SERVICE_PID), ref);
}
}
@Reference(service = OAuth20ClientMetatypeService.class, name = KEY_OAUTH_CLIENT_METATYPE_SERVICE, policy = ReferencePolicy.DYNAMIC)
protected void setOAuth20ClientMetatypeService(ServiceReference<OAuth20ClientMetatypeService> ref) {
oauth20ClientMetatypeServiceRef.setReference(ref);
}
protected void unsetOAuth20ClientMetatypeService(ServiceReference<OAuth20ClientMetatypeService> ref) {
oauth20ClientMetatypeServiceRef.unsetReference(ref);
}
@Activate
protected void activate(ComponentContext cc) {
securityServiceRef.activate(cc);
tokenIntrospectProviderRef.activate(cc);
jwtAccessTokenMediatorRef.activate(cc);
oauth20ClientMetatypeServiceRef.activate(cc);
ConfigUtils.setJwtAccessTokenMediatorService(jwtAccessTokenMediatorRef);
TokenIntrospect.setTokenIntrospect(tokenIntrospectProviderRef);
// The TraceComponent object was not initialized with the message bundle containing this message, so we cannot use
// Tr.info(tc, "OAUTH_ENDPOINT_SERVICE_ACTIVATED"). Eventually these messages will be merged into one file, making this infoMsg variable unnecessary
String infoMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"OAUTH_ENDPOINT_SERVICE_ACTIVATED",
null,
"CWWKS1410I: The OAuth endpoint service is activated.");
Tr.info(tc, infoMsg);
}
@Deactivate
protected void deactivate(ComponentContext cc) {
securityServiceRef.deactivate(cc);
tokenIntrospectProviderRef.deactivate(cc);
jwtAccessTokenMediatorRef.deactivate(cc);
oauth20ClientMetatypeServiceRef.deactivate(cc);
}
protected void handleOAuthRequest(HttpServletRequest request,
HttpServletResponse response,
ServletContext servletContext) throws ServletException, IOException {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Checking if OAuth20 Provider should process the request.");
Tr.debug(tc, "Inbound request " + com.ibm.ws.security.common.web.WebUtils.getRequestStringForTrace(request, "client_secret"));
}
OAuth20Request oauth20Request = getAuth20Request(request, response);
OAuth20Provider oauth20Provider = null;
if (oauth20Request != null) {
EndpointType endpointType = oauth20Request.getType();
oauth20Provider = getProvider(response, oauth20Request);
if (oauth20Provider != null) {
AttributeList optionalParams = new AttributeList();
if (tc.isDebugEnabled()) {
Tr.debug(tc, "OAUTH20 _SSO OP PROCESS IS STARTING.");
Tr.debug(tc, "OAUTH20 _SSO OP inbound URL " + com.ibm.ws.security.common.web.WebUtils.getRequestStringForTrace(request, "client_secret"));
}
handleEndpointRequest(request, response, servletContext, oauth20Provider, endpointType, optionalParams);
}
}
if (tc.isDebugEnabled()) {
if (oauth20Provider != null) {
Tr.debug(tc, "OAUTH20 _SSO OP PROCESS HAS ENDED.");
} else {
Tr.debug(tc, "OAUTH20 _SSO OP WILL NOT PROCESS THE REQUEST");
}
}
}
@FFDCIgnore({ OidcServerException.class })
protected void handleEndpointRequest(HttpServletRequest request,
HttpServletResponse response,
ServletContext servletContext,
OAuth20Provider oauth20Provider,
EndpointType endpointType,
AttributeList oidcOptionalParams) throws ServletException, IOException {
checkHttpsRequirement(request, response, oauth20Provider);
if (response.isCommitted()) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Response has already been committed, so likely did not pass HTTPS requirement");
}
return;
}
boolean isBrowserWithBasicAuth = false;
UIAccessTokenBuilder uitb = null;
if (tc.isDebugEnabled()) {
Tr.debug(tc, "endpointType[" + endpointType + "]");
}
try {
switch (endpointType) {
case authorize:
OAuthResult result = processAuthorizationRequest(oauth20Provider, request, response, servletContext, oidcOptionalParams);
if (result != null) {
if (result.getStatus() == OAuthResult.TAI_CHALLENGE) { // SPNEGO negotiate
break;
} else if (result.getStatus() != OAuthResult.STATUS_OK) {
userAuthentication.renderErrorPage(oauth20Provider, request, response, result);
}
}
break;
case token:
if (clientAuthentication.verify(oauth20Provider, request, response, endpointType)) {
processTokenRequest(oauth20Provider, request, response);
}
break;
case introspect:
if (clientAuthentication.verify(oauth20Provider, request, response, endpointType)) {
introspect(oauth20Provider, request, response);
}
break;
case revoke:
if (clientAuthentication.verify(oauth20Provider, request, response, endpointType)) {
revoke(oauth20Provider, request, response);
}
break;
case coverage_map: // non-spec extension
coverageMapServices.handleEndpointRequest(oauth20Provider, request, response);
break;
case registration:
secureEndpointServices(oauth20Provider, request, response, servletContext, RegistrationEndpointServices.ROLE_REQUIRED, true);
registrationEndpointServices.handleEndpointRequest(oauth20Provider, request, response);
break;
case logout:
// no need to authenticate
logout(oauth20Provider, request, response);
break;
case app_password:
tokenExchange.processAppPassword(oauth20Provider, request, response);
break;
case app_token:
tokenExchange.processAppToken(oauth20Provider, request, response);
break;
// these next 3 are for UI pages
case clientManagement:
if (!authenticateUI(request, response, servletContext, oauth20Provider, oidcOptionalParams, RegistrationEndpointServices.ROLE_REQUIRED)) {
break;
}
// new MockUiPage(request, response).render(); // TODO: replace with hook to real ui.
RequestDispatcher rd = servletContext.getRequestDispatcher("WEB-CONTENT/clientAdmin/index.jsp");
rd.forward(request, response);
break;
case personalTokenManagement:
if (!authenticateUI(request, response, servletContext, oauth20Provider, oidcOptionalParams, null)) {
break;
}
checkUIConfig(oauth20Provider, request);
// put auth header and access token and feature enablement state into request attributes for ui to use
uitb = new UIAccessTokenBuilder(oauth20Provider, request);
uitb.createHeaderValuesForUI();
// new MockUiPage(request, response).render(); // TODO: replace with hook to real ui.
RequestDispatcher rd2 = servletContext.getRequestDispatcher("WEB-CONTENT/accountManager/index.jsp");
rd2.forward(request, response);
break;
case usersTokenManagement:
if (!authenticateUI(request, response, servletContext, oauth20Provider, oidcOptionalParams, OAuth20Constants.TOKEN_MANAGER_ROLE)) {
break;
}
checkUIConfig(oauth20Provider, request);
// put auth header and access token and feature enablement state into request attributes for ui to use
uitb = new UIAccessTokenBuilder(oauth20Provider, request);
uitb.createHeaderValuesForUI();
// new MockUiPage(request, response).render(); // TODO: replace with hook to real ui.
RequestDispatcher rd3 = servletContext.getRequestDispatcher("WEB-CONTENT/tokenManager/index.jsp");
rd3.forward(request, response);
break;
case clientMetatype:
serveClientMetatypeRequest(request, response);
break;
default:
break;
}
} catch (OidcServerException e) {
if (!isBrowserWithBasicAuth) {
// we don't want routine browser auth challenges producing ffdc's.
// (but if a login is invalid in that case, we will still get a CWIML4537E from base sec.)
// however for non-browsers we want ffdc's like we had before, so generate manually
if (!e.getErrorDescription().contains("CWWKS1424E")) { // no ffdc for nonexistent clients
com.ibm.ws.ffdc.FFDCFilter.processException(e,
"com.ibm.ws.security.oauth20.web.OAuth20EndpointServices", "324", this);
}
}
boolean suppressBasicAuthChallenge = isBrowserWithBasicAuth; // ui must NOT log in using basic auth, so logout function will work.
WebUtils.sendErrorJSON(response, e.getHttpStatus(), e.getErrorCode(), e.getErrorDescription(request.getLocales()), suppressBasicAuthChallenge);
}
}
// return true if clear to go, false otherwise. Log message and/or throw exception if unsuccessful
private boolean authenticateUI(HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext, OAuth20Provider provider, AttributeList options, String requiredRole)
throws ServletException, IOException, OidcServerException {
OAuthResult result = handleUIUserAuthentication(request, response, servletContext, provider, options);
if (!isUIAuthenticationComplete(request, response, provider, result, requiredRole)) {
return false;
}
return true;
}
private boolean isUIAuthenticationComplete(HttpServletRequest request, HttpServletResponse response, OAuth20Provider provider, OAuthResult result, String requiredRole) throws OidcServerException {
if (result == null) { // sent to login page
return false;
}
if (result.getStatus() == OAuthResult.TAI_CHALLENGE) { // SPNEGO negotiate
return false;
}
if (result.getStatus() != OAuthResult.STATUS_OK) {
try {
userAuthentication.renderErrorPage(provider, request, response, result);
} catch (Exception e) {
// ffdc
}
return false;
}
if (requiredRole != null && !request.isUserInRole(requiredRole)) {
throw new OidcServerException("403", OIDCConstants.ERROR_ACCESS_DENIED, HttpServletResponse.SC_FORBIDDEN);
}
return true;
}
void serveClientMetatypeRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
OAuth20ClientMetatypeService metatypeService = oauth20ClientMetatypeServiceRef.getService();
if (metatypeService == null) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
metatypeService.sendClientMetatypeData(request, response);
}
private boolean checkUIConfig(OAuth20Provider provider, HttpServletRequest request) {
String uri = request.getRequestURI();
String id = provider.getInternalClientId();
String secret = provider.getInternalClientSecret();
OidcBaseClient client = null;
boolean result = false;
try {
client = provider.getClientProvider().get(id);
} catch (OidcServerException e) {
// ffdc
}
if (client != null) {
result = secret != null && client.isEnabled() && (client.isAppPasswordAllowed() || client.isAppTokenAllowed());
}
if (!result) {
Tr.warning(tc2, "OAUTH_UI_ENDPOINT_NOT_ENABLED", uri);
}
return result;
}
/**
* Perform logout. call base security logout to clear ltpa cookie.
* Then redirect to a configured logout page if available, else a default.
*
* This does NOT implement
* OpenID Connect Session Management 1.0 draft 28. as of Nov. 2017
* https://openid.net/specs/openid-connect-session-1_0.html#RedirectionAfterLogout
*
* Instead it is a simpler approach that just deletes the ltpa (sso) cookie
* and sends a simple error page if things go wrong.
*
* @param provider
* @param request
* @param response
*/
public void logout(OAuth20Provider provider,
HttpServletRequest request,
HttpServletResponse response) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Processing logout");
}
try {
request.logout(); // ltpa cookie removed if present. No exception if not.
} catch (ServletException e) {
FFDCFilter.processException(e,
this.getClass().getName(), "logout",
new Object[] {});
new LogoutPages().sendDefaultErrorPage(request, response);
return;
}
// not part of spec: logout url defined in config, not client-specific
String logoutRedirectURL = provider.getLogoutRedirectURL();
try {
if (logoutRedirectURL != null) {
String encodedURL = URLEncodeParams(logoutRedirectURL);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "OAUTH20 _SSO OP redirecting to [" + logoutRedirectURL + "], url encoded to [" + encodedURL + "]");
}
response.sendRedirect(encodedURL);
return;
} else {
// send default logout page
new LogoutPages().sendDefaultLogoutPage(request, response);
}
} catch (IOException e) {
FFDCFilter.processException(e,
this.getClass().getName(), "logout",
new Object[] {});
new LogoutPages().sendDefaultErrorPage(request, response);
}
}
String URLEncodeParams(String UrlStr) {
String sep = "?";
String encodedURL = UrlStr;
int index = UrlStr.indexOf(sep);
// if encoded url in server.xml, don't encode it again.
boolean alreadyEncoded = UrlStr.contains("%");
if (index > -1 && !alreadyEncoded) {
index++; // don't encode ?
String prefix = UrlStr.substring(0, index);
String suffix = UrlStr.substring(index);
try {
encodedURL = prefix + java.net.URLEncoder.encode(suffix, StandardCharsets.UTF_8.toString());
// shouldn't encode = in queries, so flip those back
encodedURL = encodedURL.replace("%3D", "=");
} catch (UnsupportedEncodingException e) {
// ffdc
}
}
return encodedURL;
}
public OAuthResult processAuthorizationRequest(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext, AttributeList options)
throws ServletException, IOException, OidcServerException {
OAuthResult oauthResult = checkForError(request);
if (oauthResult != null) {
return oauthResult;
}
boolean autoAuthz = clientAuthorization.isClientAutoAuthorized(provider, request);
String reqConsentNonce = getReqConsentNonce(request);
boolean afterLogin = isAfterLogin(request); // we've been to login.jsp or it's replacement.
if (reqConsentNonce == null) { // validate request for initial authorization request only
oauthResult = clientAuthorization.validateAuthorization(provider, request, response);
if (oauthResult.getStatus() != OAuthResult.STATUS_OK) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Status is OK, returning result");
}
return oauthResult;
}
}
oauthResult = handleUserAuthentication(oauthResult, request, response, servletContext,
provider, reqConsentNonce, options, autoAuthz, afterLogin);
return oauthResult;
}
/**
* Adds the id_token_hint_status, id_token_hint_username, and id_token_hint_clientid attributes from the options list
* into attrList, if those attributes exist.
*
* @param options
* @param attrList
*/
private void setTokenHintAttributes(AttributeList options, AttributeList attrList) {
String value = options.getAttributeValueByName(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_STATUS);
if (value != null) {
attrList.setAttribute(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_STATUS, OAuth20Constants.ATTRTYPE_REQUEST, new String[] { value });
}
value = options.getAttributeValueByName(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_USERNAME);
if (value != null) {
attrList.setAttribute(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_USERNAME, OAuth20Constants.ATTRTYPE_REQUEST, new String[] { value });
}
value = options.getAttributeValueByName(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_CLIENTID);
if (value != null) {
attrList.setAttribute(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_CLIENTID, OAuth20Constants.ATTRTYPE_REQUEST, new String[] { value });
}
}
/**
* @param attrs
* @param request
* @return OAuthResultImpl if validation failed, null otherwise.
*/
private OAuthResultImpl validateIdTokenHintIfPresent(AttributeList attrs, HttpServletRequest request) {
if (attrs != null) {
Principal user = request.getUserPrincipal();
String username = null;
if (user != null) {
username = user.getName();
}
try {
userAuthentication.validateIdTokenHint(username, attrs);
} catch (OAuth20Exception oe) {
return new OAuthResultImpl(OAuthResult.STATUS_FAILED, attrs, oe);
}
}
return null;
}
/**
* Creates a 401 STATUS_FAILED result due to the token limit being reached.
*
* @param attrs
* @param request
* @param clientId
* @return
*/
private OAuthResult createTokenLimitResult(AttributeList attrs, HttpServletRequest request, String clientId) {
if (attrs == null) {
attrs = new AttributeList();
String responseType = request.getParameter(OAuth20Constants.RESPONSE_TYPE);
attrs.setAttribute(OAuth20Constants.RESPONSE_TYPE, OAuth20Constants.RESPONSE_TYPE, new String[] { responseType });
attrs.setAttribute(OAuth20Constants.CLIENT_ID, OAuth20Constants.CLIENT_ID, new String[] { clientId });
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Attribute responseType:" + responseType + " client_id:" + clientId);
}
}
OAuth20AccessDeniedException e = new OAuth20AccessDeniedException("security.oauth20.token.limit.external.error");
e.setHttpStatusCode(HttpServletResponse.SC_BAD_REQUEST);
OAuthResult oauthResultWithExcep = new OAuthResultImpl(OAuthResult.STATUS_FAILED, attrs, e);
return oauthResultWithExcep;
}
private OAuthResult handleUIUserAuthentication(HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext, OAuth20Provider provider, AttributeList options) throws IOException, ServletException, OidcServerException {
OAuthResult oauthResult = null;
Prompt prompt = new Prompt();
if (request.getUserPrincipal() == null) {
// authenticate user if not done yet. Send to login page.
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Authenticate user if not done yet");
}
oauthResult = userAuthentication.handleAuthenticationWithOAuthResult(provider, request, response, prompt, securityServiceRef, servletContext, OAuth20EndpointServices.AUTHENTICATED, oauthResult);
}
if (request.getUserPrincipal() == null) { // must be redirect
return oauthResult;
} else if (CookieHelper.getCookieValue(request.getCookies(), ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME) != null) {
ReferrerURLCookieHandler handler = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig().createReferrerURLCookieHandler(); // GM 2017.05.31
// ReferrerURLCookieHandler handler = new ReferrerURLCookieHandler(WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig());
handler.invalidateReferrerURLCookie(request, response, ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME);
}
if (!request.isUserInRole(AUTHENTICATED)) { // must be authorized, we'll check userInRole later.
Tr.audit(tc, "security.oauth20.error.authorization", request.getUserPrincipal().getName());
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return oauthResult;
}
return new OAuthResultImpl(OAuthResult.STATUS_OK, new AttributeList());
}
@FFDCIgnore({ OAuth20BadParameterException.class })
private OAuthResult handleUserAuthentication(OAuthResult oauthResult, HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext, OAuth20Provider provider,
String reqConsentNonce, AttributeList options, boolean autoauthz, boolean afterLogin) throws IOException, ServletException, OidcServerException {
Prompt prompt = null;
String[] scopesAttr = null;
AttributeList attrs = null;
if (oauthResult != null) {
attrs = oauthResult.getAttributeList();
scopesAttr = attrs.getAttributeValuesByName(OAuth20Constants.SCOPE);
if (options != null) {
setTokenHintAttributes(options, attrs);
}
String[] validResources = attrs.getAttributeValuesByName(OAuth20Constants.RESOURCE);
if (validResources != null) {
options.setAttribute(OAuth20Constants.RESOURCE, OAuth20Constants.ATTRTYPE_PARAM_OAUTH, validResources);
}
}
// Per section 4.1.2.1 of the OAuth 2.0 spec (RFC6749), the state parameter must be included in any error response if it was
// originally provided in the request. Adding it to the attribute list here will ensure it is propagated to any failure response.
String[] stateParams = request.getParameterValues(OAuth20Constants.STATE);
if (stateParams != null) {
if (attrs == null) {
attrs = new AttributeList();
}
attrs.setAttribute(OAuth20Constants.STATE, OAuth20Constants.ATTRTYPE_PARAM_QUERY, stateParams);
}
boolean isOpenId = false;
if (scopesAttr != null) {
for (String scope : scopesAttr) {
if (OIDCConstants.SCOPE_OPENID.equals(scope)) {
isOpenId = true;
break;
}
}
}
if (isOpenId) {
// if id_token_hint exists and user is already logged in, compare...
OAuthResultImpl result = validateIdTokenHintIfPresent(attrs, request);
if (result != null) {
return result;
}
}
prompt = new Prompt(request);
if (request.getUserPrincipal() == null || (prompt.hasLogin() && !afterLogin)) {
// authenticate user if not done yet
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Authenticate user if not done yet");
}
oauthResult = userAuthentication.handleAuthenticationWithOAuthResult(provider, request, response, prompt, securityServiceRef, servletContext, OAuth20EndpointServices.AUTHENTICATED, oauthResult);
}
if (request.getUserPrincipal() == null) { // must be redirect
return oauthResult;
} else if (CookieHelper.getCookieValue(request.getCookies(), ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME) != null) {
ReferrerURLCookieHandler handler = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig().createReferrerURLCookieHandler(); // GM 2017.05.31
// ReferrerURLCookieHandler handler = new ReferrerURLCookieHandler(WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig());
handler.invalidateReferrerURLCookie(request, response, ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME);
}
if (!request.isUserInRole(AUTHENTICATED) && !request.isUserInRole(OAuth20Constants.TOKEN_MANAGER_ROLE)) { // must be authorized
Tr.audit(tc, "security.oauth20.error.authorization", request.getUserPrincipal().getName());
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return oauthResult;
}
if (reqConsentNonce != null && !consent.isNonceValid(request, reqConsentNonce)) { // nonce must be valid if has one
consent.handleNonceError(request, response);
return oauthResult;
}
String clientId = getClientId(request);
String[] reducedScopes = null;
try {
reducedScopes = clientAuthorization.getReducedScopes(provider, request, clientId, true);
} catch (Exception e1) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Caught exception, so setting reduced scopes to null. Exception was: " + e1);
}
reducedScopes = null;
}
boolean preAuthzed = false;
if (reqConsentNonce == null) {
try {
preAuthzed = clientAuthorization.isPreAuthorizedScope(provider, clientId, reducedScopes);
} catch (Exception e) {
preAuthzed = false;
}
}
// Handle consent
if (!autoauthz && !preAuthzed && reqConsentNonce == null && !consent.isCachedAndValid(oauthResult, provider, request, response)) {
if (prompt.hasNone()) {
// Prompt includes "none," however authorization has not been obtained or cached; return error
oauthResult = prompt.errorConsentRequired(attrs);
} else {
// ask user for approval if not auto authorized, or not approved
Nonce nonce = consent.setNonce(request);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "_SSO OP redirecting for consent");
}
consent.renderConsentForm(request, response, provider, clientId, nonce, oauthResult.getAttributeList(), servletContext);
}
return oauthResult;
}
if (reachedTokenLimit(provider, request)) {
return createTokenLimitResult(attrs, request, clientId);
}
if (request.getAttribute(OAuth20Constants.OIDC_REQUEST_OBJECT_ATTR_NAME) != null) {
// Ensure that the reduced scopes list is not empty
oauthResult = clientAuthorization.checkForEmptyScopeSetAfterConsent(reducedScopes, oauthResult, request, provider, clientId);
if (oauthResult != null && oauthResult.getStatus() != OAuthResult.STATUS_OK) {
response.setStatus(HttpServletResponse.SC_FOUND);
return oauthResult;
}
}
// getBack the resource. better double check it
OidcBaseClient client;
try {
client = OAuth20ProviderUtils.getOidcOAuth20Client(provider, clientId);
OAuth20ProviderUtils.validateResource(request, options, client);
} catch (OAuth20BadParameterException e) { // some exceptions need to handled separately
WebUtils.throwOidcServerException(request, e);
} catch (OAuth20Exception e) {
WebUtils.throwOidcServerException(request, e);
}
if (options != null) {
options.setAttribute(OAuth20Constants.SCOPE, OAuth20Constants.ATTRTYPE_RESPONSE_ATTRIBUTE, reducedScopes);
}
if (provider.isTrackOAuthClients()) {
OAuthClientTracker clientTracker = new OAuthClientTracker(request, response, provider);
clientTracker.trackOAuthClient(clientId);
}
consent.handleConsent(provider, request, prompt, clientId);
getExternalClaimsFromWSSubject(request, options);
oauthResult = provider.processAuthorization(request, response, options);
return oauthResult;
}
/**
* Secure registration services with BASIC Auth and validating against the required role.
*
* @param provider
* @param request
* @param response
* @param servletContext
* @param requiredRole - user must be in this role.
* @param fallbacktoBasicAuth - if false, if there is no cookie on the request, then no basic auth challenge will be sent back to browser.
* @throws OidcServerException
*/
@FFDCIgnore({ OidcServerException.class })
private void secureEndpointServices(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, String requiredRole, boolean fallbackToBasicAuth) throws OidcServerException {
try {
userAuthentication.handleBasicAuthenticationWithRequiredRole(provider, request, response, securityServiceRef, servletContext, requiredRole, fallbackToBasicAuth);
} catch (OidcServerException e) {
if (fallbackToBasicAuth) {
if (e.getHttpStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
response.setHeader(RegistrationEndpointServices.HDR_WWW_AUTHENTICATE, RegistrationEndpointServices.UNAUTHORIZED_HEADER_VALUE);
}
}
throw e;
}
}
@FFDCIgnore({ OAuth20BadParameterException.class })
public void processTokenRequest(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response) throws ServletException, OidcServerException {
String clientId = (String) request.getAttribute("authenticatedClient");
try {
// checking resource
OidcBaseClient client = OAuth20ProviderUtils.getOidcOAuth20Client(provider, clientId);
if (client == null || !client.isEnabled()) {
throw new OidcServerException("security.oauth20.error.invalid.client", OIDCConstants.ERROR_INVALID_CLIENT_METADATA, HttpServletResponse.SC_BAD_REQUEST);
}
OAuth20ProviderUtils.validateResource(request, null, client);
} catch (OAuth20BadParameterException e) { // some exceptions need to handled separately
WebUtils.throwOidcServerException(request, e);
} catch (OAuth20Exception e) {
WebUtils.throwOidcServerException(request, e);
}
OAuthResult result = clientAuthorization.validateAndHandle2LegsScope(provider, request, response, clientId);
if (result.getStatus() == OAuthResult.STATUS_OK) {
result = provider.processTokenRequest(clientId, request, response);
}
if (result.getStatus() != OAuthResult.STATUS_OK) {
OAuth20TokenRequestExceptionHandler handler = new OAuth20TokenRequestExceptionHandler();
handler.handleResultException(request, response, result);
}
}
/**
* Get the access token from the request's token parameter and look it up in
* the token cache.
*
* If the access token is found in the cache return status 200 and a JSON object.
*
* If the token is not found or the request had errors return status 400.
*
* @param provider
* @param request
* @param response
* @throws OidcServerException
* @throws IOException
*/
public void introspect(OAuth20Provider provider,
HttpServletRequest request,
HttpServletResponse response) throws OidcServerException, IOException {
TokenIntrospect tokenIntrospect = new TokenIntrospect();
tokenIntrospect.introspect(provider, request, response);
}
/**
* Revoke the provided token by removing it from the cache
*
* If the access token is found in the cache remove it from the cache
* and return status 200.
*
* @param provider
* @param request
* @param response
*/
public void revoke(OAuth20Provider provider,
HttpServletRequest request,
HttpServletResponse response) {
try {
String tokenString = request.getParameter(com.ibm.ws.security.oauth20.util.UtilConstants.TOKEN);
if (tokenString == null) {
// send 400 per OAuth Token revocation spec
WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST,
Constants.ERROR_CODE_INVALID_REQUEST, null); // invalid_request
return;
}
String tokenLookupStr = tokenString;
OAuth20Token token = null;
boolean isAppPasswordOrToken = false;
if (OidcOAuth20Util.isJwtToken(tokenString)) {
tokenLookupStr = com.ibm.ws.security.oauth20.util.HashUtils.digest(tokenString);
} else if (tokenString.length() == (provider.getAccessTokenLength() + 2)) {
// app-token
String encode = provider.getAccessTokenEncoding();
if (OAuth20Constants.PLAIN_ENCODING.equals(encode)) { // must be app-password or app-token
tokenLookupStr = EndpointUtils.computeTokenHash(tokenString);
} else {
tokenLookupStr = EndpointUtils.computeTokenHash(tokenString, encode);
}
isAppPasswordOrToken = true;
}
if (isAppPasswordOrToken) {
token = provider.getTokenCache().getByHash(tokenLookupStr);
} else {
token = provider.getTokenCache().get(tokenLookupStr);
}
boolean isAppPassword = false;
if (token != null && OAuth20Constants.APP_PASSWORD.equals(token.getGrantType())) {
isAppPassword = true;
Tr.error(tc, "security.oauth20.apppwtok.revoke.disallowed", new Object[] {});
}
if (token == null) {
// send 200 per OAuth Token revocation spec
response.setStatus(HttpServletResponse.SC_OK);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "token " + tokenString + " not in cache or wrong token type, return");
}
return;
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, "token type: " + token.getType());
}
ClientAuthnData clientAuthData = new ClientAuthnData(request, response);
if (clientAuthData.hasAuthnData() &&
clientAuthData.getUserName().equals(token.getClientId()) == true) {
if (!isAppPassword && ((token.getType().equals(OAuth20Constants.TOKENTYPE_AUTHORIZATION_GRANT) &&
token.getSubType().equals(OAuth20Constants.SUBTYPE_REFRESH_TOKEN)) ||
token.getType().equals(OAuth20Constants.TOKENTYPE_ACCESS_TOKEN))) {
// Revoke the token by removing it from the cache
if (tc.isDebugEnabled()) {
OAuth20Token theToken = provider.getTokenCache().get(tokenLookupStr);
String buf = (theToken != null) ? "is in the cache" : "is not in the cache";
Tr.debug(tc, "token " + tokenLookupStr + " " + buf + ", calling remove");
}
if (isAppPasswordOrToken) {
provider.getTokenCache().removeByHash(tokenLookupStr);
} else {
provider.getTokenCache().remove(tokenLookupStr);
}
if (token.getSubType().equals(OAuth20Constants.SUBTYPE_REFRESH_TOKEN)) {
removeAssociatedAccessTokens(request, provider, token);
}
response.setStatus(HttpServletResponse.SC_OK);
} else {
// Unsupported token type, send 400 per RFC7009 OAuth Token revocation spec
WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST,
Constants.ERROR_CODE_UNSUPPORTED_TOKEN_TYPE, null);
}
} else {
// client is not authorized. send 400 per RFC6749 5.2 OAuth Token revocation spec
String defaultMsg = "CWWKS1406E: The revoke request had an invalid client credential. The request URI was {" + request.getRequestURI() + "}.";
String errorMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"OAUTH_INVALID_CLIENT",
new Object[] { "revoke", request.getRequestURI() },
defaultMsg);
WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST,
Constants.ERROR_CODE_INVALID_CLIENT, errorMsg);
}
} catch (OAuth20DuplicateParameterException e) {
// Duplicate parameter found in request
WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST, Constants.ERROR_CODE_INVALID_REQUEST, e.getMessage());
} catch (Exception e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Internal error processing token revoke request", e);
}
try {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} catch (IOException ioe) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Internal error process token introspect revoke error", ioe);
}
}
}
}
/**
* For OpenidConnect, when a refresh token is revoked, also delete all access tokens that have become associated with it.
* (Each time a refresh token is submitted for a new one, the prior access tokens become associated with the new refresh token)
* @param request
* @param provider
* @param refreshToken
* @throws Exception
*/
private void removeAssociatedAccessTokens(HttpServletRequest request, OAuth20Provider provider, OAuth20Token refreshToken) throws Exception {
String contextPath = request.getContextPath();
if (contextPath != null && !contextPath.equals("/oidc")) {
// if this is for oauth, return. Oauth's persistence code doesn't support this token association.
// and we only wanted revocation for oidc, we wanted to leave oauth alone.
if (tc.isDebugEnabled()) {
Tr.debug(tc, "not oidc, returning");
}
return;
}
if (!provider.getRevokeAccessTokensWithRefreshTokens()) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "provider prop revokeAccessTokensWithRefreshTokens is false, returning");
}
return;
}
String username = refreshToken.getUsername();
String clientId = refreshToken.getClientId();
String refreshTokenId = refreshToken.getId();
OAuth20EnhancedTokenCache cache = provider.getTokenCache();
Collection<OAuth20Token> ctokens = cache.getAllUserTokens(username);
for (OAuth20Token ctoken : ctokens) {
boolean nullGuard = (cache != null && ctoken.getType() != null && clientId != null && ctoken.getClientId() != null && ctoken.getId() != null);
if (nullGuard && OAuth20Constants.TOKENTYPE_ACCESS_TOKEN.equals(ctoken.getType()) && clientId.equals(ctoken.getClientId())
&& refreshTokenId.equals(((OAuth20TokenImpl) ctoken).getRefreshTokenKey())) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "removing token: " + ctoken.getId());
}
cache.remove(ctoken.getId());
}
}
}
protected void checkHttpsRequirement(HttpServletRequest request, HttpServletResponse response, OAuth20Provider provider) throws IOException {
String url = request.getRequestURL().toString();
if (provider.isHttpsRequired()) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Checking if URL starts with https: " + url);
}
if (url != null && !url.startsWith("https")) {
Tr.error(tc, "security.oauth20.error.wrong.http.scheme", new Object[] { url });
response.sendError(HttpServletResponse.SC_NOT_FOUND,
Tr.formatMessage(tc, "security.oauth20.error.wrong.http.scheme",
new Object[] { url }));
}
}
}
/**
* Determines if this user hit the token limit for the user / client combination
*
* @param provider
* @param request
* @return
*/
protected boolean reachedTokenLimit(OAuth20Provider provider, HttpServletRequest request) {
String userName = getUserName(request);
String clientId = getClientId(request);
long limit = provider.getClientTokenCacheSize();
if (limit > 0) {
long numtokens = provider.getTokenCache().getNumTokens(userName, clientId);
if (numtokens >= limit) {
Tr.error(tc, "security.oauth20.token.limit.error", new Object[] { userName, clientId, limit });
return true;
}
}
return false;
}
private OAuth20Request getAuth20Request(HttpServletRequest request, HttpServletResponse response) throws IOException {
OAuth20Request oauth20Request = (OAuth20Request) request.getAttribute(OAuth20Constants.OAUTH_REQUEST_OBJECT_ATTR_NAME);
if (oauth20Request == null) {
String errorMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"OAUTH_REQUEST_ATTRIBUTE_MISSING",
new Object[] { request.getRequestURI(), OAuth20Constants.OAUTH_REQUEST_OBJECT_ATTR_NAME },
"CWWKS1412E: The request endpoint {0} does not have attribute {1}.");
Tr.error(tc, errorMsg);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
return oauth20Request;
}
private OAuth20Provider getProvider(HttpServletResponse response, OAuth20Request oauth20Request) throws IOException {
OAuth20Provider provider = ProvidersService.getOAuth20Provider(oauth20Request.getProviderName());
if (provider == null) {
String errorMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"OAUTH_PROVIDER_OBJECT_NULL",
new Object[] { oauth20Request.getProviderName(), OAuth20Constants.OAUTH_REQUEST_OBJECT_ATTR_NAME },
"CWWKS1413E: The OAuth20Provider object is null for OAuth provider {0}.");
Tr.error(tc, errorMsg);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
return provider;
}
private String getReqConsentNonce(HttpServletRequest request) {
return request.getParameter(ATTR_NONCE);
}
private String getUserName(HttpServletRequest request) {
return request.getUserPrincipal().getName();
}
private String getClientId(HttpServletRequest request) {
return request.getParameter(OAuth20Constants.CLIENT_ID);
}
/* returns whether login form had been presented */
protected boolean isAfterLogin(HttpServletRequest request) {
boolean output = false;
HttpSession session = request.getSession(false);
if (session != null) {
if (session.getAttribute(Constants.ATTR_AFTERLOGIN) != null) {
session.removeAttribute(Constants.ATTR_AFTERLOGIN);
output = true;
}
}
return output;
}
/**
* @return
*/
@SuppressWarnings("unchecked")
public Map<String, String[]> getExternalClaimsFromWSSubject(HttpServletRequest request, AttributeList options) {
final String methodName = "getExternalClaimsFromWSSubject";
try {
String externalClaimNames = options.getAttributeValueByName(OAuth20Constants.EXTERNAL_CLAIM_NAMES);
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " externalClamiNames:" + externalClaimNames);
if (externalClaimNames != null) {
Map<String, String[]> map2 = (Map<String, String[]>) getFromWSSubject(OAuth20Constants.EXTERNAL_MEDIATION);
if (map2 != null && map2.size() > 0) {
Set<Entry<String, String[]>> entries = map2.entrySet();
for (Entry<String, String[]> entry : entries) {
options.setAttribute(entry.getKey(), OAuth20Constants.EXTERNAL_MEDIATION, entry.getValue());
}
}
// get the external claims
Map<String, String[]> map = (Map<String, String[]>) getFromWSSubject(OAuth20Constants.EXTERNAL_CLAIMS);
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " externalClaims:" + map);
if (map == null)
return null;
// filter properties by externalClaimNames
StringTokenizer strTokenizer = new StringTokenizer(externalClaimNames, ", ");
while (strTokenizer.hasMoreTokens()) {
String key = strTokenizer.nextToken();
String[] values = map.get(key);
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " key:" + key + " values:'" + OAuth20Util.arrayToSpaceString(values) + "'");
if (values != null && values.length > 0) {
options.setAttribute(OAuth20Constants.EXTERNAL_CLAIMS_PREFIX + key, OAuth20Constants.EXTERNAL_CLAIMS, values);
}
}
return map;
}
} catch (WSSecurityException e) {
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " failed. Nothing changed. WSSecurityException:" + e);
}
return null;
}
/**
* @param externalClaims
* @return
*/
private Object getFromWSSubject(String externalClaims) throws WSSecurityException {
Subject runAsSubject = WSSubject.getRunAsSubject();
Object obj = null;
try {
Set<Object> publicCreds = runAsSubject.getPublicCredentials();
if (publicCreds != null && publicCreds.size() > 0) {
Iterator<Object> publicCredIterator = publicCreds.iterator();
while (publicCredIterator.hasNext()) {
Object cred = publicCredIterator.next();
if (cred != null && cred instanceof Hashtable) {
@SuppressWarnings("rawtypes")
Hashtable userCred = (Hashtable) cred;
obj = userCred.get(externalClaims);
if (obj != null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "getFromWSSubject found:" + obj);
}
break;
}
}
}
}
} catch (Exception e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Unable to match predefined cache key." + e);
}
}
return obj;
}
/**
* Check if the request contains an "error" parameter. If one is present and equals the OAuth 2.0 error type "access_denied", a message indicating the user likely canceled the request will be
* logged and a failure result will be returned.
*
* @param request
* @return A {@code OAuthResult} object initialized with AuthResult.FAILURE and 403 status code if an "error" parameter is present and equals "access_denied." Returns null otherwise.
*/
private OAuthResult checkForError(HttpServletRequest request) {
OAuthResult result = null;
String error = request.getParameter("error");
if (error != null && error.length() > 0 && OAuth20Exception.ACCESS_DENIED.equals(error)) {
// User likely canceled the request
String errorMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"security.oauth20.request.denied",
new Object[] {},
"CWOAU0067E: The request has been denied by the user, or another error occurred that resulted in denial of the request.");
Tr.error(tc, errorMsg);
OAuth20AccessDeniedException e = new OAuth20AccessDeniedException("security.oauth20.request.denied");
e.setHttpStatusCode(HttpServletResponse.SC_FORBIDDEN);
AttributeList attrs = new AttributeList();
String value = request.getParameter(OAuth20Constants.RESPONSE_TYPE);
if (value != null && value.length() > 0) {
attrs.setAttribute(OAuth20Constants.RESPONSE_TYPE, OAuth20Constants.RESPONSE_TYPE, new String[] { value });
}
value = getClientId(request);
if (value != null && value.length() > 0) {
attrs.setAttribute(OAuth20Constants.CLIENT_ID, OAuth20Constants.CLIENT_ID, new String[] { value });
}
result = new OAuthResultImpl(OAuthResult.STATUS_FAILED, attrs, e);
}
return result;
}
/**
* @param provider
* @param responseJSON
* @param accessToken
* @param groupsOnly
* @throws IOException
*/
protected Map<String, Object> getUserClaimsMap(UserClaims userClaims, boolean groupsOnly) throws IOException {
// keep this method for OidcEndpointServices
return TokenIntrospect.getUserClaimsMap(userClaims, groupsOnly);
}
protected UserClaims getUserClaimsObj(OAuth20Provider provider, OAuth20Token accessToken) throws IOException {
// keep this method for OidcEndpointServices
return TokenIntrospect.getUserClaimsObj(provider, accessToken);
}
}
| kgibm/open-liberty | dev/com.ibm.ws.security.oauth/src/com/ibm/ws/security/oauth20/web/OAuth20EndpointServices.java | Java | epl-1.0 | 60,040 |
/*******************************************************************************
* Copyright (c) 2005-2010, G. Weirich and Elexis
* 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:
* G. Weirich - initial implementation
* D. Lutz - adapted for importing data from other databases
*
*******************************************************************************/
package ch.elexis.core.ui.wizards;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import ch.elexis.core.ui.UiDesk;
import ch.elexis.core.ui.icons.ImageSize;
import ch.elexis.core.ui.icons.Images;
import ch.rgw.tools.JdbcLink;
import ch.rgw.tools.StringTool;
public class DBImportFirstPage extends WizardPage {
List dbTypes;
Text server, dbName;
String defaultUser, defaultPassword;
JdbcLink j = null;
static final String[] supportedDB = new String[] {
"mySQl", "PostgreSQL", "H2", "ODBC" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
};
static final int MYSQL = 0;
static final int POSTGRESQL = 1;
static final int ODBC = 3;
static final int H2 = 2;
public DBImportFirstPage(String pageName){
super(Messages.DBImportFirstPage_connection, Messages.DBImportFirstPage_typeOfDB,
Images.IMG_LOGO.getImageDescriptor(ImageSize._75x66_TitleDialogIconSize)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
setMessage(Messages.DBImportFirstPage_selectType + Messages.DBImportFirstPage_enterNameODBC); //$NON-NLS-1$
setDescription(Messages.DBImportFirstPage_theDesrciption); //$NON-NLS-1$
}
public DBImportFirstPage(String pageName, String title, ImageDescriptor titleImage){
super(pageName, title, titleImage);
// TODO Automatisch erstellter Konstruktoren-Stub
}
public void createControl(Composite parent){
DBImportWizard wiz = (DBImportWizard) getWizard();
FormToolkit tk = UiDesk.getToolkit();
Form form = tk.createForm(parent);
form.setText(Messages.DBImportFirstPage_Connection); //$NON-NLS-1$
Composite body = form.getBody();
body.setLayout(new TableWrapLayout());
tk.createLabel(body, Messages.DBImportFirstPage_EnterType); //$NON-NLS-1$
dbTypes = new List(body, SWT.BORDER);
dbTypes.setItems(supportedDB);
dbTypes.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e){
int it = dbTypes.getSelectionIndex();
switch (it) {
case MYSQL:
case POSTGRESQL:
server.setEnabled(true);
dbName.setEnabled(true);
defaultUser = ""; //$NON-NLS-1$
defaultPassword = ""; //$NON-NLS-1$
break;
case H2:
server.setEnabled(false);
dbName.setEnabled(true);
defaultUser = "sa";
defaultPassword = "";
break;
case ODBC:
server.setEnabled(false);
dbName.setEnabled(true);
defaultUser = "sa"; //$NON-NLS-1$
defaultPassword = ""; //$NON-NLS-1$
break;
default:
break;
}
DBImportSecondPage sec = (DBImportSecondPage) getNextPage();
sec.name.setText(defaultUser);
sec.pwd.setText(defaultPassword);
}
});
tk.adapt(dbTypes, true, true);
tk.createLabel(body, Messages.DBImportFirstPage_serverAddress); //$NON-NLS-1$
server = tk.createText(body, "", SWT.BORDER); //$NON-NLS-1$
TableWrapData twr = new TableWrapData(TableWrapData.FILL_GRAB);
server.setLayoutData(twr);
tk.createLabel(body, Messages.DBImportFirstPage_databaseName); //$NON-NLS-1$
dbName = tk.createText(body, "", SWT.BORDER); //$NON-NLS-1$
TableWrapData twr2 = new TableWrapData(TableWrapData.FILL_GRAB);
dbName.setLayoutData(twr2);
if (wiz.preset != null && wiz.preset.length > 1) {
int idx = StringTool.getIndex(supportedDB, wiz.preset[0]);
if (idx < dbTypes.getItemCount()) {
dbTypes.select(idx);
}
server.setText(wiz.preset[1]);
dbName.setText(wiz.preset[2]);
}
setControl(form);
}
}
| sazgin/elexis-3-core | ch.elexis.core.ui/src/ch/elexis/core/ui/wizards/DBImportFirstPage.java | Java | epl-1.0 | 4,493 |
/*******************************************************************************
* Copyright (c) 2020 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.install.internal;
public class MavenRepository {
private String name;
private String repositoryUrl;
private String userId;
private String password;
public MavenRepository(String name, String repositoryUrl, String userId, String password) {
this.name = name;
this.repositoryUrl = repositoryUrl;
this.userId = userId;
this.password = password;
}
public String getName(){
return name;
}
public String getRepositoryUrl() {
return repositoryUrl;
}
public String getUserId() {
return userId;
}
public String getPassword() {
return password;
}
public String toString(){
return this.repositoryUrl;
}
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/MavenRepository.java | Java | epl-1.0 | 1,293 |
/*******************************************************************************
* Copyright (c) 2011, 2016 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.datastore.internal.model.query;
import java.util.ArrayList;
import org.eclipse.kapua.service.datastore.model.Storable;
import org.eclipse.kapua.service.datastore.model.StorableListResult;
@SuppressWarnings("serial")
public class AbstractStorableListResult<E extends Storable> extends ArrayList<E> implements StorableListResult<E>
{
private Object nextKey;
private Integer totalCount;
public AbstractStorableListResult()
{
nextKey = null;
totalCount = null;
}
public AbstractStorableListResult(Object nextKey)
{
this.nextKey = nextKey;
this.totalCount = null;
}
public AbstractStorableListResult(Object nextKeyOffset, Integer totalCount)
{
this(nextKeyOffset);
this.totalCount = totalCount;
}
public Object getNextKey()
{
return nextKey;
}
public Integer getTotalCount()
{
return totalCount;
}
}
| muros-ct/kapua | service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/AbstractStorableListResult.java | Java | epl-1.0 | 1,524 |
package moCreatures.items;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.Item;
import net.minecraft.src.ItemStack;
import net.minecraft.src.World;
import moCreatures.entities.EntitySharkEgg;
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode
public class ItemSharkEgg extends Item
{
public ItemSharkEgg(int i)
{
super(i);
maxStackSize = 16;
}
public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer)
{
itemstack.stackSize--;
if(!world.singleplayerWorld)
{
EntitySharkEgg entitysharkegg = new EntitySharkEgg(world);
entitysharkegg.setPosition(entityplayer.posX, entityplayer.posY, entityplayer.posZ);
world.entityJoinedWorld(entitysharkegg);
entitysharkegg.motionY += world.rand.nextFloat() * 0.05F;
entitysharkegg.motionX += (world.rand.nextFloat() - world.rand.nextFloat()) * 0.3F;
entitysharkegg.motionZ += (world.rand.nextFloat() - world.rand.nextFloat()) * 0.3F;
}
return itemstack;
}
}
| sehrgut/minecraft-smp-mocreatures | moCreatures/server/debug/sources/moCreatures/items/ItemSharkEgg.java | Java | epl-1.0 | 1,137 |
/*******************************************************************************
* Copyright (C) 2008, 2009 Robin Rosenberg <robin.rosenberg@dewire.com>
*
* 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 org.eclipse.egit.ui.internal.decorators;
import java.io.IOException;
import java.util.Map;
import java.util.WeakHashMap;
import org.eclipse.core.resources.IResource;
import org.eclipse.egit.core.GitProvider;
import org.eclipse.egit.core.project.RepositoryMapping;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIText;
import org.eclipse.egit.ui.internal.CompareUtils;
import org.eclipse.egit.ui.internal.trace.GitTraceLocation;
import org.eclipse.jface.text.Document;
import org.eclipse.jgit.events.ListenerHandle;
import org.eclipse.jgit.events.RefsChangedEvent;
import org.eclipse.jgit.events.RefsChangedListener;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.osgi.util.NLS;
import org.eclipse.team.core.RepositoryProvider;
class GitDocument extends Document implements RefsChangedListener {
private final IResource resource;
private ObjectId lastCommit;
private ObjectId lastTree;
private ObjectId lastBlob;
private ListenerHandle myRefsChangedHandle;
static Map<GitDocument, Repository> doc2repo = new WeakHashMap<GitDocument, Repository>();
static GitDocument create(final IResource resource) throws IOException {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) create: " + resource); //$NON-NLS-1$
GitDocument ret = null;
if (RepositoryProvider.getProvider(resource.getProject()) instanceof GitProvider) {
ret = new GitDocument(resource);
ret.populate();
final Repository repository = ret.getRepository();
if (repository != null)
ret.myRefsChangedHandle = repository.getListenerList()
.addRefsChangedListener(ret);
}
return ret;
}
private GitDocument(IResource resource) {
this.resource = resource;
GitDocument.doc2repo.put(this, getRepository());
}
private void setResolved(final AnyObjectId commit, final AnyObjectId tree,
final AnyObjectId blob, final String value) {
lastCommit = commit != null ? commit.copy() : null;
lastTree = tree != null ? tree.copy() : null;
lastBlob = blob != null ? blob.copy() : null;
set(value);
if (blob != null)
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation
.getTrace()
.trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) resolved " + resource + " to " + lastBlob + " in " + lastCommit + "/" + lastTree); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
else if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) unresolved " + resource); //$NON-NLS-1$
}
void populate() throws IOException {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().traceEntry(
GitTraceLocation.QUICKDIFF.getLocation(), resource);
TreeWalk tw = null;
RevWalk rw = null;
try {
RepositoryMapping mapping = RepositoryMapping.getMapping(resource);
if (mapping == null) {
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
final String gitPath = mapping.getRepoRelativePath(resource);
final Repository repository = mapping.getRepository();
String baseline = GitQuickDiffProvider.baseline.get(repository);
if (baseline == null)
baseline = Constants.HEAD;
ObjectId commitId = repository.resolve(baseline);
if (commitId != null) {
if (commitId.equals(lastCommit)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
return;
}
} else {
String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff,
new Object[] { baseline, resource, repository });
Activator.logError(msg, new Throwable());
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
rw = new RevWalk(repository);
RevCommit baselineCommit;
try {
baselineCommit = rw.parseCommit(commitId);
} catch (IOException err) {
String msg = NLS
.bind(UIText.GitDocument_errorLoadCommit, new Object[] {
commitId, baseline, resource, repository });
Activator.logError(msg, err);
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
RevTree treeId = baselineCommit.getTree();
if (treeId.equals(lastTree)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
return;
}
tw = TreeWalk.forPath(repository, gitPath, treeId);
if (tw == null) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation
.getTrace()
.trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) resource " + resource + " not found in " + treeId + " in " + repository + ", baseline=" + baseline); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
ObjectId id = tw.getObjectId(0);
if (id.equals(ObjectId.zeroId())) {
setResolved(null, null, null, ""); //$NON-NLS-1$
String msg = NLS
.bind(UIText.GitDocument_errorLoadTree, new Object[] {
treeId.getName(), baseline, resource, repository });
Activator.logError(msg, new Throwable());
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
if (!id.equals(lastBlob)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) compareTo: " + baseline); //$NON-NLS-1$
ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB);
byte[] bytes = loader.getBytes();
String charset;
charset = CompareUtils.getResourceEncoding(resource);
// Finally we could consider validating the content with respect
// to the content. We don't do that here.
String s = new String(bytes, charset);
setResolved(commitId, treeId, id, s);
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation
.getTrace()
.trace(GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
}
} finally {
if (tw != null)
tw.release();
if (rw != null)
rw.release();
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().traceExit(
GitTraceLocation.QUICKDIFF.getLocation());
}
}
void dispose() {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) dispose: " + resource); //$NON-NLS-1$
doc2repo.remove(this);
if (myRefsChangedHandle != null) {
myRefsChangedHandle.remove();
myRefsChangedHandle = null;
}
}
public void onRefsChanged(final RefsChangedEvent e) {
try {
populate();
} catch (IOException e1) {
Activator.logError(UIText.GitDocument_errorRefreshQuickdiff, e1);
}
}
private Repository getRepository() {
RepositoryMapping mapping = RepositoryMapping.getMapping(resource);
return (mapping != null) ? mapping.getRepository() : null;
}
/**
* A change occurred to a repository. Update any GitDocument instances
* referring to such repositories.
*
* @param repository
* Repository which changed
* @throws IOException
*/
static void refreshRelevant(final Repository repository) throws IOException {
for (Map.Entry<GitDocument, Repository> i : doc2repo.entrySet()) {
if (i.getValue() == repository) {
i.getKey().populate();
}
}
}
}
| jdcasey/EGit | org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java | Java | epl-1.0 | 8,708 |
/*******************************************************************************
* Copyright (c) 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
*******************************************************************************/
// Generated from C:\SIB\Code\WASX.SIB\dd\SIB\ws\code\sib.mfp.impl\src\com\ibm\ws\sib\mfp\schema\JsHdrSchema.schema: do not edit directly
package com.ibm.ws.sib.mfp.schema;
import com.ibm.ws.sib.mfp.jmf.impl.JSchema;
public final class JsHdrAccess {
public final static JSchema schema = new JsHdrSchema();
public final static int DISCRIMINATOR = 0;
public final static int ARRIVALTIMESTAMP = 1;
public final static int SYSTEMMESSAGESOURCEUUID = 2;
public final static int SYSTEMMESSAGEVALUE = 3;
public final static int SECURITYUSERID = 4;
public final static int SECURITYSENTBYSYSTEM = 5;
public final static int MESSAGETYPE = 6;
public final static int SUBTYPE = 7;
public final static int HDR2 = 8;
public final static int API = 10;
public final static int IS_API_EMPTY = 0;
public final static int IS_API_DATA = 1;
public final static int API_DATA = 9;
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/schema/JsHdrAccess.java | Java | epl-1.0 | 1,422 |
///*******************************************************************************
// * Copyright (c) 2015, 2016 EfficiOS Inc., Alexandre Montplaisir
// *
// * 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 org.lttng.scope.lami.ui.viewers;
//
//import org.eclipse.jface.viewers.TableViewer;
//import org.eclipse.swt.SWT;
//import org.eclipse.swt.widgets.Composite;
//import org.lttng.scope.lami.core.module.LamiChartModel;
//import org.lttng.scope.lami.ui.views.LamiReportViewTabPage;
//
///**
// * Common interface for all Lami viewers.
// *
// * @author Alexandre Montplaisir
// */
//public interface ILamiViewer {
//
// /**
// * Dispose the viewer widget.
// */
// void dispose();
//
// /**
// * Factory method to create a new Table viewer.
// *
// * @param parent
// * The parent composite
// * @param page
// * The {@link LamiReportViewTabPage} parent page
// * @return The new viewer
// */
// static ILamiViewer createLamiTable(Composite parent, LamiReportViewTabPage page) {
// TableViewer tableViewer = new TableViewer(parent, SWT.FULL_SELECTION | SWT.MULTI | SWT.VIRTUAL);
// return new LamiTableViewer(tableViewer, page);
// }
//
// /**
// * Factory method to create a new chart viewer. The chart type is specified
// * by the 'chartModel' parameter.
// *
// * @param parent
// * The parent composite
// * @param page
// * The {@link LamiReportViewTabPage} parent page
// * @param chartModel
// * The information about the chart to display
// * @return The new viewer
// */
// static ILamiViewer createLamiChart(Composite parent, LamiReportViewTabPage page, LamiChartModel chartModel) {
// switch (chartModel.getChartType()) {
// case BAR_CHART:
// return new LamiBarChartViewer(parent, page, chartModel);
// case XY_SCATTER:
// return new LamiScatterViewer(parent, page, chartModel);
// case PIE_CHART:
// default:
// throw new UnsupportedOperationException("Unsupported chart type: " + chartModel.toString()); //$NON-NLS-1$
// }
// }
//}
| alexmonthy/lttng-scope | lttng-scope/src/main/java/org/lttng/scope/lami/viewers/ILamiViewer.java | Java | epl-1.0 | 2,501 |
/*******************************************************************************
* Copyright (c) 2017, 2021 Red Hat Inc and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat Inc - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.kura.simulator.app.deploy;
import org.eclipse.kapua.kura.simulator.payload.Metric;
import org.eclipse.kapua.kura.simulator.payload.Optional;
public class DeploymentUninstallPackageRequest {
@Metric("dp.name")
private String name;
@Metric("dp.version")
private String version;
@Metric("job.id")
private long jobId;
@Optional
@Metric("dp.reboot")
private Boolean reboot;
@Optional
@Metric("dp.reboot.delay")
private Integer rebootDelay;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(final String version) {
this.version = version;
}
public long getJobId() {
return jobId;
}
public void setJobId(final long jobId) {
this.jobId = jobId;
}
public Boolean getReboot() {
return reboot;
}
public void setReboot(final Boolean reboot) {
this.reboot = reboot;
}
public Integer getRebootDelay() {
return rebootDelay;
}
public void setRebootDelay(final Integer rebootDelay) {
this.rebootDelay = rebootDelay;
}
}
| stzilli/kapua | simulator-kura/src/main/java/org/eclipse/kapua/kura/simulator/app/deploy/DeploymentUninstallPackageRequest.java | Java | epl-1.0 | 1,787 |
/**
* Copyright (c) 2020 Bosch.IO GmbH 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
*/
package org.eclipse.hawkbit.ui.common.tagdetails;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.ui.common.data.proxies.ProxyTag;
import org.eclipse.hawkbit.ui.common.tagdetails.TagPanelLayout.TagAssignmentListener;
import org.eclipse.hawkbit.ui.utils.UIComponentIdProvider;
import org.eclipse.hawkbit.ui.utils.UIMessageIdProvider;
import org.eclipse.hawkbit.ui.utils.VaadinMessageSource;
import com.google.common.collect.Sets;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.themes.ValoTheme;
/**
* Combobox that lists all available Tags that can be assigned to a
* {@link Target} or {@link DistributionSet}.
*/
public class TagAssignementComboBox extends HorizontalLayout {
private static final long serialVersionUID = 1L;
private final Collection<ProxyTag> allAssignableTags;
private final transient Set<TagAssignmentListener> listeners = Sets.newConcurrentHashSet();
private final ComboBox<ProxyTag> assignableTagsComboBox;
private final boolean readOnlyMode;
/**
* Constructor.
*
* @param i18n
* the i18n
* @param readOnlyMode
* if true the combobox will be disabled so no assignment can be
* done.
*/
TagAssignementComboBox(final VaadinMessageSource i18n, final boolean readOnlyMode) {
this.readOnlyMode = readOnlyMode;
setWidth("100%");
this.assignableTagsComboBox = getAssignableTagsComboBox(
i18n.getMessage(UIMessageIdProvider.TOOLTIP_SELECT_TAG));
this.allAssignableTags = new HashSet<>();
this.assignableTagsComboBox.setItems(allAssignableTags);
addComponent(assignableTagsComboBox);
}
private ComboBox<ProxyTag> getAssignableTagsComboBox(final String description) {
final ComboBox<ProxyTag> tagsComboBox = new ComboBox<>();
tagsComboBox.setId(UIComponentIdProvider.TAG_SELECTION_ID);
tagsComboBox.setDescription(description);
tagsComboBox.addStyleName(ValoTheme.COMBOBOX_TINY);
tagsComboBox.setEnabled(!readOnlyMode);
tagsComboBox.setWidth("100%");
tagsComboBox.setEmptySelectionAllowed(true);
tagsComboBox.setItemCaptionGenerator(ProxyTag::getName);
tagsComboBox.addValueChangeListener(event -> assignTag(event.getValue()));
return tagsComboBox;
}
private void assignTag(final ProxyTag tagData) {
if (tagData == null || readOnlyMode) {
return;
}
allAssignableTags.remove(tagData);
assignableTagsComboBox.clear();
assignableTagsComboBox.getDataProvider().refreshAll();
notifyListenersTagAssigned(tagData);
}
/**
* Initializes the Combobox with all assignable tags.
*
* @param assignableTags
* assignable tags
*/
void initializeAssignableTags(final List<ProxyTag> assignableTags) {
allAssignableTags.addAll(assignableTags);
assignableTagsComboBox.getDataProvider().refreshAll();
}
/**
* Removes all Tags from Combobox.
*/
void removeAllTags() {
allAssignableTags.clear();
assignableTagsComboBox.clear();
assignableTagsComboBox.getDataProvider().refreshAll();
}
/**
* Adds an assignable Tag to the combobox.
*
* @param tagData
* the data of the Tag
*/
void addAssignableTag(final ProxyTag tagData) {
if (tagData == null) {
return;
}
allAssignableTags.add(tagData);
assignableTagsComboBox.getDataProvider().refreshAll();
}
/**
* Updates an assignable Tag in the combobox.
*
* @param tagData
* the data of the Tag
*/
void updateAssignableTag(final ProxyTag tagData) {
if (tagData == null) {
return;
}
findAssignableTagById(tagData.getId()).ifPresent(tagToUpdate -> updateAssignableTag(tagToUpdate, tagData));
}
private Optional<ProxyTag> findAssignableTagById(final Long id) {
return allAssignableTags.stream().filter(tag -> tag.getId().equals(id)).findAny();
}
private void updateAssignableTag(final ProxyTag oldTag, final ProxyTag newTag) {
allAssignableTags.remove(oldTag);
allAssignableTags.add(newTag);
assignableTagsComboBox.getDataProvider().refreshAll();
}
/**
* Removes an assignable tag from the combobox.
*
* @param tagId
* the tag Id of the Tag that should be removed.
*/
void removeAssignableTag(final Long tagId) {
findAssignableTagById(tagId).ifPresent(this::removeAssignableTag);
}
/**
* Removes an assignable tag from the combobox.
*
* @param tagData
* the {@link ProxyTag} of the Tag that should be removed.
*/
void removeAssignableTag(final ProxyTag tagData) {
allAssignableTags.remove(tagData);
assignableTagsComboBox.getDataProvider().refreshAll();
}
/**
* Registers an {@link TagAssignmentListener} on the combobox.
*
* @param listener
* the listener to register
*/
void addTagAssignmentListener(final TagAssignmentListener listener) {
listeners.add(listener);
}
/**
* Removes a {@link TagAssignmentListener} from the combobox,
*
* @param listener
* the listener that should be removed.
*/
void removeTagAssignmentListener(final TagAssignmentListener listener) {
listeners.remove(listener);
}
private void notifyListenersTagAssigned(final ProxyTag tagData) {
listeners.forEach(listener -> listener.assignTag(tagData));
}
}
| eclipse/hawkbit | hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TagAssignementComboBox.java | Java | epl-1.0 | 6,274 |
/**
* 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.fronius.internal.api;
import com.google.gson.annotations.SerializedName;
/**
* The {@link HeadRequestArguments} is responsible for storing
* the "RequestArguments" node from the {@link Head}
*
* @author Thomas Rokohl - Initial contribution
*/
public class HeadRequestArguments {
@SerializedName("DataCollection")
private String dataCollection;
@SerializedName("DeviceClass")
private String deviceClass;
@SerializedName("DeviceId")
private String deviceId;
@SerializedName("Scope")
private String scope;
public String getDataCollection() {
if (null == dataCollection) {
dataCollection = "";
}
return dataCollection;
}
public void setDataCollection(String dataCollection) {
this.dataCollection = dataCollection;
}
public String getDeviceClass() {
if (null == deviceClass) {
deviceClass = "";
}
return deviceClass;
}
public void setDeviceClass(String deviceClass) {
this.deviceClass = deviceClass;
}
public String getDeviceId() {
if (null == deviceId) {
deviceId = "";
}
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getScope() {
if (null == scope) {
scope = "";
}
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
}
| paulianttila/openhab2 | bundles/org.openhab.binding.fronius/src/main/java/org/openhab/binding/fronius/internal/api/HeadRequestArguments.java | Java | epl-1.0 | 1,893 |
/**
* Copyright (c) 2010-2020 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.vigicrues.internal.dto.vigicrues;
import java.util.List;
import com.google.gson.annotations.SerializedName;
/**
* The {@link TerEntVigiCru} is the Java class used to map the JSON
* response to an vigicrue api endpoint request.
*
* @author Gaël L'hopital - Initial contribution
*/
public class TerEntVigiCru {
public class VicTerEntVigiCru {
@SerializedName("vic:aNMoinsUn")
public List<VicANMoinsUn> vicANMoinsUn;
/*
* Currently unused, maybe interesting in the future
*
* @SerializedName("@id")
* public String id;
*
* @SerializedName("vic:CdEntVigiCru")
* public String vicCdEntVigiCru;
*
* @SerializedName("vic:TypEntVigiCru")
* public String vicTypEntVigiCru;
*
* @SerializedName("vic:LbEntVigiCru")
* public String vicLbEntVigiCru;
*
* @SerializedName("vic:DtHrCreatEntVigiCru")
* public String vicDtHrCreatEntVigiCru;
*
* @SerializedName("vic:DtHrMajEntVigiCru")
* public String vicDtHrMajEntVigiCru;
*
* @SerializedName("vic:StEntVigiCru")
* public String vicStEntVigiCru;
* public int count_aNMoinsUn;
*
* @SerializedName("LinkInfoCru")
* public String linkInfoCru;
*/
}
@SerializedName("vic:TerEntVigiCru")
public VicTerEntVigiCru vicTerEntVigiCru;
}
| openhab/openhab2 | bundles/org.openhab.binding.vigicrues/src/main/java/org/openhab/binding/vigicrues/internal/dto/vigicrues/TerEntVigiCru.java | Java | epl-1.0 | 1,863 |
/*******************************************************************************
* Copyright (c) 2016, 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.security.openidconnect.server.fat.jaxrs.config.OAuth;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import com.ibm.websphere.simplicity.log.Log;
import com.ibm.ws.security.oauth_oidc.fat.commonTest.Constants;
import com.ibm.ws.security.oauth_oidc.fat.commonTest.TestServer;
import com.ibm.ws.security.oauth_oidc.fat.commonTest.TestSettings;
import com.ibm.ws.security.openidconnect.server.fat.jaxrs.config.CommonTests.MapToUserRegistryWithRegMismatch2ServerTests;
import componenttest.custom.junit.runner.FATRunner;
import componenttest.custom.junit.runner.Mode;
import componenttest.custom.junit.runner.Mode.TestMode;
import componenttest.topology.impl.LibertyServerWrapper;
import componenttest.topology.utils.LDAPUtils;
// See test description in
// com.ibm.ws.security.openidconnect.server-1.0_fat.jaxrs.config/fat/src/com/ibm/ws/security/openidconnect/server/fat/jaxrs/config/CommonTests/MapToUserRegistryWithRegMismatch2ServerTests.java
@LibertyServerWrapper
@Mode(TestMode.FULL)
@RunWith(FATRunner.class)
public class OAuthMapToUserRegistryWithRegMismatch2ServerTests extends MapToUserRegistryWithRegMismatch2ServerTests {
private static final Class<?> thisClass = OAuthMapToUserRegistryWithRegMismatch2ServerTests.class;
@BeforeClass
public static void setupBeforeTest() throws Exception {
/*
* These tests have not been configured to run with the local LDAP server.
*/
Assume.assumeTrue(!LDAPUtils.USE_LOCAL_LDAP_SERVER);
msgUtils.printClassName(thisClass.toString());
Log.info(thisClass, "setupBeforeTest", "Prep for test");
// add any additional messages that you want the "start" to wait for
// we should wait for any providers that this test requires
List<String> extraMsgs = new ArrayList<String>();
extraMsgs.add("CWWKS1631I.*");
List<String> extraApps = new ArrayList<String>();
TestServer.addTestApp(null, extraMsgs, Constants.OP_SAMPLE_APP, Constants.OAUTH_OP);
TestServer.addTestApp(extraApps, null, Constants.OP_CLIENT_APP, Constants.OAUTH_OP);
TestServer.addTestApp(extraApps, extraMsgs, Constants.OP_TAI_APP, Constants.OAUTH_OP);
List<String> extraMsgs2 = new ArrayList<String>();
List<String> extraApps2 = new ArrayList<String>();
extraApps2.add(Constants.HELLOWORLD_SERVLET);
testSettings = new TestSettings();
testOPServer = commonSetUp(OPServerName, "server_orig_maptest_ldap.xml", Constants.OAUTH_OP, extraApps, Constants.DO_NOT_USE_DERBY, extraApps);
genericTestServer = commonSetUp(RSServerName, "server_orig_maptest_mismatchregistry.xml", Constants.GENERIC_SERVER, extraApps2, Constants.DO_NOT_USE_DERBY, extraMsgs2, null, Constants.OAUTH_OP);
targetProvider = Constants.OAUTHCONFIGSAMPLE_APP;
flowType = Constants.WEB_CLIENT_FLOW;
goodActions = Constants.BASIC_PROTECTED_RESOURCE_RS_PROTECTED_RESOURCE_ACTIONS;
// set RS protected resource to point to second server.
testSettings.setRSProtectedResource(genericTestServer.getHttpsString() + "/helloworld/rest/helloworld");
// Initial user settings for default user. Individual tests override as needed.
testSettings.setAdminUser("oidcu1");
testSettings.setAdminPswd("security");
testSettings.setGroupIds("RSGroup");
}
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.security.oidc.server_fat.jaxrs.config/fat/src/com/ibm/ws/security/openidconnect/server/fat/jaxrs/config/OAuth/OAuthMapToUserRegistryWithRegMismatch2ServerTests.java | Java | epl-1.0 | 4,019 |
/*******************************************************************************
* Copyright (c) 2016, 2021 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua;
/**
* KapuaIllegalNullArgumentException is thrown when <tt>null</tt> is passed to a method for an argument
* or as a value for field in an object where <tt>null</tt> is not allowed.<br>
* This should always be used instead of <tt>NullPointerException</tt> as the latter is too easily confused with programming bugs.
*
* @since 1.0
*
*/
public class KapuaIllegalNullArgumentException extends KapuaIllegalArgumentException {
private static final long serialVersionUID = -8762712571192128282L;
/**
* Constructor
*
* @param argumentName
*/
public KapuaIllegalNullArgumentException(String argumentName) {
super(KapuaErrorCodes.ILLEGAL_NULL_ARGUMENT, argumentName, null);
}
}
| stzilli/kapua | service/api/src/main/java/org/eclipse/kapua/KapuaIllegalNullArgumentException.java | Java | epl-1.0 | 1,278 |
<?php
/**
* Community Builder (TM) cbconditional Chinese (China) language file Frontend
* @version $Id:$
* @copyright (C) 2004-2014 www.joomlapolis.com / Lightning MultiCom SA - and its licensors, all rights reserved
* @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU/GPL version 2
*/
/**
* WARNING:
* Do not make changes to this file as it will be over-written when you upgrade CB.
* To localize you need to create your own CB language plugin and make changes there.
*/
defined('CBLIB') or die();
return array(
// 66 language strings from file plug_cbconditional/cbconditional.xml
'TAB_CONDITION_PREFERENCES_21582b' => 'Tab condition preferences',
'SELECT_CONDITIONAL_DISPLAY_FOR_THIS_TAB_244679' => 'Select conditional display for this tab.',
'NORMAL_CB_SETTINGS_a0f77c' => 'Normal CB settings',
'TAB_CONDITIONAL_46ba5c' => 'Tab conditional',
'IF_bfa9de' => 'If...',
'SELECT_FIELD_TO_MATCH_VALUE_AGAINST_IN_DETERMINING_c94841' => 'Select field to match value against in determining this tabs display.',
'FIELD_6f16a5' => 'Field',
'VALUE_689202' => 'Value',
'VIEW_ACCESS_LEVELS_c06927' => 'View Access Levels',
'USERGROUPS_6ad0aa' => 'Usergroups',
'FIELDS_a4ca5e' => 'Fields',
'VALUE_f14e9e' => 'Value...',
'INPUT_SUBSTITUTION_SUPPORTED_VALUE_TO_MATCH_AGAINS_4be26b' => 'Input substitution supported value to match against. In addition to user substitutions you can access $_REQUEST, $_GET, and $_POST substitutions as [request_VARIABLE],[post_VARIABLE], and [get_VARIABLE] (e.g. [get_task]).',
'ENABLE_OR_DISABLE_TRANSLATION_OF_LANGUAGE_STRINGS__8263a9' => 'Enable or disable translation of language strings in value.',
'TRANSLATE_VALUE_22a4e1' => 'Translate Value',
'HAS_7bac0f' => 'Has...',
'SELECT_THE_VIEW_ACCESS_LEVELS_TO_MATCH_AGAINST_THE_1c9be8' => 'Select the view access levels to match against the user. The user only needs to have one of the selected view access levels to match.',
'SELECT_THE_USERGROUPS_TO_MATCH_AGAINST_THE_USER_TH_dc4e06' => 'Select the usergroups to match against the user. The user only needs to have one of the selected usergroups to match.',
'IS_9149c7' => 'Is...',
'SELECT_OPERATOR_TO_COMPARE_FIELD_VALUE_AGAINST_INP_43ce0f' => 'Select operator to compare field value against input value.',
'OPERATOR_e1b3ec' => 'Operator',
'EQUAL_TO_c1d440' => 'Equal To',
'NOT_EQUAL_TO_9ac8c0' => 'Not Equal To',
'GREATER_THAN_728845' => 'Greater Than',
'LESS_THAN_45ed1c' => 'Less Than',
'GREATER_THAN_OR_EQUAL_TO_93301c' => 'Greater Than or Equal To',
'LESS_THAN_OR_EQUAL_TO_3181f2' => 'Less Than or Equal To',
'EMPTY_ce2c8a' => 'Empty',
'NOT_EMPTY_f49248' => 'Not Empty',
'DOES_CONTAIN_396955' => 'Does Contain',
'DOES_NOT_CONTAIN_ef739c' => 'Does Not Contain',
'IS_REGEX_44846d' => 'Is REGEX',
'IS_NOT_REGEX_4bddfd' => 'Is Not REGEX',
'TO_4a384a' => 'To...',
'INPUT_SUBSTITUTION_SUPPORTED_VALUE_TO_MATCH_AGAINS_07c86e' => 'Input substitution supported value to match against field value. In addition to user substitutions you can access $_REQUEST, $_GET, and $_POST substitutions as [request_VARIABLE],[post_VARIABLE], and [get_VARIABLE] (e.g. [get_task]).',
'THEN_c1325f' => 'Then...',
'SELECT_HOW_TO_HANDLE_THIS_TABS_DISPLAY_BASED_ON_FI_ff33e1' => 'Select how to handle this tabs display based on field value match.',
'FOR_0ba2b3' => 'For...',
'ENABLE_OR_DISABLE_CONDITIONAL_USAGE_ON_REGISTRATIO_cb622e' => 'Enable or disable conditional usage on registration.',
'REGISTRATION_0f98b7' => 'Registration',
'ENABLE_OR_DISABLE_CONDITIONAL_USAGE_ON_PROFILE_EDI_5bfd08' => 'Enable or disable conditional usage on profile edit.',
'PROFILE_EDIT_24f0eb' => 'Profile Edit',
'ENABLE_OR_DISABLE_CONDITIONAL_USAGE_ON_PROFILE_VIE_b815a1' => 'Enable or disable conditional usage on profile view.',
'PROFILE_VIEW_307f0e' => 'Profile View',
'FIELD_CONDITION_PREFERENCES_757bb6' => 'Field condition preferences',
'SELECT_CONDITIONAL_DISPLAY_FOR_THIS_FIELD_329dc4' => 'Select conditional display for this field.',
'FIELD_CONDITIONAL_OTHERS_453f6f' => 'Field conditional others',
'FIELD_CONDITIONAL_SELF_281138' => 'Field conditional self',
'SELECT_FIELD_TO_MATCH_VALUE_AGAINST_IN_DETERMINING_7d601b' => 'Select field to match value against in determining this fields display.',
'SELECT_FIELD_24af14' => '--- Select Field ---',
'SELECT_FIELDS_TO_SHOW_IF_VALUE_IS_MATCHED_f63533' => 'Select fields to show if value is matched.',
'SELECT_FIELDS_5be58c' => '--- Select Fields ---',
'SELECT_FIELDS_TO_HIDE_IF_VALUE_IS_MATCHED_e0a204' => 'Select fields to hide if value is matched.',
'FIELD_OPTIONS_9b3c51' => 'Field Options',
'SELECT_FIELD_OPTIONS_TO_SHOW_IF_VALUE_IS_MATCHED_459bc1' => 'Select field options to show if value is matched.',
'SELECT_FIELD_OPTIONS_837903' => '--- Select Field Options ---',
'SELECT_FIELD_OPTIONS_TO_HIDE_IF_VALUE_IS_MATCHED_01f5ab' => 'Select field options to hide if value is matched.',
'SELECT_HOW_TO_HANDLE_THIS_FIELDS_DISPLAY_BASED_ON__32d89f' => 'Select how to handle this fields display based on field value match.',
'ENABLE_OR_DISABLE_CONDITIONAL_USAGE_ON_USERLISTS_S_15983a' => 'Enable or disable conditional usage on userlists searching.',
'USERLISTS_SEARCH_fad6c1' => 'Userlists Search',
'ENABLE_OR_DISABLE_CONDITIONAL_USAGE_ON_USERLISTS_V_a02f8c' => 'Enable or disable conditional usage on userlists view.',
'USERLISTS_VIEW_72449c' => 'Userlists View',
'ENABLE_OR_DISABLE_USAGE_OF_CONDITIONS_IN_BACKEND_0b15b5' => 'Enable or disable usage of conditions in Backend.',
'BACKEND_2e427c' => 'Backend',
'ENABLE_OR_DISABLE_RESET_OF_FIELD_VALUES_TO_BLANK_I_278676' => 'Enable or disable reset of field values to blank if condition is not met.',
'RESET_526d68' => 'Reset',
);
| bobozhangshao/HeartCare | components/com_comprofiler/plugin/language/zh-cn/cbplugin/cbconditional-language.php | PHP | gpl-2.0 | 5,636 |
/*
* Copyright (C) 2014 Michael Joyce <ubermichael@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.
*
* 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 ca.nines.ise.util;
import java.util.ArrayDeque;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.UserDataHandler;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.LocatorImpl;
/**
* Annotates a DOM with location data during the construction process.
* <p>
* http://javacoalface.blogspot.ca/2011/04/line-and-column-numbers-in-xml-dom.html
* <p>
* @author Michael Joyce <ubermichael@gmail.com>
*/
public class LocationAnnotator extends XMLFilterImpl {
/**
* Locator returned by the construction process.
*/
private Locator locator;
/**
* The systemID of the XML.
*/
private final String source;
/**
* Stack to hold the locators which haven't been completed yet.
*/
private final ArrayDeque<Locator> locatorStack = new ArrayDeque<>();
/**
* Stack holding incomplete elements.
*/
private final ArrayDeque<Element> elementStack = new ArrayDeque<>();
/**
* A data handler to add the location data.
*/
private final UserDataHandler dataHandler = new LocationDataHandler();
/**
* Construct a location annotator for an XMLReader and Document. The systemID
* is determined automatically.
*
* @param xmlReader the reader to use the annotator
* @param dom the DOM to annotate
*/
LocationAnnotator(XMLReader xmlReader, Document dom) {
super(xmlReader);
source = "";
EventListener modListener = new EventListener() {
@Override
public void handleEvent(Event e) {
EventTarget target = e.getTarget();
elementStack.push((Element) target);
}
};
((EventTarget) dom).addEventListener("DOMNodeInserted", modListener, true);
}
/**
* Construct a location annotator for an XMLReader and Document. The systemID
* is NOT determined automatically.
*
* @param source the systemID of the XML
* @param xmlReader the reader to use the annotator
* @param dom the DOM to annotate
*/
LocationAnnotator(String source, XMLReader xmlReader, Document dom) {
super(xmlReader);
this.source = source;
EventListener modListener = new EventListener() {
@Override
public void handleEvent(Event e) {
EventTarget target = e.getTarget();
elementStack.push((Element) target);
}
};
((EventTarget) dom).addEventListener("DOMNodeInserted", modListener, true);
}
/**
* Add the locator to the document during the parse.
*
* @param locator the locator to add
*/
@Override
public void setDocumentLocator(Locator locator) {
super.setDocumentLocator(locator);
this.locator = locator;
}
/**
* Handle the start tag of an element by adding locator data.
*
* @param uri The systemID of the XML.
* @param localName the name of the tag. unused.
* @param qName the FQDN of the tag. unused.
* @param atts the attributes of the tag. unused.
* @throws SAXException
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
super.startElement(uri, localName, qName, atts);
locatorStack.push(new LocatorImpl(locator));
}
/**
* Handle the end tag of an element by adding locator data.
*
* @param uri The systemID of the XML.
* @param localName the name of the tag. unused.
* @param qName the FQDN of the tag. unused.
* @throws SAXException
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if (locatorStack.size() > 0) {
Locator startLocator = locatorStack.pop();
LocationData location = new LocationData(
(startLocator.getSystemId() == null ? source : startLocator.getSystemId()),
startLocator.getLineNumber(),
startLocator.getColumnNumber(),
locator.getLineNumber(),
locator.getColumnNumber()
);
Element e = elementStack.pop();
e.setUserData(
LocationData.LOCATION_DATA_KEY, location,
dataHandler);
}
}
/**
* UserDataHandler to insert location data into the XML DOM.
*/
private class LocationDataHandler implements UserDataHandler {
/**
* Handle an even during a parse. An even is a start/end/empty tag or some
* data.
*
* @param operation unused.
* @param key unused
* @param data unused
* @param src the source of the data
* @param dst the destination of the data
*/
@Override
public void handle(short operation, String key, Object data, Node src, Node dst) {
if (src != null && dst != null) {
LocationData locatonData = (LocationData) src.getUserData(LocationData.LOCATION_DATA_KEY);
if (locatonData != null) {
dst.setUserData(LocationData.LOCATION_DATA_KEY, locatonData, dataHandler);
}
}
}
}
}
| emmental/isetools | src/main/java/ca/nines/ise/util/LocationAnnotator.java | Java | gpl-2.0 | 5,912 |
package net.indrix.arara.servlets.pagination;
import java.sql.SQLException;
import java.util.List;
import net.indrix.arara.dao.DatabaseDownException;
public class SoundBySpeciePaginationController extends
SoundPaginationController {
/**
* Creates a new PaginationController object, with the given number of elements per page, and
* with the flag identification
*
* @param soundsPerPage The amount of sounds per page
* @param identification The flag for identification
*/
public SoundBySpeciePaginationController(int soundsPerPage, boolean identification) {
super(soundsPerPage, identification);
}
@Override
protected List retrieveAllData() throws DatabaseDownException, SQLException {
logger.debug("SoundBySpeciePaginationController.retrieveAllData : retrieving all sounds...");
List listOfSounds = null;
if (id != -1){
listOfSounds = model.retrieveIDsForSpecie(getId());
} else {
listOfSounds = model.retrieveIDsForSpecieName(getText());
}
logger.debug("SoundBySpeciePaginationController.retrieveAllData : " + listOfSounds.size() + " sounds retrieved...");
return listOfSounds;
}
}
| BackupTheBerlios/arara-svn | core/trunk/src/main/java/net/indrix/arara/servlets/pagination/SoundBySpeciePaginationController.java | Java | gpl-2.0 | 1,289 |
package dataservice.businessdataservice;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
import po.BusinessPO;
import po.DistributeReceiptPO;
import po.DriverPO;
import po.EnVehicleReceiptPO;
import po.GatheringReceiptPO;
import po.OrderAcceptReceiptPO;
import po.OrganizationPO;
import po.VehiclePO;
/**
* BusinessData
*/
public interface BusinessDataService extends Remote {
// 根据营业厅ID(找到文件)和营业厅业务员ID(查找文件内容),ID为null就返回第一个
public BusinessPO getBusinessInfo(String organizationID, String ID) throws RemoteException;
// 根据营业厅ID和车辆ID查询车辆PO
public VehiclePO getVehicleInfo(String organizationID, String vehicleID) throws RemoteException;
// 营业厅每日一个,每日早上8点发货一次
public boolean addReceipt(String organizationID, OrderAcceptReceiptPO po) throws RemoteException;
// 获得某营业厅的全部车辆信息
public ArrayList<VehiclePO> getVehicleInfos(String organizationID) throws RemoteException;
// 添加装车单到今日装车单文件中
public boolean addEnVehicleReceipt(String organizationID, ArrayList<EnVehicleReceiptPO> pos) throws RemoteException;
// 增加一个车辆信息VehiclePO到VehiclePOList中
public boolean addVehicle(String organizationID, VehiclePO po) throws RemoteException;
// 删除VehiclePOList中的一个车辆信息VehiclePO
public boolean deleteVehicle(String organizationID, VehiclePO po) throws RemoteException;
// 修改VehiclePOList中的一个车辆信息VehiclePO
public boolean modifyVehicle(String organizationID, VehiclePO po) throws RemoteException;
// 返回本营业厅司机信息列表
public ArrayList<DriverPO> getDriverInfos(String organizationID) throws RemoteException;
// 增加一个GatheringReceipt到本营业厅今日的文件中,一天也就一个
public boolean addGatheringReceipt(String organizationID, GatheringReceiptPO grp) throws RemoteException;
// 获得今日本营业厅OrderAcceptReceiptPO的个数
public int getNumOfOrderAcceptReceipt(String organizationID) throws RemoteException;
// 返回规定日期的所有GatheringReceipt,time格式 2015-11-23
public ArrayList<GatheringReceiptPO> getGatheringReceipt(String time) throws RemoteException;
public ArrayList<GatheringReceiptPO> getGatheringReceiptByHallID(String organization) throws RemoteException;
public ArrayList<GatheringReceiptPO> getGatheringReceiptByBoth(String organization, String time)
throws RemoteException;
// 增加一个DistributeOrder到本营业厅今日的文件中,一天也就一个
public boolean addDistributeReceipt(String organizationID, DistributeReceiptPO po) throws RemoteException;
// 查照死机
public DriverPO getDriverInfo(String organizationID, String ID) throws RemoteException;
// 增加一个司机到本营业厅
public boolean addDriver(String organizationID, DriverPO po) throws RemoteException;
// 删除一个司机到本营业厅
public boolean deleteDriver(String organizationID, DriverPO po) throws RemoteException;
// 修改本营业厅该司机信息
public boolean modifyDriver(String organizationID, DriverPO po) throws RemoteException;
/**
* Lizi 收款单
*/
public ArrayList<GatheringReceiptPO> getSubmittedGatheringReceiptInfo() throws RemoteException;
/**
* Lizi 派件单
*/
public ArrayList<DistributeReceiptPO> getSubmittedDistributeReceiptInfo() throws RemoteException;
/**
* Lizi 装车
*/
public ArrayList<EnVehicleReceiptPO> getSubmittedEnVehicleReceiptInfo() throws RemoteException;
/**
* Lizi 到达单
*/
public ArrayList<OrderAcceptReceiptPO> getSubmittedOrderAcceptReceiptInfo() throws RemoteException;
public void saveDistributeReceiptInfo(DistributeReceiptPO po) throws RemoteException;
public void saveOrderAcceptReceiptInfo(OrderAcceptReceiptPO po) throws RemoteException;
public void saveEnVehicleReceiptInfo(EnVehicleReceiptPO po) throws RemoteException;
public void saveGatheringReceiptInfo(GatheringReceiptPO po) throws RemoteException;
//
public boolean addDriverTime(String organizationID, String driverID) throws RemoteException;
public ArrayList<OrganizationPO> getOrganizationInfos() throws RemoteException;
public int getNumOfVehicles(String organizationID) throws RemoteException;
public int getNumOfDrivers(String organizationID) throws RemoteException;
public int getNumOfEnVechileReceipt(String organizationID) throws RemoteException;
public int getNumOfOrderReceipt(String organizationID) throws RemoteException;
public int getNumOfOrderDistributeReceipt(String organizationID) throws RemoteException;
//
// /**
// * 返回待转运的订单的列表
// */
// public ArrayList<OrderPO> getTransferOrders() throws RemoteException;
//
// /**
// * 返回待派送的订单的列表
// */
// public ArrayList<VehiclePO> getFreeVehicles() throws RemoteException;
//
// /**
// * 生成装车单
// */
// public boolean addEnVehicleReceiptPO(EnVehicleReceiptPO po) throws
// RemoteException;
//
// /**
// * 获取收款汇总单
// */
// public ArrayList<GatheringReceiptPO> getGatheringReceiptPOs() throws
// RemoteException;
//
// /**
// * 增加收货单
// */
// public boolean addReceipt(OrderAcceptReceiptPO po) throws
// RemoteException;
//
// /**
// * 增加收款汇总单
// */
//
// public boolean addGatheringReceipt(GatheringReceiptPO po);
}
| Disguiser-w/SE2 | ELS_SERVICE/src/main/java/dataservice/businessdataservice/BusinessDataService.java | Java | gpl-2.0 | 5,469 |
FusionCharts.ready(function () {
var gradientCheckBox = document.getElementById('useGradient');
//Set event listener for radio button
if (gradientCheckBox.addEventListener) {
gradientCheckBox.addEventListener("click", changeGradient);
}
function changeGradient(evt, obj) {
//Set gradient fill for chart using usePlotGradientColor attribute
(gradientCheckBox.checked) ?revenueChart.setChartAttribute('usePlotGradientColor', 1) : revenueChart.setChartAttribute('usePlotGradientColor', 0);
};
var revenueChart = new FusionCharts({
type: 'column2d',
renderAt: 'chart-container',
width: '400',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Quarterly Revenue",
"subCaption": "Last year",
"xAxisName": "Quarter",
"yAxisName": "Amount (In USD)",
"theme": "fint",
"numberPrefix": "$",
//Removing default gradient fill from columns
"usePlotGradientColor": "1"
},
"data": [{
"label": "Q1",
"value": "1950000",
"color": "#008ee4"
}, {
"label": "Q2",
"value": "1450000",
"color": "#9b59b6"
}, {
"label": "Q3",
"value": "1730000",
"color": "#6baa01"
}, {
"label": "Q4",
"value": "2120000",
"color": "#e44a00"
}]
}
}).render();
}); | sguha-work/fiddletest | backup/fiddles/Chart/Data_plots/Configuring_gradient_fill_for_columns_in_column_charts/demo.js | JavaScript | gpl-2.0 | 1,726 |
/*
Copyright (C) 2009 - 2012 by Bartosz Waresiak <dragonking@o2.pl>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
#ifndef FORMULA_AI_FUNCTION_TABLE_HPP_INCLUDED
#define FORMULA_AI_FUNCTION_TABLE_HPP_INCLUDED
#include "formula_function.hpp"
#include <set>
namespace ai {
class formula_ai;
}
namespace game_logic {
class ai_function_symbol_table : public function_symbol_table {
public:
explicit ai_function_symbol_table(ai::formula_ai& ai) :
ai_(ai),
move_functions()
{}
expression_ptr create_function(const std::string& fn,
const std::vector<expression_ptr>& args) const;
private:
ai::formula_ai& ai_;
std::set<std::string> move_functions;
};
}
#endif /* FORMULA_AI_FUNCTION_TABLE_HPP_INCLUDED */
| asimonov-im/wesnoth | src/ai/formula/function_table.hpp | C++ | gpl-2.0 | 1,169 |
/*!
* address.js - Description
* Copyright © 2012 by Ingenesis Limited. All rights reserved.
* Licensed under the GPLv3 {@see license.txt}
*/
(function($) {
jQuery.fn.upstate = function () {
if ( typeof regions === 'undefined' ) return;
$(this).change(function (e,init) {
var $this = $(this),
prefix = $this.attr('id').split('-')[0],
country = $this.val(),
state = $this.parents().find('#' + prefix + '-state'),
menu = $this.parents().find('#' + prefix + '-state-menu'),
options = '<option value=""></option>';
if (menu.length == 0) return true;
if (menu.hasClass('hidden')) menu.removeClass('hidden').hide();
if (regions[country] || (init && menu.find('option').length > 1)) {
state.setDisabled(true).addClass('_important').hide();
if (regions[country]) {
$.each(regions[country], function (value,label) {
options += '<option value="'+value+'">'+label+'</option>';
});
if (!init) menu.empty().append(options).setDisabled(false).show().focus();
if (menu.hasClass('auto-required')) menu.addClass('required');
} else {
if (menu.hasClass('auto-required')) menu.removeClass('required');
}
menu.setDisabled(false).show();
$('label[for='+state.attr('id')+']').attr('for',menu.attr('id'));
} else {
menu.empty().setDisabled(true).hide();
state.setDisabled(false).show().removeClass('_important');
$('label[for='+menu.attr('id')+']').attr('for',state.attr('id'));
if (!init) state.val('').focus();
}
}).trigger('change',[true]);
return $(this);
};
})(jQuery);
jQuery(document).ready(function($) {
var sameaddr = $('.sameaddress'),
shipFields = $('#shipping-address-fields'),
billFields = $('#billing-address-fields'),
keepLastValue = function () { // Save the current value of the field
$(this).attr('data-last', $(this).val());
};
// Handle changes to the firstname and lastname fields
$('#firstname,#lastname').each(keepLastValue).change(function () {
var namefield = $(this); // Reference to the modified field
lastfirstname = $('#firstname').attr('data-last'),
lastlastname = $('#lastname').attr('data-last'),
firstlast = ( ( $('#firstname').val() ).trim() + " " + ( $('#lastname').val() ).trim() ).trim();
namefield.val( (namefield.val()).trim() );
// Update the billing name and shipping name
$('#billing-name,#shipping-name').each(function() {
var value = $(this).val();
if ( value.trim().length == 0 ) {
// Empty billing or shipping name
$('#billing-name,#shipping-name').val(firstlast);
} else if ( '' != value && ( $('#firstname').val() == value || $('#lastname').val() == value ) ) {
// Only one name entered (so far), add the other name
$(this).val(firstlast);
} else if ( 'firstname' == namefield.attr('id') && value.indexOf(lastlastname) != -1 ) {
// firstname changed & last lastname matched
$(this).val( value.replace(lastfirstname, namefield.val()).trim() );
} else if ( 'lastname' == namefield.attr('id') && value.indexOf(lastfirstname) != -1 ) {
// lastname changed & last firstname matched
$(this).val( value.replace(lastlastname, namefield.val()).trim() );
}
});
}).change(keepLastValue);
// Update state/province
$('#billing-country,#shipping-country').upstate();
// Toggle same shipping address
sameaddr.change(function (e,init) {
var refocus = false,
bc = $('#billing-country'),
sc = $('#shipping-country'),
prime = 'billing' == sameaddr.val() ? shipFields : billFields,
alt = 'shipping' == sameaddr.val() ? shipFields : billFields;
if (sameaddr.is(':checked')) {
prime.removeClass('half');
alt.hide().find('.required').setDisabled(true);
} else {
prime.addClass('half');
alt.show().find('.disabled:not(._important)').setDisabled(false);
if (!init) refocus = true;
}
if (bc.is(':visible')) bc.trigger('change.localemenu',[init]);
if (sc.is(':visible')) sc.trigger('change.localemenu',[init]);
if (refocus) alt.find('input:first').focus();
}).trigger('change',[true])
.click(function () { $(this).change(); }); // For IE compatibility
}); | sharpmachine/whiteantelopestudio.com | wp-content/plugins/shopp/core/ui/behaviors/address.js | JavaScript | gpl-2.0 | 4,137 |
package org.xmlvm.ios;
import java.util.*;
import org.xmlvm.XMLVMSkeletonOnly;
@XMLVMSkeletonOnly
public class CFGregorianDate {
/*
* Variables
*/
public int year;
public byte month;
public byte day;
public byte hour;
public byte minute;
public double second;
/*
* Constructors
*/
/** Default constructor */
CFGregorianDate() {}
/*
* Instance methods
*/
/**
* Boolean CFGregorianDateIsValid(CFGregorianDate gdate, CFOptionFlags unitFlags);
*/
public byte isValid(long unitFlags){
throw new RuntimeException("Stub");
}
/**
* CFAbsoluteTime CFGregorianDateGetAbsoluteTime(CFGregorianDate gdate, CFTimeZoneRef tz);
*/
public double getAbsoluteTime(NSTimeZone tz){
throw new RuntimeException("Stub");
}
}
| skyHALud/codenameone | Ports/iOSPort/xmlvm/src/ios/org/xmlvm/ios/CFGregorianDate.java | Java | gpl-2.0 | 755 |
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2012 Bolton Software Ltd.
* Copyright (C) 2012 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file COPYING that should have accompanied this file.
*
* This package 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 "IpcClient.h"
#include <QTcpSocket>
#include <QHostAddress>
#include <iostream>
#include <QTimer>
#include "IpcReader.h"
#include "Ipc.h"
IpcClient::IpcClient() :
m_ReaderStarted(false),
m_Enabled(false)
{
m_Socket = new QTcpSocket(this);
connect(m_Socket, SIGNAL(connected()), this, SLOT(connected()));
connect(m_Socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError)));
m_Reader = new IpcReader(m_Socket);
connect(m_Reader, SIGNAL(readLogLine(const QString&)), this, SLOT(handleReadLogLine(const QString&)));
}
IpcClient::~IpcClient()
{
}
void IpcClient::connected()
{
char typeBuf[1];
typeBuf[0] = kIpcClientGui;
sendHello();
infoMessage("connection established");
}
void IpcClient::connectToHost()
{
m_Enabled = true;
infoMessage("connecting to service...");
m_Socket->connectToHost(QHostAddress(QHostAddress::LocalHost), IPC_PORT);
if (!m_ReaderStarted) {
m_Reader->start();
m_ReaderStarted = true;
}
}
void IpcClient::disconnectFromHost()
{
infoMessage("service disconnect");
m_Reader->stop();
m_Socket->close();
}
void IpcClient::error(QAbstractSocket::SocketError error)
{
QString text;
switch (error) {
case 0: text = "connection refused"; break;
case 1: text = "remote host closed"; break;
default: text = QString("code=%1").arg(error); break;
}
errorMessage(QString("ipc connection error, %1").arg(text));
QTimer::singleShot(1000, this, SLOT(retryConnect()));
}
void IpcClient::retryConnect()
{
if (m_Enabled) {
connectToHost();
}
}
void IpcClient::sendHello()
{
QDataStream stream(m_Socket);
stream.writeRawData(kIpcMsgHello, 4);
char typeBuf[1];
typeBuf[0] = kIpcClientGui;
stream.writeRawData(typeBuf, 1);
}
void IpcClient::sendCommand(const QString& command, bool elevate)
{
QDataStream stream(m_Socket);
stream.writeRawData(kIpcMsgCommand, 4);
std::string stdStringCommand = command.toStdString();
const char* charCommand = stdStringCommand.c_str();
int length = strlen(charCommand);
char lenBuf[4];
intToBytes(length, lenBuf, 4);
stream.writeRawData(lenBuf, 4);
stream.writeRawData(charCommand, length);
char elevateBuf[1];
elevateBuf[0] = elevate ? 1 : 0;
stream.writeRawData(elevateBuf, 1);
}
void IpcClient::handleReadLogLine(const QString& text)
{
readLogLine(text);
}
// TODO: qt must have a built in way of converting int to bytes.
void IpcClient::intToBytes(int value, char *buffer, int size)
{
if (size == 1) {
buffer[0] = value & 0xff;
}
else if (size == 2) {
buffer[0] = (value >> 8) & 0xff;
buffer[1] = value & 0xff;
}
else if (size == 4) {
buffer[0] = (value >> 24) & 0xff;
buffer[1] = (value >> 16) & 0xff;
buffer[2] = (value >> 8) & 0xff;
buffer[3] = value & 0xff;
}
else {
// TODO: other sizes, if needed.
}
}
| thecubic/synergy-foss | src/gui/src/IpcClient.cpp | C++ | gpl-2.0 | 3,524 |
#if UNITY_4_3 || UNITY_4_3_0 || UNITY_4_3_1
#define UNITY_4_3
#elif UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
#define UNITY_4
#elif UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
#define UNITY_3
#endif
using UnityEngine;
using UnityEditor;
using System.Collections;
using ProBuilder2.Common;
using ProBuilder2.MeshOperations;
using ProBuilder2.EditorEnum;
namespace ProBuilder2.Actions
{
public class ExtrudeFace : Editor
{
const int EXTRUDE = 100;
[MenuItem("Tools/" + pb_Constant.PRODUCT_NAME + "/Geometry/Extrude %#e", false, EXTRUDE + 1)]
public static void ExtrudeNoTranslation()
{
PerformExtrusion(0f);
}
[MenuItem("Tools/" + pb_Constant.PRODUCT_NAME + "/Geometry/Extrude with Translation %e", false, EXTRUDE)]
public static void Extrude()
{
PerformExtrusion(.25f);
}
private static void PerformExtrusion(float dist)
{
SelectMode mode = pb_Editor.instance.GetSelectionMode();
pb_Object[] pbs = pbUtil.GetComponents<pb_Object>(Selection.transforms);
#if !UNITY_4_3
Undo.RegisterUndo(pbUtil.GetComponents<pb_Object>(Selection.transforms), "extrude selected.");
#else
Undo.RecordObjects(pbUtil.GetComponents<pb_Object>(Selection.transforms), "extrude selected.");
#endif
int extrudedFaceCount = 0;
foreach(pb_Object pb in pbs)
{
switch(mode)
{
case SelectMode.Face:
if(pb.selected_faces.Length < 1)
continue;
extrudedFaceCount += pb.selected_faces.Length;
pb.Extrude(pb.selected_faces, dist);
break;
case SelectMode.Edge:
if(pb.selected_edges.Length < 1)
continue;
pb_Edge[] newEdges = pb.Extrude(pb.selected_edges, dist, pb_Preferences_Internal.GetBool(pb_Constant.pbPerimeterEdgeExtrusionOnly));
if(newEdges != null)
{
extrudedFaceCount += pb.selected_edges.Length;
pb.selected_edges = newEdges;
pb.selected_triangles = pb.SharedTrianglesWithTriangles( pb.selected_edges.ToIntArray() );
}
break;
}
pb.GenerateUV2(true);
}
if(extrudedFaceCount > 0)
{
string val = "";
if(mode == SelectMode.Edge)
val = (extrudedFaceCount > 1 ? extrudedFaceCount + " Edges" : "Edge");
else
val = (extrudedFaceCount > 1 ? extrudedFaceCount + " Faces" : "Face");
pb_Editor_Utility.ShowNotification("Extrude " + val, "Extrudes the selected faces / edges.");
}
if(pb_Editor.instance)
pb_Editor.instance.UpdateSelection();
}
}
}
| Jack423/TankGame | Assets/6by7/ProBuilder/Editor/Actions/ExtrudeFace.cs | C# | gpl-2.0 | 2,531 |
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2017 Paco Avila & Josep Llort
* <p>
* No bytes were intentionally harmed during the development of this application.
* <p>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.bean;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* @author jllort
*
*/
public class GWTUserConfig implements IsSerializable {
private String user = "";
private String homePath = "";
private String homeType = "";
private String homeNode = "";
/**
* GWTUserConfig
*/
public GWTUserConfig() {
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getHomePath() {
return homePath;
}
public void setHomePath(String homePath) {
this.homePath = homePath;
}
public String getHomeType() {
return homeType;
}
public void setHomeType(String homeType) {
this.homeType = homeType;
}
public String getHomeNode() {
return homeNode;
}
public void setHomeNode(String homeNode) {
this.homeNode = homeNode;
}
}
| Beau-M/document-management-system | src/main/java/com/openkm/frontend/client/bean/GWTUserConfig.java | Java | gpl-2.0 | 1,807 |
/* $Id: PDMDevHlp.cpp $ */
/** @file
* PDM - Pluggable Device and Driver Manager, Device Helpers.
*/
/*
* Copyright (C) 2006-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_PDM_DEVICE
#include "PDMInternal.h"
#include <VBox/vmm/pdm.h>
#include <VBox/vmm/mm.h>
#include <VBox/vmm/hm.h>
#include <VBox/vmm/pgm.h>
#include <VBox/vmm/iom.h>
#ifdef VBOX_WITH_REM
# include <VBox/vmm/rem.h>
#endif
#include <VBox/vmm/dbgf.h>
#include <VBox/vmm/vmapi.h>
#include <VBox/vmm/vm.h>
#include <VBox/vmm/uvm.h>
#include <VBox/vmm/vmm.h>
#include <VBox/version.h>
#include <VBox/log.h>
#include <VBox/err.h>
#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/ctype.h>
#include <iprt/string.h>
#include <iprt/thread.h>
#include "dtrace/VBoxVMM.h"
#include "PDMInline.h"
/*******************************************************************************
* Defined Constants And Macros *
*******************************************************************************/
/** @def PDM_DEVHLP_DEADLOCK_DETECTION
* Define this to enable the deadlock detection when accessing physical memory.
*/
#if /*defined(DEBUG_bird) ||*/ defined(DOXYGEN_RUNNING)
# define PDM_DEVHLP_DEADLOCK_DETECTION /**< @todo enable DevHlp deadlock detection! */
#endif
/**
* Wrapper around PDMR3LdrGetSymbolRCLazy.
*/
DECLINLINE(int) pdmR3DevGetSymbolRCLazy(PPDMDEVINS pDevIns, const char *pszSymbol, PRTRCPTR ppvValue)
{
PVM pVM = pDevIns->Internal.s.pVMR3;
if (HMIsEnabled(pVM))
{
*ppvValue = NIL_RTRCPTR;
return VINF_SUCCESS;
}
return PDMR3LdrGetSymbolRCLazy(pVM,
pDevIns->Internal.s.pDevR3->pReg->szRCMod,
pDevIns->Internal.s.pDevR3->pszRCSearchPath,
pszSymbol, ppvValue);
}
/**
* Wrapper around PDMR3LdrGetSymbolR0Lazy.
*/
DECLINLINE(int) pdmR3DevGetSymbolR0Lazy(PPDMDEVINS pDevIns, const char *pszSymbol, PRTR0PTR ppvValue)
{
return PDMR3LdrGetSymbolR0Lazy(pDevIns->Internal.s.pVMR3,
pDevIns->Internal.s.pDevR3->pReg->szR0Mod,
pDevIns->Internal.s.pDevR3->pszR0SearchPath,
pszSymbol, ppvValue);
}
/** @name R3 DevHlp
* @{
*/
/** @interface_method_impl{PDMDEVHLPR3,pfnIOPortRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_IOPortRegister(PPDMDEVINS pDevIns, RTIOPORT Port, RTIOPORT cPorts, RTHCPTR pvUser, PFNIOMIOPORTOUT pfnOut, PFNIOMIOPORTIN pfnIn,
PFNIOMIOPORTOUTSTRING pfnOutStr, PFNIOMIOPORTINSTRING pfnInStr, const char *pszDesc)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_IOPortRegister: caller='%s'/%d: Port=%#x cPorts=%#x pvUser=%p pfnOut=%p pfnIn=%p pfnOutStr=%p pfnInStr=%p p32_tszDesc=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance,
Port, cPorts, pvUser, pfnOut, pfnIn, pfnOutStr, pfnInStr, pszDesc, pszDesc));
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
#if 0 /** @todo needs a real string cache for this */
if (pDevIns->iInstance > 0)
{
char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance);
if (pszDesc2)
pszDesc = pszDesc2;
}
#endif
int rc = IOMR3IOPortRegisterR3(pDevIns->Internal.s.pVMR3, pDevIns, Port, cPorts, pvUser,
pfnOut, pfnIn, pfnOutStr, pfnInStr, pszDesc);
LogFlow(("pdmR3DevHlp_IOPortRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnIOPortRegisterRC} */
static DECLCALLBACK(int) pdmR3DevHlp_IOPortRegisterRC(PPDMDEVINS pDevIns, RTIOPORT Port, RTIOPORT cPorts, RTRCPTR pvUser,
const char *pszOut, const char *pszIn,
const char *pszOutStr, const char *pszInStr, const char *pszDesc)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_IOPortRegisterRC: caller='%s'/%d: Port=%#x cPorts=%#x pvUser=%p pszOut=%p:{%s} pszIn=%p:{%s} pszOutStr=%p:{%s} pszInStr=%p:{%s} pszDesc=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance,
Port, cPorts, pvUser, pszOut, pszOut, pszIn, pszIn, pszOutStr, pszOutStr, pszInStr, pszInStr, pszDesc, pszDesc));
/*
* Resolve the functions (one of the can be NULL).
*/
int rc = VINF_SUCCESS;
if ( pDevIns->pReg->szRCMod[0]
&& (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC)
&& !HMIsEnabled(pVM))
{
RTRCPTR RCPtrIn = NIL_RTRCPTR;
if (pszIn)
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pszIn, &RCPtrIn);
AssertMsgRC(rc, ("Failed to resolve %s.%s (pszIn)\n", pDevIns->pReg->szRCMod, pszIn));
}
RTRCPTR RCPtrOut = NIL_RTRCPTR;
if (pszOut && RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pszOut, &RCPtrOut);
AssertMsgRC(rc, ("Failed to resolve %s.%s (pszOut)\n", pDevIns->pReg->szRCMod, pszOut));
}
RTRCPTR RCPtrInStr = NIL_RTRCPTR;
if (pszInStr && RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pszInStr, &RCPtrInStr);
AssertMsgRC(rc, ("Failed to resolve %s.%s (pszInStr)\n", pDevIns->pReg->szRCMod, pszInStr));
}
RTRCPTR RCPtrOutStr = NIL_RTRCPTR;
if (pszOutStr && RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pszOutStr, &RCPtrOutStr);
AssertMsgRC(rc, ("Failed to resolve %s.%s (pszOutStr)\n", pDevIns->pReg->szRCMod, pszOutStr));
}
if (RT_SUCCESS(rc))
{
#if 0 /** @todo needs a real string cache for this */
if (pDevIns->iInstance > 0)
{
char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance);
if (pszDesc2)
pszDesc = pszDesc2;
}
#endif
rc = IOMR3IOPortRegisterRC(pVM, pDevIns, Port, cPorts, pvUser, RCPtrOut, RCPtrIn, RCPtrOutStr, RCPtrInStr, pszDesc);
}
}
else if (!HMIsEnabled(pVM))
{
AssertMsgFailed(("No RC module for this driver!\n"));
rc = VERR_INVALID_PARAMETER;
}
LogFlow(("pdmR3DevHlp_IOPortRegisterRC: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnIOPortRegisterR0} */
static DECLCALLBACK(int) pdmR3DevHlp_IOPortRegisterR0(PPDMDEVINS pDevIns, RTIOPORT Port, RTIOPORT cPorts, RTR0PTR pvUser,
const char *pszOut, const char *pszIn,
const char *pszOutStr, const char *pszInStr, const char *pszDesc)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_IOPortRegisterR0: caller='%s'/%d: Port=%#x cPorts=%#x pvUser=%p pszOut=%p:{%s} pszIn=%p:{%s} pszOutStr=%p:{%s} pszInStr=%p:{%s} pszDesc=%p:{%s}\n", pDevIns->pReg->szName, pDevIns->iInstance,
Port, cPorts, pvUser, pszOut, pszOut, pszIn, pszIn, pszOutStr, pszOutStr, pszInStr, pszInStr, pszDesc, pszDesc));
/*
* Resolve the functions (one of the can be NULL).
*/
int rc = VINF_SUCCESS;
if ( pDevIns->pReg->szR0Mod[0]
&& (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0))
{
R0PTRTYPE(PFNIOMIOPORTIN) pfnR0PtrIn = 0;
if (pszIn)
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pszIn, &pfnR0PtrIn);
AssertMsgRC(rc, ("Failed to resolve %s.%s (pszIn)\n", pDevIns->pReg->szR0Mod, pszIn));
}
R0PTRTYPE(PFNIOMIOPORTOUT) pfnR0PtrOut = 0;
if (pszOut && RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pszOut, &pfnR0PtrOut);
AssertMsgRC(rc, ("Failed to resolve %s.%s (pszOut)\n", pDevIns->pReg->szR0Mod, pszOut));
}
R0PTRTYPE(PFNIOMIOPORTINSTRING) pfnR0PtrInStr = 0;
if (pszInStr && RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pszInStr, &pfnR0PtrInStr);
AssertMsgRC(rc, ("Failed to resolve %s.%s (pszInStr)\n", pDevIns->pReg->szR0Mod, pszInStr));
}
R0PTRTYPE(PFNIOMIOPORTOUTSTRING) pfnR0PtrOutStr = 0;
if (pszOutStr && RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pszOutStr, &pfnR0PtrOutStr);
AssertMsgRC(rc, ("Failed to resolve %s.%s (pszOutStr)\n", pDevIns->pReg->szR0Mod, pszOutStr));
}
if (RT_SUCCESS(rc))
{
#if 0 /** @todo needs a real string cache for this */
if (pDevIns->iInstance > 0)
{
char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance);
if (pszDesc2)
pszDesc = pszDesc2;
}
#endif
rc = IOMR3IOPortRegisterR0(pDevIns->Internal.s.pVMR3, pDevIns, Port, cPorts, pvUser, pfnR0PtrOut, pfnR0PtrIn, pfnR0PtrOutStr, pfnR0PtrInStr, pszDesc);
}
}
else
{
AssertMsgFailed(("No R0 module for this driver!\n"));
rc = VERR_INVALID_PARAMETER;
}
LogFlow(("pdmR3DevHlp_IOPortRegisterR0: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnIOPortDeregister} */
static DECLCALLBACK(int) pdmR3DevHlp_IOPortDeregister(PPDMDEVINS pDevIns, RTIOPORT Port, RTIOPORT cPorts)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_IOPortDeregister: caller='%s'/%d: Port=%#x cPorts=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance,
Port, cPorts));
int rc = IOMR3IOPortDeregister(pDevIns->Internal.s.pVMR3, pDevIns, Port, cPorts);
LogFlow(("pdmR3DevHlp_IOPortDeregister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnMMIORegister} */
static DECLCALLBACK(int) pdmR3DevHlp_MMIORegister(PPDMDEVINS pDevIns, RTGCPHYS GCPhysStart, uint32_t cbRange, RTHCPTR pvUser,
PFNIOMMMIOWRITE pfnWrite, PFNIOMMMIOREAD pfnRead, PFNIOMMMIOFILL pfnFill,
uint32_t fFlags, const char *pszDesc)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_MMIORegister: caller='%s'/%d: GCPhysStart=%RGp cbRange=%#x pvUser=%p pfnWrite=%p pfnRead=%p pfnFill=%p fFlags=%#x pszDesc=%p:{%s}\n",
pDevIns->pReg->szName, pDevIns->iInstance, GCPhysStart, cbRange, pvUser, pfnWrite, pfnRead, pfnFill, pszDesc, fFlags, pszDesc));
if (pDevIns->iInstance > 0)
{
char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance);
if (pszDesc2)
pszDesc = pszDesc2;
}
int rc = IOMR3MmioRegisterR3(pVM, pDevIns, GCPhysStart, cbRange, pvUser,
pfnWrite, pfnRead, pfnFill, fFlags, pszDesc);
LogFlow(("pdmR3DevHlp_MMIORegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnMMIORegisterRC} */
static DECLCALLBACK(int) pdmR3DevHlp_MMIORegisterRC(PPDMDEVINS pDevIns, RTGCPHYS GCPhysStart, uint32_t cbRange, RTRCPTR pvUser,
const char *pszWrite, const char *pszRead, const char *pszFill)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_MMIORegisterRC: caller='%s'/%d: GCPhysStart=%RGp cbRange=%#x pvUser=%p pszWrite=%p:{%s} pszRead=%p:{%s} pszFill=%p:{%s}\n",
pDevIns->pReg->szName, pDevIns->iInstance, GCPhysStart, cbRange, pvUser, pszWrite, pszWrite, pszRead, pszRead, pszFill, pszFill));
/*
* Resolve the functions.
* Not all function have to present, leave it to IOM to enforce this.
*/
int rc = VINF_SUCCESS;
if ( pDevIns->pReg->szRCMod[0]
&& (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC)
&& !HMIsEnabled(pVM))
{
RTRCPTR RCPtrWrite = NIL_RTRCPTR;
if (pszWrite)
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pszWrite, &RCPtrWrite);
RTRCPTR RCPtrRead = NIL_RTRCPTR;
int rc2 = VINF_SUCCESS;
if (pszRead)
rc2 = pdmR3DevGetSymbolRCLazy(pDevIns, pszRead, &RCPtrRead);
RTRCPTR RCPtrFill = NIL_RTRCPTR;
int rc3 = VINF_SUCCESS;
if (pszFill)
rc3 = pdmR3DevGetSymbolRCLazy(pDevIns, pszFill, &RCPtrFill);
if (RT_SUCCESS(rc) && RT_SUCCESS(rc2) && RT_SUCCESS(rc3))
rc = IOMR3MmioRegisterRC(pVM, pDevIns, GCPhysStart, cbRange, pvUser, RCPtrWrite, RCPtrRead, RCPtrFill);
else
{
AssertMsgRC(rc, ("Failed to resolve %s.%s (pszWrite)\n", pDevIns->pReg->szRCMod, pszWrite));
AssertMsgRC(rc2, ("Failed to resolve %s.%s (pszRead)\n", pDevIns->pReg->szRCMod, pszRead));
AssertMsgRC(rc3, ("Failed to resolve %s.%s (pszFill)\n", pDevIns->pReg->szRCMod, pszFill));
if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
rc = rc2;
if (RT_FAILURE(rc3) && RT_SUCCESS(rc))
rc = rc3;
}
}
else if (!HMIsEnabled(pVM))
{
AssertMsgFailed(("No RC module for this driver!\n"));
rc = VERR_INVALID_PARAMETER;
}
LogFlow(("pdmR3DevHlp_MMIORegisterRC: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnMMIORegisterR0} */
static DECLCALLBACK(int) pdmR3DevHlp_MMIORegisterR0(PPDMDEVINS pDevIns, RTGCPHYS GCPhysStart, uint32_t cbRange, RTR0PTR pvUser,
const char *pszWrite, const char *pszRead, const char *pszFill)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_MMIORegisterHC: caller='%s'/%d: GCPhysStart=%RGp cbRange=%#x pvUser=%p pszWrite=%p:{%s} pszRead=%p:{%s} pszFill=%p:{%s}\n",
pDevIns->pReg->szName, pDevIns->iInstance, GCPhysStart, cbRange, pvUser, pszWrite, pszWrite, pszRead, pszRead, pszFill, pszFill));
/*
* Resolve the functions.
* Not all function have to present, leave it to IOM to enforce this.
*/
int rc = VINF_SUCCESS;
if ( pDevIns->pReg->szR0Mod[0]
&& (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0))
{
R0PTRTYPE(PFNIOMMMIOWRITE) pfnR0PtrWrite = 0;
if (pszWrite)
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pszWrite, &pfnR0PtrWrite);
R0PTRTYPE(PFNIOMMMIOREAD) pfnR0PtrRead = 0;
int rc2 = VINF_SUCCESS;
if (pszRead)
rc2 = pdmR3DevGetSymbolR0Lazy(pDevIns, pszRead, &pfnR0PtrRead);
R0PTRTYPE(PFNIOMMMIOFILL) pfnR0PtrFill = 0;
int rc3 = VINF_SUCCESS;
if (pszFill)
rc3 = pdmR3DevGetSymbolR0Lazy(pDevIns, pszFill, &pfnR0PtrFill);
if (RT_SUCCESS(rc) && RT_SUCCESS(rc2) && RT_SUCCESS(rc3))
rc = IOMR3MmioRegisterR0(pDevIns->Internal.s.pVMR3, pDevIns, GCPhysStart, cbRange, pvUser, pfnR0PtrWrite, pfnR0PtrRead, pfnR0PtrFill);
else
{
AssertMsgRC(rc, ("Failed to resolve %s.%s (pszWrite)\n", pDevIns->pReg->szR0Mod, pszWrite));
AssertMsgRC(rc2, ("Failed to resolve %s.%s (pszRead)\n", pDevIns->pReg->szR0Mod, pszRead));
AssertMsgRC(rc3, ("Failed to resolve %s.%s (pszFill)\n", pDevIns->pReg->szR0Mod, pszFill));
if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
rc = rc2;
if (RT_FAILURE(rc3) && RT_SUCCESS(rc))
rc = rc3;
}
}
else
{
AssertMsgFailed(("No R0 module for this driver!\n"));
rc = VERR_INVALID_PARAMETER;
}
LogFlow(("pdmR3DevHlp_MMIORegisterR0: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnMMIODeregister} */
static DECLCALLBACK(int) pdmR3DevHlp_MMIODeregister(PPDMDEVINS pDevIns, RTGCPHYS GCPhysStart, uint32_t cbRange)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_MMIODeregister: caller='%s'/%d: GCPhysStart=%RGp cbRange=%#x\n",
pDevIns->pReg->szName, pDevIns->iInstance, GCPhysStart, cbRange));
int rc = IOMR3MmioDeregister(pDevIns->Internal.s.pVMR3, pDevIns, GCPhysStart, cbRange);
LogFlow(("pdmR3DevHlp_MMIODeregister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/**
* @copydoc PDMDEVHLPR3::pfnMMIO2Register
*/
static DECLCALLBACK(int) pdmR3DevHlp_MMIO2Register(PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS cb, uint32_t fFlags, void **ppv, const char *pszDesc)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_MMIO2Register: caller='%s'/%d: iRegion=%#x cb=%#RGp fFlags=%RX32 ppv=%p pszDescp=%p:{%s}\n",
pDevIns->pReg->szName, pDevIns->iInstance, iRegion, cb, fFlags, ppv, pszDesc, pszDesc));
/** @todo PGMR3PhysMMIO2Register mangles the description, move it here and
* use a real string cache. */
int rc = PGMR3PhysMMIO2Register(pDevIns->Internal.s.pVMR3, pDevIns, iRegion, cb, fFlags, ppv, pszDesc);
LogFlow(("pdmR3DevHlp_MMIO2Register: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/**
* @copydoc PDMDEVHLPR3::pfnMMIO2Deregister
*/
static DECLCALLBACK(int) pdmR3DevHlp_MMIO2Deregister(PPDMDEVINS pDevIns, uint32_t iRegion)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_MMIO2Deregister: caller='%s'/%d: iRegion=%#x\n",
pDevIns->pReg->szName, pDevIns->iInstance, iRegion));
AssertReturn(iRegion <= UINT8_MAX || iRegion == UINT32_MAX, VERR_INVALID_PARAMETER);
int rc = PGMR3PhysMMIO2Deregister(pDevIns->Internal.s.pVMR3, pDevIns, iRegion);
LogFlow(("pdmR3DevHlp_MMIO2Deregister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/**
* @copydoc PDMDEVHLPR3::pfnMMIO2Map
*/
static DECLCALLBACK(int) pdmR3DevHlp_MMIO2Map(PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_MMIO2Map: caller='%s'/%d: iRegion=%#x GCPhys=%#RGp\n",
pDevIns->pReg->szName, pDevIns->iInstance, iRegion, GCPhys));
int rc = PGMR3PhysMMIO2Map(pDevIns->Internal.s.pVMR3, pDevIns, iRegion, GCPhys);
LogFlow(("pdmR3DevHlp_MMIO2Map: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/**
* @copydoc PDMDEVHLPR3::pfnMMIO2Unmap
*/
static DECLCALLBACK(int) pdmR3DevHlp_MMIO2Unmap(PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_MMIO2Unmap: caller='%s'/%d: iRegion=%#x GCPhys=%#RGp\n",
pDevIns->pReg->szName, pDevIns->iInstance, iRegion, GCPhys));
int rc = PGMR3PhysMMIO2Unmap(pDevIns->Internal.s.pVMR3, pDevIns, iRegion, GCPhys);
LogFlow(("pdmR3DevHlp_MMIO2Unmap: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/**
* @copydoc PDMDEVHLPR3::pfnMMHyperMapMMIO2
*/
static DECLCALLBACK(int) pdmR3DevHlp_MMHyperMapMMIO2(PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, RTGCPHYS cb,
const char *pszDesc, PRTRCPTR pRCPtr)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_MMHyperMapMMIO2: caller='%s'/%d: iRegion=%#x off=%RGp cb=%RGp pszDesc=%p:{%s} pRCPtr=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, iRegion, off, cb, pszDesc, pszDesc, pRCPtr));
if (pDevIns->iInstance > 0)
{
char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance);
if (pszDesc2)
pszDesc = pszDesc2;
}
int rc = MMR3HyperMapMMIO2(pVM, pDevIns, iRegion, off, cb, pszDesc, pRCPtr);
LogFlow(("pdmR3DevHlp_MMHyperMapMMIO2: caller='%s'/%d: returns %Rrc *pRCPtr=%RRv\n", pDevIns->pReg->szName, pDevIns->iInstance, rc, *pRCPtr));
return rc;
}
/**
* @copydoc PDMDEVHLPR3::pfnMMIO2MapKernel
*/
static DECLCALLBACK(int) pdmR3DevHlp_MMIO2MapKernel(PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, RTGCPHYS cb,
const char *pszDesc, PRTR0PTR pR0Ptr)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_MMIO2MapKernel: caller='%s'/%d: iRegion=%#x off=%RGp cb=%RGp pszDesc=%p:{%s} pR0Ptr=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, iRegion, off, cb, pszDesc, pszDesc, pR0Ptr));
if (pDevIns->iInstance > 0)
{
char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance);
if (pszDesc2)
pszDesc = pszDesc2;
}
int rc = PGMR3PhysMMIO2MapKernel(pVM, pDevIns, iRegion, off, cb, pszDesc, pR0Ptr);
LogFlow(("pdmR3DevHlp_MMIO2MapKernel: caller='%s'/%d: returns %Rrc *pR0Ptr=%RHv\n", pDevIns->pReg->szName, pDevIns->iInstance, rc, *pR0Ptr));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnROMRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_ROMRegister(PPDMDEVINS pDevIns, RTGCPHYS GCPhysStart, uint32_t cbRange,
const void *pvBinary, uint32_t cbBinary, uint32_t fFlags, const char *pszDesc)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_ROMRegister: caller='%s'/%d: GCPhysStart=%RGp cbRange=%#x pvBinary=%p cbBinary=%#x fFlags=%#RX32 pszDesc=%p:{%s}\n",
pDevIns->pReg->szName, pDevIns->iInstance, GCPhysStart, cbRange, pvBinary, cbBinary, fFlags, pszDesc, pszDesc));
/** @todo can we mangle pszDesc? */
int rc = PGMR3PhysRomRegister(pDevIns->Internal.s.pVMR3, pDevIns, GCPhysStart, cbRange, pvBinary, cbBinary, fFlags, pszDesc);
LogFlow(("pdmR3DevHlp_ROMRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnROMProtectShadow} */
static DECLCALLBACK(int) pdmR3DevHlp_ROMProtectShadow(PPDMDEVINS pDevIns, RTGCPHYS GCPhysStart, uint32_t cbRange, PGMROMPROT enmProt)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_ROMProtectShadow: caller='%s'/%d: GCPhysStart=%RGp cbRange=%#x enmProt=%d\n",
pDevIns->pReg->szName, pDevIns->iInstance, GCPhysStart, cbRange, enmProt));
int rc = PGMR3PhysRomProtect(pDevIns->Internal.s.pVMR3, GCPhysStart, cbRange, enmProt);
LogFlow(("pdmR3DevHlp_ROMProtectShadow: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnSSMRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_SSMRegister(PPDMDEVINS pDevIns, uint32_t uVersion, size_t cbGuess, const char *pszBefore,
PFNSSMDEVLIVEPREP pfnLivePrep, PFNSSMDEVLIVEEXEC pfnLiveExec, PFNSSMDEVLIVEVOTE pfnLiveVote,
PFNSSMDEVSAVEPREP pfnSavePrep, PFNSSMDEVSAVEEXEC pfnSaveExec, PFNSSMDEVSAVEDONE pfnSaveDone,
PFNSSMDEVLOADPREP pfnLoadPrep, PFNSSMDEVLOADEXEC pfnLoadExec, PFNSSMDEVLOADDONE pfnLoadDone)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_SSMRegister: caller='%s'/%d: uVersion=#x cbGuess=%#x pszBefore=%p:{%s}\n"
" pfnLivePrep=%p pfnLiveExec=%p pfnLiveVote=%p pfnSavePrep=%p pfnSaveExec=%p pfnSaveDone=%p pszLoadPrep=%p pfnLoadExec=%p pfnLoadDone=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, uVersion, cbGuess, pszBefore, pszBefore,
pfnLivePrep, pfnLiveExec, pfnLiveVote,
pfnSavePrep, pfnSaveExec, pfnSaveDone,
pfnLoadPrep, pfnLoadExec, pfnLoadDone));
int rc = SSMR3RegisterDevice(pDevIns->Internal.s.pVMR3, pDevIns, pDevIns->pReg->szName, pDevIns->iInstance,
uVersion, cbGuess, pszBefore,
pfnLivePrep, pfnLiveExec, pfnLiveVote,
pfnSavePrep, pfnSaveExec, pfnSaveDone,
pfnLoadPrep, pfnLoadExec, pfnLoadDone);
LogFlow(("pdmR3DevHlp_SSMRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnTMTimerCreate} */
static DECLCALLBACK(int) pdmR3DevHlp_TMTimerCreate(PPDMDEVINS pDevIns, TMCLOCK enmClock, PFNTMTIMERDEV pfnCallback, void *pvUser, uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_TMTimerCreate: caller='%s'/%d: enmClock=%d pfnCallback=%p pvUser=%p fFlags=%#x pszDesc=%p:{%s} ppTimer=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, enmClock, pfnCallback, pvUser, fFlags, pszDesc, pszDesc, ppTimer));
if (pDevIns->iInstance > 0) /** @todo use a string cache here later. */
{
char *pszDesc2 = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s [%u]", pszDesc, pDevIns->iInstance);
if (pszDesc2)
pszDesc = pszDesc2;
}
int rc = TMR3TimerCreateDevice(pVM, pDevIns, enmClock, pfnCallback, pvUser, fFlags, pszDesc, ppTimer);
LogFlow(("pdmR3DevHlp_TMTimerCreate: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnTMUtcNow} */
static DECLCALLBACK(PRTTIMESPEC) pdmR3DevHlp_TMUtcNow(PPDMDEVINS pDevIns, PRTTIMESPEC pTime)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_TMUtcNow: caller='%s'/%d: pTime=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pTime));
pTime = TMR3UtcNow(pDevIns->Internal.s.pVMR3, pTime);
LogFlow(("pdmR3DevHlp_TMUtcNow: caller='%s'/%d: returns %RU64\n", pDevIns->pReg->szName, pDevIns->iInstance, RTTimeSpecGetNano(pTime)));
return pTime;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnTMTimeVirtGet} */
static DECLCALLBACK(uint64_t) pdmR3DevHlp_TMTimeVirtGet(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_TMTimeVirtGet: caller='%s'\n",
pDevIns->pReg->szName, pDevIns->iInstance));
uint64_t u64Time = TMVirtualSyncGet(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_TMTimeVirtGet: caller='%s'/%d: returns %RU64\n", pDevIns->pReg->szName, pDevIns->iInstance, u64Time));
return u64Time;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnTMTimeVirtGetFreq} */
static DECLCALLBACK(uint64_t) pdmR3DevHlp_TMTimeVirtGetFreq(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_TMTimeVirtGetFreq: caller='%s'\n",
pDevIns->pReg->szName, pDevIns->iInstance));
uint64_t u64Freq = TMVirtualGetFreq(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_TMTimeVirtGetFreq: caller='%s'/%d: returns %RU64\n", pDevIns->pReg->szName, pDevIns->iInstance, u64Freq));
return u64Freq;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnTMTimeVirtGetNano} */
static DECLCALLBACK(uint64_t) pdmR3DevHlp_TMTimeVirtGetNano(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_TMTimeVirtGetNano: caller='%s'\n",
pDevIns->pReg->szName, pDevIns->iInstance));
uint64_t u64Time = TMVirtualGet(pDevIns->Internal.s.pVMR3);
uint64_t u64Nano = TMVirtualToNano(pDevIns->Internal.s.pVMR3, u64Time);
LogFlow(("pdmR3DevHlp_TMTimeVirtGetNano: caller='%s'/%d: returns %RU64\n", pDevIns->pReg->szName, pDevIns->iInstance, u64Nano));
return u64Nano;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnGetSupDrvSession} */
static DECLCALLBACK(PSUPDRVSESSION) pdmR3DevHlp_GetSupDrvSession(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_GetSupDrvSession: caller='%s'\n",
pDevIns->pReg->szName, pDevIns->iInstance));
PSUPDRVSESSION pSession = pDevIns->Internal.s.pVMR3->pSession;
LogFlow(("pdmR3DevHlp_GetSupDrvSession: caller='%s'/%d: returns %#p\n", pDevIns->pReg->szName, pDevIns->iInstance, pSession));
return pSession;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPhysRead} */
static DECLCALLBACK(int) pdmR3DevHlp_PhysRead(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, void *pvBuf, size_t cbRead)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
LogFlow(("pdmR3DevHlp_PhysRead: caller='%s'/%d: GCPhys=%RGp pvBuf=%p cbRead=%#x\n",
pDevIns->pReg->szName, pDevIns->iInstance, GCPhys, pvBuf, cbRead));
#if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION)
if (!VM_IS_EMT(pVM))
{
char szNames[128];
uint32_t cLocks = PDMR3CritSectCountOwned(pVM, szNames, sizeof(szNames));
AssertMsg(cLocks == 0, ("cLocks=%u %s\n", cLocks, szNames));
}
#endif
VBOXSTRICTRC rcStrict;
if (VM_IS_EMT(pVM))
rcStrict = PGMPhysRead(pVM, GCPhys, pvBuf, cbRead, PGMACCESSORIGIN_DEVICE);
else
rcStrict = PGMR3PhysReadExternal(pVM, GCPhys, pvBuf, cbRead, PGMACCESSORIGIN_DEVICE);
AssertMsg(rcStrict == VINF_SUCCESS, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict))); /** @todo track down the users for this bugger. */
Log(("pdmR3DevHlp_PhysRead: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VBOXSTRICTRC_VAL(rcStrict) ));
return VBOXSTRICTRC_VAL(rcStrict);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPhysWrite} */
static DECLCALLBACK(int) pdmR3DevHlp_PhysWrite(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, const void *pvBuf, size_t cbWrite)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
LogFlow(("pdmR3DevHlp_PhysWrite: caller='%s'/%d: GCPhys=%RGp pvBuf=%p cbWrite=%#x\n",
pDevIns->pReg->szName, pDevIns->iInstance, GCPhys, pvBuf, cbWrite));
#if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION)
if (!VM_IS_EMT(pVM))
{
char szNames[128];
uint32_t cLocks = PDMR3CritSectCountOwned(pVM, szNames, sizeof(szNames));
AssertMsg(cLocks == 0, ("cLocks=%u %s\n", cLocks, szNames));
}
#endif
VBOXSTRICTRC rcStrict;
if (VM_IS_EMT(pVM))
rcStrict = PGMPhysWrite(pVM, GCPhys, pvBuf, cbWrite, PGMACCESSORIGIN_DEVICE);
else
rcStrict = PGMR3PhysWriteExternal(pVM, GCPhys, pvBuf, cbWrite, PGMACCESSORIGIN_DEVICE);
AssertMsg(rcStrict == VINF_SUCCESS, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict))); /** @todo track down the users for this bugger. */
Log(("pdmR3DevHlp_PhysWrite: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VBOXSTRICTRC_VAL(rcStrict) ));
return VBOXSTRICTRC_VAL(rcStrict);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPhysGCPhys2CCPtr} */
static DECLCALLBACK(int) pdmR3DevHlp_PhysGCPhys2CCPtr(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, uint32_t fFlags, void **ppv, PPGMPAGEMAPLOCK pLock)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
LogFlow(("pdmR3DevHlp_PhysGCPhys2CCPtr: caller='%s'/%d: GCPhys=%RGp fFlags=%#x ppv=%p pLock=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, GCPhys, fFlags, ppv, pLock));
AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
#if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION)
if (!VM_IS_EMT(pVM))
{
char szNames[128];
uint32_t cLocks = PDMR3CritSectCountOwned(pVM, szNames, sizeof(szNames));
AssertMsg(cLocks == 0, ("cLocks=%u %s\n", cLocks, szNames));
}
#endif
int rc = PGMR3PhysGCPhys2CCPtrExternal(pVM, GCPhys, ppv, pLock);
Log(("pdmR3DevHlp_PhysGCPhys2CCPtr: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPhysGCPhys2CCPtrReadOnly} */
static DECLCALLBACK(int) pdmR3DevHlp_PhysGCPhys2CCPtrReadOnly(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, uint32_t fFlags, const void **ppv, PPGMPAGEMAPLOCK pLock)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
LogFlow(("pdmR3DevHlp_PhysGCPhys2CCPtrReadOnly: caller='%s'/%d: GCPhys=%RGp fFlags=%#x ppv=%p pLock=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, GCPhys, fFlags, ppv, pLock));
AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
#if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION)
if (!VM_IS_EMT(pVM))
{
char szNames[128];
uint32_t cLocks = PDMR3CritSectCountOwned(pVM, szNames, sizeof(szNames));
AssertMsg(cLocks == 0, ("cLocks=%u %s\n", cLocks, szNames));
}
#endif
int rc = PGMR3PhysGCPhys2CCPtrReadOnlyExternal(pVM, GCPhys, ppv, pLock);
Log(("pdmR3DevHlp_PhysGCPhys2CCPtrReadOnly: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPhysReleasePageMappingLock} */
static DECLCALLBACK(void) pdmR3DevHlp_PhysReleasePageMappingLock(PPDMDEVINS pDevIns, PPGMPAGEMAPLOCK pLock)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
LogFlow(("pdmR3DevHlp_PhysReleasePageMappingLock: caller='%s'/%d: pLock=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pLock));
PGMPhysReleasePageMappingLock(pVM, pLock);
Log(("pdmR3DevHlp_PhysReleasePageMappingLock: caller='%s'/%d: returns void\n", pDevIns->pReg->szName, pDevIns->iInstance));
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPhysReadGCVirt} */
static DECLCALLBACK(int) pdmR3DevHlp_PhysReadGCVirt(PPDMDEVINS pDevIns, void *pvDst, RTGCPTR GCVirtSrc, size_t cb)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_PhysReadGCVirt: caller='%s'/%d: pvDst=%p GCVirt=%RGv cb=%#x\n",
pDevIns->pReg->szName, pDevIns->iInstance, pvDst, GCVirtSrc, cb));
PVMCPU pVCpu = VMMGetCpu(pVM);
if (!pVCpu)
return VERR_ACCESS_DENIED;
#if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION)
/** @todo SMP. */
#endif
int rc = PGMPhysSimpleReadGCPtr(pVCpu, pvDst, GCVirtSrc, cb);
LogFlow(("pdmR3DevHlp_PhysReadGCVirt: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPhysWriteGCVirt} */
static DECLCALLBACK(int) pdmR3DevHlp_PhysWriteGCVirt(PPDMDEVINS pDevIns, RTGCPTR GCVirtDst, const void *pvSrc, size_t cb)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_PhysWriteGCVirt: caller='%s'/%d: GCVirtDst=%RGv pvSrc=%p cb=%#x\n",
pDevIns->pReg->szName, pDevIns->iInstance, GCVirtDst, pvSrc, cb));
PVMCPU pVCpu = VMMGetCpu(pVM);
if (!pVCpu)
return VERR_ACCESS_DENIED;
#if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION)
/** @todo SMP. */
#endif
int rc = PGMPhysSimpleWriteGCPtr(pVCpu, GCVirtDst, pvSrc, cb);
LogFlow(("pdmR3DevHlp_PhysWriteGCVirt: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPhysGCPtr2GCPhys} */
static DECLCALLBACK(int) pdmR3DevHlp_PhysGCPtr2GCPhys(PPDMDEVINS pDevIns, RTGCPTR GCPtr, PRTGCPHYS pGCPhys)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_PhysGCPtr2GCPhys: caller='%s'/%d: GCPtr=%RGv pGCPhys=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, GCPtr, pGCPhys));
PVMCPU pVCpu = VMMGetCpu(pVM);
if (!pVCpu)
return VERR_ACCESS_DENIED;
#if defined(VBOX_STRICT) && defined(PDM_DEVHLP_DEADLOCK_DETECTION)
/** @todo SMP. */
#endif
int rc = PGMPhysGCPtr2GCPhys(pVCpu, GCPtr, pGCPhys);
LogFlow(("pdmR3DevHlp_PhysGCPtr2GCPhys: caller='%s'/%d: returns %Rrc *pGCPhys=%RGp\n", pDevIns->pReg->szName, pDevIns->iInstance, rc, *pGCPhys));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnMMHeapAlloc} */
static DECLCALLBACK(void *) pdmR3DevHlp_MMHeapAlloc(PPDMDEVINS pDevIns, size_t cb)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_MMHeapAlloc: caller='%s'/%d: cb=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance, cb));
void *pv = MMR3HeapAlloc(pDevIns->Internal.s.pVMR3, MM_TAG_PDM_DEVICE_USER, cb);
LogFlow(("pdmR3DevHlp_MMHeapAlloc: caller='%s'/%d: returns %p\n", pDevIns->pReg->szName, pDevIns->iInstance, pv));
return pv;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnMMHeapAllocZ} */
static DECLCALLBACK(void *) pdmR3DevHlp_MMHeapAllocZ(PPDMDEVINS pDevIns, size_t cb)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_MMHeapAllocZ: caller='%s'/%d: cb=%#x\n", pDevIns->pReg->szName, pDevIns->iInstance, cb));
void *pv = MMR3HeapAllocZ(pDevIns->Internal.s.pVMR3, MM_TAG_PDM_DEVICE_USER, cb);
LogFlow(("pdmR3DevHlp_MMHeapAllocZ: caller='%s'/%d: returns %p\n", pDevIns->pReg->szName, pDevIns->iInstance, pv));
return pv;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnMMHeapFree} */
static DECLCALLBACK(void) pdmR3DevHlp_MMHeapFree(PPDMDEVINS pDevIns, void *pv)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_MMHeapFree: caller='%s'/%d: pv=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pv));
MMR3HeapFree(pv);
LogFlow(("pdmR3DevHlp_MMHeapAlloc: caller='%s'/%d: returns void\n", pDevIns->pReg->szName, pDevIns->iInstance));
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMState} */
static DECLCALLBACK(VMSTATE) pdmR3DevHlp_VMState(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VMSTATE enmVMState = VMR3GetState(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_VMState: caller='%s'/%d: returns %d (%s)\n", pDevIns->pReg->szName, pDevIns->iInstance,
enmVMState, VMR3GetStateName(enmVMState)));
return enmVMState;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMTeleportedAndNotFullyResumedYet} */
static DECLCALLBACK(bool) pdmR3DevHlp_VMTeleportedAndNotFullyResumedYet(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
bool fRc = VMR3TeleportedAndNotFullyResumedYet(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_VMState: caller='%s'/%d: returns %RTbool\n", pDevIns->pReg->szName, pDevIns->iInstance,
fRc));
return fRc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMSetError} */
static DECLCALLBACK(int) pdmR3DevHlp_VMSetError(PPDMDEVINS pDevIns, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
va_list args;
va_start(args, pszFormat);
int rc2 = VMSetErrorV(pDevIns->Internal.s.pVMR3, rc, RT_SRC_POS_ARGS, pszFormat, args); Assert(rc2 == rc); NOREF(rc2);
va_end(args);
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMSetErrorV} */
static DECLCALLBACK(int) pdmR3DevHlp_VMSetErrorV(PPDMDEVINS pDevIns, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list va)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
int rc2 = VMSetErrorV(pDevIns->Internal.s.pVMR3, rc, RT_SRC_POS_ARGS, pszFormat, va); Assert(rc2 == rc); NOREF(rc2);
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMSetRuntimeError} */
static DECLCALLBACK(int) pdmR3DevHlp_VMSetRuntimeError(PPDMDEVINS pDevIns, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
va_list args;
va_start(args, pszFormat);
int rc = VMSetRuntimeErrorV(pDevIns->Internal.s.pVMR3, fFlags, pszErrorId, pszFormat, args);
va_end(args);
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMSetRuntimeErrorV} */
static DECLCALLBACK(int) pdmR3DevHlp_VMSetRuntimeErrorV(PPDMDEVINS pDevIns, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list va)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
int rc = VMSetRuntimeErrorV(pDevIns->Internal.s.pVMR3, fFlags, pszErrorId, pszFormat, va);
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnDBGFStopV} */
static DECLCALLBACK(int) pdmR3DevHlp_DBGFStopV(PPDMDEVINS pDevIns, const char *pszFile, unsigned iLine, const char *pszFunction, const char *pszFormat, va_list args)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
#ifdef LOG_ENABLED
va_list va2;
va_copy(va2, args);
LogFlow(("pdmR3DevHlp_DBGFStopV: caller='%s'/%d: pszFile=%p:{%s} iLine=%d pszFunction=%p:{%s} pszFormat=%p:{%s} (%N)\n",
pDevIns->pReg->szName, pDevIns->iInstance, pszFile, pszFile, iLine, pszFunction, pszFunction, pszFormat, pszFormat, pszFormat, &va2));
va_end(va2);
#endif
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
int rc = DBGFR3EventSrcV(pVM, DBGFEVENT_DEV_STOP, pszFile, iLine, pszFunction, pszFormat, args);
if (rc == VERR_DBGF_NOT_ATTACHED)
rc = VINF_SUCCESS;
LogFlow(("pdmR3DevHlp_DBGFStopV: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnDBGFInfoRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_DBGFInfoRegister(PPDMDEVINS pDevIns, const char *pszName, const char *pszDesc, PFNDBGFHANDLERDEV pfnHandler)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_DBGFInfoRegister: caller='%s'/%d: pszName=%p:{%s} pszDesc=%p:{%s} pfnHandler=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pszName, pszName, pszDesc, pszDesc, pfnHandler));
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
int rc = DBGFR3InfoRegisterDevice(pVM, pszName, pszDesc, pfnHandler, pDevIns);
LogFlow(("pdmR3DevHlp_DBGFInfoRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnDBGFRegRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_DBGFRegRegister(PPDMDEVINS pDevIns, PCDBGFREGDESC paRegisters)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_DBGFRegRegister: caller='%s'/%d: paRegisters=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, paRegisters));
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
int rc = DBGFR3RegRegisterDevice(pVM, paRegisters, pDevIns, pDevIns->pReg->szName, pDevIns->iInstance);
LogFlow(("pdmR3DevHlp_DBGFRegRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnDBGFTraceBuf} */
static DECLCALLBACK(RTTRACEBUF) pdmR3DevHlp_DBGFTraceBuf(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
RTTRACEBUF hTraceBuf = pDevIns->Internal.s.pVMR3->hTraceBufR3;
LogFlow(("pdmR3DevHlp_DBGFTraceBuf: caller='%s'/%d: returns %p\n", pDevIns->pReg->szName, pDevIns->iInstance, hTraceBuf));
return hTraceBuf;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnSTAMRegister} */
static DECLCALLBACK(void) pdmR3DevHlp_STAMRegister(PPDMDEVINS pDevIns, void *pvSample, STAMTYPE enmType, const char *pszName, STAMUNIT enmUnit, const char *pszDesc)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
STAM_REG(pVM, pvSample, enmType, pszName, enmUnit, pszDesc);
NOREF(pVM);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnSTAMRegisterF} */
static DECLCALLBACK(void) pdmR3DevHlp_STAMRegisterF(PPDMDEVINS pDevIns, void *pvSample, STAMTYPE enmType, STAMVISIBILITY enmVisibility,
STAMUNIT enmUnit, const char *pszDesc, const char *pszName, ...)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
va_list args;
va_start(args, pszName);
int rc = STAMR3RegisterV(pVM, pvSample, enmType, enmVisibility, enmUnit, pszDesc, pszName, args);
va_end(args);
AssertRC(rc);
NOREF(pVM);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnSTAMRegisterV} */
static DECLCALLBACK(void) pdmR3DevHlp_STAMRegisterV(PPDMDEVINS pDevIns, void *pvSample, STAMTYPE enmType, STAMVISIBILITY enmVisibility,
STAMUNIT enmUnit, const char *pszDesc, const char *pszName, va_list args)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
int rc = STAMR3RegisterV(pVM, pvSample, enmType, enmVisibility, enmUnit, pszDesc, pszName, args);
AssertRC(rc);
NOREF(pVM);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPCIRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_PCIRegister(PPDMDEVINS pDevIns, PPCIDEVICE pPciDev)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: pPciDev=%p:{.config={%#.256Rhxs}\n",
pDevIns->pReg->szName, pDevIns->iInstance, pPciDev, pPciDev->config));
/*
* Validate input.
*/
if (!pPciDev)
{
Assert(pPciDev);
LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: returns %Rrc (pPciDev)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if (!pPciDev->config[0] && !pPciDev->config[1])
{
Assert(pPciDev->config[0] || pPciDev->config[1]);
LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: returns %Rrc (vendor)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if (pDevIns->Internal.s.pPciDeviceR3)
{
/** @todo the PCI device vs. PDM device designed is a bit flawed if we have to
* support a PDM device with multiple PCI devices. This might become a problem
* when upgrading the chipset for instance because of multiple functions in some
* devices...
*/
AssertMsgFailed(("Only one PCI device per device is currently implemented!\n"));
return VERR_PDM_ONE_PCI_FUNCTION_PER_DEVICE;
}
/*
* Choose the PCI bus for the device.
*
* This is simple. If the device was configured for a particular bus, the PCIBusNo
* configuration value will be set. If not the default bus is 0.
*/
int rc;
PPDMPCIBUS pBus = pDevIns->Internal.s.pPciBusR3;
if (!pBus)
{
uint8_t u8Bus;
rc = CFGMR3QueryU8Def(pDevIns->Internal.s.pCfgHandle, "PCIBusNo", &u8Bus, 0);
AssertLogRelMsgRCReturn(rc, ("Configuration error: PCIBusNo query failed with rc=%Rrc (%s/%d)\n",
rc, pDevIns->pReg->szName, pDevIns->iInstance), rc);
AssertLogRelMsgReturn(u8Bus < RT_ELEMENTS(pVM->pdm.s.aPciBuses),
("Configuration error: PCIBusNo=%d, max is %d. (%s/%d)\n", u8Bus,
RT_ELEMENTS(pVM->pdm.s.aPciBuses), pDevIns->pReg->szName, pDevIns->iInstance),
VERR_PDM_NO_PCI_BUS);
pBus = pDevIns->Internal.s.pPciBusR3 = &pVM->pdm.s.aPciBuses[u8Bus];
}
if (pBus->pDevInsR3)
{
if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0)
pDevIns->Internal.s.pPciBusR0 = MMHyperR3ToR0(pVM, pDevIns->Internal.s.pPciBusR3);
else
pDevIns->Internal.s.pPciBusR0 = NIL_RTR0PTR;
if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC)
pDevIns->Internal.s.pPciBusRC = MMHyperR3ToRC(pVM, pDevIns->Internal.s.pPciBusR3);
else
pDevIns->Internal.s.pPciBusRC = NIL_RTRCPTR;
/*
* Check the configuration for PCI device and function assignment.
*/
int iDev = -1;
uint8_t u8Device;
rc = CFGMR3QueryU8(pDevIns->Internal.s.pCfgHandle, "PCIDeviceNo", &u8Device);
if (RT_SUCCESS(rc))
{
AssertMsgReturn(u8Device <= 31,
("Configuration error: PCIDeviceNo=%d, max is 31. (%s/%d)\n",
u8Device, pDevIns->pReg->szName, pDevIns->iInstance),
VERR_PDM_BAD_PCI_CONFIG);
uint8_t u8Function;
rc = CFGMR3QueryU8(pDevIns->Internal.s.pCfgHandle, "PCIFunctionNo", &u8Function);
AssertMsgRCReturn(rc, ("Configuration error: PCIDeviceNo, but PCIFunctionNo query failed with rc=%Rrc (%s/%d)\n",
rc, pDevIns->pReg->szName, pDevIns->iInstance),
rc);
AssertMsgReturn(u8Function <= 7,
("Configuration error: PCIFunctionNo=%d, max is 7. (%s/%d)\n",
u8Function, pDevIns->pReg->szName, pDevIns->iInstance),
VERR_PDM_BAD_PCI_CONFIG);
iDev = (u8Device << 3) | u8Function;
}
else if (rc != VERR_CFGM_VALUE_NOT_FOUND)
{
AssertMsgFailed(("Configuration error: PCIDeviceNo query failed with rc=%Rrc (%s/%d)\n",
rc, pDevIns->pReg->szName, pDevIns->iInstance));
return rc;
}
/*
* Call the pci bus device to do the actual registration.
*/
pdmLock(pVM);
rc = pBus->pfnRegisterR3(pBus->pDevInsR3, pPciDev, pDevIns->pReg->szName, iDev);
pdmUnlock(pVM);
if (RT_SUCCESS(rc))
{
pPciDev->pDevIns = pDevIns;
pDevIns->Internal.s.pPciDeviceR3 = pPciDev;
if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0)
pDevIns->Internal.s.pPciDeviceR0 = MMHyperR3ToR0(pVM, pPciDev);
else
pDevIns->Internal.s.pPciDeviceR0 = NIL_RTR0PTR;
if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC)
pDevIns->Internal.s.pPciDeviceRC = MMHyperR3ToRC(pVM, pPciDev);
else
pDevIns->Internal.s.pPciDeviceRC = NIL_RTRCPTR;
Log(("PDM: Registered device '%s'/%d as PCI device %d on bus %d\n",
pDevIns->pReg->szName, pDevIns->iInstance, pPciDev->devfn, pDevIns->Internal.s.pPciBusR3->iBus));
}
}
else
{
AssertLogRelMsgFailed(("Configuration error: No PCI bus available. This could be related to init order too!\n"));
rc = VERR_PDM_NO_PCI_BUS;
}
LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPCIIORegionRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_PCIIORegionRegister(PPDMDEVINS pDevIns, int iRegion, uint32_t cbRegion, PCIADDRESSSPACE enmType, PFNPCIIOREGIONMAP pfnCallback)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_PCIIORegionRegister: caller='%s'/%d: iRegion=%d cbRegion=%#x enmType=%d pfnCallback=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, iRegion, cbRegion, enmType, pfnCallback));
/*
* Validate input.
*/
if (iRegion < 0 || iRegion >= PCI_NUM_REGIONS)
{
Assert(iRegion >= 0 && iRegion < PCI_NUM_REGIONS);
LogFlow(("pdmR3DevHlp_PCIIORegionRegister: caller='%s'/%d: returns %Rrc (iRegion)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
switch ((int)enmType)
{
case PCI_ADDRESS_SPACE_IO:
/*
* Sanity check: don't allow to register more than 32K of the PCI I/O space.
*/
AssertMsgReturn(cbRegion <= _32K,
("caller='%s'/%d: %#x\n", pDevIns->pReg->szName, pDevIns->iInstance, cbRegion),
VERR_INVALID_PARAMETER);
break;
case PCI_ADDRESS_SPACE_MEM:
case PCI_ADDRESS_SPACE_MEM_PREFETCH:
case PCI_ADDRESS_SPACE_MEM | PCI_ADDRESS_SPACE_BAR64:
case PCI_ADDRESS_SPACE_MEM_PREFETCH | PCI_ADDRESS_SPACE_BAR64:
/*
* Sanity check: don't allow to register more than 512MB of the PCI MMIO space for
* now. If this limit is increased beyond 2GB, adapt the aligned check below as well!
*/
AssertMsgReturn(cbRegion <= 512 * _1M,
("caller='%s'/%d: %#x\n", pDevIns->pReg->szName, pDevIns->iInstance, cbRegion),
VERR_INVALID_PARAMETER);
break;
default:
AssertMsgFailed(("enmType=%#x is unknown\n", enmType));
LogFlow(("pdmR3DevHlp_PCIIORegionRegister: caller='%s'/%d: returns %Rrc (enmType)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if (!pfnCallback)
{
Assert(pfnCallback);
LogFlow(("pdmR3DevHlp_PCIIORegionRegister: caller='%s'/%d: returns %Rrc (callback)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
AssertRelease(VMR3GetState(pVM) != VMSTATE_RUNNING);
/*
* Must have a PCI device registered!
*/
int rc;
PPCIDEVICE pPciDev = pDevIns->Internal.s.pPciDeviceR3;
if (pPciDev)
{
/*
* We're currently restricted to page aligned MMIO regions.
*/
if ( ((enmType & ~(PCI_ADDRESS_SPACE_BAR64 | PCI_ADDRESS_SPACE_MEM_PREFETCH)) == PCI_ADDRESS_SPACE_MEM)
&& cbRegion != RT_ALIGN_32(cbRegion, PAGE_SIZE))
{
Log(("pdmR3DevHlp_PCIIORegionRegister: caller='%s'/%d: aligning cbRegion %#x -> %#x\n",
pDevIns->pReg->szName, pDevIns->iInstance, cbRegion, RT_ALIGN_32(cbRegion, PAGE_SIZE)));
cbRegion = RT_ALIGN_32(cbRegion, PAGE_SIZE);
}
/*
* For registering PCI MMIO memory or PCI I/O memory, the size of the region must be a power of 2!
*/
int iLastSet = ASMBitLastSetU32(cbRegion);
Assert(iLastSet > 0);
uint32_t cbRegionAligned = RT_BIT_32(iLastSet - 1);
if (cbRegion > cbRegionAligned)
cbRegion = cbRegionAligned * 2; /* round up */
PPDMPCIBUS pBus = pDevIns->Internal.s.pPciBusR3;
Assert(pBus);
pdmLock(pVM);
rc = pBus->pfnIORegionRegisterR3(pBus->pDevInsR3, pPciDev, iRegion, cbRegion, enmType, pfnCallback);
pdmUnlock(pVM);
}
else
{
AssertMsgFailed(("No PCI device registered!\n"));
rc = VERR_PDM_NOT_PCI_DEVICE;
}
LogFlow(("pdmR3DevHlp_PCIIORegionRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPCISetConfigCallbacks} */
static DECLCALLBACK(void) pdmR3DevHlp_PCISetConfigCallbacks(PPDMDEVINS pDevIns, PPCIDEVICE pPciDev, PFNPCICONFIGREAD pfnRead, PPFNPCICONFIGREAD ppfnReadOld,
PFNPCICONFIGWRITE pfnWrite, PPFNPCICONFIGWRITE ppfnWriteOld)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_PCISetConfigCallbacks: caller='%s'/%d: pPciDev=%p pfnRead=%p ppfnReadOld=%p pfnWrite=%p ppfnWriteOld=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pPciDev, pfnRead, ppfnReadOld, pfnWrite, ppfnWriteOld));
/*
* Validate input and resolve defaults.
*/
AssertPtr(pfnRead);
AssertPtr(pfnWrite);
AssertPtrNull(ppfnReadOld);
AssertPtrNull(ppfnWriteOld);
AssertPtrNull(pPciDev);
if (!pPciDev)
pPciDev = pDevIns->Internal.s.pPciDeviceR3;
AssertReleaseMsg(pPciDev, ("You must register your device first!\n"));
PPDMPCIBUS pBus = pDevIns->Internal.s.pPciBusR3;
AssertRelease(pBus);
AssertRelease(VMR3GetState(pVM) != VMSTATE_RUNNING);
/*
* Do the job.
*/
pdmLock(pVM);
pBus->pfnSetConfigCallbacksR3(pBus->pDevInsR3, pPciDev, pfnRead, ppfnReadOld, pfnWrite, ppfnWriteOld);
pdmUnlock(pVM);
LogFlow(("pdmR3DevHlp_PCISetConfigCallbacks: caller='%s'/%d: returns void\n", pDevIns->pReg->szName, pDevIns->iInstance));
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPCIPhysRead} */
static DECLCALLBACK(int) pdmR3DevHlp_PCIPhysRead(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, void *pvBuf, size_t cbRead)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
#ifndef PDM_DO_NOT_RESPECT_PCI_BM_BIT
/*
* Just check the busmaster setting here and forward the request to the generic read helper.
*/
PPCIDEVICE pPciDev = pDevIns->Internal.s.pPciDeviceR3;
AssertReleaseMsg(pPciDev, ("No PCI device registered!\n"));
if (!PCIDevIsBusmaster(pPciDev))
{
Log(("pdmR3DevHlp_PCIPhysRead: caller='%s'/%d: returns %Rrc - Not bus master! GCPhys=%RGp cbRead=%#zx\n",
pDevIns->pReg->szName, pDevIns->iInstance, VERR_PDM_NOT_PCI_BUS_MASTER, GCPhys, cbRead));
return VERR_PDM_NOT_PCI_BUS_MASTER;
}
#endif
return pDevIns->pHlpR3->pfnPhysRead(pDevIns, GCPhys, pvBuf, cbRead);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPCIPhysRead} */
static DECLCALLBACK(int) pdmR3DevHlp_PCIPhysWrite(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, const void *pvBuf, size_t cbWrite)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
#ifndef PDM_DO_NOT_RESPECT_PCI_BM_BIT
/*
* Just check the busmaster setting here and forward the request to the generic read helper.
*/
PPCIDEVICE pPciDev = pDevIns->Internal.s.pPciDeviceR3;
AssertReleaseMsg(pPciDev, ("No PCI device registered!\n"));
if (!PCIDevIsBusmaster(pPciDev))
{
Log(("pdmR3DevHlp_PCIPhysWrite: caller='%s'/%d: returns %Rrc - Not bus master! GCPhys=%RGp cbWrite=%#zx\n",
pDevIns->pReg->szName, pDevIns->iInstance, VERR_PDM_NOT_PCI_BUS_MASTER, GCPhys, cbWrite));
return VERR_PDM_NOT_PCI_BUS_MASTER;
}
#endif
return pDevIns->pHlpR3->pfnPhysWrite(pDevIns, GCPhys, pvBuf, cbWrite);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPCISetIrq} */
static DECLCALLBACK(void) pdmR3DevHlp_PCISetIrq(PPDMDEVINS pDevIns, int iIrq, int iLevel)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_PCISetIrq: caller='%s'/%d: iIrq=%d iLevel=%d\n", pDevIns->pReg->szName, pDevIns->iInstance, iIrq, iLevel));
/*
* Validate input.
*/
Assert(iIrq == 0);
Assert((uint32_t)iLevel <= PDM_IRQ_LEVEL_FLIP_FLOP);
/*
* Must have a PCI device registered!
*/
PPCIDEVICE pPciDev = pDevIns->Internal.s.pPciDeviceR3;
if (pPciDev)
{
PPDMPCIBUS pBus = pDevIns->Internal.s.pPciBusR3; /** @todo the bus should be associated with the PCI device not the PDM device. */
Assert(pBus);
PVM pVM = pDevIns->Internal.s.pVMR3;
pdmLock(pVM);
uint32_t uTagSrc;
if (iLevel & PDM_IRQ_LEVEL_HIGH)
{
pDevIns->Internal.s.uLastIrqTag = uTagSrc = pdmCalcIrqTag(pVM, pDevIns->idTracing);
if (iLevel == PDM_IRQ_LEVEL_HIGH)
VBOXVMM_PDM_IRQ_HIGH(VMMGetCpu(pVM), RT_LOWORD(uTagSrc), RT_HIWORD(uTagSrc));
else
VBOXVMM_PDM_IRQ_HILO(VMMGetCpu(pVM), RT_LOWORD(uTagSrc), RT_HIWORD(uTagSrc));
}
else
uTagSrc = pDevIns->Internal.s.uLastIrqTag;
pBus->pfnSetIrqR3(pBus->pDevInsR3, pPciDev, iIrq, iLevel, uTagSrc);
if (iLevel == PDM_IRQ_LEVEL_LOW)
VBOXVMM_PDM_IRQ_LOW(VMMGetCpu(pVM), RT_LOWORD(uTagSrc), RT_HIWORD(uTagSrc));
pdmUnlock(pVM);
}
else
AssertReleaseMsgFailed(("No PCI device registered!\n"));
LogFlow(("pdmR3DevHlp_PCISetIrq: caller='%s'/%d: returns void\n", pDevIns->pReg->szName, pDevIns->iInstance));
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPCISetIrqNoWait} */
static DECLCALLBACK(void) pdmR3DevHlp_PCISetIrqNoWait(PPDMDEVINS pDevIns, int iIrq, int iLevel)
{
pdmR3DevHlp_PCISetIrq(pDevIns, iIrq, iLevel);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPCIRegisterMsi} */
static DECLCALLBACK(int) pdmR3DevHlp_PCIRegisterMsi(PPDMDEVINS pDevIns, PPDMMSIREG pMsiReg)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_PCIRegisterMsi: caller='%s'/%d: %d MSI vectors %d MSI-X vectors\n", pDevIns->pReg->szName, pDevIns->iInstance, pMsiReg->cMsiVectors,pMsiReg->cMsixVectors ));
int rc = VINF_SUCCESS;
/*
* Must have a PCI device registered!
*/
PPCIDEVICE pPciDev = pDevIns->Internal.s.pPciDeviceR3;
if (pPciDev)
{
PPDMPCIBUS pBus = pDevIns->Internal.s.pPciBusR3; /** @todo the bus should be associated with the PCI device not the PDM device. */
Assert(pBus);
PVM pVM = pDevIns->Internal.s.pVMR3;
pdmLock(pVM);
if (pBus->pfnRegisterMsiR3)
rc = pBus->pfnRegisterMsiR3(pBus->pDevInsR3, pPciDev, pMsiReg);
else
rc = VERR_NOT_IMPLEMENTED;
pdmUnlock(pVM);
}
else
AssertReleaseMsgFailed(("No PCI device registered!\n"));
LogFlow(("pdmR3DevHlp_PCISetIrq: caller='%s'/%d: returns void\n", pDevIns->pReg->szName, pDevIns->iInstance));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnISASetIrq} */
static DECLCALLBACK(void) pdmR3DevHlp_ISASetIrq(PPDMDEVINS pDevIns, int iIrq, int iLevel)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_ISASetIrq: caller='%s'/%d: iIrq=%d iLevel=%d\n", pDevIns->pReg->szName, pDevIns->iInstance, iIrq, iLevel));
/*
* Validate input.
*/
Assert(iIrq < 16);
Assert((uint32_t)iLevel <= PDM_IRQ_LEVEL_FLIP_FLOP);
PVM pVM = pDevIns->Internal.s.pVMR3;
/*
* Do the job.
*/
pdmLock(pVM);
uint32_t uTagSrc;
if (iLevel & PDM_IRQ_LEVEL_HIGH)
{
pDevIns->Internal.s.uLastIrqTag = uTagSrc = pdmCalcIrqTag(pVM, pDevIns->idTracing);
if (iLevel == PDM_IRQ_LEVEL_HIGH)
VBOXVMM_PDM_IRQ_HIGH(VMMGetCpu(pVM), RT_LOWORD(uTagSrc), RT_HIWORD(uTagSrc));
else
VBOXVMM_PDM_IRQ_HILO(VMMGetCpu(pVM), RT_LOWORD(uTagSrc), RT_HIWORD(uTagSrc));
}
else
uTagSrc = pDevIns->Internal.s.uLastIrqTag;
PDMIsaSetIrq(pVM, iIrq, iLevel, uTagSrc); /* (The API takes the lock recursively.) */
if (iLevel == PDM_IRQ_LEVEL_LOW)
VBOXVMM_PDM_IRQ_LOW(VMMGetCpu(pVM), RT_LOWORD(uTagSrc), RT_HIWORD(uTagSrc));
pdmUnlock(pVM);
LogFlow(("pdmR3DevHlp_ISASetIrq: caller='%s'/%d: returns void\n", pDevIns->pReg->szName, pDevIns->iInstance));
}
/** @interface_method_impl{PDMDEVHLPR3,pfnISASetIrqNoWait} */
static DECLCALLBACK(void) pdmR3DevHlp_ISASetIrqNoWait(PPDMDEVINS pDevIns, int iIrq, int iLevel)
{
pdmR3DevHlp_ISASetIrq(pDevIns, iIrq, iLevel);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnDriverAttach} */
static DECLCALLBACK(int) pdmR3DevHlp_DriverAttach(PPDMDEVINS pDevIns, uint32_t iLun, PPDMIBASE pBaseInterface, PPDMIBASE *ppBaseInterface, const char *pszDesc)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_DriverAttach: caller='%s'/%d: iLun=%d pBaseInterface=%p ppBaseInterface=%p pszDesc=%p:{%s}\n",
pDevIns->pReg->szName, pDevIns->iInstance, iLun, pBaseInterface, ppBaseInterface, pszDesc, pszDesc));
/*
* Lookup the LUN, it might already be registered.
*/
PPDMLUN pLunPrev = NULL;
PPDMLUN pLun = pDevIns->Internal.s.pLunsR3;
for (; pLun; pLunPrev = pLun, pLun = pLun->pNext)
if (pLun->iLun == iLun)
break;
/*
* Create the LUN if if wasn't found, else check if driver is already attached to it.
*/
if (!pLun)
{
if ( !pBaseInterface
|| !pszDesc
|| !*pszDesc)
{
Assert(pBaseInterface);
Assert(pszDesc || *pszDesc);
return VERR_INVALID_PARAMETER;
}
pLun = (PPDMLUN)MMR3HeapAlloc(pVM, MM_TAG_PDM_LUN, sizeof(*pLun));
if (!pLun)
return VERR_NO_MEMORY;
pLun->iLun = iLun;
pLun->pNext = pLunPrev ? pLunPrev->pNext : NULL;
pLun->pTop = NULL;
pLun->pBottom = NULL;
pLun->pDevIns = pDevIns;
pLun->pUsbIns = NULL;
pLun->pszDesc = pszDesc;
pLun->pBase = pBaseInterface;
if (!pLunPrev)
pDevIns->Internal.s.pLunsR3 = pLun;
else
pLunPrev->pNext = pLun;
Log(("pdmR3DevHlp_DriverAttach: Registered LUN#%d '%s' with device '%s'/%d.\n",
iLun, pszDesc, pDevIns->pReg->szName, pDevIns->iInstance));
}
else if (pLun->pTop)
{
AssertMsgFailed(("Already attached! The device should keep track of such things!\n"));
LogFlow(("pdmR3DevHlp_DriverAttach: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_PDM_DRIVER_ALREADY_ATTACHED));
return VERR_PDM_DRIVER_ALREADY_ATTACHED;
}
Assert(pLun->pBase == pBaseInterface);
/*
* Get the attached driver configuration.
*/
int rc;
PCFGMNODE pNode = CFGMR3GetChildF(pDevIns->Internal.s.pCfgHandle, "LUN#%u", iLun);
if (pNode)
rc = pdmR3DrvInstantiate(pVM, pNode, pBaseInterface, NULL /*pDrvAbove*/, pLun, ppBaseInterface);
else
rc = VERR_PDM_NO_ATTACHED_DRIVER;
LogFlow(("pdmR3DevHlp_DriverAttach: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnQueueCreate} */
static DECLCALLBACK(int) pdmR3DevHlp_QueueCreate(PPDMDEVINS pDevIns, size_t cbItem, uint32_t cItems, uint32_t cMilliesInterval,
PFNPDMQUEUEDEV pfnCallback, bool fGCEnabled, const char *pszName, PPDMQUEUE *ppQueue)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_QueueCreate: caller='%s'/%d: cbItem=%#x cItems=%#x cMilliesInterval=%u pfnCallback=%p fGCEnabled=%RTbool pszName=%p:{%s} ppQueue=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, cbItem, cItems, cMilliesInterval, pfnCallback, fGCEnabled, pszName, pszName, ppQueue));
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
if (pDevIns->iInstance > 0)
{
pszName = MMR3HeapAPrintf(pVM, MM_TAG_PDM_DEVICE_DESC, "%s_%u", pszName, pDevIns->iInstance);
AssertLogRelReturn(pszName, VERR_NO_MEMORY);
}
int rc = PDMR3QueueCreateDevice(pVM, pDevIns, cbItem, cItems, cMilliesInterval, pfnCallback, fGCEnabled, pszName, ppQueue);
LogFlow(("pdmR3DevHlp_QueueCreate: caller='%s'/%d: returns %Rrc *ppQueue=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, rc, *ppQueue));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnCritSectInit} */
static DECLCALLBACK(int) pdmR3DevHlp_CritSectInit(PPDMDEVINS pDevIns, PPDMCRITSECT pCritSect, RT_SRC_POS_DECL,
const char *pszNameFmt, va_list va)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_CritSectInit: caller='%s'/%d: pCritSect=%p pszNameFmt=%p:{%s}\n",
pDevIns->pReg->szName, pDevIns->iInstance, pCritSect, pszNameFmt, pszNameFmt));
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
int rc = pdmR3CritSectInitDevice(pVM, pDevIns, pCritSect, RT_SRC_POS_ARGS, pszNameFmt, va);
LogFlow(("pdmR3DevHlp_CritSectInit: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnCritSectGetNop} */
static DECLCALLBACK(PPDMCRITSECT) pdmR3DevHlp_CritSectGetNop(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
PPDMCRITSECT pCritSect = PDMR3CritSectGetNop(pVM);
LogFlow(("pdmR3DevHlp_CritSectGetNop: caller='%s'/%d: return %p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pCritSect));
return pCritSect;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnCritSectGetNopR0} */
static DECLCALLBACK(R0PTRTYPE(PPDMCRITSECT)) pdmR3DevHlp_CritSectGetNopR0(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
R0PTRTYPE(PPDMCRITSECT) pCritSect = PDMR3CritSectGetNopR0(pVM);
LogFlow(("pdmR3DevHlp_CritSectGetNopR0: caller='%s'/%d: return %RHv\n",
pDevIns->pReg->szName, pDevIns->iInstance, pCritSect));
return pCritSect;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnCritSectGetNopRC} */
static DECLCALLBACK(RCPTRTYPE(PPDMCRITSECT)) pdmR3DevHlp_CritSectGetNopRC(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
RCPTRTYPE(PPDMCRITSECT) pCritSect = PDMR3CritSectGetNopRC(pVM);
LogFlow(("pdmR3DevHlp_CritSectGetNopRC: caller='%s'/%d: return %RRv\n",
pDevIns->pReg->szName, pDevIns->iInstance, pCritSect));
return pCritSect;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnSetDeviceCritSect} */
static DECLCALLBACK(int) pdmR3DevHlp_SetDeviceCritSect(PPDMDEVINS pDevIns, PPDMCRITSECT pCritSect)
{
/*
* Validate input.
*
* Note! We only allow the automatically created default critical section
* to be replaced by this API.
*/
PDMDEV_ASSERT_DEVINS(pDevIns);
AssertPtrReturn(pCritSect, VERR_INVALID_POINTER);
LogFlow(("pdmR3DevHlp_SetDeviceCritSect: caller='%s'/%d: pCritSect=%p (%s)\n",
pDevIns->pReg->szName, pDevIns->iInstance, pCritSect, pCritSect->s.pszName));
AssertReturn(PDMCritSectIsInitialized(pCritSect), VERR_INVALID_PARAMETER);
PVM pVM = pDevIns->Internal.s.pVMR3;
AssertReturn(pCritSect->s.pVMR3 == pVM, VERR_INVALID_PARAMETER);
VM_ASSERT_EMT(pVM);
VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_WRONG_ORDER);
AssertReturn(pDevIns->pCritSectRoR3, VERR_PDM_DEV_IPE_1);
AssertReturn(pDevIns->pCritSectRoR3->s.fAutomaticDefaultCritsect, VERR_WRONG_ORDER);
AssertReturn(!pDevIns->pCritSectRoR3->s.fUsedByTimerOrSimilar, VERR_WRONG_ORDER);
AssertReturn(pDevIns->pCritSectRoR3 != pCritSect, VERR_INVALID_PARAMETER);
/*
* Replace the critical section and destroy the automatic default section.
*/
PPDMCRITSECT pOldCritSect = pDevIns->pCritSectRoR3;
pDevIns->pCritSectRoR3 = pCritSect;
if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0)
pDevIns->pCritSectRoR0 = MMHyperCCToR0(pVM, pDevIns->pCritSectRoR3);
else
Assert(pDevIns->pCritSectRoR0 == NIL_RTRCPTR);
if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC)
pDevIns->pCritSectRoRC = MMHyperCCToRC(pVM, pDevIns->pCritSectRoR3);
else
Assert(pDevIns->pCritSectRoRC == NIL_RTRCPTR);
PDMR3CritSectDelete(pOldCritSect);
if (pDevIns->pReg->fFlags & (PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0))
MMHyperFree(pVM, pOldCritSect);
else
MMR3HeapFree(pOldCritSect);
LogFlow(("pdmR3DevHlp_SetDeviceCritSect: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS));
return VINF_SUCCESS;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnThreadCreate} */
static DECLCALLBACK(int) pdmR3DevHlp_ThreadCreate(PPDMDEVINS pDevIns, PPPDMTHREAD ppThread, void *pvUser, PFNPDMTHREADDEV pfnThread,
PFNPDMTHREADWAKEUPDEV pfnWakeup, size_t cbStack, RTTHREADTYPE enmType, const char *pszName)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_ThreadCreate: caller='%s'/%d: ppThread=%p pvUser=%p pfnThread=%p pfnWakeup=%p cbStack=%#zx enmType=%d pszName=%p:{%s}\n",
pDevIns->pReg->szName, pDevIns->iInstance, ppThread, pvUser, pfnThread, pfnWakeup, cbStack, enmType, pszName, pszName));
int rc = pdmR3ThreadCreateDevice(pDevIns->Internal.s.pVMR3, pDevIns, ppThread, pvUser, pfnThread, pfnWakeup, cbStack, enmType, pszName);
LogFlow(("pdmR3DevHlp_ThreadCreate: caller='%s'/%d: returns %Rrc *ppThread=%RTthrd\n", pDevIns->pReg->szName, pDevIns->iInstance,
rc, *ppThread));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnSetAsyncNotification} */
static DECLCALLBACK(int) pdmR3DevHlp_SetAsyncNotification(PPDMDEVINS pDevIns, PFNPDMDEVASYNCNOTIFY pfnAsyncNotify)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT0(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_SetAsyncNotification: caller='%s'/%d: pfnAsyncNotify=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pfnAsyncNotify));
int rc = VINF_SUCCESS;
AssertStmt(pfnAsyncNotify, rc = VERR_INVALID_PARAMETER);
AssertStmt(!pDevIns->Internal.s.pfnAsyncNotify, rc = VERR_WRONG_ORDER);
AssertStmt(pDevIns->Internal.s.fIntFlags & (PDMDEVINSINT_FLAGS_SUSPENDED | PDMDEVINSINT_FLAGS_RESET), rc = VERR_WRONG_ORDER);
VMSTATE enmVMState = VMR3GetState(pDevIns->Internal.s.pVMR3);
AssertStmt( enmVMState == VMSTATE_SUSPENDING
|| enmVMState == VMSTATE_SUSPENDING_EXT_LS
|| enmVMState == VMSTATE_SUSPENDING_LS
|| enmVMState == VMSTATE_RESETTING
|| enmVMState == VMSTATE_RESETTING_LS
|| enmVMState == VMSTATE_POWERING_OFF
|| enmVMState == VMSTATE_POWERING_OFF_LS,
rc = VERR_INVALID_STATE);
if (RT_SUCCESS(rc))
pDevIns->Internal.s.pfnAsyncNotify = pfnAsyncNotify;
LogFlow(("pdmR3DevHlp_SetAsyncNotification: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnAsyncNotificationCompleted} */
static DECLCALLBACK(void) pdmR3DevHlp_AsyncNotificationCompleted(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VMSTATE enmVMState = VMR3GetState(pVM);
if ( enmVMState == VMSTATE_SUSPENDING
|| enmVMState == VMSTATE_SUSPENDING_EXT_LS
|| enmVMState == VMSTATE_SUSPENDING_LS
|| enmVMState == VMSTATE_RESETTING
|| enmVMState == VMSTATE_RESETTING_LS
|| enmVMState == VMSTATE_POWERING_OFF
|| enmVMState == VMSTATE_POWERING_OFF_LS)
{
LogFlow(("pdmR3DevHlp_AsyncNotificationCompleted: caller='%s'/%d:\n", pDevIns->pReg->szName, pDevIns->iInstance));
VMR3AsyncPdmNotificationWakeupU(pVM->pUVM);
}
else
LogFlow(("pdmR3DevHlp_AsyncNotificationCompleted: caller='%s'/%d: enmVMState=%d\n", pDevIns->pReg->szName, pDevIns->iInstance, enmVMState));
}
/** @interface_method_impl{PDMDEVHLPR3,pfnRTCRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_RTCRegister(PPDMDEVINS pDevIns, PCPDMRTCREG pRtcReg, PCPDMRTCHLP *ppRtcHlp)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_RTCRegister: caller='%s'/%d: pRtcReg=%p:{.u32Version=%#x, .pfnWrite=%p, .pfnRead=%p} ppRtcHlp=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pRtcReg, pRtcReg->u32Version, pRtcReg->pfnWrite,
pRtcReg->pfnWrite, ppRtcHlp));
/*
* Validate input.
*/
if (pRtcReg->u32Version != PDM_RTCREG_VERSION)
{
AssertMsgFailed(("u32Version=%#x expected %#x\n", pRtcReg->u32Version,
PDM_RTCREG_VERSION));
LogFlow(("pdmR3DevHlp_RTCRegister: caller='%s'/%d: returns %Rrc (version)\n",
pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( !pRtcReg->pfnWrite
|| !pRtcReg->pfnRead)
{
Assert(pRtcReg->pfnWrite);
Assert(pRtcReg->pfnRead);
LogFlow(("pdmR3DevHlp_RTCRegister: caller='%s'/%d: returns %Rrc (callbacks)\n",
pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if (!ppRtcHlp)
{
Assert(ppRtcHlp);
LogFlow(("pdmR3DevHlp_RTCRegister: caller='%s'/%d: returns %Rrc (ppRtcHlp)\n",
pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/*
* Only one DMA device.
*/
PVM pVM = pDevIns->Internal.s.pVMR3;
if (pVM->pdm.s.pRtc)
{
AssertMsgFailed(("Only one RTC device is supported!\n"));
LogFlow(("pdmR3DevHlp_RTCRegister: caller='%s'/%d: returns %Rrc\n",
pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/*
* Allocate and initialize pci bus structure.
*/
int rc = VINF_SUCCESS;
PPDMRTC pRtc = (PPDMRTC)MMR3HeapAlloc(pDevIns->Internal.s.pVMR3, MM_TAG_PDM_DEVICE, sizeof(*pRtc));
if (pRtc)
{
pRtc->pDevIns = pDevIns;
pRtc->Reg = *pRtcReg;
pVM->pdm.s.pRtc = pRtc;
/* set the helper pointer. */
*ppRtcHlp = &g_pdmR3DevRtcHlp;
Log(("PDM: Registered RTC device '%s'/%d pDevIns=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pDevIns));
}
else
rc = VERR_NO_MEMORY;
LogFlow(("pdmR3DevHlp_RTCRegister: caller='%s'/%d: returns %Rrc\n",
pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnDMARegister} */
static DECLCALLBACK(int) pdmR3DevHlp_DMARegister(PPDMDEVINS pDevIns, unsigned uChannel, PFNDMATRANSFERHANDLER pfnTransferHandler, void *pvUser)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_DMARegister: caller='%s'/%d: uChannel=%d pfnTransferHandler=%p pvUser=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, uChannel, pfnTransferHandler, pvUser));
int rc = VINF_SUCCESS;
if (pVM->pdm.s.pDmac)
pVM->pdm.s.pDmac->Reg.pfnRegister(pVM->pdm.s.pDmac->pDevIns, uChannel, pfnTransferHandler, pvUser);
else
{
AssertMsgFailed(("Configuration error: No DMAC controller available. This could be related to init order too!\n"));
rc = VERR_PDM_NO_DMAC_INSTANCE;
}
LogFlow(("pdmR3DevHlp_DMARegister: caller='%s'/%d: returns %Rrc\n",
pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnDMAReadMemory} */
static DECLCALLBACK(int) pdmR3DevHlp_DMAReadMemory(PPDMDEVINS pDevIns, unsigned uChannel, void *pvBuffer, uint32_t off, uint32_t cbBlock, uint32_t *pcbRead)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_DMAReadMemory: caller='%s'/%d: uChannel=%d pvBuffer=%p off=%#x cbBlock=%#x pcbRead=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, uChannel, pvBuffer, off, cbBlock, pcbRead));
int rc = VINF_SUCCESS;
if (pVM->pdm.s.pDmac)
{
uint32_t cb = pVM->pdm.s.pDmac->Reg.pfnReadMemory(pVM->pdm.s.pDmac->pDevIns, uChannel, pvBuffer, off, cbBlock);
if (pcbRead)
*pcbRead = cb;
}
else
{
AssertMsgFailed(("Configuration error: No DMAC controller available. This could be related to init order too!\n"));
rc = VERR_PDM_NO_DMAC_INSTANCE;
}
LogFlow(("pdmR3DevHlp_DMAReadMemory: caller='%s'/%d: returns %Rrc\n",
pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnDMAWriteMemory} */
static DECLCALLBACK(int) pdmR3DevHlp_DMAWriteMemory(PPDMDEVINS pDevIns, unsigned uChannel, const void *pvBuffer, uint32_t off, uint32_t cbBlock, uint32_t *pcbWritten)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_DMAWriteMemory: caller='%s'/%d: uChannel=%d pvBuffer=%p off=%#x cbBlock=%#x pcbWritten=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, uChannel, pvBuffer, off, cbBlock, pcbWritten));
int rc = VINF_SUCCESS;
if (pVM->pdm.s.pDmac)
{
uint32_t cb = pVM->pdm.s.pDmac->Reg.pfnWriteMemory(pVM->pdm.s.pDmac->pDevIns, uChannel, pvBuffer, off, cbBlock);
if (pcbWritten)
*pcbWritten = cb;
}
else
{
AssertMsgFailed(("Configuration error: No DMAC controller available. This could be related to init order too!\n"));
rc = VERR_PDM_NO_DMAC_INSTANCE;
}
LogFlow(("pdmR3DevHlp_DMAWriteMemory: caller='%s'/%d: returns %Rrc\n",
pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnDMASetDREQ} */
static DECLCALLBACK(int) pdmR3DevHlp_DMASetDREQ(PPDMDEVINS pDevIns, unsigned uChannel, unsigned uLevel)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_DMASetDREQ: caller='%s'/%d: uChannel=%d uLevel=%d\n",
pDevIns->pReg->szName, pDevIns->iInstance, uChannel, uLevel));
int rc = VINF_SUCCESS;
if (pVM->pdm.s.pDmac)
pVM->pdm.s.pDmac->Reg.pfnSetDREQ(pVM->pdm.s.pDmac->pDevIns, uChannel, uLevel);
else
{
AssertMsgFailed(("Configuration error: No DMAC controller available. This could be related to init order too!\n"));
rc = VERR_PDM_NO_DMAC_INSTANCE;
}
LogFlow(("pdmR3DevHlp_DMASetDREQ: caller='%s'/%d: returns %Rrc\n",
pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnDMAGetChannelMode} */
static DECLCALLBACK(uint8_t) pdmR3DevHlp_DMAGetChannelMode(PPDMDEVINS pDevIns, unsigned uChannel)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_DMAGetChannelMode: caller='%s'/%d: uChannel=%d\n",
pDevIns->pReg->szName, pDevIns->iInstance, uChannel));
uint8_t u8Mode;
if (pVM->pdm.s.pDmac)
u8Mode = pVM->pdm.s.pDmac->Reg.pfnGetChannelMode(pVM->pdm.s.pDmac->pDevIns, uChannel);
else
{
AssertMsgFailed(("Configuration error: No DMAC controller available. This could be related to init order too!\n"));
u8Mode = 3 << 2 /* illegal mode type */;
}
LogFlow(("pdmR3DevHlp_DMAGetChannelMode: caller='%s'/%d: returns %#04x\n",
pDevIns->pReg->szName, pDevIns->iInstance, u8Mode));
return u8Mode;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnDMASchedule} */
static DECLCALLBACK(void) pdmR3DevHlp_DMASchedule(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_DMASchedule: caller='%s'/%d: VM_FF_PDM_DMA %d -> 1\n",
pDevIns->pReg->szName, pDevIns->iInstance, VM_FF_IS_SET(pVM, VM_FF_PDM_DMA)));
AssertMsg(pVM->pdm.s.pDmac, ("Configuration error: No DMAC controller available. This could be related to init order too!\n"));
VM_FF_SET(pVM, VM_FF_PDM_DMA);
#ifdef VBOX_WITH_REM
REMR3NotifyDmaPending(pVM);
#endif
VMR3NotifyGlobalFFU(pVM->pUVM, VMNOTIFYFF_FLAGS_DONE_REM);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnCMOSWrite} */
static DECLCALLBACK(int) pdmR3DevHlp_CMOSWrite(PPDMDEVINS pDevIns, unsigned iReg, uint8_t u8Value)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_CMOSWrite: caller='%s'/%d: iReg=%#04x u8Value=%#04x\n",
pDevIns->pReg->szName, pDevIns->iInstance, iReg, u8Value));
int rc;
if (pVM->pdm.s.pRtc)
{
PPDMDEVINS pDevInsRtc = pVM->pdm.s.pRtc->pDevIns;
rc = PDMCritSectEnter(pDevInsRtc->pCritSectRoR3, VERR_IGNORED);
if (RT_SUCCESS(rc))
{
rc = pVM->pdm.s.pRtc->Reg.pfnWrite(pDevInsRtc, iReg, u8Value);
PDMCritSectLeave(pDevInsRtc->pCritSectRoR3);
}
}
else
rc = VERR_PDM_NO_RTC_INSTANCE;
LogFlow(("pdmR3DevHlp_CMOSWrite: caller='%s'/%d: return %Rrc\n",
pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnCMOSRead} */
static DECLCALLBACK(int) pdmR3DevHlp_CMOSRead(PPDMDEVINS pDevIns, unsigned iReg, uint8_t *pu8Value)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_CMOSWrite: caller='%s'/%d: iReg=%#04x pu8Value=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, iReg, pu8Value));
int rc;
if (pVM->pdm.s.pRtc)
{
PPDMDEVINS pDevInsRtc = pVM->pdm.s.pRtc->pDevIns;
rc = PDMCritSectEnter(pDevInsRtc->pCritSectRoR3, VERR_IGNORED);
if (RT_SUCCESS(rc))
{
rc = pVM->pdm.s.pRtc->Reg.pfnRead(pDevInsRtc, iReg, pu8Value);
PDMCritSectLeave(pDevInsRtc->pCritSectRoR3);
}
}
else
rc = VERR_PDM_NO_RTC_INSTANCE;
LogFlow(("pdmR3DevHlp_CMOSWrite: caller='%s'/%d: return %Rrc\n",
pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnAssertEMT} */
static DECLCALLBACK(bool) pdmR3DevHlp_AssertEMT(PPDMDEVINS pDevIns, const char *pszFile, unsigned iLine, const char *pszFunction)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
if (VM_IS_EMT(pDevIns->Internal.s.pVMR3))
return true;
char szMsg[100];
RTStrPrintf(szMsg, sizeof(szMsg), "AssertEMT '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance);
RTAssertMsg1Weak(szMsg, iLine, pszFile, pszFunction);
AssertBreakpoint();
return false;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnAssertOther} */
static DECLCALLBACK(bool) pdmR3DevHlp_AssertOther(PPDMDEVINS pDevIns, const char *pszFile, unsigned iLine, const char *pszFunction)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
if (!VM_IS_EMT(pDevIns->Internal.s.pVMR3))
return true;
char szMsg[100];
RTStrPrintf(szMsg, sizeof(szMsg), "AssertOther '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance);
RTAssertMsg1Weak(szMsg, iLine, pszFile, pszFunction);
AssertBreakpoint();
return false;
}
/** @interface_method_impl{PDMDEVHLP,pfnLdrGetRCInterfaceSymbols} */
static DECLCALLBACK(int) pdmR3DevHlp_LdrGetRCInterfaceSymbols(PPDMDEVINS pDevIns, void *pvInterface, size_t cbInterface,
const char *pszSymPrefix, const char *pszSymList)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_PDMLdrGetRCInterfaceSymbols: caller='%s'/%d: pvInterface=%p cbInterface=%zu pszSymPrefix=%p:{%s} pszSymList=%p:{%s}\n",
pDevIns->pReg->szName, pDevIns->iInstance, pvInterface, cbInterface, pszSymPrefix, pszSymPrefix, pszSymList, pszSymList));
int rc;
if ( strncmp(pszSymPrefix, "dev", 3) == 0
&& RTStrIStr(pszSymPrefix + 3, pDevIns->pReg->szName) != NULL)
{
if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC)
rc = PDMR3LdrGetInterfaceSymbols(pDevIns->Internal.s.pVMR3,
pvInterface, cbInterface,
pDevIns->pReg->szRCMod, pDevIns->Internal.s.pDevR3->pszRCSearchPath,
pszSymPrefix, pszSymList,
false /*fRing0OrRC*/);
else
{
AssertMsgFailed(("Not a raw-mode enabled driver\n"));
rc = VERR_PERMISSION_DENIED;
}
}
else
{
AssertMsgFailed(("Invalid prefix '%s' for '%s'; must start with 'dev' and contain the driver name!\n",
pszSymPrefix, pDevIns->pReg->szName));
rc = VERR_INVALID_NAME;
}
LogFlow(("pdmR3DevHlp_PDMLdrGetRCInterfaceSymbols: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName,
pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLP,pfnLdrGetR0InterfaceSymbols} */
static DECLCALLBACK(int) pdmR3DevHlp_LdrGetR0InterfaceSymbols(PPDMDEVINS pDevIns, void *pvInterface, size_t cbInterface,
const char *pszSymPrefix, const char *pszSymList)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_PDMLdrGetR0InterfaceSymbols: caller='%s'/%d: pvInterface=%p cbInterface=%zu pszSymPrefix=%p:{%s} pszSymList=%p:{%s}\n",
pDevIns->pReg->szName, pDevIns->iInstance, pvInterface, cbInterface, pszSymPrefix, pszSymPrefix, pszSymList, pszSymList));
int rc;
if ( strncmp(pszSymPrefix, "dev", 3) == 0
&& RTStrIStr(pszSymPrefix + 3, pDevIns->pReg->szName) != NULL)
{
if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0)
rc = PDMR3LdrGetInterfaceSymbols(pDevIns->Internal.s.pVMR3,
pvInterface, cbInterface,
pDevIns->pReg->szR0Mod, pDevIns->Internal.s.pDevR3->pszR0SearchPath,
pszSymPrefix, pszSymList,
true /*fRing0OrRC*/);
else
{
AssertMsgFailed(("Not a ring-0 enabled driver\n"));
rc = VERR_PERMISSION_DENIED;
}
}
else
{
AssertMsgFailed(("Invalid prefix '%s' for '%s'; must start with 'dev' and contain the driver name!\n",
pszSymPrefix, pDevIns->pReg->szName));
rc = VERR_INVALID_NAME;
}
LogFlow(("pdmR3DevHlp_PDMLdrGetR0InterfaceSymbols: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName,
pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLP,pfnCallR0} */
static DECLCALLBACK(int) pdmR3DevHlp_CallR0(PPDMDEVINS pDevIns, uint32_t uOperation, uint64_t u64Arg)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_CallR0: caller='%s'/%d: uOperation=%#x u64Arg=%#RX64\n",
pDevIns->pReg->szName, pDevIns->iInstance, uOperation, u64Arg));
/*
* Resolve the ring-0 entry point. There is not need to remember this like
* we do for drivers since this is mainly for construction time hacks and
* other things that aren't performance critical.
*/
int rc;
if (pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0)
{
char szSymbol[ sizeof("devR0") + sizeof(pDevIns->pReg->szName) + sizeof("ReqHandler")];
strcat(strcat(strcpy(szSymbol, "devR0"), pDevIns->pReg->szName), "ReqHandler");
szSymbol[sizeof("devR0") - 1] = RT_C_TO_UPPER(szSymbol[sizeof("devR0") - 1]);
PFNPDMDRVREQHANDLERR0 pfnReqHandlerR0;
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, szSymbol, &pfnReqHandlerR0);
if (RT_SUCCESS(rc))
{
/*
* Make the ring-0 call.
*/
PDMDEVICECALLREQHANDLERREQ Req;
Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
Req.Hdr.cbReq = sizeof(Req);
Req.pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
Req.pfnReqHandlerR0 = pfnReqHandlerR0;
Req.uOperation = uOperation;
Req.u32Alignment = 0;
Req.u64Arg = u64Arg;
rc = SUPR3CallVMMR0Ex(pVM->pVMR0, NIL_VMCPUID, VMMR0_DO_PDM_DEVICE_CALL_REQ_HANDLER, 0, &Req.Hdr);
}
else
pfnReqHandlerR0 = NIL_RTR0PTR;
}
else
rc = VERR_ACCESS_DENIED;
LogFlow(("pdmR3DevHlp_CallR0: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName,
pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLP,pfnVMGetSuspendReason} */
static DECLCALLBACK(VMSUSPENDREASON) pdmR3DevHlp_VMGetSuspendReason(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
VMSUSPENDREASON enmReason = VMR3GetSuspendReason(pVM->pUVM);
LogFlow(("pdmR3DevHlp_VMGetSuspendReason: caller='%s'/%d: returns %d\n",
pDevIns->pReg->szName, pDevIns->iInstance, enmReason));
return enmReason;
}
/** @interface_method_impl{PDMDEVHLP,pfnVMGetResumeReason} */
static DECLCALLBACK(VMRESUMEREASON) pdmR3DevHlp_VMGetResumeReason(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
VMRESUMEREASON enmReason = VMR3GetResumeReason(pVM->pUVM);
LogFlow(("pdmR3DevHlp_VMGetResumeReason: caller='%s'/%d: returns %d\n",
pDevIns->pReg->szName, pDevIns->iInstance, enmReason));
return enmReason;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnGetUVM} */
static DECLCALLBACK(PUVM) pdmR3DevHlp_GetUVM(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_GetUVM: caller='%s'/%d: returns %p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns->Internal.s.pVMR3));
return pDevIns->Internal.s.pVMR3->pUVM;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnGetVM} */
static DECLCALLBACK(PVM) pdmR3DevHlp_GetVM(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
LogFlow(("pdmR3DevHlp_GetVM: caller='%s'/%d: returns %p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns->Internal.s.pVMR3));
return pDevIns->Internal.s.pVMR3;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnGetVMCPU} */
static DECLCALLBACK(PVMCPU) pdmR3DevHlp_GetVMCPU(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_GetVMCPU: caller='%s'/%d for CPU %u\n", pDevIns->pReg->szName, pDevIns->iInstance, VMMGetCpuId(pDevIns->Internal.s.pVMR3)));
return VMMGetCpu(pDevIns->Internal.s.pVMR3);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnGetCurrentCpuId} */
static DECLCALLBACK(VMCPUID) pdmR3DevHlp_GetCurrentCpuId(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VMCPUID idCpu = VMMGetCpuId(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_GetCurrentCpuId: caller='%s'/%d for CPU %u\n", pDevIns->pReg->szName, pDevIns->iInstance, idCpu));
return idCpu;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPCIBusRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_PCIBusRegister(PPDMDEVINS pDevIns, PPDMPCIBUSREG pPciBusReg, PCPDMPCIHLPR3 *ppPciHlpR3)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: pPciBusReg=%p:{.u32Version=%#x, .pfnRegisterR3=%p, .pfnIORegionRegisterR3=%p, "
".pfnSetIrqR3=%p, .pfnFakePCIBIOSR3=%p, .pszSetIrqRC=%p:{%s}, .pszSetIrqR0=%p:{%s}} ppPciHlpR3=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pPciBusReg, pPciBusReg->u32Version, pPciBusReg->pfnRegisterR3,
pPciBusReg->pfnIORegionRegisterR3, pPciBusReg->pfnSetIrqR3, pPciBusReg->pfnFakePCIBIOSR3,
pPciBusReg->pszSetIrqRC, pPciBusReg->pszSetIrqRC, pPciBusReg->pszSetIrqR0, pPciBusReg->pszSetIrqR0, ppPciHlpR3));
/*
* Validate the structure.
*/
if (pPciBusReg->u32Version != PDM_PCIBUSREG_VERSION)
{
AssertMsgFailed(("u32Version=%#x expected %#x\n", pPciBusReg->u32Version, PDM_PCIBUSREG_VERSION));
LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( !pPciBusReg->pfnRegisterR3
|| !pPciBusReg->pfnIORegionRegisterR3
|| !pPciBusReg->pfnSetIrqR3
|| (!pPciBusReg->pfnFakePCIBIOSR3 && !pVM->pdm.s.aPciBuses[0].pDevInsR3)) /* Only the first bus needs to do the BIOS work. */
{
Assert(pPciBusReg->pfnRegisterR3);
Assert(pPciBusReg->pfnIORegionRegisterR3);
Assert(pPciBusReg->pfnSetIrqR3);
Assert(pPciBusReg->pfnFakePCIBIOSR3);
LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: returns %Rrc (R3 callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( pPciBusReg->pszSetIrqRC
&& !VALID_PTR(pPciBusReg->pszSetIrqRC))
{
Assert(VALID_PTR(pPciBusReg->pszSetIrqRC));
LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: returns %Rrc (GC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( pPciBusReg->pszSetIrqR0
&& !VALID_PTR(pPciBusReg->pszSetIrqR0))
{
Assert(VALID_PTR(pPciBusReg->pszSetIrqR0));
LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: returns %Rrc (GC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if (!ppPciHlpR3)
{
Assert(ppPciHlpR3);
LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: returns %Rrc (ppPciHlpR3)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/*
* Find free PCI bus entry.
*/
unsigned iBus = 0;
for (iBus = 0; iBus < RT_ELEMENTS(pVM->pdm.s.aPciBuses); iBus++)
if (!pVM->pdm.s.aPciBuses[iBus].pDevInsR3)
break;
if (iBus >= RT_ELEMENTS(pVM->pdm.s.aPciBuses))
{
AssertMsgFailed(("Too many PCI buses. Max=%u\n", RT_ELEMENTS(pVM->pdm.s.aPciBuses)));
LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: returns %Rrc (pci bus)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
PPDMPCIBUS pPciBus = &pVM->pdm.s.aPciBuses[iBus];
/*
* Resolve and init the RC bits.
*/
if (pPciBusReg->pszSetIrqRC)
{
int rc = pdmR3DevGetSymbolRCLazy(pDevIns, pPciBusReg->pszSetIrqRC, &pPciBus->pfnSetIrqRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pPciBusReg->pszSetIrqRC, rc));
if (RT_FAILURE(rc))
{
LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
pPciBus->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
}
else
{
pPciBus->pfnSetIrqRC = 0;
pPciBus->pDevInsRC = 0;
}
/*
* Resolve and init the R0 bits.
*/
if (pPciBusReg->pszSetIrqR0)
{
int rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pPciBusReg->pszSetIrqR0, &pPciBus->pfnSetIrqR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pPciBusReg->pszSetIrqR0, rc));
if (RT_FAILURE(rc))
{
LogFlow(("pdmR3DevHlp_PCIRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
pPciBus->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
}
else
{
pPciBus->pfnSetIrqR0 = 0;
pPciBus->pDevInsR0 = 0;
}
/*
* Init the R3 bits.
*/
pPciBus->iBus = iBus;
pPciBus->pDevInsR3 = pDevIns;
pPciBus->pfnRegisterR3 = pPciBusReg->pfnRegisterR3;
pPciBus->pfnRegisterMsiR3 = pPciBusReg->pfnRegisterMsiR3;
pPciBus->pfnIORegionRegisterR3 = pPciBusReg->pfnIORegionRegisterR3;
pPciBus->pfnSetConfigCallbacksR3 = pPciBusReg->pfnSetConfigCallbacksR3;
pPciBus->pfnSetIrqR3 = pPciBusReg->pfnSetIrqR3;
pPciBus->pfnFakePCIBIOSR3 = pPciBusReg->pfnFakePCIBIOSR3;
Log(("PDM: Registered PCI bus device '%s'/%d pDevIns=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns));
/* set the helper pointer and return. */
*ppPciHlpR3 = &g_pdmR3DevPciHlp;
LogFlow(("pdmR3DevHlp_PCIBusRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS));
return VINF_SUCCESS;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPICRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_PICRegister(PPDMDEVINS pDevIns, PPDMPICREG pPicReg, PCPDMPICHLPR3 *ppPicHlpR3)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: pPicReg=%p:{.u32Version=%#x, .pfnSetIrqR3=%p, .pfnGetInterruptR3=%p, .pszGetIrqRC=%p:{%s}, .pszGetInterruptRC=%p:{%s}, .pszGetIrqR0=%p:{%s}, .pszGetInterruptR0=%p:{%s} } ppPicHlpR3=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pPicReg, pPicReg->u32Version, pPicReg->pfnSetIrqR3, pPicReg->pfnGetInterruptR3,
pPicReg->pszSetIrqRC, pPicReg->pszSetIrqRC, pPicReg->pszGetInterruptRC, pPicReg->pszGetInterruptRC,
pPicReg->pszSetIrqR0, pPicReg->pszSetIrqR0, pPicReg->pszGetInterruptR0, pPicReg->pszGetInterruptR0,
ppPicHlpR3));
/*
* Validate input.
*/
if (pPicReg->u32Version != PDM_PICREG_VERSION)
{
AssertMsgFailed(("u32Version=%#x expected %#x\n", pPicReg->u32Version, PDM_PICREG_VERSION));
LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( !pPicReg->pfnSetIrqR3
|| !pPicReg->pfnGetInterruptR3)
{
Assert(pPicReg->pfnSetIrqR3);
Assert(pPicReg->pfnGetInterruptR3);
LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc (R3 callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( ( pPicReg->pszSetIrqRC
|| pPicReg->pszGetInterruptRC)
&& ( !VALID_PTR(pPicReg->pszSetIrqRC)
|| !VALID_PTR(pPicReg->pszGetInterruptRC))
)
{
Assert(VALID_PTR(pPicReg->pszSetIrqRC));
Assert(VALID_PTR(pPicReg->pszGetInterruptRC));
LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc (RC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( pPicReg->pszSetIrqRC
&& !(pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC))
{
Assert(pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_RC);
LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc (RC flag)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( pPicReg->pszSetIrqR0
&& !(pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0))
{
Assert(pDevIns->pReg->fFlags & PDM_DEVREG_FLAGS_R0);
LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc (R0 flag)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if (!ppPicHlpR3)
{
Assert(ppPicHlpR3);
LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc (ppPicHlpR3)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/*
* Only one PIC device.
*/
PVM pVM = pDevIns->Internal.s.pVMR3;
if (pVM->pdm.s.Pic.pDevInsR3)
{
AssertMsgFailed(("Only one pic device is supported!\n"));
LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/*
* RC stuff.
*/
if (pPicReg->pszSetIrqRC)
{
int rc = pdmR3DevGetSymbolRCLazy(pDevIns, pPicReg->pszSetIrqRC, &pVM->pdm.s.Pic.pfnSetIrqRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pPicReg->pszSetIrqRC, rc));
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pPicReg->pszGetInterruptRC, &pVM->pdm.s.Pic.pfnGetInterruptRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pPicReg->pszGetInterruptRC, rc));
}
if (RT_FAILURE(rc))
{
LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
pVM->pdm.s.Pic.pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
}
else
{
pVM->pdm.s.Pic.pDevInsRC = 0;
pVM->pdm.s.Pic.pfnSetIrqRC = 0;
pVM->pdm.s.Pic.pfnGetInterruptRC = 0;
}
/*
* R0 stuff.
*/
if (pPicReg->pszSetIrqR0)
{
int rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pPicReg->pszSetIrqR0, &pVM->pdm.s.Pic.pfnSetIrqR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pPicReg->pszSetIrqR0, rc));
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pPicReg->pszGetInterruptR0, &pVM->pdm.s.Pic.pfnGetInterruptR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pPicReg->pszGetInterruptR0, rc));
}
if (RT_FAILURE(rc))
{
LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
pVM->pdm.s.Pic.pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
Assert(pVM->pdm.s.Pic.pDevInsR0);
}
else
{
pVM->pdm.s.Pic.pfnSetIrqR0 = 0;
pVM->pdm.s.Pic.pfnGetInterruptR0 = 0;
pVM->pdm.s.Pic.pDevInsR0 = 0;
}
/*
* R3 stuff.
*/
pVM->pdm.s.Pic.pDevInsR3 = pDevIns;
pVM->pdm.s.Pic.pfnSetIrqR3 = pPicReg->pfnSetIrqR3;
pVM->pdm.s.Pic.pfnGetInterruptR3 = pPicReg->pfnGetInterruptR3;
Log(("PDM: Registered PIC device '%s'/%d pDevIns=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns));
/* set the helper pointer and return. */
*ppPicHlpR3 = &g_pdmR3DevPicHlp;
LogFlow(("pdmR3DevHlp_PICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS));
return VINF_SUCCESS;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnAPICRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_APICRegister(PPDMDEVINS pDevIns, PPDMAPICREG pApicReg, PCPDMAPICHLPR3 *ppApicHlpR3)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: pApicReg=%p:{.u32Version=%#x, .pfnGetInterruptR3=%p, .pfnSetBaseR3=%p, .pfnGetBaseR3=%p, "
".pfnSetTPRR3=%p, .pfnGetTPRR3=%p, .pfnWriteMSR3=%p, .pfnReadMSR3=%p, .pfnBusDeliverR3=%p, .pfnLocalInterruptR3=%p .pfnGetTimerFreqR3=%p, pszGetInterruptRC=%p:{%s}, pszSetBaseRC=%p:{%s}, pszGetBaseRC=%p:{%s}, "
".pszSetTPRRC=%p:{%s}, .pszGetTPRRC=%p:{%s}, .pszWriteMSRRC=%p:{%s}, .pszReadMSRRC=%p:{%s}, .pszBusDeliverRC=%p:{%s}, .pszLocalInterruptRC=%p:{%s}, .pszGetTimerFreqRC=%p:{%s}} ppApicHlpR3=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pApicReg, pApicReg->u32Version, pApicReg->pfnGetInterruptR3, pApicReg->pfnSetBaseR3,
pApicReg->pfnGetBaseR3, pApicReg->pfnSetTPRR3, pApicReg->pfnGetTPRR3, pApicReg->pfnWriteMSRR3, pApicReg->pfnReadMSRR3, pApicReg->pfnBusDeliverR3, pApicReg->pfnLocalInterruptR3, pApicReg->pfnGetTimerFreqR3, pApicReg->pszGetInterruptRC,
pApicReg->pszGetInterruptRC, pApicReg->pszSetBaseRC, pApicReg->pszSetBaseRC, pApicReg->pszGetBaseRC, pApicReg->pszGetBaseRC,
pApicReg->pszSetTPRRC, pApicReg->pszSetTPRRC, pApicReg->pszGetTPRRC, pApicReg->pszGetTPRRC, pApicReg->pszWriteMSRRC, pApicReg->pszWriteMSRRC, pApicReg->pszReadMSRRC, pApicReg->pszReadMSRRC, pApicReg->pszBusDeliverRC,
pApicReg->pszBusDeliverRC, pApicReg->pszLocalInterruptRC, pApicReg->pszLocalInterruptRC, pApicReg->pszGetTimerFreqRC, pApicReg->pszGetTimerFreqRC, ppApicHlpR3));
/*
* Validate input.
*/
if (pApicReg->u32Version != PDM_APICREG_VERSION)
{
AssertMsgFailed(("u32Version=%#x expected %#x\n", pApicReg->u32Version, PDM_APICREG_VERSION));
LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( !pApicReg->pfnGetInterruptR3
|| !pApicReg->pfnHasPendingIrqR3
|| !pApicReg->pfnSetBaseR3
|| !pApicReg->pfnGetBaseR3
|| !pApicReg->pfnSetTPRR3
|| !pApicReg->pfnGetTPRR3
|| !pApicReg->pfnWriteMSRR3
|| !pApicReg->pfnReadMSRR3
|| !pApicReg->pfnBusDeliverR3
|| !pApicReg->pfnLocalInterruptR3
|| !pApicReg->pfnGetTimerFreqR3)
{
Assert(pApicReg->pfnGetInterruptR3);
Assert(pApicReg->pfnHasPendingIrqR3);
Assert(pApicReg->pfnSetBaseR3);
Assert(pApicReg->pfnGetBaseR3);
Assert(pApicReg->pfnSetTPRR3);
Assert(pApicReg->pfnGetTPRR3);
Assert(pApicReg->pfnWriteMSRR3);
Assert(pApicReg->pfnReadMSRR3);
Assert(pApicReg->pfnBusDeliverR3);
Assert(pApicReg->pfnLocalInterruptR3);
Assert(pApicReg->pfnGetTimerFreqR3);
LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc (R3 callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( ( pApicReg->pszGetInterruptRC
|| pApicReg->pszHasPendingIrqRC
|| pApicReg->pszSetBaseRC
|| pApicReg->pszGetBaseRC
|| pApicReg->pszSetTPRRC
|| pApicReg->pszGetTPRRC
|| pApicReg->pszWriteMSRRC
|| pApicReg->pszReadMSRRC
|| pApicReg->pszBusDeliverRC
|| pApicReg->pszLocalInterruptRC
|| pApicReg->pszGetTimerFreqRC)
&& ( !VALID_PTR(pApicReg->pszGetInterruptRC)
|| !VALID_PTR(pApicReg->pszHasPendingIrqRC)
|| !VALID_PTR(pApicReg->pszSetBaseRC)
|| !VALID_PTR(pApicReg->pszGetBaseRC)
|| !VALID_PTR(pApicReg->pszSetTPRRC)
|| !VALID_PTR(pApicReg->pszGetTPRRC)
|| !VALID_PTR(pApicReg->pszWriteMSRRC)
|| !VALID_PTR(pApicReg->pszReadMSRRC)
|| !VALID_PTR(pApicReg->pszBusDeliverRC)
|| !VALID_PTR(pApicReg->pszLocalInterruptRC)
|| !VALID_PTR(pApicReg->pszGetTimerFreqRC))
)
{
Assert(VALID_PTR(pApicReg->pszGetInterruptRC));
Assert(VALID_PTR(pApicReg->pszHasPendingIrqRC));
Assert(VALID_PTR(pApicReg->pszSetBaseRC));
Assert(VALID_PTR(pApicReg->pszGetBaseRC));
Assert(VALID_PTR(pApicReg->pszSetTPRRC));
Assert(VALID_PTR(pApicReg->pszGetTPRRC));
Assert(VALID_PTR(pApicReg->pszReadMSRRC));
Assert(VALID_PTR(pApicReg->pszWriteMSRRC));
Assert(VALID_PTR(pApicReg->pszBusDeliverRC));
Assert(VALID_PTR(pApicReg->pszLocalInterruptRC));
Assert(VALID_PTR(pApicReg->pszGetTimerFreqRC));
LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc (RC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( ( pApicReg->pszGetInterruptR0
|| pApicReg->pszHasPendingIrqR0
|| pApicReg->pszSetBaseR0
|| pApicReg->pszGetBaseR0
|| pApicReg->pszSetTPRR0
|| pApicReg->pszGetTPRR0
|| pApicReg->pszWriteMSRR0
|| pApicReg->pszReadMSRR0
|| pApicReg->pszBusDeliverR0
|| pApicReg->pszLocalInterruptR0
|| pApicReg->pszGetTimerFreqR0)
&& ( !VALID_PTR(pApicReg->pszGetInterruptR0)
|| !VALID_PTR(pApicReg->pszHasPendingIrqR0)
|| !VALID_PTR(pApicReg->pszSetBaseR0)
|| !VALID_PTR(pApicReg->pszGetBaseR0)
|| !VALID_PTR(pApicReg->pszSetTPRR0)
|| !VALID_PTR(pApicReg->pszGetTPRR0)
|| !VALID_PTR(pApicReg->pszReadMSRR0)
|| !VALID_PTR(pApicReg->pszWriteMSRR0)
|| !VALID_PTR(pApicReg->pszBusDeliverR0)
|| !VALID_PTR(pApicReg->pszLocalInterruptR0)
|| !VALID_PTR(pApicReg->pszGetTimerFreqR0))
)
{
Assert(VALID_PTR(pApicReg->pszGetInterruptR0));
Assert(VALID_PTR(pApicReg->pszHasPendingIrqR0));
Assert(VALID_PTR(pApicReg->pszSetBaseR0));
Assert(VALID_PTR(pApicReg->pszGetBaseR0));
Assert(VALID_PTR(pApicReg->pszSetTPRR0));
Assert(VALID_PTR(pApicReg->pszGetTPRR0));
Assert(VALID_PTR(pApicReg->pszReadMSRR0));
Assert(VALID_PTR(pApicReg->pszWriteMSRR0));
Assert(VALID_PTR(pApicReg->pszBusDeliverR0));
Assert(VALID_PTR(pApicReg->pszLocalInterruptR0));
Assert(VALID_PTR(pApicReg->pszGetTimerFreqR0));
LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc (R0 callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if (!ppApicHlpR3)
{
Assert(ppApicHlpR3);
LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc (ppApicHlpR3)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/*
* Only one APIC device. On SMP we have single logical device covering all LAPICs,
* as they need to communicate and share state easily.
*/
PVM pVM = pDevIns->Internal.s.pVMR3;
if (pVM->pdm.s.Apic.pDevInsR3)
{
AssertMsgFailed(("Only one apic device is supported!\n"));
LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/*
* Resolve & initialize the RC bits.
*/
if (pApicReg->pszGetInterruptRC)
{
int rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszGetInterruptRC, &pVM->pdm.s.Apic.pfnGetInterruptRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszGetInterruptRC, rc));
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszHasPendingIrqRC, &pVM->pdm.s.Apic.pfnHasPendingIrqRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszHasPendingIrqRC, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszSetBaseRC, &pVM->pdm.s.Apic.pfnSetBaseRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszSetBaseRC, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszGetBaseRC, &pVM->pdm.s.Apic.pfnGetBaseRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszGetBaseRC, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszSetTPRRC, &pVM->pdm.s.Apic.pfnSetTPRRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszSetTPRRC, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszGetTPRRC, &pVM->pdm.s.Apic.pfnGetTPRRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszGetTPRRC, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszWriteMSRRC, &pVM->pdm.s.Apic.pfnWriteMSRRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszWriteMSRRC, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszReadMSRRC, &pVM->pdm.s.Apic.pfnReadMSRRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszReadMSRRC, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszBusDeliverRC, &pVM->pdm.s.Apic.pfnBusDeliverRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszBusDeliverRC, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszLocalInterruptRC, &pVM->pdm.s.Apic.pfnLocalInterruptRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszLocalInterruptRC, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolRCLazy(pDevIns, pApicReg->pszGetTimerFreqRC, &pVM->pdm.s.Apic.pfnGetTimerFreqRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pApicReg->pszGetTimerFreqRC, rc));
}
if (RT_FAILURE(rc))
{
LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
pVM->pdm.s.Apic.pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
}
else
{
pVM->pdm.s.Apic.pDevInsRC = 0;
pVM->pdm.s.Apic.pfnGetInterruptRC = 0;
pVM->pdm.s.Apic.pfnHasPendingIrqRC = 0;
pVM->pdm.s.Apic.pfnSetBaseRC = 0;
pVM->pdm.s.Apic.pfnGetBaseRC = 0;
pVM->pdm.s.Apic.pfnSetTPRRC = 0;
pVM->pdm.s.Apic.pfnGetTPRRC = 0;
pVM->pdm.s.Apic.pfnWriteMSRRC = 0;
pVM->pdm.s.Apic.pfnReadMSRRC = 0;
pVM->pdm.s.Apic.pfnBusDeliverRC = 0;
pVM->pdm.s.Apic.pfnLocalInterruptRC = 0;
pVM->pdm.s.Apic.pfnGetTimerFreqRC = 0;
}
/*
* Resolve & initialize the R0 bits.
*/
if (pApicReg->pszGetInterruptR0)
{
int rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszGetInterruptR0, &pVM->pdm.s.Apic.pfnGetInterruptR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszGetInterruptR0, rc));
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszHasPendingIrqR0, &pVM->pdm.s.Apic.pfnHasPendingIrqR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszHasPendingIrqR0, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszSetBaseR0, &pVM->pdm.s.Apic.pfnSetBaseR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszSetBaseR0, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszGetBaseR0, &pVM->pdm.s.Apic.pfnGetBaseR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszGetBaseR0, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszSetTPRR0, &pVM->pdm.s.Apic.pfnSetTPRR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszSetTPRR0, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszGetTPRR0, &pVM->pdm.s.Apic.pfnGetTPRR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszGetTPRR0, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszWriteMSRR0, &pVM->pdm.s.Apic.pfnWriteMSRR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszWriteMSRR0, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszReadMSRR0, &pVM->pdm.s.Apic.pfnReadMSRR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszReadMSRR0, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszBusDeliverR0, &pVM->pdm.s.Apic.pfnBusDeliverR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszBusDeliverR0, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszLocalInterruptR0, &pVM->pdm.s.Apic.pfnLocalInterruptR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszLocalInterruptR0, rc));
}
if (RT_SUCCESS(rc))
{
rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pApicReg->pszGetTimerFreqR0, &pVM->pdm.s.Apic.pfnGetTimerFreqR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pApicReg->pszGetTimerFreqR0, rc));
}
if (RT_FAILURE(rc))
{
LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
pVM->pdm.s.Apic.pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
Assert(pVM->pdm.s.Apic.pDevInsR0);
}
else
{
pVM->pdm.s.Apic.pfnGetInterruptR0 = 0;
pVM->pdm.s.Apic.pfnHasPendingIrqR0 = 0;
pVM->pdm.s.Apic.pfnSetBaseR0 = 0;
pVM->pdm.s.Apic.pfnGetBaseR0 = 0;
pVM->pdm.s.Apic.pfnSetTPRR0 = 0;
pVM->pdm.s.Apic.pfnGetTPRR0 = 0;
pVM->pdm.s.Apic.pfnWriteMSRR0 = 0;
pVM->pdm.s.Apic.pfnReadMSRR0 = 0;
pVM->pdm.s.Apic.pfnBusDeliverR0 = 0;
pVM->pdm.s.Apic.pfnLocalInterruptR0 = 0;
pVM->pdm.s.Apic.pfnGetTimerFreqR0 = 0;
pVM->pdm.s.Apic.pDevInsR0 = 0;
}
/*
* Initialize the HC bits.
*/
pVM->pdm.s.Apic.pDevInsR3 = pDevIns;
pVM->pdm.s.Apic.pfnGetInterruptR3 = pApicReg->pfnGetInterruptR3;
pVM->pdm.s.Apic.pfnHasPendingIrqR3 = pApicReg->pfnHasPendingIrqR3;
pVM->pdm.s.Apic.pfnSetBaseR3 = pApicReg->pfnSetBaseR3;
pVM->pdm.s.Apic.pfnGetBaseR3 = pApicReg->pfnGetBaseR3;
pVM->pdm.s.Apic.pfnSetTPRR3 = pApicReg->pfnSetTPRR3;
pVM->pdm.s.Apic.pfnGetTPRR3 = pApicReg->pfnGetTPRR3;
pVM->pdm.s.Apic.pfnWriteMSRR3 = pApicReg->pfnWriteMSRR3;
pVM->pdm.s.Apic.pfnReadMSRR3 = pApicReg->pfnReadMSRR3;
pVM->pdm.s.Apic.pfnBusDeliverR3 = pApicReg->pfnBusDeliverR3;
pVM->pdm.s.Apic.pfnLocalInterruptR3 = pApicReg->pfnLocalInterruptR3;
pVM->pdm.s.Apic.pfnGetTimerFreqR3 = pApicReg->pfnGetTimerFreqR3;
Log(("PDM: Registered APIC device '%s'/%d pDevIns=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns));
/* set the helper pointer and return. */
*ppApicHlpR3 = &g_pdmR3DevApicHlp;
LogFlow(("pdmR3DevHlp_APICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS));
return VINF_SUCCESS;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnIOAPICRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_IOAPICRegister(PPDMDEVINS pDevIns, PPDMIOAPICREG pIoApicReg, PCPDMIOAPICHLPR3 *ppIoApicHlpR3)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: pIoApicReg=%p:{.u32Version=%#x, .pfnSetIrqR3=%p, .pszSetIrqRC=%p:{%s}, .pszSetIrqR0=%p:{%s}} ppIoApicHlpR3=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pIoApicReg, pIoApicReg->u32Version, pIoApicReg->pfnSetIrqR3,
pIoApicReg->pszSetIrqRC, pIoApicReg->pszSetIrqRC, pIoApicReg->pszSetIrqR0, pIoApicReg->pszSetIrqR0, ppIoApicHlpR3));
/*
* Validate input.
*/
if (pIoApicReg->u32Version != PDM_IOAPICREG_VERSION)
{
AssertMsgFailed(("u32Version=%#x expected %#x\n", pIoApicReg->u32Version, PDM_IOAPICREG_VERSION));
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if (!pIoApicReg->pfnSetIrqR3 || !pIoApicReg->pfnSendMsiR3)
{
Assert(pIoApicReg->pfnSetIrqR3);
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (R3 callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( pIoApicReg->pszSetIrqRC
&& !VALID_PTR(pIoApicReg->pszSetIrqRC))
{
Assert(VALID_PTR(pIoApicReg->pszSetIrqRC));
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (GC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( pIoApicReg->pszSendMsiRC
&& !VALID_PTR(pIoApicReg->pszSendMsiRC))
{
Assert(VALID_PTR(pIoApicReg->pszSendMsiRC));
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (GC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( pIoApicReg->pszSetIrqR0
&& !VALID_PTR(pIoApicReg->pszSetIrqR0))
{
Assert(VALID_PTR(pIoApicReg->pszSetIrqR0));
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (GC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( pIoApicReg->pszSendMsiR0
&& !VALID_PTR(pIoApicReg->pszSendMsiR0))
{
Assert(VALID_PTR(pIoApicReg->pszSendMsiR0));
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (GC callbacks)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if (!ppIoApicHlpR3)
{
Assert(ppIoApicHlpR3);
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (ppApicHlp)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/*
* The I/O APIC requires the APIC to be present (hacks++).
* If the I/O APIC does GC stuff so must the APIC.
*/
PVM pVM = pDevIns->Internal.s.pVMR3;
if (!pVM->pdm.s.Apic.pDevInsR3)
{
AssertMsgFailed(("Configuration error / Init order error! No APIC!\n"));
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (no APIC)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( pIoApicReg->pszSetIrqRC
&& !pVM->pdm.s.Apic.pDevInsRC)
{
AssertMsgFailed(("Configuration error! APIC doesn't do GC, I/O APIC does!\n"));
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (no GC APIC)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/*
* Only one I/O APIC device.
*/
if (pVM->pdm.s.IoApic.pDevInsR3)
{
AssertMsgFailed(("Only one ioapic device is supported!\n"));
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc (only one)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/*
* Resolve & initialize the GC bits.
*/
if (pIoApicReg->pszSetIrqRC)
{
int rc = pdmR3DevGetSymbolRCLazy(pDevIns, pIoApicReg->pszSetIrqRC, &pVM->pdm.s.IoApic.pfnSetIrqRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pIoApicReg->pszSetIrqRC, rc));
if (RT_FAILURE(rc))
{
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
pVM->pdm.s.IoApic.pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
}
else
{
pVM->pdm.s.IoApic.pDevInsRC = 0;
pVM->pdm.s.IoApic.pfnSetIrqRC = 0;
}
if (pIoApicReg->pszSendMsiRC)
{
int rc = pdmR3DevGetSymbolRCLazy(pDevIns, pIoApicReg->pszSetIrqRC, &pVM->pdm.s.IoApic.pfnSendMsiRC);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szRCMod, pIoApicReg->pszSendMsiRC, rc));
if (RT_FAILURE(rc))
{
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
}
else
{
pVM->pdm.s.IoApic.pfnSendMsiRC = 0;
}
/*
* Resolve & initialize the R0 bits.
*/
if (pIoApicReg->pszSetIrqR0)
{
int rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pIoApicReg->pszSetIrqR0, &pVM->pdm.s.IoApic.pfnSetIrqR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pIoApicReg->pszSetIrqR0, rc));
if (RT_FAILURE(rc))
{
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
pVM->pdm.s.IoApic.pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
Assert(pVM->pdm.s.IoApic.pDevInsR0);
}
else
{
pVM->pdm.s.IoApic.pfnSetIrqR0 = 0;
pVM->pdm.s.IoApic.pDevInsR0 = 0;
}
if (pIoApicReg->pszSendMsiR0)
{
int rc = pdmR3DevGetSymbolR0Lazy(pDevIns, pIoApicReg->pszSendMsiR0, &pVM->pdm.s.IoApic.pfnSendMsiR0);
AssertMsgRC(rc, ("%s::%s rc=%Rrc\n", pDevIns->pReg->szR0Mod, pIoApicReg->pszSendMsiR0, rc));
if (RT_FAILURE(rc))
{
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
}
else
{
pVM->pdm.s.IoApic.pfnSendMsiR0 = 0;
}
/*
* Initialize the R3 bits.
*/
pVM->pdm.s.IoApic.pDevInsR3 = pDevIns;
pVM->pdm.s.IoApic.pfnSetIrqR3 = pIoApicReg->pfnSetIrqR3;
pVM->pdm.s.IoApic.pfnSendMsiR3 = pIoApicReg->pfnSendMsiR3;
Log(("PDM: Registered I/O APIC device '%s'/%d pDevIns=%p\n", pDevIns->pReg->szName, pDevIns->iInstance, pDevIns));
/* set the helper pointer and return. */
*ppIoApicHlpR3 = &g_pdmR3DevIoApicHlp;
LogFlow(("pdmR3DevHlp_IOAPICRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS));
return VINF_SUCCESS;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnHPETRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_HPETRegister(PPDMDEVINS pDevIns, PPDMHPETREG pHpetReg, PCPDMHPETHLPR3 *ppHpetHlpR3)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_HPETRegister: caller='%s'/%d:\n"));
/*
* Validate input.
*/
if (pHpetReg->u32Version != PDM_HPETREG_VERSION)
{
AssertMsgFailed(("u32Version=%#x expected %#x\n", pHpetReg->u32Version, PDM_HPETREG_VERSION));
LogFlow(("pdmR3DevHlp_HPETRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if (!ppHpetHlpR3)
{
Assert(ppHpetHlpR3);
LogFlow(("pdmR3DevHlp_HPETRegister: caller='%s'/%d: returns %Rrc (ppApicHlpR3)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/* set the helper pointer and return. */
*ppHpetHlpR3 = &g_pdmR3DevHpetHlp;
LogFlow(("pdmR3DevHlp_HPETRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS));
return VINF_SUCCESS;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnPciRawRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_PciRawRegister(PPDMDEVINS pDevIns, PPDMPCIRAWREG pPciRawReg, PCPDMPCIRAWHLPR3 *ppPciRawHlpR3)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_PciRawRegister: caller='%s'/%d:\n"));
/*
* Validate input.
*/
if (pPciRawReg->u32Version != PDM_PCIRAWREG_VERSION)
{
AssertMsgFailed(("u32Version=%#x expected %#x\n", pPciRawReg->u32Version, PDM_PCIRAWREG_VERSION));
LogFlow(("pdmR3DevHlp_PciRawRegister: caller='%s'/%d: returns %Rrc (version)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if (!ppPciRawHlpR3)
{
Assert(ppPciRawHlpR3);
LogFlow(("pdmR3DevHlp_PciRawRegister: caller='%s'/%d: returns %Rrc (ppApicHlpR3)\n", pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/* set the helper pointer and return. */
*ppPciRawHlpR3 = &g_pdmR3DevPciRawHlp;
LogFlow(("pdmR3DevHlp_PciRawRegister: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, VINF_SUCCESS));
return VINF_SUCCESS;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnDMACRegister} */
static DECLCALLBACK(int) pdmR3DevHlp_DMACRegister(PPDMDEVINS pDevIns, PPDMDMACREG pDmacReg, PCPDMDMACHLP *ppDmacHlp)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_DMACRegister: caller='%s'/%d: pDmacReg=%p:{.u32Version=%#x, .pfnRun=%p, .pfnRegister=%p, .pfnReadMemory=%p, .pfnWriteMemory=%p, .pfnSetDREQ=%p, .pfnGetChannelMode=%p} ppDmacHlp=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pDmacReg, pDmacReg->u32Version, pDmacReg->pfnRun, pDmacReg->pfnRegister,
pDmacReg->pfnReadMemory, pDmacReg->pfnWriteMemory, pDmacReg->pfnSetDREQ, pDmacReg->pfnGetChannelMode, ppDmacHlp));
/*
* Validate input.
*/
if (pDmacReg->u32Version != PDM_DMACREG_VERSION)
{
AssertMsgFailed(("u32Version=%#x expected %#x\n", pDmacReg->u32Version,
PDM_DMACREG_VERSION));
LogFlow(("pdmR3DevHlp_DMACRegister: caller='%s'/%d: returns %Rrc (version)\n",
pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if ( !pDmacReg->pfnRun
|| !pDmacReg->pfnRegister
|| !pDmacReg->pfnReadMemory
|| !pDmacReg->pfnWriteMemory
|| !pDmacReg->pfnSetDREQ
|| !pDmacReg->pfnGetChannelMode)
{
Assert(pDmacReg->pfnRun);
Assert(pDmacReg->pfnRegister);
Assert(pDmacReg->pfnReadMemory);
Assert(pDmacReg->pfnWriteMemory);
Assert(pDmacReg->pfnSetDREQ);
Assert(pDmacReg->pfnGetChannelMode);
LogFlow(("pdmR3DevHlp_DMACRegister: caller='%s'/%d: returns %Rrc (callbacks)\n",
pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
if (!ppDmacHlp)
{
Assert(ppDmacHlp);
LogFlow(("pdmR3DevHlp_DMACRegister: caller='%s'/%d: returns %Rrc (ppDmacHlp)\n",
pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/*
* Only one DMA device.
*/
PVM pVM = pDevIns->Internal.s.pVMR3;
if (pVM->pdm.s.pDmac)
{
AssertMsgFailed(("Only one DMA device is supported!\n"));
LogFlow(("pdmR3DevHlp_DMACRegister: caller='%s'/%d: returns %Rrc\n",
pDevIns->pReg->szName, pDevIns->iInstance, VERR_INVALID_PARAMETER));
return VERR_INVALID_PARAMETER;
}
/*
* Allocate and initialize pci bus structure.
*/
int rc = VINF_SUCCESS;
PPDMDMAC pDmac = (PPDMDMAC)MMR3HeapAlloc(pDevIns->Internal.s.pVMR3, MM_TAG_PDM_DEVICE, sizeof(*pDmac));
if (pDmac)
{
pDmac->pDevIns = pDevIns;
pDmac->Reg = *pDmacReg;
pVM->pdm.s.pDmac = pDmac;
/* set the helper pointer. */
*ppDmacHlp = &g_pdmR3DevDmacHlp;
Log(("PDM: Registered DMAC device '%s'/%d pDevIns=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, pDevIns));
}
else
rc = VERR_NO_MEMORY;
LogFlow(("pdmR3DevHlp_DMACRegister: caller='%s'/%d: returns %Rrc\n",
pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/**
* @copydoc PDMDEVHLPR3::pfnRegisterVMMDevHeap
*/
static DECLCALLBACK(int) pdmR3DevHlp_RegisterVMMDevHeap(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTR3PTR pvHeap, unsigned cbSize)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
int rc = PDMR3VmmDevHeapRegister(pDevIns->Internal.s.pVMR3, GCPhys, pvHeap, cbSize);
return rc;
}
/**
* @copydoc PDMDEVHLPR3::pfnUnregisterVMMDevHeap
*/
static DECLCALLBACK(int) pdmR3DevHlp_UnregisterVMMDevHeap(PPDMDEVINS pDevIns, RTGCPHYS GCPhys)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
int rc = PDMR3VmmDevHeapUnregister(pDevIns->Internal.s.pVMR3, GCPhys);
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMReset} */
static DECLCALLBACK(int) pdmR3DevHlp_VMReset(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_VMReset: caller='%s'/%d: VM_FF_RESET %d -> 1\n",
pDevIns->pReg->szName, pDevIns->iInstance, VM_FF_IS_SET(pVM, VM_FF_RESET)));
/*
* We postpone this operation because we're likely to be inside a I/O instruction
* and the EIP will be updated when we return.
* We still return VINF_EM_RESET to break out of any execution loops and force FF evaluation.
*/
bool fHaltOnReset;
int rc = CFGMR3QueryBool(CFGMR3GetChild(CFGMR3GetRoot(pVM), "PDM"), "HaltOnReset", &fHaltOnReset);
if (RT_SUCCESS(rc) && fHaltOnReset)
{
Log(("pdmR3DevHlp_VMReset: Halt On Reset!\n"));
rc = VINF_EM_HALT;
}
else
{
VM_FF_SET(pVM, VM_FF_RESET);
rc = VINF_EM_RESET;
}
LogFlow(("pdmR3DevHlp_VMReset: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMSuspend} */
static DECLCALLBACK(int) pdmR3DevHlp_VMSuspend(PPDMDEVINS pDevIns)
{
int rc;
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_VMSuspend: caller='%s'/%d:\n",
pDevIns->pReg->szName, pDevIns->iInstance));
/** @todo Always take the SMP path - fewer code paths. */
if (pVM->cCpus > 1)
{
/* We own the IOM lock here and could cause a deadlock by waiting for a VCPU that is blocking on the IOM lock. */
rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)VMR3Suspend, 2, pVM->pUVM, VMSUSPENDREASON_VM);
AssertRC(rc);
rc = VINF_EM_SUSPEND;
}
else
rc = VMR3Suspend(pVM->pUVM, VMSUSPENDREASON_VM);
LogFlow(("pdmR3DevHlp_VMSuspend: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/**
* Worker for pdmR3DevHlp_VMSuspendSaveAndPowerOff that is invoked via a queued
* EMT request to avoid deadlocks.
*
* @returns VBox status code fit for scheduling.
* @param pVM Pointer to the VM.
* @param pDevIns The device that triggered this action.
*/
static DECLCALLBACK(int) pdmR3DevHlp_VMSuspendSaveAndPowerOffWorker(PVM pVM, PPDMDEVINS pDevIns)
{
/*
* Suspend the VM first then do the saving.
*/
int rc = VMR3Suspend(pVM->pUVM, VMSUSPENDREASON_VM);
if (RT_SUCCESS(rc))
{
PUVM pUVM = pVM->pUVM;
rc = pUVM->pVmm2UserMethods->pfnSaveState(pVM->pUVM->pVmm2UserMethods, pUVM);
/*
* On success, power off the VM, on failure we'll leave it suspended.
*/
if (RT_SUCCESS(rc))
{
rc = VMR3PowerOff(pVM->pUVM);
if (RT_FAILURE(rc))
LogRel(("%s/SSP: VMR3PowerOff failed: %Rrc\n", pDevIns->pReg->szName, rc));
}
else
LogRel(("%s/SSP: pfnSaveState failed: %Rrc\n", pDevIns->pReg->szName, rc));
}
else
LogRel(("%s/SSP: Suspend failed: %Rrc\n", pDevIns->pReg->szName, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMSuspendSaveAndPowerOff} */
static DECLCALLBACK(int) pdmR3DevHlp_VMSuspendSaveAndPowerOff(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_VMSuspendSaveAndPowerOff: caller='%s'/%d:\n",
pDevIns->pReg->szName, pDevIns->iInstance));
int rc;
if ( pVM->pUVM->pVmm2UserMethods
&& pVM->pUVM->pVmm2UserMethods->pfnSaveState)
{
rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pdmR3DevHlp_VMSuspendSaveAndPowerOffWorker, 2, pVM, pDevIns);
if (RT_SUCCESS(rc))
{
LogRel(("%s: Suspending, Saving and Powering Off the VM\n", pDevIns->pReg->szName));
rc = VINF_EM_SUSPEND;
}
}
else
rc = VERR_NOT_SUPPORTED;
LogFlow(("pdmR3DevHlp_VMSuspendSaveAndPowerOff: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMPowerOff} */
static DECLCALLBACK(int) pdmR3DevHlp_VMPowerOff(PPDMDEVINS pDevIns)
{
int rc;
PDMDEV_ASSERT_DEVINS(pDevIns);
PVM pVM = pDevIns->Internal.s.pVMR3;
VM_ASSERT_EMT(pVM);
LogFlow(("pdmR3DevHlp_VMPowerOff: caller='%s'/%d:\n",
pDevIns->pReg->szName, pDevIns->iInstance));
/** @todo Always take the SMP path - fewer code paths. */
if (pVM->cCpus > 1)
{
/* We might be holding locks here and could cause a deadlock since
VMR3PowerOff rendezvous with the other CPUs. */
rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)VMR3PowerOff, 1, pVM->pUVM);
AssertRC(rc);
/* Set the VCPU state to stopped here as well to make sure no
inconsistency with the EM state occurs. */
VMCPU_SET_STATE(VMMGetCpu(pVM), VMCPUSTATE_STOPPED);
rc = VINF_EM_OFF;
}
else
rc = VMR3PowerOff(pVM->pUVM);
LogFlow(("pdmR3DevHlp_VMPowerOff: caller='%s'/%d: returns %Rrc\n", pDevIns->pReg->szName, pDevIns->iInstance, rc));
return rc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnA20IsEnabled} */
static DECLCALLBACK(bool) pdmR3DevHlp_A20IsEnabled(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
bool fRc = PGMPhysIsA20Enabled(VMMGetCpu(pDevIns->Internal.s.pVMR3));
LogFlow(("pdmR3DevHlp_A20IsEnabled: caller='%s'/%d: returns %d\n", pDevIns->pReg->szName, pDevIns->iInstance, fRc));
return fRc;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnA20Set} */
static DECLCALLBACK(void) pdmR3DevHlp_A20Set(PPDMDEVINS pDevIns, bool fEnable)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_A20Set: caller='%s'/%d: fEnable=%d\n", pDevIns->pReg->szName, pDevIns->iInstance, fEnable));
PGMR3PhysSetA20(VMMGetCpu(pDevIns->Internal.s.pVMR3), fEnable);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnGetCpuId} */
static DECLCALLBACK(void) pdmR3DevHlp_GetCpuId(PPDMDEVINS pDevIns, uint32_t iLeaf,
uint32_t *pEax, uint32_t *pEbx, uint32_t *pEcx, uint32_t *pEdx)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
VM_ASSERT_EMT(pDevIns->Internal.s.pVMR3);
LogFlow(("pdmR3DevHlp_GetCpuId: caller='%s'/%d: iLeaf=%d pEax=%p pEbx=%p pEcx=%p pEdx=%p\n",
pDevIns->pReg->szName, pDevIns->iInstance, iLeaf, pEax, pEbx, pEcx, pEdx));
AssertPtr(pEax); AssertPtr(pEbx); AssertPtr(pEcx); AssertPtr(pEdx);
CPUMGetGuestCpuId(VMMGetCpu(pDevIns->Internal.s.pVMR3), iLeaf, 0 /*iSubLeaf*/, pEax, pEbx, pEcx, pEdx);
LogFlow(("pdmR3DevHlp_GetCpuId: caller='%s'/%d: returns void - *pEax=%#x *pEbx=%#x *pEcx=%#x *pEdx=%#x\n",
pDevIns->pReg->szName, pDevIns->iInstance, *pEax, *pEbx, *pEcx, *pEdx));
}
/**
* The device helper structure for trusted devices.
*/
const PDMDEVHLPR3 g_pdmR3DevHlpTrusted =
{
PDM_DEVHLPR3_VERSION,
pdmR3DevHlp_IOPortRegister,
pdmR3DevHlp_IOPortRegisterRC,
pdmR3DevHlp_IOPortRegisterR0,
pdmR3DevHlp_IOPortDeregister,
pdmR3DevHlp_MMIORegister,
pdmR3DevHlp_MMIORegisterRC,
pdmR3DevHlp_MMIORegisterR0,
pdmR3DevHlp_MMIODeregister,
pdmR3DevHlp_MMIO2Register,
pdmR3DevHlp_MMIO2Deregister,
pdmR3DevHlp_MMIO2Map,
pdmR3DevHlp_MMIO2Unmap,
pdmR3DevHlp_MMHyperMapMMIO2,
pdmR3DevHlp_MMIO2MapKernel,
pdmR3DevHlp_ROMRegister,
pdmR3DevHlp_ROMProtectShadow,
pdmR3DevHlp_SSMRegister,
pdmR3DevHlp_TMTimerCreate,
pdmR3DevHlp_TMUtcNow,
pdmR3DevHlp_PhysRead,
pdmR3DevHlp_PhysWrite,
pdmR3DevHlp_PhysGCPhys2CCPtr,
pdmR3DevHlp_PhysGCPhys2CCPtrReadOnly,
pdmR3DevHlp_PhysReleasePageMappingLock,
pdmR3DevHlp_PhysReadGCVirt,
pdmR3DevHlp_PhysWriteGCVirt,
pdmR3DevHlp_PhysGCPtr2GCPhys,
pdmR3DevHlp_MMHeapAlloc,
pdmR3DevHlp_MMHeapAllocZ,
pdmR3DevHlp_MMHeapFree,
pdmR3DevHlp_VMState,
pdmR3DevHlp_VMTeleportedAndNotFullyResumedYet,
pdmR3DevHlp_VMSetError,
pdmR3DevHlp_VMSetErrorV,
pdmR3DevHlp_VMSetRuntimeError,
pdmR3DevHlp_VMSetRuntimeErrorV,
pdmR3DevHlp_DBGFStopV,
pdmR3DevHlp_DBGFInfoRegister,
pdmR3DevHlp_DBGFRegRegister,
pdmR3DevHlp_DBGFTraceBuf,
pdmR3DevHlp_STAMRegister,
pdmR3DevHlp_STAMRegisterF,
pdmR3DevHlp_STAMRegisterV,
pdmR3DevHlp_PCIRegister,
pdmR3DevHlp_PCIRegisterMsi,
pdmR3DevHlp_PCIIORegionRegister,
pdmR3DevHlp_PCISetConfigCallbacks,
pdmR3DevHlp_PCIPhysRead,
pdmR3DevHlp_PCIPhysWrite,
pdmR3DevHlp_PCISetIrq,
pdmR3DevHlp_PCISetIrqNoWait,
pdmR3DevHlp_ISASetIrq,
pdmR3DevHlp_ISASetIrqNoWait,
pdmR3DevHlp_DriverAttach,
pdmR3DevHlp_QueueCreate,
pdmR3DevHlp_CritSectInit,
pdmR3DevHlp_CritSectGetNop,
pdmR3DevHlp_CritSectGetNopR0,
pdmR3DevHlp_CritSectGetNopRC,
pdmR3DevHlp_SetDeviceCritSect,
pdmR3DevHlp_ThreadCreate,
pdmR3DevHlp_SetAsyncNotification,
pdmR3DevHlp_AsyncNotificationCompleted,
pdmR3DevHlp_RTCRegister,
pdmR3DevHlp_PCIBusRegister,
pdmR3DevHlp_PICRegister,
pdmR3DevHlp_APICRegister,
pdmR3DevHlp_IOAPICRegister,
pdmR3DevHlp_HPETRegister,
pdmR3DevHlp_PciRawRegister,
pdmR3DevHlp_DMACRegister,
pdmR3DevHlp_DMARegister,
pdmR3DevHlp_DMAReadMemory,
pdmR3DevHlp_DMAWriteMemory,
pdmR3DevHlp_DMASetDREQ,
pdmR3DevHlp_DMAGetChannelMode,
pdmR3DevHlp_DMASchedule,
pdmR3DevHlp_CMOSWrite,
pdmR3DevHlp_CMOSRead,
pdmR3DevHlp_AssertEMT,
pdmR3DevHlp_AssertOther,
pdmR3DevHlp_LdrGetRCInterfaceSymbols,
pdmR3DevHlp_LdrGetR0InterfaceSymbols,
pdmR3DevHlp_CallR0,
pdmR3DevHlp_VMGetSuspendReason,
pdmR3DevHlp_VMGetResumeReason,
0,
0,
0,
0,
0,
0,
0,
pdmR3DevHlp_GetUVM,
pdmR3DevHlp_GetVM,
pdmR3DevHlp_GetVMCPU,
pdmR3DevHlp_GetCurrentCpuId,
pdmR3DevHlp_RegisterVMMDevHeap,
pdmR3DevHlp_UnregisterVMMDevHeap,
pdmR3DevHlp_VMReset,
pdmR3DevHlp_VMSuspend,
pdmR3DevHlp_VMSuspendSaveAndPowerOff,
pdmR3DevHlp_VMPowerOff,
pdmR3DevHlp_A20IsEnabled,
pdmR3DevHlp_A20Set,
pdmR3DevHlp_GetCpuId,
pdmR3DevHlp_TMTimeVirtGet,
pdmR3DevHlp_TMTimeVirtGetFreq,
pdmR3DevHlp_TMTimeVirtGetNano,
pdmR3DevHlp_GetSupDrvSession,
PDM_DEVHLPR3_VERSION /* the end */
};
/** @interface_method_impl{PDMDEVHLPR3,pfnGetUVM} */
static DECLCALLBACK(PUVM) pdmR3DevHlp_Untrusted_GetUVM(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
return NULL;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnGetVM} */
static DECLCALLBACK(PVM) pdmR3DevHlp_Untrusted_GetVM(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
return NULL;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnGetVMCPU} */
static DECLCALLBACK(PVMCPU) pdmR3DevHlp_Untrusted_GetVMCPU(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
return NULL;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnGetCurrentCpuId} */
static DECLCALLBACK(VMCPUID) pdmR3DevHlp_Untrusted_GetCurrentCpuId(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
return NIL_VMCPUID;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnRegisterVMMDevHeap} */
static DECLCALLBACK(int) pdmR3DevHlp_Untrusted_RegisterVMMDevHeap(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTR3PTR pvHeap, unsigned cbSize)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
NOREF(GCPhys); NOREF(pvHeap); NOREF(cbSize);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
return VERR_ACCESS_DENIED;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnUnregisterVMMDevHeap} */
static DECLCALLBACK(int) pdmR3DevHlp_Untrusted_UnregisterVMMDevHeap(PPDMDEVINS pDevIns, RTGCPHYS GCPhys)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
NOREF(GCPhys);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
return VERR_ACCESS_DENIED;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMReset} */
static DECLCALLBACK(int) pdmR3DevHlp_Untrusted_VMReset(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
return VERR_ACCESS_DENIED;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMSuspend} */
static DECLCALLBACK(int) pdmR3DevHlp_Untrusted_VMSuspend(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
return VERR_ACCESS_DENIED;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMSuspendSaveAndPowerOff} */
static DECLCALLBACK(int) pdmR3DevHlp_Untrusted_VMSuspendSaveAndPowerOff(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
return VERR_ACCESS_DENIED;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnVMPowerOff} */
static DECLCALLBACK(int) pdmR3DevHlp_Untrusted_VMPowerOff(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
return VERR_ACCESS_DENIED;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnA20IsEnabled} */
static DECLCALLBACK(bool) pdmR3DevHlp_Untrusted_A20IsEnabled(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
return false;
}
/** @interface_method_impl{PDMDEVHLPR3,pfnA20Set} */
static DECLCALLBACK(void) pdmR3DevHlp_Untrusted_A20Set(PPDMDEVINS pDevIns, bool fEnable)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
NOREF(fEnable);
}
/** @interface_method_impl{PDMDEVHLPR3,pfnGetCpuId} */
static DECLCALLBACK(void) pdmR3DevHlp_Untrusted_GetCpuId(PPDMDEVINS pDevIns, uint32_t iLeaf,
uint32_t *pEax, uint32_t *pEbx, uint32_t *pEcx, uint32_t *pEdx)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
NOREF(iLeaf); NOREF(pEax); NOREF(pEbx); NOREF(pEcx); NOREF(pEdx);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
}
/** @interface_method_impl{PDMDEVHLPR3,pfnGetSupDrvSession} */
static DECLCALLBACK(PSUPDRVSESSION) pdmR3DevHlp_Untrusted_GetSupDrvSession(PPDMDEVINS pDevIns)
{
PDMDEV_ASSERT_DEVINS(pDevIns);
AssertReleaseMsgFailed(("Untrusted device called trusted helper! '%s'/%d\n", pDevIns->pReg->szName, pDevIns->iInstance));
return (PSUPDRVSESSION)0;
}
/**
* The device helper structure for non-trusted devices.
*/
const PDMDEVHLPR3 g_pdmR3DevHlpUnTrusted =
{
PDM_DEVHLPR3_VERSION,
pdmR3DevHlp_IOPortRegister,
pdmR3DevHlp_IOPortRegisterRC,
pdmR3DevHlp_IOPortRegisterR0,
pdmR3DevHlp_IOPortDeregister,
pdmR3DevHlp_MMIORegister,
pdmR3DevHlp_MMIORegisterRC,
pdmR3DevHlp_MMIORegisterR0,
pdmR3DevHlp_MMIODeregister,
pdmR3DevHlp_MMIO2Register,
pdmR3DevHlp_MMIO2Deregister,
pdmR3DevHlp_MMIO2Map,
pdmR3DevHlp_MMIO2Unmap,
pdmR3DevHlp_MMHyperMapMMIO2,
pdmR3DevHlp_MMIO2MapKernel,
pdmR3DevHlp_ROMRegister,
pdmR3DevHlp_ROMProtectShadow,
pdmR3DevHlp_SSMRegister,
pdmR3DevHlp_TMTimerCreate,
pdmR3DevHlp_TMUtcNow,
pdmR3DevHlp_PhysRead,
pdmR3DevHlp_PhysWrite,
pdmR3DevHlp_PhysGCPhys2CCPtr,
pdmR3DevHlp_PhysGCPhys2CCPtrReadOnly,
pdmR3DevHlp_PhysReleasePageMappingLock,
pdmR3DevHlp_PhysReadGCVirt,
pdmR3DevHlp_PhysWriteGCVirt,
pdmR3DevHlp_PhysGCPtr2GCPhys,
pdmR3DevHlp_MMHeapAlloc,
pdmR3DevHlp_MMHeapAllocZ,
pdmR3DevHlp_MMHeapFree,
pdmR3DevHlp_VMState,
pdmR3DevHlp_VMTeleportedAndNotFullyResumedYet,
pdmR3DevHlp_VMSetError,
pdmR3DevHlp_VMSetErrorV,
pdmR3DevHlp_VMSetRuntimeError,
pdmR3DevHlp_VMSetRuntimeErrorV,
pdmR3DevHlp_DBGFStopV,
pdmR3DevHlp_DBGFInfoRegister,
pdmR3DevHlp_DBGFRegRegister,
pdmR3DevHlp_DBGFTraceBuf,
pdmR3DevHlp_STAMRegister,
pdmR3DevHlp_STAMRegisterF,
pdmR3DevHlp_STAMRegisterV,
pdmR3DevHlp_PCIRegister,
pdmR3DevHlp_PCIRegisterMsi,
pdmR3DevHlp_PCIIORegionRegister,
pdmR3DevHlp_PCISetConfigCallbacks,
pdmR3DevHlp_PCIPhysRead,
pdmR3DevHlp_PCIPhysWrite,
pdmR3DevHlp_PCISetIrq,
pdmR3DevHlp_PCISetIrqNoWait,
pdmR3DevHlp_ISASetIrq,
pdmR3DevHlp_ISASetIrqNoWait,
pdmR3DevHlp_DriverAttach,
pdmR3DevHlp_QueueCreate,
pdmR3DevHlp_CritSectInit,
pdmR3DevHlp_CritSectGetNop,
pdmR3DevHlp_CritSectGetNopR0,
pdmR3DevHlp_CritSectGetNopRC,
pdmR3DevHlp_SetDeviceCritSect,
pdmR3DevHlp_ThreadCreate,
pdmR3DevHlp_SetAsyncNotification,
pdmR3DevHlp_AsyncNotificationCompleted,
pdmR3DevHlp_RTCRegister,
pdmR3DevHlp_PCIBusRegister,
pdmR3DevHlp_PICRegister,
pdmR3DevHlp_APICRegister,
pdmR3DevHlp_IOAPICRegister,
pdmR3DevHlp_HPETRegister,
pdmR3DevHlp_PciRawRegister,
pdmR3DevHlp_DMACRegister,
pdmR3DevHlp_DMARegister,
pdmR3DevHlp_DMAReadMemory,
pdmR3DevHlp_DMAWriteMemory,
pdmR3DevHlp_DMASetDREQ,
pdmR3DevHlp_DMAGetChannelMode,
pdmR3DevHlp_DMASchedule,
pdmR3DevHlp_CMOSWrite,
pdmR3DevHlp_CMOSRead,
pdmR3DevHlp_AssertEMT,
pdmR3DevHlp_AssertOther,
pdmR3DevHlp_LdrGetRCInterfaceSymbols,
pdmR3DevHlp_LdrGetR0InterfaceSymbols,
pdmR3DevHlp_CallR0,
pdmR3DevHlp_VMGetSuspendReason,
pdmR3DevHlp_VMGetResumeReason,
0,
0,
0,
0,
0,
0,
0,
pdmR3DevHlp_Untrusted_GetUVM,
pdmR3DevHlp_Untrusted_GetVM,
pdmR3DevHlp_Untrusted_GetVMCPU,
pdmR3DevHlp_Untrusted_GetCurrentCpuId,
pdmR3DevHlp_Untrusted_RegisterVMMDevHeap,
pdmR3DevHlp_Untrusted_UnregisterVMMDevHeap,
pdmR3DevHlp_Untrusted_VMReset,
pdmR3DevHlp_Untrusted_VMSuspend,
pdmR3DevHlp_Untrusted_VMSuspendSaveAndPowerOff,
pdmR3DevHlp_Untrusted_VMPowerOff,
pdmR3DevHlp_Untrusted_A20IsEnabled,
pdmR3DevHlp_Untrusted_A20Set,
pdmR3DevHlp_Untrusted_GetCpuId,
pdmR3DevHlp_TMTimeVirtGet,
pdmR3DevHlp_TMTimeVirtGetFreq,
pdmR3DevHlp_TMTimeVirtGetNano,
pdmR3DevHlp_Untrusted_GetSupDrvSession,
PDM_DEVHLPR3_VERSION /* the end */
};
/**
* Queue consumer callback for internal component.
*
* @returns Success indicator.
* If false the item will not be removed and the flushing will stop.
* @param pVM Pointer to the VM.
* @param pItem The item to consume. Upon return this item will be freed.
*/
DECLCALLBACK(bool) pdmR3DevHlpQueueConsumer(PVM pVM, PPDMQUEUEITEMCORE pItem)
{
PPDMDEVHLPTASK pTask = (PPDMDEVHLPTASK)pItem;
LogFlow(("pdmR3DevHlpQueueConsumer: enmOp=%d pDevIns=%p\n", pTask->enmOp, pTask->pDevInsR3));
switch (pTask->enmOp)
{
case PDMDEVHLPTASKOP_ISA_SET_IRQ:
PDMIsaSetIrq(pVM, pTask->u.SetIRQ.iIrq, pTask->u.SetIRQ.iLevel, pTask->u.SetIRQ.uTagSrc);
break;
case PDMDEVHLPTASKOP_PCI_SET_IRQ:
{
/* Same as pdmR3DevHlp_PCISetIrq, except we've got a tag already. */
PPDMDEVINS pDevIns = pTask->pDevInsR3;
PPCIDEVICE pPciDev = pDevIns->Internal.s.pPciDeviceR3;
if (pPciDev)
{
PPDMPCIBUS pBus = pDevIns->Internal.s.pPciBusR3; /** @todo the bus should be associated with the PCI device not the PDM device. */
Assert(pBus);
pdmLock(pVM);
pBus->pfnSetIrqR3(pBus->pDevInsR3, pPciDev, pTask->u.SetIRQ.iIrq,
pTask->u.SetIRQ.iLevel, pTask->u.SetIRQ.uTagSrc);
pdmUnlock(pVM);
}
else
AssertReleaseMsgFailed(("No PCI device registered!\n"));
break;
}
case PDMDEVHLPTASKOP_IOAPIC_SET_IRQ:
PDMIoApicSetIrq(pVM, pTask->u.SetIRQ.iIrq, pTask->u.SetIRQ.iLevel, pTask->u.SetIRQ.uTagSrc);
break;
default:
AssertReleaseMsgFailed(("Invalid operation %d\n", pTask->enmOp));
break;
}
return true;
}
/** @} */
| sobomax/virtualbox_64bit_edd | src/VBox/VMM/VMMR3/PDMDevHlp.cpp | C++ | gpl-2.0 | 158,554 |
package com.avrgaming.civcraft.endgame;
import java.util.ArrayList;
import com.avrgaming.civcraft.main.CivGlobal;
import com.avrgaming.civcraft.main.CivMessage;
import com.avrgaming.civcraft.object.Civilization;
import com.avrgaming.civcraft.object.Town;
import com.avrgaming.civcraft.sessiondb.SessionEntry;
import com.avrgaming.civcraft.structure.wonders.Wonder;
public class EndConditionScience extends EndGameCondition {
String techname;
@Override
public void onLoad() {
techname = this.getString("tech");
}
@Override
public boolean check(Civilization civ) {
if (!civ.hasTechnology(techname)) {
return false;
}
if (civ.isAdminCiv()) {
return false;
}
boolean hasGreatLibrary = false;
for (Town town : civ.getTowns()) {
if (town.getMotherCiv() != null) {
continue;
}
for (Wonder wonder :town.getWonders()) {
if (wonder.isActive()) {
if (wonder.getConfigId().equals("w_greatlibrary")) {
hasGreatLibrary = true;
break;
}
}
}
if (hasGreatLibrary) {
break;
}
}
if (!hasGreatLibrary) {
return false;
}
return true;
}
@Override
public boolean finalWinCheck(Civilization civ) {
Civilization rival = getMostAccumulatedBeakers();
if (rival != civ) {
CivMessage.global(civ.getName()+" doesn't have enough beakers for a scientific victory. The rival civilization of "+rival.getName()+" has more!");
return false;
}
return true;
}
public Civilization getMostAccumulatedBeakers() {
double most = 0;
Civilization mostCiv = null;
for (Civilization civ : CivGlobal.getCivs()) {
double beakers = getExtraBeakersInCiv(civ);
if (beakers > most) {
most = beakers;
mostCiv = civ;
}
}
return mostCiv;
}
@Override
public String getSessionKey() {
return "endgame:science";
}
@Override
protected void onWarDefeat(Civilization civ) {
/* remove any extra beakers we might have. */
CivGlobal.getSessionDB().delete_all(getBeakerSessionKey(civ));
civ.removeTech(techname);
CivMessage.sendCiv(civ, "We were defeated while trying to achieve a science victory! We've lost all of our accumulated beakers and our victory tech!");
civ.save();
this.onFailure(civ);
}
public static String getBeakerSessionKey(Civilization civ) {
return "endgame:sciencebeakers:"+civ.getId();
}
public double getExtraBeakersInCiv(Civilization civ) {
ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(getBeakerSessionKey(civ));
if (entries.size() == 0) {
return 0;
}
return Double.valueOf(entries.get(0).value);
}
public void addExtraBeakersToCiv(Civilization civ, double beakers) {
ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(getBeakerSessionKey(civ));
double current = 0;
if (entries.size() == 0) {
CivGlobal.getSessionDB().add(getBeakerSessionKey(civ), ""+beakers, civ.getId(), 0, 0);
current += beakers;
} else {
current = Double.valueOf(entries.get(0).value);
current += beakers;
CivGlobal.getSessionDB().update(entries.get(0).request_id, entries.get(0).key, ""+current);
}
//DecimalFormat df = new DecimalFormat("#.#");
//CivMessage.sendCiv(civ, "Added "+df.format(beakers)+" beakers to our scientific victory! We now have "+df.format(current)+" beakers saved up.");
}
public static Double getBeakersFor(Civilization civ) {
ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(getBeakerSessionKey(civ));
if (entries.size() == 0) {
return 0.0;
} else {
return Double.valueOf(entries.get(0).value);
}
}
}
| netizen539/civcraft | civcraft/src/com/avrgaming/civcraft/endgame/EndConditionScience.java | Java | gpl-2.0 | 3,584 |
/*
* Copyright 2010 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.
*/
package org.visage.jdi.request;
import org.visage.jdi.VisageThreadReference;
import org.visage.jdi.VisageVirtualMachine;
import org.visage.jdi.VisageWrapper;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.request.StepRequest;
/**
*
* @author sundar
*/
public class VisageStepRequest extends VisageEventRequest implements StepRequest {
public VisageStepRequest(VisageVirtualMachine visagevm, StepRequest underlying) {
super(visagevm, underlying);
}
public void addClassExclusionFilter(String arg0) {
underlying().addClassExclusionFilter(arg0);
}
public void addClassFilter(ReferenceType arg0) {
underlying().addClassFilter(VisageWrapper.unwrap(arg0));
}
public void addClassFilter(String arg0) {
underlying().addClassFilter(arg0);
}
public void addInstanceFilter(ObjectReference ref) {
underlying().addInstanceFilter(VisageWrapper.unwrap(ref));
}
public int depth() {
return underlying().depth();
}
public int size() {
return underlying().size();
}
public VisageThreadReference thread() {
return VisageWrapper.wrap(virtualMachine(), underlying().thread());
}
@Override
protected StepRequest underlying() {
return (StepRequest) super.underlying();
}
}
| pron/visage-compiler | visagejdi/src/org/visage/jdi/request/VisageStepRequest.java | Java | gpl-2.0 | 2,405 |
/*
* Copyright (C) 2014 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "bmalloc.h"
#define EXPORT __attribute__((visibility("default")))
extern "C" {
EXPORT void* mbmalloc(size_t);
EXPORT void* mbmemalign(size_t, size_t);
EXPORT void mbfree(void*, size_t);
EXPORT void* mbrealloc(void*, size_t, size_t);
EXPORT void mbscavenge();
void* mbmalloc(size_t size)
{
return bmalloc::api::malloc(size);
}
void* mbmemalign(size_t alignment, size_t size)
{
return bmalloc::api::memalign(alignment, size);
}
void mbfree(void* p, size_t)
{
bmalloc::api::free(p);
}
void* mbrealloc(void* p, size_t, size_t size)
{
return bmalloc::api::realloc(p, size);
}
void mbscavenge()
{
bmalloc::api::scavenge();
}
} // extern "C"
| qtproject/qtwebkit | Source/bmalloc/bmalloc/mbmalloc.cpp | C++ | gpl-2.0 | 2,010 |
package gr.softaware.lib_1_3.data.convert.csv;
import java.util.List;
/**
*
* @author siggouroglou
* @param <T> A class that implements the CsvGenerationModel interface.
*/
final public class CsvGenerator<T extends CsvGenerationModel> {
private final List<CsvGenerationModel> modelList;
public CsvGenerator(List<T> modelList) {
this.modelList = (List<CsvGenerationModel>)modelList;
}
public StringBuilder getContent() {
return getContent("\t", "\\t");
}
public StringBuilder getContent(String separator, String separatorAsString) {
StringBuilder builder = new StringBuilder();
// First line contains the separator.
builder.append("sep=").append(separatorAsString).append("\n");
// Get the header.
if(!modelList.isEmpty()) {
builder.append(modelList.get(0).toCsvFormattedHeader(separator)).append("\n");
}
// Get the data.
modelList.stream().forEach((model) -> {
builder.append(model.toCsvFormattedRow(separator)).append("\n");
});
return builder;
}
}
| siggouroglou/innovathens | webnew/src/main/java/gr/softaware/lib_1_3/data/convert/csv/CsvGenerator.java | Java | gpl-2.0 | 1,153 |
<?php
/**
Author: Musavir Ifitkahr:
kuala lumpur Malaysia
*/
class Admin_UserController extends Zend_Controller_Action
{
protected $user_session = null;
protected $db;
protected $language_id = null;
protected $filter = null;
protected $user = null;
protected $baseurl = '';
public function init(){
Zend_Layout::startMvc(
array('layoutPath' => APPLICATION_PATH . '/admin/layouts', 'layout' => 'layout')
);
$this->db = Zend_Db_Table::getDefaultAdapter();
$this->user = new Application_Model_User();
$this->baseurl = Zend_Controller_Front::getInstance()->getBaseUrl(); //actual base url function
$this->language_id = Zend_Registry::get('lang_id'); //get the instance of database adapter
$this->user_session = new Zend_Session_Namespace("user_session"); // default namespace
$this->filter = new Zend_Filter_StripTags;
//Zend_Registry::set('lang_id',2);
ini_set("max_execution_time", 0);
$auth = Zend_Auth::getInstance();
//if not loggedin redirect to login page
if (!$auth->hasIdentity()){
$this->_redirect('/admin/index/login');;
}
/* if(isset($this->user_session->role_id)){
$role = array('1' => 'Admin','2' => 'Payment Manager','3' => 'Content Manager','4' => 'Listing Manager', '3' => 'Deals Manager' );
$this->view->user = array(
'user_id' => $this->user_session->user_id,
'email' => $this->user_session->email,
'role_id' => $this->user_session->role_id,
'role_name' => $role[$this->user_session->role_id],
'user_name' =>$this->user_session->firstname,
);
} */
}
// this is default output function
public function indexAction() {
}
public function newAction(){
//if not admin redirect to admin index dash board
/* if ($this->user_session->role_id != 1){
$this->_redirect('/admin/index');
} */
//show message if it is set true
if (isset($this->user_session->msg)){
$this->view->msg = $this->user_session->msg;
unset($this->user_session->msg);
}
//$this->adapter = new Zend_File_Transfer_Adapter_Http();
$form = new Application_Form_UserForm();
$this->view->form = $form;
if (!$this->_request->isPost()) {
//$form->role->setValue($this->user_session->selected);
$this->view->form = $form;
return;
}
$formData = $this->_request->getPost();
if (!$form->isValid($formData)) {
$this->view->form = $form;
return;
}
$exist = $this->user->checkEmail($formData['email']);
if($exist == true){
$this->view->msg = "<div class='errors'>Email (User ID) already exists. Please make another one .</div>";
return;
}
$formData['date_added'] = date("Y-m-d");
$this->view->msg = $this->user->addUser($formData);
//$this->user_session->selected = $formData['role'];
$this->user_session->msg = $this->view->msg;
//$this->_redirect('/admin/user/new');
//clear all form fields
$form->reset();
}
public function messagePageAction(){
$this->view->msg = $this->user_session->msg;
unset($this->user_session->country);
unset($this->user_session->state);
unset($this->user_session->add_more);
}
public function listAction(){
$query_string = $this->_request->getParam("query_string");
$results = null;
$query_string = trim($query_string);
if($query_string !=''){
if(is_string($query_string)){
$results = $this->user->findUser($query_string);
}
}
else{
$results = $this->user->getUsers();
}
if (count($results) > 0) {
$this->Paginator($results);
} else {
$this->view->empty_rec = true;
}
}
// for delete users
public function deleteUsersAction(){
$user_id = $this->_request->getParam('id');
$delete = $this->user->deleteUsers($user_id);
$this->_redirect('/admin/user/list/');
//var_dump($delete);
}
public function findUsersAction(){
//$this->ajaxed();
$email = $this->_request->getParam('email');
$results = $this->user->findUser($email);
if (count($results) > 0) {
$this->Paginator($results);
} else {
$this->view->empty_rec = true;
}
}
public function editAction(){
$form = new Application_Form_UserForm();
$user_id = $this->_request->getParam('user_id');
$result = $this->user->getUser($user_id);
$form->removeElement("password");
$this->view->user_id = $result->user_id;
$form->email->setValue($result->email);
$form->user_name->setValue($result->user_name);
//$form->role->setValue($result->role);
$this->view->form = $form;
if (!$this->_request->isPost()) {
$this->view->form = $form;
return;
}
$formData = $this->_request->getPost();
if (!$form->isValid($formData)) {
$this->view->form = $form;
return;
}
$result = $this->user->updateUser($formData);
$this->_redirect('admin/user/list');
}
// for chNEGE password user
public function updatePasswordAction(){
$user_id=$this->user_session->user_id;
$this->view->user_id=$user_id;
$form = new Application_Form_ChangePasswordForm();
$this->view->form = $form;
$this->view->msg = "";
if (!$this->_request->isPost()) {
return;
}
$formData = $this->_request->getPost();
if (!$form->isValid($formData)) {
return;
}
//All business logics will come here
if(strcmp($formData['pwd_current'],$formData['pwd'] ) == 0){
$this->view->msg = "<div class='alert alert-danger'>Old and New password are same</div>";
$this->view->form = $form;
return;
}
if(strcmp($formData['pwd'],$formData['pwd_confirm'] ) != 0){
$this->view->msg = "<div class='alert alert-danger'>Passwords are not matching</div>";
$this->view->form = $form;
return;
}
// var_dump($formData);
if($this->user->passUpdate($user_id, $formData['pwd'])){
$this->view->msg = "<div class='alert alert-success'>Password successfully Updated</div>";
}else{
$this->view->msg = "<div class='alert alert-danger'>Password Update Failed. Try again</div>";
}
}
public function changePasswordAction(){
$form = new Application_Form_UserForm();
$form->removeElement("user_id");
$form->removeElement("firstname");
$form->removeElement("lastname");
$form->removeElement("email");
$user = new Application_Model_User();
$result = $user->getUser();
$form->password->setLabel("New Password");
$form->password->setValue($result->password);
$this->view->form = $form;
$formData;
if (!$this->_request->isPost()) {
$this->view->form = $form;
return;
}
$formData = $this->_request->getPost();
if (!$form->isValid($formData)) {
$this->view->form = $form;
return;
}
/*if(!$user->currentPass($formData['current_password'])){
$this->view->msg = "Wrong current password";
return;
}*/
else {
$result = $user->updatePassword($formData);
$this->view->msg = "Password is updated";
}
}
public function Paginator($results) {
$page = $this->_getParam('page', 1);
$paginator = Zend_Paginator::factory($results);
$paginator->setItemCountPerPage(20);
$paginator->setCurrentPageNumber($page);
$this->view->paginator = $paginator;
}
/*
public function confirmDeleteAction(){
$user_id = $this->_request->getParam('user_id');
$firstname = $this->_request->getParam('firstname');
$this->view->firstname = $firstname;
$this->view->user_id = $user_id;
}
*/
/* public function deleteAction(){
$user_id = $this->_request->getParam('user_id');
$user_table = new Application_Model_User();
$flag = $user_table->removeUser($user_id);
if($flag){
$this->view->user_remove_report = "user has been removed! Successfully";
}
} */
public function ajaxed() {
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout()->disableLayout();
if (!$this->_request->isXmlHttpRequest()
)return; // if not a ajax request leave function
}
public function __call($method, $args) {
if ('Action' == substr($method, -6)) {
// If the action method was not found, forward to the
// index action
return $this->_redirect('admin/index');
}
// all other methods throw an exception
throw new Exception('Invalid method "'
. $method
. '" called',
500);
}
}
| mussawir/netefct | application/admin/controllers/UserController.php | PHP | gpl-2.0 | 8,735 |
/*
* This file is part of KITCard Reader.
* Ⓒ 2012 Philipp Kern <phil@philkern.de>
*
* KITCard Reader 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.
*
* KITCard Reader 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 KITCard Reader. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Ox539.kitcard.reader;
/**
* ReadCardTask: Read an NFC tag using the Wallet class asynchronously.
*
* This class provides the glue calling the Wallet class and passing
* the information back to the Android UI layer. Detailed error
* information is not provided yet.
*
* @author Philipp Kern <pkern@debian.org>
*/
import de.Ox539.kitcard.reader.Wallet.ReadCardResult;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.os.AsyncTask;
import android.widget.Toast;
public class ReadCardTask extends AsyncTask<Tag, Integer, Pair<ReadCardResult, Wallet>> {
private ScanActivity mActivity;
public ReadCardTask(ScanActivity activity) {
super();
this.mActivity = activity;
}
protected Pair<ReadCardResult, Wallet> doInBackground(Tag... tags) {
MifareClassic card = null;
try {
card = MifareClassic.get(tags[0]);
} catch (NullPointerException e) {
/* Error while reading card. This problem occurs on HTC devices from the ONE series with Android Lollipop (status of June 2015)
* Try to repair the tag.
*/
card = MifareClassic.get(MifareUtils.repairTag(tags[0]));
}
if(card == null)
return new Pair<ReadCardResult, Wallet>(null, null);
final Wallet wallet = new Wallet(card);
final ReadCardResult result = wallet.readCard();
return new Pair<ReadCardResult, Wallet>(result, wallet);
}
protected void onPostExecute(Pair<ReadCardResult, Wallet> data) {
ReadCardResult result = data.getValue0();
if(result == ReadCardResult.FAILURE) {
// read failed
Toast.makeText(mActivity, mActivity.getResources().getString(R.string.kitcard_read_failed), Toast.LENGTH_LONG).show();
return;
} else if(result == ReadCardResult.OLD_STYLE_WALLET) {
// old-style wallet encountered
Toast.makeText(mActivity, mActivity.getResources().getString(R.string.kitcard_needs_reencode), Toast.LENGTH_LONG).show();
return;
}
final Wallet wallet = data.getValue1();
mActivity.updateCardNumber(wallet.getCardNumber());
mActivity.updateBalance(wallet.getCurrentBalance());
mActivity.updateLastTransaction(wallet.getLastTransactionValue());
mActivity.updateCardIssuer(wallet.getCardIssuer());
mActivity.updateCardType(wallet.getCardType());
}
}
| simontb/kitcard-reader | src/de/Ox539/kitcard/reader/ReadCardTask.java | Java | gpl-2.0 | 3,022 |
/***************************************************************************
qgssourcefieldsproperties.cpp
---------------------
begin : July 2017
copyright : (C) 2017 by David Signer
email : david at opengis dot ch
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgssourcefieldsproperties.h"
#include "qgsvectorlayer.h"
#include "qgsproject.h"
QgsSourceFieldsProperties::QgsSourceFieldsProperties( QgsVectorLayer *layer, QWidget *parent )
: QWidget( parent )
, mLayer( layer )
{
if ( !layer )
return;
setupUi( this );
layout()->setContentsMargins( 0, 0, 0, 0 );
layout()->setMargin( 0 );
//button appearance
mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewAttribute.svg" ) ) );
mDeleteAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteAttribute.svg" ) ) );
mToggleEditingButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionToggleEditing.svg" ) ) );
mCalculateFieldButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCalculateField.svg" ) ) );
//button signals
connect( mToggleEditingButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::toggleEditing );
connect( mAddAttributeButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::addAttributeClicked );
connect( mDeleteAttributeButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::deleteAttributeClicked );
connect( mCalculateFieldButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::calculateFieldClicked );
//slots
connect( mLayer, &QgsVectorLayer::editingStarted, this, &QgsSourceFieldsProperties::editingToggled );
connect( mLayer, &QgsVectorLayer::editingStopped, this, &QgsSourceFieldsProperties::editingToggled );
connect( mLayer, &QgsVectorLayer::attributeAdded, this, &QgsSourceFieldsProperties::attributeAdded );
connect( mLayer, &QgsVectorLayer::attributeDeleted, this, &QgsSourceFieldsProperties::attributeDeleted );
//field list appearance
mFieldsList->setColumnCount( AttrColCount );
mFieldsList->setSelectionBehavior( QAbstractItemView::SelectRows );
mFieldsList->setDragDropMode( QAbstractItemView::DragOnly );
mFieldsList->setHorizontalHeaderItem( AttrIdCol, new QTableWidgetItem( tr( "Id" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrNameCol, new QTableWidgetItem( tr( "Name" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrTypeCol, new QTableWidgetItem( tr( "Type" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrTypeNameCol, new QTableWidgetItem( tr( "Type name" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrLengthCol, new QTableWidgetItem( tr( "Length" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrPrecCol, new QTableWidgetItem( tr( "Precision" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrCommentCol, new QTableWidgetItem( tr( "Comment" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrWMSCol, new QTableWidgetItem( QStringLiteral( "WMS" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrWFSCol, new QTableWidgetItem( QStringLiteral( "WFS" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrAliasCol, new QTableWidgetItem( tr( "Alias" ) ) );
mFieldsList->setSortingEnabled( true );
mFieldsList->sortByColumn( 0, Qt::AscendingOrder );
mFieldsList->setSelectionBehavior( QAbstractItemView::SelectRows );
mFieldsList->setSelectionMode( QAbstractItemView::ExtendedSelection );
mFieldsList->verticalHeader()->hide();
//load buttons and field list
updateButtons();
}
void QgsSourceFieldsProperties::init()
{
loadRows();
}
void QgsSourceFieldsProperties::loadRows()
{
disconnect( mFieldsList, &QTableWidget::cellChanged, this, &QgsSourceFieldsProperties::attributesListCellChanged );
const QgsFields &fields = mLayer->fields();
mIndexedWidgets.clear();
mFieldsList->setRowCount( 0 );
for ( int i = 0; i < fields.count(); ++i )
attributeAdded( i );
mFieldsList->resizeColumnsToContents();
connect( mFieldsList, &QTableWidget::cellChanged, this, &QgsSourceFieldsProperties::attributesListCellChanged );
connect( mFieldsList, &QTableWidget::cellPressed, this, &QgsSourceFieldsProperties::attributesListCellPressed );
updateButtons();
updateFieldRenamingStatus();
}
void QgsSourceFieldsProperties::updateFieldRenamingStatus()
{
bool canRenameFields = mLayer->isEditable() && ( mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::RenameAttributes ) && !mLayer->readOnly();
for ( int row = 0; row < mFieldsList->rowCount(); ++row )
{
if ( canRenameFields )
mFieldsList->item( row, AttrNameCol )->setFlags( mFieldsList->item( row, AttrNameCol )->flags() | Qt::ItemIsEditable );
else
mFieldsList->item( row, AttrNameCol )->setFlags( mFieldsList->item( row, AttrNameCol )->flags() & ~Qt::ItemIsEditable );
}
}
void QgsSourceFieldsProperties::updateExpression()
{
QToolButton *btn = qobject_cast<QToolButton *>( sender() );
Q_ASSERT( btn );
int index = btn->property( "Index" ).toInt();
const QString exp = mLayer->expressionField( index );
QgsExpressionContext context;
context << QgsExpressionContextUtils::globalScope()
<< QgsExpressionContextUtils::projectScope( QgsProject::instance() );
QgsExpressionBuilderDialog dlg( mLayer, exp, nullptr, QStringLiteral( "generic" ), context );
if ( dlg.exec() )
{
mLayer->updateExpressionField( index, dlg.expressionText() );
loadRows();
}
}
void QgsSourceFieldsProperties::attributeAdded( int idx )
{
bool sorted = mFieldsList->isSortingEnabled();
if ( sorted )
mFieldsList->setSortingEnabled( false );
const QgsFields &fields = mLayer->fields();
int row = mFieldsList->rowCount();
mFieldsList->insertRow( row );
setRow( row, idx, fields.at( idx ) );
mFieldsList->setCurrentCell( row, idx );
//in case there are rows following, there is increased the id to the correct ones
for ( int i = idx + 1; i < mIndexedWidgets.count(); i++ )
mIndexedWidgets.at( i )->setData( Qt::DisplayRole, i );
if ( sorted )
mFieldsList->setSortingEnabled( true );
for ( int i = 0; i < mFieldsList->columnCount(); i++ )
{
switch ( mLayer->fields().fieldOrigin( idx ) )
{
case QgsFields::OriginExpression:
if ( i == 7 ) continue;
mFieldsList->item( row, i )->setBackgroundColor( QColor( 200, 200, 255 ) );
break;
case QgsFields::OriginJoin:
mFieldsList->item( row, i )->setBackgroundColor( QColor( 200, 255, 200 ) );
break;
default:
mFieldsList->item( row, i )->setBackgroundColor( QColor( 255, 255, 200 ) );
break;
}
}
}
void QgsSourceFieldsProperties::attributeDeleted( int idx )
{
mFieldsList->removeRow( mIndexedWidgets.at( idx )->row() );
mIndexedWidgets.removeAt( idx );
for ( int i = idx; i < mIndexedWidgets.count(); i++ )
{
mIndexedWidgets.at( i )->setData( Qt::DisplayRole, i );
}
}
void QgsSourceFieldsProperties::setRow( int row, int idx, const QgsField &field )
{
QTableWidgetItem *dataItem = new QTableWidgetItem();
dataItem->setData( Qt::DisplayRole, idx );
switch ( mLayer->fields().fieldOrigin( idx ) )
{
case QgsFields::OriginExpression:
dataItem->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpression.svg" ) ) );
break;
case QgsFields::OriginJoin:
dataItem->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/propertyicons/join.svg" ) ) );
break;
default:
dataItem->setIcon( mLayer->fields().iconForField( idx ) );
break;
}
mFieldsList->setItem( row, AttrIdCol, dataItem );
mIndexedWidgets.insert( idx, mFieldsList->item( row, 0 ) );
mFieldsList->setItem( row, AttrNameCol, new QTableWidgetItem( field.name() ) );
mFieldsList->setItem( row, AttrAliasCol, new QTableWidgetItem( field.alias() ) );
mFieldsList->setItem( row, AttrTypeCol, new QTableWidgetItem( QVariant::typeToName( field.type() ) ) );
mFieldsList->setItem( row, AttrTypeNameCol, new QTableWidgetItem( field.typeName() ) );
mFieldsList->setItem( row, AttrLengthCol, new QTableWidgetItem( QString::number( field.length() ) ) );
mFieldsList->setItem( row, AttrPrecCol, new QTableWidgetItem( QString::number( field.precision() ) ) );
if ( mLayer->fields().fieldOrigin( idx ) == QgsFields::OriginExpression )
{
QWidget *expressionWidget = new QWidget;
expressionWidget->setLayout( new QHBoxLayout );
QToolButton *editExpressionButton = new QToolButton;
editExpressionButton->setProperty( "Index", idx );
editExpressionButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpression.svg" ) ) );
connect( editExpressionButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::updateExpression );
expressionWidget->layout()->setContentsMargins( 0, 0, 0, 0 );
expressionWidget->layout()->addWidget( editExpressionButton );
expressionWidget->layout()->addWidget( new QLabel( mLayer->expressionField( idx ) ) );
expressionWidget->setStyleSheet( "background-color: rgb( 200, 200, 255 )" );
mFieldsList->setCellWidget( row, AttrCommentCol, expressionWidget );
}
else
{
mFieldsList->setItem( row, AttrCommentCol, new QTableWidgetItem( field.comment() ) );
}
QList<int> notEditableCols = QList<int>()
<< AttrIdCol
<< AttrNameCol
<< AttrAliasCol
<< AttrTypeCol
<< AttrTypeNameCol
<< AttrLengthCol
<< AttrPrecCol
<< AttrCommentCol;
Q_FOREACH ( int i, notEditableCols )
{
if ( notEditableCols[i] != AttrCommentCol || mLayer->fields().fieldOrigin( idx ) != QgsFields::OriginExpression )
mFieldsList->item( row, i )->setFlags( mFieldsList->item( row, i )->flags() & ~Qt::ItemIsEditable );
if ( notEditableCols[i] == AttrAliasCol )
mFieldsList->item( row, i )->setToolTip( tr( "Edit alias in the Form config tab" ) );
}
bool canRenameFields = mLayer->isEditable() && ( mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::RenameAttributes ) && !mLayer->readOnly();
if ( canRenameFields )
mFieldsList->item( row, AttrNameCol )->setFlags( mFieldsList->item( row, AttrNameCol )->flags() | Qt::ItemIsEditable );
else
mFieldsList->item( row, AttrNameCol )->setFlags( mFieldsList->item( row, AttrNameCol )->flags() & ~Qt::ItemIsEditable );
//published WMS/WFS attributes
QTableWidgetItem *wmsAttrItem = new QTableWidgetItem();
wmsAttrItem->setCheckState( mLayer->excludeAttributesWms().contains( field.name() ) ? Qt::Unchecked : Qt::Checked );
wmsAttrItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable );
mFieldsList->setItem( row, AttrWMSCol, wmsAttrItem );
QTableWidgetItem *wfsAttrItem = new QTableWidgetItem();
wfsAttrItem->setCheckState( mLayer->excludeAttributesWfs().contains( field.name() ) ? Qt::Unchecked : Qt::Checked );
wfsAttrItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable );
mFieldsList->setItem( row, AttrWFSCol, wfsAttrItem );
}
bool QgsSourceFieldsProperties::addAttribute( const QgsField &field )
{
QgsDebugMsg( "inserting attribute " + field.name() + " of type " + field.typeName() );
mLayer->beginEditCommand( tr( "Added attribute" ) );
if ( mLayer->addAttribute( field ) )
{
mLayer->endEditCommand();
return true;
}
else
{
mLayer->destroyEditCommand();
QMessageBox::critical( this, tr( "Add Field" ), tr( "Failed to add field '%1' of type '%2'. Is the field name unique?" ).arg( field.name(), field.typeName() ) );
return false;
}
}
void QgsSourceFieldsProperties::apply()
{
QSet<QString> excludeAttributesWMS, excludeAttributesWFS;
for ( int i = 0; i < mFieldsList->rowCount(); i++ )
{
if ( mFieldsList->item( i, AttrWMSCol )->checkState() == Qt::Unchecked )
{
excludeAttributesWMS.insert( mFieldsList->item( i, AttrNameCol )->text() );
}
if ( mFieldsList->item( i, AttrWFSCol )->checkState() == Qt::Unchecked )
{
excludeAttributesWFS.insert( mFieldsList->item( i, AttrNameCol )->text() );
}
}
mLayer->setExcludeAttributesWms( excludeAttributesWMS );
mLayer->setExcludeAttributesWfs( excludeAttributesWFS );
}
//SLOTS
void QgsSourceFieldsProperties::editingToggled()
{
updateButtons();
updateFieldRenamingStatus();
}
void QgsSourceFieldsProperties::addAttributeClicked()
{
QgsAddAttrDialog dialog( mLayer, this );
if ( dialog.exec() == QDialog::Accepted )
{
addAttribute( dialog.field() );
loadRows();
}
}
void QgsSourceFieldsProperties::deleteAttributeClicked()
{
QSet<int> providerFields;
QSet<int> expressionFields;
Q_FOREACH ( QTableWidgetItem *item, mFieldsList->selectedItems() )
{
if ( item->column() == 0 )
{
int idx = mIndexedWidgets.indexOf( item );
if ( idx < 0 )
continue;
if ( mLayer->fields().fieldOrigin( idx ) == QgsFields::OriginExpression )
expressionFields << idx;
else
providerFields << idx;
}
}
if ( !expressionFields.isEmpty() )
mLayer->deleteAttributes( expressionFields.toList() );
if ( !providerFields.isEmpty() )
{
mLayer->beginEditCommand( tr( "Deleted attributes" ) );
if ( mLayer->deleteAttributes( providerFields.toList() ) )
mLayer->endEditCommand();
else
mLayer->destroyEditCommand();
}
}
void QgsSourceFieldsProperties::calculateFieldClicked()
{
if ( !mLayer )
{
return;
}
QgsFieldCalculator calc( mLayer, this );
if ( calc.exec() == QDialog::Accepted )
{
loadRows();
}
}
void QgsSourceFieldsProperties::attributesListCellChanged( int row, int column )
{
if ( column == AttrNameCol && mLayer && mLayer->isEditable() )
{
int idx = mIndexedWidgets.indexOf( mFieldsList->item( row, AttrIdCol ) );
QTableWidgetItem *nameItem = mFieldsList->item( row, column );
//avoiding that something will be changed, just because this is triggered by simple re-sorting
if ( !nameItem ||
nameItem->text().isEmpty() ||
!mLayer->fields().exists( idx ) ||
mLayer->fields().at( idx ).name() == nameItem->text()
)
return;
mLayer->beginEditCommand( tr( "Rename attribute" ) );
if ( mLayer->renameAttribute( idx, nameItem->text() ) )
{
mLayer->endEditCommand();
}
else
{
mLayer->destroyEditCommand();
QMessageBox::critical( this, tr( "Rename Field" ), tr( "Failed to rename field to '%1'. Is the field name unique?" ).arg( nameItem->text() ) );
}
}
}
void QgsSourceFieldsProperties::attributesListCellPressed( int /*row*/, int /*column*/ )
{
updateButtons();
}
//NICE FUNCTIONS
void QgsSourceFieldsProperties::updateButtons()
{
int cap = mLayer->dataProvider()->capabilities();
mToggleEditingButton->setEnabled( ( cap & QgsVectorDataProvider::ChangeAttributeValues ) && !mLayer->readOnly() );
if ( mLayer->isEditable() )
{
mDeleteAttributeButton->setEnabled( cap & QgsVectorDataProvider::DeleteAttributes );
mAddAttributeButton->setEnabled( cap & QgsVectorDataProvider::AddAttributes );
mToggleEditingButton->setChecked( true );
}
else
{
mToggleEditingButton->setChecked( false );
mAddAttributeButton->setEnabled( false );
// Enable delete button if items are selected
mDeleteAttributeButton->setEnabled( !mFieldsList->selectedItems().isEmpty() );
// and only if all selected items have their origin in an expression
Q_FOREACH ( QTableWidgetItem *item, mFieldsList->selectedItems() )
{
if ( item->column() == 0 )
{
int idx = mIndexedWidgets.indexOf( item );
if ( mLayer->fields().fieldOrigin( idx ) != QgsFields::OriginExpression )
{
mDeleteAttributeButton->setEnabled( false );
break;
}
}
}
}
}
| dwadler/QGIS | src/app/qgssourcefieldsproperties.cpp | C++ | gpl-2.0 | 16,637 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
<!DOCTYPE html>
<html lang="es_MX">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/estilo.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<?php echo link_tag('css/sistema.css'); ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body style="background-color: #ffffff;">
<div class="container-fluid1">
<div id="foo">
<p id="spin_label" style="position:absolute; width: 100%; top: 50%; margin-top: 60px; text-align: center;">
</p>
</div>
<div class="row-fluid1" id="wrapper1">
<div class="alert" id="messages"></div>
<!-- Inicia Formulario -->
| estrategasdigitales/Golone | iframe2/app/views/header1.php | PHP | gpl-2.0 | 1,200 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_supperadmin
*
* @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
$supperAdmin = JFactory::isSupperAdmin();
// Include the component HTML helpers.
JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html');
JHtml::_('bootstrap.tooltip');
JHtml::_('behavior.multiselect');
JHtml::_('formbehavior.chosen', 'select');
$user = JFactory::getUser();
$listOrder = $this->escape($this->state->get('list.ordering'));
$listDirn = $this->escape($this->state->get('list.direction'));
$canOrder = $user->authorise('core.edit.state', 'com_supperadmin');
$saveOrder = $listOrder == 'ordering';
if ($saveOrder) {
$saveOrderingUrl = 'index.php?option=com_supperadmin&task=modules.saveOrderAjax&tmpl=component';
JHtml::_('sortablelist.sortable', 'articleList', 'adminForm', strtolower($listDirn), $saveOrderingUrl);
}
$sortFields = $this->getSortFields();
?>
<script type="text/javascript">
Joomla.orderTable = function () {
table = document.getElementById("sortTable");
direction = document.getElementById("directionTable");
order = table.options[table.selectedIndex].value;
if (order != '<?php echo $listOrder; ?>') {
dirn = 'asc';
}
else {
dirn = direction.options[direction.selectedIndex].value;
}
Joomla.tableOrdering(order, dirn, '');
}
</script>
<div class="view-modules-default">
<?php echo $this->render_toolbar() ?>
<form action="<?php echo JRoute::_('index.php?option=com_supperadmin&view=modules'); ?>" method="post"
name="adminForm" id="adminForm">
<div id="main-container">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-12">
<?php
echo JLayoutHelper::render('joomla.searchtools.default', array('view' => $this));
?>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-striped" id="itemList">
<thead>
<tr>
<th width="1%" class="nowrap center hidden-phone">
<?php echo JHtml::_('grid.sort', '<i class="icon-menu-2"></i>', 'ordering', $listDirn, $listOrder, null, 'asc', 'JGRID_HEADING_ORDERING'); ?>
</th>
<th width="1%" class="hidden-phone">
<?php echo JHtml::_('grid.checkall'); ?>
</th>
<th width="1%" class="nowrap center">
<?php echo JHtml::_('grid.sort', 'JSTATUS', 'enabled', $listDirn, $listOrder); ?>
</th>
<th class="title">
<?php echo JHtml::_('grid.sort', 'module title', 'name', $listDirn, $listOrder); ?>
</th>
<th class="title">
<?php echo JHtml::_('grid.sort', 'module name', 'name', $listDirn, $listOrder); ?>
</th>
<th class="title">
<?php echo JHtml::_('grid.sort', 'website', 'a.website_name', $listDirn, $listOrder); ?>
</th>
<th class="title">
<?php echo JHtml::_('grid.sort', 'Is System', 'a.issystem', $listDirn, $listOrder); ?>
</th>
<th width="5%" class="hidden-phone">
<?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ACCESS', 'access', $listDirn, $listOrder); ?>
</th>
<th width="1%" class="nowrap center hidden-phone">
<?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ID', 'id', $listDirn, $listOrder); ?>
</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="12">
<?php echo $this->pagination->getListFooter(); ?>
</td>
</tr>
</tfoot>
<tbody>
<?php foreach ($this->items as $i => $item) :
$ordering = ($listOrder == 'ordering');
$canEdit = $user->authorise('core.edit', 'com_supperadmin');
$canCheckin = $user->authorise('core.manage', 'com_checkin') || $item->checked_out == $user->get('id') || $item->checked_out == 0;
$canChange = $user->authorise('core.edit.state', 'com_supperadmin') && $canCheckin;
?>
<tr class="row<?php echo $i % 2; ?>" item-id="<?php echo $item->id ?>"
sortable-group-id="<?php echo $item->folder ?>">
<td class="order nowrap center hidden-phone">
<?php
$iconClass = '';
if (!$canChange) {
$iconClass = ' inactive';
} elseif (!$saveOrder) {
$iconClass = ' inactive tip-top hasTooltip" title="' . JHtml::tooltipText('JORDERINGDISABLED');
}
?>
<span class="sortable-handler<?php echo $iconClass ?>">
<i class="icon-menu"></i>
</span>
<?php if ($canChange && $saveOrder) : ?>
<input type="text" style="display:none" name="order[]" size="5"
value="<?php echo $item->ordering; ?>" class="width-20 text-area-order "/>
<?php endif; ?>
</td>
<td class="center hidden-phone">
<?php echo JHtml::_('grid.id', $i, $item->id); ?>
</td>
<td class="center">
<?php echo JHtml::_('jgrid.published', $item->enabled, $i, 'modules.', $canChange); ?>
</td>
<td>
<?php if ($item->checked_out) : ?>
<?php echo JHtml::_('jgrid.checkedout', $i, $item->editor, $item->checked_out_time, 'supperadmin.', $canCheckin); ?>
<?php endif; ?>
<?php if ($canEdit) : ?>
<a class="quick-edit-title"
href="<?php echo JRoute::_('index.php?option=com_supperadmin&task=module.edit&id=' . (int)$item->id); ?>">
<?php echo $item->title; ?></a>
<?php else : ?>
<?php echo $item->title; ?>
<?php endif; ?>
</td>
<td>
<?php if ($item->checked_out) : ?>
<?php echo JHtml::_('jgrid.checkedout', $i, $item->editor, $item->checked_out_time, 'supperadmin.', $canCheckin); ?>
<?php endif; ?>
<?php if ($canEdit) : ?>
<a class="quick-edit-title"
href="<?php echo JRoute::_('index.php?option=com_supperadmin&task=module.edit&id=' . (int)$item->id); ?>">
<?php echo $item->module; ?></a>
<?php else : ?>
<?php echo $item->module; ?>
<?php endif; ?>
</td>
<td class="center hidden-phone">
<?php echo $item->website_name ?>
</td>
<td class="center">
<?php echo JHtml::_('jgrid.is_system', $item->issystem, $i, 'modules.', $canChange); ?>
</td>
<td class="small hidden-phone">
<?php echo $this->escape($item->access_level); ?>
</td>
<td class="center hidden-phone">
<?php echo (int)$item->id; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
<input type="hidden" name="task" value=""/>
<input type="hidden" name="boxchecked" value="0"/>
<input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>"/>
<input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>"/>
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
</div>
<?php
// Search tools bar
echo JLayoutHelper::render('joomla.contextmenu.contextmenu', array('view' => $this), null, array('debug' => false));
?> | cuongnd/test_pro | components/website/website_supper_admin/com_supperadmin/views/modules/tmpl/default.php | PHP | gpl-2.0 | 11,749 |
/* Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
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, version 2.0, 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-1335 USA */
/**
@file storage/perfschema/pfs_setup_object.cc
Performance schema setup object (implementation).
*/
#include "my_global.h"
#include "my_sys.h"
#include "my_base.h"
#include "sql_string.h"
#include "pfs.h"
#include "pfs_stat.h"
#include "pfs_instr.h"
#include "pfs_setup_object.h"
#include "pfs_global.h"
/**
@addtogroup Performance_schema_buffers
@{
*/
uint setup_objects_version= 0;
ulong setup_object_max;
PFS_setup_object *setup_object_array= NULL;
LF_HASH setup_object_hash;
static bool setup_object_hash_inited= false;
/**
Initialize the setup object buffers.
@param param sizing parameters
@return 0 on success
*/
int init_setup_object(const PFS_global_param *param)
{
setup_object_max= param->m_setup_object_sizing;
setup_object_array= NULL;
if (setup_object_max > 0)
{
setup_object_array= PFS_MALLOC_ARRAY(setup_object_max, sizeof(PFS_setup_object),
PFS_setup_object, MYF(MY_ZEROFILL));
if (unlikely(setup_object_array == NULL))
return 1;
}
return 0;
}
/** Cleanup all the setup object buffers. */
void cleanup_setup_object(void)
{
pfs_free(setup_object_array);
setup_object_array= NULL;
setup_object_max= 0;
}
C_MODE_START
static uchar *setup_object_hash_get_key(const uchar *entry, size_t *length,
my_bool)
{
const PFS_setup_object * const *typed_entry;
const PFS_setup_object *setup_object;
const void *result;
typed_entry= reinterpret_cast<const PFS_setup_object* const *> (entry);
DBUG_ASSERT(typed_entry != NULL);
setup_object= *typed_entry;
DBUG_ASSERT(setup_object != NULL);
*length= setup_object->m_key.m_key_length;
result= setup_object->m_key.m_hash_key;
return const_cast<uchar*> (reinterpret_cast<const uchar*> (result));
}
C_MODE_END
/**
Initialize the setup objects hash.
@return 0 on success
*/
int init_setup_object_hash(void)
{
if ((! setup_object_hash_inited) && (setup_object_max > 0))
{
lf_hash_init(&setup_object_hash, sizeof(PFS_setup_object*), LF_HASH_UNIQUE,
0, 0, setup_object_hash_get_key, &my_charset_bin);
/* setup_object_hash.size= setup_object_max; */
setup_object_hash_inited= true;
}
return 0;
}
/** Cleanup the setup objects hash. */
void cleanup_setup_object_hash(void)
{
if (setup_object_hash_inited)
{
setup_object_hash_inited= false;
lf_hash_destroy(&setup_object_hash);
}
}
static LF_PINS* get_setup_object_hash_pins(PFS_thread *thread)
{
if (unlikely(thread->m_setup_object_hash_pins == NULL))
{
if (! setup_object_hash_inited)
return NULL;
thread->m_setup_object_hash_pins= lf_hash_get_pins(&setup_object_hash);
}
return thread->m_setup_object_hash_pins;
}
static void set_setup_object_key(PFS_setup_object_key *key,
enum_object_type object_type,
const char *schema, uint schema_length,
const char *object, uint object_length)
{
DBUG_ASSERT(schema_length <= NAME_LEN);
DBUG_ASSERT(object_length <= NAME_LEN);
char *ptr= &key->m_hash_key[0];
ptr[0]= (char) object_type;
ptr++;
if (schema_length)
{
memcpy(ptr, schema, schema_length);
ptr+= schema_length;
}
ptr[0]= 0;
ptr++;
if (object_length)
{
memcpy(ptr, object, object_length);
ptr+= object_length;
}
ptr[0]= 0;
ptr++;
key->m_key_length= (uint)(ptr - &key->m_hash_key[0]);
}
int insert_setup_object(enum_object_type object_type, const String *schema,
const String *object, bool enabled, bool timed)
{
if (setup_object_max == 0)
return HA_ERR_RECORD_FILE_FULL;
PFS_thread *thread= PFS_thread::get_current_thread();
if (unlikely(thread == NULL))
return HA_ERR_OUT_OF_MEM;
LF_PINS* pins= get_setup_object_hash_pins(thread);
if (unlikely(pins == NULL))
return HA_ERR_OUT_OF_MEM;
static uint PFS_ALIGNED setup_object_monotonic_index= 0;
uint index;
uint attempts= 0;
PFS_setup_object *pfs;
while (++attempts <= setup_object_max)
{
/* See create_mutex() */
index= PFS_atomic::add_u32(& setup_object_monotonic_index, 1) % setup_object_max;
pfs= setup_object_array + index;
if (pfs->m_lock.is_free())
{
if (pfs->m_lock.free_to_dirty())
{
set_setup_object_key(&pfs->m_key, object_type,
schema->ptr(), schema->length(),
object->ptr(), object->length());
pfs->m_schema_name= &pfs->m_key.m_hash_key[1];
pfs->m_schema_name_length= schema->length();
pfs->m_object_name= pfs->m_schema_name + pfs->m_schema_name_length + 1;
pfs->m_object_name_length= object->length();
pfs->m_enabled= enabled;
pfs->m_timed= timed;
int res;
res= lf_hash_insert(&setup_object_hash, pins, &pfs);
if (likely(res == 0))
{
pfs->m_lock.dirty_to_allocated();
setup_objects_version++;
return 0;
}
pfs->m_lock.dirty_to_free();
if (res > 0)
return HA_ERR_FOUND_DUPP_KEY;
/* OOM in lf_hash_insert */
return HA_ERR_OUT_OF_MEM;
}
}
}
return HA_ERR_RECORD_FILE_FULL;
}
int delete_setup_object(enum_object_type object_type, const String *schema,
const String *object)
{
PFS_thread *thread= PFS_thread::get_current_thread();
if (unlikely(thread == NULL))
return HA_ERR_OUT_OF_MEM;
LF_PINS* pins= get_setup_object_hash_pins(thread);
if (unlikely(pins == NULL))
return HA_ERR_OUT_OF_MEM;
PFS_setup_object_key key;
set_setup_object_key(&key, object_type,
schema->ptr(), schema->length(),
object->ptr(), object->length());
PFS_setup_object **entry;
entry= reinterpret_cast<PFS_setup_object**>
(lf_hash_search(&setup_object_hash, pins, key.m_hash_key, key.m_key_length));
if (entry && (entry != MY_ERRPTR))
{
PFS_setup_object *pfs= *entry;
lf_hash_delete(&setup_object_hash, pins, key.m_hash_key, key.m_key_length);
pfs->m_lock.allocated_to_free();
}
lf_hash_search_unpin(pins);
setup_objects_version++;
return 0;
}
int reset_setup_object()
{
PFS_thread *thread= PFS_thread::get_current_thread();
if (unlikely(thread == NULL))
return HA_ERR_OUT_OF_MEM;
LF_PINS* pins= get_setup_object_hash_pins(thread);
if (unlikely(pins == NULL))
return HA_ERR_OUT_OF_MEM;
PFS_setup_object *pfs= setup_object_array;
PFS_setup_object *pfs_last= setup_object_array + setup_object_max;
for ( ; pfs < pfs_last; pfs++)
{
if (pfs->m_lock.is_populated())
{
lf_hash_delete(&setup_object_hash, pins,
pfs->m_key.m_hash_key, pfs->m_key.m_key_length);
pfs->m_lock.allocated_to_free();
}
}
setup_objects_version++;
return 0;
}
long setup_object_count()
{
return setup_object_hash.count;
}
void lookup_setup_object(PFS_thread *thread,
enum_object_type object_type,
const char *schema_name, int schema_name_length,
const char *object_name, int object_name_length,
bool *enabled, bool *timed)
{
PFS_setup_object_key key;
PFS_setup_object **entry;
PFS_setup_object *pfs;
int i;
/*
The table io instrumentation uses "TABLE" and "TEMPORARY TABLE".
SETUP_OBJECT uses "TABLE" for both concepts.
There is no way to provide a different setup for:
- TABLE foo.bar
- TEMPORARY TABLE foo.bar
*/
DBUG_ASSERT(object_type != OBJECT_TYPE_TEMPORARY_TABLE);
LF_PINS* pins= get_setup_object_hash_pins(thread);
if (unlikely(pins == NULL))
{
*enabled= false;
*timed= false;
return;
}
for (i= 1; i<=3; i++)
{
switch(i)
{
case 1:
/* Lookup OBJECT_TYPE + OBJECT_SCHEMA + OBJECT_NAME in SETUP_OBJECTS */
set_setup_object_key(&key,
object_type,
schema_name, schema_name_length,
object_name, object_name_length);
break;
case 2:
/* Lookup OBJECT_TYPE + OBJECT_SCHEMA + "%" in SETUP_OBJECTS */
set_setup_object_key(&key,
object_type,
schema_name, schema_name_length, "%", 1);
break;
case 3:
/* Lookup OBJECT_TYPE + "%" + "%" in SETUP_OBJECTS */
set_setup_object_key(&key, object_type, "%", 1, "%", 1);
break;
}
entry= reinterpret_cast<PFS_setup_object**>
(lf_hash_search(&setup_object_hash, pins, key.m_hash_key, key.m_key_length));
if (entry && (entry != MY_ERRPTR))
{
pfs= *entry;
*enabled= pfs->m_enabled;
*timed= pfs->m_timed;
lf_hash_search_unpin(pins);
return;
}
lf_hash_search_unpin(pins);
}
*enabled= false;
*timed= false;
return;
}
/** @} */
| grooverdan/mariadb-server | storage/perfschema/pfs_setup_object.cc | C++ | gpl-2.0 | 10,104 |
<?php
/** Neapolitan (Nnapulitano)
*
* See MessagesQqq.php for message documentation incl. usage of parameters
* To improve a translation please visit http://translatewiki.net
*
* @ingroup Language
* @file
*
* @author Carmine Colacino
* @author Cryptex
* @author E. abu Filumena
* @author SabineCretella
* @author לערי ריינהארט
*/
$fallback = 'it';
$namespaceNames = array(
NS_MEDIA => 'Media',
NS_SPECIAL => 'Speciàle',
NS_TALK => 'Chiàcchiera',
NS_USER => 'Utente',
NS_USER_TALK => 'Utente_chiàcchiera',
NS_PROJECT_TALK => '$1_chiàcchiera',
NS_FILE => 'Fiùra',
NS_FILE_TALK => 'Fiùra_chiàcchiera',
NS_MEDIAWIKI => 'MediaWiki',
NS_MEDIAWIKI_TALK => 'MediaWiki_chiàcchiera',
NS_TEMPLATE => 'Modello',
NS_TEMPLATE_TALK => 'Modello_chiàcchiera',
NS_HELP => 'Ajùto',
NS_HELP_TALK => 'Ajùto_chiàcchiera',
NS_CATEGORY => 'Categurìa',
NS_CATEGORY_TALK => 'Categurìa_chiàcchiera',
);
$namespaceAliases = array(
'Speciale' => NS_SPECIAL,
'Discussione' => NS_TALK,
'Utente' => NS_USER,
'Discussioni_utente' => NS_USER_TALK,
'Discussioni_$1' => NS_PROJECT_TALK,
'Immagine' => NS_FILE,
'Discussioni_immagine' => NS_FILE_TALK,
'MediaWiki' => NS_MEDIAWIKI,
'Discussioni_MediaWiki' => NS_MEDIAWIKI_TALK,
'Discussioni_template' => NS_TEMPLATE_TALK,
'Aiuto' => NS_HELP,
'Discussioni_aiuto' => NS_HELP_TALK,
'Categoria' => NS_CATEGORY,
'Discussioni_categoria' => NS_CATEGORY_TALK,
);
$messages = array(
# User preference toggles
'tog-underline' => "Sottolinia 'e jonte:",
'tog-highlightbroken' => 'Formatta \'e jonte defettose <a href="" class="new">accussì</a> (oppure: accussì<a href="" class="internal">?</a>).',
'tog-justify' => "Alliniamento d''e paracrafe mpare",
'tog-hideminor' => "Annascunne 'e cagne piccirille 'int'a ll'úrdeme cagne",
'tog-extendwatchlist' => "Spanne ll'asservate speciale pe fà vedé tutte 'e cagne possíbbele",
'tog-usenewrc' => 'Urdeme cagne avanzate (JavaScript)',
'tog-numberheadings' => "Annúmmera automatecamente 'e títule",
'tog-showtoolbar' => "Aspone 'a barra d''e stromiente 'e cagno (JavaScript)",
'tog-editondblclick' => "Cagna 'e pàggene cliccanno ddoje vote (JavaScript)",
'tog-editsection' => "Permette 'e cagnà 'e sezzione cu a jonta [cagna]",
'tog-editsectiononrightclick' => "Permette 'e cangne 'e sezzione cliccanno p''o tasto destro ncopp 'e titule 'e sezzione (JavaScript)",
'tog-showtoc' => "Mosta ll'innece pe 'e paggene cu cchiù 'e 3 sezzione",
'tog-rememberpassword' => "Ricurda 'a registrazzione pe' cchiu sessione",
'tog-editwidth' => "Larghezza massima d''a casella pe scrivere",
'underline-always' => 'Sèmpe',
'underline-never' => 'Màje',
# Dates
'sunday' => 'dumméneca',
'monday' => 'lunnerì',
'tuesday' => 'marterì',
'wednesday' => 'miercurì',
'thursday' => 'gioverì',
'friday' => 'viernarì',
'saturday' => 'sàbbato',
'sun' => 'dum',
'mon' => 'lun',
'tue' => 'mar',
'wed' => 'mier',
'thu' => 'gio',
'fri' => 'ven',
'sat' => 'sab',
'january' => 'jennaro',
'february' => 'frevàro',
'march' => 'màrzo',
'april' => 'abbrile',
'may_long' => 'màjo',
'june' => 'giùgno',
'july' => 'luglio',
'august' => 'aústo',
'september' => 'settembre',
'october' => 'ottobbre',
'november' => 'nuvembre',
'december' => 'dicèmbre',
'january-gen' => 'jennaro',
'february-gen' => 'frevaro',
'march-gen' => 'màrzo',
'april-gen' => 'abbrile',
'may-gen' => 'maggio',
'june-gen' => 'giùgno',
'july-gen' => 'luglio',
'august-gen' => 'aùsto',
'september-gen' => 'settembre',
'october-gen' => 'ottovre',
'november-gen' => 'nuvembre',
'december-gen' => 'dicembre',
'jan' => 'jen',
'feb' => 'fre',
'mar' => 'mar',
'apr' => 'abb',
'may' => 'maj',
'jun' => 'giu',
'jul' => 'lug',
'aug' => 'aus',
'sep' => 'set',
'oct' => 'ott',
'nov' => 'nuv',
'dec' => 'dic',
# Categories related messages
'category_header' => 'Paggene rìnt\'a categurìa "$1"',
'subcategories' => 'Categurìe secunnarie',
'about' => 'Nfromma',
'article' => 'Articulo',
'newwindow' => "(s'arape n'ata fenèsta)",
'cancel' => 'Scancèlla',
'mypage' => "'A paggena mia",
'mytalk' => "'E mmie chiacchieriàte",
'anontalk' => 'Chiacchierate pe chisto IP',
# Cologne Blue skin
'qbfind' => 'Truòva',
'qbedit' => 'Càgna',
'qbpageoptions' => 'Chesta paggena',
'qbpageinfo' => "Nfrummazzione ncopp'â paggena",
'qbmyoptions' => "'E ppaggene mie",
'qbspecialpages' => 'Pàggene speciàle',
'errorpagetitle' => 'Sbaglio',
'returnto' => 'Torna a $1.',
'help' => 'Ajùto',
'search' => 'Truova',
'searchbutton' => 'Truova',
'go' => 'Vàje',
'history' => "Verziune 'e primma",
'history_short' => 'Cronologgia',
'info_short' => 'Nfurmazzione',
'printableversion' => "Verzione pe' stampa",
'permalink' => 'Jonta permanente',
'edit' => 'Càgna',
'editthispage' => 'Càgna chesta paggena',
'delete' => 'Scancèlla',
'deletethispage' => 'Scancèlla chésta paggena',
'protect' => 'Ferma',
'protectthispage' => 'Ferma chesta paggena',
'unprotect' => 'Sferma',
'unprotectthispage' => 'Sferma chesta paggena',
'newpage' => 'Paggena nòva',
'talkpage' => "Paggena 'e chiàcchiera",
'talkpagelinktext' => 'Chiàcchiera',
'specialpage' => 'Paggena speciàle',
'talk' => 'Chiàcchiera',
'toolbox' => 'Strumiente',
'imagepage' => 'Paggena fiùra',
'otherlanguages' => 'Ate léngue',
'redirectedfrom' => "(Redirect 'a $1)",
'lastmodifiedat' => "Urdema cagnamiénto pe' a paggena: $2, $1.",
'viewcount' => 'Chesta paggena è stata lètta {{PLURAL:$1|una vòta|$1 vòte}}.',
'jumpto' => 'Vaje a:',
'jumptonavigation' => 'navigazione',
'jumptosearch' => 'truova',
# All link text and link target definitions of links into project namespace that get used by other message strings, with the exception of user group pages (see grouppage) and the disambiguation template definition (see disambiguations).
'aboutsite' => "'Nfrummazione ncòpp'a {{SITENAME}}",
'aboutpage' => "Project:'Nfrummazione",
'disclaimers' => 'Avvertimiènte',
'disclaimerpage' => 'Project:Avvertimiènte generale',
'edithelp' => 'Guida',
'helppage' => 'Help:Ajùto',
'mainpage' => 'Paggena prencepale',
'mainpage-description' => 'Paggena prencepale',
'portal' => "Porta d''a cummunetà",
'portal-url' => "Project:Porta d''a cummunetà",
'badaccess' => "Nun haje 'e premmesse abbastante.",
'newmessageslink' => "nuove 'mmasciàte",
'newmessagesdifflink' => "differenze cu 'a revisione precedente",
'youhavenewmessagesmulti' => 'Tiene nuove mmasciate $1',
'editsection' => 'càgna',
'editold' => 'càgna',
'toc' => 'Énnece',
'showtoc' => 'faje vedé',
'hidetoc' => 'annascunne',
'viewdeleted' => 'Vire $1?',
# Short words for each namespace, by default used in the namespace tab in monobook
'nstab-main' => 'Articulo',
'nstab-user' => 'Paggena utente',
'nstab-project' => "Paggena 'e servizio",
'nstab-image' => 'Fiura',
'nstab-mediawiki' => "'Mmasciata",
'nstab-help' => 'Ajùto',
'nstab-category' => 'Categurìa',
# General errors
'filedeleteerror' => 'Nun se pô scancellà \'o file "$1"',
'cannotdelete' => "Nun è possibbele scassà 'a paggena o 'a fiura addamannata. (Putria éssere stato già scancellato.)",
'badtitle' => "'O nnomme nun è jùsto",
# Login and logout pages
'logouttext' => "'''Site asciùte.'''
Putite cuntinuà a ausà {{SITENAME}} comme n'utente senza nomme, o si nò putite trasì n'ata vota, cu 'o stesso nomme o cu n'ato nomme.",
'welcomecreation' => "== Bemmenuto, $1! ==
'O cunto è stato criato currettamente. Nun scurdà 'e perzonalizzà 'e ppreferenze 'e {{SITENAME}}.",
'remembermypassword' => 'Allicuordate d"a password',
'yourdomainname' => "Spiecà 'o dumminio",
'login' => 'Tràse',
'userlogin' => "Tràse o cria n'acciesso nuovo",
'logout' => 'Jèsce',
'userlogout' => 'Jèsce',
'notloggedin' => 'Acciesso nun affettuato',
'nologin' => "Nun haje ancora n'acciesso? '''$1'''.",
'nologinlink' => 'Crialo mmo',
'createaccount' => 'Cria nu cunto nuovo',
'gotaccount' => "Tiene già nu cunto? '''$1'''.",
'gotaccountlink' => 'Tràse',
'loginerror' => "Probblema 'e accièsso",
'loginsuccesstitle' => 'Acciesso affettuato',
'nosuchusershort' => 'Nun ce stanno utente cu o nòmme "<nowiki>$1</nowiki>". Cuntrolla si scrivìste buòno.',
'nouserspecified' => "Tiene 'a dìcere nu nomme pricìso.",
'acct_creation_throttle_hit' => 'Ce dispiace, haje già criato $1 utente. Nun ne pô crià ate.',
'accountcreated' => 'Cunto criato',
'loginlanguagelabel' => 'Lengua: $1',
# Edit page toolbar
'image_sample' => 'Essempio.jpg',
'image_tip' => 'Fiura ncuorporata',
# Edit pages
'minoredit' => 'Chisto è nu cagnamiénto piccerillo',
'watchthis' => "Tiene d'uocchio chesta paggena",
'savearticle' => "Sarva 'a paggena",
'preview' => 'Anteprimma',
'showpreview' => 'Vere anteprimma',
'showdiff' => "Fa veré 'e cagnamiente",
'blockededitsource' => "Ccà sotto venono mmustate 'e '''cagnamiente fatte''' â paggena '''$1''':",
'loginreqtitle' => "Pe' cagnà chesta paggena abbesognate aseguì ll'acciesso ô sito.",
'loginreqlink' => "aseguì ll'acciesso",
'loginreqpagetext' => "Pe' veré ate ppaggene abbesognate $1.",
'accmailtitle' => "'O password è stato mannato.",
'accmailtext' => '\'A password pe ll\'utente "$1" fuje mannata ô nnerizzo $2.',
'previewnote' => "'''Chesta è sola n'anteprimma; 'e cagnamiénte â paggena NUN songo ancora sarvate!'''",
'editing' => "Cagnamiento 'e $1",
'templatesused' => "Template ausate 'a chesta paggena:",
# "Undo" feature
'undo-summary' => "Canciella 'o cagnamiento $1 'e [[Special:Contributions/$2|$2]] ([[User talk:$2|Chiàcchiera]])",
# History pages
'currentrev' => "Verzione 'e mmo",
# Revision deletion
'rev-delundel' => 'faje vedé/annascunne',
# Search results
'searchresults' => "Risultato d''a recerca",
'searchresulttext' => "Pe sapé de cchiù ncopp'â comme ascia 'a {{SITENAME}}, vere [[{{MediaWiki:Helppage}}|Ricerca in {{SITENAME}}]].",
'notitlematches' => "Voce addemannata nun truvata dint' 'e titule 'e articulo",
'notextmatches' => "Voce addemannata nun truvata dint' 'e teste 'e articulo",
'searchhelp-url' => 'Help:Ajùto',
'powersearch' => 'Truova',
# Preferences page
'mypreferences' => "Preferenze d''e mie",
'changepassword' => 'Cagna password',
'prefs-rc' => 'Urdeme nove',
'prefs-watchlist' => 'Asservate speciale',
'columns' => 'Culonne:',
'timezoneregion-africa' => 'Afreca',
'username' => 'Nomme utente',
'yourlanguage' => 'Lengua:',
# User rights log
'rightsnone' => '(nisciuno)',
# Recent changes
'recentchanges' => 'Urdeme nove',
'recentchangestext' => "Ncoppa chesta paggena song' appresentate ll'urdeme cagnamiente fatto ê cuntenute d\"o sito.",
'rcnote' => "Ccà sotto nce songo ll'urdeme {{PLURAL:$1|cangiamiento|'''$1''' cangiamiente}} 'e ll'urdeme {{PLURAL:$2|juorno|'''$2''' juorne}}, agghiuornate a $3.",
'rclistfrom' => "Faje vedé 'e cagnamiénte fatte a partì 'a $1",
'rcshowhideminor' => "$1 'e cagnamiénte piccerille",
'rcshowhidebots' => "$1 'e bot",
'rcshowhideliu' => "$1 ll'utente reggìstrate",
'rcshowhideanons' => "$1 ll'utente anonime",
'rcshowhidemine' => "$1 'e ffatiche mmee",
'rclinks' => "Faje vedé ll'urdeme $1 cagnamiente dint' ll'urdeme $2 juorne<br />$3",
'hide' => 'annascunne',
'show' => 'faje vedé',
'rc_categories_any' => 'Qualònca',
# Recent changes linked
'recentchangeslinked' => 'Cagnamiénte cullegate',
'recentchangeslinked-feed' => 'Cagnamiénte cullegate',
'recentchangeslinked-toolbox' => 'Cagnamiénte cullegate',
# Upload
'upload' => 'Careca file',
'uploadedimage' => 'ha carecato "[[$1]]"',
# Special:ListFiles
'listfiles_name' => 'Nomme',
# File description page
'file-anchor-link' => 'Fiura',
'filehist-user' => 'Utente',
'imagelinks' => 'Jonte ê ffiure',
# Random page
'randompage' => 'Na paggena qualsiase',
'randompage-nopages' => 'Nessuna pagina nel namespace selezionato.',
'disambiguations' => "Paggene 'e disambigua",
'doubleredirects' => 'Redirect duppie',
# Miscellaneous special pages
'nbytes' => '$1 {{PLURAL:$1|byte|byte}}',
'ncategories' => '$1 {{PLURAL:$1|categoria|categorie}}',
'nlinks' => '$1 {{PLURAL:$1|cullegamiento|cullegamiente}}',
'popularpages' => "Paggene cchiù 'speziunate",
'wantedpages' => 'Paggene cchiù addemannate',
'shortpages' => 'Paggene curte',
'longpages' => 'Paggene cchiú longhe',
'newpages' => 'Paggene cchiù frische',
'move' => 'Spusta',
'movethispage' => 'Spusta chesta paggena',
# Special:AllPages
'allpages' => "Tutte 'e ppaggene",
'allarticles' => "Tutt' 'e vvoce",
'allinnamespace' => "Tutt' 'e ppaggene d''o namespace $1",
# Special:Categories
'categories' => 'Categurìe',
'categoriespagetext' => "Lista cumpleta d\"e categurie presente ncopp' 'o sito.",
# Special:LinkSearch
'linksearch-ok' => 'Truova',
# Watchlist
'addedwatch' => 'Aggiunto ai Osservate Speciale tue',
'watch' => 'Secuta',
'notanarticle' => 'Chesta paggena nun è na voce',
'enotif_newpagetext' => 'Chesta è na paggena nòva.',
'changed' => 'cagnata',
# Delete
'deletepage' => 'Scancella paggena',
'excontent' => "'o cuntenuto era: '$1'",
'excontentauthor' => "'o cuntenuto era: '$1' (e ll'unneco cuntribbutore era '[[Special:Contributions/$2|$2]]')",
'exbeforeblank' => "'O cuntenuto apprimm' 'a ll'arrevacamento era: '$1'",
'exblank' => "'a paggena era vacante",
'actioncomplete' => 'Azzione fernuta',
'deletedtext' => 'Qauccheruno ha scancellata \'a paggena "<nowiki>$1</nowiki>". Addumannà \'o $2 pe na lista d"e ppaggene scancellate urdemamente.',
'deletedarticle' => 'ha scancellato "[[$1]]"',
'dellogpage' => 'Scancellazione',
'deletionlog' => 'Log d"e scancellazione',
'deletecomment' => 'Raggióne',
# Rollback
'rollback' => "Ausa na revizione 'e primma",
'revertpage' => "Cangiaje 'e cagnamiénte 'e [[Special:Contributions/$2|$2]] ([[User talk:$2|discussione]]), cu â verzione 'e pprimma 'e [[User:$1|$1]]",
# Protect
'prot_1movedto2' => 'ha spustato [[$1]] a [[$2]]',
'protect-expiry-options' => '2 ore:2 hours,1 juorno:1 day,3 juorne:3 days,1 semmana:1 week,2 semmane:2 weeks,1 mise:1 month,3 mese:3 months,6 mese:6 months,1 anno:1 year,infinito:infinite',
# Undelete
'viewdeletedpage' => "Vìre 'e ppàggine scancellate",
# Namespace form on various pages
'invert' => "abbarruca 'a sceveta",
# Contributions
'contributions' => 'Contribbute utente',
'mycontris' => 'Mie contribbute',
'sp-contributions-talk' => 'Chiàcchiera',
# What links here
'whatlinkshere' => 'Paggene ca cullegano a chesta',
'whatlinkshere-title' => 'Paggene ca cullegano a $1',
'nolinkshere' => "Nisciuna paggena cuntene jonte ca mpuntano a '''[[:$1]]'''.",
# Block/unblock
'blockip' => 'Ferma utelizzatóre',
'ipadressorusername' => 'Nnerizzo IP o nomme utente',
'ipboptions' => '2 ore:2 hours,1 juorno:1 day,3 juorne:3 days,1 semmana:1 week,2 semmane:2 weeks,1 mise:1 month,3 mese:3 months,6 mese:6 months,1 anno:1 year,infinito:infinite',
'blockipsuccesssub' => 'Blocco aseguito',
'blocklistline' => '$1, $2 ha fermato $3 ($4)',
'blocklink' => 'ferma',
'blocklogpage' => 'Blocche',
'blocklogentry' => 'ha fermato "[[$1]]" pe\' nu mumento \'e $2 $3',
'blocklogtext' => "Chesta è 'a lista d''e azzione 'e blocco e sblocco utente. 'E nnerizze IP bloccate automaticamente nun nce so'. Addumannà 'a [[Special:IPBlockList|lista IP bloccate]] pp' 'a lista d''e nnerizze e nomme utente 'o ca blocco nce sta.",
# Move page
'movearticle' => "Spusta 'a paggena",
'newtitle' => 'Titulo nuovo:',
'movepagebtn' => "Spusta 'a paggena",
'articleexists' => "Na paggena cu chisto nomme asiste già, o pure 'o nomme scegliuto nun è buono. Scegliere n'ato titulo.",
'movedto' => 'spustata a',
'1movedto2' => 'ha spustato [[$1]] a [[$2]]',
'1movedto2_redir' => '[[$1]] spustata a [[$2]] trammeto redirect',
'movereason' => 'Raggióne',
'delete_and_move' => 'Scancèlla e spusta',
'delete_and_move_confirm' => "Sì, suprascrivi 'a paggena asistente",
# Export
'export' => "Spurta 'e ppaggene",
# Namespace 8 related
'allmessages' => "'Mmasciate d''o sistema",
'allmessagesname' => 'Nomme',
'allmessagescurrent' => "Testo 'e mo",
# Special:Import
'import' => 'Mpurta paggene',
'import-interwiki-submit' => 'Mpurta',
# Import log
'import-logentry-upload' => 'ha mpurtato [[$1]] trammeto upload',
# Tooltip help for the actions
'tooltip-pt-logout' => 'Jésce (logout)',
'tooltip-minoredit' => 'Rénne chìsto cagnamiénto cchiù ppiccirìllo.',
'tooltip-save' => "Sàrva 'e cagnamiénte.",
'tooltip-preview' => "Primma 'e sarvà, vìre primma chille ca hê cagnàte!",
# Attribution
'others' => 'ate',
# Info page
'numedits' => "Nummero 'e cagnamiente (articulo): $1",
'numwatchers' => "Nummero 'e asservature: $1",
# Special:NewFiles
'noimages' => "Nun nc'è nind' 'a veré.",
'ilsubmit' => 'Truova',
'exif-xyresolution-i' => '$1 punte pe pollice (dpi)',
'exif-meteringmode-0' => 'Scanusciuto',
'exif-meteringmode-255' => 'Ato',
'exif-lightsource-0' => 'Scanusciuta',
'exif-lightsource-10' => "'Ntruvulato",
'exif-lightsource-11' => 'Aumbruso',
'exif-gaincontrol-0' => 'Nisciuno',
'exif-subjectdistancerange-0' => 'Scanusciuta',
# External editor support
'edit-externally-help' => "Pe piglià cchiù nfromma veré 'e [http://www.mediawiki.org/wiki/Manual:External_editors struzione] ('n ngrese)",
# 'all' in various places, this might be different for inflected languages
'namespacesall' => 'Tutte',
# E-mail address confirmation
'confirmemail_needlogin' => "Abbesognate $1 pe cunfirmà 'o nnerizzo 'e e-mail d''o vuosto.",
'confirmemail_loggedin' => "'O nnerizzo 'e e-mail è vàleto",
# Trackbacks
'trackbackremove' => '([$1 Scarta])',
# Delete conflict
'deletedwhileediting' => 'Attenziòne: quaccherùno have scancellàto chesta pàggena prìmma ca tu accuminciàste â scrìvere!',
# Auto-summaries
'autoredircomment' => 'Redirect â paggena [[$1]]',
'autosumm-new' => 'Paggena nuova: $1',
# Special:SpecialPages
'specialpages' => 'Paggene speciale',
);
| thewebmind/docs | languages/messages/MessagesNap.php | PHP | gpl-2.0 | 19,725 |
// SPDX-License-Identifier: GPL-2.0
#include "core/subsurface-string.h"
#include "qPrefDisplay.h"
#include "qPrefPrivate.h"
#include <QApplication>
#include <QFont>
static const QString group = QStringLiteral("Display");
QPointF qPrefDisplay::st_tooltip_position;
static const QPointF st_tooltip_position_default = QPointF(0,0);
QString qPrefDisplay::st_lastDir;
static const QString st_lastDir_default = "";
QString qPrefDisplay::st_theme;
static const QString st_theme_default = "Blue";
QString qPrefDisplay::st_userSurvey;
static const QString st_userSurvey_default = "";
QByteArray qPrefDisplay::st_mainSplitter;
static const QByteArray st_mainSplitter_default = "";
QByteArray qPrefDisplay::st_topSplitter;
static const QByteArray st_topSplitter_default = "";
QByteArray qPrefDisplay::st_bottomSplitter;
static const QByteArray st_bottomSplitter_default = "";
bool qPrefDisplay::st_maximized;
static bool st_maximized_default = false;
QByteArray qPrefDisplay::st_geometry;
static const QByteArray st_geometry_default = 0;
QByteArray qPrefDisplay::st_windowState;
static const QByteArray st_windowState_default = 0;
int qPrefDisplay::st_lastState;
static int st_lastState_default = false;
qPrefDisplay::qPrefDisplay(QObject *parent) : QObject(parent)
{
}
qPrefDisplay *qPrefDisplay::instance()
{
static qPrefDisplay *self = new qPrefDisplay;
return self;
}
void qPrefDisplay::loadSync(bool doSync)
{
disk_animation_speed(doSync);
disk_divelist_font(doSync);
disk_font_size(doSync);
disk_mobile_scale(doSync);
disk_display_invalid_dives(doSync);
disk_show_developer(doSync);
if (!doSync) {
load_tooltip_position();
load_theme();
load_userSurvey();
load_mainSplitter();
load_topSplitter();
load_bottomSplitter();
load_maximized();
load_geometry();
load_windowState();
load_lastState();
}
}
void qPrefDisplay::set_divelist_font(const QString &value)
{
QString newValue = value;
if (value.contains(","))
newValue = value.left(value.indexOf(","));
if (newValue != prefs.divelist_font &&
!subsurface_ignore_font(qPrintable(newValue))) {
qPrefPrivate::copy_txt(&prefs.divelist_font, value);
disk_divelist_font(true);
qApp->setFont(QFont(newValue));
emit instance()->divelist_fontChanged(value);
}
}
void qPrefDisplay::disk_divelist_font(bool doSync)
{
if (doSync)
qPrefPrivate::propSetValue(keyFromGroupAndName(group, "divelist_font"), prefs.divelist_font, default_prefs.divelist_font);
else
setCorrectFont();
}
void qPrefDisplay::set_font_size(double value)
{
if (!IS_FP_SAME(value, prefs.font_size)) {
prefs.font_size = value;
disk_font_size(true);
QFont defaultFont = qApp->font();
defaultFont.setPointSizeF(prefs.font_size * prefs.mobile_scale);
qApp->setFont(defaultFont);
emit instance()->font_sizeChanged(value);
}
}
void qPrefDisplay::disk_font_size(bool doSync)
{
// inverted logic compared to the other disk_xxx functions
if (!doSync)
setCorrectFont();
#if !defined(SUBSURFACE_MOBILE)
// we never want to save the font_size to disk - we always want to grab that from the system default
else
qPrefPrivate::propSetValue(keyFromGroupAndName(group, "font_size"), prefs.font_size, default_prefs.font_size);
#endif
}
void qPrefDisplay::set_mobile_scale(double value)
{
if (!IS_FP_SAME(value, prefs.mobile_scale)) {
prefs.mobile_scale = value;
disk_mobile_scale(true);
QFont defaultFont = qApp->font();
defaultFont.setPointSizeF(prefs.font_size * prefs.mobile_scale);
qApp->setFont(defaultFont);
emit instance()->mobile_scaleChanged(value);
emit instance()->font_sizeChanged(value);
}
}
void qPrefDisplay::disk_mobile_scale(bool doSync)
{
if (doSync) {
qPrefPrivate::propSetValue(keyFromGroupAndName(group, "mobile_scale"), prefs.mobile_scale, default_prefs.mobile_scale);
} else {
prefs.mobile_scale = qPrefPrivate::propValue(keyFromGroupAndName(group, "mobile_scale"), default_prefs.mobile_scale).toDouble();
setCorrectFont();
}
}
//JAN static const QString group = QStringLiteral("Animations");
HANDLE_PREFERENCE_INT(Display, "animation_speed", animation_speed);
HANDLE_PREFERENCE_BOOL(Display, "displayinvalid", display_invalid_dives);
HANDLE_PREFERENCE_BOOL(Display, "show_developer", show_developer);
void qPrefDisplay::setCorrectFont()
{
// get the font from the settings or our defaults
// respect the system default font size if none is explicitly set
QFont defaultFont = qPrefPrivate::propValue(keyFromGroupAndName(group, "divelist_font"), prefs.divelist_font).value<QFont>();
if (IS_FP_SAME(system_divelist_default_font_size, -1.0)) {
prefs.font_size = qApp->font().pointSizeF();
system_divelist_default_font_size = prefs.font_size; // this way we don't save it on exit
}
prefs.font_size = qPrefPrivate::propValue(keyFromGroupAndName(group, "font_size"), prefs.font_size).toFloat();
// painful effort to ignore previous default fonts on Windows - ridiculous
QString fontName = defaultFont.toString();
if (fontName.contains(","))
fontName = fontName.left(fontName.indexOf(","));
if (subsurface_ignore_font(qPrintable(fontName))) {
defaultFont = QFont(prefs.divelist_font);
} else {
free((void *)prefs.divelist_font);
prefs.divelist_font = copy_qstring(fontName);
}
defaultFont.setPointSizeF(prefs.font_size * prefs.mobile_scale);
qApp->setFont(defaultFont);
prefs.display_invalid_dives = qPrefPrivate::propValue(keyFromGroupAndName(group, "displayinvalid"), default_prefs.display_invalid_dives).toBool();
}
HANDLE_PROP_QSTRING(Display, "FileDialog/LastDir", lastDir);
HANDLE_PROP_QSTRING(Display, "Theme/currentTheme", theme);
HANDLE_PROP_QPOINTF(Display, "ProfileMap/tooltip_position", tooltip_position);
HANDLE_PROP_QSTRING(Display, "UserSurvey/SurveyDone", userSurvey);
HANDLE_PROP_QBYTEARRAY(Display, "MainWindow/mainSplitter", mainSplitter);
HANDLE_PROP_QBYTEARRAY(Display, "MainWindow/topSplitter", topSplitter);
HANDLE_PROP_QBYTEARRAY(Display, "MainWindow/bottomSplitter", bottomSplitter);
HANDLE_PROP_BOOL(Display, "MainWindow/maximized", maximized);
HANDLE_PROP_QBYTEARRAY(Display, "MainWindow/geometry", geometry);
HANDLE_PROP_QBYTEARRAY(Display, "MainWindow/windowState", windowState);
HANDLE_PROP_INT(Display, "MainWindow/lastState", lastState);
| dirkhh/subsurface | core/settings/qPrefDisplay.cpp | C++ | gpl-2.0 | 6,241 |
from datetime import datetime
from flask import current_app
from flask.cli import with_appcontext
from invenio_db import db
from hepdata.cli import fix
from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords
from hepdata.modules.submission.models import HEPSubmission, DataSubmission
from hepdata.modules.records.utils.common import get_record_by_id
from hepdata.modules.records.utils.doi_minter import generate_doi_for_table
from hepdata.modules.records.utils.submission import finalise_datasubmission
@fix.command()
@with_appcontext
def create_missing_datasubmission_records():
# Get submissions with missing IDs
missing_submissions = DataSubmission.query \
.join(HEPSubmission, HEPSubmission.publication_recid == DataSubmission.publication_recid) \
.filter(
DataSubmission.associated_recid == None,
DataSubmission.publication_inspire_id == None,
DataSubmission.version == HEPSubmission.version,
HEPSubmission.overall_status == 'finished')
missing_submissions = missing_submissions.all()
if not missing_submissions:
print("No datasubmissions found with missing record or inspire ids.")
return
# Organise missing submissions by publication
submissions_by_publication = {}
for submission in missing_submissions:
if submission.publication_recid in submissions_by_publication:
submissions_by_publication[submission.publication_recid].append(submission)
else:
submissions_by_publication[submission.publication_recid] = [submission]
# Loop through each publication
for publication_recid, submissions in submissions_by_publication.items():
publication_record = get_record_by_id(publication_recid)
current_time = "{:%Y-%m-%d %H:%M:%S}".format(datetime.utcnow())
generated_record_ids = []
for submission in submissions:
# Finalise each data submission that does not have a record
finalise_datasubmission(current_time, {},
generated_record_ids,
publication_record, publication_recid,
submission,
submission.version)
# Register the datasubmission's DOI
if not current_app.config.get('TESTING', False):
generate_doi_for_table.delay(submission.doi)
print(f"Generated DOI {submission.doi}")
else:
print(f"Would generate DOI {submission.doi}")
# finalise_datasubmission does not commit, so commit once for each publication
db.session.commit()
# Reindex the publication and its updated datasubmissions
index_record_ids([publication_recid] + generated_record_ids)
push_data_keywords(pub_ids=[publication_recid])
| HEPData/hepdata3 | fixes/missing_record_ids.py | Python | gpl-2.0 | 2,910 |
/******************************************************************************
*
* rawverse.cpp - code for class 'RawVerse'- a module that reads raw text
* files: ot and nt using indexs ??.bks ??.cps ??.vss
* and provides lookup and parsing functions based on
* class VerseKey
*
* $Id$
*
* Copyright 1997-2013 CrossWire Bible Society (http://www.crosswire.org)
* CrossWire Bible Society
* P. O. Box 2528
* Tempe, AZ 85280-2528
*
* 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.
*
* 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.
*
*/
#include <ctype.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <utilstr.h>
#include <rawverse.h>
#include <versekey.h>
#include <sysdata.h>
#include <filemgr.h>
#include <swbuf.h>
SWORD_NAMESPACE_START
/******************************************************************************
* RawVerse Statics
*/
int RawVerse::instance = 0;
const char RawVerse::nl = '\n';
/******************************************************************************
* RawVerse Constructor - Initializes data for instance of RawVerse
*
* ENT: ipath - path of the directory where data and index files are located.
* be sure to include the trailing separator (e.g. '/' or '\')
* (e.g. 'modules/texts/rawtext/webster/')
*/
RawVerse::RawVerse(const char *ipath, int fileMode)
{
SWBuf buf;
path = 0;
stdstr(&path, ipath);
if ((path[strlen(path)-1] == '/') || (path[strlen(path)-1] == '\\'))
path[strlen(path)-1] = 0;
if (fileMode == -1) { // try read/write if possible
fileMode = FileMgr::RDWR;
}
buf.setFormatted("%s/ot.vss", path);
idxfp[0] = FileMgr::getSystemFileMgr()->open(buf, fileMode, true);
buf.setFormatted("%s/nt.vss", path);
idxfp[1] = FileMgr::getSystemFileMgr()->open(buf, fileMode, true);
buf.setFormatted("%s/ot", path);
textfp[0] = FileMgr::getSystemFileMgr()->open(buf, fileMode, true);
buf.setFormatted("%s/nt", path);
textfp[1] = FileMgr::getSystemFileMgr()->open(buf, fileMode, true);
instance++;
}
/******************************************************************************
* RawVerse Destructor - Cleans up instance of RawVerse
*/
RawVerse::~RawVerse()
{
int loop1;
if (path)
delete [] path;
--instance;
for (loop1 = 0; loop1 < 2; loop1++) {
FileMgr::getSystemFileMgr()->close(idxfp[loop1]);
FileMgr::getSystemFileMgr()->close(textfp[loop1]);
}
}
/******************************************************************************
* RawVerse::findoffset - Finds the offset of the key verse from the indexes
*
* ENT: testmt - testament to find (0 - Bible/module introduction)
* idxoff - offset into .vss
* start - address to store the starting offset
* size - address to store the size of the entry
*/
void RawVerse::findOffset(char testmt, long idxoff, long *start, unsigned short *size) const {
idxoff *= 6;
if (!testmt)
testmt = ((idxfp[1]) ? 1:2);
if (idxfp[testmt-1]->getFd() >= 0) {
idxfp[testmt-1]->seek(idxoff, SEEK_SET);
__s32 tmpStart;
__u16 tmpSize;
idxfp[testmt-1]->read(&tmpStart, 4);
long len = idxfp[testmt-1]->read(&tmpSize, 2); // read size
*start = swordtoarch32(tmpStart);
*size = swordtoarch16(tmpSize);
if (len < 2) {
*size = (unsigned short)((*start) ? (textfp[testmt-1]->seek(0, SEEK_END) - (long)*start) : 0); // if for some reason we get an error reading size, make size to end of file
}
}
else {
*start = 0;
*size = 0;
}
}
/******************************************************************************
* RawVerse::readtext - gets text at a given offset
*
* ENT: testmt - testament file to search in (0 - Old; 1 - New)
* start - starting offset where the text is located in the file
* size - size of text entry + 2 (null)(null)
* buf - buffer to store text
*
*/
void RawVerse::readText(char testmt, long start, unsigned short size, SWBuf &buf) const {
buf = "";
buf.setFillByte(0);
buf.setSize(size + 1);
if (!testmt)
testmt = ((idxfp[1]) ? 1:2);
if (size) {
if (textfp[testmt-1]->getFd() >= 0) {
textfp[testmt-1]->seek(start, SEEK_SET);
textfp[testmt-1]->read(buf.getRawData(), (int)size);
}
}
}
/******************************************************************************
* RawVerse::settext - Sets text for current offset
*
* ENT: testmt - testament to find (0 - Bible/module introduction)
* idxoff - offset into .vss
* buf - buffer to store
* len - length of buffer (0 - null terminated)
*/
void RawVerse::doSetText(char testmt, long idxoff, const char *buf, long len)
{
__s32 start;
__u16 size;
idxoff *= 6;
if (!testmt)
testmt = ((idxfp[1]) ? 1:2);
size = (len < 0) ? strlen(buf) : len;
start = (__s32)textfp[testmt-1]->seek(0, SEEK_END);
idxfp[testmt-1]->seek(idxoff, SEEK_SET);
if (size) {
textfp[testmt-1]->seek(start, SEEK_SET);
textfp[testmt-1]->write(buf, (int)size);
// add a new line to make data file easier to read in an editor
textfp[testmt-1]->write(&nl, 1);
}
else {
start = 0;
}
start = archtosword32(start);
size = archtosword16(size);
idxfp[testmt-1]->write(&start, 4);
idxfp[testmt-1]->write(&size, 2);
}
/******************************************************************************
* RawVerse::linkentry - links one entry to another
*
* ENT: testmt - testament to find (0 - Bible/module introduction)
* destidxoff - dest offset into .vss
* srcidxoff - source offset into .vss
*/
void RawVerse::doLinkEntry(char testmt, long destidxoff, long srcidxoff) {
__s32 start;
__u16 size;
destidxoff *= 6;
srcidxoff *= 6;
if (!testmt)
testmt = ((idxfp[1]) ? 1:2);
// get source
idxfp[testmt-1]->seek(srcidxoff, SEEK_SET);
idxfp[testmt-1]->read(&start, 4);
idxfp[testmt-1]->read(&size, 2);
// write dest
idxfp[testmt-1]->seek(destidxoff, SEEK_SET);
idxfp[testmt-1]->write(&start, 4);
idxfp[testmt-1]->write(&size, 2);
}
/******************************************************************************
* RawVerse::createModule - Creates new module files
*
* ENT: path - directory to store module files
* RET: error status
*/
char RawVerse::createModule(const char *ipath, const char *v11n)
{
char *path = 0;
char *buf = new char [ strlen (ipath) + 20 ];
FileDesc *fd, *fd2;
stdstr(&path, ipath);
if ((path[strlen(path)-1] == '/') || (path[strlen(path)-1] == '\\'))
path[strlen(path)-1] = 0;
sprintf(buf, "%s/ot", path);
FileMgr::removeFile(buf);
fd = FileMgr::getSystemFileMgr()->open(buf, FileMgr::CREAT|FileMgr::WRONLY, FileMgr::IREAD|FileMgr::IWRITE);
fd->getFd();
FileMgr::getSystemFileMgr()->close(fd);
sprintf(buf, "%s/nt", path);
FileMgr::removeFile(buf);
fd = FileMgr::getSystemFileMgr()->open(buf, FileMgr::CREAT|FileMgr::WRONLY, FileMgr::IREAD|FileMgr::IWRITE);
fd->getFd();
FileMgr::getSystemFileMgr()->close(fd);
sprintf(buf, "%s/ot.vss", path);
FileMgr::removeFile(buf);
fd = FileMgr::getSystemFileMgr()->open(buf, FileMgr::CREAT|FileMgr::WRONLY, FileMgr::IREAD|FileMgr::IWRITE);
fd->getFd();
sprintf(buf, "%s/nt.vss", path);
FileMgr::removeFile(buf);
fd2 = FileMgr::getSystemFileMgr()->open(buf, FileMgr::CREAT|FileMgr::WRONLY, FileMgr::IREAD|FileMgr::IWRITE);
fd2->getFd();
VerseKey vk;
vk.setVersificationSystem(v11n);
vk.setIntros(1);
__s32 offset = 0;
__u16 size = 0;
offset = archtosword32(offset);
size = archtosword16(size);
for (vk = TOP; !vk.popError(); vk++) {
if (vk.getTestament() < 2) {
fd->write(&offset, 4);
fd->write(&size, 2);
}
else {
fd2->write(&offset, 4);
fd2->write(&size, 2);
}
}
fd2->write(&offset, 4);
fd2->write(&size, 2);
FileMgr::getSystemFileMgr()->close(fd);
FileMgr::getSystemFileMgr()->close(fd2);
delete [] path;
delete [] buf;
return 0;
}
SWORD_NAMESPACE_END
| greg-hellings/sword | src/modules/common/rawverse.cpp | C++ | gpl-2.0 | 8,079 |
#pragma once
#ifndef __TRINITY_UPDATEFIELDFLAGS_H__
#define __TRINITY_UPDATEFIELDFLAGS_H__
#include "UpdateFieldFlags.h"
// Auto generated for version 17359
// > Object
uint32 ObjectUpdateFieldFlags[OBJECT_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID
UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE
};
// > Object > Item
uint32 ItemUpdateFieldFlags[ITEM_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID
UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE
UF_FLAG_PUBLIC, // ITEM_FIELD_OWNER
UF_FLAG_PUBLIC, // ITEM_FIELD_OWNER
UF_FLAG_PUBLIC, // ITEM_FIELD_CONTAINED_IN
UF_FLAG_PUBLIC, // ITEM_FIELD_CONTAINED_IN
UF_FLAG_PUBLIC, // ITEM_FIELD_CREATOR
UF_FLAG_PUBLIC, // ITEM_FIELD_CREATOR
UF_FLAG_PUBLIC, // ITEM_FIELD_GIFT_CREATOR
UF_FLAG_PUBLIC, // ITEM_FIELD_GIFT_CREATOR
UF_FLAG_OWNER, // ITEM_FIELD_STACK_COUNT
UF_FLAG_OWNER, // ITEM_FIELD_EXPIRATION
UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES
UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES
UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES
UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES
UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES
UF_FLAG_PUBLIC, // ITEM_FIELD_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_PROPERTY_SEED
UF_FLAG_PUBLIC, // ITEM_FIELD_RANDOM_PROPERTIES_ID
UF_FLAG_OWNER, // ITEM_FIELD_DURABILITY
UF_FLAG_OWNER, // ITEM_FIELD_MAX_DURABILITY
UF_FLAG_PUBLIC, // ITEM_FIELD_CREATE_PLAYED_TIME
UF_FLAG_OWNER, // ITEM_FIELD_MODIFIERS_MASK
};
// > Object > Item > Container
uint32 ContainerUpdateFieldFlags[CONTAINER_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID
UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE
UF_FLAG_PUBLIC, // ITEM_FIELD_OWNER
UF_FLAG_PUBLIC, // ITEM_FIELD_OWNER
UF_FLAG_PUBLIC, // ITEM_FIELD_CONTAINED_IN
UF_FLAG_PUBLIC, // ITEM_FIELD_CONTAINED_IN
UF_FLAG_PUBLIC, // ITEM_FIELD_CREATOR
UF_FLAG_PUBLIC, // ITEM_FIELD_CREATOR
UF_FLAG_PUBLIC, // ITEM_FIELD_GIFT_CREATOR
UF_FLAG_PUBLIC, // ITEM_FIELD_GIFT_CREATOR
UF_FLAG_OWNER, // ITEM_FIELD_STACK_COUNT
UF_FLAG_OWNER, // ITEM_FIELD_EXPIRATION
UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES
UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES
UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES
UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES
UF_FLAG_OWNER, // ITEM_FIELD_SPELL_CHARGES
UF_FLAG_PUBLIC, // ITEM_FIELD_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_ENCHANTMENT
UF_FLAG_PUBLIC, // ITEM_FIELD_PROPERTY_SEED
UF_FLAG_PUBLIC, // ITEM_FIELD_RANDOM_PROPERTIES_ID
UF_FLAG_OWNER, // ITEM_FIELD_DURABILITY
UF_FLAG_OWNER, // ITEM_FIELD_MAX_DURABILITY
UF_FLAG_PUBLIC, // ITEM_FIELD_CREATE_PLAYED_TIME
UF_FLAG_OWNER, // ITEM_FIELD_MODIFIERS_MASK
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_SLOTS
UF_FLAG_PUBLIC, // CONTAINER_FIELD_NUM_SLOTS
};
// > Object > Unit
uint32 UnitUpdateFieldFlags[UNIT_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_PUBLIC | UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID
UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE
UF_FLAG_PUBLIC, // UNIT_FIELD_CHARM
UF_FLAG_PUBLIC, // UNIT_FIELD_CHARM
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMON
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMON
UF_FLAG_PRIVATE, // UNIT_FIELD_CRITTER
UF_FLAG_PRIVATE, // UNIT_FIELD_CRITTER
UF_FLAG_PUBLIC, // UNIT_FIELD_CHARMED_BY
UF_FLAG_PUBLIC, // UNIT_FIELD_CHARMED_BY
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONED_BY
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONED_BY
UF_FLAG_PUBLIC, // UNIT_FIELD_CREATED_BY
UF_FLAG_PUBLIC, // UNIT_FIELD_CREATED_BY
UF_FLAG_PUBLIC, // UNIT_FIELD_DEMON_CREATOR
UF_FLAG_PUBLIC, // UNIT_FIELD_DEMON_CREATOR
UF_FLAG_PUBLIC, // UNIT_FIELD_TARGET
UF_FLAG_PUBLIC, // UNIT_FIELD_TARGET
UF_FLAG_PUBLIC, // UNIT_FIELD_BATTLE_PET_COMPANION_GUID
UF_FLAG_PUBLIC, // UNIT_FIELD_BATTLE_PET_COMPANION_GUID
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_CHANNEL_OBJECT
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_CHANNEL_OBJECT
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_CHANNEL_SPELL
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONED_BY_HOME_REALM
UF_FLAG_PUBLIC, // UNIT_FIELD_SEX
UF_FLAG_PUBLIC, // UNIT_FIELD_DISPLAY_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_OVERRIDE_DISPLAY_POWER_ID
UF_FLAG_PUBLIC, // UNIT_FIELD_HEALTH
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_HEALTH
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
UF_FLAG_PUBLIC, // UNIT_FIELD_LEVEL
UF_FLAG_PUBLIC, // UNIT_FIELD_EFFECTIVE_LEVEL
UF_FLAG_PUBLIC, // UNIT_FIELD_FACTION_TEMPLATE
UF_FLAG_PUBLIC, // UNIT_FIELD_VIRTUAL_ITEM_ID
UF_FLAG_PUBLIC, // UNIT_FIELD_VIRTUAL_ITEM_ID
UF_FLAG_PUBLIC, // UNIT_FIELD_VIRTUAL_ITEM_ID
UF_FLAG_PUBLIC, // UNIT_FIELD_FLAGS
UF_FLAG_PUBLIC, // UNIT_FIELD_FLAGS2
UF_FLAG_PUBLIC, // UNIT_FIELD_AURA_STATE
UF_FLAG_PUBLIC, // UNIT_FIELD_ATTACK_ROUND_BASE_TIME
UF_FLAG_PUBLIC, // UNIT_FIELD_ATTACK_ROUND_BASE_TIME
UF_FLAG_PRIVATE, // UNIT_FIELD_RANGED_ATTACK_ROUND_BASE_TIME
UF_FLAG_PUBLIC, // UNIT_FIELD_BOUNDING_RADIUS
UF_FLAG_PUBLIC, // UNIT_FIELD_COMBAT_REACH
UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // UNIT_FIELD_DISPLAY_ID
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_NATIVE_DISPLAY_ID
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_MOUNT_DISPLAY_ID
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MIN_DAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MAX_DAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MIN_OFF_HAND_DAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MAX_OFF_HAND_DAMAGE
UF_FLAG_PUBLIC, // UNIT_FIELD_ANIM_TIER
UF_FLAG_PUBLIC, // UNIT_FIELD_PET_NUMBER
UF_FLAG_PUBLIC, // UNIT_FIELD_PET_NAME_TIMESTAMP
UF_FLAG_OWNER, // UNIT_FIELD_PET_EXPERIENCE
UF_FLAG_OWNER, // UNIT_FIELD_PET_NEXT_LEVEL_EXPERIENCE
UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_CASTING_SPEED
UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_SPELL_HASTE
UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_HASTE
UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_RANGED_HASTE
UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_HASTE_REGEN
UF_FLAG_PUBLIC, // UNIT_FIELD_CREATED_BY_SPELL
UF_FLAG_PUBLIC | UF_FLAG_VIEWER_DEPENDENT, // UNIT_FIELD_NPC_FLAGS
UF_FLAG_PUBLIC, // UNIT_FIELD_NPC_FLAGS
UF_FLAG_PUBLIC, // UNIT_FIELD_EMOTE_STATE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PUBLIC, // UNIT_FIELD_BASE_MANA
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_BASE_HEALTH
UF_FLAG_PUBLIC, // UNIT_FIELD_SHAPESHIFT_FORM
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MOD_POS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MOD_NEG
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MOD_POS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MOD_NEG
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MIN_RANGED_DAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MAX_RANGED_DAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MAX_HEALTH_MODIFIER
UF_FLAG_PUBLIC, // UNIT_FIELD_HOVER_HEIGHT
UF_FLAG_PUBLIC, // UNIT_FIELD_MIN_ITEM_LEVEL
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_ITEM_LEVEL
UF_FLAG_PUBLIC, // UNIT_FIELD_WILD_BATTLE_PET_LEVEL
UF_FLAG_PUBLIC, // UNIT_FIELD_BATTLE_PET_COMPANION_NAME_TIMESTAMP
UF_FLAG_PUBLIC, // UNIT_FIELD_INTERACT_SPELL_ID
};
// > Object > Unit > Player
uint32 PlayerUpdateFieldFlags[PLAYER_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_PUBLIC | UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID
UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE
UF_FLAG_PUBLIC, // UNIT_FIELD_CHARM
UF_FLAG_PUBLIC, // UNIT_FIELD_CHARM
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMON
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMON
UF_FLAG_PRIVATE, // UNIT_FIELD_CRITTER
UF_FLAG_PRIVATE, // UNIT_FIELD_CRITTER
UF_FLAG_PUBLIC, // UNIT_FIELD_CHARMED_BY
UF_FLAG_PUBLIC, // UNIT_FIELD_CHARMED_BY
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONED_BY
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONED_BY
UF_FLAG_PUBLIC, // UNIT_FIELD_CREATED_BY
UF_FLAG_PUBLIC, // UNIT_FIELD_CREATED_BY
UF_FLAG_PUBLIC, // UNIT_FIELD_DEMON_CREATOR
UF_FLAG_PUBLIC, // UNIT_FIELD_DEMON_CREATOR
UF_FLAG_PUBLIC, // UNIT_FIELD_TARGET
UF_FLAG_PUBLIC, // UNIT_FIELD_TARGET
UF_FLAG_PUBLIC, // UNIT_FIELD_BATTLE_PET_COMPANION_GUID
UF_FLAG_PUBLIC, // UNIT_FIELD_BATTLE_PET_COMPANION_GUID
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_CHANNEL_OBJECT
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_CHANNEL_OBJECT
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_CHANNEL_SPELL
UF_FLAG_PUBLIC, // UNIT_FIELD_SUMMONED_BY_HOME_REALM
UF_FLAG_PUBLIC, // UNIT_FIELD_SEX
UF_FLAG_PUBLIC, // UNIT_FIELD_DISPLAY_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_OVERRIDE_DISPLAY_POWER_ID
UF_FLAG_PUBLIC, // UNIT_FIELD_HEALTH
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_HEALTH
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_POWER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_ALL_UNITS, // UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
UF_FLAG_PUBLIC, // UNIT_FIELD_LEVEL
UF_FLAG_PUBLIC, // UNIT_FIELD_EFFECTIVE_LEVEL
UF_FLAG_PUBLIC, // UNIT_FIELD_FACTION_TEMPLATE
UF_FLAG_PUBLIC, // UNIT_FIELD_VIRTUAL_ITEM_ID
UF_FLAG_PUBLIC, // UNIT_FIELD_VIRTUAL_ITEM_ID
UF_FLAG_PUBLIC, // UNIT_FIELD_VIRTUAL_ITEM_ID
UF_FLAG_PUBLIC, // UNIT_FIELD_FLAGS
UF_FLAG_PUBLIC, // UNIT_FIELD_FLAGS2
UF_FLAG_PUBLIC, // UNIT_FIELD_AURA_STATE
UF_FLAG_PUBLIC, // UNIT_FIELD_ATTACK_ROUND_BASE_TIME
UF_FLAG_PUBLIC, // UNIT_FIELD_ATTACK_ROUND_BASE_TIME
UF_FLAG_PRIVATE, // UNIT_FIELD_RANGED_ATTACK_ROUND_BASE_TIME
UF_FLAG_PUBLIC, // UNIT_FIELD_BOUNDING_RADIUS
UF_FLAG_PUBLIC, // UNIT_FIELD_COMBAT_REACH
UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // UNIT_FIELD_DISPLAY_ID
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_NATIVE_DISPLAY_ID
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // UNIT_FIELD_MOUNT_DISPLAY_ID
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MIN_DAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MAX_DAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MIN_OFF_HAND_DAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_MAX_OFF_HAND_DAMAGE
UF_FLAG_PUBLIC, // UNIT_FIELD_ANIM_TIER
UF_FLAG_PUBLIC, // UNIT_FIELD_PET_NUMBER
UF_FLAG_PUBLIC, // UNIT_FIELD_PET_NAME_TIMESTAMP
UF_FLAG_OWNER, // UNIT_FIELD_PET_EXPERIENCE
UF_FLAG_OWNER, // UNIT_FIELD_PET_NEXT_LEVEL_EXPERIENCE
UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_CASTING_SPEED
UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_SPELL_HASTE
UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_HASTE
UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_RANGED_HASTE
UF_FLAG_PUBLIC, // UNIT_FIELD_MOD_HASTE_REGEN
UF_FLAG_PUBLIC, // UNIT_FIELD_CREATED_BY_SPELL
UF_FLAG_PUBLIC | UF_FLAG_VIEWER_DEPENDENT, // UNIT_FIELD_NPC_FLAGS
UF_FLAG_PUBLIC, // UNIT_FIELD_NPC_FLAGS
UF_FLAG_PUBLIC, // UNIT_FIELD_EMOTE_STATE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STATS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_POS_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_STAT_NEG_BUFF
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER | UF_FLAG_EMPATH, // UNIT_FIELD_RESISTANCES
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_POSITIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RESISTANCE_BUFF_MODS_NEGATIVE
UF_FLAG_PUBLIC, // UNIT_FIELD_BASE_MANA
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_BASE_HEALTH
UF_FLAG_PUBLIC, // UNIT_FIELD_SHAPESHIFT_FORM
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MOD_POS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MOD_NEG
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_ATTACK_POWER_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MOD_POS
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MOD_NEG
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MIN_RANGED_DAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MAX_RANGED_DAMAGE
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MODIFIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_POWER_COST_MULTIPLIER
UF_FLAG_PRIVATE | UF_FLAG_OWNER, // UNIT_FIELD_MAX_HEALTH_MODIFIER
UF_FLAG_PUBLIC, // UNIT_FIELD_HOVER_HEIGHT
UF_FLAG_PUBLIC, // UNIT_FIELD_MIN_ITEM_LEVEL
UF_FLAG_PUBLIC, // UNIT_FIELD_MAX_ITEM_LEVEL
UF_FLAG_PUBLIC, // UNIT_FIELD_WILD_BATTLE_PET_LEVEL
UF_FLAG_PUBLIC, // UNIT_FIELD_BATTLE_PET_COMPANION_NAME_TIMESTAMP
UF_FLAG_PUBLIC, // UNIT_FIELD_INTERACT_SPELL_ID
UF_FLAG_PUBLIC, // PLAYER_FIELD_DUEL_ARBITER
UF_FLAG_PUBLIC, // PLAYER_FIELD_DUEL_ARBITER
UF_FLAG_PUBLIC, // PLAYER_FIELD_PLAYER_FLAGS
UF_FLAG_PUBLIC, // PLAYER_FIELD_GUILD_RANK_ID
UF_FLAG_PUBLIC, // PLAYER_FIELD_GUILD_DELETE_DATE
UF_FLAG_PUBLIC, // PLAYER_FIELD_GUILD_LEVEL
UF_FLAG_PUBLIC, // PLAYER_FIELD_HAIR_COLOR_ID
UF_FLAG_PUBLIC, // PLAYER_FIELD_REST_STATE
UF_FLAG_PUBLIC, // PLAYER_FIELD_ARENA_FACTION
UF_FLAG_PUBLIC, // PLAYER_FIELD_DUEL_TEAM
UF_FLAG_PUBLIC, // PLAYER_FIELD_GUILD_TIME_STAMP
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PARTY_MEMBER, // PLAYER_FIELD_QUEST_LOG
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_VISIBLE_ITEMS
UF_FLAG_PUBLIC, // PLAYER_FIELD_PLAYER_TITLE
UF_FLAG_PUBLIC, // PLAYER_FIELD_FAKE_INEBRIATION
UF_FLAG_PUBLIC, // PLAYER_FIELD_VIRTUAL_PLAYER_REALM
UF_FLAG_PUBLIC, // PLAYER_FIELD_CURRENT_SPEC_ID
UF_FLAG_PUBLIC, // PLAYER_FIELD_TAXI_MOUNT_ANIM_KIT_ID
UF_FLAG_PUBLIC, // PLAYER_FIELD_CURRENT_BATTLE_PET_BREED_QUALITY
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_INV_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_FARSIGHT_OBJECT
UF_FLAG_PRIVATE, // PLAYER_FIELD_FARSIGHT_OBJECT
UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES
UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES
UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES
UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES
UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES
UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES
UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES
UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES
UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES
UF_FLAG_PRIVATE, // PLAYER_FIELD_KNOWN_TITLES
UF_FLAG_PRIVATE, // PLAYER_FIELD_COINAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_COINAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_XP
UF_FLAG_PRIVATE, // PLAYER_FIELD_NEXT_LEVEL_XP
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_SKILL
UF_FLAG_PRIVATE, // PLAYER_FIELD_CHARACTER_POINTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_MAX_TALENT_TIERS
UF_FLAG_PRIVATE, // PLAYER_FIELD_TRACK_CREATURE_MASK
UF_FLAG_PRIVATE, // PLAYER_FIELD_TRACK_RESOURCE_MASK
UF_FLAG_PRIVATE, // PLAYER_FIELD_MAINHAND_EXPERTISE
UF_FLAG_PRIVATE, // PLAYER_FIELD_OFFHAND_EXPERTISE
UF_FLAG_PRIVATE, // PLAYER_FIELD_RANGED_EXPERTISE
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATING_EXPERTISE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BLOCK_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_DODGE_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_PARRY_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_RANGED_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_OFFHAND_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_SPELL_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_SHIELD_BLOCK
UF_FLAG_PRIVATE, // PLAYER_FIELD_SHIELD_BLOCK_CRIT_PERCENTAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_MASTERY
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_POWER_DAMAGE
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_POWER_HEALING
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_EXPLORED_ZONES
UF_FLAG_PRIVATE, // PLAYER_FIELD_REST_STATE_BONUS_POOL
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_POS
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_HEALING_DONE_POS
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_HEALING_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_HEALING_DONE_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_PERIODIC_HEALING_DONE_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_WEAPON_DMG_MULTIPLIERS
UF_FLAG_PRIVATE, // PLAYER_FIELD_WEAPON_DMG_MULTIPLIERS
UF_FLAG_PRIVATE, // PLAYER_FIELD_WEAPON_DMG_MULTIPLIERS
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_SPELL_POWER_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_RESILIENCE_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_OVERRIDE_SPELL_POWER_BY_APPERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_OVERRIDE_APBY_SPELL_POWER_PERCENT
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_TARGET_RESISTANCE
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
UF_FLAG_PRIVATE, // PLAYER_FIELD_LIFETIME_MAX_RANK
UF_FLAG_PRIVATE, // PLAYER_FIELD_SELF_RES_SPELL
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_MEDALS
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_PRICE
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP
UF_FLAG_PRIVATE, // PLAYER_FIELD_BUYBACK_TIMESTAMP
UF_FLAG_PRIVATE, // PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS
UF_FLAG_PRIVATE, // PLAYER_FIELD_LIFETIME_HONORABLE_KILLS
UF_FLAG_PRIVATE, // PLAYER_FIELD_WATCHED_FACTION_INDEX
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_COMBAT_RATINGS
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_PVP_INFO
UF_FLAG_PRIVATE, // PLAYER_FIELD_MAX_LEVEL
UF_FLAG_PRIVATE, // PLAYER_FIELD_RUNE_REGEN
UF_FLAG_PRIVATE, // PLAYER_FIELD_RUNE_REGEN
UF_FLAG_PRIVATE, // PLAYER_FIELD_RUNE_REGEN
UF_FLAG_PRIVATE, // PLAYER_FIELD_RUNE_REGEN
UF_FLAG_PRIVATE, // PLAYER_FIELD_NO_REAGENT_COST_MASK
UF_FLAG_PRIVATE, // PLAYER_FIELD_NO_REAGENT_COST_MASK
UF_FLAG_PRIVATE, // PLAYER_FIELD_NO_REAGENT_COST_MASK
UF_FLAG_PRIVATE, // PLAYER_FIELD_NO_REAGENT_COST_MASK
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPHS
UF_FLAG_PRIVATE, // PLAYER_FIELD_GLYPH_SLOTS_ENABLED
UF_FLAG_PRIVATE, // PLAYER_FIELD_PET_SPELL_POWER
UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING
UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING
UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING
UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING
UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING
UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING
UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING
UF_FLAG_PRIVATE, // PLAYER_FIELD_RESEARCHING
UF_FLAG_PRIVATE, // PLAYER_FIELD_PROFESSION_SKILL_LINE
UF_FLAG_PRIVATE, // PLAYER_FIELD_PROFESSION_SKILL_LINE
UF_FLAG_PRIVATE, // PLAYER_FIELD_UI_HIT_MODIFIER
UF_FLAG_PRIVATE, // PLAYER_FIELD_UI_SPELL_HIT_MODIFIER
UF_FLAG_PRIVATE, // PLAYER_FIELD_HOME_REALM_TIME_OFFSET
UF_FLAG_PRIVATE, // PLAYER_FIELD_MOD_PET_HASTE
UF_FLAG_PRIVATE, // PLAYER_FIELD_SUMMONED_BATTLE_PET_GUID
UF_FLAG_PRIVATE, // PLAYER_FIELD_SUMMONED_BATTLE_PET_GUID
UF_FLAG_PRIVATE | UF_FLAG_URGENT_SELF_ONLY, // PLAYER_FIELD_OVERRIDE_SPELLS_ID
UF_FLAG_PRIVATE, // PLAYER_FIELD_LFG_BONUS_FACTION_ID
UF_FLAG_PRIVATE, // PLAYER_FIELD_LOOT_SPEC_ID
UF_FLAG_PRIVATE | UF_FLAG_URGENT_SELF_ONLY, // PLAYER_FIELD_OVERRIDE_ZONE_PVPTYPE
UF_FLAG_PRIVATE, // PLAYER_FIELD_ITEM_LEVEL_DELTA
};
// > Object > GameObject
uint32 GameObjectUpdateFieldFlags[GAMEOBJECT_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID
UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE
UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_CREATED_BY
UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_CREATED_BY
UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_DISPLAY_ID
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // GAMEOBJECT_FIELD_FLAGS
UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_PARENT_ROTATION
UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_PARENT_ROTATION
UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_PARENT_ROTATION
UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_PARENT_ROTATION
UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_FACTION_TEMPLATE
UF_FLAG_PUBLIC, // GAMEOBJECT_FIELD_LEVEL
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // GAMEOBJECT_FIELD_PERCENT_HEALTH
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // GAMEOBJECT_FIELD_STATE_SPELL_VISUAL_ID
};
// > Object > DynamicObject
uint32 DynamicObjectUpdateFieldFlags[DYNAMICOBJECT_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID
UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE
UF_FLAG_PUBLIC, // DYNAMICOBJECT_FIELD_CASTER
UF_FLAG_PUBLIC, // DYNAMICOBJECT_FIELD_CASTER
UF_FLAG_VIEWER_DEPENDENT, // DYNAMICOBJECT_FIELD_TYPE_AND_VISUAL_ID
UF_FLAG_PUBLIC, // DYNAMICOBJECT_FIELD_SPELL_ID
UF_FLAG_PUBLIC, // DYNAMICOBJECT_FIELD_RADIUS
UF_FLAG_PUBLIC, // DYNAMICOBJECT_FIELD_CAST_TIME
};
// > Object > Corpse
uint32 CorpseUpdateFieldFlags[CORPSE_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID
UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE
UF_FLAG_PUBLIC, // CORPSE_FIELD_OWNER
UF_FLAG_PUBLIC, // CORPSE_FIELD_OWNER
UF_FLAG_PUBLIC, // CORPSE_FIELD_PARTY_GUID
UF_FLAG_PUBLIC, // CORPSE_FIELD_PARTY_GUID
UF_FLAG_PUBLIC, // CORPSE_FIELD_DISPLAY_ID
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_ITEMS
UF_FLAG_PUBLIC, // CORPSE_FIELD_SKIN_ID
UF_FLAG_PUBLIC, // CORPSE_FIELD_FACIAL_HAIR_STYLE_ID
UF_FLAG_PUBLIC, // CORPSE_FIELD_FLAGS
UF_FLAG_VIEWER_DEPENDENT, // CORPSE_FIELD_DYNAMIC_FLAGS
};
// > Object > AreaTrigger
uint32 AreaTriggerUpdateFieldFlags[AREATRIGGER_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID
UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE
UF_FLAG_PUBLIC, // AREATRIGGER_FIELD_CASTER
UF_FLAG_PUBLIC, // AREATRIGGER_FIELD_CASTER
UF_FLAG_PUBLIC, // AREATRIGGER_FIELD_DURATION
UF_FLAG_PUBLIC, // AREATRIGGER_FIELD_SPELL_ID
UF_FLAG_VIEWER_DEPENDENT, // AREATRIGGER_FIELD_SPELL_VISUAL_ID
UF_FLAG_PUBLIC | UF_FLAG_URGENT, // AREATRIGGER_FIELD_EXPLICIT_SCALE
};
// > Object > SceneObject
uint32 SceneObjectUpdateFieldFlags[SCENE_END] =
{
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_GUID
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_DATA
UF_FLAG_PUBLIC, // OBJECT_FIELD_TYPE
UF_FLAG_VIEWER_DEPENDENT, // OBJECT_FIELD_ENTRY_ID
UF_FLAG_VIEWER_DEPENDENT | UF_FLAG_URGENT, // OBJECT_FIELD_DYNAMIC_FLAGS
UF_FLAG_PUBLIC, // OBJECT_FIELD_SCALE
UF_FLAG_PUBLIC, // SCENEOBJECT_FIELD_SCRIPT_PACKAGE_ID
UF_FLAG_PUBLIC, // SCENEOBJECT_FIELD_RND_SEED_VAL
UF_FLAG_PUBLIC, // SCENEOBJECT_FIELD_CREATED_BY
UF_FLAG_PUBLIC, // SCENEOBJECT_FIELD_CREATED_BY
UF_FLAG_PUBLIC, // SCENEOBJECT_FIELD_SCENE_TYPE
};
#endif
| CaffCore/5.4.0.17399 | src/server/game/Entities/Object/Updates/UpdateFieldFlags.cpp | C++ | gpl-2.0 | 126,099 |
package gitmad.bitter.ui;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import gitmad.bitter.R;
import gitmad.bitter.model.Comment;
import gitmad.bitter.model.User;
import java.util.Map;
/**
* Created by prabh on 10/19/2015.
*/
public class CommentAdapter extends ArrayAdapter<Comment> {
private Comment[] comments;
private Map<Comment, User> commentAuthors;
public CommentAdapter(Context context, Comment[] comments, Map<Comment,
User> commentAuthors) {
super(context, 0, comments); // TODO is the zero here correct?
this.comments = comments;
this.commentAuthors = commentAuthors;
}
public View getView(int position, View convertView, ViewGroup parent) {
Comment comment = comments[position];
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout
.view_comment, parent, false);
}
TextView userText = (TextView) convertView.findViewById(R.id.user_text);
TextView commentText = (TextView) convertView.findViewById(R.id
.comment_text);
userText.setText(commentAuthors.get(comment).getName());
commentText.setText(comment.getText());
return convertView;
}
}
| nareddyt/Bitter | app/src/main/java/gitmad/bitter/ui/CommentAdapter.java | Java | gpl-2.0 | 1,425 |
<?php
if (!defined ('UPDRAFTPLUS_DIR')) die('No direct access allowed');
// Admin-area code lives here. This gets called in admin_menu, earlier than admin_init
global $updraftplus_admin;
if (!is_a($updraftplus_admin, 'UpdraftPlus_Admin')) $updraftplus_admin = new UpdraftPlus_Admin();
class UpdraftPlus_Admin {
public $logged = array();
public function __construct() {
$this->admin_init();
}
private function setup_all_admin_notices_global($service){
if ('googledrive' === $service || (is_array($service) && in_array('googledrive', $service))) {
$opts = UpdraftPlus_Options::get_updraft_option('updraft_googledrive');
if (empty($opts)) {
$clientid = UpdraftPlus_Options::get_updraft_option('updraft_googledrive_clientid', '');
$token = UpdraftPlus_Options::get_updraft_option('updraft_googledrive_token', '');
} else {
$clientid = $opts['clientid'];
$token = (empty($opts['token'])) ? '' : $opts['token'];
}
if (!empty($clientid) && empty($token)) add_action('all_admin_notices', array($this,'show_admin_warning_googledrive'));
}
if ('googlecloud' === $service || (is_array($service) && in_array('googlecloud', $service))) {
$opts = UpdraftPlus_Options::get_updraft_option('updraft_googlecloud');
if (!empty($opts)) {
$clientid = $opts['clientid'];
$token = (empty($opts['token'])) ? '' : $opts['token'];
}
if (!empty($clientid) && empty($token)) add_action('all_admin_notices', array($this,'show_admin_warning_googlecloud'));
}
if ('dropbox' === $service || (is_array($service) && in_array('dropbox', $service))) {
$opts = UpdraftPlus_Options::get_updraft_option('updraft_dropbox');
if (empty($opts['tk_request_token'])) {
add_action('all_admin_notices', array($this,'show_admin_warning_dropbox') );
}
}
if ('bitcasa' === $service || (is_array($service) && in_array('bitcasa', $service))) {
$opts = UpdraftPlus_Options::get_updraft_option('updraft_bitcasa');
if (!empty($opts['clientid']) && !empty($opts['secret']) && empty($opts['token'])) add_action('all_admin_notices', array($this,'show_admin_warning_bitcasa') );
}
if ('copycom' === $service || (is_array($service) && in_array('copycom', $service))) {
$opts = UpdraftPlus_Options::get_updraft_option('updraft_copycom');
if (!empty($opts['clientid']) && !empty($opts['secret']) && empty($opts['token'])) add_action('all_admin_notices', array($this,'show_admin_warning_copycom') );
}
if ('onedrive' === $service || (is_array($service) && in_array('onedrive', $service))) {
$opts = UpdraftPlus_Options::get_updraft_option('updraft_onedrive');
if (!empty($opts['clientid']) && !empty($opts['secret']) && empty($opts['refresh_token'])) add_action('all_admin_notices', array($this,'show_admin_warning_onedrive') );
}
if ('updraftvault' === $service || (is_array($service) && in_array('updraftvault', $service))) {
$vault_settings = UpdraftPlus_Options::get_updraft_option('updraft_updraftvault');
$connected = (is_array($vault_settings) && !empty($vault_settings['token']) && !empty($vault_settings['email'])) ? true : false;
if (!$connected) add_action('all_admin_notices', array($this,'show_admin_warning_updraftvault') );
}
if ($this->disk_space_check(1048576*35) === false) add_action('all_admin_notices', array($this, 'show_admin_warning_diskspace'));
}
private function setup_all_admin_notices_udonly($service, $override = false){
global $wp_version;
if (UpdraftPlus_Options::user_can_manage() && defined('DISABLE_WP_CRON') && DISABLE_WP_CRON == true) {
add_action('all_admin_notices', array($this, 'show_admin_warning_disabledcron'));
}
if (UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) {
@ini_set('display_errors',1);
@error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
add_action('all_admin_notices', array($this, 'show_admin_debug_warning'));
}
if (null === UpdraftPlus_Options::get_updraft_option('updraft_interval')) {
add_action('all_admin_notices', array($this, 'show_admin_nosettings_warning'));
$this->no_settings_warning = true;
}
# Avoid false positives, by attempting to raise the limit (as happens when we actually do a backup)
@set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);
$max_execution_time = (int)@ini_get('max_execution_time');
if ($max_execution_time>0 && $max_execution_time<20) {
add_action('all_admin_notices', array($this, 'show_admin_warning_execution_time'));
}
// LiteSpeed has a generic problem with terminating cron jobs
if (isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
if (!is_file(ABSPATH.'.htaccess') || !preg_match('/noabort/i', file_get_contents(ABSPATH.'.htaccess'))) {
add_action('all_admin_notices', array($this, 'show_admin_warning_litespeed'));
}
}
if (version_compare($wp_version, '3.2', '<')) add_action('all_admin_notices', array($this, 'show_admin_warning_wordpressversion'));
}
/*
private function reset_all_updraft_admin_notices() {
$actions_to_remove = array('show_admin_warning_googledrive', 'show_admin_warning_googlecloud', 'show_admin_warning_dropbox', 'show_admin_warning_bitcasa', 'show_admin_warning_copycom', 'show_admin_warning_onedrive', 'show_admin_warning_updraftvault', 'show_admin_warning_diskspace', 'show_admin_warning_disabledcron', 'show_admin_debug_warning', 'show_admin_warning_execution_time', 'show_admin_warning_litespeed', 'show_admin_warning_wordpressversion');
foreach ($actions_to_remove as $action) {
remove_action('all_admin_notices', $action);
}
}
*/
//Used to output the information for the next scheduled backup
//**// moved to function for the ajax saves
private function next_scheduled_backups_output() {
// UNIX timestamp
$next_scheduled_backup = wp_next_scheduled('updraft_backup');
if ($next_scheduled_backup) {
// Convert to GMT
$next_scheduled_backup_gmt = gmdate('Y-m-d H:i:s', $next_scheduled_backup);
// Convert to blog time zone
$next_scheduled_backup = get_date_from_gmt($next_scheduled_backup_gmt, 'D, F j, Y H:i');
// $next_scheduled_backup = date_i18n('D, F j, Y H:i', $next_scheduled_backup);
} else {
$next_scheduled_backup = __('Nothing currently scheduled', 'updraftplus');
$files_not_scheduled = true;
}
$next_scheduled_backup_database = wp_next_scheduled('updraft_backup_database');
if (UpdraftPlus_Options::get_updraft_option('updraft_interval_database',UpdraftPlus_Options::get_updraft_option('updraft_interval')) == UpdraftPlus_Options::get_updraft_option('updraft_interval')) {
if (isset($files_not_scheduled)) {
$next_scheduled_backup_database = $next_scheduled_backup;
$database_not_scheduled = true;
} else {
$next_scheduled_backup_database = __("At the same time as the files backup", 'updraftplus');
$next_scheduled_backup_database_same_time = true;
}
} else {
if ($next_scheduled_backup_database) {
// Convert to GMT
$next_scheduled_backup_database_gmt = gmdate('Y-m-d H:i:s', $next_scheduled_backup_database);
// Convert to blog time zone
$next_scheduled_backup_database = get_date_from_gmt($next_scheduled_backup_database_gmt, 'D, F j, Y H:i');
// $next_scheduled_backup_database = date_i18n('D, F j, Y H:i', $next_scheduled_backup_database);
} else {
$next_scheduled_backup_database = __('Nothing currently scheduled', 'updraftplus');
$database_not_scheduled = true;
}
}
?>
<tr>
<?php if (isset($files_not_scheduled) && isset($database_not_scheduled)) { ?>
<td colspan="2" class="not-scheduled"><?php _e('Nothing currently scheduled','updraftplus'); ?></td>
<?php } else { ?>
<td class="updraft_scheduled"><?php echo empty($next_scheduled_backup_database_same_time) ? __('Files','updraftplus') : __('Files and database', 'updraftplus'); ?>:</td><td class="updraft_all-files"><?php echo $next_scheduled_backup; ?></td>
</tr>
<?php if (empty($next_scheduled_backup_database_same_time)) { ?>
<tr>
<td class="updraft_scheduled"><?php _e('Database','updraftplus');?>: </td><td class="updraft_all-files"><?php echo $next_scheduled_backup_database; ?></td>
</tr>
<?php } ?>
<?php
}
}
private function admin_init() {
add_action('core_upgrade_preamble', array($this, 'core_upgrade_preamble'));
add_action('admin_action_upgrade-plugin', array($this, 'admin_action_upgrade_pluginortheme'));
add_action('admin_action_upgrade-theme', array($this, 'admin_action_upgrade_pluginortheme'));
add_action('admin_head', array($this,'admin_head'));
add_filter((is_multisite() ? 'network_admin_' : '').'plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
add_action('wp_ajax_updraft_download_backup', array($this, 'updraft_download_backup'));
add_action('wp_ajax_updraft_ajax', array($this, 'updraft_ajax_handler'));
add_action('wp_ajax_updraft_ajaxrestore', array($this, 'updraft_ajaxrestore'));
add_action('wp_ajax_nopriv_updraft_ajaxrestore', array($this, 'updraft_ajaxrestore'));
add_action('wp_ajax_plupload_action', array($this, 'plupload_action'));
add_action('wp_ajax_plupload_action2', array($this, 'plupload_action2'));
add_action('wp_before_admin_bar_render', array($this, 'wp_before_admin_bar_render'));
// Add a new Ajax action for saving settings
add_action('wp_ajax_updraft_savesettings', array($this, 'updraft_ajax_savesettings'));
global $updraftplus, $wp_version, $pagenow;
add_filter('updraftplus_dirlist_others', array($updraftplus, 'backup_others_dirlist'));
add_filter('updraftplus_dirlist_uploads', array($updraftplus, 'backup_uploads_dirlist'));
// First, the checks that are on all (admin) pages:
$service = UpdraftPlus_Options::get_updraft_option('updraft_service');
if (UpdraftPlus_Options::user_can_manage()) {
$this->print_restore_in_progress_box_if_needed();
// Main dashboard page advert
// Since our nonce is printed, make sure they have sufficient credentials
if (!file_exists(UPDRAFTPLUS_DIR.'/udaddons') && $pagenow == 'index.php' && current_user_can('update_plugins')) {
$dismissed_until = UpdraftPlus_Options::get_updraft_option('updraftplus_dismisseddashnotice', 0);
$backup_dir = $updraftplus->backups_dir_location();
// N.B. Not an exact proxy for the installed time; they may have tweaked the expert option to move the directory
$installed = @filemtime($backup_dir.'/index.html');
$installed_for = time() - $installed;
if (($installed && time() > $dismissed_until && $installed_for > 28*86400 && !defined('UPDRAFTPLUS_NOADS_B')) || (defined('UPDRAFTPLUS_FORCE_DASHNOTICE') && UPDRAFTPLUS_FORCE_DASHNOTICE)) {
add_action('all_admin_notices', array($this, 'show_admin_notice_upgradead') );
}
}
//Moved out for use with Ajax saving
$this->setup_all_admin_notices_global($service);
}
// Next, the actions that only come on the UpdraftPlus page
if ($pagenow != UpdraftPlus_Options::admin_page() || empty($_REQUEST['page']) || 'updraftplus' != $_REQUEST['page']) return;
$this->setup_all_admin_notices_udonly($service);
add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'), 99999);
}
public function updraft_ajaxrestore() {
// TODO: All needs testing with restricted filesystem permissions. Those credentials need to be POST-ed too - currently not.
// TODO
// error_log(serialize($_POST));
if (empty($_POST['subaction']) || 'restore' != $_POST['subaction']) {
echo json_encode(array('e' => 'Illegitimate data sent (0)'));
die();
}
if (empty($_POST['restorenonce'])) {
echo json_encode(array('e' => 'Illegitimate data sent (1)'));
die();
}
$restore_nonce = (string)$_POST['restorenonce'];
if (empty($_POST['ajaxauth'])) {
echo json_encode(array('e' => 'Illegitimate data sent (2)'));
die();
}
global $updraftplus;
$ajax_auth = get_site_option('updraft_ajax_restore_'.$restore_nonce);
if (!$ajax_auth) {
echo json_encode(array('e' => 'Illegitimate data sent (3)'));
die();
}
if (!preg_match('/^([0-9a-f]+):(\d+)/i', $ajax_auth, $matches)) {
echo json_encode(array('e' => 'Illegitimate data sent (4)'));
die();
}
$nonce_time = $matches[2];
$auth_code_sent = $matches[1];
if (time() > $nonce_time + 600) {
echo json_encode(array('e' => 'Illegitimate data sent (5)'));
die();
}
// TODO: Deactivate the auth code whilst the operation is underway
$last_one = empty($_POST['lastone']) ? false : true;
@set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);
$updraftplus->backup_time_nonce($restore_nonce);
$updraftplus->logfile_open($restore_nonce);
$timestamp = empty($_POST['timestamp']) ? false : (int)$_POST['timestamp'];
$multisite = empty($_POST['multisite']) ? false : (bool)$_POST['multisite'];
$created_by_version = empty($_POST['created_by_version']) ? false : (int)$_POST['created_by_version'];
// TODO: We need to know about first_one (not yet sent), as well as last_one
// TODO: Verify the values of these
$type = empty($_POST['type']) ? false : (int)$_POST['type'];
$backupfile = empty($_POST['backupfile']) ? false : (string)$_POST['backupfile'];
$updraftplus->log("Deferred restore resumption: $type: $backupfile (timestamp=$timestamp, last_one=$last_one)");
$backupable_entities = $updraftplus->get_backupable_file_entities(true);
if (!isset($backupable_entities[$type])) {
echo json_encode(array('e' => 'Illegitimate data sent (6 - no such entity)', 'data' => $type));
die();
}
if ($last_one) {
// Remove the auth nonce from the DB to prevent abuse
delete_site_option('updraft_ajax_restore_'.$restore_nonce);
} else {
// Reset the counter after a successful operation
update_site_option('updraft_ajax_restore_'.$restore_nonce, $auth_code_sent.':'.time());
}
echo json_encode(array('e' => 'TODO', 'd' => $_POST));
die;
}
public function wp_before_admin_bar_render() {
global $wp_admin_bar;
if (!UpdraftPlus_Options::user_can_manage()) return;
if (defined('UPDRAFTPLUS_ADMINBAR_DISABLE') && UPDRAFTPLUS_ADMINBAR_DISABLE) return;
if (false == apply_filters('updraftplus_settings_page_render', true)) return;
$option_location = UpdraftPlus_Options::admin_page_url();
$args = array(
'id' => 'updraft_admin_node',
'title' => 'UpdraftPlus'
);
$wp_admin_bar->add_node($args);
$args = array(
'id' => 'updraft_admin_node_status',
'title' => __('Current Status', 'updraftplus').' / '.__('Backup Now', 'updraftplus'),
'parent' => 'updraft_admin_node',
'href' => $option_location.'?page=updraftplus&tab=status'
);
$wp_admin_bar->add_node($args);
$args = array(
'id' => 'updraft_admin_node_backups',
'title' => __('Existing Backups', 'updraftplus'),
'parent' => 'updraft_admin_node',
'href' => $option_location.'?page=updraftplus&tab=backups'
);
$wp_admin_bar->add_node($args);
$args = array(
'id' => 'updraft_admin_node_settings',
'title' => __('Settings', 'updraftplus'),
'parent' => 'updraft_admin_node',
'href' => $option_location.'?page=updraftplus&tab=settings'
);
$wp_admin_bar->add_node($args);
$args = array(
'id' => 'updraft_admin_node_expert_content',
'title' => __('Advanced Tools', 'updraftplus'),
'parent' => 'updraft_admin_node',
'href' => $option_location.'?page=updraftplus&tab=expert'
);
$wp_admin_bar->add_node($args);
$args = array(
'id' => 'updraft_admin_node_addons',
'title' => __('Extensions', 'updraftplus'),
'parent' => 'updraft_admin_node',
'href' => $option_location.'?page=updraftplus&tab=addons'
);
$wp_admin_bar->add_node($args);
global $updraftplus;
if (!$updraftplus->have_addons) {
$args = array(
'id' => 'updraft_admin_node_premium',
'title' => 'UpdraftPlus Premium',
'parent' => 'updraft_admin_node',
'href' => 'https://updraftplus.com/shop/updraftplus-premium/'
);
$wp_admin_bar->add_node($args);
}
}
// // Defeat other plugins/themes which dump their jQuery UI CSS onto our settings page
// public function style_loader_tag($link, $handle) {
// if ('jquery-ui' != $handle || false === strpos) return $link;
// return "<link rel='stylesheet' id='$handle-css' $title href='$href' type='text/css' media='$media' />\n";
// }
public function show_admin_notice_upgradead() {
?>
<div id="updraft-dashnotice" class="updated">
<div style="float:right;"><a href="#" onclick="jQuery('#updraft-dashnotice').slideUp(); jQuery.post(ajaxurl, {action: 'updraft_ajax', subaction: 'dismissdashnotice', nonce: '<?php echo wp_create_nonce('updraftplus-credentialtest-nonce');?>' });"><?php echo sprintf(__('Dismiss (for %s months)', 'updraftplus'), 12); ?></a></div>
<h3 class="thank-you"><?php _e('Thank you for backing up with UpdraftPlus!', 'updraftplus');?></h3>
<a href="https://updraftplus.com/"><img class="udp-logo" alt="UpdraftPlus" src="<?php echo UPDRAFTPLUS_URL.'/images/ud-logo-150.png' ?>"></a>
<?php
echo '<p><strong>'.__('Free Newsletter', 'updraftplus').'</strong> <br>'.__('UpdraftPlus news, high-quality training materials for WordPress developers and site-owners, and general WordPress news. You can de-subscribe at any time.', 'updraftplus').' <a href="https://updraftplus.com/newsletter-signup">'.__('Follow this link to sign up.', 'updraftplus').'</a></p>';
echo '<p><strong>'.__('UpdraftPlus Premium', 'updraftplus').'</strong> <br>'.__('For personal support, the ability to copy sites, more storage destinations, encrypted backups for security, multiple backup destinations, better reporting, no adverts and plenty more, take a look at the premium version of UpdraftPlus - the world’s most popular backup plugin.', 'updraftplus').' <a href="https://updraftplus.com/comparison-updraftplus-free-updraftplus-premium/">'.__('Compare with the free version', 'updraftplus').'</a> / <a href="https://updraftplus.com/shop/updraftplus-premium/">'.__('Go to the shop.', 'updraftplus').'</a></p>';
echo '<p><strong>'.__('More Quality Plugins', 'updraftplus').'</strong> <br> <a href="https://wordpress.org/plugins/two-factor-authentication/">'.__('Free two-factor security plugin', 'updraftplus').'</a> | <a href="https://www.simbahosting.co.uk/s3/shop/">'.__('Premium WooCommerce plugins', 'updraftplus').'</a></p>';
?>
<div class="dismiss-dash-notice"><a href="#" onclick="jQuery('#updraft-dashnotice').slideUp(); jQuery.post(ajaxurl, {action: 'updraft_ajax', subaction: 'dismissdashnotice', nonce: '<?php echo wp_create_nonce('updraftplus-credentialtest-nonce');?>' });"><?php echo sprintf(__('Dismiss (for %s months)', 'updraftplus'), 12); ?></a></div>
</div>
<?php
}
private function ensure_sufficient_jquery_and_enqueue() {
global $updraftplus, $wp_version;
$enqueue_version = @constant('WP_DEBUG') ? $updraftplus->version.'-'.time() : $updraftplus->version;
if (version_compare($wp_version, '3.3', '<')) {
// Require a newer jQuery (3.2.1 has 1.6.1, so we go for something not too much newer). We use .on() in a way that is incompatible with < 1.7
wp_deregister_script('jquery');
wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', false, '1.7.2', false);
wp_enqueue_script('jquery');
// No plupload until 3.3
wp_enqueue_script('updraftplus-admin-ui', UPDRAFTPLUS_URL.'/includes/updraft-admin-ui.js', array('jquery', 'jquery-ui-dialog'), $enqueue_version, true);
} else {
wp_enqueue_script('updraftplus-admin-ui', UPDRAFTPLUS_URL.'/includes/updraft-admin-ui.js', array('jquery', 'jquery-ui-dialog', 'plupload-all'), $enqueue_version);
}
}
// This is also called directly from the auto-backup add-on
public function admin_enqueue_scripts() {
global $updraftplus, $wp_locale;
// Defeat other plugins/themes which dump their jQuery UI CSS onto our settings page
wp_deregister_style('jquery-ui');
wp_enqueue_style('jquery-ui', UPDRAFTPLUS_URL.'/includes/jquery-ui.custom.css', array(), '1.11.4');
$our_version = @constant('SCRIPT_DEBUG') ? $updraftplus->version.'.'.time() : $updraftplus->version;
wp_enqueue_style('updraft-admin-css', UPDRAFTPLUS_URL.'/css/admin.css', array(), $our_version);
// add_filter('style_loader_tag', array($this, 'style_loader_tag'), 10, 2);
$this->ensure_sufficient_jquery_and_enqueue();
wp_enqueue_script('jquery-blockui', UPDRAFTPLUS_URL.'/includes/jquery.blockUI.js', array('jquery'), '2.70.0');
wp_enqueue_script('jquery-labelauty', UPDRAFTPLUS_URL.'/includes/labelauty/jquery-labelauty.js', array('jquery'), '20160622-ud');
wp_enqueue_style('jquery-labelauty', UPDRAFTPLUS_URL.'/includes/labelauty/jquery-labelauty.css', array(), '20150925');
do_action('updraftplus_admin_enqueue_scripts');
$day_selector = '';
for ($day_index = 0; $day_index <= 6; $day_index++) {
// $selected = ($opt == $day_index) ? 'selected="selected"' : '';
$selected = '';
$day_selector .= "\n\t<option value='" . $day_index . "' $selected>" . $wp_locale->get_weekday($day_index) . '</option>';
}
$mday_selector = '';
for ($mday_index = 1; $mday_index <= 28; $mday_index++) {
// $selected = ($opt == $mday_index) ? 'selected="selected"' : '';
$selected = '';
$mday_selector .= "\n\t<option value='" . $mday_index . "' $selected>" . $mday_index . '</option>';
}
wp_localize_script('updraftplus-admin-ui', 'updraftlion', array(
'sendonlyonwarnings' => __('Send a report only when there are warnings/errors', 'updraftplus'),
'wholebackup' => __('When the Email storage method is enabled, also send the entire backup', 'updraftplus'),
'emailsizelimits' => esc_attr(sprintf(__('Be aware that mail servers tend to have size limits; typically around %s Mb; backups larger than any limits will likely not arrive.','updraftplus'), '10-20')),
'rescanning' => __('Rescanning (looking for backups that you have uploaded manually into the internal backup store)...','updraftplus'),
'rescanningremote' => __('Rescanning remote and local storage for backup sets...','updraftplus'),
'enteremailhere' => esc_attr(__('To send to more than one address, separate each address with a comma.', 'updraftplus')),
'excludedeverything' => __('If you exclude both the database and the files, then you have excluded everything!', 'updraftplus'),
'nofileschosen' => __('You have chosen to backup files, but no file entities have been selected', 'updraftplus'),
'restoreproceeding' => __('The restore operation has begun. Do not press stop or close your browser until it reports itself as having finished.', 'updraftplus'),
'unexpectedresponse' => __('Unexpected response:','updraftplus'),
'servererrorcode' => __('The web server returned an error code (try again, or check your web server logs)', 'updraftplus'),
'newuserpass' => __("The new user's RackSpace console password is (this will not be shown again):", 'updraftplus'),
'trying' => __('Trying...', 'updraftplus'),
'fetching' => __('Fetching...', 'updraftplus'),
'calculating' => __('calculating...','updraftplus'),
'begunlooking' => __('Begun looking for this entity','updraftplus'),
'stilldownloading' => __('Some files are still downloading or being processed - please wait.', 'updraftplus'),
'processing' => __('Processing files - please wait...', 'updraftplus'),
'emptyresponse' => __('Error: the server sent an empty response.', 'updraftplus'),
'warnings' => __('Warnings:','updraftplus'),
'errors' => __('Errors:','updraftplus'),
'jsonnotunderstood' => __('Error: the server sent us a response which we did not understand.', 'updraftplus'),
'errordata' => __('Error data:', 'updraftplus'),
'error' => __('Error:','updraftplus'),
'errornocolon' => __('Error','updraftplus'),
'fileready' => __('File ready.','updraftplus'),
'youshould' => __('You should:','updraftplus'),
'deletefromserver' => __('Delete from your web server','updraftplus'),
'downloadtocomputer' => __('Download to your computer','updraftplus'),
'andthen' => __('and then, if you wish,', 'updraftplus'),
'notunderstood' => __('Download error: the server sent us a response which we did not understand.', 'updraftplus'),
'requeststart' => __('Requesting start of backup...', 'updraftplus'),
'phpinfo' => __('PHP information', 'updraftplus'),
'delete_old_dirs' => __('Delete Old Directories', 'updraftplus'),
'raw' => __('Raw backup history', 'updraftplus'),
'notarchive' => __('This file does not appear to be an UpdraftPlus backup archive (such files are .zip or .gz files which have a name like: backup_(time)_(site name)_(code)_(type).(zip|gz)).', 'updraftplus').' '.__('However, UpdraftPlus archives are standard zip/SQL files - so if you are sure that your file has the right format, then you can rename it to match that pattern.','updraftplus'),
'notarchive2' => '<p>'.__('This file does not appear to be an UpdraftPlus backup archive (such files are .zip or .gz files which have a name like: backup_(time)_(site name)_(code)_(type).(zip|gz)).', 'updraftplus').'</p> '.apply_filters('updraftplus_if_foreign_then_premium_message', '<p><a href="https://updraftplus.com/shop/updraftplus-premium/">'.__('If this is a backup created by a different backup plugin, then UpdraftPlus Premium may be able to help you.', 'updraftplus').'</a></p>'),
'makesure' => __('(make sure that you were trying to upload a zip file previously created by UpdraftPlus)','updraftplus'),
'uploaderror' => __('Upload error:','updraftplus'),
'notdba' => __('This file does not appear to be an UpdraftPlus encrypted database archive (such files are .gz.crypt files which have a name like: backup_(time)_(site name)_(code)_db.crypt.gz).','updraftplus'),
'uploaderr' => __('Upload error', 'updraftplus'),
'followlink' => __('Follow this link to attempt decryption and download the database file to your computer.','updraftplus'),
'thiskey' => __('This decryption key will be attempted:','updraftplus'),
'unknownresp' => __('Unknown server response:','updraftplus'),
'ukrespstatus' => __('Unknown server response status:','updraftplus'),
'uploaded' => __('The file was uploaded.','updraftplus'),
'backupnow' => __('Backup Now', 'updraftplus'),
'cancel' => __('Cancel', 'updraftplus'),
'deletebutton' => __('Delete', 'updraftplus'),
'createbutton' => __('Create', 'updraftplus'),
'youdidnotselectany' => __('You did not select any components to restore. Please select at least one, and then try again.', 'updraftplus'),
'proceedwithupdate' => __('Proceed with update', 'updraftplus'),
'close' => __('Close', 'updraftplus'),
'restore' => __('Restore', 'updraftplus'),
'downloadlogfile' => __('Download log file', 'updraftplus'),
'automaticbackupbeforeupdate' => __('Automatic backup before update', 'updraftplus'),
'unsavedsettings' => __('You have made changes to your settings, and not saved.', 'updraftplus'),
'saving' => __('Saving...', 'updraftplus'),
'connect' => __('Connect', 'updraftplus'),
'connecting' => __('Connecting...', 'updraftplus'),
'disconnect' => __('Disconnect', 'updraftplus'),
'disconnecting' => __('Disconnecting...', 'updraftplus'),
'counting' => __('Counting...', 'updraftplus'),
'updatequotacount' => __('Update quota count', 'updraftplus'),
'addingsite' => __('Adding...', 'updraftplus'),
'addsite' => __('Add site', 'updraftplus'),
// 'resetting' => __('Resetting...', 'updraftplus'),
'creating' => __('Creating...', 'updraftplus'),
'sendtosite' => __('Send to site:', 'updraftplus'),
'checkrpcsetup' => sprintf(__('You should check that the remote site is online, not firewalled, does not have security modules that may be blocking access, has UpdraftPlus version %s or later active and that the keys have been entered correctly.', 'updraftplus'), '2.10.3'),
'pleasenamekey' => __('Please give this key a name (e.g. indicate the site it is for):', 'updraftplus'),
'key' => __('Key', 'updraftplus'),
'nokeynamegiven' => sprintf(__("Failure: No %s was given.",'updraftplus'), __('key name','updraftplus')),
'deleting' => __('Deleting...', 'updraftplus'),
'enter_mothership_url' => __('Please enter a valid URL', 'updraftplus'),
'delete_response_not_understood' => __("We requested to delete the file, but could not understand the server's response", 'updraftplus'),
'testingconnection' => __('Testing connection...', 'updraftplus'),
'send' => __('Send', 'updraftplus'),
'migratemodalheight' => class_exists('UpdraftPlus_Addons_Migrator') ? 555 : 300,
'migratemodalwidth' => class_exists('UpdraftPlus_Addons_Migrator') ? 770 : 500,
'download' => _x('Download', '(verb)', 'updraftplus'),
'unsavedsettingsbackup' => __('You have made changes to your settings, and not saved.', 'updraftplus')."\n".__('You should save your changes to ensure that they are used for making your backup.','updraftplus'),
'dayselector' => $day_selector,
'mdayselector' => $mday_selector,
'day' => __('day', 'updraftplus'),
'inthemonth' => __('in the month', 'updraftplus'),
'days' => __('day(s)', 'updraftplus'),
'hours' => __('hour(s)', 'updraftplus'),
'weeks' => __('week(s)', 'updraftplus'),
'forbackupsolderthan' => __('For backups older than', 'updraftplus'),
'ud_url' => UPDRAFTPLUS_URL,
'processing' => __('Processing...', 'updraftplus'),
'pleasefillinrequired' => __('Please fill in the required information.', 'updraftplus'),
'test_settings' => __('Test %s Settings', 'updraftplus'),
'testing_settings' => __('Testing %s Settings...', 'updraftplus'),
'settings_test_result' => __('%s settings test result:', 'updraftplus'),
'nothing_yet_logged' => __('Nothing yet logged', 'updraftplus'),
) );
}
// Despite the name, this fires irrespective of what capabilities the user has (even none - so be careful)
public function core_upgrade_preamble() {
// They need to be able to perform backups, and to perform updates
if (!UpdraftPlus_Options::user_can_manage() || (!current_user_can('update_core') && !current_user_can('update_plugins') && !current_user_can('update_themes'))) return;
if (!class_exists('UpdraftPlus_Addon_Autobackup')) {
if (defined('UPDRAFTPLUS_NOADS_B')) return;
$dismissed_until = UpdraftPlus_Options::get_updraft_option('updraftplus_dismissedautobackup', 0);
if ($dismissed_until > time()) return;
}
?>
<div id="updraft-autobackup" class="updated autobackup">
<?php if (!class_exists('UpdraftPlus_Addon_Autobackup')) { ?>
<div style="float:right;"><a href="#" onclick="jQuery('#updraft-autobackup').slideUp(); jQuery.post(ajaxurl, {action: 'updraft_ajax', subaction: 'dismissautobackup', nonce: '<?php echo wp_create_nonce('updraftplus-credentialtest-nonce');?>' });"><?php echo sprintf(__('Dismiss (for %s weeks)', 'updraftplus'), 12); ?></a></div> <?php } ?>
<h3 style="margin-top: 2px;"><?php _e('Be safe with an automatic backup','updraftplus');?></h3>
<?php echo apply_filters('updraftplus_autobackup_blurb', $this->autobackup_ad_content()); ?>
</div>
<script>
jQuery(document).ready(function() {
jQuery('#updraft-autobackup').appendTo('.wrap p:first');
});
</script>
<?php
}
private function autobackup_ad_content(){
global $updraftplus;
$our_version = @constant('SCRIPT_DEBUG') ? $updraftplus->version.'.'.time() : $updraftplus->version;
wp_enqueue_style('updraft-admin-css', UPDRAFTPLUS_URL.'/css/admin.css', array(), $our_version);
$ret = '<div class="autobackup-description"><img class="autobackup-image" src="'.UPDRAFTPLUS_URL.'/images/automaticbackup.png" class="automation-icon"/>';
$ret .= '<div class="advert-description">'.__('UpdraftPlus Premium can automatically take a backup of your plugins or themes and database before you update. <a href="https://updraftplus.com/shop/autobackup/" target="_blank">Be safe every time, without needing to remember - follow this link to learn more</a>', 'updraftplus').'</div></div>';
$ret .= '<div class="advert-btn"><a href="https://updraftplus.com/shop/autobackup/" class="btn btn-get-started">'.__('Just this add-on', 'updraftplus').' <span class="circle-dblarrow">»</span></a></div>';
$ret .= '<div class="advert-btn"><a href="https://updraftplus.com/shop/updraftplus-premium/" class="btn btn-get-started">'.__('Full Premium plugin', 'updraftplus').' <span class="circle-dblarrow">»</span></a></div>';
return $ret;
}
public function admin_head() {
global $pagenow;
if ($pagenow != UpdraftPlus_Options::admin_page() || !isset($_REQUEST['page']) || 'updraftplus' != $_REQUEST['page'] || !UpdraftPlus_Options::user_can_manage()) return;
$chunk_size = min(wp_max_upload_size()-1024, 1048576*2);
# The multiple_queues argument is ignored in plupload 2.x (WP3.9+) - http://make.wordpress.org/core/2014/04/11/plupload-2-x-in-wordpress-3-9/
# max_file_size is also in filters as of plupload 2.x, but in its default position is still supported for backwards-compatibility. Likewise, our use of filters.extensions below is supported by a backwards-compatibility option (the current way is filters.mime-types.extensions
$plupload_init = array(
'runtimes' => 'html5,flash,silverlight,html4',
'browse_button' => 'plupload-browse-button',
'container' => 'plupload-upload-ui',
'drop_element' => 'drag-drop-area',
'file_data_name' => 'async-upload',
'multiple_queues' => true,
'max_file_size' => '100Gb',
'chunk_size' => $chunk_size.'b',
'url' => admin_url('admin-ajax.php', 'relative'),
'multipart' => true,
'multi_selection' => true,
'urlstream_upload' => true,
// additional post data to send to our ajax hook
'multipart_params' => array(
'_ajax_nonce' => wp_create_nonce('updraft-uploader'),
'action' => 'plupload_action'
)
);
// 'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
// 'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
// We want to receive -db files also...
// if (1) {
// $plupload_init['filters'] = array(array('title' => __('Allowed Files'), 'extensions' => 'zip,tar,gz,bz2,crypt,sql,txt'));
// } else {
// }
# WP 3.9 updated to plupload 2.0 - https://core.trac.wordpress.org/ticket/25663
if (is_file(ABSPATH.WPINC.'/js/plupload/Moxie.swf')) {
$plupload_init['flash_swf_url'] = includes_url('js/plupload/Moxie.swf');
} else {
$plupload_init['flash_swf_url'] = includes_url('js/plupload/plupload.flash.swf');
}
if (is_file(ABSPATH.WPINC.'/js/plupload/Moxie.xap')) {
$plupload_init['silverlight_xap_url'] = includes_url('js/plupload/Moxie.xap');
} else {
$plupload_init['silverlight_xap_url'] = includes_url('js/plupload/plupload.silverlight.swf');
}
?><script type="text/javascript">
var updraft_credentialtest_nonce='<?php echo wp_create_nonce('updraftplus-credentialtest-nonce');?>';
var updraftplus_settings_nonce='<?php echo wp_create_nonce('updraftplus-settings-nonce');?>';
var updraft_siteurl = '<?php echo esc_js(site_url('', 'relative'));?>';
var updraft_plupload_config=<?php echo json_encode($plupload_init); ?>;
var updraft_download_nonce='<?php echo wp_create_nonce('updraftplus_download');?>';
var updraft_accept_archivename = <?php echo apply_filters('updraftplus_accept_archivename_js', "[]");?>;
<?php
$plupload_init['browse_button'] = 'plupload-browse-button2';
$plupload_init['container'] = 'plupload-upload-ui2';
$plupload_init['drop_element'] = 'drag-drop-area2';
$plupload_init['multipart_params']['action'] = 'plupload_action2';
$plupload_init['filters'] = array(array('title' => __('Allowed Files'), 'extensions' => 'crypt'));
?>
var updraft_plupload_config2=<?php echo json_encode($plupload_init); ?>;
var updraft_downloader_nonce = '<?php wp_create_nonce("updraftplus_download"); ?>'
<?php
$overdue = $this->howmany_overdue_crons();
if ($overdue >= 4) { ?>
jQuery(document).ready(function(){
setTimeout(function(){updraft_check_overduecrons();}, 11000);
function updraft_check_overduecrons() {
jQuery.get(ajaxurl, { action: 'updraft_ajax', subaction: 'checkoverduecrons', nonce: updraft_credentialtest_nonce }, function(data, response) {
if ('success' == response) {
try {
resp = jQuery.parseJSON(data);
if (resp.m) {
jQuery('#updraft-insert-admin-warning').html(resp.m);
}
} catch(err) {
console.log(data);
}
}
});
}
});
<?php } ?>
</script>
<?php
}
private function disk_space_check($space) {
global $updraftplus;
$updraft_dir = $updraftplus->backups_dir_location();
$disk_free_space = @disk_free_space($updraft_dir);
if ($disk_free_space == false) return -1;
return ($disk_free_space > $space) ? true : false;
}
# Adds the settings link under the plugin on the plugin screen.
public function plugin_action_links($links, $file) {
if (is_array($links) && $file == 'updraftplus/updraftplus.php'){
$settings_link = '<a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus">'.__("Settings", "updraftplus").'</a>';
array_unshift($links, $settings_link);
// $settings_link = '<a href="http://david.dw-perspective.org.uk/donate">'.__("Donate","UpdraftPlus").'</a>';
// array_unshift($links, $settings_link);
$settings_link = '<a href="https://updraftplus.com">'.__("Add-Ons / Pro Support","updraftplus").'</a>';
array_unshift($links, $settings_link);
}
return $links;
}
public function admin_action_upgrade_pluginortheme() {
if (isset($_GET['action']) && ($_GET['action'] == 'upgrade-plugin' || $_GET['action'] == 'upgrade-theme') && !class_exists('UpdraftPlus_Addon_Autobackup') && !defined('UPDRAFTPLUS_NOADS_B')) {
if ($_GET['action'] == 'upgrade-plugin') {
if (!current_user_can('update_plugins')) return;
} else {
if (!current_user_can('update_themes')) return;
}
$dismissed_until = UpdraftPlus_Options::get_updraft_option('updraftplus_dismissedautobackup', 0);
if ($dismissed_until > time()) return;
if ( 'upgrade-plugin' == $_GET['action'] ) {
$title = __('Update Plugin');
$parent_file = 'plugins.php';
$submenu_file = 'plugins.php';
} else {
$title = __('Update Theme');
$parent_file = 'themes.php';
$submenu_file = 'themes.php';
}
require_once(ABSPATH.'wp-admin/admin-header.php');
?>
<div id="updraft-autobackup" class="updated" style="float:left; padding: 6px; margin:8px 0px;">
<div style="float: right;"><a href="#" onclick="jQuery('#updraft-autobackup').slideUp(); jQuery.post(ajaxurl, {action: 'updraft_ajax', subaction: 'dismissautobackup', nonce: '<?php echo wp_create_nonce('updraftplus-credentialtest-nonce');?>' });"><?php echo sprintf(__('Dismiss (for %s weeks)', 'updraftplus'), 10); ?></a></div>
<h3 style="margin-top: 0px;"><?php _e('Be safe with an automatic backup','updraftplus');?></h3>
<p><?php echo $this->autobackup_ad_content(); ?></p>
</div>
<?php
}
}
public function show_admin_warning($message, $class = "updated") {
echo '<div class="updraftmessage '.$class.'">'."<p>$message</p></div>";
}
//
public function show_admin_warning_unwritable(){
$unwritable_mess = htmlspecialchars(__("The 'Backup Now' button is disabled as your backup directory is not writable (go to the 'Settings' tab and find the relevant option).", 'updraftplus'));
$this->show_admin_warning($unwritable_mess, "error");
}
public function show_admin_nosettings_warning() {
$this->show_admin_warning('<strong>'.__('Welcome to UpdraftPlus!', 'updraftplus').'</strong> '.__('To make a backup, just press the Backup Now button.', 'updraftplus').' <a href="#" id="updraft-navtab-settings2">'.__('To change any of the default settings of what is backed up, to configure scheduled backups, to send your backups to remote storage (recommended), and more, go to the settings tab.', 'updraftplus').'</a>', 'updated notice is-dismissible');
}
public function show_admin_warning_execution_time() {
$this->show_admin_warning('<strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__('The amount of time allowed for WordPress plugins to run is very low (%s seconds) - you should increase it to avoid backup failures due to time-outs (consult your web hosting company for more help - it is the max_execution_time PHP setting; the recommended value is %s seconds or more)', 'updraftplus'), (int)@ini_get('max_execution_time'), 90));
}
public function show_admin_warning_disabledcron() {
$this->show_admin_warning('<strong>'.__('Warning','updraftplus').':</strong> '.__('The scheduler is disabled in your WordPress install, via the DISABLE_WP_CRON setting. No backups can run (even "Backup Now") unless either you have set up a facility to call the scheduler manually, or until it is enabled.','updraftplus').' <a href="https://updraftplus.com/faqs/my-scheduled-backups-and-pressing-backup-now-does-nothing-however-pressing-debug-backup-does-produce-a-backup/#disablewpcron">'.__('Go here for more information.','updraftplus').'</a>', 'updated updraftplus-disable-wp-cron-warning');
}
public function show_admin_warning_diskspace() {
$this->show_admin_warning('<strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__('You have less than %s of free disk space on the disk which UpdraftPlus is configured to use to create backups. UpdraftPlus could well run out of space. Contact your the operator of your server (e.g. your web hosting company) to resolve this issue.','updraftplus'),'35 MB'));
}
public function show_admin_warning_wordpressversion() {
$this->show_admin_warning('<strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__('UpdraftPlus does not officially support versions of WordPress before %s. It may work for you, but if it does not, then please be aware that no support is available until you upgrade WordPress.', 'updraftplus'), '3.2'));
}
public function show_admin_warning_litespeed() {
$this->show_admin_warning('<strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__('Your website is hosted using the %s web server.','updraftplus'),'LiteSpeed').' <a href="https://updraftplus.com/faqs/i-am-having-trouble-backing-up-and-my-web-hosting-company-uses-the-litespeed-webserver/">'.__('Please consult this FAQ if you have problems backing up.', 'updraftplus').'</a>');
}
public function show_admin_debug_warning() {
$this->show_admin_warning('<strong>'.__('Notice','updraftplus').':</strong> '.__('UpdraftPlus\'s debug mode is on. You may see debugging notices on this page not just from UpdraftPlus, but from any other plugin installed. Please try to make sure that the notice you are seeing is from UpdraftPlus before you raise a support request.', 'updraftplus').'</a>');
}
public function show_admin_warning_overdue_crons($howmany) {
$ret = '<div class="updraftmessage updated"><p>';
$ret .= '<strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__('WordPress has a number (%d) of scheduled tasks which are overdue. Unless this is a development site, this probably means that the scheduler in your WordPress install is not working.', 'updraftplus'), $howmany).' <a href="https://updraftplus.com/faqs/scheduler-wordpress-installation-working/">'.__('Read this page for a guide to possible causes and how to fix it.', 'updraftplus').'</a>';
$ret .= '</p></div>';
return $ret;
}
public function show_admin_warning_dropbox() {
$this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> <a class="updraft_authlink" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraftmethod-dropbox-auth&updraftplus_dropboxauth=doit">'.sprintf(__('Click here to authenticate your %s account (you will not be able to back up to %s without it).','updraftplus'), 'Dropbox', 'Dropbox').'</a>');
}
public function show_admin_warning_bitcasa() {
$this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> <a class="updraft_authlink" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraftmethod-bitcasa-auth&updraftplus_bitcasaauth=doit">'.sprintf(__('Click here to authenticate your %s account (you will not be able to back up to %s without it).','updraftplus'), 'Bitcasa', 'Bitcasa').'</a>');
}
public function show_admin_warning_copycom() {
$this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> <a class="updraft_authlink" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraftmethod-copycom-auth&updraftplus_copycomauth=doit">'.sprintf(__('Click here to authenticate your %s account (you will not be able to back up to %s without it).','updraftplus'), 'Copy.Com', 'Copy').'</a>');
}
public function show_admin_warning_onedrive() {
$this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> <a class="updraft_authlink" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraftmethod-onedrive-auth&updraftplus_onedriveauth=doit">'.sprintf(__('Click here to authenticate your %s account (you will not be able to back up to %s without it).','updraftplus'), 'OneDrive', 'OneDrive').'</a>');
}
public function show_admin_warning_updraftvault() {
$this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> '.sprintf(__('%s has been chosen for remote storage, but you are not currently connected.', 'updraftplus'), 'UpdraftPlus Vault').' '.__('Go to the remote storage settings in order to connect.', 'updraftplus'));
}
public function show_admin_warning_googledrive() {
$this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> <a class="updraft_authlink" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraftmethod-googledrive-auth&updraftplus_googleauth=doit">'.sprintf(__('Click here to authenticate your %s account (you will not be able to back up to %s without it).','updraftplus'), 'Google Drive', 'Google Drive').'</a>');
}
public function show_admin_warning_googlecloud() {
$this->show_admin_warning('<strong>'.__('UpdraftPlus notice:','updraftplus').'</strong> <a class="updraft_authlink" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraftmethod-googlecloud-auth&updraftplus_googleauth=doit">'.sprintf(__('Click here to authenticate your %s account (you will not be able to back up to %s without it).','updraftplus'), 'Google Cloud', 'Google Cloud').'</a>');
}
// This options filter removes ABSPATH off the front of updraft_dir, if it is given absolutely and contained within it
public function prune_updraft_dir_prefix($updraft_dir) {
if ('/' == substr($updraft_dir, 0, 1) || "\\" == substr($updraft_dir, 0, 1) || preg_match('/^[a-zA-Z]:/', $updraft_dir)) {
$wcd = trailingslashit(WP_CONTENT_DIR);
if (strpos($updraft_dir, $wcd) === 0) {
$updraft_dir = substr($updraft_dir, strlen($wcd));
}
# Legacy
// if (strpos($updraft_dir, ABSPATH) === 0) {
// $updraft_dir = substr($updraft_dir, strlen(ABSPATH));
// }
}
return $updraft_dir;
}
public function updraft_download_backup() {
if (empty($_REQUEST['_wpnonce']) || !wp_verify_nonce($_REQUEST['_wpnonce'], 'updraftplus_download')) die;
if (empty($_REQUEST['timestamp']) || !is_numeric($_REQUEST['timestamp']) || empty($_REQUEST['type'])) exit;
$findex = empty($_REQUEST['findex']) ? 0 : (int)$_REQUEST['findex'];
$stage = empty($_REQUEST['stage']) ? '' : $_REQUEST['stage'];
// This call may not actually return, depending upon what mode it is called in
echo json_encode($this->do_updraft_download_backup($findex, $_REQUEST['type'], $_REQUEST['timestamp'], $stage));
die();
}
// This function may die(), depending on the request being made in $stage
public function do_updraft_download_backup($findex, $type, $timestamp, $stage, $close_connection_callable = false) {
@set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);
global $updraftplus;
// This is a bit ugly; these variables get placed back into $_POST (where they may possibly have come from), so that UpdraftPlus::log() can detect exactly where to log the download status.
$_POST['findex'] = $findex;
$_POST['type'] = $type;
$_POST['timestamp'] = $timestamp;
// Check that it is a known entity type; if not, die
if ('db' != substr($type, 0, 2)) {
$backupable_entities = $updraftplus->get_backupable_file_entities(true);
foreach ($backupable_entities as $t => $info) {
if ($type == $t) $type_match = true;
}
if (empty($type_match)) return array('result' => 'error', 'code' => 'no_such_type');
}
// We already know that no possible entities have an MD5 clash (even after 2 characters)
// Also, there's nothing enforcing a requirement that nonces are hexadecimal
$job_nonce = dechex($timestamp).$findex.substr(md5($type), 0, 3);
// You need a nonce before you can set job data. And we certainly don't yet have one.
$updraftplus->backup_time_nonce($job_nonce);
$debug_mode = UpdraftPlus_Options::get_updraft_option('updraft_debug_mode');
// Set the job type before logging, as there can be different logging destinations
$updraftplus->jobdata_set('job_type', 'download');
$updraftplus->jobdata_set('job_time_ms', $updraftplus->job_time_ms);
// Retrieve the information from our backup history
$backup_history = $updraftplus->get_backup_history();
// Base name
$file = $backup_history[$timestamp][$type];
// Deal with multi-archive sets
if (is_array($file)) $file=$file[$findex];
// Where it should end up being downloaded to
$fullpath = $updraftplus->backups_dir_location().'/'.$file;
if (2 == $stage) {
$updraftplus->spool_file($fullpath);
// Do not return - we do not want the caller to add any output
die;
}
if ('delete' == $stage) {
@unlink($fullpath);
$updraftplus->log("The file has been deleted ($file)");
return array('result' => 'deleted');
}
// TODO: FIXME: Failed downloads may leave log files forever (though they are small)
if ($debug_mode) $updraftplus->logfile_open($updraftplus->nonce);
set_error_handler(array($updraftplus, 'php_error'), E_ALL & ~E_STRICT);
$updraftplus->log("Requested to obtain file: timestamp=$timestamp, type=$type, index=$findex");
$itext = empty($findex) ? '' : $findex;
$known_size = isset($backup_history[$timestamp][$type.$itext.'-size']) ? $backup_history[$timestamp][$type.$itext.'-size'] : 0;
$services = (isset($backup_history[$timestamp]['service'])) ? $backup_history[$timestamp]['service'] : false;
if (is_string($services)) $services = array($services);
$updraftplus->jobdata_set('service', $services);
// Fetch it from the cloud, if we have not already got it
$needs_downloading = false;
if (!file_exists($fullpath)) {
//if the file doesn't exist and they're using one of the cloud options, fetch it down from the cloud.
$needs_downloading = true;
$updraftplus->log('File does not yet exist locally - needs downloading');
} elseif ($known_size > 0 && filesize($fullpath) < $known_size) {
$updraftplus->log("The file was found locally (".filesize($fullpath).") but did not match the size in the backup history ($known_size) - will resume downloading");
$needs_downloading = true;
} elseif ($known_size > 0) {
$updraftplus->log('The file was found locally and matched the recorded size from the backup history ('.round($known_size/1024,1).' KB)');
} else {
$updraftplus->log('No file size was found recorded in the backup history. We will assume the local one is complete.');
$known_size = filesize($fullpath);
}
// The AJAX responder that updates on progress wants to see this
$updraftplus->jobdata_set('dlfile_'.$timestamp.'_'.$type.'_'.$findex, "downloading:$known_size:$fullpath");
if ($needs_downloading) {
$msg = array(
'result' => 'needs_download'
);
if ($close_connection_callable && is_callable($close_connection_callable)) {
call_user_func($close_connection_callable, $msg);
} else {
$updraftplus->close_browser_connection(json_encode($msg));
}
$is_downloaded = false;
add_action('http_request_args', array($updraftplus, 'modify_http_options'));
foreach ($services as $service) {
if ($is_downloaded) continue;
$download = $this->download_file($file, $service);
if (is_readable($fullpath) && $download !== false) {
clearstatcache();
$updraftplus->log('Remote fetch was successful (file size: '.round(filesize($fullpath)/1024,1).' KB)');
$is_downloaded = true;
} else {
clearstatcache();
if (0 === @filesize($fullpath)) @unlink($fullpath);
$updraftplus->log('Remote fetch failed');
}
}
remove_action('http_request_args', array($updraftplus, 'modify_http_options'));
}
// Now, be ready to spool the thing to the browser
if (is_file($fullpath) && is_readable($fullpath)) {
// That message is then picked up by the AJAX listener
$updraftplus->jobdata_set('dlfile_'.$timestamp.'_'.$type.'_'.$findex, 'downloaded:'.filesize($fullpath).":$fullpath");
$result = 'downloaded';
} else {
$updraftplus->jobdata_set('dlfile_'.$timestamp.'_'.$type.'_'.$findex, 'failed');
$updraftplus->jobdata_set('dlerrors_'.$timestamp.'_'.$type.'_'.$findex, $updraftplus->errors);
$updraftplus->log('Remote fetch failed. File '.$fullpath.' did not exist or was unreadable. If you delete local backups then remote retrieval may have failed.');
$result = 'download_failed';
}
restore_error_handler();
@fclose($updraftplus->logfile_handle);
if (!$debug_mode) @unlink($updraftplus->logfile_name);
// The browser connection was possibly already closed, but not necessarily
return array('result' => $result);
}
# Pass only a single service, as a string, into this function
private function download_file($file, $service) {
global $updraftplus;
@set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);
$updraftplus->log("Requested file from remote service: $service: $file");
$method_include = UPDRAFTPLUS_DIR.'/methods/'.$service.'.php';
if (file_exists($method_include)) require_once($method_include);
$objname = "UpdraftPlus_BackupModule_${service}";
if (method_exists($objname, "download")) {
$remote_obj = new $objname;
return $remote_obj->download($file);
} else {
$updraftplus->log("Automatic backup restoration is not available with the method: $service.");
$updraftplus->log("$file: ".sprintf(__("The backup archive for this file could not be found. The remote storage method in use (%s) does not allow us to retrieve files. To perform any restoration using UpdraftPlus, you will need to obtain a copy of this file and place it inside UpdraftPlus's working folder", 'updraftplus'), $service)." (".$this->prune_updraft_dir_prefix($updraftplus->backups_dir_location()).")", 'error');
return false;
}
}
public function updraft_ajax_handler() {
global $updraftplus;
$nonce = (empty($_REQUEST['nonce'])) ? "" : $_REQUEST['nonce'];
if (!wp_verify_nonce($nonce, 'updraftplus-credentialtest-nonce') || empty($_REQUEST['subaction'])) die('Security check');
// Mitigation in case the nonce leaked to an unauthorised user
if (isset($_REQUEST['subaction']) && 'dismissautobackup' == $_REQUEST['subaction']) {
if (!current_user_can('update_plugins') && !current_user_can('update_themes')) return;
} elseif (isset($_REQUEST['subaction']) && ('dismissexpiry' == $_REQUEST['subaction'] || 'dismissdashnotice' == $_REQUEST['subaction'])) {
if (!current_user_can('update_plugins')) return;
} else {
if (!UpdraftPlus_Options::user_can_manage()) return;
}
// Some of this checks that _REQUEST['subaction'] is set, which is redundant (done already in the nonce check)
/*
// This one is no longer used anywhere
if (isset($_REQUEST['subaction']) && 'lastlog' == $_REQUEST['subaction']) {
$last_message = UpdraftPlus_Options::get_updraft_option('updraft_lastmessage');
echo htmlspecialchars( '('.__('Nothing yet logged', 'updraftplus').')'));
} else
*/
if ('forcescheduledresumption' == $_REQUEST['subaction'] && !empty($_REQUEST['resumption']) && !empty($_REQUEST['job_id']) && is_numeric($_REQUEST['resumption'])) {
// Casting $resumption to int is absolutely necessary, as the WP cron system uses a hashed serialisation of the parameters for identifying jobs. Different type => different hash => does not match
$resumption = (int)$_REQUEST['resumption'];
$job_id = $_REQUEST['job_id'];
$get_cron = $this->get_cron($job_id);
if (!is_array($get_cron)) {
echo json_encode(array('r' => false));
} else {
$updraftplus->log("Forcing resumption: job id=$job_id, resumption=$resumption");
$time = $get_cron[0];
// wp_unschedule_event($time, 'updraft_backup_resume', array($resumption, $job_id));
wp_clear_scheduled_hook('updraft_backup_resume', array($resumption, $job_id));
$updraftplus->close_browser_connection(json_encode(array('r' => true)));
$updraftplus->jobdata_set_from_array($get_cron[1]);
$updraftplus->backup_resume($resumption, $job_id);
}
} elseif (isset($_GET['subaction']) && 'activejobs_list' == $_GET['subaction']) {
echo json_encode($this->get_activejobs_list($_GET));
} elseif (isset($_REQUEST['subaction']) && 'updraftcentral_delete_key' == $_REQUEST['subaction'] && isset($_REQUEST['key_id'])) {
global $updraftplus_updraftcentral_main;
if (!is_a($updraftplus_updraftcentral_main, 'UpdraftPlus_UpdraftCentral_Main')) {
echo json_encode(array('error' => 'UpdraftPlus_UpdraftCentral_Main object not found'));
die;
}
echo json_encode($updraftplus_updraftcentral_main->delete_key($_REQUEST['key_id']));
die;
} elseif (isset($_REQUEST['subaction']) && ('updraftcentral_create_key' == $_REQUEST['subaction'] || 'updraftcentral_get_log' == $_REQUEST['subaction'])) {
global $updraftplus_updraftcentral_main;
if (!is_a($updraftplus_updraftcentral_main, 'UpdraftPlus_UpdraftCentral_Main')) {
echo json_encode(array('error' => 'UpdraftPlus_UpdraftCentral_Main object not found'));
die;
}
$call_method = substr($_REQUEST['subaction'], 15);
echo json_encode(call_user_func(array($updraftplus_updraftcentral_main, $call_method), $_REQUEST));
die;
} elseif (isset($_REQUEST['subaction']) && 'callwpaction' == $_REQUEST['subaction'] && !empty($_REQUEST['wpaction'])) {
ob_start();
$res = '<em>Request received: </em>';
if (preg_match('/^([^:]+)+:(.*)$/', stripslashes($_REQUEST['wpaction']), $matches)) {
$action = $matches[1];
if (null === ($args = json_decode($matches[2], true))) {
$res .= "The parameters (should be JSON) could not be decoded";
$action = false;
} else {
$res .= "Will despatch action: ".htmlspecialchars($action).", parameters: ".htmlspecialchars(implode(',', $args));
}
} else {
$action = $_REQUEST['wpaction'];
$res .= "Will despatch action: ".htmlspecialchars($action).", no parameters";
}
echo json_encode(array('r' => $res));
$ret = ob_get_clean();
$updraftplus->close_browser_connection($ret);
if (!empty($action)) {
if (!empty($args)) {
do_action_ref_array($action, $args);
} else {
do_action($action);
}
}
die;
} elseif (isset($_REQUEST['subaction']) && 'whichdownloadsneeded' == $_REQUEST['subaction'] && is_array($_REQUEST['downloads']) && isset($_REQUEST['timestamp']) && is_numeric($_REQUEST['timestamp'])) {
// The purpose of this is to look at the list of indicated downloads, and indicate which are not already fully downloaded. i.e. Which need further action.
$send_back = array();
$backup = $updraftplus->get_backup_history($_REQUEST['timestamp']);
$updraft_dir = $updraftplus->backups_dir_location();
$backupable_entities = $updraftplus->get_backupable_file_entities();
if (empty($backup)) {
echo json_encode(array('result' => 'asyouwere'));
} else {
foreach ($_REQUEST['downloads'] as $i => $download) {
if (is_array($download) && 2 == count($download) && isset($download[0]) && isset($download[1])) {
$entity = $download[0];
if (('db' == $entity || isset($backupable_entities[$entity])) && isset($backup[$entity])) {
$indexes = explode(',', $download[1]);
$retain_string = '';
foreach ($indexes as $index) {
$retain = true; // default
$findex = (0 == $index) ? '' : (string)$index;
$files = $backup[$entity];
if (!is_array($files)) $files = array($files);
$size_key = $entity.$findex.'-size';
if (isset($files[$index]) && isset($backup[$size_key])) {
$file = $updraft_dir.'/'.$files[$index];
if (file_exists($file) && filesize($file) >= $backup[$size_key]) {
$retain = false;
}
}
if ($retain) {
$retain_string .= ('' === $retain_string) ? $index : ','.$index;
$send_back[$i][0] = $entity;
$send_back[$i][1] = $retain_string;
}
}
} else {
$send_back[$i][0] = $entity;
$send_back[$i][1] = $download[$i][1];
}
} else {
// Format not understood. Just send it back as-is.
$send_back[$i] = $download[$i];
}
}
// Finally, renumber the keys (to usual PHP style - 0, 1, ...). Otherwise, in order to preserve the indexes, json_encode() will create an object instead of an array in the case where $send_back only has one element (and is indexed with an index > 0)
$send_back = array_values($send_back);
echo json_encode(array('downloads' => $send_back));
}
} elseif (isset($_REQUEST['subaction']) && 'httpget' == $_REQUEST['subaction']) {
if (empty($_REQUEST['uri'])) {
echo json_encode(array('r' => ''));
die;
}
$uri = $_REQUEST['uri'];
if (!empty($_REQUEST['curl'])) {
if (!function_exists('curl_exec')) {
echo json_encode(array('e' => 'No Curl installed'));
die;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $output=fopen('php://temp', "w+"));
$response = curl_exec($ch);
$error = curl_error($ch);
$getinfo = curl_getinfo($ch);
curl_close($ch);
$resp = array();
if (false === $response) {
$resp['e'] = htmlspecialchars($error);
# json_encode(array('e' => htmlspecialchars($error)));
}
$resp['r'] = (empty($response)) ? '' : htmlspecialchars(substr($response, 0, 2048));
rewind($output);
$verb = stream_get_contents($output);
if (!empty($verb)) $resp['r'] = htmlspecialchars($verb)."\n\n".$resp['r'];
echo json_encode($resp);
// echo json_encode(array('r' => htmlspecialchars(substr($response, 0, 2048))));
} else {
$response = wp_remote_get($uri, array('timeout' => 10));
if (is_wp_error($response)) {
echo json_encode(array('e' => htmlspecialchars($response->get_error_message())));
die;
}
echo json_encode(array('r' => wp_remote_retrieve_response_code($response).': '.htmlspecialchars(substr(wp_remote_retrieve_body($response), 0, 2048))));
}
die;
} elseif (isset($_REQUEST['subaction']) && 'dismissautobackup' == $_REQUEST['subaction']) {
UpdraftPlus_Options::update_updraft_option('updraftplus_dismissedautobackup', time() + 84*86400);
} elseif (isset($_REQUEST['subaction']) && 'set_autobackup_default' == $_REQUEST['subaction']) {
// This option when set should have integers, not bools
$default = empty($_REQUEST['default']) ? 0 : 1;
UpdraftPlus_Options::update_updraft_option('updraft_autobackup_default', $default);
} elseif (isset($_REQUEST['subaction']) && 'dismissexpiry' == $_REQUEST['subaction']) {
UpdraftPlus_Options::update_updraft_option('updraftplus_dismissedexpiry', time() + 14*86400);
} elseif (isset($_REQUEST['subaction']) && 'dismissdashnotice' == $_REQUEST['subaction']) {
UpdraftPlus_Options::update_updraft_option('updraftplus_dismisseddashnotice', time() + 366*86400);
} elseif (isset($_REQUEST['subaction']) && 'poplog' == $_REQUEST['subaction']){
echo json_encode($this->fetch_log($_REQUEST['backup_nonce']));
} elseif (isset($_REQUEST['subaction']) && 'restore_alldownloaded' == $_REQUEST['subaction'] && isset($_REQUEST['restoreopts']) && isset($_REQUEST['timestamp'])) {
$backups = $updraftplus->get_backup_history();
$updraft_dir = $updraftplus->backups_dir_location();
$timestamp = (int)$_REQUEST['timestamp'];
if (!isset($backups[$timestamp])) {
echo json_encode(array('m' => '', 'w' => '', 'e' => __('No such backup set exists', 'updraftplus')));
die;
}
$mess = array();
parse_str(stripslashes($_REQUEST['restoreopts']), $res);
if (isset($res['updraft_restore'])) {
set_error_handler(array($this, 'get_php_errors'), E_ALL & ~E_STRICT);
$elements = array_flip($res['updraft_restore']);
$warn = array(); $err = array();
@set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);
$max_execution_time = (int)@ini_get('max_execution_time');
if ($max_execution_time>0 && $max_execution_time<61) {
$warn[] = sprintf(__('The PHP setup on this webserver allows only %s seconds for PHP to run, and does not allow this limit to be raised. If you have a lot of data to import, and if the restore operation times out, then you will need to ask your web hosting company for ways to raise this limit (or attempt the restoration piece-by-piece).', 'updraftplus'), $max_execution_time);
}
if (isset($backups[$timestamp]['native']) && false == $backups[$timestamp]['native']) {
$warn[] = __('This backup set was not known by UpdraftPlus to be created by the current WordPress installation, but was either found in remote storage, or was sent from a remote site.', 'updraftplus').' '.__('You should make sure that this really is a backup set intended for use on this website, before you restore (rather than a backup set of an unrelated website).', 'updraftplus');
}
if (isset($elements['db'])) {
// Analyse the header of the database file + display results
list ($mess2, $warn2, $err2, $info) = $updraftplus->analyse_db_file($timestamp, $res);
$mess = array_merge($mess, $mess2);
$warn = array_merge($warn, $warn2);
$err = array_merge($err, $err2);
foreach ($backups[$timestamp] as $bid => $bval) {
if ('db' != $bid && 'db' == substr($bid, 0, 2) && '-size' != substr($bid, -5, 5)) {
$warn[] = __('Only the WordPress database can be restored; you will need to deal with the external database manually.', 'updraftplus');
break;
}
}
}
$backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
$backupable_plus_db = $backupable_entities;
$backupable_plus_db['db'] = array('path' => 'path-unused', 'description' => __('Database', 'updraftplus'));
if (!empty($backups[$timestamp]['meta_foreign'])) {
$foreign_known = apply_filters('updraftplus_accept_archivename', array());
if (!is_array($foreign_known) || empty($foreign_known[$backups[$timestamp]['meta_foreign']])) {
$err[] = sprintf(__('Backup created by unknown source (%s) - cannot be restored.', 'updraftplus'), $backups[$timestamp]['meta_foreign']);
} else {
// For some reason, on PHP 5.5 passing by reference in a single array stopped working with apply_filters_ref_array (though not with do_action_ref_array).
$backupable_plus_db = apply_filters_ref_array("updraftplus_importforeign_backupable_plus_db", array($backupable_plus_db, array($foreign_known[$backups[$timestamp]['meta_foreign']], &$mess, &$warn, &$err)));
}
}
foreach ($backupable_plus_db as $type => $entity_info) {
if (!isset($elements[$type])) continue;
$whatwegot = $backups[$timestamp][$type];
if (is_string($whatwegot)) $whatwegot = array($whatwegot);
$expected_index = 0;
$missing = '';
ksort($whatwegot);
$outof = false;
foreach ($whatwegot as $index => $file) {
if (preg_match('/\d+of(\d+)\.zip/', $file, $omatch)) { $outof = max($matches[1], 1); }
if ($index != $expected_index) {
$missing .= ($missing == '') ? (1+$expected_index) : ",".(1+$expected_index);
}
if (!file_exists($updraft_dir.'/'.$file)) {
$err[] = sprintf(__('File not found (you need to upload it): %s', 'updraftplus'), $updraft_dir.'/'.$file);
} elseif (filesize($updraft_dir.'/'.$file) == 0) {
$err[] = sprintf(__('File was found, but is zero-sized (you need to re-upload it): %s', 'updraftplus'), $file);
} else {
$itext = (0 == $index) ? '' : $index;
if (!empty($backups[$timestamp][$type.$itext.'-size']) && $backups[$timestamp][$type.$itext.'-size'] != filesize($updraft_dir.'/'.$file)) {
if (empty($warn['doublecompressfixed'])) {
$warn[] = sprintf(__('File (%s) was found, but has a different size (%s) from what was expected (%s) - it may be corrupt.', 'updraftplus'), $file, filesize($updraft_dir.'/'.$file), $backups[$timestamp][$type.$itext.'-size']);
}
}
do_action_ref_array("updraftplus_checkzip_$type", array($updraft_dir.'/'.$file, &$mess, &$warn, &$err));
}
$expected_index++;
}
do_action_ref_array("updraftplus_checkzip_end_$type", array(&$mess, &$warn, &$err));
// Detect missing archives where they are missing from the end of the set
if ($outof>0 && $expected_index < $outof) {
for ($j = $expected_index; $j<$outof; $j++) {
$missing .= ($missing == '') ? (1+$j) : ",".(1+$j);
}
}
if ('' != $missing) {
$warn[] = sprintf(__("This multi-archive backup set appears to have the following archives missing: %s", 'updraftplus'), $missing.' ('.$entity_info['description'].')');
}
}
if (0 == count($err) && 0 == count($warn)) {
$mess_first = __('The backup archive files have been successfully processed. Now press Restore again to proceed.', 'updraftplus');
} elseif (0 == count($err)) {
$mess_first = __('The backup archive files have been processed, but with some warnings. If all is well, then now press Restore again to proceed. Otherwise, cancel and correct any problems first.', 'updraftplus');
} else {
$mess_first = __('The backup archive files have been processed, but with some errors. You will need to cancel and correct any problems before retrying.', 'updraftplus');
}
if (count($this->logged) >0) {
foreach ($this->logged as $lwarn) $warn[] = $lwarn;
}
restore_error_handler();
// Get the info if it hasn't already come from the DB scan
if (!isset($info) || !is_array($info)) $info = array();
// Not all chracters can be json-encoded, and we don't need this potentially-arbitrary user-supplied info.
unset($info['label']);
if (!isset($info['created_by_version']) && !empty($backups[$timestamp]['created_by_version'])) $info['created_by_version'] = $backups[$timestamp]['created_by_version'];
if (!isset($info['multisite']) && !empty($backups[$timestamp]['is_multisite'])) $info['multisite'] = $backups[$timestamp]['is_multisite'];
do_action_ref_array('updraftplus_restore_all_downloaded_postscan', array($backups, $timestamp, $elements, &$info, &$mess, &$warn, &$err));
echo json_encode(array('m' => '<p>'.$mess_first.'</p>'.implode('<br>', $mess), 'w' => implode('<br>', $warn), 'e' => implode('<br>', $err), 'i' => json_encode($info)));
}
} elseif ('sid_reset' == $_REQUEST['subaction']) {
delete_site_option('updraftplus-addons_siteid');
echo json_encode(array('newsid' => $updraftplus->siteid()));
} elseif (('vault_connect' == $_REQUEST['subaction'] && isset($_REQUEST['email']) && isset($_REQUEST['pass'])) || 'vault_disconnect' == $_REQUEST['subaction'] || 'vault_recountquota' == $_REQUEST['subaction']) {
require_once(UPDRAFTPLUS_DIR.'/methods/updraftvault.php');
$vault = new UpdraftPlus_BackupModule_updraftvault();
call_user_func(array($vault, 'ajax_'.$_REQUEST['subaction']));
} elseif (isset($_POST['backup_timestamp']) && 'deleteset' == $_REQUEST['subaction']) {
echo json_encode($this->delete_set($_POST));
} elseif ('rawbackuphistory' == $_REQUEST['subaction']) {
echo '<h3 id="ud-debuginfo-rawbackups">'.__('Known backups (raw)', 'updraftplus').'</h3><pre>';
var_dump($updraftplus->get_backup_history());
echo '</pre>';
echo '<h3 id="ud-debuginfo-files">Files</h3><pre>';
$updraft_dir = $updraftplus->backups_dir_location();
$raw_output = array();
$d = dir($updraft_dir);
while (false !== ($entry = $d->read())) {
$fp = $updraft_dir.'/'.$entry;
$mtime = filemtime($fp);
if (is_dir($fp)) {
$size = ' d';
} elseif (is_link($fp)) {
$size = ' l';
} elseif (is_file($fp)) {
$size = sprintf("%8.1f", round(filesize($fp)/1024, 1)).' '.gmdate('r', $mtime);
} else {
$size = ' ?';
}
if (preg_match('/^log\.(.*)\.txt$/', $entry, $lmatch)) $entry = '<a target="_top" href="?action=downloadlog&page=updraftplus&updraftplus_backup_nonce='.htmlspecialchars($lmatch[1]).'">'.$entry.'</a>';
$raw_output[$mtime] = empty($raw_output[$mtime]) ? sprintf("%s %s\n", $size, $entry) : $raw_output[$mtime].sprintf("%s %s\n", $size, $entry);
}
@$d->close();
krsort($raw_output, SORT_NUMERIC);
foreach ($raw_output as $line) echo $line;
echo '</pre>';
echo '<h3 id="ud-debuginfo-options">'.__('Options (raw)', 'updraftplus').'</h3>';
$opts = $updraftplus->get_settings_keys();
asort($opts);
// <tr><th>'.__('Key','updraftplus').'</th><th>'.__('Value','updraftplus').'</th></tr>
echo '<table><thead></thead><tbody>';
foreach ($opts as $opt) {
echo '<tr><td>'.htmlspecialchars($opt).'</td><td>'.htmlspecialchars(print_r(UpdraftPlus_Options::get_updraft_option($opt), true)).'</td>';
}
echo '</tbody></table>';
do_action('updraftplus_showrawinfo');
} elseif ('countbackups' == $_REQUEST['subaction']) {
$backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history');
$backup_history = (is_array($backup_history))?$backup_history:array();
#echo sprintf(__('%d set(s) available', 'updraftplus'), count($backup_history));
echo __('Existing Backups', 'updraftplus').' ('.count($backup_history).')';
} elseif ('ping' == $_REQUEST['subaction']) {
// The purpose of this is to detect brokenness caused by extra line feeds in plugins/themes - before it breaks other AJAX operations and leads to support requests
echo 'pong';
} elseif ('checkoverduecrons' == $_REQUEST['subaction']) {
$how_many_overdue = $this->howmany_overdue_crons();
if ($how_many_overdue >= 4) echo json_encode(array('m' => $this->show_admin_warning_overdue_crons($how_many_overdue)));
} elseif ('delete_old_dirs' == $_REQUEST['subaction']) {
$this->delete_old_dirs_go(false);
} elseif ('phpinfo' == $_REQUEST['subaction']) {
phpinfo(INFO_ALL ^ (INFO_CREDITS | INFO_LICENSE));
echo '<h3 id="ud-debuginfo-constants">'.__('Constants', 'updraftplus').'</h3>';
$opts = @get_defined_constants();
ksort($opts);
// <tr><th>'.__('Key','updraftplus').'</th><th>'.__('Value','updraftplus').'</th></tr>
echo '<table><thead></thead><tbody>';
foreach ($opts as $key => $opt) {
echo '<tr><td>'.htmlspecialchars($key).'</td><td>'.htmlspecialchars(print_r($opt, true)).'</td>';
}
echo '</tbody></table>';
} elseif ('doaction' == $_REQUEST['subaction'] && !empty($_REQUEST['subsubaction']) && 'updraft_' == substr($_REQUEST['subsubaction'], 0, 8)) {
do_action($_REQUEST['subsubaction']);
} elseif ('backupnow' == $_REQUEST['subaction']) {
$this->request_backupnow($_REQUEST);
# Old-style: schedule an event in 5 seconds time. This has the advantage of testing out the scheduler, and alerting the user if it doesn't work... but has the disadvantage of not working in that case.
# I don't think the </div>s should be here - in case this is ever re-activated
// if (wp_schedule_single_event(time()+5, $event, array($backupnow_nocloud)) === false) {
// $updraftplus->log("A backup run failed to schedule");
// echo __("Failed.", 'updraftplus');
// } else {
// echo htmlspecialchars(__('OK. You should soon see activity in the "Last log message" field below.','updraftplus'))." <a href=\"https://updraftplus.com/faqs/my-scheduled-backups-and-pressing-backup-now-does-nothing-however-pressing-debug-backup-does-produce-a-backup/\"><br>".__('Nothing happening? Follow this link for help.','updraftplus')."</a>";
// $updraftplus->log("A backup run has been scheduled");
// }
} elseif (isset($_GET['subaction']) && 'lastbackup' == $_GET['subaction']) {
echo $this->last_backup_html();
} elseif (isset($_GET['subaction']) && 'activejobs_delete' == $_GET['subaction'] && isset($_GET['jobid'])) {
echo json_encode($this->activejobs_delete((string)$_GET['jobid']));
} elseif (isset($_GET['subaction']) && 'diskspaceused' == $_GET['subaction'] && isset($_GET['entity'])) {
$entity = $_GET['entity'];
// This can count either the size of the Updraft directory, or of the data to be backed up
echo $this->get_disk_space_used($entity);
} elseif (isset($_GET['subaction']) && 'historystatus' == $_GET['subaction']) {
$remotescan = !empty($_GET['remotescan']);
$rescan = ($remotescan || !empty($_GET['rescan']));
$history_status = $this->get_history_status($rescan, $remotescan);
echo @json_encode($history_status);
} elseif (isset($_POST['subaction']) && $_POST['subaction'] == 'credentials_test') {
$this->do_credentials_test($_POST);
die;
}
die;
}
// This echoes output; so, you will need to do output buffering if you want to capture it
public function do_credentials_test($test_settings) {
$method = (!empty($test_settings['method']) && preg_match("/^[a-z0-9]+$/", $test_settings['method'])) ? $test_settings['method'] : "";
$objname = "UpdraftPlus_BackupModule_$method";
$this->logged = array();
# TODO: Add action for WP HTTP SSL stuff
set_error_handler(array($this, 'get_php_errors'), E_ALL & ~E_STRICT);
if (!class_exists($objname)) include_once(UPDRAFTPLUS_DIR."/methods/$method.php");
# TODO: Add action for WP HTTP SSL stuff
if (method_exists($objname, "credentials_test")) {
$obj = new $objname;
$obj->credentials_test($test_settings);
}
if (count($this->logged) >0) {
echo "\n\n".__('Messages:', 'updraftplus')."\n";
foreach ($this->logged as $err) {
echo "* $err\n";
}
}
restore_error_handler();
}
// Relevant options (array keys): backup_timestamp, delete_remote,
public function delete_set($opts) {
global $updraftplus;
$backups = $updraftplus->get_backup_history();
$timestamps = (string)$opts['backup_timestamp'];
$timestamps = explode(',', $timestamps);
$delete_remote = empty($opts['delete_remote']) ? false : true;
// You need a nonce before you can set job data. And we certainly don't yet have one.
$updraftplus->backup_time_nonce();
// Set the job type before logging, as there can be different logging destinations
$updraftplus->jobdata_set('job_type', 'delete');
$updraftplus->jobdata_set('job_time_ms', $updraftplus->job_time_ms);
if (UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) {
$updraftplus->logfile_open($updraftplus->nonce);
set_error_handler(array($updraftplus, 'php_error'), E_ALL & ~E_STRICT);
}
$updraft_dir = $updraftplus->backups_dir_location();
$backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
$local_deleted = 0;
$remote_deleted = 0;
$sets_removed = 0;
foreach ($timestamps as $i => $timestamp) {
if (!isset($backups[$timestamp])) {
echo json_encode(array('result' => 'error', 'message' => __('Backup set not found', 'updraftplus')));
die;
}
$nonce = isset($backups[$timestamp]['nonce']) ? $backups[$timestamp]['nonce'] : '';
$delete_from_service = array();
if ($delete_remote) {
// Locate backup set
if (isset($backups[$timestamp]['service'])) {
$services = is_string($backups[$timestamp]['service']) ? array($backups[$timestamp]['service']) : $backups[$timestamp]['service'];
if (is_array($services)) {
foreach ($services as $service) {
if ($service && $service != 'none' && $service != 'email') $delete_from_service[] = $service;
}
}
}
}
$files_to_delete = array();
foreach ($backupable_entities as $key => $ent) {
if (isset($backups[$timestamp][$key])) {
$files_to_delete[$key] = $backups[$timestamp][$key];
}
}
// Delete DB
if (isset($backups[$timestamp]['db'])) $files_to_delete['db'] = $backups[$timestamp]['db'];
// Also delete the log
if ($nonce && !UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) {
$files_to_delete['log'] = "log.$nonce.txt";
}
unset($backups[$timestamp]);
$sets_removed++;
UpdraftPlus_Options::update_updraft_option('updraft_backup_history', $backups);
add_action('http_request_args', array($updraftplus, 'modify_http_options'));
foreach ($files_to_delete as $key => $files) {
# Local deletion
if (is_string($files)) $files=array($files);
foreach ($files as $file) {
if (is_file($updraft_dir.'/'.$file)) {
if (@unlink($updraft_dir.'/'.$file)) $local_deleted++;
}
}
if ('log' != $key && count($delete_from_service) > 0) {
foreach ($delete_from_service as $service) {
if ('email' == $service) continue;
if (file_exists(UPDRAFTPLUS_DIR."/methods/$service.php")) require_once(UPDRAFTPLUS_DIR."/methods/$service.php");
$objname = "UpdraftPlus_BackupModule_".$service;
$deleted = -1;
if (class_exists($objname)) {
# TODO: Re-use the object (i.e. prevent repeated connection setup/teardown)
$remote_obj = new $objname;
$deleted = $remote_obj->delete($files);
}
if ($deleted === -1) {
//echo __('Did not know how to delete from this cloud service.', 'updraftplus');
} elseif ($deleted !== false) {
$remote_deleted = $remote_deleted + count($files);
} else {
// Do nothing
}
}
}
}
remove_action('http_request_args', array($updraftplus, 'modify_http_options'));
}
$message = sprintf(__('Backup sets removed: %d', 'updraftplus'),$sets_removed)."\n";
$message .= sprintf(__('Local archives deleted: %d', 'updraftplus'),$local_deleted)."\n";
$message .= sprintf(__('Remote archives deleted: %d', 'updraftplus'),$remote_deleted)."\n";
$updraftplus->log("Local archives deleted: ".$local_deleted);
$updraftplus->log("Remote archives deleted: ".$remote_deleted);
if (UpdraftPlus_Options::get_updraft_option('updraft_debug_mode')) {
restore_error_handler();
}
return array('result' => 'success', 'message' => $message, 'removed' => array('sets' => $sets_removed, 'local' => $local_deleted, 'remote' => $remote_deleted));
}
public function get_history_status($rescan, $remotescan) {
global $updraftplus;
if ($rescan) $messages = $updraftplus->rebuild_backup_history($remotescan);
$backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history');
$backup_history = (is_array($backup_history)) ? $backup_history : array();
$output = $this->existing_backup_table($backup_history);
if (!empty($messages) && is_array($messages)) {
$noutput = '<div style="margin-left: 100px; margin-top: 10px;"><ul style="list-style: disc inside;">';
foreach ($messages as $msg) {
$noutput .= '<li>'.(($msg['desc']) ? $msg['desc'].': ' : '').'<em>'.$msg['message'].'</em></li>';
}
$noutput .= '</ul></div>';
$output = $noutput.$output;
}
$logs_exist = (false !== strpos($output, 'downloadlog'));
if (!$logs_exist) {
list($mod_time, $log_file, $nonce) = $updraftplus->last_modified_log();
if ($mod_time) $logs_exist = true;
}
return apply_filters('updraftplus_get_history_status_result', array(
'n' => sprintf(__('Existing Backups', 'updraftplus').' (%d)', count($backup_history)),
't' => $output,
'cksum' => md5($output),
'logs_exist' => $logs_exist,
));
}
public function get_disk_space_used($entity) {
global $updraftplus;
if ('updraft' == $entity) {
return $this->recursive_directory_size($updraftplus->backups_dir_location());
} else {
$backupable_entities = $updraftplus->get_backupable_file_entities(true, false);
if ('all' == $entity) {
$total_size = 0;
foreach ($backupable_entities as $entity => $data) {
# Might be an array
$basedir = $backupable_entities[$entity];
$dirs = apply_filters('updraftplus_dirlist_'.$entity, $basedir);
$size = $this->recursive_directory_size($dirs, $updraftplus->get_exclude($entity), $basedir, 'numeric');
if (is_numeric($size) && $size>0) $total_size += $size;
}
return $updraftplus->convert_numeric_size_to_text($total_size);
} elseif (!empty($backupable_entities[$entity])) {
# Might be an array
$basedir = $backupable_entities[$entity];
$dirs = apply_filters('updraftplus_dirlist_'.$entity, $basedir);
return $this->recursive_directory_size($dirs, $updraftplus->get_exclude($entity), $basedir);
}
}
return __('Error', 'updraftplus');
}
public function activejobs_delete($job_id) {
if (preg_match("/^[0-9a-f]{12}$/", $job_id)) {
global $updraftplus;
$cron = get_option('cron');
$found_it = false;
$updraft_dir = $updraftplus->backups_dir_location();
if (file_exists($updraft_dir.'/log.'.$job_id.'.txt')) touch($updraft_dir.'/deleteflag-'.$job_id.'.txt');
foreach ($cron as $time => $job) {
if (isset($job['updraft_backup_resume'])) {
foreach ($job['updraft_backup_resume'] as $hook => $info) {
if (isset($info['args'][1]) && $info['args'][1] == $job_id) {
$args = $cron[$time]['updraft_backup_resume'][$hook]['args'];
wp_unschedule_event($time, 'updraft_backup_resume', $args);
if (!$found_it) return array('ok' => 'Y', 'c' => 'deleted', 'm' => __('Job deleted', 'updraftplus'));
$found_it = true;
}
}
}
}
}
if (!$found_it) return array('ok' => 'N', 'c' => 'not_found', 'm' => __('Could not find that job - perhaps it has already finished?', 'updraftplus'));
}
// Input: an array of items
// Each item is in the format: <base>,<timestamp>,<type>(,<findex>)
// The 'base' is not for us: we just pass it straight back
public function get_download_statuses($downloaders) {
global $updraftplus;
$download_status = array();
foreach ($downloaders as $downloader) {
# prefix, timestamp, entity, index
if (preg_match('/^([^,]+),(\d+),([-a-z]+|db[0-9]+),(\d+)$/', $downloader, $matches)) {
$findex = (empty($matches[4])) ? '0' : $matches[4];
$updraftplus->nonce = dechex($matches[2]).$findex.substr(md5($matches[3]), 0, 3);
$updraftplus->jobdata_reset();
$status = $this->download_status($matches[2], $matches[3], $matches[4]);
if (is_array($status)) {
$status['base'] = $matches[1];
$status['timestamp'] = $matches[2];
$status['what'] = $matches[3];
$status['findex'] = $findex;
$download_status[] = $status;
}
}
}
return $download_status;
}
public function get_activejobs_list($request) {
global $updraftplus;
$download_status = empty($request['downloaders']) ? array(): $this->get_download_statuses(explode(':', $request['downloaders']));
if (!empty($request['oneshot'])) {
$job_id = get_site_option('updraft_oneshotnonce', false);
// print_active_job() for one-shot jobs that aren't in cron
$active_jobs = (false === $job_id) ? '' : $this->print_active_job($job_id, true);
} elseif (!empty($request['thisjobonly'])) {
// print_active_jobs() is for resumable jobs where we want the cron info to be included in the output
$active_jobs = $this->print_active_jobs($request['thisjobonly']);
} else {
$active_jobs = $this->print_active_jobs();
}
$logupdate_array = array();
if (!empty($request['log_fetch'])) {
if (isset($request['log_nonce'])) {
$log_nonce = $request['log_nonce'];
$log_pointer = isset($request['log_pointer']) ? absint($request['log_pointer']) : 0;
$logupdate_array = $this->fetch_log($log_nonce, $log_pointer);
}
}
return array(
// We allow the front-end to decide what to do if there's nothing logged - we used to (up to 1.11.29) send a pre-defined message
'l' => htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_lastmessage', '')),
'j' => $active_jobs,
'ds' => $download_status,
'u' => $logupdate_array
);
}
public function request_backupnow($request, $close_connection_callable = false) {
global $updraftplus;
$backupnow_nocloud = (empty($request['backupnow_nocloud'])) ? false : true;
$event = (!empty($request['backupnow_nofiles'])) ? 'updraft_backupnow_backup_database' : ((!empty($request['backupnow_nodb'])) ? 'updraft_backupnow_backup' : 'updraft_backupnow_backup_all');
// The call to backup_time_nonce() allows us to know the nonce in advance, and return it
$nonce = $updraftplus->backup_time_nonce();
$msg = array(
'nonce' => $nonce,
'm' => '<strong>'.__('Start backup', 'updraftplus').':</strong> '.htmlspecialchars(__('OK. You should soon see activity in the "Last log message" field below.','updraftplus'))
);
if ($close_connection_callable && is_callable($close_connection_callable)) {
call_user_func($close_connection_callable, $msg);
} else {
$updraftplus->close_browser_connection(json_encode($msg));
}
$options = array('nocloud' => $backupnow_nocloud, 'use_nonce' => $nonce);
if (!empty($request['onlythisfileentity']) && is_string($request['onlythisfileentity'])) {
// Something to see in the 'last log' field when it first appears, before the backup actually starts
$updraftplus->log(__('Start backup','updraftplus'));
$options['restrict_files_to_override'] = explode(',', $request['onlythisfileentity']);
}
if (!empty($request['extradata'])) {
$options['extradata'] = $request['extradata'];
}
do_action($event, apply_filters('updraft_backupnow_options', $options, $request));
}
public function fetch_log($backup_nonce, $log_pointer=0) {
global $updraftplus;
if (empty($backup_nonce)) {
list($mod_time, $log_file, $nonce) = $updraftplus->last_modified_log();
} else {
$nonce = $backup_nonce;
}
if (!preg_match('/^[0-9a-f]+$/', $nonce)) die('Security check');
$log_content = '';
$new_pointer = $log_pointer;
if (!empty($nonce)) {
$updraft_dir = $updraftplus->backups_dir_location();
$potential_log_file = $updraft_dir."/log.".$nonce.".txt";
if (is_readable($potential_log_file)){
$templog_array = array();
$log_file = fopen($potential_log_file, "r");
if ($log_pointer > 0) fseek($log_file, $log_pointer);
while (($buffer = fgets($log_file, 4096)) !== false) {
$templog_array[] = $buffer;
}
if (!feof($log_file)) {
$templog_array[] = __('Error: unexpected file read fail', 'updraftplus');
}
$new_pointer = ftell($log_file);
$log_content = implode("", $templog_array);
} else {
$log_content .= __('The log file could not be read.','updraftplus');
}
} else {
$log_content .= __('The log file could not be read.','updraftplus');
}
$ret_array = array(
'html' => $log_content,
'nonce' => $nonce,
'pointer' => $new_pointer
);
return $ret_array;
}
public function howmany_overdue_crons() {
$how_many_overdue = 0;
if (function_exists('_get_cron_array') || (is_file(ABSPATH.WPINC.'/cron.php') && include_once(ABSPATH.WPINC.'/cron.php') && function_exists('_get_cron_array'))) {
$crons = _get_cron_array();
if (is_array($crons)) {
$timenow = time();
foreach ($crons as $jt => $job) {
if ($jt < $timenow) {
$how_many_overdue++;
}
}
}
}
return $how_many_overdue;
}
public function get_php_errors($errno, $errstr, $errfile, $errline) {
global $updraftplus;
if (0 == error_reporting()) return true;
$logline = $updraftplus->php_error_to_logline($errno, $errstr, $errfile, $errline);
if (false !== $logline) $this->logged[] = $logline;
# Don't pass it up the chain (since it's going to be output to the user always)
return true;
}
private function download_status($timestamp, $type, $findex) {
global $updraftplus;
$response = array( 'm' => $updraftplus->jobdata_get('dlmessage_'.$timestamp.'_'.$type.'_'.$findex).'<br>' );
if ($file = $updraftplus->jobdata_get('dlfile_'.$timestamp.'_'.$type.'_'.$findex)) {
if ('failed' == $file) {
$response['e'] = __('Download failed', 'updraftplus').'<br>';
$response['failed'] = true;
$errs = $updraftplus->jobdata_get('dlerrors_'.$timestamp.'_'.$type.'_'.$findex);
if (is_array($errs) && !empty($errs)) {
$response['e'] .= '<ul class="disc">';
foreach ($errs as $err) {
if (is_array($err)) {
$response['e'] .= '<li>'.htmlspecialchars($err['message']).'</li>';
} else {
$response['e'] .= '<li>'.htmlspecialchars($err).'</li>';
}
}
$response['e'] .= '</ul>';
}
} elseif (preg_match('/^downloaded:(\d+):(.*)$/', $file, $matches) && file_exists($matches[2])) {
$response['p'] = 100;
$response['f'] = $matches[2];
$response['s'] = (int)$matches[1];
$response['t'] = (int)$matches[1];
$response['m'] = __('File ready.', 'updraftplus');
} elseif (preg_match('/^downloading:(\d+):(.*)$/', $file, $matches) && file_exists($matches[2])) {
// Convert to bytes
$response['f'] = $matches[2];
$total_size = (int)max($matches[1], 1);
$cur_size = filesize($matches[2]);
$response['s'] = $cur_size;
$file_age = time() - filemtime($matches[2]);
if ($file_age > 20) $response['a'] = time() - filemtime($matches[2]);
$response['t'] = $total_size;
$response['m'] .= __("Download in progress", 'updraftplus').' ('.round($cur_size/1024).' / '.round(($total_size/1024)).' KB)';
$response['p'] = round(100*$cur_size/$total_size);
} else {
$response['m'] .= __('No local copy present.', 'updraftplus');
$response['p'] = 0;
$response['s'] = 0;
$response['t'] = 1;
}
}
return $response;
}
public function upload_dir($uploads) {
global $updraftplus;
$updraft_dir = $updraftplus->backups_dir_location();
if (is_writable($updraft_dir)) $uploads['path'] = $updraft_dir;
return $uploads;
}
// We do actually want to over-write
public function unique_filename_callback($dir, $name, $ext) {
return $name.$ext;
}
public function sanitize_file_name($filename) {
// WordPress 3.4.2 on multisite (at least) adds in an unwanted underscore
return preg_replace('/-db(.*)\.gz_\.crypt$/', '-db$1.gz.crypt', $filename);
}
public function plupload_action() {
// check ajax nonce
global $updraftplus;
@set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);
if (!UpdraftPlus_Options::user_can_manage()) exit;
check_ajax_referer('updraft-uploader');
$updraft_dir = $updraftplus->backups_dir_location();
if (!@$updraftplus->really_is_writable($updraft_dir)) {
echo json_encode(array('e' => sprintf(__("Backup directory (%s) is not writable, or does not exist.", 'updraftplus'), $updraft_dir).' '.__('You will find more information about this in the Settings section.', 'updraftplus')));
exit;
}
add_filter('upload_dir', array($this, 'upload_dir'));
add_filter('sanitize_file_name', array($this, 'sanitize_file_name'));
// handle file upload
$farray = array('test_form' => true, 'action' => 'plupload_action');
$farray['test_type'] = false;
$farray['ext'] = 'x-gzip';
$farray['type'] = 'application/octet-stream';
if (!isset($_POST['chunks'])) {
$farray['unique_filename_callback'] = array($this, 'unique_filename_callback');
}
$status = wp_handle_upload(
$_FILES['async-upload'],
$farray
);
remove_filter('upload_dir', array($this, 'upload_dir'));
remove_filter('sanitize_file_name', array($this, 'sanitize_file_name'));
if (isset($status['error'])) {
echo json_encode(array('e' => $status['error']));
exit;
}
// If this was the chunk, then we should instead be concatenating onto the final file
if (isset($_POST['chunks']) && isset($_POST['chunk']) && preg_match('/^[0-9]+$/',$_POST['chunk'])) {
$final_file = basename($_POST['name']);
if (!rename($status['file'], $updraft_dir.'/'.$final_file.'.'.$_POST['chunk'].'.zip.tmp')) {
@unlink($status['file']);
echo json_encode(array('e' => sprintf(__('Error: %s', 'updraftplus'), __('This file could not be uploaded', 'updraftplus'))));
exit;
}
$status['file'] = $updraft_dir.'/'.$final_file.'.'.$_POST['chunk'].'.zip.tmp';
// Final chunk? If so, then stich it all back together
if ($_POST['chunk'] == $_POST['chunks']-1) {
if ($wh = fopen($updraft_dir.'/'.$final_file, 'wb')) {
for ($i=0 ; $i<$_POST['chunks']; $i++) {
$rf = $updraft_dir.'/'.$final_file.'.'.$i.'.zip.tmp';
if ($rh = fopen($rf, 'rb')) {
while ($line = fread($rh, 32768)) fwrite($wh, $line);
fclose($rh);
@unlink($rf);
}
}
fclose($wh);
$status['file'] = $updraft_dir.'/'.$final_file;
if ('.tar' == substr($final_file, -4, 4)) {
if (file_exists($status['file'].'.gz')) unlink($status['file'].'.gz');
if (file_exists($status['file'].'.bz2')) unlink($status['file'].'.bz2');
} elseif ('.tar.gz' == substr($final_file, -7, 7)) {
if (file_exists(substr($status['file'], 0, strlen($status['file'])-3))) unlink(substr($status['file'], 0, strlen($status['file'])-3));
if (file_exists(substr($status['file'], 0, strlen($status['file'])-3).'.bz2')) unlink(substr($status['file'], 0, strlen($status['file'])-3).'.bz2');
} elseif ('.tar.bz2' == substr($final_file, -8, 8)) {
if (file_exists(substr($status['file'], 0, strlen($status['file'])-4))) unlink(substr($status['file'], 0, strlen($status['file'])-4));
if (file_exists(substr($status['file'], 0, strlen($status['file'])-4).'.gz')) unlink(substr($status['file'], 0, strlen($status['file'])-3).'.gz');
}
}
}
}
$response = array();
if (!isset($_POST['chunks']) || (isset($_POST['chunk']) && $_POST['chunk'] == $_POST['chunks']-1)) {
$file = basename($status['file']);
if (!preg_match('/^log\.[a-f0-9]{12}\.txt/i', $file) && !preg_match('/^backup_([\-0-9]{15})_.*_([0-9a-f]{12})-([\-a-z]+)([0-9]+)?(\.(zip|gz|gz\.crypt))?$/i', $file, $matches)) {
$accept = apply_filters('updraftplus_accept_archivename', array());
if (is_array($accept)) {
foreach ($accept as $acc) {
if (preg_match('/'.$acc['pattern'].'/i', $file)) $accepted = $acc['desc'];
}
}
if (!empty($accepted)) {
$response['dm'] = sprintf(__('This backup was created by %s, and can be imported.', 'updraftplus'), $accepted);
} else {
@unlink($status['file']);
echo json_encode(array('e' => sprintf(__('Error: %s', 'updraftplus'),__('Bad filename format - this does not look like a file created by UpdraftPlus','updraftplus'))));
exit;
}
} else {
$backupable_entities = $updraftplus->get_backupable_file_entities(true);
$type = isset($matches[3]) ? $matches[3] : '';
if (!preg_match('/^log\.[a-f0-9]{12}\.txt/', $file) && 'db' != $type && !isset($backupable_entities[$type])) {
@unlink($status['file']);
echo json_encode(array('e' => sprintf(__('Error: %s', 'updraftplus'),sprintf(__('This looks like a file created by UpdraftPlus, but this install does not know about this type of object: %s. Perhaps you need to install an add-on?','updraftplus'), htmlspecialchars($type)))));
exit;
}
}
}
// send the uploaded file url in response
$response['m'] = $status['url'];
echo json_encode($response);
exit;
}
# Database decrypter
public function plupload_action2() {
@set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);
global $updraftplus;
if (!UpdraftPlus_Options::user_can_manage()) exit;
check_ajax_referer('updraft-uploader');
$updraft_dir = $updraftplus->backups_dir_location();
if (!is_writable($updraft_dir)) exit;
add_filter('upload_dir', array($this, 'upload_dir'));
add_filter('sanitize_file_name', array($this, 'sanitize_file_name'));
// handle file upload
$farray = array( 'test_form' => true, 'action' => 'plupload_action2' );
$farray['test_type'] = false;
$farray['ext'] = 'crypt';
$farray['type'] = 'application/octet-stream';
if (isset($_POST['chunks'])) {
// $farray['ext'] = 'zip';
// $farray['type'] = 'application/zip';
} else {
$farray['unique_filename_callback'] = array($this, 'unique_filename_callback');
}
$status = wp_handle_upload(
$_FILES['async-upload'],
$farray
);
remove_filter('upload_dir', array($this, 'upload_dir'));
remove_filter('sanitize_file_name', array($this, 'sanitize_file_name'));
if (isset($status['error'])) {
echo 'ERROR:'.$status['error'];
exit;
}
// If this was the chunk, then we should instead be concatenating onto the final file
if (isset($_POST['chunks']) && isset($_POST['chunk']) && preg_match('/^[0-9]+$/',$_POST['chunk'])) {
$final_file = basename($_POST['name']);
rename($status['file'], $updraft_dir.'/'.$final_file.'.'.$_POST['chunk'].'.zip.tmp');
$status['file'] = $updraft_dir.'/'.$final_file.'.'.$_POST['chunk'].'.zip.tmp';
// Final chunk? If so, then stich it all back together
if ($_POST['chunk'] == $_POST['chunks']-1) {
if ($wh = fopen($updraft_dir.'/'.$final_file, 'wb')) {
for ($i=0 ; $i<$_POST['chunks']; $i++) {
$rf = $updraft_dir.'/'.$final_file.'.'.$i.'.zip.tmp';
if ($rh = fopen($rf, 'rb')) {
while ($line = fread($rh, 32768)) fwrite($wh, $line);
fclose($rh);
@unlink($rf);
}
}
fclose($wh);
$status['file'] = $updraft_dir.'/'.$final_file;
}
}
}
if (!isset($_POST['chunks']) || (isset($_POST['chunk']) && $_POST['chunk'] == $_POST['chunks']-1)) {
$file = basename($status['file']);
if (!preg_match('/^backup_([\-0-9]{15})_.*_([0-9a-f]{12})-db([0-9]+)?\.(gz\.crypt)$/i', $file)) {
@unlink($status['file']);
echo 'ERROR:'.__('Bad filename format - this does not look like an encrypted database file created by UpdraftPlus','updraftplus');
exit;
}
}
// send the uploaded file url in response
// echo 'OK:'.$status['url'];
echo 'OK:'.$file;
exit;
}
public function settings_header() {
global $updraftplus;
?>
<div class="wrap" id="updraft-wrap">
<h1><?php echo $updraftplus->plugin_title; ?></h1>
<a href="https://updraftplus.com">UpdraftPlus.Com</a> |
<?php if (!defined('UPDRAFTPLUS_NOADS_B')) { ?><a href="https://updraftplus.com/shop/updraftplus-premium/"><?php _e("Premium",'updraftplus');?></a> | <?php } ?>
<a href="https://updraftplus.com/news/"><?php _e('News','updraftplus');?></a> |
<a href="https://twitter.com/updraftplus"><?php _e('Twitter', 'updraftplus');?></a> |
<a href="https://updraftplus.com/support/"><?php _e("Support",'updraftplus');?></a> |
<?php if (!is_file(UPDRAFTPLUS_DIR.'/udaddons/updraftplus-addons.php')) { ?><a href="https://updraftplus.com/newsletter-signup"><?php _e("Newsletter sign-up", 'updraftplus');?></a> | <?php } ?>
<a href="http://david.dw-perspective.org.uk"><?php _e("Lead developer's homepage",'updraftplus');?></a> |
<a href="https://updraftplus.com/support/frequently-asked-questions/"><?php _e('FAQs', 'updraftplus'); ?></a> | <a href="https://www.simbahosting.co.uk/s3/shop/"><?php _e('More plugins', 'updraftplus');?></a> - <?php _e('Version','updraftplus');?>: <?php echo $updraftplus->version; ?>
<br>
<?php
}
public function settings_output() {
if (false == ($render = apply_filters('updraftplus_settings_page_render', true))) {
do_action('updraftplus_settings_page_render_abort', $render);
return;
}
do_action('updraftplus_settings_page_init');
global $updraftplus;
/*
we use request here because the initial restore is triggered by a POSTed form. we then may need to obtain credentials
for the WP_Filesystem. to do this WP outputs a form, but we don't pass our parameters via that. So the values are
passed back in as GET parameters.
*/
if (isset($_REQUEST['action']) && (($_REQUEST['action'] == 'updraft_restore' && isset($_REQUEST['backup_timestamp'])) || ('updraft_restore_continue' == $_REQUEST['action'] && !empty($_REQUEST['restoreid'])))) {
$is_continuation = ('updraft_restore_continue' == $_REQUEST['action']) ? true : false;
if ($is_continuation) {
$restore_in_progress = get_site_option('updraft_restore_in_progress');
if ($restore_in_progress != $_REQUEST['restoreid']) {
$abort_restore_already = true;
$updraftplus->log(__('Sufficient information about the in-progress restoration operation could not be found.', 'updraftplus').' (restoreid_mismatch)', 'error', 'restoreid_mismatch');
} else {
$restore_jobdata = $updraftplus->jobdata_getarray($restore_in_progress);
if (is_array($restore_jobdata) && isset($restore_jobdata['job_type']) && 'restore' == $restore_jobdata['job_type'] && isset($restore_jobdata['second_loop_entities']) && !empty($restore_jobdata['second_loop_entities']) && isset($restore_jobdata['job_time_ms']) && isset($restore_jobdata['backup_timestamp'])) {
$backup_timestamp = $restore_jobdata['backup_timestamp'];
$continuation_data = $restore_jobdata;
} else {
$abort_restore_already = true;
$updraftplus->log(__('Sufficient information about the in-progress restoration operation could not be found.', 'updraftplus').' (restoreid_nojobdata)', 'error', 'restoreid_nojobdata');
}
}
} else {
$backup_timestamp = $_REQUEST['backup_timestamp'];
$continuation_data = null;
}
if (empty($abort_restore_already)) {
$backup_success = $this->restore_backup($backup_timestamp, $continuation_data);
} else {
$backup_success = false;
}
if (empty($updraftplus->errors) && $backup_success === true) {
// TODO: Deal with the case of some of the work having been deferred
// If we restored the database, then that will have out-of-date information which may confuse the user - so automatically re-scan for them.
$updraftplus->rebuild_backup_history();
echo '<p><strong>';
$updraftplus->log_e('Restore successful!');
echo '</strong></p>';
$updraftplus->log("Restore successful");
$s_val = 1;
if (!empty($this->entities_to_restore) && is_array($this->entities_to_restore)) {
foreach ($this->entities_to_restore as $k => $v) {
if ('db' != $v) $s_val = 2;
}
}
$pval = ($updraftplus->have_addons) ? 1 : 0;
echo '<strong>'.__('Actions','updraftplus').':</strong> <a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&updraft_restore_success='.$s_val.'&pval='.$pval.'">'.__('Return to UpdraftPlus Configuration','updraftplus').'</a>';
return;
} elseif (is_wp_error($backup_success)) {
echo '<p>';
$updraftplus->log_e('Restore failed...');
echo '</p>';
$updraftplus->log_wp_error($backup_success);
$updraftplus->log("Restore failed");
$updraftplus->list_errors();
echo '<strong>'.__('Actions','updraftplus').':</strong> <a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus">'.__('Return to UpdraftPlus Configuration','updraftplus').'</a>';
return;
} elseif (false === $backup_success) {
# This means, "not yet - but stay on the page because we may be able to do it later, e.g. if the user types in the requested information"
echo '<p>';
$updraftplus->log_e('Restore failed...');
echo '</p>';
$updraftplus->log("Restore failed");
$updraftplus->list_errors();
echo '<strong>'.__('Actions','updraftplus').':</strong> <a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus">'.__('Return to UpdraftPlus Configuration','updraftplus').'</a>';
return;
}
}
if (isset($_REQUEST['action']) && 'updraft_delete_old_dirs' == $_REQUEST['action']) {
$nonce = (empty($_REQUEST['_wpnonce'])) ? "" : $_REQUEST['_wpnonce'];
if (!wp_verify_nonce($nonce, 'updraftplus-credentialtest-nonce')) die('Security check');
$this->delete_old_dirs_go();
return;
}
if (!empty($_REQUEST['action']) && 'updraftplus_broadcastaction' == $_REQUEST['action'] && !empty($_REQUEST['subaction'])) {
$nonce = (empty($_REQUEST['nonce'])) ? "" : $_REQUEST['nonce'];
if (!wp_verify_nonce($nonce, 'updraftplus-credentialtest-nonce')) die('Security check');
do_action($_REQUEST['subaction']);
return;
}
if (isset($_GET['error'])) {
// This is used by Microsoft OneDrive authorisation failures (May 15). I am not sure what may have been using the 'error' GET parameter otherwise - but it is harmless.
if (!empty($_GET['error_description'])) {
$this->show_admin_warning(htmlspecialchars($_GET['error_description']).' ('.htmlspecialchars($_GET['error']).')', 'error');
} else {
$this->show_admin_warning(htmlspecialchars($_GET['error']), 'error');
}
}
if (isset($_GET['message'])) $this->show_admin_warning(htmlspecialchars($_GET['message']));
if (isset($_GET['action']) && $_GET['action'] == 'updraft_create_backup_dir' && isset($_GET['nonce']) && wp_verify_nonce($_GET['nonce'], 'create_backup_dir')) {
$created = $this->create_backup_dir();
if (is_wp_error($created)) {
echo '<p>'.__('Backup directory could not be created', 'updraftplus').'...<br/>';
echo '<ul class="disc">';
foreach ($created->get_error_messages() as $key => $msg) {
echo '<li>'.htmlspecialchars($msg).'</li>';
}
echo '</ul></p>';
} elseif ($created !== false) {
echo '<p>'.__('Backup directory successfully created.', 'updraftplus').'</p><br/>';
}
echo '<b>'.__('Actions','updraftplus').':</b> <a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus">'.__('Return to UpdraftPlus Configuration', 'updraftplus').'</a>';
return;
}
echo '<div id="updraft_backup_started" class="updated updraft-hidden" style="display:none;"></div>';
if (isset($_POST['action']) && 'updraft_backup_debug_all' == $_POST['action']) {
$updraftplus->boot_backup(true,true);
} elseif (isset($_POST['action']) && 'updraft_backup_debug_db' == $_POST['action']) {
$updraftplus->boot_backup(false, true, false, true);
} elseif (isset($_POST['action']) && 'updraft_wipesettings' == $_POST['action']) {
$settings = $updraftplus->get_settings_keys();
foreach ($settings as $s) UpdraftPlus_Options::delete_updraft_option($s);
// These aren't in get_settings_keys() because they are always in the options table, regardless of context
global $wpdb;
$wpdb->query("DELETE FROM $wpdb->options WHERE ( option_name LIKE 'updraftplus_unlocked_%' OR option_name LIKE 'updraftplus_locked_%' OR option_name LIKE 'updraftplus_last_lock_time_%' OR option_name LIKE 'updraftplus_semaphore_%' OR option_name LIKE 'updraft_jobdata_%' OR option_name LIKE 'updraft_last_scheduled_%' )");
$site_options = array('updraft_oneshotnonce');
foreach ($site_options as $s) delete_site_option($s);
$this->show_admin_warning(__("Your settings have been wiped.", 'updraftplus'));
}
// This opens a div
$this->settings_header();
?>
<div id="updraft-hidethis">
<p>
<strong><?php _e('Warning:', 'updraftplus'); ?> <?php _e("If you can still read these words after the page finishes loading, then there is a JavaScript or jQuery problem in the site.", 'updraftplus'); ?></strong>
<?php if (false !== strpos(basename(UPDRAFTPLUS_URL), ' ')) { ?>
<strong><?php _e('The UpdraftPlus directory in wp-content/plugins has white-space in it; WordPress does not like this. You should rename the directory to wp-content/plugins/updraftplus to fix this problem.', 'updraftplus');?></strong>
<?php } else { ?>
<a href="https://updraftplus.com/do-you-have-a-javascript-or-jquery-error/"><?php _e('Go here for more information.', 'updraftplus'); ?></a>
<?php } ?>
</p>
</div>
<?php
$include_deleteform_div = true;
// Opens a div, which needs closing later
if (isset($_GET['updraft_restore_success'])) {
$success_advert = (isset($_GET['pval']) && 0 == $_GET['pval'] && !$updraftplus->have_addons) ? '<p>'.__('For even more features and personal support, check out ','updraftplus').'<strong><a href="https://updraftplus.com/shop/updraftplus-premium/" target="_blank">UpdraftPlus Premium</a>.</strong></p>' : "";
echo "<div class=\"updated backup-restored\"><span><strong>".__('Your backup has been restored.','updraftplus').'</strong></span><br>';
// Unnecessary - will be advised of this below
// if (2 == $_GET['updraft_restore_success']) echo ' '.__('Your old (themes, uploads, plugins, whatever) directories have been retained with "-old" appended to their name. Remove them when you are satisfied that the backup worked properly.');
echo $success_advert;
$include_deleteform_div = false;
}
// $this->print_restore_in_progress_box_if_needed();
if ($this->scan_old_dirs(true)) $this->print_delete_old_dirs_form(true, $include_deleteform_div);
// Close the div opened by the earlier section
if (isset($_GET['updraft_restore_success'])) echo '</div>';
$ws_advert = $updraftplus->wordshell_random_advert(1);
if ($ws_advert && empty($success_advert) && empty($this->no_settings_warning)) { echo '<div class="updated ws_advert" style="clear:left;">'.$ws_advert.'</div>'; }
if (!$updraftplus->memory_check(64)) {?>
<div class="updated memory-limit"><?php _e("Your PHP memory limit (set by your web hosting company) is very low. UpdraftPlus attempted to raise it but was unsuccessful. This plugin may struggle with a memory limit of less than 64 Mb - especially if you have very large files uploaded (though on the other hand, many sites will be successful with a 32Mb limit - your experience may vary).",'updraftplus');?> <?php _e('Current limit is:','updraftplus');?> <?php echo $updraftplus->memory_check_current(); ?> MB</div>
<?php
}
if (!empty($updraftplus->errors)) {
echo '<div class="error updraft_list_errors">';
$updraftplus->list_errors();
echo '</div>';
}
$backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history');
if (empty($backup_history)) {
$updraftplus->rebuild_backup_history();
$backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history');
}
$backup_history = is_array($backup_history) ? $backup_history : array();
?>
<h2 class="nav-tab-wrapper">
<?php
$tabflag = 1;
if (isset($_REQUEST['tab'])){
switch($_REQUEST['tab']) {
case 'status': $tabflag = 1; break;
case 'backups': $tabflag = 2; break;
case 'settings': $tabflag = 3; break;
case 'expert': $tabflag = 4; break;
case 'addons': $tabflag = 5; break;
default : $tabflag = 1;
}
}
?>
<a class="nav-tab <?php if (1 == $tabflag) echo 'nav-tab-active'; ?>" id="updraft-navtab-status" href="#updraft-navtab-status-content" ><?php _e('Current Status', 'updraftplus');?> </span></a>
<a class="nav-tab <?php if (2 == $tabflag) echo 'nav-tab-active'; ?>" id="updraft-navtab-backups" href="#updraft-navtab-backups-contents" ><?php echo __('Existing Backups', 'updraftplus').' ('.count($backup_history).')';?> </span></a>
<a class="nav-tab <?php if (3 == $tabflag) echo 'nav-tab-active'; ?>" id="updraft-navtab-settings" href="#updraft-navtab-settings-content"><?php _e('Settings', 'updraftplus');?> </span></a>
<a class="nav-tab<?php if (4 == $tabflag) echo ' nav-tab-active'; ?>" id="updraft-navtab-expert" href="#updraft-navtab-expert-content"><?php _e('Advanced Tools', 'updraftplus');?> </span></a>
<a class="nav-tab<?php if (5 == $tabflag) echo ' nav-tab-active'; ?>" id="updraft-navtab-addons" href="#updraft-navtab-addons-content"><?php _e('Premium / Extensions', 'updraftplus');?> </span></a>
<?php //do_action('updraftplus_settings_afternavtabs'); ?>
</h2>
<?php
$updraft_dir = $updraftplus->backups_dir_location();
$backup_disabled = ($updraftplus->really_is_writable($updraft_dir)) ? '' : 'disabled="disabled"';
?>
<div id="updraft-poplog" >
<pre id="updraft-poplog-content"></pre>
</div>
<div id="updraft-navtab-status-content" class="<?php if (1 != $tabflag) echo 'updraft-hidden'; ?>" style="<?php if (1 != $tabflag) echo 'display:none;'; ?>">
<div id="updraft-insert-admin-warning"></div>
<table class="form-table" style="float:left; clear:both;">
<noscript>
<tr>
<th><?php _e('JavaScript warning','updraftplus');?>:</th>
<td style="color:red"><?php _e('This admin interface uses JavaScript heavily. You either need to activate it within your browser, or to use a JavaScript-capable browser.','updraftplus');?></td>
</tr>
</noscript>
<tr>
<th></th>
<td>
<?php
if ($backup_disabled) {
$unwritable_mess = htmlspecialchars(__("The 'Backup Now' button is disabled as your backup directory is not writable (go to the 'Settings' tab and find the relevant option).", 'updraftplus'));
$this->show_admin_warning($unwritable_mess, "error");
}
?>
<button id="updraft-backupnow-button" type="button" <?php echo $backup_disabled ?> class="updraft-bigbutton button-primary" <?php if ($backup_disabled) echo 'title="'.esc_attr(__('This button is disabled because your backup directory is not writable (see the settings).', 'updraftplus')).'" ';?> onclick="updraft_backup_dialog_open();"><?php _e('Backup Now', 'updraftplus');?></button>
<button type="button" class="updraft-bigbutton button-primary" onclick="updraft_openrestorepanel();">
<?php _e('Restore','updraftplus');?>
</button>
<button type="button" class="updraft-bigbutton button-primary" onclick="updraft_migrate_dialog_open();"><?php _e('Clone/Migrate','updraftplus');?></button>
</td>
</tr>
<?php
$last_backup_html = $this->last_backup_html();
$current_time = get_date_from_gmt(gmdate('Y-m-d H:i:s'), 'D, F j, Y H:i');
// $current_time = date_i18n('D, F j, Y H:i');
?>
<script>var lastbackup_laststatus = '<?php echo esc_js($last_backup_html);?>';</script>
<tr>
<th><span title="<?php esc_attr_e("All the times shown in this section are using WordPress's configured time zone, which you can set in Settings -> General", 'updraftplus'); ?>"><?php _e('Next scheduled backups', 'updraftplus');?>:<br>
<span style="font-weight:normal;"><em><?php _e('Now', 'updraftplus');?>: <?php echo $current_time; ?></span></span></em></th>
<td>
<table id="next-backup-table-inner" class="next-backup">
<?php $this->next_scheduled_backups_output(); ?>
</table>
</td>
</tr>
<tr>
<th><?php _e('Last backup job run:','updraftplus');?></th>
<td id="updraft_last_backup"><?php echo $last_backup_html ?></td>
</tr>
</table>
<br style="clear:both;" />
<?php $this->render_active_jobs_and_log_table(); ?>
<div id="updraft-migrate-modal" title="<?php _e('Migrate Site', 'updraftplus'); ?>" style="display:none;">
<?php
if (class_exists('UpdraftPlus_Addons_Migrator')) {
do_action('updraftplus_migrate_modal_output');
} else {
echo '<p id="updraft_migrate_modal_main">'.__('Do you want to migrate or clone/duplicate a site?', 'updraftplus').'</p><p>'.__('Then, try out our "Migrator" add-on. After using it once, you\'ll have saved the purchase price compared to the time needed to copy a site by hand.', 'updraftplus').'</p><p><a href="https://updraftplus.com/landing/migrator">'.__('Get it here.', 'updraftplus').'</a></p>';
}
?>
</div>
<div id="updraft-iframe-modal">
<div id="updraft-iframe-modal-innards">
</div>
</div>
<div id="updraft-backupnow-modal" title="UpdraftPlus - <?php _e('Perform a one-time backup', 'updraftplus'); ?>">
<!-- <p>
<?php _e("To proceed, press 'Backup Now'. Then, watch the 'Last Log Message' field for activity.", 'updraftplus');?>
</p>-->
<?php echo $this->backupnow_modal_contents(); ?>
</div>
<?php
if (is_multisite() && !file_exists(UPDRAFTPLUS_DIR.'/addons/multisite.php')) {
?>
<h2>UpdraftPlus <?php _e('Multisite','updraftplus');?></h2>
<table>
<tr>
<td>
<p class="multisite-advert-width"><?php echo __('Do you need WordPress Multisite support?','updraftplus').' <a href="https://updraftplus.com/shop/updraftplus-premium/">'. __('Please check out UpdraftPlus Premium, or the stand-alone Multisite add-on.','updraftplus');?></a>.</p>
</td>
</tr>
</table>
<?php } ?>
</div>
<div id="updraft-navtab-backups-content" <?php if (2 != $tabflag) echo 'class="updraft-hidden"'; ?> style="<?php if (2 != $tabflag) echo 'display:none;'; ?>">
<?php
$is_opera = (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') || false !== strpos($_SERVER['HTTP_USER_AGENT'], 'OPR/'));
$tmp_opts = array('include_opera_warning' => $is_opera);
$this->settings_downloading_and_restoring($backup_history, false, $tmp_opts);
$this->settings_delete_and_restore_modals();
?>
</div>
<div id="updraft-navtab-settings-content" <?php if (3 != $tabflag) echo 'class="updraft-hidden"'; ?> style="<?php if (3 != $tabflag) echo 'display:none;'; ?>">
<h2 class="updraft_settings_sectionheading"><?php _e('Backup Contents And Schedule','updraftplus');?></h2>
<?php UpdraftPlus_Options::options_form_begin(); ?>
<?php $this->settings_formcontents(); ?>
</form>
</div>
<div id="updraft-navtab-expert-content"<?php if (4 != $tabflag) echo ' class="updraft-hidden"'; ?> style="<?php if (4 != $tabflag) echo 'display:none;'; ?>">
<?php $this->settings_expertsettings($backup_disabled); ?>
</div>
<div id="updraft-navtab-addons-content"<?php if (5 != $tabflag) echo ' class="updraft-hidden"'; ?> style="<?php if (5 != $tabflag) echo 'display:none;'; ?>">
<?php
$tick = UPDRAFTPLUS_URL.'/images/updraft_tick.png';
$cross = UPDRAFTPLUS_URL.'/images/updraft_cross.png';
$freev = UPDRAFTPLUS_URL.'/images/updraft_freev.png';
$premv = UPDRAFTPLUS_URL.'/images/updraft_premv.png';
ob_start();
?>
<div>
<h2>UpdraftPlus Premium</h2>
<p>
<span class="premium-upgrade-prompt"><?php _e('You are currently using the free version of UpdraftPlus from wordpress.org.', 'updraftplus');?> <a href="https://updraftplus.com/support/installing-updraftplus-premium-your-add-on/"><br><?php echo __('If you have made a purchase from UpdraftPlus.Com, then follow this link to the instructions to install your purchase.', 'updraftplus').' '.__('The first step is to de-install the free version.', 'updraftplus')?></a></span>
<ul class="updraft_premium_description_list">
<li><a href="https://updraftplus.com/shop/updraftplus-premium/"><strong><?php _e('Get UpdraftPlus Premium', 'updraftplus');?></strong></a></li>
<li><a href="https://updraftplus.com/updraftplus-full-feature-list/"><?php _e('Full feature list', 'updraftplus');?></a></li>
<li><a href="https://updraftplus.com/faq-category/general-and-pre-sales-questions/"><?php _e('Pre-sales FAQs', 'updraftplus');?></a></li>
<li class="last"><a href="https://updraftplus.com/ask-a-pre-sales-question/"><?php _e('Ask a pre-sales question', 'updraftplus');?></a> - <a href="https://updraftplus.com/support/"><?php _e('Support', 'updraftplus');?></a></li>
</ul>
</p>
</div>
<div>
<table class="updraft_feat_table">
<tr>
<th class="updraft_feat_th" style="text-align:left;"></th>
<th class="updraft_feat_th"><img src="<?php echo $freev;?>" height="120"></th>
<th class="updraft_feat_th" style='background-color:#DF6926;'><a href="https://updraftplus.com/shop/updraftplus-premium/"><img src="<?php echo $premv;?>" height="120"></a></th>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Get it from', 'updraftplus');?></td>
<td class="updraft_tick_cell" style="vertical-align:top; line-height: 120%; margin-top:6px; padding-top:6px;">WordPress.Org</td>
<td class="updraft_tick_cell" style="padding: 6px; line-height: 120%;">
UpdraftPlus.Com<br>
<a href="https://updraftplus.com/shop/updraftplus-premium/"><strong><?php _e('Buy It Now!', 'updraftplus');?></strong></a><br>
</td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Backup WordPress files and database', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php echo sprintf(__('Translated into over %s languages', 'updraftplus'), 16);?></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Restore from backup', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Backup to remote storage', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Dropbox, Google Drive, FTP, S3, Rackspace, Email', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('WebDAV, Copy.Com, SFTP/SCP, encrypted FTP', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Microsoft OneDrive, Microsoft Azure, Google Cloud Storage', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Free 1GB for UpdraftPlus Vault', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Backup extra files and databases', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Migrate / clone (i.e. copy) websites', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Basic email reporting', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Advanced reporting features', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Automatic backup when updating WP/plugins/themes', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Send backups to multiple remote destinations', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Database encryption', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Restore backups from other plugins', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('No advertising links on UpdraftPlus settings page', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Scheduled backups', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Fix backup time', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Network/Multisite support', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Lock settings access', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
<tr>
<td class="updraft_feature_cell"><?php _e('Personal support', 'updraftplus');?></td>
<td class="updraft_tick_cell"><img src="<?php echo $cross;?>"></td>
<td class="updraft_tick_cell"><img src="<?php echo $tick;?>"></td>
</tr>
</table>
</div>
<?php
echo apply_filters('updraftplus_addonstab_content', ob_get_clean());
// Close addons tab
echo '</div>';
// settings_header() opens a div
echo '</div>';
}
private function print_restore_in_progress_box_if_needed() {
$restore_in_progress = get_site_option('updraft_restore_in_progress');
if (!empty($restore_in_progress)) {
global $updraftplus;
$restore_jobdata = $updraftplus->jobdata_getarray($restore_in_progress);
if (is_array($restore_jobdata) && !empty($restore_jobdata)) {
// Only print if within the last 24 hours; and only after 2 minutes
if (isset($restore_jobdata['job_type']) && 'restore' == $restore_jobdata['job_type'] && isset($restore_jobdata['second_loop_entities']) && !empty($restore_jobdata['second_loop_entities']) && isset($restore_jobdata['job_time_ms']) && (time() - $restore_jobdata['job_time_ms'] > 120 || (defined('UPDRAFTPLUS_RESTORE_PROGRESS_ALWAYS_SHOW') && UPDRAFTPLUS_RESTORE_PROGRESS_ALWAYS_SHOW)) && time() - $restore_jobdata['job_time_ms'] < 86400 && (empty($_REQUEST['action']) || ('updraft_restore' != $_REQUEST['action'] && 'updraft_restore_continue' != $_REQUEST['action']))) {
$restore_jobdata['jobid'] = $restore_in_progress;
$this->restore_in_progress_jobdata = $restore_jobdata;
add_action('all_admin_notices', array($this, 'show_admin_restore_in_progress_notice') );
}
}
}
}
public function show_admin_restore_in_progress_notice() {
if (isset($_REQUEST['action']) && 'updraft_restore_abort' == $_REQUEST['action'] && !empty($_REQUEST['restoreid'])) {
delete_site_option('updraft_restore_in_progress');
return;
}
$restore_jobdata = $this->restore_in_progress_jobdata;
$seconds_ago = time() - (int)$restore_jobdata['job_time_ms'];
$minutes_ago = floor($seconds_ago/60);
$seconds_ago = $seconds_ago - $minutes_ago*60;
$time_ago = sprintf(__("%s minutes, %s seconds", 'updraftplus'), $minutes_ago, $seconds_ago);
?><div class="updated show_admin_restore_in_progress_notice">
<span class="unfinished-restoration"><strong><?php echo 'UpdraftPlus: '.__('Unfinished restoration', 'updraftplus'); ?> </strong></span><br>
<p><?php printf(__('You have an unfinished restoration operation, begun %s ago.', 'updraftplus'), $time_ago);?></p>
<form method="post" action="<?php echo UpdraftPlus_Options::admin_page_url().'?page=updraftplus'; ?>">
<?php wp_nonce_field('updraftplus-credentialtest-nonce'); ?>
<input id="updraft_restore_continue_action" type="hidden" name="action" value="updraft_restore_continue">
<input type="hidden" name="restoreid" value="<?php echo $restore_jobdata['jobid'];?>" value="<?php echo esc_attr($restore_jobdata['jobid']);?>">
<button onclick="jQuery('#updraft_restore_continue_action').val('updraft_restore_continue'); jQuery(this).parent('form').submit();" type="submit" class="button-primary"><?php _e('Continue restoration', 'updraftplus'); ?></button>
<button onclick="jQuery('#updraft_restore_continue_action').val('updraft_restore_abort'); jQuery(this).parent('form').submit();" class="button-secondary"><?php _e('Dismiss', 'updraftplus');?></button>
</form><?php
echo "</div>";
}
public function backupnow_modal_contents() {
$ret = $this->backup_now_widgetry();
// $ret .= '<p>'.__('Does nothing happen when you attempt backups?','updraftplus').' <a href="https://updraftplus.com/faqs/my-scheduled-backups-and-pressing-backup-now-does-nothing-however-pressing-debug-backup-does-produce-a-backup/">'.__('Go here for help.', 'updraftplus').'</a></p>';
return $ret;
}
private function backup_now_widgetry() {
$ret = '';
$ret .= '<p>
<input type="checkbox" id="backupnow_includedb" checked="checked"> <label for="backupnow_includedb">'.__("Include the database in the backup", 'updraftplus').'</label><br>';
$ret .= '<input type="checkbox" id="backupnow_includefiles" checked="checked"> <label for="backupnow_includefiles">'.__("Include any files in the backup", 'updraftplus').'</label> (<a href="#" id="backupnow_includefiles_showmoreoptions">...</a>)<br>';
$ret .= '<div id="backupnow_includefiles_moreoptions" class="updraft-hidden" style="display:none;"><em>'.__('Your saved settings also affect what is backed up - e.g. files excluded.', 'updraftplus').'</em><br>'.$this->files_selector_widgetry('backupnow_files_', false, 'sometimes').'</div>';
$ret .= '<span id="backupnow_remote_container">'.$this->backup_now_remote_message().'</span>';
$ret .= '</p>';
$ret .= apply_filters('updraft_backupnow_modal_afteroptions', '', '');
return $ret;
}
// Also used by the auto-backups add-on
public function render_active_jobs_and_log_table($wide_format = false, $print_active_jobs = true) {
?>
<table class="form-table" id="updraft_activejobs_table">
<?php $active_jobs = ($print_active_jobs) ? $this->print_active_jobs() : '';?>
<tr id="updraft_activejobsrow" class="<?php
if (!$active_jobs && !$wide_format) { echo 'hidden'; }
if ($wide_format) { echo ".minimum-height"; }
?>">
<?php if ($wide_format) { ?>
<td id="updraft_activejobs" colspan="2">
<?php echo $active_jobs;?>
</td>
<?php } else { ?>
<th><?php _e('Backups in progress:', 'updraftplus');?></th>
<td id="updraft_activejobs"><?php echo $active_jobs;?></td>
<?php } ?>
</tr>
<tr id="updraft_lastlogmessagerow">
<?php if ($wide_format) {
// Hide for now - too ugly
?>
<td colspan="2" class="last-message"><strong><?php _e('Last log message','updraftplus');?>:</strong><br>
<span id="updraft_lastlogcontainer"><?php echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_lastmessage', __('(Nothing yet logged)','updraftplus'))); ?></span><br>
<?php $this->most_recently_modified_log_link(); ?>
</td>
<?php } else { ?>
<th><?php _e('Last log message','updraftplus');?>:</th>
<td>
<span id="updraft_lastlogcontainer"><?php echo htmlspecialchars(UpdraftPlus_Options::get_updraft_option('updraft_lastmessage', __('(Nothing yet logged)','updraftplus'))); ?></span><br>
<?php $this->most_recently_modified_log_link(); ?>
</td>
<?php } ?>
</tr>
<?php
# Currently disabled - not sure who we want to show this to
if (1==0 && !defined('UPDRAFTPLUS_NOADS_B')) {
$feed = $updraftplus->get_updraftplus_rssfeed();
if (is_a($feed, 'SimplePie')) {
echo '<tr><th style="vertical-align:top;">'.__('Latest UpdraftPlus.com news:', 'updraftplus').'</th><td class="updraft_simplepie">';
echo '<ul class="disc;">';
foreach ($feed->get_items(0, 5) as $item) {
echo '<li>';
echo '<a href="'.esc_attr($item->get_permalink()).'">';
echo htmlspecialchars($item->get_title());
# D, F j, Y H:i
echo "</a> (".htmlspecialchars($item->get_date('j F Y')).")";
echo '</li>';
}
echo '</ul></td></tr>';
}
}
?>
</table>
<?php
}
private function most_recently_modified_log_link() {
global $updraftplus;
list($mod_time, $log_file, $nonce) = $updraftplus->last_modified_log();
?>
<a href="?page=updraftplus&action=downloadlatestmodlog&wpnonce=<?php echo wp_create_nonce('updraftplus_download') ?>" <?php if (!$mod_time) echo 'style="display:none;"'; ?> class="updraft-log-link" onclick="event.preventDefault(); updraft_popuplog('');"><?php _e('Download most recently modified log file', 'updraftplus');?></a>
<?php
}
public function settings_downloading_and_restoring($backup_history = array(), $return_result = false, $options = array()) {
global $updraftplus;
if ($return_result) ob_start();
$default_options = array(
'include_uploader' => true,
'include_opera_warning' => false,
'will_immediately_calculate_disk_space' => true,
'include_whitespace_warning' => true,
'include_header' => false,
);
foreach ($default_options as $k => $v) {
if (!isset($options[$k])) $options[$k] = $v;
}
if (false === $backup_history) $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history');
if (!is_array($backup_history)) $backup_history=array();
if (!empty($options['include_header'])) echo '<h2>'.__('Existing Backups', 'updraftplus').' ('.count($backup_history).')</h2>';
?>
<div class="download-backups form-table">
<?php /* echo '<h2>'.__('Existing Backups: Downloading And Restoring', 'updraftplus').'</h2>'; */ ?>
<?php if (!empty($options['include_whitespace_warning'])) { ?>
<p class="ud-whitespace-warning updraft-hidden" style="display:none;">
<?php echo '<strong>'.__('Warning','updraftplus').':</strong> '.__('Your WordPress installation has a problem with outputting extra whitespace. This can corrupt backups that you download from here.','updraftplus').' <a href="https://updraftplus.com/problems-with-extra-white-space/">'.__('Please consult this FAQ for help on what to do about it.', 'updraftplus').'</a>';?>
</p>
<?php } ?>
<ul>
<li title="<?php esc_attr_e('This is a count of the contents of your Updraft directory', 'updraftplus');?>"><strong><?php _e('Web-server disk space in use by UpdraftPlus', 'updraftplus');?>:</strong> <span class="updraft_diskspaceused"><em><?php echo empty($options['will_immediately_calculate_disk_space']) ? '' : __('calculating...', 'updraftplus'); ?></em></span> <a class="updraft_diskspaceused_update" href="#"><?php echo empty($options['will_immediately_calculate_disk_space']) ? __('calculate', 'updraftplus') : __('refresh','updraftplus');?></a></li>
<li>
<strong><?php _e('More tasks:', 'updraftplus');?></strong>
<?php if (!empty($options['include_uploader'])) { ?><a class="updraft_uploader_toggle" href="#"><?php _e('Upload backup files', 'updraftplus');?></a> | <?php } ?>
<a href="#" class="updraft_rescan_local" title="<?php echo __('Press here to look inside your UpdraftPlus directory (in your web hosting space) for any new backup sets that you have uploaded.', 'updraftplus').' '.__('The location of this directory is set in the expert settings, in the Settings tab.', 'updraftplus'); ?>"><?php _e('Rescan local folder for new backup sets', 'updraftplus');?></a>
| <a href="#" class="updraft_rescan_remote" title="<?php _e('Press here to look inside your remote storage methods for any existing backup sets (from any site, if they are stored in the same folder).', 'updraftplus'); ?>"><?php _e('Rescan remote storage','updraftplus');?></a>
</li>
<?php if (!empty($options['include_opera_warning'])) { ?>
<li><strong><?php _e('Opera web browser', 'updraftplus');?>:</strong> <?php _e('If you are using this, then turn Turbo/Road mode off.', 'updraftplus');?></li>
<?php } ?>
</ul>
<?php if (!empty($options['include_uploader'])) { ?>
<div id="updraft-plupload-modal" style="display:none;" title="<?php _e('UpdraftPlus - Upload backup files','updraftplus'); ?>">
<p class="upload"><em><?php _e("Upload files into UpdraftPlus." ,'updraftplus');?> <?php echo htmlspecialchars(__('Or, you can place them manually into your UpdraftPlus directory (usually wp-content/updraft), e.g. via FTP, and then use the "rescan" link above.', 'updraftplus'));?></em></p>
<?php
global $wp_version;
if (version_compare($wp_version, '3.3', '<')) {
echo '<em>'.sprintf(__('This feature requires %s version %s or later', 'updraftplus'), 'WordPress', '3.3').'</em>';
} else {
?>
<div id="plupload-upload-ui">
<div id="drag-drop-area">
<div class="drag-drop-inside">
<p class="drag-drop-info"><?php _e('Drop backup files here', 'updraftplus'); ?></p>
<p><?php _ex('or', 'Uploader: Drop backup files here - or - Select Files'); ?></p>
<p class="drag-drop-buttons"><input id="plupload-browse-button" type="button" value="<?php esc_attr_e('Select Files'); ?>" class="button" /></p>
</div>
</div>
<div id="filelist">
</div>
</div>
<?php
}
?>
</div>
<?php } ?>
<div class="ud_downloadstatus"></div>
<div class="updraft_existing_backups">
<?php echo $this->existing_backup_table($backup_history); ?>
</div>
</div>
<?php
if ($return_result) return ob_get_clean();
}
public function settings_delete_and_restore_modals($return_result = false) {
global $updraftplus;
if ($return_result) ob_start();
?>
<div id="ud_massactions" class="updraft-hidden" style="display:none;">
<strong><?php _e('Actions upon selected backups', 'updraftplus');?></strong> <br>
<div class="updraftplus-remove" style="float: left;"><a href="#" onclick="updraft_deleteallselected(); return false;"><?php _e('Delete', 'updraftplus');?></a></div>
<div class="updraft-viewlogdiv"><a href="#" onclick="jQuery('#updraft-navtab-backups-content .updraft_existing_backups .updraft_existing_backups_row').addClass('backuprowselected'); return false;"><?php _e('Select all', 'updraftplus');?></a></div>
<div class="updraft-viewlogdiv"><a href="#" onclick="jQuery('#updraft-navtab-backups-content .updraft_existing_backups .updraft_existing_backups_row').removeClass('backuprowselected'); jQuery('#ud_massactions').hide(); return false;"><?php _e('Deselect', 'updraftplus');?></a></div>
</div>
<div id="updraft-message-modal" title="UpdraftPlus">
<div id="updraft-message-modal-innards">
</div>
</div>
<div id="updraft-delete-modal" title="<?php _e('Delete backup set', 'updraftplus');?>">
<form id="updraft_delete_form" method="post">
<p id="updraft_delete_question_singular">
<?php echo sprintf(__('Are you sure that you wish to remove %s from UpdraftPlus?', 'updraftplus'), __('this backup set', 'updraftplus')); ?>
</p>
<p id="updraft_delete_question_plural" class="updraft-hidden" style="display:none;">
<?php echo sprintf(__('Are you sure that you wish to remove %s from UpdraftPlus?', 'updraftplus'), __('these backup sets', 'updraftplus')); ?>
</p>
<fieldset>
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce('updraftplus-credentialtest-nonce');?>">
<input type="hidden" name="action" value="updraft_ajax">
<input type="hidden" name="subaction" value="deleteset">
<input type="hidden" name="backup_timestamp" value="0" id="updraft_delete_timestamp">
<input type="hidden" name="backup_nonce" value="0" id="updraft_delete_nonce">
<div id="updraft-delete-remote-section"><input checked="checked" type="checkbox" name="delete_remote" id="updraft_delete_remote" value="1"> <label for="updraft_delete_remote"><?php _e('Also delete from remote storage', 'updraftplus');?></label><br>
<p id="updraft-delete-waitwarning" class="updraft-hidden" style="display:none;"><em><?php _e('Deleting... please allow time for the communications with the remote storage to complete.', 'updraftplus');?></em></p>
</div>
</fieldset>
</form>
</div>
<div id="updraft-restore-modal" title="UpdraftPlus - <?php _e('Restore backup','updraftplus');?>">
<p><strong><?php _e('Restore backup from','updraftplus');?>:</strong> <span class="updraft_restore_date"></span></p>
<div id="updraft-restore-modal-stage2">
<p><strong><?php _e('Retrieving (if necessary) and preparing backup files...', 'updraftplus');?></strong></p>
<div id="ud_downloadstatus2"></div>
<div id="updraft-restore-modal-stage2a"></div>
</div>
<div id="updraft-restore-modal-stage1">
<p><?php _e("Restoring will replace this site's themes, plugins, uploads, database and/or other content directories (according to what is contained in the backup set, and your selection).",'updraftplus');?> <?php _e('Choose the components to restore','updraftplus');?>:</p>
<form id="updraft_restore_form" method="post">
<fieldset>
<input type="hidden" name="action" value="updraft_restore">
<input type="hidden" name="backup_timestamp" value="0" id="updraft_restore_timestamp">
<input type="hidden" name="meta_foreign" value="0" id="updraft_restore_meta_foreign">
<input type="hidden" name="updraft_restorer_backup_info" value="" id="updraft_restorer_backup_info">
<input type="hidden" name="updraft_restorer_restore_options" value="" id="updraft_restorer_restore_options">
<?php
# The 'off' check is for badly configured setups - http://wordpress.org/support/topic/plugin-wp-super-cache-warning-php-safe-mode-enabled-but-safe-mode-is-off
if ($updraftplus->detect_safe_mode()) {
echo "<p><em>".__("Your web server has PHP's so-called safe_mode active.", 'updraftplus').' '.__('This makes time-outs much more likely. You are recommended to turn safe_mode off, or to restore only one entity at a time, <a href="https://updraftplus.com/faqs/i-want-to-restore-but-have-either-cannot-or-have-failed-to-do-so-from-the-wp-admin-console/">or to restore manually</a>.', 'updraftplus')."</em></p><br/>";
}
$backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
foreach ($backupable_entities as $type => $info) {
if (!isset($info['restorable']) || $info['restorable'] == true) {
echo '<div><input id="updraft_restore_'.$type.'" type="checkbox" name="updraft_restore[]" value="'.$type.'"> <label id="updraft_restore_label_'.$type.'" for="updraft_restore_'.$type.'">'.$info['description'].'</label><br>';
do_action("updraftplus_restore_form_$type");
echo '</div>';
} else {
$sdescrip = isset($info['shortdescription']) ? $info['shortdescription'] : $info['description'];
echo "<div class=\"cannot-restore\"><em>".htmlspecialchars(sprintf(__('The following entity cannot be restored automatically: "%s".', 'updraftplus'), $sdescrip))." ".__('You will need to restore it manually.', 'updraftplus')."</em><br>".'<input id="updraft_restore_'.$type.'" type="hidden" name="updraft_restore[]" value="'.$type.'">';
echo '</div>';
}
}
?>
<div><input id="updraft_restore_db" type="checkbox" name="updraft_restore[]" value="db"> <label for="updraft_restore_db"><?php _e('Database','updraftplus'); ?></label><br>
<div id="updraft_restorer_dboptions" class="updraft-hidden" style="display:none;"><h4><?php echo sprintf(__('%s restoration options:','updraftplus'),__('Database','updraftplus')); ?></h4>
<?php
do_action("updraftplus_restore_form_db");
if (!class_exists('UpdraftPlus_Addons_Migrator')) {
echo '<a href="https://updraftplus.com/faqs/tell-me-more-about-the-search-and-replace-site-location-in-the-database-option/">'.__('You can search and replace your database (for migrating a website to a new location/URL) with the Migrator add-on - follow this link for more information','updraftplus').'</a>';
}
?>
</div>
</div>
</fieldset>
</form>
<p><em><a href="https://updraftplus.com/faqs/what-should-i-understand-before-undertaking-a-restoration/" target="_blank"><?php _e('Do read this helpful article of useful things to know before restoring.','updraftplus');?></a></em></p>
</div>
</div>
<?php
if ($return_result) return ob_get_clean();
}
public function settings_debugrow($head, $content) {
echo "<tr class=\"updraft_debugrow\"><th>$head</th><td>$content</td></tr>";
}
private function settings_expertsettings($backup_disabled) {
global $updraftplus, $wpdb;
$backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
?>
<div class="expertmode">
<p><em><?php _e('Unless you have a problem, you can completely ignore everything here.', 'updraftplus');?></em></p>
<table>
<?php
// It appears (Mar 2015) that some mod_security distributions block the output of the string el6.x86_64 in PHP output, on the silly assumption that only hackers are interested in knowing what environment PHP is running on.
// $uname_info = @php_uname();
$uname_info = @php_uname('s').' '.@php_uname('n').' ';
$release_name = @php_uname('r');
if (preg_match('/^(.*)\.(x86_64|[3456]86)$/', $release_name, $matches)) {
$release_name = $matches[1].' ';
} else {
$release_name = '';
}
// In case someone does something similar with just the processor type string
$mtype = @php_uname('m');
if ('x86_64' == $mtype) {
$mtype = '64-bit';
} elseif (preg_match('/^i([3456]86)$/', $mtype, $matches)) {
$mtype = $matches[1];
}
$uname_info .= $release_name.$mtype.' '.@php_uname('v');
$this->settings_debugrow(__('Web server:','updraftplus'), htmlspecialchars($_SERVER["SERVER_SOFTWARE"]).' ('.htmlspecialchars($uname_info).')');
$this->settings_debugrow('ABSPATH:', htmlspecialchars(ABSPATH));
$this->settings_debugrow('WP_CONTENT_DIR:', htmlspecialchars(WP_CONTENT_DIR));
$this->settings_debugrow('WP_PLUGIN_DIR:', htmlspecialchars(WP_PLUGIN_DIR));
$this->settings_debugrow('Table prefix:', htmlspecialchars($updraftplus->get_table_prefix()));
$peak_memory_usage = memory_get_peak_usage(true)/1024/1024;
$memory_usage = memory_get_usage(true)/1024/1024;
$this->settings_debugrow(__('Peak memory usage','updraftplus').':', $peak_memory_usage.' MB');
$this->settings_debugrow(__('Current memory usage','updraftplus').':', $memory_usage.' MB');
$this->settings_debugrow(__('Memory limit', 'updraftplus').':', htmlspecialchars(ini_get('memory_limit')));
$this->settings_debugrow(sprintf(__('%s version:','updraftplus'), 'PHP'), htmlspecialchars(phpversion()).' - <a href="admin-ajax.php?page=updraftplus&action=updraft_ajax&subaction=phpinfo&nonce='.wp_create_nonce('updraftplus-credentialtest-nonce').'" id="updraftplus-phpinfo">'.__('show PHP information (phpinfo)', 'updraftplus').'</a>');
$this->settings_debugrow(sprintf(__('%s version:','updraftplus'), 'MySQL'), htmlspecialchars($wpdb->db_version()));
if (function_exists('curl_version') && function_exists('curl_exec')) {
$cv = curl_version();
$cvs = $cv['version'].' / SSL: '.$cv['ssl_version'].' / libz: '.$cv['libz_version'];
} else {
$cvs = __('Not installed', 'updraftplus').' ('.__('required for some remote storage providers', 'updraftplus').')';
}
$this->settings_debugrow(sprintf(__('%s version:', 'updraftplus'), 'Curl'), htmlspecialchars($cvs));
$this->settings_debugrow(sprintf(__('%s version:', 'updraftplus'), 'OpenSSL'), defined('OPENSSL_VERSION_TEXT') ? OPENSSL_VERSION_TEXT : '-');
$this->settings_debugrow('MCrypt:', function_exists('mcrypt_encrypt') ? __('Yes') : __('No'));
if (version_compare(phpversion(), '5.2.0', '>=') && extension_loaded('zip')) {
$ziparchive_exists = __('Yes', 'updraftplus');
} else {
# First do class_exists, because method_exists still sometimes segfaults due to a rare PHP bug
$ziparchive_exists = (class_exists('ZipArchive') && method_exists('ZipArchive', 'addFile')) ? __('Yes', 'updraftplus') : __('No', 'updraftplus');
}
$this->settings_debugrow('ZipArchive::addFile:', $ziparchive_exists);
$binzip = $updraftplus->find_working_bin_zip(false, false);
$this->settings_debugrow(__('zip executable found:', 'updraftplus'), ((is_string($binzip)) ? __('Yes').': '.$binzip : __('No')));
$hosting_bytes_free = $updraftplus->get_hosting_disk_quota_free();
if (is_array($hosting_bytes_free)) {
$perc = round(100*$hosting_bytes_free[1]/(max($hosting_bytes_free[2], 1)), 1);
$this->settings_debugrow(__('Free disk space in account:', 'updraftplus'), sprintf(__('%s (%s used)', 'updraftplus'), round($hosting_bytes_free[3]/1048576, 1)." MB", "$perc %"));
}
$this->settings_debugrow(__('Plugins for debugging:', 'updraftplus'),'<a href="'.wp_nonce_url(self_admin_url('update.php?action=install-plugin&updraftplus_noautobackup=1&plugin=wp-crontrol'), 'install-plugin_wp-crontrol').'">WP Crontrol</a> | <a href="'.wp_nonce_url(self_admin_url('update.php?action=install-plugin&updraftplus_noautobackup=1&plugin=sql-executioner'), 'install-plugin_sql-executioner').'">SQL Executioner</a> | <a href="'.wp_nonce_url(self_admin_url('update.php?action=install-plugin&updraftplus_noautobackup=1&plugin=advanced-code-editor'), 'install-plugin_advanced-code-editor').'">Advanced Code Editor</a> '.(current_user_can('edit_plugins') ? '<a href="'.self_admin_url('plugin-editor.php?file=updraftplus/updraftplus.php').'">(edit UpdraftPlus)</a>' : '').' | <a href="'.wp_nonce_url(self_admin_url('update.php?action=install-plugin&updraftplus_noautobackup=1&plugin=wp-filemanager'), 'install-plugin_wp-filemanager').'">WP Filemanager</a>');
$this->settings_debugrow("HTTP Get: ", '<input id="updraftplus_httpget_uri" type="text" class="call-action"> <a href="#" id="updraftplus_httpget_go">'.__('Fetch', 'updraftplus').'</a> <a href="#" id="updraftplus_httpget_gocurl">'.__('Fetch', 'updraftplus').' (Curl)</a><p id="updraftplus_httpget_results"></p>');
$this->settings_debugrow(__("Call WordPress action:", 'updraftplus'), '<input id="updraftplus_callwpaction" type="text" class="call-action"> <a href="#" id="updraftplus_callwpaction_go">'.__('Call', 'updraftplus').'</a><div id="updraftplus_callwpaction_results"></div>');
$this->settings_debugrow('Site ID:', '(used to identify any Vault connections) <span id="updraft_show_sid">'.htmlspecialchars($updraftplus->siteid()).'</span> - <a href="#" id="updraft_reset_sid">'.__('reset', 'updraftplus')."</a>");
$this->settings_debugrow('', '<a href="admin-ajax.php?page=updraftplus&action=updraft_ajax&subaction=backuphistoryraw&nonce='.wp_create_nonce('updraftplus-credentialtest-nonce').'" id="updraftplus-rawbackuphistory">'.__('Show raw backup and file list', 'updraftplus').'</a>');
echo '</table>';
do_action('updraftplus_debugtools_dashboard');
if (!class_exists('UpdraftPlus_Addon_LockAdmin')) {
echo '<p class="updraftplus-lock-advert"><a href="https://updraftplus.com/shop/updraftplus-premium/"><em>'.__('For the ability to lock access to UpdraftPlus settings with a password, upgrade to UpdraftPlus Premium.', 'updraftplus').'</em></a></p>';
}
echo '<h3>'.__('Total (uncompressed) on-disk data:','updraftplus').'</h3>';
echo '<p class="uncompressed-data"><em>'.__('N.B. This count is based upon what was, or was not, excluded the last time you saved the options.', 'updraftplus').'</em></p><table>';
foreach ($backupable_entities as $key => $info) {
$sdescrip = preg_replace('/ \(.*\)$/', '', $info['description']);
if (strlen($sdescrip) > 20 && isset($info['shortdescription'])) $sdescrip = $info['shortdescription'];
// echo '<div style="clear: left;float:left; width:150px;">'.ucfirst($sdescrip).':</strong></div><div style="float:left;"><span id="updraft_diskspaceused_'.$key.'"><em></em></span> <a href="#" onclick="updraftplus_diskspace_entity(\''.$key.'\'); return false;">'.__('count','updraftplus').'</a></div>';
$this->settings_debugrow(ucfirst($sdescrip).':', '<span id="updraft_diskspaceused_'.$key.'"><em></em></span> <a href="#" onclick="updraftplus_diskspace_entity(\''.$key.'\'); return false;">'.__('count','updraftplus').'</a>');
}
?>
</table>
<p class="immediate-run"><?php _e('The buttons below will immediately execute a backup run, independently of WordPress\'s scheduler. If these work whilst your scheduled backups do absolutely nothing (i.e. not even produce a log file), then it means that your scheduler is broken.','updraftplus');?> <a href="https://updraftplus.com/faqs/my-scheduled-backups-and-pressing-backup-now-does-nothing-however-pressing-debug-backup-does-produce-a-backup/"><?php _e('Go here for more information.', 'updraftplus'); ?></a></p>
<table border="0" class="debug-table">
<tbody>
<tr>
<td>
<form method="post" action="<?php echo esc_url(add_query_arg(array('error' => false, 'updraft_restore_success' => false, 'action' => false, 'page' => 'updraftplus'))); ?>">
<input type="hidden" name="action" value="updraft_backup_debug_all" />
<p><input type="submit" class="button-primary" <?php echo $backup_disabled ?> value="<?php _e('Debug Full Backup','updraftplus');?>" onclick="return(confirm('<?php echo htmlspecialchars(__('This will cause an immediate backup. The page will stall loading until it finishes (ie, unscheduled).','updraftplus'));?>'))" /></p>
</form>
</td><td>
<form method="post" action="<?php echo esc_url(add_query_arg(array('error' => false, 'updraft_restore_success' => false, 'action' => false, 'page' => 'updraftplus'))); ?>">
<input type="hidden" name="action" value="updraft_backup_debug_db" />
<p><input type="submit" class="button-primary" <?php echo $backup_disabled ?> value="<?php _e('Debug Database Backup','updraftplus');?>" onclick="return(confirm('<?php echo htmlspecialchars(__('This will cause an immediate DB backup. The page will stall loading until it finishes (ie, unscheduled). The backup may well run out of time; really this button is only helpful for checking that the backup is able to get through the initial stages, or for small WordPress sites..','updraftplus'));?>'))" /></p>
</form>
</td>
</tr>
</tbody>
</table>
<h3><?php _e('Wipe settings', 'updraftplus');?></h3>
<p class="max-width-600"><?php echo __('This button will delete all UpdraftPlus settings and progress information for in-progress backups (but not any of your existing backups from your cloud storage).', 'updraftplus').' '.__('You will then need to enter all your settings again. You can also do this before deactivating/deinstalling UpdraftPlus if you wish.','updraftplus');?></p>
<form method="post" action="<?php echo esc_url(add_query_arg(array('error' => false, 'updraft_restore_success' => false, 'action' => false, 'page' => 'updraftplus'))); ?>">
<input type="hidden" name="action" value="updraft_wipesettings" />
<p><input type="submit" class="button-primary" value="<?php _e('Wipe settings','updraftplus'); ?>" onclick="return(confirm('<?php echo esc_js(__('This will delete all your UpdraftPlus settings - are you sure you want to do this?', 'updraftplus'));?>'))" /></p>
</form>
</div>
<?php
}
private function print_delete_old_dirs_form($include_blurb = true, $include_div = true) {
if ($include_blurb) {
if ($include_div) {
echo '<div id="updraft_delete_old_dirs_pagediv" class="updated delete-old-directories">';
}
echo '<p>'.__('Your WordPress install has old directories from its state before you restored/migrated (technical information: these are suffixed with -old). You should press this button to delete them as soon as you have verified that the restoration worked.','updraftplus').'</p>';
}
?>
<form method="post" onsubmit="return updraft_delete_old_dirs();" action="<?php echo esc_url(add_query_arg(array('error' => false, 'updraft_restore_success' => false, 'action' => false, 'page' => 'updraftplus'))); ?>">
<?php wp_nonce_field('updraftplus-credentialtest-nonce'); ?>
<input type="hidden" name="action" value="updraft_delete_old_dirs">
<input type="submit" class="button-primary" value="<?php echo esc_attr(__('Delete Old Directories', 'updraftplus'));?>" />
</form>
<?php
if ($include_blurb && $include_div) echo '</div>';
}
private function get_cron($job_id = false) {
$cron = get_option('cron');
if (!is_array($cron)) $cron = array();
if (false === $job_id) return $cron;
foreach ($cron as $time => $job) {
if (isset($job['updraft_backup_resume'])) {
foreach ($job['updraft_backup_resume'] as $hook => $info) {
if (isset($info['args'][1]) && $job_id == $info['args'][1]) {
global $updraftplus;
$jobdata = $updraftplus->jobdata_getarray($job_id);
return (!is_array($jobdata)) ? false : array($time, $jobdata);
}
}
}
}
}
// A value for $this_job_only also causes something to always be returned (to allow detection of the job having started on the front-end)
private function print_active_jobs($this_job_only = false) {
$cron = $this->get_cron();
// $found_jobs = 0;
$ret = '';
foreach ($cron as $time => $job) {
if (isset($job['updraft_backup_resume'])) {
foreach ($job['updraft_backup_resume'] as $hook => $info) {
if (isset($info['args'][1])) {
// $found_jobs++;
$job_id = $info['args'][1];
if (false === $this_job_only || $job_id == $this_job_only) {
$ret .= $this->print_active_job($job_id, false, $time, $info['args'][0]);
}
}
}
}
}
// A value for $this_job_only implies that output is required
if (false !== $this_job_only && !$ret) {
$ret = $this->print_active_job($this_job_only);
if ('' == $ret) {
// The presence of the exact ID matters to the front-end - indicates that the backup job has at least begun
$ret = '<div class="active-jobs updraft_finished" id="updraft-jobid-'.$this_job_only.'"><em>'.__('The backup has finished running', 'updraftplus').'</em> - <a class="updraft-log-link" data-jobid="'.$this_job_only.'">'.__('View Log', 'updraftplus').'</a></div>';
}
}
// if (0 == $found_jobs) $ret .= '<p><em>'.__('(None)', 'updraftplus').'</em></p>';
return $ret;
}
private function print_active_job($job_id, $is_oneshot = false, $time = false, $next_resumption = false) {
$ret = '';
global $updraftplus;
$jobdata = $updraftplus->jobdata_getarray($job_id);
if (false == apply_filters('updraftplus_print_active_job_continue', true, $is_oneshot, $next_resumption, $jobdata)) return '';
#if (!is_array($jobdata)) $jobdata = array();
if (!isset($jobdata['backup_time'])) return '';
$backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
$began_at = (isset($jobdata['backup_time'])) ? get_date_from_gmt(gmdate('Y-m-d H:i:s', (int)$jobdata['backup_time']), 'D, F j, Y H:i') : '?';
$jobstatus = empty($jobdata['jobstatus']) ? 'unknown' : $jobdata['jobstatus'];
$stage = 0;
switch ($jobstatus) {
# Stage 0
case 'begun':
$curstage = __('Backup begun', 'updraftplus');
break;
# Stage 1
case 'filescreating':
$stage = 1;
$curstage = __('Creating file backup zips', 'updraftplus');
if (!empty($jobdata['filecreating_substatus']) && isset($backupable_entities[$jobdata['filecreating_substatus']['e']]['description'])) {
$sdescrip = preg_replace('/ \(.*\)$/', '', $backupable_entities[$jobdata['filecreating_substatus']['e']]['description']);
if (strlen($sdescrip) > 20 && isset($jobdata['filecreating_substatus']['e']) && is_array($jobdata['filecreating_substatus']['e']) && isset($backupable_entities[$jobdata['filecreating_substatus']['e']]['shortdescription'])) $sdescrip = $backupable_entities[$jobdata['filecreating_substatus']['e']]['shortdescription'];
$curstage .= ' ('.$sdescrip.')';
if (isset($jobdata['filecreating_substatus']['i']) && isset($jobdata['filecreating_substatus']['t'])) {
$stage = min(2, 1 + ($jobdata['filecreating_substatus']['i']/max($jobdata['filecreating_substatus']['t'],1)));
}
}
break;
case 'filescreated':
$stage = 2;
$curstage = __('Created file backup zips', 'updraftplus');
break;
# Stage 4
case 'clouduploading':
$stage = 4;
$curstage = __('Uploading files to remote storage', 'updraftplus');
if (isset($jobdata['uploading_substatus']['t']) && isset($jobdata['uploading_substatus']['i'])) {
$t = max((int)$jobdata['uploading_substatus']['t'], 1);
$i = min($jobdata['uploading_substatus']['i']/$t, 1);
$p = min($jobdata['uploading_substatus']['p'], 1);
$pd = $i + $p/$t;
$stage = 4 + $pd;
$curstage .= ' '.sprintf(__('(%s%%, file %s of %s)', 'updraftplus'), floor(100*$pd), $jobdata['uploading_substatus']['i']+1, $t);
}
break;
case 'pruning':
$stage = 5;
$curstage = __('Pruning old backup sets', 'updraftplus');
break;
case 'resumingforerrors':
$stage = -1;
$curstage = __('Waiting until scheduled time to retry because of errors', 'updraftplus');
break;
# Stage 6
case 'finished':
$stage = 6;
$curstage = __('Backup finished', 'updraftplus');
break;
default:
# Database creation and encryption occupies the space from 2 to 4. Databases are created then encrypted, then the next databae is created/encrypted, etc.
if ('dbcreated' == substr($jobstatus, 0, 9)) {
$jobstatus = 'dbcreated';
$whichdb = substr($jobstatus, 9);
if (!is_numeric($whichdb)) $whichdb = 0;
$howmanydbs = max((empty($jobdata['backup_database']) || !is_array($jobdata['backup_database'])) ? 1 : count($jobdata['backup_database']), 1);
$perdbspace = 2/$howmanydbs;
$stage = min(4, 2 + ($whichdb+2)*$perdbspace);
$curstage = __('Created database backup', 'updraftplus');
} elseif ('dbcreating' == substr($jobstatus, 0, 10)) {
$whichdb = substr($jobstatus, 10);
if (!is_numeric($whichdb)) $whichdb = 0;
$howmanydbs = (empty($jobdata['backup_database']) || !is_array($jobdata['backup_database'])) ? 1 : count($jobdata['backup_database']);
$perdbspace = 2/$howmanydbs;
$jobstatus = 'dbcreating';
$stage = min(4, 2 + $whichdb*$perdbspace);
$curstage = __('Creating database backup', 'updraftplus');
if (!empty($jobdata['dbcreating_substatus']['t'])) {
$curstage .= ' ('.sprintf(__('table: %s', 'updraftplus'), $jobdata['dbcreating_substatus']['t']).')';
if (!empty($jobdata['dbcreating_substatus']['i']) && !empty($jobdata['dbcreating_substatus']['a'])) {
$substage = max(0.001, ($jobdata['dbcreating_substatus']['i'] / max($jobdata['dbcreating_substatus']['a'],1)));
$stage += $substage * $perdbspace * 0.5;
}
}
} elseif ('dbencrypting' == substr($jobstatus, 0, 12)) {
$whichdb = substr($jobstatus, 12);
if (!is_numeric($whichdb)) $whichdb = 0;
$howmanydbs = (empty($jobdata['backup_database']) || !is_array($jobdata['backup_database'])) ? 1 : count($jobdata['backup_database']);
$perdbspace = 2/$howmanydbs;
$stage = min(4, 2 + $whichdb*$perdbspace + $perdbspace*0.5);
$jobstatus = 'dbencrypting';
$curstage = __('Encrypting database', 'updraftplus');
} elseif ('dbencrypted' == substr($jobstatus, 0, 11)) {
$whichdb = substr($jobstatus, 11);
if (!is_numeric($whichdb)) $whichdb = 0;
$howmanydbs = (empty($jobdata['backup_database']) || !is_array($jobdata['backup_database'])) ? 1 : count($jobdata['backup_database']);
$jobstatus = 'dbencrypted';
$perdbspace = 2/$howmanydbs;
$stage = min(4, 2 + $whichdb*$perdbspace + $perdbspace);
$curstage = __('Encrypted database', 'updraftplus');
} else {
$curstage = __('Unknown', 'updraftplus');
}
}
$runs_started = (empty($jobdata['runs_started'])) ? array() : $jobdata['runs_started'];
$time_passed = (empty($jobdata['run_times'])) ? array() : $jobdata['run_times'];
$last_checkin_ago = -1;
if (is_array($time_passed)) {
foreach ($time_passed as $run => $passed) {
if (isset($runs_started[$run])) {
$time_ago = microtime(true) - ($runs_started[$run] + $time_passed[$run]);
if ($time_ago < $last_checkin_ago || $last_checkin_ago == -1) $last_checkin_ago = $time_ago;
}
}
}
$next_res_after = (int)$time-time();
$next_res_txt = ($is_oneshot) ? '' : ' - '.sprintf(__("next resumption: %d (after %ss)", 'updraftplus'), $next_resumption, $next_res_after). ' ';
$last_activity_txt = ($last_checkin_ago >= 0) ? ' - '.sprintf(__('last activity: %ss ago', 'updraftplus'), floor($last_checkin_ago)).' ' : '';
if (($last_checkin_ago < 50 && $next_res_after>30) || $is_oneshot) {
$show_inline_info = $last_activity_txt;
$title_info = $next_res_txt;
} else {
$show_inline_info = $next_res_txt;
$title_info = $last_activity_txt;
}
// Existence of the 'updraft-jobid-(id)' id is checked for in other places, so do not modify this
$ret .= '<div class="job-id" id="updraft-jobid-'.$job_id.'"><span class="updraft_jobtimings next-resumption';
if (!empty($jobdata['is_autobackup'])) $ret .= ' isautobackup';
$ret .= '" data-jobid="'.$job_id.'" data-lastactivity="'.(int)$last_checkin_ago.'" data-nextresumption="'.$next_resumption.'" data-nextresumptionafter="'.$next_res_after.'" title="'.esc_attr(sprintf(__('Job ID: %s', 'updraftplus'), $job_id)).$title_info.'">'.$began_at.'</span> ';
$ret .= $show_inline_info;
$ret .= '- <a data-jobid="'.$job_id.'" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=downloadlog&updraftplus_backup_nonce='.$job_id.'" class="updraft-log-link">'.__('show log', 'updraftplus').'</a>';
if (!$is_oneshot) $ret .=' - <a href="#" data-jobid="'.$job_id.'" title="'.esc_attr(__('Note: the progress bar below is based on stages, NOT time. Do not stop the backup simply because it seems to have remained in the same place for a while - that is normal.', 'updraftplus')).'" class="updraft_jobinfo_delete">'.__('stop', 'updraftplus').'</a>';
$ret .= apply_filters('updraft_printjob_beforewarnings', '', $jobdata, $job_id);
if (!empty($jobdata['warnings']) && is_array($jobdata['warnings'])) {
$ret .= '<ul class="disc">';
foreach ($jobdata['warnings'] as $warning) {
$ret .= '<li>'.sprintf(__('Warning: %s', 'updraftplus'), make_clickable(htmlspecialchars($warning))).'</li>';
}
$ret .= '</ul>';
}
$ret .= '<div class="curstage">';
$ret .= htmlspecialchars($curstage);
$ret .= '<div class="updraft_percentage" style="height: 100%; width:'.(($stage>0) ? (ceil((100/6)*$stage)) : '0').'%"></div>';
$ret .= '</div></div>';
$ret .= '</div>';
return $ret;
}
private function delete_old_dirs_go($show_return = true) {
echo ($show_return) ? '<h1>UpdraftPlus - '.__('Remove old directories', 'updraftplus').'</h1>' : '<h2>'.__('Remove old directories', 'updraftplus').'</h2>';
if ($this->delete_old_dirs()) {
echo '<p>'.__('Old directories successfully removed.','updraftplus').'</p><br/>';
} else {
echo '<p>',__('Old directory removal failed for some reason. You may want to do this manually.','updraftplus').'</p><br/>';
}
if ($show_return) echo '<b>'.__('Actions','updraftplus').':</b> <a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus">'.__('Return to UpdraftPlus Configuration','updraftplus').'</a>';
}
//deletes the -old directories that are created when a backup is restored.
private function delete_old_dirs() {
global $wp_filesystem, $updraftplus;
$credentials = request_filesystem_credentials(wp_nonce_url(UpdraftPlus_Options::admin_page_url()."?page=updraftplus&action=updraft_delete_old_dirs", 'updraftplus-credentialtest-nonce'));
WP_Filesystem($credentials);
if ($wp_filesystem->errors->get_error_code()) {
foreach ($wp_filesystem->errors->get_error_messages() as $message)
show_message($message);
exit;
}
// From WP_CONTENT_DIR - which contains 'themes'
$ret = $this->delete_old_dirs_dir($wp_filesystem->wp_content_dir());
$updraft_dir = $updraftplus->backups_dir_location();
if ($updraft_dir) {
$ret4 = ($updraft_dir) ? $this->delete_old_dirs_dir($updraft_dir, false) : true;
} else {
$ret4 = true;
}
// $ret2 = $this->delete_old_dirs_dir($wp_filesystem->abspath());
$plugs = untrailingslashit($wp_filesystem->wp_plugins_dir());
if ($wp_filesystem->is_dir($plugs.'-old')) {
print "<strong>".__('Delete','updraftplus').": </strong>plugins-old: ";
if (!$wp_filesystem->delete($plugs.'-old', true)) {
$ret3 = false;
print "<strong>".__('Failed', 'updraftplus')."</strong><br>";
} else {
$ret3 = true;
print "<strong>".__('OK', 'updraftplus')."</strong><br>";
}
} else {
$ret3 = true;
}
return $ret && $ret3 && $ret4;
}
private function delete_old_dirs_dir($dir, $wpfs = true) {
$dir = trailingslashit($dir);
global $wp_filesystem, $updraftplus;
if ($wpfs) {
$list = $wp_filesystem->dirlist($dir);
} else {
$list = scandir($dir);
}
if (!is_array($list)) return false;
$ret = true;
foreach ($list as $item) {
$name = (is_array($item)) ? $item['name'] : $item;
if ("-old" == substr($name, -4, 4)) {
//recursively delete
print "<strong>".__('Delete','updraftplus').": </strong>".htmlspecialchars($name).": ";
if ($wpfs) {
if (!$wp_filesystem->delete($dir.$name, true)) {
$ret = false;
echo "<strong>".__('Failed', 'updraftplus')."</strong><br>";
} else {
echo "<strong>".__('OK', 'updraftplus')."</strong><br>";
}
} else {
if ($updraftplus->remove_local_directory($dir.$name)) {
echo "<strong>".__('OK', 'updraftplus')."</strong><br>";
} else {
$ret = false;
echo "<strong>".__('Failed', 'updraftplus')."</strong><br>";
}
}
}
}
return $ret;
}
// The aim is to get a directory that is writable by the webserver, because that's the only way we can create zip files
private function create_backup_dir() {
global $wp_filesystem, $updraftplus;
if (false === ($credentials = request_filesystem_credentials(UpdraftPlus_Options::admin_page().'?page=updraftplus&action=updraft_create_backup_dir&nonce='.wp_create_nonce('create_backup_dir')))) {
return false;
}
if ( ! WP_Filesystem($credentials) ) {
// our credentials were no good, ask the user for them again
request_filesystem_credentials(UpdraftPlus_Options::admin_page().'?page=updraftplus&action=updraft_create_backup_dir&nonce='.wp_create_nonce('create_backup_dir'), '', true);
return false;
}
$updraft_dir = $updraftplus->backups_dir_location();
$default_backup_dir = $wp_filesystem->find_folder(dirname($updraft_dir)).basename($updraft_dir);
$updraft_dir = ($updraft_dir) ? $wp_filesystem->find_folder(dirname($updraft_dir)).basename($updraft_dir) : $default_backup_dir;
if (!$wp_filesystem->is_dir($default_backup_dir) && !$wp_filesystem->mkdir($default_backup_dir, 0775)) {
$wperr = new WP_Error;
if ( $wp_filesystem->errors->get_error_code() ) {
foreach ( $wp_filesystem->errors->get_error_messages() as $message ) {
$wperr->add('mkdir_error', $message);
}
return $wperr;
} else {
return new WP_Error('mkdir_error', __('The request to the filesystem to create the directory failed.', 'updraftplus'));
}
}
if ($wp_filesystem->is_dir($default_backup_dir)) {
if ($updraftplus->really_is_writable($updraft_dir)) return true;
@$wp_filesystem->chmod($default_backup_dir, 0775);
if ($updraftplus->really_is_writable($updraft_dir)) return true;
@$wp_filesystem->chmod($default_backup_dir, 0777);
if ($updraftplus->really_is_writable($updraft_dir)) {
echo '<p>'.__('The folder was created, but we had to change its file permissions to 777 (world-writable) to be able to write to it. You should check with your hosting provider that this will not cause any problems', 'updraftplus').'</p>';
return true;
} else {
@$wp_filesystem->chmod($default_backup_dir, 0775);
$show_dir = (0 === strpos($default_backup_dir, ABSPATH)) ? substr($default_backup_dir, strlen(ABSPATH)) : $default_backup_dir;
return new WP_Error('writable_error', __('The folder exists, but your webserver does not have permission to write to it.', 'updraftplus').' '.__('You will need to consult with your web hosting provider to find out how to set permissions for a WordPress plugin to write to the directory.', 'updraftplus').' ('.$show_dir.')');
}
}
return true;
}
//scans the content dir to see if any -old dirs are present
private function scan_old_dirs($print_as_comment = false) {
global $updraftplus;
$dirs = scandir(untrailingslashit(WP_CONTENT_DIR));
if (!is_array($dirs)) $dirs = array();
$dirs_u = @scandir($updraftplus->backups_dir_location());
if (!is_array($dirs_u)) $dirs_u = array();
foreach (array_merge($dirs, $dirs_u) as $dir) {
if (preg_match('/-old$/', $dir)) {
if ($print_as_comment) echo '<!--'.htmlspecialchars($dir).'-->';
return true;
}
}
# No need to scan ABSPATH - we don't backup there
if (is_dir(untrailingslashit(WP_PLUGIN_DIR).'-old')) {
if ($print_as_comment) echo '<!--'.htmlspecialchars(untrailingslashit(WP_PLUGIN_DIR).'-old').'-->';
return true;
}
return false;
}
public function storagemethod_row($method, $header, $contents) {
?>
<tr class="updraftplusmethod <?php echo $method;?>">
<th><?php echo $header;?></th>
<td><?php echo $contents;?></td>
</tr>
<?php
}
private function last_backup_html() {
global $updraftplus;
$updraft_last_backup = UpdraftPlus_Options::get_updraft_option('updraft_last_backup');
if ($updraft_last_backup) {
// Convert to GMT, then to blog time
$backup_time = (int)$updraft_last_backup['backup_time'];
$print_time = get_date_from_gmt(gmdate('Y-m-d H:i:s', $backup_time), 'D, F j, Y H:i');
// $print_time = date_i18n('D, F j, Y H:i', $backup_time);
if (empty($updraft_last_backup['backup_time_incremental'])) {
$last_backup_text = "<span style=\"color:".(($updraft_last_backup['success']) ? 'green' : 'black').";\">".$print_time.'</span>';
} else {
$inc_time = get_date_from_gmt(gmdate('Y-m-d H:i:s', $updraft_last_backup['backup_time_incremental']), 'D, F j, Y H:i');
// $inc_time = date_i18n('D, F j, Y H:i', $updraft_last_backup['backup_time_incremental']);
$last_backup_text = "<span style=\"color:".(($updraft_last_backup['success']) ? 'green' : 'black').";\">$inc_time</span> (".sprintf(__('incremental backup; base backup: %s', 'updraftplus'), $print_time).')';
}
$last_backup_text .= '<br>';
// Show errors + warnings
if (is_array($updraft_last_backup['errors'])) {
foreach ($updraft_last_backup['errors'] as $err) {
$level = (is_array($err)) ? $err['level'] : 'error';
$message = (is_array($err)) ? $err['message'] : $err;
$last_backup_text .= ('warning' == $level) ? "<span style=\"color:orange;\">" : "<span style=\"color:red;\">";
if ('warning' == $level) {
$message = sprintf(__("Warning: %s", 'updraftplus'), make_clickable(htmlspecialchars($message)));
} else {
$message = htmlspecialchars($message);
}
$last_backup_text .= $message;
$last_backup_text .= '</span><br>';
}
}
// Link log
if (!empty($updraft_last_backup['backup_nonce'])) {
$updraft_dir = $updraftplus->backups_dir_location();
$potential_log_file = $updraft_dir."/log.".$updraft_last_backup['backup_nonce'].".txt";
if (is_readable($potential_log_file)) $last_backup_text .= "<a href=\"?page=updraftplus&action=downloadlog&updraftplus_backup_nonce=".$updraft_last_backup['backup_nonce']."\" class=\"updraft-log-link\" onclick=\"event.preventDefault(); updraft_popuplog('".$updraft_last_backup['backup_nonce']."');\">".__('Download log file','updraftplus')."</a>";
}
} else {
$last_backup_text = "<span style=\"color:blue;\">".__('No backup has been completed','updraftplus')."</span>";
}
return $last_backup_text;
}
public function get_intervals() {
return apply_filters('updraftplus_backup_intervals', array(
'manual' => _x("Manual", 'i.e. Non-automatic', 'updraftplus'),
'every4hours' => sprintf(__("Every %s hours", 'updraftplus'), '4'),
'every8hours' => sprintf(__("Every %s hours", 'updraftplus'), '8'),
'twicedaily' => sprintf(__("Every %s hours", 'updraftplus'), '12'),
'daily' => __("Daily", 'updraftplus'),
'weekly' => __("Weekly", 'updraftplus'),
'fortnightly' => __("Fortnightly", 'updraftplus'),
'monthly' => __("Monthly", 'updraftplus')
));
}
private function really_writable_message($really_is_writable, $updraft_dir){
if ($really_is_writable) {
$dir_info = '<span style="color:green;">'.__('Backup directory specified is writable, which is good.','updraftplus').'</span>';
} else {
$dir_info = '<span style="color:red;">';
if (!is_dir($updraft_dir)) {
$dir_info .= __('Backup directory specified does <b>not</b> exist.','updraftplus');
} else {
$dir_info .= __('Backup directory specified exists, but is <b>not</b> writable.','updraftplus');
}
$dir_info .= '<span class="updraft-directory-not-writable-blurb"><span class="directory-permissions"><a class="updraft_create_backup_dir" href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&action=updraft_create_backup_dir&nonce='.wp_create_nonce('create_backup_dir').'">'.__('Click here to attempt to create the directory and set the permissions','updraftplus').'</a></span>, '.__('or, to reset this option','updraftplus').' <a href="#" class="updraft_backup_dir_reset">'.__('click here','updraftplus').'</a>. '.__('If that is unsuccessful check the permissions on your server or change it to another directory that is writable by your web server process.','updraftplus').'</span>';
}
return $dir_info;
}
public function settings_formcontents($options = array()) {
global $updraftplus;
$updraft_dir = $updraftplus->backups_dir_location();
$really_is_writable = $updraftplus->really_is_writable($updraft_dir);
$default_options = array(
'include_database_decrypter' => true,
'include_adverts' => true,
'include_save_button' => true
);
foreach ($default_options as $k => $v) {
if (!isset($options[$k])) $options[$k] = $v;
}
?>
<table class="form-table">
<tr>
<th><?php _e('Files backup schedule','updraftplus'); ?>:</th>
<td>
<div style="float:left; clear:both;">
<select class="updraft_interval" name="updraft_interval">
<?php
$intervals = $this->get_intervals();
$selected_interval = UpdraftPlus_Options::get_updraft_option('updraft_interval', 'manual');
foreach ($intervals as $cronsched => $descrip) {
echo "<option value=\"$cronsched\" ";
if ($cronsched == $selected_interval) echo 'selected="selected"';
echo ">".htmlspecialchars($descrip)."</option>\n";
}
?>
</select> <span class="updraft_files_timings"><?php echo apply_filters('updraftplus_schedule_showfileopts', '<input type="hidden" name="updraftplus_starttime_files" value="">', $selected_interval); ?></span>
<?php
$updraft_retain = max((int)UpdraftPlus_Options::get_updraft_option('updraft_retain', 2), 1);
$retain_files_config = __('and retain this many scheduled backups', 'updraftplus').': <input type="number" min="1" step="1" name="updraft_retain" value="'.$updraft_retain.'" class="retain-files" />';
// echo apply_filters('updraftplus_retain_files_intervalline', $retain_files_config, $updraft_retain);
echo $retain_files_config;
?>
</div>
<?php do_action('updraftplus_after_filesconfig'); ?>
</td>
</tr>
<?php if (defined('UPDRAFTPLUS_EXPERIMENTAL') && UPDRAFTPLUS_EXPERIMENTAL) { ?>
<tr class="updraft_incremental_row">
<th><?php _e('Incremental file backup schedule', 'updraftplus'); ?>:</th>
<td>
<?php do_action('updraftplus_incremental_cell', $selected_interval); ?>
<a href="https://updraftplus.com/support/tell-me-more-about-incremental-backups/"><em><?php _e('Tell me more about incremental backups', 'updraftplus'); ?><em></a>
</td>
</tr>
<?php } ?>
<?php apply_filters('updraftplus_after_file_intervals', false, $selected_interval); ?>
<tr>
<th><?php _e('Database backup schedule','updraftplus'); ?>:</th>
<td>
<div style="float:left; clear:both;">
<select class="updraft_interval_database" name="updraft_interval_database">
<?php
$selected_interval_db = UpdraftPlus_Options::get_updraft_option('updraft_interval_database', UpdraftPlus_Options::get_updraft_option('updraft_interval'));
foreach ($intervals as $cronsched => $descrip) {
echo "<option value=\"$cronsched\" ";
if ($cronsched == $selected_interval_db) echo 'selected="selected"';
echo ">$descrip</option>\n";
}
?>
</select> <span class="updraft_same_schedules_message"><?php echo apply_filters('updraftplus_schedule_sametimemsg', '');?></span><span class="updraft_db_timings"><?php echo apply_filters('updraftplus_schedule_showdbopts', '<input type="hidden" name="updraftplus_starttime_db" value="">', $selected_interval_db); ?></span>
<?php
$updraft_retain_db = max((int)UpdraftPlus_Options::get_updraft_option('updraft_retain_db', $updraft_retain), 1);
$retain_dbs_config = __('and retain this many scheduled backups', 'updraftplus').': <input type="number" min="1" step="1" name="updraft_retain_db" value="'.$updraft_retain_db.'" class="retain-files" />';
// echo apply_filters('updraftplus_retain_db_intervalline', $retain_dbs_config, $updraft_retain_db);
echo $retain_dbs_config;
?>
</div>
<?php do_action('updraftplus_after_dbconfig'); ?>
</td>
</tr>
<tr class="backup-interval-description">
<th></th>
<td><div>
<?php
echo apply_filters('updraftplus_fixtime_ftinfo', '<p>'.__('To fix the time at which a backup should take place,','updraftplus').' ('.__('e.g. if your server is busy at day and you want to run overnight','updraftplus').'), '.__('or to configure more complex schedules', 'updraftplus').', <a href="https://updraftplus.com/shop/updraftplus-premium/">'.htmlspecialchars(__('use UpdraftPlus Premium', 'updraftplus')).'</a></p>');
?>
</div></td>
</tr>
</table>
<h2 class="updraft_settings_sectionheading"><?php _e('Sending Your Backup To Remote Storage','updraftplus');?></h2>
<?php
$debug_mode = UpdraftPlus_Options::get_updraft_option('updraft_debug_mode') ? 'checked="checked"' : "";
$active_service = UpdraftPlus_Options::get_updraft_option('updraft_service');
?>
<table class="form-table width-900">
<tr>
<th><?php
echo __('Choose your remote storage','updraftplus').'<br>'.apply_filters('updraftplus_after_remote_storage_heading_message', '<em>'.__('(tap on an icon to select or unselect)', 'updraftplus').'</em>');
?>:</th>
<td>
<div id="remote-storage-container">
<?php
if (is_array($active_service)) $active_service = $updraftplus->just_one($active_service);
//Change this to give a class that we can exclude
$multi = apply_filters('updraftplus_storage_printoptions_multi', '');
foreach($updraftplus->backup_methods as $method => $description) {
$backup_using = esc_attr(sprintf(__("Backup using %s?", 'updraftplus'), $description));
echo "<input aria-label=\"$backup_using\" name=\"updraft_service[]\" class=\"updraft_servicecheckbox $method $multi\" id=\"updraft_servicecheckbox_$method\" type=\"checkbox\" value=\"$method\"";
if ($active_service === $method || (is_array($active_service) && in_array($method, $active_service))) echo ' checked="checked"';
echo " data-labelauty=\"".esc_attr($description)."\">";
}
?>
<?php
if (false === apply_filters('updraftplus_storage_printoptions', false, $active_service)) {
echo '</div>';
echo '<p><a href="https://updraftplus.com/shop/morestorage/">'.htmlspecialchars(__('You can send a backup to more than one destination with an add-on.','updraftplus')).'</a></p>';
echo '</td></tr>';
}
?>
<tr class="updraftplusmethod none ud_nostorage" style="display:none;">
<td></td>
<td><em><?php echo htmlspecialchars(__('If you choose no remote storage, then the backups remain on the web-server. This is not recommended (unless you plan to manually copy them to your computer), as losing the web-server would mean losing both your website and the backups in one event.', 'updraftplus'));?></em></td>
</tr>
<?php
$method_objects = array();
foreach ($updraftplus->backup_methods as $method => $description) {
do_action('updraftplus_config_print_before_storage', $method);
require_once(UPDRAFTPLUS_DIR.'/methods/'.$method.'.php');
$call_method = 'UpdraftPlus_BackupModule_'.$method;
$method_objects[$method] = new $call_method;
$method_objects[$method]->config_print();
do_action('updraftplus_config_print_after_storage', $method);
}
?>
</table>
<hr style="width:900px; float:left;">
<h2 class="updraft_settings_sectionheading"><?php _e('File Options', 'updraftplus');?></h2>
<table class="form-table" >
<tr>
<th><?php _e('Include in files backup', 'updraftplus');?>:</th>
<td>
<?php echo $this->files_selector_widgetry(); ?>
<p><?php echo apply_filters('updraftplus_admin_directories_description', __('The above directories are everything, except for WordPress core itself which you can download afresh from WordPress.org.', 'updraftplus').' <a href="https://updraftplus.com/shop/">'.htmlspecialchars(__('See also the "More Files" add-on from our shop.', 'updraftplus')).'</a>'); ?></p>
</td>
</tr>
</table>
<h2 class="updraft_settings_sectionheading"><?php _e('Database Options','updraftplus');?></h2>
<table class="form-table width-900">
<tr>
<th><?php _e('Database encryption phrase', 'updraftplus');?>:</th>
<td>
<?php
echo apply_filters('updraft_database_encryption_config', '<a href="https://updraftplus.com/shop/updraftplus-premium/">'.__("Don't want to be spied on? UpdraftPlus Premium can encrypt your database backup.", 'updraftplus').'</a> '.__('It can also backup external databases.', 'updraftplus'));
?>
</td>
</tr>
<?php if (!empty($options['include_database_decrypter'])) { ?>
<tr class="backup-crypt-description">
<td></td>
<td>
<a href="#" class="updraft_show_decryption_widget"><?php _e('You can manually decrypt an encrypted database here.','updraftplus');?></a>
<div id="updraft-manualdecrypt-modal" class="updraft-hidden" style="display:none;">
<p><h3><?php _e("Manually decrypt a database backup file" ,'updraftplus');?></h3></p>
<?php
global $wp_version;
if (version_compare($wp_version, '3.3', '<')) {
echo '<em>'.sprintf(__('This feature requires %s version %s or later', 'updraftplus'), 'WordPress', '3.3').'</em>';
} else {
?>
<div id="plupload-upload-ui2">
<div id="drag-drop-area2">
<div class="drag-drop-inside">
<p class="drag-drop-info"><?php _e('Drop encrypted database files (db.gz.crypt files) here to upload them for decryption', 'updraftplus'); ?></p>
<p><?php _ex('or', 'Uploader: Drop db.gz.crypt files here to upload them for decryption - or - Select Files', 'updraftplus'); ?></p>
<p class="drag-drop-buttons"><input id="plupload-browse-button2" type="button" value="<?php esc_attr_e('Select Files', 'updraftplus'); ?>" class="button" /></p>
<p style="margin-top: 18px;"><?php _e('First, enter the decryption key','updraftplus')?>: <input id="updraftplus_db_decrypt" type="text" size="12"></input></p>
</div>
</div>
<div id="filelist2">
</div>
</div>
<?php } ?>
</div>
</td>
</tr>
<?php } ?>
<?php
#'<a href="https://updraftplus.com/shop/updraftplus-premium/">'.__("This feature is part of UpdraftPlus Premium.", 'updraftplus').'</a>'
$moredbs_config = apply_filters('updraft_database_moredbs_config', false);
if (!empty($moredbs_config)) {
?>
<tr>
<th><?php _e('Back up more databases', 'updraftplus');?>:</th>
<td><?php echo $moredbs_config; ?>
</td>
</tr>
<?php } ?>
</table>
<h2 class="updraft_settings_sectionheading"><?php _e('Reporting','updraftplus');?></h2>
<table class="form-table" style="width:900px;">
<?php
$report_rows = apply_filters('updraftplus_report_form', false);
if (is_string($report_rows)) {
echo $report_rows;
} else {
?>
<tr>
<th><?php _e('Email', 'updraftplus'); ?>:</th>
<td>
<?php
$updraft_email = UpdraftPlus_Options::get_updraft_option('updraft_email');
?>
<input type="checkbox" id="updraft_email" name="updraft_email" value="<?php esc_attr_e(get_bloginfo('admin_email')); ?>"<?php if (!empty($updraft_email)) echo ' checked="checked"';?> > <br><label for="updraft_email"><?php echo __("Check this box to have a basic report sent to", 'updraftplus').' <a href="'.admin_url('options-general.php').'">'.__("your site's admin address", 'updraftplus').'</a> ('.htmlspecialchars(get_bloginfo('admin_email')).")."; ?></label>
<?php
if (!class_exists('UpdraftPlus_Addon_Reporting')) echo '<a href="https://updraftplus.com/shop/reporting/">'.__('For more reporting features, use the Reporting add-on.', 'updraftplus').'</a>';
?>
</td>
</tr>
<?php } ?>
</table>
<script type="text/javascript">
/* <![CDATA[ */
<?php echo $this->get_settings_js($method_objects, $really_is_writable, $updraft_dir); ?>
/* ]]> */
</script>
<table class="form-table width-900">
<tr>
<td colspan="2"><h2 class="updraft_settings_sectionheading"><?php _e('Advanced / Debugging Settings','updraftplus'); ?></h2></td>
</tr>
<tr>
<th><?php _e('Expert settings','updraftplus');?>:</th>
<td><a class="enableexpertmode" href="#enableexpertmode"><?php _e('Show expert settings','updraftplus');?></a> - <?php _e("click this to show some further options; don't bother with this unless you have a problem or are curious.",'updraftplus');?> <?php do_action('updraftplus_expertsettingsdescription'); ?></td>
</tr>
<?php
$delete_local = UpdraftPlus_Options::get_updraft_option('updraft_delete_local', 1);
$split_every_mb = UpdraftPlus_Options::get_updraft_option('updraft_split_every', 400);
if (!is_numeric($split_every_mb)) $split_every_mb = 400;
if ($split_every_mb < UPDRAFTPLUS_SPLIT_MIN) $split_every_mb = UPDRAFTPLUS_SPLIT_MIN;
?>
<tr class="expertmode updraft-hidden" style="display:none;">
<th><?php _e('Debug mode','updraftplus');?>:</th>
<td><input type="checkbox" id="updraft_debug_mode" name="updraft_debug_mode" value="1" <?php echo $debug_mode; ?> /> <br><label for="updraft_debug_mode"><?php _e('Check this to receive more information and emails on the backup process - useful if something is going wrong.','updraftplus');?> <?php _e('This will also cause debugging output from all plugins to be shown upon this screen - please do not be surprised to see these.', 'updraftplus');?></label></td>
</tr>
<tr class="expertmode updraft-hidden" style="display:none;">
<th><?php _e('Split archives every:','updraftplus');?></th>
<td><input type="text" name="updraft_split_every" class="updraft_split_every" value="<?php echo $split_every_mb ?>" size="5" /> MB<br><?php echo sprintf(__('UpdraftPlus will split up backup archives when they exceed this file size. The default value is %s megabytes. Be careful to leave some margin if your web-server has a hard size limit (e.g. the 2 GB / 2048 MB limit on some 32-bit servers/file systems).','updraftplus'), 400); ?></td>
</tr>
<tr class="deletelocal expertmode updraft-hidden" style="display:none;">
<th><?php _e('Delete local backup','updraftplus');?>:</th>
<td><input type="checkbox" id="updraft_delete_local" name="updraft_delete_local" value="1" <?php if ($delete_local) echo 'checked="checked"'; ?>> <br><label for="updraft_delete_local"><?php _e('Check this to delete any superfluous backup files from your server after the backup run finishes (i.e. if you uncheck, then any files despatched remotely will also remain locally, and any files being kept locally will not be subject to the retention limits).','updraftplus');?></label></td>
</tr>
<tr class="expertmode backupdirrow updraft-hidden" style="display:none;">
<th><?php _e('Backup directory','updraftplus');?>:</th>
<td><input type="text" name="updraft_dir" id="updraft_dir" style="width:525px" value="<?php echo htmlspecialchars($this->prune_updraft_dir_prefix($updraft_dir)); ?>" /></td>
</tr>
<tr class="expertmode backupdirrow updraft-hidden" style="display:none;">
<td></td>
<td>
<span id="updraft_writable_mess">
<?php
$dir_info = $this->really_writable_message($really_is_writable, $updraft_dir);
echo $dir_info;
?>
</span>
<?php
echo __("This is where UpdraftPlus will write the zip files it creates initially. This directory must be writable by your web server. It is relative to your content directory (which by default is called wp-content).", 'updraftplus').' '.__("<b>Do not</b> place it inside your uploads or plugins directory, as that will cause recursion (backups of backups of backups of...).", 'updraftplus');
?>
</td>
</tr>
<tr class="expertmode updraft-hidden" style="display:none;">
<th><?php _e("Use the server's SSL certificates", 'updraftplus');?>:</th>
<td><input data-updraft_settings_test="useservercerts" type="checkbox" id="updraft_ssl_useservercerts" name="updraft_ssl_useservercerts" value="1" <?php if (UpdraftPlus_Options::get_updraft_option('updraft_ssl_useservercerts')) echo 'checked="checked"'; ?>> <br><label for="updraft_ssl_useservercerts"><?php _e('By default UpdraftPlus uses its own store of SSL certificates to verify the identity of remote sites (i.e. to make sure it is talking to the real Dropbox, Amazon S3, etc., and not an attacker). We keep these up to date. However, if you get an SSL error, then choosing this option (which causes UpdraftPlus to use your web server\'s collection instead) may help.','updraftplus');?></label></td>
</tr>
<tr class="expertmode updraft-hidden" style="display:none;">
<th><?php _e('Do not verify SSL certificates','updraftplus');?>:</th>
<td><input data-updraft_settings_test="disableverify" type="checkbox" id="updraft_ssl_disableverify" name="updraft_ssl_disableverify" value="1" <?php if (UpdraftPlus_Options::get_updraft_option('updraft_ssl_disableverify')) echo 'checked="checked"'; ?>> <br><label for="updraft_ssl_disableverify"><?php _e('Choosing this option lowers your security by stopping UpdraftPlus from verifying the identity of encrypted sites that it connects to (e.g. Dropbox, Google Drive). It means that UpdraftPlus will be using SSL only for encryption of traffic, and not for authentication.','updraftplus');?> <?php _e('Note that not all cloud backup methods are necessarily using SSL authentication.', 'updraftplus');?></label></td>
</tr>
<tr class="expertmode updraft-hidden" style="display:none;">
<th><?php _e('Disable SSL entirely where possible', 'updraftplus');?>:</th>
<td><input data-updraft_settings_test="nossl" type="checkbox" id="updraft_ssl_nossl" name="updraft_ssl_nossl" value="1" <?php if (UpdraftPlus_Options::get_updraft_option('updraft_ssl_nossl')) echo 'checked="checked"'; ?>> <br><label for="updraft_ssl_nossl"><?php _e('Choosing this option lowers your security by stopping UpdraftPlus from using SSL for authentication and encrypted transport at all, where possible. Note that some cloud storage providers do not allow this (e.g. Dropbox), so with those providers this setting will have no effect.','updraftplus');?> <a href="https://updraftplus.com/faqs/i-get-ssl-certificate-errors-when-backing-up-andor-restoring/"><?php _e('See this FAQ also.', 'updraftplus');?></a></label></td>
</tr>
<?php do_action('updraftplus_configprint_expertoptions'); ?>
<tr>
<td></td>
<td>
<?php
$ws_ad = empty($options['include_adverts']) ? false : $updraftplus->wordshell_random_advert(1);
if ($ws_ad) {
?>
<p class="wordshell-advert">
<?php echo $ws_ad; ?>
</p>
<?php } ?>
</td>
</tr>
<?php if (!empty($options['include_save_button'])) { ?>
<tr>
<td></td>
<td>
<input type="hidden" name="action" value="update" />
<input type="submit" class="button-primary" id="updraftplus-settings-save" value="<?php _e('Save Changes','updraftplus');?>" />
</td>
</tr>
<?php } ?>
</table>
<?php
}
private function get_settings_js($method_objects, $really_is_writable, $updraft_dir) {
global $updraftplus;
ob_start();
?>
jQuery(document).ready(function() {
<?php
if (!$really_is_writable) echo "jQuery('.backupdirrow').show();\n";
?>
<?php
if (!empty($active_service)) {
if (is_array($active_service)) {
foreach ($active_service as $serv) {
echo "jQuery('.${serv}').show();\n";
}
} else {
echo "jQuery('.${active_service}').show();\n";
}
} else {
echo "jQuery('.none').show();\n";
}
foreach ($updraftplus->backup_methods as $method => $description) {
// already done: require_once(UPDRAFTPLUS_DIR.'/methods/'.$method.'.php');
$call_method = "UpdraftPlus_BackupModule_$method";
if (method_exists($call_method, 'config_print_javascript_onready')) {
$method_objects[$method]->config_print_javascript_onready();
}
}
?>
});
<?php
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}
// $include_more can be (bool) or (string)"sometimes"
public function files_selector_widgetry($prefix = '', $show_exclusion_options = true, $include_more = true) {
$ret = '';
global $updraftplus;
$backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
# The true (default value if non-existent) here has the effect of forcing a default of on.
$include_more_paths = UpdraftPlus_Options::get_updraft_option('updraft_include_more_path');
foreach ($backupable_entities as $key => $info) {
$included = (UpdraftPlus_Options::get_updraft_option("updraft_include_$key", apply_filters("updraftplus_defaultoption_include_".$key, true))) ? 'checked="checked"' : "";
if ('others' == $key || 'uploads' == $key) {
$data_toggle_exclude_field = $show_exclusion_options ? 'data-toggle_exclude_field="'.$key.'"' : '';
$ret .= '<input class="updraft_include_entity" id="'.$prefix.'updraft_include_'.$key.'" '.$data_toggle_exclude_field.' type="checkbox" name="updraft_include_'.$key.'" value="1" '.$included.'> <label '.(('others' == $key) ? 'title="'.sprintf(__('Your wp-content directory server path: %s', 'updraftplus'), WP_CONTENT_DIR).'" ' : '').' for="'.$prefix.'updraft_include_'.$key.'">'.(('others' == $key) ? __('Any other directories found inside wp-content', 'updraftplus') : htmlspecialchars($info['description'])).'</label><br>';
if ($show_exclusion_options) {
$include_exclude = UpdraftPlus_Options::get_updraft_option('updraft_include_'.$key.'_exclude', ('others' == $key) ? UPDRAFT_DEFAULT_OTHERS_EXCLUDE : UPDRAFT_DEFAULT_UPLOADS_EXCLUDE);
$display = ($included) ? '' : 'class="updraft-hidden" style="display:none;"';
$ret .= "<div id=\"".$prefix."updraft_include_".$key."_exclude\" $display>";
$ret .= '<label for="'.$prefix.'updraft_include_'.$key.'_exclude">'.__('Exclude these:', 'updraftplus').'</label>';
$ret .= '<input title="'.__('If entering multiple files/directories, then separate them with commas. For entities at the top level, you can use a * at the start or end of the entry as a wildcard.', 'updraftplus').'" type="text" id="'.$prefix.'updraft_include_'.$key.'_exclude" name="updraft_include_'.$key.'_exclude" size="54" value="'.htmlspecialchars($include_exclude).'" />';
$ret .= '<br></div>';
}
} else {
if ($key != 'more' || true === $include_more || ('sometimes' === $include_more && !empty($include_more_paths))) {
$data_toggle_exclude_field = $show_exclusion_options ? 'data-toggle_exclude_field="'.$key.'"' : '';
$ret .= "<input class=\"updraft_include_entity\" $data_toggle_exclude_field id=\"".$prefix."updraft_include_$key\" type=\"checkbox\" name=\"updraft_include_$key\" value=\"1\" $included /><label for=\"".$prefix."updraft_include_$key\"".((isset($info['htmltitle'])) ? ' title="'.htmlspecialchars($info['htmltitle']).'"' : '')."> ".htmlspecialchars($info['description']);
$ret .= "</label><br>";
$ret .= apply_filters("updraftplus_config_option_include_$key", '', $prefix);
}
}
}
return $ret;
}
public function show_double_warning($text, $extraclass = '', $echo = true) {
$ret = "<div class=\"error updraftplusmethod $extraclass\"><p>$text</p></div>";
$ret .= "<p class=\"double-warning\">$text</p>";
if ($echo) echo $ret;
return $ret;
}
public function optionfilter_split_every($value) {
$value = absint($value);
if ($value < UPDRAFTPLUS_SPLIT_MIN) $value = UPDRAFTPLUS_SPLIT_MIN;
return $value;
}
public function curl_check($service, $has_fallback = false, $extraclass = '', $echo = true) {
$ret = '';
// Check requirements
if (!function_exists("curl_init") || !function_exists('curl_exec')) {
$ret .= $this->show_double_warning('<strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__("Your web server's PHP installation does not included a <strong>required</strong> (for %s) module (%s). Please contact your web hosting provider's support and ask for them to enable it.", 'updraftplus'), $service, 'Curl').' ', $extraclass, false);
} else {
$curl_version = curl_version();
$curl_ssl_supported= ($curl_version['features'] & CURL_VERSION_SSL);
if (!$curl_ssl_supported) {
if ($has_fallback) {
$ret .= '<p><strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__("Your web server's PHP/Curl installation does not support https access. Communications with %s will be unencrypted. ask your web host to install Curl/SSL in order to gain the ability for encryption (via an add-on).",'updraftplus'),$service).'</p>';
} else {
$ret .= $this->show_double_warning('<p><strong>'.__('Warning','updraftplus').':</strong> '.sprintf(__("Your web server's PHP/Curl installation does not support https access. We cannot access %s without this support. Please contact your web hosting provider's support. %s <strong>requires</strong> Curl+https. Please do not file any support requests; there is no alternative.",'updraftplus'),$service).'</p>', $extraclass, false);
}
} else {
$ret .= '<p><em>'.sprintf(__("Good news: Your site's communications with %s can be encrypted. If you see any errors to do with encryption, then look in the 'Expert Settings' for more help.", 'updraftplus'),$service).'</em></p>';
}
}
if ($echo) {
echo $ret;
} else {
return $ret;
}
}
# If $basedirs is passed as an array, then $directorieses must be too
private function recursive_directory_size($directorieses, $exclude = array(), $basedirs = '', $format='text') {
$size = 0;
if (is_string($directorieses)) {
$basedirs = $directorieses;
$directorieses = array($directorieses);
}
if (is_string($basedirs)) $basedirs = array($basedirs);
foreach ($directorieses as $ind => $directories) {
if (!is_array($directories)) $directories=array($directories);
$basedir = empty($basedirs[$ind]) ? $basedirs[0] : $basedirs[$ind];
foreach ($directories as $dir) {
if (is_file($dir)) {
$size += @filesize($dir);
} else {
$suffix = ('' != $basedir) ? ((0 === strpos($dir, $basedir.'/')) ? substr($dir, 1+strlen($basedir)) : '') : '';
$size += $this->recursive_directory_size_raw($basedir, $exclude, $suffix);
}
}
}
if ('numeric' == $format) return $size;
global $updraftplus;
return $updraftplus->convert_numeric_size_to_text($size);
}
private function recursive_directory_size_raw($prefix_directory, &$exclude = array(), $suffix_directory = '') {
$directory = $prefix_directory.('' == $suffix_directory ? '' : '/'.$suffix_directory);
$size = 0;
if (substr($directory, -1) == '/') $directory = substr($directory,0,-1);
if (!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) return -1;
if (file_exists($directory.'/.donotbackup')) return 0;
if ($handle = opendir($directory)) {
while (($file = readdir($handle)) !== false) {
if ($file != '.' && $file != '..') {
$spath = ('' == $suffix_directory) ? $file : $suffix_directory.'/'.$file;
if (false !== ($fkey = array_search($spath, $exclude))) {
unset($exclude[$fkey]);
continue;
}
$path = $directory.'/'.$file;
if (is_file($path)) {
$size += filesize($path);
} elseif (is_dir($path)) {
$handlesize = $this->recursive_directory_size_raw($prefix_directory, $exclude, $suffix_directory.('' == $suffix_directory ? '' : '/').$file);
if ($handlesize >= 0) { $size += $handlesize; }# else { return -1; }
}
}
}
closedir($handle);
}
return $size;
}
private function raw_backup_info($backup_history, $key, $nonce) {
global $updraftplus;
$backup = $backup_history[$key];
$pretty_date = get_date_from_gmt(gmdate('Y-m-d H:i:s', (int)$key), 'M d, Y G:i');
$rawbackup = "<h2 title=\"$key\">$pretty_date</h2>";
if (!empty($backup['label'])) $rawbackup .= '<span class="raw-backup-info">'.$backup['label'].'</span>';
$rawbackup .= '<hr><p>';
$backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
if (!empty($nonce)) {
$jd = $updraftplus->jobdata_getarray($nonce);
} else {
$jd = array();
}
foreach ($backupable_entities as $type => $info) {
if (!isset($backup[$type])) continue;
$rawbackup .= $updraftplus->printfile($info['description'], $backup, $type, array('sha1'), $jd, true);
// $rawbackup .= '<h3>'.$info['description'].'</h3>';
// $files = is_string($backup[$type]) ? array($backup[$type]) : $backup[$type];
// foreach ($files as $index => $file) {
// $rawbackup .= $file.'<br>';
// }
}
$total_size = 0;
foreach ($backup as $ekey => $files) {
if ('db' == strtolower(substr($ekey, 0, 2)) && '-size' != substr($ekey, -5, 5)) {
$rawbackup .= $updraftplus->printfile(__('Database', 'updraftplus'), $backup, $ekey, array('sha1'), $jd, true);
}
if (!isset($backupable_entities[$ekey]) && ('db' != substr($ekey, 0, 2) || '-size' == substr($ekey, -5, 5))) continue;
if (is_string($files)) $files = array($files);
foreach ($files as $findex => $file) {
$size_key = (0 == $findex) ? $ekey.'-size' : $ekey.$findex.'-size';
$total_size = (false === $total_size || !isset($backup[$size_key]) || !is_numeric($backup[$size_key])) ? false : $total_size + $backup[$size_key];
}
}
$services = empty($backup['service']) ? array('none') : $backup['service'];
if (!is_array($services)) $services = array('none');
$rawbackup .= '<strong>'.__('Uploaded to:', 'updraftplus').'</strong> ';
$show_services = '';
foreach ($services as $serv) {
if ('none' == $serv || '' == $serv) {
$add_none = true;
} elseif (isset($updraftplus->backup_methods[$serv])) {
$show_services .= ($show_services) ? ', '.$updraftplus->backup_methods[$serv] : $updraftplus->backup_methods[$serv];
} else {
$show_services .= ($show_services) ? ', '.$serv : $serv;
}
}
if ('' == $show_services && $add_none) $show_services .= __('None', 'updraftplus');
$rawbackup .= $show_services;
if ($total_size !== false) {
$rawbackup .= '</p><strong>'.__('Total backup size:', 'updraftplus').'</strong> '.$updraftplus->convert_numeric_size_to_text($total_size).'<p>';
}
$rawbackup .= '</p><hr><p><pre>'.print_r($backup, true).'</p></pre>';
if (!empty($jd) && is_array($jd)) {
$rawbackup .= '<p><pre>'.print_r($jd, true).'</pre></p>';
}
return esc_attr($rawbackup);
}
private function existing_backup_table($backup_history = false) {
global $updraftplus;
if (false === $backup_history) $backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history');
if (!is_array($backup_history)) $backup_history=array();
if (empty($backup_history)) return "<p><em>".__('You have not yet made any backups.', 'updraftplus')."</em></p>";
$updraft_dir = $updraftplus->backups_dir_location();
$backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
$accept = apply_filters('updraftplus_accept_archivename', array());
if (!is_array($accept)) $accept = array();
$ret = '<table class="existing-backups-table">';
//".__('Actions', 'updraftplus')."
$ret .= "<thead>
<tr style=\"margin-bottom: 4px;\">
<th class=\"backup-date\">".__('Backup date', 'updraftplus')."</th>
<th class=\"backup-data\">".__('Backup data (click to download)', 'updraftplus')."</th>
<th class=\"updraft_backup_actions\">".__('Actions', 'updraftplus')."</th>
</tr>
<tr style=\"height:2px; padding:1px; margin:0px;\">
<td colspan=\"4\" style=\"margin:0; padding:0\"><div style=\"height: 2px; background-color:#888888;\"> </div></td>
</tr>
</thead>
<tbody>";
// $ret .= "<thead>
// </thead>
// <tbody>";
krsort($backup_history);
foreach ($backup_history as $key => $backup) {
$remote_sent = (!empty($backup['service']) && ((is_array($backup['service']) && in_array('remotesend', $backup['service'])) || 'remotesend' === $backup['service'])) ? true : false;
# https://core.trac.wordpress.org/ticket/25331 explains why the following line is wrong
# $pretty_date = date_i18n('Y-m-d G:i',$key);
// Convert to blog time zone
// $pretty_date = get_date_from_gmt(gmdate('Y-m-d H:i:s', (int)$key), 'Y-m-d G:i');
$pretty_date = get_date_from_gmt(gmdate('Y-m-d H:i:s', (int)$key), 'M d, Y G:i');
$esc_pretty_date = esc_attr($pretty_date);
$entities = '';
$non = $backup['nonce'];
$rawbackup = $this->raw_backup_info($backup_history, $key, $non);
$jobdata = $updraftplus->jobdata_getarray($non);
$delete_button = $this->delete_button($key, $non, $backup);
$date_label = $this->date_label($pretty_date, $key, $backup, $jobdata, $non);
$log_button = $this->log_button($backup);
// Remote backups with no log result in useless empty rows
// However, not showing anything messes up the "Existing Backups (14)" display, until we tweak that code to count differently
// if ($remote_sent && !$log_button) continue;
$ret .= <<<ENDHERE
<tr class="updraft_existing_backups_row updraft_existing_backups_row_$key" data-key="$key" data-nonce="$non">
<td class="updraft_existingbackup_date " data-rawbackup="$rawbackup">
$date_label
</td>
ENDHERE;
$ret .= "<td>";
if ($remote_sent) {
$ret .= __('Backup sent to remote site - not available for download.', 'updraftplus');
if (!empty($backup['remotesend_url'])) $ret .= '<br>'.__('Site', 'updraftplus').': '.htmlspecialchars($backup['remotesend_url']);
} else {
if (empty($backup['meta_foreign']) || !empty($accept[$backup['meta_foreign']]['separatedb'])) {
if (isset($backup['db'])) {
$entities .= '/db=0/';
// Set a flag according to whether or not $backup['db'] ends in .crypt, then pick this up in the display of the decrypt field.
$db = is_array($backup['db']) ? $backup['db'][0] : $backup['db'];
if ($updraftplus->is_db_encrypted($db)) $entities .= '/dbcrypted=1/';
$ret .= $this->download_db_button('db', $key, $esc_pretty_date, $backup, $accept);
} else {
// $ret .= sprintf(_x('(No %s)','Message shown when no such object is available','updraftplus'), __('database', 'updraftplus'));
}
# External databases
foreach ($backup as $bkey => $binfo) {
if ('db' == $bkey || 'db' != substr($bkey, 0, 2) || '-size' == substr($bkey, -5, 5)) continue;
$ret .= $this->download_db_button($bkey, $key, $esc_pretty_date, $backup);
}
} else {
# Foreign without separate db
$entities = '/db=0/meta_foreign=1/';
}
if (!empty($backup['meta_foreign']) && !empty($accept[$backup['meta_foreign']]) && !empty($accept[$backup['meta_foreign']]['separatedb'])) {
$entities .= '/meta_foreign=2/';
}
$download_buttons = $this->download_buttons($backup, $key, $accept, $entities, $esc_pretty_date);
$ret .= $download_buttons;
// $ret .="</td>";
// No logs expected for foreign backups
if (empty($backup['meta_foreign'])) {
// $ret .= '<td>'.$this->log_button($backup)."</td>";
}
}
$ret .= "</td>";
$ret .= '<td class="before-restore-button">';
$ret .= $this->restore_button($backup, $key, $pretty_date, $entities);
$ret .= $delete_button;
if (empty($backup['meta_foreign'])) $ret .= $log_button;
$ret .= '</td>';
$ret .= '</tr>';
$ret .= "<tr style=\"height:2px; padding:1px; margin:0px;\"><td colspan=\"4\" style=\"margin:0; padding:0\"><div style=\"height: 2px; background-color:#aaaaaa;\"> </div></td></tr>";
}
$ret .= '</tbody></table>';
return $ret;
}
private function download_db_button($bkey, $key, $esc_pretty_date, $backup, $accept = array()) {
if (!empty($backup['meta_foreign']) && isset($accept[$backup['meta_foreign']])) {
$desc_source = $accept[$backup['meta_foreign']]['desc'];
} else {
$desc_source = __('unknown source', 'updraftplus');
}
$ret = '';
if ('db' == $bkey) {
$dbt = empty($backup['meta_foreign']) ? esc_attr(__('Database','updraftplus')) : esc_attr(sprintf(__('Database (created by %s)', 'updraftplus'), $desc_source));
} else {
$dbt = __('External database','updraftplus').' ('.substr($bkey, 2).')';
}
$ret .= $this->download_button($bkey, $key, 0, null, '', $dbt, $esc_pretty_date, '0');
return $ret;
}
// Go through each of the file entities
private function download_buttons($backup, $key, $accept, &$entities, $esc_pretty_date) {
global $updraftplus;
$ret = '';
$backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
// $colspan = 1;
// if (!empty($backup['meta_foreign'])) {
// $colspan = 2;
// if (empty($accept[$backup['meta_foreign']]['separatedb'])) $colspan++;
// }
// $ret .= (1 == $colspan) ? '<td>' : '<td colspan="'.$colspan.'">';
$first_entity = true;
foreach ($backupable_entities as $type => $info) {
if (!empty($backup['meta_foreign']) && 'wpcore' != $type) continue;
// $colspan = 1;
// if (!empty($backup['meta_foreign'])) {
// $colspan = (1+count($backupable_entities));
// if (empty($accept[$backup['meta_foreign']]['separatedb'])) $colspan++;
// }
// $ret .= (1 == $colspan) ? '<td>' : '<td colspan="'.$colspan.'">';
$ide = '';
if ('wpcore' == $type) $wpcore_restore_descrip = $info['description'];
if (empty($backup['meta_foreign'])) {
$sdescrip = preg_replace('/ \(.*\)$/', '', $info['description']);
if (strlen($sdescrip) > 20 && isset($info['shortdescription'])) $sdescrip = $info['shortdescription'];
} else {
$info['description'] = 'WordPress';
if (isset($accept[$backup['meta_foreign']])) {
$desc_source = $accept[$backup['meta_foreign']]['desc'];
$ide .= sprintf(__('Backup created by: %s.', 'updraftplus'), $accept[$backup['meta_foreign']]['desc']).' ';
} else {
$desc_source = __('unknown source', 'updraftplus');
$ide .= __('Backup created by unknown source (%s) - cannot be restored.', 'updraftplus').' ';
}
$sdescrip = (empty($accept[$backup['meta_foreign']]['separatedb'])) ? sprintf(__('Files and database WordPress backup (created by %s)', 'updraftplus'), $desc_source) : sprintf(__('Files backup (created by %s)', 'updraftplus'), $desc_source);
if ('wpcore' == $type) $wpcore_restore_descrip = $sdescrip;
}
if (isset($backup[$type])) {
if (!is_array($backup[$type])) $backup[$type]=array($backup[$type]);
$howmanyinset = count($backup[$type]);
$expected_index = 0;
$index_missing = false;
$set_contents = '';
$entities .= "/$type=";
$whatfiles = $backup[$type];
ksort($whatfiles);
foreach ($whatfiles as $findex => $bfile) {
$set_contents .= ($set_contents == '') ? $findex : ",$findex";
if ($findex != $expected_index) $index_missing = true;
$expected_index++;
}
$entities .= $set_contents.'/';
if (!empty($backup['meta_foreign'])) {
$entities .= '/plugins=0//themes=0//uploads=0//others=0/';
}
$printing_first = true;
foreach ($whatfiles as $findex => $bfile) {
$pdescrip = ($findex > 0) ? $sdescrip.' ('.($findex+1).')' : $sdescrip;
if ($printing_first) {
$ide .= __('Press here to download', 'updraftplus').' '.strtolower($info['description']);
} else {
$ret .= '<div class="updraft-hidden" style="display:none;">';
}
if (count($backup[$type]) >0) {
if ($printing_first) $ide .= ' '.sprintf(__('(%d archive(s) in set).', 'updraftplus'), $howmanyinset);
}
if ($index_missing) {
if ($printing_first) $ide .= ' '.__('You appear to be missing one or more archives from this multi-archive set.', 'updraftplus');
}
if (!$first_entity) {
// $ret .= ', ';
} else {
$first_entity = false;
}
$ret .= $this->download_button($type, $key, $findex, $info, $ide, $pdescrip, $esc_pretty_date, $set_contents);
if (!$printing_first) {
$ret .= '</div>';
} else {
$printing_first = false;
}
}
} else {
// $ret .= sprintf(_x('(No %s)','Message shown when no such object is available','updraftplus'), preg_replace('/\s\(.{12,}\)/', '', strtolower($sdescrip)));
}
// $ret .= '</td>';
}
// $ret .= '</td>';
return $ret;
}
public function date_label($pretty_date, $key, $backup, $jobdata, $nonce, $simple_format = false) {
// $ret = apply_filters('updraftplus_showbackup_date', '<strong>'.$pretty_date.'</strong>', $backup, $jobdata, (int)$key);
$ret = apply_filters('updraftplus_showbackup_date', $pretty_date, $backup, $jobdata, (int)$key, $simple_format);
if (is_array($jobdata) && !empty($jobdata['resume_interval']) && (empty($jobdata['jobstatus']) || 'finished' != $jobdata['jobstatus'])) {
if ($simple_format) {
$ret .= ' '.__('(Not finished)', 'updraftplus');
} else {
$ret .= apply_filters('updraftplus_msg_unfinishedbackup', "<br><span title=\"".esc_attr(__('If you are seeing more backups than you expect, then it is probably because the deletion of old backup sets does not happen until a fresh backup completes.', 'updraftplus'))."\">".__('(Not finished)', 'updraftplus').'</span>', $jobdata, $nonce);
}
}
return $ret;
}
private function download_button($type, $backup_timestamp, $findex, $info, $title, $pdescrip, $esc_pretty_date, $set_contents) {
$ret = '';
$wp_nonce = wp_create_nonce('updraftplus_download');
// updraft_downloader(base, backup_timestamp, what, whicharea, set_contents, prettydate, async)
$ret .= '<button data-wp_nonce="'.esc_attr($wp_nonce).'" data-backup_timestamp="'.esc_attr($backup_timestamp).'" data-what="'.esc_attr($type).'" data-set_contents="'.esc_attr($set_contents).'" data-prettydate="'.esc_attr($esc_pretty_date).'" type="button" class="updraft_download_button '."uddownloadform_${type}_${backup_timestamp}_${findex}".'" title="'.$title.'">'.$pdescrip.'</button>';
// onclick="'."return updraft_downloader('uddlstatus_', '$backup_timestamp', '$type', '.ud_downloadstatus', '$set_contents', '$esc_pretty_date', true)".'"
return $ret;
}
private function restore_button($backup, $key, $pretty_date, $entities = '') {
$ret = '<div class="restore-button">';
if ($entities) {
$show_data = $pretty_date;
if (isset($backup['native']) && false == $backup['native']) {
$show_data .= ' '.__('(backup set imported from remote location)', 'updraftplus');
}
$ret .= '<button data-showdata="'.esc_attr($show_data).'" data-backup_timestamp="'.$key.'" data-entities="'.esc_attr($entities).'" title="'.__('After pressing this button, you will be given the option to choose which components you wish to restore','updraftplus').'" type="button" style="float:left; clear:none;" class="button-primary choose-components-button">'.__('Restore', 'updraftplus').'</button>';
}
$ret .= "</div>\n";
return $ret;
}
private function delete_button($key, $nonce, $backup) {
$sval = ((isset($backup['service']) && $backup['service'] != 'email' && $backup['service'] != 'none')) ? '1' : '0';
return '<div class="updraftplus-remove" style="float: left; clear: none;" data-hasremote="'.$sval.'">
<a data-hasremote="'.$sval.'" data-nonce="'.$nonce.'" data-key="'.$key.'" class="no-decoration updraft-delete-link" href="#" title="'.esc_attr(__('Delete this backup set', 'updraftplus')).'">'.__('Delete', 'updraftplus').'</a>
</div>';
}
private function log_button($backup) {
global $updraftplus;
$updraft_dir = $updraftplus->backups_dir_location();
$ret = '';
if (isset($backup['nonce']) && preg_match("/^[0-9a-f]{12}$/",$backup['nonce']) && is_readable($updraft_dir.'/log.'.$backup['nonce'].'.txt')) {
$nval = $backup['nonce'];
// $lt = esc_attr(__('View Log','updraftplus'));
$lt = __('View Log', 'updraftplus');
$url = esc_attr(UpdraftPlus_Options::admin_page()."?page=updraftplus&action=downloadlog&updraftplus_backup_nonce=$nval");
$ret .= <<<ENDHERE
<div style="clear:none;" class="updraft-viewlogdiv">
<a class="no-decoration updraft-log-link" href="$url" data-jobid="$nval">
$lt
</a>
<!--
<form action="$url" method="get">
<input type="hidden" name="action" value="downloadlog" />
<input type="hidden" name="page" value="updraftplus" />
<input type="hidden" name="updraftplus_backup_nonce" value="$nval" />
<input type="submit" value="$lt" class="updraft-log-link" onclick="event.preventDefault(); updraft_popuplog('$nval');" />
</form>
-->
</div>
ENDHERE;
return $ret;
} else {
// return str_replace(' ', ' ', '('.__('No backup log)', 'updraftplus').')');
}
}
// Return values: false = 'not yet' (not necessarily terminal); WP_Error = terminal failure; true = success
private function restore_backup($timestamp, $continuation_data = null) {
@set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);
global $wp_filesystem, $updraftplus;
$backup_history = UpdraftPlus_Options::get_updraft_option('updraft_backup_history');
if (!isset($backup_history[$timestamp]) || !is_array($backup_history[$timestamp])) {
echo '<p>'.__('This backup does not exist in the backup history - restoration aborted. Timestamp:','updraftplus')." $timestamp</p><br/>";
return new WP_Error('does_not_exist', __('Backup does not exist in the backup history', 'updraftplus'));
}
// request_filesystem_credentials passes on fields just via hidden name/value pairs.
// Build array of parameters to be passed via this
$extra_fields = array();
if (isset($_POST['updraft_restore']) && is_array($_POST['updraft_restore'])) {
foreach ($_POST['updraft_restore'] as $entity) {
$_POST['updraft_restore_'.$entity] = 1;
$extra_fields[] = 'updraft_restore_'.$entity;
}
}
if (is_array($continuation_data)) {
foreach ($continuation_data['second_loop_entities'] as $type => $files) {
$_POST['updraft_restore_'.$type] = 1;
if (!in_array('updraft_restore_'.$type, $extra_fields)) $extra_fields[] = 'updraft_restore_'.$type;
}
if (!empty($continuation_data['restore_options'])) $restore_options = $continuation_data['restore_options'];
}
// Now make sure that updraft_restorer_ option fields get passed along to request_filesystem_credentials
foreach ($_POST as $key => $value) {
if (0 === strpos($key, 'updraft_restorer_')) $extra_fields[] = $key;
}
$credentials = request_filesystem_credentials(UpdraftPlus_Options::admin_page()."?page=updraftplus&action=updraft_restore&backup_timestamp=$timestamp", '', false, false, $extra_fields);
WP_Filesystem($credentials);
if ( $wp_filesystem->errors->get_error_code() ) {
echo '<p><em><a href="https://updraftplus.com/faqs/asked-ftp-details-upon-restorationmigration-updates/">'.__('Why am I seeing this?', 'updraftplus').'</a></em></p>';
foreach ( $wp_filesystem->errors->get_error_messages() as $message ) show_message($message);
exit;
}
// If we make it this far then WP_Filesystem has been instantiated and is functional
# Set up logging
$updraftplus->backup_time_nonce();
$updraftplus->jobdata_set('job_type', 'restore');
$updraftplus->jobdata_set('job_time_ms', $updraftplus->job_time_ms);
$updraftplus->logfile_open($updraftplus->nonce);
# Provide download link for the log file
# TODO: Automatic purging of old log files
# TODO: Provide option to auto-email the log file
echo '<h1>'.__('UpdraftPlus Restoration: Progress', 'updraftplus').'</h1><div id="updraft-restore-progress">';
$this->show_admin_warning('<a target="_blank" href="?action=downloadlog&page=updraftplus&updraftplus_backup_nonce='.htmlspecialchars($updraftplus->nonce).'">'.__('Follow this link to download the log file for this restoration (needed for any support requests).', 'updraftplus').'</a>');
$updraft_dir = trailingslashit($updraftplus->backups_dir_location());
$foreign_known = apply_filters('updraftplus_accept_archivename', array());
$service = (isset($backup_history[$timestamp]['service'])) ? $backup_history[$timestamp]['service'] : false;
if (!is_array($service)) $service = array($service);
// Now, need to turn any updraft_restore_<entity> fields (that came from a potential WP_Filesystem form) back into parts of the _POST array (which we want to use)
if (empty($_POST['updraft_restore']) || (!is_array($_POST['updraft_restore']))) $_POST['updraft_restore'] = array();
$backup_set = $backup_history[$timestamp];
$entities_to_restore = array();
foreach ($_POST['updraft_restore'] as $entity) {
if (empty($backup_set['meta_foreign'])) {
$entities_to_restore[$entity] = $entity;
} else {
if ('db' == $entity && !empty($foreign_known[$backup_set['meta_foreign']]) && !empty($foreign_known[$backup_set['meta_foreign']]['separatedb'])) {
$entities_to_restore[$entity] = 'db';
} else {
$entities_to_restore[$entity] = 'wpcore';
}
}
}
foreach ($_POST as $key => $value) {
if (0 === strpos($key, 'updraft_restore_')) {
$nkey = substr($key, 16);
if (!isset($entities_to_restore[$nkey])) {
$_POST['updraft_restore'][] = $nkey;
if (empty($backup_set['meta_foreign'])) {
$entities_to_restore[$nkey] = $nkey;
} else {
if ('db' == $entity && !empty($foreign_known[$backup_set['meta_foreign']]['separatedb'])) {
$entities_to_restore[$nkey] = 'db';
} else {
$entities_to_restore[$nkey] = 'wpcore';
}
}
}
}
}
if (0 == count($_POST['updraft_restore'])) {
echo '<p>'.__('ABORT: Could not find the information on which entities to restore.', 'updraftplus').'</p>';
echo '<p>'.__('If making a request for support, please include this information:','updraftplus').' '.count($_POST).' : '.htmlspecialchars(serialize($_POST)).'</p>';
return new WP_Error('missing_info', 'Backup information not found');
}
$this->entities_to_restore = $entities_to_restore;
set_error_handler(array($updraftplus, 'php_error'), E_ALL & ~E_STRICT);
/*
$_POST['updraft_restore'] is typically something like: array( 0=>'db', 1=>'plugins', 2=>'themes'), etc.
i.e. array ( 'db', 'plugins', themes')
*/
if (empty($restore_options)) {
// Gather the restore optons into one place - code after here should read the options, and not the HTTP layer
$restore_options = array();
if (!empty($_POST['updraft_restorer_restore_options'])) {
parse_str(stripslashes($_POST['updraft_restorer_restore_options']), $restore_options);
}
$restore_options['updraft_restorer_replacesiteurl'] = empty($_POST['updraft_restorer_replacesiteurl']) ? false : true;
$restore_options['updraft_encryptionphrase'] = empty($_POST['updraft_encryptionphrase']) ? '' : (string)stripslashes($_POST['updraft_encryptionphrase']);
$restore_options['updraft_restorer_wpcore_includewpconfig'] = empty($_POST['updraft_restorer_wpcore_includewpconfig']) ? false : true;
$updraftplus->jobdata_set('restore_options', $restore_options);
}
// Restore in the most helpful order
uksort($backup_set, array($this, 'sort_restoration_entities'));
// Now log
$copy_restore_options = $restore_options;
if (!empty($copy_restore_options['updraft_encryptionphrase'])) $copy_restore_options['updraft_encryptionphrase'] = '***';
$updraftplus->log("Restore job started. Entities to restore: ".implode(', ', array_flip($entities_to_restore)).'. Restore options: '.json_encode($copy_restore_options));
$backup_set['timestamp'] = $timestamp;
$backupable_entities = $updraftplus->get_backupable_file_entities(true, true);
// Allow add-ons to adjust the restore directory (but only in the case of restore - otherwise, they could just use the filter built into UpdraftPlus::get_backupable_file_entities)
$backupable_entities = apply_filters('updraft_backupable_file_entities_on_restore', $backupable_entities, $restore_options, $backup_set);
// We use a single object for each entity, because we want to store information about the backup set
require_once(UPDRAFTPLUS_DIR.'/restorer.php');
global $updraftplus_restorer;
$updraftplus_restorer = new Updraft_Restorer(new Updraft_Restorer_Skin, $backup_set, false, $restore_options);
$second_loop = array();
echo "<h2>".__('Final checks', 'updraftplus').'</h2>';
if (empty($backup_set['meta_foreign'])) {
$entities_to_download = $entities_to_restore;
} else {
if (!empty($foreign_known[$backup_set['meta_foreign']]['separatedb'])) {
$entities_to_download = array();
if (in_array('db', $entities_to_restore)) {
$entities_to_download['db'] = 1;
}
if (count($entities_to_restore) > 1 || !in_array('db', $entities_to_restore)) {
$entities_to_download['wpcore'] = 1;
}
} else {
$entities_to_download = array('wpcore' => 1);
}
}
// First loop: make sure that files are present + readable; and populate array for second loop
foreach ($backup_set as $type => $files) {
// All restorable entities must be given explicitly, as we can store other arbitrary data in the history array
if (!isset($backupable_entities[$type]) && 'db' != $type) continue;
if (isset($backupable_entities[$type]['restorable']) && $backupable_entities[$type]['restorable'] == false) continue;
if (!isset($entities_to_download[$type])) continue;
if ('wpcore' == $type && is_multisite() && 0 === $updraftplus_restorer->ud_backup_is_multisite) {
echo "<p>$type: <strong>";
echo __('Skipping restoration of WordPress core when importing a single site into a multisite installation. If you had anything necessary in your WordPress directory then you will need to re-add it manually from the zip file.', 'updraftplus');
#TODO
#$updraftplus->log_e('Skipping restoration of WordPress core when importing a single site into a multisite installation. If you had anything necessary in your WordPress directory then you will need to re-add it manually from the zip file.');
echo "</strong></p>";
continue;
}
if (is_string($files)) $files=array($files);
foreach ($files as $ind => $file) {
$fullpath = $updraft_dir.$file;
echo sprintf(__("Looking for %s archive: file name: %s", 'updraftplus'), $type, htmlspecialchars($file))."<br>";
if (is_array($continuation_data) && isset($continuation_data['second_loop_entities'][$type]) && !in_array($file, $continuation_data['second_loop_entities'][$type])) {
echo __('Skipping: this archive was already restored.', 'updraftplus')."<br>";
// Set the marker so that the existing directory isn't moved out of the way
$updraftplus_restorer->been_restored[$type] = true;
continue;
}
add_action('http_request_args', array($updraftplus, 'modify_http_options'));
foreach ($service as $serv) {
if (!is_readable($fullpath)) {
$sd = (empty($updraftplus->backup_methods[$serv])) ? $serv : $updraftplus->backup_methods[$serv];
echo __("File is not locally present - needs retrieving from remote storage",'updraftplus')." ($sd)";
$this->download_file($file, $serv);
echo ": ";
if (!is_readable($fullpath)) {
echo __("Error", 'updraftplus');
} else {
echo __("OK", 'updraftplus');
}
echo '<br>';
}
}
remove_action('http_request_args', array($updraftplus, 'modify_http_options'));
$index = ($ind == 0) ? '' : $ind;
// If a file size is stored in the backup data, then verify correctness of the local file
if (isset($backup_history[$timestamp][$type.$index.'-size'])) {
$fs = $backup_history[$timestamp][$type.$index.'-size'];
echo __("Archive is expected to be size:",'updraftplus')." ".round($fs/1024, 1)." KB: ";
$as = @filesize($fullpath);
if ($as == $fs) {
echo __('OK','updraftplus').'<br>';
} else {
echo "<strong>".__('Error:','updraftplus')."</strong> ".__('file is size:', 'updraftplus')." ".round($as/1024)." ($fs, $as)<br>";
}
} else {
echo __("The backup records do not contain information about the proper size of this file.",'updraftplus')."<br>";
}
if (!is_readable($fullpath)) {
echo __('Could not find one of the files for restoration', 'updraftplus')." ($file)<br>";
$updraftplus->log("$file: ".__('Could not find one of the files for restoration', 'updraftplus'), 'error');
echo '</div>';
restore_error_handler();
return false;
}
}
if (empty($updraftplus_restorer->ud_foreign)) {
$types = array($type);
} else {
if ('db' != $type || empty($foreign_known[$updraftplus_restorer->ud_foreign]['separatedb'])) {
$types = array('wpcore');
} else {
$types = array('db');
}
}
foreach ($types as $check_type) {
$info = (isset($backupable_entities[$check_type])) ? $backupable_entities[$check_type] : array();
$val = $updraftplus_restorer->pre_restore_backup($files, $check_type, $info, $continuation_data);
if (is_wp_error($val)) {
$updraftplus->log_wp_error($val);
foreach ($val->get_error_messages() as $msg) {
echo '<strong>'.__('Error:', 'updraftplus').'</strong> '.htmlspecialchars($msg).'<br>';
}
foreach ($val->get_error_codes() as $code) {
if ('already_exists' == $code) $this->print_delete_old_dirs_form(false);
}
echo '</div>'; //close the updraft_restore_progress div even if we error
restore_error_handler();
return $val;
} elseif (false === $val) {
echo '</div>'; //close the updraft_restore_progress div even if we error
restore_error_handler();
return false;
}
}
foreach ($entities_to_restore as $entity => $via) {
if ($via == $type) {
if ('wpcore' == $via && 'db' == $entity && count($files) > 1) {
$second_loop[$entity] = apply_filters('updraftplus_select_wpcore_file_with_db', $files, $updraftplus_restorer->ud_foreign);
} else {
$second_loop[$entity] = $files;
}
}
}
}
$updraftplus_restorer->delete = (UpdraftPlus_Options::get_updraft_option('updraft_delete_local')) ? true : false;
if ('none' === $service || 'email' === $service || empty($service) || (is_array($service) && 1 == count($service) && (in_array('none', $service) || in_array('', $service) || in_array('email', $service))) || !empty($updraftplus_restorer->ud_foreign)) {
if ($updraftplus_restorer->delete) $updraftplus->log_e('Will not delete any archives after unpacking them, because there was no cloud storage for this backup');
$updraftplus_restorer->delete = false;
}
if (!empty($updraftplus_restorer->ud_foreign)) $updraftplus->log("Foreign backup; created by: ".$updraftplus_restorer->ud_foreign);
// Second loop: now actually do the restoration
uksort($second_loop, array($this, 'sort_restoration_entities'));
// If continuing, then prune those already done
if (is_array($continuation_data)) {
foreach ($second_loop as $type => $files) {
if (isset($continuation_data['second_loop_entities'][$type])) $second_loop[$type] = $continuation_data['second_loop_entities'][$type];
}
}
$updraftplus->jobdata_set('second_loop_entities', $second_loop);
$updraftplus->jobdata_set('backup_timestamp', $timestamp);
// use a site option, as otherwise on multisite when all the array of options is updated via UpdraftPlus_Options::update_site_option(), it will over-write any restored UD options from the backup
update_site_option('updraft_restore_in_progress', $updraftplus->nonce);
foreach ($second_loop as $type => $files) {
# Types: uploads, themes, plugins, others, db
$info = (isset($backupable_entities[$type])) ? $backupable_entities[$type] : array();
echo ('db' == $type) ? "<h2>".__('Database','updraftplus')."</h2>" : "<h2>".$info['description']."</h2>";
$updraftplus->log("Entity: ".$type);
if (is_string($files)) $files = array($files);
foreach ($files as $fkey => $file) {
$last_one = (1 == count($second_loop) && 1 == count($files));
$val = $updraftplus_restorer->restore_backup($file, $type, $info, $last_one);
if (is_wp_error($val)) {
$codes = $val->get_error_codes();
if (is_array($codes) && in_array('not_found', $codes) && !empty($updraftplus_restorer->ud_foreign) && apply_filters('updraftplus_foreign_allow_missing_entity', false, $type, $updraftplus_restorer->ud_foreign)) {
$updraftplus->log("Entity to move not found in this zip - but this is possible with this foreign backup type");
} else {
$updraftplus->log_e($val);
foreach ($val->get_error_messages() as $msg) {
echo '<strong>'.__('Error message', 'updraftplus').':</strong> '.htmlspecialchars($msg).'<br>';
}
$codes = $val->get_error_codes();
if (is_array($codes)) {
foreach ($codes as $code) {
$data = $val->get_error_data($code);
if (!empty($data)) {
$pdata = (is_string($data)) ? $data : serialize($data);
echo '<strong>'.__('Error data:', 'updraftplus').'</strong> '.htmlspecialchars($pdata).'<br>';
if (false !== strpos($pdata, 'PCLZIP_ERR_BAD_FORMAT (-10)')) {
echo '<a href="https://updraftplus.com/faqs/error-message-pclzip_err_bad_format-10-invalid-archive-structure-mean/"><strong>'.__('Please consult this FAQ for help on what to do about it.', 'updraftplus').'</strong></a><br>';
}
}
}
}
echo '</div>'; //close the updraft_restore_progress div even if we error
restore_error_handler();
return $val;
}
} elseif (false === $val) {
echo '</div>'; //close the updraft_restore_progress div even if we error
restore_error_handler();
return false;
}
unset($files[$fkey]);
$second_loop[$type] = $files;
$updraftplus->jobdata_set('second_loop_entities', $second_loop);
$updraftplus->jobdata_set('backup_timestamp', $timestamp);
do_action('updraft_restored_archive', $file, $type, $val, $fkey, $timestamp);
}
unset($second_loop[$type]);
update_site_option('updraft_restore_in_progress', $updraftplus->nonce);
$updraftplus->jobdata_set('second_loop_entities', $second_loop);
$updraftplus->jobdata_set('backup_timestamp', $timestamp);
}
// All done - remove
delete_site_option('updraft_restore_in_progress');
foreach (array('template', 'stylesheet', 'template_root', 'stylesheet_root') as $opt) {
add_filter('pre_option_'.$opt, array($this, 'option_filter_'.$opt));
}
# Clear any cached pages after the restore
$updraftplus_restorer->clear_cache();
if (!function_exists('validate_current_theme')) require_once(ABSPATH.WPINC.'/themes');
# Have seen a case where the current theme in the DB began with a capital, but not on disk - and this breaks migrating from Windows to a case-sensitive system
$template = get_option('template');
if (!empty($template) && $template != WP_DEFAULT_THEME && $template != strtolower($template)) {
$theme_root = get_theme_root($template);
$theme_root2 = get_theme_root(strtolower($template));
if (!file_exists("$theme_root/$template/style.css") && file_exists("$theme_root/".strtolower($template)."/style.css")) {
$updraftplus->log_e("Theme directory (%s) not found, but lower-case version exists; updating database option accordingly", $template);
update_option('template', strtolower($template));
}
}
if (!validate_current_theme()) {
echo '<strong>';
$updraftplus->log_e("The current theme was not found; to prevent this stopping the site from loading, your theme has been reverted to the default theme");
echo '</strong>';
}
echo '</div>'; //close the updraft_restore_progress div
restore_error_handler();
return true;
}
public function option_filter_template($val) { global $updraftplus; return $updraftplus->option_filter_get('template'); }
public function option_filter_stylesheet($val) { global $updraftplus; return $updraftplus->option_filter_get('stylesheet'); }
public function option_filter_template_root($val) { global $updraftplus; return $updraftplus->option_filter_get('template_root'); }
public function option_filter_stylesheet_root($val) { global $updraftplus; return $updraftplus->option_filter_get('stylesheet_root'); }
public function sort_restoration_entities($a, $b) {
if ($a == $b) return 0;
// Put the database first
// Put wpcore after plugins/uploads/themes (needed for restores of foreign all-in-one formats)
if ('db' == $a || 'wpcore' == $b) return -1;
if ('db' == $b || 'wpcore' == $a) return 1;
// After wpcore, next last is others
if ('others' == $b) return -1;
if ('others' == $a) return 1;
// And then uploads - this is only because we want to make sure uploads is after plugins, so that we know before we get to the uploads whether the version of UD which might have to unpack them can do this new-style or not.
if ('uploads' == $b) return -1;
if ('uploads' == $a) return 1;
return strcmp($a, $b);
}
public function return_array($input) {
if (!is_array($input)) $input = array();
return $input;
}
public function updraft_ajax_savesettings() {
global $updraftplus;
if (empty($_POST) || empty($_POST['subaction']) || 'savesettings' != $_POST['subaction'] || !isset($_POST['nonce']) || !is_user_logged_in() || !UpdraftPlus_Options::user_can_manage() || !wp_verify_nonce($_POST['nonce'], 'updraftplus-settings-nonce')) die('Security check');
if (empty($_POST['settings']) || !is_string($_POST['settings'])) die('Invalid data');
parse_str(stripslashes($_POST['settings']), $posted_settings);
// We now have $posted_settings as an array
echo json_encode($this->save_settings($posted_settings));
die;
}
private function backup_now_remote_message() {
global $updraftplus;
$service = $updraftplus->just_one(UpdraftPlus_Options::get_updraft_option('updraft_service'));
if (is_string($service)) $service = array($service);
if (!is_array($service)) $service = array();
$no_remote_configured = (empty($service) || array('none') === $service || array('') === $service) ? true : false;
if ($no_remote_configured) {
return '<input type="checkbox" disabled="disabled" id="backupnow_includecloud"> <em>'.sprintf(__("Backup won't be sent to any remote storage - none has been saved in the %s", 'updraftplus'), '<a href="'.UpdraftPlus_Options::admin_page_url().'?page=updraftplus&tab=settings" id="updraft_backupnow_gotosettings">'.__('settings', 'updraftplus')).'</a>. '.__('Not got any remote storage?', 'updraftplus').' <a href="https://updraftplus.com/landing/vault">'.__("Check out UpdraftPlus Vault.", 'updraftplus').'</a></em>';
} else {
return '<input type="checkbox" id="backupnow_includecloud" checked="checked"> <label for="backupnow_includecloud">'.__("Send this backup to remote storage", 'updraftplus').'</label>';
}
}
public function save_settings($settings) {
global $updraftplus;
// Make sure that settings filters are registered
UpdraftPlus_Options::admin_init();
$return_array = array('saved' => true);
$add_to_post_keys = array('updraft_interval', 'updraft_interval_database', 'updraft_starttime_files', 'updraft_starttime_db', 'updraft_startday_files', 'updraft_startday_db');
//If database and files are on same schedule, override the db day/time settings
if (isset($settings['updraft_interval_database']) && isset($settings['updraft_interval_database']) && $settings['updraft_interval_database'] == $settings['updraft_interval'] && isset($settings['updraft_starttime_files'])) {
$settings['updraft_starttime_db'] = $settings['updraft_starttime_files'];
$settings['updraft_startday_db'] = $settings['updraft_startday_files'];
}
foreach ($add_to_post_keys as $key) {
// For add-ons that look at $_POST to find saved settings, add the relevant keys to $_POST so that they find them there
if (isset($settings[$key])) {
$_POST[$key] = $settings[$key];
}
}
// Wipe the extra retention rules, as they are not saved correctly if the last one is deleted
UpdraftPlus_Options::update_updraft_option('updraft_retain_extrarules', array());
UpdraftPlus_Options::update_updraft_option('updraft_email', array());
UpdraftPlus_Options::update_updraft_option('updraft_report_warningsonly', array());
UpdraftPlus_Options::update_updraft_option('updraft_report_wholebackup', array());
UpdraftPlus_Options::update_updraft_option('updraft_extradbs', array());
UpdraftPlus_Options::update_updraft_option('updraft_include_more_path', array());
$relevant_keys = $updraftplus->get_settings_keys();
if (method_exists('UpdraftPlus_Options', 'mass_options_update')) {
$original_settings = $settings;
$settings = UpdraftPlus_Options::mass_options_update($settings);
$mass_updated = true;
}
foreach ($settings as $key => $value) {
// $exclude_keys = array('option_page', 'action', '_wpnonce', '_wp_http_referer');
// if (!in_array($key, $exclude_keys)) {
if (in_array($key, $relevant_keys)) {
if ($key == "updraft_service" && is_array($value)){
foreach ($value as $subkey => $subvalue){
if ($subvalue == '0') unset($value[$subkey]);
}
}
// This flag indicates that either the stored database option was changed, or that the supplied option was changed before being stored. It isn't comprehensive - it's only used to update some UI elements with invalid input.
$updated = empty($mass_updated) ? (is_string($value) && $value != UpdraftPlus_Options::get_updraft_option($key)) : (is_string($value) && (!isset($original_settings[$key]) || $original_settings[$key] != $value));
$db_updated = empty($mass_updated) ? UpdraftPlus_Options::update_updraft_option($key, $value) : true;
// Add information on what has changed to array to loop through to update links etc.
// Restricting to strings for now, to prevent any unintended leakage (since this is just used for UI updating)
if ($updated) {
$value = UpdraftPlus_Options::get_updraft_option($key);
if (is_string($value)) $return_array['changed'][$key] = $value;
}
} else {
// When last active, it was catching: option_page, action, _wpnonce, _wp_http_referer, updraft_s3_endpoint, updraft_dreamobjects_endpoint. The latter two are empty; probably don't need to be in the page at all.
//error_log("Non-UD key when saving from POSTed data: ".$key);
}
}
// Checking for various possible messages
$updraft_dir = $updraftplus->backups_dir_location(false);
$really_is_writable = $updraftplus->really_is_writable($updraft_dir);
$dir_info = $this->really_writable_message($really_is_writable, $updraft_dir);
$button_title = esc_attr(__('This button is disabled because your backup directory is not writable (see the settings).', 'updraftplus'));
$return_array['backup_now_message'] = $this->backup_now_remote_message();
$return_array['backup_dir'] = array('writable' => $really_is_writable, 'message' => $dir_info, 'button_title' => $button_title);
//Because of the single AJAX call, we need to remove the existing UD messages from the 'all_admin_notices' action
remove_all_actions('all_admin_notices');
//Moving from 2 to 1 ajax call
ob_start();
$service = UpdraftPlus_Options::get_updraft_option('updraft_service');
$this->setup_all_admin_notices_global($service);
$this->setup_all_admin_notices_udonly($service);
do_action('all_admin_notices');
if (!$really_is_writable){ //Check if writable
$this->show_admin_warning_unwritable();
}
if ($return_array['saved'] == true){ //
$this->show_admin_warning(__('Your settings have been saved.', 'updraftplus'), 'updated fade');
}
$messages_output = ob_get_contents();
ob_clean();
// Backup schedule output
$this->next_scheduled_backups_output();
$scheduled_output = ob_get_clean();
$return_array['messages'] = $messages_output;
$return_array['scheduled'] = $scheduled_output;
//*** Add the updated options to the return message, so we can update on screen ***\\
return $return_array;
}
}
| kfitz/plannedobsolescence | wp-content/plugins/updraftplus/admin.php | PHP | gpl-2.0 | 255,747 |
/*
* Created on 5 Sep 2007
*
* Copyright (c) 2004-2007 Paul John Leonard
*
* http://www.frinika.com
*
* This file is part of Frinika.
*
* Frinika 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.
* Frinika 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 Frinika; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.frinika.tootX.midi;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.ShortMessage;
public class MidiHashUtil {
static public long hashValue(ShortMessage mess) {
byte data[] = mess.getMessage();
long cmd = mess.getCommand();
if (cmd == ShortMessage.PITCH_BEND) {
return ((long) data[0] << 8);
} else {
return (((long) data[0] << 8) + data[1]);
}
}
static public void hashDisp(long hash) {
long cntrl = hash & 0xFF;
long cmd = (hash >> 8) & 0xFF;
long chn = (hash >> 16) & 0xFF;
System.out.println(chn + " " + cmd + " " + cntrl);
}
static ShortMessage reconstructShortMessage(long hash, ShortMessage mess) {
if (mess == null) mess=new ShortMessage();
int status = (int) ((hash >> 8) & 0xFF);
int data1 = (int) (hash & 0xFF);
try {
mess.setMessage(status, data1, 0);
} catch (InvalidMidiDataException ex) {
Logger.getLogger(MidiHashUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return mess;
}
}
| petersalomonsen/frinika | src/com/frinika/tootX/midi/MidiHashUtil.java | Java | gpl-2.0 | 2,069 |
#include <iostream>
using namespace std;
long long n, ans = 0;
long long dn[500][500];
long long rec(long long prlvl, long long sum)
{
if (sum < 0) return 0;
else if (sum == 0) return 1;
else
{
if (dn[prlvl][sum] != -1)
return dn[prlvl][sum];
else
{
long long res = 0;
for (int i = 1; i<prlvl; i++)
res += rec(i, sum - i);
return dn[prlvl][sum] = res;
}
}
}
void memorySet()
{
for (int i = 0; i<500; i++)
for (int j = 0; j<500; j++) dn[i][j] = -1;
}
int main()
{
memorySet();
cin >> n;
for (int i = 1; i<n; i++)
ans += rec(i, n - i);
cout << ans << endl;
} | Andriy963/e-olimp.com | acm.timus.1017.cpp | C++ | gpl-2.0 | 640 |
<?php
class Zend_View_Helper_WebSectionTemplate extends Zend_View_Helper_Abstract
{
public function webSectionTemplate($area)
{
$html = '';
$html.= '<div class="row-fluid">';
$html.= '<div class="span12">';
$html.= '<div class="page-header">';
$html.= '<h1>Header Layout Default</h1>';
$html.= '</div>';
$html.= '</div>';
$html.= '</div>';
$html.= '<div class="row-fluid">';
$html.= '<div class="span12">';
$html.= '<div class="page-header">';
$html.= '<h1>Menu <a href="/">'.$lang->translate('Home').'</a></h1>';
$html.= '</div>';
$html.= '</div>';
$html.= '</div>';
$html.= '<div class="row-fluid">';
$html.= '<div class="span6">';
$html.= '<div class="row-fluid">';
$html.= '<div class="page-header">';
$html.= '<h2>area 1</h2>';
$html.= $area[1];
$html.= '</div>';
$html.= '</div>';
$html.= '</div>';
$html.= '<div class="span6">';
$html.= '<div class="row-fluid">';
$html.= '<div class="page-header">';
$html.= '<h2>area 2</h2>';
$html.= $area[2];
$html.= '</div>';
$html.= '</div>';
$html.= '<div class="row-fluid">';
$html.= '<div class="page-header">';
$html.= '<h2>area 3</h2>';
$html.= $area[3];
$html.= '</div>';
$html.= '</div>';
$html.= '</div>';
$html.= '</div>';
//$html.= $area_1.' '.$area_2.' '.$area_3;
return $html;
}
} | AlexandrosV/beta-thesis | application/modules/default/views/helpers/WebSectionTemplate.php | PHP | gpl-2.0 | 1,478 |
var EFA = {
log: [],
/*
Prevent backspace being used as back button in infopath form in modal.
Source: http://johnliu.net/blog/2012/3/27/infopath-disabling-backspace-key-in-browser-form.html
grab a reference to the modal window object in SharePoint
*/
OpenPopUpPage: function( url ){
var options = SP.UI.$create_DialogOptions();
options.url = url;
var w = SP.UI.ModalDialog.showModalDialog(options);
/* Attempt to prevent backspace acting as navigation key on read only input - Doesn't currently work.
if (w) {
// get the modal window's iFrame element
var f = w.get_frameElement();
EFA.f = f;
// watch frame's readyState change - when page load is complete, re-attach keydown event
// on the new document
$(f).ready(function(){
var fwin = this.contentWindow || this.contentDocument;
$(fwin.document).on('focus',"input[readonly]",function(){ $(this).blur(); });
});
}*/
},
// get current user
checkCurrentUser: function (callback){
ExecuteOrDelayUntilScriptLoaded(checkCurrentUserLoaded, "sp.js");
function checkCurrentUserLoaded() {
var context = SP.ClientContext.get_current();
var siteColl = context.get_site();
var web = siteColl.get_rootWeb();
this._currentUser = web.get_currentUser();
context.load(this._currentUser);
context.executeQueryAsync(Function.createDelegate(this, callback),Function.createDelegate(this, callback));
}
},
CheckUserSucceeded: function(){
EFA['User'] = this._currentUser;
},
CheckUserfailed: function(){
//console.log('Failed to get user');
},
DoesUserHaveCreatePermissions: function(url, callback) {
var Xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\
<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\
<soap:Body>\
<DoesCurrentUserHavePermissionsToList xmlns=\"http://tempuri.org/\">\
<url>"+ url +"</url>\
</DoesCurrentUserHavePermissionsToList>\
</soap:Body>\
</soap:Envelope>";
$.ajax({
url: "/_layouts/EFA/EFAWebServices.asmx",
type: "POST",
dataType: "xml",
data: Xml,
complete: function(xData, Status){
if(Status != 'success')
throw "Failed to determine user permissions for " + url;
callback(xData);
},
contentType: "text/xml; charset=\"utf-8\""
});
}
};
/*
To access the mapping need to uses keys, therefore need to check if its available for browser and add it if not.
Then we can loop through the mapping like so:
$.each(keys(config.mapping), function(){ console.log(config.mapping[this.toString()]) });
using this to build the query and create the resultant html
*/
// SOURCE: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
var result = [];
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) result.push(prop);
}
if (hasDontEnumBug) {
for (var i=0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
}
}
return result;
};
})();
}
/*
Array.indexOf for IE
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
*/
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
'use strict';
if (this == null) {
throw new TypeError();
}
var n, k, t = Object(this),
len = t.length >>> 0;
if (len === 0) {
return -1;
}
n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
for (k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
/*
Test for Canvas Suppport
Source: http://stackoverflow.com/questions/2745432/best-way-to-detect-that-html5-canvas-is-not-supported/2746983#2746983
*/
function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
/*
Console.log() for IE 8
*/
(function() {
if (!window.console) {
window.console = {};
}
// union of Chrome, FF, IE, and Safari console methods
var m = [
"log", "info", "warn", "error", "debug", "trace", "dir", "group",
"groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd",
"dirxml", "assert", "count", "markTimeline", "timeStamp", "clear"
];
// define undefined methods as noops to prevent errors
for (var i = 0; i < m.length; i++) {
if (!window.console[m[i]]) {
window.console[m[i]] = function() {};
}
}
})();
| jwykeham/SharePoint-Bootstrap3-Master | TwitterBootstrapMasterPage/pkg/Debug/TwitterBootstrapMasterPage/Layouts/TB/js/helper.js | JavaScript | gpl-2.0 | 5,718 |
"""
Small event module
=======================
"""
import numpy as np
import logging
logger = logging.getLogger(__name__)
from ...utils.decorators import face_lookup
from ...geometry.sheet_geometry import SheetGeometry
from ...topology.sheet_topology import cell_division
from .actions import (
exchange,
remove,
merge_vertices,
detach_vertices,
increase,
decrease,
increase_linear_tension,
)
def reconnect(sheet, manager, **kwargs):
"""Performs reconnections (vertex merging / splitting) following Finegan et al. 2019
kwargs overwrite their corresponding `sheet.settings` entries
Keyword Arguments
-----------------
threshold_length : the threshold length at which vertex merging is performed
p_4 : the probability per unit time to perform a detachement from a rank 4 vertex
p_5p : the probability per unit time to perform a detachement from a rank 5 or more vertex
See Also
--------
**The tricellular vertex-specific adhesion molecule Sidekick
facilitates polarised cell intercalation during Drosophila axis
extension** _Tara M Finegan, Nathan Hervieux, Alexander
Nestor-Bergmann, Alexander G. Fletcher, Guy B Blanchard, Benedicte
Sanson_ bioRxiv 704932; doi: https://doi.org/10.1101/704932
"""
sheet.settings.update(kwargs)
nv = sheet.Nv
merge_vertices(sheet)
if nv != sheet.Nv:
logger.info(f"Merged {nv - sheet.Nv+1} vertices")
nv = sheet.Nv
retval = detach_vertices(sheet)
if retval:
logger.info("Failed to detach, skipping")
if nv != sheet.Nv:
logger.info(f"Detached {sheet.Nv - nv} vertices")
manager.append(reconnect, **kwargs)
default_division_spec = {
"face_id": -1,
"face": -1,
"growth_rate": 0.1,
"critical_vol": 2.0,
"geom": SheetGeometry,
}
@face_lookup
def division(sheet, manager, **kwargs):
"""Cell division happens through cell growth up to a critical volume,
followed by actual division of the face.
Parameters
----------
sheet : a `Sheet` object
manager : an `EventManager` instance
face_id : int,
index of the mother face
growth_rate : float, default 0.1
rate of increase of the prefered volume
critical_vol : float, default 2.
volume at which the cells stops to grow and devides
"""
division_spec = default_division_spec
division_spec.update(**kwargs)
face = division_spec["face"]
division_spec["critical_vol"] *= sheet.specs["face"]["prefered_vol"]
print(sheet.face_df.loc[face, "vol"], division_spec["critical_vol"])
if sheet.face_df.loc[face, "vol"] < division_spec["critical_vol"]:
increase(
sheet, "face", face, division_spec["growth_rate"], "prefered_vol", True
)
manager.append(division, **division_spec)
else:
daughter = cell_division(sheet, face, division_spec["geom"])
sheet.face_df.loc[daughter, "id"] = sheet.face_df.id.max() + 1
default_contraction_spec = {
"face_id": -1,
"face": -1,
"contractile_increase": 1.0,
"critical_area": 1e-2,
"max_contractility": 10,
"multiply": False,
"contraction_column": "contractility",
"unique": True,
}
@face_lookup
def contraction(sheet, manager, **kwargs):
"""Single step contraction event."""
contraction_spec = default_contraction_spec
contraction_spec.update(**kwargs)
face = contraction_spec["face"]
if (sheet.face_df.loc[face, "area"] < contraction_spec["critical_area"]) or (
sheet.face_df.loc[face, contraction_spec["contraction_column"]]
> contraction_spec["max_contractility"]
):
return
increase(
sheet,
"face",
face,
contraction_spec["contractile_increase"],
contraction_spec["contraction_column"],
contraction_spec["multiply"],
)
default_type1_transition_spec = {
"face_id": -1,
"face": -1,
"critical_length": 0.1,
"geom": SheetGeometry,
}
@face_lookup
def type1_transition(sheet, manager, **kwargs):
"""Custom type 1 transition event that tests if
the the shorter edge of the face is smaller than
the critical length.
"""
type1_transition_spec = default_type1_transition_spec
type1_transition_spec.update(**kwargs)
face = type1_transition_spec["face"]
edges = sheet.edge_df[sheet.edge_df["face"] == face]
if min(edges["length"]) < type1_transition_spec["critical_length"]:
exchange(sheet, face, type1_transition_spec["geom"])
default_face_elimination_spec = {"face_id": -1, "face": -1, "geom": SheetGeometry}
@face_lookup
def face_elimination(sheet, manager, **kwargs):
"""Removes the face with if face_id from the sheet."""
face_elimination_spec = default_face_elimination_spec
face_elimination_spec.update(**kwargs)
remove(sheet, face_elimination_spec["face"], face_elimination_spec["geom"])
default_check_tri_face_spec = {"geom": SheetGeometry}
def check_tri_faces(sheet, manager, **kwargs):
"""Three neighbourghs cell elimination
Add all cells with three neighbourghs in the manager
to be eliminated at the next time step.
Parameters
----------
sheet : a :class:`tyssue.sheet` object
manager : a :class:`tyssue.events.EventManager` object
"""
check_tri_faces_spec = default_check_tri_face_spec
check_tri_faces_spec.update(**kwargs)
tri_faces = sheet.face_df[(sheet.face_df["num_sides"] < 4)].id
manager.extend(
[
(face_elimination, {"face_id": f, "geom": check_tri_faces_spec["geom"]})
for f in tri_faces
]
)
default_contraction_line_tension_spec = {
"face_id": -1,
"face": -1,
"shrink_rate": 1.05,
"contractile_increase": 1.0,
"critical_area": 1e-2,
"max_contractility": 10,
"multiply": True,
"contraction_column": "line_tension",
"unique": True,
}
@face_lookup
def contraction_line_tension(sheet, manager, **kwargs):
"""
Single step contraction event
"""
contraction_spec = default_contraction_line_tension_spec
contraction_spec.update(**kwargs)
face = contraction_spec["face"]
if sheet.face_df.loc[face, "area"] < contraction_spec["critical_area"]:
return
# reduce prefered_area
decrease(
sheet,
"face",
face,
contraction_spec["shrink_rate"],
col="prefered_area",
divide=True,
bound=contraction_spec["critical_area"] / 2,
)
increase_linear_tension(
sheet,
face,
contraction_spec["contractile_increase"],
multiply=contraction_spec["multiply"],
isotropic=True,
limit=100,
)
| CellModels/tyssue | tyssue/behaviors/sheet/basic_events.py | Python | gpl-2.0 | 6,721 |
#include "BitArray.h"
namespace Rapid {
void BitArrayT::append(char const * Bytes, std::size_t Size)
{
mBytes.append(Bytes, Size);
}
std::size_t BitArrayT::size() const
{
return mBytes.size() * 8;
}
bool BitArrayT::operator[](std::size_t Index) const
{
auto ByteIndex = Index / 8;
auto BitIndex = Index % 8;
return static_cast<std::uint8_t>(mBytes[ByteIndex]) >> BitIndex & 0x1;
}
}
| abma/pr-downloader | src/rapid/BitArray.cpp | C++ | gpl-2.0 | 393 |
package org.compiere.dbPort;
import java.util.Collections;
import java.util.List;
/**
* Native PostgreSQL (pass-through) implementation of {@link Convert}
*
* @author tsa
*
*/
public final class Convert_PostgreSQL_Native extends Convert
{
@Override
protected final List<String> convertStatement(final String sqlStatement)
{
return Collections.singletonList(sqlStatement);
}
}
| klst-com/metasfresh | de.metas.adempiere.adempiere/base/src/main/java-legacy/org/compiere/dbPort/Convert_PostgreSQL_Native.java | Java | gpl-2.0 | 393 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MediaBrowser.Api.Reports
{
public class ReportRow
{
/// <summary>
/// Initializes a new instance of the ReportRow class.
/// </summary>
public ReportRow()
{
Columns = new List<ReportItem>();
}
/// <summary> Gets or sets the identifier. </summary>
/// <value> The identifier. </value>
public string Id { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this object has backdrop image. </summary>
/// <value> true if this object has backdrop image, false if not. </value>
public bool HasImageTagsBackdrop { get; set; }
/// <summary> Gets or sets a value indicating whether this object has image tags. </summary>
/// <value> true if this object has image tags, false if not. </value>
public bool HasImageTagsPrimary { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this object has image tags logo. </summary>
/// <value> true if this object has image tags logo, false if not. </value>
public bool HasImageTagsLogo { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this object has local trailer. </summary>
/// <value> true if this object has local trailer, false if not. </value>
public bool HasLocalTrailer { get; set; }
/// <summary> Gets or sets a value indicating whether this object has lock data. </summary>
/// <value> true if this object has lock data, false if not. </value>
public bool HasLockData { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this object has embedded image. </summary>
/// <value> true if this object has embedded image, false if not. </value>
public bool HasEmbeddedImage { get; set; }
/// <summary> Gets or sets a value indicating whether this object has subtitles. </summary>
/// <value> true if this object has subtitles, false if not. </value>
public bool HasSubtitles { get; set; }
/// <summary> Gets or sets a value indicating whether this object has specials. </summary>
/// <value> true if this object has specials, false if not. </value>
public bool HasSpecials { get; set; }
/// <summary> Gets or sets a value indicating whether this object is unidentified. </summary>
/// <value> true if this object is unidentified, false if not. </value>
public bool IsUnidentified { get; set; }
/// <summary> Gets or sets the columns. </summary>
/// <value> The columns. </value>
public List<ReportItem> Columns { get; set; }
/// <summary> Gets or sets the type. </summary>
/// <value> The type. </value>
public ReportIncludeItemTypes RowType { get; set; }
/// <summary> Gets or sets the identifier of the user. </summary>
/// <value> The identifier of the user. </value>
public string UserId { get; set; }
}
}
| mtlott/Emby | MediaBrowser.Api/Reports/Model/ReportRow.cs | C# | gpl-2.0 | 2,891 |
<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2013 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think\Db\Driver;
use Think\Db;
defined('THINK_PATH') or exit();
/**
* Mongo数据库驱动 必须配合MongoModel使用
*/
class Mongo extends Db{
protected $_mongo = null; // MongoDb Object
protected $_collection = null; // MongoCollection Object
protected $_dbName = ''; // dbName
protected $_collectionName = ''; // collectionName
protected $_cursor = null; // MongoCursor Object
protected $comparison = array('neq'=>'ne','ne'=>'ne','gt'=>'gt','egt'=>'gte','gte'=>'gte','lt'=>'lt','elt'=>'lte','lte'=>'lte','in'=>'in','not in'=>'nin','nin'=>'nin');
/**
* 架构函数 读取数据库配置信息
* @access public
* @param array $config 数据库配置数组
*/
public function __construct($config=''){
if ( !class_exists('mongoClient') ) {
throw_exception(L('_NOT_SUPPERT_').':mongoClient');
}
if(!empty($config)) {
$this->config = $config;
if(empty($this->config['params'])) {
$this->config['params'] = array();
}
}
}
/**
* 连接数据库方法
* @access public
*/
public function connect($config='',$linkNum=0) {
if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config;
$host = 'mongodb://'.($config['username']?"{$config['username']}":'').($config['password']?":{$config['password']}@":'').$config['hostname'].($config['hostport']?":{$config['hostport']}":'').'/'.($config['database']?"{$config['database']}":'');
try{
$this->linkID[$linkNum] = new \mongoClient( $host,$config['params']);
}catch (\MongoConnectionException $e){
throw_exception($e->getmessage());
}
// 标记连接成功
$this->connected = true;
// 注销数据库连接配置信息
if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
}
return $this->linkID[$linkNum];
}
/**
* 切换当前操作的Db和Collection
* @access public
* @param string $collection collection
* @param string $db db
* @param boolean $master 是否主服务器
* @return void
*/
public function switchCollection($collection,$db='',$master=true){
// 当前没有连接 则首先进行数据库连接
if ( !$this->_linkID ) $this->initConnect($master);
try{
if(!empty($db)) { // 传人Db则切换数据库
// 当前MongoDb对象
$this->_dbName = $db;
$this->_mongo = $this->_linkID->selectDb($db);
}
// 当前MongoCollection对象
if(C('DB_SQL_LOG')) {
$this->queryStr = $this->_dbName.'.getCollection('.$collection.')';
}
if($this->_collectionName != $collection) {
N('db_read',1);
// 记录开始执行时间
G('queryStartTime');
$this->_collection = $this->_mongo->selectCollection($collection);
$this->debug();
$this->_collectionName = $collection; // 记录当前Collection名称
}
}catch (MongoException $e){
throw_exception($e->getMessage());
}
}
/**
* 释放查询结果
* @access public
*/
public function free() {
$this->_cursor = null;
}
/**
* 执行命令
* @access public
* @param array $command 指令
* @return array
*/
public function command($command=array()) {
N('db_write',1);
$this->queryStr = 'command:'.json_encode($command);
// 记录开始执行时间
G('queryStartTime');
$result = $this->_mongo->command($command);
$this->debug();
if(!$result['ok']) {
throw_exception($result['errmsg']);
}
return $result;
}
/**
* 执行语句
* @access public
* @param string $code sql指令
* @param array $args 参数
* @return mixed
*/
public function execute($code,$args=array()) {
N('db_write',1);
$this->queryStr = 'execute:'.$code;
// 记录开始执行时间
G('queryStartTime');
$result = $this->_mongo->execute($code,$args);
$this->debug();
if($result['ok']) {
return $result['retval'];
}else{
throw_exception($result['errmsg']);
}
}
/**
* 关闭数据库
* @access public
*/
public function close() {
if($this->_linkID) {
$this->_linkID->close();
$this->_linkID = null;
$this->_mongo = null;
$this->_collection = null;
$this->_cursor = null;
}
}
/**
* 数据库错误信息
* @access public
* @return string
*/
public function error() {
$this->error = $this->_mongo->lastError();
trace($this->error,'','ERR');
return $this->error;
}
/**
* 插入记录
* @access public
* @param mixed $data 数据
* @param array $options 参数表达式
* @param boolean $replace 是否replace
* @return false | integer
*/
public function insert($data,$options=array(),$replace=false) {
if(isset($options['table'])) {
$this->switchCollection($options['table']);
}
$this->model = $options['model'];
N('db_write',1);
if(C('DB_SQL_LOG')) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.insert(';
$this->queryStr .= $data?json_encode($data):'{}';
$this->queryStr .= ')';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $replace? $this->_collection->save($data): $this->_collection->insert($data);
$this->debug();
if($result) {
$_id = $data['_id'];
if(is_object($_id)) {
$_id = $_id->__toString();
}
$this->lastInsID = $_id;
}
return $result;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
* 插入多条记录
* @access public
* @param array $dataList 数据
* @param array $options 参数表达式
* @return bool
*/
public function insertAll($dataList,$options=array()) {
if(isset($options['table'])) {
$this->switchCollection($options['table']);
}
$this->model = $options['model'];
N('db_write',1);
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->batchInsert($dataList);
$this->debug();
return $result;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
* 生成下一条记录ID 用于自增非MongoId主键
* @access public
* @param string $pk 主键名
* @return integer
*/
public function mongo_next_id($pk) {
N('db_read',1);
if(C('DB_SQL_LOG')) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.find({},{'.$pk.':1}).sort({'.$pk.':-1}).limit(1)';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->find(array(),array($pk=>1))->sort(array($pk=>-1))->limit(1);
$this->debug();
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
$data = $result->getNext();
return isset($data[$pk])?$data[$pk]+1:1;
}
/**
* 更新记录
* @access public
* @param mixed $data 数据
* @param array $options 表达式
* @return bool
*/
public function update($data,$options) {
if(isset($options['table'])) {
$this->switchCollection($options['table']);
}
$this->model = $options['model'];
N('db_write',1);
$query = $this->parseWhere($options['where']);
$set = $this->parseSet($data);
if(C('DB_SQL_LOG')) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.update(';
$this->queryStr .= $query?json_encode($query):'{}';
$this->queryStr .= ','.json_encode($set).')';
}
try{
// 记录开始执行时间
G('queryStartTime');
if(isset($options['limit']) && $options['limit'] == 1) {
$multiple = array("multiple" => false);
}else{
$multiple = array("multiple" => true);
}
$result = $this->_collection->update($query,$set,$multiple);
$this->debug();
return $result;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
* 删除记录
* @access public
* @param array $options 表达式
* @return false | integer
*/
public function delete($options=array()) {
if(isset($options['table'])) {
$this->switchCollection($options['table']);
}
$query = $this->parseWhere($options['where']);
$this->model = $options['model'];
N('db_write',1);
if(C('DB_SQL_LOG')) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.remove('.json_encode($query).')';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->remove($query);
$this->debug();
return $result;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
* 清空记录
* @access public
* @param array $options 表达式
* @return false | integer
*/
public function clear($options=array()){
if(isset($options['table'])) {
$this->switchCollection($options['table']);
}
$this->model = $options['model'];
N('db_write',1);
if(C('DB_SQL_LOG')) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.remove({})';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->drop();
$this->debug();
return $result;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
* 查找记录
* @access public
* @param array $options 表达式
* @return iterator
*/
public function select($options=array()) {
if(isset($options['table'])) {
$this->switchCollection($options['table'],'',false);
}
$cache = isset($options['cache'])?$options['cache']:false;
if($cache) { // 查询缓存检测
$key = is_string($cache['key'])?$cache['key']:md5(serialize($options));
$value = S($key,'','',$cache['type']);
if(false !== $value) {
return $value;
}
}
$this->model = $options['model'];
N('db_query',1);
$query = $this->parseWhere($options['where']);
$field = $this->parseField($options['field']);
try{
if(C('DB_SQL_LOG')) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.find(';
$this->queryStr .= $query? json_encode($query):'{}';
$this->queryStr .= $field? ','.json_encode($field):'';
$this->queryStr .= ')';
}
// 记录开始执行时间
G('queryStartTime');
$_cursor = $this->_collection->find($query,$field);
if($options['order']) {
$order = $this->parseOrder($options['order']);
if(C('DB_SQL_LOG')) {
$this->queryStr .= '.sort('.json_encode($order).')';
}
$_cursor = $_cursor->sort($order);
}
if(isset($options['page'])) { // 根据页数计算limit
if(strpos($options['page'],',')) {
list($page,$length) = explode(',',$options['page']);
}else{
$page = $options['page'];
}
$page = $page?$page:1;
$length = isset($length)?$length:(is_numeric($options['limit'])?$options['limit']:20);
$offset = $length*((int)$page-1);
$options['limit'] = $offset.','.$length;
}
if(isset($options['limit'])) {
list($offset,$length) = $this->parseLimit($options['limit']);
if(!empty($offset)) {
if(C('DB_SQL_LOG')) {
$this->queryStr .= '.skip('.intval($offset).')';
}
$_cursor = $_cursor->skip(intval($offset));
}
if(C('DB_SQL_LOG')) {
$this->queryStr .= '.limit('.intval($length).')';
}
$_cursor = $_cursor->limit(intval($length));
}
$this->debug();
$this->_cursor = $_cursor;
$resultSet = iterator_to_array($_cursor);
if($cache && $resultSet ) { // 查询缓存写入
S($key,$resultSet,$cache['expire'],$cache['type']);
}
return $resultSet;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
* 查找某个记录
* @access public
* @param array $options 表达式
* @return array
*/
public function find($options=array()){
if(isset($options['table'])) {
$this->switchCollection($options['table'],'',false);
}
$cache = isset($options['cache'])?$options['cache']:false;
if($cache) { // 查询缓存检测
$key = is_string($cache['key'])?$cache['key']:md5(serialize($options));
$value = S($key,'','',$cache['type']);
if(false !== $value) {
return $value;
}
}
$this->model = $options['model'];
N('db_query',1);
$query = $this->parseWhere($options['where']);
$fields = $this->parseField($options['field']);
if(C('DB_SQL_LOG')) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.findOne(';
$this->queryStr .= $query?json_encode($query):'{}';
$this->queryStr .= $fields?','.json_encode($fields):'';
$this->queryStr .= ')';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->findOne($query,$fields);
$this->debug();
if($cache && $result ) { // 查询缓存写入
S($key,$result,$cache['expire'],$cache['type']);
}
return $result;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
* 统计记录数
* @access public
* @param array $options 表达式
* @return iterator
*/
public function count($options=array()){
if(isset($options['table'])) {
$this->switchCollection($options['table'],'',false);
}
$this->model = $options['model'];
N('db_query',1);
$query = $this->parseWhere($options['where']);
if(C('DB_SQL_LOG')) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName;
$this->queryStr .= $query?'.find('.json_encode($query).')':'';
$this->queryStr .= '.count()';
}
try{
// 记录开始执行时间
G('queryStartTime');
$count = $this->_collection->count($query);
$this->debug();
return $count;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
public function group($keys,$initial,$reduce,$options=array()){
$this->_collection->group($keys,$initial,$reduce,$options);
}
/**
* 取得数据表的字段信息
* @access public
* @return array
*/
public function getFields($collection=''){
if(!empty($collection) && $collection != $this->_collectionName) {
$this->switchCollection($collection,'',false);
}
N('db_query',1);
if(C('DB_SQL_LOG')) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.findOne()';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->findOne();
$this->debug();
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
if($result) { // 存在数据则分析字段
$info = array();
foreach ($result as $key=>$val){
$info[$key] = array(
'name'=>$key,
'type'=>getType($val),
);
}
return $info;
}
// 暂时没有数据 返回false
return false;
}
/**
* 取得当前数据库的collection信息
* @access public
*/
public function getTables(){
if(C('DB_SQL_LOG')) {
$this->queryStr = $this->_dbName.'.getCollenctionNames()';
}
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$list = $this->_mongo->listCollections();
$this->debug();
$info = array();
foreach ($list as $collection){
$info[] = $collection->getName();
}
return $info;
}
/**
* set分析
* @access protected
* @param array $data
* @return string
*/
protected function parseSet($data) {
$result = array();
foreach ($data as $key=>$val){
if(is_array($val)) {
switch($val[0]) {
case 'inc':
$result['$inc'][$key] = (int)$val[1];
break;
case 'set':
case 'unset':
case 'push':
case 'pushall':
case 'addtoset':
case 'pop':
case 'pull':
case 'pullall':
$result['$'.$val[0]][$key] = $val[1];
break;
default:
$result['$set'][$key] = $val;
}
}else{
$result['$set'][$key] = $val;
}
}
return $result;
}
/**
* order分析
* @access protected
* @param mixed $order
* @return array
*/
protected function parseOrder($order) {
if(is_string($order)) {
$array = explode(',',$order);
$order = array();
foreach ($array as $key=>$val){
$arr = explode(' ',trim($val));
if(isset($arr[1])) {
$arr[1] = $arr[1]=='asc'?1:-1;
}else{
$arr[1] = 1;
}
$order[$arr[0]] = $arr[1];
}
}
return $order;
}
/**
* limit分析
* @access protected
* @param mixed $limit
* @return array
*/
protected function parseLimit($limit) {
if(strpos($limit,',')) {
$array = explode(',',$limit);
}else{
$array = array(0,$limit);
}
return $array;
}
/**
* field分析
* @access protected
* @param mixed $fields
* @return array
*/
public function parseField($fields){
if(empty($fields)) {
$fields = array();
}
if(is_string($fields)) {
$fields = explode(',',$fields);
}
return $fields;
}
/**
* where分析
* @access protected
* @param mixed $where
* @return array
*/
public function parseWhere($where){
$query = array();
foreach ($where as $key=>$val){
if('_id' != $key && 0===strpos($key,'_')) {
// 解析特殊条件表达式
$query = $this->parseThinkWhere($key,$val);
}else{
// 查询字段的安全过滤
if(!preg_match('/^[A-Z_\|\&\-.a-z0-9]+$/',trim($key))){
throw_exception(L('_ERROR_QUERY_').':'.$key);
}
$key = trim($key);
if(strpos($key,'|')) {
$array = explode('|',$key);
$str = array();
foreach ($array as $k){
$str[] = $this->parseWhereItem($k,$val);
}
$query['$or'] = $str;
}elseif(strpos($key,'&')){
$array = explode('&',$key);
$str = array();
foreach ($array as $k){
$str[] = $this->parseWhereItem($k,$val);
}
$query = array_merge($query,$str);
}else{
$str = $this->parseWhereItem($key,$val);
$query = array_merge($query,$str);
}
}
}
return $query;
}
/**
* 特殊条件分析
* @access protected
* @param string $key
* @param mixed $val
* @return string
*/
protected function parseThinkWhere($key,$val) {
$query = array();
switch($key) {
case '_query': // 字符串模式查询条件
parse_str($val,$query);
if(isset($query['_logic']) && strtolower($query['_logic']) == 'or' ) {
unset($query['_logic']);
$query['$or'] = $query;
}
break;
case '_string':// MongoCode查询
$query['$where'] = new MongoCode($val);
break;
}
return $query;
}
/**
* where子单元分析
* @access protected
* @param string $key
* @param mixed $val
* @return array
*/
protected function parseWhereItem($key,$val) {
$query = array();
if(is_array($val)) {
if(is_string($val[0])) {
$con = strtolower($val[0]);
if(in_array($con,array('neq','ne','gt','egt','gte','lt','lte','elt'))) { // 比较运算
$k = '$'.$this->comparison[$con];
$query[$key] = array($k=>$val[1]);
}elseif('like'== $con){ // 模糊查询 采用正则方式
$query[$key] = new MongoRegex("/".$val[1]."/");
}elseif('mod'==$con){ // mod 查询
$query[$key] = array('$mod'=>$val[1]);
}elseif('regex'==$con){ // 正则查询
$query[$key] = new MongoRegex($val[1]);
}elseif(in_array($con,array('in','nin','not in'))){ // IN NIN 运算
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$k = '$'.$this->comparison[$con];
$query[$key] = array($k=>$data);
}elseif('all'==$con){ // 满足所有指定条件
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$query[$key] = array('$all'=>$data);
}elseif('between'==$con){ // BETWEEN运算
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$query[$key] = array('$gte'=>$data[0],'$lte'=>$data[1]);
}elseif('not between'==$con){
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$query[$key] = array('$lt'=>$data[0],'$gt'=>$data[1]);
}elseif('exp'==$con){ // 表达式查询
$query['$where'] = new MongoCode($val[1]);
}elseif('exists'==$con){ // 字段是否存在
$query[$key] =array('$exists'=>(bool)$val[1]);
}elseif('size'==$con){ // 限制属性大小
$query[$key] =array('$size'=>intval($val[1]));
}elseif('type'==$con){ // 限制字段类型 1 浮点型 2 字符型 3 对象或者MongoDBRef 5 MongoBinData 7 MongoId 8 布尔型 9 MongoDate 10 NULL 15 MongoCode 16 32位整型 17 MongoTimestamp 18 MongoInt64 如果是数组的话判断元素的类型
$query[$key] =array('$type'=>intval($val[1]));
}else{
$query[$key] = $val;
}
return $query;
}
}
$query[$key] = $val;
return $query;
}
} | 545038947/haisys | ThinkPHP/Library/Think/Db/Driver/Mongo.class.php | PHP | gpl-2.0 | 26,886 |
package mpicbg.spim.segmentation;
import fiji.tool.SliceListener;
import fiji.tool.SliceObserver;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.WindowManager;
import ij.gui.OvalRoi;
import ij.gui.Overlay;
import ij.gui.Roi;
import ij.io.Opener;
import ij.plugin.PlugIn;
import ij.process.ByteProcessor;
import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.Rectangle;
import java.awt.Scrollbar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import mpicbg.imglib.algorithm.gauss.GaussianConvolutionReal;
import mpicbg.imglib.algorithm.math.LocalizablePoint;
import mpicbg.imglib.algorithm.scalespace.DifferenceOfGaussianPeak;
import mpicbg.imglib.algorithm.scalespace.DifferenceOfGaussianReal1;
import mpicbg.imglib.algorithm.scalespace.SubpixelLocalization;
import mpicbg.imglib.container.array.ArrayContainerFactory;
import mpicbg.imglib.cursor.LocalizableByDimCursor;
import mpicbg.imglib.cursor.LocalizableCursor;
import mpicbg.imglib.image.Image;
import mpicbg.imglib.image.ImageFactory;
import mpicbg.imglib.image.display.imagej.ImageJFunctions;
import mpicbg.imglib.multithreading.SimpleMultiThreading;
import mpicbg.imglib.outofbounds.OutOfBoundsStrategyMirrorFactory;
import mpicbg.imglib.outofbounds.OutOfBoundsStrategyValueFactory;
import mpicbg.imglib.type.numeric.real.FloatType;
import mpicbg.imglib.util.Util;
import mpicbg.spim.io.IOFunctions;
import mpicbg.spim.registration.ViewStructure;
import mpicbg.spim.registration.detection.DetectionSegmentation;
import net.imglib2.RandomAccess;
import net.imglib2.exception.ImgLibException;
import net.imglib2.img.ImagePlusAdapter;
import net.imglib2.img.imageplus.FloatImagePlus;
import net.imglib2.view.Views;
import spim.process.fusion.FusionHelper;
/**
* An interactive tool for determining the required sigma and peak threshold
*
* @author Stephan Preibisch
*/
public class InteractiveDoG implements PlugIn
{
final int extraSize = 40;
final int scrollbarSize = 1000;
float sigma = 0.5f;
float sigma2 = 0.5f;
float threshold = 0.0001f;
// steps per octave
public static int standardSenstivity = 4;
int sensitivity = standardSenstivity;
float imageSigma = 0.5f;
float sigmaMin = 0.5f;
float sigmaMax = 10f;
int sigmaInit = 300;
float thresholdMin = 0.0001f;
float thresholdMax = 1f;
int thresholdInit = 500;
double minIntensityImage = Double.NaN;
double maxIntensityImage = Double.NaN;
SliceObserver sliceObserver;
RoiListener roiListener;
ImagePlus imp;
int channel = 0;
Rectangle rectangle;
Image<FloatType> img;
FloatImagePlus< net.imglib2.type.numeric.real.FloatType > source;
ArrayList<DifferenceOfGaussianPeak<FloatType>> peaks;
Color originalColor = new Color( 0.8f, 0.8f, 0.8f );
Color inactiveColor = new Color( 0.95f, 0.95f, 0.95f );
public Rectangle standardRectangle;
boolean isComputing = false;
boolean isStarted = false;
boolean enableSigma2 = false;
boolean sigma2IsAdjustable = true;
boolean lookForMinima = false;
boolean lookForMaxima = true;
public static enum ValueChange { SIGMA, THRESHOLD, SLICE, ROI, MINMAX, ALL }
boolean isFinished = false;
boolean wasCanceled = false;
public boolean isFinished() { return isFinished; }
public boolean wasCanceled() { return wasCanceled; }
public double getInitialSigma() { return sigma; }
public void setInitialSigma( final float value )
{
sigma = value;
sigmaInit = computeScrollbarPositionFromValue( sigma, sigmaMin, sigmaMax, scrollbarSize );
}
public double getSigma2() { return sigma2; }
public double getThreshold() { return threshold; }
public void setThreshold( final float value )
{
threshold = value;
final double log1001 = Math.log10( scrollbarSize + 1);
thresholdInit = (int)Math.round( 1001-Math.pow(10, -(((threshold - thresholdMin)/(thresholdMax-thresholdMin))*log1001) + log1001 ) );
}
public boolean getSigma2WasAdjusted() { return enableSigma2; }
public boolean getLookForMaxima() { return lookForMaxima; }
public boolean getLookForMinima() { return lookForMinima; }
public void setLookForMaxima( final boolean lookForMaxima ) { this.lookForMaxima = lookForMaxima; }
public void setLookForMinima( final boolean lookForMinima ) { this.lookForMinima = lookForMinima; }
public void setSigmaMax( final float sigmaMax ) { this.sigmaMax = sigmaMax; }
public void setSigma2isAdjustable( final boolean state ) { sigma2IsAdjustable = state; }
// for the case that it is needed again, we can save one conversion
public FloatImagePlus< net.imglib2.type.numeric.real.FloatType > getConvertedImage() { return source; }
public InteractiveDoG( final ImagePlus imp, final int channel )
{
this.imp = imp;
this.channel = channel;
}
public InteractiveDoG( final ImagePlus imp ) { this.imp = imp; }
public InteractiveDoG() {}
public void setMinIntensityImage( final double min ) { this.minIntensityImage = min; }
public void setMaxIntensityImage( final double max ) { this.maxIntensityImage = max; }
@Override
public void run( String arg )
{
if ( imp == null )
imp = WindowManager.getCurrentImage();
standardRectangle = new Rectangle( imp.getWidth()/4, imp.getHeight()/4, imp.getWidth()/2, imp.getHeight()/2 );
if ( imp.getType() == ImagePlus.COLOR_RGB || imp.getType() == ImagePlus.COLOR_256 )
{
IJ.log( "Color images are not supported, please convert to 8, 16 or 32-bit grayscale" );
return;
}
Roi roi = imp.getRoi();
if ( roi == null )
{
//IJ.log( "A rectangular ROI is required to define the area..." );
imp.setRoi( standardRectangle );
roi = imp.getRoi();
}
if ( roi.getType() != Roi.RECTANGLE )
{
IJ.log( "Only rectangular rois are supported..." );
return;
}
// copy the ImagePlus into an ArrayImage<FloatType> for faster access
source = convertToFloat( imp, channel, 0, minIntensityImage, maxIntensityImage );
// show the interactive kit
displaySliders();
// add listener to the imageplus slice slider
sliceObserver = new SliceObserver( imp, new ImagePlusListener() );
// compute first version
updatePreview( ValueChange.ALL );
isStarted = true;
// check whenever roi is modified to update accordingly
roiListener = new RoiListener();
imp.getCanvas().addMouseListener( roiListener );
}
/**
* Updates the Preview with the current parameters (sigma, threshold, roi, slicenumber)
*
* @param change - what did change
*/
protected void updatePreview( final ValueChange change )
{
// check if Roi changed
boolean roiChanged = false;
Roi roi = imp.getRoi();
if ( roi == null || roi.getType() != Roi.RECTANGLE )
{
imp.setRoi( new Rectangle( standardRectangle ) );
roi = imp.getRoi();
roiChanged = true;
}
final Rectangle rect = roi.getBounds();
if ( roiChanged || img == null || change == ValueChange.SLICE ||
rect.getMinX() != rectangle.getMinX() || rect.getMaxX() != rectangle.getMaxX() ||
rect.getMinY() != rectangle.getMinY() || rect.getMaxY() != rectangle.getMaxY() )
{
rectangle = rect;
img = extractImage( source, rectangle, extraSize );
roiChanged = true;
}
// if we got some mouse click but the ROI did not change we can return
if ( !roiChanged && change == ValueChange.ROI )
{
isComputing = false;
return;
}
// compute the Difference Of Gaussian if necessary
if ( peaks == null || roiChanged || change == ValueChange.SIGMA || change == ValueChange.SLICE || change == ValueChange.ALL )
{
//
// Compute the Sigmas for the gaussian folding
//
final float k, K_MIN1_INV;
final float[] sigma, sigmaDiff;
if ( enableSigma2 )
{
sigma = new float[ 2 ];
sigma[ 0 ] = this.sigma;
sigma[ 1 ] = this.sigma2;
k = sigma[ 1 ] / sigma[ 0 ];
K_MIN1_INV = DetectionSegmentation.computeKWeight( k );
sigmaDiff = DetectionSegmentation.computeSigmaDiff( sigma, imageSigma );
}
else
{
k = (float)DetectionSegmentation.computeK( sensitivity );
K_MIN1_INV = DetectionSegmentation.computeKWeight( k );
sigma = DetectionSegmentation.computeSigma( k, this.sigma );
sigmaDiff = DetectionSegmentation.computeSigmaDiff( sigma, imageSigma );
}
// the upper boundary
this.sigma2 = sigma[ 1 ];
final DifferenceOfGaussianReal1<FloatType> dog = new DifferenceOfGaussianReal1<FloatType>( img, new OutOfBoundsStrategyValueFactory<FloatType>(), sigmaDiff[ 0 ], sigmaDiff[ 1 ], thresholdMin/4, K_MIN1_INV );
dog.setKeepDoGImage( true );
dog.process();
final SubpixelLocalization<FloatType> subpixel = new SubpixelLocalization<FloatType>( dog.getDoGImage(), dog.getPeaks() );
subpixel.process();
peaks = dog.getPeaks();
}
// extract peaks to show
Overlay o = imp.getOverlay();
if ( o == null )
{
o = new Overlay();
imp.setOverlay( o );
}
o.clear();
for ( final DifferenceOfGaussianPeak<FloatType> peak : peaks )
{
if ( ( peak.isMax() && lookForMaxima ) || ( peak.isMin() && lookForMinima ) )
{
final float x = peak.getPosition( 0 );
final float y = peak.getPosition( 1 );
if ( Math.abs( peak.getValue().get() ) > threshold &&
x >= extraSize/2 && y >= extraSize/2 &&
x < rect.width+extraSize/2 && y < rect.height+extraSize/2 )
{
final OvalRoi or = new OvalRoi( Util.round( x - sigma ) + rect.x - extraSize/2, Util.round( y - sigma ) + rect.y - extraSize/2, Util.round( sigma+sigma2 ), Util.round( sigma+sigma2 ) );
if ( peak.isMax() )
or.setStrokeColor( Color.green );
else if ( peak.isMin() )
or.setStrokeColor( Color.red );
o.add( or );
}
}
}
imp.updateAndDraw();
isComputing = false;
}
public static float computeSigma2( final float sigma1, final int sensitivity )
{
final float k = (float)DetectionSegmentation.computeK( sensitivity );
final float[] sigma = DetectionSegmentation.computeSigma( k, sigma1 );
return sigma[ 1 ];
}
/**
* Extract the current 2d region of interest from the souce image
*
* @param source - the source image, a {@link Image} which is a copy of the {@link ImagePlus}
* @param rectangle - the area of interest
* @param extraSize - the extra size around so that detections at the border of the roi are not messed up
* @return
*/
protected Image<FloatType> extractImage( final FloatImagePlus< net.imglib2.type.numeric.real.FloatType > source, final Rectangle rectangle, final int extraSize )
{
final Image<FloatType> img = new ImageFactory<FloatType>( new FloatType(), new ArrayContainerFactory() ).createImage( new int[]{ rectangle.width+extraSize, rectangle.height+extraSize } );
final int offsetX = rectangle.x - extraSize/2;
final int offsetY = rectangle.y - extraSize/2;
final int[] location = new int[ source.numDimensions() ];
if ( location.length > 2 )
location[ 2 ] = (imp.getCurrentSlice()-1)/imp.getNChannels();
final LocalizableCursor<FloatType> cursor = img.createLocalizableCursor();
final RandomAccess<net.imglib2.type.numeric.real.FloatType> positionable;
if ( offsetX >= 0 && offsetY >= 0 &&
offsetX + img.getDimension( 0 ) < source.dimension( 0 ) &&
offsetY + img.getDimension( 1 ) < source.dimension( 1 ) )
{
// it is completely inside so we need no outofbounds for copying
positionable = source.randomAccess();
}
else
{
positionable = Views.extendMirrorSingle( source ).randomAccess();
}
while ( cursor.hasNext() )
{
cursor.fwd();
cursor.getPosition( location );
location[ 0 ] += offsetX;
location[ 1 ] += offsetY;
positionable.setPosition( location );
cursor.getType().set( positionable.get().get() );
}
return img;
}
/**
* Normalize and make a copy of the {@link ImagePlus} into an {@link Image}>FloatType< for faster access when copying the slices
*
* @param imp - the {@link ImagePlus} input image
* @return - the normalized copy [0...1]
*/
public static FloatImagePlus< net.imglib2.type.numeric.real.FloatType > convertToFloat( final ImagePlus imp, int channel, int timepoint )
{
return convertToFloat( imp, channel, timepoint, Double.NaN, Double.NaN );
}
public static FloatImagePlus< net.imglib2.type.numeric.real.FloatType > convertToFloat( final ImagePlus imp, int channel, int timepoint, final double min, final double max )
{
// stupid 1-offset of imagej
channel++;
timepoint++;
final int h = imp.getHeight();
final int w = imp.getWidth();
final ArrayList< float[] > img = new ArrayList< float[] >();
if ( imp.getProcessor() instanceof FloatProcessor )
{
for ( int z = 0; z < imp.getNSlices(); ++z )
img.add( ( (float[])imp.getStack().getProcessor( imp.getStackIndex( channel, z + 1, timepoint ) ).getPixels() ).clone() );
}
else if ( imp.getProcessor() instanceof ByteProcessor )
{
for ( int z = 0; z < imp.getNSlices(); ++z )
{
final byte[] pixels = (byte[])imp.getStack().getProcessor( imp.getStackIndex( channel, z + 1, timepoint ) ).getPixels();
final float[] pixelsF = new float[ pixels.length ];
for ( int i = 0; i < pixels.length; ++i )
pixelsF[ i ] = pixels[ i ] & 0xff;
img.add( pixelsF );
}
}
else if ( imp.getProcessor() instanceof ShortProcessor )
{
for ( int z = 0; z < imp.getNSlices(); ++z )
{
final short[] pixels = (short[])imp.getStack().getProcessor( imp.getStackIndex( channel, z + 1, timepoint ) ).getPixels();
final float[] pixelsF = new float[ pixels.length ];
for ( int i = 0; i < pixels.length; ++i )
pixelsF[ i ] = pixels[ i ] & 0xffff;
img.add( pixelsF );
}
}
else // some color stuff or so
{
for ( int z = 0; z < imp.getNSlices(); ++z )
{
final ImageProcessor ip = imp.getStack().getProcessor( imp.getStackIndex( channel, z + 1, timepoint ) );
final float[] pixelsF = new float[ w * h ];
int i = 0;
for ( int y = 0; y < h; ++y )
for ( int x = 0; x < w; ++x )
pixelsF[ i++ ] = ip.getPixelValue( x, y );
img.add( pixelsF );
}
}
final FloatImagePlus< net.imglib2.type.numeric.real.FloatType > i = createImgLib2( img, w, h );
if ( Double.isNaN( min ) || Double.isNaN( max ) || Double.isInfinite( min ) || Double.isInfinite( max ) || min == max )
FusionHelper.normalizeImage( i );
else
FusionHelper.normalizeImage( i, (float)min, (float)max );
return i;
}
public static FloatImagePlus< net.imglib2.type.numeric.real.FloatType > createImgLib2( final List< float[] > img, final int w, final int h )
{
final ImagePlus imp;
if ( img.size() > 1 )
{
final ImageStack stack = new ImageStack( w, h );
for ( int z = 0; z < img.size(); ++z )
stack.addSlice( new FloatProcessor( w, h, img.get( z ) ) );
imp = new ImagePlus( "ImgLib2 FloatImagePlus (3d)", stack );
}
else
{
imp = new ImagePlus( "ImgLib2 FloatImagePlus (2d)", new FloatProcessor( w, h, img.get( 0 ) ) );
}
return ImagePlusAdapter.wrapFloat( imp );
}
/**
* Instantiates the panel for adjusting the paramters
*/
protected void displaySliders()
{
final Frame frame = new Frame("Adjust Difference-of-Gaussian Values");
frame.setSize( 400, 330 );
/* Instantiation */
final GridBagLayout layout = new GridBagLayout();
final GridBagConstraints c = new GridBagConstraints();
final Scrollbar sigma1 = new Scrollbar ( Scrollbar.HORIZONTAL, sigmaInit, 10, 0, 10 + scrollbarSize );
this.sigma = computeValueFromScrollbarPosition( sigmaInit, sigmaMin, sigmaMax, scrollbarSize);
final Scrollbar threshold = new Scrollbar ( Scrollbar.HORIZONTAL, thresholdInit, 10, 0, 10 + scrollbarSize );
final float log1001 = (float)Math.log10( scrollbarSize + 1);
this.threshold = thresholdMin + ( (log1001 - (float)Math.log10(1001-thresholdInit))/log1001 ) * (thresholdMax-thresholdMin);
this.sigma2 = computeSigma2( this.sigma, this.sensitivity );
final int sigma2init = computeScrollbarPositionFromValue( this.sigma2, sigmaMin, sigmaMax, scrollbarSize );
final Scrollbar sigma2 = new Scrollbar ( Scrollbar.HORIZONTAL, sigma2init, 10, 0, 10 + scrollbarSize );
final Label sigmaText1 = new Label( "Sigma 1 = " + this.sigma, Label.CENTER );
final Label sigmaText2 = new Label( "Sigma 2 = " + this.sigma2, Label.CENTER );
final Label thresholdText = new Label( "Threshold = " + this.threshold, Label.CENTER );
final Button apply = new Button( "Apply to Stack (will take some time)" );
final Button button = new Button( "Done" );
final Button cancel = new Button( "Cancel" );
final Checkbox sigma2Enable = new Checkbox( "Enable Manual Adjustment of Sigma 2 ", enableSigma2 );
final Checkbox min = new Checkbox( "Look for Minima (red)", lookForMinima );
final Checkbox max = new Checkbox( "Look for Maxima (green)", lookForMaxima );
/* Location */
frame.setLayout( layout );
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
frame.add ( sigma1, c );
++c.gridy;
frame.add( sigmaText1, c );
++c.gridy;
frame.add ( sigma2, c );
++c.gridy;
frame.add( sigmaText2, c );
++c.gridy;
c.insets = new Insets(0,65,0,65);
frame.add( sigma2Enable, c );
++c.gridy;
c.insets = new Insets(10,0,0,0);
frame.add ( threshold, c );
c.insets = new Insets(0,0,0,0);
++c.gridy;
frame.add( thresholdText, c );
++c.gridy;
c.insets = new Insets(0,130,0,75);
frame.add( min, c );
++c.gridy;
c.insets = new Insets(0,125,0,75);
frame.add( max, c );
++c.gridy;
c.insets = new Insets(0,75,0,75);
frame.add( apply, c );
++c.gridy;
c.insets = new Insets(10,150,0,150);
frame.add( button, c );
++c.gridy;
c.insets = new Insets(10,150,0,150);
frame.add( cancel, c );
/* Configuration */
sigma1.addAdjustmentListener( new SigmaListener( sigmaText1, sigmaMin, sigmaMax, scrollbarSize, sigma1, sigma2, sigmaText2 ) );
sigma2.addAdjustmentListener( new Sigma2Listener( sigmaMin, sigmaMax, scrollbarSize, sigma2, sigmaText2 ) );
threshold.addAdjustmentListener( new ThresholdListener( thresholdText, thresholdMin, thresholdMax ) );
button.addActionListener( new FinishedButtonListener( frame, false ) );
cancel.addActionListener( new FinishedButtonListener( frame, true ) );
apply.addActionListener( new ApplyButtonListener() );
min.addItemListener( new MinListener() );
max.addItemListener( new MaxListener() );
sigma2Enable.addItemListener( new EnableListener( sigma2, sigmaText2 ) );
if ( !sigma2IsAdjustable )
sigma2Enable.setEnabled( false );
frame.addWindowListener( new FrameListener( frame ) );
frame.setVisible( true );
originalColor = sigma2.getBackground();
sigma2.setBackground( inactiveColor );
sigmaText1.setFont( sigmaText1.getFont().deriveFont( Font.BOLD ) );
thresholdText.setFont( thresholdText.getFont().deriveFont( Font.BOLD ) );
}
protected class EnableListener implements ItemListener
{
final Scrollbar sigma2;
final Label sigmaText2;
public EnableListener( final Scrollbar sigma2, final Label sigmaText2 )
{
this.sigmaText2 = sigmaText2;
this.sigma2 = sigma2;
}
@Override
public void itemStateChanged( final ItemEvent arg0 )
{
if ( arg0.getStateChange() == ItemEvent.DESELECTED )
{
sigmaText2.setFont( sigmaText2.getFont().deriveFont( Font.PLAIN ) );
sigma2.setBackground( inactiveColor );
enableSigma2 = false;
}
else if ( arg0.getStateChange() == ItemEvent.SELECTED )
{
sigmaText2.setFont( sigmaText2.getFont().deriveFont( Font.BOLD ) );
sigma2.setBackground( originalColor );
enableSigma2 = true;
}
}
}
protected class MinListener implements ItemListener
{
@Override
public void itemStateChanged( final ItemEvent arg0 )
{
boolean oldState = lookForMinima;
if ( arg0.getStateChange() == ItemEvent.DESELECTED )
lookForMinima = false;
else if ( arg0.getStateChange() == ItemEvent.SELECTED )
lookForMinima = true;
if ( lookForMinima != oldState )
{
while ( isComputing )
SimpleMultiThreading.threadWait( 10 );
updatePreview( ValueChange.MINMAX );
}
}
}
protected class MaxListener implements ItemListener
{
@Override
public void itemStateChanged( final ItemEvent arg0 )
{
boolean oldState = lookForMaxima;
if ( arg0.getStateChange() == ItemEvent.DESELECTED )
lookForMaxima = false;
else if ( arg0.getStateChange() == ItemEvent.SELECTED )
lookForMaxima = true;
if ( lookForMaxima != oldState )
{
while ( isComputing )
SimpleMultiThreading.threadWait( 10 );
updatePreview( ValueChange.MINMAX );
}
}
}
/**
* Tests whether the ROI was changed and will recompute the preview
*
* @author Stephan Preibisch
*/
protected class RoiListener implements MouseListener
{
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased( final MouseEvent e )
{
// here the ROI might have been modified, let's test for that
final Roi roi = imp.getRoi();
if ( roi == null || roi.getType() != Roi.RECTANGLE )
return;
while ( isComputing )
SimpleMultiThreading.threadWait( 10 );
updatePreview( ValueChange.ROI );
}
}
protected class ApplyButtonListener implements ActionListener
{
@Override
public void actionPerformed( final ActionEvent arg0 )
{
ImagePlus imp;
try
{
imp = source.getImagePlus();
}
catch (ImgLibException e)
{
imp = null;
e.printStackTrace();
}
// convert ImgLib2 image to ImgLib1 image via the imageplus
final Image< FloatType > source = ImageJFunctions.wrapFloat( imp );
IOFunctions.println( "Computing DoG ... " );
// test the parameters on the complete stack
final ArrayList<DifferenceOfGaussianPeak<FloatType>> peaks =
DetectionSegmentation.extractBeadsLaPlaceImgLib(
source,
new OutOfBoundsStrategyMirrorFactory<FloatType>(),
imageSigma,
sigma,
sigma2,
threshold,
threshold/4,
lookForMaxima,
lookForMinima,
ViewStructure.DEBUG_MAIN );
IOFunctions.println( "Drawing DoG result ... " );
// display as extra image
Image<FloatType> detections = source.createNewImage();
final LocalizableByDimCursor<FloatType> c = detections.createLocalizableByDimCursor();
for ( final DifferenceOfGaussianPeak<FloatType> peak : peaks )
{
final LocalizablePoint p = new LocalizablePoint( new float[]{ peak.getSubPixelPosition( 0 ), peak.getSubPixelPosition( 1 ), peak.getSubPixelPosition( 2 ) } );
c.setPosition( p );
c.getType().set( 1 );
}
IOFunctions.println( "Convolving DoG result ... " );
final GaussianConvolutionReal<FloatType> gauss = new GaussianConvolutionReal<FloatType>( detections, new OutOfBoundsStrategyValueFactory<FloatType>(), 2 );
gauss.process();
detections = gauss.getResult();
IOFunctions.println( "Showing DoG result ... " );
ImageJFunctions.show( detections );
}
}
protected class FinishedButtonListener implements ActionListener
{
final Frame parent;
final boolean cancel;
public FinishedButtonListener( Frame parent, final boolean cancel )
{
this.parent = parent;
this.cancel = cancel;
}
@Override
public void actionPerformed( final ActionEvent arg0 )
{
wasCanceled = cancel;
close( parent, sliceObserver, imp, roiListener );
}
}
protected class FrameListener extends WindowAdapter
{
final Frame parent;
public FrameListener( Frame parent )
{
super();
this.parent = parent;
}
@Override
public void windowClosing (WindowEvent e)
{
close( parent, sliceObserver, imp, roiListener );
}
}
protected final void close( final Frame parent, final SliceObserver sliceObserver, final ImagePlus imp, final RoiListener roiListener )
{
if ( parent != null )
parent.dispose();
if ( sliceObserver != null )
sliceObserver.unregister();
if ( imp != null )
{
if ( roiListener != null )
imp.getCanvas().removeMouseListener( roiListener );
imp.getOverlay().clear();
imp.updateAndDraw();
}
isFinished = true;
}
protected class Sigma2Listener implements AdjustmentListener
{
final float min, max;
final int scrollbarSize;
final Scrollbar sigmaScrollbar2;
final Label sigma2Label;
public Sigma2Listener( final float min, final float max, final int scrollbarSize, final Scrollbar sigmaScrollbar2, final Label sigma2Label )
{
this.min = min;
this.max = max;
this.scrollbarSize = scrollbarSize;
this.sigmaScrollbar2 = sigmaScrollbar2;
this.sigma2Label = sigma2Label;
}
@Override
public void adjustmentValueChanged( final AdjustmentEvent event )
{
if ( enableSigma2 )
{
sigma2 = computeValueFromScrollbarPosition( event.getValue(), min, max, scrollbarSize );
if ( sigma2 < sigma )
{
sigma2 = sigma + 0.001f;
sigmaScrollbar2.setValue( computeScrollbarPositionFromValue( sigma2, min, max, scrollbarSize ) );
}
sigma2Label.setText( "Sigma 2 = " + sigma2 );
if ( !event.getValueIsAdjusting() )
{
while ( isComputing )
{
SimpleMultiThreading.threadWait( 10 );
}
updatePreview( ValueChange.SIGMA );
}
}
else
{
// if no manual adjustment simply reset it
sigmaScrollbar2.setValue( computeScrollbarPositionFromValue( sigma2, min, max, scrollbarSize ) );
}
}
}
protected class SigmaListener implements AdjustmentListener
{
final Label label;
final float min, max;
final int scrollbarSize;
final Scrollbar sigmaScrollbar1;
final Scrollbar sigmaScrollbar2;
final Label sigmaText2;
public SigmaListener( final Label label, final float min, final float max, final int scrollbarSize, final Scrollbar sigmaScrollbar1, final Scrollbar sigmaScrollbar2, final Label sigmaText2 )
{
this.label = label;
this.min = min;
this.max = max;
this.scrollbarSize = scrollbarSize;
this.sigmaScrollbar1 = sigmaScrollbar1;
this.sigmaScrollbar2 = sigmaScrollbar2;
this.sigmaText2 = sigmaText2;
}
@Override
public void adjustmentValueChanged( final AdjustmentEvent event )
{
sigma = computeValueFromScrollbarPosition( event.getValue(), min, max, scrollbarSize );
if ( !enableSigma2 )
{
sigma2 = computeSigma2( sigma, sensitivity );
sigmaText2.setText( "Sigma 2 = " + sigma2 );
sigmaScrollbar2.setValue( computeScrollbarPositionFromValue( sigma2, min, max, scrollbarSize ) );
}
else if ( sigma > sigma2 )
{
sigma = sigma2 - 0.001f;
sigmaScrollbar1.setValue( computeScrollbarPositionFromValue( sigma, min, max, scrollbarSize ) );
}
label.setText( "Sigma 1 = " + sigma );
if ( !event.getValueIsAdjusting() )
{
while ( isComputing )
{
SimpleMultiThreading.threadWait( 10 );
}
updatePreview( ValueChange.SIGMA );
}
}
}
protected static float computeValueFromScrollbarPosition( final int scrollbarPosition, final float min, final float max, final int scrollbarSize )
{
return min + (scrollbarPosition/(float)scrollbarSize) * (max-min);
}
protected static int computeScrollbarPositionFromValue( final float sigma, final float min, final float max, final int scrollbarSize )
{
return Util.round( ((sigma - min)/(max-min)) * scrollbarSize );
}
protected class ThresholdListener implements AdjustmentListener
{
final Label label;
final float min, max;
final float log1001 = (float)Math.log10(1001);
public ThresholdListener( final Label label, final float min, final float max )
{
this.label = label;
this.min = min;
this.max = max;
}
@Override
public void adjustmentValueChanged( final AdjustmentEvent event )
{
threshold = min + ( (log1001 - (float)Math.log10(1001-event.getValue()))/log1001 ) * (max-min);
label.setText( "Threshold = " + threshold );
if ( !isComputing )
{
updatePreview( ValueChange.THRESHOLD );
}
else if ( !event.getValueIsAdjusting() )
{
while ( isComputing )
{
SimpleMultiThreading.threadWait( 10 );
}
updatePreview( ValueChange.THRESHOLD );
}
}
}
protected class ImagePlusListener implements SliceListener
{
@Override
public void sliceChanged(ImagePlus arg0)
{
if ( isStarted )
{
while ( isComputing )
{
SimpleMultiThreading.threadWait( 10 );
}
updatePreview( ValueChange.SLICE );
}
}
}
public static void main( String[] args )
{
new ImageJ();
ImagePlus imp = new Opener().openImage( "/home/preibisch/Documents/Microscopy/SPIM/Harvard/f11e6/exp3/img_Ch0_Angle0.tif.zip" );
//ImagePlus imp = new Opener().openImage( "D:/Documents and Settings/Stephan/My Documents/Downloads/1-315--0.08-isotropic-subvolume/1-315--0.08-isotropic-subvolume.tif" );
imp.show();
imp.setSlice( 27 );
imp.setRoi( imp.getWidth()/4, imp.getHeight()/4, imp.getWidth()/2, imp.getHeight()/2 );
new InteractiveDoG().run( null );
}
}
| psteinb/SPIM_Registration | src/main/java/mpicbg/spim/segmentation/InteractiveDoG.java | Java | gpl-2.0 | 30,536 |
<?php
$name='KievitCyr-ExtraBold';
$type='TTF';
$desc=array (
'Ascent' => 872,
'Descent' => -250,
'CapHeight' => 872,
'Flags' => 262148,
'FontBBox' => '[-56 -250 1278 872]',
'ItalicAngle' => 0,
'StemV' => 165,
'MissingWidth' => 566,
);
$up=-143;
$ut=20;
$ttffile='C:/wamp/www/alfakasko/mpdf/ttfonts/KvCyXb_.ttf';
$TTCfontID='0';
$originalsize=20632;
$sip=false;
$smp=false;
$BMPselected=false;
$fontkey='kievitB';
$panose=' 0 0 2 0 8 3 0 0 0 0 0 0';
$haskerninfo=false;
$unAGlyphs=false;
?> | vponomarev279/mpdf | ttfontdata/kievitB.mtx.php | PHP | gpl-2.0 | 506 |
<?php
/**
* File containing ezcomNotification class
*
* @copyright Copyright (C) 1999-2011 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
*
*/
/**
* ezcomNotification persistent object class definition
*
*/
class ezcomNotification extends eZPersistentObject
{
/**
* Construct, use {@link ezcomNotification::create()} to create new objects.
*
* @param array $row
*/
public function __construct( $row )
{
parent::__construct( $row );
}
/**
* Fields definition
*
* @return array
*/
public static function definition()
{
static $def = array( 'fields' => array( 'id' => array( 'name' => 'ID',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
'contentobject_id' => array( 'name' => 'ContentObjectID',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
'language_id' => array( 'name' => 'LanguageID',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
'send_time' => array( 'name' => 'SendTime',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
'status' => array( 'name' => 'Status',
'datatype' => 'integer',
'default' => 1,
'required' => true ),
'comment_id' => array( 'name' => 'CommentID',
'datatype' => 'integer',
'default' => 0,
'required' => true ) ),
'keys' => array( 'id' ),
'function_attributes' => array(),
'increment_key' => 'id',
'class_name' => 'ezcomNotification',
'name' => 'ezcomment_notification' );
return $def;
}
/**
* Create new ezcomNotification object
*
* @static
* @param array $row
* @return ezcomNotification
*/
public static function create( $row = array() )
{
$object = new self( $row );
return $object;
}
/**
* Fetch notification by given id
*
* @param int $id
* @return null|ezcomNotification
*/
static function fetch( $id )
{
$cond = array( 'id' => $id );
$return = eZPersistentObject::fetchObject( self::definition(), null, $cond );
return $return;
}
/**
* Fetch the list of notification
* @param $length: count of the notification to be fetched
* @param $status: the status of the notification
* @param $offset: offset
* @return notification list
*/
static function fetchNotificationList( $status = 1, $length = null, $offset = 0, $sorts = null )
{
$cond = array();
if ( is_null( $status ) )
{
$cond = null;
}
else
{
$cond['status'] = $status;
}
$limit = array();
if ( is_null( $length ) )
{
$limit = null;
}
else
{
$limit['offset'] = $offset;
$limit['length'] = $length;
}
return eZPersistentObject::fetchObjectList( self::definition(), null, $cond, $sorts, $limit );
}
/**
* clean up the notification quque
* @param unknown_type $contentObjectID
* @param unknown_type $languageID
* @param unknown_type $commentID
* @return unknown_type
*/
public static function cleanUpNotification( $contentObjectID, $language )
{
//1. fetch the queue, judge if there is data
//
}
}
?>
| ETSGlobal/ezpublish_built | extension/ezcomments/classes/ezcomnotification.php | PHP | gpl-2.0 | 4,981 |
from flask import request, jsonify
from sql_classes import UrlList, Acl, UserGroup, User, Role
def _node_base_and_rest(path):
"""
Returns a tuple: (the substring of a path after the last nodeSeparator, the preceding path before it)
If 'base' includes its own baseSeparator - return only a string after it
So if a path is 'OU=Group,OU=Dept,OU=Company', the tuple result would be ('OU=Group,OU=Dept', 'Company')
"""
node_separator = ','
base_separator = '='
node_base = path[path.rfind(node_separator) + 1:]
if path.find(node_separator) != -1:
node_preceding = path[:len(path) - len(node_base) - 1]
else:
node_preceding = ''
return (node_preceding, node_base[node_base.find(base_separator) + 1:])
def _place_user_onto_tree(user, usertree, user_groups):
"""
Places a 'user' object on a 'usertree' object according to user's pathField string key
"""
curr_node = usertree
# Decompose 'OU=Group,OU=Dept,OU=Company' into ('OU=Group,OU=Dept', 'Company')
preceding, base = _node_base_and_rest(user['distinguishedName'])
full_node_path = ''
# Place all path groups onto a tree starting from the outermost
while base != '':
node_found = False
full_node_path = 'OU=' + base + (',' if full_node_path != '' else '') + full_node_path
# Search for corresponding base element on current hierarchy level
for obj in curr_node:
if obj.get('text') == None:
continue
if obj['text'] == base:
node_found = True
curr_node = obj['children']
break
# Create a new group node
if not node_found:
curr_node.append({
'id': 'usergroup_' + str(user_groups[full_node_path]),
'text': base,
'objectType': 'UserGroup',
'children': []
})
curr_node = curr_node[len(curr_node) - 1]['children']
preceding, base = _node_base_and_rest(preceding)
curr_node.append({
'id': 'user_' + str(user['id']),
'text': user['cn'],
'leaf': True,
'iconCls': 'x-fa fa-user' if user['status'] == 1 else 'x-fa fa-user-times',
'objectType': 'User'
})
def _sort_tree(subtree, sort_field):
"""
Sorts a subtree node by a sortField key of each element
"""
# Sort eval function, first by group property, then by text
subtree['children'] = sorted(
subtree['children'],
key=lambda obj: (1 if obj.get('children') == None else 0, obj[sort_field]))
for tree_elem in subtree['children']:
if tree_elem.get('children') != None:
_sort_tree(tree_elem, sort_field)
def _collapse_terminal_nodes(subtree):
"""
Collapses tree nodes which doesn't contain subgroups, just tree leaves
"""
subtree_has_group_nodes = False
for tree_elem in subtree['children']:
if tree_elem.get('children') != None:
subtree_has_group_nodes = True
_collapse_terminal_nodes(tree_elem)
subtree['expanded'] = subtree_has_group_nodes
def _expand_all_nodes(subtree):
"""
Expand all level nodes
"""
for tree_elem in subtree['children']:
if tree_elem.get('children') != None:
_expand_all_nodes(tree_elem)
subtree['expanded'] = True
def _get_user_tree(current_user_properties, Session):
"""
Build user tree
"""
current_user_permissions = current_user_properties['user_permissions']
session = Session()
# Get all groups
query_result = session.query(UserGroup.id, UserGroup.distinguishedName).all()
user_groups = {}
for query_result_row in query_result:
user_groups[query_result_row.distinguishedName] = query_result_row.id
# Get all users if ViewUsers permission present
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewUsers'), None) != None:
query_result = session.query(
User.id.label('user_id'), User.cn, User.status, UserGroup.id.label('usergroup_id'),
UserGroup.distinguishedName).join(UserGroup).filter(User.hidden == 0).all()
# Get just the requester otherwise
else:
query_result = session.query(
User.id.label('user_id'), User.cn, User.status, UserGroup.id.label('usergroup_id'),
UserGroup.distinguishedName).join(UserGroup).\
filter(User.id == current_user_properties['user_object']['id'], User.hidden == 0).all()
Session.remove()
# Future tree
user_tree = []
# Place each user on a tree
for query_result_row in query_result:
user_object = {
'id': query_result_row.user_id,
'distinguishedName': query_result_row.distinguishedName,
'status': query_result_row.status,
'cn': query_result_row.cn
}
_place_user_onto_tree(user_object, user_tree, user_groups)
user_tree = {
'id': 'usergroup_0',
'objectType': 'UserGroup',
'text': 'Пользователи',
'children': user_tree
}
# Sort tree elements
_sort_tree(user_tree, 'text')
# Collapse/expand tree nodes
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewUsers'), None) != None:
_collapse_terminal_nodes(user_tree)
else:
_expand_all_nodes(user_tree)
return user_tree
def _get_url_lists(Session):
"""
Get URL lists
"""
session = Session()
# Get all urllists from DB
query_result = session.query(UrlList.id, UrlList.name, UrlList.whitelist).all()
Session.remove()
urllist_list = []
# Making a list of them
for query_result_row in query_result:
url_list_object = {
'id': 'urllist_' + str(query_result_row.id),
'text': query_result_row.name,
'leaf': True,
'iconCls': 'x-fa fa-unlock' if query_result_row.whitelist else 'x-fa fa-lock',
'objectType': 'UrlList'
}
urllist_list.append(url_list_object)
url_lists = {
'id': 'urllists',
'objectType': 'UrlLists',
'text': 'Списки URL',
'iconCls': 'x-fa fa-cog',
'children': urllist_list
}
# Sort tree elements
_sort_tree(url_lists, 'text')
return url_lists
def _get_acls(Session):
"""
Get ACLs
"""
session = Session()
# Get all access control lists from DB
query_result = session.query(Acl.id, Acl.name).all()
Session.remove()
acl_list = []
# Making a list of them
for query_result_row in query_result:
acl_object = {
'id': 'acl_' + str(query_result_row.id),
'text': query_result_row.name,
'leaf': True,
'iconCls': 'x-fa fa-filter',
'objectType': 'AclContents'
}
acl_list.append(acl_object)
acls = {
'id': 'acls',
'objectType': 'Acls',
'text': 'Списки доступа',
'iconCls': 'x-fa fa-cog',
'children': acl_list
}
# Sort tree elements
_sort_tree(acls, 'text')
return acls
def _get_roles(Session):
"""
Get user roles
"""
session = Session()
# Get all roles from DB
query_result = session.query(Role.id, Role.name).all()
Session.remove()
roles_list = []
# Making a list of them
for query_result_row in query_result:
role_object = {
'id': 'role_' + str(query_result_row.id),
'text': query_result_row.name,
'leaf': True,
'iconCls': 'x-fa fa-key',
'objectType': 'Role'
}
roles_list.append(role_object)
roles = {
'id': 'roles',
'objectType': 'Roles',
'text': 'Роли',
'iconCls': 'x-fa fa-cog',
'children': roles_list
}
# Sorting tree elements
_sort_tree(roles, 'text')
return roles
def select_tree(current_user_properties, node_name, Session):
url_lists_node = None
acls_node = None
roles_node = None
users_node = None
current_user_permissions = current_user_properties['user_permissions']
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewSettings'), None) != None:
if node_name in ['root', 'urllists']:
url_lists_node = _get_url_lists(Session)
if node_name in ['root', 'acls']:
acls_node = _get_acls(Session)
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewPermissions'), None) != None:
if node_name in ['root', 'roles']:
roles_node = _get_roles(Session)
if node_name in ['root']:
users_node = _get_user_tree(current_user_properties, Session)
if node_name == 'root':
children_list = []
if url_lists_node is not None:
children_list.append(url_lists_node)
if acls_node is not None:
children_list.append(acls_node)
if roles_node is not None:
children_list.append(roles_node)
if users_node is not None:
children_list.append(users_node)
result = {
'success': True,
'children': children_list
}
elif node_name == 'urllists':
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewSettings'), None) != None:
result = {
'success': True,
'children': url_lists_node['children']
}
else:
return Response('Forbidden', 403)
elif node_name == 'acls':
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewSettings'), None) != None:
result = {
'success': True,
'children': acls_node['children']
}
else:
return Response('Forbidden', 403)
elif node_name == 'roles':
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewPermissions'), None) != None:
result = {
'success': True,
'children': roles_node['children']
}
else:
return Response('Forbidden', 403)
return jsonify(result)
| Aclz/Tentacles | python3/app/backend/maintree.py | Python | gpl-2.0 | 10,439 |
<?php
/* core/themes/stable/templates/navigation/menu--toolbar.html.twig */
class __TwigTemplate_6d5e9324ee90ee9b5c8803c6bf39943fec4c217cff21756d529e71138cf50b3a extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array("import" => 21, "macro" => 29, "if" => 31, "for" => 37, "set" => 39);
$filters = array();
$functions = array("link" => 47);
try {
$this->env->getExtension('sandbox')->checkSecurity(
array('import', 'macro', 'if', 'for', 'set'),
array(),
array('link')
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setTemplateFile($this->getTemplateName());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 21
$context["menus"] = $this;
// line 22
echo "
";
// line 27
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar($context["menus"]->getmenu_links((isset($context["items"]) ? $context["items"] : null), (isset($context["attributes"]) ? $context["attributes"] : null), 0)));
echo "
";
}
// line 29
public function getmenu_links($__items__ = null, $__attributes__ = null, $__menu_level__ = null, ...$__varargs__)
{
$context = $this->env->mergeGlobals(array(
"items" => $__items__,
"attributes" => $__attributes__,
"menu_level" => $__menu_level__,
"varargs" => $__varargs__,
));
$blocks = array();
ob_start();
try {
// line 30
echo " ";
$context["menus"] = $this;
// line 31
echo " ";
if ((isset($context["items"]) ? $context["items"] : null)) {
// line 32
echo " ";
if (((isset($context["menu_level"]) ? $context["menu_level"] : null) == 0)) {
// line 33
echo " <ul";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => "toolbar-menu"), "method"), "html", null, true));
echo ">
";
} else {
// line 35
echo " <ul class=\"toolbar-menu\">
";
}
// line 37
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["items"]) ? $context["items"] : null));
foreach ($context['_seq'] as $context["_key"] => $context["item"]) {
// line 38
echo " ";
// line 39
$context["classes"] = array(0 => "menu-item", 1 => (($this->getAttribute( // line 41
$context["item"], "is_expanded", array())) ? ("menu-item--expanded") : ("")), 2 => (($this->getAttribute( // line 42
$context["item"], "is_collapsed", array())) ? ("menu-item--collapsed") : ("")), 3 => (($this->getAttribute( // line 43
$context["item"], "in_active_trail", array())) ? ("menu-item--active-trail") : ("")));
// line 46
echo " <li";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["item"], "attributes", array()), "addClass", array(0 => (isset($context["classes"]) ? $context["classes"] : null)), "method"), "html", null, true));
echo ">
";
// line 47
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->env->getExtension('drupal_core')->getLink($this->getAttribute($context["item"], "title", array()), $this->getAttribute($context["item"], "url", array())), "html", null, true));
echo "
";
// line 48
if ($this->getAttribute($context["item"], "below", array())) {
// line 49
echo " ";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar($context["menus"]->getmenu_links($this->getAttribute($context["item"], "below", array()), (isset($context["attributes"]) ? $context["attributes"] : null), ((isset($context["menu_level"]) ? $context["menu_level"] : null) + 1))));
echo "
";
}
// line 51
echo " </li>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['item'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 53
echo " </ul>
";
}
} catch (Exception $e) {
ob_end_clean();
throw $e;
} catch (Throwable $e) {
ob_end_clean();
throw $e;
}
return ('' === $tmp = ob_get_clean()) ? '' : new Twig_Markup($tmp, $this->env->getCharset());
}
public function getTemplateName()
{
return "core/themes/stable/templates/navigation/menu--toolbar.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 124 => 53, 117 => 51, 111 => 49, 109 => 48, 105 => 47, 100 => 46, 98 => 43, 97 => 42, 96 => 41, 95 => 39, 93 => 38, 88 => 37, 84 => 35, 78 => 33, 75 => 32, 72 => 31, 69 => 30, 55 => 29, 48 => 27, 45 => 22, 43 => 21,);
}
public function getSource()
{
return "{#
/**
* @file
* Theme override to display a toolbar menu.
*
* Available variables:
* - menu_name: The machine name of the menu.
* - items: A nested list of menu items. Each menu item contains:
* - attributes: HTML attributes for the menu item.
* - below: The menu item child items.
* - title: The menu link title.
* - url: The menu link url, instance of \\Drupal\\Core\\Url
* - localized_options: Menu link localized options.
* - is_expanded: TRUE if the link has visible children within the current
* menu tree.
* - is_collapsed: TRUE if the link has children within the current menu tree
* that are not currently visible.
* - in_active_trail: TRUE if the link is in the active trail.
*/
#}
{% import _self as menus %}
{#
We call a macro which calls itself to render the full tree.
@see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}
{% macro menu_links(items, attributes, menu_level) %}
{% import _self as menus %}
{% if items %}
{% if menu_level == 0 %}
<ul{{ attributes.addClass('toolbar-menu') }}>
{% else %}
<ul class=\"toolbar-menu\">
{% endif %}
{% for item in items %}
{%
set classes = [
'menu-item',
item.is_expanded ? 'menu-item--expanded',
item.is_collapsed ? 'menu-item--collapsed',
item.in_active_trail ? 'menu-item--active-trail',
]
%}
<li{{ item.attributes.addClass(classes) }}>
{{ link(item.title, item.url) }}
{% if item.below %}
{{ menus.menu_links(item.below, attributes, menu_level + 1) }}
{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
{% endmacro %}
";
}
}
| suruchi10/newrepo | sites/drupal-8.dd/files/php/twig/596d9f9815a73_menu--toolbar.html.twig_tygcDb3aAI8l_rxPgfBnz0oJU/TsdWiV50UGMMzQDbKZxdPubu_ft8_iB9Bvy9p1rB-z8.php | PHP | gpl-2.0 | 8,688 |
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2021 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* 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/>.
* ---------------------------------------------------------------------
*/
/**
* @since 0.85
*/
include ('../inc/includes.php');
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
Session::checkCentralAccess();
// Make a select box
if ($_POST['items_id']
&& $_POST['itemtype'] && class_exists($_POST['itemtype'])) {
$devicetype = $_POST['itemtype'];
$linktype = $devicetype::getItem_DeviceType();
if (count($linktype::getSpecificities())) {
$keys = array_keys($linktype::getSpecificities());
array_walk($keys, function (&$val) use ($DB) { return $DB->quoteName($val); });
$name_field = new QueryExpression(
"CONCAT_WS(' - ', " . implode(', ', $keys) . ")"
. "AS ".$DB->quoteName("name")
);
} else {
$name_field = 'id AS name';
}
$result = $DB->request(
[
'SELECT' => ['id', $name_field],
'FROM' => $linktype::getTable(),
'WHERE' => [
$devicetype::getForeignKeyField() => $_POST['items_id'],
'itemtype' => '',
]
]
);
echo "<table width='100%'><tr><td>" . __('Choose an existing device') . "</td><td rowspan='2'>" .
__('and/or') . "</td><td>" . __('Add new devices') . '</td></tr>';
echo "<tr><td>";
if ($result->count() == 0) {
echo __('No unaffected device !');
} else {
$devices = [];
foreach ($result as $row) {
$name = $row['name'];
if (empty($name)) {
$name = $row['id'];
}
$devices[$row['id']] = $name;
}
Dropdown::showFromArray($linktype::getForeignKeyField(), $devices, ['multiple' => true]);
}
echo "</td><td>";
Dropdown::showNumber('new_devices', ['min' => 0, 'max' => 10]);
echo "</td></tr></table>";
}
| smartcitiescommunity/Civikmind | ajax/selectUnaffectedOrNewItem_Device.php | PHP | gpl-2.0 | 2,921 |
<?php
/**
* Indonesia Provinces
*
*/
global $pms_states;
$pms_states['ID'] = array(
'AC' => __( 'Daerah Istimewa Aceh', 'paid-member-subscriptions' ),
'SU' => __( 'Sumatera Utara', 'paid-member-subscriptions' ),
'SB' => __( 'Sumatera Barat', 'paid-member-subscriptions' ),
'RI' => __( 'Riau', 'paid-member-subscriptions' ),
'KR' => __( 'Kepulauan Riau', 'paid-member-subscriptions' ),
'JA' => __( 'Jambi', 'paid-member-subscriptions' ),
'SS' => __( 'Sumatera Selatan', 'paid-member-subscriptions' ),
'BB' => __( 'Bangka Belitung', 'paid-member-subscriptions' ),
'BE' => __( 'Bengkulu', 'paid-member-subscriptions' ),
'LA' => __( 'Lampung', 'paid-member-subscriptions' ),
'JK' => __( 'DKI Jakarta', 'paid-member-subscriptions' ),
'JB' => __( 'Jawa Barat', 'paid-member-subscriptions' ),
'BT' => __( 'Banten', 'paid-member-subscriptions' ),
'JT' => __( 'Jawa Tengah', 'paid-member-subscriptions' ),
'JI' => __( 'Jawa Timur', 'paid-member-subscriptions' ),
'YO' => __( 'Daerah Istimewa Yogyakarta', 'paid-member-subscriptions' ),
'BA' => __( 'Bali', 'paid-member-subscriptions' ),
'NB' => __( 'Nusa Tenggara Barat', 'paid-member-subscriptions' ),
'NT' => __( 'Nusa Tenggara Timur', 'paid-member-subscriptions' ),
'KB' => __( 'Kalimantan Barat', 'paid-member-subscriptions' ),
'KT' => __( 'Kalimantan Tengah', 'paid-member-subscriptions' ),
'KI' => __( 'Kalimantan Timur', 'paid-member-subscriptions' ),
'KS' => __( 'Kalimantan Selatan', 'paid-member-subscriptions' ),
'KU' => __( 'Kalimantan Utara', 'paid-member-subscriptions' ),
'SA' => __( 'Sulawesi Utara', 'paid-member-subscriptions' ),
'ST' => __( 'Sulawesi Tengah', 'paid-member-subscriptions' ),
'SG' => __( 'Sulawesi Tenggara', 'paid-member-subscriptions' ),
'SR' => __( 'Sulawesi Barat', 'paid-member-subscriptions' ),
'SN' => __( 'Sulawesi Selatan', 'paid-member-subscriptions' ),
'GO' => __( 'Gorontalo', 'paid-member-subscriptions' ),
'MA' => __( 'Maluku', 'paid-member-subscriptions' ),
'MU' => __( 'Maluku Utara', 'paid-member-subscriptions' ),
'PA' => __( 'Papua', 'paid-member-subscriptions' ),
'PB' => __( 'Papua Barat', 'paid-member-subscriptions' )
);
| developerdinesh/theme | wp-content/plugins/paid-member-subscriptions/i18n/ID.php | PHP | gpl-2.0 | 2,157 |
/*
* Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package test.auctionportal;
import static com.sun.org.apache.xerces.internal.jaxp.JAXPConstants.JAXP_SCHEMA_LANGUAGE;
import static com.sun.org.apache.xerces.internal.jaxp.JAXPConstants.JAXP_SCHEMA_SOURCE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.file.Paths;
import java.util.GregorianCalendar;
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import jaxp.library.JAXPFileReadOnlyBaseTest;
import static jaxp.library.JAXPTestUtilities.bomStream;
import org.testng.annotations.Test;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.TypeInfo;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import static test.auctionportal.HiBidConstants.PORTAL_ACCOUNT_NS;
import static test.auctionportal.HiBidConstants.XML_DIR;
/**
* This is the user controller class for the Auction portal HiBid.com.
*/
public class AuctionController extends JAXPFileReadOnlyBaseTest {
/**
* Check for DOMErrorHandler handling DOMError. Before fix of bug 4890927
* DOMConfiguration.setParameter("well-formed",true) throws an exception.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readLocalFiles"})
public void testCreateNewItem2Sell() throws Exception {
String xmlFile = XML_DIR + "novelsInvalid.xml";
Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(xmlFile);
document.getDomConfig().setParameter("well-formed", true);
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
MyDOMOutput domOutput = new MyDOMOutput();
domOutput.setByteStream(System.out);
LSSerializer writer = impl.createLSSerializer();
writer.write(document, domOutput);
}
/**
* Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132
* test throws DOM Level 1 node error.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readLocalFiles"})
public void testCreateNewItem2SellRetry() throws Exception {
String xmlFile = XML_DIR + "accountInfo.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document document = dbf.newDocumentBuilder().parse(xmlFile);
DOMConfiguration domConfig = document.getDomConfig();
MyDOMErrorHandler errHandler = new MyDOMErrorHandler();
domConfig.setParameter("error-handler", errHandler);
DOMImplementationLS impl =
(DOMImplementationLS) DOMImplementationRegistry.newInstance()
.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
MyDOMOutput domoutput = new MyDOMOutput();
domoutput.setByteStream(System.out);
writer.write(document, domoutput);
document.normalizeDocument();
writer.write(document, domoutput);
assertFalse(errHandler.isError());
}
/**
* Check if setting the attribute to be of type ID works. This will affect
* the Attr.isID method according to the spec.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readLocalFiles"})
public void testCreateID() throws Exception {
String xmlFile = XML_DIR + "accountInfo.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document document = dbf.newDocumentBuilder().parse(xmlFile);
Element account = (Element)document
.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0);
account.setIdAttributeNS(PORTAL_ACCOUNT_NS, "accountID", true);
Attr aID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID");
assertTrue(aID.isId());
}
/**
* Check the user data on the node.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readLocalFiles"})
public void testCheckingUserData() throws Exception {
String xmlFile = XML_DIR + "accountInfo.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document document = docBuilder.parse(xmlFile);
Element account = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0);
assertEquals(account.getNodeName(), "acc:Account");
Element firstName = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0);
assertEquals(firstName.getNodeName(), "FirstName");
Document doc1 = docBuilder.newDocument();
Element someName = doc1.createElement("newelem");
someName.setUserData("mykey", "dd",
(operation, key, data, src, dst) -> {
System.err.println("In UserDataHandler" + key);
System.out.println("In UserDataHandler");
});
Element impAccount = (Element)document.importNode(someName, true);
assertEquals(impAccount.getNodeName(), "newelem");
document.normalizeDocument();
String data = (someName.getUserData("mykey")).toString();
assertEquals(data, "dd");
}
/**
* Check the UTF-16 XMLEncoding xml file.
*
* @throws Exception If any errors occur.
* @see <a href="content/movies.xml">movies.xml</a>
*/
@Test(groups = {"readLocalFiles"})
public void testCheckingEncoding() throws Exception {
// Note since movies.xml is UTF-16 encoding. We're not using stanard XML
// file suffix.
String xmlFile = XML_DIR + "movies.xml.data";
try (InputStream source = bomStream("UTF-16", xmlFile)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document document = dbf.newDocumentBuilder().parse(source);
assertEquals(document.getXmlEncoding(), "UTF-16");
assertEquals(document.getXmlStandalone(), true);
}
}
/**
* Check validation API features. A schema which is including in Bug 4909119
* used to be testing for the functionalities.
*
* @throws Exception If any errors occur.
* @see <a href="content/userDetails.xsd">userDetails.xsd</a>
*/
@Test(groups = {"readLocalFiles"})
public void testGetOwnerInfo() throws Exception {
String schemaFile = XML_DIR + "userDetails.xsd";
String xmlFile = XML_DIR + "userDetails.xml";
try(FileInputStream fis = new FileInputStream(xmlFile)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(Paths.get(schemaFile).toFile());
Validator validator = schema.newValidator();
MyErrorHandler eh = new MyErrorHandler();
validator.setErrorHandler(eh);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
docBuilder.setErrorHandler(eh);
Document document = docBuilder.parse(fis);
DOMResult dResult = new DOMResult();
DOMSource domSource = new DOMSource(document);
validator.validate(domSource, dResult);
assertFalse(eh.isAnyError());
}
}
/**
* Check grammar caching with imported schemas.
*
* @throws Exception If any errors occur.
* @see <a href="content/coins.xsd">coins.xsd</a>
* @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a>
*/
@Test(groups = {"readLocalFiles"})
public void testGetOwnerItemList() throws Exception {
String xsdFile = XML_DIR + "coins.xsd";
String xmlFile = XML_DIR + "coins.xml";
try(FileInputStream fis = new FileInputStream(xmlFile)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
dbf.setValidating(false);
SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File(((xsdFile))));
MyErrorHandler eh = new MyErrorHandler();
Validator validator = schema.newValidator();
validator.setErrorHandler(eh);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document document = docBuilder.parse(fis);
validator.validate(new DOMSource(document), new DOMResult());
assertFalse(eh.isAnyError());
}
}
/**
* Check for the same imported schemas but will use SAXParserFactory and try
* parsing using the SAXParser. SCHEMA_SOURCE attribute is using for this
* test.
*
* @throws Exception If any errors occur.
* @see <a href="content/coins.xsd">coins.xsd</a>
* @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a>
*/
@Test(groups = {"readLocalFiles"})
public void testGetOwnerItemList1() throws Exception {
String xsdFile = XML_DIR + "coins.xsd";
String xmlFile = XML_DIR + "coins.xml";
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
sp.setProperty(JAXP_SCHEMA_SOURCE, xsdFile);
MyErrorHandler eh = new MyErrorHandler();
sp.parse(new File(xmlFile), eh);
assertFalse(eh.isAnyError());
}
/**
* Check usage of javax.xml.datatype.Duration class.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readLocalFiles"})
public void testGetItemDuration() throws Exception {
String xmlFile = XML_DIR + "itemsDuration.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document document = dbf.newDocumentBuilder().parse(xmlFile);
Element durationElement = (Element) document.getElementsByTagName("sellDuration").item(0);
NodeList childList = durationElement.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
System.out.println("child " + i + childList.item(i));
}
Duration duration = DatatypeFactory.newInstance().newDuration("P365D");
Duration sellDuration = DatatypeFactory.newInstance().newDuration(childList.item(0).getNodeValue());
assertFalse(sellDuration.isShorterThan(duration));
assertFalse(sellDuration.isLongerThan(duration));
assertEquals(sellDuration.getField(DatatypeConstants.DAYS), BigInteger.valueOf(365));
assertEquals(sellDuration.normalizeWith(new GregorianCalendar(1999, 2, 22)), duration);
Duration myDuration = sellDuration.add(duration);
assertEquals(myDuration.normalizeWith(new GregorianCalendar(2003, 2, 22)),
DatatypeFactory.newInstance().newDuration("P730D"));
}
/**
* Check usage of TypeInfo interface introduced in DOM L3.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readLocalFiles"})
public void testGetTypeInfo() throws Exception {
String xmlFile = XML_DIR + "accountInfo.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
docBuilder.setErrorHandler(new MyErrorHandler());
Document document = docBuilder.parse(xmlFile);
Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0);
TypeInfo typeInfo = userId.getSchemaTypeInfo();
assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger"));
assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI));
Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0);
TypeInfo roletypeInfo = role.getSchemaTypeInfo();
assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell"));
assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS));
}
}
| lostdj/Jaklin-OpenJDK-JAXP | test/javax/xml/jaxp/functional/test/auctionportal/AuctionController.java | Java | gpl-2.0 | 14,668 |
<?php
/**
* Custom functions that act independently of the theme templates
*
* Eventually, some of the functionality here could be replaced by core features
*
* @package Decode
*/
/**
* Get our wp_nav_menu() fallback, wp_page_menu(), to show a home link.
*/
if ( ! function_exists( 'decode_page_menu_args' ) ) {
function decode_page_menu_args( $args ) {
$args['show_home'] = true;
return $args;
}
add_filter( 'wp_page_menu_args', 'decode_page_menu_args' );
}
/**
* Adds custom classes to the array of body classes.
*/
if ( ! function_exists( 'decode_body_classes' ) ) {
function decode_body_classes( $classes ) {
// Adds a class of group-blog to blogs with more than 1 published author
if ( is_multi_author() ) {
$classes[] = 'group-blog';
}
return $classes;
}
}
add_filter( 'body_class', 'decode_body_classes' );
/**
* Filter in a link to a content ID attribute for the next/previous image links on image attachment pages
*/
if ( ! function_exists( 'decode_enhanced_image_navigation' ) ) {
function decode_enhanced_image_navigation( $url, $id ) {
if ( ! is_attachment() && ! wp_attachment_is_image( $id ) )
return $url;
$image = get_post( $id );
if ( ! empty( $image->post_parent ) && $image->post_parent != $id )
$url .= '#main';
return $url;
}
}
add_filter( 'attachment_link', 'decode_enhanced_image_navigation', 10, 2 );
/**
* Highlight search terms in search results.
*/
function decode_highlight_search_results( $text ) {
if ( is_search() ) {
$sr = get_search_query();
$keys = implode( '|', explode( ' ', get_search_query() ) );
if ($keys != '') { // Check for empty search, and don't modify text if empty
$text = preg_replace( '/(' . $keys .')/iu', '<mark class="search-highlight">\0</mark>', $text );
}
}
return $text;
}
add_filter( 'the_excerpt', 'decode_highlight_search_results' );
add_filter( 'the_title', 'decode_highlight_search_results' );
/**
* Link to post in excerpt [...] links.
*/
if ( ! function_exists( 'link_ellipses' ) ) {
function link_ellipses( $more ) {
if ( ! is_search() ) {
return ' <a class="read-more" href="'. get_permalink( get_the_ID() ) . '">[…]</a>';
}
}
}
add_filter( 'excerpt_more', 'link_ellipses' );
if ( ! function_exists( '_wp_render_title_tag' ) ) :
/**
* Filters wp_title to print a neat <title> tag based on what is being viewed.
*
* @param string $title Default title text for current view.
* @param string $sep Optional separator.
* @return string The filtered title.
*/
function decode_wp_title( $title, $sep ) {
if ( is_feed() ) {
return $title;
}
global $page, $paged;
// Add the blog name
$title .= get_bloginfo( 'name', 'display' );
// Add the blog description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) ) {
$title .= " $sep $site_description";
}
// Add a page number if necessary:
if ( ( $paged >= 2 || $page >= 2 ) && ! is_404() ) {
$title .= " $sep " . sprintf( __( 'Page %s', 'decode' ), max( $paged, $page ) );
}
return $title;
}
add_filter( 'wp_title', 'decode_wp_title', 10, 2 );
endif;
if ( ! function_exists( '_wp_render_title_tag' ) ) :
/**
* Title shim for sites older than WordPress 4.1.
*
* @link https://make.wordpress.org/core/2014/10/29/title-tags-in-4-1/
* @todo Remove this function when WordPress 4.3 is released.
*/
function decode_render_title() {
?>
<title><?php wp_title( '|', false, 'right' ); ?></title>
<?php
}
add_action( 'wp_head', 'decode_render_title' );
endif;
/**
* Sets the authordata global when viewing an author archive.
*
* This provides backwards compatibility for WP versions below 3.7
* that don't have this change:
* http://core.trac.wordpress.org/changeset/25574.
*
* It removes the need to call the_post() and rewind_posts() in an author
* template to print information about the author.
*
* @global WP_Query $wp_query WordPress Query object.
* @return void
*/
if ( ! function_exists( 'decode_setup_author' ) ) {
function decode_setup_author() {
global $wp_query;
if ( $wp_query->is_author() && isset( $wp_query->post ) ) {
$GLOBALS['authordata'] = get_userdata( $wp_query->post->post_author );
}
}
}
add_action( 'wp', 'decode_setup_author' ); | casrep/wordpress-blog | wp-content/themes/decode/inc/extras.php | PHP | gpl-2.0 | 4,335 |
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2014 Adept Technology
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
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
robots@mobilerobots.com or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 1.3.40
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.mobilerobots.Aria;
public class ArUrg extends ArLaser {
/* (begin code from javabody_derived typemap) */
private long swigCPtr;
/* for internal use by swig only */
public ArUrg(long cPtr, boolean cMemoryOwn) {
super(AriaJavaJNI.SWIGArUrgUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/* for internal use by swig only */
public static long getCPtr(ArUrg obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
/* (end code from javabody_derived typemap) */
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
AriaJavaJNI.delete_ArUrg(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public ArUrg(int laserNumber, String name) {
this(AriaJavaJNI.new_ArUrg__SWIG_0(laserNumber, name), true);
}
public ArUrg(int laserNumber) {
this(AriaJavaJNI.new_ArUrg__SWIG_1(laserNumber), true);
}
public boolean blockingConnect() {
return AriaJavaJNI.ArUrg_blockingConnect(swigCPtr, this);
}
public boolean asyncConnect() {
return AriaJavaJNI.ArUrg_asyncConnect(swigCPtr, this);
}
public boolean disconnect() {
return AriaJavaJNI.ArUrg_disconnect(swigCPtr, this);
}
public boolean isConnected() {
return AriaJavaJNI.ArUrg_isConnected(swigCPtr, this);
}
public boolean isTryingToConnect() {
return AriaJavaJNI.ArUrg_isTryingToConnect(swigCPtr, this);
}
public void log() {
AriaJavaJNI.ArUrg_log(swigCPtr, this);
}
}
| sfe1012/Robot | java/com/mobilerobots/Aria/ArUrg.java | Java | gpl-2.0 | 3,101 |
// Copyright (C) 2007, 2008, 2009 EPITA Research and Development Laboratory (LRDE)
//
// This file is part of Olena.
//
// Olena is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation, version 2 of the License.
//
// Olena 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 Olena. If not, see <http://www.gnu.org/licenses/>.
//
// As a special exception, you may use this file as part of a free
// software project without restriction. Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to produce
// an executable, this file does not by itself cause the resulting
// executable to be covered by the GNU General Public License. This
// exception does not however invalidate any other reasons why the
// executable file might be covered by the GNU General Public License.
#include <mln/core/image/image2d.hh>
#include <mln/core/image/dmorph/sub_image.hh>
#include <mln/core/image/dmorph/image_if.hh>
#include <mln/fun/p2b/chess.hh>
#include <mln/border/get.hh>
#include <mln/literal/origin.hh>
struct f_box2d_t : mln::Function_v2b< f_box2d_t >
{
f_box2d_t(const mln::box2d& b)
: b_(b)
{
}
mln::box2d b_;
bool operator()(const mln::point2d& p) const
{
return b_.has(p);
}
};
int main()
{
using namespace mln;
typedef image2d<int> I;
box2d b(literal::origin, point2d(1,1));
f_box2d_t f_b(b);
I ima(3,3, 51);
mln_assertion(border::get(ima) == 51);
mln_assertion(ima.has(point2d(2,2)) == true);
sub_image<I, box2d> sub(ima, b);
mln_assertion(sub.has(point2d(2,2)) == false &&
sub.has(point2d(2,2)) == false);
mln_assertion(border::get(sub) == 0);
image_if<I, f_box2d_t> imaif(ima, f_b);
mln_assertion(imaif.has(point2d(2,2)) == false &&
ima.has(point2d(2,2)) == true);
mln_assertion(border::get(imaif) == 0);
mln_assertion(border::get((ima | b) | f_b) == 0);
}
| glazzara/olena | milena/tests/border/get.cc | C++ | gpl-2.0 | 2,307 |
<?php
/**
* GISMO block
*
* @package block_gismo
* @copyright eLab Christian Milani
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// error mode
$error_mode = (isset($error_mode) AND in_array($error_mode, array("json", "moodle"))) ? $error_mode : "moodle";
// define constants
if (!defined('ROOT')) {
//define('ROOT', (realpath(dirname( __FILE__ )) . DIRECTORY_SEPARATOR));
define('ROOT', substr(realpath(dirname(__FILE__)), 0, stripos(realpath(dirname(__FILE__)), "blocks", 0)) . 'blocks/gismo/');
}
//$path_base=substr(realpath(dirname( __FILE__ )),0,stripos(realpath(dirname( __FILE__ )),"blocks",0)).'blocks/gismo/';
if (!defined('LIB_DIR')) {
define('LIB_DIR', ROOT . "lib" . DIRECTORY_SEPARATOR);
//define('LIB_DIR', $path_base . "lib" . DIRECTORY_SEPARATOR);
}
// include moodle config file
require_once realpath(ROOT . ".." . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "config.php");
$q = optional_param('q', '', PARAM_TEXT);
$srv_data_encoded = required_param('srv_data',PARAM_RAW);
// query filter between pages
$query = (isset($q)) ? addslashes($q) : '';
// LIBRARIES MANAGEMENT
// Please use this section to set server side and cliend side libraries to be included
// server side: please note that '.php' extension will be automatically added
$server_side_libraries = array("third_parties" => array());
// client side: please note that '.js' extension will NOT be automatically added, in order to allow to create file thgat can be parsed by PHP
$client_side_libraries = array("gismo" => array("gismo.js.php", "top_menu.js.php", "left_menu.js.php", "time_line.js", "gismo_util.js"),
"third_parties" => array("jquery/jquery-1.10.0.min.js",
"jquery-ui-1.10.3/js/jquery-ui-1.10.3.custom.min.js",
"jqplot.1.0.8r1250/jquery.jqplot.min.js",
"jqplot.1.0.8r1250/plugins/jqplot.barRenderer.min.js",
"jqplot.1.0.8r1250/plugins/jqplot.canvasAxisLabelRenderer.min.js",
"jqplot.1.0.8r1250/plugins/jqplot.canvasAxisTickRenderer.min.js",
"jqplot.1.0.8r1250/plugins/jqplot.canvasTextRenderer.min.js",
"jqplot.1.0.8r1250/plugins/jqplot.categoryAxisRenderer.min.js",
"jqplot.1.0.8r1250/plugins/jqplot.dateAxisRenderer.min.js",
"jqplot.1.0.8r1250/plugins/jqplot.highlighter.min.js",
"jqplot.1.0.8r1250/plugins/jqplot.pointLabels.min.js",
"simpleFadeSlideShow/fadeSlideShow.min.js"
));
// include server-side libraries libraries
if (is_array($server_side_libraries) AND count($server_side_libraries) > 0) {
foreach ($server_side_libraries as $key => $server_side_libs) {
if (is_array($server_side_libs) AND count($server_side_libs) > 0) {
foreach ($server_side_libs as $server_side_lib) {
$lib_full_path = LIB_DIR . $key . DIRECTORY_SEPARATOR . "server_side" . DIRECTORY_SEPARATOR . $server_side_lib . ".php";
if (is_file($lib_full_path) AND is_readable($lib_full_path)) {
require_once $lib_full_path;
}
}
}
}
}
// check input data
if (!isset($srv_data_encoded)) {
block_gismo\GISMOutil::gismo_error('err_srv_data_not_set', $error_mode);
exit;
}
$srv_data = (object) unserialize(base64_decode(urldecode($srv_data_encoded)));
// course id
if (!property_exists($srv_data, "course_id")) {
block_gismo\GISMOutil::gismo_error('err_course_not_set', $error_mode);
exit;
}
// block instance id
if (!property_exists($srv_data, "block_instance_id")) {
block_gismo\GISMOutil::gismo_error('err_block_instance_id_not_set', $error_mode);
exit;
}
// check authentication
switch ($error_mode) {
case "json":
try {
require_login($srv_data->course_id, false, NULL, true, true);
} catch (Exception $e) {
block_gismo\GISMOutil::gismo_error("err_authentication", $error_mode);
exit;
}
break;
case "moodle":
default:
require_login();
break;
}
// extract the course
if (!$course = $DB->get_record("course", array("id" => intval($srv_data->course_id)))) {
block_gismo\GISMOutil::gismo_error('err_course_not_set', $error_mode);
exit;
}
// context
$context_obj = context_block::instance(intval($srv_data->block_instance_id));
//Get block_gismo settings
$gismoconfig = get_config('block_gismo');
if ($gismoconfig->student_reporting === "false") {
// check authorization
require_capability('block/gismo:view', $context_obj);
}
// get gismo settings
$gismo_settings = $DB->get_field("block_instances", "configdata", array("id" => intval($srv_data->block_instance_id)));
if (is_null($gismo_settings) OR $gismo_settings === "") {
$gismo_settings = get_object_vars(block_gismo\GISMOutil::get_default_options());
} else {
$gismo_settings = get_object_vars(unserialize(base64_decode($gismo_settings)));
if (is_array($gismo_settings) AND count($gismo_settings) > 0) {
foreach ($gismo_settings as $key => $value) {
if (is_numeric($value)) {
if (strval(intval($value)) === strval($value)) {
$gismo_settings[$key] = intval($value);
} else if (strval(floatval($value)) === strval($value)) {
$gismo_settings[$key] = floatval($value);
}
}
}
}
// include_hidden_items
if (!array_key_exists("include_hidden_items", $gismo_settings)) {
$gismo_settings["include_hidden_items"] = 1;
}
}
$block_gismo_config = json_encode($gismo_settings);
// actor (teacher or student)
$actor = "student";
if (has_capability("block/gismo:trackuser", $context_obj)) {
$actor = "student";
}
if (has_capability("block/gismo:trackteacher", $context_obj)) {
$actor = "teacher";
}
?>
| lglopezf/Moodle2.8.2_Adaptativo_Trus_Model | blocks/gismo/common.php | PHP | gpl-2.0 | 5,932 |
<?php
/**
* The following variables are available in this template:
* - $this: the CrudCode object
*/
?>
<div id="mainPage" class="main">
<?php
echo "<?php\n";
$nameColumn = $this->guessNameColumn($this->tableSchema->columns);
$label = $this->pluralize($this->class2name($this->modelClass));
echo "\$this->breadcrumbs=array(
'$label'=>array('index'),
\$model->{$nameColumn}=>array('view','id'=>\$model->{$this->tableSchema->primaryKey}),
'Update',
);\n";
?>
$title=Yii::t('default', 'Update <?php echo $this->modelClass ?>: ');
$contextDesc = Yii::t('default', 'Available actions that may be taken on <?php echo $this->modelClass; ?>.');
$this->menu=array(
array('label'=> Yii::t('default', 'Create a new <?php echo $this->modelClass; ?>'), 'url'=>array('create'),'description' => Yii::t('default', 'This action create a new <?php echo $this->modelClass; ?>')),
array('label'=> Yii::t('default', 'List <?php echo $this->modelClass; ?>'), 'url'=>array('index'),'description' => Yii::t('default', 'This action list all <?php echo $this->pluralize($this->class2name($this->modelClass)) ?>, you can search, delete and update')),
);
?>
<div class="twoColumn">
<div class="columnone" style="padding-right: 1em">
<?php echo "<?php echo \$this->renderPartial('_form', array('model'=>\$model,'title'=>\$title)); ?>"; ?>
</div>
<div class="columntwo">
<?php echo "<?php echo \$this->renderPartial('////common/defaultcontext', array('contextDesc'=>\$contextDesc)); ?>"; ?>
</div>
</div>
</div> | ipti/tag | app/gii/crud/templates/yvj/update.php | PHP | gpl-2.0 | 1,608 |
/*
* #%L
* BSD implementations of Bio-Formats readers and writers
* %%
* Copyright (C) 2005 - 2016 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package loci.formats.codec;
import java.io.IOException;
import java.util.Vector;
import loci.common.ByteArrayHandle;
import loci.common.DataTools;
import loci.common.RandomAccessInputStream;
import loci.formats.FormatException;
import loci.formats.UnsupportedCompressionException;
/**
* Decompresses lossless JPEG images.
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class LosslessJPEGCodec extends BaseCodec {
// -- Constants --
// Start of Frame markers - non-differential, Huffman coding
private static final int SOF0 = 0xffc0; // baseline DCT
private static final int SOF1 = 0xffc1; // extended sequential DCT
private static final int SOF2 = 0xffc2; // progressive DCT
private static final int SOF3 = 0xffc3; // lossless (sequential)
// Start of Frame markers - differential, Huffman coding
private static final int SOF5 = 0xffc5; // differential sequential DCT
private static final int SOF6 = 0xffc6; // differential progressive DCT
private static final int SOF7 = 0xffc7; // differential lossless (sequential)
// Start of Frame markers - non-differential, arithmetic coding
private static final int JPG = 0xffc8; // reserved for JPEG extensions
private static final int SOF9 = 0xffc9; // extended sequential DCT
private static final int SOF10 = 0xffca; // progressive DCT
private static final int SOF11 = 0xffcb; // lossless (sequential)
// Start of Frame markers - differential, arithmetic coding
private static final int SOF13 = 0xffcd; // differential sequential DCT
private static final int SOF14 = 0xffce; // differential progressive DCT
private static final int SOF15 = 0xffcf; // differential lossless (sequential)
private static final int DHT = 0xffc4; // define Huffman table(s)
private static final int DAC = 0xffcc; // define arithmetic coding conditions
// Restart interval termination
private static final int RST_0 = 0xffd0;
private static final int RST_1 = 0xffd1;
private static final int RST_2 = 0xffd2;
private static final int RST_3 = 0xffd3;
private static final int RST_4 = 0xffd4;
private static final int RST_5 = 0xffd5;
private static final int RST_6 = 0xffd6;
private static final int RST_7 = 0xffd7;
private static final int SOI = 0xffd8; // start of image
private static final int EOI = 0xffd9; // end of image
private static final int SOS = 0xffda; // start of scan
private static final int DQT = 0xffdb; // define quantization table(s)
private static final int DNL = 0xffdc; // define number of lines
private static final int DRI = 0xffdd; // define restart interval
private static final int DHP = 0xffde; // define hierarchical progression
private static final int EXP = 0xffdf; // expand reference components
private static final int COM = 0xfffe; // comment
// -- Codec API methods --
/* @see Codec#compress(byte[], CodecOptions) */
@Override
public byte[] compress(byte[] data, CodecOptions options)
throws FormatException
{
throw new UnsupportedCompressionException(
"Lossless JPEG compression not supported");
}
/**
* The CodecOptions parameter should have the following fields set:
* {@link CodecOptions#interleaved interleaved}
* {@link CodecOptions#littleEndian littleEndian}
*
* @see Codec#decompress(RandomAccessInputStream, CodecOptions)
*/
@Override
public byte[] decompress(RandomAccessInputStream in, CodecOptions options)
throws FormatException, IOException
{
if (in == null)
throw new IllegalArgumentException("No data to decompress.");
if (options == null) options = CodecOptions.getDefaultOptions();
byte[] buf = new byte[0];
int width = 0, height = 0;
int bitsPerSample = 0, nComponents = 0, bytesPerSample = 0;
int[] horizontalSampling = null, verticalSampling = null;
int[] quantizationTable = null;
short[][] huffmanTables = null;
int startPredictor = 0, endPredictor = 0;
int pointTransform = 0;
int[] dcTable = null, acTable = null;
while (in.getFilePointer() < in.length() - 1) {
int code = in.readShort() & 0xffff;
int length = in.readShort() & 0xffff;
long fp = in.getFilePointer();
if (length > 0xff00) {
length = 0;
in.seek(fp - 2);
}
else if (code == SOS) {
nComponents = in.read();
dcTable = new int[nComponents];
acTable = new int[nComponents];
for (int i=0; i<nComponents; i++) {
int componentSelector = in.read();
int tableSelector = in.read();
dcTable[i] = (tableSelector & 0xf0) >> 4;
acTable[i] = tableSelector & 0xf;
}
startPredictor = in.read();
endPredictor = in.read();
pointTransform = in.read() & 0xf;
// read image data
byte[] toDecode = new byte[(int) (in.length() - in.getFilePointer())];
in.read(toDecode);
// scrub out byte stuffing
ByteVector b = new ByteVector();
for (int i=0; i<toDecode.length; i++) {
byte val = toDecode[i];
if (val == (byte) 0xff) {
if (toDecode[i + 1] == 0)
b.add(val);
i++;
} else {
b.add(val);
}
}
toDecode = b.toByteArray();
RandomAccessInputStream bb = new RandomAccessInputStream(
new ByteArrayHandle(toDecode));
HuffmanCodec huffman = new HuffmanCodec();
HuffmanCodecOptions huffmanOptions = new HuffmanCodecOptions();
huffmanOptions.bitsPerSample = bitsPerSample;
huffmanOptions.maxBytes = buf.length / nComponents;
int nextSample = 0;
while (nextSample < buf.length / nComponents) {
for (int i=0; i<nComponents; i++) {
huffmanOptions.table = huffmanTables[dcTable[i]];
int v = 0;
if (huffmanTables != null) {
v = huffman.getSample(bb, huffmanOptions);
if (nextSample == 0) {
v += (int) Math.pow(2, bitsPerSample - 1);
}
}
else {
throw new UnsupportedCompressionException(
"Arithmetic coding not supported");
}
// apply predictor to the sample
int predictor = startPredictor;
if (nextSample < width * bytesPerSample) predictor = 1;
else if ((nextSample % (width * bytesPerSample)) == 0) {
predictor = 2;
}
int componentOffset = i * (buf.length / nComponents);
int indexA = nextSample - bytesPerSample + componentOffset;
int indexB = nextSample - width * bytesPerSample + componentOffset;
int indexC = nextSample - (width + 1) * bytesPerSample +
componentOffset;
int sampleA = indexA < 0 ? 0 :
DataTools.bytesToInt(buf, indexA, bytesPerSample, false);
int sampleB = indexB < 0 ? 0 :
DataTools.bytesToInt(buf, indexB, bytesPerSample, false);
int sampleC = indexC < 0 ? 0 :
DataTools.bytesToInt(buf, indexC, bytesPerSample, false);
if (nextSample > 0) {
int pred = 0;
switch (predictor) {
case 1:
pred = sampleA;
break;
case 2:
pred = sampleB;
break;
case 3:
pred = sampleC;
break;
case 4:
pred = sampleA + sampleB + sampleC;
break;
case 5:
pred = sampleA + ((sampleB - sampleC) / 2);
break;
case 6:
pred = sampleB + ((sampleA - sampleC) / 2);
break;
case 7:
pred = (sampleA + sampleB) / 2;
break;
}
v += pred;
}
int offset = componentOffset + nextSample;
DataTools.unpackBytes(v, buf, offset, bytesPerSample, false);
}
nextSample += bytesPerSample;
}
bb.close();
}
else {
length -= 2; // stored length includes length param
if (length == 0) continue;
if (code == EOI) { }
else if (code == SOF3) {
// lossless w/Huffman coding
bitsPerSample = in.read();
height = in.readShort();
width = in.readShort();
nComponents = in.read();
horizontalSampling = new int[nComponents];
verticalSampling = new int[nComponents];
quantizationTable = new int[nComponents];
for (int i=0; i<nComponents; i++) {
in.skipBytes(1);
int s = in.read();
horizontalSampling[i] = (s & 0xf0) >> 4;
verticalSampling[i] = s & 0x0f;
quantizationTable[i] = in.read();
}
bytesPerSample = bitsPerSample / 8;
if ((bitsPerSample % 8) != 0) bytesPerSample++;
buf = new byte[width * height * nComponents * bytesPerSample];
}
else if (code == SOF11) {
throw new UnsupportedCompressionException(
"Arithmetic coding is not yet supported");
}
else if (code == DHT) {
if (huffmanTables == null) {
huffmanTables = new short[4][];
}
int bytesRead = 0;
while (bytesRead < length) {
int s = in.read();
byte tableClass = (byte) ((s & 0xf0) >> 4);
byte destination = (byte) (s & 0xf);
int[] nCodes = new int[16];
Vector table = new Vector();
for (int i=0; i<nCodes.length; i++) {
nCodes[i] = in.read();
table.add(new Short((short) nCodes[i]));
}
for (int i=0; i<nCodes.length; i++) {
for (int j=0; j<nCodes[i]; j++) {
table.add(new Short((short) (in.read() & 0xff)));
}
}
huffmanTables[destination] = new short[table.size()];
for (int i=0; i<huffmanTables[destination].length; i++) {
huffmanTables[destination][i] = ((Short) table.get(i)).shortValue();
}
bytesRead += table.size() + 1;
}
}
in.seek(fp + length);
}
}
if (options.interleaved && nComponents > 1) {
// data is stored in planar (RRR...GGG...BBB...) order
byte[] newBuf = new byte[buf.length];
for (int i=0; i<buf.length; i+=nComponents*bytesPerSample) {
for (int c=0; c<nComponents; c++) {
int src = c * (buf.length / nComponents) + (i / nComponents);
int dst = i + c * bytesPerSample;
System.arraycopy(buf, src, newBuf, dst, bytesPerSample);
}
}
buf = newBuf;
}
if (options.littleEndian && bytesPerSample > 1) {
// data is stored in big endian order
// reverse the bytes in each sample
byte[] newBuf = new byte[buf.length];
for (int i=0; i<buf.length; i+=bytesPerSample) {
for (int q=0; q<bytesPerSample; q++) {
newBuf[i + bytesPerSample - q - 1] = buf[i + q];
}
}
buf = newBuf;
}
return buf;
}
}
| imunro/bioformats | components/formats-bsd/src/loci/formats/codec/LosslessJPEGCodec.java | Java | gpl-2.0 | 12,867 |
<?php
/**
* The template for displaying all pages
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages and that
* other 'pages' on your WordPress site will use a different template.
*
* @package WordPress
* @subpackage Twenty_Fourteen
* @since Twenty Fourteen 1.0
*/
get_header(); ?>
<div id="main-content" class="main-content">
<?php
if (is_front_page() && twentyfourteen_has_featured_posts()) {
// Include the featured content template.
get_template_part('featured-content');
}
?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php
// Start the Loop.
while (have_posts()) : the_post();
// Include the page content template.
get_template_part('content', 'page');
// If comments are open or we have at least one comment, load up the comment template.
if (comments_open() || get_comments_number()) {
comments_template();
}
endwhile;
?>
</div>
<!-- #content -->
</div>
<!-- #primary -->
<?php get_sidebar('content'); ?>
</div><!-- #main-content -->
<?php
get_sidebar();
get_footer();
| richardbota/WordPress-Theme-Development-with-Bootstrap | wp-content/themes/twentyfourteen/page.php | PHP | gpl-2.0 | 1,451 |
<?php
namespace SJBR\StaticInfoTables\Domain\Model;
/***************************************************************
* Copyright notice
*
* (c) 2011-2012 Armin Rüdiger Vieweg <info@professorweb.de>
* (c) 2013 Stanislas Rolland <typo3(arobas)sjbr.ca>
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* The Country model
*
* @copyright Copyright belongs to the respective authors
* @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later
*/
class Country extends AbstractEntity {
/**
* The German short name
* @var string
*/
protected $shortNameDe = '';
/**
* Sets the German short name.
*
* @param string $shortNameDe
*
* @return void
*/
public function setShortNameDe($shortNameDe) {
$this->shortNameDe = $shortNameDe;
}
/**
* Gets the German short name.
*
* @return string
*/
public function getShortNameDe() {
return $this->shortNameDe;
}
}
?> | Loopshape/Portfolio | hostweb/typo3conf/ext/static_info_tables_de/Classes/Domain/Model/Country.php | PHP | gpl-2.0 | 1,688 |
using System;
using System.Reflection;
namespace OLPL_API_Server.Areas.HelpPage.ModelDescriptions
{
public interface IModelDocumentationProvider
{
string GetDocumentation(MemberInfo member);
string GetDocumentation(Type type);
}
} | gholpl/OLPL_API-Server | OLPL-API-Server/obj/Debug/Package/PackageTmp/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs | C# | gpl-2.0 | 260 |
# Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""Standard input/out/err support.
API Stability: semi-stable
Future Plans: support for stderr, perhaps
Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
"""
# system imports
import sys, os, select, errno
# Sibling Imports
import abstract, fdesc, protocol
from main import CONNECTION_LOST
_stdio_in_use = 0
class StandardIOWriter(abstract.FileDescriptor):
connected = 1
ic = 0
def __init__(self):
abstract.FileDescriptor.__init__(self)
self.fileno = sys.__stdout__.fileno
fdesc.setNonBlocking(self.fileno())
def writeSomeData(self, data):
try:
return os.write(self.fileno(), data)
return rv
except IOError, io:
if io.args[0] == errno.EAGAIN:
return 0
elif io.args[0] == errno.EPERM:
return 0
return CONNECTION_LOST
except OSError, ose:
if ose.errno == errno.EPIPE:
return CONNECTION_LOST
if ose.errno == errno.EAGAIN:
return 0
raise
def connectionLost(self, reason):
abstract.FileDescriptor.connectionLost(self, reason)
os.close(self.fileno())
class StandardIO(abstract.FileDescriptor):
"""I can connect Standard IO to a twisted.protocol
I act as a selectable for sys.stdin, and provide a write method that writes
to stdout.
"""
def __init__(self, protocol):
"""Create me with a protocol.
This will fail if a StandardIO has already been instantiated.
"""
abstract.FileDescriptor.__init__(self)
global _stdio_in_use
if _stdio_in_use:
raise RuntimeError, "Standard IO already in use."
_stdio_in_use = 1
self.fileno = sys.__stdin__.fileno
fdesc.setNonBlocking(self.fileno())
self.protocol = protocol
self.startReading()
self.writer = StandardIOWriter()
self.protocol.makeConnection(self)
def write(self, data):
"""Write some data to standard output.
"""
self.writer.write(data)
def doRead(self):
"""Some data's readable from standard input.
"""
return fdesc.readFromFD(self.fileno(), self.protocol.dataReceived)
def closeStdin(self):
"""Close standard input.
"""
self.writer.loseConnection()
def connectionLost(self, reason):
"""The connection was lost.
"""
self.protocol.connectionLost()
| fxia22/ASM_xf | PythonD/site_python/twisted/internet/stdio.py | Python | gpl-2.0 | 3,287 |
/**
Copyright 2008, 2009 UFPE - Universidade Federal de Pernambuco
Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS
O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como
publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença.
Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes.
Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENCA.txt", junto com este programa, se não, escreva para a Fundação do Software Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
**/
package br.ufpe.cin.amadeus.amadeus_mobile.util;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile;
import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Forum;
import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Game;
import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.LearningObject;
import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll;
public class Conversor {
/**
* Method that converts AMADeUs Course object into Mobile Course object
* @param curso - AMADeUs Course to be converted
* @return - Converted Mobile Course object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile converterCurso(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Course curso){
br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile();
retorno.setId(curso.getId());
retorno.setName(curso.getName());
retorno.setContent(curso.getContent());
retorno.setObjectives(curso.getObjectives());
retorno.setModules(converterModulos(curso.getModules()));
retorno.setKeywords(converterKeywords(curso.getKeywords()));
ArrayList<String> nomes = new ArrayList<String>();
nomes.add(curso.getProfessor().getName());
retorno.setTeachers(nomes);
retorno.setCount(0);
retorno.setMaxAmountStudents(curso.getMaxAmountStudents());
retorno.setFinalCourseDate(curso.getFinalCourseDate());
retorno.setInitialCourseDate(curso.getInitialCourseDate());
return retorno;
}
/**
* Method that converts a AMADeUs Course object list into Mobile Course object list
* @param cursos - AMADeUs Course object list to be converted
* @return - Converted Mobile Course object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile> converterCursos(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Course> cursos){
ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Course c : cursos){
retorno.add(Conversor.converterCurso(c));
}
return retorno;
}
/**
* Method that converts AMADeUs Module object into Mobile Module object
* @param modulo - AMADeUs Module object to be converted
* @return - Converted Mobile Module object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile converterModulo(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Module modulo){
br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile mod = new br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile(modulo.getId(), modulo.getName());
List<HomeworkMobile> listHomeworks = new ArrayList<HomeworkMobile>();
for (Poll poll : modulo.getPolls()) {
listHomeworks.add( Conversor.converterPollToHomework(poll) );
}
for (Forum forum : modulo.getForums()) {
listHomeworks.add( Conversor.converterForumToHomework(forum) );
}
for(Game game : modulo.getGames()){
listHomeworks.add( Conversor.converterGameToHomework(game) );
}
for(LearningObject learning : modulo.getLearningObjects()){
listHomeworks.add( Conversor.converterLearningObjectToHomework(learning) );
}
mod.setHomeworks(listHomeworks);
mod.setMaterials(converterMaterials(modulo.getMaterials()));
return mod;
}
/**
* Mothod that converts a AMADeUs Module object list into Mobile Module object list
* @param modulos - AMADeUs Module object list to be converted
* @return - Converted Mobile Module object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile> converterModulos(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Module> modulos){
ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Module m : modulos){
retorno.add(Conversor.converterModulo(m));
}
return retorno;
}
/**
* Method that converts AMADeUs Homework object into Mobile Homework object
* @param home - AMADeUs Homework object to be converted
* @return - Converted Mobile Homework object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Homework home){
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(home.getId());
retorno.setName(home.getName());
retorno.setDescription(home.getDescription());
retorno.setInitDate(home.getInitDate());
retorno.setDeadline(home.getDeadline());
retorno.setAlowPostponing(home.getAllowPostponing());
retorno.setInfoExtra("");
retorno.setTypeActivity(HomeworkMobile.HOMEWORK);
return retorno;
}
/**
* Method that converts AMADeUs Game object into Mobile Homework object
* @param game - AMADeUs Game object to be converted
* @return - Converted Mobile Homework object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterGameToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Game game){
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(game.getId());
retorno.setName(game.getName());
retorno.setDescription(game.getDescription());
retorno.setInfoExtra(game.getUrl());
retorno.setTypeActivity(HomeworkMobile.GAME);
return retorno;
}
/**
* Method that converts AMADeUs Forum object into Mobile Homework object
* @param forum - AMADeUs Forum object to be converted
* @return - Converted Mobile Homework object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterForumToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Forum forum){
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(forum.getId());
retorno.setName(forum.getName());
retorno.setDescription(forum.getDescription());
retorno.setInitDate(forum.getCreationDate());
retorno.setInfoExtra("");
retorno.setTypeActivity(HomeworkMobile.FORUM);
return retorno;
}
/**
* Method that converts AMADeUs Poll object into Mobile Homework object
* @param poll - AMADeUs Poll object to be converted
* @return - Converted Mobile Homework object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterPollToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll poll){
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(poll.getId());
retorno.setName(poll.getName());
retorno.setDescription(poll.getQuestion());
retorno.setInitDate(poll.getCreationDate());
retorno.setDeadline(poll.getFinishDate());
retorno.setInfoExtra("");
retorno.setTypeActivity(HomeworkMobile.POLL);
return retorno;
}
/**
* Method that converts AMADeUs Multimedia object into Mobile Homework object
* @param media - AMADeUs Multimedia object to be converted
* @return - Converted Mobile Homework object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterMultimediaToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Multimedia media){
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(media.getId());
retorno.setName(media.getName());
retorno.setDescription(media.getDescription());
retorno.setInfoExtra(media.getUrl());
retorno.setTypeActivity(HomeworkMobile.MULTIMEDIA);
return retorno;
}
/**
* Method that converts AMADeUs Video object into Mobile Homework object
* @param video - AMADeUs Video object to be converted
* @return - Converted Mobile Homework object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterVideoToHomework(br.ufpe.cin.amadeus.amadeus_sdmm.dao.Video video){
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(video.getId());
retorno.setName(video.getName());
retorno.setDescription(video.getDescription());
retorno.setInitDate(video.getDateinsertion());
retorno.setInfoExtra(video.getTags());
retorno.setTypeActivity(HomeworkMobile.VIDEO);
return retorno;
}
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterLearningObjectToHomework(
br.ufpe.cin.amadeus.amadeus_web.domain.content_management.LearningObject learning) {
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(learning.getId());
retorno.setName(learning.getName());
retorno.setUrl(learning.getUrl());
retorno.setDescription(learning.getDescription());
retorno.setDeadline(learning.getCreationDate());
retorno.setTypeActivity(HomeworkMobile.LEARNING_OBJECT);
return retorno;
}
/**
* Method that converts AMADeUs Homework object list into Mobile Homework object list
* @param homes - AMADeUs Homework object list to be converted
* @return - Converted Mobile Homework object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile> converterHomeworks(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Homework> homes){
ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Homework h : homes){
retorno.add(Conversor.converterHomework(h));
}
return retorno;
}
/**
* Method that converts AMADeUs Material object into Mobile Material object
* @param mat - AMADeUs Material object to be converted
* @return - Mobile Material object converted
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile converterMaterial(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Material mat){
br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile();
retorno.setId(mat.getId());
retorno.setName(mat.getArchiveName());
retorno.setAuthor(converterPerson(mat.getAuthor()));
retorno.setPostDate(mat.getCreationDate());
return retorno;
}
/**
* Method that converts AMADeUs Mobile Material object list into Mobile Material object list
* @param mats - AMADeUs Material object list
* @return - Mobile Material object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile> converterMaterials(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Material> mats){
ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Material mat : mats){
retorno.add(Conversor.converterMaterial(mat));
}
return retorno;
}
/**
* Method that converts AMADeUs Keyword object into Mobile Keyword object
* @param key - AMADeUs Keyword object to be converted
* @return - Converted Keywork object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile converterKeyword(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Keyword key){
br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile();
retorno.setId(key.getId());
retorno.setName(key.getName());
retorno.setPopularity(key.getPopularity());
return retorno;
}
/**
* Method that converts AMADeUs Keyword object list into a Mobile Keyword HashSet object
* @param keys - AMADeUs Keyword object list to be converted
* @return - Mobile Keywork HashSet object list
*/
public static HashSet<br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile> converterKeywords(Set<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Keyword> keys){
HashSet<br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile> retorno = new HashSet<br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Keyword k : keys){
retorno.add(Conversor.converterKeyword(k));
}
return retorno;
}
/**
* Method that converts AMADeUs Choice object into Mobile Choice object
* @param ch - AMADeUs Choice object to be converted
* @return - Converted Mobile Choice object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile converterChoice(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice ch){
br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile();
retorno.setId(ch.getId());
retorno.setAlternative(ch.getAlternative());
retorno.setVotes(ch.getVotes());
retorno.setPercentage(ch.getPercentage());
return retorno;
}
/**
* Method that converts AMADeUs Choice object list into Mobile Choice object list
* @param chs - AMADeUs Choice object list to be converted
* @return - Converted Mobile Choice object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile> converterChoices(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice> chs){
List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice c : chs){
retorno.add(Conversor.converterChoice(c));
}
return retorno;
}
/**
* Method that converts AMADeUs Poll object into Mobile Poll Object
* @param p - AMADeUs Poll object to be converted
* @return - Converted Mobile Poll object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile converterPool(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll p){
br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile();
retorno.setId(p.getId());
retorno.setName(p.getName());
retorno.setQuestion(p.getQuestion());
retorno.setInitDate(p.getCreationDate());
retorno.setFinishDate(p.getFinishDate());
retorno.setAnswered(false);
retorno.setChoices(converterChoices(p.getChoices()));
retorno.setAnsewered(converterAnswers(p.getAnswers()));
return retorno;
}
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.LearningObjectMobile converterLearningObject (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.LearningObject learning){
br.ufpe.cin.amadeus.amadeus_mobile.basics.LearningObjectMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.LearningObjectMobile();
retorno.setId(learning.getId());
retorno.setName(learning.getName());
retorno.setDescription(learning.getDescription());
retorno.setDatePublication(learning.getCreationDate());
retorno.setUrl(learning.getUrl());
return retorno;
}
/**
* Method that converts AMADeUs Poll object list into Mobile Poll object list
* @param pls - AMADeUs Poll object list
* @return - Converted Mobile object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile> converterPools(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll> pls){
List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll p : pls){
retorno.add(Conversor.converterPool(p));
}
return retorno;
}
/**
* Method that converts AMADeUs Answer object into Mobile Answer object
* @param ans - AMADeUs Answer object to be converted
* @return - Converted Mobile Answer object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile converterAnswer(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer ans){
br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile();
retorno.setId(ans.getId());
retorno.setAnswerDate(ans.getAnswerDate());
retorno.setPerson(converterPerson(ans.getPerson()));
return retorno;
}
/**
* Method that converts AMADeUs Answer object list into Mobile Answer object list
* @param anss - AMADeUs Answer object list
* @return - Converted Mobile object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile> converterAnswers(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer> anss){
List<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer an : anss){
retorno.add(Conversor.converterAnswer(an));
}
return retorno;
}
/**
* Method that converts AMADeUs Person object into Mobile Person object
* @param p - AMADeUs Person object to be converted
* @return - Converted Mobile Person object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile converterPerson(br.ufpe.cin.amadeus.amadeus_web.domain.register.Person p){
return new br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile(p.getId(), p.getAccessInfo().getLogin(), p.getPhoneNumber());
}
/**
* Method that converts AMADeUs Person object list into Mobile Person object list
* @param persons - AMADeUs Person object list to be converted
* @return - Converted Mobile Person object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile> converterPersons(List<br.ufpe.cin.amadeus.amadeus_web.domain.register.Person> persons){
List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.register.Person p : persons){
retorno.add(Conversor.converterPerson(p));
}
return retorno;
}
/**
* Method that converts Mobile Poll object into AMADeUs Poll Object
* @param p - Mobile Poll object to be converted
* @return - Converted AMADeUs Poll object
*/
public static br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll converterPool(br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile p){
br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll retorno = new br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll();
retorno.setId(p.getId());
retorno.setName(p.getName());
retorno.setQuestion(p.getQuestion());
retorno.setCreationDate(p.getInitDate());
retorno.setFinishDate(p.getFinishDate());
retorno.setChoices(converterChoices2(p.getChoices()));
retorno.setAnswers(converterAnswers2(p.getAnsewered()));
return retorno;
}
/**
* Method that converts Mobile Choice object into AMADeUs Choice object
* @param ch - Mobile Choice object to be converted
* @return - Converted AMADeUs Choice object
*/
public static br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice converterChoice(br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile ch){
br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice retorno = new br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice();
retorno.setId(ch.getId());
retorno.setAlternative(ch.getAlternative());
retorno.setVotes(ch.getVotes());
retorno.setPercentage(ch.getPercentage());
return retorno;
}
/**
* Method that converts Mobile Choiceobject list into AMADeUs Choice object list
* @param chs - Mobile Choice object list to be converted
* @return - Converted AMADeUs Choice object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice> converterChoices2(List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile> chs){
List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice>();
for (br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile c : chs){
retorno.add(Conversor.converterChoice(c));
}
return retorno;
}
/**
* Method that converts Mobile Answer object into AMADeUs Answer object
* @param ans - Mobile Answer object to be converted
* @return - Converted AMADeUs Answer object
*/
public static br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer converterAnswer(br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile ans){
br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer retorno = new br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer();
retorno.setId(ans.getId());
retorno.setAnswerDate(ans.getAnswerDate());
retorno.setPerson(converterPerson(ans.getPerson()));
return retorno;
}
/**
* Method that converts Mobile Answer object list into AMADeUs Answer object list
* @param anss - Mobile Answer object list
* @return - Converted AMADeUs Answer object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer> converterAnswers2(List<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile> anss){
List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer>();
for (br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile an : anss){
retorno.add(Conversor.converterAnswer(an));
}
return retorno;
}
/**
* Method that converts Mobile Person object into AMADeUs Person object
* @param p - Mobile Person object to be converted
* @return - Converted AMADeUs Person object
*/
public static br.ufpe.cin.amadeus.amadeus_web.domain.register.Person converterPerson(br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile p){
br.ufpe.cin.amadeus.amadeus_web.domain.register.Person p1 = new br.ufpe.cin.amadeus.amadeus_web.domain.register.Person();
p1.setId(p.getId());
p1.setName(p.getName());
p1.setPhoneNumber(p.getPhoneNumber());
return p1;
}
} | phcp/AmadeusLMS | src/br/ufpe/cin/amadeus/amadeus_mobile/util/Conversor.java | Java | gpl-2.0 | 24,368 |
package net.sf.memoranda.ui.htmleditor;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import net.sf.memoranda.ui.htmleditor.util.Local;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: </p>
* @author unascribed
* @version 1.0
*/
public class ImageDialog extends JDialog implements WindowListener {
/**
*
*/
private static final long serialVersionUID = 5326851249529076804L;
JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel header = new JLabel();
JPanel areaPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc;
JLabel jLabel1 = new JLabel();
public JTextField fileField = new JTextField();
JButton browseB = new JButton();
JLabel jLabel2 = new JLabel();
public JTextField altField = new JTextField();
JLabel jLabel3 = new JLabel();
public JTextField widthField = new JTextField();
JLabel jLabel4 = new JLabel();
public JTextField heightField = new JTextField();
JLabel jLabel5 = new JLabel();
public JTextField hspaceField = new JTextField();
JLabel jLabel6 = new JLabel();
public JTextField vspaceField = new JTextField();
JLabel jLabel7 = new JLabel();
public JTextField borderField = new JTextField();
JLabel jLabel8 = new JLabel();
String[] aligns = {"left", "right", "top", "middle", "bottom", "absmiddle",
"texttop", "baseline"};
// Note: align values are not localized because they are HTML keywords
public JComboBox<String> alignCB = new JComboBox<String>(aligns);
JLabel jLabel9 = new JLabel();
public JTextField urlField = new JTextField();
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
JButton okB = new JButton();
JButton cancelB = new JButton();
public boolean CANCELLED = false;
public ImageDialog(Frame frame) {
super(frame, Local.getString("Image"), true);
try {
jbInit();
pack();
}
catch (Exception ex) {
ex.printStackTrace();
}
super.addWindowListener(this);
}
public ImageDialog() {
this(null);
}
void jbInit() throws Exception {
this.setResizable(false);
// three Panels, so used BorderLayout for this dialog.
headerPanel.setBorder(new EmptyBorder(new Insets(0, 5, 0, 5)));
headerPanel.setBackground(Color.WHITE);
header.setFont(new java.awt.Font("Dialog", 0, 20));
header.setForeground(new Color(0, 0, 124));
header.setText(Local.getString("Image"));
header.setIcon(new ImageIcon(
net.sf.memoranda.ui.htmleditor.ImageDialog.class.getResource(
"resources/icons/imgbig.png")));
headerPanel.add(header);
this.getContentPane().add(headerPanel, BorderLayout.NORTH);
areaPanel.setBorder(new EtchedBorder(Color.white, new Color(142, 142,
142)));
jLabel1.setText(Local.getString("Image file"));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(10, 10, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel1, gbc);
fileField.setMinimumSize(new Dimension(200, 25));
fileField.setPreferredSize(new Dimension(285, 25));
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 5;
gbc.insets = new Insets(10, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
areaPanel.add(fileField, gbc);
browseB.setMinimumSize(new Dimension(25, 25));
browseB.setPreferredSize(new Dimension(25, 25));
browseB.setIcon(new ImageIcon(
net.sf.memoranda.ui.htmleditor.ImageDialog.class.getResource(
"resources/icons/fileopen16.png")));
browseB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
browseB_actionPerformed(e);
}
});
gbc = new GridBagConstraints();
gbc.gridx = 6;
gbc.gridy = 0;
gbc.insets = new Insets(10, 5, 5, 10);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(browseB, gbc);
jLabel2.setText(Local.getString("ALT text"));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = new Insets(5, 10, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel2, gbc);
altField.setPreferredSize(new Dimension(315, 25));
altField.setMinimumSize(new Dimension(200, 25));
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 6;
gbc.insets = new Insets(5, 5, 5, 10);
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
areaPanel.add(altField, gbc);
jLabel3.setText(Local.getString("Width"));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.insets = new Insets(5, 10, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel3, gbc);
widthField.setPreferredSize(new Dimension(30, 25));
widthField.setMinimumSize(new Dimension(30, 25));
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(widthField, gbc);
jLabel4.setText(Local.getString("Height"));
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 2;
gbc.insets = new Insets(5, 50, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel4, gbc);
heightField.setMinimumSize(new Dimension(30, 25));
heightField.setPreferredSize(new Dimension(30, 25));
gbc = new GridBagConstraints();
gbc.gridx = 3;
gbc.gridy = 2;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(heightField, gbc);
jLabel5.setText(Local.getString("H. space"));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
gbc.insets = new Insets(5, 10, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel5, gbc);
hspaceField.setMinimumSize(new Dimension(30, 25));
hspaceField.setPreferredSize(new Dimension(30, 25));
hspaceField.setText("0");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 3;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(hspaceField, gbc);
jLabel6.setText(Local.getString("V. space"));
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 3;
gbc.insets = new Insets(5, 50, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel6, gbc);
vspaceField.setMinimumSize(new Dimension(30, 25));
vspaceField.setPreferredSize(new Dimension(30, 25));
vspaceField.setText("0");
gbc = new GridBagConstraints();
gbc.gridx = 3;
gbc.gridy = 3;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(vspaceField, gbc);
jLabel7.setText(Local.getString("Border"));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 4;
gbc.insets = new Insets(5, 10, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel7, gbc);
borderField.setMinimumSize(new Dimension(30, 25));
borderField.setPreferredSize(new Dimension(30, 25));
borderField.setText("0");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 4;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(borderField, gbc);
jLabel8.setText(Local.getString("Align"));
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 4;
gbc.insets = new Insets(5, 50, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel8, gbc);
alignCB.setBackground(new Color(230, 230, 230));
alignCB.setFont(new java.awt.Font("Dialog", 1, 10));
alignCB.setPreferredSize(new Dimension(100, 25));
alignCB.setSelectedIndex(0);
gbc = new GridBagConstraints();
gbc.gridx = 3;
gbc.gridy = 4;
gbc.gridwidth = 2;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(alignCB, gbc);
jLabel9.setText(Local.getString("Hyperlink"));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 5;
gbc.insets = new Insets(5, 10, 10, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel9, gbc);
urlField.setPreferredSize(new Dimension(315, 25));
urlField.setMinimumSize(new Dimension(200, 25));
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 5;
gbc.gridwidth = 6;
gbc.insets = new Insets(5, 5, 10, 10);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(urlField, gbc);
this.getContentPane().add(areaPanel, BorderLayout.CENTER);
okB.setMaximumSize(new Dimension(100, 26));
okB.setMinimumSize(new Dimension(100, 26));
okB.setPreferredSize(new Dimension(100, 26));
okB.setText(Local.getString("Ok"));
okB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
okB_actionPerformed(e);
}
});
this.getRootPane().setDefaultButton(okB);
cancelB.setMaximumSize(new Dimension(100, 26));
cancelB.setMinimumSize(new Dimension(100, 26));
cancelB.setPreferredSize(new Dimension(100, 26));
cancelB.setText(Local.getString("Cancel"));
cancelB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelB_actionPerformed(e);
}
});
buttonsPanel.add(okB, null);
buttonsPanel.add(cancelB, null);
this.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
}
void okB_actionPerformed(ActionEvent e) {
this.dispose();
}
void cancelB_actionPerformed(ActionEvent e) {
CANCELLED = true;
this.dispose();
}
private ImageIcon getPreviewIcon(java.io.File file) {
ImageIcon tmpIcon = new ImageIcon(file.getPath());
ImageIcon thmb = null;
if (tmpIcon.getIconHeight() > 48) {
thmb = new ImageIcon(tmpIcon.getImage()
.getScaledInstance( -1, 48, Image.SCALE_DEFAULT));
}
else {
thmb = tmpIcon;
}
if (thmb.getIconWidth() > 350) {
return new ImageIcon(thmb.getImage()
.getScaledInstance(350, -1, Image.SCALE_DEFAULT));
}
else {
return thmb;
}
}
public void updatePreview() {
try {
if (!(new java.net.URL(fileField.getText()).getPath()).equals(""))
header.setIcon(getPreviewIcon(new java.io.File(
new java.net.URL(fileField.getText()).getPath())));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
CANCELLED = true;
this.dispose();
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
void browseB_actionPerformed(ActionEvent e) {
// Fix until Sun's JVM supports more locales...
UIManager.put("FileChooser.lookInLabelText", Local
.getString("Look in:"));
UIManager.put("FileChooser.upFolderToolTipText", Local.getString(
"Up One Level"));
UIManager.put("FileChooser.newFolderToolTipText", Local.getString(
"Create New Folder"));
UIManager.put("FileChooser.listViewButtonToolTipText", Local
.getString("List"));
UIManager.put("FileChooser.detailsViewButtonToolTipText", Local
.getString("Details"));
UIManager.put("FileChooser.fileNameLabelText", Local.getString(
"File Name:"));
UIManager.put("FileChooser.filesOfTypeLabelText", Local.getString(
"Files of Type:"));
UIManager.put("FileChooser.openButtonText", Local.getString("Open"));
UIManager.put("FileChooser.openButtonToolTipText", Local.getString(
"Open selected file"));
UIManager
.put("FileChooser.cancelButtonText", Local.getString("Cancel"));
UIManager.put("FileChooser.cancelButtonToolTipText", Local.getString(
"Cancel"));
JFileChooser chooser = new JFileChooser();
chooser.setFileHidingEnabled(false);
chooser.setDialogTitle(Local.getString("Choose an image file"));
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.addChoosableFileFilter(
new net.sf.memoranda.ui.htmleditor.filechooser.ImageFilter());
chooser.setAccessory(
new net.sf.memoranda.ui.htmleditor.filechooser.ImagePreview(
chooser));
chooser.setPreferredSize(new Dimension(550, 375));
java.io.File lastSel = (java.io.File) Context.get(
"LAST_SELECTED_IMG_FILE");
if (lastSel != null)
chooser.setCurrentDirectory(lastSel);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
fileField.setText(chooser.getSelectedFile().toURI().toURL().toString());
header.setIcon(getPreviewIcon(chooser.getSelectedFile()));
Context
.put("LAST_SELECTED_IMG_FILE", chooser
.getSelectedFile());
}
catch (Exception ex) {
fileField.setText(chooser.getSelectedFile().getPath());
}
try {
ImageIcon img = new ImageIcon(chooser.getSelectedFile()
.getPath());
widthField.setText(new Integer(img.getIconWidth()).toString());
heightField
.setText(new Integer(img.getIconHeight()).toString());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
} | jzalden/SER316-Karlsruhe | src/net/sf/memoranda/ui/htmleditor/ImageDialog.java | Java | gpl-2.0 | 13,558 |
// SPDX-License-Identifier: GPL-2.0
#include "color.h"
#include <QMap>
#include <array>
// Note that std::array<QColor, 2> is in every respect equivalent to QColor[2],
// but allows assignment, comparison, can be returned from functions, etc.
static QMap<color_index_t, std::array<QColor, 2>> profile_color = {
{ SAC_1, {{ FUNGREEN1, BLACK1_LOW_TRANS }} },
{ SAC_2, {{ APPLE1, BLACK1_LOW_TRANS }} },
{ SAC_3, {{ ATLANTIS1, BLACK1_LOW_TRANS }} },
{ SAC_4, {{ ATLANTIS2, BLACK1_LOW_TRANS }} },
{ SAC_5, {{ EARLSGREEN1, BLACK1_LOW_TRANS }} },
{ SAC_6, {{ HOKEYPOKEY1, BLACK1_LOW_TRANS }} },
{ SAC_7, {{ TUSCANY1, BLACK1_LOW_TRANS }} },
{ SAC_8, {{ CINNABAR1, BLACK1_LOW_TRANS }} },
{ SAC_9, {{ REDORANGE1, BLACK1_LOW_TRANS }} },
{ VELO_STABLE, {{ CAMARONE1, BLACK1_LOW_TRANS }} },
{ VELO_SLOW, {{ LIMENADE1, BLACK1_LOW_TRANS }} },
{ VELO_MODERATE, {{ RIOGRANDE1, BLACK1_LOW_TRANS }} },
{ VELO_FAST, {{ PIRATEGOLD1, BLACK1_LOW_TRANS }} },
{ VELO_CRAZY, {{ RED1, BLACK1_LOW_TRANS }} },
{ PO2, {{ APPLE1, BLACK1_LOW_TRANS }} },
{ PO2_ALERT, {{ RED1, BLACK1_LOW_TRANS }} },
{ PN2, {{ BLACK1_LOW_TRANS, BLACK1_LOW_TRANS }} },
{ PN2_ALERT, {{ RED1, BLACK1_LOW_TRANS }} },
{ PHE, {{ PEANUT, BLACK1_LOW_TRANS }} },
{ PHE_ALERT, {{ RED1, BLACK1_LOW_TRANS }} },
{ O2SETPOINT, {{ PIRATEGOLD1_MED_TRANS, BLACK1_LOW_TRANS }} },
{ CCRSENSOR1, {{ TUNDORA1_MED_TRANS, BLACK1_LOW_TRANS }} },
{ CCRSENSOR2, {{ ROYALBLUE2_LOW_TRANS, BLACK1_LOW_TRANS }} },
{ CCRSENSOR3, {{ PEANUT, BLACK1_LOW_TRANS }} },
{ SCR_OCPO2, {{ PIRATEGOLD1_MED_TRANS, BLACK1_LOW_TRANS }} },
{ PP_LINES, {{ BLACK1_HIGH_TRANS, BLACK1_LOW_TRANS }} },
{ TEXT_BACKGROUND, {{ CONCRETE1_LOWER_TRANS, WHITE1 }} },
{ ALERT_BG, {{ BROOM1_LOWER_TRANS, BLACK1_LOW_TRANS }} },
{ ALERT_FG, {{ BLACK1_LOW_TRANS, WHITE1 }} },
{ EVENTS, {{ REDORANGE1, BLACK1_LOW_TRANS }} },
{ SAMPLE_DEEP, {{ QColor(Qt::red).darker(), BLACK1 }} },
{ SAMPLE_SHALLOW, {{ QColor(Qt::red).lighter(), BLACK1_LOW_TRANS }} },
{ SMOOTHED, {{ REDORANGE1_HIGH_TRANS, BLACK1_LOW_TRANS }} },
{ MINUTE, {{ MEDIUMREDVIOLET1_HIGHER_TRANS, BLACK1_LOW_TRANS }} },
{ TIME_GRID, {{ WHITE1, BLACK1_HIGH_TRANS }} },
{ TIME_TEXT, {{ FORESTGREEN1, BLACK1 }} },
{ DEPTH_GRID, {{ WHITE1, BLACK1_HIGH_TRANS }} },
{ MEAN_DEPTH, {{ REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS }} },
{ HR_PLOT, {{ REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS }} },
{ HR_TEXT, {{ REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS }} },
{ HR_AXIS, {{ MED_GRAY_HIGH_TRANS, MED_GRAY_HIGH_TRANS }} },
{ DEPTH_BOTTOM, {{ GOVERNORBAY1_MED_TRANS, BLACK1_HIGH_TRANS }} },
{ DEPTH_TOP, {{ MERCURY1_MED_TRANS, WHITE1_MED_TRANS }} },
{ TEMP_TEXT, {{ GOVERNORBAY2, BLACK1_LOW_TRANS }} },
{ TEMP_PLOT, {{ ROYALBLUE2_LOW_TRANS, BLACK1_LOW_TRANS }} },
{ SAC_DEFAULT, {{ WHITE1, BLACK1_LOW_TRANS }} },
{ BOUNDING_BOX, {{ WHITE1, BLACK1_LOW_TRANS }} },
{ PRESSURE_TEXT, {{ KILLARNEY1, BLACK1_LOW_TRANS }} },
{ BACKGROUND, {{ SPRINGWOOD1, WHITE1 }} },
{ BACKGROUND_TRANS, {{ SPRINGWOOD1_MED_TRANS, WHITE1_MED_TRANS }} },
{ CEILING_SHALLOW, {{ REDORANGE1_HIGH_TRANS, BLACK1_HIGH_TRANS }} },
{ CEILING_DEEP, {{ RED1_MED_TRANS, BLACK1_HIGH_TRANS }} },
{ CALC_CEILING_SHALLOW, {{ FUNGREEN1_HIGH_TRANS, BLACK1_HIGH_TRANS }} },
{ CALC_CEILING_DEEP, {{ APPLE1_HIGH_TRANS, BLACK1_HIGH_TRANS }} },
{ TISSUE_PERCENTAGE, {{ GOVERNORBAY2, BLACK1_LOW_TRANS }} },
{ DURATION_LINE, {{ BLACK1, BLACK1_LOW_TRANS }} }
};
QColor getColor(const color_index_t i, bool isGrayscale)
{
if (profile_color.count() > i && i >= 0)
return profile_color[i][isGrayscale ? 1 : 0];
return QColor(Qt::black);
}
QColor getSacColor(int sac, int avg_sac)
{
int sac_index = 0;
int delta = sac - avg_sac + 7000;
sac_index = delta / 2000;
if (sac_index < 0)
sac_index = 0;
if (sac_index > SAC_COLORS - 1)
sac_index = SAC_COLORS - 1;
return getColor((color_index_t)(SAC_COLORS_START_IDX + sac_index), false);
}
QColor getPressureColor(double density)
{
QColor color;
int h = ((int) (180.0 - 180.0 * density / 8.0));
while (h < 0)
h += 360;
color.setHsv(h , 255, 255);
return color;
}
| janmulder/subsurface | core/color.cpp | C++ | gpl-2.0 | 4,063 |
// Copyright 2013 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include <sstream>
#include <unordered_map>
#include "Common/GL/GLInterfaceBase.h"
#include "Common/GL/GLExtensions/GLExtensions.h"
#include "Common/Logging/Log.h"
#if defined(__linux__) || defined(__APPLE__)
#include <dlfcn.h>
#endif
// gl_1_1
PFNDOLCLEARINDEXPROC dolClearIndex;
PFNDOLCLEARCOLORPROC dolClearColor;
PFNDOLCLEARPROC dolClear;
PFNDOLINDEXMASKPROC dolIndexMask;
PFNDOLCOLORMASKPROC dolColorMask;
PFNDOLALPHAFUNCPROC dolAlphaFunc;
PFNDOLBLENDFUNCPROC dolBlendFunc;
PFNDOLLOGICOPPROC dolLogicOp;
PFNDOLCULLFACEPROC dolCullFace;
PFNDOLFRONTFACEPROC dolFrontFace;
PFNDOLPOINTSIZEPROC dolPointSize;
PFNDOLLINEWIDTHPROC dolLineWidth;
PFNDOLLINESTIPPLEPROC dolLineStipple;
PFNDOLPOLYGONMODEPROC dolPolygonMode;
PFNDOLPOLYGONOFFSETPROC dolPolygonOffset;
PFNDOLPOLYGONSTIPPLEPROC dolPolygonStipple;
PFNDOLGETPOLYGONSTIPPLEPROC dolGetPolygonStipple;
PFNDOLEDGEFLAGPROC dolEdgeFlag;
PFNDOLEDGEFLAGVPROC dolEdgeFlagv;
PFNDOLSCISSORPROC dolScissor;
PFNDOLCLIPPLANEPROC dolClipPlane;
PFNDOLGETCLIPPLANEPROC dolGetClipPlane;
PFNDOLDRAWBUFFERPROC dolDrawBuffer;
PFNDOLREADBUFFERPROC dolReadBuffer;
PFNDOLENABLEPROC dolEnable;
PFNDOLDISABLEPROC dolDisable;
PFNDOLISENABLEDPROC dolIsEnabled;
PFNDOLENABLECLIENTSTATEPROC dolEnableClientState;
PFNDOLDISABLECLIENTSTATEPROC dolDisableClientState;
PFNDOLGETBOOLEANVPROC dolGetBooleanv;
PFNDOLGETDOUBLEVPROC dolGetDoublev;
PFNDOLGETFLOATVPROC dolGetFloatv;
PFNDOLGETINTEGERVPROC dolGetIntegerv;
PFNDOLPUSHATTRIBPROC dolPushAttrib;
PFNDOLPOPATTRIBPROC dolPopAttrib;
PFNDOLPUSHCLIENTATTRIBPROC dolPushClientAttrib;
PFNDOLPOPCLIENTATTRIBPROC dolPopClientAttrib;
PFNDOLRENDERMODEPROC dolRenderMode;
PFNDOLGETERRORPROC dolGetError;
PFNDOLGETSTRINGPROC dolGetString;
PFNDOLFINISHPROC dolFinish;
PFNDOLFLUSHPROC dolFlush;
PFNDOLHINTPROC dolHint;
PFNDOLCLEARDEPTHPROC dolClearDepth;
PFNDOLDEPTHFUNCPROC dolDepthFunc;
PFNDOLDEPTHMASKPROC dolDepthMask;
PFNDOLDEPTHRANGEPROC dolDepthRange;
PFNDOLCLEARACCUMPROC dolClearAccum;
PFNDOLACCUMPROC dolAccum;
PFNDOLMATRIXMODEPROC dolMatrixMode;
PFNDOLORTHOPROC dolOrtho;
PFNDOLFRUSTUMPROC dolFrustum;
PFNDOLVIEWPORTPROC dolViewport;
PFNDOLPUSHMATRIXPROC dolPushMatrix;
PFNDOLPOPMATRIXPROC dolPopMatrix;
PFNDOLLOADIDENTITYPROC dolLoadIdentity;
PFNDOLLOADMATRIXDPROC dolLoadMatrixd;
PFNDOLLOADMATRIXFPROC dolLoadMatrixf;
PFNDOLMULTMATRIXDPROC dolMultMatrixd;
PFNDOLMULTMATRIXFPROC dolMultMatrixf;
PFNDOLROTATEDPROC dolRotated;
PFNDOLROTATEFPROC dolRotatef;
PFNDOLSCALEDPROC dolScaled;
PFNDOLSCALEFPROC dolScalef;
PFNDOLTRANSLATEDPROC dolTranslated;
PFNDOLTRANSLATEFPROC dolTranslatef;
PFNDOLISLISTPROC dolIsList;
PFNDOLDELETELISTSPROC dolDeleteLists;
PFNDOLGENLISTSPROC dolGenLists;
PFNDOLNEWLISTPROC dolNewList;
PFNDOLENDLISTPROC dolEndList;
PFNDOLCALLLISTPROC dolCallList;
PFNDOLCALLLISTSPROC dolCallLists;
PFNDOLLISTBASEPROC dolListBase;
PFNDOLBEGINPROC dolBegin;
PFNDOLENDPROC dolEnd;
PFNDOLVERTEX2DPROC dolVertex2d;
PFNDOLVERTEX2FPROC dolVertex2f;
PFNDOLVERTEX2IPROC dolVertex2i;
PFNDOLVERTEX2SPROC dolVertex2s;
PFNDOLVERTEX3DPROC dolVertex3d;
PFNDOLVERTEX3FPROC dolVertex3f;
PFNDOLVERTEX3IPROC dolVertex3i;
PFNDOLVERTEX3SPROC dolVertex3s;
PFNDOLVERTEX4DPROC dolVertex4d;
PFNDOLVERTEX4FPROC dolVertex4f;
PFNDOLVERTEX4IPROC dolVertex4i;
PFNDOLVERTEX4SPROC dolVertex4s;
PFNDOLVERTEX2DVPROC dolVertex2dv;
PFNDOLVERTEX2FVPROC dolVertex2fv;
PFNDOLVERTEX2IVPROC dolVertex2iv;
PFNDOLVERTEX2SVPROC dolVertex2sv;
PFNDOLVERTEX3DVPROC dolVertex3dv;
PFNDOLVERTEX3FVPROC dolVertex3fv;
PFNDOLVERTEX3IVPROC dolVertex3iv;
PFNDOLVERTEX3SVPROC dolVertex3sv;
PFNDOLVERTEX4DVPROC dolVertex4dv;
PFNDOLVERTEX4FVPROC dolVertex4fv;
PFNDOLVERTEX4IVPROC dolVertex4iv;
PFNDOLVERTEX4SVPROC dolVertex4sv;
PFNDOLNORMAL3BPROC dolNormal3b;
PFNDOLNORMAL3DPROC dolNormal3d;
PFNDOLNORMAL3FPROC dolNormal3f;
PFNDOLNORMAL3IPROC dolNormal3i;
PFNDOLNORMAL3SPROC dolNormal3s;
PFNDOLNORMAL3BVPROC dolNormal3bv;
PFNDOLNORMAL3DVPROC dolNormal3dv;
PFNDOLNORMAL3FVPROC dolNormal3fv;
PFNDOLNORMAL3IVPROC dolNormal3iv;
PFNDOLNORMAL3SVPROC dolNormal3sv;
PFNDOLINDEXDPROC dolIndexd;
PFNDOLINDEXFPROC dolIndexf;
PFNDOLINDEXIPROC dolIndexi;
PFNDOLINDEXSPROC dolIndexs;
PFNDOLINDEXUBPROC dolIndexub;
PFNDOLINDEXDVPROC dolIndexdv;
PFNDOLINDEXFVPROC dolIndexfv;
PFNDOLINDEXIVPROC dolIndexiv;
PFNDOLINDEXSVPROC dolIndexsv;
PFNDOLINDEXUBVPROC dolIndexubv;
PFNDOLCOLOR3BPROC dolColor3b;
PFNDOLCOLOR3DPROC dolColor3d;
PFNDOLCOLOR3FPROC dolColor3f;
PFNDOLCOLOR3IPROC dolColor3i;
PFNDOLCOLOR3SPROC dolColor3s;
PFNDOLCOLOR3UBPROC dolColor3ub;
PFNDOLCOLOR3UIPROC dolColor3ui;
PFNDOLCOLOR3USPROC dolColor3us;
PFNDOLCOLOR4BPROC dolColor4b;
PFNDOLCOLOR4DPROC dolColor4d;
PFNDOLCOLOR4FPROC dolColor4f;
PFNDOLCOLOR4IPROC dolColor4i;
PFNDOLCOLOR4SPROC dolColor4s;
PFNDOLCOLOR4UBPROC dolColor4ub;
PFNDOLCOLOR4UIPROC dolColor4ui;
PFNDOLCOLOR4USPROC dolColor4us;
PFNDOLCOLOR3BVPROC dolColor3bv;
PFNDOLCOLOR3DVPROC dolColor3dv;
PFNDOLCOLOR3FVPROC dolColor3fv;
PFNDOLCOLOR3IVPROC dolColor3iv;
PFNDOLCOLOR3SVPROC dolColor3sv;
PFNDOLCOLOR3UBVPROC dolColor3ubv;
PFNDOLCOLOR3UIVPROC dolColor3uiv;
PFNDOLCOLOR3USVPROC dolColor3usv;
PFNDOLCOLOR4BVPROC dolColor4bv;
PFNDOLCOLOR4DVPROC dolColor4dv;
PFNDOLCOLOR4FVPROC dolColor4fv;
PFNDOLCOLOR4IVPROC dolColor4iv;
PFNDOLCOLOR4SVPROC dolColor4sv;
PFNDOLCOLOR4UBVPROC dolColor4ubv;
PFNDOLCOLOR4UIVPROC dolColor4uiv;
PFNDOLCOLOR4USVPROC dolColor4usv;
PFNDOLTEXCOORD1DPROC dolTexCoord1d;
PFNDOLTEXCOORD1FPROC dolTexCoord1f;
PFNDOLTEXCOORD1IPROC dolTexCoord1i;
PFNDOLTEXCOORD1SPROC dolTexCoord1s;
PFNDOLTEXCOORD2DPROC dolTexCoord2d;
PFNDOLTEXCOORD2FPROC dolTexCoord2f;
PFNDOLTEXCOORD2IPROC dolTexCoord2i;
PFNDOLTEXCOORD2SPROC dolTexCoord2s;
PFNDOLTEXCOORD3DPROC dolTexCoord3d;
PFNDOLTEXCOORD3FPROC dolTexCoord3f;
PFNDOLTEXCOORD3IPROC dolTexCoord3i;
PFNDOLTEXCOORD3SPROC dolTexCoord3s;
PFNDOLTEXCOORD4DPROC dolTexCoord4d;
PFNDOLTEXCOORD4FPROC dolTexCoord4f;
PFNDOLTEXCOORD4IPROC dolTexCoord4i;
PFNDOLTEXCOORD4SPROC dolTexCoord4s;
PFNDOLTEXCOORD1DVPROC dolTexCoord1dv;
PFNDOLTEXCOORD1FVPROC dolTexCoord1fv;
PFNDOLTEXCOORD1IVPROC dolTexCoord1iv;
PFNDOLTEXCOORD1SVPROC dolTexCoord1sv;
PFNDOLTEXCOORD2DVPROC dolTexCoord2dv;
PFNDOLTEXCOORD2FVPROC dolTexCoord2fv;
PFNDOLTEXCOORD2IVPROC dolTexCoord2iv;
PFNDOLTEXCOORD2SVPROC dolTexCoord2sv;
PFNDOLTEXCOORD3DVPROC dolTexCoord3dv;
PFNDOLTEXCOORD3FVPROC dolTexCoord3fv;
PFNDOLTEXCOORD3IVPROC dolTexCoord3iv;
PFNDOLTEXCOORD3SVPROC dolTexCoord3sv;
PFNDOLTEXCOORD4DVPROC dolTexCoord4dv;
PFNDOLTEXCOORD4FVPROC dolTexCoord4fv;
PFNDOLTEXCOORD4IVPROC dolTexCoord4iv;
PFNDOLTEXCOORD4SVPROC dolTexCoord4sv;
PFNDOLRASTERPOS2DPROC dolRasterPos2d;
PFNDOLRASTERPOS2FPROC dolRasterPos2f;
PFNDOLRASTERPOS2IPROC dolRasterPos2i;
PFNDOLRASTERPOS2SPROC dolRasterPos2s;
PFNDOLRASTERPOS3DPROC dolRasterPos3d;
PFNDOLRASTERPOS3FPROC dolRasterPos3f;
PFNDOLRASTERPOS3IPROC dolRasterPos3i;
PFNDOLRASTERPOS3SPROC dolRasterPos3s;
PFNDOLRASTERPOS4DPROC dolRasterPos4d;
PFNDOLRASTERPOS4FPROC dolRasterPos4f;
PFNDOLRASTERPOS4IPROC dolRasterPos4i;
PFNDOLRASTERPOS4SPROC dolRasterPos4s;
PFNDOLRASTERPOS2DVPROC dolRasterPos2dv;
PFNDOLRASTERPOS2FVPROC dolRasterPos2fv;
PFNDOLRASTERPOS2IVPROC dolRasterPos2iv;
PFNDOLRASTERPOS2SVPROC dolRasterPos2sv;
PFNDOLRASTERPOS3DVPROC dolRasterPos3dv;
PFNDOLRASTERPOS3FVPROC dolRasterPos3fv;
PFNDOLRASTERPOS3IVPROC dolRasterPos3iv;
PFNDOLRASTERPOS3SVPROC dolRasterPos3sv;
PFNDOLRASTERPOS4DVPROC dolRasterPos4dv;
PFNDOLRASTERPOS4FVPROC dolRasterPos4fv;
PFNDOLRASTERPOS4IVPROC dolRasterPos4iv;
PFNDOLRASTERPOS4SVPROC dolRasterPos4sv;
PFNDOLRECTDPROC dolRectd;
PFNDOLRECTFPROC dolRectf;
PFNDOLRECTIPROC dolRecti;
PFNDOLRECTSPROC dolRects;
PFNDOLRECTDVPROC dolRectdv;
PFNDOLRECTFVPROC dolRectfv;
PFNDOLRECTIVPROC dolRectiv;
PFNDOLRECTSVPROC dolRectsv;
PFNDOLVERTEXPOINTERPROC dolVertexPointer;
PFNDOLNORMALPOINTERPROC dolNormalPointer;
PFNDOLCOLORPOINTERPROC dolColorPointer;
PFNDOLINDEXPOINTERPROC dolIndexPointer;
PFNDOLTEXCOORDPOINTERPROC dolTexCoordPointer;
PFNDOLEDGEFLAGPOINTERPROC dolEdgeFlagPointer;
PFNDOLGETPOINTERVPROC dolGetPointerv;
PFNDOLARRAYELEMENTPROC dolArrayElement;
PFNDOLDRAWARRAYSPROC dolDrawArrays;
PFNDOLDRAWELEMENTSPROC dolDrawElements;
PFNDOLINTERLEAVEDARRAYSPROC dolInterleavedArrays;
PFNDOLSHADEMODELPROC dolShadeModel;
PFNDOLLIGHTFPROC dolLightf;
PFNDOLLIGHTIPROC dolLighti;
PFNDOLLIGHTFVPROC dolLightfv;
PFNDOLLIGHTIVPROC dolLightiv;
PFNDOLGETLIGHTFVPROC dolGetLightfv;
PFNDOLGETLIGHTIVPROC dolGetLightiv;
PFNDOLLIGHTMODELFPROC dolLightModelf;
PFNDOLLIGHTMODELIPROC dolLightModeli;
PFNDOLLIGHTMODELFVPROC dolLightModelfv;
PFNDOLLIGHTMODELIVPROC dolLightModeliv;
PFNDOLMATERIALFPROC dolMaterialf;
PFNDOLMATERIALIPROC dolMateriali;
PFNDOLMATERIALFVPROC dolMaterialfv;
PFNDOLMATERIALIVPROC dolMaterialiv;
PFNDOLGETMATERIALFVPROC dolGetMaterialfv;
PFNDOLGETMATERIALIVPROC dolGetMaterialiv;
PFNDOLCOLORMATERIALPROC dolColorMaterial;
PFNDOLPIXELZOOMPROC dolPixelZoom;
PFNDOLPIXELSTOREFPROC dolPixelStoref;
PFNDOLPIXELSTOREIPROC dolPixelStorei;
PFNDOLPIXELTRANSFERFPROC dolPixelTransferf;
PFNDOLPIXELTRANSFERIPROC dolPixelTransferi;
PFNDOLPIXELMAPFVPROC dolPixelMapfv;
PFNDOLPIXELMAPUIVPROC dolPixelMapuiv;
PFNDOLPIXELMAPUSVPROC dolPixelMapusv;
PFNDOLGETPIXELMAPFVPROC dolGetPixelMapfv;
PFNDOLGETPIXELMAPUIVPROC dolGetPixelMapuiv;
PFNDOLGETPIXELMAPUSVPROC dolGetPixelMapusv;
PFNDOLBITMAPPROC dolBitmap;
PFNDOLREADPIXELSPROC dolReadPixels;
PFNDOLDRAWPIXELSPROC dolDrawPixels;
PFNDOLCOPYPIXELSPROC dolCopyPixels;
PFNDOLSTENCILFUNCPROC dolStencilFunc;
PFNDOLSTENCILMASKPROC dolStencilMask;
PFNDOLSTENCILOPPROC dolStencilOp;
PFNDOLCLEARSTENCILPROC dolClearStencil;
PFNDOLTEXGENDPROC dolTexGend;
PFNDOLTEXGENFPROC dolTexGenf;
PFNDOLTEXGENIPROC dolTexGeni;
PFNDOLTEXGENDVPROC dolTexGendv;
PFNDOLTEXGENFVPROC dolTexGenfv;
PFNDOLTEXGENIVPROC dolTexGeniv;
PFNDOLGETTEXGENDVPROC dolGetTexGendv;
PFNDOLGETTEXGENFVPROC dolGetTexGenfv;
PFNDOLGETTEXGENIVPROC dolGetTexGeniv;
PFNDOLTEXENVFPROC dolTexEnvf;
PFNDOLTEXENVIPROC dolTexEnvi;
PFNDOLTEXENVFVPROC dolTexEnvfv;
PFNDOLTEXENVIVPROC dolTexEnviv;
PFNDOLGETTEXENVFVPROC dolGetTexEnvfv;
PFNDOLGETTEXENVIVPROC dolGetTexEnviv;
PFNDOLTEXPARAMETERFPROC dolTexParameterf;
PFNDOLTEXPARAMETERIPROC dolTexParameteri;
PFNDOLTEXPARAMETERFVPROC dolTexParameterfv;
PFNDOLTEXPARAMETERIVPROC dolTexParameteriv;
PFNDOLGETTEXPARAMETERFVPROC dolGetTexParameterfv;
PFNDOLGETTEXPARAMETERIVPROC dolGetTexParameteriv;
PFNDOLGETTEXLEVELPARAMETERFVPROC dolGetTexLevelParameterfv;
PFNDOLGETTEXLEVELPARAMETERIVPROC dolGetTexLevelParameteriv;
PFNDOLTEXIMAGE1DPROC dolTexImage1D;
PFNDOLTEXIMAGE2DPROC dolTexImage2D;
PFNDOLGETTEXIMAGEPROC dolGetTexImage;
PFNDOLGENTEXTURESPROC dolGenTextures;
PFNDOLDELETETEXTURESPROC dolDeleteTextures;
PFNDOLBINDTEXTUREPROC dolBindTexture;
PFNDOLPRIORITIZETEXTURESPROC dolPrioritizeTextures;
PFNDOLARETEXTURESRESIDENTPROC dolAreTexturesResident;
PFNDOLISTEXTUREPROC dolIsTexture;
PFNDOLTEXSUBIMAGE1DPROC dolTexSubImage1D;
PFNDOLTEXSUBIMAGE2DPROC dolTexSubImage2D;
PFNDOLCOPYTEXIMAGE1DPROC dolCopyTexImage1D;
PFNDOLCOPYTEXIMAGE2DPROC dolCopyTexImage2D;
PFNDOLCOPYTEXSUBIMAGE1DPROC dolCopyTexSubImage1D;
PFNDOLCOPYTEXSUBIMAGE2DPROC dolCopyTexSubImage2D;
PFNDOLMAP1DPROC dolMap1d;
PFNDOLMAP1FPROC dolMap1f;
PFNDOLMAP2DPROC dolMap2d;
PFNDOLMAP2FPROC dolMap2f;
PFNDOLGETMAPDVPROC dolGetMapdv;
PFNDOLGETMAPFVPROC dolGetMapfv;
PFNDOLGETMAPIVPROC dolGetMapiv;
PFNDOLEVALCOORD1DPROC dolEvalCoord1d;
PFNDOLEVALCOORD1FPROC dolEvalCoord1f;
PFNDOLEVALCOORD1DVPROC dolEvalCoord1dv;
PFNDOLEVALCOORD1FVPROC dolEvalCoord1fv;
PFNDOLEVALCOORD2DPROC dolEvalCoord2d;
PFNDOLEVALCOORD2FPROC dolEvalCoord2f;
PFNDOLEVALCOORD2DVPROC dolEvalCoord2dv;
PFNDOLEVALCOORD2FVPROC dolEvalCoord2fv;
PFNDOLMAPGRID1DPROC dolMapGrid1d;
PFNDOLMAPGRID1FPROC dolMapGrid1f;
PFNDOLMAPGRID2DPROC dolMapGrid2d;
PFNDOLMAPGRID2FPROC dolMapGrid2f;
PFNDOLEVALPOINT1PROC dolEvalPoint1;
PFNDOLEVALPOINT2PROC dolEvalPoint2;
PFNDOLEVALMESH1PROC dolEvalMesh1;
PFNDOLEVALMESH2PROC dolEvalMesh2;
PFNDOLFOGFPROC dolFogf;
PFNDOLFOGIPROC dolFogi;
PFNDOLFOGFVPROC dolFogfv;
PFNDOLFOGIVPROC dolFogiv;
PFNDOLFEEDBACKBUFFERPROC dolFeedbackBuffer;
PFNDOLPASSTHROUGHPROC dolPassThrough;
PFNDOLSELECTBUFFERPROC dolSelectBuffer;
PFNDOLINITNAMESPROC dolInitNames;
PFNDOLLOADNAMEPROC dolLoadName;
PFNDOLPUSHNAMEPROC dolPushName;
PFNDOLPOPNAMEPROC dolPopName;
// gl_1_2
PFNDOLCOPYTEXSUBIMAGE3DPROC dolCopyTexSubImage3D;
PFNDOLDRAWRANGEELEMENTSPROC dolDrawRangeElements;
PFNDOLTEXIMAGE3DPROC dolTexImage3D;
PFNDOLTEXSUBIMAGE3DPROC dolTexSubImage3D;
// gl_1_3
PFNDOLACTIVETEXTUREARBPROC dolActiveTexture;
PFNDOLCLIENTACTIVETEXTUREARBPROC dolClientActiveTexture;
PFNDOLCOMPRESSEDTEXIMAGE1DPROC dolCompressedTexImage1D;
PFNDOLCOMPRESSEDTEXIMAGE2DPROC dolCompressedTexImage2D;
PFNDOLCOMPRESSEDTEXIMAGE3DPROC dolCompressedTexImage3D;
PFNDOLCOMPRESSEDTEXSUBIMAGE1DPROC dolCompressedTexSubImage1D;
PFNDOLCOMPRESSEDTEXSUBIMAGE2DPROC dolCompressedTexSubImage2D;
PFNDOLCOMPRESSEDTEXSUBIMAGE3DPROC dolCompressedTexSubImage3D;
PFNDOLGETCOMPRESSEDTEXIMAGEPROC dolGetCompressedTexImage;
PFNDOLLOADTRANSPOSEMATRIXDARBPROC dolLoadTransposeMatrixd;
PFNDOLLOADTRANSPOSEMATRIXFARBPROC dolLoadTransposeMatrixf;
PFNDOLMULTTRANSPOSEMATRIXDARBPROC dolMultTransposeMatrixd;
PFNDOLMULTTRANSPOSEMATRIXFARBPROC dolMultTransposeMatrixf;
PFNDOLMULTITEXCOORD1DARBPROC dolMultiTexCoord1d;
PFNDOLMULTITEXCOORD1DVARBPROC dolMultiTexCoord1dv;
PFNDOLMULTITEXCOORD1FARBPROC dolMultiTexCoord1f;
PFNDOLMULTITEXCOORD1FVARBPROC dolMultiTexCoord1fv;
PFNDOLMULTITEXCOORD1IARBPROC dolMultiTexCoord1i;
PFNDOLMULTITEXCOORD1IVARBPROC dolMultiTexCoord1iv;
PFNDOLMULTITEXCOORD1SARBPROC dolMultiTexCoord1s;
PFNDOLMULTITEXCOORD1SVARBPROC dolMultiTexCoord1sv;
PFNDOLMULTITEXCOORD2DARBPROC dolMultiTexCoord2d;
PFNDOLMULTITEXCOORD2DVARBPROC dolMultiTexCoord2dv;
PFNDOLMULTITEXCOORD2FARBPROC dolMultiTexCoord2f;
PFNDOLMULTITEXCOORD2FVARBPROC dolMultiTexCoord2fv;
PFNDOLMULTITEXCOORD2IARBPROC dolMultiTexCoord2i;
PFNDOLMULTITEXCOORD2IVARBPROC dolMultiTexCoord2iv;
PFNDOLMULTITEXCOORD2SARBPROC dolMultiTexCoord2s;
PFNDOLMULTITEXCOORD2SVARBPROC dolMultiTexCoord2sv;
PFNDOLMULTITEXCOORD3DARBPROC dolMultiTexCoord3d;
PFNDOLMULTITEXCOORD3DVARBPROC dolMultiTexCoord3dv;
PFNDOLMULTITEXCOORD3FARBPROC dolMultiTexCoord3f;
PFNDOLMULTITEXCOORD3FVARBPROC dolMultiTexCoord3fv;
PFNDOLMULTITEXCOORD3IARBPROC dolMultiTexCoord3i;
PFNDOLMULTITEXCOORD3IVARBPROC dolMultiTexCoord3iv;
PFNDOLMULTITEXCOORD3SARBPROC dolMultiTexCoord3s;
PFNDOLMULTITEXCOORD3SVARBPROC dolMultiTexCoord3sv;
PFNDOLMULTITEXCOORD4DARBPROC dolMultiTexCoord4d;
PFNDOLMULTITEXCOORD4DVARBPROC dolMultiTexCoord4dv;
PFNDOLMULTITEXCOORD4FARBPROC dolMultiTexCoord4f;
PFNDOLMULTITEXCOORD4FVARBPROC dolMultiTexCoord4fv;
PFNDOLMULTITEXCOORD4IARBPROC dolMultiTexCoord4i;
PFNDOLMULTITEXCOORD4IVARBPROC dolMultiTexCoord4iv;
PFNDOLMULTITEXCOORD4SARBPROC dolMultiTexCoord4s;
PFNDOLMULTITEXCOORD4SVARBPROC dolMultiTexCoord4sv;
PFNDOLSAMPLECOVERAGEARBPROC dolSampleCoverage;
// gl_1_4
PFNDOLBLENDCOLORPROC dolBlendColor;
PFNDOLBLENDEQUATIONPROC dolBlendEquation;
PFNDOLBLENDFUNCSEPARATEPROC dolBlendFuncSeparate;
PFNDOLFOGCOORDPOINTERPROC dolFogCoordPointer;
PFNDOLFOGCOORDDPROC dolFogCoordd;
PFNDOLFOGCOORDDVPROC dolFogCoorddv;
PFNDOLFOGCOORDFPROC dolFogCoordf;
PFNDOLFOGCOORDFVPROC dolFogCoordfv;
PFNDOLMULTIDRAWARRAYSPROC dolMultiDrawArrays;
PFNDOLMULTIDRAWELEMENTSPROC dolMultiDrawElements;
PFNDOLPOINTPARAMETERFPROC dolPointParameterf;
PFNDOLPOINTPARAMETERFVPROC dolPointParameterfv;
PFNDOLPOINTPARAMETERIPROC dolPointParameteri;
PFNDOLPOINTPARAMETERIVPROC dolPointParameteriv;
PFNDOLSECONDARYCOLOR3BPROC dolSecondaryColor3b;
PFNDOLSECONDARYCOLOR3BVPROC dolSecondaryColor3bv;
PFNDOLSECONDARYCOLOR3DPROC dolSecondaryColor3d;
PFNDOLSECONDARYCOLOR3DVPROC dolSecondaryColor3dv;
PFNDOLSECONDARYCOLOR3FPROC dolSecondaryColor3f;
PFNDOLSECONDARYCOLOR3FVPROC dolSecondaryColor3fv;
PFNDOLSECONDARYCOLOR3IPROC dolSecondaryColor3i;
PFNDOLSECONDARYCOLOR3IVPROC dolSecondaryColor3iv;
PFNDOLSECONDARYCOLOR3SPROC dolSecondaryColor3s;
PFNDOLSECONDARYCOLOR3SVPROC dolSecondaryColor3sv;
PFNDOLSECONDARYCOLOR3UBPROC dolSecondaryColor3ub;
PFNDOLSECONDARYCOLOR3UBVPROC dolSecondaryColor3ubv;
PFNDOLSECONDARYCOLOR3UIPROC dolSecondaryColor3ui;
PFNDOLSECONDARYCOLOR3UIVPROC dolSecondaryColor3uiv;
PFNDOLSECONDARYCOLOR3USPROC dolSecondaryColor3us;
PFNDOLSECONDARYCOLOR3USVPROC dolSecondaryColor3usv;
PFNDOLSECONDARYCOLORPOINTERPROC dolSecondaryColorPointer;
PFNDOLWINDOWPOS2DPROC dolWindowPos2d;
PFNDOLWINDOWPOS2DVPROC dolWindowPos2dv;
PFNDOLWINDOWPOS2FPROC dolWindowPos2f;
PFNDOLWINDOWPOS2FVPROC dolWindowPos2fv;
PFNDOLWINDOWPOS2IPROC dolWindowPos2i;
PFNDOLWINDOWPOS2IVPROC dolWindowPos2iv;
PFNDOLWINDOWPOS2SPROC dolWindowPos2s;
PFNDOLWINDOWPOS2SVPROC dolWindowPos2sv;
PFNDOLWINDOWPOS3DPROC dolWindowPos3d;
PFNDOLWINDOWPOS3DVPROC dolWindowPos3dv;
PFNDOLWINDOWPOS3FPROC dolWindowPos3f;
PFNDOLWINDOWPOS3FVPROC dolWindowPos3fv;
PFNDOLWINDOWPOS3IPROC dolWindowPos3i;
PFNDOLWINDOWPOS3IVPROC dolWindowPos3iv;
PFNDOLWINDOWPOS3SPROC dolWindowPos3s;
PFNDOLWINDOWPOS3SVPROC dolWindowPos3sv;
// gl_1_5
PFNDOLBEGINQUERYPROC dolBeginQuery;
PFNDOLBINDBUFFERPROC dolBindBuffer;
PFNDOLBUFFERDATAPROC dolBufferData;
PFNDOLBUFFERSUBDATAPROC dolBufferSubData;
PFNDOLDELETEBUFFERSPROC dolDeleteBuffers;
PFNDOLDELETEQUERIESPROC dolDeleteQueries;
PFNDOLENDQUERYPROC dolEndQuery;
PFNDOLGENBUFFERSPROC dolGenBuffers;
PFNDOLGENQUERIESPROC dolGenQueries;
PFNDOLGETBUFFERPARAMETERIVPROC dolGetBufferParameteriv;
PFNDOLGETBUFFERPOINTERVPROC dolGetBufferPointerv;
PFNDOLGETBUFFERSUBDATAPROC dolGetBufferSubData;
PFNDOLGETQUERYOBJECTIVPROC dolGetQueryObjectiv;
PFNDOLGETQUERYOBJECTUIVPROC dolGetQueryObjectuiv;
PFNDOLGETQUERYIVPROC dolGetQueryiv;
PFNDOLISBUFFERPROC dolIsBuffer;
PFNDOLISQUERYPROC dolIsQuery;
PFNDOLMAPBUFFERPROC dolMapBuffer;
PFNDOLUNMAPBUFFERPROC dolUnmapBuffer;
// gl_2_0
PFNDOLATTACHSHADERPROC dolAttachShader;
PFNDOLBINDATTRIBLOCATIONPROC dolBindAttribLocation;
PFNDOLBLENDEQUATIONSEPARATEPROC dolBlendEquationSeparate;
PFNDOLCOMPILESHADERPROC dolCompileShader;
PFNDOLCREATEPROGRAMPROC dolCreateProgram;
PFNDOLCREATESHADERPROC dolCreateShader;
PFNDOLDELETEPROGRAMPROC dolDeleteProgram;
PFNDOLDELETESHADERPROC dolDeleteShader;
PFNDOLDETACHSHADERPROC dolDetachShader;
PFNDOLDISABLEVERTEXATTRIBARRAYPROC dolDisableVertexAttribArray;
PFNDOLDRAWBUFFERSPROC dolDrawBuffers;
PFNDOLENABLEVERTEXATTRIBARRAYPROC dolEnableVertexAttribArray;
PFNDOLGETACTIVEATTRIBPROC dolGetActiveAttrib;
PFNDOLGETACTIVEUNIFORMPROC dolGetActiveUniform;
PFNDOLGETATTACHEDSHADERSPROC dolGetAttachedShaders;
PFNDOLGETATTRIBLOCATIONPROC dolGetAttribLocation;
PFNDOLGETPROGRAMINFOLOGPROC dolGetProgramInfoLog;
PFNDOLGETPROGRAMIVPROC dolGetProgramiv;
PFNDOLGETSHADERINFOLOGPROC dolGetShaderInfoLog;
PFNDOLGETSHADERSOURCEPROC dolGetShaderSource;
PFNDOLGETSHADERIVPROC dolGetShaderiv;
PFNDOLGETUNIFORMLOCATIONPROC dolGetUniformLocation;
PFNDOLGETUNIFORMFVPROC dolGetUniformfv;
PFNDOLGETUNIFORMIVPROC dolGetUniformiv;
PFNDOLGETVERTEXATTRIBPOINTERVPROC dolGetVertexAttribPointerv;
PFNDOLGETVERTEXATTRIBDVPROC dolGetVertexAttribdv;
PFNDOLGETVERTEXATTRIBFVPROC dolGetVertexAttribfv;
PFNDOLGETVERTEXATTRIBIVPROC dolGetVertexAttribiv;
PFNDOLISPROGRAMPROC dolIsProgram;
PFNDOLISSHADERPROC dolIsShader;
PFNDOLLINKPROGRAMPROC dolLinkProgram;
PFNDOLSHADERSOURCEPROC dolShaderSource;
PFNDOLSTENCILFUNCSEPARATEPROC dolStencilFuncSeparate;
PFNDOLSTENCILMASKSEPARATEPROC dolStencilMaskSeparate;
PFNDOLSTENCILOPSEPARATEPROC dolStencilOpSeparate;
PFNDOLUNIFORM1FPROC dolUniform1f;
PFNDOLUNIFORM1FVPROC dolUniform1fv;
PFNDOLUNIFORM1IPROC dolUniform1i;
PFNDOLUNIFORM1IVPROC dolUniform1iv;
PFNDOLUNIFORM2FPROC dolUniform2f;
PFNDOLUNIFORM2FVPROC dolUniform2fv;
PFNDOLUNIFORM2IPROC dolUniform2i;
PFNDOLUNIFORM2IVPROC dolUniform2iv;
PFNDOLUNIFORM3FPROC dolUniform3f;
PFNDOLUNIFORM3FVPROC dolUniform3fv;
PFNDOLUNIFORM3IPROC dolUniform3i;
PFNDOLUNIFORM3IVPROC dolUniform3iv;
PFNDOLUNIFORM4FPROC dolUniform4f;
PFNDOLUNIFORM4FVPROC dolUniform4fv;
PFNDOLUNIFORM4IPROC dolUniform4i;
PFNDOLUNIFORM4IVPROC dolUniform4iv;
PFNDOLUNIFORMMATRIX2FVPROC dolUniformMatrix2fv;
PFNDOLUNIFORMMATRIX3FVPROC dolUniformMatrix3fv;
PFNDOLUNIFORMMATRIX4FVPROC dolUniformMatrix4fv;
PFNDOLUSEPROGRAMPROC dolUseProgram;
PFNDOLVALIDATEPROGRAMPROC dolValidateProgram;
PFNDOLVERTEXATTRIB1DPROC dolVertexAttrib1d;
PFNDOLVERTEXATTRIB1DVPROC dolVertexAttrib1dv;
PFNDOLVERTEXATTRIB1FPROC dolVertexAttrib1f;
PFNDOLVERTEXATTRIB1FVPROC dolVertexAttrib1fv;
PFNDOLVERTEXATTRIB1SPROC dolVertexAttrib1s;
PFNDOLVERTEXATTRIB1SVPROC dolVertexAttrib1sv;
PFNDOLVERTEXATTRIB2DPROC dolVertexAttrib2d;
PFNDOLVERTEXATTRIB2DVPROC dolVertexAttrib2dv;
PFNDOLVERTEXATTRIB2FPROC dolVertexAttrib2f;
PFNDOLVERTEXATTRIB2FVPROC dolVertexAttrib2fv;
PFNDOLVERTEXATTRIB2SPROC dolVertexAttrib2s;
PFNDOLVERTEXATTRIB2SVPROC dolVertexAttrib2sv;
PFNDOLVERTEXATTRIB3DPROC dolVertexAttrib3d;
PFNDOLVERTEXATTRIB3DVPROC dolVertexAttrib3dv;
PFNDOLVERTEXATTRIB3FPROC dolVertexAttrib3f;
PFNDOLVERTEXATTRIB3FVPROC dolVertexAttrib3fv;
PFNDOLVERTEXATTRIB3SPROC dolVertexAttrib3s;
PFNDOLVERTEXATTRIB3SVPROC dolVertexAttrib3sv;
PFNDOLVERTEXATTRIB4NBVPROC dolVertexAttrib4Nbv;
PFNDOLVERTEXATTRIB4NIVPROC dolVertexAttrib4Niv;
PFNDOLVERTEXATTRIB4NSVPROC dolVertexAttrib4Nsv;
PFNDOLVERTEXATTRIB4NUBPROC dolVertexAttrib4Nub;
PFNDOLVERTEXATTRIB4NUBVPROC dolVertexAttrib4Nubv;
PFNDOLVERTEXATTRIB4NUIVPROC dolVertexAttrib4Nuiv;
PFNDOLVERTEXATTRIB4NUSVPROC dolVertexAttrib4Nusv;
PFNDOLVERTEXATTRIB4BVPROC dolVertexAttrib4bv;
PFNDOLVERTEXATTRIB4DPROC dolVertexAttrib4d;
PFNDOLVERTEXATTRIB4DVPROC dolVertexAttrib4dv;
PFNDOLVERTEXATTRIB4FPROC dolVertexAttrib4f;
PFNDOLVERTEXATTRIB4FVPROC dolVertexAttrib4fv;
PFNDOLVERTEXATTRIB4IVPROC dolVertexAttrib4iv;
PFNDOLVERTEXATTRIB4SPROC dolVertexAttrib4s;
PFNDOLVERTEXATTRIB4SVPROC dolVertexAttrib4sv;
PFNDOLVERTEXATTRIB4UBVPROC dolVertexAttrib4ubv;
PFNDOLVERTEXATTRIB4UIVPROC dolVertexAttrib4uiv;
PFNDOLVERTEXATTRIB4USVPROC dolVertexAttrib4usv;
PFNDOLVERTEXATTRIBPOINTERPROC dolVertexAttribPointer;
// gl_2_1
PFNDOLUNIFORMMATRIX2X3FVPROC dolUniformMatrix2x3fv;
PFNDOLUNIFORMMATRIX2X4FVPROC dolUniformMatrix2x4fv;
PFNDOLUNIFORMMATRIX3X2FVPROC dolUniformMatrix3x2fv;
PFNDOLUNIFORMMATRIX3X4FVPROC dolUniformMatrix3x4fv;
PFNDOLUNIFORMMATRIX4X2FVPROC dolUniformMatrix4x2fv;
PFNDOLUNIFORMMATRIX4X3FVPROC dolUniformMatrix4x3fv;
// gl_3_0
PFNDOLBEGINCONDITIONALRENDERPROC dolBeginConditionalRender;
PFNDOLBEGINTRANSFORMFEEDBACKPROC dolBeginTransformFeedback;
PFNDOLBINDFRAGDATALOCATIONPROC dolBindFragDataLocation;
PFNDOLCLAMPCOLORPROC dolClampColor;
PFNDOLCLEARBUFFERFIPROC dolClearBufferfi;
PFNDOLCLEARBUFFERFVPROC dolClearBufferfv;
PFNDOLCLEARBUFFERIVPROC dolClearBufferiv;
PFNDOLCLEARBUFFERUIVPROC dolClearBufferuiv;
PFNDOLCOLORMASKIPROC dolColorMaski;
PFNDOLDISABLEIPROC dolDisablei;
PFNDOLENABLEIPROC dolEnablei;
PFNDOLENDCONDITIONALRENDERPROC dolEndConditionalRender;
PFNDOLENDTRANSFORMFEEDBACKPROC dolEndTransformFeedback;
PFNDOLGETBOOLEANI_VPROC dolGetBooleani_v;
PFNDOLGETFRAGDATALOCATIONPROC dolGetFragDataLocation;
PFNDOLGETSTRINGIPROC dolGetStringi;
PFNDOLGETTEXPARAMETERIIVPROC dolGetTexParameterIiv;
PFNDOLGETTEXPARAMETERIUIVPROC dolGetTexParameterIuiv;
PFNDOLGETTRANSFORMFEEDBACKVARYINGPROC dolGetTransformFeedbackVarying;
PFNDOLGETUNIFORMUIVPROC dolGetUniformuiv;
PFNDOLGETVERTEXATTRIBIIVPROC dolGetVertexAttribIiv;
PFNDOLGETVERTEXATTRIBIUIVPROC dolGetVertexAttribIuiv;
PFNDOLISENABLEDIPROC dolIsEnabledi;
PFNDOLTEXPARAMETERIIVPROC dolTexParameterIiv;
PFNDOLTEXPARAMETERIUIVPROC dolTexParameterIuiv;
PFNDOLTRANSFORMFEEDBACKVARYINGSPROC dolTransformFeedbackVaryings;
PFNDOLUNIFORM1UIPROC dolUniform1ui;
PFNDOLUNIFORM1UIVPROC dolUniform1uiv;
PFNDOLUNIFORM2UIPROC dolUniform2ui;
PFNDOLUNIFORM2UIVPROC dolUniform2uiv;
PFNDOLUNIFORM3UIPROC dolUniform3ui;
PFNDOLUNIFORM3UIVPROC dolUniform3uiv;
PFNDOLUNIFORM4UIPROC dolUniform4ui;
PFNDOLUNIFORM4UIVPROC dolUniform4uiv;
PFNDOLVERTEXATTRIBI1IPROC dolVertexAttribI1i;
PFNDOLVERTEXATTRIBI1IVPROC dolVertexAttribI1iv;
PFNDOLVERTEXATTRIBI1UIPROC dolVertexAttribI1ui;
PFNDOLVERTEXATTRIBI1UIVPROC dolVertexAttribI1uiv;
PFNDOLVERTEXATTRIBI2IPROC dolVertexAttribI2i;
PFNDOLVERTEXATTRIBI2IVPROC dolVertexAttribI2iv;
PFNDOLVERTEXATTRIBI2UIPROC dolVertexAttribI2ui;
PFNDOLVERTEXATTRIBI2UIVPROC dolVertexAttribI2uiv;
PFNDOLVERTEXATTRIBI3IPROC dolVertexAttribI3i;
PFNDOLVERTEXATTRIBI3IVPROC dolVertexAttribI3iv;
PFNDOLVERTEXATTRIBI3UIPROC dolVertexAttribI3ui;
PFNDOLVERTEXATTRIBI3UIVPROC dolVertexAttribI3uiv;
PFNDOLVERTEXATTRIBI4BVPROC dolVertexAttribI4bv;
PFNDOLVERTEXATTRIBI4IPROC dolVertexAttribI4i;
PFNDOLVERTEXATTRIBI4IVPROC dolVertexAttribI4iv;
PFNDOLVERTEXATTRIBI4SVPROC dolVertexAttribI4sv;
PFNDOLVERTEXATTRIBI4UBVPROC dolVertexAttribI4ubv;
PFNDOLVERTEXATTRIBI4UIPROC dolVertexAttribI4ui;
PFNDOLVERTEXATTRIBI4UIVPROC dolVertexAttribI4uiv;
PFNDOLVERTEXATTRIBI4USVPROC dolVertexAttribI4usv;
PFNDOLVERTEXATTRIBIPOINTERPROC dolVertexAttribIPointer;
// gl_3_1
PFNDOLDRAWARRAYSINSTANCEDPROC dolDrawArraysInstanced;
PFNDOLDRAWELEMENTSINSTANCEDPROC dolDrawElementsInstanced;
PFNDOLPRIMITIVERESTARTINDEXPROC dolPrimitiveRestartIndex;
PFNDOLTEXBUFFERPROC dolTexBuffer;
// gl_3_2
PFNDOLFRAMEBUFFERTEXTUREPROC dolFramebufferTexture;
PFNDOLGETBUFFERPARAMETERI64VPROC dolGetBufferParameteri64v;
PFNDOLGETINTEGER64I_VPROC dolGetInteger64i_v;
// gl 4_2
PFNDOLDRAWARRAYSINSTANCEDBASEINSTANCEPROC dolDrawArraysInstancedBaseInstance;
PFNDOLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC dolDrawElementsInstancedBaseInstance;
PFNDOLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC dolDrawElementsInstancedBaseVertexBaseInstance;
PFNDOLGETINTERNALFORMATIVPROC dolGetInternalformativ;
PFNDOLGETACTIVEATOMICCOUNTERBUFFERIVPROC dolGetActiveAtomicCounterBufferiv;
PFNDOLBINDIMAGETEXTUREPROC dolBindImageTexture;
PFNDOLMEMORYBARRIERPROC dolMemoryBarrier;
PFNDOLTEXSTORAGE1DPROC dolTexStorage1D;
PFNDOLTEXSTORAGE2DPROC dolTexStorage2D;
PFNDOLTEXSTORAGE3DPROC dolTexStorage3D;
PFNDOLDRAWTRANSFORMFEEDBACKINSTANCEDPROC dolDrawTransformFeedbackInstanced;
PFNDOLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC dolDrawTransformFeedbackStreamInstanced;
// gl_4_3
PFNDOLCLEARBUFFERDATAPROC dolClearBufferData;
PFNDOLCLEARBUFFERSUBDATAPROC dolClearBufferSubData;
PFNDOLDISPATCHCOMPUTEPROC dolDispatchCompute;
PFNDOLDISPATCHCOMPUTEINDIRECTPROC dolDispatchComputeIndirect;
PFNDOLFRAMEBUFFERPARAMETERIPROC dolFramebufferParameteri;
PFNDOLGETFRAMEBUFFERPARAMETERIVPROC dolGetFramebufferParameteriv;
PFNDOLGETINTERNALFORMATI64VPROC dolGetInternalformati64v;
PFNDOLINVALIDATETEXSUBIMAGEPROC dolInvalidateTexSubImage;
PFNDOLINVALIDATETEXIMAGEPROC dolInvalidateTexImage;
PFNDOLINVALIDATEBUFFERSUBDATAPROC dolInvalidateBufferSubData;
PFNDOLINVALIDATEBUFFERDATAPROC dolInvalidateBufferData;
PFNDOLINVALIDATEFRAMEBUFFERPROC dolInvalidateFramebuffer;
PFNDOLINVALIDATESUBFRAMEBUFFERPROC dolInvalidateSubFramebuffer;
PFNDOLMULTIDRAWARRAYSINDIRECTPROC dolMultiDrawArraysIndirect;
PFNDOLMULTIDRAWELEMENTSINDIRECTPROC dolMultiDrawElementsIndirect;
PFNDOLGETPROGRAMINTERFACEIVPROC dolGetProgramInterfaceiv;
PFNDOLGETPROGRAMRESOURCEINDEXPROC dolGetProgramResourceIndex;
PFNDOLGETPROGRAMRESOURCENAMEPROC dolGetProgramResourceName;
PFNDOLGETPROGRAMRESOURCEIVPROC dolGetProgramResourceiv;
PFNDOLGETPROGRAMRESOURCELOCATIONPROC dolGetProgramResourceLocation;
PFNDOLGETPROGRAMRESOURCELOCATIONINDEXPROC dolGetProgramResourceLocationIndex;
PFNDOLTEXBUFFERRANGEPROC dolTexBufferRange;
PFNDOLTEXTUREVIEWPROC dolTextureView;
PFNDOLBINDVERTEXBUFFERPROC dolBindVertexBuffer;
PFNDOLVERTEXATTRIBFORMATPROC dolVertexAttribFormat;
PFNDOLVERTEXATTRIBIFORMATPROC dolVertexAttribIFormat;
PFNDOLVERTEXATTRIBLFORMATPROC dolVertexAttribLFormat;
PFNDOLVERTEXATTRIBBINDINGPROC dolVertexAttribBinding;
PFNDOLVERTEXBINDINGDIVISORPROC dolVertexBindingDivisor;
// gl_4_4
PFNDOLCLEARTEXIMAGEPROC dolClearTexImage;
PFNDOLCLEARTEXSUBIMAGEPROC dolClearTexSubImage;
PFNDOLBINDBUFFERSBASEPROC dolBindBuffersBase;
PFNDOLBINDBUFFERSRANGEPROC dolBindBuffersRange;
PFNDOLBINDTEXTURESPROC dolBindTextures;
PFNDOLBINDSAMPLERSPROC dolBindSamplers;
PFNDOLBINDIMAGETEXTURESPROC dolBindImageTextures;
PFNDOLBINDVERTEXBUFFERSPROC dolBindVertexBuffers;
// gl_4_5
PFNDOLCREATETRANSFORMFEEDBACKSPROC dolCreateTransformFeedbacks;
PFNDOLTRANSFORMFEEDBACKBUFFERBASEPROC dolTransformFeedbackBufferBase;
PFNDOLTRANSFORMFEEDBACKBUFFERRANGEPROC dolTransformFeedbackBufferRange;
PFNDOLGETTRANSFORMFEEDBACKIVPROC dolGetTransformFeedbackiv;
PFNDOLGETTRANSFORMFEEDBACKI_VPROC dolGetTransformFeedbacki_v;
PFNDOLGETTRANSFORMFEEDBACKI64_VPROC dolGetTransformFeedbacki64_v;
PFNDOLCREATEBUFFERSPROC dolCreateBuffers;
PFNDOLNAMEDBUFFERSTORAGEPROC dolNamedBufferStorage;
PFNDOLNAMEDBUFFERDATAPROC dolNamedBufferData;
PFNDOLNAMEDBUFFERSUBDATAPROC dolNamedBufferSubData;
PFNDOLCOPYNAMEDBUFFERSUBDATAPROC dolCopyNamedBufferSubData;
PFNDOLCLEARNAMEDBUFFERDATAPROC dolClearNamedBufferData;
PFNDOLCLEARNAMEDBUFFERSUBDATAPROC dolClearNamedBufferSubData;
PFNDOLMAPNAMEDBUFFERPROC dolMapNamedBuffer;
PFNDOLMAPNAMEDBUFFERRANGEPROC dolMapNamedBufferRange;
PFNDOLUNMAPNAMEDBUFFERPROC dolUnmapNamedBuffer;
PFNDOLFLUSHMAPPEDNAMEDBUFFERRANGEPROC dolFlushMappedNamedBufferRange;
PFNDOLGETNAMEDBUFFERPARAMETERIVPROC dolGetNamedBufferParameteriv;
PFNDOLGETNAMEDBUFFERPARAMETERI64VPROC dolGetNamedBufferParameteri64v;
PFNDOLGETNAMEDBUFFERPOINTERVPROC dolGetNamedBufferPointerv;
PFNDOLGETNAMEDBUFFERSUBDATAPROC dolGetNamedBufferSubData;
PFNDOLCREATEFRAMEBUFFERSPROC dolCreateFramebuffers;
PFNDOLNAMEDFRAMEBUFFERRENDERBUFFERPROC dolNamedFramebufferRenderbuffer;
PFNDOLNAMEDFRAMEBUFFERPARAMETERIPROC dolNamedFramebufferParameteri;
PFNDOLNAMEDFRAMEBUFFERTEXTUREPROC dolNamedFramebufferTexture;
PFNDOLNAMEDFRAMEBUFFERTEXTURELAYERPROC dolNamedFramebufferTextureLayer;
PFNDOLNAMEDFRAMEBUFFERDRAWBUFFERPROC dolNamedFramebufferDrawBuffer;
PFNDOLNAMEDFRAMEBUFFERDRAWBUFFERSPROC dolNamedFramebufferDrawBuffers;
PFNDOLNAMEDFRAMEBUFFERREADBUFFERPROC dolNamedFramebufferReadBuffer;
PFNDOLINVALIDATENAMEDFRAMEBUFFERDATAPROC dolInvalidateNamedFramebufferData;
PFNDOLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC dolInvalidateNamedFramebufferSubData;
PFNDOLCLEARNAMEDFRAMEBUFFERIVPROC dolClearNamedFramebufferiv;
PFNDOLCLEARNAMEDFRAMEBUFFERUIVPROC dolClearNamedFramebufferuiv;
PFNDOLCLEARNAMEDFRAMEBUFFERFVPROC dolClearNamedFramebufferfv;
PFNDOLCLEARNAMEDFRAMEBUFFERFIPROC dolClearNamedFramebufferfi;
PFNDOLBLITNAMEDFRAMEBUFFERPROC dolBlitNamedFramebuffer;
PFNDOLCHECKNAMEDFRAMEBUFFERSTATUSPROC dolCheckNamedFramebufferStatus;
PFNDOLGETNAMEDFRAMEBUFFERPARAMETERIVPROC dolGetNamedFramebufferParameteriv;
PFNDOLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC dolGetNamedFramebufferAttachmentParameteriv;
PFNDOLCREATERENDERBUFFERSPROC dolCreateRenderbuffers;
PFNDOLNAMEDRENDERBUFFERSTORAGEPROC dolNamedRenderbufferStorage;
PFNDOLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC dolNamedRenderbufferStorageMultisample;
PFNDOLGETNAMEDRENDERBUFFERPARAMETERIVPROC dolGetNamedRenderbufferParameteriv;
PFNDOLCREATETEXTURESPROC dolCreateTextures;
PFNDOLTEXTUREBUFFERPROC dolTextureBuffer;
PFNDOLTEXTUREBUFFERRANGEPROC dolTextureBufferRange;
PFNDOLTEXTURESTORAGE1DPROC dolTextureStorage1D;
PFNDOLTEXTURESTORAGE2DPROC dolTextureStorage2D;
PFNDOLTEXTURESTORAGE3DPROC dolTextureStorage3D;
PFNDOLTEXTURESTORAGE2DMULTISAMPLEPROC dolTextureStorage2DMultisample;
PFNDOLTEXTURESTORAGE3DMULTISAMPLEPROC dolTextureStorage3DMultisample;
PFNDOLTEXTURESUBIMAGE1DPROC dolTextureSubImage1D;
PFNDOLTEXTURESUBIMAGE2DPROC dolTextureSubImage2D;
PFNDOLTEXTURESUBIMAGE3DPROC dolTextureSubImage3D;
PFNDOLCOMPRESSEDTEXTURESUBIMAGE1DPROC dolCompressedTextureSubImage1D;
PFNDOLCOMPRESSEDTEXTURESUBIMAGE2DPROC dolCompressedTextureSubImage2D;
PFNDOLCOMPRESSEDTEXTURESUBIMAGE3DPROC dolCompressedTextureSubImage3D;
PFNDOLCOPYTEXTURESUBIMAGE1DPROC dolCopyTextureSubImage1D;
PFNDOLCOPYTEXTURESUBIMAGE2DPROC dolCopyTextureSubImage2D;
PFNDOLCOPYTEXTURESUBIMAGE3DPROC dolCopyTextureSubImage3D;
PFNDOLTEXTUREPARAMETERFPROC dolTextureParameterf;
PFNDOLTEXTUREPARAMETERFVPROC dolTextureParameterfv;
PFNDOLTEXTUREPARAMETERIPROC dolTextureParameteri;
PFNDOLTEXTUREPARAMETERIIVPROC dolTextureParameterIiv;
PFNDOLTEXTUREPARAMETERIUIVPROC dolTextureParameterIuiv;
PFNDOLTEXTUREPARAMETERIVPROC dolTextureParameteriv;
PFNDOLGENERATETEXTUREMIPMAPPROC dolGenerateTextureMipmap;
PFNDOLBINDTEXTUREUNITPROC dolBindTextureUnit;
PFNDOLGETTEXTUREIMAGEPROC dolGetTextureImage;
PFNDOLGETCOMPRESSEDTEXTUREIMAGEPROC dolGetCompressedTextureImage;
PFNDOLGETTEXTURELEVELPARAMETERFVPROC dolGetTextureLevelParameterfv;
PFNDOLGETTEXTURELEVELPARAMETERIVPROC dolGetTextureLevelParameteriv;
PFNDOLGETTEXTUREPARAMETERFVPROC dolGetTextureParameterfv;
PFNDOLGETTEXTUREPARAMETERIIVPROC dolGetTextureParameterIiv;
PFNDOLGETTEXTUREPARAMETERIUIVPROC dolGetTextureParameterIuiv;
PFNDOLGETTEXTUREPARAMETERIVPROC dolGetTextureParameteriv;
PFNDOLCREATEVERTEXARRAYSPROC dolCreateVertexArrays;
PFNDOLDISABLEVERTEXARRAYATTRIBPROC dolDisableVertexArrayAttrib;
PFNDOLENABLEVERTEXARRAYATTRIBPROC dolEnableVertexArrayAttrib;
PFNDOLVERTEXARRAYELEMENTBUFFERPROC dolVertexArrayElementBuffer;
PFNDOLVERTEXARRAYVERTEXBUFFERPROC dolVertexArrayVertexBuffer;
PFNDOLVERTEXARRAYVERTEXBUFFERSPROC dolVertexArrayVertexBuffers;
PFNDOLVERTEXARRAYATTRIBBINDINGPROC dolVertexArrayAttribBinding;
PFNDOLVERTEXARRAYATTRIBFORMATPROC dolVertexArrayAttribFormat;
PFNDOLVERTEXARRAYATTRIBIFORMATPROC dolVertexArrayAttribIFormat;
PFNDOLVERTEXARRAYATTRIBLFORMATPROC dolVertexArrayAttribLFormat;
PFNDOLVERTEXARRAYBINDINGDIVISORPROC dolVertexArrayBindingDivisor;
PFNDOLGETVERTEXARRAYIVPROC dolGetVertexArrayiv;
PFNDOLGETVERTEXARRAYINDEXEDIVPROC dolGetVertexArrayIndexediv;
PFNDOLGETVERTEXARRAYINDEXED64IVPROC dolGetVertexArrayIndexed64iv;
PFNDOLCREATESAMPLERSPROC dolCreateSamplers;
PFNDOLCREATEPROGRAMPIPELINESPROC dolCreateProgramPipelines;
PFNDOLCREATEQUERIESPROC dolCreateQueries;
PFNDOLGETQUERYBUFFEROBJECTI64VPROC dolGetQueryBufferObjecti64v;
PFNDOLGETQUERYBUFFEROBJECTIVPROC dolGetQueryBufferObjectiv;
PFNDOLGETQUERYBUFFEROBJECTUI64VPROC dolGetQueryBufferObjectui64v;
PFNDOLGETQUERYBUFFEROBJECTUIVPROC dolGetQueryBufferObjectuiv;
PFNDOLMEMORYBARRIERBYREGIONPROC dolMemoryBarrierByRegion;
PFNDOLGETTEXTURESUBIMAGEPROC dolGetTextureSubImage;
PFNDOLGETCOMPRESSEDTEXTURESUBIMAGEPROC dolGetCompressedTextureSubImage;
PFNDOLGETGRAPHICSRESETSTATUSPROC dolGetGraphicsResetStatus;
PFNDOLGETNCOMPRESSEDTEXIMAGEPROC dolGetnCompressedTexImage;
PFNDOLGETNTEXIMAGEPROC dolGetnTexImage;
PFNDOLGETNUNIFORMDVPROC dolGetnUniformdv;
PFNDOLGETNUNIFORMFVPROC dolGetnUniformfv;
PFNDOLGETNUNIFORMIVPROC dolGetnUniformiv;
PFNDOLGETNUNIFORMUIVPROC dolGetnUniformuiv;
PFNDOLREADNPIXELSPROC dolReadnPixels;
PFNDOLGETNMAPDVPROC dolGetnMapdv;
PFNDOLGETNMAPFVPROC dolGetnMapfv;
PFNDOLGETNMAPIVPROC dolGetnMapiv;
PFNDOLGETNPIXELMAPFVPROC dolGetnPixelMapfv;
PFNDOLGETNPIXELMAPUIVPROC dolGetnPixelMapuiv;
PFNDOLGETNPIXELMAPUSVPROC dolGetnPixelMapusv;
PFNDOLGETNPOLYGONSTIPPLEPROC dolGetnPolygonStipple;
PFNDOLGETNCOLORTABLEPROC dolGetnColorTable;
PFNDOLGETNCONVOLUTIONFILTERPROC dolGetnConvolutionFilter;
PFNDOLGETNSEPARABLEFILTERPROC dolGetnSeparableFilter;
PFNDOLGETNHISTOGRAMPROC dolGetnHistogram;
PFNDOLGETNMINMAXPROC dolGetnMinmax;
PFNDOLTEXTUREBARRIERPROC dolTextureBarrier;
// ARB_uniform_buffer_object
PFNDOLBINDBUFFERBASEPROC dolBindBufferBase;
PFNDOLBINDBUFFERRANGEPROC dolBindBufferRange;
PFNDOLGETACTIVEUNIFORMBLOCKNAMEPROC dolGetActiveUniformBlockName;
PFNDOLGETACTIVEUNIFORMBLOCKIVPROC dolGetActiveUniformBlockiv;
PFNDOLGETACTIVEUNIFORMNAMEPROC dolGetActiveUniformName;
PFNDOLGETACTIVEUNIFORMSIVPROC dolGetActiveUniformsiv;
PFNDOLGETINTEGERI_VPROC dolGetIntegeri_v;
PFNDOLGETUNIFORMBLOCKINDEXPROC dolGetUniformBlockIndex;
PFNDOLGETUNIFORMINDICESPROC dolGetUniformIndices;
PFNDOLUNIFORMBLOCKBINDINGPROC dolUniformBlockBinding;
// ARB_sampler_objects
PFNDOLBINDSAMPLERPROC dolBindSampler;
PFNDOLDELETESAMPLERSPROC dolDeleteSamplers;
PFNDOLGENSAMPLERSPROC dolGenSamplers;
PFNDOLGETSAMPLERPARAMETERIIVPROC dolGetSamplerParameterIiv;
PFNDOLGETSAMPLERPARAMETERIUIVPROC dolGetSamplerParameterIuiv;
PFNDOLGETSAMPLERPARAMETERFVPROC dolGetSamplerParameterfv;
PFNDOLGETSAMPLERPARAMETERIVPROC dolGetSamplerParameteriv;
PFNDOLISSAMPLERPROC dolIsSampler;
PFNDOLSAMPLERPARAMETERIIVPROC dolSamplerParameterIiv;
PFNDOLSAMPLERPARAMETERIUIVPROC dolSamplerParameterIuiv;
PFNDOLSAMPLERPARAMETERFPROC dolSamplerParameterf;
PFNDOLSAMPLERPARAMETERFVPROC dolSamplerParameterfv;
PFNDOLSAMPLERPARAMETERIPROC dolSamplerParameteri;
PFNDOLSAMPLERPARAMETERIVPROC dolSamplerParameteriv;
// ARB_map_buffer_range
PFNDOLFLUSHMAPPEDBUFFERRANGEPROC dolFlushMappedBufferRange;
PFNDOLMAPBUFFERRANGEPROC dolMapBufferRange;
// ARB_vertex_array_object
PFNDOLBINDVERTEXARRAYPROC dolBindVertexArray;
PFNDOLDELETEVERTEXARRAYSPROC dolDeleteVertexArrays;
PFNDOLGENVERTEXARRAYSPROC dolGenVertexArrays;
PFNDOLISVERTEXARRAYPROC dolIsVertexArray;
// ARB_framebuffer_object
PFNDOLBINDFRAMEBUFFERPROC dolBindFramebuffer;
PFNDOLBINDRENDERBUFFERPROC dolBindRenderbuffer;
PFNDOLBLITFRAMEBUFFERPROC dolBlitFramebuffer;
PFNDOLCHECKFRAMEBUFFERSTATUSPROC dolCheckFramebufferStatus;
PFNDOLDELETEFRAMEBUFFERSPROC dolDeleteFramebuffers;
PFNDOLDELETERENDERBUFFERSPROC dolDeleteRenderbuffers;
PFNDOLFRAMEBUFFERRENDERBUFFERPROC dolFramebufferRenderbuffer;
PFNDOLFRAMEBUFFERTEXTURE1DPROC dolFramebufferTexture1D;
PFNDOLFRAMEBUFFERTEXTURE2DPROC dolFramebufferTexture2D;
PFNDOLFRAMEBUFFERTEXTURE3DPROC dolFramebufferTexture3D;
PFNDOLFRAMEBUFFERTEXTURELAYERPROC dolFramebufferTextureLayer;
PFNDOLGENFRAMEBUFFERSPROC dolGenFramebuffers;
PFNDOLGENRENDERBUFFERSPROC dolGenRenderbuffers;
PFNDOLGENERATEMIPMAPPROC dolGenerateMipmap;
PFNDOLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC dolGetFramebufferAttachmentParameteriv;
PFNDOLGETRENDERBUFFERPARAMETERIVPROC dolGetRenderbufferParameteriv;
PFNDOLISFRAMEBUFFERPROC dolIsFramebuffer;
PFNDOLISRENDERBUFFERPROC dolIsRenderbuffer;
PFNDOLRENDERBUFFERSTORAGEPROC dolRenderbufferStorage;
PFNDOLRENDERBUFFERSTORAGEMULTISAMPLEPROC dolRenderbufferStorageMultisample;
// ARB_get_program_binary
PFNDOLGETPROGRAMBINARYPROC dolGetProgramBinary;
PFNDOLPROGRAMBINARYPROC dolProgramBinary;
PFNDOLPROGRAMPARAMETERIPROC dolProgramParameteri;
// ARB_sync
PFNDOLCLIENTWAITSYNCPROC dolClientWaitSync;
PFNDOLDELETESYNCPROC dolDeleteSync;
PFNDOLFENCESYNCPROC dolFenceSync;
PFNDOLGETINTEGER64VPROC dolGetInteger64v;
PFNDOLGETSYNCIVPROC dolGetSynciv;
PFNDOLISSYNCPROC dolIsSync;
PFNDOLWAITSYNCPROC dolWaitSync;
// ARB_texture_multisample
PFNDOLTEXIMAGE2DMULTISAMPLEPROC dolTexImage2DMultisample;
PFNDOLTEXIMAGE3DMULTISAMPLEPROC dolTexImage3DMultisample;
PFNDOLGETMULTISAMPLEFVPROC dolGetMultisamplefv;
PFNDOLSAMPLEMASKIPROC dolSampleMaski;
// ARB_texture_storage_multisample
PFNDOLTEXSTORAGE2DMULTISAMPLEPROC dolTexStorage2DMultisample;
PFNDOLTEXSTORAGE3DMULTISAMPLEPROC dolTexStorage3DMultisample;
// ARB_ES2_compatibility
PFNDOLCLEARDEPTHFPROC dolClearDepthf;
PFNDOLDEPTHRANGEFPROC dolDepthRangef;
PFNDOLGETSHADERPRECISIONFORMATPROC dolGetShaderPrecisionFormat;
PFNDOLRELEASESHADERCOMPILERPROC dolReleaseShaderCompiler;
PFNDOLSHADERBINARYPROC dolShaderBinary;
// NV_primitive_restart
PFNDOLPRIMITIVERESTARTINDEXNVPROC dolPrimitiveRestartIndexNV;
PFNDOLPRIMITIVERESTARTNVPROC dolPrimitiveRestartNV;
// ARB_blend_func_extended
PFNDOLBINDFRAGDATALOCATIONINDEXEDPROC dolBindFragDataLocationIndexed;
PFNDOLGETFRAGDATAINDEXPROC dolGetFragDataIndex;
// ARB_viewport_array
PFNDOLDEPTHRANGEARRAYVPROC dolDepthRangeArrayv;
PFNDOLDEPTHRANGEINDEXEDPROC dolDepthRangeIndexed;
PFNDOLGETDOUBLEI_VPROC dolGetDoublei_v;
PFNDOLGETFLOATI_VPROC dolGetFloati_v;
PFNDOLSCISSORARRAYVPROC dolScissorArrayv;
PFNDOLSCISSORINDEXEDPROC dolScissorIndexed;
PFNDOLSCISSORINDEXEDVPROC dolScissorIndexedv;
PFNDOLVIEWPORTARRAYVPROC dolViewportArrayv;
PFNDOLVIEWPORTINDEXEDFPROC dolViewportIndexedf;
PFNDOLVIEWPORTINDEXEDFVPROC dolViewportIndexedfv;
// ARB_draw_elements_base_vertex
PFNDOLDRAWELEMENTSBASEVERTEXPROC dolDrawElementsBaseVertex;
PFNDOLDRAWELEMENTSINSTANCEDBASEVERTEXPROC dolDrawElementsInstancedBaseVertex;
PFNDOLDRAWRANGEELEMENTSBASEVERTEXPROC dolDrawRangeElementsBaseVertex;
PFNDOLMULTIDRAWELEMENTSBASEVERTEXPROC dolMultiDrawElementsBaseVertex;
// ARB_sample_shading
PFNDOLMINSAMPLESHADINGARBPROC dolMinSampleShading;
// ARB_debug_output
PFNDOLDEBUGMESSAGECALLBACKARBPROC dolDebugMessageCallbackARB;
PFNDOLDEBUGMESSAGECONTROLARBPROC dolDebugMessageControlARB;
PFNDOLDEBUGMESSAGEINSERTARBPROC dolDebugMessageInsertARB;
PFNDOLGETDEBUGMESSAGELOGARBPROC dolGetDebugMessageLogARB;
// KHR_debug
PFNDOLDEBUGMESSAGECALLBACKPROC dolDebugMessageCallback;
PFNDOLDEBUGMESSAGECONTROLPROC dolDebugMessageControl;
PFNDOLDEBUGMESSAGEINSERTPROC dolDebugMessageInsert;
PFNDOLGETDEBUGMESSAGELOGPROC dolGetDebugMessageLog;
PFNDOLGETOBJECTLABELPROC dolGetObjectLabel;
PFNDOLGETOBJECTPTRLABELPROC dolGetObjectPtrLabel;
PFNDOLOBJECTLABELPROC dolObjectLabel;
PFNDOLOBJECTPTRLABELPROC dolObjectPtrLabel;
PFNDOLPOPDEBUGGROUPPROC dolPopDebugGroup;
PFNDOLPUSHDEBUGGROUPPROC dolPushDebugGroup;
// ARB_buffer_storage
PFNDOLBUFFERSTORAGEPROC dolBufferStorage;
// GL_NV_occlusion_query_samples
PFNDOLGENOCCLUSIONQUERIESNVPROC dolGenOcclusionQueriesNV;
PFNDOLDELETEOCCLUSIONQUERIESNVPROC dolDeleteOcclusionQueriesNV;
PFNDOLISOCCLUSIONQUERYNVPROC dolIsOcclusionQueryNV;
PFNDOLBEGINOCCLUSIONQUERYNVPROC dolBeginOcclusionQueryNV;
PFNDOLENDOCCLUSIONQUERYNVPROC dolEndOcclusionQueryNV;
PFNDOLGETOCCLUSIONQUERYIVNVPROC dolGetOcclusionQueryivNV;
PFNDOLGETOCCLUSIONQUERYUIVNVPROC dolGetOcclusionQueryuivNV;
// ARB_clip_control
PFNDOLCLIPCONTROLPROC dolClipControl;
// ARB_copy_image
PFNDOLCOPYIMAGESUBDATAPROC dolCopyImageSubData;
// ARB_shader_storage_buffer_object
PFNDOLSHADERSTORAGEBLOCKBINDINGPROC dolShaderStorageBlockBinding;
// Creates a GLFunc object that requires a feature
#define GLFUNC_REQUIRES(x, y) { (void**)&x, #x, y }
// Creates a GLFunc object with a different function suffix
// For when we want to use the same function pointer, but different function name
#define GLFUNC_SUFFIX(x, y, z) { (void**)&x, #x #y, z }
// Creates a GLFunc object that should always be able to get grabbed
// Used for Desktop OpenGL functions that should /always/ be provided.
// aka GL 1.1/1.2/1.3/1.4
#define GLFUNC_ALWAYS_REQUIRED(x) { (void**)&x, #x, "VERSION_GL" }
// Creates a GLFunc object that should be able to get grabbed
// on both GL and ES
#define GL_ES_FUNC_ALWAYS_REQUIRED(x) { (void**)&x, #x, "VERSION_GL |VERSION_GLES_2" }
// Creates a GLFunc object that should be able to get grabbed
// on both GL and ES 3.0
#define GL_ES3_FUNC_ALWAYS_REQUIRED(x) { (void**)&x, #x, "VERSION_GL |VERSION_GLES_3" }
// Creates a GLFunc object that should be able to get grabbed
// on both GL and ES 3.2
#define GL_ES32_FUNC_ALWAYS_REQUIRED(x) { (void**)&x, #x, "VERSION_GL |VERSION_GLES_3_2" }
struct GLFunc
{
void** function_ptr;
const std::string function_name;
const std::string requirements;
};
const GLFunc gl_function_array[] =
{
// gl_1_1
GLFUNC_ALWAYS_REQUIRED(glClearIndex),
GLFUNC_ALWAYS_REQUIRED(glIndexMask),
GLFUNC_ALWAYS_REQUIRED(glAlphaFunc),
GLFUNC_ALWAYS_REQUIRED(glLogicOp),
GLFUNC_ALWAYS_REQUIRED(glPointSize),
GLFUNC_ALWAYS_REQUIRED(glLineStipple),
GLFUNC_ALWAYS_REQUIRED(glPolygonMode),
GLFUNC_ALWAYS_REQUIRED(glPolygonStipple),
GLFUNC_ALWAYS_REQUIRED(glGetPolygonStipple),
GLFUNC_ALWAYS_REQUIRED(glEdgeFlag),
GLFUNC_ALWAYS_REQUIRED(glEdgeFlagv),
GLFUNC_ALWAYS_REQUIRED(glClipPlane),
GLFUNC_ALWAYS_REQUIRED(glGetClipPlane),
GLFUNC_ALWAYS_REQUIRED(glDrawBuffer),
GLFUNC_ALWAYS_REQUIRED(glEnableClientState),
GLFUNC_ALWAYS_REQUIRED(glDisableClientState),
GLFUNC_ALWAYS_REQUIRED(glGetDoublev),
GLFUNC_ALWAYS_REQUIRED(glPushAttrib),
GLFUNC_ALWAYS_REQUIRED(glPopAttrib),
GLFUNC_ALWAYS_REQUIRED(glPushClientAttrib),
GLFUNC_ALWAYS_REQUIRED(glPopClientAttrib),
GLFUNC_ALWAYS_REQUIRED(glRenderMode),
GLFUNC_ALWAYS_REQUIRED(glClearDepth),
GLFUNC_ALWAYS_REQUIRED(glDepthRange),
GLFUNC_ALWAYS_REQUIRED(glClearAccum),
GLFUNC_ALWAYS_REQUIRED(glAccum),
GLFUNC_ALWAYS_REQUIRED(glMatrixMode),
GLFUNC_ALWAYS_REQUIRED(glOrtho),
GLFUNC_ALWAYS_REQUIRED(glFrustum),
GLFUNC_ALWAYS_REQUIRED(glPushMatrix),
GLFUNC_ALWAYS_REQUIRED(glPopMatrix),
GLFUNC_ALWAYS_REQUIRED(glLoadIdentity),
GLFUNC_ALWAYS_REQUIRED(glLoadMatrixd),
GLFUNC_ALWAYS_REQUIRED(glLoadMatrixf),
GLFUNC_ALWAYS_REQUIRED(glMultMatrixd),
GLFUNC_ALWAYS_REQUIRED(glMultMatrixf),
GLFUNC_ALWAYS_REQUIRED(glRotated),
GLFUNC_ALWAYS_REQUIRED(glRotatef),
GLFUNC_ALWAYS_REQUIRED(glScaled),
GLFUNC_ALWAYS_REQUIRED(glScalef),
GLFUNC_ALWAYS_REQUIRED(glTranslated),
GLFUNC_ALWAYS_REQUIRED(glTranslatef),
GLFUNC_ALWAYS_REQUIRED(glIsList),
GLFUNC_ALWAYS_REQUIRED(glDeleteLists),
GLFUNC_ALWAYS_REQUIRED(glGenLists),
GLFUNC_ALWAYS_REQUIRED(glNewList),
GLFUNC_ALWAYS_REQUIRED(glEndList),
GLFUNC_ALWAYS_REQUIRED(glCallList),
GLFUNC_ALWAYS_REQUIRED(glCallLists),
GLFUNC_ALWAYS_REQUIRED(glListBase),
GLFUNC_ALWAYS_REQUIRED(glBegin),
GLFUNC_ALWAYS_REQUIRED(glEnd),
GLFUNC_ALWAYS_REQUIRED(glVertex2d),
GLFUNC_ALWAYS_REQUIRED(glVertex2f),
GLFUNC_ALWAYS_REQUIRED(glVertex2i),
GLFUNC_ALWAYS_REQUIRED(glVertex2s),
GLFUNC_ALWAYS_REQUIRED(glVertex3d),
GLFUNC_ALWAYS_REQUIRED(glVertex3f),
GLFUNC_ALWAYS_REQUIRED(glVertex3i),
GLFUNC_ALWAYS_REQUIRED(glVertex3s),
GLFUNC_ALWAYS_REQUIRED(glVertex4d),
GLFUNC_ALWAYS_REQUIRED(glVertex4f),
GLFUNC_ALWAYS_REQUIRED(glVertex4i),
GLFUNC_ALWAYS_REQUIRED(glVertex4s),
GLFUNC_ALWAYS_REQUIRED(glVertex2dv),
GLFUNC_ALWAYS_REQUIRED(glVertex2fv),
GLFUNC_ALWAYS_REQUIRED(glVertex2iv),
GLFUNC_ALWAYS_REQUIRED(glVertex2sv),
GLFUNC_ALWAYS_REQUIRED(glVertex3dv),
GLFUNC_ALWAYS_REQUIRED(glVertex3fv),
GLFUNC_ALWAYS_REQUIRED(glVertex3iv),
GLFUNC_ALWAYS_REQUIRED(glVertex3sv),
GLFUNC_ALWAYS_REQUIRED(glVertex4dv),
GLFUNC_ALWAYS_REQUIRED(glVertex4fv),
GLFUNC_ALWAYS_REQUIRED(glVertex4iv),
GLFUNC_ALWAYS_REQUIRED(glVertex4sv),
GLFUNC_ALWAYS_REQUIRED(glNormal3b),
GLFUNC_ALWAYS_REQUIRED(glNormal3d),
GLFUNC_ALWAYS_REQUIRED(glNormal3f),
GLFUNC_ALWAYS_REQUIRED(glNormal3i),
GLFUNC_ALWAYS_REQUIRED(glNormal3s),
GLFUNC_ALWAYS_REQUIRED(glNormal3bv),
GLFUNC_ALWAYS_REQUIRED(glNormal3dv),
GLFUNC_ALWAYS_REQUIRED(glNormal3fv),
GLFUNC_ALWAYS_REQUIRED(glNormal3iv),
GLFUNC_ALWAYS_REQUIRED(glNormal3sv),
GLFUNC_ALWAYS_REQUIRED(glIndexd),
GLFUNC_ALWAYS_REQUIRED(glIndexf),
GLFUNC_ALWAYS_REQUIRED(glIndexi),
GLFUNC_ALWAYS_REQUIRED(glIndexs),
GLFUNC_ALWAYS_REQUIRED(glIndexub),
GLFUNC_ALWAYS_REQUIRED(glIndexdv),
GLFUNC_ALWAYS_REQUIRED(glIndexfv),
GLFUNC_ALWAYS_REQUIRED(glIndexiv),
GLFUNC_ALWAYS_REQUIRED(glIndexsv),
GLFUNC_ALWAYS_REQUIRED(glIndexubv),
GLFUNC_ALWAYS_REQUIRED(glColor3b),
GLFUNC_ALWAYS_REQUIRED(glColor3d),
GLFUNC_ALWAYS_REQUIRED(glColor3f),
GLFUNC_ALWAYS_REQUIRED(glColor3i),
GLFUNC_ALWAYS_REQUIRED(glColor3s),
GLFUNC_ALWAYS_REQUIRED(glColor3ub),
GLFUNC_ALWAYS_REQUIRED(glColor3ui),
GLFUNC_ALWAYS_REQUIRED(glColor3us),
GLFUNC_ALWAYS_REQUIRED(glColor4b),
GLFUNC_ALWAYS_REQUIRED(glColor4d),
GLFUNC_ALWAYS_REQUIRED(glColor4f),
GLFUNC_ALWAYS_REQUIRED(glColor4i),
GLFUNC_ALWAYS_REQUIRED(glColor4s),
GLFUNC_ALWAYS_REQUIRED(glColor4ub),
GLFUNC_ALWAYS_REQUIRED(glColor4ui),
GLFUNC_ALWAYS_REQUIRED(glColor4us),
GLFUNC_ALWAYS_REQUIRED(glColor3bv),
GLFUNC_ALWAYS_REQUIRED(glColor3dv),
GLFUNC_ALWAYS_REQUIRED(glColor3fv),
GLFUNC_ALWAYS_REQUIRED(glColor3iv),
GLFUNC_ALWAYS_REQUIRED(glColor3sv),
GLFUNC_ALWAYS_REQUIRED(glColor3ubv),
GLFUNC_ALWAYS_REQUIRED(glColor3uiv),
GLFUNC_ALWAYS_REQUIRED(glColor3usv),
GLFUNC_ALWAYS_REQUIRED(glColor4bv),
GLFUNC_ALWAYS_REQUIRED(glColor4dv),
GLFUNC_ALWAYS_REQUIRED(glColor4fv),
GLFUNC_ALWAYS_REQUIRED(glColor4iv),
GLFUNC_ALWAYS_REQUIRED(glColor4sv),
GLFUNC_ALWAYS_REQUIRED(glColor4ubv),
GLFUNC_ALWAYS_REQUIRED(glColor4uiv),
GLFUNC_ALWAYS_REQUIRED(glColor4usv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord1d),
GLFUNC_ALWAYS_REQUIRED(glTexCoord1f),
GLFUNC_ALWAYS_REQUIRED(glTexCoord1i),
GLFUNC_ALWAYS_REQUIRED(glTexCoord1s),
GLFUNC_ALWAYS_REQUIRED(glTexCoord2d),
GLFUNC_ALWAYS_REQUIRED(glTexCoord2f),
GLFUNC_ALWAYS_REQUIRED(glTexCoord2i),
GLFUNC_ALWAYS_REQUIRED(glTexCoord2s),
GLFUNC_ALWAYS_REQUIRED(glTexCoord3d),
GLFUNC_ALWAYS_REQUIRED(glTexCoord3f),
GLFUNC_ALWAYS_REQUIRED(glTexCoord3i),
GLFUNC_ALWAYS_REQUIRED(glTexCoord3s),
GLFUNC_ALWAYS_REQUIRED(glTexCoord4d),
GLFUNC_ALWAYS_REQUIRED(glTexCoord4f),
GLFUNC_ALWAYS_REQUIRED(glTexCoord4i),
GLFUNC_ALWAYS_REQUIRED(glTexCoord4s),
GLFUNC_ALWAYS_REQUIRED(glTexCoord1dv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord1fv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord1iv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord1sv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord2dv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord2fv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord2iv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord2sv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord3dv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord3fv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord3iv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord3sv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord4dv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord4fv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord4iv),
GLFUNC_ALWAYS_REQUIRED(glTexCoord4sv),
GLFUNC_ALWAYS_REQUIRED(glRasterPos2d),
GLFUNC_ALWAYS_REQUIRED(glRasterPos2f),
GLFUNC_ALWAYS_REQUIRED(glRasterPos2i),
GLFUNC_ALWAYS_REQUIRED(glRasterPos2s),
GLFUNC_ALWAYS_REQUIRED(glRasterPos3d),
GLFUNC_ALWAYS_REQUIRED(glRasterPos3f),
GLFUNC_ALWAYS_REQUIRED(glRasterPos3i),
GLFUNC_ALWAYS_REQUIRED(glRasterPos3s),
GLFUNC_ALWAYS_REQUIRED(glRasterPos4d),
GLFUNC_ALWAYS_REQUIRED(glRasterPos4f),
GLFUNC_ALWAYS_REQUIRED(glRasterPos4i),
GLFUNC_ALWAYS_REQUIRED(glRasterPos4s),
GLFUNC_ALWAYS_REQUIRED(glRasterPos2dv),
GLFUNC_ALWAYS_REQUIRED(glRasterPos2fv),
GLFUNC_ALWAYS_REQUIRED(glRasterPos2iv),
GLFUNC_ALWAYS_REQUIRED(glRasterPos2sv),
GLFUNC_ALWAYS_REQUIRED(glRasterPos3dv),
GLFUNC_ALWAYS_REQUIRED(glRasterPos3fv),
GLFUNC_ALWAYS_REQUIRED(glRasterPos3iv),
GLFUNC_ALWAYS_REQUIRED(glRasterPos3sv),
GLFUNC_ALWAYS_REQUIRED(glRasterPos4dv),
GLFUNC_ALWAYS_REQUIRED(glRasterPos4fv),
GLFUNC_ALWAYS_REQUIRED(glRasterPos4iv),
GLFUNC_ALWAYS_REQUIRED(glRasterPos4sv),
GLFUNC_ALWAYS_REQUIRED(glRectd),
GLFUNC_ALWAYS_REQUIRED(glRectf),
GLFUNC_ALWAYS_REQUIRED(glRecti),
GLFUNC_ALWAYS_REQUIRED(glRects),
GLFUNC_ALWAYS_REQUIRED(glRectdv),
GLFUNC_ALWAYS_REQUIRED(glRectfv),
GLFUNC_ALWAYS_REQUIRED(glRectiv),
GLFUNC_ALWAYS_REQUIRED(glRectsv),
GLFUNC_ALWAYS_REQUIRED(glVertexPointer),
GLFUNC_ALWAYS_REQUIRED(glNormalPointer),
GLFUNC_ALWAYS_REQUIRED(glColorPointer),
GLFUNC_ALWAYS_REQUIRED(glIndexPointer),
GLFUNC_ALWAYS_REQUIRED(glTexCoordPointer),
GLFUNC_ALWAYS_REQUIRED(glEdgeFlagPointer),
GLFUNC_ALWAYS_REQUIRED(glArrayElement),
GLFUNC_ALWAYS_REQUIRED(glInterleavedArrays),
GLFUNC_ALWAYS_REQUIRED(glShadeModel),
GLFUNC_ALWAYS_REQUIRED(glLightf),
GLFUNC_ALWAYS_REQUIRED(glLighti),
GLFUNC_ALWAYS_REQUIRED(glLightfv),
GLFUNC_ALWAYS_REQUIRED(glLightiv),
GLFUNC_ALWAYS_REQUIRED(glGetLightfv),
GLFUNC_ALWAYS_REQUIRED(glGetLightiv),
GLFUNC_ALWAYS_REQUIRED(glLightModelf),
GLFUNC_ALWAYS_REQUIRED(glLightModeli),
GLFUNC_ALWAYS_REQUIRED(glLightModelfv),
GLFUNC_ALWAYS_REQUIRED(glLightModeliv),
GLFUNC_ALWAYS_REQUIRED(glMaterialf),
GLFUNC_ALWAYS_REQUIRED(glMateriali),
GLFUNC_ALWAYS_REQUIRED(glMaterialfv),
GLFUNC_ALWAYS_REQUIRED(glMaterialiv),
GLFUNC_ALWAYS_REQUIRED(glGetMaterialfv),
GLFUNC_ALWAYS_REQUIRED(glGetMaterialiv),
GLFUNC_ALWAYS_REQUIRED(glColorMaterial),
GLFUNC_ALWAYS_REQUIRED(glPixelZoom),
GLFUNC_ALWAYS_REQUIRED(glPixelStoref),
GLFUNC_ALWAYS_REQUIRED(glPixelTransferf),
GLFUNC_ALWAYS_REQUIRED(glPixelTransferi),
GLFUNC_ALWAYS_REQUIRED(glPixelMapfv),
GLFUNC_ALWAYS_REQUIRED(glPixelMapuiv),
GLFUNC_ALWAYS_REQUIRED(glPixelMapusv),
GLFUNC_ALWAYS_REQUIRED(glGetPixelMapfv),
GLFUNC_ALWAYS_REQUIRED(glGetPixelMapuiv),
GLFUNC_ALWAYS_REQUIRED(glGetPixelMapusv),
GLFUNC_ALWAYS_REQUIRED(glBitmap),
GLFUNC_ALWAYS_REQUIRED(glDrawPixels),
GLFUNC_ALWAYS_REQUIRED(glCopyPixels),
GLFUNC_ALWAYS_REQUIRED(glTexGend),
GLFUNC_ALWAYS_REQUIRED(glTexGenf),
GLFUNC_ALWAYS_REQUIRED(glTexGeni),
GLFUNC_ALWAYS_REQUIRED(glTexGendv),
GLFUNC_ALWAYS_REQUIRED(glTexGenfv),
GLFUNC_ALWAYS_REQUIRED(glTexGeniv),
GLFUNC_ALWAYS_REQUIRED(glGetTexGendv),
GLFUNC_ALWAYS_REQUIRED(glGetTexGenfv),
GLFUNC_ALWAYS_REQUIRED(glGetTexGeniv),
GLFUNC_ALWAYS_REQUIRED(glTexEnvf),
GLFUNC_ALWAYS_REQUIRED(glTexEnvi),
GLFUNC_ALWAYS_REQUIRED(glTexEnvfv),
GLFUNC_ALWAYS_REQUIRED(glTexEnviv),
GLFUNC_ALWAYS_REQUIRED(glGetTexEnvfv),
GLFUNC_ALWAYS_REQUIRED(glGetTexEnviv),
GLFUNC_ALWAYS_REQUIRED(glGetTexLevelParameterfv),
GLFUNC_ALWAYS_REQUIRED(glGetTexLevelParameteriv),
GLFUNC_ALWAYS_REQUIRED(glTexImage1D),
GLFUNC_ALWAYS_REQUIRED(glGetTexImage),
GLFUNC_ALWAYS_REQUIRED(glPrioritizeTextures),
GLFUNC_ALWAYS_REQUIRED(glAreTexturesResident),
GLFUNC_ALWAYS_REQUIRED(glTexSubImage1D),
GLFUNC_ALWAYS_REQUIRED(glCopyTexImage1D),
GLFUNC_ALWAYS_REQUIRED(glCopyTexSubImage1D),
GLFUNC_ALWAYS_REQUIRED(glMap1d),
GLFUNC_ALWAYS_REQUIRED(glMap1f),
GLFUNC_ALWAYS_REQUIRED(glMap2d),
GLFUNC_ALWAYS_REQUIRED(glMap2f),
GLFUNC_ALWAYS_REQUIRED(glGetMapdv),
GLFUNC_ALWAYS_REQUIRED(glGetMapfv),
GLFUNC_ALWAYS_REQUIRED(glGetMapiv),
GLFUNC_ALWAYS_REQUIRED(glEvalCoord1d),
GLFUNC_ALWAYS_REQUIRED(glEvalCoord1f),
GLFUNC_ALWAYS_REQUIRED(glEvalCoord1dv),
GLFUNC_ALWAYS_REQUIRED(glEvalCoord1fv),
GLFUNC_ALWAYS_REQUIRED(glEvalCoord2d),
GLFUNC_ALWAYS_REQUIRED(glEvalCoord2f),
GLFUNC_ALWAYS_REQUIRED(glEvalCoord2dv),
GLFUNC_ALWAYS_REQUIRED(glEvalCoord2fv),
GLFUNC_ALWAYS_REQUIRED(glMapGrid1d),
GLFUNC_ALWAYS_REQUIRED(glMapGrid1f),
GLFUNC_ALWAYS_REQUIRED(glMapGrid2d),
GLFUNC_ALWAYS_REQUIRED(glMapGrid2f),
GLFUNC_ALWAYS_REQUIRED(glEvalPoint1),
GLFUNC_ALWAYS_REQUIRED(glEvalPoint2),
GLFUNC_ALWAYS_REQUIRED(glEvalMesh1),
GLFUNC_ALWAYS_REQUIRED(glEvalMesh2),
GLFUNC_ALWAYS_REQUIRED(glFogf),
GLFUNC_ALWAYS_REQUIRED(glFogi),
GLFUNC_ALWAYS_REQUIRED(glFogfv),
GLFUNC_ALWAYS_REQUIRED(glFogiv),
GLFUNC_ALWAYS_REQUIRED(glFeedbackBuffer),
GLFUNC_ALWAYS_REQUIRED(glPassThrough),
GLFUNC_ALWAYS_REQUIRED(glSelectBuffer),
GLFUNC_ALWAYS_REQUIRED(glInitNames),
GLFUNC_ALWAYS_REQUIRED(glLoadName),
GLFUNC_ALWAYS_REQUIRED(glPushName),
GLFUNC_ALWAYS_REQUIRED(glPopName),
GL_ES_FUNC_ALWAYS_REQUIRED(glTexImage2D),
GL_ES_FUNC_ALWAYS_REQUIRED(glClearColor),
GL_ES_FUNC_ALWAYS_REQUIRED(glClear),
GL_ES_FUNC_ALWAYS_REQUIRED(glColorMask),
GL_ES_FUNC_ALWAYS_REQUIRED(glBlendFunc),
GL_ES_FUNC_ALWAYS_REQUIRED(glCullFace),
GL_ES_FUNC_ALWAYS_REQUIRED(glFrontFace),
GL_ES_FUNC_ALWAYS_REQUIRED(glLineWidth),
GL_ES_FUNC_ALWAYS_REQUIRED(glPolygonOffset),
GL_ES_FUNC_ALWAYS_REQUIRED(glScissor),
GL_ES_FUNC_ALWAYS_REQUIRED(glEnable),
GL_ES_FUNC_ALWAYS_REQUIRED(glDisable),
GL_ES_FUNC_ALWAYS_REQUIRED(glIsEnabled),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetBooleanv),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetFloatv),
GL_ES_FUNC_ALWAYS_REQUIRED(glFinish),
GL_ES_FUNC_ALWAYS_REQUIRED(glFlush),
GL_ES_FUNC_ALWAYS_REQUIRED(glHint),
GL_ES_FUNC_ALWAYS_REQUIRED(glDepthFunc),
GL_ES_FUNC_ALWAYS_REQUIRED(glDepthMask),
GL_ES_FUNC_ALWAYS_REQUIRED(glViewport),
GL_ES_FUNC_ALWAYS_REQUIRED(glDrawArrays),
GL_ES_FUNC_ALWAYS_REQUIRED(glDrawElements),
GL_ES_FUNC_ALWAYS_REQUIRED(glPixelStorei),
GL_ES_FUNC_ALWAYS_REQUIRED(glReadPixels),
GL_ES_FUNC_ALWAYS_REQUIRED(glStencilFunc),
GL_ES_FUNC_ALWAYS_REQUIRED(glStencilMask),
GL_ES_FUNC_ALWAYS_REQUIRED(glStencilOp),
GL_ES_FUNC_ALWAYS_REQUIRED(glClearStencil),
GL_ES_FUNC_ALWAYS_REQUIRED(glTexParameterf),
GL_ES_FUNC_ALWAYS_REQUIRED(glTexParameteri),
GL_ES_FUNC_ALWAYS_REQUIRED(glTexParameterfv),
GL_ES_FUNC_ALWAYS_REQUIRED(glTexParameteriv),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetTexParameterfv),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetTexParameteriv),
GL_ES_FUNC_ALWAYS_REQUIRED(glGenTextures),
GL_ES_FUNC_ALWAYS_REQUIRED(glDeleteTextures),
GL_ES_FUNC_ALWAYS_REQUIRED(glBindTexture),
GL_ES_FUNC_ALWAYS_REQUIRED(glIsTexture),
GL_ES_FUNC_ALWAYS_REQUIRED(glTexSubImage2D),
GL_ES_FUNC_ALWAYS_REQUIRED(glCopyTexImage2D),
GL_ES_FUNC_ALWAYS_REQUIRED(glCopyTexSubImage2D),
GL_ES3_FUNC_ALWAYS_REQUIRED(glReadBuffer),
GL_ES32_FUNC_ALWAYS_REQUIRED(glGetPointerv),
// gl_1_2
GL_ES3_FUNC_ALWAYS_REQUIRED(glCopyTexSubImage3D),
GL_ES3_FUNC_ALWAYS_REQUIRED(glDrawRangeElements),
GL_ES3_FUNC_ALWAYS_REQUIRED(glTexImage3D),
GL_ES3_FUNC_ALWAYS_REQUIRED(glTexSubImage3D),
// gl_1_3
GLFUNC_ALWAYS_REQUIRED(glClientActiveTexture),
GLFUNC_ALWAYS_REQUIRED(glCompressedTexImage1D),
GLFUNC_ALWAYS_REQUIRED(glCompressedTexSubImage1D),
GLFUNC_ALWAYS_REQUIRED(glGetCompressedTexImage),
GLFUNC_ALWAYS_REQUIRED(glLoadTransposeMatrixd),
GLFUNC_ALWAYS_REQUIRED(glLoadTransposeMatrixf),
GLFUNC_ALWAYS_REQUIRED(glMultTransposeMatrixd),
GLFUNC_ALWAYS_REQUIRED(glMultTransposeMatrixf),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1d),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1dv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1f),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1fv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1i),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1iv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1s),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1sv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2d),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2dv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2f),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2fv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2i),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2iv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2s),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2sv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3d),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3dv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3f),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3fv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3i),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3iv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3s),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3sv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4d),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4dv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4f),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4fv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4i),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4iv),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4s),
GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4sv),
GL_ES_FUNC_ALWAYS_REQUIRED(glSampleCoverage),
GL_ES_FUNC_ALWAYS_REQUIRED(glActiveTexture),
GL_ES_FUNC_ALWAYS_REQUIRED(glCompressedTexImage2D),
GL_ES_FUNC_ALWAYS_REQUIRED(glCompressedTexSubImage2D),
GL_ES3_FUNC_ALWAYS_REQUIRED(glCompressedTexImage3D),
GL_ES3_FUNC_ALWAYS_REQUIRED(glCompressedTexSubImage3D),
// gl_1_4
GLFUNC_ALWAYS_REQUIRED(glFogCoordPointer),
GLFUNC_ALWAYS_REQUIRED(glFogCoordd),
GLFUNC_ALWAYS_REQUIRED(glFogCoorddv),
GLFUNC_ALWAYS_REQUIRED(glFogCoordf),
GLFUNC_ALWAYS_REQUIRED(glFogCoordfv),
GLFUNC_ALWAYS_REQUIRED(glMultiDrawArrays),
GLFUNC_ALWAYS_REQUIRED(glMultiDrawElements),
GLFUNC_ALWAYS_REQUIRED(glPointParameterf),
GLFUNC_ALWAYS_REQUIRED(glPointParameterfv),
GLFUNC_ALWAYS_REQUIRED(glPointParameteri),
GLFUNC_ALWAYS_REQUIRED(glPointParameteriv),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3b),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3bv),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3d),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3dv),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3f),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3fv),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3i),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3iv),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3s),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3sv),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3ub),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3ubv),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3ui),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3uiv),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3us),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3usv),
GLFUNC_ALWAYS_REQUIRED(glSecondaryColorPointer),
GLFUNC_ALWAYS_REQUIRED(glWindowPos2d),
GLFUNC_ALWAYS_REQUIRED(glWindowPos2dv),
GLFUNC_ALWAYS_REQUIRED(glWindowPos2f),
GLFUNC_ALWAYS_REQUIRED(glWindowPos2fv),
GLFUNC_ALWAYS_REQUIRED(glWindowPos2i),
GLFUNC_ALWAYS_REQUIRED(glWindowPos2iv),
GLFUNC_ALWAYS_REQUIRED(glWindowPos2s),
GLFUNC_ALWAYS_REQUIRED(glWindowPos2sv),
GLFUNC_ALWAYS_REQUIRED(glWindowPos3d),
GLFUNC_ALWAYS_REQUIRED(glWindowPos3dv),
GLFUNC_ALWAYS_REQUIRED(glWindowPos3f),
GLFUNC_ALWAYS_REQUIRED(glWindowPos3fv),
GLFUNC_ALWAYS_REQUIRED(glWindowPos3i),
GLFUNC_ALWAYS_REQUIRED(glWindowPos3iv),
GLFUNC_ALWAYS_REQUIRED(glWindowPos3s),
GLFUNC_ALWAYS_REQUIRED(glWindowPos3sv),
GL_ES_FUNC_ALWAYS_REQUIRED(glBlendColor),
GL_ES_FUNC_ALWAYS_REQUIRED(glBlendEquation),
GL_ES_FUNC_ALWAYS_REQUIRED(glBlendFuncSeparate),
// gl_1_5
GLFUNC_ALWAYS_REQUIRED(glGetBufferSubData),
GLFUNC_ALWAYS_REQUIRED(glGetQueryObjectiv),
GLFUNC_ALWAYS_REQUIRED(glMapBuffer),
GL_ES_FUNC_ALWAYS_REQUIRED(glBindBuffer),
GL_ES_FUNC_ALWAYS_REQUIRED(glBufferData),
GL_ES_FUNC_ALWAYS_REQUIRED(glBufferSubData),
GL_ES_FUNC_ALWAYS_REQUIRED(glDeleteBuffers),
GL_ES_FUNC_ALWAYS_REQUIRED(glGenBuffers),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetBufferParameteriv),
GL_ES_FUNC_ALWAYS_REQUIRED(glIsBuffer),
GL_ES3_FUNC_ALWAYS_REQUIRED(glBeginQuery),
GL_ES3_FUNC_ALWAYS_REQUIRED(glDeleteQueries),
GL_ES3_FUNC_ALWAYS_REQUIRED(glEndQuery),
GL_ES3_FUNC_ALWAYS_REQUIRED(glGenQueries),
GL_ES3_FUNC_ALWAYS_REQUIRED(glIsQuery),
GL_ES3_FUNC_ALWAYS_REQUIRED(glGetQueryiv),
GL_ES3_FUNC_ALWAYS_REQUIRED(glGetQueryObjectuiv),
GL_ES3_FUNC_ALWAYS_REQUIRED(glGetBufferPointerv),
GL_ES3_FUNC_ALWAYS_REQUIRED(glUnmapBuffer),
// gl_2_0
GLFUNC_ALWAYS_REQUIRED(glGetVertexAttribdv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib1d),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib1dv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib1s),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib1sv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib2d),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib2dv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib2s),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib2sv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib3d),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib3dv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib3s),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib3sv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Nbv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Niv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Nsv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Nub),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Nubv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Nuiv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Nusv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4bv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4d),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4dv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4iv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4s),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4sv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4ubv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4uiv),
GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4usv),
GL_ES_FUNC_ALWAYS_REQUIRED(glAttachShader),
GL_ES_FUNC_ALWAYS_REQUIRED(glBindAttribLocation),
GL_ES_FUNC_ALWAYS_REQUIRED(glBlendEquationSeparate),
GL_ES_FUNC_ALWAYS_REQUIRED(glCompileShader),
GL_ES_FUNC_ALWAYS_REQUIRED(glCreateProgram),
GL_ES_FUNC_ALWAYS_REQUIRED(glCreateShader),
GL_ES_FUNC_ALWAYS_REQUIRED(glDeleteProgram),
GL_ES_FUNC_ALWAYS_REQUIRED(glDeleteShader),
GL_ES_FUNC_ALWAYS_REQUIRED(glDetachShader),
GL_ES_FUNC_ALWAYS_REQUIRED(glDisableVertexAttribArray),
GL_ES_FUNC_ALWAYS_REQUIRED(glEnableVertexAttribArray),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetActiveAttrib),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetActiveUniform),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetAttachedShaders),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetAttribLocation),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetProgramInfoLog),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetProgramiv),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetShaderInfoLog),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetShaderSource),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetShaderiv),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetUniformLocation),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetUniformfv),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetUniformiv),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetVertexAttribPointerv),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetVertexAttribfv),
GL_ES_FUNC_ALWAYS_REQUIRED(glGetVertexAttribiv),
GL_ES_FUNC_ALWAYS_REQUIRED(glIsProgram),
GL_ES_FUNC_ALWAYS_REQUIRED(glIsShader),
GL_ES_FUNC_ALWAYS_REQUIRED(glLinkProgram),
GL_ES_FUNC_ALWAYS_REQUIRED(glShaderSource),
GL_ES_FUNC_ALWAYS_REQUIRED(glStencilFuncSeparate),
GL_ES_FUNC_ALWAYS_REQUIRED(glStencilMaskSeparate),
GL_ES_FUNC_ALWAYS_REQUIRED(glStencilOpSeparate),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform1f),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform1fv),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform1i),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform1iv),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform2f),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform2fv),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform2i),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform2iv),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform3f),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform3fv),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform3i),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform3iv),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform4f),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform4fv),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform4i),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniform4iv),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniformMatrix2fv),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniformMatrix3fv),
GL_ES_FUNC_ALWAYS_REQUIRED(glUniformMatrix4fv),
GL_ES_FUNC_ALWAYS_REQUIRED(glUseProgram),
GL_ES_FUNC_ALWAYS_REQUIRED(glValidateProgram),
GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib1f),
GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib1fv),
GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib2f),
GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib2fv),
GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib3f),
GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib3fv),
GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib4f),
GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib4fv),
GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttribPointer),
GL_ES3_FUNC_ALWAYS_REQUIRED(glDrawBuffers),
// gl_2_1
GLFUNC_ALWAYS_REQUIRED(glUniformMatrix2x3fv),
GLFUNC_ALWAYS_REQUIRED(glUniformMatrix2x4fv),
GLFUNC_ALWAYS_REQUIRED(glUniformMatrix3x2fv),
GLFUNC_ALWAYS_REQUIRED(glUniformMatrix3x4fv),
GLFUNC_ALWAYS_REQUIRED(glUniformMatrix4x2fv),
GLFUNC_ALWAYS_REQUIRED(glUniformMatrix4x3fv),
// gl_3_0
GLFUNC_REQUIRES(glBeginConditionalRender, "VERSION_3_0"),
GLFUNC_REQUIRES(glBindFragDataLocation, "VERSION_3_0"),
GLFUNC_REQUIRES(glClampColor, "VERSION_3_0"),
GLFUNC_REQUIRES(glEndConditionalRender, "VERSION_3_0"),
GLFUNC_REQUIRES(glGetBooleani_v, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI1i, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI1iv, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI1ui, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI1uiv, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI2i, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI2iv, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI2ui, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI2uiv, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI3i, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI3iv, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI3ui, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI3uiv, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI4bv, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI4sv, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI4ubv, "VERSION_3_0"),
GLFUNC_REQUIRES(glVertexAttribI4usv, "VERSION_3_0"),
GLFUNC_REQUIRES(glBeginTransformFeedback, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glClearBufferfi, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glClearBufferfv, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glClearBufferiv, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glClearBufferuiv, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glEndTransformFeedback, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetFragDataLocation, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetStringi, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetTransformFeedbackVarying, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetUniformuiv, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetVertexAttribIiv, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetVertexAttribIuiv, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glTransformFeedbackVaryings, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glUniform1ui, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glUniform1uiv, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glUniform2ui, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glUniform2uiv, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glUniform3ui, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glUniform3uiv, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glUniform4ui, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glUniform4uiv, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glVertexAttribI4i, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glVertexAttribI4iv, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glVertexAttribI4ui, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glVertexAttribI4uiv, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glVertexAttribIPointer, "VERSION_3_0 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glColorMaski, "VERSION_3_0 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glDisablei, "VERSION_3_0 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glEnablei, "VERSION_3_0 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glGetTexParameterIiv, "VERSION_3_0 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glGetTexParameterIuiv, "VERSION_3_0 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glIsEnabledi, "VERSION_3_0 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glTexParameterIiv, "VERSION_3_0 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glTexParameterIuiv, "VERSION_3_0 |VERSION_GLES_3_2"),
// gl_3_1
GLFUNC_REQUIRES(glPrimitiveRestartIndex, "VERSION_3_1"),
GLFUNC_REQUIRES(glDrawArraysInstanced, "VERSION_3_1 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glDrawElementsInstanced, "VERSION_3_1 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glTexBuffer, "VERSION_3_1 |VERSION_GLES_3_2"),
// gl_3_2
GLFUNC_REQUIRES(glGetBufferParameteri64v, "VERSION_3_2 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetInteger64i_v, "VERSION_3_2 |VERSION_GLES_3"),
GLFUNC_REQUIRES(glFramebufferTexture, "VERSION_3_2 |VERSION_GLES_3_2"),
// gl_4_2
GLFUNC_REQUIRES(glDrawArraysInstancedBaseInstance, "VERSION_4_2"),
GLFUNC_REQUIRES(glDrawElementsInstancedBaseInstance, "VERSION_4_2"),
GLFUNC_REQUIRES(glDrawElementsInstancedBaseVertexBaseInstance, "VERSION_4_2"),
GLFUNC_REQUIRES(glGetInternalformativ, "VERSION_4_2"),
GLFUNC_REQUIRES(glGetActiveAtomicCounterBufferiv, "VERSION_4_2"),
GLFUNC_REQUIRES(glBindImageTexture, "VERSION_4_2"),
GLFUNC_REQUIRES(glMemoryBarrier, "VERSION_4_2"),
GLFUNC_REQUIRES(glTexStorage1D, "VERSION_4_2"),
GLFUNC_REQUIRES(glTexStorage2D, "VERSION_4_2"),
GLFUNC_REQUIRES(glTexStorage3D, "VERSION_4_2"),
GLFUNC_REQUIRES(glDrawTransformFeedbackInstanced, "VERSION_4_2"),
GLFUNC_REQUIRES(glDrawTransformFeedbackStreamInstanced, "VERSION_4_2"),
// gl_4_3
GLFUNC_REQUIRES(glClearBufferData, "VERSION_4_3"),
GLFUNC_REQUIRES(glClearBufferSubData, "VERSION_4_3"),
GLFUNC_REQUIRES(glDispatchCompute, "VERSION_4_3"),
GLFUNC_REQUIRES(glDispatchComputeIndirect, "VERSION_4_3"),
GLFUNC_REQUIRES(glCopyImageSubData, "VERSION_4_3"),
GLFUNC_REQUIRES(glFramebufferParameteri, "VERSION_4_3"),
GLFUNC_REQUIRES(glGetFramebufferParameteriv, "VERSION_4_3"),
GLFUNC_REQUIRES(glGetInternalformati64v, "VERSION_4_3"),
GLFUNC_REQUIRES(glInvalidateTexSubImage, "VERSION_4_3"),
GLFUNC_REQUIRES(glInvalidateTexImage, "VERSION_4_3"),
GLFUNC_REQUIRES(glInvalidateBufferSubData, "VERSION_4_3"),
GLFUNC_REQUIRES(glInvalidateBufferData, "VERSION_4_3"),
GLFUNC_REQUIRES(glInvalidateFramebuffer, "VERSION_4_3"),
GLFUNC_REQUIRES(glInvalidateSubFramebuffer, "VERSION_4_3"),
GLFUNC_REQUIRES(glMultiDrawArraysIndirect, "VERSION_4_3"),
GLFUNC_REQUIRES(glMultiDrawElementsIndirect, "VERSION_4_3"),
GLFUNC_REQUIRES(glGetProgramInterfaceiv, "VERSION_4_3"),
GLFUNC_REQUIRES(glGetProgramResourceIndex, "VERSION_4_3"),
GLFUNC_REQUIRES(glGetProgramResourceName, "VERSION_4_3"),
GLFUNC_REQUIRES(glGetProgramResourceiv, "VERSION_4_3"),
GLFUNC_REQUIRES(glGetProgramResourceLocation, "VERSION_4_3"),
GLFUNC_REQUIRES(glGetProgramResourceLocationIndex, "VERSION_4_3"),
GLFUNC_REQUIRES(glShaderStorageBlockBinding, "VERSION_4_3"),
GLFUNC_REQUIRES(glTexBufferRange, "VERSION_4_3"),
GLFUNC_REQUIRES(glTexStorage2DMultisample, "VERSION_4_3"),
GLFUNC_REQUIRES(glTexStorage3DMultisample, "VERSION_4_3"),
GLFUNC_REQUIRES(glTextureView, "VERSION_4_3"),
GLFUNC_REQUIRES(glBindVertexBuffer, "VERSION_4_3"),
GLFUNC_REQUIRES(glVertexAttribFormat, "VERSION_4_3"),
GLFUNC_REQUIRES(glVertexAttribIFormat, "VERSION_4_3"),
GLFUNC_REQUIRES(glVertexAttribLFormat, "VERSION_4_3"),
GLFUNC_REQUIRES(glVertexAttribBinding, "VERSION_4_3"),
GLFUNC_REQUIRES(glVertexBindingDivisor, "VERSION_4_3"),
GLFUNC_REQUIRES(glDebugMessageControl, "VERSION_4_3"),
GLFUNC_REQUIRES(glDebugMessageInsert, "VERSION_4_3"),
GLFUNC_REQUIRES(glDebugMessageCallback, "VERSION_4_3"),
GLFUNC_REQUIRES(glGetDebugMessageLog, "VERSION_4_3"),
GLFUNC_REQUIRES(glPushDebugGroup, "VERSION_4_3"),
GLFUNC_REQUIRES(glPopDebugGroup, "VERSION_4_3"),
GLFUNC_REQUIRES(glObjectLabel, "VERSION_4_3"),
GLFUNC_REQUIRES(glGetObjectLabel, "VERSION_4_3"),
GLFUNC_REQUIRES(glObjectPtrLabel, "VERSION_4_3"),
GLFUNC_REQUIRES(glGetObjectPtrLabel, "VERSION_4_3"),
// gl_4_4
GLFUNC_REQUIRES(glBufferStorage, "VERSION_4_4"),
GLFUNC_REQUIRES(glClearTexImage, "VERSION_4_4"),
GLFUNC_REQUIRES(glClearTexSubImage, "VERSION_4_4"),
GLFUNC_REQUIRES(glBindBuffersBase, "VERSION_4_4"),
GLFUNC_REQUIRES(glBindBuffersRange, "VERSION_4_4"),
GLFUNC_REQUIRES(glBindTextures, "VERSION_4_4"),
GLFUNC_REQUIRES(glBindSamplers, "VERSION_4_4"),
GLFUNC_REQUIRES(glBindImageTextures, "VERSION_4_4"),
GLFUNC_REQUIRES(glBindVertexBuffers, "VERSION_4_4"),
// gl_4_5
GLFUNC_REQUIRES(glClipControl, "VERSION_4_5"),
GLFUNC_REQUIRES(glCreateTransformFeedbacks, "VERSION_4_5"),
GLFUNC_REQUIRES(glTransformFeedbackBufferBase, "VERSION_4_5"),
GLFUNC_REQUIRES(glTransformFeedbackBufferRange, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetTransformFeedbackiv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetTransformFeedbacki_v, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetTransformFeedbacki64_v, "VERSION_4_5"),
GLFUNC_REQUIRES(glCreateBuffers, "VERSION_4_5"),
GLFUNC_REQUIRES(glNamedBufferStorage, "VERSION_4_5"),
GLFUNC_REQUIRES(glNamedBufferData, "VERSION_4_5"),
GLFUNC_REQUIRES(glNamedBufferSubData, "VERSION_4_5"),
GLFUNC_REQUIRES(glCopyNamedBufferSubData, "VERSION_4_5"),
GLFUNC_REQUIRES(glClearNamedBufferData, "VERSION_4_5"),
GLFUNC_REQUIRES(glClearNamedBufferSubData, "VERSION_4_5"),
GLFUNC_REQUIRES(glMapNamedBuffer, "VERSION_4_5"),
GLFUNC_REQUIRES(glMapNamedBufferRange, "VERSION_4_5"),
GLFUNC_REQUIRES(glUnmapNamedBuffer, "VERSION_4_5"),
GLFUNC_REQUIRES(glFlushMappedNamedBufferRange, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetNamedBufferParameteriv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetNamedBufferParameteri64v, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetNamedBufferPointerv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetNamedBufferSubData, "VERSION_4_5"),
GLFUNC_REQUIRES(glCreateFramebuffers, "VERSION_4_5"),
GLFUNC_REQUIRES(glNamedFramebufferRenderbuffer, "VERSION_4_5"),
GLFUNC_REQUIRES(glNamedFramebufferParameteri, "VERSION_4_5"),
GLFUNC_REQUIRES(glNamedFramebufferTexture, "VERSION_4_5"),
GLFUNC_REQUIRES(glNamedFramebufferTextureLayer, "VERSION_4_5"),
GLFUNC_REQUIRES(glNamedFramebufferDrawBuffer, "VERSION_4_5"),
GLFUNC_REQUIRES(glNamedFramebufferDrawBuffers, "VERSION_4_5"),
GLFUNC_REQUIRES(glNamedFramebufferReadBuffer, "VERSION_4_5"),
GLFUNC_REQUIRES(glInvalidateNamedFramebufferData, "VERSION_4_5"),
GLFUNC_REQUIRES(glInvalidateNamedFramebufferSubData, "VERSION_4_5"),
GLFUNC_REQUIRES(glClearNamedFramebufferiv, "VERSION_4_5"),
GLFUNC_REQUIRES(glClearNamedFramebufferuiv, "VERSION_4_5"),
GLFUNC_REQUIRES(glClearNamedFramebufferfv, "VERSION_4_5"),
GLFUNC_REQUIRES(glClearNamedFramebufferfi, "VERSION_4_5"),
GLFUNC_REQUIRES(glBlitNamedFramebuffer, "VERSION_4_5"),
GLFUNC_REQUIRES(glCheckNamedFramebufferStatus, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetNamedFramebufferParameteriv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetNamedFramebufferAttachmentParameteriv, "VERSION_4_5"),
GLFUNC_REQUIRES(glCreateRenderbuffers, "VERSION_4_5"),
GLFUNC_REQUIRES(glNamedRenderbufferStorage, "VERSION_4_5"),
GLFUNC_REQUIRES(glNamedRenderbufferStorageMultisample, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetNamedRenderbufferParameteriv, "VERSION_4_5"),
GLFUNC_REQUIRES(glCreateTextures, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureBuffer, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureBufferRange, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureStorage1D, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureStorage2D, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureStorage3D, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureStorage2DMultisample, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureStorage3DMultisample, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureSubImage1D, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureSubImage2D, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureSubImage3D, "VERSION_4_5"),
GLFUNC_REQUIRES(glCompressedTextureSubImage1D, "VERSION_4_5"),
GLFUNC_REQUIRES(glCompressedTextureSubImage2D, "VERSION_4_5"),
GLFUNC_REQUIRES(glCompressedTextureSubImage3D, "VERSION_4_5"),
GLFUNC_REQUIRES(glCopyTextureSubImage1D, "VERSION_4_5"),
GLFUNC_REQUIRES(glCopyTextureSubImage2D, "VERSION_4_5"),
GLFUNC_REQUIRES(glCopyTextureSubImage3D, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureParameterf, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureParameterfv, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureParameteri, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureParameterIiv, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureParameterIuiv, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureParameteriv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGenerateTextureMipmap, "VERSION_4_5"),
GLFUNC_REQUIRES(glBindTextureUnit, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetTextureImage, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetCompressedTextureImage, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetTextureLevelParameterfv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetTextureLevelParameteriv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetTextureParameterfv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetTextureParameterIiv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetTextureParameterIuiv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetTextureParameteriv, "VERSION_4_5"),
GLFUNC_REQUIRES(glCreateVertexArrays, "VERSION_4_5"),
GLFUNC_REQUIRES(glDisableVertexArrayAttrib, "VERSION_4_5"),
GLFUNC_REQUIRES(glEnableVertexArrayAttrib, "VERSION_4_5"),
GLFUNC_REQUIRES(glVertexArrayElementBuffer, "VERSION_4_5"),
GLFUNC_REQUIRES(glVertexArrayVertexBuffer, "VERSION_4_5"),
GLFUNC_REQUIRES(glVertexArrayVertexBuffers, "VERSION_4_5"),
GLFUNC_REQUIRES(glVertexArrayAttribBinding, "VERSION_4_5"),
GLFUNC_REQUIRES(glVertexArrayAttribFormat, "VERSION_4_5"),
GLFUNC_REQUIRES(glVertexArrayAttribIFormat, "VERSION_4_5"),
GLFUNC_REQUIRES(glVertexArrayAttribLFormat, "VERSION_4_5"),
GLFUNC_REQUIRES(glVertexArrayBindingDivisor, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetVertexArrayiv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetVertexArrayIndexediv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetVertexArrayIndexed64iv, "VERSION_4_5"),
GLFUNC_REQUIRES(glCreateSamplers, "VERSION_4_5"),
GLFUNC_REQUIRES(glCreateProgramPipelines, "VERSION_4_5"),
GLFUNC_REQUIRES(glCreateQueries, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetQueryBufferObjecti64v, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetQueryBufferObjectiv, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetQueryBufferObjectui64v, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetQueryBufferObjectuiv, "VERSION_4_5"),
GLFUNC_REQUIRES(glMemoryBarrierByRegion, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetTextureSubImage, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetCompressedTextureSubImage, "VERSION_4_5"),
GLFUNC_REQUIRES(glGetGraphicsResetStatus, "VERSION_4_5"),
GLFUNC_REQUIRES(glReadnPixels, "VERSION_4_5"),
GLFUNC_REQUIRES(glTextureBarrier, "VERSION_4_5"),
// AMD's video driver is trash and doesn't expose these function pointers
// Remove them for now until they learn how to implement the spec properly.
// GLFUNC_REQUIRES(glGetnCompressedTexImage, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnTexImage, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnUniformdv, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnUniformfv, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnUniformiv, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnUniformuiv, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnMapdv, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnMapfv, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnMapiv, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnPixelMapfv, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnPixelMapuiv, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnPixelMapusv, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnPolygonStipple, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnColorTable, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnConvolutionFilter, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnSeparableFilter, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnHistogram, "VERSION_4_5"),
// GLFUNC_REQUIRES(glGetnMinmax, "VERSION_4_5"),
// ARB_uniform_buffer_object
GLFUNC_REQUIRES(glGetActiveUniformName, "GL_ARB_uniform_buffer_object"),
GLFUNC_REQUIRES(glBindBufferBase, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glBindBufferRange, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetActiveUniformBlockName, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetActiveUniformBlockiv, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetActiveUniformsiv, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetIntegeri_v, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetUniformBlockIndex, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetUniformIndices, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glUniformBlockBinding, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"),
// ARB_sampler_objects
GLFUNC_REQUIRES(glBindSampler, "GL_ARB_sampler_objects |VERSION_GLES_3"),
GLFUNC_REQUIRES(glDeleteSamplers, "GL_ARB_sampler_objects |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGenSamplers, "GL_ARB_sampler_objects |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetSamplerParameterfv, "GL_ARB_sampler_objects |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetSamplerParameteriv, "GL_ARB_sampler_objects |VERSION_GLES_3"),
GLFUNC_REQUIRES(glIsSampler, "GL_ARB_sampler_objects |VERSION_GLES_3"),
GLFUNC_REQUIRES(glSamplerParameterf, "GL_ARB_sampler_objects |VERSION_GLES_3"),
GLFUNC_REQUIRES(glSamplerParameterfv, "GL_ARB_sampler_objects |VERSION_GLES_3"),
GLFUNC_REQUIRES(glSamplerParameteri, "GL_ARB_sampler_objects |VERSION_GLES_3"),
GLFUNC_REQUIRES(glSamplerParameteriv, "GL_ARB_sampler_objects |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetSamplerParameterIiv, "GL_ARB_sampler_objects |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glGetSamplerParameterIuiv, "GL_ARB_sampler_objects |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glSamplerParameterIiv, "GL_ARB_sampler_objects |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glSamplerParameterIuiv, "GL_ARB_sampler_objects |VERSION_GLES_3_2"),
// ARB_map_buffer_range
GLFUNC_REQUIRES(glFlushMappedBufferRange, "GL_ARB_map_buffer_range |VERSION_GLES_3"),
GLFUNC_REQUIRES(glMapBufferRange, "GL_ARB_map_buffer_range |VERSION_GLES_3"),
// ARB_vertex_array_object
GLFUNC_REQUIRES(glBindVertexArray, "GL_ARB_vertex_array_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glDeleteVertexArrays, "GL_ARB_vertex_array_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGenVertexArrays, "GL_ARB_vertex_array_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glIsVertexArray, "GL_ARB_vertex_array_object |VERSION_GLES_3"),
// APPLE_vertex_array_object
GLFUNC_SUFFIX(glBindVertexArray, APPLE, "GL_APPLE_vertex_array_object !GL_ARB_vertex_array_object"),
GLFUNC_SUFFIX(glDeleteVertexArrays, APPLE, "GL_APPLE_vertex_array_object !GL_ARB_vertex_array_object"),
GLFUNC_SUFFIX(glGenVertexArrays, APPLE, "GL_APPLE_vertex_array_object !GL_ARB_vertex_array_object"),
GLFUNC_SUFFIX(glIsVertexArray, APPLE, "GL_APPLE_vertex_array_object !GL_ARB_vertex_array_object"),
// ARB_framebuffer_object
GLFUNC_REQUIRES(glFramebufferTexture1D, "GL_ARB_framebuffer_object"),
GLFUNC_REQUIRES(glFramebufferTexture3D, "GL_ARB_framebuffer_object"),
GLFUNC_REQUIRES(glBindFramebuffer, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glBindRenderbuffer, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glBlitFramebuffer, "GL_ARB_framebuffer_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glCheckFramebufferStatus, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glDeleteFramebuffers, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glDeleteRenderbuffers, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glFramebufferRenderbuffer, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glFramebufferTexture2D, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glFramebufferTextureLayer, "GL_ARB_framebuffer_object |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGenFramebuffers, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glGenRenderbuffers, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glGenerateMipmap, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glGetFramebufferAttachmentParameteriv, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glGetRenderbufferParameteriv, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glIsFramebuffer, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glIsRenderbuffer, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glRenderbufferStorage, "GL_ARB_framebuffer_object |VERSION_GLES_2"),
GLFUNC_REQUIRES(glRenderbufferStorageMultisample, "GL_ARB_framebuffer_object |VERSION_GLES_3"),
// ARB_get_program_binary
GLFUNC_REQUIRES(glGetProgramBinary, "GL_ARB_get_program_binary |VERSION_GLES_3"),
GLFUNC_REQUIRES(glProgramBinary, "GL_ARB_get_program_binary |VERSION_GLES_3"),
GLFUNC_REQUIRES(glProgramParameteri, "GL_ARB_get_program_binary |VERSION_GLES_3"),
// ARB_sync
GLFUNC_REQUIRES(glClientWaitSync, "GL_ARB_sync |VERSION_GLES_3"),
GLFUNC_REQUIRES(glDeleteSync, "GL_ARB_sync |VERSION_GLES_3"),
GLFUNC_REQUIRES(glFenceSync, "GL_ARB_sync |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetInteger64v, "GL_ARB_sync |VERSION_GLES_3"),
GLFUNC_REQUIRES(glGetSynciv, "GL_ARB_sync |VERSION_GLES_3"),
GLFUNC_REQUIRES(glIsSync, "GL_ARB_sync |VERSION_GLES_3"),
GLFUNC_REQUIRES(glWaitSync, "GL_ARB_sync |VERSION_GLES_3"),
// ARB_texture_multisample
GLFUNC_REQUIRES(glTexImage2DMultisample, "GL_ARB_texture_multisample"),
GLFUNC_REQUIRES(glTexImage3DMultisample, "GL_ARB_texture_multisample"),
GLFUNC_REQUIRES(glGetMultisamplefv, "GL_ARB_texture_multisample"),
GLFUNC_REQUIRES(glSampleMaski, "GL_ARB_texture_multisample"),
// ARB_texture_storage_multisample
GLFUNC_REQUIRES(glTexStorage2DMultisample, "GL_ARB_texture_storage_multisample !VERSION_4_3 |VERSION_GLES_3_1"),
GLFUNC_REQUIRES(glTexStorage3DMultisample, "GL_ARB_texture_storage_multisample !VERSION_4_3 |VERSION_GLES_3_2"),
GLFUNC_SUFFIX(glTexStorage3DMultisample, OES, "GL_OES_texture_storage_multisample_2d_array !VERSION_GLES_3_2"),
// ARB_ES2_compatibility
GLFUNC_REQUIRES(glClearDepthf, "GL_ARB_ES2_compatibility |VERSION_GLES_2"),
GLFUNC_REQUIRES(glDepthRangef, "GL_ARB_ES2_compatibility |VERSION_GLES_2"),
GLFUNC_REQUIRES(glGetShaderPrecisionFormat, "GL_ARB_ES2_compatibility |VERSION_GLES_2"),
GLFUNC_REQUIRES(glReleaseShaderCompiler, "GL_ARB_ES2_compatibility |VERSION_GLES_2"),
GLFUNC_REQUIRES(glShaderBinary, "GL_ARB_ES2_compatibility |VERSION_GLES_2"),
// NV_primitive_restart
GLFUNC_REQUIRES(glPrimitiveRestartIndexNV, "GL_NV_primitive_restart"),
GLFUNC_REQUIRES(glPrimitiveRestartNV, "GL_NV_primitive_restart"),
// ARB_blend_func_extended
GLFUNC_REQUIRES(glBindFragDataLocationIndexed, "GL_ARB_blend_func_extended"),
GLFUNC_REQUIRES(glGetFragDataIndex, "GL_ARB_blend_func_extended"),
// ARB_viewport_array
GLFUNC_REQUIRES(glDepthRangeArrayv, "GL_ARB_viewport_array"),
GLFUNC_REQUIRES(glDepthRangeIndexed, "GL_ARB_viewport_array"),
GLFUNC_REQUIRES(glGetDoublei_v, "GL_ARB_viewport_array"),
GLFUNC_REQUIRES(glGetFloati_v, "GL_ARB_viewport_array"),
GLFUNC_REQUIRES(glScissorArrayv, "GL_ARB_viewport_array"),
GLFUNC_REQUIRES(glScissorIndexed, "GL_ARB_viewport_array"),
GLFUNC_REQUIRES(glScissorIndexedv, "GL_ARB_viewport_array"),
GLFUNC_REQUIRES(glViewportArrayv, "GL_ARB_viewport_array"),
GLFUNC_REQUIRES(glViewportIndexedf, "GL_ARB_viewport_array"),
GLFUNC_REQUIRES(glViewportIndexedfv, "GL_ARB_viewport_array"),
// ARB_draw_elements_base_vertex
GLFUNC_REQUIRES(glDrawElementsBaseVertex, "GL_ARB_draw_elements_base_vertex |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glDrawElementsInstancedBaseVertex, "GL_ARB_draw_elements_base_vertex |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glDrawRangeElementsBaseVertex, "GL_ARB_draw_elements_base_vertex |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glMultiDrawElementsBaseVertex, "GL_ARB_draw_elements_base_vertex"),
// OES_draw_elements_base_vertex
GLFUNC_SUFFIX(glDrawElementsBaseVertex, OES, "GL_OES_draw_elements_base_vertex !VERSION_GLES_3_2"),
GLFUNC_SUFFIX(glDrawElementsInstancedBaseVertex, OES, "GL_OES_draw_elements_base_vertex VERSION_GLES_3 !VERSION_GLES_3_2"),
GLFUNC_SUFFIX(glDrawRangeElementsBaseVertex, OES, "GL_OES_draw_elements_base_vertex VERSION_GLES_3 !VERSION_GLES_3_2"),
GLFUNC_SUFFIX(glMultiDrawElementsBaseVertex, OES, "GL_OES_draw_elements_base_vertex GL_EXT_multi_draw_arrays"),
// EXT_draw_elements_base_vertex
GLFUNC_SUFFIX(glDrawElementsBaseVertex, EXT, "GL_EXT_draw_elements_base_vertex !GL_OES_draw_elements_base_vertex !VERSION_GLES_3_2"),
GLFUNC_SUFFIX(glDrawElementsInstancedBaseVertex, EXT, "GL_EXT_draw_elements_base_vertex VERSION_GLES_3 !GL_OES_draw_elements_base_vertex !VERSION_GLES_3_2"),
GLFUNC_SUFFIX(glDrawRangeElementsBaseVertex, EXT, "GL_EXT_draw_elements_base_vertex VERSION_GLES_3 !GL_OES_draw_elements_base_vertex !VERSION_GLES_3_2"),
GLFUNC_SUFFIX(glMultiDrawElementsBaseVertex, EXT, "GL_EXT_draw_elements_base_vertex GL_EXT_multi_draw_arrays !GL_OES_draw_elements_base_vertex !VERSION_GLES_3_2"),
// ARB_sample_shading
GLFUNC_SUFFIX(glMinSampleShading, ARB, "GL_ARB_sample_shading"),
// OES_sample_shading
GLFUNC_SUFFIX(glMinSampleShading, OES, "GL_OES_sample_shading !VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glMinSampleShading, "VERSION_GLES_3_2"),
// ARB_debug_output
GLFUNC_REQUIRES(glDebugMessageCallbackARB, "GL_ARB_debug_output"),
GLFUNC_REQUIRES(glDebugMessageControlARB, "GL_ARB_debug_output"),
GLFUNC_REQUIRES(glDebugMessageInsertARB, "GL_ARB_debug_output"),
GLFUNC_REQUIRES(glGetDebugMessageLogARB, "GL_ARB_debug_output"),
// KHR_debug
GLFUNC_SUFFIX(glDebugMessageCallback, KHR, "GL_KHR_debug VERSION_GLES_3"),
GLFUNC_SUFFIX(glDebugMessageControl, KHR, "GL_KHR_debug VERSION_GLES_3"),
GLFUNC_SUFFIX(glDebugMessageInsert, KHR, "GL_KHR_debug VERSION_GLES_3"),
GLFUNC_SUFFIX(glGetDebugMessageLog, KHR, "GL_KHR_debug VERSION_GLES_3"),
GLFUNC_SUFFIX(glGetObjectLabel, KHR, "GL_KHR_debug VERSION_GLES_3"),
GLFUNC_SUFFIX(glGetObjectPtrLabel, KHR, "GL_KHR_debug VERSION_GLES_3"),
GLFUNC_SUFFIX(glObjectLabel, KHR, "GL_KHR_debug VERSION_GLES_3"),
GLFUNC_SUFFIX(glObjectPtrLabel, KHR, "GL_KHR_debug VERSION_GLES_3"),
GLFUNC_SUFFIX(glPopDebugGroup, KHR, "GL_KHR_debug VERSION_GLES_3"),
GLFUNC_SUFFIX(glPushDebugGroup, KHR, "GL_KHR_debug VERSION_GLES_3"),
GLFUNC_REQUIRES(glDebugMessageCallback, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glDebugMessageControl, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glDebugMessageInsert, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glGetDebugMessageLog, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glGetObjectLabel, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glGetObjectPtrLabel, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glObjectLabel, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glObjectPtrLabel, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glPopDebugGroup, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"),
GLFUNC_REQUIRES(glPushDebugGroup, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"),
// ARB_buffer_storage
GLFUNC_REQUIRES(glBufferStorage, "GL_ARB_buffer_storage !VERSION_4_4"),
GLFUNC_SUFFIX(glNamedBufferStorage, EXT, "GL_ARB_buffer_storage GL_EXT_direct_state_access !VERSION_4_5"),
// EXT_buffer_storage
GLFUNC_SUFFIX(glBufferStorage, EXT, "GL_EXT_buffer_storage !GL_ARB_buffer_storage !VERSION_4_4"),
// EXT_geometry_shader
GLFUNC_SUFFIX(glFramebufferTexture, EXT, "GL_EXT_geometry_shader !VERSION_3_2"),
// NV_occlusion_query_samples
GLFUNC_REQUIRES(glGenOcclusionQueriesNV, "GL_NV_occlusion_query_samples"),
GLFUNC_REQUIRES(glDeleteOcclusionQueriesNV, "GL_NV_occlusion_query_samples"),
GLFUNC_REQUIRES(glIsOcclusionQueryNV, "GL_NV_occlusion_query_samples"),
GLFUNC_REQUIRES(glBeginOcclusionQueryNV, "GL_NV_occlusion_query_samples"),
GLFUNC_REQUIRES(glEndOcclusionQueryNV, "GL_NV_occlusion_query_samples"),
GLFUNC_REQUIRES(glGetOcclusionQueryivNV, "GL_NV_occlusion_query_samples"),
GLFUNC_REQUIRES(glGetOcclusionQueryuivNV, "GL_NV_occlusion_query_samples"),
// ARB_clip_control
GLFUNC_REQUIRES(glClipControl, "GL_ARB_clip_control !VERSION_4_5"),
// ARB_copy_image
GLFUNC_REQUIRES(glCopyImageSubData, "GL_ARB_copy_image !VERSION_4_3 |VERSION_GLES_3_2"),
// NV_copy_image
GLFUNC_SUFFIX(glCopyImageSubData, NV, "GL_NV_copy_image !GL_ARB_copy_image !VERSION_GLES_3_2"),
// OES_copy_image
GLFUNC_SUFFIX(glCopyImageSubData, OES, "GL_OES_copy_image !VERSION_GLES_3_2"),
// EXT_copy_image
GLFUNC_SUFFIX(glCopyImageSubData, EXT, "GL_EXT_copy_image !GL_OES_copy_image !VERSION_GLES_3_2"),
// EXT_texture_buffer
GLFUNC_SUFFIX(glTexBuffer, OES, "GL_OES_texture_buffer !VERSION_GLES_3_2"),
// EXT_texture_buffer
GLFUNC_SUFFIX(glTexBuffer, EXT, "GL_EXT_texture_buffer !GL_OES_texture_buffer !VERSION_GLES_3_2"),
// EXT_blend_func_extended
GLFUNC_SUFFIX(glBindFragDataLocationIndexed, EXT, "GL_EXT_blend_func_extended"),
GLFUNC_SUFFIX(glGetFragDataIndex, EXT, "GL_EXT_blend_func_extended"),
// ARB_shader_storage_buffer_object
GLFUNC_REQUIRES(glShaderStorageBlockBinding, "ARB_shader_storage_buffer_object !VERSION_4_3"),
};
namespace GLExtensions
{
// Private members and functions
static bool _isES;
static u32 _GLVersion;
static std::unordered_map<std::string, bool> m_extension_list;
// Private initialization functions
bool InitFunctionPointers();
// Initializes the extension list the old way
static void InitExtensionList21()
{
const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
std::string tmp(extensions);
std::istringstream buffer(tmp);
while (buffer >> tmp)
m_extension_list[tmp] = true;
}
static void InitExtensionList()
{
m_extension_list.clear();
if (_isES)
{
switch (_GLVersion)
{
default:
case 320:
m_extension_list["VERSION_GLES_3_2"] = true;
case 310:
m_extension_list["VERSION_GLES_3_1"] = true;
case 300:
m_extension_list["VERSION_GLES_3"] = true;
break;
}
// We always have ES 2.0
m_extension_list["VERSION_GLES_2"] = true;
}
else
{
// Some OpenGL implementations chose to not expose core extensions as extensions
// Let's add them to the list manually depending on which version of OpenGL we have
// We need to be slightly careful here
// When an extension got merged in to core, the naming may have changed
// This has intentional fall through
switch (_GLVersion)
{
default:
case 450:
{
std::string gl450exts[] = {
"GL_ARB_ES3_1_compatibility",
"GL_ARB_clip_control",
"GL_ARB_conditional_render_inverted",
"GL_ARB_cull_distance",
"GL_ARB_derivative_control",
"GL_ARB_direct_state_access",
"GL_ARB_get_texture_sub_image",
"GL_ARB_robustness",
"GL_ARB_shader_texture_image_samples",
"GL_ARB_texture_barrier",
"VERSION_4_5",
};
for (auto it : gl450exts)
m_extension_list[it] = true;
}
case 440:
{
std::string gl440exts[] = {
"GL_ARB_buffer_storage",
"GL_ARB_clear_texture",
"GL_ARB_enhanced_layouts",
"GL_ARB_multi_bind",
"GL_ARB_query_buffer_object",
"GL_ARB_texture_mirror_clamp_to_edge",
"GL_ARB_texture_stencil8",
"GL_ARB_vertex_type_10f_11f_11f_rev",
"VERSION_4_4",
};
for (auto it : gl440exts)
m_extension_list[it] = true;
}
case 430:
{
std::string gl430exts[] = {
"GL_ARB_ES3_compatibility",
"GL_ARB_arrays_of_arrays",
"GL_ARB_clear_buffer_object",
"GL_ARB_compute_shader",
"GL_ARB_copy_image",
"GL_ARB_explicit_uniform_location",
"GL_ARB_fragment_layer_viewport",
"GL_ARB_framebuffer_no_attachments",
"GL_ARB_internalformat_query2",
"GL_ARB_invalidate_subdata",
"GL_ARB_multi_draw_indirect",
"GL_ARB_program_interface_query",
"GL_ARB_shader_image_size",
"GL_ARB_shader_storage_buffer_object",
"GL_ARB_stencil_texturing",
"GL_ARB_texture_buffer_range",
"GL_ARB_texture_query_levels",
"GL_ARB_texture_storage_multisample",
"GL_ARB_texture_view",
"GL_ARB_vertex_attrib_binding",
"VERSION_4_3",
};
for (auto it : gl430exts)
m_extension_list[it] = true;
}
case 420:
{
std::string gl420exts[] = {
"GL_ARB_base_instance",
"GL_ARB_compressed_texture_pixel_storage",
"GL_ARB_conservative_depth",
"GL_ARB_internalformat_query",
"GL_ARB_map_buffer_alignment",
"GL_ARB_shader_atomic_counters",
"GL_ARB_shader_image_load_store",
"GL_ARB_shading_language_420pack",
"GL_ARB_shading_language_packing",
"GL_ARB_texture_compression_BPTC",
"GL_ARB_texture_storage",
"GL_ARB_transform_feedback_instanced",
"VERSION_4_2",
};
for (auto it : gl420exts)
m_extension_list[it] = true;
}
case 410:
{
std::string gl410exts[] = {
"GL_ARB_ES2_compatibility",
"GL_ARB_get_program_binary",
"GL_ARB_separate_shader_objects",
"GL_ARB_shader_precision",
"GL_ARB_vertex_attrib_64_bit",
"GL_ARB_viewport_array",
"VERSION_4_1",
};
for (auto it : gl410exts)
m_extension_list[it] = true;
}
case 400:
{
std::string gl400exts[] = {
"GL_ARB_draw_indirect",
"GL_ARB_gpu_shader5",
"GL_ARB_gpu_shader_fp64",
"GL_ARB_sample_shading",
"GL_ARB_shader_subroutine",
"GL_ARB_tessellation_shader",
"GL_ARB_texture_buffer_object_rgb32",
"GL_ARB_texture_cube_map_array",
"GL_ARB_texture_gather",
"GL_ARB_texture_query_lod",
"GL_ARB_transform_feedback2",
"GL_ARB_transform_feedback3",
"VERSION_4_0",
};
for (auto it : gl400exts)
m_extension_list[it] = true;
}
case 330:
{
std::string gl330exts[] = {
"GL_ARB_shader_bit_encoding",
"GL_ARB_blend_func_extended",
"GL_ARB_explicit_attrib_location",
"GL_ARB_occlusion_query2",
"GL_ARB_sampler_objects",
"GL_ARB_texture_swizzle",
"GL_ARB_timer_query",
"GL_ARB_instanced_arrays",
"GL_ARB_texture_rgb10_a2ui",
"GL_ARB_vertex_type_2_10_10_10_rev",
"VERSION_3_3",
};
for (auto it : gl330exts)
m_extension_list[it] = true;
}
case 320:
{
std::string gl320exts[] = {
"GL_ARB_geometry_shader4",
"GL_ARB_sync",
"GL_ARB_vertex_array_bgra",
"GL_ARB_draw_elements_base_vertex",
"GL_ARB_seamless_cube_map",
"GL_ARB_texture_multisample",
"GL_ARB_fragment_coord_conventions",
"GL_ARB_provoking_vertex",
"GL_ARB_depth_clamp",
"VERSION_3_2",
};
for (auto it : gl320exts)
m_extension_list[it] = true;
}
case 310:
{
// Can't add NV_primitive_restart since function name changed
std::string gl310exts[] = {
"GL_ARB_draw_instanced",
"GL_ARB_copy_buffer",
"GL_ARB_texture_buffer_object",
"GL_ARB_texture_rectangle",
"GL_ARB_uniform_buffer_object",
//"GL_NV_primitive_restart",
"VERSION_3_1",
};
for (auto it : gl310exts)
m_extension_list[it] = true;
}
case 300:
{
// Quite a lot of these had their names changed when merged in to core
// Disable the ones that have
std::string gl300exts[] = {
"GL_ARB_map_buffer_range",
//"GL_EXT_gpu_shader4",
//"GL_APPLE_flush_buffer_range",
"GL_ARB_color_buffer_float",
//"GL_NV_depth_buffer_float",
"GL_ARB_texture_float",
//"GL_EXT_packed_float",
//"GL_EXT_texture_shared_exponent",
"GL_ARB_half_float_pixel",
//"GL_NV_half_float",
"GL_ARB_framebuffer_object",
//"GL_EXT_framebuffer_sRGB",
"GL_ARB_texture_float",
//"GL_EXT_texture_integer",
//"GL_EXT_draw_buffers2",
//"GL_EXT_texture_integer",
//"GL_EXT_texture_array",
//"GL_EXT_texture_compression_rgtc",
//"GL_EXT_transform_feedback",
"GL_ARB_vertex_array_object",
//"GL_NV_conditional_render",
"VERSION_3_0",
};
for (auto it : gl300exts)
m_extension_list[it] = true;
}
case 210:
case 200:
case 150:
case 140:
case 130:
case 121:
case 120:
case 110:
case 100:
break;
}
// So we can easily determine if we are running dekstop GL
m_extension_list["VERSION_GL"] = true;
}
if (_GLVersion < 300)
{
InitExtensionList21();
return;
}
GLint NumExtension = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &NumExtension);
for (GLint i = 0; i < NumExtension; ++i)
m_extension_list[std::string((const char*)glGetStringi(GL_EXTENSIONS, i))] = true;
}
static void InitVersion()
{
GLint major, minor;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
if (glGetError() == GL_NO_ERROR)
_GLVersion = major * 100 + minor * 10;
else
_GLVersion = 210;
}
static void* GetFuncAddress(const std::string& name, void **func)
{
*func = GLInterface->GetFuncAddress(name);
if (*func == nullptr)
{
#if defined(__linux__) || defined(__APPLE__)
// Give it a second try with dlsym
*func = dlsym(RTLD_NEXT, name.c_str());
#endif
if (*func == nullptr)
ERROR_LOG(VIDEO, "Couldn't load function %s", name.c_str());
}
return *func;
}
// Public members
u32 Version() { return _GLVersion; }
bool Supports(const std::string& name)
{
return m_extension_list[name];
}
bool Init()
{
_isES = GLInterface->GetMode() != GLInterfaceMode::MODE_OPENGL;
// Grab a few functions for initial checking
// We need them to grab the extension list
// Also to check if there is an error grabbing the version
if (GetFuncAddress("glGetIntegerv", (void**)&glGetIntegerv) == nullptr)
return false;
if (GetFuncAddress("glGetString", (void**)&glGetString) == nullptr)
return false;
if (GetFuncAddress("glGetError", (void**)&glGetError) == nullptr)
return false;
InitVersion();
// We need to use glGetStringi to get the extension list
// if we are using GLES3 or a GL version greater than 2.1
if (_GLVersion > 210 && GetFuncAddress("glGetStringi", (void**)&glGetStringi) == nullptr)
return false;
InitExtensionList();
return InitFunctionPointers();
}
// Private initialization functions
static bool HasFeatures(const std::string& extensions)
{
bool result = true;
std::string tmp;
std::istringstream buffer(extensions);
while (buffer >> tmp)
{
if (tmp[0] == '!')
result &= !m_extension_list[tmp.erase(0, 1)];
else if (tmp[0] == '|')
result |= m_extension_list[tmp.erase(0, 1)];
else
result &= m_extension_list[tmp];
}
return result;
}
bool InitFunctionPointers()
{
bool result = true;
for (const auto &it : gl_function_array)
if (HasFeatures(it.requirements))
result &= !!GetFuncAddress(it.function_name, it.function_ptr);
return result;
}
}
| mmastrac/dolphin | Source/Core/Common/GL/GLExtensions/GLExtensions.cpp | C++ | gpl-2.0 | 108,368 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
/*
* This code is based on Labyrinth of Time code with assistance of
*
* Copyright (c) 1993 Terra Nova Development
* Copyright (c) 2004 The Wyrmkeep Entertainment Co.
*
*/
#include "lab/lab.h"
#include "lab/anim.h"
#include "lab/dispman.h"
#include "lab/eventman.h"
#include "lab/intro.h"
#include "lab/music.h"
#include "lab/resource.h"
#include "lab/utils.h"
namespace Lab {
Intro::Intro(LabEngine *vm) : _vm(vm) {
_quitIntro = false;
_introDoBlack = false;
_font = _vm->_resource->getFont("F:Map.fon");
}
Intro::~Intro() {
_vm->_graphics->freeFont(&_font);
}
void Intro::introEatMessages() {
while (1) {
IntuiMessage *msg = _vm->_event->getMsg();
if (_vm->shouldQuit()) {
_quitIntro = true;
return;
}
if (!msg)
return;
if ((msg->_msgClass == kMessageRightClick)
|| ((msg->_msgClass == kMessageRawKey) && (msg->_code == Common::KEYCODE_ESCAPE)))
_quitIntro = true;
}
}
void Intro::doPictText(const Common::String filename, bool isScreen) {
Common::String path = Common::String("Lab:rooms/Intro/") + filename;
uint timeDelay = (isScreen) ? 35 : 7;
_vm->updateEvents();
if (_quitIntro)
return;
uint32 lastMillis = 0;
bool drawNextText = true;
bool doneFl = false;
bool begin = true;
Common::File *textFile = _vm->_resource->openDataFile(path);
char *textBuffer = new char[textFile->size()];
textFile->read(textBuffer, textFile->size());
delete textFile;
const char *curText = textBuffer;
while (1) {
if (drawNextText) {
if (begin)
begin = false;
else if (isScreen)
_vm->_graphics->fade(false);
if (isScreen) {
_vm->_graphics->rectFillScaled(10, 10, 310, 190, 7);
curText += _vm->_graphics->flowText(_font, _vm->_isHiRes ? 0 : -1, 5, 7, false, false, true, true, _vm->_utils->vgaRectScale(14, 11, 306, 189), curText);
_vm->_graphics->fade(true);
} else
curText += _vm->_graphics->longDrawMessage(Common::String(curText), false);
doneFl = (*curText == 0);
drawNextText = false;
introEatMessages();
if (_quitIntro) {
if (isScreen)
_vm->_graphics->fade(false);
delete[] textBuffer;
return;
}
lastMillis = _vm->_system->getMillis();
}
IntuiMessage *msg = _vm->_event->getMsg();
if (_vm->shouldQuit()) {
_quitIntro = true;
return;
}
if (!msg) {
_vm->updateEvents();
_vm->_anim->diffNextFrame();
uint32 elapsedSeconds = (_vm->_system->getMillis() - lastMillis) / 1000;
if (elapsedSeconds > timeDelay) {
if (doneFl) {
if (isScreen)
_vm->_graphics->fade(false);
delete[] textBuffer;
return;
} else {
drawNextText = true;
}
}
_vm->waitTOF();
} else {
uint32 msgClass = msg->_msgClass;
uint16 code = msg->_code;
if ((msgClass == kMessageRightClick) ||
((msgClass == kMessageRawKey) && (code == Common::KEYCODE_ESCAPE))) {
_quitIntro = true;
if (isScreen)
_vm->_graphics->fade(false);
delete[] textBuffer;
return;
} else if ((msgClass == kMessageLeftClick) || (msgClass == kMessageRightClick)) {
if (msgClass == kMessageLeftClick) {
if (doneFl) {
if (isScreen)
_vm->_graphics->fade(false);
delete[] textBuffer;
return;
} else
drawNextText = true;
}
introEatMessages();
if (_quitIntro) {
if (isScreen)
_vm->_graphics->fade(false);
delete[] textBuffer;
return;
}
}
if (doneFl) {
if (isScreen)
_vm->_graphics->fade(false);
delete[] textBuffer;
return;
} else
drawNextText = true;
}
} // while(1)
}
void Intro::musicDelay() {
_vm->updateEvents();
if (_quitIntro)
return;
for (int i = 0; i < 20; i++) {
_vm->updateEvents();
_vm->waitTOF();
_vm->waitTOF();
_vm->waitTOF();
}
}
void Intro::nReadPict(const Common::String filename, bool playOnce) {
Common::String finalFileName = Common::String("P:Intro/") + filename;
_vm->updateEvents();
introEatMessages();
if (_quitIntro)
return;
_vm->_anim->_doBlack = _introDoBlack;
_vm->_anim->stopDiffEnd();
_vm->_graphics->readPict(finalFileName, playOnce);
}
void Intro::play() {
uint16 palette[16] = {
0x0000, 0x0855, 0x0FF9, 0x0EE7,
0x0ED5, 0x0DB4, 0x0CA2, 0x0C91,
0x0B80, 0x0B80, 0x0B91, 0x0CA2,
0x0CB3, 0x0DC4, 0x0DD6, 0x0EE7
};
_vm->_anim->_doBlack = true;
if (_vm->getPlatform() == Common::kPlatformDOS) {
nReadPict("EA0");
nReadPict("EA1");
nReadPict("EA2");
nReadPict("EA3");
} else if (_vm->getPlatform() == Common::kPlatformWindows) {
nReadPict("WYRMKEEP");
// Wait 4 seconds (400 x 10ms)
for (int i = 0; i < 400; i++) {
introEatMessages();
if (_quitIntro)
break;
_vm->_system->delayMillis(10);
}
}
_vm->_graphics->blackAllScreen();
if (_vm->getPlatform() != Common::kPlatformAmiga)
_vm->_music->changeMusic("Music:BackGrou", false, false);
else
_vm->_music->changeMusic("Music:BackGround", false, false);
_vm->_anim->_noPalChange = true;
if (_vm->getPlatform() == Common::kPlatformDOS)
nReadPict("TNDcycle.pic");
else
nReadPict("TNDcycle2.pic");
_vm->_anim->_noPalChange = false;
_vm->_graphics->_fadePalette = palette;
for (int i = 0; i < 16; i++) {
palette[i] = ((_vm->_anim->_diffPalette[i * 3] >> 2) << 8) +
((_vm->_anim->_diffPalette[i * 3 + 1] >> 2) << 4) +
(_vm->_anim->_diffPalette[i * 3 + 2] >> 2);
}
_vm->updateEvents();
if (!_quitIntro)
_vm->_graphics->fade(true);
for (int times = 0; times < 150; times++) {
introEatMessages();
if (_quitIntro)
break;
_vm->updateEvents();
uint16 temp = palette[2];
for (int i = 2; i < 15; i++)
palette[i] = palette[i + 1];
palette[15] = temp;
_vm->_graphics->setAmigaPal(palette);
_vm->waitTOF();
}
if (!_quitIntro) {
_vm->_graphics->fade(false);
_vm->_graphics->blackAllScreen();
_vm->updateEvents();
}
nReadPict("Title.A");
nReadPict("AB");
musicDelay();
nReadPict("BA");
nReadPict("AC");
musicDelay();
if (_vm->getPlatform() == Common::kPlatformWindows)
musicDelay(); // more credits on this page now
nReadPict("CA");
nReadPict("AD");
musicDelay();
if (_vm->getPlatform() == Common::kPlatformWindows)
musicDelay(); // more credits on this page now
nReadPict("DA");
musicDelay();
_vm->updateEvents();
_vm->_graphics->blackAllScreen();
_vm->updateEvents();
_vm->_anim->_noPalChange = true;
nReadPict("Intro.1");
_vm->_anim->_noPalChange = false;
for (int i = 0; i < 16; i++) {
palette[i] = ((_vm->_anim->_diffPalette[i * 3] >> 2) << 8) +
((_vm->_anim->_diffPalette[i * 3 + 1] >> 2) << 4) +
(_vm->_anim->_diffPalette[i * 3 + 2] >> 2);
}
doPictText("i.1", true);
if (_vm->getPlatform() == Common::kPlatformWindows) {
doPictText("i.2A", true);
doPictText("i.2B", true);
}
_vm->_graphics->blackAllScreen();
_vm->updateEvents();
_introDoBlack = true;
nReadPict("Station1");
doPictText("i.3");
nReadPict("Station2");
doPictText("i.4");
nReadPict("Stiles4");
doPictText("i.5");
nReadPict("Stiles3");
doPictText("i.6");
if (_vm->getPlatform() == Common::kPlatformWindows)
nReadPict("Platform2");
else
nReadPict("Platform");
doPictText("i.7");
nReadPict("Subway.1");
doPictText("i.8");
nReadPict("Subway.2");
doPictText("i.9");
doPictText("i.10");
doPictText("i.11");
if (!_quitIntro)
for (int i = 0; i < 50; i++) {
for (int idx = (8 * 3); idx < (255 * 3); idx++)
_vm->_anim->_diffPalette[idx] = 255 - _vm->_anim->_diffPalette[idx];
_vm->updateEvents();
_vm->waitTOF();
_vm->_graphics->setPalette(_vm->_anim->_diffPalette, 256);
_vm->waitTOF();
_vm->waitTOF();
}
doPictText("i.12");
doPictText("i.13");
_introDoBlack = false;
nReadPict("Daed0");
doPictText("i.14");
nReadPict("Daed1");
doPictText("i.15");
nReadPict("Daed2");
doPictText("i.16");
doPictText("i.17");
doPictText("i.18");
nReadPict("Daed3");
doPictText("i.19");
doPictText("i.20");
nReadPict("Daed4");
doPictText("i.21");
nReadPict("Daed5");
doPictText("i.22");
doPictText("i.23");
doPictText("i.24");
nReadPict("Daed6");
doPictText("i.25");
doPictText("i.26");
nReadPict("Daed7", false);
doPictText("i.27");
doPictText("i.28");
_vm->_anim->stopDiffEnd();
nReadPict("Daed8");
doPictText("i.29");
doPictText("i.30");
nReadPict("Daed9");
doPictText("i.31");
doPictText("i.32");
doPictText("i.33");
nReadPict("Daed9a");
nReadPict("Daed10");
doPictText("i.34");
doPictText("i.35");
doPictText("i.36");
nReadPict("SubX");
if (_quitIntro) {
_vm->_graphics->rectFill(0, 0, _vm->_graphics->_screenWidth - 1, _vm->_graphics->_screenHeight - 1, 0);
_vm->_anim->_doBlack = true;
}
}
} // End of namespace Lab
| project-cabal/cabal | engines/lab/intro.cpp | C++ | gpl-2.0 | 9,600 |
using System;
using Server.Mobiles;
using Server.Network;
using Server.Targeting;
namespace Server.Spells.First
{
public class HealSpell : MagerySpell
{
private static readonly SpellInfo m_Info = new SpellInfo(
"Heal", "In Mani",
224,
9061,
Reagent.Garlic,
Reagent.Ginseng,
Reagent.SpidersSilk);
public HealSpell(Mobile caster, Item scroll)
: base(caster, scroll, m_Info)
{
}
public override SpellCircle Circle
{
get
{
return SpellCircle.First;
}
}
public override bool CheckCast()
{
if (Engines.ConPVP.DuelContext.CheckSuddenDeath(this.Caster))
{
this.Caster.SendMessage(0x22, "You cannot cast this spell when in sudden death.");
return false;
}
return base.CheckCast();
}
public override void OnCast()
{
this.Caster.Target = new InternalTarget(this);
}
public void Target(Mobile m)
{
if (!this.Caster.CanSee(m))
{
this.Caster.SendLocalizedMessage(500237); // Target can not be seen.
}
else if (m.IsDeadBondedPet)
{
this.Caster.SendLocalizedMessage(1060177); // You cannot heal a creature that is already dead!
}
else if (m is BaseCreature && ((BaseCreature)m).IsAnimatedDead)
{
this.Caster.SendLocalizedMessage(1061654); // You cannot heal that which is not alive.
}
else if (m is IRepairableMobile)
{
this.Caster.LocalOverheadMessage(MessageType.Regular, 0x3B2, 500951); // You cannot heal that.
}
else if (m.Poisoned || Server.Items.MortalStrike.IsWounded(m))
{
this.Caster.LocalOverheadMessage(MessageType.Regular, 0x22, (this.Caster == m) ? 1005000 : 1010398);
}
else if (this.CheckBSequence(m))
{
SpellHelper.Turn(this.Caster, m);
int toHeal;
if (Core.AOS)
{
toHeal = this.Caster.Skills.Magery.Fixed / 120;
toHeal += Utility.RandomMinMax(1, 4);
if (Core.SE && this.Caster != m)
toHeal = (int)(toHeal * 1.5);
}
else
{
toHeal = (int)(this.Caster.Skills[SkillName.Magery].Value * 0.1);
toHeal += Utility.Random(1, 5);
}
//m.Heal( toHeal, Caster );
SpellHelper.Heal(toHeal, m, this.Caster);
m.FixedParticles(0x376A, 9, 32, 5005, EffectLayer.Waist);
m.PlaySound(0x1F2);
}
this.FinishSequence();
}
public class InternalTarget : Target
{
private readonly HealSpell m_Owner;
public InternalTarget(HealSpell owner)
: base(Core.ML ? 10 : 12, false, TargetFlags.Beneficial)
{
this.m_Owner = owner;
}
protected override void OnTarget(Mobile from, object o)
{
if (o is Mobile)
{
this.m_Owner.Target((Mobile)o);
}
}
protected override void OnTargetFinish(Mobile from)
{
this.m_Owner.FinishSequence();
}
}
}
} | SirGrizzlyBear/ServUOGrizzly | Scripts/Spells/First/Heal.cs | C# | gpl-2.0 | 3,667 |
<?php
/*
+---------------------------------------------------------------------------+
| OpenX v2.8 |
| ========== |
| |
| Copyright (c) 2003-2009 OpenX Limited |
| For contact details, see: http://www.openx.org/ |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by |
| the Free Software Foundation; either version 2 of the License, or |
| (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License |
| along with this program; if not, write to the Free Software |
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
+---------------------------------------------------------------------------+
$Id: BasePublisherService.php 79311 2011-11-03 21:18:14Z chris.nutting $
*/
/**
* @package OpenX
* @author Andriy Petlyovanyy <apetlyovanyy@lohika.com>
*
*/
// Require Publisher Service Implementation
require_once MAX_PATH . '/www/api/v2/xmlrpc/PublisherServiceImpl.php';
/**
* Base Publisher Service
*
*/
class BasePublisherService
{
/**
* Reference to Publisher Service implementation.
*
* @var PublisherServiceImpl $_oPublisherServiceImp
*/
var $_oPublisherServiceImp;
/**
* This method initialises Service implementation object field.
*
*/
function BasePublisherService()
{
$this->_oPublisherServiceImp = new PublisherServiceImpl();
}
}
?> | kriwil/OpenX | www/api/v2/common/BasePublisherService.php | PHP | gpl-2.0 | 2,377 |
/***************************************************************************
qgsogcutils.cpp
---------------------
begin : March 2013
copyright : (C) 2013 by Martin Dobias
email : wonder dot sk at gmail dot 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. *
* *
***************************************************************************/
#include "qgsogcutils.h"
#include "qgsexpression.h"
#include "qgsexpressionnodeimpl.h"
#include "qgsexpressionfunction.h"
#include "qgsexpressionprivate.h"
#include "qgsgeometry.h"
#include "qgswkbptr.h"
#include "qgscoordinatereferencesystem.h"
#include "qgsrectangle.h"
#include "qgsvectorlayer.h"
#include "qgsexpressioncontextutils.h"
#include <QColor>
#include <QStringList>
#include <QTextStream>
#include <QObject>
#ifndef Q_OS_WIN
#include <netinet/in.h>
#else
#include <winsock.h>
#endif
static const QString GML_NAMESPACE = QStringLiteral( "http://www.opengis.net/gml" );
static const QString GML32_NAMESPACE = QStringLiteral( "http://www.opengis.net/gml/3.2" );
static const QString OGC_NAMESPACE = QStringLiteral( "http://www.opengis.net/ogc" );
static const QString FES_NAMESPACE = QStringLiteral( "http://www.opengis.net/fes/2.0" );
QgsOgcUtilsExprToFilter::QgsOgcUtilsExprToFilter( QDomDocument &doc,
QgsOgcUtils::GMLVersion gmlVersion,
QgsOgcUtils::FilterVersion filterVersion,
const QString &geometryName,
const QString &srsName,
bool honourAxisOrientation,
bool invertAxisOrientation )
: mDoc( doc )
, mGMLUsed( false )
, mGMLVersion( gmlVersion )
, mFilterVersion( filterVersion )
, mGeometryName( geometryName )
, mSrsName( srsName )
, mInvertAxisOrientation( invertAxisOrientation )
, mFilterPrefix( ( filterVersion == QgsOgcUtils::FILTER_FES_2_0 ) ? "fes" : "ogc" )
, mPropertyName( ( filterVersion == QgsOgcUtils::FILTER_FES_2_0 ) ? "ValueReference" : "PropertyName" )
, mGeomId( 1 )
{
QgsCoordinateReferenceSystem crs;
if ( !mSrsName.isEmpty() )
crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( mSrsName );
if ( crs.isValid() )
{
if ( honourAxisOrientation && crs.hasAxisInverted() )
{
mInvertAxisOrientation = !mInvertAxisOrientation;
}
}
}
QgsGeometry QgsOgcUtils::geometryFromGML( const QDomNode &geometryNode )
{
QDomElement geometryTypeElement = geometryNode.toElement();
QString geomType = geometryTypeElement.tagName();
if ( !( geomType == QLatin1String( "Point" ) || geomType == QLatin1String( "LineString" ) || geomType == QLatin1String( "Polygon" ) ||
geomType == QLatin1String( "MultiPoint" ) || geomType == QLatin1String( "MultiLineString" ) || geomType == QLatin1String( "MultiPolygon" ) ||
geomType == QLatin1String( "Box" ) || geomType == QLatin1String( "Envelope" ) ) )
{
QDomNode geometryChild = geometryNode.firstChild();
if ( geometryChild.isNull() )
{
return QgsGeometry();
}
geometryTypeElement = geometryChild.toElement();
geomType = geometryTypeElement.tagName();
}
if ( !( geomType == QLatin1String( "Point" ) || geomType == QLatin1String( "LineString" ) || geomType == QLatin1String( "Polygon" ) ||
geomType == QLatin1String( "MultiPoint" ) || geomType == QLatin1String( "MultiLineString" ) || geomType == QLatin1String( "MultiPolygon" ) ||
geomType == QLatin1String( "Box" ) || geomType == QLatin1String( "Envelope" ) ) )
return QgsGeometry();
if ( geomType == QLatin1String( "Point" ) )
{
return geometryFromGMLPoint( geometryTypeElement );
}
else if ( geomType == QLatin1String( "LineString" ) )
{
return geometryFromGMLLineString( geometryTypeElement );
}
else if ( geomType == QLatin1String( "Polygon" ) )
{
return geometryFromGMLPolygon( geometryTypeElement );
}
else if ( geomType == QLatin1String( "MultiPoint" ) )
{
return geometryFromGMLMultiPoint( geometryTypeElement );
}
else if ( geomType == QLatin1String( "MultiLineString" ) )
{
return geometryFromGMLMultiLineString( geometryTypeElement );
}
else if ( geomType == QLatin1String( "MultiPolygon" ) )
{
return geometryFromGMLMultiPolygon( geometryTypeElement );
}
else if ( geomType == QLatin1String( "Box" ) )
{
return QgsGeometry::fromRect( rectangleFromGMLBox( geometryTypeElement ) );
}
else if ( geomType == QLatin1String( "Envelope" ) )
{
return QgsGeometry::fromRect( rectangleFromGMLEnvelope( geometryTypeElement ) );
}
else //unknown type
{
return QgsGeometry();
}
}
QgsGeometry QgsOgcUtils::geometryFromGML( const QString &xmlString )
{
// wrap the string into a root tag to have "gml" namespace (and also as a default namespace)
QString xml = QStringLiteral( "<tmp xmlns=\"%1\" xmlns:gml=\"%1\">%2</tmp>" ).arg( GML_NAMESPACE, xmlString );
QDomDocument doc;
if ( !doc.setContent( xml, true ) )
return QgsGeometry();
return geometryFromGML( doc.documentElement().firstChildElement() );
}
QgsGeometry QgsOgcUtils::geometryFromGMLPoint( const QDomElement &geometryElement )
{
QgsPolylineXY pointCoordinate;
QDomNodeList coordList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) );
if ( !coordList.isEmpty() )
{
QDomElement coordElement = coordList.at( 0 ).toElement();
if ( readGMLCoordinates( pointCoordinate, coordElement ) != 0 )
{
return QgsGeometry();
}
}
else
{
QDomNodeList posList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "pos" ) );
if ( posList.size() < 1 )
{
return QgsGeometry();
}
QDomElement posElement = posList.at( 0 ).toElement();
if ( readGMLPositions( pointCoordinate, posElement ) != 0 )
{
return QgsGeometry();
}
}
if ( pointCoordinate.empty() )
{
return QgsGeometry();
}
QgsPolylineXY::const_iterator point_it = pointCoordinate.constBegin();
char e = htonl( 1 ) != 1;
double x = point_it->x();
double y = point_it->y();
int size = 1 + sizeof( int ) + 2 * sizeof( double );
QgsWkbTypes::Type type = QgsWkbTypes::Point;
unsigned char *wkb = new unsigned char[size];
int wkbPosition = 0; //current offset from wkb beginning (in bytes)
memcpy( &( wkb )[wkbPosition], &e, 1 );
wkbPosition += 1;
memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) );
wkbPosition += sizeof( int );
memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) );
wkbPosition += sizeof( double );
memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) );
QgsGeometry g;
g.fromWkb( wkb, size );
return g;
}
QgsGeometry QgsOgcUtils::geometryFromGMLLineString( const QDomElement &geometryElement )
{
QgsPolylineXY lineCoordinates;
QDomNodeList coordList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) );
if ( !coordList.isEmpty() )
{
QDomElement coordElement = coordList.at( 0 ).toElement();
if ( readGMLCoordinates( lineCoordinates, coordElement ) != 0 )
{
return QgsGeometry();
}
}
else
{
QDomNodeList posList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) );
if ( posList.size() < 1 )
{
return QgsGeometry();
}
QDomElement posElement = posList.at( 0 ).toElement();
if ( readGMLPositions( lineCoordinates, posElement ) != 0 )
{
return QgsGeometry();
}
}
char e = htonl( 1 ) != 1;
int size = 1 + 2 * sizeof( int ) + lineCoordinates.size() * 2 * sizeof( double );
QgsWkbTypes::Type type = QgsWkbTypes::LineString;
unsigned char *wkb = new unsigned char[size];
int wkbPosition = 0; //current offset from wkb beginning (in bytes)
double x, y;
int nPoints = lineCoordinates.size();
//fill the contents into *wkb
memcpy( &( wkb )[wkbPosition], &e, 1 );
wkbPosition += 1;
memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) );
wkbPosition += sizeof( int );
memcpy( &( wkb )[wkbPosition], &nPoints, sizeof( int ) );
wkbPosition += sizeof( int );
QgsPolylineXY::const_iterator iter;
for ( iter = lineCoordinates.constBegin(); iter != lineCoordinates.constEnd(); ++iter )
{
x = iter->x();
y = iter->y();
memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) );
wkbPosition += sizeof( double );
memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) );
wkbPosition += sizeof( double );
}
QgsGeometry g;
g.fromWkb( wkb, size );
return g;
}
QgsGeometry QgsOgcUtils::geometryFromGMLPolygon( const QDomElement &geometryElement )
{
//read all the coordinates (as QgsPoint) into memory. Each linear ring has an entry in the vector
QgsMultiPolylineXY ringCoordinates;
//read coordinates for outer boundary
QgsPolylineXY exteriorPointList;
QDomNodeList outerBoundaryList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "outerBoundaryIs" ) );
if ( !outerBoundaryList.isEmpty() ) //outer ring is necessary
{
QDomElement coordinatesElement = outerBoundaryList.at( 0 ).firstChild().firstChild().toElement();
if ( coordinatesElement.isNull() )
{
return QgsGeometry();
}
if ( readGMLCoordinates( exteriorPointList, coordinatesElement ) != 0 )
{
return QgsGeometry();
}
ringCoordinates.push_back( exteriorPointList );
//read coordinates for inner boundary
QDomNodeList innerBoundaryList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "innerBoundaryIs" ) );
for ( int i = 0; i < innerBoundaryList.size(); ++i )
{
QgsPolylineXY interiorPointList;
coordinatesElement = innerBoundaryList.at( i ).firstChild().firstChild().toElement();
if ( coordinatesElement.isNull() )
{
return QgsGeometry();
}
if ( readGMLCoordinates( interiorPointList, coordinatesElement ) != 0 )
{
return QgsGeometry();
}
ringCoordinates.push_back( interiorPointList );
}
}
else
{
//read coordinates for exterior
QDomNodeList exteriorList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "exterior" ) );
if ( exteriorList.size() < 1 ) //outer ring is necessary
{
return QgsGeometry();
}
QDomElement posElement = exteriorList.at( 0 ).firstChild().firstChild().toElement();
if ( posElement.isNull() )
{
return QgsGeometry();
}
if ( readGMLPositions( exteriorPointList, posElement ) != 0 )
{
return QgsGeometry();
}
ringCoordinates.push_back( exteriorPointList );
//read coordinates for inner boundary
QDomNodeList interiorList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "interior" ) );
for ( int i = 0; i < interiorList.size(); ++i )
{
QgsPolylineXY interiorPointList;
QDomElement posElement = interiorList.at( i ).firstChild().firstChild().toElement();
if ( posElement.isNull() )
{
return QgsGeometry();
}
if ( readGMLPositions( interiorPointList, posElement ) != 0 )
{
return QgsGeometry();
}
ringCoordinates.push_back( interiorPointList );
}
}
//calculate number of bytes to allocate
int nrings = ringCoordinates.size();
if ( nrings < 1 )
return QgsGeometry();
int npoints = 0;//total number of points
for ( QgsMultiPolylineXY::const_iterator it = ringCoordinates.constBegin(); it != ringCoordinates.constEnd(); ++it )
{
npoints += it->size();
}
int size = 1 + 2 * sizeof( int ) + nrings * sizeof( int ) + 2 * npoints * sizeof( double );
QgsWkbTypes::Type type = QgsWkbTypes::Polygon;
unsigned char *wkb = new unsigned char[size];
//char e = QgsApplication::endian();
char e = htonl( 1 ) != 1;
int wkbPosition = 0; //current offset from wkb beginning (in bytes)
int nPointsInRing = 0;
double x, y;
//fill the contents into *wkb
memcpy( &( wkb )[wkbPosition], &e, 1 );
wkbPosition += 1;
memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) );
wkbPosition += sizeof( int );
memcpy( &( wkb )[wkbPosition], &nrings, sizeof( int ) );
wkbPosition += sizeof( int );
for ( QgsMultiPolylineXY::const_iterator it = ringCoordinates.constBegin(); it != ringCoordinates.constEnd(); ++it )
{
nPointsInRing = it->size();
memcpy( &( wkb )[wkbPosition], &nPointsInRing, sizeof( int ) );
wkbPosition += sizeof( int );
//iterate through the string list converting the strings to x-/y- doubles
QgsPolylineXY::const_iterator iter;
for ( iter = it->begin(); iter != it->end(); ++iter )
{
x = iter->x();
y = iter->y();
//qWarning("currentCoordinate: " + QString::number(x) + " // " + QString::number(y));
memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) );
wkbPosition += sizeof( double );
memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) );
wkbPosition += sizeof( double );
}
}
QgsGeometry g;
g.fromWkb( wkb, size );
return g;
}
QgsGeometry QgsOgcUtils::geometryFromGMLMultiPoint( const QDomElement &geometryElement )
{
QgsPolylineXY pointList;
QgsPolylineXY currentPoint;
QDomNodeList pointMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "pointMember" ) );
if ( pointMemberList.size() < 1 )
{
return QgsGeometry();
}
QDomNodeList pointNodeList;
// coordinates or pos element
QDomNodeList coordinatesList;
QDomNodeList posList;
for ( int i = 0; i < pointMemberList.size(); ++i )
{
//<Point> element
pointNodeList = pointMemberList.at( i ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "Point" ) );
if ( pointNodeList.size() < 1 )
{
continue;
}
//<coordinates> element
coordinatesList = pointNodeList.at( 0 ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) );
if ( !coordinatesList.isEmpty() )
{
currentPoint.clear();
if ( readGMLCoordinates( currentPoint, coordinatesList.at( 0 ).toElement() ) != 0 )
{
continue;
}
if ( currentPoint.empty() )
{
continue;
}
pointList.push_back( ( *currentPoint.begin() ) );
continue;
}
else
{
//<pos> element
posList = pointNodeList.at( 0 ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "pos" ) );
if ( posList.size() < 1 )
{
continue;
}
currentPoint.clear();
if ( readGMLPositions( currentPoint, posList.at( 0 ).toElement() ) != 0 )
{
continue;
}
if ( currentPoint.empty() )
{
continue;
}
pointList.push_back( ( *currentPoint.begin() ) );
}
}
int nPoints = pointList.size(); //number of points
if ( nPoints < 1 )
return QgsGeometry();
//calculate the required wkb size
int size = 1 + 2 * sizeof( int ) + pointList.size() * ( 2 * sizeof( double ) + 1 + sizeof( int ) );
QgsWkbTypes::Type type = QgsWkbTypes::MultiPoint;
unsigned char *wkb = new unsigned char[size];
//fill the wkb content
char e = htonl( 1 ) != 1;
int wkbPosition = 0; //current offset from wkb beginning (in bytes)
double x, y;
memcpy( &( wkb )[wkbPosition], &e, 1 );
wkbPosition += 1;
memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) );
wkbPosition += sizeof( int );
memcpy( &( wkb )[wkbPosition], &nPoints, sizeof( int ) );
wkbPosition += sizeof( int );
type = QgsWkbTypes::Point;
for ( QgsPolylineXY::const_iterator it = pointList.constBegin(); it != pointList.constEnd(); ++it )
{
memcpy( &( wkb )[wkbPosition], &e, 1 );
wkbPosition += 1;
memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) );
wkbPosition += sizeof( int );
x = it->x();
memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) );
wkbPosition += sizeof( double );
y = it->y();
memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) );
wkbPosition += sizeof( double );
}
QgsGeometry g;
g.fromWkb( wkb, size );
return g;
}
QgsGeometry QgsOgcUtils::geometryFromGMLMultiLineString( const QDomElement &geometryElement )
{
//geoserver has
//<gml:MultiLineString>
//<gml:lineStringMember>
//<gml:LineString>
//mapserver has directly
//<gml:MultiLineString
//<gml:LineString
QList< QgsPolylineXY > lineCoordinates; //first list: lines, second list: points of one line
QDomElement currentLineStringElement;
QDomNodeList currentCoordList;
QDomNodeList currentPosList;
QDomNodeList lineStringMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "lineStringMember" ) );
if ( !lineStringMemberList.isEmpty() ) //geoserver
{
for ( int i = 0; i < lineStringMemberList.size(); ++i )
{
QDomNodeList lineStringNodeList = lineStringMemberList.at( i ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LineString" ) );
if ( lineStringNodeList.size() < 1 )
{
return QgsGeometry();
}
currentLineStringElement = lineStringNodeList.at( 0 ).toElement();
currentCoordList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) );
if ( !currentCoordList.isEmpty() )
{
QgsPolylineXY currentPointList;
if ( readGMLCoordinates( currentPointList, currentCoordList.at( 0 ).toElement() ) != 0 )
{
return QgsGeometry();
}
lineCoordinates.push_back( currentPointList );
}
else
{
currentPosList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) );
if ( currentPosList.size() < 1 )
{
return QgsGeometry();
}
QgsPolylineXY currentPointList;
if ( readGMLPositions( currentPointList, currentPosList.at( 0 ).toElement() ) != 0 )
{
return QgsGeometry();
}
lineCoordinates.push_back( currentPointList );
}
}
}
else
{
QDomNodeList lineStringList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LineString" ) );
if ( !lineStringList.isEmpty() ) //mapserver
{
for ( int i = 0; i < lineStringList.size(); ++i )
{
currentLineStringElement = lineStringList.at( i ).toElement();
currentCoordList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) );
if ( !currentCoordList.isEmpty() )
{
QgsPolylineXY currentPointList;
if ( readGMLCoordinates( currentPointList, currentCoordList.at( 0 ).toElement() ) != 0 )
{
return QgsGeometry();
}
lineCoordinates.push_back( currentPointList );
return QgsGeometry();
}
else
{
currentPosList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) );
if ( currentPosList.size() < 1 )
{
return QgsGeometry();
}
QgsPolylineXY currentPointList;
if ( readGMLPositions( currentPointList, currentPosList.at( 0 ).toElement() ) != 0 )
{
return QgsGeometry();
}
lineCoordinates.push_back( currentPointList );
}
}
}
else
{
return QgsGeometry();
}
}
int nLines = lineCoordinates.size();
if ( nLines < 1 )
return QgsGeometry();
//calculate the required wkb size
int size = ( lineCoordinates.size() + 1 ) * ( 1 + 2 * sizeof( int ) );
for ( QList< QgsPolylineXY >::const_iterator it = lineCoordinates.constBegin(); it != lineCoordinates.constEnd(); ++it )
{
size += it->size() * 2 * sizeof( double );
}
QgsWkbTypes::Type type = QgsWkbTypes::MultiLineString;
unsigned char *wkb = new unsigned char[size];
//fill the wkb content
char e = htonl( 1 ) != 1;
int wkbPosition = 0; //current offset from wkb beginning (in bytes)
int nPoints; //number of points in a line
double x, y;
memcpy( &( wkb )[wkbPosition], &e, 1 );
wkbPosition += 1;
memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) );
wkbPosition += sizeof( int );
memcpy( &( wkb )[wkbPosition], &nLines, sizeof( int ) );
wkbPosition += sizeof( int );
type = QgsWkbTypes::LineString;
for ( QList< QgsPolylineXY >::const_iterator it = lineCoordinates.constBegin(); it != lineCoordinates.constEnd(); ++it )
{
memcpy( &( wkb )[wkbPosition], &e, 1 );
wkbPosition += 1;
memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) );
wkbPosition += sizeof( int );
nPoints = it->size();
memcpy( &( wkb )[wkbPosition], &nPoints, sizeof( int ) );
wkbPosition += sizeof( int );
for ( QgsPolylineXY::const_iterator iter = it->begin(); iter != it->end(); ++iter )
{
x = iter->x();
y = iter->y();
// QgsDebugMsg( QStringLiteral( "x, y is %1,%2" ).arg( x, 'f' ).arg( y, 'f' ) );
memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) );
wkbPosition += sizeof( double );
memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) );
wkbPosition += sizeof( double );
}
}
QgsGeometry g;
g.fromWkb( wkb, size );
return g;
}
QgsGeometry QgsOgcUtils::geometryFromGMLMultiPolygon( const QDomElement &geometryElement )
{
//first list: different polygons, second list: different rings, third list: different points
QgsMultiPolygonXY multiPolygonPoints;
QDomElement currentPolygonMemberElement;
QDomNodeList polygonList;
QDomElement currentPolygonElement;
// rings in GML2
QDomNodeList outerBoundaryList;
QDomElement currentOuterBoundaryElement;
QDomNodeList innerBoundaryList;
QDomElement currentInnerBoundaryElement;
// rings in GML3
QDomNodeList exteriorList;
QDomElement currentExteriorElement;
QDomElement currentInteriorElement;
QDomNodeList interiorList;
// lienar ring
QDomNodeList linearRingNodeList;
QDomElement currentLinearRingElement;
// Coordinates or position list
QDomNodeList currentCoordinateList;
QDomNodeList currentPosList;
QDomNodeList polygonMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "polygonMember" ) );
QgsPolygonXY currentPolygonList;
for ( int i = 0; i < polygonMemberList.size(); ++i )
{
currentPolygonList.resize( 0 ); // preserve capacity - don't use clear
currentPolygonMemberElement = polygonMemberList.at( i ).toElement();
polygonList = currentPolygonMemberElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "Polygon" ) );
if ( polygonList.size() < 1 )
{
continue;
}
currentPolygonElement = polygonList.at( 0 ).toElement();
//find exterior ring
outerBoundaryList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "outerBoundaryIs" ) );
if ( !outerBoundaryList.isEmpty() )
{
currentOuterBoundaryElement = outerBoundaryList.at( 0 ).toElement();
QgsPolylineXY ringCoordinates;
linearRingNodeList = currentOuterBoundaryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) );
if ( linearRingNodeList.size() < 1 )
{
continue;
}
currentLinearRingElement = linearRingNodeList.at( 0 ).toElement();
currentCoordinateList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) );
if ( currentCoordinateList.size() < 1 )
{
continue;
}
if ( readGMLCoordinates( ringCoordinates, currentCoordinateList.at( 0 ).toElement() ) != 0 )
{
continue;
}
currentPolygonList.push_back( ringCoordinates );
//find interior rings
QDomNodeList innerBoundaryList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "innerBoundaryIs" ) );
for ( int j = 0; j < innerBoundaryList.size(); ++j )
{
QgsPolylineXY ringCoordinates;
currentInnerBoundaryElement = innerBoundaryList.at( j ).toElement();
linearRingNodeList = currentInnerBoundaryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) );
if ( linearRingNodeList.size() < 1 )
{
continue;
}
currentLinearRingElement = linearRingNodeList.at( 0 ).toElement();
currentCoordinateList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) );
if ( currentCoordinateList.size() < 1 )
{
continue;
}
if ( readGMLCoordinates( ringCoordinates, currentCoordinateList.at( 0 ).toElement() ) != 0 )
{
continue;
}
currentPolygonList.push_back( ringCoordinates );
}
}
else
{
//find exterior ring
exteriorList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "exterior" ) );
if ( exteriorList.size() < 1 )
{
continue;
}
currentExteriorElement = exteriorList.at( 0 ).toElement();
QgsPolylineXY ringPositions;
linearRingNodeList = currentExteriorElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) );
if ( linearRingNodeList.size() < 1 )
{
continue;
}
currentLinearRingElement = linearRingNodeList.at( 0 ).toElement();
currentPosList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) );
if ( currentPosList.size() < 1 )
{
continue;
}
if ( readGMLPositions( ringPositions, currentPosList.at( 0 ).toElement() ) != 0 )
{
continue;
}
currentPolygonList.push_back( ringPositions );
//find interior rings
QDomNodeList interiorList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "interior" ) );
for ( int j = 0; j < interiorList.size(); ++j )
{
QgsPolylineXY ringPositions;
currentInteriorElement = interiorList.at( j ).toElement();
linearRingNodeList = currentInteriorElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) );
if ( linearRingNodeList.size() < 1 )
{
continue;
}
currentLinearRingElement = linearRingNodeList.at( 0 ).toElement();
currentPosList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) );
if ( currentPosList.size() < 1 )
{
continue;
}
if ( readGMLPositions( ringPositions, currentPosList.at( 0 ).toElement() ) != 0 )
{
continue;
}
currentPolygonList.push_back( ringPositions );
}
}
multiPolygonPoints.push_back( currentPolygonList );
}
int nPolygons = multiPolygonPoints.size();
if ( nPolygons < 1 )
return QgsGeometry();
int size = 1 + 2 * sizeof( int );
//calculate the wkb size
for ( QgsMultiPolygonXY::const_iterator it = multiPolygonPoints.constBegin(); it != multiPolygonPoints.constEnd(); ++it )
{
size += 1 + 2 * sizeof( int );
for ( QgsPolygonXY::const_iterator iter = it->begin(); iter != it->end(); ++iter )
{
size += sizeof( int ) + 2 * iter->size() * sizeof( double );
}
}
QgsWkbTypes::Type type = QgsWkbTypes::MultiPolygon;
unsigned char *wkb = new unsigned char[size];
char e = htonl( 1 ) != 1;
int wkbPosition = 0; //current offset from wkb beginning (in bytes)
double x, y;
int nRings;
int nPointsInRing;
//fill the contents into *wkb
memcpy( &( wkb )[wkbPosition], &e, 1 );
wkbPosition += 1;
memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) );
wkbPosition += sizeof( int );
memcpy( &( wkb )[wkbPosition], &nPolygons, sizeof( int ) );
wkbPosition += sizeof( int );
type = QgsWkbTypes::Polygon;
for ( QgsMultiPolygonXY::const_iterator it = multiPolygonPoints.constBegin(); it != multiPolygonPoints.constEnd(); ++it )
{
memcpy( &( wkb )[wkbPosition], &e, 1 );
wkbPosition += 1;
memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) );
wkbPosition += sizeof( int );
nRings = it->size();
memcpy( &( wkb )[wkbPosition], &nRings, sizeof( int ) );
wkbPosition += sizeof( int );
for ( QgsPolygonXY::const_iterator iter = it->begin(); iter != it->end(); ++iter )
{
nPointsInRing = iter->size();
memcpy( &( wkb )[wkbPosition], &nPointsInRing, sizeof( int ) );
wkbPosition += sizeof( int );
for ( QgsPolylineXY::const_iterator iterator = iter->begin(); iterator != iter->end(); ++iterator )
{
x = iterator->x();
y = iterator->y();
memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) );
wkbPosition += sizeof( double );
memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) );
wkbPosition += sizeof( double );
}
}
}
QgsGeometry g;
g.fromWkb( wkb, size );
return g;
}
bool QgsOgcUtils::readGMLCoordinates( QgsPolylineXY &coords, const QDomElement &elem )
{
QString coordSeparator = QStringLiteral( "," );
QString tupelSeparator = QStringLiteral( " " );
//"decimal" has to be "."
coords.clear();
if ( elem.hasAttribute( QStringLiteral( "cs" ) ) )
{
coordSeparator = elem.attribute( QStringLiteral( "cs" ) );
}
if ( elem.hasAttribute( QStringLiteral( "ts" ) ) )
{
tupelSeparator = elem.attribute( QStringLiteral( "ts" ) );
}
QStringList tupels = elem.text().split( tupelSeparator, QString::SkipEmptyParts );
QStringList tuple_coords;
double x, y;
bool conversionSuccess;
QStringList::const_iterator it;
for ( it = tupels.constBegin(); it != tupels.constEnd(); ++it )
{
tuple_coords = ( *it ).split( coordSeparator, QString::SkipEmptyParts );
if ( tuple_coords.size() < 2 )
{
continue;
}
x = tuple_coords.at( 0 ).toDouble( &conversionSuccess );
if ( !conversionSuccess )
{
return true;
}
y = tuple_coords.at( 1 ).toDouble( &conversionSuccess );
if ( !conversionSuccess )
{
return true;
}
coords.push_back( QgsPointXY( x, y ) );
}
return false;
}
QgsRectangle QgsOgcUtils::rectangleFromGMLBox( const QDomNode &boxNode )
{
QgsRectangle rect;
QDomElement boxElem = boxNode.toElement();
if ( boxElem.tagName() != QLatin1String( "Box" ) )
return rect;
QDomElement bElem = boxElem.firstChild().toElement();
QString coordSeparator = QStringLiteral( "," );
QString tupelSeparator = QStringLiteral( " " );
if ( bElem.hasAttribute( QStringLiteral( "cs" ) ) )
{
coordSeparator = bElem.attribute( QStringLiteral( "cs" ) );
}
if ( bElem.hasAttribute( QStringLiteral( "ts" ) ) )
{
tupelSeparator = bElem.attribute( QStringLiteral( "ts" ) );
}
QString bString = bElem.text();
bool ok1, ok2, ok3, ok4;
double xmin = bString.section( tupelSeparator, 0, 0 ).section( coordSeparator, 0, 0 ).toDouble( &ok1 );
double ymin = bString.section( tupelSeparator, 0, 0 ).section( coordSeparator, 1, 1 ).toDouble( &ok2 );
double xmax = bString.section( tupelSeparator, 1, 1 ).section( coordSeparator, 0, 0 ).toDouble( &ok3 );
double ymax = bString.section( tupelSeparator, 1, 1 ).section( coordSeparator, 1, 1 ).toDouble( &ok4 );
if ( ok1 && ok2 && ok3 && ok4 )
{
rect = QgsRectangle( xmin, ymin, xmax, ymax );
rect.normalize();
}
return rect;
}
bool QgsOgcUtils::readGMLPositions( QgsPolylineXY &coords, const QDomElement &elem )
{
coords.clear();
QStringList pos = elem.text().split( ' ', QString::SkipEmptyParts );
double x, y;
bool conversionSuccess;
int posSize = pos.size();
int srsDimension = 2;
if ( elem.hasAttribute( QStringLiteral( "srsDimension" ) ) )
{
srsDimension = elem.attribute( QStringLiteral( "srsDimension" ) ).toInt( &conversionSuccess );
if ( !conversionSuccess )
{
srsDimension = 2;
}
}
else if ( elem.hasAttribute( QStringLiteral( "dimension" ) ) )
{
srsDimension = elem.attribute( QStringLiteral( "dimension" ) ).toInt( &conversionSuccess );
if ( !conversionSuccess )
{
srsDimension = 2;
}
}
for ( int i = 0; i < posSize / srsDimension; i++ )
{
x = pos.at( i * srsDimension ).toDouble( &conversionSuccess );
if ( !conversionSuccess )
{
return true;
}
y = pos.at( i * srsDimension + 1 ).toDouble( &conversionSuccess );
if ( !conversionSuccess )
{
return true;
}
coords.push_back( QgsPointXY( x, y ) );
}
return false;
}
QgsRectangle QgsOgcUtils::rectangleFromGMLEnvelope( const QDomNode &envelopeNode )
{
QgsRectangle rect;
QDomElement envelopeElem = envelopeNode.toElement();
if ( envelopeElem.tagName() != QLatin1String( "Envelope" ) )
return rect;
QDomNodeList lowerCornerList = envelopeElem.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "lowerCorner" ) );
if ( lowerCornerList.size() < 1 )
return rect;
QDomNodeList upperCornerList = envelopeElem.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "upperCorner" ) );
if ( upperCornerList.size() < 1 )
return rect;
bool conversionSuccess;
int srsDimension = 2;
QDomElement elem = lowerCornerList.at( 0 ).toElement();
if ( elem.hasAttribute( QStringLiteral( "srsDimension" ) ) )
{
srsDimension = elem.attribute( QStringLiteral( "srsDimension" ) ).toInt( &conversionSuccess );
if ( !conversionSuccess )
{
srsDimension = 2;
}
}
else if ( elem.hasAttribute( QStringLiteral( "dimension" ) ) )
{
srsDimension = elem.attribute( QStringLiteral( "dimension" ) ).toInt( &conversionSuccess );
if ( !conversionSuccess )
{
srsDimension = 2;
}
}
QString bString = elem.text();
double xmin = bString.section( ' ', 0, 0 ).toDouble( &conversionSuccess );
if ( !conversionSuccess )
return rect;
double ymin = bString.section( ' ', 1, 1 ).toDouble( &conversionSuccess );
if ( !conversionSuccess )
return rect;
elem = upperCornerList.at( 0 ).toElement();
if ( elem.hasAttribute( QStringLiteral( "srsDimension" ) ) )
{
srsDimension = elem.attribute( QStringLiteral( "srsDimension" ) ).toInt( &conversionSuccess );
if ( !conversionSuccess )
{
srsDimension = 2;
}
}
else if ( elem.hasAttribute( QStringLiteral( "dimension" ) ) )
{
srsDimension = elem.attribute( QStringLiteral( "dimension" ) ).toInt( &conversionSuccess );
if ( !conversionSuccess )
{
srsDimension = 2;
}
}
Q_UNUSED( srsDimension )
bString = elem.text();
double xmax = bString.section( ' ', 0, 0 ).toDouble( &conversionSuccess );
if ( !conversionSuccess )
return rect;
double ymax = bString.section( ' ', 1, 1 ).toDouble( &conversionSuccess );
if ( !conversionSuccess )
return rect;
rect = QgsRectangle( xmin, ymin, xmax, ymax );
rect.normalize();
return rect;
}
QDomElement QgsOgcUtils::rectangleToGMLBox( QgsRectangle *box, QDomDocument &doc, int precision )
{
return rectangleToGMLBox( box, doc, QString(), false, precision );
}
QDomElement QgsOgcUtils::rectangleToGMLBox( QgsRectangle *box, QDomDocument &doc,
const QString &srsName,
bool invertAxisOrientation,
int precision )
{
if ( !box )
{
return QDomElement();
}
QDomElement boxElem = doc.createElement( QStringLiteral( "gml:Box" ) );
if ( !srsName.isEmpty() )
{
boxElem.setAttribute( QStringLiteral( "srsName" ), srsName );
}
QDomElement coordElem = doc.createElement( QStringLiteral( "gml:coordinates" ) );
coordElem.setAttribute( QStringLiteral( "cs" ), QStringLiteral( "," ) );
coordElem.setAttribute( QStringLiteral( "ts" ), QStringLiteral( " " ) );
QString coordString;
coordString += qgsDoubleToString( invertAxisOrientation ? box->yMinimum() : box->xMinimum(), precision );
coordString += ',';
coordString += qgsDoubleToString( invertAxisOrientation ? box->xMinimum() : box->yMinimum(), precision );
coordString += ' ';
coordString += qgsDoubleToString( invertAxisOrientation ? box->yMaximum() : box->xMaximum(), precision );
coordString += ',';
coordString += qgsDoubleToString( invertAxisOrientation ? box->xMaximum() : box->yMaximum(), precision );
QDomText coordText = doc.createTextNode( coordString );
coordElem.appendChild( coordText );
boxElem.appendChild( coordElem );
return boxElem;
}
QDomElement QgsOgcUtils::rectangleToGMLEnvelope( QgsRectangle *env, QDomDocument &doc, int precision )
{
return rectangleToGMLEnvelope( env, doc, QString(), false, precision );
}
QDomElement QgsOgcUtils::rectangleToGMLEnvelope( QgsRectangle *env, QDomDocument &doc,
const QString &srsName,
bool invertAxisOrientation,
int precision )
{
if ( !env )
{
return QDomElement();
}
QDomElement envElem = doc.createElement( QStringLiteral( "gml:Envelope" ) );
if ( !srsName.isEmpty() )
{
envElem.setAttribute( QStringLiteral( "srsName" ), srsName );
}
QString posList;
QDomElement lowerCornerElem = doc.createElement( QStringLiteral( "gml:lowerCorner" ) );
posList = qgsDoubleToString( invertAxisOrientation ? env->yMinimum() : env->xMinimum(), precision );
posList += ' ';
posList += qgsDoubleToString( invertAxisOrientation ? env->xMinimum() : env->yMinimum(), precision );
QDomText lowerCornerText = doc.createTextNode( posList );
lowerCornerElem.appendChild( lowerCornerText );
envElem.appendChild( lowerCornerElem );
QDomElement upperCornerElem = doc.createElement( QStringLiteral( "gml:upperCorner" ) );
posList = qgsDoubleToString( invertAxisOrientation ? env->yMaximum() : env->xMaximum(), precision );
posList += ' ';
posList += qgsDoubleToString( invertAxisOrientation ? env->xMaximum() : env->yMaximum(), precision );
QDomText upperCornerText = doc.createTextNode( posList );
upperCornerElem.appendChild( upperCornerText );
envElem.appendChild( upperCornerElem );
return envElem;
}
QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry &geometry, QDomDocument &doc, const QString &format, int precision )
{
return geometryToGML( geometry, doc, ( format == QLatin1String( "GML2" ) ) ? GML_2_1_2 : GML_3_2_1, QString(), false, QString(), precision );
}
QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry &geometry, QDomDocument &doc,
GMLVersion gmlVersion,
const QString &srsName,
bool invertAxisOrientation,
const QString &gmlIdBase,
int precision )
{
if ( geometry.isNull() )
return QDomElement();
// coordinate separator
QString cs = QStringLiteral( "," );
// tuple separator
QString ts = QStringLiteral( " " );
// coord element tagname
QDomElement baseCoordElem;
bool hasZValue = false;
QByteArray wkb( geometry.asWkb() );
QgsConstWkbPtr wkbPtr( wkb );
try
{
wkbPtr.readHeader();
}
catch ( const QgsWkbException &e )
{
Q_UNUSED( e )
// WKB exception while reading header
return QDomElement();
}
if ( gmlVersion != GML_2_1_2 )
{
switch ( geometry.wkbType() )
{
case QgsWkbTypes::Point25D:
case QgsWkbTypes::Point:
case QgsWkbTypes::MultiPoint25D:
case QgsWkbTypes::MultiPoint:
baseCoordElem = doc.createElement( QStringLiteral( "gml:pos" ) );
break;
default:
baseCoordElem = doc.createElement( QStringLiteral( "gml:posList" ) );
break;
}
baseCoordElem.setAttribute( QStringLiteral( "srsDimension" ), QStringLiteral( "2" ) );
cs = ' ';
}
else
{
baseCoordElem = doc.createElement( QStringLiteral( "gml:coordinates" ) );
baseCoordElem.setAttribute( QStringLiteral( "cs" ), cs );
baseCoordElem.setAttribute( QStringLiteral( "ts" ), ts );
}
try
{
switch ( geometry.wkbType() )
{
case QgsWkbTypes::Point25D:
case QgsWkbTypes::Point:
{
QDomElement pointElem = doc.createElement( QStringLiteral( "gml:Point" ) );
if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() )
pointElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase );
if ( !srsName.isEmpty() )
pointElem.setAttribute( QStringLiteral( "srsName" ), srsName );
QDomElement coordElem = baseCoordElem.cloneNode().toElement();
double x, y;
if ( invertAxisOrientation )
wkbPtr >> y >> x;
else
wkbPtr >> x >> y;
QDomText coordText = doc.createTextNode( qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ) );
coordElem.appendChild( coordText );
pointElem.appendChild( coordElem );
return pointElem;
}
case QgsWkbTypes::MultiPoint25D:
hasZValue = true;
//intentional fall-through
FALLTHROUGH
case QgsWkbTypes::MultiPoint:
{
QDomElement multiPointElem = doc.createElement( QStringLiteral( "gml:MultiPoint" ) );
if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() )
multiPointElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase );
if ( !srsName.isEmpty() )
multiPointElem.setAttribute( QStringLiteral( "srsName" ), srsName );
int nPoints;
wkbPtr >> nPoints;
for ( int idx = 0; idx < nPoints; ++idx )
{
QDomElement pointMemberElem = doc.createElement( QStringLiteral( "gml:pointMember" ) );
QDomElement pointElem = doc.createElement( QStringLiteral( "gml:Point" ) );
if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() )
pointElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase + QStringLiteral( ".%1" ).arg( idx + 1 ) );
QDomElement coordElem = baseCoordElem.cloneNode().toElement();
wkbPtr.readHeader();
double x, y;
if ( invertAxisOrientation )
wkbPtr >> y >> x;
else
wkbPtr >> x >> y;
QDomText coordText = doc.createTextNode( qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ) );
coordElem.appendChild( coordText );
pointElem.appendChild( coordElem );
if ( hasZValue )
{
wkbPtr += sizeof( double );
}
pointMemberElem.appendChild( pointElem );
multiPointElem.appendChild( pointMemberElem );
}
return multiPointElem;
}
case QgsWkbTypes::LineString25D:
hasZValue = true;
//intentional fall-through
FALLTHROUGH
case QgsWkbTypes::LineString:
{
QDomElement lineStringElem = doc.createElement( QStringLiteral( "gml:LineString" ) );
if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() )
lineStringElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase );
if ( !srsName.isEmpty() )
lineStringElem.setAttribute( QStringLiteral( "srsName" ), srsName );
// get number of points in the line
int nPoints;
wkbPtr >> nPoints;
QDomElement coordElem = baseCoordElem.cloneNode().toElement();
QString coordString;
for ( int idx = 0; idx < nPoints; ++idx )
{
if ( idx != 0 )
{
coordString += ts;
}
double x, y;
if ( invertAxisOrientation )
wkbPtr >> y >> x;
else
wkbPtr >> x >> y;
coordString += qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision );
if ( hasZValue )
{
wkbPtr += sizeof( double );
}
}
QDomText coordText = doc.createTextNode( coordString );
coordElem.appendChild( coordText );
lineStringElem.appendChild( coordElem );
return lineStringElem;
}
case QgsWkbTypes::MultiLineString25D:
hasZValue = true;
//intentional fall-through
FALLTHROUGH
case QgsWkbTypes::MultiLineString:
{
QDomElement multiLineStringElem = doc.createElement( QStringLiteral( "gml:MultiLineString" ) );
if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() )
multiLineStringElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase );
if ( !srsName.isEmpty() )
multiLineStringElem.setAttribute( QStringLiteral( "srsName" ), srsName );
int nLines;
wkbPtr >> nLines;
for ( int jdx = 0; jdx < nLines; jdx++ )
{
QDomElement lineStringMemberElem = doc.createElement( QStringLiteral( "gml:lineStringMember" ) );
QDomElement lineStringElem = doc.createElement( QStringLiteral( "gml:LineString" ) );
if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() )
lineStringElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase + QStringLiteral( ".%1" ).arg( jdx + 1 ) );
wkbPtr.readHeader();
int nPoints;
wkbPtr >> nPoints;
QDomElement coordElem = baseCoordElem.cloneNode().toElement();
QString coordString;
for ( int idx = 0; idx < nPoints; idx++ )
{
if ( idx != 0 )
{
coordString += ts;
}
double x, y;
if ( invertAxisOrientation )
wkbPtr >> y >> x;
else
wkbPtr >> x >> y;
coordString += qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision );
if ( hasZValue )
{
wkbPtr += sizeof( double );
}
}
QDomText coordText = doc.createTextNode( coordString );
coordElem.appendChild( coordText );
lineStringElem.appendChild( coordElem );
lineStringMemberElem.appendChild( lineStringElem );
multiLineStringElem.appendChild( lineStringMemberElem );
}
return multiLineStringElem;
}
case QgsWkbTypes::Polygon25D:
hasZValue = true;
//intentional fall-through
FALLTHROUGH
case QgsWkbTypes::Polygon:
{
QDomElement polygonElem = doc.createElement( QStringLiteral( "gml:Polygon" ) );
if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() )
polygonElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase );
if ( !srsName.isEmpty() )
polygonElem.setAttribute( QStringLiteral( "srsName" ), srsName );
// get number of rings in the polygon
int numRings;
wkbPtr >> numRings;
if ( numRings == 0 ) // sanity check for zero rings in polygon
return QDomElement();
int *ringNumPoints = new int[numRings]; // number of points in each ring
for ( int idx = 0; idx < numRings; idx++ )
{
QString boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:outerBoundaryIs" : "gml:exterior";
if ( idx != 0 )
{
boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:innerBoundaryIs" : "gml:interior";
}
QDomElement boundaryElem = doc.createElement( boundaryName );
QDomElement ringElem = doc.createElement( QStringLiteral( "gml:LinearRing" ) );
// get number of points in the ring
int nPoints;
wkbPtr >> nPoints;
ringNumPoints[idx] = nPoints;
QDomElement coordElem = baseCoordElem.cloneNode().toElement();
QString coordString;
for ( int jdx = 0; jdx < nPoints; jdx++ )
{
if ( jdx != 0 )
{
coordString += ts;
}
double x, y;
if ( invertAxisOrientation )
wkbPtr >> y >> x;
else
wkbPtr >> x >> y;
coordString += qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision );
if ( hasZValue )
{
wkbPtr += sizeof( double );
}
}
QDomText coordText = doc.createTextNode( coordString );
coordElem.appendChild( coordText );
ringElem.appendChild( coordElem );
boundaryElem.appendChild( ringElem );
polygonElem.appendChild( boundaryElem );
}
delete [] ringNumPoints;
return polygonElem;
}
case QgsWkbTypes::MultiPolygon25D:
hasZValue = true;
//intentional fall-through
FALLTHROUGH
case QgsWkbTypes::MultiPolygon:
{
QDomElement multiPolygonElem = doc.createElement( QStringLiteral( "gml:MultiPolygon" ) );
if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() )
multiPolygonElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase );
if ( !srsName.isEmpty() )
multiPolygonElem.setAttribute( QStringLiteral( "srsName" ), srsName );
int numPolygons;
wkbPtr >> numPolygons;
for ( int kdx = 0; kdx < numPolygons; kdx++ )
{
QDomElement polygonMemberElem = doc.createElement( QStringLiteral( "gml:polygonMember" ) );
QDomElement polygonElem = doc.createElement( QStringLiteral( "gml:Polygon" ) );
if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() )
polygonElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase + QStringLiteral( ".%1" ).arg( kdx + 1 ) );
wkbPtr.readHeader();
int numRings;
wkbPtr >> numRings;
for ( int idx = 0; idx < numRings; idx++ )
{
QString boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:outerBoundaryIs" : "gml:exterior";
if ( idx != 0 )
{
boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:innerBoundaryIs" : "gml:interior";
}
QDomElement boundaryElem = doc.createElement( boundaryName );
QDomElement ringElem = doc.createElement( QStringLiteral( "gml:LinearRing" ) );
int nPoints;
wkbPtr >> nPoints;
QDomElement coordElem = baseCoordElem.cloneNode().toElement();
QString coordString;
for ( int jdx = 0; jdx < nPoints; jdx++ )
{
if ( jdx != 0 )
{
coordString += ts;
}
double x, y;
if ( invertAxisOrientation )
wkbPtr >> y >> x;
else
wkbPtr >> x >> y;
coordString += qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision );
if ( hasZValue )
{
wkbPtr += sizeof( double );
}
}
QDomText coordText = doc.createTextNode( coordString );
coordElem.appendChild( coordText );
ringElem.appendChild( coordElem );
boundaryElem.appendChild( ringElem );
polygonElem.appendChild( boundaryElem );
polygonMemberElem.appendChild( polygonElem );
multiPolygonElem.appendChild( polygonMemberElem );
}
}
return multiPolygonElem;
}
default:
return QDomElement();
}
}
catch ( const QgsWkbException &e )
{
Q_UNUSED( e )
return QDomElement();
}
}
QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry &geometry, QDomDocument &doc, int precision )
{
return geometryToGML( geometry, doc, QStringLiteral( "GML2" ), precision );
}
QDomElement QgsOgcUtils::createGMLCoordinates( const QgsPolylineXY &points, QDomDocument &doc )
{
QDomElement coordElem = doc.createElement( QStringLiteral( "gml:coordinates" ) );
coordElem.setAttribute( QStringLiteral( "cs" ), QStringLiteral( "," ) );
coordElem.setAttribute( QStringLiteral( "ts" ), QStringLiteral( " " ) );
QString coordString;
QVector<QgsPointXY>::const_iterator pointIt = points.constBegin();
for ( ; pointIt != points.constEnd(); ++pointIt )
{
if ( pointIt != points.constBegin() )
{
coordString += ' ';
}
coordString += qgsDoubleToString( pointIt->x() );
coordString += ',';
coordString += qgsDoubleToString( pointIt->y() );
}
QDomText coordText = doc.createTextNode( coordString );
coordElem.appendChild( coordText );
return coordElem;
}
QDomElement QgsOgcUtils::createGMLPositions( const QgsPolylineXY &points, QDomDocument &doc )
{
QDomElement posElem = doc.createElement( QStringLiteral( "gml:pos" ) );
if ( points.size() > 1 )
posElem = doc.createElement( QStringLiteral( "gml:posList" ) );
posElem.setAttribute( QStringLiteral( "srsDimension" ), QStringLiteral( "2" ) );
QString coordString;
QVector<QgsPointXY>::const_iterator pointIt = points.constBegin();
for ( ; pointIt != points.constEnd(); ++pointIt )
{
if ( pointIt != points.constBegin() )
{
coordString += ' ';
}
coordString += qgsDoubleToString( pointIt->x() );
coordString += ' ';
coordString += qgsDoubleToString( pointIt->y() );
}
QDomText coordText = doc.createTextNode( coordString );
posElem.appendChild( coordText );
return posElem;
}
// -----------------------------------------
QColor QgsOgcUtils::colorFromOgcFill( const QDomElement &fillElement )
{
if ( fillElement.isNull() || !fillElement.hasChildNodes() )
{
return QColor();
}
QString cssName;
QString elemText;
QColor color;
QDomElement cssElem = fillElement.firstChildElement( QStringLiteral( "CssParameter" ) );
while ( !cssElem.isNull() )
{
cssName = cssElem.attribute( QStringLiteral( "name" ), QStringLiteral( "not_found" ) );
if ( cssName != QLatin1String( "not_found" ) )
{
elemText = cssElem.text();
if ( cssName == QLatin1String( "fill" ) )
{
color.setNamedColor( elemText );
}
else if ( cssName == QLatin1String( "fill-opacity" ) )
{
bool ok;
double opacity = elemText.toDouble( &ok );
if ( ok )
{
color.setAlphaF( opacity );
}
}
}
cssElem = cssElem.nextSiblingElement( QStringLiteral( "CssParameter" ) );
}
return color;
}
QgsExpression *QgsOgcUtils::expressionFromOgcFilter( const QDomElement &element, QgsVectorLayer *layer )
{
return expressionFromOgcFilter( element, QgsOgcUtils::FILTER_OGC_1_0, layer );
}
QgsExpression *QgsOgcUtils::expressionFromOgcFilter( const QDomElement &element, const FilterVersion version, QgsVectorLayer *layer )
{
if ( element.isNull() || !element.hasChildNodes() )
return nullptr;
QgsExpression *expr = new QgsExpression();
// check if it is a single string value not having DOM elements
// that express OGC operators
if ( element.firstChild().nodeType() == QDomNode::TextNode )
{
expr->setExpression( element.firstChild().nodeValue() );
return expr;
}
QgsOgcUtilsExpressionFromFilter utils( version, layer );
// then check OGC DOM elements that contain OGC tags specifying
// OGC operators.
QDomElement childElem = element.firstChildElement();
while ( !childElem.isNull() )
{
QgsExpressionNode *node = utils.nodeFromOgcFilter( childElem );
if ( !node )
{
// invalid expression, parser error
expr->d->mParserErrorString = utils.errorMessage();
return expr;
}
// use the concat binary operator to append to the root node
if ( !expr->d->mRootNode )
{
expr->d->mRootNode = node;
}
else
{
expr->d->mRootNode = new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boConcat, expr->d->mRootNode, node );
}
childElem = childElem.nextSiblingElement();
}
// update expression string
expr->d->mExp = expr->dump();
return expr;
}
static const QMap<QString, int> BINARY_OPERATORS_TAG_NAMES_MAP
{
// logical
{ QStringLiteral( "Or" ), QgsExpressionNodeBinaryOperator::boOr },
{ QStringLiteral( "And" ), QgsExpressionNodeBinaryOperator::boAnd },
// comparison
{ QStringLiteral( "PropertyIsEqualTo" ), QgsExpressionNodeBinaryOperator::boEQ },
{ QStringLiteral( "PropertyIsNotEqualTo" ), QgsExpressionNodeBinaryOperator::boNE },
{ QStringLiteral( "PropertyIsLessThanOrEqualTo" ), QgsExpressionNodeBinaryOperator::boLE },
{ QStringLiteral( "PropertyIsGreaterThanOrEqualTo" ), QgsExpressionNodeBinaryOperator::boGE },
{ QStringLiteral( "PropertyIsLessThan" ), QgsExpressionNodeBinaryOperator::boLT },
{ QStringLiteral( "PropertyIsGreaterThan" ), QgsExpressionNodeBinaryOperator::boGT },
{ QStringLiteral( "PropertyIsLike" ), QgsExpressionNodeBinaryOperator::boLike },
// arithmetic
{ QStringLiteral( "Add" ), QgsExpressionNodeBinaryOperator::boPlus },
{ QStringLiteral( "Sub" ), QgsExpressionNodeBinaryOperator::boMinus },
{ QStringLiteral( "Mul" ), QgsExpressionNodeBinaryOperator::boMul },
{ QStringLiteral( "Div" ), QgsExpressionNodeBinaryOperator::boDiv },
};
static int binaryOperatorFromTagName( const QString &tagName )
{
return BINARY_OPERATORS_TAG_NAMES_MAP.value( tagName, -1 );
}
static QString binaryOperatorToTagName( QgsExpressionNodeBinaryOperator::BinaryOperator op )
{
if ( op == QgsExpressionNodeBinaryOperator::boILike )
{
return QStringLiteral( "PropertyIsLike" );
}
return BINARY_OPERATORS_TAG_NAMES_MAP.key( op, QString() );
}
static bool isBinaryOperator( const QString &tagName )
{
return binaryOperatorFromTagName( tagName ) >= 0;
}
static bool isSpatialOperator( const QString &tagName )
{
static QStringList spatialOps;
if ( spatialOps.isEmpty() )
{
spatialOps << QStringLiteral( "BBOX" ) << QStringLiteral( "Intersects" ) << QStringLiteral( "Contains" ) << QStringLiteral( "Crosses" ) << QStringLiteral( "Equals" )
<< QStringLiteral( "Disjoint" ) << QStringLiteral( "Overlaps" ) << QStringLiteral( "Touches" ) << QStringLiteral( "Within" );
}
return spatialOps.contains( tagName );
}
QgsExpressionNode *QgsOgcUtils::nodeFromOgcFilter( QDomElement &element, QString &errorMessage, QgsVectorLayer *layer )
{
QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0, layer );
QgsExpressionNode *node = utils.nodeFromOgcFilter( element );
errorMessage = utils.errorMessage();
return node;
}
QgsExpressionNodeBinaryOperator *QgsOgcUtils::nodeBinaryOperatorFromOgcFilter( QDomElement &element, QString &errorMessage, QgsVectorLayer *layer )
{
QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0, layer );
QgsExpressionNodeBinaryOperator *node = utils.nodeBinaryOperatorFromOgcFilter( element );
errorMessage = utils.errorMessage();
return node;
}
QgsExpressionNodeFunction *QgsOgcUtils::nodeSpatialOperatorFromOgcFilter( QDomElement &element, QString &errorMessage )
{
QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 );
QgsExpressionNodeFunction *node = utils.nodeSpatialOperatorFromOgcFilter( element );
errorMessage = utils.errorMessage();
return node;
}
QgsExpressionNodeUnaryOperator *QgsOgcUtils::nodeNotFromOgcFilter( QDomElement &element, QString &errorMessage )
{
QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 );
QgsExpressionNodeUnaryOperator *node = utils.nodeNotFromOgcFilter( element );
errorMessage = utils.errorMessage();
return node;
}
QgsExpressionNodeFunction *QgsOgcUtils::nodeFunctionFromOgcFilter( QDomElement &element, QString &errorMessage )
{
QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 );
QgsExpressionNodeFunction *node = utils.nodeFunctionFromOgcFilter( element );
errorMessage = utils.errorMessage();
return node;
}
QgsExpressionNode *QgsOgcUtils::nodeLiteralFromOgcFilter( QDomElement &element, QString &errorMessage, QgsVectorLayer *layer )
{
QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0, layer );
QgsExpressionNode *node = utils.nodeLiteralFromOgcFilter( element );
errorMessage = utils.errorMessage();
return node;
}
QgsExpressionNodeColumnRef *QgsOgcUtils::nodeColumnRefFromOgcFilter( QDomElement &element, QString &errorMessage )
{
QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 );
QgsExpressionNodeColumnRef *node = utils.nodeColumnRefFromOgcFilter( element );
errorMessage = utils.errorMessage();
return node;
}
QgsExpressionNode *QgsOgcUtils::nodeIsBetweenFromOgcFilter( QDomElement &element, QString &errorMessage )
{
QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 );
QgsExpressionNode *node = utils.nodeIsBetweenFromOgcFilter( element );
errorMessage = utils.errorMessage();
return node;
}
QgsExpressionNodeBinaryOperator *QgsOgcUtils::nodePropertyIsNullFromOgcFilter( QDomElement &element, QString &errorMessage )
{
QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 );
QgsExpressionNodeBinaryOperator *node = utils.nodePropertyIsNullFromOgcFilter( element );
errorMessage = utils.errorMessage();
return node;
}
/////////////////
QDomElement QgsOgcUtils::expressionToOgcFilter( const QgsExpression &exp, QDomDocument &doc, QString *errorMessage )
{
return expressionToOgcFilter( exp, doc, GML_2_1_2, FILTER_OGC_1_0,
QStringLiteral( "geometry" ), QString(), false, false, errorMessage );
}
QDomElement QgsOgcUtils::expressionToOgcExpression( const QgsExpression &exp, QDomDocument &doc, QString *errorMessage )
{
return expressionToOgcExpression( exp, doc, GML_2_1_2, FILTER_OGC_1_0,
QStringLiteral( "geometry" ), QString(), false, false, errorMessage );
}
QDomElement QgsOgcUtils::expressionToOgcFilter( const QgsExpression &expression,
QDomDocument &doc,
GMLVersion gmlVersion,
FilterVersion filterVersion,
const QString &geometryName,
const QString &srsName,
bool honourAxisOrientation,
bool invertAxisOrientation,
QString *errorMessage )
{
if ( !expression.rootNode() )
return QDomElement();
QgsExpression exp = expression;
QgsExpressionContext context;
context << QgsExpressionContextUtils::globalScope();
QgsOgcUtilsExprToFilter utils( doc, gmlVersion, filterVersion, geometryName, srsName, honourAxisOrientation, invertAxisOrientation );
QDomElement exprRootElem = utils.expressionNodeToOgcFilter( exp.rootNode(), &exp, &context );
if ( errorMessage )
*errorMessage = utils.errorMessage();
if ( exprRootElem.isNull() )
return QDomElement();
QDomElement filterElem =
( filterVersion == FILTER_FES_2_0 ) ?
doc.createElementNS( FES_NAMESPACE, QStringLiteral( "fes:Filter" ) ) :
doc.createElementNS( OGC_NAMESPACE, QStringLiteral( "ogc:Filter" ) );
if ( utils.GMLNamespaceUsed() )
{
QDomAttr attr = doc.createAttribute( QStringLiteral( "xmlns:gml" ) );
if ( gmlVersion == GML_3_2_1 )
attr.setValue( GML32_NAMESPACE );
else
attr.setValue( GML_NAMESPACE );
filterElem.setAttributeNode( attr );
}
filterElem.appendChild( exprRootElem );
return filterElem;
}
QDomElement QgsOgcUtils::expressionToOgcExpression( const QgsExpression &expression,
QDomDocument &doc,
GMLVersion gmlVersion,
FilterVersion filterVersion,
const QString &geometryName,
const QString &srsName,
bool honourAxisOrientation,
bool invertAxisOrientation,
QString *errorMessage )
{
QgsExpressionContext context;
context << QgsExpressionContextUtils::globalScope();
QgsExpression exp = expression;
const QgsExpressionNode *node = exp.rootNode();
if ( !node )
return QDomElement();
switch ( node->nodeType() )
{
case QgsExpressionNode::ntFunction:
case QgsExpressionNode::ntLiteral:
case QgsExpressionNode::ntColumnRef:
{
QgsOgcUtilsExprToFilter utils( doc, gmlVersion, filterVersion, geometryName, srsName, honourAxisOrientation, invertAxisOrientation );
QDomElement exprRootElem = utils.expressionNodeToOgcFilter( node, &exp, &context );
if ( errorMessage )
*errorMessage = utils.errorMessage();
if ( !exprRootElem.isNull() )
{
return exprRootElem;
}
break;
}
default:
{
if ( errorMessage )
*errorMessage = QObject::tr( "Node type not supported in expression translation: %1" ).arg( node->nodeType() );
}
}
// got an error
return QDomElement();
}
QDomElement QgsOgcUtils::SQLStatementToOgcFilter( const QgsSQLStatement &statement,
QDomDocument &doc,
GMLVersion gmlVersion,
FilterVersion filterVersion,
const QList<LayerProperties> &layerProperties,
bool honourAxisOrientation,
bool invertAxisOrientation,
const QMap< QString, QString> &mapUnprefixedTypenameToPrefixedTypename,
QString *errorMessage )
{
if ( !statement.rootNode() )
return QDomElement();
QgsOgcUtilsSQLStatementToFilter utils( doc, gmlVersion, filterVersion,
layerProperties, honourAxisOrientation, invertAxisOrientation,
mapUnprefixedTypenameToPrefixedTypename );
QDomElement exprRootElem = utils.toOgcFilter( statement.rootNode() );
if ( errorMessage )
*errorMessage = utils.errorMessage();
if ( exprRootElem.isNull() )
return QDomElement();
QDomElement filterElem =
( filterVersion == FILTER_FES_2_0 ) ?
doc.createElementNS( FES_NAMESPACE, QStringLiteral( "fes:Filter" ) ) :
doc.createElementNS( OGC_NAMESPACE, QStringLiteral( "ogc:Filter" ) );
if ( utils.GMLNamespaceUsed() )
{
QDomAttr attr = doc.createAttribute( QStringLiteral( "xmlns:gml" ) );
if ( gmlVersion == GML_3_2_1 )
attr.setValue( GML32_NAMESPACE );
else
attr.setValue( GML_NAMESPACE );
filterElem.setAttributeNode( attr );
}
filterElem.appendChild( exprRootElem );
return filterElem;
}
//
QDomElement QgsOgcUtilsExprToFilter::expressionNodeToOgcFilter( const QgsExpressionNode *node, QgsExpression *expression, const QgsExpressionContext *context )
{
switch ( node->nodeType() )
{
case QgsExpressionNode::ntUnaryOperator:
return expressionUnaryOperatorToOgcFilter( static_cast<const QgsExpressionNodeUnaryOperator *>( node ), expression, context );
case QgsExpressionNode::ntBinaryOperator:
return expressionBinaryOperatorToOgcFilter( static_cast<const QgsExpressionNodeBinaryOperator *>( node ), expression, context );
case QgsExpressionNode::ntInOperator:
return expressionInOperatorToOgcFilter( static_cast<const QgsExpressionNodeInOperator *>( node ), expression, context );
case QgsExpressionNode::ntFunction:
return expressionFunctionToOgcFilter( static_cast<const QgsExpressionNodeFunction *>( node ), expression, context );
case QgsExpressionNode::ntLiteral:
return expressionLiteralToOgcFilter( static_cast<const QgsExpressionNodeLiteral *>( node ), expression, context );
case QgsExpressionNode::ntColumnRef:
return expressionColumnRefToOgcFilter( static_cast<const QgsExpressionNodeColumnRef *>( node ), expression, context );
default:
mErrorMessage = QObject::tr( "Node type not supported: %1" ).arg( node->nodeType() );
return QDomElement();
}
}
QDomElement QgsOgcUtilsExprToFilter::expressionUnaryOperatorToOgcFilter( const QgsExpressionNodeUnaryOperator *node, QgsExpression *expression, const QgsExpressionContext *context )
{
QDomElement operandElem = expressionNodeToOgcFilter( node->operand(), expression, context );
if ( !mErrorMessage.isEmpty() )
return QDomElement();
QDomElement uoElem;
switch ( node->op() )
{
case QgsExpressionNodeUnaryOperator::uoMinus:
uoElem = mDoc.createElement( mFilterPrefix + ":Literal" );
if ( node->operand()->nodeType() == QgsExpressionNode::ntLiteral )
{
// operand expression already created a Literal node:
// take the literal value, prepend - and remove old literal node
uoElem.appendChild( mDoc.createTextNode( "-" + operandElem.text() ) );
mDoc.removeChild( operandElem );
}
else
{
mErrorMessage = QObject::tr( "This use of unary operator not implemented yet" );
return QDomElement();
}
break;
case QgsExpressionNodeUnaryOperator::uoNot:
uoElem = mDoc.createElement( mFilterPrefix + ":Not" );
uoElem.appendChild( operandElem );
break;
default:
mErrorMessage = QObject::tr( "Unary operator '%1' not implemented yet" ).arg( node->text() );
return QDomElement();
}
return uoElem;
}
QDomElement QgsOgcUtilsExprToFilter::expressionBinaryOperatorToOgcFilter( const QgsExpressionNodeBinaryOperator *node, QgsExpression *expression, const QgsExpressionContext *context )
{
QDomElement leftElem = expressionNodeToOgcFilter( node->opLeft(), expression, context );
if ( !mErrorMessage.isEmpty() )
return QDomElement();
QgsExpressionNodeBinaryOperator::BinaryOperator op = node->op();
// before right operator is parsed: to allow NULL handling
if ( op == QgsExpressionNodeBinaryOperator::boIs || op == QgsExpressionNodeBinaryOperator::boIsNot )
{
if ( node->opRight()->nodeType() == QgsExpressionNode::ntLiteral )
{
const QgsExpressionNodeLiteral *rightLit = static_cast<const QgsExpressionNodeLiteral *>( node->opRight() );
if ( rightLit->value().isNull() )
{
QDomElement elem = mDoc.createElement( mFilterPrefix + ":PropertyIsNull" );
elem.appendChild( leftElem );
if ( op == QgsExpressionNodeBinaryOperator::boIsNot )
{
QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" );
notElem.appendChild( elem );
return notElem;
}
return elem;
}
// continue with equal / not equal operator once the null case is handled
op = ( op == QgsExpressionNodeBinaryOperator::boIs ? QgsExpressionNodeBinaryOperator::boEQ : QgsExpressionNodeBinaryOperator::boNE );
}
}
QDomElement rightElem = expressionNodeToOgcFilter( node->opRight(), expression, context );
if ( !mErrorMessage.isEmpty() )
return QDomElement();
QString opText = binaryOperatorToTagName( op );
if ( opText.isEmpty() )
{
// not implemented binary operators
// TODO: regex, % (mod), ^ (pow) are not supported yet
mErrorMessage = QObject::tr( "Binary operator %1 not implemented yet" ).arg( node->text() );
return QDomElement();
}
QDomElement boElem = mDoc.createElement( mFilterPrefix + ":" + opText );
if ( op == QgsExpressionNodeBinaryOperator::boLike || op == QgsExpressionNodeBinaryOperator::boILike )
{
if ( op == QgsExpressionNodeBinaryOperator::boILike )
boElem.setAttribute( QStringLiteral( "matchCase" ), QStringLiteral( "false" ) );
// setup wildCards to <ogc:PropertyIsLike>
boElem.setAttribute( QStringLiteral( "wildCard" ), QStringLiteral( "%" ) );
boElem.setAttribute( QStringLiteral( "singleChar" ), QStringLiteral( "_" ) );
if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 )
boElem.setAttribute( QStringLiteral( "escape" ), QStringLiteral( "\\" ) );
else
boElem.setAttribute( QStringLiteral( "escapeChar" ), QStringLiteral( "\\" ) );
}
boElem.appendChild( leftElem );
boElem.appendChild( rightElem );
return boElem;
}
QDomElement QgsOgcUtilsExprToFilter::expressionLiteralToOgcFilter( const QgsExpressionNodeLiteral *node, QgsExpression *expression, const QgsExpressionContext *context )
{
Q_UNUSED( expression )
Q_UNUSED( context )
QString value;
switch ( node->value().type() )
{
case QVariant::Int:
value = QString::number( node->value().toInt() );
break;
case QVariant::Double:
value = qgsDoubleToString( node->value().toDouble() );
break;
case QVariant::String:
value = node->value().toString();
break;
case QVariant::Date:
value = node->value().toDate().toString( Qt::ISODate );
break;
case QVariant::DateTime:
value = node->value().toDateTime().toString( Qt::ISODate );
break;
default:
mErrorMessage = QObject::tr( "Literal type not supported: %1" ).arg( node->value().type() );
return QDomElement();
}
QDomElement litElem = mDoc.createElement( mFilterPrefix + ":Literal" );
litElem.appendChild( mDoc.createTextNode( value ) );
return litElem;
}
QDomElement QgsOgcUtilsExprToFilter::expressionColumnRefToOgcFilter( const QgsExpressionNodeColumnRef *node, QgsExpression *expression, const QgsExpressionContext *context )
{
Q_UNUSED( expression )
Q_UNUSED( context )
QDomElement propElem = mDoc.createElement( mFilterPrefix + ":" + mPropertyName );
propElem.appendChild( mDoc.createTextNode( node->name() ) );
return propElem;
}
QDomElement QgsOgcUtilsExprToFilter::expressionInOperatorToOgcFilter( const QgsExpressionNodeInOperator *node, QgsExpression *expression, const QgsExpressionContext *context )
{
if ( node->list()->list().size() == 1 )
return expressionNodeToOgcFilter( node->list()->list()[0], expression, context );
QDomElement orElem = mDoc.createElement( mFilterPrefix + ":Or" );
QDomElement leftNode = expressionNodeToOgcFilter( node->node(), expression, context );
const auto constList = node->list()->list();
for ( QgsExpressionNode *n : constList )
{
QDomElement listNode = expressionNodeToOgcFilter( n, expression, context );
if ( !mErrorMessage.isEmpty() )
return QDomElement();
QDomElement eqElem = mDoc.createElement( mFilterPrefix + ":PropertyIsEqualTo" );
eqElem.appendChild( leftNode.cloneNode() );
eqElem.appendChild( listNode );
orElem.appendChild( eqElem );
}
if ( node->isNotIn() )
{
QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" );
notElem.appendChild( orElem );
return notElem;
}
return orElem;
}
static const QMap<QString, QString> BINARY_SPATIAL_OPS_MAP
{
{ QStringLiteral( "disjoint" ), QStringLiteral( "Disjoint" ) },
{ QStringLiteral( "intersects" ), QStringLiteral( "Intersects" )},
{ QStringLiteral( "touches" ), QStringLiteral( "Touches" ) },
{ QStringLiteral( "crosses" ), QStringLiteral( "Crosses" ) },
{ QStringLiteral( "contains" ), QStringLiteral( "Contains" ) },
{ QStringLiteral( "overlaps" ), QStringLiteral( "Overlaps" ) },
{ QStringLiteral( "within" ), QStringLiteral( "Within" ) }
};
static bool isBinarySpatialOperator( const QString &fnName )
{
return BINARY_SPATIAL_OPS_MAP.contains( fnName );
}
static QString tagNameForSpatialOperator( const QString &fnName )
{
return BINARY_SPATIAL_OPS_MAP.value( fnName );
}
static bool isGeometryColumn( const QgsExpressionNode *node )
{
if ( node->nodeType() != QgsExpressionNode::ntFunction )
return false;
const QgsExpressionNodeFunction *fn = static_cast<const QgsExpressionNodeFunction *>( node );
QgsExpressionFunction *fd = QgsExpression::Functions()[fn->fnIndex()];
return fd->name() == QLatin1String( "$geometry" );
}
static QgsGeometry geometryFromConstExpr( const QgsExpressionNode *node )
{
// Right now we support only geomFromWKT(' ..... ')
// Ideally we should support any constant sub-expression (not dependent on feature's geometry or attributes)
if ( node->nodeType() == QgsExpressionNode::ntFunction )
{
const QgsExpressionNodeFunction *fnNode = static_cast<const QgsExpressionNodeFunction *>( node );
QgsExpressionFunction *fnDef = QgsExpression::Functions()[fnNode->fnIndex()];
if ( fnDef->name() == QLatin1String( "geom_from_wkt" ) )
{
const QList<QgsExpressionNode *> &args = fnNode->args()->list();
if ( args[0]->nodeType() == QgsExpressionNode::ntLiteral )
{
QString wkt = static_cast<const QgsExpressionNodeLiteral *>( args[0] )->value().toString();
return QgsGeometry::fromWkt( wkt );
}
}
}
return QgsGeometry();
}
QDomElement QgsOgcUtilsExprToFilter::expressionFunctionToOgcFilter( const QgsExpressionNodeFunction *node, QgsExpression *expression, const QgsExpressionContext *context )
{
QgsExpressionFunction *fd = QgsExpression::Functions()[node->fnIndex()];
if ( fd->name() == QLatin1String( "intersects_bbox" ) )
{
QList<QgsExpressionNode *> argNodes = node->args()->list();
Q_ASSERT( argNodes.count() == 2 ); // binary spatial ops must have two args
QgsGeometry geom = geometryFromConstExpr( argNodes[1] );
if ( !geom.isNull() && isGeometryColumn( argNodes[0] ) )
{
QgsRectangle rect = geom.boundingBox();
mGMLUsed = true;
QDomElement elemBox = ( mGMLVersion == QgsOgcUtils::GML_2_1_2 ) ?
QgsOgcUtils::rectangleToGMLBox( &rect, mDoc, mSrsName, mInvertAxisOrientation ) :
QgsOgcUtils::rectangleToGMLEnvelope( &rect, mDoc, mSrsName, mInvertAxisOrientation );
QDomElement geomProperty = mDoc.createElement( mFilterPrefix + ":" + mPropertyName );
geomProperty.appendChild( mDoc.createTextNode( mGeometryName ) );
QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":BBOX" );
funcElem.appendChild( geomProperty );
funcElem.appendChild( elemBox );
return funcElem;
}
else
{
mErrorMessage = QObject::tr( "<BBOX> is currently supported only in form: bbox($geometry, geomFromWKT('…'))" );
return QDomElement();
}
}
if ( isBinarySpatialOperator( fd->name() ) )
{
QList<QgsExpressionNode *> argNodes = node->args()->list();
Q_ASSERT( argNodes.count() == 2 ); // binary spatial ops must have two args
QgsExpressionNode *otherNode = nullptr;
if ( isGeometryColumn( argNodes[0] ) )
otherNode = argNodes[1];
else if ( isGeometryColumn( argNodes[1] ) )
otherNode = argNodes[0];
else
{
mErrorMessage = QObject::tr( "Unable to translate spatial operator: at least one must refer to geometry." );
return QDomElement();
}
QDomElement otherGeomElem;
// the other node must be a geometry constructor
if ( otherNode->nodeType() != QgsExpressionNode::ntFunction )
{
mErrorMessage = QObject::tr( "spatial operator: the other operator must be a geometry constructor function" );
return QDomElement();
}
const QgsExpressionNodeFunction *otherFn = static_cast<const QgsExpressionNodeFunction *>( otherNode );
QgsExpressionFunction *otherFnDef = QgsExpression::Functions()[otherFn->fnIndex()];
if ( otherFnDef->name() == QLatin1String( "geom_from_wkt" ) )
{
QgsExpressionNode *firstFnArg = otherFn->args()->list()[0];
if ( firstFnArg->nodeType() != QgsExpressionNode::ntLiteral )
{
mErrorMessage = QObject::tr( "geom_from_wkt: argument must be string literal" );
return QDomElement();
}
QString wkt = static_cast<const QgsExpressionNodeLiteral *>( firstFnArg )->value().toString();
QgsGeometry geom = QgsGeometry::fromWkt( wkt );
otherGeomElem = QgsOgcUtils::geometryToGML( geom, mDoc, mGMLVersion, mSrsName, mInvertAxisOrientation,
QStringLiteral( "qgis_id_geom_%1" ).arg( mGeomId ) );
mGeomId ++;
}
else if ( otherFnDef->name() == QLatin1String( "geom_from_gml" ) )
{
QgsExpressionNode *firstFnArg = otherFn->args()->list()[0];
if ( firstFnArg->nodeType() != QgsExpressionNode::ntLiteral )
{
mErrorMessage = QObject::tr( "geom_from_gml: argument must be string literal" );
return QDomElement();
}
QDomDocument geomDoc;
QString gml = static_cast<const QgsExpressionNodeLiteral *>( firstFnArg )->value().toString();
if ( !geomDoc.setContent( gml, true ) )
{
mErrorMessage = QObject::tr( "geom_from_gml: unable to parse XML" );
return QDomElement();
}
QDomNode geomNode = mDoc.importNode( geomDoc.documentElement(), true );
otherGeomElem = geomNode.toElement();
}
else
{
mErrorMessage = QObject::tr( "spatial operator: unknown geometry constructor function" );
return QDomElement();
}
mGMLUsed = true;
QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":" + tagNameForSpatialOperator( fd->name() ) );
QDomElement geomProperty = mDoc.createElement( mFilterPrefix + ":" + mPropertyName );
geomProperty.appendChild( mDoc.createTextNode( mGeometryName ) );
funcElem.appendChild( geomProperty );
funcElem.appendChild( otherGeomElem );
return funcElem;
}
if ( fd->isStatic( node, expression, context ) )
{
QVariant result = fd->run( node->args(), context, expression, node );
QgsExpressionNodeLiteral literal( result );
return expressionLiteralToOgcFilter( &literal, expression, context );
}
if ( fd->params() == 0 )
{
mErrorMessage = QObject::tr( "Special columns/constants are not supported." );
return QDomElement();
}
// this is somehow wrong - we are just hoping that the other side supports the same functions as we do...
QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":Function" );
funcElem.setAttribute( QStringLiteral( "name" ), fd->name() );
const auto constList = node->args()->list();
for ( QgsExpressionNode *n : constList )
{
QDomElement childElem = expressionNodeToOgcFilter( n, expression, context );
if ( !mErrorMessage.isEmpty() )
return QDomElement();
funcElem.appendChild( childElem );
}
return funcElem;
}
//
QgsOgcUtilsSQLStatementToFilter::QgsOgcUtilsSQLStatementToFilter( QDomDocument &doc,
QgsOgcUtils::GMLVersion gmlVersion,
QgsOgcUtils::FilterVersion filterVersion,
const QList<QgsOgcUtils::LayerProperties> &layerProperties,
bool honourAxisOrientation,
bool invertAxisOrientation,
const QMap< QString, QString> &mapUnprefixedTypenameToPrefixedTypename )
: mDoc( doc )
, mGMLUsed( false )
, mGMLVersion( gmlVersion )
, mFilterVersion( filterVersion )
, mLayerProperties( layerProperties )
, mHonourAxisOrientation( honourAxisOrientation )
, mInvertAxisOrientation( invertAxisOrientation )
, mFilterPrefix( ( filterVersion == QgsOgcUtils::FILTER_FES_2_0 ) ? "fes" : "ogc" )
, mPropertyName( ( filterVersion == QgsOgcUtils::FILTER_FES_2_0 ) ? "ValueReference" : "PropertyName" )
, mGeomId( 1 )
, mMapUnprefixedTypenameToPrefixedTypename( mapUnprefixedTypenameToPrefixedTypename )
{
}
QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::Node *node )
{
switch ( node->nodeType() )
{
case QgsSQLStatement::ntUnaryOperator:
return toOgcFilter( static_cast<const QgsSQLStatement::NodeUnaryOperator *>( node ) );
case QgsSQLStatement::ntBinaryOperator:
return toOgcFilter( static_cast<const QgsSQLStatement::NodeBinaryOperator *>( node ) );
case QgsSQLStatement::ntInOperator:
return toOgcFilter( static_cast<const QgsSQLStatement::NodeInOperator *>( node ) );
case QgsSQLStatement::ntBetweenOperator:
return toOgcFilter( static_cast<const QgsSQLStatement::NodeBetweenOperator *>( node ) );
case QgsSQLStatement::ntFunction:
return toOgcFilter( static_cast<const QgsSQLStatement::NodeFunction *>( node ) );
case QgsSQLStatement::ntLiteral:
return toOgcFilter( static_cast<const QgsSQLStatement::NodeLiteral *>( node ) );
case QgsSQLStatement::ntColumnRef:
return toOgcFilter( static_cast<const QgsSQLStatement::NodeColumnRef *>( node ) );
case QgsSQLStatement::ntSelect:
return toOgcFilter( static_cast<const QgsSQLStatement::NodeSelect *>( node ) );
default:
mErrorMessage = QObject::tr( "Node type not supported: %1" ).arg( node->nodeType() );
return QDomElement();
}
}
QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeUnaryOperator *node )
{
QDomElement operandElem = toOgcFilter( node->operand() );
if ( !mErrorMessage.isEmpty() )
return QDomElement();
QDomElement uoElem;
switch ( node->op() )
{
case QgsSQLStatement::uoMinus:
uoElem = mDoc.createElement( mFilterPrefix + ":Literal" );
if ( node->operand()->nodeType() == QgsSQLStatement::ntLiteral )
{
// operand expression already created a Literal node:
// take the literal value, prepend - and remove old literal node
uoElem.appendChild( mDoc.createTextNode( "-" + operandElem.text() ) );
mDoc.removeChild( operandElem );
}
else
{
mErrorMessage = QObject::tr( "This use of unary operator not implemented yet" );
return QDomElement();
}
break;
case QgsSQLStatement::uoNot:
uoElem = mDoc.createElement( mFilterPrefix + ":Not" );
uoElem.appendChild( operandElem );
break;
default:
mErrorMessage = QObject::tr( "Unary operator %1 not implemented yet" ).arg( QgsSQLStatement::UNARY_OPERATOR_TEXT[node->op()] );
return QDomElement();
}
return uoElem;
}
QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeBinaryOperator *node )
{
QDomElement leftElem = toOgcFilter( node->opLeft() );
if ( !mErrorMessage.isEmpty() )
return QDomElement();
QgsSQLStatement::BinaryOperator op = node->op();
// before right operator is parsed: to allow NULL handling
if ( op == QgsSQLStatement::boIs || op == QgsSQLStatement::boIsNot )
{
if ( node->opRight()->nodeType() == QgsSQLStatement::ntLiteral )
{
const QgsSQLStatement::NodeLiteral *rightLit = static_cast<const QgsSQLStatement::NodeLiteral *>( node->opRight() );
if ( rightLit->value().isNull() )
{
QDomElement elem = mDoc.createElement( mFilterPrefix + ":PropertyIsNull" );
elem.appendChild( leftElem );
if ( op == QgsSQLStatement::boIsNot )
{
QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" );
notElem.appendChild( elem );
return notElem;
}
return elem;
}
// continue with equal / not equal operator once the null case is handled
op = ( op == QgsSQLStatement::boIs ? QgsSQLStatement::boEQ : QgsSQLStatement::boNE );
}
}
QDomElement rightElem = toOgcFilter( node->opRight() );
if ( !mErrorMessage.isEmpty() )
return QDomElement();
QString opText;
if ( op == QgsSQLStatement::boOr )
opText = QStringLiteral( "Or" );
else if ( op == QgsSQLStatement::boAnd )
opText = QStringLiteral( "And" );
else if ( op == QgsSQLStatement::boEQ )
opText = QStringLiteral( "PropertyIsEqualTo" );
else if ( op == QgsSQLStatement::boNE )
opText = QStringLiteral( "PropertyIsNotEqualTo" );
else if ( op == QgsSQLStatement::boLE )
opText = QStringLiteral( "PropertyIsLessThanOrEqualTo" );
else if ( op == QgsSQLStatement::boGE )
opText = QStringLiteral( "PropertyIsGreaterThanOrEqualTo" );
else if ( op == QgsSQLStatement::boLT )
opText = QStringLiteral( "PropertyIsLessThan" );
else if ( op == QgsSQLStatement::boGT )
opText = QStringLiteral( "PropertyIsGreaterThan" );
else if ( op == QgsSQLStatement::boLike )
opText = QStringLiteral( "PropertyIsLike" );
else if ( op == QgsSQLStatement::boILike )
opText = QStringLiteral( "PropertyIsLike" );
if ( opText.isEmpty() )
{
// not implemented binary operators
mErrorMessage = QObject::tr( "Binary operator %1 not implemented yet" ).arg( QgsSQLStatement::BINARY_OPERATOR_TEXT[op] );
return QDomElement();
}
QDomElement boElem = mDoc.createElement( mFilterPrefix + ":" + opText );
if ( op == QgsSQLStatement::boLike || op == QgsSQLStatement::boILike )
{
if ( op == QgsSQLStatement::boILike )
boElem.setAttribute( QStringLiteral( "matchCase" ), QStringLiteral( "false" ) );
// setup wildCards to <ogc:PropertyIsLike>
boElem.setAttribute( QStringLiteral( "wildCard" ), QStringLiteral( "%" ) );
boElem.setAttribute( QStringLiteral( "singleChar" ), QStringLiteral( "_" ) );
if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 )
boElem.setAttribute( QStringLiteral( "escape" ), QStringLiteral( "\\" ) );
else
boElem.setAttribute( QStringLiteral( "escapeChar" ), QStringLiteral( "\\" ) );
}
boElem.appendChild( leftElem );
boElem.appendChild( rightElem );
return boElem;
}
QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeLiteral *node )
{
QString value;
switch ( node->value().type() )
{
case QVariant::Int:
value = QString::number( node->value().toInt() );
break;
case QVariant::LongLong:
value = QString::number( node->value().toLongLong() );
break;
case QVariant::Double:
value = qgsDoubleToString( node->value().toDouble() );
break;
case QVariant::String:
value = node->value().toString();
break;
default:
mErrorMessage = QObject::tr( "Literal type not supported: %1" ).arg( node->value().type() );
return QDomElement();
}
QDomElement litElem = mDoc.createElement( mFilterPrefix + ":Literal" );
litElem.appendChild( mDoc.createTextNode( value ) );
return litElem;
}
QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeColumnRef *node )
{
QDomElement propElem = mDoc.createElement( mFilterPrefix + ":" + mPropertyName );
if ( node->tableName().isEmpty() || mLayerProperties.size() == 1 )
propElem.appendChild( mDoc.createTextNode( node->name() ) );
else
{
QString tableName( mMapTableAliasToNames[node->tableName()] );
if ( mMapUnprefixedTypenameToPrefixedTypename.contains( tableName ) )
tableName = mMapUnprefixedTypenameToPrefixedTypename[tableName];
propElem.appendChild( mDoc.createTextNode( tableName + "/" + node->name() ) );
}
return propElem;
}
QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeInOperator *node )
{
if ( node->list()->list().size() == 1 )
return toOgcFilter( node->list()->list()[0] );
QDomElement orElem = mDoc.createElement( mFilterPrefix + ":Or" );
QDomElement leftNode = toOgcFilter( node->node() );
const auto constList = node->list()->list();
for ( QgsSQLStatement::Node *n : constList )
{
QDomElement listNode = toOgcFilter( n );
if ( !mErrorMessage.isEmpty() )
return QDomElement();
QDomElement eqElem = mDoc.createElement( mFilterPrefix + ":PropertyIsEqualTo" );
eqElem.appendChild( leftNode.cloneNode() );
eqElem.appendChild( listNode );
orElem.appendChild( eqElem );
}
if ( node->isNotIn() )
{
QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" );
notElem.appendChild( orElem );
return notElem;
}
return orElem;
}
QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeBetweenOperator *node )
{
QDomElement elem = mDoc.createElement( mFilterPrefix + ":PropertyIsBetween" );
elem.appendChild( toOgcFilter( node->node() ) );
QDomElement lowerBoundary = mDoc.createElement( mFilterPrefix + ":LowerBoundary" );
lowerBoundary.appendChild( toOgcFilter( node->minVal() ) );
elem.appendChild( lowerBoundary );
QDomElement upperBoundary = mDoc.createElement( mFilterPrefix + ":UpperBoundary" );
upperBoundary.appendChild( toOgcFilter( node->maxVal() ) );
elem.appendChild( upperBoundary );
if ( node->isNotBetween() )
{
QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" );
notElem.appendChild( elem );
return notElem;
}
return elem;
}
static QString mapBinarySpatialToOgc( const QString &name )
{
QString nameCompare( name );
if ( name.size() > 3 && name.midRef( 0, 3 ).compare( QLatin1String( "ST_" ), Qt::CaseInsensitive ) == 0 )
nameCompare = name.mid( 3 );
QStringList spatialOps;
spatialOps << QStringLiteral( "BBOX" ) << QStringLiteral( "Intersects" ) << QStringLiteral( "Contains" ) << QStringLiteral( "Crosses" ) << QStringLiteral( "Equals" )
<< QStringLiteral( "Disjoint" ) << QStringLiteral( "Overlaps" ) << QStringLiteral( "Touches" ) << QStringLiteral( "Within" );
const auto constSpatialOps = spatialOps;
for ( QString op : constSpatialOps )
{
if ( nameCompare.compare( op, Qt::CaseInsensitive ) == 0 )
return op;
}
return QString();
}
static QString mapTernarySpatialToOgc( const QString &name )
{
QString nameCompare( name );
if ( name.size() > 3 && name.midRef( 0, 3 ).compare( QLatin1String( "ST_" ), Qt::CaseInsensitive ) == 0 )
nameCompare = name.mid( 3 );
if ( nameCompare.compare( QLatin1String( "DWithin" ), Qt::CaseInsensitive ) == 0 )
return QStringLiteral( "DWithin" );
if ( nameCompare.compare( QLatin1String( "Beyond" ), Qt::CaseInsensitive ) == 0 )
return QStringLiteral( "Beyond" );
return QString();
}
QString QgsOgcUtilsSQLStatementToFilter::getGeometryColumnSRSName( const QgsSQLStatement::Node *node )
{
if ( node->nodeType() != QgsSQLStatement::ntColumnRef )
return QString();
const QgsSQLStatement::NodeColumnRef *col = static_cast<const QgsSQLStatement::NodeColumnRef *>( node );
if ( !col->tableName().isEmpty() )
{
const auto constMLayerProperties = mLayerProperties;
for ( QgsOgcUtils::LayerProperties prop : constMLayerProperties )
{
if ( prop.mName.compare( mMapTableAliasToNames[col->tableName()], Qt::CaseInsensitive ) == 0 &&
prop.mGeometryAttribute.compare( col->name(), Qt::CaseInsensitive ) == 0 )
{
return prop.mSRSName;
}
}
}
if ( !mLayerProperties.empty() &&
mLayerProperties.at( 0 ).mGeometryAttribute.compare( col->name(), Qt::CaseInsensitive ) == 0 )
{
return mLayerProperties.at( 0 ).mSRSName;
}
return QString();
}
bool QgsOgcUtilsSQLStatementToFilter::processSRSName( const QgsSQLStatement::NodeFunction *mainNode,
QList<QgsSQLStatement::Node *> args,
bool lastArgIsSRSName,
QString &srsName,
bool &axisInversion )
{
srsName = mCurrentSRSName;
axisInversion = mInvertAxisOrientation;
if ( lastArgIsSRSName )
{
QgsSQLStatement::Node *lastArg = args[ args.size() - 1 ];
if ( lastArg->nodeType() != QgsSQLStatement::ntLiteral )
{
mErrorMessage = QObject::tr( "%1: Last argument must be string or integer literal" ).arg( mainNode->name() );
return false;
}
const QgsSQLStatement::NodeLiteral *lit = static_cast<const QgsSQLStatement::NodeLiteral *>( lastArg );
if ( lit->value().type() == QVariant::Int )
{
if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 )
{
srsName = "EPSG:" + QString::number( lit->value().toInt() );
}
else
{
srsName = "urn:ogc:def:crs:EPSG::" + QString::number( lit->value().toInt() );
}
}
else
{
srsName = lit->value().toString();
if ( srsName.startsWith( QLatin1String( "EPSG:" ), Qt::CaseInsensitive ) )
return true;
}
}
QgsCoordinateReferenceSystem crs;
if ( !srsName.isEmpty() )
crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( srsName );
if ( crs.isValid() )
{
if ( mHonourAxisOrientation && crs.hasAxisInverted() )
{
axisInversion = !axisInversion;
}
}
return true;
}
QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeFunction *node )
{
// ST_GeometryFromText
if ( node->name().compare( QLatin1String( "ST_GeometryFromText" ), Qt::CaseInsensitive ) == 0 )
{
QList<QgsSQLStatement::Node *> args = node->args()->list();
if ( args.size() != 1 && args.size() != 2 )
{
mErrorMessage = QObject::tr( "Function %1 should have 1 or 2 arguments" ).arg( node->name() );
return QDomElement();
}
QgsSQLStatement::Node *firstFnArg = args[0];
if ( firstFnArg->nodeType() != QgsSQLStatement::ntLiteral )
{
mErrorMessage = QObject::tr( "%1: First argument must be string literal" ).arg( node->name() );
return QDomElement();
}
QString srsName;
bool axisInversion;
if ( ! processSRSName( node, args, args.size() == 2, srsName, axisInversion ) )
{
return QDomElement();
}
QString wkt = static_cast<const QgsSQLStatement::NodeLiteral *>( firstFnArg )->value().toString();
QgsGeometry geom = QgsGeometry::fromWkt( wkt );
QDomElement geomElem = QgsOgcUtils::geometryToGML( geom, mDoc, mGMLVersion, srsName, axisInversion,
QStringLiteral( "qgis_id_geom_%1" ).arg( mGeomId ) );
mGeomId ++;
if ( geomElem.isNull() )
{
mErrorMessage = QObject::tr( "%1: invalid WKT" ).arg( node->name() );
return QDomElement();
}
mGMLUsed = true;
return geomElem;
}
// ST_MakeEnvelope
if ( node->name().compare( QLatin1String( "ST_MakeEnvelope" ), Qt::CaseInsensitive ) == 0 )
{
QList<QgsSQLStatement::Node *> args = node->args()->list();
if ( args.size() != 4 && args.size() != 5 )
{
mErrorMessage = QObject::tr( "Function %1 should have 4 or 5 arguments" ).arg( node->name() );
return QDomElement();
}
QgsRectangle rect;
for ( int i = 0; i < 4; i++ )
{
QgsSQLStatement::Node *arg = args[i];
if ( arg->nodeType() != QgsSQLStatement::ntLiteral )
{
mErrorMessage = QObject::tr( "%1: Argument %2 must be numeric literal" ).arg( node->name() ).arg( i + 1 );
return QDomElement();
}
const QgsSQLStatement::NodeLiteral *lit = static_cast<const QgsSQLStatement::NodeLiteral *>( arg );
double val = 0.0;
if ( lit->value().type() == QVariant::Int )
val = lit->value().toInt();
else if ( lit->value().type() == QVariant::LongLong )
val = lit->value().toLongLong();
else if ( lit->value().type() == QVariant::Double )
val = lit->value().toDouble();
else
{
mErrorMessage = QObject::tr( "%1 Argument %2 must be numeric literal" ).arg( node->name() ).arg( i + 1 );
return QDomElement();
}
if ( i == 0 )
rect.setXMinimum( val );
else if ( i == 1 )
rect.setYMinimum( val );
else if ( i == 2 )
rect.setXMaximum( val );
else
rect.setYMaximum( val );
}
QString srsName;
bool axisInversion;
if ( ! processSRSName( node, args, args.size() == 5, srsName, axisInversion ) )
{
return QDomElement();
}
mGMLUsed = true;
return ( mGMLVersion == QgsOgcUtils::GML_2_1_2 ) ?
QgsOgcUtils::rectangleToGMLBox( &rect, mDoc, srsName, axisInversion, 15 ) :
QgsOgcUtils::rectangleToGMLEnvelope( &rect, mDoc, srsName, axisInversion, 15 );
}
// ST_GeomFromGML
if ( node->name().compare( QLatin1String( "ST_GeomFromGML" ), Qt::CaseInsensitive ) == 0 )
{
QList<QgsSQLStatement::Node *> args = node->args()->list();
if ( args.size() != 1 )
{
mErrorMessage = QObject::tr( "Function %1 should have 1 argument" ).arg( node->name() );
return QDomElement();
}
QgsSQLStatement::Node *firstFnArg = args[0];
if ( firstFnArg->nodeType() != QgsSQLStatement::ntLiteral )
{
mErrorMessage = QObject::tr( "%1: Argument must be string literal" ).arg( node->name() );
return QDomElement();
}
QDomDocument geomDoc;
QString gml = static_cast<const QgsSQLStatement::NodeLiteral *>( firstFnArg )->value().toString();
if ( !geomDoc.setContent( gml, true ) )
{
mErrorMessage = QObject::tr( "ST_GeomFromGML: unable to parse XML" );
return QDomElement();
}
QDomNode geomNode = mDoc.importNode( geomDoc.documentElement(), true );
mGMLUsed = true;
return geomNode.toElement();
}
// Binary geometry operators
QString ogcName( mapBinarySpatialToOgc( node->name() ) );
if ( !ogcName.isEmpty() )
{
QList<QgsSQLStatement::Node *> args = node->args()->list();
if ( args.size() != 2 )
{
mErrorMessage = QObject::tr( "Function %1 should have 2 arguments" ).arg( node->name() );
return QDomElement();
}
for ( int i = 0; i < 2; i ++ )
{
if ( args[i]->nodeType() == QgsSQLStatement::ntFunction &&
( static_cast<const QgsSQLStatement::NodeFunction *>( args[i] )->name().compare( QLatin1String( "ST_GeometryFromText" ), Qt::CaseInsensitive ) == 0 ||
static_cast<const QgsSQLStatement::NodeFunction *>( args[i] )->name().compare( QLatin1String( "ST_MakeEnvelope" ), Qt::CaseInsensitive ) == 0 ) )
{
mCurrentSRSName = getGeometryColumnSRSName( args[1 - i] );
break;
}
}
//if( ogcName == "Intersects" && mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 )
// ogcName = "Intersect";
QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":" + ogcName );
const auto constArgs = args;
for ( QgsSQLStatement::Node *n : constArgs )
{
QDomElement childElem = toOgcFilter( n );
if ( !mErrorMessage.isEmpty() )
{
mCurrentSRSName.clear();
return QDomElement();
}
funcElem.appendChild( childElem );
}
mCurrentSRSName.clear();
return funcElem;
}
ogcName = mapTernarySpatialToOgc( node->name() );
if ( !ogcName.isEmpty() )
{
QList<QgsSQLStatement::Node *> args = node->args()->list();
if ( args.size() != 3 )
{
mErrorMessage = QObject::tr( "Function %1 should have 3 arguments" ).arg( node->name() );
return QDomElement();
}
for ( int i = 0; i < 2; i ++ )
{
if ( args[i]->nodeType() == QgsSQLStatement::ntFunction &&
( static_cast<const QgsSQLStatement::NodeFunction *>( args[i] )->name().compare( QLatin1String( "ST_GeometryFromText" ), Qt::CaseInsensitive ) == 0 ||
static_cast<const QgsSQLStatement::NodeFunction *>( args[i] )->name().compare( QLatin1String( "ST_MakeEnvelope" ), Qt::CaseInsensitive ) == 0 ) )
{
mCurrentSRSName = getGeometryColumnSRSName( args[1 - i] );
break;
}
}
QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":" + node->name().mid( 3 ) );
for ( int i = 0; i < 2; i++ )
{
QDomElement childElem = toOgcFilter( args[i] );
if ( !mErrorMessage.isEmpty() )
{
mCurrentSRSName.clear();
return QDomElement();
}
funcElem.appendChild( childElem );
}
mCurrentSRSName.clear();
QgsSQLStatement::Node *distanceNode = args[2];
if ( distanceNode->nodeType() != QgsSQLStatement::ntLiteral )
{
mErrorMessage = QObject::tr( "Function %1 3rd argument should be a numeric value or a string made of a numeric value followed by a string" ).arg( node->name() );
return QDomElement();
}
const QgsSQLStatement::NodeLiteral *lit = static_cast<const QgsSQLStatement::NodeLiteral *>( distanceNode );
if ( lit->value().isNull() )
{
mErrorMessage = QObject::tr( "Function %1 3rd argument should be a numeric value or a string made of a numeric value followed by a string" ).arg( node->name() );
return QDomElement();
}
QString distance;
QString unit( QStringLiteral( "m" ) );
switch ( lit->value().type() )
{
case QVariant::Int:
distance = QString::number( lit->value().toInt() );
break;
case QVariant::LongLong:
distance = QString::number( lit->value().toLongLong() );
break;
case QVariant::Double:
distance = qgsDoubleToString( lit->value().toDouble() );
break;
case QVariant::String:
{
distance = lit->value().toString();
for ( int i = 0; i < distance.size(); i++ )
{
if ( !( ( distance[i] >= '0' && distance[i] <= '9' ) || distance[i] == '-' || distance[i] == '.' || distance[i] == 'e' || distance[i] == 'E' ) )
{
unit = distance.mid( i ).trimmed();
distance = distance.mid( 0, i );
break;
}
}
break;
}
default:
mErrorMessage = QObject::tr( "Literal type not supported: %1" ).arg( lit->value().type() );
return QDomElement();
}
QDomElement distanceElem = mDoc.createElement( mFilterPrefix + ":Distance" );
if ( mFilterVersion == QgsOgcUtils::FILTER_FES_2_0 )
distanceElem.setAttribute( QStringLiteral( "uom" ), unit );
else
distanceElem.setAttribute( QStringLiteral( "unit" ), unit );
distanceElem.appendChild( mDoc.createTextNode( distance ) );
funcElem.appendChild( distanceElem );
return funcElem;
}
// Other function
QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":Function" );
funcElem.setAttribute( QStringLiteral( "name" ), node->name() );
const auto constList = node->args()->list();
for ( QgsSQLStatement::Node *n : constList )
{
QDomElement childElem = toOgcFilter( n );
if ( !mErrorMessage.isEmpty() )
return QDomElement();
funcElem.appendChild( childElem );
}
return funcElem;
}
QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeJoin *node,
const QString &leftTable )
{
QgsSQLStatement::Node *onExpr = node->onExpr();
if ( onExpr )
{
return toOgcFilter( onExpr );
}
QList<QDomElement> listElem;
const auto constUsingColumns = node->usingColumns();
for ( const QString &columnName : constUsingColumns )
{
QDomElement eqElem = mDoc.createElement( mFilterPrefix + ":PropertyIsEqualTo" );
QDomElement propElem1 = mDoc.createElement( mFilterPrefix + ":" + mPropertyName );
propElem1.appendChild( mDoc.createTextNode( leftTable + "/" + columnName ) );
eqElem.appendChild( propElem1 );
QDomElement propElem2 = mDoc.createElement( mFilterPrefix + ":" + mPropertyName );
propElem2.appendChild( mDoc.createTextNode( node->tableDef()->name() + "/" + columnName ) );
eqElem.appendChild( propElem2 );
listElem.append( eqElem );
}
if ( listElem.size() == 1 )
{
return listElem[0];
}
else if ( listElem.size() > 1 )
{
QDomElement andElem = mDoc.createElement( mFilterPrefix + ":And" );
const auto constListElem = listElem;
for ( const QDomElement &elem : constListElem )
{
andElem.appendChild( elem );
}
return andElem;
}
return QDomElement();
}
void QgsOgcUtilsSQLStatementToFilter::visit( const QgsSQLStatement::NodeTableDef *node )
{
if ( node->alias().isEmpty() )
{
mMapTableAliasToNames[ node->name()] = node->name();
}
else
{
mMapTableAliasToNames[ node->alias()] = node->name();
}
}
QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeSelect *node )
{
QList<QDomElement> listElem;
if ( mFilterVersion != QgsOgcUtils::FILTER_FES_2_0 &&
( node->tables().size() != 1 || !node->joins().empty() ) )
{
mErrorMessage = QObject::tr( "Joins are only supported with WFS 2.0" );
return QDomElement();
}
// Register all table name aliases
const auto constTables = node->tables();
for ( QgsSQLStatement::NodeTableDef *table : constTables )
{
visit( table );
}
const auto constJoins = node->joins();
for ( QgsSQLStatement::NodeJoin *join : constJoins )
{
visit( join->tableDef() );
}
// Process JOIN conditions
QList< QgsSQLStatement::NodeTableDef *> nodeTables = node->tables();
QString leftTable = nodeTables.at( nodeTables.length() - 1 )->name();
for ( QgsSQLStatement::NodeJoin *join : constJoins )
{
QDomElement joinElem = toOgcFilter( join, leftTable );
if ( !mErrorMessage.isEmpty() )
return QDomElement();
listElem.append( joinElem );
leftTable = join->tableDef()->name();
}
// Process WHERE conditions
if ( node->where() )
{
QDomElement whereElem = toOgcFilter( node->where() );
if ( !mErrorMessage.isEmpty() )
return QDomElement();
listElem.append( whereElem );
}
// Concatenate all conditions
if ( listElem.size() == 1 )
{
return listElem[0];
}
else if ( listElem.size() > 1 )
{
QDomElement andElem = mDoc.createElement( mFilterPrefix + ":And" );
const auto constListElem = listElem;
for ( const QDomElement &elem : constListElem )
{
andElem.appendChild( elem );
}
return andElem;
}
return QDomElement();
}
QgsOgcUtilsExpressionFromFilter::QgsOgcUtilsExpressionFromFilter( const QgsOgcUtils::FilterVersion version, const QgsVectorLayer *layer )
: mLayer( layer )
{
mPropertyName = QStringLiteral( "PropertyName" );
mPrefix = QStringLiteral( "ogc" );
if ( version == QgsOgcUtils::FILTER_FES_2_0 )
{
mPropertyName = QStringLiteral( "ValueReference" );
mPrefix = QStringLiteral( "fes" );
}
}
QgsExpressionNode *QgsOgcUtilsExpressionFromFilter::nodeFromOgcFilter( const QDomElement &element )
{
if ( element.isNull() )
return nullptr;
// check for binary operators
if ( isBinaryOperator( element.tagName() ) )
{
return nodeBinaryOperatorFromOgcFilter( element );
}
// check for spatial operators
if ( isSpatialOperator( element.tagName() ) )
{
return nodeSpatialOperatorFromOgcFilter( element );
}
// check for other OGC operators, convert them to expressions
if ( element.tagName() == QLatin1String( "Not" ) )
{
return nodeNotFromOgcFilter( element );
}
else if ( element.tagName() == QLatin1String( "PropertyIsNull" ) )
{
return nodePropertyIsNullFromOgcFilter( element );
}
else if ( element.tagName() == QLatin1String( "Literal" ) )
{
return nodeLiteralFromOgcFilter( element );
}
else if ( element.tagName() == QLatin1String( "Function" ) )
{
return nodeFunctionFromOgcFilter( element );
}
else if ( element.tagName() == mPropertyName )
{
return nodeColumnRefFromOgcFilter( element );
}
else if ( element.tagName() == QLatin1String( "PropertyIsBetween" ) )
{
return nodeIsBetweenFromOgcFilter( element );
}
mErrorMessage += QObject::tr( "unable to convert '%1' element to a valid expression: it is not supported yet or it has invalid arguments" ).arg( element.tagName() );
return nullptr;
}
QgsExpressionNodeBinaryOperator *QgsOgcUtilsExpressionFromFilter::nodeBinaryOperatorFromOgcFilter( const QDomElement &element )
{
if ( element.isNull() )
return nullptr;
int op = binaryOperatorFromTagName( element.tagName() );
if ( op < 0 )
{
mErrorMessage = QObject::tr( "'%1' binary operator not supported." ).arg( element.tagName() );
return nullptr;
}
if ( op == QgsExpressionNodeBinaryOperator::boLike && element.hasAttribute( QStringLiteral( "matchCase" ) ) && element.attribute( QStringLiteral( "matchCase" ) ) == QLatin1String( "false" ) )
{
op = QgsExpressionNodeBinaryOperator::boILike;
}
QDomElement operandElem = element.firstChildElement();
std::unique_ptr<QgsExpressionNode> expr( nodeFromOgcFilter( operandElem ) );
if ( !expr )
{
mErrorMessage = QObject::tr( "invalid left operand for '%1' binary operator" ).arg( element.tagName() );
return nullptr;
}
std::unique_ptr<QgsExpressionNode> leftOp( expr->clone() );
for ( operandElem = operandElem.nextSiblingElement(); !operandElem.isNull(); operandElem = operandElem.nextSiblingElement() )
{
std::unique_ptr<QgsExpressionNode> opRight( nodeFromOgcFilter( operandElem ) );
if ( !opRight )
{
mErrorMessage = QObject::tr( "invalid right operand for '%1' binary operator" ).arg( element.tagName() );
return nullptr;
}
if ( op == QgsExpressionNodeBinaryOperator::boLike || op == QgsExpressionNodeBinaryOperator::boILike )
{
QString wildCard;
if ( element.hasAttribute( QStringLiteral( "wildCard" ) ) )
{
wildCard = element.attribute( QStringLiteral( "wildCard" ) );
}
QString singleChar;
if ( element.hasAttribute( QStringLiteral( "singleChar" ) ) )
{
singleChar = element.attribute( QStringLiteral( "singleChar" ) );
}
QString escape = QStringLiteral( "\\" );
if ( element.hasAttribute( QStringLiteral( "escape" ) ) )
{
escape = element.attribute( QStringLiteral( "escape" ) );
}
if ( element.hasAttribute( QStringLiteral( "escapeChar" ) ) )
{
escape = element.attribute( QStringLiteral( "escapeChar" ) );
}
// replace
QString oprValue = static_cast<const QgsExpressionNodeLiteral *>( opRight.get() )->value().toString();
if ( !wildCard.isEmpty() && wildCard != QLatin1String( "%" ) )
{
oprValue.replace( '%', QLatin1String( "\\%" ) );
if ( oprValue.startsWith( wildCard ) )
{
oprValue.replace( 0, 1, QStringLiteral( "%" ) );
}
QRegExp rx( "[^" + QRegExp::escape( escape ) + "](" + QRegExp::escape( wildCard ) + ")" );
int pos = 0;
while ( ( pos = rx.indexIn( oprValue, pos ) ) != -1 )
{
oprValue.replace( pos + 1, 1, QStringLiteral( "%" ) );
pos += 1;
}
oprValue.replace( escape + wildCard, wildCard );
}
if ( !singleChar.isEmpty() && singleChar != QLatin1String( "_" ) )
{
oprValue.replace( '_', QLatin1String( "\\_" ) );
if ( oprValue.startsWith( singleChar ) )
{
oprValue.replace( 0, 1, QStringLiteral( "_" ) );
}
QRegExp rx( "[^" + QRegExp::escape( escape ) + "](" + QRegExp::escape( singleChar ) + ")" );
int pos = 0;
while ( ( pos = rx.indexIn( oprValue, pos ) ) != -1 )
{
oprValue.replace( pos + 1, 1, QStringLiteral( "_" ) );
pos += 1;
}
oprValue.replace( escape + singleChar, singleChar );
}
if ( !escape.isEmpty() && escape != QLatin1String( "\\" ) )
{
oprValue.replace( escape + escape, escape );
}
opRight.reset( new QgsExpressionNodeLiteral( oprValue ) );
}
expr.reset( new QgsExpressionNodeBinaryOperator( static_cast< QgsExpressionNodeBinaryOperator::BinaryOperator >( op ), expr.release(), opRight.release() ) );
}
if ( expr == leftOp )
{
mErrorMessage = QObject::tr( "only one operand for '%1' binary operator" ).arg( element.tagName() );
return nullptr;
}
return dynamic_cast< QgsExpressionNodeBinaryOperator * >( expr.release() );
}
QgsExpressionNodeFunction *QgsOgcUtilsExpressionFromFilter::nodeSpatialOperatorFromOgcFilter( const QDomElement &element )
{
// we are exploiting the fact that our function names are the same as the XML tag names
const int opIdx = QgsExpression::functionIndex( element.tagName().toLower() );
std::unique_ptr<QgsExpressionNode::NodeList> gml2Args( new QgsExpressionNode::NodeList() );
QDomElement childElem = element.firstChildElement();
QString gml2Str;
while ( !childElem.isNull() && gml2Str.isEmpty() )
{
if ( childElem.tagName() != mPropertyName )
{
QTextStream gml2Stream( &gml2Str );
childElem.save( gml2Stream, 0 );
}
childElem = childElem.nextSiblingElement();
}
if ( !gml2Str.isEmpty() )
{
gml2Args->append( new QgsExpressionNodeLiteral( QVariant( gml2Str.remove( '\n' ) ) ) );
}
else
{
mErrorMessage = QObject::tr( "No OGC Geometry found" );
return nullptr;
}
std::unique_ptr<QgsExpressionNode::NodeList> opArgs( new QgsExpressionNode::NodeList() );
opArgs->append( new QgsExpressionNodeFunction( QgsExpression::functionIndex( QStringLiteral( "$geometry" ) ), new QgsExpressionNode::NodeList() ) );
opArgs->append( new QgsExpressionNodeFunction( QgsExpression::functionIndex( QStringLiteral( "geomFromGML" ) ), gml2Args.release() ) );
return new QgsExpressionNodeFunction( opIdx, opArgs.release() );
}
QgsExpressionNodeColumnRef *QgsOgcUtilsExpressionFromFilter::nodeColumnRefFromOgcFilter( const QDomElement &element )
{
if ( element.isNull() || element.tagName() != mPropertyName )
{
mErrorMessage = QObject::tr( "%1:PropertyName expected, got %2" ).arg( mPrefix, element.tagName() );
return nullptr;
}
return new QgsExpressionNodeColumnRef( element.firstChild().nodeValue() );
}
QgsExpressionNode *QgsOgcUtilsExpressionFromFilter::nodeLiteralFromOgcFilter( const QDomElement &element )
{
if ( element.isNull() || element.tagName() != QLatin1String( "Literal" ) )
{
mErrorMessage = QObject::tr( "%1:Literal expected, got %2" ).arg( mPrefix, element.tagName() );
return nullptr;
}
std::unique_ptr<QgsExpressionNode> root;
// the literal content can have more children (e.g. CDATA section, text, ...)
QDomNode childNode = element.firstChild();
while ( !childNode.isNull() )
{
std::unique_ptr<QgsExpressionNode> operand;
if ( childNode.nodeType() == QDomNode::ElementNode )
{
// found a element node (e.g. PropertyName), convert it
const QDomElement operandElem = childNode.toElement();
operand.reset( nodeFromOgcFilter( operandElem ) );
if ( !operand )
{
mErrorMessage = QObject::tr( "'%1' is an invalid or not supported content for %2:Literal" ).arg( operandElem.tagName(), mPrefix );
return nullptr;
}
}
else
{
// probably a text/CDATA node
QVariant value = childNode.nodeValue();
bool converted = false;
// try to convert the node content to corresponding field type if possible
if ( mLayer )
{
QDomElement propertyNameElement = element.previousSiblingElement( mPropertyName );
if ( propertyNameElement.isNull() || propertyNameElement.tagName() != mPropertyName )
{
propertyNameElement = element.nextSiblingElement( mPropertyName );
}
if ( !propertyNameElement.isNull() || propertyNameElement.tagName() == mPropertyName )
{
const int fieldIndex = mLayer->fields().indexOf( propertyNameElement.firstChild().nodeValue() );
if ( fieldIndex != -1 )
{
QgsField field = mLayer->fields().field( propertyNameElement.firstChild().nodeValue() );
field.convertCompatible( value );
converted = true;
}
}
}
if ( !converted )
{
// try to convert the node content to number if possible,
// otherwise let's use it as string
bool ok;
const double d = value.toDouble( &ok );
if ( ok )
value = d;
}
operand.reset( new QgsExpressionNodeLiteral( value ) );
if ( !operand )
continue;
}
// use the concat operator to merge the ogc:Literal children
if ( !root )
{
root = std::move( operand );
}
else
{
root.reset( new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boConcat, root.release(), operand.release() ) );
}
childNode = childNode.nextSibling();
}
if ( root )
return root.release();
return nullptr;
}
QgsExpressionNodeUnaryOperator *QgsOgcUtilsExpressionFromFilter::nodeNotFromOgcFilter( const QDomElement &element )
{
if ( element.tagName() != QLatin1String( "Not" ) )
return nullptr;
const QDomElement operandElem = element.firstChildElement();
std::unique_ptr<QgsExpressionNode> operand( nodeFromOgcFilter( operandElem ) );
if ( !operand )
{
mErrorMessage = QObject::tr( "invalid operand for '%1' unary operator" ).arg( element.tagName() );
return nullptr;
}
return new QgsExpressionNodeUnaryOperator( QgsExpressionNodeUnaryOperator::uoNot, operand.release() );
}
QgsExpressionNodeBinaryOperator *QgsOgcUtilsExpressionFromFilter::nodePropertyIsNullFromOgcFilter( const QDomElement &element )
{
// convert ogc:PropertyIsNull to IS operator with NULL right operand
if ( element.tagName() != QLatin1String( "PropertyIsNull" ) )
{
return nullptr;
}
const QDomElement operandElem = element.firstChildElement();
std::unique_ptr<QgsExpressionNode> opLeft( nodeFromOgcFilter( operandElem ) );
if ( !opLeft )
return nullptr;
std::unique_ptr<QgsExpressionNode> opRight( new QgsExpressionNodeLiteral( QVariant() ) );
return new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boIs, opLeft.release(), opRight.release() );
}
QgsExpressionNodeFunction *QgsOgcUtilsExpressionFromFilter::nodeFunctionFromOgcFilter( const QDomElement &element )
{
if ( element.isNull() || element.tagName() != QLatin1String( "Function" ) )
{
mErrorMessage = QObject::tr( "%1:Function expected, got %2" ).arg( mPrefix, element.tagName() );
return nullptr;
}
for ( int i = 0; i < QgsExpression::Functions().size(); i++ )
{
const QgsExpressionFunction *funcDef = QgsExpression::Functions()[i];
if ( element.attribute( QStringLiteral( "name" ) ) != funcDef->name() )
continue;
std::unique_ptr<QgsExpressionNode::NodeList> args( new QgsExpressionNode::NodeList() );
QDomElement operandElem = element.firstChildElement();
while ( !operandElem.isNull() )
{
std::unique_ptr<QgsExpressionNode> op( nodeFromOgcFilter( operandElem ) );
if ( !op )
{
return nullptr;
}
args->append( op.release() );
operandElem = operandElem.nextSiblingElement();
}
return new QgsExpressionNodeFunction( i, args.release() );
}
return nullptr;
}
QgsExpressionNode *QgsOgcUtilsExpressionFromFilter::nodeIsBetweenFromOgcFilter( const QDomElement &element )
{
// <ogc:PropertyIsBetween> encode a Range check
std::unique_ptr<QgsExpressionNode> operand;
std::unique_ptr<QgsExpressionNode> lowerBound;
std::unique_ptr<QgsExpressionNode> upperBound;
QDomElement operandElem = element.firstChildElement();
while ( !operandElem.isNull() )
{
if ( operandElem.tagName() == QLatin1String( "LowerBoundary" ) )
{
QDomElement lowerBoundElem = operandElem.firstChildElement();
lowerBound.reset( nodeFromOgcFilter( lowerBoundElem ) );
}
else if ( operandElem.tagName() == QLatin1String( "UpperBoundary" ) )
{
QDomElement upperBoundElem = operandElem.firstChildElement();
upperBound.reset( nodeFromOgcFilter( upperBoundElem ) );
}
else
{
// <ogc:expression>
operand.reset( nodeFromOgcFilter( operandElem ) );
}
if ( operand && lowerBound && upperBound )
break;
operandElem = operandElem.nextSiblingElement();
}
if ( !operand || !lowerBound || !upperBound )
{
mErrorMessage = QObject::tr( "missing some required sub-elements in %1:PropertyIsBetween" ).arg( mPrefix );
return nullptr;
}
std::unique_ptr<QgsExpressionNode> leOperator( new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boLE, operand->clone(), upperBound.release() ) );
std::unique_ptr<QgsExpressionNode> geOperator( new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boGE, operand.release(), lowerBound.release() ) );
return new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boAnd, geOperator.release(), leOperator.release() );
}
QString QgsOgcUtilsExpressionFromFilter::errorMessage() const
{
return mErrorMessage;
}
| tudorbarascu/QGIS | src/core/qgsogcutils.cpp | C++ | gpl-2.0 | 122,763 |
<?php
/**
*------------------------------------------------------------------------------
* @package T3 Framework for Joomla!
*------------------------------------------------------------------------------
* @copyright Copyright (C) 2004-2013 JoomlArt.com. All Rights Reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @authors JoomlArt, JoomlaBamboo, (contribute to this project at github
* & Google group to become co-author)
* @Google group: https://groups.google.com/forum/#!forum/t3fw
* @Link: http://t3-framework.org
*------------------------------------------------------------------------------
*/
// No direct access
defined('_JEXEC') or die();
/**
* T3Action class
*
* @package T3
*/
class T3Action
{
public static function run ($action) {
if (method_exists('T3Action', $action)) {
$option = preg_replace('/[^A-Z0-9_\.-]/i', '', JFactory::getApplication()->input->getCmd('view'));
if(!defined('JPATH_COMPONENT')){
define('JPATH_COMPONENT', JPATH_BASE . '/components/' . $option);
}
if(!defined('JPATH_COMPONENT_SITE')){
define('JPATH_COMPONENT_SITE', JPATH_SITE . '/components/' . $option);
}
if(!defined('JPATH_COMPONENT_ADMINISTRATOR')){
define('JPATH_COMPONENT_ADMINISTRATOR', JPATH_ADMINISTRATOR . '/components/' . $option);
}
T3Action::$action();
}
exit;
}
public static function lessc () {
$path = JFactory::getApplication()->input->getString ('s');
T3::import ('core/less');
$t3less = new T3Less;
$css = $t3less->getCss($path);
header("Content-Type: text/css");
header("Content-length: ".strlen($css));
echo $css;
}
public static function lesscall(){
T3::import ('core/less');
$result = array();
try{
T3Less::compileAll();
$result['successful'] = JText::_('T3_MSG_COMPILE_SUCCESS');
}catch(Exception $e){
$result['error'] = JText::sprintf('T3_MSG_COMPILE_FAILURE', $e->getMessage());
}
echo json_encode($result);
}
public static function theme(){
JFactory::getLanguage()->load('tpl_' . T3_TEMPLATE, JPATH_SITE);
if(!defined('T3')) {
die(json_encode(array(
'error' => JText::_('T3_MSG_PLUGIN_NOT_READY')
)));
}
$user = JFactory::getUser();
$action = JFactory::getApplication()->input->getCmd('t3task', '');
if ($action != 'thememagic' && !$user->authorise('core.manage', 'com_templates')) {
die(json_encode(array(
'error' => JText::_('T3_MSG_NO_PERMISSION')
)));
}
if(empty($action)){
die(json_encode(array(
'error' => JText::_('T3_MSG_UNKNOW_ACTION')
)));
}
T3::import('admin/theme');
if(method_exists('T3AdminTheme', $action)){
T3AdminTheme::$action(T3_TEMPLATE_PATH);
} else {
die(json_encode(array(
'error' => JText::_('T3_MSG_UNKNOW_ACTION')
)));
}
}
public static function layout(){
self::cloneParam('t3layout');
if(!defined('T3')) {
die(json_encode(array(
'error' => JText::_('T3_MSG_PLUGIN_NOT_READY')
)));
}
$action = JFactory::getApplication()->input->get('t3task', '');
if(empty($action)){
die(json_encode(array(
'error' => JText::_('T3_MSG_UNKNOW_ACTION')
)));
}
if($action != 'display'){
$user = JFactory::getUser();
if (!$user->authorise('core.manage', 'com_templates')) {
die(json_encode(array(
'error' => JText::_('T3_MSG_NO_PERMISSION')
)));
}
}
T3::import('admin/layout');
if(method_exists('T3AdminLayout', $action)){
T3AdminLayout::$action(T3_TEMPLATE_PATH);
} else {
die(json_encode(array(
'error' => JText::_('T3_MSG_UNKNOW_ACTION')
)));
}
}
public static function megamenu() {
self::cloneParam('t3menu');
if(!defined('T3')) {
die(json_encode(array(
'error' => JText::_('T3_MSG_PLUGIN_NOT_READY')
)));
}
$action = JFactory::getApplication()->input->get('t3task', '');
if(empty($action)){
die(json_encode(array(
'error' => JText::_('T3_MSG_UNKNOW_ACTION')
)));
}
if($action != 'display'){
$user = JFactory::getUser();
if (!$user->authorise('core.manage', 'com_templates')) {
die(json_encode(array(
'error' => JText::_('T3_MSG_NO_PERMISSION')
)));
}
}
T3::import('admin/megamenu');
if(method_exists('T3AdminMegamenu', $action)){
T3AdminMegamenu::$action();
exit;
} else {
die(json_encode(array(
'error' => JText::_('T3_MSG_UNKNOW_ACTION')
)));
}
}
public static function module () {
$input = JFactory::getApplication()->input;
$id = $input->getInt ('mid');
$module = null;
if ($id) {
// load module
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('m.id, m.title, m.module, m.position, m.content, m.showtitle, m.params')
->from('#__modules AS m')
->where('m.id = '.$id)
->where('m.published = 1');
$db->setQuery($query);
$module = $db->loadObject ();
}
if (!empty ($module)) {
$style = $input->getCmd ('style', 'T3Xhtml');
$buffer = JModuleHelper::renderModule($module, array('style'=>$style));
// replace relative images url
$base = JURI::base(true).'/';
$protocols = '[a-zA-Z0-9]+:'; //To check for all unknown protocals (a protocol must contain at least one alpahnumeric fillowed by :
$regex = '#(src)="(?!/|' . $protocols . '|\#|\')([^"]*)"#m';
$buffer = preg_replace($regex, "$1=\"$base\$2\"", $buffer);
}
//remove invisibile content, there are more ... but ...
$buffer = preg_replace(array( '@<style[^>]*?>.*?</style>@siu', '@<script[^>]*?.*?</script>@siu'), array('', ''), $buffer);
echo $buffer;
}
//translate param name to new name, from jvalue => to desired param name
public static function cloneParam($param = '', $from = 'jvalue'){
$input = JFactory::getApplication()->input;
if(!empty($param) && $input->getWord($param, '') == ''){
$input->set($param, $input->getCmd($from));
}
}
} | Sophist-UK/Sophist_t3framework | source/plg_system_t3/includes/core/action.php | PHP | gpl-2.0 | 5,926 |
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project https://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* Fighting.
*/
#include "actions/attack.hpp"
#include "actions/advancement.hpp"
#include "actions/vision.hpp"
#include "ai/lua/aspect_advancements.hpp"
#include "formula/callable_objects.hpp"
#include "formula/formula.hpp"
#include "game_config.hpp"
#include "game_data.hpp"
#include "game_events/pump.hpp"
#include "gettext.hpp"
#include "log.hpp"
#include "map/map.hpp"
#include "mouse_handler_base.hpp"
#include "play_controller.hpp"
#include "preferences/game.hpp"
#include "random.hpp"
#include "replay.hpp"
#include "resources.hpp"
#include "statistics.hpp"
#include "synced_checkup.hpp"
#include "synced_user_choice.hpp"
#include "team.hpp"
#include "tod_manager.hpp"
#include "units/abilities.hpp"
#include "units/animation_component.hpp"
#include "units/helper.hpp"
#include "units/filter.hpp"
#include "units/map.hpp"
#include "units/udisplay.hpp"
#include "units/unit.hpp"
#include "whiteboard/manager.hpp"
#include "wml_exception.hpp"
static lg::log_domain log_engine("engine");
#define DBG_NG LOG_STREAM(debug, log_engine)
#define LOG_NG LOG_STREAM(info, log_engine)
#define WRN_NG LOG_STREAM(err, log_engine)
#define ERR_NG LOG_STREAM(err, log_engine)
static lg::log_domain log_attack("engine/attack");
#define DBG_AT LOG_STREAM(debug, log_attack)
#define LOG_AT LOG_STREAM(info, log_attack)
#define WRN_AT LOG_STREAM(err, log_attack)
#define ERR_AT LOG_STREAM(err, log_attack)
static lg::log_domain log_config("config");
#define LOG_CF LOG_STREAM(info, log_config)
// ==================================================================================
// BATTLE CONTEXT UNIT STATS
// ==================================================================================
battle_context_unit_stats::battle_context_unit_stats(const unit& u,
const map_location& u_loc,
int u_attack_num,
bool attacking,
const unit& opp,
const map_location& opp_loc,
const_attack_ptr opp_weapon,
const unit_map& units)
: weapon(nullptr)
, attack_num(u_attack_num)
, is_attacker(attacking)
, is_poisoned(u.get_state(unit::STATE_POISONED))
, is_slowed(u.get_state(unit::STATE_SLOWED))
, slows(false)
, drains(false)
, petrifies(false)
, plagues(false)
, poisons(false)
, backstab_pos(false)
, swarm(false)
, firststrike(false)
, disable(false)
, experience(u.experience())
, max_experience(u.max_experience())
, level(u.level())
, rounds(1)
, hp(0)
, max_hp(u.max_hitpoints())
, chance_to_hit(0)
, damage(0)
, slow_damage(0)
, drain_percent(0)
, drain_constant(0)
, num_blows(0)
, swarm_min(0)
, swarm_max(0)
, plague_type()
{
// Get the current state of the unit.
if(attack_num >= 0) {
weapon = u.attacks()[attack_num].shared_from_this();
}
if(u.hitpoints() < 0) {
LOG_CF << "Unit with " << u.hitpoints() << " hitpoints found, set to 0 for damage calculations\n";
hp = 0;
} else if(u.hitpoints() > u.max_hitpoints()) {
// If a unit has more hp than its maximum, the engine will fail with an
// assertion failure due to accessing the prob_matrix out of bounds.
hp = u.max_hitpoints();
} else {
hp = u.hitpoints();
}
// Exit if no weapon.
if(!weapon) {
return;
}
// Get the weapon characteristics as appropriate.
auto ctx = weapon->specials_context(&u, &opp, u_loc, opp_loc, attacking, opp_weapon);
boost::optional<decltype(ctx)> opp_ctx;
if(opp_weapon) {
opp_ctx.emplace(opp_weapon->specials_context(&opp, &u, opp_loc, u_loc, !attacking, weapon));
}
slows = weapon->bool_ability("slow");
drains = !opp.get_state("undrainable") && weapon->bool_ability("drains");
petrifies = weapon->bool_ability("petrifies");
poisons = !opp.get_state("unpoisonable") && weapon->bool_ability("poison") && !opp.get_state(unit::STATE_POISONED);
backstab_pos = is_attacker && backstab_check(u_loc, opp_loc, units, resources::gameboard->teams());
rounds = weapon->get_specials("berserk").highest("value", 1).first;
if(weapon->combat_ability("berserk", 1).second) {
rounds = weapon->combat_ability("berserk", 1).first;
}
firststrike = weapon->bool_ability("firststrike");
{
const int distance = distance_between(u_loc, opp_loc);
const bool out_of_range = distance > weapon->max_range() || distance < weapon->min_range();
disable = weapon->get_special_bool("disable") || out_of_range;
}
// Handle plague.
unit_ability_list plague_specials = weapon->get_specials("plague");
plagues = !opp.get_state("unplagueable") && !plague_specials.empty() &&
opp.undead_variation() != "null" && !resources::gameboard->map().is_village(opp_loc);
if(plagues) {
plague_type = (*plague_specials.front().first)["type"].str();
if(plague_type.empty()) {
plague_type = u.type().base_id();
}
}
// Compute chance to hit.
signed int cth = opp.defense_modifier(resources::gameboard->map().get_terrain(opp_loc)) + weapon->accuracy()
- (opp_weapon ? opp_weapon->parry() : 0);
cth = utils::clamp(cth, 0, 100);
unit_ability_list cth_specials = weapon->get_specials("chance_to_hit");
unit_abilities::effect cth_effects(cth_specials, cth, backstab_pos);
cth = cth_effects.get_composite_value();
cth = utils::clamp(cth, 0, 100);
cth = weapon->combat_ability("chance_to_hit", cth, backstab_pos).first;
if(opp.get_state("invulnerable")) {
cth = 0;
}
chance_to_hit = utils::clamp(cth, 0, 100);
// Compute base damage done with the weapon.
int base_damage = weapon->modified_damage(backstab_pos);
// Get the damage multiplier applied to the base damage of the weapon.
int damage_multiplier = 100;
// Time of day bonus.
damage_multiplier += combat_modifier(
resources::gameboard->units(), resources::gameboard->map(), u_loc, u.alignment(), u.is_fearless());
// Leadership bonus.
int leader_bonus = under_leadership(u, u_loc, weapon, opp_weapon);
if(leader_bonus != 0) {
damage_multiplier += leader_bonus;
}
// Resistance modifier.
damage_multiplier *= opp.damage_from(*weapon, !attacking, opp_loc, opp_weapon);
// Compute both the normal and slowed damage.
damage = round_damage(base_damage, damage_multiplier, 10000);
slow_damage = round_damage(base_damage, damage_multiplier, 20000);
if(is_slowed) {
damage = slow_damage;
}
// Compute drain amounts only if draining is possible.
if(drains) {
if (weapon->get_special_bool("drains")) {
unit_ability_list drain_specials = weapon->get_specials("drains");
// Compute the drain percent (with 50% as the base for backward compatibility)
unit_abilities::effect drain_percent_effects(drain_specials, 50, backstab_pos);
drain_percent = drain_percent_effects.get_composite_value();
}
if (weapon->combat_ability("drains", 50, backstab_pos).second) {
drain_percent = weapon->combat_ability("drains", 50, backstab_pos).first;
}
}
// Add heal_on_hit (the drain constant)
unit_ability_list heal_on_hit_specials = weapon->get_specials("heal_on_hit");
unit_abilities::effect heal_on_hit_effects(heal_on_hit_specials, 0, backstab_pos);
drain_constant += heal_on_hit_effects.get_composite_value();
drains = drain_constant || drain_percent;
// Compute the number of blows and handle swarm.
weapon->modified_attacks(backstab_pos, swarm_min, swarm_max);
swarm = swarm_min != swarm_max;
num_blows = calc_blows(hp);
}
battle_context_unit_stats::battle_context_unit_stats(const unit_type* u_type,
const_attack_ptr att_weapon,
bool attacking,
const unit_type* opp_type,
const_attack_ptr opp_weapon,
unsigned int opp_terrain_defense,
int lawful_bonus)
: weapon(att_weapon)
, attack_num(-2) // This is and stays invalid. Always use weapon when using this constructor.
, is_attacker(attacking)
, is_poisoned(false)
, is_slowed(false)
, slows(false)
, drains(false)
, petrifies(false)
, plagues(false)
, poisons(false)
, backstab_pos(false)
, swarm(false)
, firststrike(false)
, disable(false)
, experience(0)
, max_experience(0)
, level(0)
, rounds(1)
, hp(0)
, max_hp(0)
, chance_to_hit(0)
, damage(0)
, slow_damage(0)
, drain_percent(0)
, drain_constant(0)
, num_blows(0)
, swarm_min(0)
, swarm_max(0)
, plague_type()
{
if(!u_type || !opp_type) {
return;
}
// Get the current state of the unit.
if(u_type->hitpoints() < 0) {
hp = 0;
} else {
hp = u_type->hitpoints();
}
max_experience = u_type->experience_needed();
level = (u_type->level());
max_hp = (u_type->hitpoints());
// Exit if no weapon.
if(!weapon) {
return;
}
// Get the weapon characteristics as appropriate.
auto ctx = weapon->specials_context(*u_type, map_location::null_location(), attacking);
boost::optional<decltype(ctx)> opp_ctx;
if(opp_weapon) {
opp_ctx.emplace(opp_weapon->specials_context(*opp_type, map_location::null_location(), !attacking));
}
slows = weapon->get_special_bool("slow");
drains = !opp_type->musthave_status("undrainable") && weapon->get_special_bool("drains");
petrifies = weapon->get_special_bool("petrifies");
poisons = !opp_type->musthave_status("unpoisonable") && weapon->get_special_bool("poison");
rounds = weapon->get_specials("berserk").highest("value", 1).first;
firststrike = weapon->get_special_bool("firststrike");
disable = weapon->get_special_bool("disable");
unit_ability_list plague_specials = weapon->get_specials("plague");
plagues = !opp_type->musthave_status("unplagueable") && !plague_specials.empty() &&
opp_type->undead_variation() != "null";
if(plagues) {
plague_type = (*plague_specials.front().first)["type"].str();
if(plague_type.empty()) {
plague_type = u_type->base_id();
}
}
signed int cth = 100 - opp_terrain_defense + weapon->accuracy() - (opp_weapon ? opp_weapon->parry() : 0);
cth = utils::clamp(cth, 0, 100);
unit_ability_list cth_specials = weapon->get_specials("chance_to_hit");
unit_abilities::effect cth_effects(cth_specials, cth, backstab_pos);
cth = cth_effects.get_composite_value();
chance_to_hit = utils::clamp(cth, 0, 100);
int base_damage = weapon->modified_damage(backstab_pos);
int damage_multiplier = 100;
damage_multiplier
+= generic_combat_modifier(lawful_bonus, u_type->alignment(), u_type->musthave_status("fearless"), 0);
damage_multiplier *= opp_type->resistance_against(weapon->type(), !attacking);
damage = round_damage(base_damage, damage_multiplier, 10000);
slow_damage = round_damage(base_damage, damage_multiplier, 20000);
if(drains) {
unit_ability_list drain_specials = weapon->get_specials("drains");
// Compute the drain percent (with 50% as the base for backward compatibility)
unit_abilities::effect drain_percent_effects(drain_specials, 50, backstab_pos);
drain_percent = drain_percent_effects.get_composite_value();
}
// Add heal_on_hit (the drain constant)
unit_ability_list heal_on_hit_specials = weapon->get_specials("heal_on_hit");
unit_abilities::effect heal_on_hit_effects(heal_on_hit_specials, 0, backstab_pos);
drain_constant += heal_on_hit_effects.get_composite_value();
drains = drain_constant || drain_percent;
// Compute the number of blows and handle swarm.
weapon->modified_attacks(backstab_pos, swarm_min, swarm_max);
swarm = swarm_min != swarm_max;
num_blows = calc_blows(hp);
}
// ==================================================================================
// BATTLE CONTEXT
// ==================================================================================
battle_context::battle_context(
const unit& attacker,
const map_location& a_loc,
int a_wep_index,
const unit& defender,
const map_location& d_loc,
int d_wep_index,
const unit_map& units)
: attacker_stats_()
, defender_stats_()
, attacker_combatant_()
, defender_combatant_()
{
size_t a_wep_uindex = static_cast<size_t>(a_wep_index);
size_t d_wep_uindex = static_cast<size_t>(d_wep_index);
const_attack_ptr a_wep(a_wep_uindex < attacker.attacks().size() ? attacker.attacks()[a_wep_index].shared_from_this() : nullptr);
const_attack_ptr d_wep(d_wep_uindex < defender.attacks().size() ? defender.attacks()[d_wep_index].shared_from_this() : nullptr);
attacker_stats_.reset(new battle_context_unit_stats(attacker, a_loc, a_wep_index, true , defender, d_loc, d_wep, units));
defender_stats_.reset(new battle_context_unit_stats(defender, d_loc, d_wep_index, false, attacker, a_loc, a_wep, units));
}
void battle_context::simulate(const combatant* prev_def)
{
assert((attacker_combatant_.get() != nullptr) == (defender_combatant_.get() != nullptr));
assert(attacker_stats_);
assert(defender_stats_);
if(!attacker_combatant_) {
attacker_combatant_.reset(new combatant(*attacker_stats_));
defender_combatant_.reset(new combatant(*defender_stats_, prev_def));
attacker_combatant_->fight(*defender_combatant_);
}
}
// more like a factory method than a constructor, always calls one of the other constructors.
battle_context::battle_context(const unit_map& units,
const map_location& attacker_loc,
const map_location& defender_loc,
int attacker_weapon,
int defender_weapon,
double aggression,
const combatant* prev_def,
const unit* attacker_ptr,
const unit* defender_ptr)
: attacker_stats_(nullptr)
, defender_stats_(nullptr)
, attacker_combatant_(nullptr)
, defender_combatant_(nullptr)
{
//TODO: maybe check before dereferencing units.find(attacker_loc),units.find(defender_loc) ?
const unit& attacker = attacker_ptr ? *attacker_ptr : *units.find(attacker_loc);
const unit& defender = defender_ptr ? *defender_ptr : *units.find(defender_loc);
const double harm_weight = 1.0 - aggression;
if(attacker_weapon == -1) {
*this = choose_attacker_weapon(
attacker, defender, units, attacker_loc, defender_loc, harm_weight, prev_def
);
}
else if(defender_weapon == -1) {
*this = choose_defender_weapon(
attacker, defender, attacker_weapon, units, attacker_loc, defender_loc, prev_def
);
}
else {
*this = battle_context(attacker, attacker_loc, attacker_weapon, defender, defender_loc, defender_weapon, units);
}
assert(attacker_stats_);
assert(defender_stats_);
}
battle_context::battle_context(const battle_context_unit_stats& att, const battle_context_unit_stats& def)
: attacker_stats_(new battle_context_unit_stats(att))
, defender_stats_(new battle_context_unit_stats(def))
, attacker_combatant_(nullptr)
, defender_combatant_(nullptr)
{
}
/** @todo FIXME: better to initialize combatant initially (move into
battle_context_unit_stats?), just do fight() when required. */
const combatant& battle_context::get_attacker_combatant(const combatant* prev_def)
{
// We calculate this lazily, since AI doesn't always need it.
simulate(prev_def);
return *attacker_combatant_;
}
const combatant& battle_context::get_defender_combatant(const combatant* prev_def)
{
// We calculate this lazily, since AI doesn't always need it.
simulate(prev_def);
return *defender_combatant_;
}
// Given this harm_weight, are we better than that other context?
bool battle_context::better_attack(class battle_context& that, double harm_weight)
{
return better_combat(
get_attacker_combatant(),
get_defender_combatant(),
that.get_attacker_combatant(),
that.get_defender_combatant(),
harm_weight
);
}
// Given this harm_weight, are we better than that other context?
bool battle_context::better_defense(class battle_context& that, double harm_weight)
{
return better_combat(
get_defender_combatant(),
get_attacker_combatant(),
that.get_defender_combatant(),
that.get_attacker_combatant(),
harm_weight
);
}
// Does combat A give us a better result than combat B?
bool battle_context::better_combat(const combatant& us_a,
const combatant& them_a,
const combatant& us_b,
const combatant& them_b,
double harm_weight)
{
double a, b;
// Compare: P(we kill them) - P(they kill us).
a = them_a.hp_dist[0] - us_a.hp_dist[0] * harm_weight;
b = them_b.hp_dist[0] - us_b.hp_dist[0] * harm_weight;
if(a - b < -0.01) {
return false;
}
if(a - b > 0.01) {
return true;
}
// Add poison to calculations
double poison_a_us = (us_a.poisoned) * game_config::poison_amount;
double poison_a_them = (them_a.poisoned) * game_config::poison_amount;
double poison_b_us = (us_b.poisoned) * game_config::poison_amount;
double poison_b_them = (them_b.poisoned) * game_config::poison_amount;
// Compare: damage to them - damage to us (average_hp replaces -damage)
a = (us_a.average_hp() - poison_a_us) * harm_weight - (them_a.average_hp() - poison_a_them);
b = (us_b.average_hp() - poison_b_us) * harm_weight - (them_b.average_hp() - poison_b_them);
if(a - b < -0.01) {
return false;
}
if(a - b > 0.01) {
return true;
}
// All else equal: go for most damage.
return them_a.average_hp() < them_b.average_hp();
}
battle_context battle_context::choose_attacker_weapon(const unit& attacker,
const unit& defender,
const unit_map& units,
const map_location& attacker_loc,
const map_location& defender_loc,
double harm_weight,
const combatant* prev_def)
{
log_scope2(log_attack, "choose_attacker_weapon");
std::vector<battle_context> choices;
// What options does attacker have?
for(size_t i = 0; i < attacker.attacks().size(); ++i) {
const attack_type& att = attacker.attacks()[i];
if(att.attack_weight() <= 0) {
continue;
}
battle_context bc = choose_defender_weapon(attacker, defender, i, units, attacker_loc, defender_loc, prev_def);
//choose_defender_weapon will always choose the weapon that disabels the attackers weapon if possible.
if(bc.attacker_stats_->disable) {
continue;
}
choices.emplace_back(std::move(bc));
}
if(choices.empty()) {
return battle_context(attacker, attacker_loc, -1, defender, defender_loc, -1, units);
}
if(choices.size() == 1) {
return std::move(choices[0]);
}
// Multiple options: simulate them, save best.
battle_context* best_choice = nullptr;
for(auto& choice : choices) {
// If choose_defender_weapon didn't simulate, do so now.
choice.simulate(prev_def);
if(!best_choice || choice.better_attack(*best_choice, harm_weight)) {
best_choice = &choice;
}
}
if(best_choice) {
return std::move(*best_choice);
}
else {
return battle_context(attacker, attacker_loc, -1, defender, defender_loc, -1, units);
}
}
/** @todo FIXME: Hand previous defender unit in here. */
battle_context battle_context::choose_defender_weapon(const unit& attacker,
const unit& defender,
unsigned attacker_weapon,
const unit_map& units,
const map_location& attacker_loc,
const map_location& defender_loc,
const combatant* prev_def)
{
log_scope2(log_attack, "choose_defender_weapon");
VALIDATE(attacker_weapon < attacker.attacks().size(), _("An invalid attacker weapon got selected."));
const attack_type& att = attacker.attacks()[attacker_weapon];
auto no_weapon = [&]() { return battle_context(attacker, attacker_loc, attacker_weapon, defender, defender_loc, -1, units); };
std::vector<battle_context> choices;
// What options does defender have?
for(size_t i = 0; i < defender.attacks().size(); ++i) {
const attack_type& def = defender.attacks()[i];
if(def.range() != att.range() || def.defense_weight() <= 0) {
//no need to calculate the battle_context here.
continue;
}
battle_context bc(attacker, attacker_loc, attacker_weapon, defender, defender_loc, i, units);
if(bc.defender_stats_->disable) {
continue;
}
if(bc.attacker_stats_->disable) {
//the defenders attack disables the attakers attack: always choose this one.
return bc;
}
choices.emplace_back(std::move(bc));
}
if(choices.empty()) {
return no_weapon();
}
if(choices.size() == 1) {
//only one usable weapon, don't simulate
return std::move(choices[0]);
}
// Multiple options:
// First pass : get the best weight and the minimum simple rating for this weight.
// simple rating = number of blows * damage per blows (resistance taken in account) * cth * weight
// Eligible attacks for defense should have a simple rating greater or equal to this weight.
int min_rating = 0;
{
double max_weight = 0.0;
for(const auto& choice : choices) {
const attack_type& def = defender.attacks()[choice.defender_stats_->attack_num];
if(def.defense_weight() >= max_weight) {
const battle_context_unit_stats& def_stats = *choice.defender_stats_;
max_weight = def.defense_weight();
int rating = static_cast<int>(
def_stats.num_blows * def_stats.damage * def_stats.chance_to_hit * def.defense_weight());
if(def.defense_weight() > max_weight || rating < min_rating) {
min_rating = rating;
}
}
}
}
battle_context* best_choice = nullptr;
// Multiple options: simulate them, save best.
for(auto& choice : choices) {
const attack_type& def = defender.attacks()[choice.defender_stats_->attack_num];
choice.simulate(prev_def);
int simple_rating = static_cast<int>(
choice.defender_stats_->num_blows * choice.defender_stats_->damage * choice.defender_stats_->chance_to_hit * def.defense_weight());
//FIXME: make sure there is no mostake in the better_combat call-
if(simple_rating >= min_rating && (!best_choice || choice.better_defense(*best_choice, 1.0))) {
best_choice = &choice;
}
}
return best_choice ? std::move(*best_choice) : no_weapon();
}
// ==================================================================================
// HELPERS
// ==================================================================================
namespace
{
void refresh_weapon_index(int& weap_index, const std::string& weap_id, attack_itors attacks)
{
// No attacks to choose from.
if(attacks.empty()) {
weap_index = -1;
return;
}
// The currently selected attack fits.
if(weap_index >= 0 && weap_index < static_cast<int>(attacks.size()) && attacks[weap_index].id() == weap_id) {
return;
}
// Look up the weapon by id.
if(!weap_id.empty()) {
for(int i = 0; i < static_cast<int>(attacks.size()); ++i) {
if(attacks[i].id() == weap_id) {
weap_index = i;
return;
}
}
}
// Lookup has failed.
weap_index = -1;
return;
}
/** Helper class for performing an attack. */
class attack
{
public:
attack(const map_location& attacker,
const map_location& defender,
int attack_with,
int defend_with,
bool update_display = true);
void perform();
private:
class attack_end_exception
{
};
bool perform_hit(bool, statistics::attack_context&);
void fire_event(const std::string& n);
void refresh_bc();
/** Structure holding unit info used in the attack action. */
struct unit_info
{
const map_location loc_;
int weapon_;
unit_map& units_;
std::size_t id_; /**< unit.underlying_id() */
std::string weap_id_;
int orig_attacks_;
int n_attacks_; /**< Number of attacks left. */
int cth_;
int damage_;
int xp_;
unit_info(const map_location& loc, int weapon, unit_map& units);
unit& get_unit();
bool valid();
std::string dump();
};
/**
* Used in perform_hit to confirm a replay is in sync.
* Check OOS_error_ after this method, true if error detected.
*/
void check_replay_attack_result(bool&, int, int&, config, unit_info&);
void unit_killed(
unit_info&, unit_info&, const battle_context_unit_stats*&, const battle_context_unit_stats*&, bool);
std::unique_ptr<battle_context> bc_;
const battle_context_unit_stats* a_stats_;
const battle_context_unit_stats* d_stats_;
int abs_n_attack_, abs_n_defend_;
// update_att_fog_ is not used, other than making some code simpler.
bool update_att_fog_, update_def_fog_, update_minimap_;
unit_info a_, d_;
unit_map& units_;
std::ostringstream errbuf_;
bool update_display_;
bool OOS_error_;
bool use_prng_;
std::vector<bool> prng_attacker_;
std::vector<bool> prng_defender_;
};
attack::unit_info::unit_info(const map_location& loc, int weapon, unit_map& units)
: loc_(loc)
, weapon_(weapon)
, units_(units)
, id_()
, weap_id_()
, orig_attacks_(0)
, n_attacks_(0)
, cth_(0)
, damage_(0)
, xp_(0)
{
unit_map::iterator i = units_.find(loc_);
if(!i.valid()) {
return;
}
id_ = i->underlying_id();
}
unit& attack::unit_info::get_unit()
{
unit_map::iterator i = units_.find(loc_);
assert(i.valid() && i->underlying_id() == id_);
return *i;
}
bool attack::unit_info::valid()
{
unit_map::iterator i = units_.find(loc_);
return i.valid() && i->underlying_id() == id_;
}
std::string attack::unit_info::dump()
{
std::stringstream s;
s << get_unit().type_id() << " (" << loc_.wml_x() << ',' << loc_.wml_y() << ')';
return s.str();
}
attack::attack(const map_location& attacker,
const map_location& defender,
int attack_with,
int defend_with,
bool update_display)
: bc_(nullptr)
, a_stats_(nullptr)
, d_stats_(nullptr)
, abs_n_attack_(0)
, abs_n_defend_(0)
, update_att_fog_(false)
, update_def_fog_(false)
, update_minimap_(false)
, a_(attacker, attack_with, resources::gameboard->units())
, d_(defender, defend_with, resources::gameboard->units())
, units_(resources::gameboard->units())
, errbuf_()
, update_display_(update_display)
, OOS_error_(false)
//new experimental prng mode.
, use_prng_(preferences::get("use_prng") == "yes" && randomness::generator->is_networked() == false)
{
if(use_prng_) {
std::cerr << "Using experimental PRNG for combat\n";
}
}
void attack::fire_event(const std::string& n)
{
LOG_NG << "attack: firing '" << n << "' event\n";
// prepare the event data for weapon filtering
config ev_data;
config& a_weapon_cfg = ev_data.add_child("first");
config& d_weapon_cfg = ev_data.add_child("second");
// Need these to ensure weapon filters work correctly
boost::optional<attack_type::specials_context_t> a_ctx, d_ctx;
if(a_stats_->weapon != nullptr && a_.valid()) {
if(d_stats_->weapon != nullptr && d_.valid()) {
a_ctx.emplace(a_stats_->weapon->specials_context(nullptr, nullptr, a_.loc_, d_.loc_, true, d_stats_->weapon));
} else {
a_ctx.emplace(a_stats_->weapon->specials_context(nullptr, a_.loc_, true));
}
a_stats_->weapon->write(a_weapon_cfg);
}
if(d_stats_->weapon != nullptr && d_.valid()) {
if(a_stats_->weapon != nullptr && a_.valid()) {
d_ctx.emplace(d_stats_->weapon->specials_context(nullptr, nullptr, d_.loc_, a_.loc_, false, a_stats_->weapon));
} else {
d_ctx.emplace(d_stats_->weapon->specials_context(nullptr, d_.loc_, false));
}
d_stats_->weapon->write(d_weapon_cfg);
}
if(a_weapon_cfg["name"].empty()) {
a_weapon_cfg["name"] = "none";
}
if(d_weapon_cfg["name"].empty()) {
d_weapon_cfg["name"] = "none";
}
if(n == "attack_end") {
// We want to fire attack_end event in any case! Even if one of units was removed by WML.
resources::game_events->pump().fire(n, a_.loc_, d_.loc_, ev_data);
return;
}
// damage_inflicted is set in these two events.
// TODO: should we set this value from unit_info::damage, or continue using the WML variable?
if(n == "attacker_hits" || n == "defender_hits") {
ev_data["damage_inflicted"] = resources::gamedata->get_variable("damage_inflicted");
}
const int defender_side = d_.get_unit().side();
bool wml_aborted;
std::tie(std::ignore, wml_aborted) = resources::game_events->pump().fire(n,
game_events::entity_location(a_.loc_, a_.id_),
game_events::entity_location(d_.loc_, d_.id_), ev_data);
// The event could have killed either the attacker or
// defender, so we have to make sure they still exist.
refresh_bc();
if(wml_aborted || !a_.valid() || !d_.valid()
|| !resources::gameboard->get_team(a_.get_unit().side()).is_enemy(d_.get_unit().side())
) {
actions::recalculate_fog(defender_side);
if(update_display_) {
display::get_singleton()->redraw_minimap();
}
fire_event("attack_end");
throw attack_end_exception();
}
}
void attack::refresh_bc()
{
// Fix index of weapons.
if(a_.valid()) {
refresh_weapon_index(a_.weapon_, a_.weap_id_, a_.get_unit().attacks());
}
if(d_.valid()) {
refresh_weapon_index(d_.weapon_, d_.weap_id_, d_.get_unit().attacks());
}
if(!a_.valid() || !d_.valid()) {
// Fix pointer to weapons.
const_cast<battle_context_unit_stats*>(a_stats_)->weapon
= a_.valid() && a_.weapon_ >= 0 ? a_.get_unit().attacks()[a_.weapon_].shared_from_this() : nullptr;
const_cast<battle_context_unit_stats*>(d_stats_)->weapon
= d_.valid() && d_.weapon_ >= 0 ? d_.get_unit().attacks()[d_.weapon_].shared_from_this() : nullptr;
return;
}
bc_.reset(new battle_context(units_, a_.loc_, d_.loc_, a_.weapon_, d_.weapon_));
a_stats_ = &bc_->get_attacker_stats();
d_stats_ = &bc_->get_defender_stats();
a_.cth_ = a_stats_->chance_to_hit;
d_.cth_ = d_stats_->chance_to_hit;
a_.damage_ = a_stats_->damage;
d_.damage_ = d_stats_->damage;
}
bool attack::perform_hit(bool attacker_turn, statistics::attack_context& stats)
{
unit_info& attacker = attacker_turn ? a_ : d_;
unit_info& defender = attacker_turn ? d_ : a_;
// NOTE: we need to use a reference-to-pointer here so a_stats_ and d_stats_ can be
// modified without. Using a pointer directly would render them invalid when that happened.
const battle_context_unit_stats*& attacker_stats = attacker_turn ? a_stats_ : d_stats_;
const battle_context_unit_stats*& defender_stats = attacker_turn ? d_stats_ : a_stats_;
int& abs_n = attacker_turn ? abs_n_attack_ : abs_n_defend_;
bool& update_fog = attacker_turn ? update_def_fog_ : update_att_fog_;
int ran_num;
if(use_prng_) {
std::vector<bool>& prng_seq = attacker_turn ? prng_attacker_ : prng_defender_;
if(prng_seq.empty()) {
const int ntotal = attacker.cth_*attacker.n_attacks_;
int num_hits = ntotal/100;
const int additional_hit_chance = ntotal%100;
if(additional_hit_chance > 0 && randomness::generator->get_random_int(0, 99) < additional_hit_chance) {
++num_hits;
}
std::vector<int> indexes;
for(int i = 0; i != attacker.n_attacks_; ++i) {
prng_seq.push_back(false);
indexes.push_back(i);
}
for(int i = 0; i != num_hits; ++i) {
int n = randomness::generator->get_random_int(0, static_cast<int>(indexes.size())-1);
prng_seq[indexes[n]] = true;
indexes.erase(indexes.begin() + n);
}
}
bool does_hit = prng_seq.back();
prng_seq.pop_back();
ran_num = does_hit ? 0 : 99;
} else {
ran_num = randomness::generator->get_random_int(0, 99);
}
bool hits = (ran_num < attacker.cth_);
int damage = 0;
if(hits) {
damage = attacker.damage_;
resources::gamedata->get_variable("damage_inflicted") = damage;
}
// Make sure that if we're serializing a game here,
// we got the same results as the game did originally.
const config local_results {"chance", attacker.cth_, "hits", hits, "damage", damage};
config replay_results;
bool equals_replay = checkup_instance->local_checkup(local_results, replay_results);
if(!equals_replay) {
check_replay_attack_result(hits, ran_num, damage, replay_results, attacker);
}
// can do no more damage than the defender has hitpoints
int damage_done = std::min<int>(defender.get_unit().hitpoints(), attacker.damage_);
// expected damage = damage potential * chance to hit (as a percentage)
double expected_damage = damage_done * attacker.cth_ * 0.01;
if(attacker_turn) {
stats.attack_expected_damage(expected_damage, 0);
} else {
stats.attack_expected_damage(0, expected_damage);
}
int drains_damage = 0;
if(hits && attacker_stats->drains) {
drains_damage = damage_done * attacker_stats->drain_percent / 100 + attacker_stats->drain_constant;
// don't drain so much that the attacker gets more than his maximum hitpoints
drains_damage =
std::min<int>(drains_damage, attacker.get_unit().max_hitpoints() - attacker.get_unit().hitpoints());
// if drain is negative, don't allow drain to kill the attacker
drains_damage = std::max<int>(drains_damage, 1 - attacker.get_unit().hitpoints());
}
if(update_display_) {
std::ostringstream float_text;
std::vector<std::string> extra_hit_sounds;
if(hits) {
const unit& defender_unit = defender.get_unit();
if(attacker_stats->poisons && !defender_unit.get_state(unit::STATE_POISONED)) {
float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^poisoned") : _("poisoned"))
<< '\n';
extra_hit_sounds.push_back(game_config::sounds::status::poisoned);
}
if(attacker_stats->slows && !defender_unit.get_state(unit::STATE_SLOWED)) {
float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^slowed") : _("slowed")) << '\n';
extra_hit_sounds.push_back(game_config::sounds::status::slowed);
}
if(attacker_stats->petrifies) {
float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^petrified") : _("petrified"))
<< '\n';
extra_hit_sounds.push_back(game_config::sounds::status::petrified);
}
}
unit_display::unit_attack(
game_display::get_singleton(),
*resources::gameboard,
attacker.loc_, defender.loc_,
damage,
*attacker_stats->weapon, defender_stats->weapon,
abs_n, float_text.str(), drains_damage, "",
&extra_hit_sounds
);
}
bool dies = defender.get_unit().take_hit(damage);
LOG_NG << "defender took " << damage << (dies ? " and died\n" : "\n");
if(attacker_turn) {
stats.attack_result(hits
? (dies
? statistics::attack_context::KILLS
: statistics::attack_context::HITS)
: statistics::attack_context::MISSES,
attacker.cth_, damage_done, drains_damage
);
} else {
stats.defend_result(hits
? (dies
? statistics::attack_context::KILLS
: statistics::attack_context::HITS)
: statistics::attack_context::MISSES,
attacker.cth_, damage_done, drains_damage
);
}
replay_results.clear();
// There was also a attribute cfg["unit_hit"] which was never used so i deleted.
equals_replay = checkup_instance->local_checkup(config{"dies", dies}, replay_results);
if(!equals_replay) {
bool results_dies = replay_results["dies"].to_bool();
errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the "
<< (attacker_turn ? "defender" : "attacker") << ' ' << (results_dies ? "perished" : "survived")
<< " while in-game calculations show it " << (dies ? "perished" : "survived")
<< " (over-riding game calculations with data source results)\n";
dies = results_dies;
// Set hitpoints to 0 so later checks don't invalidate the death.
if(results_dies) {
defender.get_unit().set_hitpoints(0);
}
OOS_error_ = true;
}
if(hits) {
try {
fire_event(attacker_turn ? "attacker_hits" : "defender_hits");
} catch(const attack_end_exception&) {
refresh_bc();
return false;
}
} else {
try {
fire_event(attacker_turn ? "attacker_misses" : "defender_misses");
} catch(const attack_end_exception&) {
refresh_bc();
return false;
}
}
refresh_bc();
bool attacker_dies = false;
if(drains_damage > 0) {
attacker.get_unit().heal(drains_damage);
} else if(drains_damage < 0) {
attacker_dies = attacker.get_unit().take_hit(-drains_damage);
}
if(dies) {
unit_killed(attacker, defender, attacker_stats, defender_stats, false);
update_fog = true;
}
if(attacker_dies) {
unit_killed(defender, attacker, defender_stats, attacker_stats, true);
(attacker_turn ? update_att_fog_ : update_def_fog_) = true;
}
if(dies) {
update_minimap_ = true;
return false;
}
if(hits) {
unit& defender_unit = defender.get_unit();
if(attacker_stats->poisons && !defender_unit.get_state(unit::STATE_POISONED)) {
defender_unit.set_state(unit::STATE_POISONED, true);
LOG_NG << "defender poisoned\n";
}
if(attacker_stats->slows && !defender_unit.get_state(unit::STATE_SLOWED)) {
defender_unit.set_state(unit::STATE_SLOWED, true);
update_fog = true;
defender.damage_ = defender_stats->slow_damage;
LOG_NG << "defender slowed\n";
}
// If the defender is petrified, the fight stops immediately
if(attacker_stats->petrifies) {
defender_unit.set_state(unit::STATE_PETRIFIED, true);
update_fog = true;
attacker.n_attacks_ = 0;
defender.n_attacks_ = -1; // Petrified.
resources::game_events->pump().fire("petrified", defender.loc_, attacker.loc_);
refresh_bc();
}
}
// Delay until here so that poison and slow go through
if(attacker_dies) {
update_minimap_ = true;
return false;
}
--attacker.n_attacks_;
return true;
}
void attack::unit_killed(unit_info& attacker,
unit_info& defender,
const battle_context_unit_stats*& attacker_stats,
const battle_context_unit_stats*& defender_stats,
bool drain_killed)
{
attacker.xp_ = game_config::kill_xp(defender.get_unit().level());
defender.xp_ = 0;
display::get_singleton()->invalidate(attacker.loc_);
game_events::entity_location death_loc(defender.loc_, defender.id_);
game_events::entity_location attacker_loc(attacker.loc_, attacker.id_);
std::string undead_variation = defender.get_unit().undead_variation();
fire_event("attack_end");
refresh_bc();
// Get weapon info for last_breath and die events.
config dat;
config a_weapon_cfg = attacker_stats->weapon && attacker.valid() ? attacker_stats->weapon->to_config() : config();
config d_weapon_cfg = defender_stats->weapon && defender.valid() ? defender_stats->weapon->to_config() : config();
if(a_weapon_cfg["name"].empty()) {
a_weapon_cfg["name"] = "none";
}
if(d_weapon_cfg["name"].empty()) {
d_weapon_cfg["name"] = "none";
}
dat.add_child("first", d_weapon_cfg);
dat.add_child("second", a_weapon_cfg);
resources::game_events->pump().fire("last_breath", death_loc, attacker_loc, dat);
refresh_bc();
// WML has invalidated the dying unit, abort.
if(!defender.valid() || defender.get_unit().hitpoints() > 0) {
return;
}
if(!attacker.valid()) {
unit_display::unit_die(
defender.loc_,
defender.get_unit(),
nullptr,
defender_stats->weapon
);
} else {
unit_display::unit_die(
defender.loc_,
defender.get_unit(),
attacker_stats->weapon,
defender_stats->weapon,
attacker.loc_,
&attacker.get_unit()
);
}
resources::game_events->pump().fire("die", death_loc, attacker_loc, dat);
refresh_bc();
if(!defender.valid() || defender.get_unit().hitpoints() > 0) {
// WML has invalidated the dying unit, abort
return;
}
units_.erase(defender.loc_);
resources::whiteboard->on_kill_unit();
// Plague units make new units on the target hex.
if(attacker.valid() && attacker_stats->plagues && !drain_killed) {
LOG_NG << "trying to reanimate " << attacker_stats->plague_type << '\n';
if(const unit_type* reanimator = unit_types.find(attacker_stats->plague_type)) {
LOG_NG << "found unit type:" << reanimator->id() << '\n';
unit_ptr newunit = unit::create(*reanimator, attacker.get_unit().side(), true, unit_race::MALE);
newunit->set_attacks(0);
newunit->set_movement(0, true);
newunit->set_facing(map_location::get_opposite_dir(attacker.get_unit().facing()));
// Apply variation
if(undead_variation != "null") {
config mod;
config& variation = mod.add_child("effect");
variation["apply_to"] = "variation";
variation["name"] = undead_variation;
newunit->add_modification("variation", mod);
newunit->heal_fully();
}
newunit->set_location(death_loc);
units_.insert(newunit);
game_events::entity_location reanim_loc(defender.loc_, newunit->underlying_id());
resources::game_events->pump().fire("unit_placed", reanim_loc);
preferences::encountered_units().insert(newunit->type_id());
if(update_display_) {
display::get_singleton()->invalidate(death_loc);
}
}
} else {
LOG_NG << "unit not reanimated\n";
}
}
void attack::perform()
{
// Stop the user from issuing any commands while the units are fighting.
const events::command_disabler disable_commands;
if(!a_.valid() || !d_.valid()) {
return;
}
// no attack weapon => stop here and don't attack
if(a_.weapon_ < 0) {
a_.get_unit().set_attacks(a_.get_unit().attacks_left() - 1);
a_.get_unit().set_movement(-1, true);
return;
}
if(a_.get_unit().attacks_left() <= 0) {
LOG_NG << "attack::perform(): not enough ap.\n";
return;
}
a_.get_unit().set_facing(a_.loc_.get_relative_dir(d_.loc_));
d_.get_unit().set_facing(d_.loc_.get_relative_dir(a_.loc_));
a_.get_unit().set_attacks(a_.get_unit().attacks_left() - 1);
VALIDATE(a_.weapon_ < static_cast<int>(a_.get_unit().attacks().size()),
_("An invalid attacker weapon got selected."));
a_.get_unit().set_movement(a_.get_unit().movement_left() - a_.get_unit().attacks()[a_.weapon_].movement_used(), true);
a_.get_unit().set_state(unit::STATE_NOT_MOVED, false);
a_.get_unit().set_resting(false);
d_.get_unit().set_resting(false);
// If the attacker was invisible, she isn't anymore!
a_.get_unit().set_state(unit::STATE_UNCOVERED, true);
bc_.reset(new battle_context(units_, a_.loc_, d_.loc_, a_.weapon_, d_.weapon_));
a_stats_ = &bc_->get_attacker_stats();
d_stats_ = &bc_->get_defender_stats();
if(a_stats_->disable) {
LOG_NG << "attack::perform(): tried to attack with a disabled attack.\n";
return;
}
if(a_stats_->weapon) {
a_.weap_id_ = a_stats_->weapon->id();
}
if(d_stats_->weapon) {
d_.weap_id_ = d_stats_->weapon->id();
}
try {
fire_event("attack");
} catch(const attack_end_exception&) {
return;
}
refresh_bc();
DBG_NG << "getting attack statistics\n";
statistics::attack_context attack_stats(
a_.get_unit(), d_.get_unit(), a_stats_->chance_to_hit, d_stats_->chance_to_hit);
a_.orig_attacks_ = a_stats_->num_blows;
d_.orig_attacks_ = d_stats_->num_blows;
a_.n_attacks_ = a_.orig_attacks_;
d_.n_attacks_ = d_.orig_attacks_;
a_.xp_ = game_config::combat_xp(d_.get_unit().level());
d_.xp_ = game_config::combat_xp(a_.get_unit().level());
bool defender_strikes_first = (d_stats_->firststrike && !a_stats_->firststrike);
unsigned int rounds = std::max<unsigned int>(a_stats_->rounds, d_stats_->rounds) - 1;
const int defender_side = d_.get_unit().side();
LOG_NG << "Fight: (" << a_.loc_ << ") vs (" << d_.loc_ << ") ATT: " << a_stats_->weapon->name() << " "
<< a_stats_->damage << "-" << a_stats_->num_blows << "(" << a_stats_->chance_to_hit
<< "%) vs DEF: " << (d_stats_->weapon ? d_stats_->weapon->name() : "none") << " " << d_stats_->damage << "-"
<< d_stats_->num_blows << "(" << d_stats_->chance_to_hit << "%)"
<< (defender_strikes_first ? " defender first-strike" : "") << "\n";
// Play the pre-fight animation
unit_display::unit_draw_weapon(a_.loc_, a_.get_unit(), a_stats_->weapon, d_stats_->weapon, d_.loc_, &d_.get_unit());
for(;;) {
DBG_NG << "start of attack loop...\n";
++abs_n_attack_;
if(a_.n_attacks_ > 0 && !defender_strikes_first) {
if(!perform_hit(true, attack_stats)) {
DBG_NG << "broke from attack loop on attacker turn\n";
break;
}
}
// If the defender got to strike first, they use it up here.
defender_strikes_first = false;
++abs_n_defend_;
if(d_.n_attacks_ > 0) {
if(!perform_hit(false, attack_stats)) {
DBG_NG << "broke from attack loop on defender turn\n";
break;
}
}
// Continue the fight to death; if one of the units got petrified,
// either n_attacks or n_defends is -1
if(rounds > 0 && d_.n_attacks_ == 0 && a_.n_attacks_ == 0) {
a_.n_attacks_ = a_.orig_attacks_;
d_.n_attacks_ = d_.orig_attacks_;
--rounds;
defender_strikes_first = (d_stats_->firststrike && !a_stats_->firststrike);
}
if(a_.n_attacks_ <= 0 && d_.n_attacks_ <= 0) {
fire_event("attack_end");
refresh_bc();
break;
}
}
// Set by attacker_hits and defender_hits events.
resources::gamedata->clear_variable("damage_inflicted");
if(update_def_fog_) {
actions::recalculate_fog(defender_side);
}
// TODO: if we knew the viewing team, we could skip this display update
if(update_minimap_ && update_display_) {
display::get_singleton()->redraw_minimap();
}
if(a_.valid()) {
unit& u = a_.get_unit();
u.anim_comp().set_standing();
u.set_experience(u.experience() + a_.xp_);
}
if(d_.valid()) {
unit& u = d_.get_unit();
u.anim_comp().set_standing();
u.set_experience(u.experience() + d_.xp_);
}
unit_display::unit_sheath_weapon(a_.loc_, a_.valid() ? &a_.get_unit() : nullptr, a_stats_->weapon, d_stats_->weapon,
d_.loc_, d_.valid() ? &d_.get_unit() : nullptr);
if(update_display_) {
game_display::get_singleton()->invalidate_unit();
display::get_singleton()->invalidate(a_.loc_);
display::get_singleton()->invalidate(d_.loc_);
}
if(OOS_error_) {
replay::process_error(errbuf_.str());
}
}
void attack::check_replay_attack_result(
bool& hits, int ran_num, int& damage, config replay_results, unit_info& attacker)
{
int results_chance = replay_results["chance"];
bool results_hits = replay_results["hits"].to_bool();
int results_damage = replay_results["damage"];
#if 0
errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump()
<< " replay data differs from local calculated data:"
<< " chance to hit in data source: " << results_chance
<< " chance to hit in calculated: " << attacker.cth_
<< " chance to hit in data source: " << results_chance
<< " chance to hit in calculated: " << attacker.cth_
;
attacker.cth_ = results_chance;
hits = results_hits;
damage = results_damage;
OOS_error_ = true;
#endif
if(results_chance != attacker.cth_) {
errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump()
<< ": chance to hit is inconsistent. Data source: " << results_chance
<< "; Calculation: " << attacker.cth_ << " (over-riding game calculations with data source results)\n";
attacker.cth_ = results_chance;
OOS_error_ = true;
}
if(results_hits != hits) {
errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the hit was "
<< (results_hits ? "successful" : "unsuccessful") << ", while in-game calculations say the hit was "
<< (hits ? "successful" : "unsuccessful") << " random number: " << ran_num << " = " << (ran_num % 100)
<< "/" << results_chance << " (over-riding game calculations with data source results)\n";
hits = results_hits;
OOS_error_ = true;
}
if(results_damage != damage) {
errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the hit did "
<< results_damage << " damage, while in-game calculations show the hit doing " << damage
<< " damage (over-riding game calculations with data source results)\n";
damage = results_damage;
OOS_error_ = true;
}
}
} // end anonymous namespace
// ==================================================================================
// FREE-STANDING FUNCTIONS
// ==================================================================================
void attack_unit(const map_location& attacker,
const map_location& defender,
int attack_with,
int defend_with,
bool update_display)
{
attack dummy(attacker, defender, attack_with, defend_with, update_display);
dummy.perform();
}
void attack_unit_and_advance(const map_location& attacker,
const map_location& defender,
int attack_with,
int defend_with,
bool update_display,
const ai::unit_advancements_aspect& ai_advancement)
{
attack_unit(attacker, defender, attack_with, defend_with, update_display);
unit_map::const_iterator atku = resources::gameboard->units().find(attacker);
if(atku != resources::gameboard->units().end()) {
advance_unit_at(advance_unit_params(attacker).ai_advancements(ai_advancement));
}
unit_map::const_iterator defu = resources::gameboard->units().find(defender);
if(defu != resources::gameboard->units().end()) {
advance_unit_at(advance_unit_params(defender).ai_advancements(ai_advancement));
}
}
int under_leadership(const unit &u, const map_location& loc, const_attack_ptr weapon, const_attack_ptr opp_weapon)
{
unit_ability_list abil = u.get_abilities("leadership", loc, weapon, opp_weapon);
unit_abilities::effect leader_effect(abil, 0, false);
return leader_effect.get_composite_value();
}
//begin of weapon emulates function.
bool unit::abilities_filter_matches(const config& cfg, bool attacker, int res) const
{
if(!(cfg["active_on"].empty() || (attacker && cfg["active_on"] == "offense") || (!attacker && cfg["active_on"] == "defense"))) {
return false;
}
if(!unit_abilities::filter_base_matches(cfg, res)) {
return false;
}
return true;
}
//functions for emulate weapon specials.
//filter opponent and affect self/opponent/both option.
bool unit::ability_filter_fighter(const std::string& ability, const std::string& filter_attacker , const config& cfg, const map_location& loc, const unit& u2) const
{
const config &filter = cfg.child(filter_attacker);
if(!filter) {
return true;
}
return unit_filter(vconfig(filter)).set_use_flat_tod(ability == "illuminates").matches(*this, loc, u2);
}
static bool ability_apply_filter(const unit_map::const_iterator un, const unit_map::const_iterator up, const std::string& ability, const config& cfg, const map_location& loc, const map_location& opp_loc, bool attacker )
{
if(!up->ability_filter_fighter(ability, "filter_opponent", cfg, opp_loc, *un)){
return true;
}
if(!un->ability_filter_fighter(ability, "filter_student", cfg, loc, *up)){
return true;
}
if((attacker && !un->ability_filter_fighter(ability, "filter_attacker", cfg, loc, *up)) || (!attacker && !up->ability_filter_fighter(ability, "filter_attacker", cfg, opp_loc, *un))){
return true;
}
if((!attacker && !un->ability_filter_fighter(ability, "filter_defender", cfg, loc, *up)) || (attacker && !up->ability_filter_fighter(ability, "filter_defender", cfg, opp_loc, *un))){
return true;
}
return false;
}
bool leadership_affects_self(const std::string& ability,const unit_map& units, const map_location& loc, bool attacker, const_attack_ptr weapon,const_attack_ptr opp_weapon)
{
const unit_map::const_iterator un = units.find(loc);
if(un == units.end()) {
return false;
}
unit_ability_list abil = un->get_abilities(ability, weapon, opp_weapon);
for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) {
const std::string& apply_to = (*i->first)["apply_to"];
if(apply_to.empty() || apply_to == "both" || apply_to == "self") {
return true;
}
if(attacker && apply_to == "attacker") {
return true;
}
if(!attacker && apply_to == "defender") {
return true;
}
++i;
}
return false;
}
bool leadership_affects_opponent(const std::string& ability,const unit_map& units, const map_location& loc, bool attacker, const_attack_ptr weapon,const_attack_ptr opp_weapon)
{
const unit_map::const_iterator un = units.find(loc);
if(un == units.end()) {
return false;
}
unit_ability_list abil = un->get_abilities(ability, weapon, opp_weapon);
for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) {
const std::string& apply_to = (*i->first)["apply_to"];
if(apply_to == "both" || apply_to == "opponent") {
return true;
}
if(attacker && apply_to == "defender") {
return true;
}
if(!attacker && apply_to == "attacker") {
return true;
}
++i;
}
return false;
}
//sub function for emulate chance_to_hit,damage drains and attacks special.
std::pair<int, bool> ability_leadership(const std::string& ability,const unit_map& units, const map_location& loc, const map_location& opp_loc, bool attacker, int abil_value, bool backstab_pos, const_attack_ptr weapon, const_attack_ptr opp_weapon)
{
const unit_map::const_iterator un = units.find(loc);
const unit_map::const_iterator up = units.find(opp_loc);
if(un == units.end()) {
return {abil_value, false};
}
unit_ability_list abil = un->get_abilities(ability, weapon, opp_weapon);
for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) {
const config &filter = (*i->first).child("filter_opponent");
const config &filter_student = (*i->first).child("filter_student");
const config &filter_attacker = (*i->first).child("filter_attacker");
const config &filter_defender = (*i->first).child("filter_defender");
bool show_result = false;
if(up == units.end() && !filter_student && !filter && !filter_attacker && !filter_defender) {
show_result = un->abilities_filter_matches(*i->first, attacker, abil_value);
} else if(up == units.end() && (filter_student || filter || filter_attacker || filter_defender)) {
return {abil_value, false};
} else {
show_result = !(!un->abilities_filter_matches(*i->first, attacker, abil_value) || ability_apply_filter(un, up, ability, *i->first, loc, opp_loc, attacker));
}
if(!show_result) {
i = abil.erase(i);
} else {
++i;
}
}
if(!abil.empty()) {
unit_abilities::effect leader_effect(abil, abil_value, backstab_pos);
return {leader_effect.get_composite_value(), true};
}
return {abil_value, false};
}
//sub function for wmulate boolean special(slow, poison...)
bool bool_leadership(const std::string& ability,const unit_map& units, const map_location& loc, const map_location& opp_loc, bool attacker, const_attack_ptr weapon, const_attack_ptr opp_weapon)
{
const unit_map::const_iterator un = units.find(loc);
const unit_map::const_iterator up = units.find(opp_loc);
if(un == units.end() || up == units.end()) {
return false;
}
unit_ability_list abil = un->get_abilities(ability, weapon, opp_weapon);
for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) {
const std::string& active_on = (*i->first)["active_on"];
if(!(active_on.empty() || (attacker && active_on == "offense") || (!attacker && active_on == "defense")) || ability_apply_filter(un, up, ability, *i->first, loc, opp_loc, attacker)) {
i = abil.erase(i);
} else {
++i;
}
}
if(!abil.empty()) {
return true;
}
return false;
}
//emulate boolean special for self/adjacent and/or opponent.
bool attack_type::bool_ability(const std::string& ability) const
{
bool abil_bool= get_special_bool(ability);
const unit_map& units = display::get_singleton()->get_units();
if(leadership_affects_self(ability, units, self_loc_, is_attacker_, shared_from_this(), other_attack_)) {
abil_bool = get_special_bool(ability) || bool_leadership(ability, units, self_loc_, other_loc_, is_attacker_, shared_from_this(), other_attack_);
}
if(leadership_affects_opponent(ability, units, other_loc_, !is_attacker_, other_attack_, shared_from_this())) {
abil_bool = get_special_bool(ability) || bool_leadership(ability, units, other_loc_, self_loc_, !is_attacker_, other_attack_, shared_from_this());
}
return abil_bool;
}
//emulate numerical special for self/adjacent and/or opponent.
std::pair<int, bool> attack_type::combat_ability(const std::string& ability, int abil_value, bool backstab_pos) const
{
const unit_map& units = display::get_singleton()->get_units();
if(leadership_affects_self(ability, units, self_loc_, is_attacker_, shared_from_this(), other_attack_)) {
return ability_leadership(ability, units, self_loc_, other_loc_, is_attacker_, abil_value, backstab_pos, shared_from_this(), other_attack_);
}
if(leadership_affects_opponent(ability, units, other_loc_, !is_attacker_, other_attack_, shared_from_this())) {
return ability_leadership(ability, units, other_loc_,self_loc_, !is_attacker_, abil_value, backstab_pos, other_attack_, shared_from_this());
}
return {abil_value, false};
}
//end of emulate weapon special functions.
int combat_modifier(const unit_map& units,
const gamemap& map,
const map_location& loc,
unit_type::ALIGNMENT alignment,
bool is_fearless)
{
const tod_manager& tod_m = *resources::tod_manager;
const time_of_day& effective_tod = tod_m.get_illuminated_time_of_day(units, map, loc);
return combat_modifier(effective_tod, alignment, is_fearless);
}
int combat_modifier(const time_of_day& effective_tod,
unit_type::ALIGNMENT alignment,
bool is_fearless)
{
const tod_manager& tod_m = *resources::tod_manager;
const int lawful_bonus = effective_tod.lawful_bonus;
return generic_combat_modifier(lawful_bonus, alignment, is_fearless, tod_m.get_max_liminal_bonus());
}
int generic_combat_modifier(int lawful_bonus, unit_type::ALIGNMENT alignment, bool is_fearless, int max_liminal_bonus)
{
int bonus;
switch(alignment.v) {
case unit_type::ALIGNMENT::LAWFUL:
bonus = lawful_bonus;
break;
case unit_type::ALIGNMENT::NEUTRAL:
bonus = 0;
break;
case unit_type::ALIGNMENT::CHAOTIC:
bonus = -lawful_bonus;
break;
case unit_type::ALIGNMENT::LIMINAL:
bonus = std::max(0, max_liminal_bonus-std::abs(lawful_bonus));
break;
default:
bonus = 0;
}
if(is_fearless) {
bonus = std::max<int>(bonus, 0);
}
return bonus;
}
bool backstab_check(const map_location& attacker_loc,
const map_location& defender_loc,
const unit_map& units,
const std::vector<team>& teams)
{
const unit_map::const_iterator defender = units.find(defender_loc);
if(defender == units.end()) {
return false; // No defender
}
adjacent_loc_array_t adj;
get_adjacent_tiles(defender_loc, adj.data());
unsigned i;
for(i = 0; i < adj.size(); ++i) {
if(adj[i] == attacker_loc) {
break;
}
}
if(i >= 6) {
return false; // Attack not from adjacent location
}
const unit_map::const_iterator opp = units.find(adj[(i + 3) % 6]);
// No opposite unit.
if(opp == units.end()) {
return false;
}
if(opp->incapacitated()) {
return false;
}
// If sides aren't valid teams, then they are enemies.
if(std::size_t(defender->side() - 1) >= teams.size() || std::size_t(opp->side() - 1) >= teams.size()) {
return true;
}
// Defender and opposite are enemies.
if(teams[defender->side() - 1].is_enemy(opp->side())) {
return true;
}
// Defender and opposite are friends.
return false;
}
| spixi/wesnoth | src/actions/attack.cpp | C++ | gpl-2.0 | 57,856 |
#!/usr/bin/env python2
import copy
import Queue
import os
import socket
import struct
import subprocess
import sys
import threading
import time
import unittest
import dns
import dns.message
import libnacl
import libnacl.utils
class DNSDistTest(unittest.TestCase):
"""
Set up a dnsdist instance and responder threads.
Queries sent to dnsdist are relayed to the responder threads,
who reply with the response provided by the tests themselves
on a queue. Responder threads also queue the queries received
from dnsdist on a separate queue, allowing the tests to check
that the queries sent from dnsdist were as expected.
"""
_dnsDistPort = 5340
_dnsDistListeningAddr = "127.0.0.1"
_testServerPort = 5350
_toResponderQueue = Queue.Queue()
_fromResponderQueue = Queue.Queue()
_queueTimeout = 1
_dnsdistStartupDelay = 2.0
_dnsdist = None
_responsesCounter = {}
_shutUp = True
_config_template = """
"""
_config_params = ['_testServerPort']
_acl = ['127.0.0.1/32']
_consolePort = 5199
_consoleKey = None
@classmethod
def startResponders(cls):
print("Launching responders..")
cls._UDPResponder = threading.Thread(name='UDP Responder', target=cls.UDPResponder, args=[cls._testServerPort])
cls._UDPResponder.setDaemon(True)
cls._UDPResponder.start()
cls._TCPResponder = threading.Thread(name='TCP Responder', target=cls.TCPResponder, args=[cls._testServerPort])
cls._TCPResponder.setDaemon(True)
cls._TCPResponder.start()
@classmethod
def startDNSDist(cls, shutUp=True):
print("Launching dnsdist..")
conffile = 'dnsdist_test.conf'
params = tuple([getattr(cls, param) for param in cls._config_params])
print(params)
with open(conffile, 'w') as conf:
conf.write("-- Autogenerated by dnsdisttests.py\n")
conf.write(cls._config_template % params)
dnsdistcmd = [os.environ['DNSDISTBIN'], '-C', conffile,
'-l', '%s:%d' % (cls._dnsDistListeningAddr, cls._dnsDistPort) ]
for acl in cls._acl:
dnsdistcmd.extend(['--acl', acl])
print(' '.join(dnsdistcmd))
if shutUp:
with open(os.devnull, 'w') as fdDevNull:
cls._dnsdist = subprocess.Popen(dnsdistcmd, close_fds=True, stdout=fdDevNull)
else:
cls._dnsdist = subprocess.Popen(dnsdistcmd, close_fds=True)
if 'DNSDIST_FAST_TESTS' in os.environ:
delay = 0.5
else:
delay = cls._dnsdistStartupDelay
time.sleep(delay)
if cls._dnsdist.poll() is not None:
cls._dnsdist.kill()
sys.exit(cls._dnsdist.returncode)
@classmethod
def setUpSockets(cls):
print("Setting up UDP socket..")
cls._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
cls._sock.settimeout(2.0)
cls._sock.connect(("127.0.0.1", cls._dnsDistPort))
@classmethod
def setUpClass(cls):
cls.startResponders()
cls.startDNSDist(cls._shutUp)
cls.setUpSockets()
print("Launching tests..")
@classmethod
def tearDownClass(cls):
if 'DNSDIST_FAST_TESTS' in os.environ:
delay = 0.1
else:
delay = 1.0
if cls._dnsdist:
cls._dnsdist.terminate()
if cls._dnsdist.poll() is None:
time.sleep(delay)
if cls._dnsdist.poll() is None:
cls._dnsdist.kill()
cls._dnsdist.wait()
@classmethod
def _ResponderIncrementCounter(cls):
if threading.currentThread().name in cls._responsesCounter:
cls._responsesCounter[threading.currentThread().name] += 1
else:
cls._responsesCounter[threading.currentThread().name] = 1
@classmethod
def _getResponse(cls, request):
response = None
if len(request.question) != 1:
print("Skipping query with question count %d" % (len(request.question)))
return None
healthcheck = not str(request.question[0].name).endswith('tests.powerdns.com.')
if not healthcheck:
cls._ResponderIncrementCounter()
if not cls._toResponderQueue.empty():
response = cls._toResponderQueue.get(True, cls._queueTimeout)
if response:
response = copy.copy(response)
response.id = request.id
cls._fromResponderQueue.put(request, True, cls._queueTimeout)
if not response:
# unexpected query, or health check
response = dns.message.make_response(request)
return response
@classmethod
def UDPResponder(cls, port, ignoreTrailing=False):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.bind(("127.0.0.1", port))
while True:
data, addr = sock.recvfrom(4096)
request = dns.message.from_wire(data, ignore_trailing=ignoreTrailing)
response = cls._getResponse(request)
if not response:
continue
sock.settimeout(2.0)
sock.sendto(response.to_wire(), addr)
sock.settimeout(None)
sock.close()
@classmethod
def TCPResponder(cls, port, ignoreTrailing=False, multipleResponses=False):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
try:
sock.bind(("127.0.0.1", port))
except socket.error as e:
print("Error binding in the TCP responder: %s" % str(e))
sys.exit(1)
sock.listen(100)
while True:
(conn, _) = sock.accept()
conn.settimeout(2.0)
data = conn.recv(2)
(datalen,) = struct.unpack("!H", data)
data = conn.recv(datalen)
request = dns.message.from_wire(data, ignore_trailing=ignoreTrailing)
response = cls._getResponse(request)
if not response:
conn.close()
continue
wire = response.to_wire()
conn.send(struct.pack("!H", len(wire)))
conn.send(wire)
while multipleResponses:
if cls._toResponderQueue.empty():
break
response = cls._toResponderQueue.get(True, cls._queueTimeout)
if not response:
break
response = copy.copy(response)
response.id = request.id
wire = response.to_wire()
try:
conn.send(struct.pack("!H", len(wire)))
conn.send(wire)
except socket.error as e:
# some of the tests are going to close
# the connection on us, just deal with it
break
conn.close()
sock.close()
@classmethod
def sendUDPQuery(cls, query, response, useQueue=True, timeout=2.0, rawQuery=False):
if useQueue:
cls._toResponderQueue.put(response, True, timeout)
if timeout:
cls._sock.settimeout(timeout)
try:
if not rawQuery:
query = query.to_wire()
cls._sock.send(query)
data = cls._sock.recv(4096)
except socket.timeout:
data = None
finally:
if timeout:
cls._sock.settimeout(None)
receivedQuery = None
message = None
if useQueue and not cls._fromResponderQueue.empty():
receivedQuery = cls._fromResponderQueue.get(True, timeout)
if data:
message = dns.message.from_wire(data)
return (receivedQuery, message)
@classmethod
def openTCPConnection(cls, timeout=None):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if timeout:
sock.settimeout(timeout)
sock.connect(("127.0.0.1", cls._dnsDistPort))
return sock
@classmethod
def sendTCPQueryOverConnection(cls, sock, query, rawQuery=False):
if not rawQuery:
wire = query.to_wire()
else:
wire = query
sock.send(struct.pack("!H", len(wire)))
sock.send(wire)
@classmethod
def recvTCPResponseOverConnection(cls, sock):
message = None
data = sock.recv(2)
if data:
(datalen,) = struct.unpack("!H", data)
data = sock.recv(datalen)
if data:
message = dns.message.from_wire(data)
return message
@classmethod
def sendTCPQuery(cls, query, response, useQueue=True, timeout=2.0, rawQuery=False):
message = None
if useQueue:
cls._toResponderQueue.put(response, True, timeout)
sock = cls.openTCPConnection(timeout)
try:
cls.sendTCPQueryOverConnection(sock, query, rawQuery)
message = cls.recvTCPResponseOverConnection(sock)
except socket.timeout as e:
print("Timeout: %s" % (str(e)))
except socket.error as e:
print("Network error: %s" % (str(e)))
finally:
sock.close()
receivedQuery = None
if useQueue and not cls._fromResponderQueue.empty():
receivedQuery = cls._fromResponderQueue.get(True, timeout)
return (receivedQuery, message)
@classmethod
def sendTCPQueryWithMultipleResponses(cls, query, responses, useQueue=True, timeout=2.0, rawQuery=False):
if useQueue:
for response in responses:
cls._toResponderQueue.put(response, True, timeout)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if timeout:
sock.settimeout(timeout)
sock.connect(("127.0.0.1", cls._dnsDistPort))
messages = []
try:
if not rawQuery:
wire = query.to_wire()
else:
wire = query
sock.send(struct.pack("!H", len(wire)))
sock.send(wire)
while True:
data = sock.recv(2)
if not data:
break
(datalen,) = struct.unpack("!H", data)
data = sock.recv(datalen)
messages.append(dns.message.from_wire(data))
except socket.timeout as e:
print("Timeout: %s" % (str(e)))
except socket.error as e:
print("Network error: %s" % (str(e)))
finally:
sock.close()
receivedQuery = None
if useQueue and not cls._fromResponderQueue.empty():
receivedQuery = cls._fromResponderQueue.get(True, timeout)
return (receivedQuery, messages)
def setUp(self):
# This function is called before every tests
# Clear the responses counters
for key in self._responsesCounter:
self._responsesCounter[key] = 0
# Make sure the queues are empty, in case
# a previous test failed
while not self._toResponderQueue.empty():
self._toResponderQueue.get(False)
while not self._fromResponderQueue.empty():
self._fromResponderQueue.get(False)
@classmethod
def clearToResponderQueue(cls):
while not cls._toResponderQueue.empty():
cls._toResponderQueue.get(False)
@classmethod
def clearFromResponderQueue(cls):
while not cls._fromResponderQueue.empty():
cls._fromResponderQueue.get(False)
@classmethod
def clearResponderQueues(cls):
cls.clearToResponderQueue()
cls.clearFromResponderQueue()
@staticmethod
def generateConsoleKey():
return libnacl.utils.salsa_key()
@classmethod
def _encryptConsole(cls, command, nonce):
if cls._consoleKey is None:
return command
return libnacl.crypto_secretbox(command, nonce, cls._consoleKey)
@classmethod
def _decryptConsole(cls, command, nonce):
if cls._consoleKey is None:
return command
return libnacl.crypto_secretbox_open(command, nonce, cls._consoleKey)
@classmethod
def sendConsoleCommand(cls, command, timeout=1.0):
ourNonce = libnacl.utils.rand_nonce()
theirNonce = None
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if timeout:
sock.settimeout(timeout)
sock.connect(("127.0.0.1", cls._consolePort))
sock.send(ourNonce)
theirNonce = sock.recv(len(ourNonce))
halfNonceSize = len(ourNonce) / 2
readingNonce = ourNonce[0:halfNonceSize] + theirNonce[halfNonceSize:]
writingNonce = theirNonce[0:halfNonceSize] + ourNonce[halfNonceSize:]
msg = cls._encryptConsole(command, writingNonce)
sock.send(struct.pack("!I", len(msg)))
sock.send(msg)
data = sock.recv(4)
(responseLen,) = struct.unpack("!I", data)
data = sock.recv(responseLen)
response = cls._decryptConsole(data, readingNonce)
return response
| DrRemorse/pdns | regression-tests.dnsdist/dnsdisttests.py | Python | gpl-2.0 | 13,296 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.harmony.unpack200.bytecode.forms;
import org.apache.harmony.unpack200.SegmentConstantPool;
import org.apache.harmony.unpack200.bytecode.ByteCode;
import org.apache.harmony.unpack200.bytecode.CPInterfaceMethodRef;
import org.apache.harmony.unpack200.bytecode.OperandManager;
/**
* This class implements the byte code form for those bytecodes which have
* IMethod references (and only IMethod references).
*/
public class IMethodRefForm extends ReferenceForm {
public IMethodRefForm(int opcode, String name, int[] rewrite) {
super(opcode, name, rewrite);
}
protected int getOffset(OperandManager operandManager) {
return operandManager.nextIMethodRef();
}
protected int getPoolID() {
return SegmentConstantPool.CP_IMETHOD;
}
/*
* (non-Javadoc)
*
* @see org.apache.harmony.unpack200.bytecode.forms.ByteCodeForm#setByteCodeOperands(org.apache.harmony.unpack200.bytecode.ByteCode,
* org.apache.harmony.unpack200.bytecode.OperandTable,
* org.apache.harmony.unpack200.Segment)
*/
public void setByteCodeOperands(ByteCode byteCode,
OperandManager operandManager, int codeLength) {
super.setByteCodeOperands(byteCode, operandManager, codeLength);
final int count = ((CPInterfaceMethodRef) byteCode
.getNestedClassFileEntries()[0]).invokeInterfaceCount();
byteCode.getRewrite()[3] = count;
}
}
| skyHALud/codenameone | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/pack200/src/main/java/org/apache/harmony/unpack200/bytecode/forms/IMethodRefForm.java | Java | gpl-2.0 | 2,333 |
/*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.pouyadr.ui;
import android.animation.ObjectAnimator;
import android.animation.StateListAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Outline;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Html;
import android.text.InputType;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Base64;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.pouyadr.PhoneFormat.PhoneFormat;
import org.pouyadr.Pouya.Helper.GhostPorotocol;
import org.pouyadr.Pouya.Helper.ThemeChanger;
import org.pouyadr.Pouya.Setting.Setting;
import org.pouyadr.finalsoft.FontActivity;
import org.pouyadr.finalsoft.Fonts;
import org.pouyadr.messenger.AndroidUtilities;
import org.pouyadr.messenger.AnimationCompat.AnimatorListenerAdapterProxy;
import org.pouyadr.messenger.AnimationCompat.AnimatorSetProxy;
import org.pouyadr.messenger.AnimationCompat.ObjectAnimatorProxy;
import org.pouyadr.messenger.AnimationCompat.ViewProxy;
import org.pouyadr.messenger.ApplicationLoader;
import org.pouyadr.messenger.BuildVars;
import org.pouyadr.messenger.FileLoader;
import org.pouyadr.messenger.FileLog;
import org.pouyadr.messenger.LocaleController;
import org.pouyadr.messenger.MediaController;
import org.pouyadr.messenger.MessageObject;
import org.pouyadr.messenger.MessagesController;
import org.pouyadr.messenger.MessagesStorage;
import org.pouyadr.messenger.NotificationCenter;
import org.pouyadr.messenger.R;
import org.pouyadr.messenger.UserConfig;
import org.pouyadr.messenger.UserObject;
import org.pouyadr.messenger.browser.Browser;
import org.pouyadr.tgnet.ConnectionsManager;
import org.pouyadr.tgnet.RequestDelegate;
import org.pouyadr.tgnet.SerializedData;
import org.pouyadr.tgnet.TLObject;
import org.pouyadr.tgnet.TLRPC;
import org.pouyadr.ui.ActionBar.ActionBar;
import org.pouyadr.ui.ActionBar.ActionBarMenu;
import org.pouyadr.ui.ActionBar.ActionBarMenuItem;
import org.pouyadr.ui.ActionBar.BaseFragment;
import org.pouyadr.ui.ActionBar.BottomSheet;
import org.pouyadr.ui.ActionBar.Theme;
import org.pouyadr.ui.Adapters.BaseFragmentAdapter;
import org.pouyadr.ui.Cells.CheckBoxCell;
import org.pouyadr.ui.Cells.EmptyCell;
import org.pouyadr.ui.Cells.HeaderCell;
import org.pouyadr.ui.Cells.ShadowSectionCell;
import org.pouyadr.ui.Cells.TextCheckCell;
import org.pouyadr.ui.Cells.TextDetailSettingsCell;
import org.pouyadr.ui.Cells.TextInfoCell;
import org.pouyadr.ui.Cells.TextSettingsCell;
import org.pouyadr.ui.Components.AvatarDrawable;
import org.pouyadr.ui.Components.AvatarUpdater;
import org.pouyadr.ui.Components.BackupImageView;
import org.pouyadr.ui.Components.LayoutHelper;
import org.pouyadr.ui.Components.NumberPicker;
import java.io.File;
import java.util.ArrayList;
import java.util.Locale;
public class SettingsActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, PhotoViewer.PhotoViewerProvider {
private ListView listView;
private ListAdapter listAdapter;
private BackupImageView avatarImage;
private TextView nameTextView;
private TextView onlineTextView;
private ImageView writeButton;
private AnimatorSetProxy writeButtonAnimation;
private AvatarUpdater avatarUpdater = new AvatarUpdater();
private View extraHeightView;
private View shadowView;
private int extraHeight;
private int overscrollRow;
private int emptyRow;
private int numberSectionRow;
private int newgeramsectionrow;
private int newgeramsectionrow2;
private int ghostactivate;
private int showdateshamsi;
private int sendtyping;
private int showtimeago;
private int numberRow;
private int usernameRow;
private int settingsSectionRow;
private int settingsSectionRow2;
private int enableAnimationsRow;
private int notificationRow;
private int backgroundRow;
private int languageRow;
private int privacyRow;
private int mediaDownloadSection;
private int mediaDownloadSection2;
private int mobileDownloadRow;
private int wifiDownloadRow;
private int roamingDownloadRow;
private int saveToGalleryRow;
private int messagesSectionRow;
private int messagesSectionRow2;
private int customTabsRow;
private int directShareRow;
private int textSizeRow;
private int fontType;
private int stickersRow;
private int cacheRow;
private int raiseToSpeakRow;
private int sendByEnterRow;
private int supportSectionRow;
private int supportSectionRow2;
private int askQuestionRow;
private int telegramFaqRow;
private int privacyPolicyRow;
private int sendLogsRow;
private int clearLogsRow;
private int switchBackendButtonRow;
private int versionRow;
private int contactsSectionRow;
private int contactsReimportRow;
private int contactsSortRow;
private int autoplayGifsRow;
private int rowCount;
private final static int edit_name = 1;
private final static int logout = 2;
private int answeringmachinerow2;
private int answeringmachinerow;
private int tabletforceoverride;
private int anweringmachinactive;
private int answermachinetext;
private static class LinkMovementMethodMy extends LinkMovementMethod {
@Override
public boolean onTouchEvent(@NonNull TextView widget, @NonNull Spannable buffer, @NonNull MotionEvent event) {
try {
return super.onTouchEvent(widget, buffer, event);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return false;
}
}
@Override
public boolean onFragmentCreate() {
super.onFragmentCreate();
avatarUpdater.parentFragment = this;
avatarUpdater.delegate = new AvatarUpdater.AvatarUpdaterDelegate() {
@Override
public void didUploadedPhoto(TLRPC.InputFile file, TLRPC.PhotoSize small, TLRPC.PhotoSize big) {
TLRPC.TL_photos_uploadProfilePhoto req = new TLRPC.TL_photos_uploadProfilePhoto();
req.caption = "";
req.crop = new TLRPC.TL_inputPhotoCropAuto();
req.file = file;
req.geo_point = new TLRPC.TL_inputGeoPointEmpty();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user == null) {
user = UserConfig.getCurrentUser();
if (user == null) {
return;
}
MessagesController.getInstance().putUser(user, false);
} else {
UserConfig.setCurrentUser(user);
}
TLRPC.TL_photos_photo photo = (TLRPC.TL_photos_photo) response;
ArrayList<TLRPC.PhotoSize> sizes = photo.photo.sizes;
TLRPC.PhotoSize smallSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 100);
TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 1000);
user.photo = new TLRPC.TL_userProfilePhoto();
user.photo.photo_id = photo.photo.id;
if (smallSize != null) {
user.photo.photo_small = smallSize.location;
}
if (bigSize != null) {
user.photo.photo_big = bigSize.location;
} else if (smallSize != null) {
user.photo.photo_small = smallSize.location;
}
MessagesStorage.getInstance().clearUserPhotos(user.id);
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(user);
MessagesStorage.getInstance().putUsersAndChats(users, null, false, true);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);
UserConfig.saveConfig(true);
}
});
}
}
});
}
};
NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces);
rowCount = 0;
overscrollRow = rowCount++;
emptyRow = rowCount++;
numberSectionRow = rowCount++;
numberRow = rowCount++;
usernameRow = rowCount++;
newgeramsectionrow = rowCount++;
newgeramsectionrow2 = rowCount++;
ghostactivate = rowCount++;
sendtyping = rowCount++;
showtimeago = rowCount++;
showdateshamsi = rowCount++;
tabletforceoverride = rowCount++;
answeringmachinerow = rowCount++;
answeringmachinerow2 = rowCount++;
anweringmachinactive = rowCount++;
answermachinetext = rowCount++;
settingsSectionRow = rowCount++;
settingsSectionRow2 = rowCount++;
notificationRow = rowCount++;
privacyRow = rowCount++;
backgroundRow = rowCount++;
languageRow = rowCount++;
enableAnimationsRow = rowCount++;
mediaDownloadSection = rowCount++;
mediaDownloadSection2 = rowCount++;
mobileDownloadRow = rowCount++;
wifiDownloadRow = rowCount++;
roamingDownloadRow = rowCount++;
if (Build.VERSION.SDK_INT >= 11) {
autoplayGifsRow = rowCount++;
}
saveToGalleryRow = rowCount++;
messagesSectionRow = rowCount++;
messagesSectionRow2 = rowCount++;
customTabsRow = rowCount++;
if (Build.VERSION.SDK_INT >= 23) {
directShareRow = rowCount++;
}
textSizeRow = rowCount++;
fontType = rowCount++;
stickersRow = rowCount++;
cacheRow = rowCount++;
raiseToSpeakRow = rowCount++;
sendByEnterRow = rowCount++;
supportSectionRow = rowCount++;
supportSectionRow2 = rowCount++;
askQuestionRow = rowCount++;
telegramFaqRow = rowCount++;
privacyPolicyRow = rowCount++;
if (BuildVars.DEBUG_VERSION) {
sendLogsRow = rowCount++;
clearLogsRow = rowCount++;
switchBackendButtonRow = rowCount++;
}
versionRow = rowCount++;
//contactsSectionRow = rowCount++;
//contactsReimportRow = rowCount++;
//contactsSortRow = rowCount++;
MessagesController.getInstance().loadFullUser(UserConfig.getCurrentUser(), classGuid, true);
return true;
}
@Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
if (avatarImage != null) {
avatarImage.setImageDrawable(null);
}
MessagesController.getInstance().cancelLoadFullUser(UserConfig.getClientUserId());
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces);
avatarUpdater.clear();
}
@Override
public View createView(final Context context) {
actionBar.setBackgroundColor(ThemeChanger.getcurrent().getActionbarcolor());
actionBar.setItemsBackgroundColor(ThemeChanger.getcurrent().getActionbarcolor());
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAddToContainer(false);
extraHeight = 88;
if (AndroidUtilities.isTablet()) {
actionBar.setOccupyStatusBar(false);
}
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == edit_name) {
presentFragment(new ChangeNameActivity());
} else if (id == logout) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSureLogout", R.string.AreYouSureLogout));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MessagesController.getInstance().performLogout(true);
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
}
}
});
ActionBarMenu menu = actionBar.createMenu();
ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other);
item.addSubItem(edit_name, LocaleController.getString("EditName", R.string.EditName), 0);
item.addSubItem(logout, LocaleController.getString("LogOut", R.string.LogOut), 0);
listAdapter = new ListAdapter(context);
fragmentView = new FrameLayout(context) {
@Override
protected boolean drawChild(@NonNull Canvas canvas, @NonNull View child, long drawingTime) {
if (child == listView) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (parentLayout != null) {
int actionBarHeight = 0;
int childCount = getChildCount();
for (int a = 0; a < childCount; a++) {
View view = getChildAt(a);
if (view == child) {
continue;
}
if (view instanceof ActionBar && view.getVisibility() == VISIBLE) {
if (((ActionBar) view).getCastShadows()) {
actionBarHeight = view.getMeasuredHeight();
}
break;
}
}
parentLayout.drawHeaderShadow(canvas, actionBarHeight);
}
return result;
} else {
return super.drawChild(canvas, child, drawingTime);
}
}
};
FrameLayout frameLayout = (FrameLayout) fragmentView;
listView = new ListView(context);
listView.setDivider(null);
listView.setDividerHeight(0);
listView.setVerticalScrollBarEnabled(false);
AndroidUtilities.setListViewEdgeEffectColor(listView, AvatarDrawable.getProfileBackColorForId(5));
frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
if (i == textSizeRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("TextSize", R.string.TextSize));
final NumberPicker numberPicker = new NumberPicker(getParentActivity());
numberPicker.setMinValue(12);
numberPicker.setMaxValue(30);
numberPicker.setValue(MessagesController.getInstance().fontSize);
builder.setView(numberPicker);
builder.setNegativeButton(LocaleController.getString("Done", R.string.Done), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("fons_size", numberPicker.getValue());
MessagesController.getInstance().fontSize = numberPicker.getValue();
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
}
});
showDialog(builder.create());
} else if (i == fontType) {
// Toast.makeText(context, "ssssssssssss", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, FontActivity.class);
context.startActivity(intent);
} else if (i == enableAnimationsRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean animations = preferences.getBoolean("view_animations", true);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("view_animations", !animations);
editor.commit();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!animations);
}
} else if (i == notificationRow) {
presentFragment(new NotificationsSettingsActivity());
} else if (i == answermachinetext) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(LocaleController.getString("Answeringmachinetext", R.string.Answeringmachinetext));
final EditText input = new EditText(context);
input.setText(Setting.getAnsweringmachineText());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Setting.setAnsweringmachineText(input.getText().toString());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else if (i == backgroundRow) {
presentFragment(new WallpapersActivity());
} else if (i == askQuestionRow) {
if (getParentActivity() == null) {
return;
}
final TextView message = new TextView(getParentActivity());
message.setText(Html.fromHtml(LocaleController.getString("AskAQuestionInfo", R.string.AskAQuestionInfo)));
message.setTextSize(18);
message.setLinkTextColor(Theme.MSG_LINK_TEXT_COLOR);
// message.setTypeface(AndroidUtilities.getTypeface(org.pouyadr.finalsoft.Fonts.CurrentFont()));
message.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(5), AndroidUtilities.dp(8), AndroidUtilities.dp(6));
message.setMovementMethod(new LinkMovementMethodMy());
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setView(message);
builder.setPositiveButton(LocaleController.getString("AskButton", R.string.AskButton), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
performAskAQuestion();
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
} else if (i == sendLogsRow) {
sendLogs();
} else if (i == clearLogsRow) {
FileLog.cleanupLogs();
} else if (i == sendByEnterRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean send = preferences.getBoolean("send_by_enter", false);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("send_by_enter", !send);
editor.commit();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == ghostactivate) {
boolean send = Setting.getGhostMode();
GhostPorotocol.toggleGhostPortocol();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == sendtyping) {
boolean send = Setting.getSendTyping();
Setting.setSendTyping(!send);
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == anweringmachinactive) {
boolean send = Setting.getAnsweringMachine();
Setting.setAnsweringMachine(!send);
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == showtimeago) {
boolean send = Setting.getShowTimeAgo();
Setting.setShowTimeAgo(!send);
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == showdateshamsi) {
boolean send = Setting.getDatePersian();
Setting.setDatePersian(!send);
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == tabletforceoverride) {
boolean send = Setting.getTabletMode();
Setting.setTabletMode(!send);
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == raiseToSpeakRow) {
MediaController.getInstance().toogleRaiseToSpeak();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(MediaController.getInstance().canRaiseToSpeak());
}
} else if (i == autoplayGifsRow) {
MediaController.getInstance().toggleAutoplayGifs();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(MediaController.getInstance().canAutoplayGifs());
}
} else if (i == saveToGalleryRow) {
MediaController.getInstance().toggleSaveToGallery();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(MediaController.getInstance().canSaveToGallery());
}
} else if (i == customTabsRow) {
MediaController.getInstance().toggleCustomTabs();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(MediaController.getInstance().canCustomTabs());
}
} else if (i == directShareRow) {
MediaController.getInstance().toggleDirectShare();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(MediaController.getInstance().canDirectShare());
}
} else if (i == privacyRow) {
presentFragment(new PrivacySettingsActivity());
} else if (i == languageRow) {
presentFragment(new LanguageSelectActivity());
} else if (i == switchBackendButtonRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ConnectionsManager.getInstance().switchBackend();
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
} else if (i == telegramFaqRow) {
Browser.openUrl(getParentActivity(), LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
} else if (i == privacyPolicyRow) {
Browser.openUrl(getParentActivity(), LocaleController.getString("PrivacyPolicyUrl", R.string.PrivacyPolicyUrl));
} else if (i == contactsReimportRow) {
//not implemented
} else if (i == contactsSortRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("SortBy", R.string.SortBy));
builder.setItems(new CharSequence[]{
LocaleController.getString("Default", R.string.Default),
LocaleController.getString("SortFirstName", R.string.SortFirstName),
LocaleController.getString("SortLastName", R.string.SortLastName)
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("sortContactsBy", which);
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
} else if (i == wifiDownloadRow || i == mobileDownloadRow || i == roamingDownloadRow) {
if (getParentActivity() == null) {
return;
}
final boolean maskValues[] = new boolean[6];
BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
int mask = 0;
if (i == mobileDownloadRow) {
mask = MediaController.getInstance().mobileDataDownloadMask;
} else if (i == wifiDownloadRow) {
mask = MediaController.getInstance().wifiDownloadMask;
} else if (i == roamingDownloadRow) {
mask = MediaController.getInstance().roamingDownloadMask;
}
builder.setApplyTopPadding(false);
builder.setApplyBottomPadding(false);
LinearLayout linearLayout = new LinearLayout(getParentActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
for (int a = 0; a < 6; a++) {
String name = null;
if (a == 0) {
maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0;
name = LocaleController.getString("AttachPhoto", R.string.AttachPhoto);
} else if (a == 1) {
maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0;
name = LocaleController.getString("AttachAudio", R.string.AttachAudio);
} else if (a == 2) {
maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0;
name = LocaleController.getString("AttachVideo", R.string.AttachVideo);
} else if (a == 3) {
maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0;
name = LocaleController.getString("AttachDocument", R.string.AttachDocument);
} else if (a == 4) {
maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_MUSIC) != 0;
name = LocaleController.getString("AttachMusic", R.string.AttachMusic);
} else if (a == 5) {
if (Build.VERSION.SDK_INT >= 11) {
maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_GIF) != 0;
name = LocaleController.getString("AttachGif", R.string.AttachGif);
} else {
continue;
}
}
CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity());
checkBoxCell.setTag(a);
checkBoxCell.setBackgroundResource(R.drawable.list_selector);
linearLayout.addView(checkBoxCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
checkBoxCell.setText(name, "", maskValues[a], true);
checkBoxCell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBoxCell cell = (CheckBoxCell) v;
int num = (Integer) cell.getTag();
maskValues[num] = !maskValues[num];
cell.setChecked(maskValues[num], true);
}
});
}
BottomSheet.BottomSheetCell cell = new BottomSheet.BottomSheetCell(getParentActivity(), 1);
cell.setBackgroundResource(R.drawable.list_selector);
cell.setTextAndIcon(LocaleController.getString("Save", R.string.Save).toUpperCase(), 0);
cell.setTextColor(Theme.AUTODOWNLOAD_SHEET_SAVE_TEXT_COLOR);
cell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (visibleDialog != null) {
visibleDialog.dismiss();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
int newMask = 0;
for (int a = 0; a < 6; a++) {
if (maskValues[a]) {
if (a == 0) {
newMask |= MediaController.AUTODOWNLOAD_MASK_PHOTO;
} else if (a == 1) {
newMask |= MediaController.AUTODOWNLOAD_MASK_AUDIO;
} else if (a == 2) {
newMask |= MediaController.AUTODOWNLOAD_MASK_VIDEO;
} else if (a == 3) {
newMask |= MediaController.AUTODOWNLOAD_MASK_DOCUMENT;
} else if (a == 4) {
newMask |= MediaController.AUTODOWNLOAD_MASK_MUSIC;
} else if (a == 5) {
newMask |= MediaController.AUTODOWNLOAD_MASK_GIF;
}
}
}
SharedPreferences.Editor editor = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit();
if (i == mobileDownloadRow) {
editor.putInt("mobileDataDownloadMask", newMask);
MediaController.getInstance().mobileDataDownloadMask = newMask;
} else if (i == wifiDownloadRow) {
editor.putInt("wifiDownloadMask", newMask);
MediaController.getInstance().wifiDownloadMask = newMask;
} else if (i == roamingDownloadRow) {
editor.putInt("roamingDownloadMask", newMask);
MediaController.getInstance().roamingDownloadMask = newMask;
}
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
}
});
linearLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
builder.setCustomView(linearLayout);
showDialog(builder.create());
} else if (i == usernameRow) {
presentFragment(new ChangeUsernameActivity());
} else if (i == numberRow) {
presentFragment(new ChangePhoneHelpActivity());
} else if (i == stickersRow) {
presentFragment(new StickersActivity());
} else if (i == cacheRow) {
presentFragment(new CacheControlActivity());
}
}
});
frameLayout.addView(actionBar);
extraHeightView = new View(context);
ViewProxy.setPivotY(extraHeightView, 0);
extraHeightView.setBackgroundColor(ThemeChanger.getcurrent().getActionbarcolor());
frameLayout.addView(extraHeightView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 88));
shadowView = new View(context);
shadowView.setBackgroundResource(R.drawable.header_shadow);
frameLayout.addView(shadowView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3));
avatarImage = new BackupImageView(context);
avatarImage.setRoundRadius(AndroidUtilities.dp(21));
ViewProxy.setPivotX(avatarImage, 0);
ViewProxy.setPivotY(avatarImage, 0);
frameLayout.addView(avatarImage, LayoutHelper.createFrame(42, 42, Gravity.TOP | Gravity.LEFT, 64, 0, 0, 0));
avatarImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user != null && user.photo != null && user.photo.photo_big != null) {
PhotoViewer.getInstance().setParentActivity(getParentActivity());
PhotoViewer.getInstance().openPhoto(user.photo.photo_big, SettingsActivity.this);
}
}
});
nameTextView = new TextView(context);
nameTextView.setTextColor(0xffffffff);
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
nameTextView.setLines(1);
nameTextView.setMaxLines(1);
nameTextView.setSingleLine(true);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
nameTextView.setGravity(Gravity.LEFT);
nameTextView.setTypeface(AndroidUtilities.getTypeface(org.pouyadr.finalsoft.Fonts.CurrentFont()));
ViewProxy.setPivotX(nameTextView, 0);
ViewProxy.setPivotY(nameTextView, 0);
frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, 48, 0));
onlineTextView = new TextView(context);
onlineTextView.setTextColor(AvatarDrawable.getProfileTextColorForId(5));
onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
onlineTextView.setLines(1);
onlineTextView.setMaxLines(1);
onlineTextView.setSingleLine(true);
onlineTextView.setEllipsize(TextUtils.TruncateAt.END);
onlineTextView.setGravity(Gravity.LEFT);
frameLayout.addView(onlineTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, 48, 0));
writeButton = new ImageView(context);
writeButton.setBackgroundResource(R.drawable.floating_user_states);
writeButton.setImageResource(R.drawable.floating_camera);
writeButton.setScaleType(ImageView.ScaleType.CENTER);
if (Build.VERSION.SDK_INT >= 21) {
StateListAnimator animator = new StateListAnimator();
animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
animator.addState(new int[]{}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
writeButton.setStateListAnimator(animator);
writeButton.setOutlineProvider(new ViewOutlineProvider() {
@SuppressLint("NewApi")
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
}
});
}
frameLayout.addView(writeButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.RIGHT | Gravity.TOP, 0, 0, 16, 0));
writeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
CharSequence[] items;
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user == null) {
user = UserConfig.getCurrentUser();
}
if (user == null) {
return;
}
boolean fullMenu = false;
if (user.photo != null && user.photo.photo_big != null && !(user.photo instanceof TLRPC.TL_userProfilePhotoEmpty)) {
items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)};
fullMenu = true;
} else {
items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)};
}
final boolean full = fullMenu;
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
avatarUpdater.openCamera();
} else if (i == 1) {
avatarUpdater.openGallery();
} else if (i == 2) {
MessagesController.getInstance().deleteUserPhoto(null);
}
}
});
showDialog(builder.create());
}
});
needLayout();
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (totalItemCount == 0) {
return;
}
int height = 0;
View child = view.getChildAt(0);
if (child != null) {
if (firstVisibleItem == 0) {
height = AndroidUtilities.dp(88) + (child.getTop() < 0 ? child.getTop() : 0);
}
if (extraHeight != height) {
extraHeight = height;
needLayout();
}
}
}
});
return fragmentView;
}
@Override
protected void onDialogDismiss(Dialog dialog) {
MediaController.getInstance().checkAutodownloadSettings();
}
@Override
public void updatePhotoAtIndex(int index) {
}
@Override
public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
if (fileLocation == null) {
return null;
}
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user != null && user.photo != null && user.photo.photo_big != null) {
TLRPC.FileLocation photoBig = user.photo.photo_big;
if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) {
int coords[] = new int[2];
avatarImage.getLocationInWindow(coords);
PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject();
object.viewX = coords[0];
object.viewY = coords[1] - AndroidUtilities.statusBarHeight;
object.parentView = avatarImage;
object.imageReceiver = avatarImage.getImageReceiver();
object.user_id = UserConfig.getClientUserId();
object.thumb = object.imageReceiver.getBitmap();
object.size = -1;
object.radius = avatarImage.getImageReceiver().getRoundRadius();
object.scale = ViewProxy.getScaleX(avatarImage);
return object;
}
}
return null;
}
@Override
public Bitmap getThumbForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
return null;
}
@Override
public void willSwitchFromPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
}
@Override
public void willHidePhotoViewer() {
avatarImage.getImageReceiver().setVisible(true, true);
}
@Override
public boolean isPhotoChecked(int index) {
return false;
}
@Override
public void setPhotoChecked(int index) {
}
@Override
public boolean cancelButtonPressed() {
return true;
}
@Override
public void sendButtonPressed(int index) {
}
@Override
public int getSelectedCount() {
return 0;
}
public void performAskAQuestion() {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
int uid = preferences.getInt("support_id", 0);
TLRPC.User supportUser = null;
if (uid != 0) {
supportUser = MessagesController.getInstance().getUser(uid);
if (supportUser == null) {
String userString = preferences.getString("support_user", null);
if (userString != null) {
try {
byte[] datacentersBytes = Base64.decode(userString, Base64.DEFAULT);
if (datacentersBytes != null) {
SerializedData data = new SerializedData(datacentersBytes);
supportUser = TLRPC.User.TLdeserialize(data, data.readInt32(false), false);
if (supportUser != null && supportUser.id == 333000) {
supportUser = null;
}
data.cleanup();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
supportUser = null;
}
}
}
}
if (supportUser == null) {
final ProgressDialog progressDialog = new ProgressDialog(getParentActivity());
progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
TLRPC.TL_help_getSupport req = new TLRPC.TL_help_getSupport();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
final TLRPC.TL_help_support res = (TLRPC.TL_help_support) response;
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("support_id", res.user.id);
SerializedData data = new SerializedData();
res.user.serializeToStream(data);
editor.putString("support_user", Base64.encodeToString(data.toByteArray(), Base64.DEFAULT));
editor.commit();
data.cleanup();
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(res.user);
MessagesStorage.getInstance().putUsersAndChats(users, null, true, true);
MessagesController.getInstance().putUser(res.user, false);
Bundle args = new Bundle();
args.putInt("user_id", res.user.id);
presentFragment(new ChatActivity(args));
}
});
} else {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
}
});
} else {
MessagesController.getInstance().putUser(supportUser, true);
Bundle args = new Bundle();
args.putInt("user_id", supportUser.id);
presentFragment(new ChatActivity(args));
}
}
@Override
public void onActivityResultFragment(int requestCode, int resultCode, Intent data) {
avatarUpdater.onActivityResult(requestCode, resultCode, data);
}
@Override
public void saveSelfArgs(Bundle args) {
if (avatarUpdater != null && avatarUpdater.currentPicturePath != null) {
args.putString("path", avatarUpdater.currentPicturePath);
}
}
@Override
public void restoreSelfArgs(Bundle args) {
if (avatarUpdater != null) {
avatarUpdater.currentPicturePath = args.getString("path");
}
}
@Override
public void didReceivedNotification(int id, Object... args) {
if (id == NotificationCenter.updateInterfaces) {
int mask = (Integer) args[0];
if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) {
updateUserData();
}
}
}
@Override
public void onResume() {
super.onResume();
if (listAdapter != null) {
listAdapter.notifyDataSetChanged();
}
updateUserData();
fixLayout();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
fixLayout();
}
private void needLayout() {
FrameLayout.LayoutParams layoutParams;
int newTop = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight();
if (listView != null) {
layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams();
if (layoutParams.topMargin != newTop) {
layoutParams.topMargin = newTop;
listView.setLayoutParams(layoutParams);
ViewProxy.setTranslationY(extraHeightView, newTop);
}
}
if (avatarImage != null) {
float diff = extraHeight / (float) AndroidUtilities.dp(88);
ViewProxy.setScaleY(extraHeightView, diff);
ViewProxy.setTranslationY(shadowView, newTop + extraHeight);
if (Build.VERSION.SDK_INT < 11) {
layoutParams = (FrameLayout.LayoutParams) writeButton.getLayoutParams();
layoutParams.topMargin = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight() + extraHeight - AndroidUtilities.dp(29.5f);
writeButton.setLayoutParams(layoutParams);
} else {
ViewProxy.setTranslationY(writeButton, (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight() + extraHeight - AndroidUtilities.dp(29.5f));
}
final boolean setVisible = diff > 0.2f;
boolean currentVisible = writeButton.getTag() == null;
if (setVisible != currentVisible) {
if (setVisible) {
writeButton.setTag(null);
writeButton.setVisibility(View.VISIBLE);
} else {
writeButton.setTag(0);
}
if (writeButtonAnimation != null) {
AnimatorSetProxy old = writeButtonAnimation;
writeButtonAnimation = null;
old.cancel();
}
writeButtonAnimation = new AnimatorSetProxy();
if (setVisible) {
writeButtonAnimation.setInterpolator(new DecelerateInterpolator());
writeButtonAnimation.playTogether(
ObjectAnimatorProxy.ofFloat(writeButton, "scaleX", 1.0f),
ObjectAnimatorProxy.ofFloat(writeButton, "scaleY", 1.0f),
ObjectAnimatorProxy.ofFloat(writeButton, "alpha", 1.0f)
);
} else {
writeButtonAnimation.setInterpolator(new AccelerateInterpolator());
writeButtonAnimation.playTogether(
ObjectAnimatorProxy.ofFloat(writeButton, "scaleX", 0.2f),
ObjectAnimatorProxy.ofFloat(writeButton, "scaleY", 0.2f),
ObjectAnimatorProxy.ofFloat(writeButton, "alpha", 0.0f)
);
}
writeButtonAnimation.setDuration(150);
writeButtonAnimation.addListener(new AnimatorListenerAdapterProxy() {
@Override
public void onAnimationEnd(Object animation) {
if (writeButtonAnimation != null && writeButtonAnimation.equals(animation)) {
writeButton.clearAnimation();
writeButton.setVisibility(setVisible ? View.VISIBLE : View.GONE);
writeButtonAnimation = null;
}
}
});
writeButtonAnimation.start();
}
ViewProxy.setScaleX(avatarImage, (42 + 18 * diff) / 42.0f);
ViewProxy.setScaleY(avatarImage, (42 + 18 * diff) / 42.0f);
float avatarY = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight() / 2.0f * (1.0f + diff) - 21 * AndroidUtilities.density + 27 * AndroidUtilities.density * diff;
ViewProxy.setTranslationX(avatarImage, -AndroidUtilities.dp(47) * diff);
ViewProxy.setTranslationY(avatarImage, (float) Math.ceil(avatarY));
ViewProxy.setTranslationX(nameTextView, -21 * AndroidUtilities.density * diff);
ViewProxy.setTranslationY(nameTextView, (float) Math.floor(avatarY) - (float) Math.ceil(AndroidUtilities.density) + (float) Math.floor(7 * AndroidUtilities.density * diff));
ViewProxy.setTranslationX(onlineTextView, -21 * AndroidUtilities.density * diff);
ViewProxy.setTranslationY(onlineTextView, (float) Math.floor(avatarY) + AndroidUtilities.dp(22) + (float) Math.floor(11 * AndroidUtilities.density) * diff);
ViewProxy.setScaleX(nameTextView, 1.0f + 0.12f * diff);
ViewProxy.setScaleY(nameTextView, 1.0f + 0.12f * diff);
}
}
private void fixLayout() {
if (fragmentView == null) {
return;
}
fragmentView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
if (fragmentView != null) {
needLayout();
fragmentView.getViewTreeObserver().removeOnPreDrawListener(this);
}
return true;
}
});
}
private void updateUserData() {
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
TLRPC.FileLocation photo = null;
TLRPC.FileLocation photoBig = null;
if (user.photo != null) {
photo = user.photo.photo_small;
photoBig = user.photo.photo_big;
}
AvatarDrawable avatarDrawable = new AvatarDrawable(user, true);
avatarDrawable.setColor(Theme.ACTION_BAR_MAIN_AVATAR_COLOR);
if (avatarImage != null) {
avatarImage.setImage(photo, "50_50", avatarDrawable);
avatarImage.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false);
nameTextView.setText(UserObject.getUserName(user));
onlineTextView.setText(LocaleController.getString("Online", R.string.Online));
avatarImage.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false);
}
}
private void sendLogs() {
try {
ArrayList<Uri> uris = new ArrayList<>();
File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null);
File dir = new File(sdCard.getAbsolutePath() + "/logs");
File[] files = dir.listFiles();
for (File file : files) {
uris.add(Uri.fromFile(file));
}
if (uris.isEmpty()) {
return;
}
Intent i = new Intent(Intent.ACTION_SEND_MULTIPLE);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{BuildVars.SEND_LOGS_EMAIL});
i.putExtra(Intent.EXTRA_SUBJECT, "last logs");
i.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
getParentActivity().startActivityForResult(Intent.createChooser(i, "Select email application."), 500);
} catch (Exception e) {
e.printStackTrace();
}
}
private class ListAdapter extends BaseFragmentAdapter {
private Context mContext;
public ListAdapter(Context context) {
mContext = context;
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int i) {
return i == textSizeRow || i == fontType || i == tabletforceoverride || i == anweringmachinactive || i == answermachinetext || i == sendtyping || i == showdateshamsi || i == showtimeago || i == ghostactivate || i == enableAnimationsRow || i == notificationRow || i == backgroundRow || i == numberRow ||
i == askQuestionRow || i == sendLogsRow || i == sendByEnterRow || i == autoplayGifsRow || i == privacyRow || i == wifiDownloadRow ||
i == mobileDownloadRow || i == clearLogsRow || i == roamingDownloadRow || i == languageRow || i == usernameRow ||
i == switchBackendButtonRow || i == telegramFaqRow || i == contactsSortRow || i == contactsReimportRow || i == saveToGalleryRow ||
i == stickersRow || i == cacheRow || i == raiseToSpeakRow || i == privacyPolicyRow || i == customTabsRow || i == directShareRow;
}
@Override
public int getCount() {
return rowCount;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
int type = getItemViewType(i);
if (type == 0) {
if (view == null) {
view = new EmptyCell(mContext);
}
if (i == overscrollRow) {
((EmptyCell) view).setHeight(AndroidUtilities.dp(88));
} else {
((EmptyCell) view).setHeight(AndroidUtilities.dp(16));
}
} else if (type == 1) {
if (view == null) {
view = new ShadowSectionCell(mContext);
}
} else if (type == 2) {
if (view == null) {
view = new TextSettingsCell(mContext);
}
TextSettingsCell textCell = (TextSettingsCell) view;
if (i == textSizeRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
int size = preferences.getInt("fons_size", AndroidUtilities.isTablet() ? 18 : 16);
textCell.setTextAndValue(LocaleController.getString("TextSize", R.string.TextSize), String.format("%d", size), true);
} else if (i == fontType) {
textCell.setTextAndValue( "نوع خط نوشتاری", Fonts.CurrentFont().replace("fonts/","").replace(".ttf",""), true);
} else if (i == languageRow) {
textCell.setTextAndValue(LocaleController.getString("Language", R.string.Language), LocaleController.getCurrentLanguageName(), true);
} else if (i == contactsSortRow) {
String value;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
int sort = preferences.getInt("sortContactsBy", 0);
if (sort == 0) {
value = LocaleController.getString("Default", R.string.Default);
} else if (sort == 1) {
value = LocaleController.getString("FirstName", R.string.SortFirstName);
} else {
value = LocaleController.getString("LastName", R.string.SortLastName);
}
textCell.setTextAndValue(LocaleController.getString("SortBy", R.string.SortBy), value, true);
} else if (i == notificationRow) {
textCell.setText(LocaleController.getString("NotificationsAndSounds", R.string.NotificationsAndSounds), true);
} else if (i == backgroundRow) {
textCell.setText(LocaleController.getString("ChatBackground", R.string.ChatBackground), true);
} else if (i == answermachinetext) {
textCell.setTextAndValue(LocaleController.getString("Answeringmachinetext", R.string.Answeringmachinetext), Setting.getAnsweringmachineText(), true);
} else if (i == sendLogsRow) {
textCell.setText("Send Logs", true);
} else if (i == clearLogsRow) {
textCell.setText("Clear Logs", true);
} else if (i == askQuestionRow) {
textCell.setText(LocaleController.getString("AskAQuestion", R.string.AskAQuestion), true);
} else if (i == privacyRow) {
textCell.setText(LocaleController.getString("PrivacySettings", R.string.PrivacySettings), true);
} else if (i == switchBackendButtonRow) {
textCell.setText("Switch Backend", true);
} else if (i == telegramFaqRow) {
textCell.setText(LocaleController.getString("TelegramFAQ", R.string.TelegramFaq), true);
} else if (i == contactsReimportRow) {
textCell.setText(LocaleController.getString("ImportContacts", R.string.ImportContacts), true);
} else if (i == stickersRow) {
textCell.setText(LocaleController.getString("Stickers", R.string.Stickers), true);
} else if (i == cacheRow) {
textCell.setText(LocaleController.getString("CacheSettings", R.string.CacheSettings), true);
} else if (i == privacyPolicyRow) {
textCell.setText(LocaleController.getString("PrivacyPolicy", R.string.PrivacyPolicy), true);
}
} else if (type == 3) {
if (view == null) {
view = new TextCheckCell(mContext);
}
TextCheckCell textCell = (TextCheckCell) view;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
if (i == enableAnimationsRow) {
textCell.setTextAndCheck(LocaleController.getString("EnableAnimations", R.string.EnableAnimations), preferences.getBoolean("view_animations", true), false);
} else if (i == sendByEnterRow) {
textCell.setTextAndCheck(LocaleController.getString("SendByEnter", R.string.SendByEnter), preferences.getBoolean("send_by_enter", false), false);
} else if (i == ghostactivate) {
textCell.setTextAndValueAndCheck(LocaleController.getString("GhostMode", R.string.GhostMode), LocaleController.getString("GhostModeInfo", R.string.GhostModeInfo), Setting.getGhostMode(), true, true);
} else if (i == sendtyping) {
textCell.setTextAndValueAndCheck(LocaleController.getString("HideTypingState", R.string.HideTypingState), LocaleController.getString("HideTypingStateinfo", R.string.HideTypingStateinfo), Setting.getSendTyping(), true, true);
} else if (i == anweringmachinactive) {
textCell.setTextAndValueAndCheck(LocaleController.getString("Answeringmachineenable", R.string.Answeringmachineenable), LocaleController.getString("Answeringmachineenableinfo", R.string.Answeringmachineenableinfo), Setting.getAnsweringMachine(), true, true);
} else if (i == showtimeago) {
textCell.setTextAndValueAndCheck(LocaleController.getString("showtimeago", R.string.showtimeago), LocaleController.getString("showtimeagoinfo", R.string.showtimeagoinfo), Setting.getShowTimeAgo(), true, true);
} else if (i == showdateshamsi) {
textCell.setTextAndValueAndCheck(LocaleController.getString("showshamsidate", R.string.Showshamsidate), LocaleController.getString("showshamsidateinfo", R.string.showshamsidateinfo), Setting.getDatePersian(), true, true);
} else if (i == tabletforceoverride) {
textCell.setTextAndValueAndCheck(LocaleController.getString("TabletMode", R.string.TabletMode), LocaleController.getString("tabletmodeinfo", R.string.tabletmodeinfo), Setting.getTabletMode(), true, true);
} else if (i == saveToGalleryRow) {
textCell.setTextAndCheck(LocaleController.getString("SaveToGallerySettings", R.string.SaveToGallerySettings), MediaController.getInstance().canSaveToGallery(), false);
} else if (i == autoplayGifsRow) {
textCell.setTextAndCheck(LocaleController.getString("AutoplayGifs", R.string.AutoplayGifs), MediaController.getInstance().canAutoplayGifs(), true);
} else if (i == raiseToSpeakRow) {
textCell.setTextAndCheck(LocaleController.getString("RaiseToSpeak", R.string.RaiseToSpeak), MediaController.getInstance().canRaiseToSpeak(), true);
} else if (i == customTabsRow) {
textCell.setTextAndValueAndCheck(LocaleController.getString("ChromeCustomTabs", R.string.ChromeCustomTabs), LocaleController.getString("ChromeCustomTabsInfo", R.string.ChromeCustomTabsInfo), MediaController.getInstance().canCustomTabs(), false, true);
} else if (i == directShareRow) {
textCell.setTextAndValueAndCheck(LocaleController.getString("DirectShare", R.string.DirectShare), LocaleController.getString("DirectShareInfo", R.string.DirectShareInfo), MediaController.getInstance().canDirectShare(), false, true);
}
} else if (type == 4) {
if (view == null) {
view = new HeaderCell(mContext);
}
if (i == answeringmachinerow2) {
((HeaderCell) view).setText(LocaleController.getString("AnsweringMachin", R.string.answeringmachine));
} else if (i == settingsSectionRow2) {
((HeaderCell) view).setText(LocaleController.getString("SETTINGS", R.string.SETTINGS));
} else if (i == supportSectionRow2) {
((HeaderCell) view).setText(LocaleController.getString("Support", R.string.Support));
} else if (i == messagesSectionRow2) {
((HeaderCell) view).setText(LocaleController.getString("MessagesSettings", R.string.MessagesSettings));
} else if (i == mediaDownloadSection2) {
((HeaderCell) view).setText(LocaleController.getString("AutomaticMediaDownload", R.string.AutomaticMediaDownload));
} else if (i == numberSectionRow) {
((HeaderCell) view).setText(LocaleController.getString("Info", R.string.Info));
} else if (i == newgeramsectionrow2) {
((HeaderCell) view).setText(LocaleController.getString("NewGramSettings", R.string.newgeramsettings));
}
} else if (type == 5) {
if (view == null) {
view = new TextInfoCell(mContext);
try {
PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0);
int code = pInfo.versionCode / 10;
String abi = "";
switch (pInfo.versionCode % 10) {
case 0:
abi = "arm";
break;
case 1:
abi = "arm-v7a";
break;
case 2:
abi = "x86";
break;
case 3:
abi = "universal";
break;
}
((TextInfoCell) view).setText(String.format(Locale.US, "AriaGram for Android v%s (%d) %s", pInfo.versionName, code, abi));
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
} else if (type == 6) {
if (view == null) {
view = new TextDetailSettingsCell(mContext);
}
TextDetailSettingsCell textCell = (TextDetailSettingsCell) view;
if (i == mobileDownloadRow || i == wifiDownloadRow || i == roamingDownloadRow) {
int mask;
String value;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
if (i == mobileDownloadRow) {
value = LocaleController.getString("WhenUsingMobileData", R.string.WhenUsingMobileData);
mask = MediaController.getInstance().mobileDataDownloadMask;
} else if (i == wifiDownloadRow) {
value = LocaleController.getString("WhenConnectedOnWiFi", R.string.WhenConnectedOnWiFi);
mask = MediaController.getInstance().wifiDownloadMask;
} else {
value = LocaleController.getString("WhenRoaming", R.string.WhenRoaming);
mask = MediaController.getInstance().roamingDownloadMask;
}
String text = "";
if ((mask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0) {
text += LocaleController.getString("AttachPhoto", R.string.AttachPhoto);
}
if ((mask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0) {
if (text.length() != 0) {
text += ", ";
}
text += LocaleController.getString("AttachAudio", R.string.AttachAudio);
}
if ((mask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0) {
if (text.length() != 0) {
text += ", ";
}
text += LocaleController.getString("AttachVideo", R.string.AttachVideo);
}
if ((mask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0) {
if (text.length() != 0) {
text += ", ";
}
text += LocaleController.getString("AttachDocument", R.string.AttachDocument);
}
if ((mask & MediaController.AUTODOWNLOAD_MASK_MUSIC) != 0) {
if (text.length() != 0) {
text += ", ";
}
text += LocaleController.getString("AttachMusic", R.string.AttachMusic);
}
if (Build.VERSION.SDK_INT >= 11) {
if ((mask & MediaController.AUTODOWNLOAD_MASK_GIF) != 0) {
if (text.length() != 0) {
text += ", ";
}
text += LocaleController.getString("AttachGif", R.string.AttachGif);
}
}
if (text.length() == 0) {
text = LocaleController.getString("NoMediaAutoDownload", R.string.NoMediaAutoDownload);
}
textCell.setTextAndValue(value, text, true);
} else if (i == numberRow) {
TLRPC.User user = UserConfig.getCurrentUser();
String value;
if (user != null && user.phone != null && user.phone.length() != 0) {
value = PhoneFormat.getInstance().format("+" + user.phone);
} else {
value = LocaleController.getString("NumberUnknown", R.string.NumberUnknown);
}
textCell.setTextAndValue(value, LocaleController.getString("Phone", R.string.Phone), true);
} else if (i == usernameRow) {
TLRPC.User user = UserConfig.getCurrentUser();
String value;
if (user != null && user.username != null && user.username.length() != 0) {
value = "@" + user.username;
} else {
value = LocaleController.getString("UsernameEmpty", R.string.UsernameEmpty);
}
// Log.i("username",""+ user.username);
textCell.setTextAndValue(value, LocaleController.getString("Username", R.string.Username), false);
}
}
return view;
}
@Override
public int getItemViewType(int i) {
if (i == emptyRow || i == overscrollRow) {
return 0;
}
if (i == answeringmachinerow || i == settingsSectionRow || i == newgeramsectionrow || i == supportSectionRow || i == messagesSectionRow || i == mediaDownloadSection || i == contactsSectionRow) {
return 1;
} else if (i == enableAnimationsRow || i == tabletforceoverride || i == showdateshamsi || i == showtimeago || i == anweringmachinactive || i == sendtyping || i == ghostactivate || i == sendByEnterRow || i == saveToGalleryRow || i == autoplayGifsRow || i == raiseToSpeakRow || i == customTabsRow || i == directShareRow) {
return 3;
} else if (i == notificationRow || i == answermachinetext || i == backgroundRow || i == askQuestionRow || i == sendLogsRow || i == privacyRow || i == clearLogsRow || i == switchBackendButtonRow || i == telegramFaqRow || i == contactsReimportRow || i == textSizeRow || i == fontType || i == languageRow || i == contactsSortRow || i == stickersRow || i == cacheRow || i == privacyPolicyRow) {
return 2;
} else if (i == versionRow) {
return 5;
} else if (i == wifiDownloadRow || i == mobileDownloadRow || i == roamingDownloadRow || i == numberRow || i == usernameRow) {
return 6;
} else if (i == settingsSectionRow2 || i == answeringmachinerow2 || i == newgeramsectionrow2 || i == messagesSectionRow2 || i == supportSectionRow2 || i == numberSectionRow || i == mediaDownloadSection2) {
return 4;
} else {
return 2;
}
}
@Override
public int getViewTypeCount() {
return 7;
}
@Override
public boolean isEmpty() {
return false;
}
}
}
| Fakkar/TeligramFars | TMessagesProj/src/main/java/com/teligramfars/ui/SettingsActivity.java | Java | gpl-2.0 | 80,162 |
/***************************************************************************
Copyright (C) 2014-2015 by Nick Thijssen <lamah83@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
***************************************************************************/
using test.Controls;
namespace test
{
partial class TestTransform
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.bottomPanel = new System.Windows.Forms.FlowLayoutPanel();
this.cancelButton = new System.Windows.Forms.Button();
this.okButton = new System.Windows.Forms.Button();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel();
this.xNumeric = new System.Windows.Forms.NumericUpDown();
this.yNumeric = new System.Windows.Forms.NumericUpDown();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.wNumeric = new System.Windows.Forms.NumericUpDown();
this.hNumeric = new System.Windows.Forms.NumericUpDown();
this.positionLabel = new System.Windows.Forms.Label();
this.sizeLabel = new System.Windows.Forms.Label();
this.rotationLabel = new System.Windows.Forms.Label();
this.positionalalignmentLabel = new System.Windows.Forms.Label();
this.Alignment = new test.Controls.AlignmentBox();
this.Rotation = new test.Controls.RotationBox();
this.bottomPanel.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.flowLayoutPanel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.xNumeric)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.yNumeric)).BeginInit();
this.flowLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.wNumeric)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.hNumeric)).BeginInit();
this.SuspendLayout();
//
// bottomPanel
//
this.bottomPanel.AutoSize = true;
this.bottomPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.bottomPanel.Controls.Add(this.cancelButton);
this.bottomPanel.Controls.Add(this.okButton);
this.bottomPanel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.bottomPanel.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft;
this.bottomPanel.Location = new System.Drawing.Point(0, 230);
this.bottomPanel.Name = "bottomPanel";
this.bottomPanel.Size = new System.Drawing.Size(364, 29);
this.bottomPanel.TabIndex = 0;
//
// cancelButton
//
this.cancelButton.Location = new System.Drawing.Point(286, 3);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 23);
this.cancelButton.TabIndex = 1;
this.cancelButton.Text = "Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
//
// okButton
//
this.okButton.Location = new System.Drawing.Point(205, 3);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23);
this.okButton.TabIndex = 0;
this.okButton.Text = "OK";
this.okButton.UseVisualStyleBackColor = true;
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.AutoSize = true;
this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel1.ColumnCount = 2;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel2, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.positionLabel, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.sizeLabel, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.rotationLabel, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.positionalalignmentLabel, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.Alignment, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.Rotation, 1, 2);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 5;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(364, 230);
this.tableLayoutPanel1.TabIndex = 0;
//
// flowLayoutPanel2
//
this.flowLayoutPanel2.AutoSize = true;
this.flowLayoutPanel2.Controls.Add(this.xNumeric);
this.flowLayoutPanel2.Controls.Add(this.yNumeric);
this.flowLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel2.Location = new System.Drawing.Point(107, 0);
this.flowLayoutPanel2.Margin = new System.Windows.Forms.Padding(0);
this.flowLayoutPanel2.Name = "flowLayoutPanel2";
this.flowLayoutPanel2.Size = new System.Drawing.Size(257, 26);
this.flowLayoutPanel2.TabIndex = 7;
//
// xNumeric
//
this.xNumeric.DecimalPlaces = 3;
this.xNumeric.Location = new System.Drawing.Point(3, 3);
this.xNumeric.Name = "xNumeric";
this.xNumeric.Size = new System.Drawing.Size(120, 20);
this.xNumeric.TabIndex = 0;
//
// yNumeric
//
this.yNumeric.DecimalPlaces = 3;
this.yNumeric.Location = new System.Drawing.Point(129, 3);
this.yNumeric.Name = "yNumeric";
this.yNumeric.Size = new System.Drawing.Size(120, 20);
this.yNumeric.TabIndex = 1;
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.AutoSize = true;
this.flowLayoutPanel1.Controls.Add(this.wNumeric);
this.flowLayoutPanel1.Controls.Add(this.hNumeric);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel1.Location = new System.Drawing.Point(107, 26);
this.flowLayoutPanel1.Margin = new System.Windows.Forms.Padding(0);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(257, 26);
this.flowLayoutPanel1.TabIndex = 1;
//
// wNumeric
//
this.wNumeric.DecimalPlaces = 3;
this.wNumeric.Location = new System.Drawing.Point(3, 3);
this.wNumeric.Name = "wNumeric";
this.wNumeric.Size = new System.Drawing.Size(120, 20);
this.wNumeric.TabIndex = 1;
//
// hNumeric
//
this.hNumeric.DecimalPlaces = 3;
this.hNumeric.Location = new System.Drawing.Point(129, 3);
this.hNumeric.Name = "hNumeric";
this.hNumeric.Size = new System.Drawing.Size(120, 20);
this.hNumeric.TabIndex = 0;
//
// positionLabel
//
this.positionLabel.AutoSize = true;
this.positionLabel.Dock = System.Windows.Forms.DockStyle.Fill;
this.positionLabel.Location = new System.Drawing.Point(3, 0);
this.positionLabel.Name = "positionLabel";
this.positionLabel.Size = new System.Drawing.Size(101, 26);
this.positionLabel.TabIndex = 0;
this.positionLabel.Text = "Position";
this.positionLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// sizeLabel
//
this.sizeLabel.AutoSize = true;
this.sizeLabel.Dock = System.Windows.Forms.DockStyle.Fill;
this.sizeLabel.Location = new System.Drawing.Point(3, 26);
this.sizeLabel.Name = "sizeLabel";
this.sizeLabel.Size = new System.Drawing.Size(101, 26);
this.sizeLabel.TabIndex = 6;
this.sizeLabel.Text = "Size";
this.sizeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// rotationLabel
//
this.rotationLabel.AutoSize = true;
this.rotationLabel.Dock = System.Windows.Forms.DockStyle.Fill;
this.rotationLabel.Location = new System.Drawing.Point(3, 52);
this.rotationLabel.Name = "rotationLabel";
this.rotationLabel.Size = new System.Drawing.Size(101, 78);
this.rotationLabel.TabIndex = 5;
this.rotationLabel.Text = "Rotation";
this.rotationLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// positionalalignmentLabel
//
this.positionalalignmentLabel.AutoSize = true;
this.positionalalignmentLabel.Dock = System.Windows.Forms.DockStyle.Fill;
this.positionalalignmentLabel.Location = new System.Drawing.Point(3, 130);
this.positionalalignmentLabel.Name = "positionalalignmentLabel";
this.positionalalignmentLabel.Size = new System.Drawing.Size(101, 78);
this.positionalalignmentLabel.TabIndex = 4;
this.positionalalignmentLabel.Text = "Positional Alignment";
this.positionalalignmentLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// Alignment
//
this.Alignment.Alignment = OBS.ObsAlignment.Center;
this.Alignment.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.Alignment.AutoSize = true;
this.Alignment.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.Alignment.Location = new System.Drawing.Point(110, 133);
this.Alignment.Name = "Alignment";
this.Alignment.Size = new System.Drawing.Size(72, 72);
this.Alignment.TabIndex = 2;
//
// Rotation
//
this.Rotation.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.Rotation.Debug = false;
this.Rotation.Location = new System.Drawing.Point(110, 55);
this.Rotation.MaximumSize = new System.Drawing.Size(400, 400);
this.Rotation.MinimumSize = new System.Drawing.Size(50, 50);
this.Rotation.Name = "Rotation";
this.Rotation.Rotation = 0;
this.Rotation.Size = new System.Drawing.Size(72, 72);
this.Rotation.SnapAngle = 45;
this.Rotation.SnapToAngle = true;
this.Rotation.SnapTolerance = 10;
this.Rotation.TabIndex = 3;
//
// TestTransform
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.ClientSize = new System.Drawing.Size(364, 259);
this.ControlBox = false;
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.bottomPanel);
this.Name = "TestTransform";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Text = "Edit Transform";
this.bottomPanel.ResumeLayout(false);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.flowLayoutPanel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.xNumeric)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.yNumeric)).EndInit();
this.flowLayoutPanel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.wNumeric)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.hNumeric)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.FlowLayoutPanel bottomPanel;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.NumericUpDown wNumeric;
private System.Windows.Forms.NumericUpDown hNumeric;
private System.Windows.Forms.Label positionLabel;
private System.Windows.Forms.Label sizeLabel;
private System.Windows.Forms.Label rotationLabel;
private System.Windows.Forms.Label positionalalignmentLabel;
private AlignmentBox Alignment;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2;
private System.Windows.Forms.NumericUpDown xNumeric;
private System.Windows.Forms.NumericUpDown yNumeric;
private RotationBox Rotation;
}
} | GoaLitiuM/libobs-sharp | test/TestTransform.Designer.cs | C# | gpl-2.0 | 13,346 |
/*
* RapidMiner
*
* Copyright (C) 2001-2008 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.similarity;
import java.util.Iterator;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Attributes;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.SimpleAttributes;
import com.rapidminer.example.set.AbstractExampleReader;
import com.rapidminer.example.set.AbstractExampleSet;
import com.rapidminer.example.set.MappedExampleSet;
import com.rapidminer.example.table.AttributeFactory;
import com.rapidminer.example.table.DoubleArrayDataRow;
import com.rapidminer.example.table.ExampleTable;
import com.rapidminer.example.table.NominalMapping;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.math.similarity.DistanceMeasure;
/**
* This similarity based example set is used for the operator
* {@link ExampleSet2SimilarityExampleSet}.
*
* @author Ingo Mierswa
* @version $Id: SimilarityExampleSet.java,v 1.1 2008/09/08 18:53:49 ingomierswa Exp $
*/
public class SimilarityExampleSet extends AbstractExampleSet {
private static final long serialVersionUID = 4757975818441794105L;
private static class IndexExampleReader extends AbstractExampleReader {
private int index = 0;
private ExampleSet exampleSet;
public IndexExampleReader(ExampleSet exampleSet) {
this.exampleSet = exampleSet;
}
public boolean hasNext() {
return index < exampleSet.size() - 1;
}
public Example next() {
Example example = exampleSet.getExample(index);
index++;
return example;
}
}
private ExampleSet parent;
private Attribute parentIdAttribute;
private Attributes attributes;
private DistanceMeasure measure;
public SimilarityExampleSet(ExampleSet parent, DistanceMeasure measure) {
this.parent = parent;
this.parentIdAttribute = parent.getAttributes().getId();
this.attributes = new SimpleAttributes();
Attribute firstIdAttribute = null;
Attribute secondIdAttribute = null;
if (parentIdAttribute.isNominal()) {
firstIdAttribute = AttributeFactory.createAttribute("FIRST_ID", Ontology.NOMINAL);
secondIdAttribute = AttributeFactory.createAttribute("SECOND_ID", Ontology.NOMINAL);
} else {
firstIdAttribute = AttributeFactory.createAttribute("FIRST_ID", Ontology.NUMERICAL);
secondIdAttribute = AttributeFactory.createAttribute("SECOND_ID", Ontology.NUMERICAL);
}
this.attributes.addRegular(firstIdAttribute);
this.attributes.addRegular(secondIdAttribute);
firstIdAttribute.setTableIndex(0);
secondIdAttribute.setTableIndex(1);
// copying mapping of original id attribute
if (parentIdAttribute.isNominal()) {
NominalMapping mapping = parentIdAttribute.getMapping();
firstIdAttribute.setMapping(mapping);
secondIdAttribute.setMapping(mapping);
}
String name = "SIMILARITY";
if (measure.isDistance()) {
name = "DISTANCE";
}
Attribute similarityAttribute = AttributeFactory.createAttribute(name, Ontology.REAL);
this.attributes.addRegular(similarityAttribute);
similarityAttribute.setTableIndex(2);
this.measure = measure;
}
public boolean equals(Object o) {
if (!super.equals(o))
return false;
if (!(o instanceof MappedExampleSet))
return false;
SimilarityExampleSet other = (SimilarityExampleSet)o;
if (!this.measure.getClass().equals(other.measure.getClass()))
return false;
return true;
}
public int hashCode() {
return super.hashCode() ^ this.measure.getClass().hashCode();
}
public Attributes getAttributes() {
return this.attributes;
}
public Example getExample(int index) {
int firstIndex = index / this.parent.size();
int secondIndex = index % this.parent.size();
Example firstExample = this.parent.getExample(firstIndex);
Example secondExample = this.parent.getExample(secondIndex);
double[] data = new double[3];
data[0] = firstExample.getValue(parentIdAttribute);
data[1] = secondExample.getValue(parentIdAttribute);
if (measure.isDistance())
data[2] = measure.calculateDistance(firstExample, secondExample);
else
data[2] = measure.calculateSimilarity(firstExample, secondExample);
return new Example(new DoubleArrayDataRow(data), this);
}
public Iterator<Example> iterator() {
return new IndexExampleReader(this);
}
public ExampleTable getExampleTable() {
return null;//this.parent.getExampleTable();
}
public int size() {
return this.parent.size() * this.parent.size();
}
}
| ntj/ComplexRapidMiner | src/com/rapidminer/operator/similarity/SimilarityExampleSet.java | Java | gpl-2.0 | 5,564 |
<?php
//
// ZoneMinder web action file
// Copyright (C) 2019 ZoneMinder LLC
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// Event scope actions, view permissions only required
if ( !canView('Events') ) {
ZM\Warning('You do not have permission to view Events.');
return;
}
if ( isset($_REQUEST['object']) and ( $_REQUEST['object'] == 'filter' ) ) {
if ( $action == 'addterm' ) {
$_REQUEST['filter'] = addFilterTerm($_REQUEST['filter'], $_REQUEST['line']);
} elseif ( $action == 'delterm' ) {
$_REQUEST['filter'] = delFilterTerm($_REQUEST['filter'], $_REQUEST['line']);
} else if ( canEdit('Events') ) {
require_once('includes/Filter.php');
$filter = new ZM\Filter($_REQUEST['Id']);
if ( $action == 'delete' ) {
if ( !empty($_REQUEST['Id']) ) {
if ( $filter->Background() ) {
$filter->control('stop');
}
$filter->delete();
} else {
ZM\Error('No filter id passed when deleting');
}
} else if ( ( $action == 'Save' ) or ( $action == 'SaveAs' ) or ( $action == 'execute' ) ) {
$sql = '';
$_REQUEST['filter']['Query']['sort_field'] = validStr($_REQUEST['filter']['Query']['sort_field']);
$_REQUEST['filter']['Query']['sort_asc'] = validStr($_REQUEST['filter']['Query']['sort_asc']);
$_REQUEST['filter']['Query']['limit'] = validInt($_REQUEST['filter']['Query']['limit']);
$_REQUEST['filter']['AutoCopy'] = empty($_REQUEST['filter']['AutoCopy']) ? 0 : 1;
$_REQUEST['filter']['AutoMove'] = empty($_REQUEST['filter']['AutoMove']) ? 0 : 1;
$_REQUEST['filter']['AutoArchive'] = empty($_REQUEST['filter']['AutoArchive']) ? 0 : 1;
$_REQUEST['filter']['AutoVideo'] = empty($_REQUEST['filter']['AutoVideo']) ? 0 : 1;
$_REQUEST['filter']['AutoUpload'] = empty($_REQUEST['filter']['AutoUpload']) ? 0 : 1;
$_REQUEST['filter']['AutoEmail'] = empty($_REQUEST['filter']['AutoEmail']) ? 0 : 1;
$_REQUEST['filter']['AutoMessage'] = empty($_REQUEST['filter']['AutoMessage']) ? 0 : 1;
$_REQUEST['filter']['AutoExecute'] = empty($_REQUEST['filter']['AutoExecute']) ? 0 : 1;
$_REQUEST['filter']['AutoDelete'] = empty($_REQUEST['filter']['AutoDelete']) ? 0 : 1;
$_REQUEST['filter']['UpdateDiskSpace'] = empty($_REQUEST['filter']['UpdateDiskSpace']) ? 0 : 1;
$_REQUEST['filter']['Background'] = empty($_REQUEST['filter']['Background']) ? 0 : 1;
$_REQUEST['filter']['Concurrent'] = empty($_REQUEST['filter']['Concurrent']) ? 0 : 1;
$changes = $filter->changes($_REQUEST['filter']);
ZM\Logger::Debug('Changes: ' . print_r($changes,true));
if ( $_REQUEST['Id'] and ( $action == 'Save' ) ) {
if ( $filter->Background() )
$filter->control('stop');
$filter->save($changes);
} else {
if ( $action == 'execute' ) {
if ( count($changes) ) {
$filter->Name('_TempFilter'.time());
$filter->Id(null);
}
} else if ( $action == 'SaveAs' ) {
$filter->Id(null);
}
$filter->save($changes);
// We update the request id so that the newly saved filter is auto-selected
$_REQUEST['Id'] = $filter->Id();
}
if ( $action == 'execute' ) {
$filter->execute();
if ( count($changes) )
$filter->delete();
$view = 'events';
} else if ( $filter->Background() ) {
$filter->control('start');
}
$redirect = '?view=filter&Id='.$filter->Id();
} else if ( $action == 'control' ) {
if ( $_REQUEST['command'] == 'start'
or $_REQUEST['command'] == 'stop'
or $_REQUEST['command'] == 'restart'
) {
$filter->control($_REQUEST['command'], $_REQUEST['ServerId']);
} else {
ZM\Error('Invalid command for filter ('.$_REQUEST['command'].')');
}
} // end if save or execute
} // end if canEdit(Events)
} // end if object == filter
?>
| ZoneMinder/ZoneMinder | web/includes/actions/filter.php | PHP | gpl-2.0 | 4,624 |
/*
* Copyright (C) 2011-2012 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "CoreAudioDevice.h"
#include "CoreAudioAEHAL.h"
#include "CoreAudioChannelLayout.h"
#include "CoreAudioHardware.h"
#include "utils/log.h"
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CCoreAudioDevice
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CCoreAudioDevice::CCoreAudioDevice() :
m_Started (false ),
m_pSource (NULL ),
m_DeviceId (0 ),
m_MixerRestore (-1 ),
m_IoProc (NULL ),
m_ObjectListenerProc (NULL ),
m_SampleRateRestore (0.0f ),
m_HogPid (-1 ),
m_frameSize (0 ),
m_OutputBufferIndex (0 ),
m_BufferSizeRestore (0 )
{
}
CCoreAudioDevice::CCoreAudioDevice(AudioDeviceID deviceId) :
m_Started (false ),
m_pSource (NULL ),
m_DeviceId (deviceId ),
m_MixerRestore (-1 ),
m_IoProc (NULL ),
m_ObjectListenerProc (NULL ),
m_SampleRateRestore (0.0f ),
m_HogPid (-1 ),
m_frameSize (0 ),
m_OutputBufferIndex (0 ),
m_BufferSizeRestore (0 )
{
}
CCoreAudioDevice::~CCoreAudioDevice()
{
Close();
}
bool CCoreAudioDevice::Open(AudioDeviceID deviceId)
{
m_DeviceId = deviceId;
m_BufferSizeRestore = GetBufferSize();
return true;
}
void CCoreAudioDevice::Close()
{
if (!m_DeviceId)
return;
// Stop the device if it was started
Stop();
// Unregister the IOProc if we have one
if (m_IoProc)
SetInputSource(NULL, 0, 0);
SetHogStatus(false);
CCoreAudioHardware::SetAutoHogMode(false);
if (m_MixerRestore > -1) // We changed the mixer status
SetMixingSupport((m_MixerRestore ? true : false));
m_MixerRestore = -1;
if (m_SampleRateRestore != 0.0f)
SetNominalSampleRate(m_SampleRateRestore);
if (m_BufferSizeRestore && m_BufferSizeRestore != GetBufferSize())
{
SetBufferSize(m_BufferSizeRestore);
m_BufferSizeRestore = 0;
}
m_IoProc = NULL;
m_pSource = NULL;
m_DeviceId = 0;
m_ObjectListenerProc = NULL;
}
void CCoreAudioDevice::Start()
{
if (!m_DeviceId || m_Started)
return;
OSStatus ret = AudioDeviceStart(m_DeviceId, m_IoProc);
if (ret)
CLog::Log(LOGERROR, "CCoreAudioDevice::Start: "
"Unable to start device. Error = %s", GetError(ret).c_str());
else
m_Started = true;
}
void CCoreAudioDevice::Stop()
{
if (!m_DeviceId || !m_Started)
return;
OSStatus ret = AudioDeviceStop(m_DeviceId, m_IoProc);
if (ret)
CLog::Log(LOGERROR, "CCoreAudioDevice::Stop: "
"Unable to stop device. Error = %s", GetError(ret).c_str());
m_Started = false;
}
void CCoreAudioDevice::RemoveObjectListenerProc(AudioObjectPropertyListenerProc callback, void* pClientData)
{
if (!m_DeviceId)
return;
AudioObjectPropertyAddress audioProperty;
audioProperty.mSelector = kAudioObjectPropertySelectorWildcard;
audioProperty.mScope = kAudioObjectPropertyScopeWildcard;
audioProperty.mElement = kAudioObjectPropertyElementWildcard;
OSStatus ret = AudioObjectRemovePropertyListener(m_DeviceId, &audioProperty, callback, pClientData);
if (ret)
{
CLog::Log(LOGERROR, "CCoreAudioDevice::RemoveObjectListenerProc: "
"Unable to set ObjectListener callback. Error = %s", GetError(ret).c_str());
}
m_ObjectListenerProc = NULL;
}
bool CCoreAudioDevice::SetObjectListenerProc(AudioObjectPropertyListenerProc callback, void* pClientData)
{
// Allow only one ObjectListener at a time
if (!m_DeviceId || m_ObjectListenerProc)
return false;
AudioObjectPropertyAddress audioProperty;
audioProperty.mSelector = kAudioObjectPropertySelectorWildcard;
audioProperty.mScope = kAudioObjectPropertyScopeWildcard;
audioProperty.mElement = kAudioObjectPropertyElementWildcard;
OSStatus ret = AudioObjectAddPropertyListener(m_DeviceId, &audioProperty, callback, pClientData);
if (ret)
{
CLog::Log(LOGERROR, "CCoreAudioDevice::SetObjectListenerProc: "
"Unable to remove ObjectListener callback. Error = %s", GetError(ret).c_str());
return false;
}
m_ObjectListenerProc = callback;
return true;
}
bool CCoreAudioDevice::SetInputSource(ICoreAudioSource* pSource, unsigned int frameSize, unsigned int outputBufferIndex)
{
m_pSource = pSource;
m_frameSize = frameSize;
m_OutputBufferIndex = outputBufferIndex;
if (pSource)
return AddIOProc();
else
return RemoveIOProc();
}
bool CCoreAudioDevice::AddIOProc()
{
// Allow only one IOProc at a time
if (!m_DeviceId || m_IoProc)
return false;
OSStatus ret = AudioDeviceCreateIOProcID(m_DeviceId, DirectRenderCallback, this, &m_IoProc);
if (ret)
{
CLog::Log(LOGERROR, "CCoreAudioDevice::AddIOProc: "
"Unable to add IOProc. Error = %s", GetError(ret).c_str());
m_IoProc = NULL;
return false;
}
Start();
return true;
}
bool CCoreAudioDevice::RemoveIOProc()
{
if (!m_DeviceId || !m_IoProc)
return false;
Stop();
OSStatus ret = AudioDeviceDestroyIOProcID(m_DeviceId, m_IoProc);
if (ret)
CLog::Log(LOGERROR, "CCoreAudioDevice::RemoveIOProc: "
"Unable to remove IOProc. Error = %s", GetError(ret).c_str());
m_IoProc = NULL; // Clear the reference no matter what
m_pSource = NULL;
Sleep(100);
return true;
}
std::string CCoreAudioDevice::GetName()
{
if (!m_DeviceId)
return NULL;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyDeviceName;
UInt32 propertySize;
OSStatus ret = AudioObjectGetPropertyDataSize(m_DeviceId, &propertyAddress, 0, NULL, &propertySize);
if (ret != noErr)
return NULL;
std::string name = "";
char *buff = new char[propertySize + 1];
buff[propertySize] = 0x00;
ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, buff);
if (ret != noErr)
{
CLog::Log(LOGERROR, "CCoreAudioDevice::GetName: "
"Unable to get device name - id: 0x%04x. Error = %s", (uint)m_DeviceId, GetError(ret).c_str());
}
else
{
name = buff;
}
delete buff;
return name;
}
UInt32 CCoreAudioDevice::GetTotalOutputChannels()
{
UInt32 channels = 0;
if (!m_DeviceId)
return channels;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyStreamConfiguration;
UInt32 size = 0;
OSStatus ret = AudioObjectGetPropertyDataSize(m_DeviceId, &propertyAddress, 0, NULL, &size);
if (ret != noErr)
return channels;
AudioBufferList* pList = (AudioBufferList*)malloc(size);
ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &size, pList);
if (ret == noErr)
{
for(UInt32 buffer = 0; buffer < pList->mNumberBuffers; ++buffer)
channels += pList->mBuffers[buffer].mNumberChannels;
}
else
{
CLog::Log(LOGERROR, "CCoreAudioDevice::GetTotalOutputChannels: "
"Unable to get total device output channels - id: 0x%04x. Error = %s",
(uint)m_DeviceId, GetError(ret).c_str());
}
free(pList);
return channels;
}
bool CCoreAudioDevice::GetStreams(AudioStreamIdList* pList)
{
if (!pList || !m_DeviceId)
return false;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyStreams;
UInt32 propertySize = 0;
OSStatus ret = AudioObjectGetPropertyDataSize(m_DeviceId, &propertyAddress, 0, NULL, &propertySize);
if (ret != noErr)
return false;
UInt32 streamCount = propertySize / sizeof(AudioStreamID);
AudioStreamID* pStreamList = new AudioStreamID[streamCount];
ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, pStreamList);
if (ret == noErr)
{
for (UInt32 stream = 0; stream < streamCount; stream++)
pList->push_back(pStreamList[stream]);
}
delete[] pStreamList;
return ret == noErr;
}
bool CCoreAudioDevice::IsRunning()
{
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyDeviceIsRunning;
UInt32 isRunning = 0;
UInt32 propertySize = sizeof(isRunning);
OSStatus ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, &isRunning);
if (ret != noErr)
return false;
return isRunning != 0;
}
bool CCoreAudioDevice::SetHogStatus(bool hog)
{
// According to Jeff Moore (Core Audio, Apple), Setting kAudioDevicePropertyHogMode
// is a toggle and the only way to tell if you do get hog mode is to compare
// the returned pid against getpid, if the match, you have hog mode, if not you don't.
if (!m_DeviceId)
return false;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyHogMode;
if (hog)
{
// Not already set
if (m_HogPid == -1)
{
OSStatus ret = AudioObjectSetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, sizeof(m_HogPid), &m_HogPid);
// even if setting hogmode was successfull our PID might not get written
// into m_HogPid (so it stays -1). Readback hogstatus for judging if we
// had success on getting hog status
m_HogPid = GetHogStatus();
if (ret || m_HogPid != getpid())
{
CLog::Log(LOGERROR, "CCoreAudioDevice::SetHogStatus: "
"Unable to set 'hog' status. Error = %s", GetError(ret).c_str());
return false;
}
}
}
else
{
// Currently Set
if (m_HogPid > -1)
{
pid_t hogPid = -1;
OSStatus ret = AudioObjectSetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, sizeof(hogPid), &hogPid);
if (ret || hogPid == getpid())
{
CLog::Log(LOGERROR, "CCoreAudioDevice::SetHogStatus: "
"Unable to release 'hog' status. Error = %s", GetError(ret).c_str());
return false;
}
// Reset internal state
m_HogPid = hogPid;
}
}
return true;
}
pid_t CCoreAudioDevice::GetHogStatus()
{
if (!m_DeviceId)
return false;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyHogMode;
pid_t hogPid = -1;
UInt32 size = sizeof(hogPid);
AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &size, &hogPid);
return hogPid;
}
bool CCoreAudioDevice::SetMixingSupport(UInt32 mix)
{
if (!m_DeviceId)
return false;
if (!GetMixingSupport())
return false;
int restore = -1;
if (m_MixerRestore == -1)
{
// This is our first change to this setting. Store the original setting for restore
restore = (GetMixingSupport() ? 1 : 0);
}
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertySupportsMixing;
UInt32 mixEnable = mix ? 1 : 0;
OSStatus ret = AudioObjectSetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, sizeof(mixEnable), &mixEnable);
if (ret != noErr)
{
CLog::Log(LOGERROR, "CCoreAudioDevice::SetMixingSupport: "
"Unable to set MixingSupport to %s. Error = %s", mix ? "'On'" : "'Off'", GetError(ret).c_str());
return false;
}
if (m_MixerRestore == -1)
m_MixerRestore = restore;
return true;
}
bool CCoreAudioDevice::GetMixingSupport()
{
if (!m_DeviceId)
return false;
UInt32 size;
UInt32 mix = 0;
Boolean writable = false;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertySupportsMixing;
if( AudioObjectHasProperty( m_DeviceId, &propertyAddress ) )
{
OSStatus ret = AudioObjectIsPropertySettable(m_DeviceId, &propertyAddress, &writable);
if (ret)
{
CLog::Log(LOGERROR, "CCoreAudioDevice::SupportsMixing: "
"Unable to get propertyinfo mixing support. Error = %s", GetError(ret).c_str());
writable = false;
}
if (writable)
{
size = sizeof(mix);
ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &size, &mix);
if (ret != noErr)
mix = 0;
}
}
CLog::Log(LOGERROR, "CCoreAudioDevice::SupportsMixing: "
"Device mixing support : %s.", mix ? "'Yes'" : "'No'");
return (mix > 0);
}
bool CCoreAudioDevice::SetCurrentVolume(Float32 vol)
{
if (!m_DeviceId)
return false;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kHALOutputParam_Volume;
OSStatus ret = AudioObjectSetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, sizeof(Float32), &vol);
if (ret != noErr)
{
CLog::Log(LOGERROR, "CCoreAudioDevice::SetCurrentVolume: "
"Unable to set AudioUnit volume. Error = %s", GetError(ret).c_str());
return false;
}
return true;
}
bool CCoreAudioDevice::GetPreferredChannelLayout(CCoreAudioChannelLayout& layout)
{
if (!m_DeviceId)
return false;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyPreferredChannelLayout;
UInt32 propertySize = 0;
OSStatus ret = AudioObjectGetPropertyDataSize(m_DeviceId, &propertyAddress, 0, NULL, &propertySize);
if (ret)
return false;
void* pBuf = malloc(propertySize);
ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, pBuf);
if (ret != noErr)
CLog::Log(LOGERROR, "CCoreAudioDevice::GetPreferredChannelLayout: "
"Unable to retrieve preferred channel layout. Error = %s", GetError(ret).c_str());
else
{
// Copy the result into the caller's instance
layout.CopyLayout(*((AudioChannelLayout*)pBuf));
}
free(pBuf);
return (ret == noErr);
}
bool CCoreAudioDevice::GetDataSources(CoreAudioDataSourceList* pList)
{
if (!pList || !m_DeviceId)
return false;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyDataSources;
UInt32 propertySize = 0;
OSStatus ret = AudioObjectGetPropertyDataSize(m_DeviceId, &propertyAddress, 0, NULL, &propertySize);
if (ret != noErr)
return false;
UInt32 sources = propertySize / sizeof(UInt32);
UInt32* pSources = new UInt32[sources];
ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, pSources);
if (ret == noErr)
{
for (UInt32 i = 0; i < sources; i++)
pList->push_back(pSources[i]);
}
delete[] pSources;
return (!ret);
}
Float64 CCoreAudioDevice::GetNominalSampleRate()
{
if (!m_DeviceId)
return 0.0f;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyNominalSampleRate;
Float64 sampleRate = 0.0f;
UInt32 propertySize = sizeof(Float64);
OSStatus ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, &sampleRate);
if (ret != noErr)
{
CLog::Log(LOGERROR, "CCoreAudioDevice::GetNominalSampleRate: "
"Unable to retrieve current device sample rate. Error = %s", GetError(ret).c_str());
return 0.0f;
}
return sampleRate;
}
bool CCoreAudioDevice::SetNominalSampleRate(Float64 sampleRate)
{
if (!m_DeviceId || sampleRate == 0.0f)
return false;
Float64 currentRate = GetNominalSampleRate();
if (currentRate == sampleRate)
return true; //No need to change
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyNominalSampleRate;
OSStatus ret = AudioObjectSetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, sizeof(Float64), &sampleRate);
if (ret != noErr)
{
CLog::Log(LOGERROR, "CCoreAudioDevice::SetNominalSampleRate: "
"Unable to set current device sample rate to %0.0f. Error = %s",
(float)sampleRate, GetError(ret).c_str());
return false;
}
if (m_SampleRateRestore == 0.0f)
m_SampleRateRestore = currentRate;
return true;
}
UInt32 CCoreAudioDevice::GetNumLatencyFrames()
{
UInt32 num_latency_frames = 0;
if (!m_DeviceId)
return 0;
// number of frames of latency in the AudioDevice
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyLatency;
UInt32 i_param = 0;
UInt32 i_param_size = sizeof(uint32_t);
OSStatus ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &i_param_size, &i_param);
if (ret == noErr)
num_latency_frames += i_param;
// number of frames in the IO buffers
propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSize;
ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &i_param_size, &i_param);
if (ret == noErr)
num_latency_frames += i_param;
// number for frames in ahead the current hardware position that is safe to do IO
propertyAddress.mSelector = kAudioDevicePropertySafetyOffset;
ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &i_param_size, &i_param);
if (ret == noErr)
num_latency_frames += i_param;
return (num_latency_frames);
}
UInt32 CCoreAudioDevice::GetBufferSize()
{
if (!m_DeviceId)
return false;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSize;
UInt32 size = 0;
UInt32 propertySize = sizeof(size);
OSStatus ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, &size);
if (ret != noErr)
CLog::Log(LOGERROR, "CCoreAudioDevice::GetBufferSize: "
"Unable to retrieve buffer size. Error = %s", GetError(ret).c_str());
return size;
}
bool CCoreAudioDevice::SetBufferSize(UInt32 size)
{
if (!m_DeviceId)
return false;
AudioObjectPropertyAddress propertyAddress;
propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
propertyAddress.mElement = 0;
propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSize;
UInt32 propertySize = sizeof(size);
OSStatus ret = AudioObjectSetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, propertySize, &size);
if (ret != noErr)
{
CLog::Log(LOGERROR, "CCoreAudioDevice::SetBufferSize: "
"Unable to set buffer size. Error = %s", GetError(ret).c_str());
}
if (GetBufferSize() != size)
CLog::Log(LOGERROR, "CCoreAudioDevice::SetBufferSize: Buffer size change not applied.");
return (ret == noErr);
}
OSStatus CCoreAudioDevice::DirectRenderCallback(AudioDeviceID inDevice,
const AudioTimeStamp *inNow,
const AudioBufferList *inInputData,
const AudioTimeStamp *inInputTime,
AudioBufferList *outOutputData,
const AudioTimeStamp *inOutputTime,
void *inClientData)
{
OSStatus ret = noErr;
CCoreAudioDevice *audioDevice = (CCoreAudioDevice*)inClientData;
if (audioDevice->m_pSource && audioDevice->m_frameSize)
{
UInt32 frames = outOutputData->mBuffers[audioDevice->m_OutputBufferIndex].mDataByteSize / audioDevice->m_frameSize;
ret = audioDevice->m_pSource->Render(NULL, inInputTime, 0, frames, outOutputData);
}
else
{
outOutputData->mBuffers[audioDevice->m_OutputBufferIndex].mDataByteSize = 0;
}
return ret;
}
| mekinik232/ambipi | xbmc/cores/AudioEngine/Engines/CoreAudio/CoreAudioDevice.cpp | C++ | gpl-2.0 | 21,096 |
<?php
/**
* Write users to file
* @param string $filename
* @param array $array_data
* @return null
*/
// function insert($user,$config)
function readUser($id, $config)
{
switch ($config['adapter'])
{
case 'txt':
include_once('file/users.php');
$user=readUserFromFile($id, $config);
return $users;
break;
case 'mysql':
include_once('mysql/users.php');
$users = select($id,$config);
return $users;
break;
case 'googledocs':
include_once('googledocs/users.php');
$users = selectAll($config);
return $users;
break;
}
}
function update($user, $id, $config)
{
switch ($config['adapter'])
{
case 'txt':
include_once('file/users.php');
updateUserTofile($id, $user, $user['filename'], $config);
return;
break;
case 'mysql':
include_once('mysql/users.php');
$users = updateUser($id, $user, $config);
return $users;
break;
case 'googledocs':
include_once('googledocs/users.php');
$users = selectAll($config);
return $users;
break;
}
}
// function select($id, $config)
function readUsers($config)
{
switch ($config['adapter'])
{
case 'txt':
include_once('file/users.php');
$users=readUsersFromFile($config);
return $users;
break;
case 'mysql':
include_once('mysql/users.php');
$users = selectAll($config);
return $users;
break;
case 'googledocs':
include_once('googledocs/users.php');
$users = selectAll($config);
return $users;
break;
}
}
// function delete($id, $config)
| zerophp/zgz2013octM | proyecto7/model/users/usersModel.php | PHP | gpl-2.0 | 1,523 |
/**
* yamsLog is a program for real time multi sensor logging and
* supervision
* Copyright (C) 2014
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import Database.Messages.ProjectMetaData;
import Database.Sensors.Sensor;
import Errors.BackendError;
import FrontendConnection.Backend;
import FrontendConnection.Listeners.ProjectCreationStatusListener;
import protobuf.Protocol;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created with IntelliJ IDEA.
* User: Aitesh
* Date: 2014-04-10
* Time: 09:34
* To change this template use File | Settings | File Templates.
*/
public class NewDebugger implements ProjectCreationStatusListener {
private boolean projectListChanged;
public NewDebugger(){
try{
Backend.createInstance(null); //args[0],Integer.parseInt(args[1]),
Backend.getInstance().addProjectCreationStatusListener(this);
Backend.getInstance().connectToServer("130.236.63.46",2001);
} catch (BackendError b){
b.printStackTrace();
}
projectListChanged = false;
}
private synchronized boolean readWriteBoolean(Boolean b){
if(b!=null) projectListChanged=b;
return projectListChanged;
}
public void runPlayback() {
try{
Thread.sleep(1000); //Backend.getInstance().sendSettingsRequestMessageALlSensors(0);
readWriteBoolean(false);
Random r = new Random();
String[] strings = new String[]{"Name","Code","File","Today","Monday","Tuesday","Wednesday","Thursday","Friday","Gotta","Get","Out","It","S","Friday"};
String project = "projectName" +r.nextInt()%10000;
String playbackProject = "realCollection";
Thread.sleep(1000);
System.out.println("Setting active project to : " + playbackProject);
Backend.getInstance().setActiveProject(playbackProject);
ProjectMetaData d = new ProjectMetaData();
d.setTest_leader("ffu");
d.setDate(1l);
List<String> s = new ArrayList<String>();
s.add("memer1");
d.setMember_names(s);
d.setTags(s);
d.setDescription("desc");
List l = d.getMember_names();
l.add(r.nextInt()+". name");
d.setMember_names(l);
Backend.getInstance().sendProjectMetaData(d);
System.out.println("starting data collection");
Thread.sleep(100);
String experimentName = "smallrun";
//Backend.getInstance().setActiveProject(playbackProject);
// projektnamn:
Thread.sleep(3000);
// Backend.getInstance().getSensorConfigurationForPlayback().getSensorId();
List<Protocol.SensorConfiguration> playbackConfig;
playbackConfig = Backend.getInstance().getSensorConfigurationForPlayback();
List<Integer> listOfIds = new ArrayList<Integer>();
/* for (Protocol.SensorConfiguration aPlaybackConfig : playbackConfig) {
listOfIds.add(aPlaybackConfig.getSensorId());
}*/
System.out.println("LIST OF IDS SENT TO SERVER-------------------------------------------");
System.out.println(listOfIds);
System.out.println("LIST OF IDS END -----------------------------------------------------");
System.out.println("LIST OF IDS CURRENTLY IN DATABASE -----------------------------------");
System.out.println(Backend.getInstance().getSensors());
System.out.println("LIST IN DATABASE END ------------------------------------------------");
Backend.getInstance().sendExperimentPlaybackRequest(experimentName, listOfIds);
//Thread.sleep(3000);
//Backend.getInstance().stopConnection();
} catch (BackendError b){
b.printStackTrace();
} catch (InterruptedException ignore){
}
}
public void run(){
try{
Thread.sleep(1000); Backend.getInstance().sendSettingsRequestMessageALlSensors(0);
readWriteBoolean(false);
Random r = new Random();
String[] strings = new String[]{"Name","Code","File","Today","Monday","Tuesday","Wednesday","Thursday","Friday","Gotta","Get","Out","It","S","Friday"};
String project = "projectName" +r.nextInt()%10000;
String playbackProject = "realCollection";
for(int i = 0; i < 1000; i++){
// project+=strings[r.nextInt(strings.length)];
}
//System.out.println(project);
//if(r.nextInt()>0) return;
Thread.sleep(1000); Backend.getInstance().createNewProjectRequest(project);//"projectName"+ System.currentTimeMillis());
if(!readWriteBoolean(null)){
System.out.println("Waiting on projectListAgain");
while (!readWriteBoolean(null));
System.out.println("finished waiting");
}
// = Backend.getInstance().getProjectFilesFromServer().get());
System.out.println("Setting active project to : " + project);
Backend.getInstance().setActiveProject(project);
ProjectMetaData d = new ProjectMetaData();
//d.setEmail("NotMyEmail@gmail.com");
d.setTest_leader("ffu");
d.setDate(1l);
List<String> s = new ArrayList<String>();
s.add("memer1");
d.setMember_names(s);
d.setTags(s);
d.setDescription("desc");
List l = d.getMember_names();
l.add(r.nextInt() + ". name");
d.setMember_names(l);
Backend.getInstance().sendProjectMetaData(d);
/* while(!readWriteBoolean(null) && readWriteBoolean(null)){
Backend.getInstance().sendProjectMetaData(d);
List<String> f =d.getTags();
f.add(String.valueOf(System.currentTimeMillis()));
d.setTags(f);
} **/
System.out.println("starting data collection");
Thread.sleep(100);
String experimentName = "experimentNam5"+System.currentTimeMillis();
//String experimentName = "smallrun";
// projektnamn:
Backend.getInstance().startDataCollection(experimentName);
Thread.sleep(3000);
Backend.getInstance().stopDataCollection(); Thread.sleep(1);
} catch (BackendError b){
b.printStackTrace();
} catch (InterruptedException ignore){
}
System.out.println("Exiting");
}
public void runTest(){
// try{
// Thread.sleep(1000); Backend.getInstance().sendSettingsRequestMessageALlSensors(0);
// Thread.sleep(1000); Backend.getInstance().createNewProjectRequest("projectName"+ System.currentTimeMillis());
//
// //Backend.getInstance().startDataCollection("test1234");
//
// //Thread.sleep(5000); Backend.getInstance().stopDataCollection();
// Backend localInstance = Backend.getInstance();
//
// Sensor sensor = localInstance.getSensors().get(0);
// for(int i = 0; i<sensor.getAttributeList(0).size();i++){
// System.out.print(String.format("%f", sensor.getAttributeList(0).get(i).floatValue()).replace(',', '.') + ",");
//
// System.out.print(sensor.getId() + ",");
// for (int j = 1; j < sensor.getAttributesName().length;j++){
//
// System.out.print(sensor.getAttributeList(j).get(i).floatValue() + " ,");
// }
// System.out.println();
// }
//
// } catch (BackendError b){
// b.printStackTrace();
// } catch (InterruptedException ignore){}
}
@Override
public void projectCreationStatusChanged(Protocol.CreateNewProjectResponseMsg.ResponseType responseType) {
readWriteBoolean(true);
}
}
| droberg/yamsLog | client-backend/src/NewDebugger.java | Java | gpl-2.0 | 8,996 |